"""The database adapter module: provides typed schema binding, query execution,
transactions, and leases across database backends (SQLite, PostgreSQL, etc.).
Instantiated with the compartment into a database adapter module.
"""
from __future__ import annotations
from typing import Any, Callable, Optional, Sequence
from .base import LEASE_SECONDS, BaseStore
from .dialect import Dialect, SqliteDialect
[docs]class DatabaseAdapter(BaseStore):
"""The database adapter module: binds a compartment's declared SCHEMA to a
database backend and provides query execution, transactions, and leases."""
[docs] def __init__(
self,
target: str = ':memory:',
schema: Sequence[Any] = (),
migrations: Sequence[Any] = (),
timeout: float = 5.0,
dialect: Optional[Dialect] = None,
owner: Optional[str] = None,
lease_seconds: int = LEASE_SECONDS,
clock: Optional[Callable[[], int]] = None,
readonly: bool = False,
) -> None:
self.raw_schema: tuple[Any, ...] = tuple(schema)
# If schema is provided, override SCHEMA attribute before base _ensure_schema runs
if self.raw_schema:
self.SCHEMA = self.raw_schema
self.raw_migrations: tuple[Any, ...] = tuple(migrations)
if self.raw_migrations:
self.MIGRATIONS = tuple(
m.to_tuple() if hasattr(m, 'to_tuple') else m
for m in self.raw_migrations
)
super().__init__(
path=target,
timeout=timeout,
dialect=dialect,
owner=owner,
lease_seconds=lease_seconds,
clock=clock,
readonly=readonly,
schema=self.SCHEMA,
)
[docs] def one(self, q: str, args: Sequence[Any] = ()) -> Optional[tuple[Any, ...]]:
"""Execute query and fetch one row, closing the cursor before returning."""
return self._one(q, args)
[docs] def all(self, q: str, args: Sequence[Any] = ()) -> list[tuple[Any, ...]]:
"""Execute query and fetch all rows, closing the cursor before returning."""
return self._all(q, args)
[docs]class SqliteAdapter(DatabaseAdapter):
"""SQLite database adapter module."""
[docs] def __init__(
self,
path: str = ':memory:',
schema: Sequence[Any] = (),
migrations: Sequence[Any] = (),
timeout: float = 5.0,
dialect: Optional[Dialect] = None,
owner: Optional[str] = None,
lease_seconds: int = LEASE_SECONDS,
clock: Optional[Callable[[], int]] = None,
readonly: bool = False,
) -> None:
super().__init__(
target=path,
schema=schema,
migrations=migrations,
timeout=timeout,
dialect=dialect or SqliteDialect(),
owner=owner,
lease_seconds=lease_seconds,
clock=clock,
readonly=readonly,
)
[docs]class PsqlAdapter(DatabaseAdapter):
"""PostgreSQL database adapter module."""
[docs] def __init__(
self,
url: str,
schema: Sequence[Any] = (),
migrations: Sequence[Any] = (),
timeout: float = 5.0,
dialect: Optional[Dialect] = None,
owner: Optional[str] = None,
lease_seconds: int = LEASE_SECONDS,
clock: Optional[Callable[[], int]] = None,
readonly: bool = False,
) -> None:
if dialect is None:
from .postgres import PostgresDialect
dialect = PostgresDialect()
super().__init__(
target=url,
schema=schema,
migrations=migrations,
timeout=timeout,
dialect=dialect,
owner=owner,
lease_seconds=lease_seconds,
clock=clock,
readonly=readonly,
)
PostgresAdapter = PsqlAdapter
[docs]def create_adapter(
backend: Optional[str] = None,
target: Optional[str] = None,
schema: Sequence[Any] = (),
migrations: Sequence[Any] = (),
**kw: Any,
) -> DatabaseAdapter:
"""Create a DatabaseAdapter for the specified backend or target."""
tgt = target or ':memory:'
b = (backend or '').lower()
if b in ('psql', 'postgres', 'postgresql') or tgt.startswith(('postgresql://', 'postgres://')):
return PsqlAdapter(url=tgt, schema=schema, migrations=migrations, **kw)
return SqliteAdapter(path=tgt, schema=schema, migrations=migrations, **kw)
[docs]def adapter_from_locator(
locator: Any,
name: str,
schema: Sequence[Any] = (),
migrations: Sequence[Any] = (),
**kw: Any,
) -> DatabaseAdapter:
"""Instantiate a DatabaseAdapter using the node's storage Locator."""
target = locator.target(name)
dialect = getattr(locator, 'dialect', None)
owner = kw.pop('owner', getattr(locator, 'owner', None))
if dialect is not None and dialect.name == 'postgres':
return PsqlAdapter(url=target, schema=schema, migrations=migrations, dialect=dialect, owner=owner, **kw)
return SqliteAdapter(path=target, schema=schema, migrations=migrations, dialect=dialect, owner=owner, **kw)
__all__ = [
'DatabaseAdapter',
'SqliteAdapter',
'PsqlAdapter',
'PostgresAdapter',
'create_adapter',
'adapter_from_locator',
]