|
| 1 | +"""Issue #203 — ObjectManager honors ``field.timestamp @autoSet: onCreate|onUpdate``. |
| 2 | +
|
| 3 | +The runtime write path (``create`` / ``update`` / ``insert_preserving``) owns |
| 4 | +the ``now()`` stamping so adopters stop hand-writing it in every repository. The |
| 5 | +contract (identical across ports): |
| 6 | +
|
| 7 | +* ``create`` — stamps EVERY ``onCreate`` AND ``onUpdate`` column with a single |
| 8 | + shared ``now()`` (the caller's value is ignored; a fresh row's updated == |
| 9 | + created). |
| 10 | +* ``update`` — stamps ``onUpdate`` with ``now()`` and NEVER writes an |
| 11 | + ``onCreate`` column (stripped even when the caller supplies one — the |
| 12 | + lost-update guard). |
| 13 | +* ``insert_preserving`` — the escape hatch: writes the ``@autoSet`` columns |
| 14 | + VERBATIM (import / restore / replication paths that must keep the original |
| 15 | + timestamps). |
| 16 | +* ``now()`` is keyed off the COLUMN's temporal type (``field.timestamp`` → |
| 17 | + datetime, tz-aware unless ``@localTime``; ``field.date`` → date). |
| 18 | +
|
| 19 | +White-box: a fake driver captures the emitted INSERT/UPDATE SQL + bound params |
| 20 | +so the stamping is asserted without a database. |
| 21 | +""" |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import json |
| 25 | +import re |
| 26 | +from datetime import date, datetime |
| 27 | +from typing import Any |
| 28 | + |
| 29 | +from metaobjects import load_string |
| 30 | +from metaobjects.runtime import ObjectManager |
| 31 | +from metaobjects.runtime.object_manager import SelectResult |
| 32 | + |
| 33 | +# BaseAudit carries the @autoSet timestamps; Doc INHERITS them via extends — the |
| 34 | +# issue's exact real-world shape (declared once on a base, inherited everywhere). |
| 35 | +# Plain has no @autoSet (proves byte-identical behavior for non-@autoSet entities). |
| 36 | +# DateDoc exercises a non-timestamp temporal (field.date) @autoSet column. |
| 37 | +_META = { |
| 38 | + "metadata.root": { |
| 39 | + "package": "t", |
| 40 | + "children": [ |
| 41 | + { |
| 42 | + "object.entity": { |
| 43 | + "name": "BaseAudit", |
| 44 | + "abstract": True, |
| 45 | + "children": [ |
| 46 | + {"field.timestamp": {"name": "createdAt", "@autoSet": "onCreate"}}, |
| 47 | + {"field.timestamp": {"name": "updatedAt", "@autoSet": "onUpdate"}}, |
| 48 | + ], |
| 49 | + } |
| 50 | + }, |
| 51 | + { |
| 52 | + "object.entity": { |
| 53 | + "name": "Doc", |
| 54 | + "extends": "BaseAudit", |
| 55 | + "children": [ |
| 56 | + {"source.rdb": {"@table": "docs"}}, |
| 57 | + {"field.long": {"name": "id"}}, |
| 58 | + {"field.string": {"name": "title", "@required": True}}, |
| 59 | + # @localTime opt-out → naive wall-clock stamp (no tzinfo). |
| 60 | + {"field.timestamp": {"name": "touchedAt", "@autoSet": "onUpdate", "@localTime": True}}, |
| 61 | + {"identity.primary": {"name": "id", "@fields": ["id"]}}, |
| 62 | + ], |
| 63 | + } |
| 64 | + }, |
| 65 | + { |
| 66 | + "object.entity": { |
| 67 | + "name": "Plain", |
| 68 | + "children": [ |
| 69 | + {"source.rdb": {"@table": "plains"}}, |
| 70 | + {"field.long": {"name": "id"}}, |
| 71 | + {"field.string": {"name": "name"}}, |
| 72 | + {"identity.primary": {"name": "id", "@fields": ["id"]}}, |
| 73 | + ], |
| 74 | + } |
| 75 | + }, |
| 76 | + { |
| 77 | + "object.entity": { |
| 78 | + "name": "DateDoc", |
| 79 | + "children": [ |
| 80 | + {"source.rdb": {"@table": "datedocs"}}, |
| 81 | + {"field.long": {"name": "id"}}, |
| 82 | + {"field.date": {"name": "createdOn", "@autoSet": "onCreate"}}, |
| 83 | + {"identity.primary": {"name": "id", "@fields": ["id"]}}, |
| 84 | + ], |
| 85 | + } |
| 86 | + }, |
| 87 | + ], |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | + |
| 92 | +class FakeWriteDriver: |
| 93 | + """Captures the write SQL + params; returns a canned single-row result so the |
| 94 | + ObjectManager's RETURNING-row mapping does not crash.""" |
| 95 | + |
| 96 | + def __init__(self) -> None: |
| 97 | + self.inserts: list[tuple[str, tuple[Any, ...]]] = [] |
| 98 | + self.updates: list[tuple[str, tuple[Any, ...]]] = [] |
| 99 | + |
| 100 | + def insert_returning(self, sql: str, params: tuple[Any, ...] = ()) -> SelectResult: |
| 101 | + self.inserts.append((sql, params)) |
| 102 | + return SelectResult([{"id": 1}], {}) |
| 103 | + |
| 104 | + def update_returning(self, sql: str, params: tuple[Any, ...] = ()) -> SelectResult: |
| 105 | + self.updates.append((sql, params)) |
| 106 | + return SelectResult([{"id": 1}], {}) |
| 107 | + |
| 108 | + def select(self, sql: str, params: tuple[Any, ...] = ()) -> SelectResult: # pragma: no cover |
| 109 | + return SelectResult([{"id": 1}], {}) |
| 110 | + |
| 111 | + def scalar(self, sql: str, params: tuple[Any, ...] = ()) -> Any: # pragma: no cover |
| 112 | + return None |
| 113 | + |
| 114 | + def execute_rowcount(self, sql: str, params: tuple[Any, ...] = ()) -> int: # pragma: no cover |
| 115 | + return 1 |
| 116 | + |
| 117 | + |
| 118 | +def _om() -> tuple[ObjectManager, FakeWriteDriver]: |
| 119 | + root = load_string(json.dumps(_META)).root |
| 120 | + driver = FakeWriteDriver() |
| 121 | + return ObjectManager(root, driver), driver # type: ignore[arg-type] |
| 122 | + |
| 123 | + |
| 124 | +def _insert_cols(sql: str, params: tuple[Any, ...]) -> dict[str, Any]: |
| 125 | + """Map INSERT column → bound param.""" |
| 126 | + m = re.search(r'INSERT INTO "[^"]+" \(([^)]*)\) VALUES', sql) |
| 127 | + assert m is not None, sql |
| 128 | + cols = [c.strip().strip('"') for c in m.group(1).split(",")] |
| 129 | + return dict(zip(cols, params)) |
| 130 | + |
| 131 | + |
| 132 | +def _update_set(sql: str, params: tuple[Any, ...]) -> dict[str, Any]: |
| 133 | + """Map UPDATE SET column → bound param (WHERE/pk params excluded).""" |
| 134 | + m = re.search(r"\bSET (.*?) WHERE ", sql) |
| 135 | + assert m is not None, sql |
| 136 | + cols = re.findall(r'"([^"]+)" = %s', m.group(1)) |
| 137 | + return dict(zip(cols, params[: len(cols)])) |
| 138 | + |
| 139 | + |
| 140 | +# --- create ----------------------------------------------------------------- |
| 141 | + |
| 142 | + |
| 143 | +def test_create_stamps_both_oncreate_and_onupdate_equal() -> None: |
| 144 | + om, d = _om() |
| 145 | + om.create("Doc", {"title": "hello"}) |
| 146 | + cols = _insert_cols(*d.inserts[0]) |
| 147 | + assert isinstance(cols["createdAt"], datetime) |
| 148 | + assert isinstance(cols["updatedAt"], datetime) |
| 149 | + # A fresh row's updated timestamp equals its created one (single shared now()). |
| 150 | + assert cols["createdAt"] == cols["updatedAt"] |
| 151 | + |
| 152 | + |
| 153 | +def test_create_ignores_caller_supplied_autoset_values() -> None: |
| 154 | + om, d = _om() |
| 155 | + om.create("Doc", {"title": "x", "createdAt": "2000-01-01T00:00:00Z", "updatedAt": "2000-01-01T00:00:00Z"}) |
| 156 | + cols = _insert_cols(*d.inserts[0]) |
| 157 | + # The stale caller value is overridden with a fresh now(), not persisted. |
| 158 | + assert cols["createdAt"].year != 2000 |
| 159 | + assert cols["createdAt"] == cols["updatedAt"] |
| 160 | + |
| 161 | + |
| 162 | +def test_create_localtime_is_naive_default_is_tzaware() -> None: |
| 163 | + om, d = _om() |
| 164 | + om.create("Doc", {"title": "x"}) |
| 165 | + cols = _insert_cols(*d.inserts[0]) |
| 166 | + # Default field.timestamp is instant / tz-aware; @localTime opts into naive. |
| 167 | + assert cols["createdAt"].tzinfo is not None |
| 168 | + assert cols["touchedAt"].tzinfo is None |
| 169 | + |
| 170 | + |
| 171 | +def test_create_date_autoset_stamped_as_date() -> None: |
| 172 | + om, d = _om() |
| 173 | + om.create("DateDoc", {}) |
| 174 | + cols = _insert_cols(*d.inserts[0]) |
| 175 | + # field.date now() is a date, not a datetime (keyed off the column's type). |
| 176 | + assert isinstance(cols["createdOn"], date) |
| 177 | + assert not isinstance(cols["createdOn"], datetime) |
| 178 | + |
| 179 | + |
| 180 | +# --- update ----------------------------------------------------------------- |
| 181 | + |
| 182 | + |
| 183 | +def test_update_bumps_onupdate_and_skips_oncreate() -> None: |
| 184 | + om, d = _om() |
| 185 | + om.update("Doc", 1, {"title": "new"}) |
| 186 | + setmap = _update_set(*d.updates[0]) |
| 187 | + assert isinstance(setmap["updatedAt"], datetime) |
| 188 | + assert isinstance(setmap["touchedAt"], datetime) |
| 189 | + # created_at is write-once: never in the UPDATE SET clause. |
| 190 | + assert "createdAt" not in setmap |
| 191 | + |
| 192 | + |
| 193 | +def test_update_strips_caller_supplied_createdAt() -> None: |
| 194 | + om, d = _om() |
| 195 | + # A full-row update carrying a stale createdAt must NOT rewrite it (lost-update guard). |
| 196 | + om.update("Doc", 1, {"title": "new", "createdAt": "2000-01-01T00:00:00Z"}) |
| 197 | + setmap = _update_set(*d.updates[0]) |
| 198 | + assert "createdAt" not in setmap |
| 199 | + |
| 200 | + |
| 201 | +def test_update_overrides_caller_supplied_updatedAt() -> None: |
| 202 | + om, d = _om() |
| 203 | + om.update("Doc", 1, {"updatedAt": "2000-01-01T00:00:00Z"}) |
| 204 | + setmap = _update_set(*d.updates[0]) |
| 205 | + assert isinstance(setmap["updatedAt"], datetime) |
| 206 | + # Server owns updated_at — the caller's stale value is replaced with now(). |
| 207 | + assert setmap["updatedAt"].year != 2000 |
| 208 | + |
| 209 | + |
| 210 | +# --- insert_preserving (escape hatch) --------------------------------------- |
| 211 | + |
| 212 | + |
| 213 | +def test_insert_preserving_writes_autoset_verbatim() -> None: |
| 214 | + om, d = _om() |
| 215 | + om.insert_preserving( |
| 216 | + "Doc", |
| 217 | + {"title": "x", "createdAt": "2000-01-01T00:00:00Z", "updatedAt": "2001-02-03T04:05:06Z"}, |
| 218 | + ) |
| 219 | + cols = _insert_cols(*d.inserts[0]) |
| 220 | + # Verbatim: the caller's original instants are preserved (no now() stamping). |
| 221 | + assert cols["createdAt"].year == 2000 |
| 222 | + assert cols["updatedAt"].year == 2001 |
| 223 | + |
| 224 | + |
| 225 | +# --- non-@autoSet entity: byte-identical (no behavior change) --------------- |
| 226 | + |
| 227 | + |
| 228 | +def test_entity_without_autoset_is_unchanged_on_create() -> None: |
| 229 | + om, d = _om() |
| 230 | + om.create("Plain", {"id": 5, "name": "n"}) |
| 231 | + cols = _insert_cols(*d.inserts[0]) |
| 232 | + assert set(cols.keys()) == {"id", "name"} |
| 233 | + |
| 234 | + |
| 235 | +def test_entity_without_autoset_is_unchanged_on_update() -> None: |
| 236 | + om, d = _om() |
| 237 | + om.update("Plain", 5, {"name": "n2"}) |
| 238 | + setmap = _update_set(*d.updates[0]) |
| 239 | + assert set(setmap.keys()) == {"name"} |
0 commit comments