本文整理汇总了Python中asyncpg.Connection方法的典型用法代码示例。如果您正苦于以下问题:Python asyncpg.Connection方法的具体用法?Python asyncpg.Connection怎么用?Python asyncpg.Connection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncpg
的用法示例。
在下文中一共展示了asyncpg.Connection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _load_reflection_cache
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def _load_reflection_cache(
self,
connection: asyncpg.Connection,
) -> FrozenSet[str]:
data = await connection.fetch('''
SELECT
eql_hash,
argnames
FROM
ROWS FROM(edgedb._get_cached_reflection())
AS t(eql_hash text, argnames text[])
''')
return immutables.Map({
r['eql_hash']: tuple(r['argnames']) for r in data
})
示例2: ensure_initialized
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def ensure_initialized(self, con: asyncpg.Connection) -> None:
if self._std_schema is None:
self._std_schema = await load_cached_schema(con, 'stdschema')
if self._refl_schema is None:
self._refl_schema = await load_cached_schema(con, 'reflschema')
if self._schema_class_layout is None:
self._schema_class_layout = await load_schema_class_layout(con)
if self._intro_query is None:
self._intro_query = await load_schema_intro_query(con)
if self._config_spec is None:
self._config_spec = config.load_spec_from_schema(
self._std_schema)
config.set_settings(self._config_spec)
示例3: _instrument
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def _instrument(self, **kwargs):
tracer_provider = kwargs.get(
"tracer_provider", trace.get_tracer_provider()
)
setattr(
asyncpg,
_APPLIED,
tracer_provider.get_tracer("asyncpg", __version__),
)
for method in [
"Connection.execute",
"Connection.executemany",
"Connection.fetch",
"Connection.fetchval",
"Connection.fetchrow",
]:
wrapt.wrap_function_wrapper(
"asyncpg.connection", method, _do_execute
)
示例4: update_world
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def update_world(self, conn: PoolConn, world: str, update_self=True) -> bool:
"""Updates the world of the character on the database.
:param conn: Connection to the database.
:param world: The new world to set.
:param update_self: Whether to also update the object or not.
:return: Whether the world was updated in the database or not.
"""
result = await self.update_field_by_id(conn, self.id, "world", world)
if result and update_self:
self.world = world
return result is not None
# endregion
# region Class methods
示例5: get_latest
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def get_latest(cls, conn: PoolConn, *, minimum_level=0, user_id=0, worlds: Union[List[str], str] = None):
"""Gets an asynchronous generator of the character's level ups.
:param conn: Connection to the database.
:param minimum_level: The minimum level to show.
:param user_id: The id of an user to only show level ups of characters they own.
:param worlds: A list of worlds to only show level ups of characters in that world.
:return: An asynchronous generator containing the levels.
"""
if isinstance(worlds, str):
worlds = [worlds]
if not worlds:
worlds = []
async with conn.transaction():
async for row in conn.cursor("""
SELECT l.*, (json_agg(c)->>0)::jsonb as char FROM character_levelup l
LEFT JOIN "character" c ON c.id = l.character_id
WHERE ($1::bigint = 0 OR c.user_id = $1) AND (cardinality($2::text[]) = 0 OR c.world = any($2))
AND l.level >= $3
GROUP BY l.id
ORDER BY date DESC""", user_id, worlds, minimum_level):
yield cls(**row)
示例6: import_roles
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def import_roles(conn: asyncpg.Connection, c: sqlite3.Cursor):
log.info("Importing roles...")
auto_roles = []
joinable_roles = []
log.debug("Gathering auto roles from sqlite...")
c.execute("SELECT server_id, role_id, guild FROM auto_roles")
rows = c.fetchall()
for server_id, role_id, guild in rows:
auto_roles.append((server_id, role_id, guild))
log.debug(f"Collected {len(auto_roles):,} records from old database.")
log.info("Copying records to auto roles table")
res = await conn.copy_records_to_table("role_auto", records=auto_roles, columns=["server_id", "role_id", "rule"])
log.info(f"Copied {get_affected_count(res):,} records successfully.")
log.debug("Gathering joinable roles from sqlite...")
c.execute("SELECT server_id, role_id FROM joinable_roles")
rows = c.fetchall()
for server_id, role_id in rows:
joinable_roles.append((server_id, role_id))
log.debug(f"Collected {len(joinable_roles):,} records from old database.")
log.info("Copying records to joinable roles table")
res = await conn.copy_records_to_table("role_joinable", records=joinable_roles, columns=["server_id", "role_id"])
log.info(f"Copied {get_affected_count(res):,} records successfully.")
log.info("Finished importing roles.")
示例7: get_by_name
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def get_by_name(cls, conn: PoolConn, channel_id: int, name: str, is_guild: bool) -> \
Optional['WatchlistEntry']:
"""Gets an entry by its name.
:param conn: Connection to the database.
:param channel_id: The id of the channel.
:param name: Name of the entry.
:param is_guild: Whether the entry is a guild or a character.
:return: The entry if found.
"""
row = await conn.fetchrow("SELECT * FROM watchlist_entry "
"WHERE channel_id = $1 AND lower(name) = $2 AND is_guild = $3",
channel_id, name.lower().strip(), is_guild)
if row is None:
return None
return cls(**row)
示例8: insert
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def insert(cls, conn: PoolConn, channel_id: int, name: str, is_guild: bool, user_id: int, reason=None)\
-> Optional['WatchlistEntry']:
"""Inserts a watchlist entry into the database.
:param conn: Connection to the database.
:param channel_id: The id of the watchlist's channel.
:param name: Name of the entry.
:param is_guild: Whether the entry is a guild or a character.
:param user_id: The id of the user that added the entry.
:param reason: The reason for the entry.
:return: The inserted entry.
"""
row = await conn.fetchrow("INSERT INTO watchlist_entry(channel_id, name, is_guild, reason, user_id) "
"VALUES($1, $2, $3, $4, $5) RETURNING *", channel_id, name, is_guild, reason, user_id)
if row is None:
return None
return cls(**row)
# endregion
示例9: add_listener
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def add_listener(self, channel, callback):
"""Add a listener for Postgres notifications.
:param str channel: Channel to listen on.
:param callable callback:
A callable receiving the following arguments:
**connection**: a Connection the callback is registered with;
**pid**: PID of the Postgres server that sent the notification;
**channel**: name of the channel the notification was sent to;
**payload**: the payload.
"""
self._check_open()
if channel not in self._listeners:
await self.fetch('LISTEN {}'.format(utils._quote_ident(channel)))
self._listeners[channel] = set()
self._listeners[channel].add(callback)
示例10: add_log_listener
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def add_log_listener(self, callback):
"""Add a listener for Postgres log messages.
It will be called when asyncronous NoticeResponse is received
from the connection. Possible message types are: WARNING, NOTICE,
DEBUG, INFO, or LOG.
:param callable callback:
A callable receiving the following arguments:
**connection**: a Connection the callback is registered with;
**message**: the `exceptions.PostgresLogMessage` message.
.. versionadded:: 0.12.0
"""
if self.is_closed():
raise exceptions.InterfaceError('connection is closed')
self._log_listeners.add(callback)
示例11: introspect
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def introspect(
self,
connection: asyncpg.Connection,
) -> s_schema.Schema:
data = await connection.fetch(self._intro_query)
return s_refl.parse_into(
schema=self._std_schema,
data=[r[0] for r in data],
schema_class_layout=self._schema_class_layout,
)
示例12: __init__
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def __init__(self, conn: Connection):
super().__init__(conn)
self._users_repo = UsersRepository(conn)
示例13: __init__
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def __init__(self, conn: Connection) -> None:
super().__init__(conn)
self._profiles_repo = ProfilesRepository(conn)
示例14: __init__
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def __init__(self, conn: Connection) -> None:
super().__init__(conn)
self._profiles_repo = ProfilesRepository(conn)
self._tags_repo = TagsRepository(conn)
示例15: init_table
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import Connection [as 别名]
def init_table(connection: asyncpg.Connection):
query = """
CREATE TABLE IF NOT EXISTS STORY (
id BIGINT PRIMARY KEY,
content bytea NOT NULL
);
"""
await connection.execute(query)
query = "DELETE FROM STORY;"
await connection.execute(query)