Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /TrueSelph_jvspatial /jvspatial /db /database.py
| """Simplified database interface focusing on essential CRUD operations. | |
| This module provides a streamlined database interface that removes | |
| unnecessary complexity while maintaining core functionality. | |
| """ | |
| import base64 | |
| import json | |
| import logging | |
| from abc import ABC, abstractmethod | |
| from dataclasses import dataclass, field | |
| from functools import partial | |
| from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Union | |
| from jvspatial.db.query import QueryEngine | |
| # ---- cursor encoding ------------------------------------------------------- | |
| # Opaque bytes that callers pass back to ``find_iter(cursor=...)`` to | |
| # resume a paged iteration. We encode as base64-of-json-of-the-last-row's | |
| # (sort_keys, id) tuple — opaque to the caller, debuggable on demand. | |
| def encode_cursor(payload: Dict[str, Any]) -> bytes: | |
| """Encode a cursor payload to opaque bytes. | |
| Format: base64(json(payload)). Stable across backends; callers | |
| should treat the bytes as fully opaque. | |
| """ | |
| raw = json.dumps(payload, default=str, separators=(",", ":")).encode("utf-8") | |
| return base64.urlsafe_b64encode(raw) | |
| def decode_cursor(cursor: Optional[bytes]) -> Optional[Dict[str, Any]]: | |
| """Decode an opaque cursor produced by :func:`encode_cursor`. | |
| ``None`` and empty bytes both decode to ``None`` so callers can | |
| start a fresh iteration without special-casing. | |
| """ | |
| if not cursor: | |
| return None | |
| try: | |
| raw = base64.urlsafe_b64decode(cursor) | |
| return json.loads(raw.decode("utf-8")) # type: ignore[no-any-return] | |
| except (ValueError, TypeError, json.JSONDecodeError) as exc: | |
| raise ValueError(f"invalid cursor: {exc}") from exc | |
| class BulkSaveResult: | |
| """Structured outcome of a :meth:`Database.bulk_save_detailed` call. | |
| Adapters with partial-success semantics (JsonDB, DynamoDB, MongoDB | |
| ``ordered=False``) report the per-record breakdown so callers can | |
| distinguish "all saved" from "some lost" — previously every adapter | |
| returned the same ``int`` and silent drops were indistinguishable | |
| from success (audit §5.7 / §5.13). | |
| """ | |
| attempted: int | |
| saved: int | |
| failed_ids: List[str] = field(default_factory=list) | |
| def all_saved(self) -> bool: | |
| """Return True when every attempted record persisted.""" | |
| return self.saved == self.attempted and not self.failed_ids | |
| logger = logging.getLogger(__name__) | |
| def resolve_sort_value(record: Dict[str, Any], field: str) -> Any: | |
| """Read ``field`` out of ``record``, following dotted paths. | |
| ``field`` may be a plain key (``id``) or a dotted path into nested | |
| documents (``context.started_at``), matching what the SQLite/Postgres | |
| sort pushdowns and Mongo's native sort accept. A missing key — or a | |
| non-dict encountered part-way along the path — resolves to ``None`` | |
| rather than raising, so a malformed record sorts as "missing" instead | |
| of breaking the whole page. | |
| Anything that mints or interprets a sort value should go through this | |
| rather than a flat ``record.get(field)``: cursor payloads in | |
| :meth:`GraphContext.find_page` and adapter-side sorting must agree on | |
| what a sort field resolves to. | |
| """ | |
| if "." not in field: | |
| return record.get(field) | |
| value: Any = record | |
| for part in field.split("."): | |
| if not isinstance(value, dict): | |
| return None | |
| value = value.get(part) | |
| return value | |
| def _find_sort_key( | |
| record: Dict[str, Any], field: str, *, descending: bool = False | |
| ) -> Tuple[bool, Any]: | |
| """Sort key placing missing values last, ascending or descending. | |
| Supports dotted paths (``context.started_at``) so callers can sort attribute | |
| fields the same way they query them. The SQLite/Postgres sort pushdowns | |
| (``_sqlite_translate.translate_sort`` / ``_postgres_translate.translate_sort``) | |
| and Mongo's native sort already resolve dotted paths; without this the same | |
| sort spec silently degraded to "every key is ``None``" whenever a backend | |
| fell back to the in-memory path. | |
| ``finalize_find_results`` sorts descending via ``reverse=True``, which flips | |
| the whole key — including the ``None`` flag. Inverting the flag for | |
| descending sorts keeps missing values last in both directions, matching the | |
| ``NULLS LAST`` both SQL translators emit. All missing values share a flag, | |
| so ``None`` is never compared against a real value. | |
| """ | |
| value = resolve_sort_value(record, field) | |
| missing = value is None | |
| return (not missing if descending else missing, value) | |
| def _normalize_id_query(query: Dict[str, Any]) -> Dict[str, Any]: | |
| """Map ``_id`` → ``id`` when only ``_id`` is present. | |
| The default ``find_one_and_update`` / ``find_one_and_delete`` impls | |
| feed the query into ``QueryEngine.match`` against records stored by | |
| non-Mongo backends (JsonDB / SQLite / DynamoDB) which only persist | |
| ``id``. Callers that follow the Mongo-style convention of querying | |
| by ``_id`` would otherwise silently miss every row on those backends | |
| (audit §5.3). When both keys are present the caller's intent is | |
| preserved verbatim. | |
| """ | |
| if "_id" in query and "id" not in query: | |
| normalized = {k: v for k, v in query.items() if k != "_id"} | |
| normalized["id"] = query["_id"] | |
| return normalized | |
| return query | |
| def finalize_find_results( | |
| records: List[Dict[str, Any]], | |
| *, | |
| sort: Optional[List[Tuple[str, int]]] = None, | |
| limit: Optional[int] = None, | |
| ) -> List[Dict[str, Any]]: | |
| """Apply optional Mongo-style sort and limit in memory. | |
| ``sort`` is a list of ``(field, direction)`` with ``direction`` ``1`` for | |
| ascending and ``-1`` for descending. Sorting is stable; compound sorts are | |
| applied from the last key to the first. Records missing the sort field sort | |
| last in both directions, matching the ``NULLS LAST`` the SQLite and Postgres | |
| pushdowns emit. | |
| """ | |
| out = records | |
| if sort: | |
| out = list(records) | |
| for sort_field, direction in reversed(sort): | |
| descending = direction == -1 | |
| out.sort( | |
| key=partial(_find_sort_key, field=sort_field, descending=descending), | |
| reverse=descending, | |
| ) | |
| if limit is not None: | |
| out = out[:limit] | |
| return out | |
| class Database(ABC): | |
| """Simplified abstract base class for database adapters. | |
| Provides essential CRUD operations without complex transaction support. | |
| Focuses on core functionality. | |
| All implementations must support: | |
| - Basic CRUD operations (save, get, delete, find) | |
| - Collection-based data organization | |
| - Simple query operations with dict-based filters | |
| **Standard compound operations** (always available on built-in adapters): | |
| - ``find_one_and_update`` — default uses ``find_one`` + ``QueryEngine.apply_update`` | |
| + ``save`` (read-modify-write; **not** atomic under concurrency except where | |
| overridden, e.g. MongoDB native). | |
| - ``find_one_and_delete`` — default uses ``find_one`` + ``delete`` (not atomic | |
| except MongoDB native override). | |
| Query matching for both follows the same rules as :meth:`find_one` / :meth:`find` | |
| (Mongo-style operators via :class:`~jvspatial.db.query.QueryEngine` where the | |
| adapter applies it). | |
| Capability flags | |
| ---------------- | |
| Subclasses set the following class attributes so callers can branch on | |
| capabilities without sniffing for adapter classes: | |
| ``supports_transactions`` | |
| ``True`` if :meth:`begin_transaction` returns a real transaction | |
| with ACID semantics (e.g. MongoDB replica set). ``False`` for | |
| adapters where transactions are unavailable or only available in a | |
| weak buffered form. Default ``False``. | |
| """ | |
| # Capability flags. Override in subclasses. | |
| supports_transactions: bool = False | |
| async def save(self, collection: str, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Save a record to the database. | |
| Args: | |
| collection: Collection name | |
| data: Record data | |
| Returns: | |
| Saved record with any database-generated fields | |
| """ | |
| pass | |
| async def get(self, collection: str, id: str) -> Optional[Dict[str, Any]]: | |
| """Retrieve a record by ID. | |
| Args: | |
| collection: Collection name | |
| id: Record ID | |
| Returns: | |
| Record data or None if not found | |
| """ | |
| pass | |
| async def delete(self, collection: str, id: str) -> None: | |
| """Delete a record by ID. | |
| Args: | |
| collection: Collection name | |
| id: Record ID | |
| """ | |
| pass | |
| async def find( | |
| self, | |
| collection: str, | |
| query: Dict[str, Any], | |
| *, | |
| limit: Optional[int] = None, | |
| sort: Optional[List[Tuple[str, int]]] = None, | |
| ) -> List[Dict[str, Any]]: | |
| """Find records matching a query. | |
| Args: | |
| collection: Collection name | |
| query: Query parameters (empty dict for all records) | |
| limit: Optional maximum number of documents to return after matching | |
| sort: Optional list of ``(field, direction)`` tuples (``1`` asc, ``-1`` desc) | |
| Returns: | |
| List of matching records | |
| Ordering contract (SPEC §4.1) — implementations must satisfy all of | |
| it whether they push the sort into the backend or fall back to | |
| :func:`finalize_find_results`: | |
| * ``field`` may be a dotted path into nested documents | |
| (``context.started_at``); resolve it with | |
| :func:`resolve_sort_value`, never a flat ``record.get(field)``. | |
| * Records with no value for the sort field come **last in both | |
| directions**, matching the ``NULLS LAST`` the SQL translators emit. | |
| * The sort is stable; compound sorts apply from the last key first. | |
| * If the ordering cannot be expressed in the backend, ``limit`` must | |
| not be pushed down either — fetch the full match set and apply | |
| ``sort`` and ``limit`` together in memory, or the result is the top | |
| N of an arbitrary N. | |
| Known divergences are listed in SPEC §4.1 (MongoDB places missing | |
| values first on ascending sorts; heterogeneous value types raise in | |
| memory but order by storage class in SQL). | |
| """ | |
| pass | |
| async def count( | |
| self, collection: str, query: Optional[Dict[str, Any]] = None | |
| ) -> int: | |
| """Count records matching a query. | |
| Args: | |
| collection: Collection name | |
| query: Query parameters (empty dict for all records) | |
| Returns: | |
| Number of matching records | |
| """ | |
| if query is None: | |
| query = {} | |
| results = await self.find(collection, query) | |
| return len(results) | |
| async def find_iter( | |
| self, | |
| collection: str, | |
| query: Dict[str, Any], | |
| *, | |
| sort: Optional[List[Tuple[str, int]]] = None, | |
| batch_size: int = 100, | |
| cursor: Optional[bytes] = None, | |
| ) -> AsyncIterator[Dict[str, Any]]: | |
| """Page through ``query`` results in constant memory. | |
| Yields one record at a time. Callers iterate with:: | |
| async for record in db.find_iter("user", {"context.active": True}): | |
| ... | |
| The default implementation provides keyset pagination over | |
| the ``id`` field (always-unique, lexically sortable per | |
| SPEC §1.1). Adapters with native cursors (Mongo motor cursor, | |
| DynamoDB ``LastEvaluatedKey``, asyncpg ``server-side cursor``) | |
| override this for fewer round trips. | |
| Args: | |
| collection: Collection name. | |
| query: Mongo-style query (same operator surface as ``find``). | |
| sort: Optional ``[(field, direction)]``, defaulting to ``id`` | |
| ascending. **The default implementation's cursor tracks | |
| ``id`` only**, so a non-``id`` sort is not safely pageable | |
| here: each batch asks for ``id > last_id``, which drops | |
| records that sort after the batch but carry a lower ``id``. | |
| Use ``sort=None`` (or an ``id`` sort) with this default, or | |
| an adapter override with a native cursor. A composite | |
| ``(sort_value, id)`` cursor is not yet implemented — for a | |
| custom sort key with correct paging use | |
| :meth:`jvspatial.core.context.GraphContext.find_page`. | |
| batch_size: Records per round trip. Default 100. | |
| cursor: Opaque bytes from a prior call's last record. Pass | |
| back to resume; pass ``None`` (default) to start fresh. | |
| Yields: | |
| One record dict per iteration. The caller's last-seen | |
| record's ``id`` can be encoded into a fresh cursor via | |
| :func:`encode_cursor` if you want to checkpoint progress; | |
| otherwise ``find_iter`` manages cursor advancement internally. | |
| Notes: | |
| * Keyset pagination is consistent under concurrent inserts | |
| — a new row appearing earlier in the sort order won't | |
| be skipped, but a row updated to a later sort value | |
| between batches may be visited twice. For exactly-once | |
| semantics across long iterations, snapshot the query at | |
| a transaction. | |
| * The default implementation issues N/batch_size round | |
| trips; expect linear behavior, not constant. Adapter | |
| overrides amortize the cost. | |
| """ | |
| last_id: Optional[str] = None | |
| if cursor is not None: | |
| decoded = decode_cursor(cursor) | |
| if decoded is not None: | |
| last_id = decoded.get("id") | |
| while True: | |
| page_query = dict(query) | |
| if last_id is not None: | |
| # Compose an id > last_id constraint into the user query. | |
| existing_id_clause = page_query.pop("id", None) | |
| # Merge: keep any user-provided id clause + add the | |
| # keyset filter. | |
| if existing_id_clause is None: | |
| page_query["id"] = {"$gt": last_id} | |
| elif isinstance(existing_id_clause, dict): | |
| merged = dict(existing_id_clause) | |
| existing_gt = merged.get("$gt") | |
| if existing_gt is None or last_id > existing_gt: | |
| merged["$gt"] = last_id | |
| page_query["id"] = merged | |
| else: | |
| # Caller pinned id to a literal — single-row query, | |
| # not pageable. Yield once if it hasn't been seen. | |
| if str(existing_id_clause) <= last_id: | |
| return | |
| page_query["id"] = existing_id_clause | |
| results = await self.find( | |
| collection, | |
| page_query, | |
| sort=sort or [("id", 1)], | |
| limit=batch_size, | |
| ) | |
| if not results: | |
| return | |
| for rec in results: | |
| yield rec | |
| last_id = rec.get("id") or last_id | |
| if len(results) < batch_size: | |
| return | |
| async def find_one( | |
| self, collection: str, query: Dict[str, Any] | |
| ) -> Optional[Dict[str, Any]]: | |
| """Find the first record matching a query. | |
| Args: | |
| collection: Collection name | |
| query: Query parameters | |
| Returns: | |
| First matching record or None if not found | |
| """ | |
| results = await self.find(collection, query) | |
| return results[0] if results else None | |
| async def find_many( | |
| self, collection: str, ids: List[str] | |
| ) -> Dict[str, Dict[str, Any]]: | |
| """Bulk-fetch records by id in one round trip per backend. | |
| Args: | |
| collection: Collection name. | |
| ids: Record IDs to fetch. Duplicates are de-duplicated. | |
| Returns: | |
| ``{id: record}`` for each id that exists. Missing ids are | |
| simply absent from the result (no exception, no ``None`` | |
| placeholder). Order is **not** preserved across backends -- | |
| iterate the returned dict by your input ``ids`` list if you | |
| need stable ordering. | |
| Performance: | |
| * MongoDB: single ``find({"_id": {"$in": ids}})`` call. | |
| * SQLite: single ``WHERE collection=? AND id IN (?,?,...)`` SELECT. | |
| * DynamoDB: chunked ``BatchGetItem`` (100 ids/request) with | |
| parallel batches. | |
| * JsonDB: parallel ``asyncio.gather`` over per-file reads. | |
| The default implementation in this base class issues N | |
| sequential ``get()`` calls -- adapters should override. | |
| """ | |
| if not ids: | |
| return {} | |
| unique_ids = list(dict.fromkeys(ids)) # de-dup, preserve order | |
| out: Dict[str, Dict[str, Any]] = {} | |
| for rec_id in unique_ids: | |
| doc = await self.get(collection, rec_id) | |
| if doc is not None: | |
| out[rec_id] = doc | |
| return out | |
| async def bulk_save(self, collection: str, records: List[Dict[str, Any]]) -> int: | |
| """Save many records in one round trip per backend. | |
| Args: | |
| collection: Collection name. | |
| records: Iterable of record dicts. Each must have an ``id`` | |
| field. Records without ``id`` raise ``ValueError``. | |
| Returns: | |
| Number of records successfully saved. | |
| For partial-success visibility (which IDs failed) use | |
| :meth:`bulk_save_detailed`. Adapters with all-or-nothing | |
| semantics (SQLite) raise rather than return a partial count. | |
| """ | |
| result = await self.bulk_save_detailed(collection, records) | |
| return result.saved | |
| async def bulk_save_detailed( | |
| self, collection: str, records: List[Dict[str, Any]] | |
| ) -> BulkSaveResult: | |
| """Save many records, returning a structured per-record outcome. | |
| Args: | |
| collection: Collection name. | |
| records: Iterable of record dicts. Each must have an ``id`` | |
| field. Records without ``id`` raise ``ValueError`` (the | |
| check is per-batch, before any save attempt). | |
| Returns: | |
| :class:`BulkSaveResult` with ``attempted`` / ``saved`` / | |
| ``failed_ids``. | |
| Atomicity (per backend): | |
| * MongoDB: ``bulk_write`` with ``ordered=False`` — partial | |
| successes are reported; failures don't block other writes. | |
| * SQLite: single transaction with ``executemany``; **all | |
| records or none** land. A constraint violation rolls back | |
| the whole batch and raises (``failed_ids`` is unset). | |
| * DynamoDB: ``BatchWriteItem`` with unprocessed-item retry; | |
| unprocessed items after retries land in ``failed_ids``. | |
| * JsonDB: parallel atomic per-file writes; per-record | |
| exceptions land in ``failed_ids``. | |
| The default implementation in this base class is a serial | |
| loop of ``save()`` calls catching per-record exceptions. | |
| Adapters should override for round-trip efficiency. | |
| """ | |
| if not records: | |
| return BulkSaveResult(attempted=0, saved=0, failed_ids=[]) | |
| for idx, r in enumerate(records): | |
| if "id" not in r: | |
| # Caller error — surface the offending index for fast | |
| # debugging (audit §5.15). | |
| raise ValueError(f"bulk_save: record at index {idx} has no 'id' field") | |
| saved = 0 | |
| failed_ids: List[str] = [] | |
| for r in records: | |
| try: | |
| await self.save(collection, dict(r)) | |
| saved += 1 | |
| except Exception as e: # pragma: no cover — defensive | |
| logger.warning( | |
| "%s.bulk_save: record id=%r failed: %s", | |
| type(self).__name__, | |
| r.get("id"), | |
| e, | |
| ) | |
| failed_ids.append(str(r.get("id", ""))) | |
| return BulkSaveResult( | |
| attempted=len(records), saved=saved, failed_ids=failed_ids | |
| ) | |
| async def find_one_and_delete( | |
| self, collection: str, query: Dict[str, Any] | |
| ) -> Optional[Dict[str, Any]]: | |
| """Find and delete the first record matching ``query``. | |
| **Query semantics** match :meth:`find_one` (same dict filters and operators | |
| supported by the adapter, typically via :class:`~jvspatial.db.query.QueryEngine`). | |
| **Atomicity:** the default implementation is ``find_one`` then ``delete`` and is | |
| **not** atomic under concurrent writers. MongoDB overrides with a native | |
| ``find_one_and_delete`` for atomicity. | |
| Args: | |
| collection: Collection name | |
| query: Query parameters (e.g. ``{"_id": "x", "_jv_claim": "token"}``) | |
| Returns: | |
| Deleted document if found, ``None`` otherwise | |
| """ | |
| # Non-Mongo backends store records keyed by ``id`` only. Normalize | |
| # the Mongo-style ``_id`` filter so default matching works | |
| # uniformly (audit §5.3 / SPEC §4.1). | |
| doc = await self.find_one(collection, _normalize_id_query(query)) | |
| if doc is None: | |
| return None | |
| record_id = doc.get("_id", doc.get("id")) | |
| if record_id is not None: | |
| await self.delete(collection, str(record_id)) | |
| return doc | |
| async def find_one_and_update( | |
| self, | |
| collection: str, | |
| query: Dict[str, Any], | |
| update: Dict[str, Any], | |
| upsert: bool = False, | |
| ) -> Optional[Dict[str, Any]]: | |
| """Find and update the first record matching ``query``. | |
| Default implementation: ``find_one`` + ``QueryEngine.apply_update`` + ``save``. | |
| **Not atomic** under concurrent writers (MongoDB overrides with native | |
| ``find_one_and_update``). | |
| Supported update operators include ``$set``, ``$unset``, ``$inc``, ``$push``, | |
| ``$addToSet``, and ``$setOnInsert`` when ``upsert=True``. | |
| Args: | |
| collection: Collection name | |
| query: Query parameters (e.g. ``{"_id": "sender_id"}``) | |
| update: MongoDB-style update document | |
| upsert: If ``True``, create a document when no match | |
| Returns: | |
| Updated document, or ``None`` if no match and ``upsert`` is ``False`` | |
| """ | |
| # Non-Mongo backends store records keyed by ``id`` only. Normalize | |
| # the Mongo-style ``_id`` filter so default matching works | |
| # uniformly (audit §5.3 / SPEC §4.1). | |
| normalized = _normalize_id_query(query) | |
| doc = await self.find_one(collection, normalized) | |
| is_new = doc is None | |
| if is_new: | |
| if not upsert: | |
| return None | |
| doc = {} | |
| doc_id = query.get("_id", query.get("id")) | |
| if doc_id is not None: | |
| doc["_id"] = doc_id | |
| doc["id"] = str(doc_id) | |
| QueryEngine.apply_update(doc, update, apply_set_on_insert=True) | |
| else: | |
| QueryEngine.apply_update(doc, update, apply_set_on_insert=False) | |
| record_id = doc.get("id", doc.get("_id")) | |
| if record_id is not None: | |
| doc["id"] = str(record_id) | |
| await self.save(collection, doc) | |
| return doc | |
| async def create_index( | |
| self, | |
| collection: str, | |
| field_or_fields: Union[str, List[Tuple[str, int]]], | |
| unique: bool = False, | |
| **kwargs: Any, | |
| ) -> None: | |
| """Create an index on the specified field(s). | |
| This is an optional method that databases can implement for performance optimization. | |
| Databases that don't support indexing should override this with a no-op implementation. | |
| Args: | |
| collection: Collection name | |
| field_or_fields: Single field name (str) or list of (field_name, direction) tuples for compound indexes | |
| unique: Whether the index should enforce uniqueness | |
| **kwargs: Additional database-specific index options (e.g., expireAfterSeconds for TTL indexes) | |
| Note: | |
| Default implementation logs a warning. Database implementations should override this method. | |
| """ | |
| logger.warning( | |
| f"create_index() called on {self.__class__.__name__} but indexing is not implemented. " | |
| f"Index creation for collection '{collection}' on field(s) '{field_or_fields}' was ignored." | |
| ) | |
| async def drop_deprecated_indexes(self, deprecated: Dict[str, List[str]]) -> None: | |
| """Drop indexes that were removed or renamed in code (orphan cleanup). | |
| Called once at startup with a map of collection name → list of old index | |
| names to remove. The default implementation is a no-op so that adapters | |
| which do not use named indexes (e.g. in-memory) can ignore it. | |
| Adapters that do support named indexes (MongoDB, PostgreSQL with explicit | |
| index names, etc.) should override this to silently skip missing indexes | |
| and log a warning for any other errors. | |
| Args: | |
| deprecated: Mapping of collection name to old index names. | |
| Example: ``{"node": ["conv_id_only", "context.session_id_1"]}`` | |
| """ | |
| return None | |
| __all__ = [ | |
| "Database", | |
| "DatabaseError", | |
| "VersionConflictError", | |
| "BulkSaveResult", | |
| "encode_cursor", | |
| "decode_cursor", | |
| "finalize_find_results", | |
| "resolve_sort_value", | |
| ] | |
| class DatabaseError(Exception): | |
| """Base exception for database operations.""" | |
| pass | |
| class VersionConflictError(DatabaseError): | |
| """Raised when a document version conflict occurs during update.""" | |
| pass | |
Xet Storage Details
- Size:
- 26 kB
- Xet hash:
- 5c0e9d4efe4454c5002300e010a1d2bb53423571481e8d550f104d31491d80f6
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.