A D1 client: an SqlClientService with batch, its config and
the HTTP API it runs on (api).
Attributes#
| Attribute | Type | Description |
|---|---|---|
config | D1ClientConfig = config | |
api | D1Api = api | |
has_transforms | bool = config.transform_query_names is not None or config.transform_result_names is not None |
Functions#
__init__#
__init__(*, config, api, **fields) -> None| Parameter | Type | Description |
|---|---|---|
config | D1ClientConfig | |
api | D1Api | |
fields | Unpack[ClientFields] = {} |
def __init__(
self,
*,
config: D1ClientConfig,
api: D1Api,
**fields: Unpack[ClientFields],
) -> None:
super().__init__(**fields)
self.config = config
self.api = api
self.has_transforms = (
config.transform_query_names is not None or config.transform_result_names is not None
)without_transforms#
without_transforms() -> SelfThis client, without renaming identifiers or result columns (also when it only renames identifiers).
Returns Self
def without_transforms(self) -> Self:
"""This client, without renaming identifiers or result columns
(also when it only renames identifiers)."""
if not self.has_transforms:
return self
copy = copy_module.copy(self)
copy.compiler = self.compiler.without_transform
copy.transform_rows = None
copy.has_transforms = False
return copybatch#
batch(statements: tuple[], /) -> Effect[tuple[], SqlError]
batch[A](statements: tuple[Statement[A]], /) -> Effect[tuple[list[A]], SqlError]
batch[A, B](statements: tuple[Statement[A], Statement[B]], /) -> Effect[tuple[list[A], list[B]], SqlError]
batch[A, B, C](statements: tuple[Statement[A], Statement[B], Statement[C]], /) -> Effect[tuple[list[A], list[B], list[C]], SqlError]
batch[A, B, C, D](statements: tuple[Statement[A], Statement[B], Statement[C], Statement[D]], /) -> Effect[tuple[list[A], list[B], list[C], list[D]], SqlError]
batch[A](statements: Sequence[Statement[A]], /) -> Effect[tuple[list[A], ...], SqlError]Run statements in one request, as one transaction: their
rows in order, each renamed by the client that made it. A failure
rolls back all of them. Outside the client's transactions (inside
one it is a defect, as every D1 transaction is).
| Parameter | Type | Description |
|---|---|---|
statements |
@overload
def batch(self, statements: tuple[()], /) -> Effect[tuple[()], SqlError]: ...
@overload
def batch[A](self, statements: tuple[Statement[A]], /) -> Effect[tuple[list[A]], SqlError]: ...
@overload
def batch[A, B](
self, statements: tuple[Statement[A], Statement[B]], /
) -> Effect[tuple[list[A], list[B]], SqlError]: ...
@overload
def batch[A, B, C](
self, statements: tuple[Statement[A], Statement[B], Statement[C]], /
) -> Effect[tuple[list[A], list[B], list[C]], SqlError]: ...
@overload
def batch[A, B, C, D](
self, statements: tuple[Statement[A], Statement[B], Statement[C], Statement[D]], /
) -> Effect[tuple[list[A], list[B], list[C], list[D]], SqlError]: ...
@overload
def batch[A](
self, statements: Sequence[Statement[A]], /
) -> Effect[tuple[list[A], ...], SqlError]: ...
def batch(self, statements: Sequence[Statement[Any]], /) -> Effect[tuple[Any, ...], SqlError]:
"""Run ``statements`` in one request, as one transaction: their
rows in order, each renamed by the client that made it. A failure
rolls back all of them. Outside the client's transactions (inside
one it is a defect, as every D1 transaction is)."""
if not statements:
return succeed(())
attributes = self.span_attributes
is_batch = len(statements) > 1
name = _batch_span_name(attributes) if is_batch else span_name(attributes)
return use_span(name, lambda span: self._batch(statements, span), kind="client")update_values#
update_values(value, alias) -> RecordUpdateHelperNot supported by D1: a type error (Effect's never), and a
TypeError when called anyway.
| Parameter | Type | Description |
|---|---|---|
value | Sequence[Mapping[str, object]] | |
alias | str |
Returns RecordUpdateHelper
@staticmethod
@deprecated("update_values is not supported by D1")
def update_values(value: Sequence[Mapping[str, object]], alias: str) -> RecordUpdateHelper:
"""Not supported by D1: a type error (Effect's ``never``), and a
``TypeError`` when called anyway."""
raise TypeError("update_values is not supported by D1")__call__#
__call__(template, *args, **kwargs) -> Statement[Row]| Parameter | Type | Description |
|---|---|---|
template | SqlText | |
args | object = () | |
kwargs | object = {} |
Returns Statement[Row]
def __call__(self, template: SqlText, /, *args: object, **kwargs: object) -> Statement[Row]:
return self._statement(segments_of(template, args, kwargs))unsafe#
unsafe(sql, params=None) -> Statement[Row]A statement of SQL text built at runtime, with params bound to
its placeholders. Never build the text from untrusted input.
| Parameter | Type | Description |
|---|---|---|
sql | str | |
params | Sequence[object] | None = None |
Returns Statement[Row]
def unsafe(self, sql: str, params: Sequence[object] | None = None) -> Statement[Row]:
"""A statement of SQL text built at runtime, with ``params`` bound to
its placeholders. Never build the text from untrusted input."""
return self._statement((literal_unsafe(sql, params),))literal#
literal(sql) -> FragmentSQL text as a fragment.
| Parameter | Type | Description |
|---|---|---|
sql | LiteralString |
Returns Fragment
@staticmethod
def literal(sql: LiteralString) -> Fragment:
"""SQL text as a fragment."""
return Fragment((literal(sql),))identifier#
identifier(name) -> IdentifierA name, escaped (Effect's sql("name")).
| Parameter | Type | Description |
|---|---|---|
name | str |
Returns Identifier
@staticmethod
def identifier(name: str) -> Identifier:
"""A name, escaped (Effect's ``sql("name")``)."""
return identifier(name)in_#
in_(values: Sequence[object], /) -> ArrayHelper
in_(column: str, values: Sequence[object], /) -> Fragmentin_(values): (a, b, ...); in_(column, values):
"column" IN (...), or 1=0 for no values.
| Parameter | Type | Description |
|---|---|---|
args | = () |
@overload
@staticmethod
def in_(values: Sequence[object], /) -> ArrayHelper: ...
@overload
@staticmethod
def in_(column: str, values: Sequence[object], /) -> Fragment: ...
@staticmethod
def in_(*args: Any) -> ArrayHelper | Fragment:
"""``in_(values)``: ``(a, b, ...)``; ``in_(column, values)``:
``"column" IN (...)``, or ``1=0`` for no values."""
if len(args) == 1:
return in_(args[0])
column, values = args
return in_(column, values)insert#
insert(value) -> RecordInsertHelper(columns) VALUES (...) for one row or several.
| Parameter | Type | Description |
|---|---|---|
value | Mapping[str, object] | Sequence[Mapping[str, object]] |
Returns RecordInsertHelper
@staticmethod
def insert(value: Mapping[str, object] | Sequence[Mapping[str, object]]) -> RecordInsertHelper:
"""``(columns) VALUES (...)`` for one row or several."""
return insert(value)update#
update(value, omit=()) -> RecordUpdateHelperSinglecolumn = value, ... for one row, without the omit
columns.
| Parameter | Type | Description |
|---|---|---|
value | Mapping[str, object] | |
omit | Sequence[str] = () |
Returns RecordUpdateHelperSingle
@staticmethod
def update(value: Mapping[str, object], omit: Sequence[str] = ()) -> RecordUpdateHelperSingle:
"""``column = value, ...`` for one row, without the ``omit``
columns."""
return update(value, omit)and_#
and_(clauses) -> Fragment(a AND b ...); 1=1 for no clauses.
| Parameter | Type | Description |
|---|---|---|
clauses | Sequence[LiteralString | Fragment] |
Returns Fragment
@staticmethod
def and_(clauses: Sequence[LiteralString | Fragment]) -> Fragment:
"""``(a AND b ...)``; ``1=1`` for no clauses."""
return and_(clauses)or_#
or_(clauses) -> Fragment(a OR b ...); 1=1 for no clauses.
| Parameter | Type | Description |
|---|---|---|
clauses | Sequence[LiteralString | Fragment] |
Returns Fragment
@staticmethod
def or_(clauses: Sequence[LiteralString | Fragment]) -> Fragment:
"""``(a OR b ...)``; ``1=1`` for no clauses."""
return or_(clauses)csv#
csv(values, prefix=None) -> Fragmenta,b,... after prefix (ORDER BY); nothing for none.
| Parameter | Type | Description |
|---|---|---|
values | Sequence[LiteralString | Fragment] | |
prefix | LiteralString | None = None |
Returns Fragment
@staticmethod
def csv(
values: Sequence[LiteralString | Fragment], prefix: LiteralString | None = None
) -> Fragment:
"""``a,b,...`` after ``prefix`` (``ORDER BY``); nothing for none."""
return csv(values, prefix)join#
join(separator, add_parens=True, fallback='') -> Callable[[Sequence[LiteralString | Fragment]], Fragment]A function joining clauses with separator: several in
parentheses (unless add_parens=False), one as it is, none as
fallback.
| Parameter | Type | Description |
|---|---|---|
separator | LiteralString | |
add_parens | bool = True | |
fallback | LiteralString = '' |
Returns Callable[[Sequence[LiteralString | Fragment]], Fragment]
@staticmethod
def join(
separator: LiteralString, add_parens: bool = True, fallback: LiteralString = ""
) -> Callable[[Sequence[LiteralString | Fragment]], Fragment]:
"""A function joining clauses with ``separator``: several in
parentheses (unless ``add_parens=False``), one as it is, none as
``fallback``."""
return join(separator, add_parens, fallback)on_dialect#
on_dialect[T](*, sqlite, pg, mysql, mssql, clickhouse) -> TThe result of the function for the client's dialect.
| Parameter | Type | Description |
|---|---|---|
sqlite | Callable[[], T] | |
pg | Callable[[], T] | |
mysql | Callable[[], T] | |
mssql | Callable[[], T] | |
clickhouse | Callable[[], T] |
Returns T
def on_dialect[T](
self,
*,
sqlite: Callable[[], T],
pg: Callable[[], T],
mysql: Callable[[], T],
mssql: Callable[[], T],
clickhouse: Callable[[], T],
) -> T:
"""The result of the function for the client's dialect."""
branches: dict[str, Callable[[], T]] = {
"sqlite": sqlite,
"pg": pg,
"mysql": mysql,
"mssql": mssql,
"clickhouse": clickhouse,
}
return branches[self.dialect]()on_dialect_or_else#
on_dialect_or_else[T](*, or_else, sqlite=None, pg=None, mysql=None, mssql=None, clickhouse=None) -> TThe result of the function for the client's dialect, or of
or_else when it has none.
| Parameter | Type | Description |
|---|---|---|
or_else | Callable[[], T] | |
sqlite | Callable[[], T] | None = None | |
pg | Callable[[], T] | None = None | |
mysql | Callable[[], T] | None = None | |
mssql | Callable[[], T] | None = None | |
clickhouse | Callable[[], T] | None = None |
Returns T
def on_dialect_or_else[T](
self,
*,
or_else: Callable[[], T],
sqlite: Callable[[], T] | None = None,
pg: Callable[[], T] | None = None,
mysql: Callable[[], T] | None = None,
mssql: Callable[[], T] | None = None,
clickhouse: Callable[[], T] | None = None,
) -> T:
"""The result of the function for the client's dialect, or of
``or_else`` when it has none."""
branches: dict[str, Callable[[], T] | None] = {
"sqlite": sqlite,
"pg": pg,
"mysql": mysql,
"mssql": mssql,
"clickhouse": clickhouse,
}
branch = branches[self.dialect]
return (or_else if branch is None else branch)()fields#
fields() -> ClientFieldsWhat the client was built from, to build a driver's own client
class on it: Driver(extra=..., **client.fields()).
Returns ClientFields
def fields(self) -> ClientFields:
"""What the client was built from, to build a driver's own client
class on it: ``Driver(extra=..., **client.fields())``."""
return {
"acquirer": self.acquirer,
"compiler": self.compiler,
"span_attributes": self.span_attributes,
"transform_rows": self.transform_rows,
"borrower": self.borrower,
"driver": self.driver,
"reserve": self._reserve,
"transaction_service": self.transaction_service,
"with_transaction": self._with_transaction,
"after_commit": self._after_commit,
"reactivity": self._reactivity,
"reactive_queue": self._reactive_queue,
}with_transaction#
with_transaction[A, E, R](effect) -> Effect[A, E | SqlError, R]Run effect in a transaction: it commits if effect
succeeds and rolls back otherwise (also when interrupted). Nested,
it is a savepoint.
Inside, Reactivity invalidations wait for the outermost commit
(and are dropped on rollback). BeginTransaction replaces the
client's BEGIN. Statements from a fiber that outlives the
transaction it was forked in fail with an SqlError: use
after_commit for work after the commit.
| Parameter | Type | Description |
|---|---|---|
effect | Effect[A, E, R] |
Returns Effect[A, E | SqlError, R]
def with_transaction[A, E, R](self, effect: Effect[A, E, R]) -> Effect[A, E | SqlError, R]:
"""Run ``effect`` in a transaction: it commits if ``effect``
succeeds and rolls back otherwise (also when interrupted). Nested,
it is a savepoint.
Inside, ``Reactivity`` invalidations wait for the outermost commit
(and are dropped on rollback). ``BeginTransaction`` replaces the
client's ``BEGIN``. Statements from a fiber that outlives the
transaction it was forked in fail with an ``SqlError``: use
``after_commit`` for work after the commit."""
require_effect(effect, "effect")
return self._with_transaction(effect)after_commit#
after_commit[R](effect) -> Effect[None, Never, R]Run effect once the outermost transaction commits, or now
outside a transaction.
Callbacks are dropped if the transaction (or their savepoint) rolls
back or its COMMIT fails. They run in registration order, after
the connection is released and before with_transaction returns,
uninterruptibly, with the services in scope when registered minus
the transaction. A callback that dies is logged at
UnhandledLogLevel. Registering after the transaction ended is a
defect.
| Parameter | Type | Description |
|---|---|---|
effect | Effect[None, Never, R] |
Returns Effect[None, Never, R]
def after_commit[R](self, effect: Effect[None, Never, R]) -> Effect[None, Never, R]:
"""Run ``effect`` once the outermost transaction commits, or now
outside a transaction.
Callbacks are dropped if the transaction (or their savepoint) rolls
back or its ``COMMIT`` fails. They run in registration order, after
the connection is released and before ``with_transaction`` returns,
uninterruptibly, with the services in scope when registered minus
the transaction. A callback that dies is logged at
``UnhandledLogLevel``. Registering after the transaction ended is a
defect."""
require_effect(effect, "effect")
return self._after_commit(effect)reactive#
reactive[A, E, R](keys, effect) -> Stream[A, E, R]effect's results, again each time keys are
invalidated.
| Parameter | Type | Description |
|---|---|---|
keys | Keys | |
effect | Effect[A, E, R] |
Returns Stream[A, E, R]
def reactive[A, E, R](self, keys: Keys, effect: Effect[A, E, R]) -> Stream[A, E, R]:
"""``effect``'s results, again each time ``keys`` are
invalidated."""
from pyfect import stream
require_effect(effect, "effect")
if self._reactive_queue is None:
return self._reactivity.stream(keys, effect)
queues = self._reactive_queue(keys, effect).map(stream.from_queue)
return stream.unwrap(cast("Effect[Stream[A, E, R], E, Scope | R]", queues))reactive_mailbox#
reactive_mailbox[A, E, R](keys, effect) -> Effect[Dequeue[A, E | Done], Never, R | Scope]A queue of effect's results, refreshed when keys are
invalidated.
| Parameter | Type | Description |
|---|---|---|
keys | Keys | |
effect | Effect[A, E, R] |
Returns Effect[Dequeue[A, E | Done], Never, R | Scope]
def reactive_mailbox[A, E, R](
self, keys: Keys, effect: Effect[A, E, R]
) -> Effect[Dequeue[A, E | Done], Never, R | Scope]:
"""A queue of ``effect``'s results, refreshed when ``keys`` are
invalidated."""
require_effect(effect, "effect")
if self._reactive_queue is None:
return self._reactivity.query(keys, effect)
return self._reactive_queue(keys, effect)