本文整理匯總了Python中sqlalchemy.inspect方法的典型用法代碼示例。如果您正苦於以下問題:Python sqlalchemy.inspect方法的具體用法?Python sqlalchemy.inspect怎麽用?Python sqlalchemy.inspect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sqlalchemy
的用法示例。
在下文中一共展示了sqlalchemy.inspect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: jsonify
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def jsonify(self):
d = {
"id": self.id,
"creator": self.creator,
"name": self.name,
"unit": self.unit,
}
unloaded = sqlalchemy.inspect(self).unloaded
if 'resource' in unloaded:
d['resource_id'] = self.resource_id
else:
d['resource'] = self.resource
if 'archive_policy' in unloaded:
d['archive_policy_name'] = self.archive_policy_name
else:
d['archive_policy'] = self.archive_policy
if self.creator is None:
d['created_by_user_id'] = d['created_by_project_id'] = None
else:
d['created_by_user_id'], _, d['created_by_project_id'] = (
self.creator.partition(":")
)
return d
示例2: upgrade
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def upgrade():
conn = op.get_bind()
insp = inspect(conn)
fk_names = [fk['name'] for fk in insp.get_foreign_keys('host')]
if ("fk_hypervisor_id_resource_id" not in fk_names and
"fk_host_id_resource_id" in fk_names):
# NOTE(sileht): we are already good, the BD have been created from
# scratch after "a54c57ada3f5"
return
op.drop_constraint("fk_hypervisor_id_resource_id", "host",
type_="foreignkey")
op.drop_constraint("fk_hypervisor_history_resource_history_revision",
"host_history", type_="foreignkey")
op.create_foreign_key("fk_host_id_resource_id", "host", "resource",
["id"], ["id"], ondelete="CASCADE")
op.create_foreign_key("fk_host_history_resource_history_revision",
"host_history", "resource_history",
["revision"], ["revision"], ondelete="CASCADE")
示例3: _test_get_table_names
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def _test_get_table_names(self, schema=None, table_type='table',
order_by=None):
meta = self.metadata
users, addresses, dingalings = self.tables.users, \
self.tables.email_addresses, self.tables.dingalings
insp = inspect(meta.bind)
if table_type == 'view':
table_names = insp.get_view_names(schema)
table_names.sort()
answer = ['email_addresses_v', 'users_v']
eq_(sorted(table_names), answer)
else:
table_names = insp.get_table_names(schema,
order_by=order_by)
if order_by == 'foreign_key':
answer = ['users', 'email_addresses', 'dingalings']
eq_(table_names, answer)
else:
answer = ['dingalings', 'email_addresses', 'users']
eq_(sorted(table_names), answer)
示例4: _test_get_indexes
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def _test_get_indexes(self, schema=None):
meta = self.metadata
users, addresses, dingalings = self.tables.users, \
self.tables.email_addresses, self.tables.dingalings
# The database may decide to create indexes for foreign keys, etc.
# so there may be more indexes than expected.
insp = inspect(meta.bind)
indexes = insp.get_indexes('users', schema=schema)
expected_indexes = [
{'unique': False,
'column_names': ['test1', 'test2'],
'name': 'users_t_idx'},
{'unique': False,
'column_names': ['user_id', 'test2', 'test1'],
'name': 'users_all_idx'}
]
index_names = [d['name'] for d in indexes]
for e_index in expected_indexes:
assert e_index['name'] in index_names
index = indexes[index_names.index(e_index['name'])]
for key in e_index:
eq_(e_index[key], index[key])
示例5: test_autoincrement_col
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def test_autoincrement_col(self):
"""test that 'autoincrement' is reflected according to sqla's policy.
Don't mark this test as unsupported for any backend !
(technically it fails with MySQL InnoDB since "id" comes before "id2")
A backend is better off not returning "autoincrement" at all,
instead of potentially returning "False" for an auto-incrementing
primary key column.
"""
meta = self.metadata
insp = inspect(meta.bind)
for tname, cname in [
('users', 'user_id'),
('email_addresses', 'address_id'),
('dingalings', 'dingaling_id'),
]:
cols = insp.get_columns(tname)
id_ = dict((c['name'], c) for c in cols)[cname]
assert id_.get('autoincrement', True)
示例6: force_drop_names
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def force_drop_names(*names):
"""Force the given table names to be dropped after test complete,
isolating for foreign key cycles
"""
from . import config
from sqlalchemy import inspect
@decorator
def go(fn, *args, **kw):
try:
return fn(*args, **kw)
finally:
drop_all_tables(
config.db, inspect(config.db), include_names=names)
return go
示例7: __init__
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def __init__(self, obj, visited_objects=None, relations=[]):
self.visited_objects = visited_objects or []
self.obj = obj
self.version_parent = self.obj.version_parent
self.parent_class = parent_class(self.obj.__class__)
self.parent_mapper = sa.inspect(self.parent_class)
self.session = sa.orm.object_session(self.obj)
self.relations = list(relations)
for path in relations:
subpath = path.split('.')[0]
if subpath not in self.parent_mapper.relationships:
raise ReverterException(
"Could not initialize Reverter. Class '%s' does not have "
"relationship '%s'." % (
parent_class(self.obj.__class__).__name__,
subpath
)
)
示例8: option
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def option(obj_or_class, option_name):
"""
Return the option value of given option for given versioned object or
class.
:param obj_or_class: SQLAlchemy declarative model object or class
:param option_name: The name of an option to return
"""
if isinstance(obj_or_class, AliasedClass):
obj_or_class = sa.inspect(obj_or_class).mapper.class_
cls = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__
if not hasattr(cls, '__versioned__'):
cls = parent_class(cls)
return get_versioning_manager(cls).option(
cls, option_name
)
示例9: get_inherited_denormalized_columns
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def get_inherited_denormalized_columns(self, table):
parent_models = list(versioned_parents(self.manager, self.model))
mapper = sa.inspect(self.model)
args = {}
if parent_models and not (mapper.single or mapper.concrete):
columns = [
self.manager.option(self.model, 'operation_type_column_name'),
self.manager.option(self.model, 'transaction_column_name')
]
if self.manager.option(self.model, 'strategy') == 'validity':
columns.append(
self.manager.option(
self.model,
'end_transaction_column_name'
)
)
for column in columns:
args[column] = column_property(
table.c[column],
*[m.__table__.c[column] for m in parent_models]
)
return args
示例10: changeset
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def changeset(self):
"""
Return a dictionary of changed fields in this version with keys as
field names and values as lists with first value as the old field value
and second list value as the new value.
"""
previous_version = self.previous
data = {}
for key in sa.inspect(self.__class__).columns.keys():
if is_internal_column(self, key):
continue
if not previous_version:
old = None
else:
old = getattr(previous_version, key)
new = getattr(self, key)
if old != new:
data[key] = [old, new]
manager = get_versioning_manager(self)
manager.plugins.after_construct_changeset(self, data)
return data
示例11: object_as_dict
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def object_as_dict(obj, relationships=False):
"""
Converts an SQLAlchemy instance to a dictionary.
:param relationships: If true, also include relationships in the output dict
"""
properties = inspect(obj).mapper.all_orm_descriptors
if not relationships:
properties = {
key: value
for key, value in properties.items()
if not hasattr(value, "prop")
or not isinstance(value.prop, RelationshipProperty)
}
return {key: getattr(obj, key) for key, value in properties.items()}
示例12: aliased_attrs
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def aliased_attrs(cls, aliased_class: AliasedClass, obj: object, *attr_names: str):
""" Wrap a whole list of dictionaries into aliased wrappers """
# Prepare AliasedInsp: this is what adapt_to_entity() wants
aliased_inspector = inspect(aliased_class)
assert aliased_inspector.is_aliased_class, '`aliased_class` must be an alias!'
# Convert every attribute
for attr_name in attr_names:
setattr(obj, attr_name,
# Wrap it with self
cls(getattr(obj, attr_name),
aliased_inspector)
)
# Done
return obj
示例13: sqlalchemy_to_dict
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def sqlalchemy_to_dict(obj):
"""Convert SQLAlchemy object to dict.
Args:
query (class): SQLAlchemy Object.
Returns:
dict: Return a dict representation of an SQLAlchemy object.
"""
fields = {}
for field in [c.key for c in inspect(obj).mapper.column_attrs]:
data = obj.__getattribute__(field)
try:
if isinstance(data, datetime):
data = data.strftime('%Y-%m-%d %H:%M:%S')
json.dumps(data)
fields[field] = data
except TypeError:
fields[field] = None
return fields
示例14: test_create_table_unknown_mysql_connector_error
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def test_create_table_unknown_mysql_connector_error(
self, sqlite_database, mysql_database, mysql_credentials, mocker, caplog
):
proc = MySQLtoSQLite(
sqlite_file=sqlite_database,
mysql_user=mysql_credentials.user,
mysql_password=mysql_credentials.password,
mysql_database=mysql_credentials.database,
mysql_host=mysql_credentials.host,
mysql_port=mysql_credentials.port,
)
class FakeSQLiteCursor:
def executescript(self, statement):
raise mysql.connector.Error(
msg="Error Code: 2000. Unknown MySQL error",
errno=errorcode.CR_UNKNOWN_ERROR,
)
mysql_inspect = inspect(mysql_database.engine)
mysql_tables = mysql_inspect.get_table_names()
mocker.patch.object(proc, "_sqlite_cur", FakeSQLiteCursor())
caplog.set_level(logging.DEBUG)
with pytest.raises(mysql.connector.Error):
proc._create_table(choice(mysql_tables))
示例15: test_create_table_sqlite3_error
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import inspect [as 別名]
def test_create_table_sqlite3_error(
self, sqlite_database, mysql_database, mysql_credentials, mocker, caplog
):
proc = MySQLtoSQLite(
sqlite_file=sqlite_database,
mysql_user=mysql_credentials.user,
mysql_password=mysql_credentials.password,
mysql_database=mysql_credentials.database,
mysql_host=mysql_credentials.host,
mysql_port=mysql_credentials.port,
)
class FakeSQLiteCursor:
def executescript(self, *args, **kwargs):
raise sqlite3.Error("Unknown SQLite error")
mysql_inspect = inspect(mysql_database.engine)
mysql_tables = mysql_inspect.get_table_names()
mocker.patch.object(proc, "_sqlite_cur", FakeSQLiteCursor())
caplog.set_level(logging.DEBUG)
with pytest.raises(sqlite3.Error):
proc._create_table(choice(mysql_tables))