本文整理汇总了Python中sqlalchemy.exists方法的典型用法代码示例。如果您正苦于以下问题:Python sqlalchemy.exists方法的具体用法?Python sqlalchemy.exists怎么用?Python sqlalchemy.exists使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy
的用法示例。
在下文中一共展示了sqlalchemy.exists方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: insert_single
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def insert_single(object_: Dict[str, Any], session: scoped_session) -> Any:
"""Insert instance of classes with single objects.
:param object_: object to be inserted
:param session: sqlalchemy scoped session
:return:
Raises:
ClassNotFound: If `type_` does not represt a valid/defined RDFClass.
Instance: If an Instance of type `type_` already exists.
"""
try:
rdf_class = session.query(RDFClass).filter(
RDFClass.name == object_["@type"]).one()
except NoResultFound:
raise ClassNotFound(type_=object_["@type"])
try:
session.query(Instance).filter(
Instance.type_ == rdf_class.id).all()[-1]
except (NoResultFound, IndexError, ValueError):
return insert(object_, session=session)
raise InstanceExists(type_=rdf_class.name)
示例2: init_db
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def init_db(app_db_path):
# Open session for database connection
global session
global app_DB_path
app_DB_path = app_db_path
engine = create_engine(u'sqlite:///{0}'.format(app_db_path), echo=False)
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
if os.path.exists(app_db_path):
Base.metadata.create_all(engine)
migrate_Database(session)
clean_database(session)
else:
Base.metadata.create_all(engine)
create_admin_user(session)
create_anonymous_user(session)
示例3: set_tombstone
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def set_tombstone(rse_id, scope, name, tombstone=OBSOLETE, session=None):
"""
Sets a tombstone on a replica.
:param rse_id: ID of RSE.
:param scope: scope of the replica DID.
:param name: name of the replica DID.
:param tombstone: the tombstone to set. Default is OBSOLETE
:param session: database session in use.
"""
stmt = update(models.RSEFileAssociation).where(and_(models.RSEFileAssociation.rse_id == rse_id, models.RSEFileAssociation.name == name, models.RSEFileAssociation.scope == scope,
~session.query(models.ReplicaLock).filter_by(scope=scope, name=name, rse_id=rse_id).exists()))\
.values(tombstone=tombstone)
result = session.execute(stmt)
if not result.rowcount:
try:
session.query(models.RSEFileAssociation).filter_by(scope=scope, name=name, rse_id=rse_id).one()
raise exception.ReplicaIsLocked('Replica %s:%s on RSE %s is locked.' % (scope, name, get_rse_name(rse_id=rse_id, session=session)))
except NoResultFound:
raise exception.ReplicaNotFound('Replica %s:%s on RSE %s could not be found.' % (scope, name, get_rse_name(rse_id=rse_id, session=session)))
示例4: _last_error_free_job
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def _last_error_free_job(cls, harvest_job):
# TODO weed out cancelled jobs somehow.
# look for jobs with no gather errors
jobs = \
model.Session.query(HarvestJob) \
.filter(HarvestJob.source == harvest_job.source) \
.filter(HarvestJob.gather_started != None) \
.filter(HarvestJob.status == 'Finished') \
.filter(HarvestJob.id != harvest_job.id) \
.filter(
~exists().where(
HarvestGatherError.harvest_job_id == HarvestJob.id)) \
.order_by(HarvestJob.gather_started.desc())
# now check them until we find one with no fetch/import errors
# (looping rather than doing sql, in case there are lots of objects
# and lots of jobs)
for job in jobs:
for obj in job.objects:
if obj.current is False and \
obj.report_status != 'not modified':
# unsuccessful, so go onto the next job
break
else:
return job
示例5: key_valid_const
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def key_valid_const(app_id: int, token: str, origin: Origin) -> bool:
"""Constant time check to see if `token` exists in the database. Compares
against all keys even if a match is found. Validates against the app id
and the hardware id provided."""
current_app.logger.info(f"key lookup by token {token} from {origin}")
found = False
for key in Key.query.all():
if (compare_digest(token, key.token) and
key.enabled and key.app_id == app_id
and compare_digest(origin.hwid, key.hwid)):
found = True
key.last_check_ts = datetime.utcnow()
key.last_check_ip = origin.ip
key.total_checks += 1
AuditLog.from_key(key, f"key check from {origin}", Event.KeyAccess)
return found
示例6: choose_vnfd
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def choose_vnfd(self, context, service_type,
required_attributes=None):
required_attributes = required_attributes or []
LOG.debug('required_attributes %s', required_attributes)
with context.session.begin(subtransactions=True):
query = (
context.session.query(VNFD).
filter(
sa.exists().
where(sa.and_(
VNFD.id == ServiceType.vnfd_id,
ServiceType.service_type == service_type))))
for key in required_attributes:
query = query.filter(
sa.exists().
where(sa.and_(
VNFD.id ==
VNFDAttribute.vnfd_id,
VNFDAttribute.key == key)))
LOG.debug('statements %s', query)
vnfd_db = query.first()
if vnfd_db:
return self._make_vnfd_dict(vnfd_db)
示例7: get_or_create_table
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def get_or_create_table(
self, table_name: Text
) -> "boto3.resources.factory.dynamodb.Table":
"""Returns table or creates one if the table name is not in the table list"""
import boto3
dynamo = boto3.resource("dynamodb", region_name=self.region)
if self.table_name not in self.client.list_tables()["TableNames"]:
table = dynamo.create_table(
TableName=self.table_name,
KeySchema=[
{"AttributeName": "sender_id", "KeyType": "HASH"},
{"AttributeName": "session_date", "KeyType": "RANGE"},
],
AttributeDefinitions=[
{"AttributeName": "sender_id", "AttributeType": "S"},
{"AttributeName": "session_date", "AttributeType": "N"},
],
ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
)
# Wait until the table exists.
table.meta.client.get_waiter("table_exists").wait(TableName=table_name)
return dynamo.Table(table_name)
示例8: ensure_schema_exists
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def ensure_schema_exists(session: "Session") -> None:
"""Ensure that the requested PostgreSQL schema exists in the database.
Args:
session: Session used to inspect the database.
Raises:
`ValueError` if the requested schema does not exist.
"""
schema_name = os.environ.get(POSTGRESQL_SCHEMA)
if not schema_name:
return
engine = session.get_bind()
if is_postgresql_url(engine.url):
query = sa.exists(
sa.select([(sa.text("schema_name"))])
.select_from(sa.text("information_schema.schemata"))
.where(sa.text(f"schema_name = '{schema_name}'"))
)
if not session.query(query).scalar():
raise ValueError(schema_name)
示例9: _create_database
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def _create_database(engine: "Engine", db: Text):
"""Create database `db` on `engine` if it does not exist."""
import psycopg2
conn = engine.connect()
cursor = conn.connection.cursor()
cursor.execute("COMMIT")
cursor.execute(f"SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{db}'")
exists = cursor.fetchone()
if not exists:
try:
cursor.execute(f"CREATE DATABASE {db}")
except psycopg2.IntegrityError as e:
logger.error(f"Could not create database '{db}': {e}")
cursor.close()
conn.close()
示例10: type_exists
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def type_exists(cls,
session,
inventory_index_id,
type_list=None):
"""Check if certain types of resources exists in the inventory.
Args:
session (object): Database session.
inventory_index_id (str): the id of the inventory to query.
type_list (list): List of types to check.
Returns:
bool: If these types of resources exists.
"""
return session.query(exists().where(and_(
Inventory.inventory_index_id == inventory_index_id,
Inventory.category == Categories.resource,
Inventory.resource_type.in_(type_list)
))).scalar()
示例11: test_correlation_to_extra
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def test_correlation_to_extra(self):
users, addresses = self.tables.users, self.tables.addresses
stmt = (
users.update()
.values(name="newname")
.where(users.c.id == addresses.c.user_id)
.where(
~exists()
.where(addresses.c.user_id == users.c.id)
.where(addresses.c.email_address == "foo")
.correlate(addresses)
)
)
self.assert_compile(
stmt,
"UPDATE users SET name=:name FROM addresses WHERE "
"users.id = addresses.user_id AND NOT "
"(EXISTS (SELECT * FROM users WHERE addresses.user_id = users.id "
"AND addresses.email_address = :email_address_1))",
)
示例12: test_dont_correlate_to_extra
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def test_dont_correlate_to_extra(self):
users, addresses = self.tables.users, self.tables.addresses
stmt = (
users.update()
.values(name="newname")
.where(users.c.id == addresses.c.user_id)
.where(
~exists()
.where(addresses.c.user_id == users.c.id)
.where(addresses.c.email_address == "foo")
.correlate()
)
)
self.assert_compile(
stmt,
"UPDATE users SET name=:name FROM addresses WHERE "
"users.id = addresses.user_id AND NOT "
"(EXISTS (SELECT * FROM addresses, users "
"WHERE addresses.user_id = users.id "
"AND addresses.email_address = :email_address_1))",
)
示例13: test_autocorrelate_error
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def test_autocorrelate_error(self):
users, addresses = self.tables.users, self.tables.addresses
stmt = (
users.update()
.values(name="newname")
.where(users.c.id == addresses.c.user_id)
.where(
~exists()
.where(addresses.c.user_id == users.c.id)
.where(addresses.c.email_address == "foo")
)
)
assert_raises_message(
exc.InvalidRequestError,
".*returned no FROM clauses due to auto-correlation.*",
stmt.compile,
dialect=default.StrCompileDialect(),
)
示例14: test_correlation_to_extra
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def test_correlation_to_extra(self):
table1, table2 = self.tables.mytable, self.tables.myothertable
stmt = (
table1.delete()
.where(table1.c.myid == table2.c.otherid)
.where(
~exists()
.where(table2.c.otherid == table1.c.myid)
.where(table2.c.othername == "x")
.correlate(table2)
)
)
self.assert_compile(
stmt,
"DELETE FROM mytable , myothertable WHERE mytable.myid = "
"myothertable.otherid AND NOT (EXISTS "
"(SELECT * FROM mytable WHERE myothertable.otherid = "
"mytable.myid AND myothertable.othername = :othername_1))",
)
示例15: test_dont_correlate_to_extra
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import exists [as 别名]
def test_dont_correlate_to_extra(self):
table1, table2 = self.tables.mytable, self.tables.myothertable
stmt = (
table1.delete()
.where(table1.c.myid == table2.c.otherid)
.where(
~exists()
.where(table2.c.otherid == table1.c.myid)
.where(table2.c.othername == "x")
.correlate()
)
)
self.assert_compile(
stmt,
"DELETE FROM mytable , myothertable WHERE mytable.myid = "
"myothertable.otherid AND NOT (EXISTS "
"(SELECT * FROM myothertable, mytable "
"WHERE myothertable.otherid = "
"mytable.myid AND myothertable.othername = :othername_1))",
)