korbase 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
korbase/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """Async ORM for Postgres, built the Korvex way.
2
+
3
+ @table("users")
4
+ class User(msgspec.Struct):
5
+ id: Annotated[int, PK()]
6
+ name: str
7
+
8
+ db = await Database.connect(dsn)
9
+ users = await db.run(select(User).where(cols(User).name == param("n")), n="Ada")
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from importlib.metadata import version
15
+
16
+ from korbase._backend import Backend
17
+ from korbase._db import Database, Transaction
18
+ from korbase._expr import Column, Expr, Param, RelRef, cols, param
19
+ from korbase._ident import KorbaseError
20
+ from korbase._meta import FK, PK, Default, Index, Rel, SqlType, Unique, table
21
+ from korbase._query import delete, insert, select, update, upsert
22
+
23
+ __all__ = [
24
+ "table",
25
+ "PK",
26
+ "FK",
27
+ "Unique",
28
+ "Default",
29
+ "SqlType",
30
+ "Index",
31
+ "Rel",
32
+ "Column",
33
+ "Expr",
34
+ "Param",
35
+ "RelRef",
36
+ "cols",
37
+ "param",
38
+ "select",
39
+ "insert",
40
+ "update",
41
+ "delete",
42
+ "upsert",
43
+ "Database",
44
+ "Transaction",
45
+ "KorbaseError",
46
+ "Backend",
47
+ "__version__",
48
+ ]
49
+
50
+ __version__: str = version("korbase")
korbase/_asyncpg.py ADDED
@@ -0,0 +1,91 @@
1
+ """The asyncpg backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from contextlib import AbstractAsyncContextManager
7
+ from typing import Any
8
+
9
+ from korbase._backend import M, Pool, RowBuilder
10
+
11
+ __all__ = ["AsyncpgBackend"]
12
+
13
+
14
+ class _AsyncpgConn:
15
+ """A `Conn` over one asyncpg connection."""
16
+
17
+ def __init__(self, conn: Any) -> None:
18
+ """Wrap an asyncpg connection."""
19
+ self._conn = conn
20
+
21
+ async def fetch(self, sql: str, args: Sequence[object], builder: RowBuilder[M]) -> list[M]:
22
+ """Run `sql` and build one model per record."""
23
+ records = await self._conn.fetch(sql, *args)
24
+ return [builder(r) for r in records]
25
+
26
+ async def fetchrow(self, sql: str, args: Sequence[object], builder: RowBuilder[M]) -> M | None:
27
+ """Run `sql` and build the first record, or return `None`."""
28
+ record = await self._conn.fetchrow(sql, *args)
29
+ return None if record is None else builder(record)
30
+
31
+ async def fetch_columns(self, sql: str, args: Sequence[object]) -> tuple[Sequence[str], list[Sequence[object]]]:
32
+ """Run `sql` through a prepared statement; return column names and records."""
33
+ stmt = await self._conn.prepare(sql)
34
+ names = [a.name for a in stmt.get_attributes()]
35
+ return names, list(await stmt.fetch(*args))
36
+
37
+ async def execute(self, sql: str, args: Sequence[object]) -> str:
38
+ """Run `sql` and return the status tag."""
39
+ return await self._conn.execute(sql, *args)
40
+
41
+ async def execute_script(self, sql: str) -> None:
42
+ """Run a multi-statement SQL text with the simple protocol."""
43
+ await self._conn.execute(sql)
44
+
45
+ def transaction(self) -> AbstractAsyncContextManager[None]:
46
+ """Open an asyncpg transaction."""
47
+ return self._conn.transaction() # type: ignore[no-any-return]
48
+
49
+
50
+ class _AsyncpgPool:
51
+ """A `Pool` over an asyncpg pool."""
52
+
53
+ def __init__(self, pool: Any) -> None:
54
+ """Wrap an asyncpg pool."""
55
+ self._pool = pool
56
+
57
+ def acquire(self) -> AbstractAsyncContextManager[_AsyncpgConn]:
58
+ """Borrow a connection."""
59
+ return _Acquire(self._pool)
60
+
61
+ async def close(self) -> None:
62
+ """Close the pool."""
63
+ await self._pool.close()
64
+
65
+
66
+ class _Acquire:
67
+ """Async context manager that yields a wrapped connection."""
68
+
69
+ def __init__(self, pool: Any) -> None:
70
+ """Remember the pool to borrow from."""
71
+ self._pool = pool
72
+ self._ctx: Any = None
73
+
74
+ async def __aenter__(self) -> _AsyncpgConn:
75
+ """Acquire a connection."""
76
+ self._ctx = self._pool.acquire()
77
+ return _AsyncpgConn(await self._ctx.__aenter__())
78
+
79
+ async def __aexit__(self, *exc: Any) -> None:
80
+ """Release the connection."""
81
+ await self._ctx.__aexit__(*exc)
82
+
83
+
84
+ class AsyncpgBackend:
85
+ """Backend on `asyncpg`. Install asyncpg to use it."""
86
+
87
+ async def connect(self, dsn: str, **opts: Any) -> Pool:
88
+ """Create an asyncpg pool; `opts` go to `asyncpg.create_pool`."""
89
+ import asyncpg
90
+
91
+ return _AsyncpgPool(await asyncpg.create_pool(dsn, **opts)) # type: ignore[return-value]
korbase/_backend.py ADDED
@@ -0,0 +1,80 @@
1
+ """Backend protocols: what Korbase needs from a database driver."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Sequence
6
+ from contextlib import AbstractAsyncContextManager
7
+ from typing import Any, Protocol, TypeVar
8
+
9
+ __all__ = ["Backend", "Pool", "Conn", "RowBuilder"]
10
+
11
+ M = TypeVar("M")
12
+ M_co = TypeVar("M_co", covariant=True)
13
+
14
+
15
+ class RowBuilder(Protocol[M_co]):
16
+ """Turns one result row into a model.
17
+
18
+ The row is positional: its values come in the same order as the
19
+ columns of the `SELECT`. Builders never see column names.
20
+ """
21
+
22
+ def __call__(self, row: Sequence[Any], /) -> M_co:
23
+ """Build one model from one row."""
24
+ ...
25
+
26
+
27
+ class Conn(Protocol):
28
+ """One database connection."""
29
+
30
+ def fetch(self, sql: str, args: Sequence[object], builder: RowBuilder[M]) -> Awaitable[list[M]]:
31
+ """Run `sql` and build one model per row, in `SELECT` order."""
32
+ ...
33
+
34
+ def fetchrow(self, sql: str, args: Sequence[object], builder: RowBuilder[M]) -> Awaitable[M | None]:
35
+ """Run `sql` and build the first row, or return `None` if empty."""
36
+ ...
37
+
38
+ def fetch_columns(
39
+ self, sql: str, args: Sequence[object]
40
+ ) -> Awaitable[tuple[Sequence[str], list[Sequence[object]]]]:
41
+ """Run `sql` and return the column names (in `SELECT` order) with the rows.
42
+
43
+ The names are known even when there are no rows.
44
+ """
45
+ ...
46
+
47
+ def execute(self, sql: str, args: Sequence[object]) -> Awaitable[str]:
48
+ """Run `sql` and return the driver's status tag, such as `INSERT 0 1`."""
49
+ ...
50
+
51
+ def execute_script(self, sql: str) -> Awaitable[None]:
52
+ """Run a multi-statement SQL text as written, with no parameters.
53
+
54
+ Used by migrations.
55
+ """
56
+ ...
57
+
58
+ def transaction(self) -> AbstractAsyncContextManager[None]:
59
+ """Open a transaction: commit on success, roll back on error."""
60
+ ...
61
+
62
+
63
+ class Pool(Protocol):
64
+ """A pool of connections."""
65
+
66
+ def acquire(self) -> AbstractAsyncContextManager[Conn]:
67
+ """Borrow a connection for the length of an `async with` block."""
68
+ ...
69
+
70
+ def close(self) -> Awaitable[None]:
71
+ """Close every connection."""
72
+ ...
73
+
74
+
75
+ class Backend(Protocol):
76
+ """A database driver."""
77
+
78
+ def connect(self, dsn: str, **opts: Any) -> Awaitable[Pool]:
79
+ """Open a pool on `dsn`. Extra options go to the driver."""
80
+ ...
korbase/_build.py ADDED
@@ -0,0 +1,189 @@
1
+ """Row builders: turn positional rows into model instances."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import inspect
7
+ from collections.abc import Sequence
8
+ from functools import partial
9
+ from typing import Any, Optional
10
+
11
+ from korbase._backend import RowBuilder
12
+ from korbase._dialect import PG, Dialect, _strip_optional
13
+ from korbase._ident import KorbaseError
14
+ from korbase._meta import TableMeta, table_meta
15
+
16
+ __all__ = ["positional_builder", "named_builder", "validating_builder"]
17
+
18
+ _NAMED: dict[tuple[type, tuple[str, ...], str], RowBuilder[Any]] = {}
19
+ _PLAIN = (int, float, str, bytes)
20
+
21
+
22
+ def _positional_params(model: type) -> list[str]:
23
+ """Return the names `model` accepts positionally, in order."""
24
+ if hasattr(model, "__struct_fields__"):
25
+ return list(model.__match_args__) # type: ignore[attr-defined]
26
+ try:
27
+ params = inspect.signature(model).parameters.values()
28
+ except (TypeError, ValueError):
29
+ return []
30
+ return [p.name for p in params if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
31
+
32
+
33
+ def _positional_safe(meta: TableMeta) -> bool:
34
+ """Tell whether `model(*row)` maps a row onto the columns correctly."""
35
+ cols = [c.name for c in meta.columns]
36
+ return _positional_params(meta.model)[: len(cols)] == cols
37
+
38
+
39
+ def _init_names(model: type) -> set[str]:
40
+ """Return the names `model.__init__` accepts."""
41
+ if hasattr(model, "__struct_fields__"):
42
+ return set(model.__struct_fields__) # type: ignore[attr-defined]
43
+ return set(inspect.signature(model).parameters)
44
+
45
+
46
+ def _maker(model: type, names: Sequence[str]) -> Any:
47
+ """Return `make(values)` building a `model` from values for `names`.
48
+
49
+ Fields that `__init__` does not accept (`init=False`) are set afterwards.
50
+ """
51
+ accepted = _init_names(model)
52
+ late = [(i, n) for i, n in enumerate(names) if n not in accepted]
53
+ if not late:
54
+ keys = tuple(names)
55
+ return lambda values: model(**dict(zip(keys, values, strict=True)))
56
+ early = [(i, n) for i, n in enumerate(names) if n in accepted]
57
+
58
+ def make(values: Sequence[Any]) -> Any:
59
+ """Build one model, then set the `init=False` fields."""
60
+ obj = model(**{n: values[i] for i, n in early})
61
+ for i, n in late:
62
+ object.__setattr__(obj, n, values[i])
63
+ return obj
64
+
65
+ return make
66
+
67
+
68
+ def _decoders(meta: TableMeta, names: Sequence[str], dialect: Dialect) -> list[tuple[int, Any]]:
69
+ """Return `(index, decode)` for the result columns `names` that need decoding."""
70
+ types = {c.name: _strip_optional(c.python_type) for c in meta.columns}
71
+ return [
72
+ (i, partial(dialect.decode_value, types[n]))
73
+ for i, n in enumerate(names)
74
+ if n in types and types[n] not in _PLAIN
75
+ ]
76
+
77
+
78
+ def _decoding(build: RowBuilder[Any], pairs: list[tuple[int, Any]]) -> RowBuilder[Any]:
79
+ """Wrap `build` so the columns in `pairs` are decoded first."""
80
+ if not pairs:
81
+ return build
82
+
83
+ def decode(row: Sequence[Any]) -> Any:
84
+ """Decode the stored values of one row, then build the model."""
85
+ values = list(row)
86
+ for i, fn in pairs:
87
+ values[i] = fn(values[i])
88
+ return build(values)
89
+
90
+ return decode
91
+
92
+
93
+ def decoding_rows(model: type, names: Sequence[str], dialect: Dialect) -> Any:
94
+ """Return `decode(row)` giving the row with its stored values converted (raw SQL with a model)."""
95
+ pairs = _decoders(table_meta(model), names, dialect)
96
+
97
+ def decode(row: Sequence[Any]) -> Sequence[Any]:
98
+ """Convert the stored values of one row."""
99
+ values = list(row)
100
+ for i, fn in pairs:
101
+ values[i] = fn(values[i])
102
+ return values
103
+
104
+ return decode
105
+
106
+
107
+ def positional_builder(meta: TableMeta, dialect: Optional[Dialect] = None) -> RowBuilder[Any]:
108
+ """Return a builder for rows in column order, with no validation."""
109
+ dialect = dialect or PG
110
+ names = tuple(c.name for c in meta.columns)
111
+ build: RowBuilder[Any] = _positional(meta)
112
+ return build if dialect is PG else _decoding(build, _decoders(meta, names, dialect))
113
+
114
+
115
+ def _positional(meta: TableMeta) -> RowBuilder[Any]:
116
+ """Return the undecoded positional builder."""
117
+ model = meta.model
118
+ names = tuple(c.name for c in meta.columns)
119
+ if meta.kind == "typeddict":
120
+ return lambda row: dict(zip(names, row, strict=True))
121
+ if _positional_safe(meta):
122
+ return lambda row: model(*row)
123
+ return _maker(model, names)
124
+
125
+
126
+ def _field_names(model: type) -> tuple[list[str], set[str]]:
127
+ """Return all field names and those with no Python default."""
128
+ meta = table_meta(model)
129
+ names = [c.name for c in meta.columns]
130
+ if meta.kind == "typeddict":
131
+ return names, set(model.__required_keys__) # type: ignore[attr-defined]
132
+ if meta.kind == "struct":
133
+ fields = model.__struct_fields__ # type: ignore[attr-defined]
134
+ n_default = len(model.__struct_defaults__) # type: ignore[attr-defined]
135
+ return names, set(fields[: len(fields) - n_default])
136
+ required = {
137
+ f.name
138
+ for f in dataclasses.fields(model) # type: ignore[arg-type]
139
+ if f.default is dataclasses.MISSING and f.default_factory is dataclasses.MISSING
140
+ }
141
+ return names, required
142
+
143
+
144
+ def named_builder(model: type, column_names: Sequence[str], dialect: Dialect = PG) -> RowBuilder[Any]:
145
+ """Return a builder mapping result columns by name to `model` fields.
146
+
147
+ Extra columns are ignored. Raises `KorbaseError` if a required field
148
+ has no column.
149
+ """
150
+ key = (model, tuple(column_names), dialect.name)
151
+ cached = _NAMED.get(key)
152
+ if cached is not None:
153
+ return cached
154
+ names, required = _field_names(model)
155
+ missing = [n for n in names if n in required and n not in column_names]
156
+ if missing:
157
+ raise KorbaseError(f"missing columns for {model.__name__}: {', '.join(missing)}")
158
+ picks = [(i, c) for i, c in enumerate(column_names) if c in names]
159
+ kind = table_meta(model).kind
160
+ make = None if kind == "typeddict" else _maker(model, [c for _, c in picks])
161
+ idx = [i for i, _ in picks]
162
+
163
+ def build(row: Sequence[Any]) -> Any:
164
+ """Build one model from a row."""
165
+ if make is None:
166
+ return {c: row[i] for i, c in picks}
167
+ return make([row[i] for i in idx])
168
+
169
+ result: RowBuilder[Any] = build
170
+ if dialect is not PG:
171
+ result = _decoding(build, _decoders(table_meta(model), column_names, dialect))
172
+ _NAMED[key] = result
173
+ return result
174
+
175
+
176
+ def validating_builder(meta: TableMeta, dialect: Optional[Dialect] = None) -> RowBuilder[Any]:
177
+ """Return a builder that validates each row with `msgspec.convert`."""
178
+ import msgspec
179
+
180
+ dialect = dialect or PG
181
+
182
+ names = tuple(c.name for c in meta.columns)
183
+ model = meta.model
184
+
185
+ def build(row: Sequence[Any]) -> Any:
186
+ """Validate one row and build the model."""
187
+ return msgspec.convert(dict(zip(names, row, strict=True)), model, from_attributes=True)
188
+
189
+ return build if dialect is PG else _decoding(build, _decoders(meta, names, dialect))
korbase/_db.py ADDED
@@ -0,0 +1,252 @@
1
+ """The user-facing `Database` and `Transaction`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator, Sequence
6
+ from contextlib import AbstractAsyncContextManager, asynccontextmanager
7
+ from typing import Any, Optional, TypeVar, Union, overload
8
+
9
+ from korbase._backend import Backend, Conn, Pool
10
+ from korbase._build import decoding_rows, named_builder, positional_builder, validating_builder
11
+ from korbase._dialect import PG, Dialect
12
+ from korbase._expr import Param
13
+ from korbase._ident import KorbaseError
14
+ from korbase._query import (
15
+ Compiled,
16
+ Delete,
17
+ DeleteReturning,
18
+ Insert,
19
+ Select,
20
+ Update,
21
+ UpdateReturning,
22
+ Upsert,
23
+ _Query,
24
+ )
25
+ from korbase._relations import load_relations
26
+
27
+ __all__ = ["Database", "Transaction"]
28
+
29
+ M = TypeVar("M")
30
+ Rows = Union[Select[M], Insert[M], Upsert[M], UpdateReturning[M], DeleteReturning[M]]
31
+ Count = Union[Update[M], Delete[M]]
32
+
33
+
34
+ def _args(compiled: Compiled, params: dict[str, Any]) -> list[Any]:
35
+ """Map `params` to the positional arguments of `compiled`."""
36
+ names = {s.name for s in compiled.slots if isinstance(s, Param)}
37
+ missing = sorted(names - params.keys())
38
+ extra = sorted(params.keys() - names)
39
+ if missing:
40
+ raise KorbaseError(f"missing params: {', '.join(missing)}")
41
+ if extra:
42
+ raise KorbaseError(f"unexpected params: {', '.join(extra)}")
43
+ if any(v is None for v in params.values()):
44
+ _reject_null_eq(compiled, params)
45
+ return [params[s.name] if isinstance(s, Param) else s.value for s in compiled.slots]
46
+
47
+
48
+ def _reject_null_eq(compiled: Compiled, params: dict[str, Any]) -> None:
49
+ """Raise if a `None` param is compared with `==`, `!=` or `.in_()`, which never match NULL."""
50
+ for s in compiled.slots:
51
+ if isinstance(s, Param) and s.eq and params[s.name] is None:
52
+ raise KorbaseError(
53
+ f"param {s.name!r} is None but is compared with ==, != or in_(), which never match NULL: "
54
+ "use .is_null() or .where(column=None)"
55
+ )
56
+
57
+
58
+ def _row_builder(query: _Query[Any], validate: bool, dialect: Dialect) -> Any:
59
+ """Return the row builder for the columns of the query's model."""
60
+ if validate:
61
+ return validating_builder(query._meta, dialect)
62
+ return positional_builder(query._meta, dialect)
63
+
64
+
65
+ def _count(tag: str) -> int:
66
+ """Return the row count at the end of a command tag: `"UPDATE 3"` gives 3."""
67
+ return int(tag.rsplit(" ", 1)[-1])
68
+
69
+
70
+ def _by_name(model: type, names: Sequence[str], validate: bool, dialect: Dialect) -> Any:
71
+ """Return a builder that maps a row with column `names` to `model`."""
72
+ if not validate:
73
+ return named_builder(model, tuple(names), dialect)
74
+ import msgspec
75
+
76
+ decode = None if dialect is PG else decoding_rows(model, names, dialect)
77
+
78
+ def build(row: Sequence[Any]) -> Any:
79
+ """Validate one row and build the model."""
80
+ data = dict(zip(names, row if decode is None else decode(row), strict=True))
81
+ return msgspec.convert(data, model, from_attributes=True)
82
+
83
+ return build
84
+
85
+
86
+ def _backend_for(dsn: str) -> Backend:
87
+ """Return the backend for the scheme of `dsn`; the DSN is never shown in errors."""
88
+ scheme = dsn.split(":", 1)[0].lower() if ":" in dsn else ""
89
+ if scheme in ("postgresql", "postgres"):
90
+ from korbase._asyncpg import AsyncpgBackend
91
+
92
+ return AsyncpgBackend()
93
+ if scheme == "sqlite":
94
+ from korbase._sqlite import SqliteBackend
95
+
96
+ return SqliteBackend()
97
+ raise KorbaseError("unknown database scheme: use postgresql://, postgres:// or sqlite:")
98
+
99
+
100
+ class _Runner:
101
+ """Shared query methods; subclasses say how to get a connection."""
102
+
103
+ _validate = False
104
+ _dialect: Dialect = PG
105
+
106
+ def _conn(self) -> AbstractAsyncContextManager[Conn]:
107
+ """Return a context manager that yields a connection."""
108
+ raise NotImplementedError
109
+
110
+ @overload
111
+ async def run(self, query: Rows[M], /, **params: Any) -> list[M]: ...
112
+
113
+ @overload
114
+ async def run(self, query: Count[M], /, **params: Any) -> int: ...
115
+
116
+ async def run(self, query: Any, /, **params: Any) -> Any:
117
+ """Run a query builder with `params`.
118
+
119
+ A select, insert, upsert, or an update or delete with `.returning()`,
120
+ returns a list of models. Any other update or delete returns the
121
+ number of rows it changed.
122
+ """
123
+ compiled = query.compile(self._dialect)
124
+ args = _args(compiled, params)
125
+ async with self._conn() as conn:
126
+ if not query.returns_rows:
127
+ return _count(await conn.execute(compiled.sql, args))
128
+ rows = await conn.fetch(compiled.sql, args, _row_builder(query, self._validate, self._dialect))
129
+ if isinstance(query, Select):
130
+ await self._load(conn, rows, query)
131
+ return rows
132
+
133
+ async def _load(self, conn: Conn, rows: list[Any], query: Any) -> None:
134
+ """Load the relations of `query` into `rows`, decoding children by dialect."""
135
+ await load_relations(conn, rows, query._loads, self._validate, self._dialect)
136
+
137
+ async def first(self, query: Rows[M], /, **params: Any) -> Optional[M]:
138
+ """Run a query that returns rows and return the first model, or `None`.
139
+
140
+ Other updates and deletes raise `KorbaseError`: add `.returning()`.
141
+ """
142
+ compiled = query.compile(self._dialect)
143
+ args = _args(compiled, params)
144
+ if not query.returns_rows:
145
+ raise KorbaseError("first() needs a query that returns rows: add .returning()")
146
+ async with self._conn() as conn:
147
+ row = await conn.fetchrow(compiled.sql, args, _row_builder(query, self._validate, self._dialect))
148
+ if row is not None and isinstance(query, Select):
149
+ await self._load(conn, [row], query)
150
+ return row
151
+
152
+ @overload
153
+ async def fetch(self, sql: str, *args: Any, model: type[M]) -> list[M]: ...
154
+
155
+ @overload
156
+ async def fetch(self, sql: str, *args: Any, model: None = None) -> list[tuple[Any, ...]]: ...
157
+
158
+ async def fetch(self, sql: str, *args: Any, model: Optional[type] = None) -> list[Any]:
159
+ """Run raw SQL; rows become `model` (by column name) or tuples."""
160
+ async with self._conn() as conn:
161
+ if model is None:
162
+ return await conn.fetch(sql, args, tuple)
163
+ names, rows = await conn.fetch_columns(sql, args)
164
+ build = _by_name(model, names, self._validate, self._dialect)
165
+ return [build(r) for r in rows]
166
+
167
+ @overload
168
+ async def fetchrow(self, sql: str, *args: Any, model: type[M]) -> Optional[M]: ...
169
+
170
+ @overload
171
+ async def fetchrow(self, sql: str, *args: Any, model: None = None) -> Optional[tuple[Any, ...]]: ...
172
+
173
+ async def fetchrow(self, sql: str, *args: Any, model: Optional[type] = None) -> Any:
174
+ """Run raw SQL and return the first row, or `None`."""
175
+ async with self._conn() as conn:
176
+ if model is None:
177
+ return await conn.fetchrow(sql, args, tuple)
178
+ names, rows = await conn.fetch_columns(sql, args)
179
+ build = _by_name(model, names, self._validate, self._dialect)
180
+ return build(rows[0]) if rows else None
181
+
182
+ async def execute(self, sql: str, *args: Any) -> str:
183
+ """Run raw SQL and return the command tag, such as `"UPDATE 3"`."""
184
+ async with self._conn() as conn:
185
+ return await conn.execute(sql, args)
186
+
187
+
188
+ class Transaction(_Runner):
189
+ """Queries bound to one connection inside a transaction."""
190
+
191
+ def __init__(self, conn: Conn, validate: bool, dialect: Dialect = PG) -> None:
192
+ """Bind to `conn`; use `Database.transaction()` instead."""
193
+ self._bound = conn
194
+ self._validate = validate
195
+ self._dialect = dialect
196
+
197
+ @asynccontextmanager
198
+ async def _conn(self) -> AsyncIterator[Conn]:
199
+ """Yield the bound connection."""
200
+ yield self._bound
201
+
202
+ @asynccontextmanager
203
+ async def transaction(self) -> AsyncIterator[Transaction]:
204
+ """Open a nested transaction, which is a savepoint."""
205
+ async with self._bound.transaction():
206
+ yield Transaction(self._bound, self._validate, self._dialect)
207
+
208
+
209
+ class Database(_Runner):
210
+ """A pool of connections plus the methods to run queries."""
211
+
212
+ def __init__(self, pool: Pool, validate: bool = False, dialect: Dialect = PG) -> None:
213
+ """Wrap `pool`; use `Database.connect()` instead."""
214
+ self._pool = pool
215
+ self._validate = validate
216
+ self._dialect = dialect
217
+
218
+ @classmethod
219
+ async def connect(
220
+ cls, dsn: str, *, backend: Optional[Backend] = None, validate: bool = False, **opts: Any
221
+ ) -> Database:
222
+ """Open a pool on `dsn`. `validate=True` checks every row against its model.
223
+
224
+ Without `backend`, the DSN scheme picks it: `postgresql://` or
225
+ `postgres://` for Postgres, `sqlite:` for SQLite.
226
+ """
227
+ if backend is None:
228
+ backend = _backend_for(dsn)
229
+ dialect = getattr(backend, "dialect", PG)
230
+ return cls(await backend.connect(dsn, **opts), validate, dialect)
231
+
232
+ def _conn(self) -> AbstractAsyncContextManager[Conn]:
233
+ """Borrow a pooled connection."""
234
+ return self._pool.acquire()
235
+
236
+ @asynccontextmanager
237
+ async def transaction(self) -> AsyncIterator[Transaction]:
238
+ """Open a transaction on one connection: commit on success, roll back on error."""
239
+ async with self._pool.acquire() as conn, conn.transaction():
240
+ yield Transaction(conn, self._validate, self._dialect)
241
+
242
+ async def close(self) -> None:
243
+ """Close the pool."""
244
+ await self._pool.close()
245
+
246
+ async def __aenter__(self) -> Database:
247
+ """Return the database."""
248
+ return self
249
+
250
+ async def __aexit__(self, *exc: Any) -> None:
251
+ """Close the pool."""
252
+ await self.close()