@reventlessdev/reventless-postgres 3.0.0-alpha.4 → 3.0.0-alpha.41
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 +293 -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 +3 -1
- package/lib/bs/compiler-info.json +2 -2
- 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 +32 -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 +350 -0
- package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res.mjs +380 -0
- package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/bs/src/EventLogChangeFeed.ast +0 -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 +20 -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 +180 -0
- package/lib/bs/src/EventLogStorage_Postgres_Ops.res.mjs +202 -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/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/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/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 +11 -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 +259 -0
- package/lib/bs/src/QueryEnginePostgres.res.mjs +165 -0
- 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/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 +312 -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 +350 -0
- package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/EventLogChangeFeed.ast +0 -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 +180 -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/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/PgSchema-ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/PgSchema-ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/PgSchema.ast +0 -0
- 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 +11 -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 +259 -0
- package/lib/ocaml/QueryEnginePostgresListPageTest.res +312 -0
- package/lib/ocaml/ReventlessPostgres.cmi +0 -0
- package/lib/ocaml/ReventlessPostgres.cmt +0 -0
- package/lib/ocaml/ReventlessPostgres.mlmap +4 -0
- package/package.json +12 -12
- package/rescript.json +2 -1
- package/src/DcbEventLogStorage_Postgres.res +25 -340
- package/src/DcbEventLogStorage_Postgres.res.mjs +32 -348
- package/src/DcbEventLogStorage_Postgres_Ops.res +350 -0
- package/src/DcbEventLogStorage_Postgres_Ops.res.mjs +380 -0
- package/src/EventLogStorage_Postgres.res +12 -170
- package/src/EventLogStorage_Postgres.res.mjs +20 -186
- package/src/EventLogStorage_Postgres_Ops.res +180 -0
- package/src/EventLogStorage_Postgres_Ops.res.mjs +202 -0
- package/src/QueryDbStorage_Postgres.res +11 -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 +259 -0
- package/src/QueryEnginePostgres.res.mjs +165 -0
- package/tests/QueryEnginePostgresListPageTest.res +312 -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 -377
|
@@ -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/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 =>
|
|
18
|
+
s->String.replaceRegExp(%re("/[^A-Za-z0-9_]/g"), "_")
|
|
19
|
+
|
|
20
|
+
let notExpiredClause = "(expires_at IS NULL OR expires_at > extract(epoch from now()))"
|
|
21
|
+
|
|
22
|
+
// JSONB text extraction for a single top-level field.
|
|
23
|
+
let jsonField = (field: string): string =>
|
|
24
|
+
`(item->>'${field->String.replaceAll("'", "''")}')`
|
|
25
|
+
|
|
26
|
+
let compositeExpr = (fields: array<string>, sep: string): string => {
|
|
27
|
+
let escapedSep = sep->String.replaceAll("'", "''")
|
|
28
|
+
fields->Array.map(jsonField)->Array.join(` || '${escapedSep}' || `)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let indexExpressions = (idx: indexConfig): (string, option<string>) => {
|
|
32
|
+
let pkExpr = switch idx.pkFields {
|
|
33
|
+
| Some(fields) if fields->Array.length > 0 => compositeExpr(fields, idx.pkSep->Option.getOr("/"))
|
|
34
|
+
| _ =>
|
|
35
|
+
switch idx.idField {
|
|
36
|
+
| Some(field) => jsonField(field)
|
|
37
|
+
| None => jsonField(idx.index)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
let skExpr = switch idx.skFields {
|
|
41
|
+
| Some(fields) if fields->Array.length > 0 =>
|
|
42
|
+
Some(compositeExpr(fields, idx.skSep->Option.getOr("/")))
|
|
43
|
+
| _ =>
|
|
44
|
+
switch idx.subIdField {
|
|
45
|
+
| Some(field) => Some(jsonField(field))
|
|
46
|
+
| None => None
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
(pkExpr, skExpr)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let ensureTable = async (~pool, ~table) => {
|
|
53
|
+
await pool->PgDriver.exec(
|
|
54
|
+
`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))`,
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let ensureIndexes = async (~pool, ~table, ~indexes: array<indexConfig>) => {
|
|
59
|
+
for i in 0 to indexes->Array.length - 1 {
|
|
60
|
+
let idx = indexes->Array.getUnsafe(i)
|
|
61
|
+
let (pkExpr, skExprOpt) = indexExpressions(idx)
|
|
62
|
+
let indexName = `idx_${table}_${sanitizeIdent(idx.index)}`
|
|
63
|
+
let cols = switch skExprOpt {
|
|
64
|
+
| Some(skExpr) => `${pkExpr}, ${skExpr}`
|
|
65
|
+
| None => pkExpr
|
|
66
|
+
}
|
|
67
|
+
await pool->PgDriver.exec(`CREATE INDEX IF NOT EXISTS ${indexName} ON ${table} (${cols})`)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
let decodeItem = (row: dict<JSON.t>): JSON.t =>
|
|
72
|
+
row->Dict.get("item")->Option.getOr(JSON.Encode.null)
|
|
73
|
+
|
|
74
|
+
let computeSubKey = (item: JSON.t, subIdField: option<string>): string =>
|
|
75
|
+
switch subIdField {
|
|
76
|
+
| None => ""
|
|
77
|
+
| Some(field) =>
|
|
78
|
+
switch item->JSON.Decode.object->Option.flatMap(o => o->Dict.get(field)) {
|
|
79
|
+
| Some(JSON.String(s)) => s
|
|
80
|
+
| _ => ""
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let withId = (item: JSON.t, partitionKey: string): JSON.t =>
|
|
85
|
+
switch item->JSON.Decode.object {
|
|
86
|
+
| Some(obj) if obj->Dict.get("id")->Option.isNone =>
|
|
87
|
+
let copy = Dict.copy(obj)
|
|
88
|
+
copy->Dict.set("id", JSON.Encode.string(partitionKey))
|
|
89
|
+
JSON.Encode.object(copy)
|
|
90
|
+
| _ => item
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Plain operation set for a read model's qdb table. Exposed separately from
|
|
94
|
+
// `makeStorage` so the deployed-Lambda runtime (reventless-aws) can bind ops
|
|
95
|
+
// without touching the Pulumi-shaped `storage` record.
|
|
96
|
+
let makeOperations = (
|
|
97
|
+
~pool: PgDriver.pool,
|
|
98
|
+
~name: string,
|
|
99
|
+
~indexes: array<indexConfig>,
|
|
100
|
+
~subIdField: option<string>,
|
|
101
|
+
): QueryDb_Adapter.operations => {
|
|
102
|
+
let table = tableName(name)
|
|
103
|
+
// Schema setup is async and LAZY: kicked off by the first operation, not at
|
|
104
|
+
// construction. A deploy-time caller may build the ops on a machine that
|
|
105
|
+
// cannot reach the database (VPC-private RDS) — only the runtime, which
|
|
106
|
+
// actually calls an operation, may open a connection. Subsequent operations
|
|
107
|
+
// await the same promise (table + index creation runs exactly once).
|
|
108
|
+
let readyRef: ref<option<promise<unit>>> = ref(None)
|
|
109
|
+
let ready = () =>
|
|
110
|
+
switch readyRef.contents {
|
|
111
|
+
| Some(p) => p
|
|
112
|
+
| None =>
|
|
113
|
+
let p = {
|
|
114
|
+
open Promise
|
|
115
|
+
ensureTable(~pool, ~table)->then(() => ensureIndexes(~pool, ~table, ~indexes))
|
|
116
|
+
}
|
|
117
|
+
readyRef := Some(p)
|
|
118
|
+
p
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
let rowsFor = async (id: string): array<JSON.t> => {
|
|
122
|
+
await ready()
|
|
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
|
+
))->Array.map(decodeItem)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
let saveOne = async (id: string, state: JSON.t, ttl: option<int>) => {
|
|
130
|
+
await ready()
|
|
131
|
+
let subKey = computeSubKey(state, subIdField)
|
|
132
|
+
let expiresAt = switch ttl {
|
|
133
|
+
| Some(t) => JSON.Encode.int(t)
|
|
134
|
+
| None => JSON.Encode.null
|
|
135
|
+
}
|
|
136
|
+
let _ = await pool->PgDriver.query(
|
|
137
|
+
`INSERT INTO ${table}(partition_key, sub_key, item, expires_at)
|
|
138
|
+
VALUES ($1, $2, $3::jsonb, $4)
|
|
139
|
+
ON CONFLICT (partition_key, sub_key)
|
|
140
|
+
DO UPDATE SET item = EXCLUDED.item, expires_at = EXCLUDED.expires_at`,
|
|
141
|
+
[
|
|
142
|
+
JSON.Encode.string(id),
|
|
143
|
+
JSON.Encode.string(subKey),
|
|
144
|
+
JSON.Encode.string(JSON.stringify(state)),
|
|
145
|
+
expiresAt,
|
|
146
|
+
],
|
|
147
|
+
)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let load: QueryDb.load<string, JSON.t> = async id => Ok(await rowsFor(id))
|
|
151
|
+
|
|
152
|
+
let loadStream: QueryDb.loadStream<string, JSON.t> =
|
|
153
|
+
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
|
|
@@ -122,6 +122,265 @@ module Make = (P: {let pool: PgDriver.pool}) => {
|
|
|
122
122
|
(await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=true, ...))
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
// GraphQL resolver push-downs (B3.2). The Postgres resolver Lambda dispatches
|
|
127
|
+
// these; they parallel the SQLite backend's `lookupByField` / `listPage` (the
|
|
128
|
+
// ones registered on LocalBus). All return `id`-carrying items (COALESCE from
|
|
129
|
+
// partition_key), matching the shape `QueryDbListQuery.run` operates over so
|
|
130
|
+
// the connection helpers agree.
|
|
131
|
+
//
|
|
132
|
+
// Text comparisons use `COLLATE "C"` (byte order — memcmp), the Postgres
|
|
133
|
+
// analogue of SQLite's BINARY collation, so cursor/order comparisons match
|
|
134
|
+
// JS string `<` for the ASCII id/status/name fields used as sort/filter keys.
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
// Equality lookup on an indexed JSON field — rides the expression index
|
|
138
|
+
// (`ensureIndexes`) instead of scanning. String comparison mirrors the
|
|
139
|
+
// resolver's JS path (which only matched string-typed fields).
|
|
140
|
+
let indexLookup = async (~readModelName, field: string, value: string): array<JSON.t> => {
|
|
141
|
+
let table = QueryDbStorage_Postgres.tableName(readModelName)
|
|
142
|
+
let b = {params: []}
|
|
143
|
+
let sql = `SELECT partition_key, item FROM ${table} WHERE ${col(field)} = ${b->param(
|
|
144
|
+
JSON.Encode.string(value),
|
|
145
|
+
)} AND ${notExpired}`
|
|
146
|
+
(await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=true, ...))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Batched-by-ids lookup: BatchGetItem analogue over the projection's own
|
|
150
|
+
// table. Single-key projections only (partition_key = the id). Missing ids
|
|
151
|
+
// drop out of the response (no cardinality preservation), matching
|
|
152
|
+
// BatchGetItem semantics.
|
|
153
|
+
let byIds = async (~readModelName, ids: array<string>): array<JSON.t> => {
|
|
154
|
+
if ids->Array.length == 0 {
|
|
155
|
+
[]
|
|
156
|
+
} else {
|
|
157
|
+
let table = QueryDbStorage_Postgres.tableName(readModelName)
|
|
158
|
+
let b = {params: []}
|
|
159
|
+
let idsJson = JSON.Encode.array(ids->Array.map(JSON.Encode.string))
|
|
160
|
+
let sql = `SELECT partition_key, item FROM ${table} WHERE partition_key = ANY(${b->param(
|
|
161
|
+
idsJson,
|
|
162
|
+
)}::text[]) AND ${notExpired}`
|
|
163
|
+
(await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=true, ...))
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// COALESCE(item->>'id', partition_key) — the effective id, byte-ordered.
|
|
168
|
+
let idExprC = `COALESCE(item->>'id', partition_key) COLLATE "C"`
|
|
169
|
+
let jsonTextC = (field: string): string => `${col(field)} COLLATE "C"`
|
|
170
|
+
|
|
171
|
+
// Connection-list push-down. Builds `item->>'field'` predicates + keyset
|
|
172
|
+
// WHERE + `ORDER BY … LIMIT pageSize+1` so a page reads only what it returns
|
|
173
|
+
// rather than the whole read model. Reproduces `QueryDbListQuery` semantics
|
|
174
|
+
// exactly for the shapes it handles; returns `None` (→ the resolver Lambda
|
|
175
|
+
// falls back to `scan` + the shared spec) for shapes not bit-exact in SQL:
|
|
176
|
+
// case-insensitive search/searchPrefix, Relay-global-id `ids`, and backward
|
|
177
|
+
// pagination (last/before). Cursor values, edges, and pageInfo are built by
|
|
178
|
+
// the SAME `QueryDbListQuery` helpers the fallback uses, so only the
|
|
179
|
+
// WHERE/ORDER/LIMIT needs to match — the parity harness asserts it does
|
|
180
|
+
// (SQLite ≡ Postgres ≡ spec). Mirrors QueryDbStorage_Sqlite.listPage.
|
|
181
|
+
let listPage = async (
|
|
182
|
+
~readModelName,
|
|
183
|
+
~argsDict: dict<JSON.t>,
|
|
184
|
+
~capability: GraphQL_FragmentGenerator.serverCapability,
|
|
185
|
+
~labelField as _,
|
|
186
|
+
): option<JSON.t> => {
|
|
187
|
+
let table = QueryDbStorage_Postgres.tableName(readModelName)
|
|
188
|
+
let filterDict =
|
|
189
|
+
argsDict->Dict.get("filter")->Option.flatMap(JSON.Decode.object)->Option.getOr(Dict.make())
|
|
190
|
+
let strNonEmpty = k =>
|
|
191
|
+
filterDict
|
|
192
|
+
->Dict.get(k)
|
|
193
|
+
->Option.flatMap(JSON.Decode.string)
|
|
194
|
+
->Option.mapOr(false, s => s->String.length > 0)
|
|
195
|
+
let hasIds =
|
|
196
|
+
filterDict
|
|
197
|
+
->Dict.get("ids")
|
|
198
|
+
->Option.flatMap(JSON.Decode.array)
|
|
199
|
+
->Option.mapOr(false, a => a->Array.length > 0)
|
|
200
|
+
let last = argsDict->Dict.get("last")->Option.flatMap(JSON.Decode.float)
|
|
201
|
+
let before = argsDict->Dict.get("before")->Option.flatMap(JSON.Decode.string)
|
|
202
|
+
if (
|
|
203
|
+
strNonEmpty("search") ||
|
|
204
|
+
strNonEmpty("searchPrefix") ||
|
|
205
|
+
hasIds ||
|
|
206
|
+
last->Option.isSome ||
|
|
207
|
+
before->Option.isSome
|
|
208
|
+
) {
|
|
209
|
+
None
|
|
210
|
+
} else {
|
|
211
|
+
let b = {params: []}
|
|
212
|
+
let whereParts = [notExpired]
|
|
213
|
+
let valString = v =>
|
|
214
|
+
switch v->JSON.Decode.string {
|
|
215
|
+
| Some(s) => Some(s)
|
|
216
|
+
| None => v->JSON.Decode.float->Option.map(f => Float.toString(f))
|
|
217
|
+
}
|
|
218
|
+
capability.filterFields->Array.forEach(f => {
|
|
219
|
+
switch filterDict->Dict.get(f.name ++ "Eq") {
|
|
220
|
+
| Some(v) when v != JSON.Encode.null =>
|
|
221
|
+
whereParts->Array.push(
|
|
222
|
+
`${jsonTextC(f.name)} = ${b->param(JSON.Encode.string(valString(v)->Option.getOr("")))}`,
|
|
223
|
+
)
|
|
224
|
+
| _ => ()
|
|
225
|
+
}
|
|
226
|
+
if f.range {
|
|
227
|
+
switch filterDict->Dict.get(f.name ++ "From") {
|
|
228
|
+
| Some(v) when v != JSON.Encode.null =>
|
|
229
|
+
whereParts->Array.push(
|
|
230
|
+
`${jsonTextC(f.name)} >= ${b->param(
|
|
231
|
+
JSON.Encode.string(valString(v)->Option.getOr("")),
|
|
232
|
+
)}`,
|
|
233
|
+
)
|
|
234
|
+
| _ => ()
|
|
235
|
+
}
|
|
236
|
+
switch filterDict->Dict.get(f.name ++ "To") {
|
|
237
|
+
| Some(v) when v != JSON.Encode.null =>
|
|
238
|
+
whereParts->Array.push(
|
|
239
|
+
`${jsonTextC(f.name)} <= ${b->param(
|
|
240
|
+
JSON.Encode.string(valString(v)->Option.getOr("")),
|
|
241
|
+
)}`,
|
|
242
|
+
)
|
|
243
|
+
| _ => ()
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
})
|
|
247
|
+
let orderByDict = argsDict->Dict.get("orderBy")->Option.flatMap(JSON.Decode.object)
|
|
248
|
+
let orderByField =
|
|
249
|
+
orderByDict->Option.flatMap(ob => ob->Dict.get("field"))->Option.flatMap(JSON.Decode.string)
|
|
250
|
+
let isDesc =
|
|
251
|
+
orderByDict
|
|
252
|
+
->Option.flatMap(ob => ob->Dict.get("direction"))
|
|
253
|
+
->Option.flatMap(JSON.Decode.string)
|
|
254
|
+
->Option.getOr("ASC") == "DESC"
|
|
255
|
+
let cursorExpr = switch orderByField {
|
|
256
|
+
| Some(f) => jsonTextC(f)
|
|
257
|
+
| None => idExprC
|
|
258
|
+
}
|
|
259
|
+
switch argsDict->Dict.get("after")->Option.flatMap(JSON.Decode.string) {
|
|
260
|
+
| Some(c) =>
|
|
261
|
+
whereParts->Array.push(
|
|
262
|
+
`${cursorExpr} ${isDesc ? "<" : ">"} ${b->param(
|
|
263
|
+
JSON.Encode.string(ReventlessCore.QueryDbListQuery.decodeCursor(c)),
|
|
264
|
+
)}`,
|
|
265
|
+
)
|
|
266
|
+
| None => ()
|
|
267
|
+
}
|
|
268
|
+
let orderClause = switch orderByField {
|
|
269
|
+
| Some(f) => `${jsonTextC(f)} ${isDesc ? "DESC" : "ASC"}, ${idExprC} ASC`
|
|
270
|
+
| None => `${idExprC} ASC`
|
|
271
|
+
}
|
|
272
|
+
let pageSize =
|
|
273
|
+
argsDict
|
|
274
|
+
->Dict.get("first")
|
|
275
|
+
->Option.flatMap(JSON.Decode.float)
|
|
276
|
+
->Option.map(Float.toInt)
|
|
277
|
+
->Option.getOr(ReventlessCore.QueryDbListQuery.defaultListPageSize)
|
|
278
|
+
let sql = `SELECT partition_key, item FROM ${table} WHERE ${whereParts->Array.join(
|
|
279
|
+
" AND ",
|
|
280
|
+
)} ORDER BY ${orderClause} LIMIT ${b->param(JSON.Encode.int(pageSize + 1))}`
|
|
281
|
+
let rows = (await P.pool->PgDriver.query(sql, b.params))->Array.map(decodeRow(~withId=true, ...))
|
|
282
|
+
let hasMore = rows->Array.length > pageSize
|
|
283
|
+
let pageItems = rows->Array.slice(~start=0, ~end=pageSize)
|
|
284
|
+
let cursorField = orderByField->Option.getOr("id")
|
|
285
|
+
let cursorValueOf = item =>
|
|
286
|
+
ReventlessCore.QueryDbListQuery.getFieldString(item, cursorField)->Option.getOr(
|
|
287
|
+
ReventlessCore.QueryDbListQuery.getId(item),
|
|
288
|
+
)
|
|
289
|
+
Some(
|
|
290
|
+
ReventlessCore.QueryDbListQuery.buildConnection(
|
|
291
|
+
~pageItems,
|
|
292
|
+
~hasNextPage=hasMore,
|
|
293
|
+
~hasPreviousPage=false,
|
|
294
|
+
~cursorValueOf,
|
|
295
|
+
),
|
|
296
|
+
)
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Sub-id connection push-down: the `{single}Items(id, filter, first/after/
|
|
301
|
+
// last/before)` query. Keyset over `sub_key` WITHIN one partition — a page
|
|
302
|
+
// reads only what it returns. Reproduces QueryDbResolvers_GraphQL's items
|
|
303
|
+
// resolver (SortKey_Filter + forward/backward keyset), entirely in SQL since
|
|
304
|
+
// sub_key IS the sort key. Cursor = base64 of the sub_key value; comparisons
|
|
305
|
+
// use COLLATE "C" (byte order) to match JS string `<`. Unlike the main list
|
|
306
|
+
// there is no declined-shape fallback — every items shape maps to SQL.
|
|
307
|
+
let itemsPage = async (
|
|
308
|
+
~readModelName,
|
|
309
|
+
~subIdField as _: string,
|
|
310
|
+
~id: string,
|
|
311
|
+
~argsDict: dict<JSON.t>,
|
|
312
|
+
): JSON.t => {
|
|
313
|
+
let table = QueryDbStorage_Postgres.tableName(readModelName)
|
|
314
|
+
let filterDict =
|
|
315
|
+
argsDict->Dict.get("filter")->Option.flatMap(JSON.Decode.object)->Option.getOr(Dict.make())
|
|
316
|
+
let fstr = k => filterDict->Dict.get(k)->Option.flatMap(JSON.Decode.string)
|
|
317
|
+
let orderDesc = fstr("order")->Option.mapOr(false, o => o == "DESC")
|
|
318
|
+
let last = argsDict->Dict.get("last")->Option.flatMap(JSON.Decode.float)->Option.map(Float.toInt)
|
|
319
|
+
let first = argsDict->Dict.get("first")->Option.flatMap(JSON.Decode.float)->Option.map(Float.toInt)
|
|
320
|
+
let after = argsDict->Dict.get("after")->Option.flatMap(JSON.Decode.string)
|
|
321
|
+
let before = argsDict->Dict.get("before")->Option.flatMap(JSON.Decode.string)
|
|
322
|
+
let isBackward = last->Option.isSome
|
|
323
|
+
|
|
324
|
+
let sk = `sub_key COLLATE "C"`
|
|
325
|
+
let b = {params: []}
|
|
326
|
+
let where = [`partition_key = ${b->param(JSON.Encode.string(id))}`, notExpired]
|
|
327
|
+
fstr("prefix")->Option.forEach(p =>
|
|
328
|
+
where->Array.push(`starts_with(sub_key, ${b->param(JSON.Encode.string(p))})`)
|
|
329
|
+
)
|
|
330
|
+
fstr("from")->Option.forEach(f => where->Array.push(`${sk} >= ${b->param(JSON.Encode.string(f))}`))
|
|
331
|
+
fstr("to")->Option.forEach(t => where->Array.push(`${sk} <= ${b->param(JSON.Encode.string(t))}`))
|
|
332
|
+
fstr("eq")->Option.forEach(e => where->Array.push(`${sk} = ${b->param(JSON.Encode.string(e))}`))
|
|
333
|
+
// Keyset: forward excludes ≤ after; backward excludes ≥ before.
|
|
334
|
+
switch (isBackward, after, before) {
|
|
335
|
+
| (false, Some(c), _) =>
|
|
336
|
+
where->Array.push(`${sk} > ${b->param(JSON.Encode.string(ReventlessCore.QueryDbListQuery.decodeCursor(c)))}`)
|
|
337
|
+
| (true, _, Some(c)) =>
|
|
338
|
+
where->Array.push(`${sk} < ${b->param(JSON.Encode.string(ReventlessCore.QueryDbListQuery.decodeCursor(c)))}`)
|
|
339
|
+
| _ => ()
|
|
340
|
+
}
|
|
341
|
+
// Page-fetch direction is the LOGICAL order forward, and its OPPOSITE
|
|
342
|
+
// backward (take the N nearest `before`, then reverse to logical) — mirrors
|
|
343
|
+
// the resolver's `reverse = isBackward ? !orderDesc : orderDesc`.
|
|
344
|
+
let fetchDesc = isBackward ? !orderDesc : orderDesc
|
|
345
|
+
let pageSize = (isBackward ? last : first)->Option.getOr(ReventlessCore.QueryDbListQuery.defaultListPageSize)
|
|
346
|
+
let sql = `SELECT partition_key, sub_key, item FROM ${table} WHERE ${where->Array.join(
|
|
347
|
+
" AND ",
|
|
348
|
+
)} ORDER BY ${sk} ${fetchDesc ? "DESC" : "ASC"} LIMIT ${b->param(JSON.Encode.int(pageSize + 1))}`
|
|
349
|
+
let rows = await P.pool->PgDriver.query(sql, b.params)
|
|
350
|
+
let hasMore = rows->Array.length > pageSize
|
|
351
|
+
let taken = rows->Array.slice(~start=0, ~end=pageSize)
|
|
352
|
+
// Backward fetched in reverse-logical order → flip back to logical.
|
|
353
|
+
let logical = isBackward ? taken->Array.toReversed : taken
|
|
354
|
+
let pageItems = logical->Array.map(decodeRow(~withId=false, ...))
|
|
355
|
+
// Cursor = the row's sub_key (== the item's subIdField value).
|
|
356
|
+
let subKeyOf = (row: dict<JSON.t>) =>
|
|
357
|
+
switch row->Dict.get("sub_key") {
|
|
358
|
+
| Some(JSON.String(s)) => s
|
|
359
|
+
| _ => ""
|
|
360
|
+
}
|
|
361
|
+
let cursors = logical->Array.map(subKeyOf)
|
|
362
|
+
let edges =
|
|
363
|
+
pageItems->Array.mapWithIndex((item, i) =>
|
|
364
|
+
Obj.magic({
|
|
365
|
+
"node": item,
|
|
366
|
+
"cursor": ReventlessCore.QueryDbListQuery.encodeCursor(cursors->Array.getUnsafe(i)),
|
|
367
|
+
})
|
|
368
|
+
)
|
|
369
|
+
let startCursor =
|
|
370
|
+
cursors->Array.get(0)->Option.map(ReventlessCore.QueryDbListQuery.encodeCursor)
|
|
371
|
+
let endCursor =
|
|
372
|
+
cursors->Array.get(cursors->Array.length - 1)->Option.map(ReventlessCore.QueryDbListQuery.encodeCursor)
|
|
373
|
+
Obj.magic({
|
|
374
|
+
"edges": edges,
|
|
375
|
+
"pageInfo": {
|
|
376
|
+
"hasNextPage": !isBackward && hasMore,
|
|
377
|
+
"hasPreviousPage": isBackward && hasMore,
|
|
378
|
+
"startCursor": startCursor->Nullable.fromOption,
|
|
379
|
+
"endCursor": endCursor->Nullable.fromOption,
|
|
380
|
+
},
|
|
381
|
+
})
|
|
382
|
+
}
|
|
383
|
+
|
|
125
384
|
let make: QueryDb_Adapter.queryEngineMaker = _allQueryDbs =>
|
|
126
385
|
Pulumi.Output.make({QueryEngine.scan, query})
|
|
127
386
|
}
|