I am trying to move an object from one database into another. The mappings are the same but the tables are different. This is a merging tool where data from an old database need to be imported into a new one. Still, I think I am missing something fundamental about SQLAlchemy here. What is it?
from sqlalchemy import Column, Float, String, Enum
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import orm
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
DeclarativeBase = declarative_base()
class Datum (DeclarativeBase):
__tablename__ = "xUnitTestData"
Key = Column(String, primary_key=True)
Value = Column(Float)
def __init__ (self, k, v):
self.Key = k
self.Value = v
src_engine = create_engine('sqlite:///:memory:', echo=False)
dst_engine = create_engine('sqlite:///:memory:', echo=False)
DeclarativeBase.metadata.create_all(src_engine)
DeclarativeBase.metadata.create_all(dst_engine)
SessionSRC = sessionmaker(bind=src_engine)
SessionDST = sessionmaker(bind=dst_engine)
item = Datum('eek', 666)
session1 = SessionSRC()
session1.add(item)
session1.commit()
session1.close()
session2 = SessionDST()
session2.add(item)
session2.commit()
print item in session2 # >>> True
print session2.query(Datum).all() # >>> []
session2.close()
I’m not really aware about what happens under the hood, but in the ORM pattern an object matches to a particular row in a particular table. If you try to add the same object to two different tables in two different databases, that doesn’t sound like a good practice even if the table definition is exactly the same.
What I’d do to workaround this problem is just create a new object that is a copy of the original object and add it to the database:
Note that
session1isn’t closed immediately to be able to read the original object attributes while creating the new object.