# HG changeset patch # User Thierry Florac # Date 1435738580 -7200 # Node ID d775bab6f983e0892425668a0474873c2ef22c0c # Parent d114654e742314f101dbb725dbefeafd984130bc Added DataLoader class to help data migration between databases diff -r d114654e7423 -r d775bab6f983 src/pyams_alchemy/loader.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/pyams_alchemy/loader.py Wed Jul 01 10:16:20 2015 +0200 @@ -0,0 +1,56 @@ +# +# Copyright (c) 2008-2015 Thierry Florac +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# + +__docformat__ = 'restructuredtext' + + +# import standard library +import logging +logger = logging.getLogger('PyAMS (alchemy)') + +# import interfaces + +# import packages +from pyams_alchemy.engine import get_user_session +from sqlalchemy.orm.session import make_transient + + +class DataLoader(object): + """SQLAlchemy data loader + + This utility class is used to migrate entities from a given connection + to another one. + WARNING: actually, given entities must share the same schema name!!! + """ + + def __init__(self, source, target, entities): + """ + Initialize data loader + + :param source: name of registered source engine + :param target: name of registered target engine + :param entities: list of migrated entities + :return: + """ + self.source_session = get_user_session(source) + self.target_session = get_user_session(target) + self.entities = entities + + def run(self): + source = self.source_session + target = self.target_session + for entity in self.entities: + logger.info('Loading entity {0!r}'.format(entity)) + for record in source.query(entity): + source.expunge(record) + make_transient(record) + target.add(record)