我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sqlalchemy.Index()。
def test_noindexes_table(self): simple_items = Table( 'simple_items', self.metadata, Column('number', INTEGER), CheckConstraint('number > 2') ) simple_items.indexes.add(Index('idx_number', simple_items.c.number)) assert self.generate_code(noindexes=True) == """\ # coding: utf-8 from sqlalchemy import CheckConstraint, Column, Integer, MetaData, Table metadata = MetaData() t_simple_items = Table( 'simple_items', metadata, Column('number', Integer), CheckConstraint('number > 2') ) """
def define_index(cls, metadata, users): Index("users_t_idx", users.c.test1, users.c.test2) Index("users_all_idx", users.c.user_id, users.c.test2, users.c.test1)
def upgrade(): op.create_table( 'container_actions', sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('id', sa.Integer(), nullable=False), sa.Column('action', sa.String(length=255), nullable=True), sa.Column('container_uuid', sa.String(length=36), nullable=False), sa.Column('request_id', sa.String(length=255), nullable=True), sa.Column('user_id', sa.String(length=255), nullable=True), sa.Column('project_id', sa.String(length=255), nullable=True), sa.Column('start_time', sa.DateTime(), nullable=True), sa.Column('finish_time', sa.DateTime(), nullable=True), sa.Column('message', sa.String(length=255), nullable=True), sa.Index('container_uuid_idx', 'container_uuid'), sa.Index('request_id_idx', 'request_id'), sa.ForeignKeyConstraint(['container_uuid'], ['container.uuid'], ), sa.PrimaryKeyConstraint('id') )
def upgrade(): op.create_table( 'allocation', sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('id', sa.Integer(), nullable=False), sa.Column('resource_provider_id', sa.Integer(), nullable=False), sa.Column('consumer_id', sa.String(36), nullable=False), sa.Column('resource_class_id', sa.Integer(), nullable=False), sa.Column('used', sa.Integer(), nullable=False), sa.Column('is_nested', sa.Integer(), nullable=False), sa.Column('blob', zun.db.sqlalchemy.models.JSONEncodedList(), nullable=True), sa.Index('allocation_resource_provider_class_used_idx', 'resource_provider_id', 'resource_class_id', 'used'), sa.Index('allocation_consumer_id_idx', 'consumer_id'), sa.Index('allocation_resource_class_id_idx', 'resource_class_id'), sa.PrimaryKeyConstraint('id'), )
def test_noconstraints_table(self): simple_items = Table( 'simple_items', self.metadata, Column('number', INTEGER), CheckConstraint('number > 2') ) simple_items.indexes.add(Index('idx_number', simple_items.c.number)) assert self.generate_code(noconstraints=True) == """\ # coding: utf-8 from sqlalchemy import Column, Integer, MetaData, Table metadata = MetaData() t_simple_items = Table( 'simple_items', metadata, Column('number', Integer, index=True) ) """
def test_indexes_class(self): simple_items = Table( 'simple_items', self.metadata, Column('id', INTEGER, primary_key=True), Column('number', INTEGER), Column('text', VARCHAR) ) simple_items.indexes.add(Index('idx_number', simple_items.c.number)) simple_items.indexes.add(Index('idx_text_number', simple_items.c.text, simple_items.c.number)) simple_items.indexes.add(Index('idx_text', simple_items.c.text, unique=True)) assert self.generate_code() == """\ # coding: utf-8 from sqlalchemy import Column, Index, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class SimpleItem(Base): __tablename__ = 'simple_items' __table_args__ = ( Index('idx_text_number', 'text', 'number'), ) id = Column(Integer, primary_key=True) number = Column(Integer, index=True) text = Column(String, unique=True) """
def _to_table(self, param): """Returns the table object for the given param object.""" if isinstance(param, (sa.Column, sa.Index, sa.schema.Constraint)): ret = param.table else: ret = param return ret
def start_alter_table(self, param): """Returns the start of an ``ALTER TABLE`` SQL-Statement. Use the param object to determine the table name and use it for building the SQL statement. :param param: object to determine the table from :type param: :class:`sqlalchemy.Column`, :class:`sqlalchemy.Index`, :class:`sqlalchemy.schema.Constraint`, :class:`sqlalchemy.Table`, or string (table name) """ table = self._to_table(param) self.append('\nALTER TABLE %s ' % self.preparer.format_table(table)) return table
def visit_column(self, column): """Create a column (table already exists). :param column: column object :type column: :class:`sqlalchemy.Column` instance """ if column.default is not None: self.traverse_single(column.default) table = self.start_alter_table(column) self.append("ADD ") self.append(self.get_column_specification(column)) for cons in column.constraints: self.traverse_single(cons) self.execute() # ALTER TABLE STATEMENTS # add indexes and unique constraints if column.index_name: Index(column.index_name,column).create() elif column.unique_name: constraint.UniqueConstraint(column, name=column.unique_name).create() # SA bounds FK constraints to table, add manually for fk in column.foreign_keys: self.add_foreignkey(fk.constraint) # add primary key constraint if needed if column.primary_key_name: cons = constraint.PrimaryKeyConstraint(column, name=column.primary_key_name) cons.create()
def _to_index(index, table=None, engine=None): """Return if instance of Index, else construct new with metadata""" if isinstance(index, sqlalchemy.Index): return index # Given: index name; table name required table = _to_table(table, engine) ret = sqlalchemy.Index(index) ret.table = table return ret
def rename(self, name, connection=None, **kwargs): """Change the name of an index. :param name: New name of the Index. :type name: string :param connection: reuse connection istead of creating new one. :type connection: :class:`sqlalchemy.engine.base.Connection` instance """ engine = self.table.bind self.new_name = name visitorcallable = get_engine_visitor(engine, 'schemachanger') engine._run_visitor(visitorcallable, self, connection, **kwargs) self.name = name
def define_temp_tables(cls, metadata): # cheat a bit, we should fix this with some dialect-level # temp table fixture if testing.against("oracle"): kw = { 'prefixes': ["GLOBAL TEMPORARY"], 'oracle_on_commit': 'PRESERVE ROWS' } else: kw = { 'prefixes': ["TEMPORARY"], } user_tmp = Table( "user_tmp", metadata, Column("id", sa.INT, primary_key=True), Column('name', sa.VARCHAR(50)), Column('foo', sa.INT), sa.UniqueConstraint('name', name='user_tmp_uq'), sa.Index("user_tmp_ix", "foo"), **kw ) if testing.requires.view_reflection.enabled and \ testing.requires.temporary_views.enabled: event.listen( user_tmp, "after_create", DDL("create temporary view user_tmp_v as " "select * from user_tmp") ) event.listen( user_tmp, "before_drop", DDL("drop view user_tmp_v") )
def contract_creation_exceptions(): """Special migration for the blueprint to support Keystone V3. We drop all tenant_id columns and create project_id columns instead. """ return { sa.Column: ['.'.join([table, 'project_id']) for table in get_tables()], sa.Index: get_tables() }
def index(self): sys.stderr.write("indexing ... ") t0 = time.time() sql.Index("idx_variants_chrom_start", self.variants.c.chrom, self.variants.c.start).create() sql.Index("idx_variants_exonic", self.variants.c.is_exonic).create() sql.Index("idx_variants_coding", self.variants.c.is_coding).create() sql.Index("idx_variants_impact", self.variants.c.impact).create() sql.Index("idx_variants_impact_severity", self.variants.c.impact_severity).create() sys.stderr.write("finished in %.1f seconds...\n" % (time.time() - t0)) sys.stderr.write("total time: in %.1f seconds...\n" % (time.time() - self.t0))
def daily_market_table(metadata, market): table_name = history_key(market) # Index columns date_col = sa.Column('Date', sa.DATETIME, nullable=False) asset_col = sa.Column( config.ASSET_ID, sa.INTEGER, sa.ForeignKey(config.ASSETS + '.' + config.ID), nullable=False ) return sa.Table( table_name, metadata, date_col, asset_col, sa.Column('Units', sa.INTEGER, nullable=False), sa.Column('$Volume', sa.INTEGER, nullable=False), sa.Column('LowPrice', sa.INTEGER, nullable=False), sa.Column('HighPrice', sa.INTEGER, nullable=False), sa.Column('AvgPrice', sa.DECIMAL, nullable=False), sa.Column('LastPrice', sa.INTEGER, nullable=True), # Null == NaN? sa.Index('idx', asset_col, date_col, unique=True), )
def quotes_table(metadata, market): table_name = quote_key(market) # Index columns ts_col = sa.Column('Timestamp', sa.TIMESTAMP, nullable=False) asset_col = sa.Column( config.ASSET_ID, sa.INTEGER, sa.ForeignKey(config.ASSETS + '.' + config.ID), nullable=False ) return sa.Table( table_name, metadata, ts_col, asset_col, sa.Column('Bid', sa.INTEGER, nullable=False), # No example of nullable sa.Column('Ask', sa.INTEGER, nullable=False), sa.Column('Last', sa.INTEGER, nullable=False), sa.Column('Low', sa.INTEGER, nullable=True), sa.Column('High', sa.INTEGER, nullable=True), sa.Column('Average', sa.DECIMAL, nullable=True), sa.Index('idx', asset_col, ts_col, unique=True), )
def table(self, Base): class ArticleTranslation(Base): __tablename__ = 'article_translation' id = sa.Column(sa.Integer, primary_key=True) locale = sa.Column(sa.String(10), primary_key=True) title = sa.Column(sa.String(100)) is_published = sa.Column(sa.Boolean, index=True) is_deleted = sa.Column(sa.Boolean) is_archived = sa.Column(sa.Boolean) __table_args__ = ( sa.Index('my_index', is_deleted, is_archived), ) return ArticleTranslation.__table__
def test_composite_fk_with_index(self, Base): class User(Base): __tablename__ = 'user' first_name = sa.Column(sa.Unicode(255), primary_key=True) last_name = sa.Column(sa.Unicode(255), primary_key=True) class Article(Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) author_first_name = sa.Column(sa.Unicode(255)) author_last_name = sa.Column(sa.Unicode(255)) __table_args__ = ( sa.ForeignKeyConstraint( [author_first_name, author_last_name], [User.first_name, User.last_name] ), sa.Index( 'my_index', author_first_name, author_last_name ) ) table = Article.__table__ constraint = get_fk_constraint_for_columns( table, table.c.author_first_name, table.c.author_last_name ) assert has_index(constraint)
def test_composite_fk_with_partial_index_match(self, Base): class User(Base): __tablename__ = 'user' first_name = sa.Column(sa.Unicode(255), primary_key=True) last_name = sa.Column(sa.Unicode(255), primary_key=True) class Article(Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) author_first_name = sa.Column(sa.Unicode(255)) author_last_name = sa.Column(sa.Unicode(255)) __table_args__ = ( sa.ForeignKeyConstraint( [author_first_name, author_last_name], [User.first_name, User.last_name] ), sa.Index( 'my_index', author_first_name, author_last_name, id ) ) table = Article.__table__ constraint = get_fk_constraint_for_columns( table, table.c.author_first_name, table.c.author_last_name ) assert has_index(constraint)
def article_translations(self, Base): class ArticleTranslation(Base): __tablename__ = 'article_translation' id = sa.Column(sa.Integer, primary_key=True) locale = sa.Column(sa.String(10), primary_key=True) title = sa.Column(sa.String(100)) is_published = sa.Column(sa.Boolean, index=True) is_deleted = sa.Column(sa.Boolean, unique=True) is_archived = sa.Column(sa.Boolean) __table_args__ = ( sa.Index('my_index', is_archived, is_published, unique=True), ) return ArticleTranslation.__table__
def test_composite_fk_with_partial_index_match(self, Base): class User(Base): __tablename__ = 'user' first_name = sa.Column(sa.Unicode(255), primary_key=True) last_name = sa.Column(sa.Unicode(255), primary_key=True) class Article(Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) author_first_name = sa.Column(sa.Unicode(255)) author_last_name = sa.Column(sa.Unicode(255)) __table_args__ = ( sa.ForeignKeyConstraint( [author_first_name, author_last_name], [User.first_name, User.last_name] ), sa.Index( 'my_index', author_first_name, author_last_name, id, unique=True ) ) table = Article.__table__ constraint = get_fk_constraint_for_columns( table, table.c.author_first_name, table.c.author_last_name ) assert not has_unique_index(constraint)
def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) # Add a new column to store PCI device parent address pci_devices = Table('pci_devices', meta, autoload=True) shadow_pci_devices = Table('shadow_pci_devices', meta, autoload=True) parent_addr = Column('parent_addr', String(12), nullable=True) if not hasattr(pci_devices.c, 'parent_addr'): pci_devices.create_column(parent_addr) if not hasattr(shadow_pci_devices.c, 'parent_addr'): shadow_pci_devices.create_column(parent_addr.copy()) # Create index parent_index = Index('ix_pci_devices_compute_node_id_parent_addr_deleted', pci_devices.c.compute_node_id, pci_devices.c.parent_addr, pci_devices.c.deleted) parent_index.create(migrate_engine)
def upgrade(migrate_engine): meta = sa.MetaData(bind=migrate_engine) tags = sa.Table('tags', meta, sa.Column('resource_id', sa.String(36), primary_key=True, nullable=False), sa.Column('tag', sa.Unicode(80), primary_key=True, nullable=False), sa.Index('tags_tag_idx', 'tag'), mysql_engine='InnoDB', mysql_charset='utf8') tags.create()