@event-driven-io/pongo 0.17.0-alpha.5 → 0.17.0-beta.1

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 (53) hide show
  1. package/dist/chunk-3KNMMQUV.cjs +362 -0
  2. package/dist/chunk-3KNMMQUV.cjs.map +1 -0
  3. package/dist/chunk-5LN762VW.js +362 -0
  4. package/dist/chunk-5LN762VW.js.map +1 -0
  5. package/dist/chunk-7W6X4QGY.cjs +10 -0
  6. package/dist/chunk-7W6X4QGY.cjs.map +1 -0
  7. package/dist/{chunk-OO7GMTMP.js → chunk-DL4E3N6J.js} +574 -873
  8. package/dist/chunk-DL4E3N6J.js.map +1 -0
  9. package/dist/chunk-IBJKZ6TS.js +10 -0
  10. package/dist/chunk-IBJKZ6TS.js.map +1 -0
  11. package/dist/chunk-YLV7YIPZ.cjs +876 -0
  12. package/dist/chunk-YLV7YIPZ.cjs.map +1 -0
  13. package/dist/cli.cjs +94 -35
  14. package/dist/cli.cjs.map +1 -1
  15. package/dist/cli.js +92 -33
  16. package/dist/cli.js.map +1 -1
  17. package/dist/index.cjs +3 -6
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +58 -18
  20. package/dist/index.d.ts +58 -18
  21. package/dist/index.js +14 -17
  22. package/dist/pg-WUYRNGST.js +11 -0
  23. package/dist/pg-WUYRNGST.js.map +1 -0
  24. package/dist/pg-XCWP4FAM.cjs +11 -0
  25. package/dist/pg-XCWP4FAM.cjs.map +1 -0
  26. package/dist/pg.cjs +4 -3
  27. package/dist/pg.cjs.map +1 -1
  28. package/dist/pg.d.cts +33 -6
  29. package/dist/pg.d.ts +33 -6
  30. package/dist/pg.js +10 -9
  31. package/dist/pongoCollectionSchemaComponent-BsHlVyN-.d.cts +422 -0
  32. package/dist/pongoCollectionSchemaComponent-BsHlVyN-.d.ts +422 -0
  33. package/dist/shim.cjs +38 -8
  34. package/dist/shim.cjs.map +1 -1
  35. package/dist/shim.d.cts +10 -8
  36. package/dist/shim.d.ts +10 -8
  37. package/dist/shim.js +35 -5
  38. package/dist/shim.js.map +1 -1
  39. package/dist/sqlite3.cjs +382 -1
  40. package/dist/sqlite3.cjs.map +1 -1
  41. package/dist/sqlite3.d.cts +12 -1
  42. package/dist/sqlite3.d.ts +12 -1
  43. package/dist/sqlite3.js +381 -0
  44. package/dist/sqlite3.js.map +1 -1
  45. package/package.json +20 -12
  46. package/README.md +0 -230
  47. package/dist/chunk-AV4SHJQB.cjs +0 -1175
  48. package/dist/chunk-AV4SHJQB.cjs.map +0 -1
  49. package/dist/chunk-OO7GMTMP.js.map +0 -1
  50. package/dist/pg-BfTNWLV9.d.ts +0 -39
  51. package/dist/pg-C9NmCQe7.d.cts +0 -39
  52. package/dist/pongoClient-D8jPedlZ.d.cts +0 -364
  53. package/dist/pongoClient-D8jPedlZ.d.ts +0 -364
@@ -0,0 +1,362 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+ var _chunkYLV7YIPZcjs = require('./chunk-YLV7YIPZ.cjs');
13
+
14
+ // src/storage/postgresql/pg/index.ts
15
+ var _dumbo = require('@event-driven-io/dumbo');
16
+
17
+
18
+
19
+
20
+ var _pg = require('@event-driven-io/dumbo/pg');
21
+ require('pg');
22
+
23
+ // src/storage/postgresql/core/sqlBuilder/index.ts
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+ // src/storage/postgresql/core/sqlBuilder/filter/index.ts
32
+
33
+
34
+ // src/storage/postgresql/core/sqlBuilder/filter/queryOperators.ts
35
+
36
+ var handleOperator = (path, operator, value) => {
37
+ if (path === "_id" || path === "_version") {
38
+ return handleMetadataOperator(path, operator, value);
39
+ }
40
+ switch (operator) {
41
+ case "$eq": {
42
+ const nestedPath = _dumbo.JSONSerializer.serialize(
43
+ buildNestedObject(path, value)
44
+ );
45
+ const serializedValue = _dumbo.JSONSerializer.serialize(value);
46
+ return _dumbo.SQL`(data @> ${nestedPath}::jsonb OR jsonb_path_exists(data, '$.${_dumbo.SQL.plain(path)}[*] ? (@ == ${_dumbo.SQL.plain(serializedValue)})'))`;
47
+ }
48
+ case "$gt":
49
+ case "$gte":
50
+ case "$lt":
51
+ case "$lte":
52
+ case "$ne": {
53
+ const jsonPath = _dumbo.SQL.plain(path.split(".").join(","));
54
+ return _dumbo.SQL`data ->> '${jsonPath}' ${_dumbo.SQL.plain(_chunkYLV7YIPZcjs.OperatorMap[operator])} ${value}`;
55
+ }
56
+ case "$in": {
57
+ const jsonPath = `{${path.split(".").join(",")}}`;
58
+ return _dumbo.SQL`data #>> ${jsonPath} IN ${value}`;
59
+ }
60
+ case "$nin": {
61
+ const jsonPath = `{${path.split(".").join(",")}}`;
62
+ return _dumbo.SQL`data #>> ${jsonPath} NOT IN ${value}`;
63
+ }
64
+ case "$elemMatch": {
65
+ const subQuery = _chunkYLV7YIPZcjs.objectEntries.call(void 0, value).map(
66
+ ([subKey, subValue]) => `@."${subKey}" == ${_dumbo.JSONSerializer.serialize(subValue)}`
67
+ ).join(" && ");
68
+ return _dumbo.SQL`jsonb_path_exists(data, '$.${_dumbo.SQL.plain(path)}[*] ? (${_dumbo.SQL.plain(subQuery)})')`;
69
+ }
70
+ case "$all": {
71
+ const nestedPath = _dumbo.JSONSerializer.serialize(
72
+ buildNestedObject(path, value)
73
+ );
74
+ return _dumbo.SQL`data @> ${nestedPath}::jsonb`;
75
+ }
76
+ case "$size": {
77
+ const jsonPath = `{${path.split(".").join(",")}}`;
78
+ return _dumbo.SQL`jsonb_array_length(data #> ${jsonPath}) = ${value}`;
79
+ }
80
+ default:
81
+ throw new Error(`Unsupported operator: ${operator}`);
82
+ }
83
+ };
84
+ var handleMetadataOperator = (fieldName, operator, value) => {
85
+ switch (operator) {
86
+ case "$eq":
87
+ return _dumbo.SQL`${_dumbo.SQL.plain(fieldName)} = ${value}`;
88
+ case "$gt":
89
+ case "$gte":
90
+ case "$lt":
91
+ case "$lte":
92
+ case "$ne":
93
+ return _dumbo.SQL`${_dumbo.SQL.plain(fieldName)} ${_dumbo.SQL.plain(_chunkYLV7YIPZcjs.OperatorMap[operator])} ${value}`;
94
+ case "$in":
95
+ return _dumbo.SQL`${_dumbo.SQL.plain(fieldName)} IN ${value}`;
96
+ case "$nin":
97
+ return _dumbo.SQL`${_dumbo.SQL.plain(fieldName)} NOT IN ${value}`;
98
+ default:
99
+ throw new Error(`Unsupported operator: ${operator}`);
100
+ }
101
+ };
102
+ var buildNestedObject = (path, value) => path.split(".").reverse().reduce((acc, key) => ({ [key]: acc }), value);
103
+
104
+ // src/storage/postgresql/core/sqlBuilder/filter/index.ts
105
+ var AND = "AND";
106
+ var constructFilterQuery = (filter) => _dumbo.SQL.merge(
107
+ Object.entries(filter).map(
108
+ ([key, value]) => isRecord(value) ? constructComplexFilterQuery(key, value) : handleOperator(key, "$eq", value)
109
+ ),
110
+ ` ${AND} `
111
+ );
112
+ var constructComplexFilterQuery = (key, value) => {
113
+ const isEquality = !_chunkYLV7YIPZcjs.hasOperators.call(void 0, value);
114
+ return _dumbo.SQL.merge(
115
+ _chunkYLV7YIPZcjs.objectEntries.call(void 0, value).map(
116
+ ([nestedKey, val]) => isEquality ? handleOperator(`${key}.${nestedKey}`, _chunkYLV7YIPZcjs.QueryOperators.$eq, val) : handleOperator(key, nestedKey, val)
117
+ ),
118
+ ` ${AND} `
119
+ );
120
+ };
121
+ var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
122
+
123
+ // src/storage/postgresql/core/sqlBuilder/update/index.ts
124
+
125
+ var buildUpdateQuery = (update) => _chunkYLV7YIPZcjs.objectEntries.call(void 0, update).reduce(
126
+ (currentUpdateQuery, [op, value]) => {
127
+ switch (op) {
128
+ case "$set":
129
+ return buildSetQuery(value, currentUpdateQuery);
130
+ case "$unset":
131
+ return buildUnsetQuery(value, currentUpdateQuery);
132
+ case "$inc":
133
+ return buildIncQuery(value, currentUpdateQuery);
134
+ case "$push":
135
+ return buildPushQuery(value, currentUpdateQuery);
136
+ default:
137
+ return currentUpdateQuery;
138
+ }
139
+ },
140
+ _dumbo.SQL`data`
141
+ );
142
+ var buildSetQuery = (set, currentUpdateQuery) => _dumbo.SQL`${currentUpdateQuery} || ${_dumbo.JSONSerializer.serialize(set)}::jsonb`;
143
+ var buildUnsetQuery = (unset, currentUpdateQuery) => _dumbo.SQL`${currentUpdateQuery} - ${Object.keys(unset).map((k) => `{${k}}`).join(", ")}`;
144
+ var buildIncQuery = (inc, currentUpdateQuery) => {
145
+ for (const [key, value] of Object.entries(inc)) {
146
+ currentUpdateQuery = typeof value === "bigint" ? _dumbo.SQL`jsonb_set(${currentUpdateQuery}, '{${_dumbo.SQL.plain(key)}}', to_jsonb((COALESCE((data->>'${_dumbo.SQL.plain(key)}')::BIGINT, 0) + ${value})::TEXT), true)` : _dumbo.SQL`jsonb_set(${currentUpdateQuery}, '{${_dumbo.SQL.plain(key)}}', to_jsonb(COALESCE((data->>'${_dumbo.SQL.plain(key)}')::NUMERIC, 0) + ${value}), true)`;
147
+ }
148
+ return currentUpdateQuery;
149
+ };
150
+ var buildPushQuery = (push, currentUpdateQuery) => {
151
+ for (const [key, value] of Object.entries(push)) {
152
+ const serializedValue = _dumbo.JSONSerializer.serialize([value]);
153
+ currentUpdateQuery = _dumbo.SQL`jsonb_set(${currentUpdateQuery}, '{${_dumbo.SQL.plain(key)}}', (coalesce(data->'${_dumbo.SQL.plain(key)}', '[]'::jsonb) || ${serializedValue}::jsonb), true)`;
154
+ }
155
+ return currentUpdateQuery;
156
+ };
157
+
158
+ // src/storage/postgresql/core/sqlBuilder/index.ts
159
+ var createCollection = (collectionName) => _dumbo.SQL`
160
+ CREATE TABLE IF NOT EXISTS ${_dumbo.SQL.identifier(collectionName)} (
161
+ _id TEXT PRIMARY KEY,
162
+ data JSONB NOT NULL,
163
+ metadata JSONB NOT NULL DEFAULT '{}',
164
+ _version BIGINT NOT NULL DEFAULT 1,
165
+ _partition TEXT NOT NULL DEFAULT 'png_global',
166
+ _archived BOOLEAN NOT NULL DEFAULT FALSE,
167
+ _created TIMESTAMPTZ NOT NULL DEFAULT now(),
168
+ _updated TIMESTAMPTZ NOT NULL DEFAULT now()
169
+ )`;
170
+ var pongoCollectionPostgreSQLMigrations = (collectionName) => [
171
+ _dumbo.sqlMigration.call(void 0, `pongoCollection:${collectionName}:001:createtable`, [
172
+ createCollection(collectionName)
173
+ ])
174
+ ];
175
+ var postgresSQLBuilder = (collectionName) => ({
176
+ createCollection: () => createCollection(collectionName),
177
+ insertOne: (document) => {
178
+ const serialized = _dumbo.JSONSerializer.serialize(document);
179
+ const id = document._id;
180
+ const version = _nullishCoalesce(document._version, () => ( 1n));
181
+ return _dumbo.SQL`
182
+ INSERT INTO ${_dumbo.SQL.identifier(collectionName)} (_id, data, _version)
183
+ VALUES (${id}, ${serialized}, ${version}) ON CONFLICT(_id) DO NOTHING;`;
184
+ },
185
+ insertMany: (documents) => {
186
+ const values = _dumbo.SQL.merge(
187
+ documents.map(
188
+ (doc) => _dumbo.SQL`(${doc._id}, ${_dumbo.JSONSerializer.serialize(doc)}, ${_nullishCoalesce(doc._version, () => ( 1n))})`
189
+ ),
190
+ ","
191
+ );
192
+ return _dumbo.SQL`
193
+ INSERT INTO ${_dumbo.SQL.identifier(collectionName)} (_id, data, _version) VALUES ${values}
194
+ ON CONFLICT(_id) DO NOTHING
195
+ RETURNING _id;`;
196
+ },
197
+ updateOne: (filter, update, options) => {
198
+ const expectedVersion = _chunkYLV7YIPZcjs.expectedVersionValue.call(void 0, _optionalChain([options, 'optionalAccess', _ => _.expectedVersion]));
199
+ const expectedVersionUpdate = expectedVersion != null ? _dumbo.SQL`AND ${_dumbo.SQL.identifier(collectionName)}._version = ${expectedVersion}` : _dumbo.SQL``;
200
+ const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
201
+ const updateQuery = _dumbo.isSQL.call(void 0, update) ? update : buildUpdateQuery(update);
202
+ return _dumbo.SQL`
203
+ WITH existing AS (
204
+ SELECT _id, _version as current_version
205
+ FROM ${_dumbo.SQL.identifier(collectionName)} ${where(filterQuery)}
206
+ LIMIT 1
207
+ ),
208
+ updated AS (
209
+ UPDATE ${_dumbo.SQL.identifier(collectionName)}
210
+ SET
211
+ data = ${updateQuery} || jsonb_build_object('_id', ${_dumbo.SQL.identifier(collectionName)}._id) || jsonb_build_object('_version', (_version + 1)::text),
212
+ _version = _version + 1
213
+ FROM existing
214
+ WHERE ${_dumbo.SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
215
+ RETURNING ${_dumbo.SQL.identifier(collectionName)}._id, ${_dumbo.SQL.identifier(collectionName)}._version
216
+ )
217
+ SELECT
218
+ existing._id,
219
+ COALESCE(updated._version, existing.current_version) AS version,
220
+ COUNT(existing._id) over() AS matched,
221
+ COUNT(updated._id) over() AS modified
222
+ FROM existing
223
+ LEFT JOIN updated
224
+ ON existing._id = updated._id;`;
225
+ },
226
+ replaceOne: (filter, document, options) => {
227
+ const expectedVersion = _chunkYLV7YIPZcjs.expectedVersionValue.call(void 0, _optionalChain([options, 'optionalAccess', _2 => _2.expectedVersion]));
228
+ const expectedVersionUpdate = expectedVersion != null ? _dumbo.SQL`AND ${_dumbo.SQL.identifier(collectionName)}._version = ${expectedVersion}` : _dumbo.SQL``;
229
+ const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
230
+ return _dumbo.SQL`
231
+ WITH existing AS (
232
+ SELECT _id, _version as current_version
233
+ FROM ${_dumbo.SQL.identifier(collectionName)} ${where(filterQuery)}
234
+ LIMIT 1
235
+ ),
236
+ updated AS (
237
+ UPDATE ${_dumbo.SQL.identifier(collectionName)}
238
+ SET
239
+ data = ${_dumbo.JSONSerializer.serialize(document)} || jsonb_build_object('_id', ${_dumbo.SQL.identifier(collectionName)}._id) || jsonb_build_object('_version', (_version + 1)::text),
240
+ _version = _version + 1
241
+ FROM existing
242
+ WHERE ${_dumbo.SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
243
+ RETURNING ${_dumbo.SQL.identifier(collectionName)}._id, ${_dumbo.SQL.identifier(collectionName)}._version
244
+ )
245
+ SELECT
246
+ existing._id,
247
+ COALESCE(updated._version, existing.current_version) AS version,
248
+ COUNT(existing._id) over() AS matched,
249
+ COUNT(updated._id) over() AS modified
250
+ FROM existing
251
+ LEFT JOIN updated
252
+ ON existing._id = updated._id;`;
253
+ },
254
+ updateMany: (filter, update) => {
255
+ const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
256
+ const updateQuery = _dumbo.isSQL.call(void 0, update) ? update : buildUpdateQuery(update);
257
+ return _dumbo.SQL`
258
+ UPDATE ${_dumbo.SQL.identifier(collectionName)}
259
+ SET
260
+ data = ${updateQuery} || jsonb_build_object('_version', (_version + 1)::text),
261
+ _version = _version + 1
262
+ ${where(filterQuery)};`;
263
+ },
264
+ deleteOne: (filter, options) => {
265
+ const expectedVersion = _chunkYLV7YIPZcjs.expectedVersionValue.call(void 0, _optionalChain([options, 'optionalAccess', _3 => _3.expectedVersion]));
266
+ const expectedVersionUpdate = expectedVersion != null ? _dumbo.SQL`AND ${_dumbo.SQL.identifier(collectionName)}._version = ${expectedVersion}` : _dumbo.SQL``;
267
+ const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
268
+ return _dumbo.SQL`
269
+ WITH existing AS (
270
+ SELECT _id
271
+ FROM ${_dumbo.SQL.identifier(collectionName)} ${where(filterQuery)}
272
+ LIMIT 1
273
+ ),
274
+ deleted AS (
275
+ DELETE FROM ${_dumbo.SQL.identifier(collectionName)}
276
+ USING existing
277
+ WHERE ${_dumbo.SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
278
+ RETURNING ${_dumbo.SQL.identifier(collectionName)}._id
279
+ )
280
+ SELECT
281
+ existing._id,
282
+ COUNT(existing._id) over() AS matched,
283
+ COUNT(deleted._id) over() AS deleted
284
+ FROM existing
285
+ LEFT JOIN deleted
286
+ ON existing._id = deleted._id;`;
287
+ },
288
+ deleteMany: (filter) => {
289
+ const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
290
+ return _dumbo.SQL`DELETE FROM ${_dumbo.SQL.identifier(collectionName)} ${where(filterQuery)}`;
291
+ },
292
+ findOne: (filter) => {
293
+ const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
294
+ return _dumbo.SQL`SELECT data FROM ${_dumbo.SQL.identifier(collectionName)} ${where(filterQuery)} LIMIT 1;`;
295
+ },
296
+ find: (filter, options) => {
297
+ const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
298
+ const query = [];
299
+ query.push(_dumbo.SQL`SELECT data FROM ${_dumbo.SQL.identifier(collectionName)}`);
300
+ query.push(where(filterQuery));
301
+ if (_optionalChain([options, 'optionalAccess', _4 => _4.limit])) {
302
+ query.push(_dumbo.SQL`LIMIT ${options.limit}`);
303
+ }
304
+ if (_optionalChain([options, 'optionalAccess', _5 => _5.skip])) {
305
+ query.push(_dumbo.SQL`OFFSET ${options.skip}`);
306
+ }
307
+ return _dumbo.SQL.merge([...query, _dumbo.SQL`;`]);
308
+ },
309
+ countDocuments: (filter) => {
310
+ const filterQuery = _dumbo.SQL.check.isSQL(filter) ? filter : constructFilterQuery(filter);
311
+ return _dumbo.SQL`SELECT COUNT(1) as count FROM ${_dumbo.SQL.identifier(collectionName)} ${where(filterQuery)};`;
312
+ },
313
+ rename: (newName) => _dumbo.SQL`ALTER TABLE ${_dumbo.SQL.identifier(collectionName)} RENAME TO ${_dumbo.SQL.identifier(newName)};`,
314
+ drop: (targetName = collectionName) => _dumbo.SQL`DROP TABLE IF EXISTS ${_dumbo.SQL.identifier(targetName)}`
315
+ });
316
+ var where = (filterQuery) => _dumbo.SQL.check.isEmpty(filterQuery) ? _dumbo.SQL.EMPTY : _dumbo.SQL.merge([_dumbo.SQL`WHERE `, filterQuery]);
317
+
318
+ // src/storage/postgresql/pg/index.ts
319
+ var pgDatabaseDriver = {
320
+ driverType: _pg.NodePostgresDriverType,
321
+ databaseFactory: (options) => {
322
+ const databaseName = _nullishCoalesce(options.databaseName, () => ( _pg.getDatabaseNameOrDefault.call(void 0, options.connectionString)));
323
+ return _chunkYLV7YIPZcjs.PongoDatabase.call(void 0, {
324
+ ...options,
325
+ pool: _dumbo.dumbo.call(void 0, {
326
+ connectionString: options.connectionString,
327
+ driver: _pg.pgDatabaseDriver,
328
+ ...options.connectionOptions
329
+ }),
330
+ schemaComponent: _chunkYLV7YIPZcjs.PongoDatabaseSchemaComponent.call(void 0, {
331
+ driverType: _pg.NodePostgresDriverType,
332
+ collectionFactory: (schema) => _chunkYLV7YIPZcjs.PongoCollectionSchemaComponent.call(void 0, {
333
+ driverType: _pg.NodePostgresDriverType,
334
+ definition: schema,
335
+ migrationsOrSchemaComponents: {
336
+ migrations: pongoCollectionPostgreSQLMigrations(schema.name)
337
+ },
338
+ sqlBuilder: postgresSQLBuilder(schema.name)
339
+ }),
340
+ definition: _nullishCoalesce(_optionalChain([options, 'access', _6 => _6.schema, 'optionalAccess', _7 => _7.definition]), () => ( _chunkYLV7YIPZcjs.pongoSchema.db(databaseName, {})))
341
+ }),
342
+ databaseName
343
+ });
344
+ },
345
+ getDatabaseNameOrDefault: _pg.getDatabaseNameOrDefault,
346
+ defaultConnectionString: "postgresql://localhost:5432/postgres"
347
+ };
348
+ var usePgDatabaseDriver = () => {
349
+ _chunkYLV7YIPZcjs.pongoDatabaseDriverRegistry.register(
350
+ _pg.NodePostgresDriverType,
351
+ pgDatabaseDriver
352
+ );
353
+ };
354
+ usePgDatabaseDriver();
355
+
356
+
357
+
358
+
359
+
360
+
361
+ exports.pongoCollectionPostgreSQLMigrations = pongoCollectionPostgreSQLMigrations; exports.postgresSQLBuilder = postgresSQLBuilder; exports.pgDatabaseDriver = pgDatabaseDriver; exports.usePgDatabaseDriver = usePgDatabaseDriver;
362
+ //# sourceMappingURL=chunk-3KNMMQUV.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-3KNMMQUV.cjs","../src/storage/postgresql/pg/index.ts","../src/storage/postgresql/core/sqlBuilder/index.ts","../src/storage/postgresql/core/sqlBuilder/filter/index.ts","../src/storage/postgresql/core/sqlBuilder/filter/queryOperators.ts","../src/storage/postgresql/core/sqlBuilder/update/index.ts"],"names":["SQL","JSONSerializer"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACbA,+CAAsB;AACtB;AACE;AACA;AACA;AAAA,+CAEK;AACP,cAAe;ADcf;AACA;AEtBA;AACE;AACA;AACA;AACA;AAAA;AFyBF;AACA;AG9BA;AHgCA;AACA;AIjCA;AAGO,IAAM,eAAA,EAAiB,CAC5B,IAAA,EACA,QAAA,EACA,KAAA,EAAA,GACQ;AACR,EAAA,GAAA,CAAI,KAAA,IAAS,MAAA,GAAS,KAAA,IAAS,UAAA,EAAY;AACzC,IAAA,OAAO,sBAAA,CAAuB,IAAA,EAAM,QAAA,EAAU,KAAK,CAAA;AAAA,EACrD;AAEA,EAAA,OAAA,CAAQ,QAAA,EAAU;AAAA,IAChB,KAAK,KAAA,EAAO;AACV,MAAA,MAAM,WAAA,EAAa,qBAAA,CAAe,SAAA;AAAA,QAChC,i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4D,QAAA;AAChE,MAAA;AACD,MAAA;AACD,IAAA;AACH,EAAA;AACA,EAAA;AACyB,EAAA;AAC3B;AAEyC;AACX,EAAA;AAC1B,IAAA;AACA,IAAA;AACF,EAAA;AACF;AAEoB;AD0PgE;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-3KNMMQUV.cjs","sourcesContent":[null,"import { dumbo } from '@event-driven-io/dumbo';\nimport {\n pgDatabaseDriver as dumboDriver,\n getDatabaseNameOrDefault,\n NodePostgresDriverType,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo/pg';\nimport pg from 'pg';\nimport {\n PongoCollectionSchemaComponent,\n PongoDatabase,\n pongoDatabaseDriverRegistry,\n PongoDatabaseSchemaComponent,\n pongoSchema,\n type PongoDatabaseDriver,\n type PongoDatabaseDriverOptions,\n type PongoDb,\n} from '../../../core';\nimport {\n pongoCollectionPostgreSQLMigrations,\n postgresSQLBuilder,\n} from '../core';\n\nexport type NodePostgresPongoClientOptions =\n | PooledPongoClientOptions\n | NotPooledPongoOptions;\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\ntype NodePostgresDatabaseDriverOptions =\n PongoDatabaseDriverOptions<NodePostgresPongoClientOptions>;\n\nconst pgDatabaseDriver: PongoDatabaseDriver<\n PongoDb<NodePostgresDriverType>,\n NodePostgresDatabaseDriverOptions\n> = {\n driverType: NodePostgresDriverType,\n databaseFactory: (options) => {\n const databaseName =\n options.databaseName ??\n getDatabaseNameOrDefault(options.connectionString);\n\n return PongoDatabase({\n ...options,\n pool: dumbo({\n connectionString: options.connectionString,\n driver: dumboDriver,\n ...options.connectionOptions,\n }),\n schemaComponent: PongoDatabaseSchemaComponent({\n driverType: NodePostgresDriverType,\n collectionFactory: (schema) =>\n PongoCollectionSchemaComponent({\n driverType: NodePostgresDriverType,\n definition: schema,\n migrationsOrSchemaComponents: {\n migrations: pongoCollectionPostgreSQLMigrations(schema.name),\n },\n sqlBuilder: postgresSQLBuilder(schema.name),\n }),\n definition:\n options.schema?.definition ?? pongoSchema.db(databaseName, {}),\n }),\n databaseName,\n });\n },\n getDatabaseNameOrDefault,\n defaultConnectionString: 'postgresql://localhost:5432/postgres',\n};\n\nexport const usePgDatabaseDriver = () => {\n pongoDatabaseDriverRegistry.register(\n NodePostgresDriverType,\n pgDatabaseDriver,\n );\n};\n\nusePgDatabaseDriver();\n\nexport { pgDatabaseDriver as databaseDriver, pgDatabaseDriver as pgDriver };\n","import {\n isSQL,\n JSONSerializer,\n SQL,\n sqlMigration,\n} from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\n type FindOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type ReplaceOneOptions,\n type UpdateOneOptions,\n type WithoutId,\n} from '../../../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n SQL`\n CREATE TABLE IF NOT EXISTS ${SQL.identifier(collectionName)} (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`;\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n const serialized = JSONSerializer.serialize(document);\n const id = document._id;\n const version = document._version ?? 1n;\n\n return SQL`\n INSERT INTO ${SQL.identifier(collectionName)} (_id, data, _version) \n VALUES (${id}, ${serialized}, ${version}) ON CONFLICT(_id) DO NOTHING;`;\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = SQL.merge(\n documents.map(\n (doc) =>\n SQL`(${doc._id}, ${JSONSerializer.serialize(doc)}, ${doc._version ?? 1n})`,\n ),\n ',',\n );\n\n return SQL`\n INSERT INTO ${SQL.identifier(collectionName)} (_id, data, _version) VALUES ${values}\n ON CONFLICT(_id) DO NOTHING\n RETURNING _id;`;\n },\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null\n ? SQL`AND ${SQL.identifier(collectionName)}._version = ${expectedVersion}`\n : SQL``;\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return SQL`\n WITH existing AS (\n SELECT _id, _version as current_version\n FROM ${SQL.identifier(collectionName)} ${where(filterQuery)}\n LIMIT 1\n ),\n updated AS (\n UPDATE ${SQL.identifier(collectionName)} \n SET \n data = ${updateQuery} || jsonb_build_object('_id', ${SQL.identifier(collectionName)}._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE ${SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}\n RETURNING ${SQL.identifier(collectionName)}._id, ${SQL.identifier(collectionName)}._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`;\n },\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null\n ? SQL`AND ${SQL.identifier(collectionName)}._version = ${expectedVersion}`\n : SQL``;\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return SQL`\n WITH existing AS (\n SELECT _id, _version as current_version\n FROM ${SQL.identifier(collectionName)} ${where(filterQuery)}\n LIMIT 1\n ),\n updated AS (\n UPDATE ${SQL.identifier(collectionName)} \n SET \n data = ${JSONSerializer.serialize(document)} || jsonb_build_object('_id', ${SQL.identifier(collectionName)}._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE ${SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}\n RETURNING ${SQL.identifier(collectionName)}._id, ${SQL.identifier(collectionName)}._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`;\n },\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? update : buildUpdateQuery(update);\n\n return SQL`\n UPDATE ${SQL.identifier(collectionName)} \n SET \n data = ${updateQuery} || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n ${where(filterQuery)};`;\n },\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null\n ? SQL`AND ${SQL.identifier(collectionName)}._version = ${expectedVersion}`\n : SQL``;\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return SQL`\n WITH existing AS (\n SELECT _id\n FROM ${SQL.identifier(collectionName)} ${where(filterQuery)}\n LIMIT 1\n ),\n deleted AS (\n DELETE FROM ${SQL.identifier(collectionName)}\n USING existing\n WHERE ${SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}\n RETURNING ${SQL.identifier(collectionName)}._id\n )\n SELECT \n existing._id,\n COUNT(existing._id) over() AS matched,\n COUNT(deleted._id) over() AS deleted\n FROM existing\n LEFT JOIN deleted \n ON existing._id = deleted._id;`;\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return SQL`DELETE FROM ${SQL.identifier(collectionName)} ${where(filterQuery)}`;\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return SQL`SELECT data FROM ${SQL.identifier(collectionName)} ${where(filterQuery)} LIMIT 1;`;\n },\n find: <T>(filter: PongoFilter<T> | SQL, options?: FindOptions): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const query: SQL[] = [];\n\n query.push(SQL`SELECT data FROM ${SQL.identifier(collectionName)}`);\n\n query.push(where(filterQuery));\n\n if (options?.limit) {\n query.push(SQL`LIMIT ${options.limit}`);\n }\n\n if (options?.skip) {\n query.push(SQL`OFFSET ${options.skip}`);\n }\n\n return SQL.merge([...query, SQL`;`]);\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = SQL.check.isSQL(filter)\n ? filter\n : constructFilterQuery(filter);\n return SQL`SELECT COUNT(1) as count FROM ${SQL.identifier(collectionName)} ${where(filterQuery)};`;\n },\n rename: (newName: string): SQL =>\n SQL`ALTER TABLE ${SQL.identifier(collectionName)} RENAME TO ${SQL.identifier(newName)};`,\n drop: (targetName: string = collectionName): SQL =>\n SQL`DROP TABLE IF EXISTS ${SQL.identifier(targetName)}`,\n});\n\nconst where = (filterQuery: SQL): SQL =>\n SQL.check.isEmpty(filterQuery)\n ? SQL.EMPTY\n : SQL.merge([SQL`WHERE `, filterQuery]);\n","import { SQL } from '@event-driven-io/dumbo';\nimport {\n hasOperators,\n objectEntries,\n QueryOperators,\n type PongoFilter,\n} from '../../../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): SQL =>\n SQL.merge(\n Object.entries(filter).map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n ),\n ` ${AND} `,\n );\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): SQL => {\n const isEquality = !hasOperators(value);\n\n return SQL.merge(\n objectEntries(value).map(([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val)\n : handleOperator(key, nestedKey, val),\n ),\n ` ${AND} `,\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { JSONSerializer, SQL } from '@event-driven-io/dumbo';\nimport { objectEntries, OperatorMap } from '../../../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): SQL => {\n if (path === '_id' || path === '_version') {\n return handleMetadataOperator(path, operator, value);\n }\n\n switch (operator) {\n case '$eq': {\n const nestedPath = JSONSerializer.serialize(\n buildNestedObject(path, value),\n );\n const serializedValue = JSONSerializer.serialize(value);\n\n return SQL`(data @> ${nestedPath}::jsonb OR jsonb_path_exists(data, '$.${SQL.plain(path)}[*] ? (@ == ${SQL.plain(serializedValue)})'))`;\n }\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne': {\n const jsonPath = SQL.plain(path.split('.').join(','));\n\n return SQL`data ->> '${jsonPath}' ${SQL.plain(OperatorMap[operator])} ${value}`;\n }\n case '$in': {\n const jsonPath = `{${path.split('.').join(',')}}`;\n\n return SQL`data #>> ${jsonPath} IN ${value as unknown[]}`;\n }\n case '$nin': {\n const jsonPath = `{${path.split('.').join(',')}}`;\n\n return SQL`data #>> ${jsonPath} NOT IN ${value as unknown[]}`;\n }\n case '$elemMatch': {\n const subQuery = objectEntries(value as Record<string, unknown>)\n .map(\n ([subKey, subValue]) =>\n `@.\"${subKey}\" == ${JSONSerializer.serialize(subValue)}`,\n )\n .join(' && ');\n return SQL`jsonb_path_exists(data, '$.${SQL.plain(path)}[*] ? (${SQL.plain(subQuery)})')`;\n }\n case '$all': {\n const nestedPath = JSONSerializer.serialize(\n buildNestedObject(path, value),\n );\n return SQL`data @> ${nestedPath}::jsonb`;\n }\n case '$size': {\n const jsonPath = `{${path.split('.').join(',')}}`;\n\n return SQL`jsonb_array_length(data #> ${jsonPath}) = ${value}`;\n }\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleMetadataOperator = (\n fieldName: string,\n operator: string,\n value: unknown,\n): SQL => {\n switch (operator) {\n case '$eq':\n return SQL`${SQL.plain(fieldName)} = ${value}`;\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return SQL`${SQL.plain(fieldName)} ${SQL.plain(OperatorMap[operator])} ${value}`;\n case '$in':\n return SQL`${SQL.plain(fieldName)} IN ${value as unknown[]}`;\n case '$nin':\n return SQL`${SQL.plain(fieldName)} NOT IN ${value as unknown[]}`;\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import { JSONSerializer, SQL } from '@event-driven-io/dumbo';\nimport {\n objectEntries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../../../core';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n objectEntries(update).reduce(\n (currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n },\n SQL`data`,\n );\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n SQL`${currentUpdateQuery} || ${JSONSerializer.serialize(set)}::jsonb`;\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL =>\n SQL`${currentUpdateQuery} - ${Object.keys(unset)\n .map((k) => `{${k}}`)\n .join(', ')}`;\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery =\n typeof value === 'bigint'\n ? SQL`jsonb_set(${currentUpdateQuery}, '{${SQL.plain(key)}}', to_jsonb((COALESCE((data->>'${SQL.plain(key)}')::BIGINT, 0) + ${value})::TEXT), true)`\n : SQL`jsonb_set(${currentUpdateQuery}, '{${SQL.plain(key)}}', to_jsonb(COALESCE((data->>'${SQL.plain(key)}')::NUMERIC, 0) + ${value}), true)`;\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n const serializedValue = JSONSerializer.serialize([value]);\n currentUpdateQuery = SQL`jsonb_set(${currentUpdateQuery}, '{${SQL.plain(key)}}', (coalesce(data->'${SQL.plain(key)}', '[]'::jsonb) || ${serializedValue}::jsonb), true)`;\n }\n return currentUpdateQuery;\n};\n"]}