sqlalchemy.MetaData

Here are the examples of the python api sqlalchemy.MetaData taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: motorway
Source File: intersections.py
View license
    def __init__(self, *args, **kwargs):
        self.engine = create_engine(self.database_uri, echo=self.debug_sql_statements)
        self.metadata = MetaData(bind=self.engine)
        self.connection = self.engine.connect()
        try:
            self.table = Table(self.table, self.metadata, autoload=True, schema=self.schema)
        except NoSuchTableError:
            if not self.create_table:
                raise
            else:
                self.table = Table(self.table, self.metadata,
                    *[
                        Column(column['name'], column['type'], primary_key=column.get('primary_key', False))
                    for column in self.table_columns],
                schema = self.schema)
                self.table.create(self.engine)

        super(DatabaseInsertIntersection, self).__init__(*args, **kwargs)

Example 2

Project: pagure
Source File: dev-data.py
View license
def init_database():
    DB_URL = pagure.APP.config['DB_URL']

    # create the table if it doesnt exist
    pagure.lib.model.create_tables(
        DB_URL,
        pagure.APP.config.get('PATH_ALEMBIC_INI', None),
        acls=pagure.APP.config.get('ACLS', {}),
        debug=True)

    engine = create_engine('%s' % DB_URL, echo=True)

    metadata = MetaData(engine)
    metadata.reflect(bind=engine)
    return engine, metadata

Example 3

Project: lux
Source File: alembic.py
View license
    def get_metadata(self, config):
        '''
        MetaData object stored in odm extension contains aggregated data
        from all databases defined in project. This function splits the data
        to correspond with related database only.
        '''
        from sqlalchemy import MetaData
        odm = self.app.odm()
        metadata = {}

        for key, db_engine in odm.keys_engines():
            if not key:
                key = 'default'
            metadata[key] = meta = MetaData()
            for table, engine in odm.binds.items():
                if engine == db_engine:
                    table.tometadata(meta)

        config.metadata = metadata

Example 4

Project: climber
Source File: DBPipeline.py
View license
    def __init__(self, engine, max_working = 1):
        self.condition     = Condition(RLock())
        self.engine        = engine
        self.max_working   = max_working
        self.running       = False
        self.paused        = False
        self.metadata      = sa.MetaData(self.engine)
        self._table_prefix = 'exscript_pipeline_'
        self._table_map    = {}
        self.__update_table_names()
        self.clear()

Example 5

Project: bitQuant
Source File: clss.py
View license
    def __init__(self):
        engine_str = stmt.auth()
        if engine_str.find('sqlite') == 0:
            self.sql_type = 'sqlite'
            self.eng = create_engine(engine_str, module=sqlite)
        else:
            self.sql_type = 'mysql'
            self.eng = create_engine(engine_str)
        self.conn = self.eng.connect()
        self.meta = MetaData(self.eng)
        self.tbl = self.load_tables()

Example 6

Project: piecash
Source File: sa_extra.py
View license
def get_foreign_keys(metadata, engine):
    """ Retrieve all foreign keys from metadata bound to an engine
    :param metadata:
    :param engine:
    :return:
    """
    reflected_metadata = MetaData()
    for table_name in list(metadata.tables.keys()):
        table = Table(
            table_name,
            reflected_metadata,
            autoload=True,
            autoload_with=engine,
        )

        for constraint in table.constraints:
            if not isinstance(constraint, ForeignKeyConstraint):
                continue
            yield constraint

Example 7

Project: SickGear
Source File: test_types.py
View license
    @requirements.unbounded_varchar
    def test_nolength_string(self):
        metadata = MetaData()
        foo = Table('foo', metadata,
                    Column('one', String)
                )

        foo.create(config.db)
        foo.drop(config.db)

Example 8

Project: shiftmanager
Source File: reflection.py
View license
    @memoized_property
    def meta(self):
        """A `sqlalchemy.schema.MetaData` instance used for reflection calls.
        """
        meta = sqlalchemy.MetaData()
        meta.bind = self.engine
        return meta

Example 9

Project: sopython-site
Source File: sqlalchemy.py
View license
    def make_declarative_base(self, metadata=None):
        metadata = MetaData(naming_convention={
            'pk': 'pk_%(table_name)s',
            'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s',
            'uq': 'uq_%(table_name)s_%(column_0_name)s',
            'ix': 'ix_%(table_name)s_%(column_0_name)s',
            'ck': 'ck_%(table_name)s_%(constraint_name)s',
        })
        base = declarative_base(metadata=metadata, cls=self.BaseModel, name='Model', metaclass=self.DeclarativeMeta)
        base.query = _QueryProperty(self)
        base.db = self
        return base

Example 10

Project: luigi
Source File: sqla_test.py
View license
    def _check_entries(self, engine):
        with engine.begin() as conn:
            meta = sqlalchemy.MetaData()
            meta.reflect(bind=engine)
            self.assertEqual(set([u'table_updates', u'item_property']), set(meta.tables.keys()))
            table = meta.tables[self.SQLATask.table]
            s = sqlalchemy.select([sqlalchemy.func.count(table.c.item)])
            result = conn.execute(s).fetchone()
            self.assertEqual(len(BaseTask.TASK_LIST), result[0])
            s = sqlalchemy.select([table]).order_by(table.c.item)
            result = conn.execute(s).fetchall()
            for i in range(len(BaseTask.TASK_LIST)):
                given = BaseTask.TASK_LIST[i].strip("\n").split("\t")
                given = (unicode(given[0]), unicode(given[1]))
                self.assertEqual(given, tuple(result[i]))

Example 11

View license
def test_different_tables():
    metdata = sa.MetaData()
    t1 = sa.Table('t1', metdata, sa.Column('col1', sa.Unicode()))
    t2 = sa.Table('t2', metdata, sa.Column('col1', sa.Unicode()))
    with pytest.raises(ValueError):
        dialect.CopyCommand(
            [t1.c.col1, t2.c.col1],
            data_location='s3://bucket',
            access_key_id=access_key_id,
            secret_access_key=secret_access_key,
            format='CSV'
        )

Example 12

View license
    def test_create_table_simple(self, compiler):

        table = Table('t1',
                      MetaData(),
                      Column('id', Integer, primary_key=True),
                      Column('name', String))

        create_table = CreateTable(table)
        actual = compiler.process(create_table)
        expected = (
            u"\nCREATE TABLE t1 ("
            u"\n\tid INTEGER NOT NULL, "
            u"\n\tname VARCHAR, "
            u"\n\tPRIMARY KEY (id)\n)\n\n"
        )
        assert expected == actual, self._compare_strings(expected, actual)

Example 13

Project: sign-language-tutor
Source File: db.py
View license
def get_engine_and_table():
    engine = create_engine('sqlite:///asl_data.db', echo=True)

    metadata = MetaData()
    columns = [Column('feat' + str(i), Numeric) for i in range(NUM_FEATURES)]
    columns.append(Column('sign', String(length=1)))
    tagged_data = Table('tagged_data', metadata, *columns)
    
    metadata.create_all(engine)

    return engine, tagged_data

Example 14

Project: brewery
Source File: test_sql_streams.py
View license
    def setUp(self):
        self.engine = create_engine("sqlite://")
        self.metadata = MetaData()
        
        self.fields = brewery.metadata.FieldList([
                            ("category", "string"),
                            ("category_label", "string"), 
                            ("subcategory", "string"), 
                            ("subcategory_label", "string"), 
                            ("line_item", "string"),
                            ("year", "integer"), 
                            ("amount", "integer")])
        self.example_row = ["cat", "Category", "scat", "Sub-category", "foo", 2012, 100]

Example 15

Project: talkatv
Source File: migrations.py
View license
@RegisterMigration(1, MIGRATIONS)
def create_site_table(db_conn):
    metadata = MetaData(bind=db_conn.bind)

    user_table = Table('user', metadata, autoload=True,
            autoload_with=db_conn.bind)

    site_table = Table('site', metadata,
            Column('id', Integer, primary_key=True),
            Column('domain', Unicode),
            Column('owner_id', Integer, ForeignKey(user_table.columns['id'])))

    site_table.create()

    db_conn.commit()

Example 16

Project: talkatv
Source File: migrations.py
View license
@RegisterMigration(2, MIGRATIONS)
def item_add_site_id(db_conn):
    metadata = MetaData(bind=db_conn.bind)

    item_table = Table('item', metadata, autoload=True)
    site_table = Table('site', metadata, autoload=True)

    site_id_col = Column('site_id', Integer, ForeignKey(
        site_table.columns['id']))

    site_id_col.create(item_table)

    db_conn.commit()

Example 17

Project: sendgrid-python-dmarc-parser
Source File: app.py
View license
def load_session():
	""""""    
	engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], echo=True)
	metadata = MetaData(engine)
	sg_policy_published = Table('policy_published', metadata, autoload=True)
	mapper(Policy_Published, sg_policy_published)
	sg_records = Table('records', metadata, autoload=True)
	mapper(Records, sg_records)
	sg_report_metadata = Table('report_metadata', metadata, autoload=True)
	mapper(Report_Metadata, sg_report_metadata)
	Session = sessionmaker(bind=engine)
	session = Session()
	return session

Example 18

Project: tuskar
Source File: migration.py
View license
def db_version():
    repository = _find_migrate_repo()
    try:
        return versioning_api.db_version(get_engine(), repository)
    except versioning_exceptions.DatabaseNotControlledError:
        meta = sqlalchemy.MetaData()
        engine = get_engine()
        meta.reflect(bind=engine)
        tables = meta.tables
        if len(tables) == 0:
            db_version_control(migration.INIT_VERSION)
            return versioning_api.db_version(get_engine(), repository)
        else:
            # Some pre-Essex DB's may not be version controlled.
            # Require them to upgrade using Essex first.
            raise exception.TuskarException(
                _("Upgrade DB using Essex release first."))

Example 19

Project: raco
Source File: catalog.py
View license
    def __init__(self, engine=None, push_grouping=False,
                 provider=_DefaultSQLFunctionProvider()):
        self.engine = engine
        self.push_grouping = push_grouping
        self.provider = provider
        self.metadata = MetaData()

Example 20

Project: csvkit
Source File: sql.py
View license
def make_table(csv_table, name='table_name', no_constraints=False, db_schema=None, metadata=None):
    """
    Creates a sqlalchemy table from a csvkit Table.
    """
    if not metadata:
        metadata = MetaData()

    sql_table = Table(csv_table.name, metadata, schema=db_schema)

    for column in csv_table:
        sql_table.append_column(make_column(column, no_constraints))

    return sql_table

Example 21

Project: xraylarch
Source File: xraydb.py
View license
def isxrayDB(dbname):
    """test if a file is a valid scan database:
    must be a sqlite db file, with tables named
    'Coster_Kronig', 'elements', 'photoabsorption', 'scattering'

    """
    _tables = ('Chantler', 'Waasmaier', 'Coster_Kronig',
               'KeskiRahkonen_Krause',
               'elements', 'photoabsorption', 'scattering')
    result = False
    try:
        engine = make_engine(dbname)
        meta = MetaData(engine)
        meta.reflect()
        result = all([t in meta.tables for t in _tables])
    except:
        pass
    return result

Example 22

Project: odo
Source File: test_mysql.py
View license
def test_decimal(decimal_sql):
    t = sa.Table(decimal_sql.name, sa.MetaData(decimal_sql.bind), autoload=True)
    assert discover(t) == dshape(
        "var * {a: ?decimal[10, 3], b: decimal[11, 2]}"
    )
    assert isinstance(t.c.a.type, sa.Numeric)
    assert isinstance(t.c.b.type, sa.Numeric)

Example 23

Project: odo
Source File: test_sql.py
View license
@pytest.fixture
def recursive_fkey():
    return sa.Table(
        'employees',
        sa.MetaData(),
        sa.Column('eid', sa.BIGINT, primary_key=True),
        sa.Column('name', sa.TEXT),
        sa.Column('mgr_eid', sa.BIGINT, sa.ForeignKey('employees.eid'),
                  nullable=False)
    )

Example 24

Project: sqlalchemy_exasol
Source File: test_exasol.py
View license
    def test_distribute_by_constraint(self):
        try:
           reflected = Table('t', MetaData(testing.db), autoload=True)
        except:
           assert False
        #TODO: check that reflected table object is identical
        # i.e. contains the constraint
        insp = inspect(testing.db)
        for c in insp.get_columns('t'):
            if not (c['name'] == 'c'):
                assert c['is_distribution_key'] == True
            else:
                assert c['is_distribution_key'] == False

Example 25

Project: acoustid-server
Source File: create_dev_db.py
View license
def main(script, opts, args):
    logging.getLogger('sqlalchemy.engine').setLevel(logging.ERROR)
    with script.engine.connect() as conn:
        with conn.begin():
            if opts.drop:
                old_metadata = sqlalchemy.MetaData(conn)
                old_metadata.reflect()
                old_metadata.reflect(schema='musicbrainz')
                old_metadata.drop_all(checkfirst=False)
            if opts.create:
                metadata.create_all(conn)
                if not opts.empty:
                    session = sqlalchemy.orm.Session(conn)
                    create_sample_musicbrainz_data(session)
                    create_sample_data(session)
        if opts.create:
            alembic_cfg = alembic.config.Config(os.path.join(os.path.dirname(__file__), "..", "..", "alembic.ini"))
            alembic.command.stamp(alembic_cfg, "head")

Example 26

Project: applib
Source File: _simpledb.py
View license
def setup(db_class, simple_object_cls, primary_keys):
    """A simple API to configure the metadata"""
    table_name = simple_object_cls.__name__
    column_names = simple_object_cls.FIELDS
    
    metadata = MetaData()
    table = Table(table_name, metadata,
                  *[Column(cname, _get_best_column_type(cname),
                           primary_key=cname in primary_keys)
                    for cname in column_names])

    db_class.metadata = metadata
    db_class.mapper_class = simple_object_cls
    db_class.table = table

    mapper(simple_object_cls, table)

Example 27

Project: traces
Source File: web_parser.py
View license
def loadChromeSession():
	dbPath = os.path.expanduser('~/Library/Application Support/Google/Chrome/Default/History')
	engine = create_engine('sqlite:///%s' % dbPath, echo=True)

	metadata = MetaData(engine)
	urls = Table('urls', metadata, autoload=True)
	mapper(URLS, urls)

	Session = sessionmaker(bind=engine)
	session = Session()
	return session

Example 28

Project: ckanext-googleanalytics
Source File: dbutil.py
View license
def init_tables():
    metadata = MetaData()
    package_stats = Table('package_stats', metadata,
                          Column('package_id', String(60),
                                 primary_key=True),
                          Column('visits_recently', Integer),
                          Column('visits_ever', Integer))
    resource_stats = Table('resource_stats', metadata,
                           Column('resource_id', String(60),
                                  primary_key=True),
                           Column('visits_recently', Integer),
                           Column('visits_ever', Integer))
    metadata.create_all(model.meta.engine)

Example 29

Project: ckanext-googleanalytics
Source File: dbutil.py
View license
def get_table(name):
    if name not in cached_tables:
        meta = MetaData()
        meta.reflect(bind=model.meta.engine)
        table = meta.tables[name]
        cached_tables[name] = table
    return cached_tables[name]

Example 30

Project: ibis
Source File: test_sqlalchemy.py
View license
    def setUp(self):
        self.con = MockAlchemyConnection()
        self.alltypes = self.con.table('functional_alltypes')
        self.sa_alltypes = self.con.meta.tables['functional_alltypes']
        self.meta = sa.MetaData()

        self.sa_star1 = self._get_sqla('star1')

Example 31

Project: mindpark
Source File: metric.py
View license
    def _create_table(self, names):
        metadata = sql.MetaData()
        columns = [
            sql.Column('id', mp.utility.Uuid, primary_key=True, default=uuid.uuid4),
            sql.Column('timestamp', sql.DateTime, default=datetime.now),
            sql.Column('step', sql.Integer),
            sql.Column('epoch', sql.Integer),
            sql.Column('training', sql.Boolean),
            sql.Column('episode', sql.Integer)]
        columns += [sql.Column(x, sql.Float) for x in names]
        table = sql.Table(self.name, metadata, *columns)
        metadata.create_all(self._engine)
        return table

Example 32

Project: aiohttp_admin
Source File: test_sa_validator.py
View license
@pytest.fixture
def table():

    meta = sa.MetaData()
    post = sa.Table(
        'post', meta,
        sa.Column('id', sa.Integer, nullable=False),
        sa.Column('title', sa.String(200), nullable=False),
        sa.Column('body', sa.Text, nullable=False),
        sa.Column('views', sa.Integer, nullable=False),
        sa.Column('average_note', sa.Float, nullable=False),
        sa.Column('pictures', postgresql.JSON, server_default='{}'),
        sa.Column('published_at', sa.Date, nullable=False),
        sa.Column('tags', postgresql.ARRAY(sa.Integer), server_default='[]'),

        # Indexes #
        sa.PrimaryKeyConstraint('id', name='post_id_pkey'))
    return post

Example 33

Project: awesomestream
Source File: backends.py
View license
    def setup_table(self):
        from sqlalchemy import MetaData, Table, Column, String, Text, DateTime
        index_columns = []
        for k in self.keys:
            index_columns.append(Column(k, Text, index=True))
        self.metadata = MetaData()
        self.metadata.bind = self.engine
        self.table = Table(self.table_name, self.metadata,
            Column('key', String(length=36), primary_key=True),
            Column('data', Text, nullable=False),
            Column('date', DateTime, default=datetime.datetime.now, index=True,
                nullable=False),
            *index_columns
        )
        self.table.create(bind=self.engine, checkfirst=True)

Example 34

View license
def upgrade(migrate_engine):
    meta = MetaData(bind=migrate_engine)
    people = Table('people', meta, autoload=True)
    privacyc = Column("privacy", Boolean, default=False, nullable=False)
    try:
        privacyc.create(people)
    except ProgrammingError:
        print "Column exists."

Example 35

View license
def reset_alembic(alembic_version):

    with createApp().app_context():
        db = GlobalDB.db()

        engine = db.engine
        sess = db.session
        metadata = MetaData(bind=engine)
        alembic_table = Table('alembic_version', metadata, autoload=True)
        u = update(alembic_table)
        u = u.values({"version_num": alembic_version})
        sess.execute(u)
        sess.commit()

Example 36

Project: alchimia
Source File: test_engine.py
View license
    def test_transaction_commit(self):
        metadata = sqlalchemy.MetaData()
        tbl = sqlalchemy.Table(
            'mytable', metadata,
            sqlalchemy.Column("id", sqlalchemy.Integer(), primary_key=True),
            sqlalchemy.Column("num", sqlalchemy.Integer()),
        )

        conn = self.get_connection()
        self.successResultOf(conn.execute(CreateTable(tbl)))
        trx = self.successResultOf(conn.begin())
        self.successResultOf(conn.execute(tbl.insert().values(num=42)))
        rows = self.execute_fetchall(conn, tbl.select())
        assert len(rows) == 1

        self.successResultOf(trx.commit())
        rows = self.execute_fetchall(conn, tbl.select())
        assert len(rows) == 1

Example 37

Project: fingerprint-securedrop
Source File: database.py
View license
    def __init__(self, **kwargs):
        """Read current structure from database"""
        super().__init__(**kwargs)

        # Generate mappings from existing tables
        metadata = MetaData(schema='raw')
        metadata.reflect(self.engine)
        Base = automap_base(metadata=metadata)
        Base.prepare()

        # Our fundamental objects are:
        self.Onion = Base.classes.hs_history
        self.Example = Base.classes.frontpage_examples
        self.Cell = Base.classes.frontpage_traces
        self.Crawl = Base.classes.crawls

Example 38

Project: jsontableschema-sql-py
Source File: storage.py
View license
    def __init__(self, engine, dbschema=None, prefix=''):

        # Set attributes
        self.__connection = engine.connect()
        self.__dbschema = dbschema
        self.__prefix = prefix
        self.__descriptors = {}

        # Create metadata
        self.__metadata = MetaData(
            bind=self.__connection,
            schema=self.__dbschema,
            reflect=True)

Example 39

Project: bedup
Source File: migrations.py
View license
def upgrade_schema(engine):
    context = MigrationContext.configure(engine.connect())
    context._ensure_version_table()
    current_rev = context.get_current_revision()

    if current_rev is None:
        inspected_meta = MetaData()
        inspected_meta.reflect(bind=engine)
        if 'Inode' in inspected_meta.tables:
            inspected_rev = 1
            upgrade_with_range(context, inspected_rev, REV)
        else:
            META.create_all(engine)
        context.impl._exec(context._version.insert().values(version_num=REV))
    else:
        current_rev = int(current_rev)
        upgrade_with_range(context, current_rev, REV)
        context.impl._exec(context._version.update().values(version_num=REV).where(
                        context._version.c.version_num == current_rev))

Example 40

Project: geoalchemy2
Source File: test_functional.py
View license
    def test_reflection(self):
        t = Table(
            'lake',
            MetaData(),
            schema='gis',
            autoload=True,
            autoload_with=engine)
        type_ = t.c.geom.type
        assert isinstance(type_, Geometry)
        if not postgis_version.startswith('2.'):
            assert type_.geometry_type == 'GEOMETRY'
            assert type_.srid == -1
        else:
            assert type_.geometry_type == 'LINESTRING'
            assert type_.srid == 4326

Example 41

Project: Flask-Blogging
Source File: test_sqlastorage.py
View license
    def _create_storage(self):
        self._engine = create_engine(
            "postgresql+psycopg2://postgres:@localhost/flask_blogging")
        self._meta = sqla.MetaData()
        self.storage = SQLAStorage(self._engine, metadata=self._meta)
        self._meta.create_all(bind=self._engine)

Example 42

Project: Flask-Blogging
Source File: test_views.py
View license
    def _create_storage(self):
        temp_dir = tempfile.gettempdir()
        self._dbfile = os.path.join(temp_dir, "temp.db")
        conn_string = 'sqlite:///'+self._dbfile
        engine = create_engine(conn_string)
        meta = MetaData()
        self.storage = SQLAStorage(engine, metadata=meta)
        meta.create_all(bind=engine)

Example 43

Project: emailhunter-clone
Source File: database.py
View license
	def connect(self):

		self.engine = create_engine('sqlite:///' + DATABASE_NAME)
		self.connection = self.engine.connect()
		self.connected = True if self.connection else False
		self.metadata = MetaData()

		# Define the tables
		self.website_table = Table('website', self.metadata,
			Column('id', Integer, primary_key=True),
			Column('url', String, nullable=False),
			Column('has_crawled', Boolean, default=False),
			Column('emails', String, nullable=True),
		)

		# Create the tables
		self.metadata.create_all(self.engine)

Example 44

Project: synnefo
Source File: public.py
View license
    def __init__(self, **params):
        DBWorker.__init__(self, **params)
        try:
            metadata = MetaData(self.engine)
            self.public = Table('public', metadata, autoload=True)
        except NoSuchTableError:
            tables = create_tables(self.engine)
            map(lambda t: self.__setattr__(t.name, t), tables)

Example 45

Project: synnefo
Source File: quotaholder_serials.py
View license
def create_tables(engine):
    metadata = MetaData()
    columns = []
    columns.append(Column('serial', BigInteger, primary_key=True))
    Table('qh_serials', metadata, *columns, mysql_engine='InnoDB')

    metadata.create_all(engine)
    return metadata.sorted_tables

Example 46

Project: montage
Source File: drop_schema.py
View license
def drop_schema(db_url, echo=True):

    # echo="debug" also prints results of selects, etc.
    engine = create_engine(db_url, echo=echo)
    metadata = MetaData()
    metadata.reflect(bind=engine)
    metadata.drop_all(engine)

    return

Example 47

Project: coilmq
Source File: __init__.py
View license
def init_model(engine, create=True, drop=False):
    """
    Initializes the shared SQLAlchemy state in the L{coilmq.store.sa.model} module.

    @param engine: The SQLAlchemy engine instance.
    @type engine: C{sqlalchemy.Engine}

    @param create: Whether to create the tables (if they do not exist).
    @type create: C{bool}

    @param drop: Whether to drop the tables (if they exist).
    @type drop: C{bool}
    """
    meta.engine = engine
    meta.metadata = MetaData(bind=meta.engine)
    meta.Session = scoped_session(sessionmaker(bind=meta.engine))
    model.setup_tables(create=create, drop=drop)

Example 48

Project: kittystore
Source File: test_sa_migrations.py
View license
    def test_existing_db_from_storm(self):
        Base.metadata.create_all(self.sm.engine)
        # Create a patch table to look like a Storm DB
        tmpmd = sa.MetaData()
        sa.Table("patch", tmpmd, sa.Column("version", sa.Integer))
        tmpmd.create_all(self.sm.engine)
        # Now test
        self.sm._create = Mock()
        version = self.sm.setup_db()
        self.assertFalse(self.sm._create.called)
        self.assertEqual(version, self.sm.script.get_current_head())
        self.assertAllTablesCreated()
        # Check that the patch table is gone
        tmpmd = sa.MetaData()
        tmpmd.reflect(self.sm.engine)
        self.assertFalse("patch" in tmpmd.tables)
        self.assertEqual(self._get_db_rev(), version)

Example 49

Project: indico
Source File: createDatabaseGraphs.py
View license
def generate_schema_graph(uri, output):
    graph = create_schema_graph(metadata=MetaData(uri),
                                show_datatypes=False,
                                show_indexes=False,
                                rankdir='LR', # or TP
                                concentrate=False) # no joins of tables together
    graph.write_png(output)

Example 50

Project: census
Source File: utils.py
View license
def _create_base_table(name):
    metadata = MetaData()
    sql_table = Table(name, metadata)
    for name,length in LINKING_COLUMNS:
        sql_table.append_column(Column(name, String(length=length), nullable=False))

    return sql_table