fix(focus): bind uuid, jsonb, and timestamptz on Postgres

This commit is contained in:
kert
2026-11-14 11:47:27 -05:00
parent 8bd413fe44
commit 7c878b3fc8
3 changed files with 176 additions and 13 deletions

View File

@@ -10,8 +10,10 @@ from __future__ import annotations
from sqlalchemy import event, text
from sqlalchemy.engine import Engine
#: Live DDL. Column types match the plan; ``store`` inserts string uuids
#: and lets Postgres coerce them.
#: Live DDL. Column types match the plan. ``store`` binds ``uuid``,
#: ``jsonb`` and ``timestamptz`` on Postgres: psycopg3 casts a String
#: parameter as varchar, which Postgres will not coerce into those
#: columns. SQLite keeps text and JSON.
POSTGRES_DDL = """
CREATE TABLE IF NOT EXISTS focus_annotation (
id uuid PRIMARY KEY,

View File

@@ -15,6 +15,7 @@ from typing import Any
from sqlalchemy import (
JSON,
Column,
DateTime,
Integer,
MetaData,
String,
@@ -22,19 +23,82 @@ from sqlalchemy import (
select,
update,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.engine import Connection, Engine
from sqlalchemy.types import TypeDecorator
from focus.protocols import Protocol, load
KINDS = ("responds_to", "supports", "contradicts")
PROVENANCE = ("human", "model")
class _UuidStr(TypeDecorator):
"""UUID text in Python. Postgres binds the native ``uuid`` type.
A ``String`` column is sent as varchar. Postgres rejects that for a
``uuid`` column instead of coercing it.
"""
impl = String
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == "postgresql":
return dialect.type_descriptor(PG_UUID(as_uuid=False))
return dialect.type_descriptor(String())
def process_result_value(self, value, dialect):
if value is None:
return None
return str(value)
class _IsoTimestamp(TypeDecorator):
"""ISO-8601 text in Python. Postgres binds ``timestamptz``."""
impl = String
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == "postgresql":
return dialect.type_descriptor(DateTime(timezone=True))
return dialect.type_descriptor(String())
def process_bind_param(self, value, dialect):
if value is None or dialect.name != "postgresql":
return value
if isinstance(value, dt.datetime):
parsed = value
else:
parsed = dt.datetime.fromisoformat(value)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=dt.timezone.utc)
return parsed
def process_result_value(self, value, dialect):
return _iso(value)
class _JsonDoc(TypeDecorator):
"""JSON in Python. Postgres binds ``jsonb`` to match the live DDL."""
impl = JSON
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == "postgresql":
return dialect.type_descriptor(JSONB())
return dialect.type_descriptor(JSON())
_meta = MetaData()
annotation = Table(
"focus_annotation",
_meta,
Column("id", String, primary_key=True),
Column("id", _UuidStr, primary_key=True),
Column("item_key", String, nullable=False),
Column("attachment", String, nullable=False),
Column("protocol", String, nullable=False),
@@ -46,35 +110,35 @@ annotation = Table(
Column("start_char", Integer),
Column("end_char", Integer),
Column("page", Integer),
Column("rects", JSON),
Column("rects", _JsonDoc),
Column("note", String, nullable=False),
Column("actor", String, nullable=False),
Column("provenance", String, nullable=False),
Column("model", String),
Column("created_at", String, nullable=False),
Column("deleted_at", String),
Column("created_at", _IsoTimestamp, nullable=False),
Column("deleted_at", _IsoTimestamp),
)
link_table = Table(
"focus_link",
_meta,
Column("from_id", String, primary_key=True),
Column("to_id", String, primary_key=True),
Column("from_id", _UuidStr, primary_key=True),
Column("to_id", _UuidStr, primary_key=True),
Column("kind", String, primary_key=True),
Column("actor", String, nullable=False),
Column("created_at", String, nullable=False),
Column("deleted_at", String),
Column("created_at", _IsoTimestamp, nullable=False),
Column("deleted_at", _IsoTimestamp),
)
event = Table(
"focus_event",
_meta,
Column("id", Integer, primary_key=True),
Column("annotation_id", String, nullable=False),
Column("annotation_id", _UuidStr, nullable=False),
Column("op", String, nullable=False),
Column("payload", JSON, nullable=False),
Column("payload", _JsonDoc, nullable=False),
Column("actor", String, nullable=False),
Column("at", String, nullable=False),
Column("at", _IsoTimestamp, nullable=False),
)

View File

@@ -91,6 +91,103 @@ def test_ensure_postgres_branch_uses_the_live_types():
assert "jsonb" in joined and "timestamptz" in joined
def test_postgres_binds_match_the_live_column_types():
"""psycopg3 casts String as varchar. The live columns are uuid/jsonb/
timestamptz, and Postgres does not coerce those."""
from sqlalchemy.dialects import postgresql
from focus.store import annotation, event, link_table
dialect = postgresql.dialect()
ann_sql = str(
annotation.insert()
.values(
id="00000000-0000-4000-8000-000000000001",
item_key=KEY,
attachment="",
protocol="comment-stance",
protocol_version=1,
label="support",
quote="q",
prefix="",
suffix="",
start_char=None,
end_char=None,
page=1,
rects=[{"x": 1}],
note="",
actor="kert",
provenance="human",
model=None,
created_at="2026-11-14T00:00:00+00:00",
deleted_at=None,
)
.compile(dialect=dialect)
)
assert "%(id)s::UUID" in ann_sql
assert "%(rects)s::JSONB" in ann_sql
assert "%(created_at)s::TIMESTAMP WITH TIME ZONE" in ann_sql
assert "%(deleted_at)s::TIMESTAMP WITH TIME ZONE" in ann_sql
assert "%(id)s::VARCHAR" not in ann_sql
event_sql = str(
event.insert()
.values(
annotation_id="00000000-0000-4000-8000-000000000001",
op="add",
payload={"label": "support"},
actor="kert",
at="2026-11-14T00:00:00+00:00",
)
.compile(dialect=dialect)
)
assert "%(annotation_id)s::UUID" in event_sql
assert "%(payload)s::JSONB" in event_sql
assert "%(at)s::TIMESTAMP WITH TIME ZONE" in event_sql
assert "%(id)s" not in event_sql
link_sql = str(
link_table.insert()
.values(
from_id="00000000-0000-4000-8000-000000000001",
to_id="00000000-0000-4000-8000-000000000002",
kind="supports",
actor="kert",
created_at="2026-11-14T00:00:00+00:00",
deleted_at=None,
)
.compile(dialect=dialect)
)
assert "%(from_id)s::UUID" in link_sql
assert "%(to_id)s::UUID" in link_sql
assert "%(created_at)s::TIMESTAMP WITH TIME ZONE" in link_sql
def test_iso_timestamp_bind_and_result_cover_postgres_and_text():
from focus.store import _IsoTimestamp, _UuidStr
stamps = _IsoTimestamp()
pg = MagicMock()
pg.name = "postgresql"
other = MagicMock()
other.name = "sqlite"
assert stamps.process_bind_param(None, pg) is None
assert stamps.process_bind_param("keep", other) == "keep"
aware = dt.datetime(2026, 1, 2, 3, 4, 5, tzinfo=dt.timezone.utc)
assert stamps.process_bind_param(aware, pg) is aware
naive = stamps.process_bind_param("2026-01-02T03:04:05", pg)
assert naive.tzinfo is not None
bound = stamps.process_bind_param("2026-01-02T03:04:05+00:00", pg)
assert bound == aware
assert stamps.process_result_value(None, pg) is None
assert stamps.process_result_value(aware, pg) == "2026-01-02T03:04:05+00:00"
assert _UuidStr().process_result_value(None, pg) is None
assert (
_UuidStr().process_result_value("00000000-0000-4000-8000-000000000001", other)
== "00000000-0000-4000-8000-000000000001"
)
def test_iso_normalises_datetimes_and_text():
aware = dt.datetime(2026, 1, 2, 3, 4, 5, tzinfo=dt.timezone.utc)
naive = dt.datetime(2026, 1, 2, 3, 4, 5)