本文整理汇总了Python中alembic.operations.Operations类的典型用法代码示例。如果您正苦于以下问题:Python Operations类的具体用法?Python Operations怎么用?Python Operations使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Operations类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_operations
def create_operations(ctx=None, **kwargs):
"""Create an alembic operations object."""
if ctx is None:
ctx = create_migration_ctx(**kwargs)
operations = Operations(ctx)
operations.has_table = has_table
return operations
示例2: test_standalone_op
def test_standalone_op():
eng, buf = capture_db()
env = MigrationContext.configure(eng)
op = Operations(env)
op.alter_column("t", "c", nullable=True)
eq_(buf, ['ALTER TABLE t ALTER COLUMN c DROP NOT NULL'])
示例3: _fixture
def _fixture(self):
migration_context = mock.Mock(opts={})
op = Operations(migration_context)
batch = op.batch_alter_table('tname', recreate='never').__enter__()
with mock.patch("alembic.operations.sa_schema") as mock_schema:
yield batch
batch.impl.flush()
self.mock_schema = mock_schema
示例4: fix
def fix(self):
context = MigrationContext.configure(self.parent.engine.connect())
op = Operations(context)
for table in self.parent.base.metadata.sorted_tables:
if table.name == self.table:
for column in table.columns:
if column.name == self.name:
with op.batch_alter_table(table.name) as batch_op:
batch_op.add_column(column.copy())
return
示例5: add_columns
def add_columns(engine, raw_diffs, table_names):
with engine.begin() as conn:
ctx = get_migration_context(conn, table_names)
op = Operations(ctx)
columns = _get_columns_to_add(raw_diffs, table_names)
for col in columns:
table_name = col.table.name
# the column has a reference to a table definition that already
# has the column defined, so remove that and add the column
col.table = None
op.add_column(table_name, col)
示例6: _fixture
def _fixture(self, schema=None):
migration_context = mock.Mock(
opts={}, impl=mock.MagicMock(__dialect__='sqlite'))
op = Operations(migration_context)
batch = op.batch_alter_table(
'tname', recreate='never', schema=schema).__enter__()
mock_schema = mock.MagicMock()
with mock.patch("alembic.operations.schemaobj.sa_schema", mock_schema):
yield batch
batch.impl.flush()
self.mock_schema = mock_schema
示例7: get_db_tables
def get_db_tables(conn):
"""Get current and default table values from the db.
:param engine: Initialized alembic engine object.
:type engine: object
:returns: tuple
"""
query = text("SELECT TABLE_NAME from information_schema.tables\
WHERE TABLE_NAME\
LIKE '%alembic_version%'\
AND table_schema = 'refstack'")
context = alembic_migration.MigrationContext.configure(conn)
op = Operations(context)
connection = op.get_bind()
search = connection.execute(query)
result = search.fetchall()
if isinstance(result, Iterable):
result = [table[0] for table in result]
else:
result = None
# if there is more than one version table, modify the
# one that does not have the default name, because subunit2sql uses the
# default name.
if result:
current_name =\
next((table for table in result if table != "alembic_version"),
result[0])
current_name = current_name.decode('utf-8')
current_version = get_table_version(conn, current_name)
default_name =\
next((table for table in result
if table == "alembic_version"), None)
default_version = get_table_version(conn, default_name)
if len(result) > 1 and not current_version:
if not default_name:
# this is the case where there is more than one
# nonstandard-named alembic table, and no default
current_name = next((table for table in result
if table != current_name),
result[0])
current_name = current_name.decode('utf-8')
elif current_name:
# this is the case where the current-named table
# exists, but is empty
current_name = default_name
current_version = default_version
current_table = (current_name, current_version)
default_table = (default_name, default_version)
else:
default_table = (None, None)
current_table = default_table
return current_table, default_table
示例8: PostgresqlInlineLiteralTest
class PostgresqlInlineLiteralTest(TestBase):
__only_on__ = "postgresql"
__backend__ = True
@classmethod
def setup_class(cls):
cls.bind = config.db
cls.bind.execute(
"""
create table tab (
col varchar(50)
)
"""
)
cls.bind.execute(
"""
insert into tab (col) values
('old data 1'),
('old data 2.1'),
('old data 3')
"""
)
@classmethod
def teardown_class(cls):
cls.bind.execute("drop table tab")
def setUp(self):
self.conn = self.bind.connect()
ctx = MigrationContext.configure(self.conn)
self.op = Operations(ctx)
def tearDown(self):
self.conn.close()
def test_inline_percent(self):
# TODO: here's the issue, you need to escape this.
tab = table("tab", column("col"))
self.op.execute(
tab.update()
.where(tab.c.col.like(self.op.inline_literal("%.%")))
.values(col=self.op.inline_literal("new data")),
execution_options={"no_parameters": True},
)
eq_(
self.conn.execute(
"select count(*) from tab where col='new data'"
).scalar(),
1,
)
示例9: replace
def replace(cls, operations: Operations,
target, replaces=None, replace_with=None) -> None:
if replaces:
old_obj = cls._get_object_from_version(operations, replaces)
drop_old = cls(old_obj).reverse()
create_new = cls(target)
elif replace_with:
old_obj = cls._get_object_from_version(operations, replace_with)
drop_old = cls(target).reverse()
create_new = cls(old_obj)
else:
raise TypeError("replaces or replace_with is required")
operations.invoke(drop_old)
operations.invoke(create_new)
示例10: test_missing_column
def test_missing_column(self):
adapter = self._get_adapter()
adapter.build_table()
with adapter.engine.begin() as connection:
context = MigrationContext.configure(connection)
op = Operations(context)
op.drop_column(adapter.get_table().name, 'name')
doc = {
"_id": '123',
"domain": "domain",
"doc_type": "CommCareCase",
"name": 'bob'
}
with self.assertRaises(MissingColumnWarning):
adapter.best_effort_save(doc)
示例11: _alter_column_name
def _alter_column_name(self, base, old_name, new_name):
# NOTE: Create alembic connection and operation object! By John Doe
db_conn=config.ENGINE.connect()
alembic_ctx=MigrationContext.configure(db_conn)
alembic_op=Operations(alembic_ctx)
doc_table=get_doc_table(
base.metadata.name,
config.METADATA,
**base.relational_fields
)
alembic_op.alter_column(
doc_table.name,
old_name,
new_column_name=new_name
)
db_conn.close()
示例12: add_columns
def add_columns(engine, raw_diffs, table_names):
changes = defaultdict(list)
with engine.begin() as conn:
ctx = get_migration_context(conn, table_names)
op = Operations(ctx)
columns = _get_columns_to_add(raw_diffs, table_names)
for col in columns:
table_name = col.table.name
# the column has a reference to a table definition that already
# has the column defined, so remove that and add the column
col.table = None
changes[table_name].append({
'type': DiffTypes.ADD_COLUMN,
'value': col.name
})
op.add_column(table_name, col)
return dict(changes)
示例13: recheck_alembic_table
def recheck_alembic_table(conn):
"""check and update alembic version table.
Should check current alembic version table against conf and rename the
existing table if the two values don't match.
"""
conf_table = getattr(CONF, 'version_table')
conf_table_version = get_table_version(conn, conf_table)
current_table, default_table = get_db_tables(conn)
if current_table[0]:
if current_table[0] != conf_table:
context = alembic_migration.MigrationContext.configure(conn)
op = Operations(context)
if conf_table and not conf_table_version:
# make sure there is not present-but-empty table
# that will prevent us from renaming the current table
op.drop_table(conf_table)
op.rename_table(current_table[0], conf_table)
示例14: PostgresqlInlineLiteralTest
class PostgresqlInlineLiteralTest(TestCase):
@classmethod
def setup_class(cls):
cls.bind = db_for_dialect("postgresql")
cls.bind.execute("""
create table tab (
col varchar(50)
)
""")
cls.bind.execute("""
insert into tab (col) values
('old data 1'),
('old data 2.1'),
('old data 3')
""")
@classmethod
def teardown_class(cls):
cls.bind.execute("drop table tab")
def setUp(self):
self.conn = self.bind.connect()
ctx = MigrationContext.configure(self.conn)
self.op = Operations(ctx)
def tearDown(self):
self.conn.close()
def test_inline_percent(self):
# TODO: here's the issue, you need to escape this.
tab = table('tab', column('col'))
self.op.execute(
tab.update().where(
tab.c.col.like(self.op.inline_literal('%.%'))
).values(col=self.op.inline_literal('new data')),
execution_options={'no_parameters': True}
)
eq_(
self.conn.execute(
"select count(*) from tab where col='new data'").scalar(),
1,
)
示例15: run_migrations
def run_migrations(self, **kw):
"""Run migrations as determined by the current command line
configuration
as well as versioning information present (or not) in the current
database connection (if one is present).
The function accepts optional ``**kw`` arguments. If these are
passed, they are sent directly to the ``upgrade()`` and
``downgrade()``
functions within each target revision file. By modifying the
``script.py.mako`` file so that the ``upgrade()`` and ``downgrade()``
functions accept arguments, parameters can be passed here so that
contextual information, usually information to identify a particular
database in use, can be passed from a custom ``env.py`` script
to the migration functions.
This function requires that a :class:`.MigrationContext` has
first been made available via :meth:`.configure`.
"""
with Operations.context(self._migration_context):
self.get_context().run_migrations(**kw)