@reventlessdev/reventless-postgres 3.0.0-alpha.2 → 3.0.0-alpha.20

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 (151) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +83 -0
  3. package/lib/bs/.compiler.log +2 -2
  4. package/lib/bs/ReventlessPostgres.cmi +0 -0
  5. package/lib/bs/ReventlessPostgres.cmt +0 -0
  6. package/lib/bs/ReventlessPostgres.mlmap +4 -1
  7. package/lib/bs/compiler-info.json +2 -2
  8. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  9. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
  10. package/lib/bs/src/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  11. package/lib/bs/src/DcbEventLogStorage_Postgres.ast +0 -0
  12. package/lib/bs/src/DcbEventLogStorage_Postgres.res +25 -340
  13. package/lib/bs/src/DcbEventLogStorage_Postgres.res.mjs +32 -348
  14. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  15. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  16. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  17. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.ast +0 -0
  18. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res +350 -0
  19. package/lib/bs/src/DcbEventLogStorage_Postgres_Ops.res.mjs +380 -0
  20. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
  21. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
  22. package/lib/bs/src/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
  23. package/lib/bs/src/EventLogChangeFeed.ast +0 -0
  24. package/lib/bs/src/EventLogChangeFeed.res +184 -0
  25. package/lib/bs/src/EventLogChangeFeed.res.mjs +134 -0
  26. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  27. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
  28. package/lib/bs/src/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  29. package/lib/bs/src/EventLogStorage_Postgres.ast +0 -0
  30. package/lib/bs/src/EventLogStorage_Postgres.res +12 -170
  31. package/lib/bs/src/EventLogStorage_Postgres.res.mjs +20 -186
  32. package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  33. package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  34. package/lib/bs/src/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  35. package/lib/bs/src/EventLogStorage_Postgres_Ops.ast +0 -0
  36. package/lib/bs/src/EventLogStorage_Postgres_Ops.res +180 -0
  37. package/lib/bs/src/EventLogStorage_Postgres_Ops.res.mjs +202 -0
  38. package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmi +0 -0
  39. package/lib/bs/src/PgChangeFeed-ReventlessPostgres.cmt +0 -0
  40. package/lib/bs/src/PgSchema-ReventlessPostgres.cmi +0 -0
  41. package/lib/bs/src/PgSchema-ReventlessPostgres.cmt +0 -0
  42. package/lib/bs/src/PgSchema.ast +0 -0
  43. package/lib/bs/src/PgSchema.res +36 -2
  44. package/lib/bs/src/PgSchema.res.mjs +9 -2
  45. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
  46. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
  47. package/lib/bs/src/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
  48. package/lib/bs/src/QueryDbStorage_Postgres.ast +0 -0
  49. package/lib/bs/src/QueryDbStorage_Postgres.res +10 -212
  50. package/lib/bs/src/QueryDbStorage_Postgres.res.mjs +27 -191
  51. package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  52. package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  53. package/lib/bs/src/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  54. package/lib/bs/src/QueryDbStorage_Postgres_Ops.ast +0 -0
  55. package/lib/bs/src/QueryDbStorage_Postgres_Ops.res +229 -0
  56. package/lib/bs/src/QueryDbStorage_Postgres_Ops.res.mjs +222 -0
  57. package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
  58. package/lib/bs/src/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
  59. package/lib/bs/src/QueryEnginePostgres.ast +0 -0
  60. package/lib/bs/src/QueryEnginePostgres.res +259 -0
  61. package/lib/bs/src/QueryEnginePostgres.res.mjs +165 -0
  62. package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
  63. package/lib/bs/tests/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
  64. package/lib/bs/tests/PostgresIntegrationTest.ast +0 -0
  65. package/lib/bs/tests/PostgresIntegrationTest.res +68 -0
  66. package/lib/bs/tests/PostgresIntegrationTest.res.mjs +49 -0
  67. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmi +0 -0
  68. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmj +0 -0
  69. package/lib/bs/tests/QueryEnginePostgresListPageTest-ReventlessPostgres.cmt +0 -0
  70. package/lib/bs/tests/QueryEnginePostgresListPageTest.ast +0 -0
  71. package/lib/bs/tests/QueryEnginePostgresListPageTest.res +312 -0
  72. package/lib/bs/tests/QueryEnginePostgresListPageTest.res.mjs +461 -0
  73. package/lib/ocaml/.compiler.log +2 -2
  74. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  75. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
  76. package/lib/ocaml/DcbEventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  77. package/lib/ocaml/DcbEventLogStorage_Postgres.ast +0 -0
  78. package/lib/ocaml/DcbEventLogStorage_Postgres.res +25 -340
  79. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  80. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  81. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  82. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops.ast +0 -0
  83. package/lib/ocaml/DcbEventLogStorage_Postgres_Ops.res +350 -0
  84. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmi +0 -0
  85. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmj +0 -0
  86. package/lib/ocaml/EventLogChangeFeed-ReventlessPostgres.cmt +0 -0
  87. package/lib/ocaml/EventLogChangeFeed.ast +0 -0
  88. package/lib/ocaml/EventLogChangeFeed.res +184 -0
  89. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmi +0 -0
  90. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmj +0 -0
  91. package/lib/ocaml/EventLogStorage_Postgres-ReventlessPostgres.cmt +0 -0
  92. package/lib/ocaml/EventLogStorage_Postgres.ast +0 -0
  93. package/lib/ocaml/EventLogStorage_Postgres.res +12 -170
  94. package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  95. package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  96. package/lib/ocaml/EventLogStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  97. package/lib/ocaml/EventLogStorage_Postgres_Ops.ast +0 -0
  98. package/lib/ocaml/EventLogStorage_Postgres_Ops.res +180 -0
  99. package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmi +0 -0
  100. package/lib/ocaml/PgChangeFeed-ReventlessPostgres.cmt +0 -0
  101. package/lib/ocaml/PgSchema-ReventlessPostgres.cmi +0 -0
  102. package/lib/ocaml/PgSchema-ReventlessPostgres.cmt +0 -0
  103. package/lib/ocaml/PgSchema.ast +0 -0
  104. package/lib/ocaml/PgSchema.res +36 -2
  105. package/lib/ocaml/PostgresIntegrationTest.res +68 -0
  106. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmi +0 -0
  107. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmj +0 -0
  108. package/lib/ocaml/QueryDbStorage_Postgres-ReventlessPostgres.cmt +0 -0
  109. package/lib/ocaml/QueryDbStorage_Postgres.ast +0 -0
  110. package/lib/ocaml/QueryDbStorage_Postgres.res +10 -212
  111. package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmi +0 -0
  112. package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmj +0 -0
  113. package/lib/ocaml/QueryDbStorage_Postgres_Ops-ReventlessPostgres.cmt +0 -0
  114. package/lib/ocaml/QueryDbStorage_Postgres_Ops.ast +0 -0
  115. package/lib/ocaml/QueryDbStorage_Postgres_Ops.res +229 -0
  116. package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmi +0 -0
  117. package/lib/ocaml/QueryEnginePostgres-ReventlessPostgres.cmt +0 -0
  118. package/lib/ocaml/QueryEnginePostgres.ast +0 -0
  119. package/lib/ocaml/QueryEnginePostgres.res +259 -0
  120. package/lib/ocaml/QueryEnginePostgresListPageTest.res +312 -0
  121. package/lib/ocaml/ReventlessPostgres.cmi +0 -0
  122. package/lib/ocaml/ReventlessPostgres.cmt +0 -0
  123. package/lib/ocaml/ReventlessPostgres.mlmap +5 -0
  124. package/package.json +9 -9
  125. package/rescript.json +2 -1
  126. package/src/DcbEventLogStorage_Postgres.res +25 -340
  127. package/src/DcbEventLogStorage_Postgres.res.mjs +32 -348
  128. package/src/DcbEventLogStorage_Postgres_Ops.res +350 -0
  129. package/src/DcbEventLogStorage_Postgres_Ops.res.mjs +380 -0
  130. package/src/EventLogChangeFeed.res +184 -0
  131. package/src/EventLogChangeFeed.res.mjs +134 -0
  132. package/src/EventLogStorage_Postgres.res +12 -170
  133. package/src/EventLogStorage_Postgres.res.mjs +20 -186
  134. package/src/EventLogStorage_Postgres_Ops.res +180 -0
  135. package/src/EventLogStorage_Postgres_Ops.res.mjs +202 -0
  136. package/src/PgSchema.res +36 -2
  137. package/src/PgSchema.res.mjs +9 -2
  138. package/src/QueryDbStorage_Postgres.res +10 -212
  139. package/src/QueryDbStorage_Postgres.res.mjs +27 -191
  140. package/src/QueryDbStorage_Postgres_Ops.res +229 -0
  141. package/src/QueryDbStorage_Postgres_Ops.res.mjs +222 -0
  142. package/src/QueryEnginePostgres.res +259 -0
  143. package/src/QueryEnginePostgres.res.mjs +165 -0
  144. package/tests/PostgresIntegrationTest.res +68 -0
  145. package/tests/PostgresIntegrationTest.res.mjs +49 -0
  146. package/tests/QueryEnginePostgresListPageTest.res +312 -0
  147. package/tests/QueryEnginePostgresListPageTest.res.mjs +461 -0
  148. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmi +0 -0
  149. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmj +0 -0
  150. package/lib/ocaml/PostgresIntegrationTest-ReventlessPostgres.cmt +0 -0
  151. package/lib/ocaml/PostgresIntegrationTest.ast +0 -0
@@ -1,101 +1,16 @@
1
- // Postgres-backed QueryDb storage JSONB document tables, one per read model.
1
+ // Deploy/local wrapper over the runtime-pure QueryDbStorage_Postgres_Ops.
2
2
  //
3
- // Implements the clean QueryDb_Adapter.storageMaker (the shape
4
- // QueryDbStorage_DynamoDb implements): no in-process bus. The reventless-local
5
- // bridge that publishes state-changes to live GraphQL subscriptions wraps this
6
- // at integration time (Phase E), the way QueryDbStorage_Sqlite wraps its data
7
- // access today.
8
- //
9
- // Table `qdb_<name>`: partition_key text, sub_key text, item jsonb, expires_at
10
- // double precision (unix epoch seconds; null = never), PRIMARY KEY
11
- // (partition_key, sub_key). `item jsonb` returns already parsed. TTL is lazy —
12
- // every read carries `(expires_at IS NULL OR expires_at > epoch_now)`.
13
- //
14
- // GSI: each declared indexConfig becomes an expression index on `item->>'field'`
15
- // (composite keys concatenated with the configured separator). projectionType is
16
- // irrelevant in a relational store (every column is on the same row).
3
+ // `makeOperations` + all SQL helpers live in QueryDbStorage_Postgres_Ops, which
4
+ // imports NO `@pulumi/pulumi` so the deployed-Lambda runtime binds ops without
5
+ // dragging a deploy-time dep into its ESM import graph. This module `include`s
6
+ // that pure module (so every existing `QueryDbStorage_Postgres.*` reference keeps
7
+ // working) and adds only the deploy-time `Pulumi.Output`-shaped `storage` record
8
+ // and the `Make` provider functor.
9
+ // See docs/plans/deployed-lambda-esm-self-containment.md (Rung-3 finding).
17
10
 
18
11
  open ReventlessCore
19
12
  open Reventless.ReadModel
20
-
21
- let tableName = (name: string): string => "qdb_" ++ name->String.replaceAll("-", "_")
22
-
23
- // Collapse anything outside [A-Za-z0-9_] to _ — predictable, injection-safe idents.
24
- let sanitizeIdent = (s: string): string =>
25
- s->String.replaceRegExp(%re("/[^A-Za-z0-9_]/g"), "_")
26
-
27
- let notExpiredClause = "(expires_at IS NULL OR expires_at > extract(epoch from now()))"
28
-
29
- // JSONB text extraction for a single top-level field.
30
- let jsonField = (field: string): string =>
31
- `(item->>'${field->String.replaceAll("'", "''")}')`
32
-
33
- let compositeExpr = (fields: array<string>, sep: string): string => {
34
- let escapedSep = sep->String.replaceAll("'", "''")
35
- fields->Array.map(jsonField)->Array.join(` || '${escapedSep}' || `)
36
- }
37
-
38
- let indexExpressions = (idx: indexConfig): (string, option<string>) => {
39
- let pkExpr = switch idx.pkFields {
40
- | Some(fields) if fields->Array.length > 0 => compositeExpr(fields, idx.pkSep->Option.getOr("/"))
41
- | _ =>
42
- switch idx.idField {
43
- | Some(field) => jsonField(field)
44
- | None => jsonField(idx.index)
45
- }
46
- }
47
- let skExpr = switch idx.skFields {
48
- | Some(fields) if fields->Array.length > 0 =>
49
- Some(compositeExpr(fields, idx.skSep->Option.getOr("/")))
50
- | _ =>
51
- switch idx.subIdField {
52
- | Some(field) => Some(jsonField(field))
53
- | None => None
54
- }
55
- }
56
- (pkExpr, skExpr)
57
- }
58
-
59
- let ensureTable = async (~pool, ~table) => {
60
- await pool->PgDriver.exec(
61
- `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))`,
62
- )
63
- }
64
-
65
- let ensureIndexes = async (~pool, ~table, ~indexes: array<indexConfig>) => {
66
- for i in 0 to indexes->Array.length - 1 {
67
- let idx = indexes->Array.getUnsafe(i)
68
- let (pkExpr, skExprOpt) = indexExpressions(idx)
69
- let indexName = `idx_${table}_${sanitizeIdent(idx.index)}`
70
- let cols = switch skExprOpt {
71
- | Some(skExpr) => `${pkExpr}, ${skExpr}`
72
- | None => pkExpr
73
- }
74
- await pool->PgDriver.exec(`CREATE INDEX IF NOT EXISTS ${indexName} ON ${table} (${cols})`)
75
- }
76
- }
77
-
78
- let decodeItem = (row: dict<JSON.t>): JSON.t =>
79
- row->Dict.get("item")->Option.getOr(JSON.Encode.null)
80
-
81
- let computeSubKey = (item: JSON.t, subIdField: option<string>): string =>
82
- switch subIdField {
83
- | None => ""
84
- | Some(field) =>
85
- switch item->JSON.Decode.object->Option.flatMap(o => o->Dict.get(field)) {
86
- | Some(JSON.String(s)) => s
87
- | _ => ""
88
- }
89
- }
90
-
91
- let withId = (item: JSON.t, partitionKey: string): JSON.t =>
92
- switch item->JSON.Decode.object {
93
- | Some(obj) if obj->Dict.get("id")->Option.isNone =>
94
- let copy = Dict.copy(obj)
95
- copy->Dict.set("id", JSON.Encode.string(partitionKey))
96
- JSON.Encode.object(copy)
97
- | _ => item
98
- }
13
+ include QueryDbStorage_Postgres_Ops
99
14
 
100
15
  let makeStorage = (
101
16
  ~pool: PgDriver.pool,
@@ -103,127 +18,10 @@ let makeStorage = (
103
18
  ~indexes: array<indexConfig>,
104
19
  ~subIdField: option<string>,
105
20
  ): QueryDb_Adapter.storage => {
106
- let table = tableName(name)
107
- // Schema setup is async but makeStorage is synchronous; gate every operation on
108
- // this promise so the first access waits for table + index creation exactly
109
- // once (subsequent awaits resolve immediately).
110
- let ready = {
111
- open Promise
112
- ensureTable(~pool, ~table)->then(() => ensureIndexes(~pool, ~table, ~indexes))
113
- }
114
-
115
- let rowsFor = async (id: string): array<JSON.t> => {
116
- await ready
117
- (await pool->PgDriver.query(
118
- `SELECT item FROM ${table} WHERE partition_key = $1 AND ${notExpiredClause} ORDER BY sub_key ASC`,
119
- [JSON.Encode.string(id)],
120
- ))->Array.map(decodeItem)
121
- }
122
-
123
- let saveOne = async (id: string, state: JSON.t, ttl: option<int>) => {
124
- await ready
125
- let subKey = computeSubKey(state, subIdField)
126
- let expiresAt = switch ttl {
127
- | Some(t) => JSON.Encode.int(t)
128
- | None => JSON.Encode.null
129
- }
130
- let _ = await pool->PgDriver.query(
131
- `INSERT INTO ${table}(partition_key, sub_key, item, expires_at)
132
- VALUES ($1, $2, $3::jsonb, $4)
133
- ON CONFLICT (partition_key, sub_key)
134
- DO UPDATE SET item = EXCLUDED.item, expires_at = EXCLUDED.expires_at`,
135
- [
136
- JSON.Encode.string(id),
137
- JSON.Encode.string(subKey),
138
- JSON.Encode.string(JSON.stringify(state)),
139
- expiresAt,
140
- ],
141
- )
142
- }
143
-
144
- let load: QueryDb.load<string, JSON.t> = async id => Ok(await rowsFor(id))
145
-
146
- let loadStream: QueryDb.loadStream<string, JSON.t> =
147
- id =>
148
- Effect.promise(() => rowsFor(id))
149
- ->Stream.fromEffect
150
- ->Stream.flatMap(arr => Stream.fromIterable(arr))
151
-
152
- let save: QueryDb.save<string, JSON.t> = async (id, state, _saveMode, ttl) => {
153
- await saveOne(id, state, ttl)
154
- Ok()
155
- }
156
-
157
- let saveBatch: QueryDb.saveBatch<string, JSON.t> = async batch => {
158
- // pg has no synchronous multi-statement transaction helper here; the upserts
159
- // are independent (distinct keys) so a sequential apply is equivalent.
160
- for i in 0 to batch->Array.length - 1 {
161
- let (id, state, ttl) = batch->Array.getUnsafe(i)
162
- await saveOne(id, state, ttl)
163
- }
164
- Ok()
165
- }
166
-
167
- // Mirror DynamoDB's `ADD #field :inc`: read the counter on the partition item
168
- // (counters are single-state, sub_key=""), add inc, upsert, return NEW total.
169
- let count: QueryDb.count<string> = async (id, fieldName, inc) => {
170
- await ready
171
- let existing = (await rowsFor(id))->Array.get(0)->Option.flatMap(JSON.Decode.object)
172
- let current =
173
- existing
174
- ->Option.flatMap(o => o->Dict.get(fieldName))
175
- ->Option.flatMap(JSON.Decode.float)
176
- ->Option.mapOr(0, Float.toInt)
177
- let next = current + inc
178
- let obj = switch existing {
179
- | Some(o) => Dict.copy(o)
180
- | None => Dict.make()
181
- }
182
- obj->Dict.set("id", JSON.Encode.string(id))
183
- obj->Dict.set(fieldName, JSON.Encode.int(next))
184
- await saveOne(id, JSON.Encode.object(obj), None)
185
- Ok(next)
186
- }
187
-
188
- let delete: QueryDb.delete<string> = async (id, subIdOpt) => {
189
- await ready
190
- let _ = switch subIdOpt {
191
- | None =>
192
- await pool->PgDriver.query(
193
- `DELETE FROM ${table} WHERE partition_key = $1`,
194
- [JSON.Encode.string(id)],
195
- )
196
- | Some((_, subValue)) =>
197
- await pool->PgDriver.query(
198
- `DELETE FROM ${table} WHERE partition_key = $1 AND sub_key = $2`,
199
- [JSON.Encode.string(id), JSON.Encode.string(subValue)],
200
- )
201
- }
202
- Ok()
203
- }
204
-
205
- let deleteBatch: QueryDb.deleteBatch<string> = async ids => {
206
- for i in 0 to ids->Array.length - 1 {
207
- let (id, subIdOpt) = ids->Array.getUnsafe(i)
208
- let _ = await delete(id, subIdOpt)
209
- }
210
- Ok()
211
- }
212
-
213
- let ops: QueryDb_Adapter.operations = {
214
- load,
215
- loadStream,
216
- save,
217
- saveBatch,
218
- count,
219
- delete,
220
- deleteBatch,
221
- }
222
-
223
21
  {
224
22
  QueryDb_Adapter.resources: [],
225
23
  dataSourceName: ""->Pulumi.Output.make,
226
- operations: Pulumi.Output.make(ops),
24
+ operations: Pulumi.Output.make(makeOperations(~pool, ~name, ~indexes, ~subIdField)),
227
25
  }
228
26
  }
229
27
 
@@ -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