@reventlessdev/reventless-postgres 3.0.0-alpha.2 → 3.0.0-alpha.200
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.
- package/CHANGELOG.md +1584 -0
- package/README.md +83 -0
- package/lib/bs/.compiler.log +2 -2
- package/lib/bs/ReventlessPostgres.cmi +0 -0
- package/lib/bs/ReventlessPostgres.cmt +0 -0
- package/lib/bs/ReventlessPostgres.mlmap +4 -1
- package/lib/bs/compiler-info.json +4 -4
- package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres.ast +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres.res +25 -340
- package/lib/bs/src/DcbEventLogStorage_Postgres.res.mjs +38 -348
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.ast +0 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res +422 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res.mjs +437 -0
- package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/EventLogChangeFeed.ast +0 -0
- package/lib/bs/src/EventLogChangeFeed.res +193 -0
- package/lib/bs/src/EventLogChangeFeed.res.mjs +134 -0
- package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/EventLogStorage_Postgres.ast +0 -0
- package/lib/bs/src/EventLogStorage_Postgres.res +12 -170
- package/lib/bs/src/EventLogStorage_Postgres.res.mjs +23 -186
- package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops.ast +0 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops.res +240 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops.res.mjs +232 -0
- package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/PgChangeFeed.ast +0 -0
- package/lib/bs/src/PgChangeFeed.res +21 -9
- package/lib/bs/src/PgChangeFeed.res.mjs +6 -6
- package/lib/bs/src/PgDriver-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/PgDriver-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/PgDriver-ReventlessPostgres.cmti +0 -0
- package/lib/bs/src/PgDriver.ast +0 -0
- package/lib/bs/src/PgDriver.iast +0 -0
- package/lib/bs/src/PgDriver.res +1 -2
- package/lib/bs/src/PgSchema-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/PgSchema-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/PgSchema.ast +0 -0
- package/lib/bs/src/PgSchema.res +44 -2
- package/lib/bs/src/PgSchema.res.mjs +13 -3
- package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres.ast +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres.res +16 -213
- package/lib/bs/src/QueryDbStorage_Postgres.res.mjs +27 -191
- package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops.ast +0 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops.res +229 -0
- package/lib/bs/src/QueryDbStorage_Postgres_Ops.res.mjs +222 -0
- package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/QueryEnginePostgres.ast +0 -0
- package/lib/bs/src/QueryEnginePostgres.res +372 -14
- package/lib/bs/src/QueryEnginePostgres.res.mjs +203 -15
- package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
- package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
- package/lib/bs/tests/PostgresIntegrationTest.ast +0 -0
- package/lib/bs/tests/PostgresIntegrationTest.res +168 -47
- package/lib/bs/tests/PostgresIntegrationTest.res.mjs +50 -1
- package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmi +0 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmj +0 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmt +0 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest.ast +0 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest.res +335 -0
- package/lib/bs/tests/QueryEnginePostgresListPageTest.res.mjs +461 -0
- package/lib/ocaml/.compiler.log +2 -2
- package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres.ast +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres.res +25 -340
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops.ast +0 -0
- package/lib/ocaml/DcbEventLogStorage_Postgres_Ops.res +422 -0
- package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/EventLogChangeFeed.ast +0 -0
- package/lib/ocaml/EventLogChangeFeed.res +193 -0
- package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/EventLogStorage_Postgres.ast +0 -0
- package/lib/ocaml/EventLogStorage_Postgres.res +12 -170
- package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/EventLogStorage_Postgres_Ops.ast +0 -0
- package/lib/ocaml/EventLogStorage_Postgres_Ops.res +240 -0
- package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgChangeFeed.ast +0 -0
- package/lib/ocaml/PgChangeFeed.res +21 -9
- package/lib/ocaml/PgDriver-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgDriver-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgDriver-ReventlessPostgres.cmti +0 -0
- package/lib/ocaml/PgDriver.ast +0 -0
- package/lib/ocaml/PgDriver.iast +0 -0
- package/lib/ocaml/PgDriver.res +1 -2
- package/lib/ocaml/PgSchema-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgSchema-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgSchema.ast +0 -0
- package/lib/ocaml/PgSchema.res +44 -2
- package/lib/ocaml/PostgresIntegrationTest.res +168 -47
- package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres.ast +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres.res +16 -213
- package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres_Ops.ast +0 -0
- package/lib/ocaml/QueryDbStorage_Postgres_Ops.res +229 -0
- package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/QueryEnginePostgres.ast +0 -0
- package/lib/ocaml/QueryEnginePostgres.res +372 -14
- package/lib/ocaml/QueryEnginePostgresListPageTest.res +335 -0
- package/lib/ocaml/ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/ReventlessPostgres.mlmap +5 -0
- package/package.json +14 -14
- package/rescript.json +2 -1
- package/src/DcbEventLogStorage_Postgres.res +25 -340
- package/src/DcbEventLogStorage_Postgres.res.mjs +38 -348
- package/src/DcbEventLogStorage_Postgres_Ops.res +422 -0
- package/src/DcbEventLogStorage_Postgres_Ops.res.mjs +437 -0
- package/src/EventLogChangeFeed.res +193 -0
- package/src/EventLogChangeFeed.res.mjs +134 -0
- package/src/EventLogStorage_Postgres.res +12 -170
- package/src/EventLogStorage_Postgres.res.mjs +23 -186
- package/src/EventLogStorage_Postgres_Ops.res +240 -0
- package/src/EventLogStorage_Postgres_Ops.res.mjs +232 -0
- package/src/PgChangeFeed.res +21 -9
- package/src/PgChangeFeed.res.mjs +6 -6
- package/src/PgDriver.res +1 -2
- package/src/PgSchema.res +44 -2
- package/src/PgSchema.res.mjs +13 -3
- package/src/QueryDbStorage_Postgres.res +16 -213
- package/src/QueryDbStorage_Postgres.res.mjs +27 -191
- package/src/QueryDbStorage_Postgres_Ops.res +229 -0
- package/src/QueryDbStorage_Postgres_Ops.res.mjs +222 -0
- package/src/QueryEnginePostgres.res +372 -14
- package/src/QueryEnginePostgres.res.mjs +203 -15
- package/tests/PostgresIntegrationTest.res +168 -47
- package/tests/QueryEnginePostgresListPageTest.res +335 -0
- package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmj +0 -0
- package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PostgresIntegrationTest.ast +0 -0
- package/tests/PostgresIntegrationTest.res.mjs +0 -328
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// Runtime-pure QueryDb operations for the Postgres backend — JSONB document
|
|
2
|
+
// tables, one per read model.
|
|
3
|
+
//
|
|
4
|
+
// Holds the operation set + all SQL helpers and imports NO `@pulumi/pulumi`
|
|
5
|
+
// (deploy-time only), so the deployed-Lambda runtime can bind ops without dragging
|
|
6
|
+
// a deploy-time dep into its ESM import graph (which fails resolution on real
|
|
7
|
+
// Lambda). The thin `QueryDbStorage_Postgres` wrapper `include`s this and adds the
|
|
8
|
+
// deploy-time `Pulumi.Output`-shaped `storage` record + the `Make` functor.
|
|
9
|
+
// See docs/plans/done/deployed-lambda-esm-self-containment.md (Rung-3 finding).
|
|
10
|
+
|
|
11
|
+
open ReventlessCore
|
|
12
|
+
open Reventless.ReadModel
|
|
13
|
+
|
|
14
|
+
let tableName = (name: string): string => "qdb_" ++ name->String.replaceAll("-", "_")
|
|
15
|
+
|
|
16
|
+
// Collapse anything outside [A-Za-z0-9_] to _ — predictable, injection-safe idents.
|
|
17
|
+
let sanitizeIdent = (s: string): string => s->String.replaceRegExp(/[^A-Za-z0-9_]/g, "_")
|
|
18
|
+
|
|
19
|
+
let notExpiredClause = "(expires_at IS NULL OR expires_at > extract(epoch from now()))"
|
|
20
|
+
|
|
21
|
+
// JSONB text extraction for a single top-level field.
|
|
22
|
+
let jsonField = (field: string): string => `(item->>'${field->String.replaceAll("'", "''")}')`
|
|
23
|
+
|
|
24
|
+
let compositeExpr = (fields: array<string>, sep: string): string => {
|
|
25
|
+
let escapedSep = sep->String.replaceAll("'", "''")
|
|
26
|
+
fields->Array.map(jsonField)->Array.join(` || '${escapedSep}' || `)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let indexExpressions = (idx: indexConfig): (string, option<string>) => {
|
|
30
|
+
let pkExpr = switch idx.pkFields {
|
|
31
|
+
| Some(fields) if fields->Array.length > 0 => compositeExpr(fields, idx.pkSep->Option.getOr("/"))
|
|
32
|
+
| _ =>
|
|
33
|
+
switch idx.idField {
|
|
34
|
+
| Some(field) => jsonField(field)
|
|
35
|
+
| None => jsonField(idx.index)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
let skExpr = switch idx.skFields {
|
|
39
|
+
| Some(fields) if fields->Array.length > 0 =>
|
|
40
|
+
Some(compositeExpr(fields, idx.skSep->Option.getOr("/")))
|
|
41
|
+
| _ =>
|
|
42
|
+
switch idx.subIdField {
|
|
43
|
+
| Some(field) => Some(jsonField(field))
|
|
44
|
+
| None => None
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
(pkExpr, skExpr)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
let ensureTable = async (~pool, ~table) => {
|
|
51
|
+
await pool->PgDriver.exec(
|
|
52
|
+
`CREATE TABLE IF NOT EXISTS ${table} (partition_key text NOT NULL, sub_key text NOT NULL DEFAULT '', item jsonb NOT NULL, expires_at double precision, PRIMARY KEY (partition_key, sub_key))`,
|
|
53
|
+
)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let ensureIndexes = async (~pool, ~table, ~indexes: array<indexConfig>) => {
|
|
57
|
+
for i in 0 to indexes->Array.length - 1 {
|
|
58
|
+
let idx = indexes->Array.getUnsafe(i)
|
|
59
|
+
let (pkExpr, skExprOpt) = indexExpressions(idx)
|
|
60
|
+
let indexName = `idx_${table}_${sanitizeIdent(idx.index)}`
|
|
61
|
+
let cols = switch skExprOpt {
|
|
62
|
+
| Some(skExpr) => `${pkExpr}, ${skExpr}`
|
|
63
|
+
| None => pkExpr
|
|
64
|
+
}
|
|
65
|
+
await pool->PgDriver.exec(`CREATE INDEX IF NOT EXISTS ${indexName} ON ${table} (${cols})`)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let decodeItem = (row: dict<JSON.t>): JSON.t =>
|
|
70
|
+
row->Dict.get("item")->Option.getOr(JSON.Encode.null)
|
|
71
|
+
|
|
72
|
+
let computeSubKey = (item: JSON.t, subIdField: option<string>): string =>
|
|
73
|
+
switch subIdField {
|
|
74
|
+
| None => ""
|
|
75
|
+
| Some(field) =>
|
|
76
|
+
switch item->JSON.Decode.object->Option.flatMap(o => o->Dict.get(field)) {
|
|
77
|
+
| Some(JSON.String(s)) => s
|
|
78
|
+
| _ => ""
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let withId = (item: JSON.t, partitionKey: string): JSON.t =>
|
|
83
|
+
switch item->JSON.Decode.object {
|
|
84
|
+
| Some(obj) if obj->Dict.get("id")->Option.isNone =>
|
|
85
|
+
let copy = Dict.copy(obj)
|
|
86
|
+
copy->Dict.set("id", JSON.Encode.string(partitionKey))
|
|
87
|
+
JSON.Encode.object(copy)
|
|
88
|
+
| _ => item
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Plain operation set for a read model's qdb table. Exposed separately from
|
|
92
|
+
// `makeStorage` so the deployed-Lambda runtime (reventless-aws) can bind ops
|
|
93
|
+
// without touching the Pulumi-shaped `storage` record.
|
|
94
|
+
let makeOperations = (
|
|
95
|
+
~pool: PgDriver.pool,
|
|
96
|
+
~name: string,
|
|
97
|
+
~indexes: array<indexConfig>,
|
|
98
|
+
~subIdField: option<string>,
|
|
99
|
+
): QueryDb_Adapter.operations => {
|
|
100
|
+
let table = tableName(name)
|
|
101
|
+
// Schema setup is async and LAZY: kicked off by the first operation, not at
|
|
102
|
+
// construction. A deploy-time caller may build the ops on a machine that
|
|
103
|
+
// cannot reach the database (VPC-private RDS) — only the runtime, which
|
|
104
|
+
// actually calls an operation, may open a connection. Subsequent operations
|
|
105
|
+
// await the same promise (table + index creation runs exactly once).
|
|
106
|
+
let readyRef: ref<option<promise<unit>>> = ref(None)
|
|
107
|
+
let ready = () =>
|
|
108
|
+
switch readyRef.contents {
|
|
109
|
+
| Some(p) => p
|
|
110
|
+
| None =>
|
|
111
|
+
let p = {
|
|
112
|
+
open Promise
|
|
113
|
+
ensureTable(~pool, ~table)->then(() => ensureIndexes(~pool, ~table, ~indexes))
|
|
114
|
+
}
|
|
115
|
+
readyRef := Some(p)
|
|
116
|
+
p
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let rowsFor = async (id: string): array<JSON.t> => {
|
|
120
|
+
await ready()
|
|
121
|
+
|
|
122
|
+
(
|
|
123
|
+
await pool->PgDriver.query(
|
|
124
|
+
`SELECT item FROM ${table} WHERE partition_key = $1 AND ${notExpiredClause} ORDER BY sub_key ASC`,
|
|
125
|
+
[JSON.Encode.string(id)],
|
|
126
|
+
)
|
|
127
|
+
)->Array.map(decodeItem)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let saveOne = async (id: string, state: JSON.t, ttl: option<int>) => {
|
|
131
|
+
await ready()
|
|
132
|
+
let subKey = computeSubKey(state, subIdField)
|
|
133
|
+
let expiresAt = switch ttl {
|
|
134
|
+
| Some(t) => JSON.Encode.int(t)
|
|
135
|
+
| None => JSON.Encode.null
|
|
136
|
+
}
|
|
137
|
+
let _ = await pool->PgDriver.query(
|
|
138
|
+
`INSERT INTO ${table}(partition_key, sub_key, item, expires_at)
|
|
139
|
+
VALUES ($1, $2, $3::jsonb, $4)
|
|
140
|
+
ON CONFLICT (partition_key, sub_key)
|
|
141
|
+
DO UPDATE SET item = EXCLUDED.item, expires_at = EXCLUDED.expires_at`,
|
|
142
|
+
[
|
|
143
|
+
JSON.Encode.string(id),
|
|
144
|
+
JSON.Encode.string(subKey),
|
|
145
|
+
JSON.Encode.string(JSON.stringify(state)),
|
|
146
|
+
expiresAt,
|
|
147
|
+
],
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let load: QueryDb.load<string, JSON.t> = async id => Ok(await rowsFor(id))
|
|
152
|
+
|
|
153
|
+
let loadStream: QueryDb.loadStream<string, JSON.t> = id =>
|
|
154
|
+
Effect.promise(() => rowsFor(id))
|
|
155
|
+
->Stream.fromEffect
|
|
156
|
+
->Stream.flatMap(arr => Stream.fromIterable(arr))
|
|
157
|
+
|
|
158
|
+
let save: QueryDb.save<string, JSON.t> = async (id, state, _saveMode, ttl) => {
|
|
159
|
+
await saveOne(id, state, ttl)
|
|
160
|
+
Ok()
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
let saveBatch: QueryDb.saveBatch<string, JSON.t> = async batch => {
|
|
164
|
+
// pg has no synchronous multi-statement transaction helper here; the upserts
|
|
165
|
+
// are independent (distinct keys) so a sequential apply is equivalent.
|
|
166
|
+
for i in 0 to batch->Array.length - 1 {
|
|
167
|
+
let (id, state, ttl) = batch->Array.getUnsafe(i)
|
|
168
|
+
await saveOne(id, state, ttl)
|
|
169
|
+
}
|
|
170
|
+
Ok()
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Mirror DynamoDB's `ADD #field :inc`: read the counter on the partition item
|
|
174
|
+
// (counters are single-state, sub_key=""), add inc, upsert, return NEW total.
|
|
175
|
+
let count: QueryDb.count<string> = async (id, fieldName, inc) => {
|
|
176
|
+
await ready()
|
|
177
|
+
let existing = (await rowsFor(id))->Array.get(0)->Option.flatMap(JSON.Decode.object)
|
|
178
|
+
let current =
|
|
179
|
+
existing
|
|
180
|
+
->Option.flatMap(o => o->Dict.get(fieldName))
|
|
181
|
+
->Option.flatMap(JSON.Decode.float)
|
|
182
|
+
->Option.mapOr(0, Float.toInt)
|
|
183
|
+
let next = current + inc
|
|
184
|
+
let obj = switch existing {
|
|
185
|
+
| Some(o) => Dict.copy(o)
|
|
186
|
+
| None => Dict.make()
|
|
187
|
+
}
|
|
188
|
+
obj->Dict.set("id", JSON.Encode.string(id))
|
|
189
|
+
obj->Dict.set(fieldName, JSON.Encode.int(next))
|
|
190
|
+
await saveOne(id, JSON.Encode.object(obj), None)
|
|
191
|
+
Ok(next)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
let delete: QueryDb.delete<string> = async (id, subIdOpt) => {
|
|
195
|
+
await ready()
|
|
196
|
+
let _ = switch subIdOpt {
|
|
197
|
+
| None =>
|
|
198
|
+
await pool->PgDriver.query(
|
|
199
|
+
`DELETE FROM ${table} WHERE partition_key = $1`,
|
|
200
|
+
[JSON.Encode.string(id)],
|
|
201
|
+
)
|
|
202
|
+
| Some((_, subValue)) =>
|
|
203
|
+
await pool->PgDriver.query(
|
|
204
|
+
`DELETE FROM ${table} WHERE partition_key = $1 AND sub_key = $2`,
|
|
205
|
+
[JSON.Encode.string(id), JSON.Encode.string(subValue)],
|
|
206
|
+
)
|
|
207
|
+
}
|
|
208
|
+
Ok()
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
let deleteBatch: QueryDb.deleteBatch<string> = async ids => {
|
|
212
|
+
for i in 0 to ids->Array.length - 1 {
|
|
213
|
+
let (id, subIdOpt) = ids->Array.getUnsafe(i)
|
|
214
|
+
let _ = await delete(id, subIdOpt)
|
|
215
|
+
}
|
|
216
|
+
Ok()
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
let ops: QueryDb_Adapter.operations = {
|
|
220
|
+
load,
|
|
221
|
+
loadStream,
|
|
222
|
+
save,
|
|
223
|
+
saveBatch,
|
|
224
|
+
count,
|
|
225
|
+
delete,
|
|
226
|
+
deleteBatch,
|
|
227
|
+
}
|
|
228
|
+
ops
|
|
229
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -28,7 +28,12 @@ let param = (b: paramBuilder, v: JSON.t): string => {
|
|
|
28
28
|
let col = (field: string): string => `(item->>'${field->String.replaceAll("'", "''")}')`
|
|
29
29
|
|
|
30
30
|
// One Filter.config → SQL predicate, appending any bound params.
|
|
31
|
-
let filterSql = (
|
|
31
|
+
let filterSql = (
|
|
32
|
+
b: paramBuilder,
|
|
33
|
+
field: string,
|
|
34
|
+
cmp: QueryEngine.Filter.comparator,
|
|
35
|
+
v: QueryEngine.value,
|
|
36
|
+
): string => {
|
|
32
37
|
let c = col(field)
|
|
33
38
|
let bind = () => b->param(JSON.Encode.string(valueToText(v)))
|
|
34
39
|
let cmpSql = op =>
|
|
@@ -48,10 +53,16 @@ let filterSql = (b: paramBuilder, field: string, cmp: QueryEngine.Filter.compara
|
|
|
48
53
|
}
|
|
49
54
|
}
|
|
50
55
|
|
|
51
|
-
let subIdSql = (
|
|
56
|
+
let subIdSql = (
|
|
57
|
+
b: paramBuilder,
|
|
58
|
+
field: string,
|
|
59
|
+
cmp: QueryEngine.SubId.comparator,
|
|
60
|
+
v: QueryEngine.value,
|
|
61
|
+
): string => {
|
|
52
62
|
let c = col(field)
|
|
53
63
|
let bind = () => b->param(JSON.Encode.string(valueToText(v)))
|
|
54
|
-
let cmpSql = op =>
|
|
64
|
+
let cmpSql = op =>
|
|
65
|
+
isNumeric(v) ? `${c}::numeric ${op} ${bind()}::numeric` : `${c} ${op} ${bind()}`
|
|
55
66
|
switch cmp {
|
|
56
67
|
| QueryEngine.SubId.Equal => cmpSql("=")
|
|
57
68
|
| Unequal => cmpSql("<>")
|
|
@@ -63,24 +74,28 @@ let subIdSql = (b: paramBuilder, field: string, cmp: QueryEngine.SubId.comparato
|
|
|
63
74
|
}
|
|
64
75
|
}
|
|
65
76
|
|
|
66
|
-
let notExpired =
|
|
77
|
+
let notExpired = QueryDbStorage_Postgres_Ops.notExpiredClause
|
|
67
78
|
|
|
68
79
|
// Add `id` (from partition_key) when absent — matches allRows/scan in the SQLite
|
|
69
80
|
// engine; partition-key queries return items as stored.
|
|
70
81
|
let decodeRow = (~withId, row: dict<JSON.t>): JSON.t => {
|
|
71
|
-
let item =
|
|
82
|
+
let item = QueryDbStorage_Postgres_Ops.decodeItem(row)
|
|
72
83
|
if withId {
|
|
73
84
|
let pk = switch row->Dict.get("partition_key") {
|
|
74
85
|
| Some(JSON.String(s)) => s
|
|
75
86
|
| _ => ""
|
|
76
87
|
}
|
|
77
|
-
|
|
88
|
+
QueryDbStorage_Postgres_Ops.withId(item, pk)
|
|
78
89
|
} else {
|
|
79
90
|
item
|
|
80
91
|
}
|
|
81
92
|
}
|
|
82
93
|
|
|
83
|
-
module Make = (
|
|
94
|
+
module Make = (
|
|
95
|
+
P: {
|
|
96
|
+
let pool: PgDriver.pool
|
|
97
|
+
},
|
|
98
|
+
) => {
|
|
84
99
|
let query = async (
|
|
85
100
|
~readModelName,
|
|
86
101
|
~key=?,
|
|
@@ -90,7 +105,7 @@ module Make = (P: {let pool: PgDriver.pool}) => {
|
|
|
90
105
|
~ascending=?,
|
|
91
106
|
~limit=?,
|
|
92
107
|
): array<JSON.t> => {
|
|
93
|
-
let table =
|
|
108
|
+
let table = QueryDbStorage_Postgres_Ops.tableName(readModelName)
|
|
94
109
|
let keyStr = switch key {
|
|
95
110
|
| Some(k) => k
|
|
96
111
|
| None => valueToText(id)
|
|
@@ -109,19 +124,362 @@ module Make = (P: {let pool: PgDriver.pool}) => {
|
|
|
109
124
|
| Some(n) => ` LIMIT ${b->param(JSON.Encode.int(n))}`
|
|
110
125
|
| None => ""
|
|
111
126
|
}
|
|
112
|
-
let sql = `SELECT partition_key, item FROM ${table} WHERE ${where->Array.join(
|
|
127
|
+
let sql = `SELECT partition_key, item FROM ${table} WHERE ${where->Array.join(
|
|
128
|
+
" AND ",
|
|
129
|
+
)} ORDER BY sub_key ${dir}${limitClause}`
|
|
113
130
|
(await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=false, ...))
|
|
114
131
|
}
|
|
115
132
|
|
|
116
133
|
let scan = async (~readModelName, ~filterConfigs, ~limit): array<JSON.t> => {
|
|
117
|
-
let table =
|
|
134
|
+
let table = QueryDbStorage_Postgres_Ops.tableName(readModelName)
|
|
118
135
|
let b = {params: []}
|
|
119
136
|
let where = [notExpired]
|
|
120
|
-
filterConfigs->Array.forEach(((field, cmp, v)) =>
|
|
121
|
-
|
|
137
|
+
filterConfigs->Array.forEach(((field, cmp, v)) =>
|
|
138
|
+
where->Array.push(filterSql(b, field, cmp, v))
|
|
139
|
+
)
|
|
140
|
+
let sql = `SELECT partition_key, item FROM ${table} WHERE ${where->Array.join(
|
|
141
|
+
" AND ",
|
|
142
|
+
)} ORDER BY partition_key, sub_key LIMIT ${b->param(JSON.Encode.int(limit))}`
|
|
143
|
+
(await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=true, ...))
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
// GraphQL resolver push-downs (B3.2). The Postgres resolver Lambda dispatches
|
|
148
|
+
// these; they parallel the SQLite backend's `lookupByField` / `listPage` (the
|
|
149
|
+
// ones registered on LocalBus). All return `id`-carrying items (COALESCE from
|
|
150
|
+
// partition_key), matching the shape `QueryDbListQuery.run` operates over so
|
|
151
|
+
// the connection helpers agree.
|
|
152
|
+
//
|
|
153
|
+
// Text comparisons use `COLLATE "C"` (byte order — memcmp), the Postgres
|
|
154
|
+
// analogue of SQLite's BINARY collation, so cursor/order comparisons match
|
|
155
|
+
// JS string `<` for the ASCII id/status/name fields used as sort/filter keys.
|
|
156
|
+
// ---------------------------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
// Equality lookup on an indexed JSON field — rides the expression index
|
|
159
|
+
// (`ensureIndexes`) instead of scanning. String comparison mirrors the
|
|
160
|
+
// resolver's JS path (which only matched string-typed fields).
|
|
161
|
+
let indexLookup = async (~readModelName, field: string, value: string): array<JSON.t> => {
|
|
162
|
+
let table = QueryDbStorage_Postgres_Ops.tableName(readModelName)
|
|
163
|
+
let b = {params: []}
|
|
164
|
+
let sql = `SELECT partition_key, item FROM ${table} WHERE ${col(field)} = ${b->param(
|
|
165
|
+
JSON.Encode.string(value),
|
|
166
|
+
)} AND ${notExpired}`
|
|
122
167
|
(await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=true, ...))
|
|
123
168
|
}
|
|
124
169
|
|
|
125
|
-
|
|
126
|
-
|
|
170
|
+
// Batched-by-ids lookup: BatchGetItem analogue over the projection's own
|
|
171
|
+
// table. Single-key projections only (partition_key = the id). Missing ids
|
|
172
|
+
// drop out of the response (no cardinality preservation), matching
|
|
173
|
+
// BatchGetItem semantics.
|
|
174
|
+
let byIds = async (~readModelName, ids: array<string>): array<JSON.t> => {
|
|
175
|
+
if ids->Array.length == 0 {
|
|
176
|
+
[]
|
|
177
|
+
} else {
|
|
178
|
+
let table = QueryDbStorage_Postgres_Ops.tableName(readModelName)
|
|
179
|
+
let b = {params: []}
|
|
180
|
+
let idsJson = JSON.Encode.array(ids->Array.map(JSON.Encode.string))
|
|
181
|
+
let sql = `SELECT partition_key, item FROM ${table} WHERE partition_key = ANY(${b->param(
|
|
182
|
+
idsJson,
|
|
183
|
+
)}::text[]) AND ${notExpired}`
|
|
184
|
+
(await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=true, ...))
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// COALESCE(item->>'id', partition_key) — the effective id, byte-ordered.
|
|
189
|
+
let idExprC = `COALESCE(item->>'id', partition_key) COLLATE "C"`
|
|
190
|
+
let jsonTextC = (field: string): string => `${col(field)} COLLATE "C"`
|
|
191
|
+
|
|
192
|
+
// "not retired", as jsonb rather than text. `->` keeps the value typed, so a
|
|
193
|
+
// JSON boolean true is distinguishable from the JSON string "true"; `->>`
|
|
194
|
+
// would render both as 'true' and hide a row the shared spec keeps, since that
|
|
195
|
+
// spec decodes strictly and reads a non-boolean as "no flag". `IS DISTINCT
|
|
196
|
+
// FROM` rather than `<>` so an absent key — NULL — keeps the row instead of
|
|
197
|
+
// making the whole predicate NULL and dropping it.
|
|
198
|
+
//
|
|
199
|
+
// The state form compares against JSON strings instead of `true`, one
|
|
200
|
+
// `IS DISTINCT FROM` per state, ANDed. Not `NOT IN`: that is ordinary
|
|
201
|
+
// equality, so an absent key makes the predicate NULL and drops a row this
|
|
202
|
+
// spec keeps. Same shape and same index behavior as the single-state form —
|
|
203
|
+
// a handful of equality predicates over an enum-valued attribute cost what one
|
|
204
|
+
// over a boolean does — so the `@index` guidance carries over unchanged.
|
|
205
|
+
//
|
|
206
|
+
// A set naming no states withdraws nothing, so the predicate is vacuously
|
|
207
|
+
// true, matching what `isRetiredValue` answers for it.
|
|
208
|
+
let notRetiredC = (scope: Reventless.OwnerScope.retiredScope): string => {
|
|
209
|
+
let key = scope.field->String.replaceAll("'", "''")
|
|
210
|
+
let distinctFrom = lit => `(item->'${key}') IS DISTINCT FROM ${lit}`
|
|
211
|
+
switch scope.values {
|
|
212
|
+
| None => distinctFrom("'true'::jsonb")
|
|
213
|
+
| Some([]) => "TRUE"
|
|
214
|
+
| Some(states) =>
|
|
215
|
+
// Parenthesised though every caller ANDs these together already: a clause
|
|
216
|
+
// that is safe only because of where it is spliced is a clause that breaks
|
|
217
|
+
// the first time it is spliced somewhere else.
|
|
218
|
+
"(" ++
|
|
219
|
+
states
|
|
220
|
+
->Array.map(state => distinctFrom(`'"${state->String.replaceAll("'", "''")}"'::jsonb`))
|
|
221
|
+
->Array.join(" AND ") ++ ")"
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Connection-list push-down. Builds `item->>'field'` predicates + keyset
|
|
226
|
+
// WHERE + `ORDER BY … LIMIT pageSize+1` so a page reads only what it returns
|
|
227
|
+
// rather than the whole read model. Reproduces `QueryDbListQuery` semantics
|
|
228
|
+
// exactly for the shapes it handles; returns `None` (→ the resolver Lambda
|
|
229
|
+
// falls back to `scan` + the shared spec) for shapes not bit-exact in SQL:
|
|
230
|
+
// case-insensitive search/searchPrefix, Relay-global-id `ids`, and backward
|
|
231
|
+
// pagination (last/before). Cursor values, edges, and pageInfo are built by
|
|
232
|
+
// the SAME `QueryDbListQuery` helpers the fallback uses, so only the
|
|
233
|
+
// WHERE/ORDER/LIMIT needs to match — the parity harness asserts it does
|
|
234
|
+
// (SQLite ≡ Postgres ≡ spec). Mirrors QueryDbStorage_Sqlite.listPage.
|
|
235
|
+
let listPage = async (
|
|
236
|
+
~readModelName,
|
|
237
|
+
~argsDict: dict<JSON.t>,
|
|
238
|
+
~capability: GraphQL_FragmentGenerator.serverCapability,
|
|
239
|
+
~labelField as _,
|
|
240
|
+
~ownerScope: option<(string, string)>=?,
|
|
241
|
+
~retiredScope: option<Reventless.OwnerScope.retiredScope>=?,
|
|
242
|
+
): option<JSON.t> => {
|
|
243
|
+
let table = QueryDbStorage_Postgres_Ops.tableName(readModelName)
|
|
244
|
+
let filterDict =
|
|
245
|
+
argsDict->Dict.get("filter")->Option.flatMap(JSON.Decode.object)->Option.getOr(Dict.make())
|
|
246
|
+
let strNonEmpty = k =>
|
|
247
|
+
filterDict
|
|
248
|
+
->Dict.get(k)
|
|
249
|
+
->Option.flatMap(JSON.Decode.string)
|
|
250
|
+
->Option.mapOr(false, s => s->String.length > 0)
|
|
251
|
+
let hasIds =
|
|
252
|
+
filterDict
|
|
253
|
+
->Dict.get("ids")
|
|
254
|
+
->Option.flatMap(JSON.Decode.array)
|
|
255
|
+
->Option.mapOr(false, a => a->Array.length > 0)
|
|
256
|
+
let last = argsDict->Dict.get("last")->Option.flatMap(JSON.Decode.float)
|
|
257
|
+
let before = argsDict->Dict.get("before")->Option.flatMap(JSON.Decode.string)
|
|
258
|
+
if (
|
|
259
|
+
strNonEmpty("search") ||
|
|
260
|
+
strNonEmpty("searchPrefix") ||
|
|
261
|
+
hasIds ||
|
|
262
|
+
last->Option.isSome ||
|
|
263
|
+
before->Option.isSome
|
|
264
|
+
) {
|
|
265
|
+
None
|
|
266
|
+
} else {
|
|
267
|
+
let b = {params: []}
|
|
268
|
+
let whereParts = [notExpired]
|
|
269
|
+
// Into the SQL, before the LIMIT — narrowing the returned page instead
|
|
270
|
+
// would hand back fewer rows than asked for while still claiming a next
|
|
271
|
+
// page. Mirrors the SQLite push-down; the parity harness holds the two
|
|
272
|
+
// and the shared spec to the same answer.
|
|
273
|
+
switch ownerScope {
|
|
274
|
+
| Some((field, required)) =>
|
|
275
|
+
whereParts->Array.push(`${jsonTextC(field)} = ${b->param(JSON.Encode.string(required))}`)
|
|
276
|
+
| None => ()
|
|
277
|
+
}
|
|
278
|
+
switch retiredScope {
|
|
279
|
+
| Some(scope) => whereParts->Array.push(notRetiredC(scope))
|
|
280
|
+
| None => ()
|
|
281
|
+
}
|
|
282
|
+
let valString = v =>
|
|
283
|
+
switch v->JSON.Decode.string {
|
|
284
|
+
| Some(s) => Some(s)
|
|
285
|
+
| None => v->JSON.Decode.float->Option.map(f => Float.toString(f))
|
|
286
|
+
}
|
|
287
|
+
capability.filterFields->Array.forEach(f => {
|
|
288
|
+
switch filterDict->Dict.get(f.name ++ "Eq") {
|
|
289
|
+
| Some(v) if v != JSON.Encode.null =>
|
|
290
|
+
whereParts->Array.push(
|
|
291
|
+
`${jsonTextC(f.name)} = ${b->param(
|
|
292
|
+
JSON.Encode.string(valString(v)->Option.getOr("")),
|
|
293
|
+
)}`,
|
|
294
|
+
)
|
|
295
|
+
| _ => ()
|
|
296
|
+
}
|
|
297
|
+
if f.range {
|
|
298
|
+
switch filterDict->Dict.get(f.name ++ "From") {
|
|
299
|
+
| Some(v) if v != JSON.Encode.null =>
|
|
300
|
+
whereParts->Array.push(
|
|
301
|
+
`${jsonTextC(f.name)} >= ${b->param(
|
|
302
|
+
JSON.Encode.string(valString(v)->Option.getOr("")),
|
|
303
|
+
)}`,
|
|
304
|
+
)
|
|
305
|
+
| _ => ()
|
|
306
|
+
}
|
|
307
|
+
switch filterDict->Dict.get(f.name ++ "To") {
|
|
308
|
+
| Some(v) if v != JSON.Encode.null =>
|
|
309
|
+
whereParts->Array.push(
|
|
310
|
+
`${jsonTextC(f.name)} <= ${b->param(
|
|
311
|
+
JSON.Encode.string(valString(v)->Option.getOr("")),
|
|
312
|
+
)}`,
|
|
313
|
+
)
|
|
314
|
+
| _ => ()
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
})
|
|
318
|
+
let orderByDict = argsDict->Dict.get("orderBy")->Option.flatMap(JSON.Decode.object)
|
|
319
|
+
let orderByField =
|
|
320
|
+
orderByDict->Option.flatMap(ob => ob->Dict.get("field"))->Option.flatMap(JSON.Decode.string)
|
|
321
|
+
let isDesc =
|
|
322
|
+
orderByDict
|
|
323
|
+
->Option.flatMap(ob => ob->Dict.get("direction"))
|
|
324
|
+
->Option.flatMap(JSON.Decode.string)
|
|
325
|
+
->Option.getOr("ASC") == "DESC"
|
|
326
|
+
let cursorExpr = switch orderByField {
|
|
327
|
+
| Some(f) => jsonTextC(f)
|
|
328
|
+
| None => idExprC
|
|
329
|
+
}
|
|
330
|
+
let afterCursor = argsDict->Dict.get("after")->Option.flatMap(JSON.Decode.string)
|
|
331
|
+
switch afterCursor {
|
|
332
|
+
| Some(c) =>
|
|
333
|
+
whereParts->Array.push(
|
|
334
|
+
`${cursorExpr} ${isDesc ? "<" : ">"} ${b->param(
|
|
335
|
+
JSON.Encode.string(ReventlessCore.QueryDbListQuery.decodeCursor(c)),
|
|
336
|
+
)}`,
|
|
337
|
+
)
|
|
338
|
+
| None => ()
|
|
339
|
+
}
|
|
340
|
+
let orderClause = switch orderByField {
|
|
341
|
+
| Some(f) => `${jsonTextC(f)} ${isDesc ? "DESC" : "ASC"}, ${idExprC} ASC`
|
|
342
|
+
| None => `${idExprC} ASC`
|
|
343
|
+
}
|
|
344
|
+
let pageSize =
|
|
345
|
+
argsDict
|
|
346
|
+
->Dict.get("first")
|
|
347
|
+
->Option.flatMap(JSON.Decode.float)
|
|
348
|
+
->Option.map(Float.toInt)
|
|
349
|
+
->Option.getOr(ReventlessCore.QueryDbListQuery.defaultListPageSize)
|
|
350
|
+
let sql = `SELECT partition_key, item FROM ${table} WHERE ${whereParts->Array.join(
|
|
351
|
+
" AND ",
|
|
352
|
+
)} ORDER BY ${orderClause} LIMIT ${b->param(JSON.Encode.int(pageSize + 1))}`
|
|
353
|
+
let rows =
|
|
354
|
+
(await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=true, ...))
|
|
355
|
+
let hasMore = rows->Array.length > pageSize
|
|
356
|
+
let pageItems = rows->Array.slice(~start=0, ~end=pageSize)
|
|
357
|
+
let cursorField = orderByField->Option.getOr("id")
|
|
358
|
+
let cursorValueOf = item =>
|
|
359
|
+
ReventlessCore.QueryDbListQuery.getFieldString(item, cursorField)->Option.getOr(
|
|
360
|
+
ReventlessCore.QueryDbListQuery.getId(item),
|
|
361
|
+
)
|
|
362
|
+
Some(
|
|
363
|
+
ReventlessCore.QueryDbListQuery.buildConnection(
|
|
364
|
+
~pageItems,
|
|
365
|
+
~hasNextPage=hasMore,
|
|
366
|
+
// Same rule the spec uses, because the parity suite compares them: a
|
|
367
|
+
// forward page reached by a cursor has one behind it. Hardcoding false
|
|
368
|
+
// made Prev disappear on exactly the pages that have a previous one.
|
|
369
|
+
~hasPreviousPage=afterCursor->Option.isSome,
|
|
370
|
+
~cursorValueOf,
|
|
371
|
+
),
|
|
372
|
+
)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Sub-id connection push-down: the `{single}Items(id, filter, first/after/
|
|
377
|
+
// last/before)` query. Keyset over `sub_key` WITHIN one partition — a page
|
|
378
|
+
// reads only what it returns. Reproduces QueryDbResolvers_GraphQL's items
|
|
379
|
+
// resolver (SortKey_Filter + forward/backward keyset), entirely in SQL since
|
|
380
|
+
// sub_key IS the sort key. Cursor = base64 of the sub_key value; comparisons
|
|
381
|
+
// use COLLATE "C" (byte order) to match JS string `<`. Unlike the main list
|
|
382
|
+
// there is no declined-shape fallback — every items shape maps to SQL.
|
|
383
|
+
let itemsPage = async (
|
|
384
|
+
~readModelName,
|
|
385
|
+
~subIdField as _: string,
|
|
386
|
+
~id: string,
|
|
387
|
+
~argsDict: dict<JSON.t>,
|
|
388
|
+
~ownerScope: option<(string, string)>=?,
|
|
389
|
+
~retiredScope: option<Reventless.OwnerScope.retiredScope>=?,
|
|
390
|
+
): JSON.t => {
|
|
391
|
+
let table = QueryDbStorage_Postgres_Ops.tableName(readModelName)
|
|
392
|
+
let filterDict =
|
|
393
|
+
argsDict->Dict.get("filter")->Option.flatMap(JSON.Decode.object)->Option.getOr(Dict.make())
|
|
394
|
+
let fstr = k => filterDict->Dict.get(k)->Option.flatMap(JSON.Decode.string)
|
|
395
|
+
let orderDesc = fstr("order")->Option.mapOr(false, o => o == "DESC")
|
|
396
|
+
let last =
|
|
397
|
+
argsDict->Dict.get("last")->Option.flatMap(JSON.Decode.float)->Option.map(Float.toInt)
|
|
398
|
+
let first =
|
|
399
|
+
argsDict->Dict.get("first")->Option.flatMap(JSON.Decode.float)->Option.map(Float.toInt)
|
|
400
|
+
let after = argsDict->Dict.get("after")->Option.flatMap(JSON.Decode.string)
|
|
401
|
+
let before = argsDict->Dict.get("before")->Option.flatMap(JSON.Decode.string)
|
|
402
|
+
let isBackward = last->Option.isSome
|
|
403
|
+
|
|
404
|
+
let sk = `sub_key COLLATE "C"`
|
|
405
|
+
let b = {params: []}
|
|
406
|
+
let where = [`partition_key = ${b->param(JSON.Encode.string(id))}`, notExpired]
|
|
407
|
+
// Before the keyset window and the LIMIT, for the same reason as `listPage`.
|
|
408
|
+
switch ownerScope {
|
|
409
|
+
| Some((field, required)) =>
|
|
410
|
+
where->Array.push(`${jsonTextC(field)} = ${b->param(JSON.Encode.string(required))}`)
|
|
411
|
+
| None => ()
|
|
412
|
+
}
|
|
413
|
+
switch retiredScope {
|
|
414
|
+
| Some(scope) => where->Array.push(notRetiredC(scope))
|
|
415
|
+
| None => ()
|
|
416
|
+
}
|
|
417
|
+
fstr("prefix")->Option.forEach(p =>
|
|
418
|
+
where->Array.push(`starts_with(sub_key, ${b->param(JSON.Encode.string(p))})`)
|
|
419
|
+
)
|
|
420
|
+
fstr("from")->Option.forEach(f =>
|
|
421
|
+
where->Array.push(`${sk} >= ${b->param(JSON.Encode.string(f))}`)
|
|
422
|
+
)
|
|
423
|
+
fstr("to")->Option.forEach(t =>
|
|
424
|
+
where->Array.push(`${sk} <= ${b->param(JSON.Encode.string(t))}`)
|
|
425
|
+
)
|
|
426
|
+
fstr("eq")->Option.forEach(e => where->Array.push(`${sk} = ${b->param(JSON.Encode.string(e))}`))
|
|
427
|
+
// Keyset: forward excludes ≤ after; backward excludes ≥ before.
|
|
428
|
+
switch (isBackward, after, before) {
|
|
429
|
+
| (false, Some(c), _) =>
|
|
430
|
+
where->Array.push(
|
|
431
|
+
`${sk} > ${b->param(JSON.Encode.string(ReventlessCore.QueryDbListQuery.decodeCursor(c)))}`,
|
|
432
|
+
)
|
|
433
|
+
| (true, _, Some(c)) =>
|
|
434
|
+
where->Array.push(
|
|
435
|
+
`${sk} < ${b->param(JSON.Encode.string(ReventlessCore.QueryDbListQuery.decodeCursor(c)))}`,
|
|
436
|
+
)
|
|
437
|
+
| _ => ()
|
|
438
|
+
}
|
|
439
|
+
// Page-fetch direction is the LOGICAL order forward, and its OPPOSITE
|
|
440
|
+
// backward (take the N nearest `before`, then reverse to logical) — mirrors
|
|
441
|
+
// the resolver's `reverse = isBackward ? !orderDesc : orderDesc`.
|
|
442
|
+
let fetchDesc = isBackward ? !orderDesc : orderDesc
|
|
443
|
+
let pageSize =
|
|
444
|
+
(isBackward ? last : first)->Option.getOr(ReventlessCore.QueryDbListQuery.defaultListPageSize)
|
|
445
|
+
let sql = `SELECT partition_key, sub_key, item FROM ${table} WHERE ${where->Array.join(
|
|
446
|
+
" AND ",
|
|
447
|
+
)} ORDER BY ${sk} ${fetchDesc ? "DESC" : "ASC"} LIMIT ${b->param(
|
|
448
|
+
JSON.Encode.int(pageSize + 1),
|
|
449
|
+
)}`
|
|
450
|
+
let rows = await P.pool->PgDriver.query(sql, b.params)
|
|
451
|
+
let hasMore = rows->Array.length > pageSize
|
|
452
|
+
let taken = rows->Array.slice(~start=0, ~end=pageSize)
|
|
453
|
+
// Backward fetched in reverse-logical order → flip back to logical.
|
|
454
|
+
let logical = isBackward ? taken->Array.toReversed : taken
|
|
455
|
+
let pageItems = logical->Array.map(decodeRow(~withId=false, ...))
|
|
456
|
+
// Cursor = the row's sub_key (== the item's subIdField value).
|
|
457
|
+
let subKeyOf = (row: dict<JSON.t>) =>
|
|
458
|
+
switch row->Dict.get("sub_key") {
|
|
459
|
+
| Some(JSON.String(s)) => s
|
|
460
|
+
| _ => ""
|
|
461
|
+
}
|
|
462
|
+
let cursors = logical->Array.map(subKeyOf)
|
|
463
|
+
let edges = pageItems->Array.mapWithIndex((item, i) =>
|
|
464
|
+
Obj.magic({
|
|
465
|
+
"node": item,
|
|
466
|
+
"cursor": ReventlessCore.QueryDbListQuery.encodeCursor(cursors->Array.getUnsafe(i)),
|
|
467
|
+
})
|
|
468
|
+
)
|
|
469
|
+
let startCursor =
|
|
470
|
+
cursors->Array.get(0)->Option.map(ReventlessCore.QueryDbListQuery.encodeCursor)
|
|
471
|
+
let endCursor =
|
|
472
|
+
cursors
|
|
473
|
+
->Array.get(cursors->Array.length - 1)
|
|
474
|
+
->Option.map(ReventlessCore.QueryDbListQuery.encodeCursor)
|
|
475
|
+
Obj.magic({
|
|
476
|
+
"edges": edges,
|
|
477
|
+
"pageInfo": {
|
|
478
|
+
"hasNextPage": !isBackward && hasMore,
|
|
479
|
+
"hasPreviousPage": isBackward && hasMore,
|
|
480
|
+
"startCursor": startCursor->Nullable.fromOption,
|
|
481
|
+
"endCursor": endCursor->Nullable.fromOption,
|
|
482
|
+
},
|
|
483
|
+
})
|
|
484
|
+
}
|
|
127
485
|
}
|