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/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 68672e28c..0515f10ac 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). @@ -265,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/docs/dev/design_issues/ITL-1552-CA4.md b/docs/dev/design_issues/ITL-1552-CA4.md new file mode 100644 index 000000000..46bc77031 --- /dev/null +++ b/docs/dev/design_issues/ITL-1552-CA4.md @@ -0,0 +1,16 @@ +## `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. +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/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 4c9a4af72..b7f57e38b 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..255573b72 --- /dev/null +++ b/src/orcapod/databases/_sql_store.py @@ -0,0 +1,140 @@ +"""Catalog contract for SQLite and PostgreSQL connector stores.""" + +from __future__ import annotations + +import json +from contextlib import AbstractContextManager +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 +# 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 +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, 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, *, schema: str + ) -> 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.""" + ... + + +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 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: + 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..267caf622 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -21,18 +21,30 @@ 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, first_logical_identity_change, in_held_column_order, + sql_table_identifier, ) from orcapod.errors import ( InputValidationError, @@ -51,6 +63,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 +111,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 @@ -117,10 +134,16 @@ 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: self._connector = connector + self._sql_store: SQLStoreConnector | None = ( + connector if isinstance(connector, SQLStoreConnector) else None + ) self.max_hierarchy_depth = max_hierarchy_depth self._path_prefix = _path_prefix self._root = _root @@ -135,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. @@ -144,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 @@ -157,21 +190,47 @@ 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) + full_path = self._plain_path(self._path_prefix + record_path) + if self._sql_store is None: + 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 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 _path_to_table_name(self, record_path: tuple[str, ...]) -> str: - """Map a record_path to a safe SQL table name. + 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("/")) - 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. - """ + 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( + self._plain_path(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(): @@ -187,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')" ) @@ -249,13 +311,41 @@ def _deduplicate_within_table(self, table: pa.Table) -> pa.Table: # ── Committed data access ───────────────────────────────────────────────── - def _get_committed_table(self, record_path: tuple[str, ...]) -> pa.Table | None: + def _find_committed_table( + 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 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 table_schema, name + return 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.""" - 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(): + table = self._find_committed_table(table_name, full_path, schema=schema) + 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) @@ -263,17 +353,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,9 +364,36 @@ 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: + full_prefix = self._plain_path(full_prefix) + stem = STORE_TABLE_NAME_PREFIX + table_name_hint( + full_prefix, hint_length=_SQL_HINT_LENGTH + ) + owners: dict[str, tuple[str, ...]] = {} + 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 + for (schema, name), (_, path) in self._pending_table_owners.items(): + if schema != current_schema: + continue + if path[: len(full_prefix)] == full_prefix: + require_store_table_owner(name, path, owners.setdefault(name, path)) + return sorted( + path[len(self._path_prefix) :] + for path in owners.values() + if path[: len(full_prefix)] == full_prefix + ) + 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 "" @@ -311,12 +420,16 @@ 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() + 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 ────────────────────────────────────────────────────── @@ -324,18 +437,28 @@ 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: - if table_name not in self._connector.get_table_names(): - pending = self._pending_batches.get(self._get_record_key(record_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 + 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 @@ -440,6 +563,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 @@ -474,13 +599,24 @@ 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) records = normalize_table_to_large_types(records, keep_null=True) 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: + 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: + 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). @@ -524,6 +660,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( @@ -555,19 +697,23 @@ def _held_column_order( return list(pending.schema) return None - def _stored_columns(self, table_name: 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(): - return None + 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( c.name, 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: @@ -578,15 +724,22 @@ 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) - table_name = self._path_to_table_name(self._path_prefix + record_path) - stored = self._stored_schemas.get(table_name) - if stored is None and table_name in self._connector.get_table_names(): - stored = self._read_stored_schema(table_name) - if stored is not None: - self._stored_schemas[table_name] = stored + full_path = self._path_prefix + record_path + table_name = self._path_to_table_name(full_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, schema=schema) + if table is not None: + schema, name = table + stored = self._read_stored_schema(name, schema) + if stored is not None: + self._stored_schemas[stored_key] = stored if stored is not None: held.append(stored) return held @@ -627,7 +780,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`` @@ -637,7 +792,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 @@ -651,8 +811,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: @@ -660,16 +819,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( @@ -679,6 +831,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, ) @@ -739,58 +893,92 @@ 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: + 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) - 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." + 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 + ) + except BaseException: + self._pending_commits.finish(record_key, committed=False) + raise + else: + self._pending_commits.finish(record_key, committed=True) + finally: + self._pending_commits.forget(record_key, ids) + + def _write_ready_batch( + self, + record_key: str, + table_name: str, + 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, 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)) + 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())) + + "}" ) - # 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) + 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) + if self._sql_store is None: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN ) @@ -800,13 +988,17 @@ def _fmt(cols: dict) -> str: id_column=self.RECORD_ID_COLUMN, skip_existing=skip_existing, ) - except BaseException: - self._pending_commits.finish(record_key, committed=False) - raise else: - self._pending_commits.finish(record_key, committed=True) - finally: - self._pending_commits.forget(record_key, ids) + 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 ────────────────────────────────────────────────────────── @@ -821,16 +1013,22 @@ 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()): 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, 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) @@ -846,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 0417c04c5..b767a955d 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -20,12 +20,28 @@ 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.utils import is_direct_projection -from orcapod.errors import UnstorableTableNameError +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_layout, + require_catalog_pair, +) +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 @@ -258,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", @@ -281,22 +307,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 = _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"). @@ -312,7 +332,24 @@ 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=_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: @@ -392,6 +429,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 ────────────────────────────────────────────────────── @@ -415,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 @@ -427,6 +465,173 @@ 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, 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 + + conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) + # 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, + 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 + LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid + AND rel.relname = %s AND rel.relkind = 'r' + WHERE ns.nspname = COALESCE(%s, current_schema()) + """, + (STORE_PATH_CATALOG, schema), + ) + row = cur.fetchone() + 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) + match = pg_sql.SQL("= %s" if exact else "LIKE %s ESCAPE '!'") + _ = cur.execute( + pg_sql.SQL(""" + SELECT paths.table_name, paths.entry_value, paths.layout_version, + physical.oid IS NOT NULL + FROM {catalog} AS paths + 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), + ( + row[1], + name if exact else catalog_name_pattern(name), + TABLE_PATH_ENTRY_KIND, + ), + ) + paths: list[tuple[str, str, str]] = [] + for table_name, path_json, version, exists in cast( + "list[tuple[str, str, int, bool]]", cur.fetchall() + ): + 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(force_rollback=True), 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, *, schema: str + ) -> Iterator[tuple[str, 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 + 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 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 = %s + """, + (0x4F524341, schema), + ) + location = cur.fetchone() + 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) + ) + _ = cur.execute( + pg_sql.SQL("CREATE TABLE IF NOT EXISTS {} {}").format( + catalog, fields + ) + ) + catalog = pg_sql.Identifier( + schema.replace("%", "%%"), STORE_PATH_CATALOG + ) + _ = cur.execute( + pg_sql.SQL(""" + 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 = %s AND rel.relname = %s + """, + (schema, 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, 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 schema, physical is not None + 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. @@ -448,7 +653,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: @@ -510,7 +715,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 @@ -528,22 +733,23 @@ 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: 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 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( @@ -631,6 +837,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) @@ -649,15 +857,17 @@ 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: 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( @@ -666,6 +876,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) @@ -693,17 +905,22 @@ 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 "{table_name}" ({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()) 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..684de8bb7 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -19,11 +19,27 @@ 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.utils import is_direct_projection +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_layout, + require_catalog_pair, +) +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 logger = logging.getLogger(__name__) @@ -286,6 +302,118 @@ 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, 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 ( + 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.entry_value, paths.layout_version, + physical.name IS NOT NULL + FROM main."{STORE_PATH_CATALOG}" AS paths + 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 = '' + """, + ( + name if exact else catalog_name_pattern(name), + TABLE_PATH_ENTRY_KIND, + ), + ), + ) + paths: list[tuple[str, str, str]] = [] + for row in rows: + table_name = cast(str, row[0]) + 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, *, 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") + 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}" {fields}' + ) + row = cast( + "sqlite3.Row | None", + conn.execute( + f""" + 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( + "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, entry_kind, entry_name, entry_value, layout_version) + VALUES (?, ?, '', ?, ?) + """, + ( + table_name, + TABLE_PATH_ENTRY_KIND, + path_json, + STORE_PATH_LAYOUT_VERSION, + ), + ) + yield "main", physical is not None + 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. @@ -302,19 +430,31 @@ 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. """ + 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() - 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({sql_table_identifier(table_name)})" + ) return [ ColumnInfo( name=row["name"], @@ -349,8 +489,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 @@ -372,15 +510,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 @@ -422,6 +566,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. @@ -429,6 +575,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: @@ -445,7 +592,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) @@ -456,6 +603,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. @@ -467,6 +616,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() @@ -475,7 +625,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/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/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/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_append_by_name.py b/tests/test_databases/test_append_by_name.py index 8cb22a0f0..fe428e867 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, TABLE_PATH_ENTRY_KIND 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( @@ -596,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 @@ -606,18 +604,35 @@ 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", 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 (names.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 (names.call_count, info.call_count) == (1, 1) + assert (catalog.call_count, registration.call_count, info.call_count) == ( + 2, + 1, + 1, + ) db.flush() - assert (names.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] ) @@ -639,9 +654,31 @@ 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}" WHERE entry_kind = ?', + (TABLE_PATH_ENTRY_KIND,), + ).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 +693,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 +717,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 +736,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 @@ -708,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( { @@ -722,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_table_names", 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_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 489905221..9e8006978 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -25,13 +25,24 @@ import os import uuid from collections.abc import Iterator +from typing import cast +from unittest.mock import DEFAULT, patch 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.errors import OrcapodDatabaseError from orcapod.types import ColumnInfo +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, check_result_lookup_timestamp_tie, @@ -236,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: @@ -589,7 +615,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 @@ -608,32 +634,526 @@ 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: + """Keep separate tables even when PostgreSQL would truncate the old names.""" + db = ConnectorArrowDatabase(connector) + 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] + + +@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: - """A table name PostgreSQL would truncate is never sent to it (ITL-1162).""" - from orcapod.errors import UnstorableTableNameError + _, _, _, primary = connector.current_location() + 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(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( + 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} + ] + _ = 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", "pending_point", "queue", "flush"] +) +def test_unsupported_catalog_layout_is_refused( + connector: PostgreSQLConnector, operation: str +) -> None: 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() == [] + path = ("versioned",) + one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) + db.add_record(path, b"id", one, flush=True) + if operation in ("flush", "pending_point"): + 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_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 +@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, +) -> 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 +@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)") + + assert db.list_table_paths() == [path] + _check_catalog_can_be_locked(connector) + + 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 +@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, +) -> 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 +@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 +) -> 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 6720ea0cb..32dc4dac9 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -2,12 +2,18 @@ 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.protocols.db_connector_protocol import DBConnectorProtocol +from orcapod.types import ColumnInfo @pytest.fixture @@ -18,7 +24,366 @@ 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("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 +) -> 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 + ) -> 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(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.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_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: + 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", "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 in ("flush", "pending_point"): + 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,) + + 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 + ) -> 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 = [ + 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_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). @@ -116,3 +481,62 @@ 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.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) + assert rows is not None and rows.equals(one) + + +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": + 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) + 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", + ) 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..3be9da8ff --- /dev/null +++ b/tests/test_databases/test_store_table_names.py @@ -0,0 +1,43 @@ +"""Tests for the shared connector store table names.""" + +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 + + 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..288db7f32 100644 --- a/tests/test_databases/test_unstorable_columns.py +++ b/tests/test_databases/test_unstorable_columns.py @@ -536,6 +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() + 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 @@ -751,30 +765,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 +802,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 +818,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 +860,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", }