Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save malefs/d542b61558e0637ff699bc9588154325 to your computer and use it in GitHub Desktop.
Save malefs/d542b61558e0637ff699bc9588154325 to your computer and use it in GitHub Desktop.

Revisions

  1. @jcrudy jcrudy created this gist Jul 5, 2016.
    32 changes: 32 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    from sqlalchemy.ext.automap import automap_base
    from sqlalchemy import create_engine, MetaData, Column, String, Integer
    import pickle
    from sqlalchemy.sql.schema import ForeignKey

    # Create some tables in the database
    engine = create_engine('sqlite://')
    engine.execute('CREATE TABLE user (id INTEGER, name TEXT, favorite_color TEXT)')
    engine.execute('CREATE TABLE profile (id INTEGER, userid INTEGER, summary TEXT)')

    # Create a metadata based on the database
    metadata = MetaData()
    metadata.reflect(bind=engine)

    # Pickle and unpickle the metadata
    metadata = pickle.loads(pickle.dumps(metadata))

    # Attempt to automap some classes and override some existing columns
    Base = automap_base(metadata=metadata)

    class User(Base):
    __tablename__ = 'user'

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String)

    class Profile(Base):
    __tablename__ = 'profile'
    id = Column('id', Integer, primary_key=True)
    userid = Column('userid', ForeignKey('user.id'))

    Base.prepare()