@reventlessdev/reventless-postgres 3.0.0-alpha.4 → 3.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/lib/bs/.compiler.log +2 -2
  3. package/lib/bs/ReventlessPostgres.cmi +0 -0
  4. package/lib/bs/ReventlessPostgres.cmt +0 -0
  5. package/lib/bs/ReventlessPostgres.mlmap +1 -0
  6. package/lib/bs/compiler-info.json +1 -1
  7. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  8. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  9. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
  10. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
  11. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  12. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  13. package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmi +0 -0
  14. package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmt +0 -0
  15. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
  16. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
  17. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
  18. package/lib/bs/src/QueryDbStorage_Postgres.ast +0 -0
  19. package/lib/bs/src/QueryDbStorage_Postgres.res +35 -14
  20. package/lib/bs/src/QueryDbStorage_Postgres.res.mjs +23 -8
  21. package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
  22. package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
  23. package/lib/bs/src/QueryEnginePostgres.ast +0 -0
  24. package/lib/bs/src/QueryEnginePostgres.res +259 -0
  25. package/lib/bs/src/QueryEnginePostgres.res.mjs +165 -0
  26. package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
  27. package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
  28. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmi +0 -0
  29. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmj +0 -0
  30. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmt +0 -0
  31. package/lib/bs/tests/QueryEnginePostgresListPageTest.ast +0 -0
  32. package/lib/bs/tests/QueryEnginePostgresListPageTest.res +312 -0
  33. package/lib/bs/tests/QueryEnginePostgresListPageTest.res.mjs +461 -0
  34. package/lib/ocaml/.compiler.log +2 -2
  35. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  36. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  37. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
  38. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
  39. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  40. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  41. package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmi +0 -0
  42. package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmt +0 -0
  43. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
  44. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
  45. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
  46. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
  47. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
  48. package/lib/ocaml/QueryDbStorage_Postgres.ast +0 -0
  49. package/lib/ocaml/QueryDbStorage_Postgres.res +35 -14
  50. package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
  51. package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
  52. package/lib/ocaml/QueryEnginePostgres.ast +0 -0
  53. package/lib/ocaml/QueryEnginePostgres.res +259 -0
  54. package/lib/ocaml/QueryEnginePostgresListPageTest-ReventlessPostgres.cmi +0 -0
  55. package/lib/ocaml/QueryEnginePostgresListPageTest-ReventlessPostgres.cmj +0 -0
  56. package/lib/ocaml/QueryEnginePostgresListPageTest-ReventlessPostgres.cmt +0 -0
  57. package/lib/ocaml/QueryEnginePostgresListPageTest.ast +0 -0
  58. package/lib/ocaml/QueryEnginePostgresListPageTest.res +312 -0
  59. package/lib/ocaml/ReventlessPostgres.cmi +0 -0
  60. package/lib/ocaml/ReventlessPostgres.cmt +0 -0
  61. package/lib/ocaml/ReventlessPostgres.mlmap +1 -0
  62. package/package.json +7 -7
  63. package/src/QueryDbStorage_Postgres.res +35 -14
  64. package/src/QueryDbStorage_Postgres.res.mjs +23 -8
  65. package/src/QueryEnginePostgres.res +259 -0
  66. package/src/QueryEnginePostgres.res.mjs +165 -0
  67. package/tests/QueryEnginePostgresListPageTest.res +312 -0
  68. package/tests/QueryEnginePostgresListPageTest.res.mjs +461 -0
@@ -1,8 +1,11 @@
1
1
  // Generated by ReScript, PLEASE EDIT WITH CARE
2
2
 
3
+ import * as Stdlib_JSON from "@rescript/runtime/lib/es6/Stdlib_JSON.js";
3
4
  import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
4
5
  import * as Pulumi from "@pulumi/pulumi";
6
+ import * as Stdlib_Nullable from "@rescript/runtime/lib/es6/Stdlib_Nullable.js";
5
7
  import * as PgDriver$ReventlessPostgres from "./PgDriver.res.mjs";
8
+ import * as QueryDbListQuery$ReventlessCore from "@reventlessdev/reventless-core/src/components/Api/QueryDbListQuery.res.mjs";
6
9
  import * as QueryDbStorage_Postgres$ReventlessPostgres from "./QueryDbStorage_Postgres.res.mjs";
7
10
 
8
11
  function valueToText(v) {
@@ -145,6 +148,162 @@ function Make(P) {
145
148
  let sql = `SELECT partition_key, item FROM ` + table + ` WHERE ` + where.join(" AND ") + ` ORDER BY partition_key, sub_key LIMIT ` + param(b, limit);
146
149
  return (await PgDriver$ReventlessPostgres.query(P.pool, sql, b.params)).map(extra => decodeRow(true, extra));
147
150
  };
151
+ let indexLookup = async (readModelName, field, value) => {
152
+ let table = QueryDbStorage_Postgres$ReventlessPostgres.tableName(readModelName);
153
+ let b = {
154
+ params: []
155
+ };
156
+ let sql = `SELECT partition_key, item FROM ` + table + ` WHERE ` + col(field) + ` = ` + param(b, value) + ` AND ` + QueryDbStorage_Postgres$ReventlessPostgres.notExpiredClause;
157
+ return (await PgDriver$ReventlessPostgres.query(P.pool, sql, b.params)).map(extra => decodeRow(true, extra));
158
+ };
159
+ let byIds = async (readModelName, ids) => {
160
+ if (ids.length === 0) {
161
+ return [];
162
+ }
163
+ let table = QueryDbStorage_Postgres$ReventlessPostgres.tableName(readModelName);
164
+ let b = {
165
+ params: []
166
+ };
167
+ let idsJson = ids.map(prim => prim);
168
+ let sql = `SELECT partition_key, item FROM ` + table + ` WHERE partition_key = ANY(` + param(b, idsJson) + `::text[]) AND ` + QueryDbStorage_Postgres$ReventlessPostgres.notExpiredClause;
169
+ return (await PgDriver$ReventlessPostgres.query(P.pool, sql, b.params)).map(extra => decodeRow(true, extra));
170
+ };
171
+ let idExprC = `COALESCE(item->>'id', partition_key) COLLATE "C"`;
172
+ let jsonTextC = field => col(field) + ` COLLATE "C"`;
173
+ let listPage = async (readModelName, argsDict, capability, param$1) => {
174
+ let table = QueryDbStorage_Postgres$ReventlessPostgres.tableName(readModelName);
175
+ let filterDict = Stdlib_Option.getOr(Stdlib_Option.flatMap(argsDict["filter"], Stdlib_JSON.Decode.object), {});
176
+ let strNonEmpty = k => Stdlib_Option.mapOr(Stdlib_Option.flatMap(filterDict[k], Stdlib_JSON.Decode.string), false, s => s.length > 0);
177
+ let hasIds = Stdlib_Option.mapOr(Stdlib_Option.flatMap(filterDict["ids"], Stdlib_JSON.Decode.array), false, a => a.length !== 0);
178
+ let last = Stdlib_Option.flatMap(argsDict["last"], Stdlib_JSON.Decode.float);
179
+ let before = Stdlib_Option.flatMap(argsDict["before"], Stdlib_JSON.Decode.string);
180
+ if (strNonEmpty("search") || strNonEmpty("searchPrefix") || hasIds || Stdlib_Option.isSome(last) || Stdlib_Option.isSome(before)) {
181
+ return;
182
+ }
183
+ let b = {
184
+ params: []
185
+ };
186
+ let whereParts = [QueryDbStorage_Postgres$ReventlessPostgres.notExpiredClause];
187
+ let valString = v => {
188
+ let s = Stdlib_JSON.Decode.string(v);
189
+ if (s !== undefined) {
190
+ return s;
191
+ } else {
192
+ return Stdlib_Option.map(Stdlib_JSON.Decode.float(v), f => f.toString());
193
+ }
194
+ };
195
+ capability.filterFields.forEach(f => {
196
+ let v = filterDict[f.name + "Eq"];
197
+ if (v !== undefined && v !== null) {
198
+ whereParts.push(jsonTextC(f.name) + ` = ` + param(b, Stdlib_Option.getOr(valString(v), "")));
199
+ }
200
+ if (!f.range) {
201
+ return;
202
+ }
203
+ let v$1 = filterDict[f.name + "From"];
204
+ if (v$1 !== undefined && v$1 !== null) {
205
+ whereParts.push(jsonTextC(f.name) + ` >= ` + param(b, Stdlib_Option.getOr(valString(v$1), "")));
206
+ }
207
+ let v$2 = filterDict[f.name + "To"];
208
+ if (v$2 !== undefined && v$2 !== null) {
209
+ whereParts.push(jsonTextC(f.name) + ` <= ` + param(b, Stdlib_Option.getOr(valString(v$2), "")));
210
+ return;
211
+ }
212
+ });
213
+ let orderByDict = Stdlib_Option.flatMap(argsDict["orderBy"], Stdlib_JSON.Decode.object);
214
+ let orderByField = Stdlib_Option.flatMap(Stdlib_Option.flatMap(orderByDict, ob => ob["field"]), Stdlib_JSON.Decode.string);
215
+ let isDesc = Stdlib_Option.getOr(Stdlib_Option.flatMap(Stdlib_Option.flatMap(orderByDict, ob => ob["direction"]), Stdlib_JSON.Decode.string), "ASC") === "DESC";
216
+ let cursorExpr = orderByField !== undefined ? jsonTextC(orderByField) : idExprC;
217
+ let c = Stdlib_Option.flatMap(argsDict["after"], Stdlib_JSON.Decode.string);
218
+ if (c !== undefined) {
219
+ whereParts.push(cursorExpr + ` ` + (
220
+ isDesc ? "<" : ">"
221
+ ) + ` ` + param(b, QueryDbListQuery$ReventlessCore.decodeCursor(c)));
222
+ }
223
+ let orderClause = orderByField !== undefined ? jsonTextC(orderByField) + ` ` + (
224
+ isDesc ? "DESC" : "ASC"
225
+ ) + `, ` + idExprC + ` ASC` : idExprC + ` ASC`;
226
+ let pageSize = Stdlib_Option.getOr(Stdlib_Option.map(Stdlib_Option.flatMap(argsDict["first"], Stdlib_JSON.Decode.float), prim => prim | 0), QueryDbListQuery$ReventlessCore.defaultListPageSize);
227
+ let sql = `SELECT partition_key, item FROM ` + table + ` WHERE ` + whereParts.join(" AND ") + ` ORDER BY ` + orderClause + ` LIMIT ` + param(b, pageSize + 1 | 0);
228
+ let rows = (await PgDriver$ReventlessPostgres.query(P.pool, sql, b.params)).map(extra => decodeRow(true, extra));
229
+ let hasMore = rows.length > pageSize;
230
+ let pageItems = rows.slice(0, pageSize);
231
+ let cursorField = Stdlib_Option.getOr(orderByField, "id");
232
+ let cursorValueOf = item => Stdlib_Option.getOr(QueryDbListQuery$ReventlessCore.getFieldString(item, cursorField), QueryDbListQuery$ReventlessCore.getId(item));
233
+ return QueryDbListQuery$ReventlessCore.buildConnection(pageItems, hasMore, false, cursorValueOf);
234
+ };
235
+ let itemsPage = async (readModelName, param$1, id, argsDict) => {
236
+ let table = QueryDbStorage_Postgres$ReventlessPostgres.tableName(readModelName);
237
+ let filterDict = Stdlib_Option.getOr(Stdlib_Option.flatMap(argsDict["filter"], Stdlib_JSON.Decode.object), {});
238
+ let fstr = k => Stdlib_Option.flatMap(filterDict[k], Stdlib_JSON.Decode.string);
239
+ let orderDesc = Stdlib_Option.mapOr(fstr("order"), false, o => o === "DESC");
240
+ let last = Stdlib_Option.map(Stdlib_Option.flatMap(argsDict["last"], Stdlib_JSON.Decode.float), prim => prim | 0);
241
+ let first = Stdlib_Option.map(Stdlib_Option.flatMap(argsDict["first"], Stdlib_JSON.Decode.float), prim => prim | 0);
242
+ let after = Stdlib_Option.flatMap(argsDict["after"], Stdlib_JSON.Decode.string);
243
+ let before = Stdlib_Option.flatMap(argsDict["before"], Stdlib_JSON.Decode.string);
244
+ let isBackward = Stdlib_Option.isSome(last);
245
+ let sk = `sub_key COLLATE "C"`;
246
+ let b = {
247
+ params: []
248
+ };
249
+ let where = [
250
+ `partition_key = ` + param(b, id),
251
+ QueryDbStorage_Postgres$ReventlessPostgres.notExpiredClause
252
+ ];
253
+ Stdlib_Option.forEach(fstr("prefix"), p => {
254
+ where.push(`starts_with(sub_key, ` + param(b, p) + `)`);
255
+ });
256
+ Stdlib_Option.forEach(fstr("from"), f => {
257
+ where.push(sk + ` >= ` + param(b, f));
258
+ });
259
+ Stdlib_Option.forEach(fstr("to"), t => {
260
+ where.push(sk + ` <= ` + param(b, t));
261
+ });
262
+ Stdlib_Option.forEach(fstr("eq"), e => {
263
+ where.push(sk + ` = ` + param(b, e));
264
+ });
265
+ if (isBackward) {
266
+ if (before !== undefined) {
267
+ where.push(sk + ` < ` + param(b, QueryDbListQuery$ReventlessCore.decodeCursor(before)));
268
+ }
269
+ } else if (after !== undefined) {
270
+ where.push(sk + ` > ` + param(b, QueryDbListQuery$ReventlessCore.decodeCursor(after)));
271
+ }
272
+ let fetchDesc = isBackward ? !orderDesc : orderDesc;
273
+ let pageSize = Stdlib_Option.getOr(isBackward ? last : first, QueryDbListQuery$ReventlessCore.defaultListPageSize);
274
+ let sql = `SELECT partition_key, sub_key, item FROM ` + table + ` WHERE ` + where.join(" AND ") + ` ORDER BY ` + sk + ` ` + (
275
+ fetchDesc ? "DESC" : "ASC"
276
+ ) + ` LIMIT ` + param(b, pageSize + 1 | 0);
277
+ let rows = await PgDriver$ReventlessPostgres.query(P.pool, sql, b.params);
278
+ let hasMore = rows.length > pageSize;
279
+ let taken = rows.slice(0, pageSize);
280
+ let logical = isBackward ? taken.toReversed() : taken;
281
+ let pageItems = logical.map(extra => decodeRow(false, extra));
282
+ let subKeyOf = row => {
283
+ let match = row["sub_key"];
284
+ if (typeof match === "string") {
285
+ return match;
286
+ } else {
287
+ return "";
288
+ }
289
+ };
290
+ let cursors = logical.map(subKeyOf);
291
+ let edges = pageItems.map((item, i) => ({
292
+ node: item,
293
+ cursor: QueryDbListQuery$ReventlessCore.encodeCursor(cursors[i])
294
+ }));
295
+ let startCursor = Stdlib_Option.map(cursors[0], QueryDbListQuery$ReventlessCore.encodeCursor);
296
+ let endCursor = Stdlib_Option.map(cursors[cursors.length - 1 | 0], QueryDbListQuery$ReventlessCore.encodeCursor);
297
+ return {
298
+ edges: edges,
299
+ pageInfo: {
300
+ hasNextPage: !isBackward && hasMore,
301
+ hasPreviousPage: isBackward && hasMore,
302
+ startCursor: Stdlib_Nullable.fromOption(startCursor),
303
+ endCursor: Stdlib_Nullable.fromOption(endCursor)
304
+ }
305
+ };
306
+ };
148
307
  let make = _allQueryDbs => Pulumi.output({
149
308
  scan: scan,
150
309
  query: query
@@ -152,6 +311,12 @@ function Make(P) {
152
311
  return {
153
312
  query: query,
154
313
  scan: scan,
314
+ indexLookup: indexLookup,
315
+ byIds: byIds,
316
+ idExprC: idExprC,
317
+ jsonTextC: jsonTextC,
318
+ listPage: listPage,
319
+ itemsPage: itemsPage,
155
320
  make: make
156
321
  };
157
322
  }
@@ -0,0 +1,312 @@
1
+ // Parity harness for the Postgres connection-list push-down (B3.2a-1).
2
+ //
3
+ // `QueryEnginePostgres.listPage` builds `item->>'field'` predicates + keyset
4
+ // WHERE + ORDER BY … LIMIT to serve a page without materialising the whole read
5
+ // model. Its result MUST equal `QueryDbListQuery.run` (the shared spec in
6
+ // reventless-core that the in-memory backend, the SQLite push-down, and the
7
+ // resolver fallback all use) for every shape it claims to handle. This is the
8
+ // Postgres twin of reventless-local's `QueryDbListPushdownParityTest` — same
9
+ // capability, same rows, same (data, args) matrix — so all three backends are
10
+ // held to one spec.
11
+ //
12
+ // Skipped unless PG_URL is set (like PostgresIntegrationTest), so the default
13
+ // `pnpm test` stays dependency-free. Run with e.g.:
14
+ // PG_URL=postgres://postgres:postgres@localhost:5432/postgres pnpm test
15
+
16
+ open JestGlobals
17
+ open ReventlessCore
18
+
19
+ @val external processEnv: dict<string> = "process.env"
20
+
21
+ let capability: GraphQL_FragmentGenerator.serverCapability = {
22
+ filterFields: [
23
+ {name: "status", gqlType: "String", range: false},
24
+ {name: "qty", gqlType: "Int", range: true},
25
+ ],
26
+ sortFields: ["name", "qty", "status"],
27
+ }
28
+
29
+ let mk = (id, status, name, qty) => {
30
+ let o = Dict.make()
31
+ o->Dict.set("id", JSON.Encode.string(id))
32
+ o->Dict.set("status", JSON.Encode.string(status))
33
+ o->Dict.set("name", JSON.Encode.string(name))
34
+ o->Dict.set("qty", JSON.Encode.int(qty))
35
+ JSON.Encode.object(o)
36
+ }
37
+
38
+ // Names differ from id-order; status has duplicates (tiebreak); qty exercises the
39
+ // numeric-field-as-string comparison the push-down must match.
40
+ let rows = [
41
+ ("p-1", "active", "Charlie", 3),
42
+ ("p-2", "active", "Alpha", 1),
43
+ ("p-3", "inactive", "Echo", 5),
44
+ ("p-4", "active", "Bravo", 2),
45
+ ("p-5", "inactive", "Delta", 4),
46
+ ]
47
+
48
+ // The exact items seeded, in memory — the spec runs over these (equivalent to a
49
+ // full scan of the table, since every save upserts one of these by id).
50
+ let seededItems = rows->Array.map(((id, status, name, qty)) => mk(id, status, name, qty))
51
+
52
+ // ── normalise a connection to a comparable value ────────────────────────────
53
+ type normEdge = {id: string, cursor: string}
54
+ type normConn = {
55
+ edges: array<normEdge>,
56
+ hasNext: bool,
57
+ hasPrev: bool,
58
+ startCursor: option<string>,
59
+ endCursor: option<string>,
60
+ }
61
+
62
+ let field = (j, k) => j->JSON.Decode.object->Option.flatMap(d => d->Dict.get(k))
63
+ let str = (j, k) => j->field(k)->Option.flatMap(JSON.Decode.string)
64
+
65
+ let norm = (conn: JSON.t): normConn => {
66
+ let edges =
67
+ conn
68
+ ->field("edges")
69
+ ->Option.flatMap(JSON.Decode.array)
70
+ ->Option.getOr([])
71
+ ->Array.map(e => {
72
+ id: e->field("node")->Option.flatMap(n => n->str("id"))->Option.getOr(""),
73
+ cursor: e->str("cursor")->Option.getOr(""),
74
+ })
75
+ let pi = conn->field("pageInfo")->Option.getOr(JSON.Encode.null)
76
+ {
77
+ edges,
78
+ hasNext: pi->field("hasNextPage")->Option.flatMap(JSON.Decode.bool)->Option.getOr(false),
79
+ hasPrev: pi->field("hasPreviousPage")->Option.flatMap(JSON.Decode.bool)->Option.getOr(false),
80
+ startCursor: pi->str("startCursor"),
81
+ endCursor: pi->str("endCursor"),
82
+ }
83
+ }
84
+
85
+ let argsOf = (entries: array<(string, JSON.t)>): dict<JSON.t> => Dict.fromArray(entries)
86
+ let filterOf = (entries: array<(string, JSON.t)>): JSON.t =>
87
+ JSON.Encode.object(Dict.fromArray(entries))
88
+ let orderBy = (f, dir) =>
89
+ JSON.Encode.object(
90
+ Dict.fromArray([("field", JSON.Encode.string(f)), ("direction", JSON.Encode.string(dir))]),
91
+ )
92
+ let cur = QueryDbListQuery.encodeCursor
93
+
94
+ let expectedFor = argsDict =>
95
+ QueryDbListQuery.run(
96
+ ~items=seededItems,
97
+ ~argsDict,
98
+ ~capability,
99
+ ~labelField="name",
100
+ ~decodeLocalId=_ => None,
101
+ )->norm
102
+
103
+ switch processEnv->Dict.get("PG_URL") {
104
+ | None =>
105
+ testSync("Postgres list push-down parity (skipped — set PG_URL to run)", () =>
106
+ expect(true)->toBe(true)
107
+ )
108
+ | Some(url) =>
109
+ let pool = PgDriver.makePool({connectionString: url})
110
+ module Eng = QueryEnginePostgres.Make({
111
+ let pool = pool
112
+ })
113
+ let name = "listparity"
114
+
115
+ // Seed via the real storage ops (upsert by id → table converges to the 5 rows).
116
+ beforeAllAsync(async () => {
117
+ let ops = QueryDbStorage_Postgres.makeOperations(~pool, ~name, ~indexes=[], ~subIdField=None)
118
+ for i in 0 to rows->Array.length - 1 {
119
+ let (id, status, nm, qty) = rows->Array.getUnsafe(i)
120
+ let _ = await ops.save(id, mk(id, status, nm, qty), QueryDb.Any, None)
121
+ }
122
+ })
123
+ afterAll(() => {
124
+ let _ = pool->PgDriver.endPool
125
+ })
126
+
127
+ // Assert the push-down serves this shape AND matches the spec exactly.
128
+ let checkPushed = async (~label, args) => {
129
+ let argsDict = argsOf(args)
130
+ switch await Eng.listPage(~readModelName=name, ~argsDict, ~capability, ~labelField="name") {
131
+ | Some(actual) => expect(actual->norm)->toEqual(expectedFor(argsDict))
132
+ | None => expect("push-down for " ++ label)->toBe("returned None")
133
+ }
134
+ }
135
+
136
+ // Assert the push-down declines this shape (resolver falls back to the spec).
137
+ let checkFallback = async args => {
138
+ let r = await Eng.listPage(~readModelName=name, ~argsDict=argsOf(args), ~capability, ~labelField="name")
139
+ expect(r->Option.isSome)->toBe(false)
140
+ }
141
+
142
+ describe("QueryDb list push-down parity (Postgres ≡ QueryDbListQuery spec)", () => {
143
+ testPromise("bare page", () => checkPushed(~label="bare", []))
144
+ testPromise("first:2", () => checkPushed(~label="first", [("first", JSON.Encode.int(2))]))
145
+ testPromise("first:2 + after", () =>
146
+ checkPushed(
147
+ ~label="after",
148
+ [("first", JSON.Encode.int(2)), ("after", JSON.Encode.string(cur("p-2")))],
149
+ )
150
+ )
151
+ testPromise("statusEq active", () =>
152
+ checkPushed(~label="eq", [("filter", filterOf([("statusEq", JSON.Encode.string("active"))]))])
153
+ )
154
+ testPromise("statusEq active + first:2", () =>
155
+ checkPushed(
156
+ ~label="eq+first",
157
+ [
158
+ ("filter", filterOf([("statusEq", JSON.Encode.string("active"))])),
159
+ ("first", JSON.Encode.int(2)),
160
+ ],
161
+ )
162
+ )
163
+ testPromise("orderBy name ASC", () =>
164
+ checkPushed(~label="order-asc", [("orderBy", orderBy("name", "ASC"))])
165
+ )
166
+ testPromise("orderBy name DESC", () =>
167
+ checkPushed(~label="order-desc", [("orderBy", orderBy("name", "DESC"))])
168
+ )
169
+ testPromise("orderBy name DESC + first:2 + after", () =>
170
+ checkPushed(
171
+ ~label="order-desc-after",
172
+ [
173
+ ("orderBy", orderBy("name", "DESC")),
174
+ ("first", JSON.Encode.int(2)),
175
+ ("after", JSON.Encode.string(cur("Delta"))),
176
+ ],
177
+ )
178
+ )
179
+ // status has duplicate values → exercises the id tiebreak in ORDER BY.
180
+ testPromise("orderBy status ASC (tiebreak by id)", () =>
181
+ checkPushed(~label="order-tiebreak", [("orderBy", orderBy("status", "ASC"))])
182
+ )
183
+ // qty is numeric → exercises `item->>'qty'` (text) vs Float.toString string parity.
184
+ testPromise("qty range From/To (numeric-as-string)", () =>
185
+ checkPushed(
186
+ ~label="range",
187
+ [
188
+ (
189
+ "filter",
190
+ filterOf([("qtyFrom", JSON.Encode.string("2")), ("qtyTo", JSON.Encode.string("4"))]),
191
+ ),
192
+ ],
193
+ )
194
+ )
195
+ testPromise("orderBy qty ASC (numeric-as-string sort)", () =>
196
+ checkPushed(~label="order-qty", [("orderBy", orderBy("qty", "ASC"))])
197
+ )
198
+
199
+ // Shapes the push-down declines → resolver uses the JS fallback.
200
+ testPromise("search → fallback", () =>
201
+ checkFallback([("filter", filterOf([("search", JSON.Encode.string("alp"))]))])
202
+ )
203
+ testPromise("searchPrefix → fallback", () =>
204
+ checkFallback([("filter", filterOf([("searchPrefix", JSON.Encode.string("A"))]))])
205
+ )
206
+ testPromise("ids → fallback", () =>
207
+ checkFallback([("filter", filterOf([("ids", JSON.Encode.array([JSON.Encode.string("p-1")]))]))])
208
+ )
209
+ testPromise("backward (last/before) → fallback", () =>
210
+ checkFallback([("last", JSON.Encode.int(2)), ("before", JSON.Encode.string(cur("p-4")))])
211
+ )
212
+ })
213
+
214
+ // ── indexLookup / byIds push-downs ────────────────────────────────────────
215
+ let idsOf = (items: array<JSON.t>): array<string> =>
216
+ items->Array.filterMap(i => i->str("id"))->Array.toSorted(String.compare)
217
+
218
+ describe("QueryEnginePostgres index / batch push-downs", () => {
219
+ testPromise("indexLookup by status = active", async () => {
220
+ let items = await Eng.indexLookup(~readModelName=name, "status", "active")
221
+ expect(items->idsOf)->toEqual(["p-1", "p-2", "p-4"])
222
+ })
223
+ testPromise("indexLookup miss → empty", async () => {
224
+ let items = await Eng.indexLookup(~readModelName=name, "status", "nope")
225
+ expect(items->Array.length)->toBe(0)
226
+ })
227
+ testPromise("byIds returns matches, drops missing", async () => {
228
+ let items = await Eng.byIds(~readModelName=name, ["p-1", "p-3", "absent"])
229
+ expect(items->idsOf)->toEqual(["p-1", "p-3"])
230
+ })
231
+ testPromise("byIds [] → empty (no query)", async () => {
232
+ let items = await Eng.byIds(~readModelName=name, [])
233
+ expect(items->Array.length)->toBe(0)
234
+ })
235
+ })
236
+
237
+ // ── itemsPage (sub-id connection) ─────────────────────────────────────────
238
+ // A sub-id read model: partition "order-1" holds 5 lines keyed by `seq`.
239
+ let itemsName = "itemsparity"
240
+ let mkLine = seq => {
241
+ let o = Dict.make()
242
+ o->Dict.set("id", JSON.Encode.string("order-1"))
243
+ o->Dict.set("seq", JSON.Encode.string(seq))
244
+ JSON.Encode.object(o)
245
+ }
246
+ let seqs = ["a", "b", "c", "d", "e"]
247
+ beforeAllAsync(async () => {
248
+ let ops = QueryDbStorage_Postgres.makeOperations(
249
+ ~pool,
250
+ ~name=itemsName,
251
+ ~indexes=[],
252
+ ~subIdField=Some("seq"),
253
+ )
254
+ for i in 0 to seqs->Array.length - 1 {
255
+ let _ = await ops.save("order-1", mkLine(seqs->Array.getUnsafe(i)), QueryDb.Any, None)
256
+ }
257
+ })
258
+
259
+ // Extract node `seq` values in edge order.
260
+ let itemSeqs = (conn: JSON.t) =>
261
+ conn
262
+ ->field("edges")
263
+ ->Option.flatMap(JSON.Decode.array)
264
+ ->Option.getOr([])
265
+ ->Array.filterMap(e => e->field("node")->Option.flatMap(n => n->str("seq")))
266
+
267
+ let pageInfoBool = (conn, key) =>
268
+ conn->field("pageInfo")->Option.getOr(JSON.Encode.null)->field(key)->Option.flatMap(JSON.Decode.bool)->Option.getOr(false)
269
+
270
+ let itemsPage = args =>
271
+ Eng.itemsPage(~readModelName=itemsName, ~subIdField="seq", ~id="order-1", ~argsDict=argsOf(args))
272
+
273
+ describe("QueryEnginePostgres itemsPage (sub-id keyset)", () => {
274
+ testPromise("bare → all lines ASC, no next page", async () => {
275
+ let r = await itemsPage([])
276
+ expect(r->itemSeqs)->toEqual(["a", "b", "c", "d", "e"])
277
+ expect(pageInfoBool(r, "hasNextPage"))->toBe(false)
278
+ })
279
+ testPromise("first:2 → [a,b], hasNextPage", async () => {
280
+ let r = await itemsPage([("first", JSON.Encode.int(2))])
281
+ expect(r->itemSeqs)->toEqual(["a", "b"])
282
+ expect(pageInfoBool(r, "hasNextPage"))->toBe(true)
283
+ })
284
+ testPromise("first:2 after b → [c,d]", async () => {
285
+ let r = await itemsPage([("first", JSON.Encode.int(2)), ("after", JSON.Encode.string(cur("b")))])
286
+ expect(r->itemSeqs)->toEqual(["c", "d"])
287
+ })
288
+ testPromise("order DESC → [e..a]", async () => {
289
+ let r = await itemsPage([("filter", filterOf([("order", JSON.Encode.string("DESC"))]))])
290
+ expect(r->itemSeqs)->toEqual(["e", "d", "c", "b", "a"])
291
+ })
292
+ testPromise("filter eq c → [c]", async () => {
293
+ let r = await itemsPage([("filter", filterOf([("eq", JSON.Encode.string("c"))]))])
294
+ expect(r->itemSeqs)->toEqual(["c"])
295
+ })
296
+ testPromise("filter from b to d → [b,c,d]", async () => {
297
+ let r = await itemsPage([
298
+ ("filter", filterOf([("from", JSON.Encode.string("b")), ("to", JSON.Encode.string("d"))])),
299
+ ])
300
+ expect(r->itemSeqs)->toEqual(["b", "c", "d"])
301
+ })
302
+ testPromise("prefix c → [c]", async () => {
303
+ let r = await itemsPage([("filter", filterOf([("prefix", JSON.Encode.string("c"))]))])
304
+ expect(r->itemSeqs)->toEqual(["c"])
305
+ })
306
+ testPromise("backward last:2 before d → [b,c] (logical ASC)", async () => {
307
+ let r = await itemsPage([("last", JSON.Encode.int(2)), ("before", JSON.Encode.string(cur("d")))])
308
+ expect(r->itemSeqs)->toEqual(["b", "c"])
309
+ expect(pageInfoBool(r, "hasPreviousPage"))->toBe(true)
310
+ })
311
+ })
312
+ }