Being new to sqlalchemy I gave myself an exercise to
test my understanding: duplicating a database through
objects.  To my naive understanding, sessions act like
Saran Wrap, they seem to stick to objects when I don't
want them to, and not elsewhere.  My toy example:

# An attempt to duplicate a database through objects

from sqlalchemy import *

metadata = DynamicMetaData()

simpleTable = Table('simple', metadata,
    Column('simple_id', Integer, primary_key=True),
    Column('name', String))

class Simple(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "%s(%r)" % (self.__class__.__name__, self.name)

mapper(Simple, simpleTable)

# Read from one data base
engine = create_engine('sqlite:///Simple.db')
metadata.connect(engine)
session = create_session(bind_to=engine)
objects = session.query(Simple).select()

# My feeble attempt to divorce the objects from the session
for obj in objects:
    session.expunge(obj)
session.close()

# Take a peek to see the objects are still with us
for obj in objects:
    print obj,
print ""

# Write to another database
engine = create_engine('sqlite:///SonOfSimple.db')
metadata.connect(engine)
session = create_session(bind_to=engine)
metadata.create_all()

# Connect the objects to the "write" session
for obj in objects:
    session.save(obj)

# But here is my sin, apparently my objects were not transient ...
#    sqlalchemy.exceptions.InvalidRequestError: Instance
'Simple(u'They')'
#    is a detached instance or is already persistent in a different
Session

session.flush()


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to