From 93f5a625e969e7695e0d942fef65264d11704262 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 18:11:48 -0800 Subject: [PATCH 01/13] fix(databases)!: hash SQL store table names (ITL-1552) --- changelog.d/ITL-1552.md | 7 + docs/dev/design_issues/ITL-1552-CA4.md | 12 + docs/dev/plans/itl-1552-sql-table-names.md | 14 ++ docs/reference/hashing.md | 1 + src/orcapod/databases/_sql_store.py | 81 ++++++ .../databases/connector_arrow_database.py | 231 ++++++++++++------ src/orcapod/databases/postgresql_connector.py | 135 +++++++++- src/orcapod/databases/sqlite_connector.py | 88 ++++++- src/orcapod/databases/store_table_names.py | 72 ++++++ src/orcapod/protocols/database_protocols.py | 6 +- tests/test_databases/test_list_table_paths.py | 58 +++-- .../test_postgresql_connector_integration.py | 64 +++-- .../test_sqlite_connector_integration.py | 102 ++++++++ .../test_databases/test_store_table_names.py | 22 ++ .../test_databases/test_unstorable_columns.py | 58 ++--- tests/test_hashing/test_hash_label_rule.py | 1 + 16 files changed, 785 insertions(+), 167 deletions(-) create mode 100644 changelog.d/ITL-1552.md create mode 100644 docs/dev/design_issues/ITL-1552-CA4.md create mode 100644 docs/dev/plans/itl-1552-sql-table-names.md create mode 100644 src/orcapod/databases/_sql_store.py create mode 100644 src/orcapod/databases/store_table_names.py create mode 100644 tests/test_databases/test_store_table_names.py diff --git a/changelog.d/ITL-1552.md b/changelog.d/ITL-1552.md new file mode 100644 index 000000000..7fb327f8f --- /dev/null +++ b/changelog.d/ITL-1552.md @@ -0,0 +1,7 @@ +### Breaking changes and migration + +- SQLite and PostgreSQL stores now name record tables using a readable path hint + and a digest of the full path. Existing tables under the old names stay in the + database, but Orcapod omits them from listings and reads their paths as missing. + Rebuild an existing store from its inputs in a fresh SQLite database or + PostgreSQL schema. Orcapod leaves the old tables untouched and does not migrate them. diff --git a/docs/dev/design_issues/ITL-1552-CA4.md b/docs/dev/design_issues/ITL-1552-CA4.md new file mode 100644 index 000000000..6fb370f2a --- /dev/null +++ b/docs/dev/design_issues/ITL-1552-CA4.md @@ -0,0 +1,12 @@ +## `src/orcapod/databases/connector_arrow_database.py` + +### CA4 — Distinct paths could share a SQL record table +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1552 + +Path sanitization could turn distinct paths into the same table name and let one +write overwrite the other's rows. PostgreSQL also refused names beyond 63 bytes. + +**Fix:** Both SQL backends use a 63-byte budget for the path hint and digest. A +versioned catalog keeps the original paths so lookups can refuse name collisions. diff --git a/docs/dev/plans/itl-1552-sql-table-names.md b/docs/dev/plans/itl-1552-sql-table-names.md new file mode 100644 index 000000000..79d246751 --- /dev/null +++ b/docs/dev/plans/itl-1552-sql-table-names.md @@ -0,0 +1,14 @@ +# ITL-1552 SQL store table names + +1. Reproduce the table-name collision through the SQLite store and add a + PostgreSQL integration test for long Unicode paths. +2. Extract the readable hint and canonical path digest from PR 589 into a shared + naming helper with caller-supplied length limits. Verify the helper against + one of PR 589's name examples. +3. Apply the approved identifier budget and path listing design to the SQL + stores. Test that another connection can list and read the tables and that + the stale-table check finds older layouts and result revisions under the + node name. Test that tables written under the old names are ignored and + preserved. +4. Document the required store rebuild and record the digest in the hash site + inventory. Run the targeted suites, lint, type checks, and golden check. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e05ee87b3..8571d6b08 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -331,6 +331,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | | SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` | +| Connector store table name | the full store path, as a compact UTF-8 JSON array of path components | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`) | the bare hexadecimal suffix in a table name, with a length set by the backend | `databases/store_table_names.py:store_table_digest` | | synthesized struct class name | the field signature | MD5 hex, 8 digits | a Python class name (a name) | (not reached by a traced test) `semantic_types/universal_converter.py` | | random ids | nothing | `uuid4`, `uuid7` | run ids, datagram and record uuids, observer ids, correlation keys | (not hashes) | | unused code | Arrow tables | SHA-256, SHA3, BLAKE2b | no caller; removal is ITL-1156 | (not reached) `hashing/arrow_utils.py`, `hashing/arrow_serialization.py` | diff --git a/src/orcapod/databases/_sql_store.py b/src/orcapod/databases/_sql_store.py new file mode 100644 index 000000000..7ba7dd764 --- /dev/null +++ b/src/orcapod/databases/_sql_store.py @@ -0,0 +1,81 @@ +"""Catalog contract for SQLite and PostgreSQL connector stores.""" + +from __future__ import annotations + +import json +from contextlib import AbstractContextManager +from typing import Protocol, cast, runtime_checkable + +from orcapod.errors import OrcapodDatabaseError + +# Quoted as one identifier. The dots keep this versioned layout marker outside +# both the old and the current grammar for record table names. +STORE_PATH_CATALOG = "orcapod.store_paths.v1" + + +@runtime_checkable +class SQLStoreConnector(Protocol): + """SQL operations a connector store needs to track record table ownership.""" + + def get_store_table_paths( + self, name: str, *, exact: bool = False + ) -> list[tuple[str, str]]: + """Return physical names and stored JSON paths for existing record tables.""" + ... + + def store_table_transaction( + self, table_name: str, path_json: str + ) -> AbstractContextManager[None]: + """Verify or register a path and commit its record write in one transaction.""" + ... + + +def catalog_name_pattern(name: str) -> str: + """Escape a physical name prefix for a SQL LIKE expression with escape '!'.""" + return name.replace("!", "!!").replace("_", "!_").replace("%", "!%") + "%" + + +def stored_path(table_name: str, path_json: str) -> tuple[str, ...]: + """Decode the original path, refusing an unreadable catalog entry.""" + try: + value: object = json.loads(path_json) # pyright: ignore[reportAny] + except (TypeError, ValueError) as exc: + raise OrcapodDatabaseError( + f"Table {table_name!r} has an unreadable stored path" + ) from exc + if isinstance(value, list): + components = cast("list[object]", value) + if components and all(isinstance(part, str) for part in components): + return tuple(cast("list[str]", components)) + raise OrcapodDatabaseError(f"Table {table_name!r} has an invalid stored path") + + +def require_store_table_owner( + table_name: str, + expected: tuple[str, ...], + actual: tuple[str, ...], +) -> None: + """Refuse to open the table for a different path with the same name.""" + if actual != expected: + raise OrcapodDatabaseError( + f"Table {table_name!r} already belongs to path {actual!r} and cannot be used for {expected!r}" + ) + + +def require_catalog_pair( + table_name: str, has_table: bool, recorded_path: str | None, path_json: str +) -> None: + """Refuse inconsistent ownership before creating or changing either object.""" + if recorded_path is None: + if has_table: + raise OrcapodDatabaseError(f"Table {table_name!r} has no stored path") + return + require_store_table_owner( + table_name, + stored_path(table_name, path_json), + stored_path(table_name, recorded_path), + ) + if not has_table: + raise OrcapodDatabaseError( + f"Stored path for table {table_name!r} has no record table" + ) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6e7bd8a63..c61bf4dcc 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -21,13 +21,24 @@ import re from collections import defaultdict from collections.abc import Callable, Collection, Mapping -from contextlib import AbstractContextManager +from contextlib import AbstractContextManager, nullcontext from typing import Any, cast import pyarrow as pa import pyarrow.compute as pc from orcapod.databases._pending_commits import PendingCommit, PendingCommits +from orcapod.databases._sql_store import ( + SQLStoreConnector, + require_store_table_owner, + stored_path, +) +from orcapod.databases.store_table_names import ( + STORE_TABLE_NAME_PREFIX, + store_table_name, + store_table_path_json, + table_name_hint, +) from orcapod.databases.utils import ( coerce_record_id, first_changed_column, @@ -51,6 +62,11 @@ #: The ``type`` of a connector database's saved configuration. CONNECTOR_DATABASE_TYPE = "connector_arrow_database" +# The name prefix and separator use four bytes. The hint and the SHA-256 +# suffix use the rest of the 63-byte PostgreSQL identifier budget. +_SQL_HINT_LENGTH = 27 +_SQL_DIGEST_LENGTH = 32 + def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: """Convert a PyArrow schema to a list of ColumnInfo.""" @@ -94,8 +110,8 @@ class ConnectorArrowDatabase: """Generic ``ArrowDatabaseProtocol`` implementation backed by a ``DBConnectorProtocol``. Records are buffered in memory (pending batch) and written to the connector - on ``flush()``. The ``record_path`` tuple is mapped to a sanitized SQL table - name using ``"__".join(sanitized_parts)``. + on ``flush()``. SQLite and PostgreSQL table names use a readable path hint + and a digest of the full path. A catalog records the original path. Args: connector: A ``DBConnectorProtocol`` implementation providing the @@ -121,6 +137,9 @@ def __init__( _scoped_path: tuple[str, ...] = (), ) -> None: self._connector = connector + self._sql_store = ( + connector if isinstance(connector, SQLStoreConnector) else None + ) self.max_hierarchy_depth = max_hierarchy_depth self._path_prefix = _path_prefix self._root = _root @@ -166,12 +185,13 @@ def _get_record_key(self, record_path: tuple[str, ...]) -> str: return "/".join(self._path_prefix + record_path) def _path_to_table_name(self, record_path: tuple[str, ...]) -> str: - """Map a record_path to a safe SQL table name. - - Each component is sanitized (non-alphanumeric chars → ``_``), then - joined with ``__`` as separator. A ``t_`` prefix is added if the result - starts with a digit to ensure a valid SQL identifier. - """ + """Map a full record path to a name the connector can store.""" + if self._sql_store is not None and record_path: + return store_table_name( + record_path, + hint_length=_SQL_HINT_LENGTH, + digest_length=_SQL_DIGEST_LENGTH, + ) parts = [re.sub(r"[^a-zA-Z0-9_]", "_", part) for part in record_path] name = "__".join(parts) if name and name[0].isdigit(): @@ -249,11 +269,25 @@ def _deduplicate_within_table(self, table: pa.Table) -> pa.Table: # ── Committed data access ───────────────────────────────────────────────── + def _has_committed_table(self, table_name: str, full_path: tuple[str, ...]) -> bool: + """Check that this path owns a table in the backend.""" + if self._sql_store is None: + return table_name in self._connector.get_table_names() + for _, path_json in self._sql_store.get_store_table_paths( + table_name, exact=True + ): + require_store_table_owner( + table_name, full_path, stored_path(table_name, path_json) + ) + return True + return False + def _get_committed_table(self, record_path: tuple[str, ...]) -> pa.Table | None: """Fetch all committed records for a path from the connector.""" - table_name = self._path_to_table_name(self._path_prefix + record_path) + full_path = self._path_prefix + record_path + table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) - if table_name not in self._connector.get_table_names(): + if not self._has_committed_table(table_name, full_path): return None batches = list(self._connector.iter_batches(f'SELECT * FROM "{table_name}"')) if not batches: @@ -263,17 +297,9 @@ def _get_committed_table(self, record_path: tuple[str, ...]) -> pa.Table | None: def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. - A table name in the backend does not keep the path it was made from (see - ``_path_to_table_name``), so this lists by name: the tables, committed or - pending, whose name starts with the name ``prefix`` maps to. The components - after ``prefix`` are the rest of the name split at ``__``. They are in the - backend's form: every character other than letters, digits and ``_`` is - ``_``, and a component that holds ``__`` comes back as two. Such a path - still names the same table. A table of another path that maps to a name - with the same beginning is listed as well. With an empty prefix at the - root, a name that got the ``t_`` prefix keeps it. - - Costs one listing of the backend's table names; no table is read. + SQLite and PostgreSQL match the original path components from the + catalog and pending batches. Other connectors list by sanitized names. + No record table is read. Args: prefix: Leading path components, relative to ``self.base_path``. @@ -282,6 +308,24 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] The table paths, relative to ``self.base_path``, sorted. """ full_prefix = self._path_prefix + prefix + if self._sql_store is not None: + stem = STORE_TABLE_NAME_PREFIX + table_name_hint( + full_prefix, hint_length=_SQL_HINT_LENGTH + ) + found_paths = {tuple(key.split("/")) for key in self._pending_batches} + for name, path_json in self._sql_store.get_store_table_paths(stem): + path = stored_path(name, path_json) + if self._path_to_table_name(path) != name: + raise OrcapodDatabaseError( + f"Table {name!r} does not match its stored path {path!r}" + ) + found_paths.add(path) + return sorted( + path[len(self._path_prefix) :] + for path in found_paths + if path[: len(full_prefix)] == full_prefix + ) + names = set(self._connector.get_table_names()) names.update( self._path_to_table_name(tuple(key.split("/"))) @@ -311,12 +355,15 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: Returns: ``True`` if a table exists at the given path, ``False`` otherwise. """ - table_name = self._path_to_table_name(self._path_prefix + record_path) + full_path = self._path_prefix + record_path + table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) record_key = self._get_record_key(record_path) - if record_key in self._pending_batches: + if self._sql_store is None and record_key in self._pending_batches: return True - return table_name in self._connector.get_table_names() + return self._has_committed_table(table_name, full_path) or ( + record_key in self._pending_batches + ) # ── Storable columns ────────────────────────────────────────────────────── @@ -330,7 +377,7 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) try: - if table_name not in self._connector.get_table_names(): + if not self._has_committed_table(table_name, full_path): pending = self._pending_batches.get(self._get_record_key(record_path)) return None if pending is None else pending.schema return pa.schema( @@ -474,9 +521,11 @@ def add_records( self.require_storable( normalize_schema_to_large_types(records.schema, keep_null=True) ) - self._require_table_name( - self._path_to_table_name(self._path_prefix + record_path) - ) + full_path = self._path_prefix + record_path + table_name = self._path_to_table_name(full_path) + self._require_table_name(table_name) + if self._sql_store is not None: + self._has_committed_table(table_name, full_path) records = normalize_table_to_large_types(records, keep_null=True) self._connector.validate_records(records) @@ -555,11 +604,13 @@ def _held_column_order( return list(pending.schema) return None - def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]] | None": + def _stored_columns( + self, table_name: str, full_path: tuple[str, ...] + ) -> "list[pa.Field[Any]] | None": """The stored table's columns as the connector reports them now, in its order (``get_column_info``, large-normalized types), or ``None`` when it does not exist. Never remembered: each call asks the connector.""" - if table_name not in self._connector.get_table_names(): + if not self._has_committed_table(table_name, full_path): return None return [ pa.field( @@ -581,9 +632,10 @@ def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: held.append(pending.schema) - table_name = self._path_to_table_name(self._path_prefix + record_path) + full_path = self._path_prefix + record_path + table_name = self._path_to_table_name(full_path) stored = self._stored_schemas.get(table_name) - if stored is None and table_name in self._connector.get_table_names(): + if stored is None and self._has_committed_table(table_name, full_path): stored = self._read_stored_schema(table_name) if stored is not None: self._stored_schemas[table_name] = stored @@ -751,55 +803,17 @@ def _flush_by_key(self, record_key: str) -> None: try: self._require_table_name(table_name) - columns = _arrow_schema_to_column_infos(pending.schema) - - # Schema validation: if the table already exists, confirm the column - # names and Arrow types match before writing. Schema evolution is - # intentionally out of scope; a clear ValueError is preferable to a - # cryptic DB-level error or a silent partial write. - # Looked up now, as the check needs: nothing about the stored table is - # trusted from an earlier call (ITL-1367). - existing = self._stored_columns(table_name) - check = self._pending_commits.schema_check(record_key) - if check is not None: - check(pending.schema if existing is None else pa.schema(existing)) - if existing is not None: - # A connector reads text and binary back in their large variants, - # which are the same types (ITL-1162). - existing_cols = {f.name: f.type for f in existing} - pending_cols = { - c.name: normalize_to_large_types(c.arrow_type, keep_null=True) - for c in columns - } - if existing_cols != pending_cols: - - def _fmt(cols: dict) -> str: - return ( - "{" - + ", ".join(f"{k}: {v}" for k, v in sorted(cols.items())) - + "}" - ) - - raise ValueError( - f"Schema mismatch for table {table_name!r}: " - f"existing={_fmt(existing_cols)}, " - f"pending={_fmt(pending_cols)}. " - "Schema evolution is not supported." - ) - - # Checked by exact name and type above: only then are the rows put - # in the stored order, by name (ITL-1367). - pending = in_held_column_order(pending, existing) - - self._connector.create_table_if_not_exists( - table_name, columns, pk_column=self.RECORD_ID_COLUMN - ) - self._connector.upsert_records( - table_name, - pending, - id_column=self.RECORD_ID_COLUMN, - skip_existing=skip_existing, + transaction = ( + nullcontext() + if self._sql_store is None + else self._sql_store.store_table_transaction( + table_name, store_table_path_json(record_path).decode() + ) ) + with transaction: + self._write_ready_batch( + record_key, record_path, table_name, pending, skip_existing + ) except BaseException: self._pending_commits.finish(record_key, committed=False) raise @@ -808,6 +822,56 @@ def _fmt(cols: dict) -> str: finally: self._pending_commits.forget(record_key, ids) + def _write_ready_batch( + self, + record_key: str, + record_path: tuple[str, ...], + table_name: str, + pending: pa.Table, + skip_existing: bool, + ) -> None: + """Check the current schema and write the ready rows.""" + columns = _arrow_schema_to_column_infos(pending.schema) + # Look up the held schema inside the write transaction (ITL-1367). + existing = self._stored_columns(table_name, record_path) + check = self._pending_commits.schema_check(record_key) + if check is not None: + check(pending.schema if existing is None else pa.schema(existing)) + if existing is not None: + # A connector reads text and binary back in their large variants, + # which are the same types (ITL-1162). + existing_cols = {f.name: cast(pa.DataType, f.type) for f in existing} + pending_cols = { + c.name: normalize_to_large_types(c.arrow_type, keep_null=True) + for c in columns + } + if existing_cols != pending_cols: + + def _fmt(cols: Mapping[str, pa.DataType]) -> str: + return ( + "{" + + ", ".join(f"{k}: {v}" for k, v in sorted(cols.items())) + + "}" + ) + + raise ValueError( + f"Schema mismatch for table {table_name!r}: " + f"existing={_fmt(existing_cols)}, " + f"pending={_fmt(pending_cols)}. " + "Schema evolution is not supported." + ) + pending = in_held_column_order(pending, existing) + + self._connector.create_table_if_not_exists( + table_name, columns, pk_column=self.RECORD_ID_COLUMN + ) + self._connector.upsert_records( + table_name, + pending, + id_column=self.RECORD_ID_COLUMN, + skip_existing=skip_existing, + ) + # ── Read methods ────────────────────────────────────────────────────────── def get_record_by_id( @@ -827,6 +891,11 @@ def get_record_by_id( pending = self._pending_batches[record_key] filtered = pending.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows > 0: + if self._sql_store is not None: + full_path = self._path_prefix + record_path + self._has_committed_table( + self._path_to_table_name(full_path), full_path + ) return self._handle_record_id_column(filtered, record_id_column) # Check committed diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 0417c04c5..e91bdac05 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -20,19 +20,27 @@ import threading import uuid from collections.abc import Iterator -from typing import TYPE_CHECKING, Any +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any, cast import pyarrow as pa +from orcapod.databases._sql_store import ( + STORE_PATH_CATALOG, + catalog_name_pattern, + require_catalog_pair, +) from orcapod.databases.utils import is_direct_projection -from orcapod.errors import UnstorableTableNameError +from orcapod.errors import OrcapodDatabaseError, UnstorableTableNameError from orcapod.types import ColumnInfo from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: import psycopg + from psycopg import sql as pg_sql else: psycopg = LazyModule("psycopg") + pg_sql = LazyModule("psycopg.sql") logger = logging.getLogger(__name__) @@ -392,6 +400,7 @@ def __init__(self, dsn: str) -> None: self._conn: Any = psycopg.connect(dsn, autocommit=False) self._lock = threading.RLock() # RLock required: iter_batches → _resolve_column_type_lookup → get_column_info re-enters the lock self._cursor_seq = itertools.count() + self._store_transaction_active = False # ── Internal helpers ────────────────────────────────────────────────────── @@ -427,6 +436,116 @@ def get_table_names(self) -> list[str]: ) return [row[0] for row in cur.fetchall()] + def get_store_table_paths( + self, name: str, *, exact: bool = False + ) -> list[tuple[str, str]]: + """Return registered record tables matching a physical name or prefix.""" + with ( + self._lock, + cast( + "psycopg.Connection[tuple[object, ...]]", self._require_open() + ).cursor() as cur, + ): + _ = cur.execute( + """ + SELECT ns.nspname + FROM pg_catalog.pg_namespace AS ns + JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid + WHERE ns.nspname = current_schema() AND rel.relname = %s + AND rel.relkind = 'r' + """, + (STORE_PATH_CATALOG,), + ) + row = cur.fetchone() + if row is None: + return [] + catalog = pg_sql.Identifier(cast(str, row[0]), STORE_PATH_CATALOG) + match = pg_sql.SQL("= %s" if exact else "LIKE %s ESCAPE '!'") + _ = cur.execute( + pg_sql.SQL(""" + SELECT paths.table_name, paths.path_json + FROM {catalog} AS paths + JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name + JOIN pg_catalog.pg_namespace AS ns ON ns.oid = physical.relnamespace + WHERE ns.nspname = current_schema() + AND physical.relkind IN ('r', 'p') AND paths.table_name {match} + """).format(catalog=catalog, match=match), + (name if exact else catalog_name_pattern(name),), + ) + return cast("list[tuple[str, str]]", cur.fetchall()) + + @contextmanager + def store_table_transaction( + self, table_name: str, path_json: str + ) -> Iterator[None]: + """Register and write a record table in one PostgreSQL transaction.""" + with self._lock: + conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) + self._store_transaction_active = True + try: + with conn.cursor() as cur: + # Serialize registrations in this schema, including when the + # catalog does not exist yet. 0x4F524341 is the Orcapod lock key. + _ = cur.execute( + """ + SELECT nspname, pg_advisory_xact_lock(%s, oid::integer) + FROM pg_catalog.pg_namespace WHERE nspname = current_schema() + """, + (0x4F524341,), + ) + location = cur.fetchone() + if location is None or location[0] is None: + raise OrcapodDatabaseError("PostgreSQL has no current schema") + catalog = pg_sql.Identifier( + cast(str, location[0]), STORE_PATH_CATALOG + ) + _ = cur.execute( + pg_sql.SQL(""" + CREATE TABLE IF NOT EXISTS {} + (table_name TEXT NOT NULL PRIMARY KEY, path_json TEXT NOT NULL) + """).format(catalog) + ) + _ = cur.execute( + pg_sql.SQL( + "SELECT path_json FROM {} WHERE table_name = %s" + ).format(catalog), + (table_name,), + ) + row = cur.fetchone() + _ = cur.execute( + """ + SELECT rel.relkind FROM pg_catalog.pg_class AS rel + JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace + WHERE ns.nspname = current_schema() AND rel.relname = %s + """, + (table_name,), + ) + physical = cur.fetchone() + if physical is not None and physical[0] not in ("r", "p"): + raise OrcapodDatabaseError( + f"Relation {table_name!r} is not a record table" + ) + require_catalog_pair( + table_name, + physical is not None, + cast(str, row[0]) if row else None, + path_json, + ) + if row is None: + _ = cur.execute( + pg_sql.SQL( + "INSERT INTO {} (table_name, path_json) VALUES (%s, %s)" + ).format(catalog), + (table_name, path_json), + ) + yield + conn.commit() + except BaseException: + conn.rollback() + raise + finally: + self._store_transaction_active = False + def current_location(self) -> tuple[str, int, str, str]: """Return the server, database and schema the connection reached. @@ -655,9 +774,11 @@ def create_table_if_not_exists( try: with conn.cursor() as cur: cur.execute(ddl) - conn.commit() + if not self._store_transaction_active: + conn.commit() except Exception: - conn.rollback() + if not self._store_transaction_active: + conn.rollback() raise def upsert_records( @@ -701,9 +822,11 @@ def upsert_records( try: with conn.cursor() as cur: cur.executemany(sql, rows_iter) - conn.commit() + if not self._store_transaction_active: + conn.commit() except Exception: - conn.rollback() + if not self._store_transaction_active: + conn.rollback() raise @property diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index e3bb8e10f..edf2f6077 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -19,11 +19,18 @@ import sqlite3 import threading from collections.abc import Iterator -from typing import Any +from contextlib import contextmanager +from typing import Any, cast import pyarrow as pa +from orcapod.databases._sql_store import ( + STORE_PATH_CATALOG, + catalog_name_pattern, + require_catalog_pair, +) from orcapod.databases.utils import is_direct_projection +from orcapod.errors import OrcapodDatabaseError from orcapod.types import ColumnInfo logger = logging.getLogger(__name__) @@ -286,6 +293,85 @@ def get_table_names(self) -> list[str]: ) return [row["name"] for row in cursor] + def get_store_table_paths( + self, name: str, *, exact: bool = False + ) -> list[tuple[str, str]]: + """Return registered record tables matching a physical name or prefix.""" + with self._lock: + conn = self._require_open() + if ( + conn.execute( + "SELECT 1 FROM main.sqlite_schema WHERE type = 'table' AND name = ?", + (STORE_PATH_CATALOG,), + ).fetchone() + is None + ): + return [] + match = "= ?" if exact else "LIKE ? ESCAPE '!'" + rows = cast( + "Iterator[sqlite3.Row]", + conn.execute( + f""" + SELECT paths.table_name, paths.path_json + FROM main."{STORE_PATH_CATALOG}" AS paths + JOIN main.sqlite_schema AS physical ON physical.name = paths.table_name + WHERE physical.type = 'table' AND paths.table_name {match} + """, + (name if exact else catalog_name_pattern(name),), + ), + ) + return [(cast(str, row[0]), cast(str, row[1])) for row in rows] + + @contextmanager + def store_table_transaction( + self, table_name: str, path_json: str + ) -> Iterator[None]: + """Register and write a record table in one SQLite transaction.""" + with self._lock: + conn = self._require_open() + _ = conn.execute("BEGIN IMMEDIATE") + try: + _ = conn.execute( + f""" + CREATE TABLE IF NOT EXISTS main."{STORE_PATH_CATALOG}" + (table_name TEXT NOT NULL PRIMARY KEY, path_json TEXT NOT NULL) + """ + ) + row = cast( + "sqlite3.Row | None", + conn.execute( + f'SELECT path_json FROM main."{STORE_PATH_CATALOG}" WHERE table_name = ?', + (table_name,), + ).fetchone(), + ) + physical = cast( + "sqlite3.Row | None", + conn.execute( + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE", + (table_name,), + ).fetchone(), + ) + if physical is not None and tuple(physical) != (table_name, "table"): + raise OrcapodDatabaseError( + f"Object {table_name!r} is not a record table" + ) + require_catalog_pair( + table_name, + physical is not None, + cast(str, row[0]) if row else None, + path_json, + ) + if row is None: + _ = conn.execute( + f'INSERT INTO main."{STORE_PATH_CATALOG}" (table_name, path_json) VALUES (?, ?)', + (table_name, path_json), + ) + yield + conn.commit() + except BaseException: + conn.rollback() + raise + def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in key-sequence order. diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py new file mode 100644 index 000000000..96f05453e --- /dev/null +++ b/src/orcapod/databases/store_table_names.py @@ -0,0 +1,72 @@ +"""Path-based table names shared by connector stores.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Sequence + +SPIRAL_TABLE_NAME_LABEL = "spiral_table_name_v1" +"""The digest algorithm shared with SpiralDB. The name's grammar carries its version.""" + +STORE_TABLE_NAME_PREFIX = "o1_" + + +def store_table_path_json(path: Sequence[str]) -> bytes: + """Encode the full store path as a compact UTF-8 JSON array. + + Args: + path: The store's base path followed by its record path. + + Raises: + ValueError: If the path is empty or contains a component that cannot be + represented by a UTF-8 string. + """ + components = list(path) + if not components: + raise ValueError("a store table path has at least one component") + if not all(type(component) is str for component in components): + raise ValueError(f"a store table path holds strings only: {components!r}") + try: + return json.dumps( + components, ensure_ascii=False, separators=(",", ":") + ).encode() + except UnicodeEncodeError as exc: + raise ValueError(f"a store table path must be valid UTF-8: {exc}") from exc + + +def store_table_digest(path: Sequence[str]) -> str: + """Return the full, bare SHA-256 hex digest of the canonical JSON path. + + Args: + path: The store's base path followed by its record path. + """ + return hashlib.sha256(store_table_path_json(path)).hexdigest() + + +def table_name_hint(path: Sequence[str], *, hint_length: int) -> str: + """Return a readable ASCII hint from the leading path characters. + + Args: + path: Full path components or leading components when filtering by name. + hint_length: The maximum number of characters to keep. + """ + return "".join( + char.lower() if char.isascii() and char.isalnum() else "_" + for char in "/".join(path)[:hint_length] + ) + + +def store_table_name( + path: Sequence[str], *, hint_length: int, digest_length: int +) -> str: + """Return a table name using the backend's identifier budget. + + Args: + path: The store's base path followed by its record path. + hint_length: The maximum number of characters from the readable hint. + digest_length: The number of hex digits to keep from the start of the digest. + """ + digest = store_table_digest(path)[:digest_length] + hint = table_name_hint(path, hint_length=hint_length) + return f"{STORE_TABLE_NAME_PREFIX}{hint}_{digest}" diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index 4b07d1b15..15779e33a 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -199,7 +199,7 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] (a table at ``prefix`` itself included). Tables stored below another table are listed too. Paths are relative to ``self.base_path``, like the ``record_path`` of every other method, and each begins with ``prefix``. - The listing opens no table and loads no record. + The listing opens no record table and loads no record. Orcapod uses it to find tables written by an earlier version, whose paths it cannot compute because the hashes inside them changed (ITL-954). @@ -214,7 +214,9 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] ``abfs://`` only when the matching ``fsspec`` package is installed and can reach the database with its default credentials. A cloud database that cannot be listed raises ``TableListingNotSupportedError``. - - ``ConnectorArrowDatabase`` (SQLite, PostgreSQL, SpiralDB): the tables + - ``ConnectorArrowDatabase`` on SQLite or PostgreSQL: the original paths of + registered record tables and pending batches, matched by exact components. + - ``ConnectorArrowDatabase`` on other connectors: the tables whose name in the backend starts with the name ``prefix`` maps to. A table name does not keep the path it was made from, so the components after ``prefix`` come back as the backend stores them: every character diff --git a/tests/test_databases/test_list_table_paths.py b/tests/test_databases/test_list_table_paths.py index f8159f89c..8e2e5cad0 100644 --- a/tests/test_databases/test_list_table_paths.py +++ b/tests/test_databases/test_list_table_paths.py @@ -330,26 +330,48 @@ def ls(self, path: str, detail: bool = True) -> list[dict[str, Any]]: class TestConnector: """Listing behaviour specific to ``ConnectorArrowDatabase``.""" - def test_components_after_the_prefix_come_back_sanitized(self, tmp_path: Path): - """Listed components are the sanitized names, and the sanitized path reads the - same table. - """ - store = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "s.db"))) + def test_original_paths_are_listed_and_read_after_reopen(self, tmp_path: Path): + """Keep exact paths and prefix boundaries through an independent connection.""" + location = tmp_path / "s.db" path = ("job", "f", "semantic_v0.1:ab12", "v0", "python.function.v1", "rdb_v2") - _fill(store, [path]) - listed = store.list_table_paths(("job", "f")) - assert listed == [ - ("job", "f", "semantic_v0_1_ab12", "v0", "python_function_v1", "rdb_v2") - ] - # The sanitized path names the same table. - assert store.table_exists(listed[0]) - records = store.get_all_records(listed[0]) - assert records is not None and records.num_rows == 1 + long_name = "name" * 30 + long_path = (long_name + ":", "old!layout") + other_path = (long_name + "-", "old!layout") + with SQLiteConnector(location) as connector: + _fill(ConnectorArrowDatabase(connector), [path, long_path, other_path]) + with SQLiteConnector(location) as connector: + store = ConnectorArrowDatabase(connector) + assert store.list_table_paths(("job", "f")) == [path] + assert not store.table_exists( + ("job", "f", "semantic_v0_1_ab12", "v0", "python_function_v1", "rdb_v2") + ) + assert store.list_table_paths((long_path[0],)) == [long_path] + scoped = store.at("job", "f") + assert scoped.list_table_paths() == [path[2:]] + for listed in store.list_table_paths(): + assert store.table_exists(listed) + records = store.get_all_records(listed) + assert records is not None and records.num_rows == 1 + + def test_stale_lookup_uses_layout_and_revision_after_a_long_name( + self, tmp_path: Path + ): + from orcapod.contexts.stored import tables_of_another_layout + + with SQLiteConnector(tmp_path / "s.db") as connector: + store = ConnectorArrowDatabase(connector).at("job") + name = ("function" * 15 + ":",) + old_layout = name + ("old_hash", "rev1", "rdb_v0") + old_revision = name + ("old_hash", "rev0", "rdb_v1") + current = name + ("new_hash", "rev1", "rdb_v1") + other = (name[0][:-1] + "-", "old_hash", "rev0", "rdb_v0") + _fill(store, [old_layout, old_revision, current, other]) + assert tables_of_another_layout(store, name, "rev1") == sorted( + [old_layout, old_revision] + ) def test_the_last_component_is_the_layout(self, tmp_path: Path): - """The last listed component is the sanitized last component of the written - path. - """ + """The last listed component is the original layout component.""" store = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "s.db"))) _fill( store, @@ -360,7 +382,7 @@ def test_the_last_component_is_the_layout(self, tmp_path: Path): ) assert [path[-1] for path in store.list_table_paths(("job",))] == [ "rdb_v1", - "schema_semantic_v0_1_cd", + "schema:semantic_v0.1:cd", ] diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index ae5436de4..05439e7e3 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -573,7 +573,7 @@ def test_operator_cache_refused_at_write_and_nothing_written( """An operator cache's system-tag column names exceed 63 bytes (ITL-1162).""" from orcapod import PipelineJob from orcapod.core.operators import SelectDataColumns - from orcapod.errors import UnstorableColumnError, UnstorableTableNameError + from orcapod.errors import UnstorableColumnError from orcapod.sources import DictSource from orcapod.types import CacheMode @@ -592,32 +592,60 @@ def test_operator_cache_refused_at_write_and_nothing_written( ) with pytest.raises(Exception) as exc_info: _ = job.run() - # The cache's table name (over 63 bytes) or its system-tag column names are - # refused, whichever entry comes first; nothing reaches the server. + # The system-tag column names are refused before any write. chain: list[BaseException] = [] err: BaseException | None = exc_info.value while err is not None: chain.append(err) err = err.__cause__ or err.__context__ - assert any( - isinstance(e, (UnstorableColumnError, UnstorableTableNameError)) for e in chain - ), chain + assert any(isinstance(e, UnstorableColumnError) for e in chain), chain assert connector.get_table_names() == [] @pytest.mark.postgres -def test_long_table_name_refused_and_nothing_written( +def test_long_non_ascii_paths_fit_postgresql_table_names( connector: PostgreSQLConnector, ) -> None: - """A table name PostgreSQL would truncate is never sent to it (ITL-1162).""" - from orcapod.errors import UnstorableTableNameError - + """Keep separate tables even when PostgreSQL would truncate the old names.""" db = ConnectorArrowDatabase(connector) - path = ("fn", "x" * 70) - table = pa.table({"v": pa.array([1], type=pa.int64())}) - with pytest.raises(UnstorableTableNameError): - db.add_record(path, b"1", table) - with pytest.raises(UnstorableTableNameError): - db.get_all_records(path) - db.flush() - assert connector.get_table_names() == [] + first = ("job", "é" * 70 + "a", "pdb_v2") + second = ("job", "é" * 70 + "b", "pdb_v2") + db.add_record(first, b"one", pa.table({"value": [1]}), flush=True) + db.add_record(second, b"one", pa.table({"value": [2]}), flush=True) + + names = [name for name in connector.get_table_names() if name.startswith("o1_")] + assert len(names) == 2 + assert all(len(name.encode("utf-8")) == 63 for name in names) + with PostgreSQLConnector(connector._dsn) as reopened: + store = ConnectorArrowDatabase(reopened) + assert store.list_table_paths(("job", first[1])) == [first] + assert store.at("job").list_table_paths() == [first[1:], second[1:]] + first_rows = store.get_all_records(first) + second_rows = store.get_all_records(second) + assert first_rows is not None and first_rows.to_pylist() == [{"value": 1}] + assert second_rows is not None and second_rows.to_pylist() == [{"value": 2}] + + +@pytest.mark.postgres +def test_record_write_failure_rolls_back_the_table_and_registration( + connector: PostgreSQLConnector, monkeypatch: pytest.MonkeyPatch +) -> None: + """The catalog, record table and rows are committed together.""" + store = ConnectorArrowDatabase(connector) + path = ("job", "new") + record = pa.table({"value": [1]}) + + def fail_write(*args: object, **kwargs: object) -> None: + raise RuntimeError("simulated write failure") + + with monkeypatch.context() as patch: + patch.setattr(connector, "upsert_records", fail_write) + with pytest.raises(RuntimeError, match="simulated write failure"): + store.add_record(path, b"one", record, flush=True) + + with PostgreSQLConnector(connector._dsn) as reopened: + assert reopened.get_table_names() == [] + other = ConnectorArrowDatabase(reopened) + assert other.list_table_paths() == [] + other.add_record(path, b"one", record, flush=True) + assert other.list_table_paths() == [path] diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index 6720ea0cb..81a49e985 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -8,6 +8,8 @@ import pytest from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector +from orcapod.errors import OrcapodDatabaseError +from orcapod.types import ColumnInfo @pytest.fixture @@ -19,6 +21,106 @@ def db() -> Iterator[ConnectorArrowDatabase]: class TestConnectorArrowDatabaseWithSQLite: + def test_long_paths_with_the_same_sanitized_name_store_separate_rows( + self, db: ConnectorArrowDatabase + ) -> None: + common = "shared_prefix_" * 12 + first = ("job", common + ":a", "pdb_v2") + second = ("job", common + "-a", "pdb_v2") + db.add_record(first, b"one", pa.table({"value": [1]}), flush=True) + db.add_record(second, b"one", pa.table({"value": [2]}), flush=True) + + first_rows = db.get_all_records(first) + second_rows = db.get_all_records(second) + assert first_rows is not None and first_rows.to_pylist() == [{"value": 1}] + assert second_rows is not None and second_rows.to_pylist() == [{"value": 2}] + + def test_paths_with_a_forced_digest_collision_cannot_share_a_table( + self, db: ConnectorArrowDatabase, monkeypatch: pytest.MonkeyPatch + ) -> None: + from orcapod.databases import store_table_names + + monkeypatch.setattr( + store_table_names, "store_table_digest", lambda path: "a" * 64 + ) + first = ("name:part",) + second = ("name-part",) + db.add_record(second, b"one", pa.table({"value": [2]})) + db.add_record(first, b"one", pa.table({"value": [1]})) + db.flush_batch(first) + with pytest.raises(OrcapodDatabaseError, match="already belongs"): + db.get_all_records(second) + with pytest.raises(OrcapodDatabaseError, match="already belongs"): + db.flush_batch(second) + with pytest.raises(OrcapodDatabaseError, match="already belongs"): + db.add_record(second, b"one", pa.table({"value": [2]}), flush=True) + assert db.list_table_paths() == [first] + records = db.get_all_records(first) + assert records is not None and records.to_pylist() == [{"value": 1}] + + def test_legacy_table_is_ignored_and_preserved(self) -> None: + with SQLiteConnector(":memory:") as connector: + columns = [ + ColumnInfo("__record_id", pa.large_binary(), False), + ColumnInfo("value", pa.int64(), False), + ] + connector.create_table_if_not_exists("job__pdb_v2", columns, "__record_id") + connector.upsert_records( + "job__pdb_v2", + pa.table({"__record_id": [b"one"], "value": [1]}), + "__record_id", + ) + db = ConnectorArrowDatabase(connector) + path = ("job", "pdb_v2") + assert not db.table_exists(path) + assert db.get_table_schema(path) is None + assert db.get_all_records(path) is None + assert db.list_table_paths(("job",)) == [] + + db.add_record(path, b"one", pa.table({"value": [2]}), flush=True) + assert db.list_table_paths(("job",)) == [path] + old = pa.Table.from_batches( + list(connector.iter_batches('SELECT "value" FROM "job__pdb_v2"')) + ) + assert old.to_pylist() == [{"value": 1}] + + def test_unregistered_physical_name_is_not_claimed(self) -> None: + from orcapod.databases.store_table_names import store_table_name + + with SQLiteConnector(":memory:") as connector: + path = ("unregistered",) + name = store_table_name(path, hint_length=27, digest_length=32) + connector.create_table_if_not_exists( + name, + [ColumnInfo("__record_id", pa.large_binary(), False)], + "__record_id", + ) + db = ConnectorArrowDatabase(connector) + assert not db.table_exists(path) + assert db.list_table_paths() == [] + with pytest.raises(OrcapodDatabaseError, match="no stored path"): + db.add_record(path, b"one", pa.table({"value": [1]}), flush=True) + assert connector.get_table_names() == [name] + + def test_registration_and_table_creation_roll_back_on_write_error( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + with SQLiteConnector(":memory:") as connector: + db = ConnectorArrowDatabase(connector) + + def fail_write(*args: object, **kwargs: object) -> None: + raise RuntimeError("simulated write failure") + + with monkeypatch.context() as patch: + patch.setattr(connector, "upsert_records", fail_write) + with pytest.raises(RuntimeError, match="simulated write failure"): + db.add_record( + ("new",), b"one", pa.table({"value": [1]}), flush=True + ) + assert connector.get_table_names() == [] + db.add_record(("new",), b"one", pa.table({"value": [1]}), flush=True) + assert db.list_table_paths() == [("new",)] + def test_add_and_get_record(self, db: ConnectorArrowDatabase) -> None: # add_record stamps all rows with the same __record_id, so within-batch # deduplication keeps only the last row (same behaviour as InMemoryArrowDatabase). diff --git a/tests/test_databases/test_store_table_names.py b/tests/test_databases/test_store_table_names.py new file mode 100644 index 000000000..ba0c8c009 --- /dev/null +++ b/tests/test_databases/test_store_table_names.py @@ -0,0 +1,22 @@ +"""Tests for the shared connector store table names.""" + +from __future__ import annotations + + +def test_shared_rule_reproduces_the_spiraldb_name() -> None: + from orcapod.databases.store_table_names import store_table_name + + path = ("función", "数据", "rdb_v1") + assert store_table_name(path, hint_length=96, digest_length=64) == ( + "o1_funci_n____rdb_v1_" + "4c0b0f48110dc57f910431847088e2e11d05b6bf2b26c3e8dfb8dd9dabf2c43b" + ) + + +def test_shorter_limits_keep_the_same_hint_and_digest_prefixes() -> None: + from orcapod.databases.store_table_names import store_table_name + + path = ("función", "数据", "rdb_v1") + assert store_table_name(path, hint_length=7, digest_length=40) == ( + "o1_funci_n_4c0b0f48110dc57f910431847088e2e11d05b6bf" + ) diff --git a/tests/test_databases/test_unstorable_columns.py b/tests/test_databases/test_unstorable_columns.py index 35c0b828e..c9dc0f2a0 100644 --- a/tests/test_databases/test_unstorable_columns.py +++ b/tests/test_databases/test_unstorable_columns.py @@ -536,6 +536,7 @@ def _mocked_postgresql() -> tuple[PostgreSQLConnector, MagicMock]: """A ``PostgreSQLConnector`` over a mocked connection (no server).""" with patch("psycopg.connect") as mock_connect: conn = MagicMock() + conn.cursor.return_value.__enter__.return_value.fetchone.return_value = None mock_connect.return_value = conn return PostgreSQLConnector("postgresql://localhost/test"), conn @@ -751,30 +752,17 @@ def test_connector_rules(self, tmp_path: pathlib.Path): finally: sqlite.close() - def test_every_table_entry_refuses_a_long_name(self): - """Write, read and check all refuse before anything is sent to the server.""" - from orcapod.errors import UnstorableTableNameError - - connector, conn = _mocked_postgresql() + def test_long_paths_can_be_buffered_and_read(self): + connector, _ = _mocked_postgresql() try: database = ConnectorArrowDatabase(connector) path = ("fn", "x" * 70) table = pa.table({"v": pa.array([1], type=pa.int64())}) - calls_before = len(conn.mock_calls) - - with pytest.raises(UnstorableTableNameError) as exc_info: - database.add_record(path, b"1", table) - with pytest.raises(UnstorableTableNameError): - database.get_all_records(path) - with pytest.raises(UnstorableTableNameError): - database.table_exists(path) - database.flush() # nothing was buffered - - assert len(conn.mock_calls) == calls_before - err = exc_info.value - assert err.database_kind == "PostgreSQLConnector" - assert err.table_name == "fn__" + "x" * 70 - assert "DeltaTableDatabase" in str(err) + database.add_record(path, b"1", table) + assert database.table_exists(path) + assert database.list_table_paths() == [path] + stored = database.get_all_records(path) + assert stored is not None and stored.equals(table) finally: connector._conn = None @@ -801,16 +789,8 @@ def test_connector_entries_refuse_a_long_name(self): connector._conn = None def test_cached_source_on_postgresql_refused(self): - """A cached source's table name holds a hash: over 63 bytes on PostgreSQL. - - Its system-tag column names hold a hash too. Either refusal comes before - anything is created or written. Since the look-up of a table at an older layout - is gone (ITL-1259), the read-only listing of tables under the source's name (for - tables of another layout) runs first; before, that look-up named the table and - was refused before any call. - """ + """A cached source's system-tag column names exceed 63 bytes.""" from orcapod.core.sources.cached_source import CachedSource - from orcapod.errors import UnstorableTableNameError connector, conn = _mocked_postgresql() try: @@ -825,10 +805,7 @@ def test_cached_source_on_postgresql_refused(self): while err is not None: chain.append(err) err = err.__cause__ or err.__context__ - assert any( - isinstance(e, (UnstorableTableNameError, UnstorableColumnError)) - for e in chain - ), chain + assert any(isinstance(e, UnstorableColumnError) for e in chain), chain statements = " ".join( str(call.args[0]).upper() for call in conn.mock_calls[calls_before:] @@ -870,13 +847,12 @@ def cached_double(x: int) -> int: assert CALLS == [] @pytest.mark.parametrize("name", ["sqlite_results", "SQLite_x", "SQLITE_"]) - def test_sqlite_reserved_table_prefix(self, tmp_path: pathlib.Path, name): - from orcapod.errors import UnstorableTableNameError - + def test_path_can_start_with_a_reserved_sqlite_prefix( + self, tmp_path: pathlib.Path, name + ): database = _sqlite_database(tmp_path) table = pa.table({"v": pa.array([1], type=pa.int64())}) - - with pytest.raises(UnstorableTableNameError): - database.add_record((name,), b"1", table) - database.flush() - assert database.list_table_paths() == [] + database.add_record((name,), b"1", table, flush=True) + assert database.list_table_paths() == [(name,)] + stored = database.get_all_records((name,)) + assert stored is not None and stored.equals(table) diff --git a/tests/test_hashing/test_hash_label_rule.py b/tests/test_hashing/test_hash_label_rule.py index 22f4c9d4f..9694fd886 100644 --- a/tests/test_hashing/test_hash_label_rule.py +++ b/tests/test_hashing/test_hash_label_rule.py @@ -818,6 +818,7 @@ def test_identity_does_not_cover_the_derived_content_hash_column(self) -> None: "polars_series_v1": "hashing/semantic_hashing/builtin_handlers.py", "group_v1": "core/operators/group_by.py", "batch_v1": "core/operators/batch.py", + "spiral_table_name_v1": "databases/store_table_names.py", } From dfc81471ef966e6c5a07f9dcd6362f869ce80a84 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 18:29:35 -0800 Subject: [PATCH 02/13] fix(databases): preserve SQL append lookups with catalog names --- src/orcapod/databases/_sql_store.py | 4 +- .../databases/connector_arrow_database.py | 27 +++----- src/orcapod/databases/postgresql_connector.py | 6 +- src/orcapod/databases/sqlite_connector.py | 6 +- tests/test_databases/test_append_by_name.py | 61 +++++++++++++------ 5 files changed, 57 insertions(+), 47 deletions(-) diff --git a/src/orcapod/databases/_sql_store.py b/src/orcapod/databases/_sql_store.py index 7ba7dd764..c4f64b7b8 100644 --- a/src/orcapod/databases/_sql_store.py +++ b/src/orcapod/databases/_sql_store.py @@ -25,8 +25,8 @@ def get_store_table_paths( def store_table_transaction( self, table_name: str, path_json: str - ) -> AbstractContextManager[None]: - """Verify or register a path and commit its record write in one transaction.""" + ) -> AbstractContextManager[bool]: + """Verify or register a path and yield whether its table already exists.""" ... diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index c61bf4dcc..6b479b89d 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -524,8 +524,6 @@ def add_records( full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) - if self._sql_store is not None: - self._has_committed_table(table_name, full_path) records = normalize_table_to_large_types(records, keep_null=True) self._connector.validate_records(records) @@ -604,14 +602,8 @@ def _held_column_order( return list(pending.schema) return None - def _stored_columns( - self, table_name: str, full_path: tuple[str, ...] - ) -> "list[pa.Field[Any]] | None": - """The stored table's columns as the connector reports them now, in its order - (``get_column_info``, large-normalized types), or ``None`` when it does not - exist. Never remembered: each call asks the connector.""" - if not self._has_committed_table(table_name, full_path): - return None + def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]]": + """Read the columns of an existing table in its order and large types.""" return [ pa.field( c.name, @@ -804,15 +796,15 @@ def _flush_by_key(self, record_key: str) -> None: try: self._require_table_name(table_name) transaction = ( - nullcontext() + nullcontext(table_name in self._connector.get_table_names()) if self._sql_store is None else self._sql_store.store_table_transaction( table_name, store_table_path_json(record_path).decode() ) ) - with transaction: + with transaction as table_exists: self._write_ready_batch( - record_key, record_path, table_name, pending, skip_existing + record_key, table_name, pending, skip_existing, table_exists ) except BaseException: self._pending_commits.finish(record_key, committed=False) @@ -825,15 +817,15 @@ def _flush_by_key(self, record_key: str) -> None: def _write_ready_batch( self, record_key: str, - record_path: tuple[str, ...], table_name: str, pending: pa.Table, skip_existing: bool, + table_exists: bool, ) -> None: """Check the current schema and write the ready rows.""" columns = _arrow_schema_to_column_infos(pending.schema) # Look up the held schema inside the write transaction (ITL-1367). - existing = self._stored_columns(table_name, record_path) + existing = self._stored_columns(table_name) if table_exists else None check = self._pending_commits.schema_check(record_key) if check is not None: check(pending.schema if existing is None else pa.schema(existing)) @@ -891,11 +883,6 @@ def get_record_by_id( pending = self._pending_batches[record_key] filtered = pending.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows > 0: - if self._sql_store is not None: - full_path = self._path_prefix + record_path - self._has_committed_table( - self._path_to_table_name(full_path), full_path - ) return self._handle_record_id_column(filtered, record_id_column) # Check committed diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index e91bdac05..04ee76b45 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -477,8 +477,8 @@ def get_store_table_paths( @contextmanager def store_table_transaction( self, table_name: str, path_json: str - ) -> Iterator[None]: - """Register and write a record table in one PostgreSQL transaction.""" + ) -> Iterator[bool]: + """Register and write a record table, yielding whether it already exists.""" with self._lock: conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) self._store_transaction_active = True @@ -538,7 +538,7 @@ def store_table_transaction( ).format(catalog), (table_name, path_json), ) - yield + yield physical is not None conn.commit() except BaseException: conn.rollback() diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index edf2f6077..659d00bec 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -325,8 +325,8 @@ def get_store_table_paths( @contextmanager def store_table_transaction( self, table_name: str, path_json: str - ) -> Iterator[None]: - """Register and write a record table in one SQLite transaction.""" + ) -> Iterator[bool]: + """Register and write a record table, yielding whether it already exists.""" with self._lock: conn = self._require_open() _ = conn.execute("BEGIN IMMEDIATE") @@ -366,7 +366,7 @@ def store_table_transaction( f'INSERT INTO main."{STORE_PATH_CATALOG}" (table_name, path_json) VALUES (?, ?)', (table_name, path_json), ) - yield + yield physical is not None conn.commit() except BaseException: conn.rollback() diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 8cb22a0f0..16e0a5b8e 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -33,6 +33,7 @@ InMemoryArrowDatabase, SQLiteConnector, ) +from orcapod.databases._sql_store import STORE_PATH_CATALOG from orcapod.databases.utils import in_held_column_order from orcapod.errors import ( InputValidationError, @@ -206,8 +207,7 @@ def test_a_table_created_again_in_another_order_is_read_as_it_is_now( with open_database("SQLite", tmp_path) as db: _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) _add(db, _rows(["c", "a", "b", ID], [2]), flush=True) - with sqlite3.connect(tmp_path / "store.db") as other: - other.execute('DROP TABLE "t"') + _drop_sqlite_store_table(tmp_path / "store.db") other_db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) @@ -227,8 +227,7 @@ def test_rows_queued_before_a_table_is_created_again_are_read_with_it_by_name( with open_database("SQLite", tmp_path) as db: _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) _add(db, _rows(["b", ID, "c", "a"], [2])) # queued as [id, a, c, b] - with sqlite3.connect(tmp_path / "store.db") as other: - other.execute('DROP TABLE "t"') + _drop_sqlite_store_table(tmp_path / "store.db") other_db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) _check( @@ -606,18 +605,23 @@ def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> Non db = ConnectorArrowDatabase(connector) with ( patch.object( - connector, "get_table_names", wraps=connector.get_table_names - ) as names, + connector, + "store_table_transaction", + wraps=connector.store_table_transaction, + ) as registration, + patch.object( + connector, "get_store_table_paths", side_effect=AssertionError("listed") + ), patch.object( connector, "get_column_info", wraps=connector.get_column_info ) as info, ): _add(db, _rows([ID, "a", "c", "b"], [2]), flush=True) - assert (names.call_count, info.call_count) == (1, 1) + assert (registration.call_count, info.call_count) == (1, 1) _add(db, _rows(["b", ID, "c", "a"], [3])) - assert (names.call_count, info.call_count) == (1, 1) + assert (registration.call_count, info.call_count) == (1, 1) db.flush() - assert (names.call_count, info.call_count) == (2, 2) + assert (registration.call_count, info.call_count) == (2, 2) _check( db.get_all_records(PATH, record_id_column=ID), [ID, "a", "c", "b"], [1, 2, 3] ) @@ -639,9 +643,28 @@ def _sqlite(path: Path) -> ConnectorArrowDatabase: return ConnectorArrowDatabase(SQLiteConnector(str(path))) -def _recreate_with_text_a(path: Path) -> None: +def _sqlite_table_name(conn: sqlite3.Connection) -> str: + """Get the physical name of the one registered table in these fixtures.""" + ((table_name,),) = cast( + "list[tuple[str]]", + conn.execute(f'SELECT table_name FROM "{STORE_PATH_CATALOG}"').fetchall(), + ) + return table_name + + +def _drop_sqlite_store_table(path: Path) -> None: + """Drop the table and its registration together.""" with sqlite3.connect(path) as other: - other.execute('DROP TABLE "t"') + name = _sqlite_table_name(other) + _ = other.execute("BEGIN") + _ = other.execute(f'DROP TABLE "{name}"') + _ = other.execute( + f'DELETE FROM "{STORE_PATH_CATALOG}" WHERE table_name = ?', (name,) + ) + + +def _recreate_with_text_a(path: Path) -> None: + _drop_sqlite_store_table(path) _sqlite(path).add_records( PATH, pa.table( @@ -656,10 +679,10 @@ def _recreate_with_text_a(path: Path) -> None: ) -CHANGES: dict[str, Any] = { - "rename": lambda c: c.execute('ALTER TABLE "t" RENAME COLUMN a TO A'), - "add": lambda c: c.execute('ALTER TABLE "t" ADD COLUMN extra INTEGER'), - "drop": lambda c: c.execute('ALTER TABLE "t" DROP COLUMN b'), +CHANGES = { + "rename": "RENAME COLUMN a TO A", + "add": "ADD COLUMN extra INTEGER", + "drop": "DROP COLUMN b", } @@ -680,7 +703,8 @@ def test_a_table_changed_between_queue_and_flush_is_refused_as_on_main( _recreate_with_text_a(path) else: with sqlite3.connect(path) as other: - CHANGES[change](other) + name = _sqlite_table_name(other) + _ = other.execute(f'ALTER TABLE "{name}" {CHANGES[change]}') before = _sqlite(path).get_all_records(PATH, record_id_column="rid") with pytest.raises(ValueError, match="Schema mismatch"): db.flush() @@ -698,8 +722,7 @@ def test_a_table_dropped_and_written_again_by_the_same_handle_takes_the_new_orde path = tmp_path / "store.db" db = _sqlite(path) db.add_records(PATH, _abc(1), record_id_column="rid", flush=True) - with sqlite3.connect(path) as other: - other.execute('DROP TABLE "t"') + _drop_sqlite_store_table(path) db.add_records(PATH, _abc(2, ("b", "rid", "a")), record_id_column="rid", flush=True) table = _sqlite(path).get_all_records(PATH, record_id_column="rid") assert table is not None @@ -723,7 +746,7 @@ def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: second = rows.set_column(0, "rid", pa.array([bytes([2])], pa.large_binary())) db.add_records(PATH, second, record_id_column="rid") with patch.object( - db._connector, "get_table_names", side_effect=AssertionError("listed") + db._connector, "get_store_table_paths", side_effect=AssertionError("listed") ): queued = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") assert queued is not None From b491e1887a3794e74bbd399f2ad6bb67a1141fec Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 18:31:11 -0800 Subject: [PATCH 03/13] fix(postgresql): import SQL composition within connector operations --- src/orcapod/databases/postgresql_connector.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 04ee76b45..12753e59c 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -37,10 +37,8 @@ if TYPE_CHECKING: import psycopg - from psycopg import sql as pg_sql else: psycopg = LazyModule("psycopg") - pg_sql = LazyModule("psycopg.sql") logger = logging.getLogger(__name__) @@ -440,6 +438,8 @@ def get_store_table_paths( self, name: str, *, exact: bool = False ) -> list[tuple[str, str]]: """Return registered record tables matching a physical name or prefix.""" + from psycopg import sql as pg_sql + with ( self._lock, cast( @@ -479,6 +479,8 @@ def store_table_transaction( self, table_name: str, path_json: str ) -> Iterator[bool]: """Register and write a record table, yielding whether it already exists.""" + from psycopg import sql as pg_sql + with self._lock: conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) self._store_transaction_active = True From c1501bf410743567751fce081925b31032cfc826 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 18:48:31 -0800 Subject: [PATCH 04/13] feat(databases): version SQL store catalog entries --- src/orcapod/databases/_sql_store.py | 19 ++++- src/orcapod/databases/postgresql_connector.py | 41 ++++++---- src/orcapod/databases/sqlite_connector.py | 39 +++++++--- tests/test_databases/test_append_by_name.py | 7 +- .../test_postgresql_connector_integration.py | 77 +++++++++++++++++++ .../test_sqlite_connector_integration.py | 30 ++++++++ 6 files changed, 184 insertions(+), 29 deletions(-) diff --git a/src/orcapod/databases/_sql_store.py b/src/orcapod/databases/_sql_store.py index c4f64b7b8..e942f1f96 100644 --- a/src/orcapod/databases/_sql_store.py +++ b/src/orcapod/databases/_sql_store.py @@ -8,9 +8,22 @@ from orcapod.errors import OrcapodDatabaseError -# Quoted as one identifier. The dots keep this versioned layout marker outside -# both the old and the current grammar for record table names. -STORE_PATH_CATALOG = "orcapod.store_paths.v1" +STORE_PATH_LAYOUT_VERSION = 1 +# Quoted as one identifier. The dots keep this name outside the grammar for +# both old and current record table names. +STORE_PATH_CATALOG = f"orcapod.store_paths.v{STORE_PATH_LAYOUT_VERSION}" +TABLE_PATH_ENTRY_KIND = "table" + +# A table entry uses an empty entry_name and holds the path as canonical JSON. +# A future column entry can key its mapping by the physical column name. +STORE_PATH_CATALOG_FIELDS = """( + table_name TEXT NOT NULL, + entry_kind TEXT NOT NULL, + entry_name TEXT NOT NULL, + entry_value TEXT NOT NULL, + layout_version INTEGER NOT NULL CHECK (layout_version = {layout_version}), + PRIMARY KEY (table_name, entry_kind, entry_name) +)""" @runtime_checkable diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 12753e59c..6a78304ef 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -27,6 +27,9 @@ from orcapod.databases._sql_store import ( STORE_PATH_CATALOG, + STORE_PATH_CATALOG_FIELDS, + STORE_PATH_LAYOUT_VERSION, + TABLE_PATH_ENTRY_KIND, catalog_name_pattern, require_catalog_pair, ) @@ -463,14 +466,15 @@ def get_store_table_paths( match = pg_sql.SQL("= %s" if exact else "LIKE %s ESCAPE '!'") _ = cur.execute( pg_sql.SQL(""" - SELECT paths.table_name, paths.path_json + SELECT paths.table_name, paths.entry_value FROM {catalog} AS paths JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name JOIN pg_catalog.pg_namespace AS ns ON ns.oid = physical.relnamespace WHERE ns.nspname = current_schema() AND physical.relkind IN ('r', 'p') AND paths.table_name {match} + AND paths.entry_kind = %s AND paths.entry_name = '' """).format(catalog=catalog, match=match), - (name if exact else catalog_name_pattern(name),), + (name if exact else catalog_name_pattern(name), TABLE_PATH_ENTRY_KIND), ) return cast("list[tuple[str, str]]", cur.fetchall()) @@ -501,17 +505,20 @@ def store_table_transaction( catalog = pg_sql.Identifier( cast(str, location[0]), STORE_PATH_CATALOG ) + fields = pg_sql.SQL(STORE_PATH_CATALOG_FIELDS).format( + layout_version=pg_sql.Literal(STORE_PATH_LAYOUT_VERSION) + ) _ = cur.execute( - pg_sql.SQL(""" - CREATE TABLE IF NOT EXISTS {} - (table_name TEXT NOT NULL PRIMARY KEY, path_json TEXT NOT NULL) - """).format(catalog) + pg_sql.SQL("CREATE TABLE IF NOT EXISTS {} {}").format( + catalog, fields + ) ) _ = cur.execute( - pg_sql.SQL( - "SELECT path_json FROM {} WHERE table_name = %s" - ).format(catalog), - (table_name,), + pg_sql.SQL(""" + SELECT entry_value FROM {} + WHERE table_name = %s AND entry_kind = %s AND entry_name = '' + """).format(catalog), + (table_name, TABLE_PATH_ENTRY_KIND), ) row = cur.fetchone() _ = cur.execute( @@ -535,10 +542,16 @@ def store_table_transaction( ) if row is None: _ = cur.execute( - pg_sql.SQL( - "INSERT INTO {} (table_name, path_json) VALUES (%s, %s)" - ).format(catalog), - (table_name, path_json), + pg_sql.SQL(""" + INSERT INTO {} (table_name, entry_kind, entry_name, entry_value, layout_version) + VALUES (%s, %s, '', %s, %s) + """).format(catalog), + ( + table_name, + TABLE_PATH_ENTRY_KIND, + path_json, + STORE_PATH_LAYOUT_VERSION, + ), ) yield physical is not None conn.commit() diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index 659d00bec..862ba774b 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -26,6 +26,9 @@ from orcapod.databases._sql_store import ( STORE_PATH_CATALOG, + STORE_PATH_CATALOG_FIELDS, + STORE_PATH_LAYOUT_VERSION, + TABLE_PATH_ENTRY_KIND, catalog_name_pattern, require_catalog_pair, ) @@ -312,12 +315,16 @@ def get_store_table_paths( "Iterator[sqlite3.Row]", conn.execute( f""" - SELECT paths.table_name, paths.path_json + SELECT paths.table_name, paths.entry_value FROM main."{STORE_PATH_CATALOG}" AS paths JOIN main.sqlite_schema AS physical ON physical.name = paths.table_name WHERE physical.type = 'table' AND paths.table_name {match} + AND paths.entry_kind = ? AND paths.entry_name = '' """, - (name if exact else catalog_name_pattern(name),), + ( + name if exact else catalog_name_pattern(name), + TABLE_PATH_ENTRY_KIND, + ), ), ) return [(cast(str, row[0]), cast(str, row[1])) for row in rows] @@ -331,17 +338,20 @@ def store_table_transaction( conn = self._require_open() _ = conn.execute("BEGIN IMMEDIATE") try: + fields = STORE_PATH_CATALOG_FIELDS.format( + layout_version=STORE_PATH_LAYOUT_VERSION + ) _ = conn.execute( - f""" - CREATE TABLE IF NOT EXISTS main."{STORE_PATH_CATALOG}" - (table_name TEXT NOT NULL PRIMARY KEY, path_json TEXT NOT NULL) - """ + f'CREATE TABLE IF NOT EXISTS main."{STORE_PATH_CATALOG}" {fields}' ) row = cast( "sqlite3.Row | None", conn.execute( - f'SELECT path_json FROM main."{STORE_PATH_CATALOG}" WHERE table_name = ?', - (table_name,), + f""" + SELECT entry_value FROM main."{STORE_PATH_CATALOG}" + WHERE table_name = ? AND entry_kind = ? AND entry_name = '' + """, + (table_name, TABLE_PATH_ENTRY_KIND), ).fetchone(), ) physical = cast( @@ -363,8 +373,17 @@ def store_table_transaction( ) if row is None: _ = conn.execute( - f'INSERT INTO main."{STORE_PATH_CATALOG}" (table_name, path_json) VALUES (?, ?)', - (table_name, path_json), + f""" + INSERT INTO main."{STORE_PATH_CATALOG}" + (table_name, entry_kind, entry_name, entry_value, layout_version) + VALUES (?, ?, '', ?, ?) + """, + ( + table_name, + TABLE_PATH_ENTRY_KIND, + path_json, + STORE_PATH_LAYOUT_VERSION, + ), ) yield physical is not None conn.commit() diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 16e0a5b8e..9a09f9f66 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -33,7 +33,7 @@ InMemoryArrowDatabase, SQLiteConnector, ) -from orcapod.databases._sql_store import STORE_PATH_CATALOG +from orcapod.databases._sql_store import STORE_PATH_CATALOG, TABLE_PATH_ENTRY_KIND from orcapod.databases.utils import in_held_column_order from orcapod.errors import ( InputValidationError, @@ -647,7 +647,10 @@ def _sqlite_table_name(conn: sqlite3.Connection) -> str: """Get the physical name of the one registered table in these fixtures.""" ((table_name,),) = cast( "list[tuple[str]]", - conn.execute(f'SELECT table_name FROM "{STORE_PATH_CATALOG}"').fetchall(), + conn.execute( + f'SELECT table_name FROM "{STORE_PATH_CATALOG}" WHERE entry_kind = ?', + (TABLE_PATH_ENTRY_KIND,), + ).fetchall(), ) return table_name diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 05439e7e3..e3419d337 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -29,8 +29,10 @@ import psycopg import pyarrow as pa import pytest +from psycopg import sql from orcapod.databases import ConnectorArrowDatabase, PostgreSQLConnector +from orcapod.databases._sql_store import STORE_PATH_CATALOG from orcapod.types import ColumnInfo @@ -649,3 +651,78 @@ def fail_write(*args: object, **kwargs: object) -> None: assert other.list_table_paths() == [] other.add_record(path, b"one", record, flush=True) assert other.list_table_paths() == [path] + + +@pytest.mark.postgres +def test_unknown_catalog_entries_are_ignored(connector: PostgreSQLConnector) -> None: + path = ("job", "pdb_v2") + store = ConnectorArrowDatabase(connector) + store.add_record(path, b"one", pa.table({"value": [1]}), flush=True) + catalog = sql.Identifier(STORE_PATH_CATALOG) + with psycopg.connect(connector._dsn) as conn: + row = conn.execute( + sql.SQL("SELECT layout_version, table_name FROM {}").format(catalog) + ).fetchone() + assert row is not None + version, name = row + assert version == 1 + _ = conn.execute( + sql.SQL(""" + INSERT INTO {} (layout_version, table_name, entry_kind, entry_name, entry_value) + VALUES (%s, %s, 'future', 'short_name', 'an opaque value') + """).format(catalog), + (version, name), + ) + assert store.list_table_paths(("job",)) == [path] + rows = store.get_all_records(path) + assert rows is not None and rows.to_pylist() == [{"value": 1}] + store.add_record(path, b"two", pa.table({"value": [2]}), flush=True) + + +@pytest.mark.postgres +def test_catalog_uses_the_first_schema_on_the_search_path( + connector: PostgreSQLConnector, +) -> None: + _, _, _, primary = connector.current_location() + fallback = f"test_{uuid.uuid4().hex[:12]}" + base_dsn = _base_dsn() + path = ("job", "pdb_v2") + with psycopg.connect(base_dsn, autocommit=True) as admin: + _ = admin.execute(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(fallback))) + try: + with ( + PostgreSQLConnector( + f"{base_dsn} options=-csearch_path={fallback}" + ) as other, + PostgreSQLConnector( + f"{base_dsn} options=-csearch_path={primary},{fallback}" + ) as first, + ): + other_store = ConnectorArrowDatabase(other) + store = ConnectorArrowDatabase(first) + other_store.add_record( + path, b"one", pa.table({"value": [1]}), flush=True + ) + + assert store.list_table_paths() == [] + assert store.get_all_records(path) is None + store.add_record(path, b"one", pa.table({"value": [2]}), flush=True) + + assert len(STORE_PATH_CATALOG.encode("utf-8")) <= 63 + assert STORE_PATH_CATALOG in first.get_table_names() + assert STORE_PATH_CATALOG in other.get_table_names() + assert ( + store.list_table_paths() == other_store.list_table_paths() == [path] + ) + primary_rows = store.get_all_records(path) + fallback_rows = other_store.get_all_records(path) + assert primary_rows is not None and primary_rows.to_pylist() == [ + {"value": 2} + ] + assert fallback_rows is not None and fallback_rows.to_pylist() == [ + {"value": 1} + ] + finally: + _ = admin.execute( + sql.SQL("DROP SCHEMA {} CASCADE").format(sql.Identifier(fallback)) + ) diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index 81a49e985..be70473c7 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -2,12 +2,15 @@ from __future__ import annotations +import sqlite3 from collections.abc import Iterator +from pathlib import Path import pyarrow as pa import pytest from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector +from orcapod.databases._sql_store import STORE_PATH_CATALOG from orcapod.errors import OrcapodDatabaseError from orcapod.types import ColumnInfo @@ -121,6 +124,33 @@ def fail_write(*args: object, **kwargs: object) -> None: db.add_record(("new",), b"one", pa.table({"value": [1]}), flush=True) assert db.list_table_paths() == [("new",)] + def test_unknown_catalog_entries_are_ignored(self, tmp_path: Path) -> None: + location = tmp_path / "store.db" + path = ("job", "pdb_v2") + with SQLiteConnector(location) as connector: + ConnectorArrowDatabase(connector).add_record( + path, b"one", pa.table({"value": [1]}), flush=True + ) + with sqlite3.connect(location) as conn: + row = conn.execute( + f'SELECT layout_version, table_name FROM "{STORE_PATH_CATALOG}"' + ).fetchone() + assert row is not None + version, name = row + assert version == 1 + _ = conn.execute( + f'INSERT INTO "{STORE_PATH_CATALOG}" ' + "(layout_version, table_name, entry_kind, entry_name, entry_value) " + "VALUES (?, ?, 'future', 'short_name', 'an opaque value')", + (version, name), + ) + with SQLiteConnector(location) as connector: + db = ConnectorArrowDatabase(connector) + assert db.list_table_paths(("job",)) == [path] + rows = db.get_all_records(path) + assert rows is not None and rows.to_pylist() == [{"value": 1}] + db.add_record(path, b"two", pa.table({"value": [2]}), flush=True) + def test_add_and_get_record(self, db: ConnectorArrowDatabase) -> None: # add_record stamps all rows with the same __record_id, so within-batch # deduplication keeps only the last row (same behaviour as InMemoryArrowDatabase). From a9abacf8249104149eef68887de22d0c5008820e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:25:00 -0800 Subject: [PATCH 05/13] fix(databases): enforce SQL store catalog ownership --- docs/concepts/pipeline-job.md | 6 +- src/orcapod/databases/_sql_store.py | 52 ++++++- .../databases/connector_arrow_database.py | 128 +++++++++++++----- src/orcapod/databases/postgresql_connector.py | 110 +++++++++------ src/orcapod/databases/sqlite_connector.py | 70 +++++++--- src/orcapod/databases/utils.py | 35 ++++- tests/test_databases/test_append_by_name.py | 25 +++- .../test_postgresql_connector_integration.py | 118 +++++++++++++++- .../test_sqlite_connector_integration.py | 99 +++++++++++++- 9 files changed, 514 insertions(+), 129 deletions(-) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 68672e28c..da53b91ba 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -243,8 +243,10 @@ A non-null column is created `NOT NULL` and reads back non-null. SQLite refuses `double` column holding a NaN or `-0.0`, which it would read back as NULL and `0.0`. Any other type (lists, structs, dates or timestamps on SQLite, narrower integers and floats, logical types) is -refused. PostgreSQL also refuses a column name or a table name longer than -63 bytes, which it would truncate (`UnstorableTableNameError` for a table). A database on +refused. PostgreSQL also refuses column names and explicit table identifiers longer than +63 bytes, which it would truncate (`UnstorableTableNameError` for a table). +SQLite and PostgreSQL stores generate table names within 63 bytes from the node's +path, using a readable hint and a digest of the full path. A database on `SpiralDBConnector` refuses every write for now (`SpiralDBWriteNotSupportedError`): Orcapod reads SpiralDB only. The full list, type by type, is [Data types per database](../reference/database-types.md). diff --git a/src/orcapod/databases/_sql_store.py b/src/orcapod/databases/_sql_store.py index e942f1f96..f5dd682c6 100644 --- a/src/orcapod/databases/_sql_store.py +++ b/src/orcapod/databases/_sql_store.py @@ -4,9 +4,13 @@ import json from contextlib import AbstractContextManager -from typing import Protocol, cast, runtime_checkable +from typing import TYPE_CHECKING, Protocol, cast, runtime_checkable from orcapod.errors import OrcapodDatabaseError +from orcapod.types import ColumnInfo + +if TYPE_CHECKING: + import pyarrow as pa STORE_PATH_LAYOUT_VERSION = 1 # Quoted as one identifier. The dots keep this name outside the grammar for @@ -32,14 +36,43 @@ class SQLStoreConnector(Protocol): def get_store_table_paths( self, name: str, *, exact: bool = False - ) -> list[tuple[str, str]]: - """Return physical names and stored JSON paths for existing record tables.""" + ) -> list[tuple[str, str, str]]: + """Return schema, physical name and stored JSON path for each record table.""" ... def store_table_transaction( self, table_name: str, path_json: str - ) -> AbstractContextManager[bool]: - """Verify or register a path and yield whether its table already exists.""" + ) -> AbstractContextManager[tuple[str, bool]]: + """Verify or register a path and yield its schema and table existence.""" + ... + + def get_column_info( + self, table_name: str, *, schema: str | None = None + ) -> list[ColumnInfo]: + """Inspect the columns of a table in the verified schema.""" + ... + + def create_table_if_not_exists( + self, + table_name: str, + columns: list[ColumnInfo], + pk_column: str, + *, + schema: str | None = None, + ) -> None: + """Create a record table in the verified schema.""" + ... + + def upsert_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool = False, + *, + schema: str | None = None, + ) -> None: + """Write rows to the record table in the verified schema.""" ... @@ -48,6 +81,15 @@ def catalog_name_pattern(name: str) -> str: return name.replace("!", "!!").replace("_", "!_").replace("%", "!%") + "%" +def require_catalog_layout(table_name: str, layout_version: object) -> None: + """Refuse to interpret a table entry in an unsupported catalog layout.""" + if layout_version != STORE_PATH_LAYOUT_VERSION: + raise OrcapodDatabaseError( + f"Table {table_name!r} uses unsupported catalog layout version " + f"{layout_version!r}; this client supports version {STORE_PATH_LAYOUT_VERSION}" + ) + + def stored_path(table_name: str, path_json: str) -> tuple[str, ...]: """Decode the original path, refusing an unreadable catalog entry.""" try: diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6b479b89d..5dde99290 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -44,6 +44,7 @@ first_changed_column, first_logical_identity_change, in_held_column_order, + sql_table_identifier, ) from orcapod.errors import ( InputValidationError, @@ -269,27 +270,37 @@ def _deduplicate_within_table(self, table: pa.Table) -> pa.Table: # ── Committed data access ───────────────────────────────────────────────── - def _has_committed_table(self, table_name: str, full_path: tuple[str, ...]) -> bool: - """Check that this path owns a table in the backend.""" + def _find_committed_table( + self, table_name: str, full_path: tuple[str, ...] + ) -> tuple[str | None, str] | None: + """Return the verified schema and name of a committed table.""" if self._sql_store is None: - return table_name in self._connector.get_table_names() - for _, path_json in self._sql_store.get_store_table_paths( + if table_name in self._connector.get_table_names(): + return None, table_name + return None + for schema, name, path_json in self._sql_store.get_store_table_paths( table_name, exact=True ): require_store_table_owner( table_name, full_path, stored_path(table_name, path_json) ) - return True - return False + return schema, name + return None def _get_committed_table(self, record_path: tuple[str, ...]) -> pa.Table | None: """Fetch all committed records for a path from the connector.""" full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) - if not self._has_committed_table(table_name, full_path): + table = self._find_committed_table(table_name, full_path) + if table is None: return None - batches = list(self._connector.iter_batches(f'SELECT * FROM "{table_name}"')) + schema, name = table + batches = list( + self._connector.iter_batches( + f"SELECT * FROM {sql_table_identifier(name, schema)}" + ) + ) if not batches: return None return pa.Table.from_batches(batches) @@ -312,17 +323,22 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] stem = STORE_TABLE_NAME_PREFIX + table_name_hint( full_prefix, hint_length=_SQL_HINT_LENGTH ) - found_paths = {tuple(key.split("/")) for key in self._pending_batches} - for name, path_json in self._sql_store.get_store_table_paths(stem): + owners: dict[str, tuple[str, ...]] = {} + for _, name, path_json in self._sql_store.get_store_table_paths(stem): path = stored_path(name, path_json) if self._path_to_table_name(path) != name: raise OrcapodDatabaseError( f"Table {name!r} does not match its stored path {path!r}" ) - found_paths.add(path) + owners[name] = path + for key in self._pending_batches: + path = tuple(key.split("/")) + if path[: len(full_prefix)] == full_prefix: + name = self._path_to_table_name(path) + require_store_table_owner(name, path, owners.setdefault(name, path)) return sorted( path[len(self._path_prefix) :] - for path in found_paths + for path in owners.values() if path[: len(full_prefix)] == full_prefix ) @@ -361,7 +377,7 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: record_key = self._get_record_key(record_path) if self._sql_store is None and record_key in self._pending_batches: return True - return self._has_committed_table(table_name, full_path) or ( + return self._find_committed_table(table_name, full_path) is not None or ( record_key in self._pending_batches ) @@ -377,12 +393,14 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) try: - if not self._has_committed_table(table_name, full_path): + table = self._find_committed_table(table_name, full_path) + if table is None: pending = self._pending_batches.get(self._get_record_key(record_path)) return None if pending is None else pending.schema + schema, name = table return pa.schema( pa.field(column.name, column.arrow_type, nullable=column.nullable) - for column in self._connector.get_column_info(table_name) + for column in self._column_info(name, schema) ) except OrcapodDatabaseError: raise @@ -528,6 +546,13 @@ def add_records( self._connector.validate_records(records) record_key = self._get_record_key(record_path) + if self._sql_store is not None: + _ = self._find_committed_table(table_name, full_path) + if record_key not in self._pending_batches: + for key in self._pending_batches: + queued_path = tuple(key.split("/")) + if self._path_to_table_name(queued_path) == table_name: + require_store_table_owner(table_name, full_path, queued_path) # Columns match by name: rows with the held columns in another order are # put in the held order, so the connector always receives the stored order # (ITL-1367). @@ -602,7 +627,15 @@ def _held_column_order( return list(pending.schema) return None - def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]]": + def _column_info(self, table_name: str, schema: str | None) -> list[ColumnInfo]: + """Inspect the relation selected by the catalog when a schema was verified.""" + if self._sql_store is not None: + return self._sql_store.get_column_info(table_name, schema=schema) + return self._connector.get_column_info(table_name) + + def _stored_columns( + self, table_name: str, schema: str | None + ) -> "list[pa.Field[Any]]": """Read the columns of an existing table in its order and large types.""" return [ pa.field( @@ -610,7 +643,7 @@ def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]]": normalize_to_large_types(c.arrow_type, keep_null=True), nullable=c.nullable, ) - for c in self._connector.get_column_info(table_name) + for c in self._column_info(table_name, schema) ] def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: @@ -627,10 +660,13 @@ def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) stored = self._stored_schemas.get(table_name) - if stored is None and self._has_committed_table(table_name, full_path): - stored = self._read_stored_schema(table_name) - if stored is not None: - self._stored_schemas[table_name] = stored + if stored is None: + table = self._find_committed_table(table_name, full_path) + if table is not None: + schema, name = table + stored = self._read_stored_schema(name, schema) + if stored is not None: + self._stored_schemas[table_name] = stored if stored is not None: held.append(stored) return held @@ -671,7 +707,9 @@ def _refuse_changed_columns( f"{changed[0]!r}: {changed[1]}. Nothing was written." ) - def _read_stored_schema(self, table_name: str) -> pa.Schema | None: + def _read_stored_schema( + self, table_name: str, schema: str | None + ) -> pa.Schema | None: """The schema a read of the stored table gives, its field metadata included. Read without rows from a connector that offers ``get_arrow_schema`` @@ -681,7 +719,12 @@ def _read_stored_schema(self, table_name: str) -> pa.Schema | None: if callable(get_arrow_schema): return cast("pa.Schema", get_arrow_schema(table_name)) first = next( - iter(self._connector.iter_batches(f'SELECT * FROM "{table_name}"')), None + iter( + self._connector.iter_batches( + f"SELECT * FROM {sql_table_identifier(table_name, schema)}" + ) + ), + None, ) return None if first is None else first.schema @@ -796,15 +839,15 @@ def _flush_by_key(self, record_key: str) -> None: try: self._require_table_name(table_name) transaction = ( - nullcontext(table_name in self._connector.get_table_names()) + nullcontext((None, table_name in self._connector.get_table_names())) if self._sql_store is None else self._sql_store.store_table_transaction( table_name, store_table_path_json(record_path).decode() ) ) - with transaction as table_exists: + with transaction as (schema, table_exists): self._write_ready_batch( - record_key, table_name, pending, skip_existing, table_exists + record_key, table_name, pending, skip_existing, table_exists, schema ) except BaseException: self._pending_commits.finish(record_key, committed=False) @@ -821,11 +864,12 @@ def _write_ready_batch( pending: pa.Table, skip_existing: bool, table_exists: bool, + schema: str | None, ) -> None: """Check the current schema and write the ready rows.""" columns = _arrow_schema_to_column_infos(pending.schema) # Look up the held schema inside the write transaction (ITL-1367). - existing = self._stored_columns(table_name) if table_exists else None + existing = self._stored_columns(table_name, schema) if table_exists else None check = self._pending_commits.schema_check(record_key) if check is not None: check(pending.schema if existing is None else pa.schema(existing)) @@ -854,15 +898,27 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: ) pending = in_held_column_order(pending, existing) - self._connector.create_table_if_not_exists( - table_name, columns, pk_column=self.RECORD_ID_COLUMN - ) - self._connector.upsert_records( - table_name, - pending, - id_column=self.RECORD_ID_COLUMN, - skip_existing=skip_existing, - ) + if self._sql_store is None: + self._connector.create_table_if_not_exists( + table_name, columns, pk_column=self.RECORD_ID_COLUMN + ) + self._connector.upsert_records( + table_name, + pending, + id_column=self.RECORD_ID_COLUMN, + skip_existing=skip_existing, + ) + else: + self._sql_store.create_table_if_not_exists( + table_name, columns, pk_column=self.RECORD_ID_COLUMN, schema=schema + ) + self._sql_store.upsert_records( + table_name, + pending, + id_column=self.RECORD_ID_COLUMN, + skip_existing=skip_existing, + schema=schema, + ) # ── Read methods ────────────────────────────────────────────────────────── diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 6a78304ef..e1c8d9a95 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -31,9 +31,16 @@ STORE_PATH_LAYOUT_VERSION, TABLE_PATH_ENTRY_KIND, catalog_name_pattern, + require_catalog_layout, require_catalog_pair, ) -from orcapod.databases.utils import is_direct_projection +from orcapod.databases.utils import ( + SQL_FROM_TABLE, + is_direct_projection, + match_direct_projection, + sql_table_identifier, + unquote_sql_identifier, +) from orcapod.errors import OrcapodDatabaseError, UnstorableTableNameError from orcapod.types import ColumnInfo from orcapod.utils.lazy_module import LazyModule @@ -290,22 +297,16 @@ def _resolve_column_type_lookup( # tables, multiple FROM clauses, subqueries, etc.) return {} so callers # fall back to treating all columns as pa.large_string(). - # Fast path: any JOIN keyword means multi-table. - if re.search(r"\bJOIN\b", query, re.IGNORECASE): - return {} - - # Find all FROM occurrences. We only proceed when there is - # exactly one (multiple FROMs indicate subqueries or CTEs). - from_pattern = re.compile( - r'\bFROM\b\s+(?:"([^"]+)"|(\w+))', - re.IGNORECASE, - ) - from_matches = list(from_pattern.finditer(query)) - if len(from_matches) != 1: - return {} - - match = from_matches[0] - table_name = match.group(1) or match.group(2) + match = match_direct_projection(query) + if match is None: + if re.search(r"\bJOIN\b", query, re.IGNORECASE): + return {} + # A non-projection is ambiguous if it has several FROM clauses. + from_matches = list(SQL_FROM_TABLE.finditer(query)) + if len(from_matches) != 1: + return {} + match = from_matches[0] + table_name = unquote_sql_identifier(match["table"]) # Inspect the text after the table name up to the next major SQL clause. # A comma before the clause boundary means comma-joined tables ("FROM a, b"). @@ -321,7 +322,15 @@ def _resolve_column_type_lookup( if "," in from_tail: return {} - return {ci.name: ci for ci in connector.get_column_info(table_name)} + namespace = match["schema"] + columns = ( + connector.get_column_info(table_name) + if namespace is None + else connector.get_column_info( + table_name, schema=unquote_sql_identifier(namespace) + ) + ) + return {ci.name: ci for ci in columns} def _field_has_metadata(field: pa.Field) -> bool: @@ -439,7 +448,7 @@ def get_table_names(self) -> list[str]: def get_store_table_paths( self, name: str, *, exact: bool = False - ) -> list[tuple[str, str]]: + ) -> list[tuple[str, str, str]]: """Return registered record tables matching a physical name or prefix.""" from psycopg import sql as pg_sql @@ -451,7 +460,7 @@ def get_store_table_paths( ): _ = cur.execute( """ - SELECT ns.nspname + SELECT ns.nspname, ns.oid FROM pg_catalog.pg_namespace AS ns JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid WHERE ns.nspname = current_schema() AND rel.relname = %s @@ -462,26 +471,38 @@ def get_store_table_paths( row = cur.fetchone() if row is None: return [] - catalog = pg_sql.Identifier(cast(str, row[0]), STORE_PATH_CATALOG) + schema = cast(str, row[0]) + catalog = pg_sql.Identifier(schema, STORE_PATH_CATALOG) match = pg_sql.SQL("= %s" if exact else "LIKE %s ESCAPE '!'") _ = cur.execute( pg_sql.SQL(""" - SELECT paths.table_name, paths.entry_value + SELECT paths.table_name, paths.entry_value, paths.layout_version, + physical.oid IS NOT NULL FROM {catalog} AS paths - JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name - JOIN pg_catalog.pg_namespace AS ns ON ns.oid = physical.relnamespace - WHERE ns.nspname = current_schema() - AND physical.relkind IN ('r', 'p') AND paths.table_name {match} + LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name + AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') + WHERE paths.table_name {match} AND paths.entry_kind = %s AND paths.entry_name = '' """).format(catalog=catalog, match=match), - (name if exact else catalog_name_pattern(name), TABLE_PATH_ENTRY_KIND), + ( + row[1], + name if exact else catalog_name_pattern(name), + TABLE_PATH_ENTRY_KIND, + ), ) - return cast("list[tuple[str, str]]", cur.fetchall()) + paths: list[tuple[str, str, str]] = [] + for table_name, path_json, version, exists in cast( + "list[tuple[str, str, int, bool]]", cur.fetchall() + ): + require_catalog_layout(table_name, version) + if exists: + paths.append((schema, table_name, path_json)) + return paths @contextmanager def store_table_transaction( self, table_name: str, path_json: str - ) -> Iterator[bool]: + ) -> Iterator[tuple[str, bool]]: """Register and write a record table, yielding whether it already exists.""" from psycopg import sql as pg_sql @@ -502,9 +523,8 @@ def store_table_transaction( location = cur.fetchone() if location is None or location[0] is None: raise OrcapodDatabaseError("PostgreSQL has no current schema") - catalog = pg_sql.Identifier( - cast(str, location[0]), STORE_PATH_CATALOG - ) + schema = cast(str, location[0]) + catalog = pg_sql.Identifier(schema, STORE_PATH_CATALOG) fields = pg_sql.SQL(STORE_PATH_CATALOG_FIELDS).format( layout_version=pg_sql.Literal(STORE_PATH_LAYOUT_VERSION) ) @@ -515,19 +535,21 @@ def store_table_transaction( ) _ = cur.execute( pg_sql.SQL(""" - SELECT entry_value FROM {} + SELECT entry_value, layout_version FROM {} WHERE table_name = %s AND entry_kind = %s AND entry_name = '' """).format(catalog), (table_name, TABLE_PATH_ENTRY_KIND), ) row = cur.fetchone() + if row is not None: + require_catalog_layout(table_name, row[1]) _ = cur.execute( """ SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace - WHERE ns.nspname = current_schema() AND rel.relname = %s + WHERE ns.nspname = %s AND rel.relname = %s """, - (table_name,), + (schema, table_name), ) physical = cur.fetchone() if physical is not None and physical[0] not in ("r", "p"): @@ -553,7 +575,7 @@ def store_table_transaction( STORE_PATH_LAYOUT_VERSION, ), ) - yield physical is not None + yield schema, physical is not None conn.commit() except BaseException: conn.rollback() @@ -662,7 +684,9 @@ def get_pk_columns(self, table_name: str) -> list[str]: ) return [row[0] for row in cur.fetchall()] - def get_column_info(self, table_name: str) -> list[ColumnInfo]: + def get_column_info( + self, table_name: str, *, schema: str | None = None + ) -> list[ColumnInfo]: """Return column metadata with Arrow-mapped types.""" self._require_table_name(table_name) with self._lock: @@ -673,11 +697,11 @@ def get_column_info(self, table_name: str) -> list[ColumnInfo]: """ SELECT column_name, data_type, udt_name, is_nullable FROM information_schema.columns - WHERE table_schema = current_schema() + WHERE table_schema = COALESCE(%s, current_schema()) AND table_name = %s ORDER BY ordinal_position """, - (table_name,), + (schema, table_name), ) return [ ColumnInfo( @@ -765,6 +789,8 @@ def create_table_if_not_exists( table_name: str, columns: list[ColumnInfo], pk_column: str, + *, + schema: str | None = None, ) -> None: """Create a table with the given columns if it does not already exist.""" self._require_table_name(table_name) @@ -783,7 +809,7 @@ def create_table_if_not_exists( pk = " PRIMARY KEY" if col.name == pk_column else "" escaped = col.name.replace('"', '""') col_defs.append(f' "{escaped}" {pg_type}{not_null}{pk}') - ddl = f'CREATE TABLE IF NOT EXISTS "{table_name}" (\n' + ddl = f"CREATE TABLE IF NOT EXISTS {sql_table_identifier(table_name, schema)} (\n" ddl += ",\n".join(col_defs) ddl += "\n)" try: @@ -802,6 +828,8 @@ def upsert_records( records: pa.Table, id_column: str, skip_existing: bool = False, + *, + schema: str | None = None, ) -> None: """Write records to a table using upsert semantics.""" self._require_table_name(table_name) @@ -830,7 +858,7 @@ def upsert_records( conflict_clause = f'ON CONFLICT ("{escaped_id}") DO NOTHING' sql = ( - f'INSERT INTO "{table_name}" ({col_list}) VALUES ({placeholders}) ' + f"INSERT INTO {sql_table_identifier(table_name, schema)} ({col_list}) VALUES ({placeholders}) " f"{conflict_clause}" ) rows_iter = (tuple(row[c] for c in cols) for row in records.to_pylist()) diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index 862ba774b..4481a07f0 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -30,9 +30,15 @@ STORE_PATH_LAYOUT_VERSION, TABLE_PATH_ENTRY_KIND, catalog_name_pattern, + require_catalog_layout, require_catalog_pair, ) -from orcapod.databases.utils import is_direct_projection +from orcapod.databases.utils import ( + SQL_FROM_TABLE, + is_direct_projection, + sql_table_identifier, + unquote_sql_identifier, +) from orcapod.errors import OrcapodDatabaseError from orcapod.types import ColumnInfo @@ -298,7 +304,7 @@ def get_table_names(self) -> list[str]: def get_store_table_paths( self, name: str, *, exact: bool = False - ) -> list[tuple[str, str]]: + ) -> list[tuple[str, str, str]]: """Return registered record tables matching a physical name or prefix.""" with self._lock: conn = self._require_open() @@ -315,10 +321,12 @@ def get_store_table_paths( "Iterator[sqlite3.Row]", conn.execute( f""" - SELECT paths.table_name, paths.entry_value + SELECT paths.table_name, paths.entry_value, paths.layout_version, + physical.name IS NOT NULL FROM main."{STORE_PATH_CATALOG}" AS paths - JOIN main.sqlite_schema AS physical ON physical.name = paths.table_name - WHERE physical.type = 'table' AND paths.table_name {match} + LEFT JOIN main.sqlite_schema AS physical + ON physical.name = paths.table_name AND physical.type = 'table' + WHERE paths.table_name {match} AND paths.entry_kind = ? AND paths.entry_name = '' """, ( @@ -327,12 +335,18 @@ def get_store_table_paths( ), ), ) - return [(cast(str, row[0]), cast(str, row[1])) for row in rows] + paths: list[tuple[str, str, str]] = [] + for row in rows: + table_name = cast(str, row[0]) + require_catalog_layout(table_name, cast(object, row[2])) + if row[3]: + paths.append(("main", table_name, cast(str, row[1]))) + return paths @contextmanager def store_table_transaction( self, table_name: str, path_json: str - ) -> Iterator[bool]: + ) -> Iterator[tuple[str, bool]]: """Register and write a record table, yielding whether it already exists.""" with self._lock: conn = self._require_open() @@ -348,12 +362,14 @@ def store_table_transaction( "sqlite3.Row | None", conn.execute( f""" - SELECT entry_value FROM main."{STORE_PATH_CATALOG}" + SELECT entry_value, layout_version FROM main."{STORE_PATH_CATALOG}" WHERE table_name = ? AND entry_kind = ? AND entry_name = '' """, (table_name, TABLE_PATH_ENTRY_KIND), ).fetchone(), ) + if row is not None: + require_catalog_layout(table_name, cast(object, row[1])) physical = cast( "sqlite3.Row | None", conn.execute( @@ -385,7 +401,7 @@ def store_table_transaction( STORE_PATH_LAYOUT_VERSION, ), ) - yield physical is not None + yield "main", physical is not None conn.commit() except BaseException: conn.rollback() @@ -407,11 +423,14 @@ def get_pk_columns(self, table_name: str) -> list[str]: rows = [row for row in cursor if row["pk"] > 0] return [row["name"] for row in sorted(rows, key=lambda r: r["pk"])] - def get_column_info(self, table_name: str) -> list[ColumnInfo]: + def get_column_info( + self, table_name: str, *, schema: str | None = None + ) -> list[ColumnInfo]: """Return column metadata with Arrow-mapped types. Args: table_name: Name of the table to introspect. + schema: The verified schema when called by a connector store. Returns: List of ColumnInfo objects; empty list if table doesn't exist. @@ -419,7 +438,8 @@ def get_column_info(self, table_name: str) -> list[ColumnInfo]: with self._lock: conn = self._require_open() self._validate_table_name(table_name) - cursor = conn.execute(f'PRAGMA table_info("{table_name}")') + namespace = "" if schema is None else sql_table_identifier(schema) + "." + cursor = conn.execute(f'PRAGMA {namespace}table_info("{table_name}")') return [ ColumnInfo( name=row["name"], @@ -454,8 +474,6 @@ def iter_batches( Yields: Arrow RecordBatch objects. """ - import re as _re - import pyarrow as _pa # Execute the query and resolve the schema under the lock, then fetch @@ -477,15 +495,21 @@ def iter_batches( # A column created NOT NULL reads back non-null (ITL-1276): the stored # flag, not the type alone, makes the field. nullable_lookup: dict[str, bool] = {} - table_match = _re.search(r'FROM\s+"([^"]+)"', query, _re.IGNORECASE) - if not table_match: - table_match = _re.search(r"FROM\s+(\w+)", query, _re.IGNORECASE) + table_match = SQL_FROM_TABLE.search(query) if table_match: - queried_table = table_match.group(1) + queried_table = unquote_sql_identifier(table_match["table"]) + namespace = table_match["schema"] + column_info = ( + self.get_column_info(queried_table) + if namespace is None + else self.get_column_info( + queried_table, schema=unquote_sql_identifier(namespace) + ) + ) # The stored NOT NULL holds for a column only as a direct projection # of its table (an outer join can give it nulls). direct = is_direct_projection(query) - for ci in self.get_column_info(queried_table): + for ci in column_info: type_lookup[ci.name] = ci.arrow_type nullable_lookup[ci.name] = ci.nullable or not direct @@ -527,6 +551,8 @@ def create_table_if_not_exists( table_name: str, columns: list[ColumnInfo], pk_column: str, + *, + schema: str | None = None, ) -> None: """Create a table with the given columns if it does not already exist. @@ -534,6 +560,7 @@ def create_table_if_not_exists( table_name: Table to create. columns: Column definitions with Arrow-mapped types. pk_column: Name of the column to use as the primary key. + schema: The verified schema when called by a connector store. """ col_names = [col.name for col in columns] if pk_column not in col_names: @@ -550,7 +577,7 @@ def create_table_if_not_exists( pk = " PRIMARY KEY" if col.name == pk_column else "" escaped = col.name.replace('"', '""') col_defs.append(f' "{escaped}" {sql_type}{not_null}{pk}') - ddl = f'CREATE TABLE IF NOT EXISTS "{table_name}" (\n' + ddl = f"CREATE TABLE IF NOT EXISTS {sql_table_identifier(table_name, schema)} (\n" ddl += ",\n".join(col_defs) ddl += "\n)" conn.execute(ddl) @@ -561,6 +588,8 @@ def upsert_records( records: pa.Table, id_column: str, skip_existing: bool = False, + *, + schema: str | None = None, ) -> None: """Write records to a table using upsert semantics. @@ -572,6 +601,7 @@ def upsert_records( this argument is accepted for protocol compliance. skip_existing: If True, skip rows whose id already exists (INSERT OR IGNORE). If False, overwrite (INSERT OR REPLACE). + schema: The verified schema when called by a connector store. """ with self._lock: conn = self._require_open() @@ -580,7 +610,7 @@ def upsert_records( col_list = ", ".join('"' + c.replace('"', '""') + '"' for c in cols) placeholders = ", ".join("?" for _ in cols) verb = "INSERT OR IGNORE" if skip_existing else "INSERT OR REPLACE" - sql = f'{verb} INTO "{table_name}" ({col_list}) VALUES ({placeholders})' + sql = f"{verb} INTO {sql_table_identifier(table_name, schema)} ({col_list}) VALUES ({placeholders})" rows = (tuple(row[c] for c in cols) for row in records.to_pylist()) conn.executemany(sql, rows) diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 789f1b076..1bb640db2 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -65,10 +65,12 @@ def as_table_committing(database: object) -> TableCommittingDatabaseProtocol | N return cast("TableCommittingDatabaseProtocol", database) -_IDENTIFIER = r'(?:"[^"]+"|\w+)' +_IDENTIFIER = r'(?:"(?:[^"]|"")+"|\w+)' +_RELATION = rf"(?:(?P{_IDENTIFIER})\s*\.\s*)?(?P
{_IDENTIFIER})" +SQL_FROM_TABLE = re.compile(rf"\bFROM\s+{_RELATION}", re.IGNORECASE) _DIRECT_PROJECTION = re.compile( rf"^\s*SELECT\s+(?:\*|{_IDENTIFIER}(?:\s*,\s*{_IDENTIFIER})*)\s+" - rf"FROM\s+{_IDENTIFIER}\s*(?P.*?)\s*;?\s*$", + rf"FROM\s+{_RELATION}\s*(?P.*?)\s*;?\s*$", re.IGNORECASE | re.DOTALL, ) # After the table: nothing, or a clause that only chooses or orders rows. @@ -78,6 +80,29 @@ def as_table_committing(database: object) -> TableCommittingDatabaseProtocol | N ) +def sql_table_identifier(table: str, schema: str | None = None) -> str: + """Quote a table identifier and, if provided, its separate schema identifier.""" + parts = (table,) if schema is None else (schema, table) + return ".".join('"' + part.replace('"', '""') + '"' for part in parts) + + +def unquote_sql_identifier(identifier: str) -> str: + """Decode one identifier read by the SQL relation pattern.""" + if identifier.startswith('"'): + return identifier[1:-1].replace('""', '"') + return identifier + + +def match_direct_projection(query: str) -> re.Match[str] | None: + """Match a direct projection and identify its source relation.""" + match = _DIRECT_PROJECTION.match(query) + if match is not None: + rest = match["rest"] + if _ROW_CLAUSE.match(rest) is not None and _NOT_DIRECT.search(rest) is None: + return match + return None + + def is_direct_projection(query: str) -> bool: """Whether ``query`` gives rows of one table's columns unchanged (ITL-1334). @@ -93,11 +118,7 @@ def is_direct_projection(query: str) -> bool: Returns: Whether every result column is a stored column as it is stored. """ - match = _DIRECT_PROJECTION.match(query) - if match is None: - return False - rest = match.group("rest") - return _ROW_CLAUSE.match(rest) is not None and _NOT_DIRECT.search(rest) is None + return match_direct_projection(query) is not None def metadata_bytes(metadata: Mapping[Any, Any] | None) -> dict[bytes, bytes]: diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 9a09f9f66..c20d8dbfb 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -595,8 +595,7 @@ def test_an_all_duplicate_append_looks_up_no_order(tmp_path: Path) -> None: def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> None: - """The connector database looks a table up once per flushed append, at the - flush, as main does: an append looks nothing up when it is queued.""" + """Check ownership before queuing and inspect the current schema once per flush.""" path = str(tmp_path / "store.db") ConnectorArrowDatabase(SQLiteConnector(path)).add_records( PATH, _rows([ID, "a", "c", "b"], [1]), record_id_column=ID, flush=True @@ -610,18 +609,30 @@ def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> Non wraps=connector.store_table_transaction, ) as registration, patch.object( - connector, "get_store_table_paths", side_effect=AssertionError("listed") - ), + connector, "get_store_table_paths", wraps=connector.get_store_table_paths + ) as catalog, patch.object( connector, "get_column_info", wraps=connector.get_column_info ) as info, ): _add(db, _rows([ID, "a", "c", "b"], [2]), flush=True) - assert (registration.call_count, info.call_count) == (1, 1) + assert (catalog.call_count, registration.call_count, info.call_count) == ( + 1, + 1, + 1, + ) _add(db, _rows(["b", ID, "c", "a"], [3])) - assert (registration.call_count, info.call_count) == (1, 1) + assert (catalog.call_count, registration.call_count, info.call_count) == ( + 2, + 1, + 1, + ) db.flush() - assert (registration.call_count, info.call_count) == (2, 2) + assert (catalog.call_count, registration.call_count, info.call_count) == ( + 2, + 2, + 2, + ) _check( db.get_all_records(PATH, record_id_column=ID), [ID, "a", "c", "b"], [1, 2, 3] ) diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index e3419d337..7ef356707 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -33,7 +33,12 @@ from orcapod.databases import ConnectorArrowDatabase, PostgreSQLConnector from orcapod.databases._sql_store import STORE_PATH_CATALOG +from orcapod.errors import OrcapodDatabaseError from orcapod.types import ColumnInfo +from tests.test_databases.test_sqlite_connector_integration import ( + _check_catalog_operation, + _check_pending_collision, +) # --------------------------------------------------------------------------- @@ -684,20 +689,24 @@ def test_catalog_uses_the_first_schema_on_the_search_path( connector: PostgreSQLConnector, ) -> None: _, _, _, primary = connector.current_location() - fallback = f"test_{uuid.uuid4().hex[:12]}" + fallback = f'JOIN."{uuid.uuid4().hex[:12]}' base_dsn = _base_dsn() path = ("job", "pdb_v2") with psycopg.connect(base_dsn, autocommit=True) as admin: _ = admin.execute(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(fallback))) try: with ( - PostgreSQLConnector( - f"{base_dsn} options=-csearch_path={fallback}" - ) as other, - PostgreSQLConnector( - f"{base_dsn} options=-csearch_path={primary},{fallback}" - ) as first, + PostgreSQLConnector(base_dsn) as other, + PostgreSQLConnector(base_dsn) as first, ): + _ = other._require_open().execute( + sql.SQL("SET search_path TO {}").format(sql.Identifier(fallback)) + ) + _ = first._require_open().execute( + sql.SQL("SET search_path TO {}, {}").format( + sql.Identifier(primary), sql.Identifier(fallback) + ) + ) other_store = ConnectorArrowDatabase(other) store = ConnectorArrowDatabase(first) other_store.add_record( @@ -722,7 +731,102 @@ def test_catalog_uses_the_first_schema_on_the_search_path( assert fallback_rows is not None and fallback_rows.to_pylist() == [ {"value": 1} ] + _ = first._require_open().execute( + sql.SQL("SET search_path TO {}").format(sql.Identifier(fallback)) + ) + switched_rows = store.get_all_records(path) + assert switched_rows is not None and switched_rows.equals(fallback_rows) finally: _ = admin.execute( sql.SQL("DROP SCHEMA {} CASCADE").format(sql.Identifier(fallback)) ) + + +@pytest.mark.postgres +@pytest.mark.parametrize("operation", ["list", "read", "queue", "flush"]) +def test_unsupported_catalog_layout_is_refused( + connector: PostgreSQLConnector, operation: str +) -> None: + db = ConnectorArrowDatabase(connector) + path = ("versioned",) + one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) + db.add_record(path, b"id", one, flush=True) + if operation == "flush": + db.add_record(path, b"id", two) + connector._require_open().commit() + catalog = sql.Identifier(STORE_PATH_CATALOG) + with psycopg.connect(connector._dsn) as conn: + _ = conn.execute( + sql.SQL("ALTER TABLE {} DROP CONSTRAINT {}").format( + catalog, sql.Identifier(f"{STORE_PATH_CATALOG}_layout_version_check") + ) + ) + _ = conn.execute(sql.SQL("UPDATE {} SET layout_version = 2").format(catalog)) + with pytest.raises( + OrcapodDatabaseError, match="unsupported catalog layout version 2" + ): + _check_catalog_operation(db, path, two, operation) + name = next(n for n in connector.get_table_names() if n.startswith("o1_")) + with psycopg.connect(connector._dsn) as conn: + assert conn.execute( + sql.SQL("SELECT value FROM {}").format(sql.Identifier(name)) + ).fetchone() == (1,) + + +@pytest.mark.postgres +def test_store_writes_to_the_verified_schema_when_a_temp_table_shadows_its_name( + connector: PostgreSQLConnector, +) -> None: + db = ConnectorArrowDatabase(connector) + path = ("shadow",) + db.add_record(path, b"id", pa.table({"value": [1]}), flush=True) + name = next(n for n in connector.get_table_names() if n.startswith("o1_")) + conn = connector._require_open() + _ = conn.execute( + sql.SQL( + 'CREATE TEMP TABLE {} ("__record_id" BYTEA PRIMARY KEY, value BIGINT)' + ).format(sql.Identifier(name)) + ) + temp = sql.Identifier("pg_temp", name) + _ = conn.execute( + sql.SQL("INSERT INTO {} VALUES (%s, %s)").format(temp), (b"id", 99) + ) + db.add_record(path, b"id", pa.table({"value": [2]}), flush=True) + assert conn.execute(sql.SQL("SELECT value FROM {}").format(temp)).fetchone() == ( + 99, + ) + rows = db.get_all_records(path) + assert rows is not None and rows.to_pylist() == [{"value": 2}] + + +@pytest.mark.postgres +def test_pending_path_is_refused_if_another_writer_claims_name( + connector: PostgreSQLConnector, monkeypatch: pytest.MonkeyPatch +) -> None: + from orcapod.databases import store_table_names + + monkeypatch.setattr(store_table_names, "store_table_digest", lambda path: "a" * 64) + with PostgreSQLConnector(connector._dsn) as other: + _check_pending_collision(connector, other) + + +@pytest.mark.postgres +def test_paths_with_a_forced_digest_collision_cannot_share_a_table( + connector: PostgreSQLConnector, monkeypatch: pytest.MonkeyPatch +) -> None: + from orcapod.databases import store_table_names + + monkeypatch.setattr(store_table_names, "store_table_digest", lambda path: "a" * 64) + db = ConnectorArrowDatabase(connector) + committed, colliding = ("name-part",), ("name:part",) + one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) + db.add_record(committed, b"id", one) + with pytest.raises(OrcapodDatabaseError, match="name-part.*name:part"): + db.add_record(colliding, b"id", two) + db.flush_batch(committed) + with pytest.raises(OrcapodDatabaseError, match="name-part.*name:part"): + db.add_record(colliding, b"id", two) + with pytest.raises(OrcapodDatabaseError, match="name-part.*name:part"): + db.get_all_records(colliding) + rows = db.get_all_records(committed) + assert rows is not None and rows.equals(one) diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index be70473c7..e1193e1bb 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -12,6 +12,7 @@ from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector from orcapod.databases._sql_store import STORE_PATH_CATALOG from orcapod.errors import OrcapodDatabaseError +from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.types import ColumnInfo @@ -48,19 +49,80 @@ def test_paths_with_a_forced_digest_collision_cannot_share_a_table( ) first = ("name:part",) second = ("name-part",) - db.add_record(second, b"one", pa.table({"value": [2]})) db.add_record(first, b"one", pa.table({"value": [1]})) + with pytest.raises(OrcapodDatabaseError, match="already belongs"): + db.add_record(second, b"one", pa.table({"value": [2]})) db.flush_batch(first) with pytest.raises(OrcapodDatabaseError, match="already belongs"): db.get_all_records(second) with pytest.raises(OrcapodDatabaseError, match="already belongs"): - db.flush_batch(second) - with pytest.raises(OrcapodDatabaseError, match="already belongs"): - db.add_record(second, b"one", pa.table({"value": [2]}), flush=True) + db.add_record(second, b"one", pa.table({"value": [2]})) assert db.list_table_paths() == [first] records = db.get_all_records(first) assert records is not None and records.to_pylist() == [{"value": 1}] + def test_pending_path_is_refused_if_another_writer_claims_name( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + from orcapod.databases import store_table_names + + monkeypatch.setattr( + store_table_names, "store_table_digest", lambda path: "a" * 64 + ) + location = tmp_path / "store.db" + with SQLiteConnector(location) as first, SQLiteConnector(location) as second: + _check_pending_collision(first, second) + + @pytest.mark.parametrize("operation", ["list", "read", "queue", "flush"]) + def test_unsupported_catalog_layout_is_refused(self, operation: str) -> None: + path = ("versioned",) + one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) + with SQLiteConnector() as connector: + db = ConnectorArrowDatabase(connector) + db.add_record(path, b"id", one, flush=True) + if operation == "flush": + db.add_record(path, b"id", two) + conn = connector._require_open() + _ = conn.execute("PRAGMA ignore_check_constraints=ON") + _ = conn.execute( + f'UPDATE main."{STORE_PATH_CATALOG}" SET layout_version = 2' + ) + with pytest.raises( + OrcapodDatabaseError, match="unsupported catalog layout version 2" + ): + _check_catalog_operation(db, path, two, operation) + name = next(n for n in connector.get_table_names() if n.startswith("o1_")) + assert tuple( + conn.execute(f'SELECT value FROM main."{name}"').fetchone() + ) == (1,) + + @pytest.mark.parametrize("write", [False, True]) + def test_store_uses_main_when_a_temp_table_shadows_its_name( + self, write: bool + ) -> None: + path = ("shadow",) + one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) + with SQLiteConnector() as connector: + store = ConnectorArrowDatabase(connector) + store.add_record(path, b"id", one, flush=True) + name = next(n for n in connector.get_table_names() if n.startswith("o1_")) + conn = connector._require_open() + _ = conn.execute( + f'CREATE TEMP TABLE "{name}" ("__record_id" BLOB PRIMARY KEY, value INTEGER)' + ) + _ = conn.execute(f'INSERT INTO temp."{name}" VALUES (?, ?)', (b"id", 99)) + if write: + store.add_record(path, b"id", two, flush=True) + assert tuple( + conn.execute(f'SELECT value FROM main."{name}"').fetchone() + ) == (2,) + assert tuple( + conn.execute(f'SELECT value FROM temp."{name}"').fetchone() + ) == (99,) + else: + records = store.get_all_records(path) + assert records is not None and records.equals(one) + def test_legacy_table_is_ignored_and_preserved(self) -> None: with SQLiteConnector(":memory:") as connector: columns = [ @@ -248,3 +310,32 @@ def test_get_records_by_ids(self, db: ConnectorArrowDatabase) -> None: result = db.get_records_by_ids(("fn", "test"), ["r1", "r3"]) assert result is not None assert result.num_rows == 2 + + +def _check_pending_collision( + first: DBConnectorProtocol, second: DBConnectorProtocol +) -> None: + queued = ConnectorArrowDatabase(first) + winner = ConnectorArrowDatabase(second) + pending, committed = ("name:part",), ("name-part",) + one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) + queued.add_record(pending, b"id", two) + winner.add_record(committed, b"id", one, flush=True) + for check in (queued.list_table_paths, lambda: queued.flush_batch(pending)): + with pytest.raises(OrcapodDatabaseError, match="name-part.*name:part"): + check() + rows = winner.get_all_records(committed) + assert rows is not None and rows.equals(one) + + +def _check_catalog_operation( + db: ConnectorArrowDatabase, path: tuple[str, ...], table: pa.Table, operation: str +) -> None: + if operation == "list": + db.list_table_paths() + elif operation == "read": + db.get_all_records(path) + elif operation == "queue": + db.add_record(path, b"id", table) + else: + db.flush_batch(path) From 973409255877646a574b712eb61f65e0154f2964 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:28:03 -0800 Subject: [PATCH 06/13] fix(postgresql): escape schema qualifiers in bound store queries --- src/orcapod/databases/connector_arrow_database.py | 2 +- src/orcapod/databases/postgresql_connector.py | 12 ++++++++++-- .../test_postgresql_connector_integration.py | 2 +- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 5dde99290..fd38547d6 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -138,7 +138,7 @@ def __init__( _scoped_path: tuple[str, ...] = (), ) -> None: self._connector = connector - self._sql_store = ( + self._sql_store: SQLStoreConnector | None = ( connector if isinstance(connector, SQLStoreConnector) else None ) self.max_hierarchy_depth = max_hierarchy_depth diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index e1c8d9a95..f9727c8ad 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -472,7 +472,9 @@ def get_store_table_paths( if row is None: return [] schema = cast(str, row[0]) - catalog = pg_sql.Identifier(schema, STORE_PATH_CATALOG) + # Psycopg scans percent signs even inside quoted identifiers when + # the statement also has bound parameters. + catalog = pg_sql.Identifier(schema.replace("%", "%%"), STORE_PATH_CATALOG) match = pg_sql.SQL("= %s" if exact else "LIKE %s ESCAPE '!'") _ = cur.execute( pg_sql.SQL(""" @@ -533,6 +535,9 @@ def store_table_transaction( catalog, fields ) ) + catalog = pg_sql.Identifier( + schema.replace("%", "%%"), STORE_PATH_CATALOG + ) _ = cur.execute( pg_sql.SQL(""" SELECT entry_value, layout_version FROM {} @@ -857,8 +862,11 @@ def upsert_records( else: conflict_clause = f'ON CONFLICT ("{escaped_id}") DO NOTHING' + target = sql_table_identifier(table_name, schema) + if schema is not None: + target = target.replace("%", "%%") sql = ( - f"INSERT INTO {sql_table_identifier(table_name, schema)} ({col_list}) VALUES ({placeholders}) " + f"INSERT INTO {target} ({col_list}) VALUES ({placeholders}) " f"{conflict_clause}" ) rows_iter = (tuple(row[c] for c in cols) for row in records.to_pylist()) diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 7ef356707..1d2b0e815 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -689,7 +689,7 @@ def test_catalog_uses_the_first_schema_on_the_search_path( connector: PostgreSQLConnector, ) -> None: _, _, _, primary = connector.current_location() - fallback = f'JOIN."{uuid.uuid4().hex[:12]}' + fallback = f'JOIN."%{uuid.uuid4().hex[:12]}' base_dsn = _base_dsn() path = ("job", "pdb_v2") with psycopg.connect(base_dsn, autocommit=True) as admin: From 651d3b4c0ffa1c50b0cb38be4d0bd893cffc2168 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 20:13:29 -0800 Subject: [PATCH 07/13] fix(databases): guard pending reads and refuse temporary store schemas --- .../databases/connector_arrow_database.py | 5 +++ src/orcapod/databases/postgresql_connector.py | 27 +++++++++--- tests/test_databases/test_append_by_name.py | 16 ++++--- .../test_postgresql_connector_integration.py | 42 ++++++++++++++++++- .../test_sqlite_connector_integration.py | 14 +++++-- 5 files changed, 89 insertions(+), 15 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index fd38547d6..bf5ba8a28 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -939,6 +939,11 @@ def get_record_by_id( pending = self._pending_batches[record_key] filtered = pending.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows > 0: + if self._sql_store is not None: + full_path = self._path_prefix + record_path + _ = self._find_committed_table( + self._path_to_table_name(full_path), full_path + ) return self._handle_record_id_column(filtered, record_id_column) # Check committed diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index f9727c8ad..76036efa5 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -274,6 +274,16 @@ def _coerce_pg_value(value: Any, arrow_type: "pa.DataType") -> Any: return value +def _require_persistent_store_schema(schema: str, temporary: object) -> None: + """Refuse a store namespace that would disappear with a PostgreSQL session.""" + # PostgreSQL's namespace checks omit the current session's temporary + # TOAST namespace, whose name uses this reserved system prefix. + if temporary or schema.startswith("pg_toast_temp_"): + raise OrcapodDatabaseError( + f"Cannot use temporary PostgreSQL schema {schema!r} for a connector store" + ) + + def _resolve_column_type_lookup( query: str, connector: "PostgreSQLConnector", @@ -460,11 +470,13 @@ def get_store_table_paths( ): _ = cur.execute( """ - SELECT ns.nspname, ns.oid + SELECT ns.nspname, ns.oid, + ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), + rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns - JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid - WHERE ns.nspname = current_schema() AND rel.relname = %s - AND rel.relkind = 'r' + LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid + AND rel.relname = %s AND rel.relkind = 'r' + WHERE ns.nspname = current_schema() """, (STORE_PATH_CATALOG,), ) @@ -472,6 +484,9 @@ def get_store_table_paths( if row is None: return [] schema = cast(str, row[0]) + _require_persistent_store_schema(schema, row[2]) + if not row[3]: + return [] # Psycopg scans percent signs even inside quoted identifiers when # the statement also has bound parameters. catalog = pg_sql.Identifier(schema.replace("%", "%%"), STORE_PATH_CATALOG) @@ -517,7 +532,8 @@ def store_table_transaction( # catalog does not exist yet. 0x4F524341 is the Orcapod lock key. _ = cur.execute( """ - SELECT nspname, pg_advisory_xact_lock(%s, oid::integer) + SELECT nspname, oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), + pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = current_schema() """, (0x4F524341,), @@ -526,6 +542,7 @@ def store_table_transaction( if location is None or location[0] is None: raise OrcapodDatabaseError("PostgreSQL has no current schema") schema = cast(str, location[0]) + _require_persistent_store_schema(schema, location[1]) catalog = pg_sql.Identifier(schema, STORE_PATH_CATALOG) fields = pg_sql.SQL(STORE_PATH_CATALOG_FIELDS).format( layout_version=pg_sql.Literal(STORE_PATH_LAYOUT_VERSION) diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index c20d8dbfb..fe428e867 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -745,9 +745,7 @@ def test_a_table_dropped_and_written_again_by_the_same_handle_takes_the_new_orde def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: - """A point lookup of a queued row answers from memory, in the order the row is - queued, with no lookup of the stored table (as main): the stored table is not - even listed. Presentation order is a reader's business (ITL-1370).""" + """Check catalog ownership before returning a queued row in its queued order.""" with open_database("SQLite", tmp_path) as db: rows = pa.table( { @@ -759,10 +757,18 @@ def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: db.add_records(PATH, rows, record_id_column="rid", flush=True) second = rows.set_column(0, "rid", pa.array([bytes([2])], pa.large_binary())) db.add_records(PATH, second, record_id_column="rid") - with patch.object( - db._connector, "get_store_table_paths", side_effect=AssertionError("listed") + with ( + patch.object( + db._connector, + "get_store_table_paths", + wraps=db._connector.get_store_table_paths, + ) as catalog, + patch.object( + db._connector, "iter_batches", side_effect=AssertionError("read rows") + ), ): queued = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + catalog.assert_called_once() assert queued is not None assert queued.column_names == ["rid", "z", "a"] db.flush() diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 1d2b0e815..b91c63170 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -25,6 +25,7 @@ import os import uuid from collections.abc import Iterator +from typing import cast import psycopg import pyarrow as pa @@ -743,7 +744,9 @@ def test_catalog_uses_the_first_schema_on_the_search_path( @pytest.mark.postgres -@pytest.mark.parametrize("operation", ["list", "read", "queue", "flush"]) +@pytest.mark.parametrize( + "operation", ["list", "read", "pending_point", "queue", "flush"] +) def test_unsupported_catalog_layout_is_refused( connector: PostgreSQLConnector, operation: str ) -> None: @@ -751,7 +754,7 @@ def test_unsupported_catalog_layout_is_refused( path = ("versioned",) one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) db.add_record(path, b"id", one, flush=True) - if operation == "flush": + if operation in ("flush", "pending_point"): db.add_record(path, b"id", two) connector._require_open().commit() catalog = sql.Identifier(STORE_PATH_CATALOG) @@ -799,6 +802,41 @@ def test_store_writes_to_the_verified_schema_when_a_temp_table_shadows_its_name( assert rows is not None and rows.to_pylist() == [{"value": 2}] +@pytest.mark.postgres +@pytest.mark.parametrize("operation", ["list", "queue", "flush"]) +@pytest.mark.parametrize("toast", [False, True], ids=["pg_temp", "temporary_toast"]) +def test_store_refuses_a_temporary_schema( + connector: PostgreSQLConnector, operation: str, toast: bool +) -> None: + db = ConnectorArrowDatabase(connector) + path = ("temporary",) + data = pa.table({"value": [1]}) + if operation == "flush": + db.add_record(path, b"id", data) + conn = connector._require_open() + _ = conn.execute("CREATE TEMP TABLE seed (value INTEGER)") + schema = "pg_temp" + if toast: + (temporary_schema,) = conn.execute( + "SELECT nspname FROM pg_catalog.pg_namespace WHERE oid = pg_my_temp_schema()" + ).fetchone() + schema = cast(str, temporary_schema).replace("pg_temp_", "pg_toast_temp_", 1) + _ = conn.execute( + sql.SQL("SET search_path TO {}, public").format(sql.Identifier(schema)) + ) + conn.commit() + + with pytest.raises(OrcapodDatabaseError, match="temporary PostgreSQL schema"): + _check_catalog_operation(db, path, data, operation) + + assert conn.execute( + """ + SELECT relname FROM pg_catalog.pg_class + WHERE relnamespace = pg_my_temp_schema() AND relkind = 'r' + """ + ).fetchall() == [("seed",)] + + @pytest.mark.postgres def test_pending_path_is_refused_if_another_writer_claims_name( connector: PostgreSQLConnector, monkeypatch: pytest.MonkeyPatch diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index e1193e1bb..6ef532ab9 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -73,14 +73,16 @@ def test_pending_path_is_refused_if_another_writer_claims_name( with SQLiteConnector(location) as first, SQLiteConnector(location) as second: _check_pending_collision(first, second) - @pytest.mark.parametrize("operation", ["list", "read", "queue", "flush"]) + @pytest.mark.parametrize( + "operation", ["list", "read", "pending_point", "queue", "flush"] + ) def test_unsupported_catalog_layout_is_refused(self, operation: str) -> None: path = ("versioned",) one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) with SQLiteConnector() as connector: db = ConnectorArrowDatabase(connector) db.add_record(path, b"id", one, flush=True) - if operation == "flush": + if operation in ("flush", "pending_point"): db.add_record(path, b"id", two) conn = connector._require_open() _ = conn.execute("PRAGMA ignore_check_constraints=ON") @@ -321,7 +323,11 @@ def _check_pending_collision( one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) queued.add_record(pending, b"id", two) winner.add_record(committed, b"id", one, flush=True) - for check in (queued.list_table_paths, lambda: queued.flush_batch(pending)): + for check in ( + queued.list_table_paths, + lambda: queued.get_record_by_id(pending, b"id"), + lambda: queued.flush_batch(pending), + ): with pytest.raises(OrcapodDatabaseError, match="name-part.*name:part"): check() rows = winner.get_all_records(committed) @@ -335,6 +341,8 @@ def _check_catalog_operation( db.list_table_paths() elif operation == "read": db.get_all_records(path) + elif operation == "pending_point": + db.get_record_by_id(path, b"id") elif operation == "queue": db.add_record(path, b"id", table) else: From ba18f17a41ef0a8e8490233183ed1c3dcc080a80 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 21:57:34 -0800 Subject: [PATCH 08/13] fix(databases): address CodeRabbit review findings --- docs/concepts/pipeline-job.md | 9 +- src/orcapod/databases/_sql_store.py | 4 + .../databases/connector_arrow_database.py | 102 +++++++++++--- src/orcapod/databases/postgresql_connector.py | 42 ++++-- src/orcapod/databases/sqlite_connector.py | 12 +- .../test_postgresql_connector_integration.py | 133 ++++++++++++++++++ .../test_sqlite_connector_integration.py | 115 ++++++++++++++- 7 files changed, 378 insertions(+), 39 deletions(-) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index da53b91ba..0515f10ac 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -267,11 +267,10 @@ is attached to them, before anything runs: An operator cache or cached source on a SQL connector is also refused when it is written, before anything is stored, if one of its own columns has a type or name the connector does not store. On PostgreSQL that is every operator cache with caching on: its system-tag column names -(`_tag_source_id::` and a 64-character hash) are longer than 63 bytes. -A table's name is its Orcapod path joined by `__`, and every node table and cached source path -holds a 64-character hash, so on PostgreSQL only tables you write through `ConnectorArrowDatabase` -yourself under short paths fit; reading an existing table with `PostgreSQLTableSource` is -unaffected. Use +(`_tag_source_id::` and a 64-character hash) are longer than 63 bytes. Connector store table names +use a readable path hint and a digest of the full path, so long paths fit the SQLite and PostgreSQL +table-name limits. These generated names do not change the separate column-name restrictions. +Reading an existing table with `PostgreSQLTableSource` is unaffected. Use `InMemoryArrowDatabase` or `DeltaTableDatabase` for such jobs. Storing these columns on connector databases is planned for a later release. diff --git a/src/orcapod/databases/_sql_store.py b/src/orcapod/databases/_sql_store.py index f5dd682c6..3f2ce7ec9 100644 --- a/src/orcapod/databases/_sql_store.py +++ b/src/orcapod/databases/_sql_store.py @@ -34,6 +34,10 @@ class SQLStoreConnector(Protocol): """SQL operations a connector store needs to track record table ownership.""" + def get_current_store_schema(self) -> str: + """Return the persistent schema selected for this store operation.""" + ... + def get_store_table_paths( self, name: str, *, exact: bool = False ) -> list[tuple[str, str, str]]: diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index bf5ba8a28..75c2c85a7 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -134,6 +134,9 @@ def __init__( _shared_pending_batches: dict[str, pa.Table] | None = None, _shared_pending_record_ids: dict[str, set[bytes]] | None = None, _shared_pending_skip_existing: dict[str, bool] | None = None, + _shared_pending_table_owners: dict[tuple[str, str], tuple[str, tuple[str, ...]]] + | None = None, + _shared_pending_owner_keys: dict[str, tuple[str, str]] | None = None, _root: ConnectorArrowDatabase | None = None, _scoped_path: tuple[str, ...] = (), ) -> None: @@ -155,7 +158,7 @@ def __init__( ) # The schema each stored table was read with, for the append check # (``_refuse_changed_columns``). - self._stored_schemas: dict[str, pa.Schema] = {} + self._stored_schemas: dict[tuple[str | None, str], pa.Schema] = {} # Per-batch flag: True when the batch was added with skip_duplicates=True, # so flush() can pass skip_existing=True to the connector and let it use # native INSERT-OR-IGNORE semantics rather than Python-side prefiltering. @@ -164,6 +167,16 @@ def __init__( if _shared_pending_skip_existing is not None else {} ) + self._pending_table_owners: dict[ + tuple[str, str], tuple[str, tuple[str, ...]] + ] = ( + _shared_pending_table_owners + if _shared_pending_table_owners is not None + else {} + ) + self._pending_owner_keys = ( + _shared_pending_owner_keys if _shared_pending_owner_keys is not None else {} + ) self._pending_commits = ( _root._pending_commits @@ -177,19 +190,41 @@ def __init__( ) def _discard_pending_duplicate_policy(self, key: str) -> None: - """Forget the duplicate policy when an entire queued batch is discarded.""" + """Forget indexes when an entire queued batch is discarded.""" self._pending_skip_existing.pop(key, None) + owner_key = self._pending_owner_keys.pop(key, None) + if owner_key is not None: + self._pending_table_owners.pop(owner_key, None) # ── Path helpers ────────────────────────────────────────────────────────── def _get_record_key(self, record_path: tuple[str, ...]) -> str: - return "/".join(self._path_prefix + record_path) + path_key = "/".join(self._plain_path(self._path_prefix + record_path)) + if self._sql_store is None: + return path_key + return f"{self._sql_store.get_current_store_schema()}\0{path_key}" + + @staticmethod + def _plain_path(path: tuple[str, ...]) -> tuple[str, ...]: + """Copy accepted string components to ordinary strings.""" + return tuple("".join((part,)) for part in path) + + def _record_path_from_key(self, record_key: str) -> tuple[str, ...]: + """Decode the path portion of a shared pending key.""" + path_key = ( + record_key.split("\0", 1)[1] if self._sql_store is not None else record_key + ) + return tuple(path_key.split("/")) + + def _schema_from_record_key(self, record_key: str) -> str | None: + """Return the store schema encoded in a pending key, if it has one.""" + return record_key.split("\0", 1)[0] if self._sql_store is not None else None def _path_to_table_name(self, record_path: tuple[str, ...]) -> str: """Map a full record path to a name the connector can store.""" if self._sql_store is not None and record_path: return store_table_name( - record_path, + self._plain_path(record_path), hint_length=_SQL_HINT_LENGTH, digest_length=_SQL_DIGEST_LENGTH, ) @@ -282,7 +317,9 @@ def _find_committed_table( table_name, exact=True ): require_store_table_owner( - table_name, full_path, stored_path(table_name, path_json) + table_name, + self._plain_path(full_path), + stored_path(table_name, path_json), ) return schema, name return None @@ -331,10 +368,11 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] f"Table {name!r} does not match its stored path {path!r}" ) owners[name] = path - for key in self._pending_batches: - path = tuple(key.split("/")) + current_schema = self._sql_store.get_current_store_schema() + for (schema, name), (_, path) in self._pending_table_owners.items(): + if schema != current_schema: + continue if path[: len(full_prefix)] == full_prefix: - name = self._path_to_table_name(path) require_store_table_owner(name, path, owners.setdefault(name, path)) return sorted( path[len(self._path_prefix) :] @@ -344,7 +382,7 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] names = set(self._connector.get_table_names()) names.update( - self._path_to_table_name(tuple(key.split("/"))) + self._path_to_table_name(self._record_path_from_key(key)) for key in self._pending_batches ) stem = self._path_to_table_name(full_prefix) if full_prefix else "" @@ -546,13 +584,17 @@ def add_records( self._connector.validate_records(records) record_key = self._get_record_key(record_path) + pending_owner_key: tuple[str, str] | None = None if self._sql_store is not None: _ = self._find_committed_table(table_name, full_path) - if record_key not in self._pending_batches: - for key in self._pending_batches: - queued_path = tuple(key.split("/")) - if self._path_to_table_name(queued_path) == table_name: - require_store_table_owner(table_name, full_path, queued_path) + schema = self._schema_from_record_key(record_key) + assert schema is not None + pending_owner_key = (schema, table_name) + queued = self._pending_table_owners.get(pending_owner_key) + if queued is not None and queued[0] != record_key: + require_store_table_owner( + table_name, self._plain_path(full_path), queued[1] + ) # Columns match by name: rows with the held columns in another order are # put in the held order, so the connector always receives the stored order # (ITL-1367). @@ -596,6 +638,12 @@ def add_records( # Buffer in pending batch existing_pending = self._pending_batches.get(record_key) if existing_pending is None: + if pending_owner_key is not None: + self._pending_table_owners[pending_owner_key] = ( + record_key, + self._plain_path(full_path), + ) + self._pending_owner_keys[record_key] = pending_owner_key self._pending_batches[record_key] = records else: self._pending_batches[record_key] = pa.concat_tables( @@ -659,14 +707,16 @@ def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: held.append(pending.schema) full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) - stored = self._stored_schemas.get(table_name) + schema = self._schema_from_record_key(self._get_record_key(record_path)) + stored_key = (schema, table_name) + stored = self._stored_schemas.get(stored_key) if stored is None: table = self._find_committed_table(table_name, full_path) if table is not None: schema, name = table stored = self._read_stored_schema(name, schema) if stored is not None: - self._stored_schemas[table_name] = stored + self._stored_schemas[stored_key] = stored if stored is not None: held.append(stored) return held @@ -738,8 +788,7 @@ def base_path(self) -> tuple[str, ...]: def at(self, *path_components: str) -> "ConnectorArrowDatabase": """Return a new ConnectorArrowDatabase scoped to the given sub-path. - The returned instance shares the connector and all three pending dicts - (_pending_batches, _pending_record_ids, _pending_skip_existing) by reference. + The returned instance shares the connector and all pending state by reference. Calling flush() on any view drains the entire shared pending queue. Raises: @@ -766,6 +815,8 @@ def at(self, *path_components: str) -> "ConnectorArrowDatabase": _shared_pending_batches=self._pending_batches, _shared_pending_record_ids=self._pending_record_ids, _shared_pending_skip_existing=self._pending_skip_existing, + _shared_pending_table_owners=self._pending_table_owners, + _shared_pending_owner_keys=self._pending_owner_keys, _root=new_root, _scoped_path=new_scoped_path, ) @@ -826,15 +877,24 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: def _flush_by_key(self, record_key: str) -> None: """Commit the ready records at a key shared by all views.""" + if self._sql_store is not None: + queued_schema = self._schema_from_record_key(record_key) + active_schema = self._sql_store.get_current_store_schema() + if queued_schema != active_schema: + raise OrcapodDatabaseError( + f"Pending store batch belongs to schema " + f"{queued_schema!r}, not active schema {active_schema!r}; " + "switch back to the original schema and retry the flush" + ) ready = self._pending_commits.take_ready(record_key) if ready is None: return pending, ids = ready - record_path = tuple(record_key.split("/")) - table_name = self._path_to_table_name(record_path) skip_existing = self._pending_skip_existing.get(record_key, False) if record_key not in self._pending_batches: - self._pending_skip_existing.pop(record_key, None) + self._discard_pending_duplicate_policy(record_key) + record_path = self._record_path_from_key(record_key) + table_name = self._path_to_table_name(record_path) try: self._require_table_name(table_name) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 76036efa5..a3681f7d1 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -316,7 +316,7 @@ def _resolve_column_type_lookup( if len(from_matches) != 1: return {} match = from_matches[0] - table_name = unquote_sql_identifier(match["table"]) + table_name = _normalize_pg_identifier(match["table"]) # Inspect the text after the table name up to the next major SQL clause. # A comma before the clause boundary means comma-joined tables ("FROM a, b"). @@ -337,12 +337,21 @@ def _resolve_column_type_lookup( connector.get_column_info(table_name) if namespace is None else connector.get_column_info( - table_name, schema=unquote_sql_identifier(namespace) + table_name, schema=_normalize_pg_identifier(namespace) ) ) return {ci.name: ci for ci in columns} +def _normalize_pg_identifier(identifier: str) -> str: + """Resolve a parsed PostgreSQL identifier as the server would.""" + if identifier.startswith('"'): + return unquote_sql_identifier(identifier) + return identifier.translate( + str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") + ) + + def _field_has_metadata(field: pa.Field) -> bool: """Return True if ``field`` or any nested child carries Arrow metadata. @@ -462,12 +471,8 @@ def get_store_table_paths( """Return registered record tables matching a physical name or prefix.""" from psycopg import sql as pg_sql - with ( - self._lock, - cast( - "psycopg.Connection[tuple[object, ...]]", self._require_open() - ).cursor() as cur, - ): + conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) + with self._lock, conn.transaction(), conn.cursor() as cur: _ = cur.execute( """ SELECT ns.nspname, ns.oid, @@ -511,11 +516,30 @@ def get_store_table_paths( for table_name, path_json, version, exists in cast( "list[tuple[str, str, int, bool]]", cur.fetchall() ): - require_catalog_layout(table_name, version) if exists: + require_catalog_layout(table_name, version) paths.append((schema, table_name, path_json)) return paths + def get_current_store_schema(self) -> str: + """Return the persistent schema selected for connector stores.""" + conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) + with self._lock, conn.transaction(), conn.cursor() as cur: + _ = cur.execute( + """ + SELECT ns.nspname, + ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) + FROM pg_catalog.pg_namespace AS ns + WHERE ns.nspname = current_schema() + """ + ) + row = cur.fetchone() + if row is None: + raise OrcapodDatabaseError("PostgreSQL has no current schema") + schema = cast(str, row[0]) + _require_persistent_store_schema(schema, row[1]) + return schema + @contextmanager def store_table_transaction( self, table_name: str, path_json: str diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index 4481a07f0..de916dba4 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -338,11 +338,16 @@ def get_store_table_paths( paths: list[tuple[str, str, str]] = [] for row in rows: table_name = cast(str, row[0]) - require_catalog_layout(table_name, cast(object, row[2])) if row[3]: + require_catalog_layout(table_name, cast(object, row[2])) paths.append(("main", table_name, cast(str, row[1]))) return paths + def get_current_store_schema(self) -> str: + """Return SQLite's persistent schema selected for connector stores.""" + self._require_open() + return "main" + @contextmanager def store_table_transaction( self, table_name: str, path_json: str @@ -437,9 +442,10 @@ def get_column_info( """ with self._lock: conn = self._require_open() - self._validate_table_name(table_name) namespace = "" if schema is None else sql_table_identifier(schema) + "." - cursor = conn.execute(f'PRAGMA {namespace}table_info("{table_name}")') + cursor = conn.execute( + f"PRAGMA {namespace}table_info({sql_table_identifier(table_name)})" + ) return [ ColumnInfo( name=row["name"], diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index a0414b1b8..0ced3c466 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -792,6 +792,139 @@ def test_unsupported_catalog_layout_is_refused( ).fetchone() == (1,) +@pytest.mark.postgres +def test_missing_record_table_ignores_unsupported_catalog_version( + connector: PostgreSQLConnector, +) -> None: + db = ConnectorArrowDatabase(connector) + path = ("orphan",) + db.add_record(path, b"id", pa.table({"value": [1]}), flush=True) + name = next(n for n in connector.get_table_names() if n.startswith("o1_")) + catalog = sql.Identifier(STORE_PATH_CATALOG) + with psycopg.connect(connector._dsn) as conn: + _ = conn.execute( + sql.SQL("ALTER TABLE {} DROP CONSTRAINT {}").format( + catalog, sql.Identifier(f"{STORE_PATH_CATALOG}_layout_version_check") + ) + ) + _ = conn.execute(sql.SQL("UPDATE {} SET layout_version = 2").format(catalog)) + _ = conn.execute(sql.SQL("DROP TABLE {}").format(sql.Identifier(name))) + + assert db.get_all_records(path) is None + assert db.list_table_paths() == [] + + +@pytest.mark.postgres +def test_str_subclass_path_reopens_as_ordinary_string( + connector: PostgreSQLConnector, +) -> None: + class OddString(str): + def __eq__(self, other: object) -> bool: + return self is other + + __hash__ = str.__hash__ + + db = ConnectorArrowDatabase(connector) + db.add_record(("same",), b"id", pa.table({"value": [1]}), flush=True) + + rows = db.get_all_records((OddString("same"),)) + assert rows is not None and rows.to_pylist() == [{"value": 1}] + + +@pytest.mark.postgres +def test_metadata_lookup_folds_unquoted_schema_identifier( + connector: PostgreSQLConnector, +) -> None: + _, _, _, schema = connector.current_location() + _ = connector._require_open().execute( + "CREATE TABLE records (value BIGINT NOT NULL)" + ) + _ = connector._require_open().execute("INSERT INTO records VALUES (7)") + connector._require_open().commit() + + batches = list( + connector.iter_batches(f"SELECT value FROM {schema.upper()}.records") + ) + + assert len(batches) == 1 + assert batches[0].schema.field("value").type == pa.int64() + assert batches[0].schema.field("value").nullable is False + assert batches[0].column(0).to_pylist() == [7] + + _ = connector._require_open().execute( + 'CREATE TABLE "MixedCase" (value BIGINT NOT NULL)' + ) + _ = connector._require_open().execute('INSERT INTO "MixedCase" VALUES (8)') + connector._require_open().commit() + quoted = list(connector.iter_batches(f'SELECT value FROM "{schema}"."MixedCase"')) + assert quoted[0].schema.field("value").type == pa.int64() + assert quoted[0].column(0).to_pylist() == [8] + + +@pytest.mark.postgres +def test_standalone_catalog_lookup_releases_its_transaction( + connector: PostgreSQLConnector, +) -> None: + db = ConnectorArrowDatabase(connector) + db.add_record(("lock-test",), b"id", pa.table({"value": [1]}), flush=True) + + paths = connector.get_store_table_paths("o1_", exact=False) + + assert paths + assert connector._require_open().info.transaction_status.name == "IDLE" + + +@pytest.mark.postgres +def test_catalog_lookup_does_not_commit_a_callers_transaction( + connector: PostgreSQLConnector, +) -> None: + conn = connector._require_open() + _ = conn.execute("CREATE TABLE caller_work (value INTEGER)") + + _ = connector.get_store_table_paths("o1_") + + assert conn.info.transaction_status.name == "INTRANS" + conn.rollback() + with psycopg.connect(connector._dsn) as check: + assert check.execute("SELECT to_regclass('caller_work')").fetchone() == (None,) + + +@pytest.mark.postgres +def test_pending_rows_remain_bound_to_their_postgresql_schema( + connector: PostgreSQLConnector, +) -> None: + base_dsn = _base_dsn() + schema_b = f"pending_{uuid.uuid4().hex[:12]}" + with psycopg.connect(base_dsn, autocommit=True) as admin: + _ = admin.execute(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(schema_b))) + try: + db = ConnectorArrowDatabase(connector) + path = ("same",) + (schema_a,) = ( + connector._require_open().execute("SELECT current_schema()").fetchone() + ) + db.add_record(path, b"a", pa.table({"value": [1]})) + + _ = connector._require_open().execute( + sql.SQL("SET search_path TO {}").format(sql.Identifier(schema_b)) + ) + assert db.get_record_by_id(path, b"a") is None + with pytest.raises(OrcapodDatabaseError, match="pending.*schema"): + db.flush() + + _ = connector._require_open().execute( + sql.SQL("SET search_path TO {}").format(sql.Identifier(schema_a)) + ) + db.flush() + rows = db.get_all_records(path) + assert rows is not None and rows.to_pylist() == [{"value": 1}] + finally: + with psycopg.connect(base_dsn, autocommit=True) as admin: + _ = admin.execute( + sql.SQL("DROP SCHEMA {} CASCADE").format(sql.Identifier(schema_b)) + ) + + @pytest.mark.postgres def test_store_writes_to_the_verified_schema_when_a_temp_table_shadows_its_name( connector: PostgreSQLConnector, diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index 6ef532ab9..ccf20cb03 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -61,6 +61,79 @@ def test_paths_with_a_forced_digest_collision_cannot_share_a_table( records = db.get_all_records(first) assert records is not None and records.to_pylist() == [{"value": 1}] + def test_str_subclass_path_reopens_as_ordinary_string( + self, db: ConnectorArrowDatabase + ) -> None: + class OddString(str): + def __eq__(self, other: object) -> bool: + return self is other + + __hash__ = str.__hash__ + + path = (OddString("same"),) + db.add_record(("same",), b"id", pa.table({"value": [1]}), flush=True) + + rows = db.get_all_records(path) + assert rows is not None and rows.to_pylist() == [{"value": 1}] + + def test_iter_batches_reads_quoted_table_name_metadata(self) -> None: + with SQLiteConnector() as connector: + conn = connector._require_open() + _ = conn.execute( + 'CREATE TABLE main."order""items" (value INTEGER NOT NULL)' + ) + _ = conn.execute('INSERT INTO main."order""items" VALUES (7)') + + batches = list( + connector.iter_batches('SELECT value FROM main."order""items"') + ) + + assert len(batches) == 1 + assert batches[0].schema.field("value").type == pa.int64() + assert batches[0].column(0).to_pylist() == [7] + + def test_pending_collision_check_uses_indexed_table_names( + self, db: ConnectorArrowDatabase, monkeypatch: pytest.MonkeyPatch + ) -> None: + from orcapod.databases import connector_arrow_database + + assert db._sql_store is not None # pyright: ignore[reportPrivateUsage] + original = connector_arrow_database.store_table_name + calls = 0 + + def counted( + path: tuple[str, ...], *, hint_length: int, digest_length: int + ) -> str: + nonlocal calls + calls += 1 + return original(path, hint_length=hint_length, digest_length=digest_length) + + monkeypatch.setattr(connector_arrow_database, "store_table_name", counted) + for index in range(30): + db.add_record( + (f"path-{index}",), + str(index).encode(), + pa.table({"v": [index]}), + ) + + assert calls < 250 + + def test_failed_dependency_removes_pending_owner_index_entry( + self, db: ConnectorArrowDatabase + ) -> None: + parent_path = ("parent",) + child_path = ("child",) + attempt = db._pending_commits.attempt( # pyright: ignore[reportPrivateUsage] + db._get_record_key(parent_path) # pyright: ignore[reportPrivateUsage] + ) + with db.guard_record(child_path, b"child", attempt): + db.add_record(child_path, b"child", pa.table({"value": [1]})) + assert db.list_table_paths() == [child_path] + + db.fail_pending_result(parent_path) + + assert db.list_table_paths() == [] + def test_pending_path_is_refused_if_another_writer_claims_name( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -98,6 +171,22 @@ def test_unsupported_catalog_layout_is_refused(self, operation: str) -> None: conn.execute(f'SELECT value FROM main."{name}"').fetchone() ) == (1,) + def test_missing_record_table_ignores_unsupported_catalog_version(self) -> None: + path = ("orphan",) + with SQLiteConnector() as connector: + db = ConnectorArrowDatabase(connector) + db.add_record(path, b"id", pa.table({"value": [1]}), flush=True) + conn = connector._require_open() + name = next(n for n in connector.get_table_names() if n.startswith("o1_")) + _ = conn.execute("PRAGMA ignore_check_constraints=ON") + _ = conn.execute( + f'UPDATE main."{STORE_PATH_CATALOG}" SET layout_version = 2' + ) + _ = conn.execute(f'DROP TABLE main."{name}"') + + assert db.get_all_records(path) is None + assert db.list_table_paths() == [] + @pytest.mark.parametrize("write", [False, True]) def test_store_uses_main_when_a_temp_table_shadows_its_name( self, write: bool @@ -337,6 +426,17 @@ def _check_pending_collision( def _check_catalog_operation( db: ConnectorArrowDatabase, path: tuple[str, ...], table: pa.Table, operation: str ) -> None: + """Run one named catalog operation shared by the SQLite and PostgreSQL tests. + + Args: + db: The connector-backed database under test. + path: The path passed to the selected operation. + table: The record table used by queue operations. + operation: One of ``list``, ``read``, ``pending_point``, ``queue``, or ``flush``. + + Raises: + ValueError: If ``operation`` is not one of the supported values. + """ if operation == "list": db.list_table_paths() elif operation == "read": @@ -345,5 +445,18 @@ def _check_catalog_operation( db.get_record_by_id(path, b"id") elif operation == "queue": db.add_record(path, b"id", table) - else: + elif operation == "flush": db.flush_batch(path) + else: + raise ValueError(f"Unknown catalog operation: {operation!r}") + + +def test_catalog_operation_helper_rejects_unknown_operation() -> None: + with SQLiteConnector(":memory:") as connector: + with pytest.raises(ValueError, match="Unknown catalog operation"): + _check_catalog_operation( + ConnectorArrowDatabase(connector), + ("path",), + pa.table({"value": [1]}), + "flsuh", + ) From ec268937888739db8debb1bb9e752e1819180470 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 22:25:59 -0800 Subject: [PATCH 09/13] fix(databases): preserve metadata validation and mocks --- src/orcapod/databases/sqlite_connector.py | 11 +++++++++-- tests/test_databases/test_unstorable_columns.py | 15 ++++++++++++++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index de916dba4..fb31e7727 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -440,6 +440,13 @@ def get_column_info( Returns: List of ColumnInfo objects; empty list if table doesn't exist. """ + self._validate_table_name(table_name) + return self._get_column_info(table_name, schema=schema) + + def _get_column_info( + self, table_name: str, *, schema: str | None = None + ) -> list[ColumnInfo]: + """Read metadata for an already parsed, safely quoted table identifier.""" with self._lock: conn = self._require_open() namespace = "" if schema is None else sql_table_identifier(schema) + "." @@ -506,9 +513,9 @@ def iter_batches( queried_table = unquote_sql_identifier(table_match["table"]) namespace = table_match["schema"] column_info = ( - self.get_column_info(queried_table) + self._get_column_info(queried_table) if namespace is None - else self.get_column_info( + else self._get_column_info( queried_table, schema=unquote_sql_identifier(namespace) ) ) diff --git a/tests/test_databases/test_unstorable_columns.py b/tests/test_databases/test_unstorable_columns.py index c9dc0f2a0..288db7f32 100644 --- a/tests/test_databases/test_unstorable_columns.py +++ b/tests/test_databases/test_unstorable_columns.py @@ -536,7 +536,20 @@ def _mocked_postgresql() -> tuple[PostgreSQLConnector, MagicMock]: """A ``PostgreSQLConnector`` over a mocked connection (no server).""" with patch("psycopg.connect") as mock_connect: conn = MagicMock() - conn.cursor.return_value.__enter__.return_value.fetchone.return_value = None + cursor = conn.cursor.return_value.__enter__.return_value + + def fetchone(): + query = cursor.execute.call_args.args[0] + if ( + isinstance(query, str) + and "SELECT ns.nspname," in query + and "ns.oid," not in query + and "WHERE ns.nspname = current_schema()" in query + ): + return ("public", False) + return None + + cursor.fetchone.side_effect = fetchone mock_connect.return_value = conn return PostgreSQLConnector("postgresql://localhost/test"), conn From b06d9c9fa1d35f3904d1e88a9fd6350eda95de84 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 01:12:05 -0800 Subject: [PATCH 10/13] fix(store): normalize SQL paths and release PostgreSQL read locks --- docs/dev/design_issues/ITL-1552-CA4.md | 2 + .../databases/connector_arrow_database.py | 44 +++++++-------- src/orcapod/databases/postgresql_connector.py | 14 ++--- .../test_postgresql_connector_integration.py | 54 ++++++++++++++++++- .../test_sqlite_connector_integration.py | 53 ++++++++++++++++++ 5 files changed, 139 insertions(+), 28 deletions(-) diff --git a/docs/dev/design_issues/ITL-1552-CA4.md b/docs/dev/design_issues/ITL-1552-CA4.md index 6fb370f2a..074d93a31 100644 --- a/docs/dev/design_issues/ITL-1552-CA4.md +++ b/docs/dev/design_issues/ITL-1552-CA4.md @@ -10,3 +10,5 @@ write overwrite the other's rows. PostgreSQL also refused names beyond 63 bytes. **Fix:** Both SQL backends use a 63-byte budget for the path hint and digest. A versioned catalog keeps the original paths so lookups can refuse name collisions. +SQL stores normalize string subclasses before validating path components or +matching prefixes, so subclass methods cannot change which path a table uses. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 75c2c85a7..f2a099b6f 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -199,15 +199,18 @@ def _discard_pending_duplicate_policy(self, key: str) -> None: # ── Path helpers ────────────────────────────────────────────────────────── def _get_record_key(self, record_path: tuple[str, ...]) -> str: - path_key = "/".join(self._plain_path(self._path_prefix + record_path)) + full_path = self._plain_path(self._path_prefix + record_path) if self._sql_store is None: - return path_key - return f"{self._sql_store.get_current_store_schema()}\0{path_key}" + return "/".join(full_path) + self._validate_path_components(full_path) + return f"{self._sql_store.get_current_store_schema()}\0{'/'.join(full_path)}" @staticmethod def _plain_path(path: tuple[str, ...]) -> tuple[str, ...]: - """Copy accepted string components to ordinary strings.""" - return tuple("".join((part,)) for part in path) + """Copy the underlying text of string components to ordinary strings.""" + return tuple( + str.__str__(part) if isinstance(part, str) else part for part in path + ) def _record_path_from_key(self, record_key: str) -> tuple[str, ...]: """Decode the path portion of a shared pending key.""" @@ -243,17 +246,20 @@ def _validate_record_path(self, record_path: tuple[str, ...]) -> None: f"{self.max_hierarchy_depth - len(self._path_prefix)} " f"(base_path uses {len(self._path_prefix)} components)" ) - for i, component in enumerate(record_path): - if not component or not isinstance(component, str): - raise ValueError( - f"record_path component {i} is invalid: {repr(component)}" - ) + self._validate_path_components(record_path) + + @staticmethod + def _validate_path_components(path: tuple[str, ...]) -> None: + """Check components before encoding the path as a pending key.""" + for i, component in enumerate(path): + if not isinstance(component, str) or not component: + raise ValueError(f"Path component {i} is invalid: {component!r}") # "/" is the separator used by _get_record_key; "\0" is a common # string-boundary sentinel. Both would corrupt key round-tripping # in flush() where record_path is reconstructed via split("/"). if "/" in component or "\0" in component: raise ValueError( - f"record_path component {repr(component)} contains an " + f"Path component {component!r} contains an " "invalid character ('/' or '\\0')" ) @@ -357,6 +363,7 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] """ full_prefix = self._path_prefix + prefix if self._sql_store is not None: + full_prefix = self._plain_path(full_prefix) stem = STORE_TABLE_NAME_PREFIX + table_name_hint( full_prefix, hint_length=_SQL_HINT_LENGTH ) @@ -543,6 +550,8 @@ def add_records( flush: bool = False, ) -> None: """Add multiple records to the pending batch.""" + if self._sql_store is not None: + record_path = self._plain_path(record_path) self._validate_record_path(record_path) if records.num_rows == 0: return @@ -796,16 +805,9 @@ def at(self, *path_components: str) -> "ConnectorArrowDatabase": ``'/'`` or ``'\\0'`` (which would corrupt the ``'/'``-separated record key scheme and break ``flush()``'s key reconstruction). """ - for i, component in enumerate(path_components): - if not component or not isinstance(component, str): - raise ValueError( - f"at() path component {i} is invalid: {repr(component)}" - ) - if "/" in component or "\0" in component: - raise ValueError( - f"at() path component {repr(component)} contains an invalid character " - "('/' or '\\0')" - ) + if self._sql_store is not None: + path_components = self._plain_path(path_components) + self._validate_path_components(path_components) new_root = self._root if self._root is not None else self new_scoped_path = self._scoped_path + path_components return ConnectorArrowDatabase( diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index a3681f7d1..7c453eed0 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -453,7 +453,7 @@ def get_table_names(self) -> list[str]: """Return all user table names in this database (sorted, excludes views).""" with self._lock: conn = self._require_open() - with conn.cursor() as cur: + with conn.transaction(force_rollback=True), conn.cursor() as cur: cur.execute( """ SELECT table_name @@ -472,7 +472,9 @@ def get_store_table_paths( from psycopg import sql as pg_sql conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) - with self._lock, conn.transaction(), conn.cursor() as cur: + # Rolling back the read scope also releases its catalog lock when + # psycopg uses a savepoint inside a caller-owned transaction. + with self._lock, conn.transaction(force_rollback=True), conn.cursor() as cur: _ = cur.execute( """ SELECT ns.nspname, ns.oid, @@ -524,7 +526,7 @@ def get_store_table_paths( def get_current_store_schema(self) -> str: """Return the persistent schema selected for connector stores.""" conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) - with self._lock, conn.transaction(), conn.cursor() as cur: + with self._lock, conn.transaction(force_rollback=True), conn.cursor() as cur: _ = cur.execute( """ SELECT ns.nspname, @@ -650,7 +652,7 @@ def current_location(self) -> tuple[str, int, str, str]: with self._lock: conn = self._require_open() host, port = conn.info.host, conn.info.port - with conn.cursor() as cur: + with conn.transaction(force_rollback=True), conn.cursor() as cur: cur.execute("SELECT current_database(), current_schema()") row = cur.fetchone() if row is None or row[0] is None or row[1] is None: @@ -712,7 +714,7 @@ def get_pk_columns(self, table_name: str) -> list[str]: with self._lock: conn = self._require_open() self._validate_table_name(table_name) - with conn.cursor() as cur: + with conn.transaction(force_rollback=True), conn.cursor() as cur: cur.execute( """ SELECT kcu.column_name @@ -738,7 +740,7 @@ def get_column_info( with self._lock: conn = self._require_open() self._validate_table_name(table_name) - with conn.cursor() as cur: + with conn.transaction(force_rollback=True), conn.cursor() as cur: cur.execute( """ SELECT column_name, data_type, udt_name, is_nullable diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 0ced3c466..6de6b676d 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -39,6 +39,8 @@ from tests.test_databases.test_sqlite_connector_integration import ( _check_catalog_operation, _check_pending_collision, + _check_sql_listing_normalizes_subclass_prefix, + _check_sql_path_rejects_hidden_separator, ) from tests.test_core.test_result_cache import ( TIE_ORDERS, @@ -831,6 +833,26 @@ def __eq__(self, other: object) -> bool: assert rows is not None and rows.to_pylist() == [{"value": 1}] +@pytest.mark.postgres +@pytest.mark.parametrize("scoped", [False, True]) +def test_sql_path_rejects_hidden_separator( + connector: PostgreSQLConnector, scoped: bool +) -> None: + _check_sql_path_rejects_hidden_separator( + ConnectorArrowDatabase(connector), scoped=scoped + ) + + +@pytest.mark.postgres +@pytest.mark.parametrize("flush", [False, True]) +def test_sql_listing_normalizes_subclass_prefix( + connector: PostgreSQLConnector, flush: bool +) -> None: + _check_sql_listing_normalizes_subclass_prefix( + ConnectorArrowDatabase(connector), flush=flush + ) + + @pytest.mark.postgres def test_metadata_lookup_folds_unquoted_schema_identifier( connector: PostgreSQLConnector, @@ -874,14 +896,44 @@ def test_standalone_catalog_lookup_releases_its_transaction( assert connector._require_open().info.transaction_status.name == "IDLE" +@pytest.mark.postgres +@pytest.mark.parametrize("read", ["get_all_records", "get_table_schema"]) +def test_public_store_read_and_listing_release_catalog_lock( + connector: PostgreSQLConnector, read: str +) -> None: + db = ConnectorArrowDatabase(connector) + path = ("lock-test",) + db.add_record(path, b"id", pa.table({"value": [1]}), flush=True) + + assert getattr(db, read)(path) is not None + assert db.list_table_paths() == [path] + + _check_catalog_can_be_locked(connector) + assert connector._require_open().info.transaction_status.name == "IDLE" + + +def _check_catalog_can_be_locked(connector: PostgreSQLConnector) -> None: + """Verify the store's catalog can take an exclusive lock from another connection.""" + with psycopg.connect(connector._dsn) as independent: + _ = independent.execute( + sql.SQL("LOCK TABLE {} IN ACCESS EXCLUSIVE MODE NOWAIT").format( + sql.Identifier(STORE_PATH_CATALOG) + ) + ) + + @pytest.mark.postgres def test_catalog_lookup_does_not_commit_a_callers_transaction( connector: PostgreSQLConnector, ) -> None: + db = ConnectorArrowDatabase(connector) + path = ("lock-test",) + db.add_record(path, b"id", pa.table({"value": [1]}), flush=True) conn = connector._require_open() _ = conn.execute("CREATE TABLE caller_work (value INTEGER)") - _ = connector.get_store_table_paths("o1_") + assert db.list_table_paths() == [path] + _check_catalog_can_be_locked(connector) assert conn.info.transaction_status.name == "INTRANS" conn.rollback() diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index ccf20cb03..7ebfbdef7 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -24,6 +24,59 @@ def db() -> Iterator[ConnectorArrowDatabase]: connector.close() +def _check_sql_path_rejects_hidden_separator( + db: ConnectorArrowDatabase, *, scoped: bool +) -> None: + class HiddenSeparator(str): + def __contains__(self, item: object) -> bool: + return False + + db.add_record(("a", "b"), b"id", pa.table({"value": [10]}), flush=True) + if scoped: + with pytest.raises(ValueError, match="invalid character"): + db.at(HiddenSeparator("a/b")) + else: + with pytest.raises(ValueError, match="invalid character"): + db.add_record( + (HiddenSeparator("a/b"),), b"id", pa.table({"value": [99]}), flush=True + ) + rows = db.get_all_records(("a", "b")) + assert rows is not None and rows.to_pylist() == [{"value": 10}] + + +def _check_sql_listing_normalizes_subclass_prefix( + db: ConnectorArrowDatabase, *, flush: bool +) -> None: + class OddString(str): + def __eq__(self, other: object) -> bool: + return self is other + + __hash__ = str.__hash__ + + def __str__(self) -> str: + return "different" + + scope = db.at(OddString("same")) + scope.add_record(("child",), b"id", pa.table({"value": [1]}), flush=flush) + + assert scope.list_table_paths() == [("child",)] + assert db.list_table_paths((OddString("same"),)) == [("same", "child")] + + +@pytest.mark.parametrize("scoped", [False, True]) +def test_sql_path_rejects_hidden_separator( + db: ConnectorArrowDatabase, scoped: bool +) -> None: + _check_sql_path_rejects_hidden_separator(db, scoped=scoped) + + +@pytest.mark.parametrize("flush", [False, True]) +def test_sql_listing_normalizes_subclass_prefix( + db: ConnectorArrowDatabase, flush: bool +) -> None: + _check_sql_listing_normalizes_subclass_prefix(db, flush=flush) + + class TestConnectorArrowDatabaseWithSQLite: def test_long_paths_with_the_same_sanitized_name_store_separate_rows( self, db: ConnectorArrowDatabase From 5b11c517f02d0268798ee10ea78a3549aa0e4851 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 01:33:10 -0800 Subject: [PATCH 11/13] test(store): pin SQL table name v1 vectors --- .../test_databases/test_store_table_names.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/test_databases/test_store_table_names.py b/tests/test_databases/test_store_table_names.py index ba0c8c009..3be9da8ff 100644 --- a/tests/test_databases/test_store_table_names.py +++ b/tests/test_databases/test_store_table_names.py @@ -3,6 +3,27 @@ from __future__ import annotations +def test_sql_store_name_v1_has_frozen_canonical_path_digest_and_boundary() -> None: + """Freeze compact UTF-8 JSON, SHA-256 and the o1 name's 27/32 limits.""" + from orcapod.databases.store_table_names import ( + store_table_digest, + store_table_name, + store_table_path_json, + ) + + path = ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "b/c", "é") + assert ( + store_table_path_json(path) + == b'["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","b/c","\xc3\xa9"]' + ) + assert store_table_digest(path) == ( + "71fdebbe6a6f5cb2d4bb274c8345cc81983efbc7f9bf1ecb0f2f51a0c0235b67" + ) + assert store_table_name(path, hint_length=27, digest_length=32) == ( + "o1_aaaaaaaaaaaaaaaaaaaaaaaaaaa_71fdebbe6a6f5cb2d4bb274c8345cc81" + ) + + def test_shared_rule_reproduces_the_spiraldb_name() -> None: from orcapod.databases.store_table_names import store_table_name From 9d0aa19eef4f808fc4296c85b998784f78dbb26a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 01:59:24 -0800 Subject: [PATCH 12/13] fix(databases): refuse an invalid SQL path in get_table_schema as the other reads do An invalid path (an empty component, or one holding '/' or NUL) names no table. get_table_schema wrapped that refusal in OrcapodDatabaseReadError, whose message says the table exists. The path is now checked outside the wrapped read, so the ValueError of table_exists and get_all_records is raised. Co-Authored-By: Claude Fable 5.2 --- .../databases/connector_arrow_database.py | 11 ++++++-- .../test_sqlite_connector_integration.py | 27 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index f2a099b6f..40665790c 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -432,15 +432,22 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the committed or queued schema without fetching rows. Raises: - OrcapodDatabaseReadError: If the connector cannot inspect the schema. + ValueError: If a SQL store is given a path that names no table (an + empty component, or one holding ``/`` or ``\0``), as + ``table_exists`` and ``get_all_records`` raise for it. + OrcapodDatabaseReadError: If the connector cannot inspect the schema + of a table that exists. """ full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) + # Outside the ``try``: an invalid path is no table, so its refusal must + # not be reported as a stored table that could not be read. + record_key = self._get_record_key(record_path) try: table = self._find_committed_table(table_name, full_path) if table is None: - pending = self._pending_batches.get(self._get_record_key(record_path)) + pending = self._pending_batches.get(record_key) return None if pending is None else pending.schema schema, name = table return pa.schema( diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index 7ebfbdef7..32dc4dac9 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -63,6 +63,33 @@ def __str__(self) -> str: assert db.list_table_paths((OddString("same"),)) == [("same", "child")] +@pytest.mark.parametrize("path", [("a/b",), ("",), ("a", "b\0c")]) +def test_sql_schema_read_refuses_an_invalid_path_as_the_other_reads_do( + db: ConnectorArrowDatabase, path: tuple[str, ...] +) -> None: + """An invalid path names no table, so no read may say that a table exists. + + Every read of a SQL store refuses such a path with the same ``ValueError``; + ``get_table_schema`` used to report it as a stored table it could not read. + """ + db.add_record(("a", "b"), b"id", pa.table({"value": [10]}), flush=True) + + with pytest.raises(ValueError, match="Path component") as schema_error: + db.get_table_schema(path) + with pytest.raises(ValueError, match="Path component") as exists_error: + db.table_exists(path) + with pytest.raises(ValueError, match="Path component") as records_error: + db.get_all_records(path) + + assert not isinstance(schema_error.value, OrcapodDatabaseError) + assert "exists" not in str(schema_error.value) + assert str(schema_error.value) == str(exists_error.value) + assert str(schema_error.value) == str(records_error.value) + stored = db.get_table_schema(("a", "b")) + assert stored is not None and stored.field("value").type == pa.int64() + assert db.get_table_schema(("missing",)) is None + + @pytest.mark.parametrize("scoped", [False, True]) def test_sql_path_rejects_hidden_separator( db: ConnectorArrowDatabase, scoped: bool From 293f906d05ea67e0f2fae07888801ba65ab0c067 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:58:42 -0800 Subject: [PATCH 13/13] fix(databases): bind SQL store operations to their selected schema --- docs/dev/design_issues/ITL-1552-CA4.md | 2 + src/orcapod/databases/_sql_store.py | 4 +- .../databases/connector_arrow_database.py | 66 ++++++++----- src/orcapod/databases/postgresql_connector.py | 24 ++--- src/orcapod/databases/sqlite_connector.py | 6 +- .../test_postgresql_connector_integration.py | 94 ++++++++++++++++++- 6 files changed, 151 insertions(+), 45 deletions(-) diff --git a/docs/dev/design_issues/ITL-1552-CA4.md b/docs/dev/design_issues/ITL-1552-CA4.md index 074d93a31..46bc77031 100644 --- a/docs/dev/design_issues/ITL-1552-CA4.md +++ b/docs/dev/design_issues/ITL-1552-CA4.md @@ -12,3 +12,5 @@ write overwrite the other's rows. PostgreSQL also refused names beyond 63 bytes. versioned catalog keeps the original paths so lookups can refuse name collisions. SQL stores normalize string subclasses before validating path components or matching prefixes, so subclass methods cannot change which path a table uses. +PostgreSQL catalog reads and flush transactions use the schema selected for the +operation, even if another connection makes an earlier search-path entry available. diff --git a/src/orcapod/databases/_sql_store.py b/src/orcapod/databases/_sql_store.py index 3f2ce7ec9..255573b72 100644 --- a/src/orcapod/databases/_sql_store.py +++ b/src/orcapod/databases/_sql_store.py @@ -39,13 +39,13 @@ def get_current_store_schema(self) -> str: ... def get_store_table_paths( - self, name: str, *, exact: bool = False + self, name: str, *, exact: bool = False, schema: str | None = None ) -> list[tuple[str, str, str]]: """Return schema, physical name and stored JSON path for each record table.""" ... def store_table_transaction( - self, table_name: str, path_json: str + self, table_name: str, path_json: str, *, schema: str ) -> AbstractContextManager[tuple[str, bool]]: """Verify or register a path and yield its schema and table existence.""" ... diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 40665790c..267caf622 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -312,30 +312,32 @@ def _deduplicate_within_table(self, table: pa.Table) -> pa.Table: # ── Committed data access ───────────────────────────────────────────────── def _find_committed_table( - self, table_name: str, full_path: tuple[str, ...] + self, table_name: str, full_path: tuple[str, ...], *, schema: str | None ) -> tuple[str | None, str] | None: """Return the verified schema and name of a committed table.""" if self._sql_store is None: if table_name in self._connector.get_table_names(): return None, table_name return None - for schema, name, path_json in self._sql_store.get_store_table_paths( - table_name, exact=True + for table_schema, name, path_json in self._sql_store.get_store_table_paths( + table_name, exact=True, schema=schema ): require_store_table_owner( table_name, self._plain_path(full_path), stored_path(table_name, path_json), ) - return schema, name + return table_schema, name return None - def _get_committed_table(self, record_path: tuple[str, ...]) -> pa.Table | None: + def _get_committed_table( + self, record_path: tuple[str, ...], *, schema: str | None + ) -> pa.Table | None: """Fetch all committed records for a path from the connector.""" full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) - table = self._find_committed_table(table_name, full_path) + table = self._find_committed_table(table_name, full_path, schema=schema) if table is None: return None schema, name = table @@ -368,14 +370,16 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] full_prefix, hint_length=_SQL_HINT_LENGTH ) owners: dict[str, tuple[str, ...]] = {} - for _, name, path_json in self._sql_store.get_store_table_paths(stem): + current_schema = self._sql_store.get_current_store_schema() + for _, name, path_json in self._sql_store.get_store_table_paths( + stem, schema=current_schema + ): path = stored_path(name, path_json) if self._path_to_table_name(path) != name: raise OrcapodDatabaseError( f"Table {name!r} does not match its stored path {path!r}" ) owners[name] = path - current_schema = self._sql_store.get_current_store_schema() for (schema, name), (_, path) in self._pending_table_owners.items(): if schema != current_schema: continue @@ -422,9 +426,10 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: record_key = self._get_record_key(record_path) if self._sql_store is None and record_key in self._pending_batches: return True - return self._find_committed_table(table_name, full_path) is not None or ( - record_key in self._pending_batches - ) + schema = self._schema_from_record_key(record_key) + return self._find_committed_table( + table_name, full_path, schema=schema + ) is not None or (record_key in self._pending_batches) # ── Storable columns ────────────────────────────────────────────────────── @@ -445,7 +450,8 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: # not be reported as a stored table that could not be read. record_key = self._get_record_key(record_path) try: - table = self._find_committed_table(table_name, full_path) + schema = self._schema_from_record_key(record_key) + table = self._find_committed_table(table_name, full_path, schema=schema) if table is None: pending = self._pending_batches.get(record_key) return None if pending is None else pending.schema @@ -602,9 +608,9 @@ def add_records( record_key = self._get_record_key(record_path) pending_owner_key: tuple[str, str] | None = None if self._sql_store is not None: - _ = self._find_committed_table(table_name, full_path) schema = self._schema_from_record_key(record_key) assert schema is not None + _ = self._find_committed_table(table_name, full_path, schema=schema) pending_owner_key = (schema, table_name) queued = self._pending_table_owners.get(pending_owner_key) if queued is not None and queued[0] != record_key: @@ -718,16 +724,17 @@ def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: if not self.keeps_field_metadata: return None held: list[pa.Schema] = [] - pending = self._pending_batches.get(self._get_record_key(record_path)) + record_key = self._get_record_key(record_path) + pending = self._pending_batches.get(record_key) if pending is not None: held.append(pending.schema) full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) - schema = self._schema_from_record_key(self._get_record_key(record_path)) + schema = self._schema_from_record_key(record_key) stored_key = (schema, table_name) stored = self._stored_schemas.get(stored_key) if stored is None: - table = self._find_committed_table(table_name, full_path) + table = self._find_committed_table(table_name, full_path, schema=schema) if table is not None: schema, name = table stored = self._read_stored_schema(name, schema) @@ -886,8 +893,8 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: def _flush_by_key(self, record_key: str) -> None: """Commit the ready records at a key shared by all views.""" + queued_schema = self._schema_from_record_key(record_key) if self._sql_store is not None: - queued_schema = self._schema_from_record_key(record_key) active_schema = self._sql_store.get_current_store_schema() if queued_schema != active_schema: raise OrcapodDatabaseError( @@ -907,13 +914,17 @@ def _flush_by_key(self, record_key: str) -> None: try: self._require_table_name(table_name) - transaction = ( - nullcontext((None, table_name in self._connector.get_table_names())) - if self._sql_store is None - else self._sql_store.store_table_transaction( - table_name, store_table_path_json(record_path).decode() + if self._sql_store is None: + transaction = nullcontext( + (None, table_name in self._connector.get_table_names()) + ) + else: + assert queued_schema is not None + transaction = self._sql_store.store_table_transaction( + table_name, + store_table_path_json(record_path).decode(), + schema=queued_schema, ) - ) with transaction as (schema, table_exists): self._write_ready_batch( record_key, table_name, pending, skip_existing, table_exists, schema @@ -1002,6 +1013,7 @@ def get_record_by_id( self.flush() record_id = coerce_record_id(record_id) record_key = self._get_record_key(record_path) + schema = self._schema_from_record_key(record_key) # Check pending first if record_id in self._pending_record_ids.get(record_key, set()): @@ -1011,12 +1023,12 @@ def get_record_by_id( if self._sql_store is not None: full_path = self._path_prefix + record_path _ = self._find_committed_table( - self._path_to_table_name(full_path), full_path + self._path_to_table_name(full_path), full_path, schema=schema ) return self._handle_record_id_column(filtered, record_id_column) # Check committed - committed = self._get_committed_table(record_path) + committed = self._get_committed_table(record_path, schema=schema) if committed is None: return None filtered = committed.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) @@ -1032,7 +1044,9 @@ def get_all_records( record_key = self._get_record_key(record_path) parts: list[pa.Table] = [] - committed = self._get_committed_table(record_path) + committed = self._get_committed_table( + record_path, schema=self._schema_from_record_key(record_key) + ) if committed is not None and committed.num_rows > 0: parts.append(committed) pending = self._pending_batches.get(record_key) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 7c453eed0..b767a955d 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -466,7 +466,7 @@ def get_table_names(self) -> list[str]: return [row[0] for row in cur.fetchall()] def get_store_table_paths( - self, name: str, *, exact: bool = False + self, name: str, *, exact: bool = False, schema: str | None = None ) -> list[tuple[str, str, str]]: """Return registered record tables matching a physical name or prefix.""" from psycopg import sql as pg_sql @@ -483,9 +483,9 @@ def get_store_table_paths( FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' - WHERE ns.nspname = current_schema() + WHERE ns.nspname = COALESCE(%s, current_schema()) """, - (STORE_PATH_CATALOG,), + (STORE_PATH_CATALOG, schema), ) row = cur.fetchone() if row is None: @@ -544,7 +544,7 @@ def get_current_store_schema(self) -> str: @contextmanager def store_table_transaction( - self, table_name: str, path_json: str + self, table_name: str, path_json: str, *, schema: str ) -> Iterator[tuple[str, bool]]: """Register and write a record table, yielding whether it already exists.""" from psycopg import sql as pg_sql @@ -558,17 +558,18 @@ def store_table_transaction( # catalog does not exist yet. 0x4F524341 is the Orcapod lock key. _ = cur.execute( """ - SELECT nspname, oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), + SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) - FROM pg_catalog.pg_namespace WHERE nspname = current_schema() + FROM pg_catalog.pg_namespace WHERE nspname = %s """, - (0x4F524341,), + (0x4F524341, schema), ) location = cur.fetchone() - if location is None or location[0] is None: - raise OrcapodDatabaseError("PostgreSQL has no current schema") - schema = cast(str, location[0]) - _require_persistent_store_schema(schema, location[1]) + if location is None: + raise OrcapodDatabaseError( + f"PostgreSQL store schema {schema!r} no longer exists" + ) + _require_persistent_store_schema(schema, location[0]) catalog = pg_sql.Identifier(schema, STORE_PATH_CATALOG) fields = pg_sql.SQL(STORE_PATH_CATALOG_FIELDS).format( layout_version=pg_sql.Literal(STORE_PATH_LAYOUT_VERSION) @@ -739,7 +740,6 @@ def get_column_info( self._require_table_name(table_name) with self._lock: conn = self._require_open() - self._validate_table_name(table_name) with conn.transaction(force_rollback=True), conn.cursor() as cur: cur.execute( """ diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index fb31e7727..684de8bb7 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -303,9 +303,10 @@ def get_table_names(self) -> list[str]: return [row["name"] for row in cursor] def get_store_table_paths( - self, name: str, *, exact: bool = False + self, name: str, *, exact: bool = False, schema: str | None = None ) -> list[tuple[str, str, str]]: """Return registered record tables matching a physical name or prefix.""" + assert schema in (None, "main") with self._lock: conn = self._require_open() if ( @@ -350,9 +351,10 @@ def get_current_store_schema(self) -> str: @contextmanager def store_table_transaction( - self, table_name: str, path_json: str + self, table_name: str, path_json: str, *, schema: str ) -> Iterator[tuple[str, bool]]: """Register and write a record table, yielding whether it already exists.""" + assert schema == "main" with self._lock: conn = self._require_open() _ = conn.execute("BEGIN IMMEDIATE") diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 6de6b676d..9e8006978 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -26,6 +26,7 @@ import uuid from collections.abc import Iterator from typing import cast +from unittest.mock import DEFAULT, patch import psycopg import pyarrow as pa @@ -246,9 +247,24 @@ def test_nonexistent_table_returns_empty( ) -> None: assert connector.get_column_info("no_such_table") == [] - def test_raises_on_invalid_table_name(self, connector: PostgreSQLConnector) -> None: - with pytest.raises(ValueError, match="double-quote"): - connector.get_column_info('bad"name') + def test_accepts_a_decoded_quoted_table_name( + self, connector: PostgreSQLConnector + ) -> None: + _, _, _, schema = connector.current_location() + table = sql.Identifier(schema, 'order"items') + conn = connector._require_open() + _ = conn.execute( + sql.SQL("CREATE TABLE {} (value BIGINT NOT NULL)").format(table) + ) + _ = conn.execute(sql.SQL("INSERT INTO {} VALUES (7)").format(table)) + conn.commit() + + query = sql.SQL("SELECT value FROM {}").format(table).as_string(conn) + batches = list(connector.iter_batches(query)) + + assert len(batches) == 1 + assert batches[0].schema == pa.schema([pa.field("value", pa.int64(), False)]) + assert batches[0].column(0).to_pylist() == [7] def test_array_column(self, connector: PostgreSQLConnector) -> None: with connector._conn.cursor() as cur: @@ -977,6 +993,78 @@ def test_pending_rows_remain_bound_to_their_postgresql_schema( ) +@pytest.mark.postgres +@pytest.mark.parametrize("operation", ["read", "flush"]) +def test_store_uses_the_queued_schema_when_a_preferred_schema_appears( + connector: PostgreSQLConnector, operation: str +) -> None: + base_dsn = _base_dsn() + preferred = f"preferred_{uuid.uuid4().hex[:12]}" + fallback = connector.get_current_store_schema() + conn = connector._require_open() + _ = conn.execute( + sql.SQL("SET search_path TO {}, {}").format( + sql.Identifier(preferred), sql.Identifier(fallback) + ) + ) + conn.commit() + db = ConnectorArrowDatabase(connector) + path = ("same",) + db.add_record(path, b"stored", pa.table({"value": [1]}), flush=True) + db.add_record(path, b"queued", pa.table({"value": [2]})) + + def create_preferred_schema(*_args: object, **_kwargs: object) -> object: + with psycopg.connect(base_dsn, autocommit=True) as admin: + _ = admin.execute( + sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(preferred)) + ) + with PostgreSQLConnector( + f"{base_dsn} options=-csearch_path={preferred}" + ) as other: + ConnectorArrowDatabase(other).add_record( + path, b"queued", pa.table({"value": [3]}), flush=True + ) + return DEFAULT + + try: + if operation == "read": + with patch.object( + connector, + "get_store_table_paths", + wraps=connector.get_store_table_paths, + side_effect=create_preferred_schema, + ): + rows = db.get_all_records(path) + assert rows is not None and rows.to_pylist() == [{"value": 1}, {"value": 2}] + else: + with patch.object( + connector, + "store_table_transaction", + wraps=connector.store_table_transaction, + side_effect=create_preferred_schema, + ): + db.flush() + rows = db.get_all_records(path) + assert rows is not None and rows.to_pylist() == [{"value": 3}] + _ = conn.execute( + sql.SQL("SET search_path TO {}").format(sql.Identifier(fallback)) + ) + rows = db.get_all_records(path, record_id_column="id") + assert rows is not None + assert {row["id"]: row["value"] for row in rows.to_pylist()} == { + b"stored": 1, + b"queued": 2, + } + finally: + conn.rollback() + with psycopg.connect(base_dsn, autocommit=True) as admin: + _ = admin.execute( + sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format( + sql.Identifier(preferred) + ) + ) + + @pytest.mark.postgres def test_store_writes_to_the_verified_schema_when_a_temp_table_shadows_its_name( connector: PostgreSQLConnector,