@event-driven-io/pongo 0.17.0-beta.34 → 0.17.0-beta.36

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 (61) hide show
  1. package/dist/cli.cjs +311 -494
  2. package/dist/cli.cjs.map +1 -1
  3. package/dist/cli.d.cts +4 -4
  4. package/dist/cli.d.ts +4 -3
  5. package/dist/cli.js +279 -494
  6. package/dist/cli.js.map +1 -1
  7. package/dist/cloudflare.cjs +36 -48
  8. package/dist/cloudflare.cjs.map +1 -1
  9. package/dist/cloudflare.d.cts +7 -7
  10. package/dist/cloudflare.d.ts +7 -7
  11. package/dist/cloudflare.js +29 -47
  12. package/dist/cloudflare.js.map +1 -1
  13. package/dist/core-CwxxuUAn.cjs +1590 -0
  14. package/dist/core-CwxxuUAn.cjs.map +1 -0
  15. package/dist/core-D_iZiiYe.js +1308 -0
  16. package/dist/core-D_iZiiYe.js.map +1 -0
  17. package/dist/core-DwoTLYbR.cjs +319 -0
  18. package/dist/core-DwoTLYbR.cjs.map +1 -0
  19. package/dist/core-fsJmsQDa.js +307 -0
  20. package/dist/core-fsJmsQDa.js.map +1 -0
  21. package/dist/index-DMq6F3x9.d.ts +705 -0
  22. package/dist/index-Du_IHXAj.d.ts +10 -0
  23. package/dist/index-ZKOB86ub.d.cts +10 -0
  24. package/dist/index-qeC-p0Tq.d.cts +705 -0
  25. package/dist/index.cjs +61 -118
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +11 -130
  28. package/dist/index.d.ts +11 -130
  29. package/dist/index.js +14 -119
  30. package/dist/index.js.map +1 -1
  31. package/dist/pg.cjs +214 -320
  32. package/dist/pg.cjs.map +1 -1
  33. package/dist/pg.d.cts +24 -22
  34. package/dist/pg.d.ts +24 -22
  35. package/dist/pg.js +209 -321
  36. package/dist/pg.js.map +1 -1
  37. package/dist/shim.cjs +281 -367
  38. package/dist/shim.cjs.map +1 -1
  39. package/dist/shim.d.cts +140 -137
  40. package/dist/shim.d.ts +140 -137
  41. package/dist/shim.js +275 -366
  42. package/dist/shim.js.map +1 -1
  43. package/dist/sqlite3.cjs +41 -56
  44. package/dist/sqlite3.cjs.map +1 -1
  45. package/dist/sqlite3.d.cts +9 -9
  46. package/dist/sqlite3.d.ts +9 -9
  47. package/dist/sqlite3.js +35 -56
  48. package/dist/sqlite3.js.map +1 -1
  49. package/package.json +15 -15
  50. package/dist/chunk-OJVG4KXA.js +0 -399
  51. package/dist/chunk-OJVG4KXA.js.map +0 -1
  52. package/dist/chunk-TYTEQJBC.cjs +0 -1583
  53. package/dist/chunk-TYTEQJBC.cjs.map +0 -1
  54. package/dist/chunk-U4NNEXNH.js +0 -1583
  55. package/dist/chunk-U4NNEXNH.js.map +0 -1
  56. package/dist/chunk-UP6HTRMM.cjs +0 -399
  57. package/dist/chunk-UP6HTRMM.cjs.map +0 -1
  58. package/dist/index-DHszkVjP.d.ts +0 -8
  59. package/dist/index-DLDCIBgH.d.cts +0 -8
  60. package/dist/pongoTransactionCache-BsigBOq1.d.cts +0 -556
  61. package/dist/pongoTransactionCache-BsigBOq1.d.ts +0 -556
package/dist/pg.js CHANGED
@@ -1,150 +1,86 @@
1
- import {
2
- OperatorMap,
3
- PongoCollectionSchemaComponent,
4
- PongoDatabase,
5
- PongoDatabaseSchemaComponent,
6
- QueryOperators,
7
- expectedVersionValue,
8
- hasOperators,
9
- objectEntries,
10
- pongoDriverRegistry,
11
- pongoSchema
12
- } from "./chunk-U4NNEXNH.js";
1
+ import { A as objectEntries, C as expectedVersionValue, I as PongoCollectionSchemaComponent, M as OperatorMap, N as QueryOperators, P as hasOperators, d as PongoDatabase, f as PongoDatabaseSchemaComponent, p as pongoSchema, u as pongoDriverRegistry } from "./core-D_iZiiYe.js";
2
+ import { JSONSerializer, SQL, dumbo, isSQL, sqlMigration } from "@event-driven-io/dumbo";
3
+ import { PgDriverType, pgDumboDriver, postgreSQLMetadata } from "@event-driven-io/dumbo/pg";
13
4
 
14
- // src/storage/postgresql/core/sqlBuilder/index.ts
15
- import { isSQL, SQL as SQL4, sqlMigration } from "@event-driven-io/dumbo";
16
-
17
- // src/storage/postgresql/core/sqlBuilder/filter/index.ts
18
- import { SQL as SQL2 } from "@event-driven-io/dumbo";
19
-
20
- // src/storage/postgresql/core/sqlBuilder/filter/queryOperators.ts
21
- import { SQL } from "@event-driven-io/dumbo";
22
- var handleOperator = (path, operator, value, serializer) => {
23
- if (path === "_id" || path === "_version") {
24
- return handleMetadataOperator(path, operator, value);
25
- }
26
- switch (operator) {
27
- case "$eq": {
28
- const nestedPath = serializer.serialize(buildNestedObject(path, value));
29
- const serializedValue = serializer.serialize(value);
30
- return SQL`(data @> ${nestedPath}::jsonb OR jsonb_path_exists(data, '$.${SQL.plain(path)}[*] ? (@ == ${SQL.plain(serializedValue)})'))`;
31
- }
32
- case "$gt":
33
- case "$gte":
34
- case "$lt":
35
- case "$lte":
36
- case "$ne": {
37
- const jsonPath = SQL.plain(path.split(".").join(","));
38
- return SQL`data ->> '${jsonPath}' ${SQL.plain(OperatorMap[operator])} ${value}`;
39
- }
40
- case "$in": {
41
- const jsonPath = `{${path.split(".").join(",")}}`;
42
- return SQL`data #>> ${jsonPath} = ANY (${value})`;
43
- }
44
- case "$nin": {
45
- const jsonPath = `{${path.split(".").join(",")}}`;
46
- return SQL`data #>> ${jsonPath} != ALL (${value})`;
47
- }
48
- case "$elemMatch": {
49
- const subQuery = objectEntries(value).map(
50
- ([subKey, subValue]) => `@."${subKey}" == ${serializer.serialize(subValue)}`
51
- ).join(" && ");
52
- return SQL`jsonb_path_exists(data, '$.${SQL.plain(path)}[*] ? (${SQL.plain(subQuery)})')`;
53
- }
54
- case "$all": {
55
- const nestedPath = serializer.serialize(buildNestedObject(path, value));
56
- return SQL`data @> ${nestedPath}::jsonb`;
57
- }
58
- case "$size": {
59
- const jsonPath = `{${path.split(".").join(",")}}`;
60
- return SQL`jsonb_array_length(data #> ${jsonPath}) = ${value}`;
61
- }
62
- default:
63
- throw new Error(`Unsupported operator: ${operator}`);
64
- }
5
+ //#region src/storage/postgresql/core/sqlBuilder/filter/queryOperators.ts
6
+ const handleOperator = (path, operator, value, serializer) => {
7
+ if (path === "_id" || path === "_version") return handleMetadataOperator(path, operator, value);
8
+ switch (operator) {
9
+ case "$eq": {
10
+ const nestedPath = serializer.serialize(buildNestedObject(path, value));
11
+ const serializedValue = serializer.serialize(value);
12
+ return SQL`(data @> ${nestedPath}::jsonb OR jsonb_path_exists(data, '$.${SQL.plain(path)}[*] ? (@ == ${SQL.plain(serializedValue)})'))`;
13
+ }
14
+ case "$gt":
15
+ case "$gte":
16
+ case "$lt":
17
+ case "$lte":
18
+ case "$ne": return SQL`data ->> '${SQL.plain(path.split(".").join(","))}' ${SQL.plain(OperatorMap[operator])} ${value}`;
19
+ case "$in": return SQL`data #>> ${`{${path.split(".").join(",")}}`} = ANY (${value})`;
20
+ case "$nin": return SQL`data #>> ${`{${path.split(".").join(",")}}`} != ALL (${value})`;
21
+ case "$elemMatch": {
22
+ const subQuery = objectEntries(value).map(([subKey, subValue]) => `@."${subKey}" == ${serializer.serialize(subValue)}`).join(" && ");
23
+ return SQL`jsonb_path_exists(data, '$.${SQL.plain(path)}[*] ? (${SQL.plain(subQuery)})')`;
24
+ }
25
+ case "$all": return SQL`data @> ${serializer.serialize(buildNestedObject(path, value))}::jsonb`;
26
+ case "$size": return SQL`jsonb_array_length(data #> ${`{${path.split(".").join(",")}}`}) = ${value}`;
27
+ default: throw new Error(`Unsupported operator: ${operator}`);
28
+ }
65
29
  };
66
- var handleMetadataOperator = (fieldName, operator, value) => {
67
- switch (operator) {
68
- case "$eq":
69
- return SQL`${SQL.plain(fieldName)} = ${value}`;
70
- case "$gt":
71
- case "$gte":
72
- case "$lt":
73
- case "$lte":
74
- case "$ne":
75
- return SQL`${SQL.plain(fieldName)} ${SQL.plain(OperatorMap[operator])} ${value}`;
76
- case "$in":
77
- return SQL`${SQL.plain(fieldName)} = ANY (${value})`;
78
- case "$nin":
79
- return SQL`${SQL.plain(fieldName)} != ALL (${value})`;
80
- default:
81
- throw new Error(`Unsupported operator: ${operator}`);
82
- }
30
+ const handleMetadataOperator = (fieldName, operator, value) => {
31
+ switch (operator) {
32
+ case "$eq": return SQL`${SQL.plain(fieldName)} = ${value}`;
33
+ case "$gt":
34
+ case "$gte":
35
+ case "$lt":
36
+ case "$lte":
37
+ case "$ne": return SQL`${SQL.plain(fieldName)} ${SQL.plain(OperatorMap[operator])} ${value}`;
38
+ case "$in": return SQL`${SQL.plain(fieldName)} = ANY (${value})`;
39
+ case "$nin": return SQL`${SQL.plain(fieldName)} != ALL (${value})`;
40
+ default: throw new Error(`Unsupported operator: ${operator}`);
41
+ }
83
42
  };
84
- var buildNestedObject = (path, value) => path.split(".").reverse().reduce((acc, key) => ({ [key]: acc }), value);
43
+ const buildNestedObject = (path, value) => path.split(".").reverse().reduce((acc, key) => ({ [key]: acc }), value);
85
44
 
86
- // src/storage/postgresql/core/sqlBuilder/filter/index.ts
87
- var AND = "AND";
88
- var constructFilterQuery = (filter, serializer) => SQL2.merge(
89
- Object.entries(filter).map(
90
- ([key, value]) => isRecord(value) ? constructComplexFilterQuery(key, value, serializer) : handleOperator(key, "$eq", value, serializer)
91
- ),
92
- ` ${AND} `
93
- );
94
- var constructComplexFilterQuery = (key, value, serializer) => {
95
- const isEquality = !hasOperators(value);
96
- return SQL2.merge(
97
- objectEntries(value).map(
98
- ([nestedKey, val]) => isEquality ? handleOperator(
99
- `${key}.${nestedKey}`,
100
- QueryOperators.$eq,
101
- val,
102
- serializer
103
- ) : handleOperator(key, nestedKey, val, serializer)
104
- ),
105
- ` ${AND} `
106
- );
45
+ //#endregion
46
+ //#region src/storage/postgresql/core/sqlBuilder/filter/index.ts
47
+ const AND = "AND";
48
+ const constructFilterQuery = (filter, serializer) => SQL.merge(Object.entries(filter).map(([key, value]) => isRecord(value) ? constructComplexFilterQuery(key, value, serializer) : handleOperator(key, "$eq", value, serializer)), ` ${AND} `);
49
+ const constructComplexFilterQuery = (key, value, serializer) => {
50
+ const isEquality = !hasOperators(value);
51
+ return SQL.merge(objectEntries(value).map(([nestedKey, val]) => isEquality ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val, serializer) : handleOperator(key, nestedKey, val, serializer)), ` ${AND} `);
107
52
  };
108
- var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
53
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
109
54
 
110
- // src/storage/postgresql/core/sqlBuilder/update/index.ts
111
- import { SQL as SQL3 } from "@event-driven-io/dumbo";
112
- var buildUpdateQuery = (update, serializer) => objectEntries(update).reduce(
113
- (currentUpdateQuery, [op, value]) => {
114
- switch (op) {
115
- case "$set":
116
- return buildSetQuery(value, currentUpdateQuery, serializer);
117
- case "$unset":
118
- return buildUnsetQuery(value, currentUpdateQuery);
119
- case "$inc":
120
- return buildIncQuery(value, currentUpdateQuery);
121
- case "$push":
122
- return buildPushQuery(value, currentUpdateQuery, serializer);
123
- default:
124
- return currentUpdateQuery;
125
- }
126
- },
127
- SQL3`data`
128
- );
129
- var buildSetQuery = (set, currentUpdateQuery, serializer) => SQL3`${currentUpdateQuery} || ${serializer.serialize(set)}::jsonb`;
130
- var buildUnsetQuery = (unset, currentUpdateQuery) => SQL3`${currentUpdateQuery} - ${Object.keys(unset).map((k) => `{${k}}`).join(", ")}`;
131
- var buildIncQuery = (inc, currentUpdateQuery) => {
132
- for (const [key, value] of Object.entries(inc)) {
133
- currentUpdateQuery = typeof value === "bigint" ? SQL3`jsonb_set(${currentUpdateQuery}, '{${SQL3.plain(key)}}', to_jsonb((COALESCE((data->>'${SQL3.plain(key)}')::BIGINT, 0) + ${value})::TEXT), true)` : SQL3`jsonb_set(${currentUpdateQuery}, '{${SQL3.plain(key)}}', to_jsonb(COALESCE((data->>'${SQL3.plain(key)}')::NUMERIC, 0) + ${value}), true)`;
134
- }
135
- return currentUpdateQuery;
55
+ //#endregion
56
+ //#region src/storage/postgresql/core/sqlBuilder/update/index.ts
57
+ const buildUpdateQuery = (update, serializer) => objectEntries(update).reduce((currentUpdateQuery, [op, value]) => {
58
+ switch (op) {
59
+ case "$set": return buildSetQuery(value, currentUpdateQuery, serializer);
60
+ case "$unset": return buildUnsetQuery(value, currentUpdateQuery);
61
+ case "$inc": return buildIncQuery(value, currentUpdateQuery);
62
+ case "$push": return buildPushQuery(value, currentUpdateQuery, serializer);
63
+ default: return currentUpdateQuery;
64
+ }
65
+ }, SQL`data`);
66
+ const buildSetQuery = (set, currentUpdateQuery, serializer) => SQL`${currentUpdateQuery} || ${serializer.serialize(set)}::jsonb`;
67
+ const buildUnsetQuery = (unset, currentUpdateQuery) => SQL`${currentUpdateQuery} - ${Object.keys(unset).map((k) => `{${k}}`).join(", ")}`;
68
+ const buildIncQuery = (inc, currentUpdateQuery) => {
69
+ for (const [key, value] of Object.entries(inc)) currentUpdateQuery = typeof value === "bigint" ? SQL`jsonb_set(${currentUpdateQuery}, '{${SQL.plain(key)}}', to_jsonb((COALESCE((data->>'${SQL.plain(key)}')::BIGINT, 0) + ${value})::TEXT), true)` : SQL`jsonb_set(${currentUpdateQuery}, '{${SQL.plain(key)}}', to_jsonb(COALESCE((data->>'${SQL.plain(key)}')::NUMERIC, 0) + ${value}), true)`;
70
+ return currentUpdateQuery;
136
71
  };
137
- var buildPushQuery = (push, currentUpdateQuery, serializer) => {
138
- for (const [key, value] of Object.entries(push)) {
139
- const serializedValue = serializer.serialize([value]);
140
- currentUpdateQuery = SQL3`jsonb_set(${currentUpdateQuery}, '{${SQL3.plain(key)}}', (coalesce(data->'${SQL3.plain(key)}', '[]'::jsonb) || ${serializedValue}::jsonb), true)`;
141
- }
142
- return currentUpdateQuery;
72
+ const buildPushQuery = (push, currentUpdateQuery, serializer) => {
73
+ for (const [key, value] of Object.entries(push)) {
74
+ const serializedValue = serializer.serialize([value]);
75
+ currentUpdateQuery = SQL`jsonb_set(${currentUpdateQuery}, '{${SQL.plain(key)}}', (coalesce(data->'${SQL.plain(key)}', '[]'::jsonb) || ${serializedValue}::jsonb), true)`;
76
+ }
77
+ return currentUpdateQuery;
143
78
  };
144
79
 
145
- // src/storage/postgresql/core/sqlBuilder/index.ts
146
- var createCollection = (collectionName) => SQL4`
147
- CREATE TABLE IF NOT EXISTS ${SQL4.identifier(collectionName)} (
80
+ //#endregion
81
+ //#region src/storage/postgresql/core/sqlBuilder/index.ts
82
+ const createCollection = (collectionName) => SQL`
83
+ CREATE TABLE IF NOT EXISTS ${SQL.identifier(collectionName)} (
148
84
  _id TEXT PRIMARY KEY,
149
85
  data JSONB NOT NULL,
150
86
  metadata JSONB NOT NULL DEFAULT '{}',
@@ -154,52 +90,43 @@ var createCollection = (collectionName) => SQL4`
154
90
  _created TIMESTAMPTZ NOT NULL DEFAULT now(),
155
91
  _updated TIMESTAMPTZ NOT NULL DEFAULT now()
156
92
  )`;
157
- var pongoCollectionPostgreSQLMigrations = (collectionName) => [
158
- sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [
159
- createCollection(collectionName)
160
- ])
161
- ];
162
- var postgresSQLBuilder = (collectionName, serializer) => ({
163
- createCollection: () => createCollection(collectionName),
164
- insertOne: (document) => {
165
- const serialized = serializer.serialize(document);
166
- const id = document._id;
167
- const version = document._version ?? 1n;
168
- return SQL4`
169
- INSERT INTO ${SQL4.identifier(collectionName)} (_id, data, _version)
93
+ const pongoCollectionPostgreSQLMigrations = (collectionName) => [sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [createCollection(collectionName)])];
94
+ const postgresSQLBuilder = (collectionName, serializer) => ({
95
+ createCollection: () => createCollection(collectionName),
96
+ insertOne: (document) => {
97
+ const serialized = serializer.serialize(document);
98
+ const id = document._id;
99
+ const version = document._version ?? 1n;
100
+ return SQL`
101
+ INSERT INTO ${SQL.identifier(collectionName)} (_id, data, _version)
170
102
  VALUES (${id}, ${serialized}, ${version}) ON CONFLICT(_id) DO NOTHING;`;
171
- },
172
- insertMany: (documents) => {
173
- const values = SQL4.merge(
174
- documents.map(
175
- (doc) => SQL4`(${doc._id}, ${serializer.serialize(doc)}, ${doc._version ?? 1n})`
176
- ),
177
- ","
178
- );
179
- return SQL4`
180
- INSERT INTO ${SQL4.identifier(collectionName)} (_id, data, _version) VALUES ${values}
103
+ },
104
+ insertMany: (documents) => {
105
+ const values = SQL.merge(documents.map((doc) => SQL`(${doc._id}, ${serializer.serialize(doc)}, ${doc._version ?? 1n})`), ",");
106
+ return SQL`
107
+ INSERT INTO ${SQL.identifier(collectionName)} (_id, data, _version) VALUES ${values}
181
108
  ON CONFLICT(_id) DO NOTHING
182
109
  RETURNING _id;`;
183
- },
184
- updateOne: (filter, update, options) => {
185
- const expectedVersion = expectedVersionValue(options?.expectedVersion);
186
- const expectedVersionUpdate = expectedVersion != null ? SQL4`AND ${SQL4.identifier(collectionName)}._version = ${expectedVersion}` : SQL4``;
187
- const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
188
- const updateQuery = isSQL(update) ? update : buildUpdateQuery(update, serializer);
189
- return SQL4`
110
+ },
111
+ updateOne: (filter, update, options) => {
112
+ const expectedVersion = expectedVersionValue(options?.expectedVersion);
113
+ const expectedVersionUpdate = expectedVersion != null ? SQL`AND ${SQL.identifier(collectionName)}._version = ${expectedVersion}` : SQL``;
114
+ const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
115
+ const updateQuery = isSQL(update) ? update : buildUpdateQuery(update, serializer);
116
+ return SQL`
190
117
  WITH existing AS (
191
118
  SELECT _id, _version as current_version
192
- FROM ${SQL4.identifier(collectionName)} ${where(filterQuery)}
119
+ FROM ${SQL.identifier(collectionName)} ${where(filterQuery)}
193
120
  LIMIT 1
194
121
  ),
195
122
  updated AS (
196
- UPDATE ${SQL4.identifier(collectionName)}
123
+ UPDATE ${SQL.identifier(collectionName)}
197
124
  SET
198
- data = ${updateQuery} || jsonb_build_object('_id', ${SQL4.identifier(collectionName)}._id) || jsonb_build_object('_version', (_version + 1)::text),
125
+ data = ${updateQuery} || jsonb_build_object('_id', ${SQL.identifier(collectionName)}._id) || jsonb_build_object('_version', (_version + 1)::text),
199
126
  _version = _version + 1
200
127
  FROM existing
201
- WHERE ${SQL4.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
202
- RETURNING ${SQL4.identifier(collectionName)}._id, ${SQL4.identifier(collectionName)}._version
128
+ WHERE ${SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
129
+ RETURNING ${SQL.identifier(collectionName)}._id, ${SQL.identifier(collectionName)}._version
203
130
  )
204
131
  SELECT
205
132
  existing._id,
@@ -209,25 +136,25 @@ var postgresSQLBuilder = (collectionName, serializer) => ({
209
136
  FROM existing
210
137
  LEFT JOIN updated
211
138
  ON existing._id = updated._id;`;
212
- },
213
- replaceOne: (filter, document, options) => {
214
- const expectedVersion = expectedVersionValue(options?.expectedVersion);
215
- const expectedVersionUpdate = expectedVersion != null ? SQL4`AND ${SQL4.identifier(collectionName)}._version = ${expectedVersion}` : SQL4``;
216
- const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
217
- return SQL4`
139
+ },
140
+ replaceOne: (filter, document, options) => {
141
+ const expectedVersion = expectedVersionValue(options?.expectedVersion);
142
+ const expectedVersionUpdate = expectedVersion != null ? SQL`AND ${SQL.identifier(collectionName)}._version = ${expectedVersion}` : SQL``;
143
+ const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
144
+ return SQL`
218
145
  WITH existing AS (
219
146
  SELECT _id, _version as current_version
220
- FROM ${SQL4.identifier(collectionName)} ${where(filterQuery)}
147
+ FROM ${SQL.identifier(collectionName)} ${where(filterQuery)}
221
148
  LIMIT 1
222
149
  ),
223
150
  updated AS (
224
- UPDATE ${SQL4.identifier(collectionName)}
151
+ UPDATE ${SQL.identifier(collectionName)}
225
152
  SET
226
- data = ${serializer.serialize(document)} || jsonb_build_object('_id', ${SQL4.identifier(collectionName)}._id) || jsonb_build_object('_version', (_version + 1)::text),
153
+ data = ${serializer.serialize(document)} || jsonb_build_object('_id', ${SQL.identifier(collectionName)}._id) || jsonb_build_object('_version', (_version + 1)::text),
227
154
  _version = _version + 1
228
155
  FROM existing
229
- WHERE ${SQL4.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
230
- RETURNING ${SQL4.identifier(collectionName)}._id, ${SQL4.identifier(collectionName)}._version
156
+ WHERE ${SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
157
+ RETURNING ${SQL.identifier(collectionName)}._id, ${SQL.identifier(collectionName)}._version
231
158
  )
232
159
  SELECT
233
160
  existing._id,
@@ -237,32 +164,32 @@ var postgresSQLBuilder = (collectionName, serializer) => ({
237
164
  FROM existing
238
165
  LEFT JOIN updated
239
166
  ON existing._id = updated._id;`;
240
- },
241
- updateMany: (filter, update) => {
242
- const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
243
- const updateQuery = isSQL(update) ? update : buildUpdateQuery(update, serializer);
244
- return SQL4`
245
- UPDATE ${SQL4.identifier(collectionName)}
167
+ },
168
+ updateMany: (filter, update) => {
169
+ const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
170
+ const updateQuery = isSQL(update) ? update : buildUpdateQuery(update, serializer);
171
+ return SQL`
172
+ UPDATE ${SQL.identifier(collectionName)}
246
173
  SET
247
174
  data = ${updateQuery} || jsonb_build_object('_version', (_version + 1)::text),
248
175
  _version = _version + 1
249
176
  ${where(filterQuery)};`;
250
- },
251
- deleteOne: (filter, options) => {
252
- const expectedVersion = expectedVersionValue(options?.expectedVersion);
253
- const expectedVersionUpdate = expectedVersion != null ? SQL4`AND ${SQL4.identifier(collectionName)}._version = ${expectedVersion}` : SQL4``;
254
- const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
255
- return SQL4`
177
+ },
178
+ deleteOne: (filter, options) => {
179
+ const expectedVersion = expectedVersionValue(options?.expectedVersion);
180
+ const expectedVersionUpdate = expectedVersion != null ? SQL`AND ${SQL.identifier(collectionName)}._version = ${expectedVersion}` : SQL``;
181
+ const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
182
+ return SQL`
256
183
  WITH existing AS (
257
184
  SELECT _id
258
- FROM ${SQL4.identifier(collectionName)} ${where(filterQuery)}
185
+ FROM ${SQL.identifier(collectionName)} ${where(filterQuery)}
259
186
  LIMIT 1
260
187
  ),
261
188
  deleted AS (
262
- DELETE FROM ${SQL4.identifier(collectionName)}
189
+ DELETE FROM ${SQL.identifier(collectionName)}
263
190
  USING existing
264
- WHERE ${SQL4.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
265
- RETURNING ${SQL4.identifier(collectionName)}._id
191
+ WHERE ${SQL.identifier(collectionName)}._id = existing._id ${expectedVersionUpdate}
192
+ RETURNING ${SQL.identifier(collectionName)}._id
266
193
  )
267
194
  SELECT
268
195
  existing._id,
@@ -271,27 +198,17 @@ var postgresSQLBuilder = (collectionName, serializer) => ({
271
198
  FROM existing
272
199
  LEFT JOIN deleted
273
200
  ON existing._id = deleted._id;`;
274
- },
275
- deleteMany: (filter) => {
276
- const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
277
- return SQL4`DELETE FROM ${SQL4.identifier(collectionName)} ${where(filterQuery)}`;
278
- },
279
- replaceMany: (documents) => {
280
- const hasVersions = documents.some(
281
- (d) => "_version" in d && d._version !== void 0
282
- );
283
- if (hasVersions) {
284
- const values2 = SQL4.merge(
285
- documents.map(
286
- (d) => SQL4`(${d._id}::text, ${serializer.serialize(d)}::jsonb, ${d._version ?? 0n}::bigint)`
287
- ),
288
- ","
289
- );
290
- return SQL4`
201
+ },
202
+ deleteMany: (filter) => {
203
+ const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
204
+ return SQL`DELETE FROM ${SQL.identifier(collectionName)} ${where(filterQuery)}`;
205
+ },
206
+ replaceMany: (documents) => {
207
+ if (documents.some((d) => "_version" in d && d._version !== void 0)) return SQL`
291
208
  WITH replacements(_id, data, expected_version) AS (
292
- VALUES ${values2}
209
+ VALUES ${SQL.merge(documents.map((d) => SQL`(${d._id}::text, ${serializer.serialize(d)}::jsonb, ${d._version ?? 0n}::bigint)`), ",")}
293
210
  )
294
- UPDATE ${SQL4.identifier(collectionName)} t
211
+ UPDATE ${SQL.identifier(collectionName)} t
295
212
  SET
296
213
  data = r.data
297
214
  || jsonb_build_object('_id', t._id)
@@ -300,18 +217,11 @@ var postgresSQLBuilder = (collectionName, serializer) => ({
300
217
  FROM replacements r
301
218
  WHERE t._id = r._id AND t._version = r.expected_version
302
219
  RETURNING t._id, t._version AS version;`;
303
- }
304
- const values = SQL4.merge(
305
- documents.map(
306
- (d) => SQL4`(${d._id}::text, ${serializer.serialize(d)}::jsonb)`
307
- ),
308
- ","
309
- );
310
- return SQL4`
220
+ return SQL`
311
221
  WITH replacements(_id, data) AS (
312
- VALUES ${values}
222
+ VALUES ${SQL.merge(documents.map((d) => SQL`(${d._id}::text, ${serializer.serialize(d)}::jsonb)`), ",")}
313
223
  )
314
- UPDATE ${SQL4.identifier(collectionName)} t
224
+ UPDATE ${SQL.identifier(collectionName)} t
315
225
  SET
316
226
  data = r.data
317
227
  || jsonb_build_object('_id', t._id)
@@ -320,20 +230,14 @@ var postgresSQLBuilder = (collectionName, serializer) => ({
320
230
  FROM replacements r
321
231
  WHERE t._id = r._id
322
232
  RETURNING t._id, t._version AS version;`;
323
- },
324
- deleteManyByIds: (ids) => {
325
- const hasVersions = ids.some((d) => d._version !== void 0);
326
- if (hasVersions) {
327
- const values2 = SQL4.merge(
328
- ids.map((d) => SQL4`(${d._id}::text, ${d._version ?? 0n}::bigint)`),
329
- ","
330
- );
331
- return SQL4`
233
+ },
234
+ deleteManyByIds: (ids) => {
235
+ if (ids.some((d) => d._version !== void 0)) return SQL`
332
236
  WITH targets(_id, expected_version) AS (
333
- VALUES ${values2}
237
+ VALUES ${SQL.merge(ids.map((d) => SQL`(${d._id}::text, ${d._version ?? 0n}::bigint)`), ",")}
334
238
  ),
335
239
  deleted AS (
336
- DELETE FROM ${SQL4.identifier(collectionName)} t
240
+ DELETE FROM ${SQL.identifier(collectionName)} t
337
241
  USING targets r
338
242
  WHERE t._id = r._id AND t._version = r.expected_version
339
243
  RETURNING t._id
@@ -342,17 +246,12 @@ var postgresSQLBuilder = (collectionName, serializer) => ({
342
246
  CASE WHEN d._id IS NOT NULL THEN 1 ELSE 0 END as deleted
343
247
  FROM targets r
344
248
  LEFT JOIN deleted d ON r._id = d._id;`;
345
- }
346
- const values = SQL4.merge(
347
- ids.map((d) => SQL4`(${d._id}::text)`),
348
- ","
349
- );
350
- return SQL4`
249
+ return SQL`
351
250
  WITH targets(_id) AS (
352
- VALUES ${values}
251
+ VALUES ${SQL.merge(ids.map((d) => SQL`(${d._id}::text)`), ",")}
353
252
  ),
354
253
  deleted AS (
355
- DELETE FROM ${SQL4.identifier(collectionName)} t
254
+ DELETE FROM ${SQL.identifier(collectionName)} t
356
255
  USING targets r
357
256
  WHERE t._id = r._id
358
257
  RETURNING t._id
@@ -361,82 +260,71 @@ var postgresSQLBuilder = (collectionName, serializer) => ({
361
260
  CASE WHEN d._id IS NOT NULL THEN 1 ELSE 0 END as deleted
362
261
  FROM targets r
363
262
  LEFT JOIN deleted d ON r._id = d._id;`;
364
- },
365
- findOne: (filter) => {
366
- const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
367
- return SQL4`SELECT data, _version FROM ${SQL4.identifier(collectionName)} ${where(filterQuery)} LIMIT 1;`;
368
- },
369
- find: (filter, options) => {
370
- const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
371
- const query = [];
372
- query.push(
373
- SQL4`SELECT data, _version FROM ${SQL4.identifier(collectionName)}`
374
- );
375
- query.push(where(filterQuery));
376
- if (options?.limit) {
377
- query.push(SQL4`LIMIT ${options.limit}`);
378
- }
379
- if (options?.skip) {
380
- query.push(SQL4`OFFSET ${options.skip}`);
381
- }
382
- return SQL4.merge([...query, SQL4`;`]);
383
- },
384
- countDocuments: (filter) => {
385
- const filterQuery = SQL4.check.isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
386
- return SQL4`SELECT COUNT(1) as count FROM ${SQL4.identifier(collectionName)} ${where(filterQuery)};`;
387
- },
388
- rename: (newName) => SQL4`ALTER TABLE ${SQL4.identifier(collectionName)} RENAME TO ${SQL4.identifier(newName)};`,
389
- drop: (targetName = collectionName) => SQL4`DROP TABLE IF EXISTS ${SQL4.identifier(targetName)}`
263
+ },
264
+ findOne: (filter) => {
265
+ const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
266
+ return SQL`SELECT data, _version FROM ${SQL.identifier(collectionName)} ${where(filterQuery)} LIMIT 1;`;
267
+ },
268
+ find: (filter, options) => {
269
+ const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
270
+ const query = [];
271
+ query.push(SQL`SELECT data, _version FROM ${SQL.identifier(collectionName)}`);
272
+ query.push(where(filterQuery));
273
+ if (options?.sort && Object.keys(options.sort).length > 0) {
274
+ const clauses = Object.entries(options.sort).map(([field, dir]) => {
275
+ const isMetadata = field === "_id" || field === "_version";
276
+ const isNested = !isMetadata && field.includes(".");
277
+ const accessor = isMetadata ? SQL`${SQL.plain(field)}` : isNested ? SQL`data #> '${SQL.plain(`{${field.split(".").join(",")}}`)}'` : SQL`data -> '${SQL.plain(field)}'`;
278
+ return dir === 1 ? SQL`${accessor} ASC NULLS FIRST` : SQL`${accessor} DESC NULLS LAST`;
279
+ });
280
+ query.push(SQL`ORDER BY ${SQL.merge(clauses, ",")}`);
281
+ }
282
+ if (options?.limit) query.push(SQL`LIMIT ${options.limit}`);
283
+ if (options?.skip) query.push(SQL`OFFSET ${options.skip}`);
284
+ return SQL.merge([...query, SQL`;`]);
285
+ },
286
+ countDocuments: (filter) => {
287
+ const filterQuery = SQL.check.isSQL(filter) ? filter : constructFilterQuery(filter, serializer);
288
+ return SQL`SELECT COUNT(1) as count FROM ${SQL.identifier(collectionName)} ${where(filterQuery)};`;
289
+ },
290
+ rename: (newName) => SQL`ALTER TABLE ${SQL.identifier(collectionName)} RENAME TO ${SQL.identifier(newName)};`,
291
+ drop: (targetName = collectionName) => SQL`DROP TABLE IF EXISTS ${SQL.identifier(targetName)}`
390
292
  });
391
- var where = (filterQuery) => SQL4.check.isEmpty(filterQuery) ? SQL4.EMPTY : SQL4.merge([SQL4`WHERE `, filterQuery]);
293
+ const where = (filterQuery) => SQL.check.isEmpty(filterQuery) ? SQL.EMPTY : SQL.merge([SQL`WHERE `, filterQuery]);
392
294
 
393
- // src/storage/postgresql/pg/index.ts
394
- import { dumbo, JSONSerializer } from "@event-driven-io/dumbo";
395
- import {
396
- pgDumboDriver as dumboDriver,
397
- PgDriverType,
398
- postgreSQLMetadata
399
- } from "@event-driven-io/dumbo/pg";
400
- var pgPongoDriver = {
401
- driverType: PgDriverType,
402
- databaseFactory: (options) => {
403
- const databaseName = options.databaseName ?? postgreSQLMetadata.parseDatabaseName(options.connectionString) ?? postgreSQLMetadata.defaultDatabaseName;
404
- return PongoDatabase({
405
- ...options,
406
- pool: dumbo({
407
- connectionString: options.connectionString,
408
- driver: dumboDriver,
409
- ...options.connectionOptions,
410
- serialization: { serializer: options.serializer }
411
- }),
412
- schemaComponent: PongoDatabaseSchemaComponent({
413
- driverType: PgDriverType,
414
- collectionFactory: (schema) => PongoCollectionSchemaComponent({
415
- driverType: PgDriverType,
416
- definition: schema,
417
- migrationsOrSchemaComponents: {
418
- migrations: pongoCollectionPostgreSQLMigrations(schema.name)
419
- },
420
- sqlBuilder: postgresSQLBuilder(
421
- schema.name,
422
- options.serialization?.serializer ?? JSONSerializer
423
- )
424
- }),
425
- definition: options.schema?.definition ?? pongoSchema.db(databaseName, {})
426
- }),
427
- databaseName
428
- });
429
- }
295
+ //#endregion
296
+ //#region src/storage/postgresql/pg/index.ts
297
+ const pgPongoDriver = {
298
+ driverType: PgDriverType,
299
+ databaseFactory: (options) => {
300
+ const databaseName = options.databaseName ?? postgreSQLMetadata.parseDatabaseName(options.connectionString) ?? postgreSQLMetadata.defaultDatabaseName;
301
+ return PongoDatabase({
302
+ ...options,
303
+ pool: dumbo({
304
+ connectionString: options.connectionString,
305
+ driver: pgDumboDriver,
306
+ ...options.connectionOptions,
307
+ serialization: { serializer: options.serializer }
308
+ }),
309
+ schemaComponent: PongoDatabaseSchemaComponent({
310
+ driverType: PgDriverType,
311
+ collectionFactory: (schema) => PongoCollectionSchemaComponent({
312
+ driverType: PgDriverType,
313
+ definition: schema,
314
+ migrationsOrSchemaComponents: { migrations: pongoCollectionPostgreSQLMigrations(schema.name) },
315
+ sqlBuilder: postgresSQLBuilder(schema.name, options.serialization?.serializer ?? JSONSerializer)
316
+ }),
317
+ definition: options.schema?.definition ?? pongoSchema.db(databaseName, {})
318
+ }),
319
+ databaseName
320
+ });
321
+ }
430
322
  };
431
- var usePgPongoDriver = () => {
432
- pongoDriverRegistry.register(PgDriverType, pgPongoDriver);
323
+ const usePgPongoDriver = () => {
324
+ pongoDriverRegistry.register(PgDriverType, pgPongoDriver);
433
325
  };
434
326
  usePgPongoDriver();
435
- export {
436
- pgPongoDriver as pgDriver,
437
- pongoCollectionPostgreSQLMigrations,
438
- pgPongoDriver as pongoDriver,
439
- postgresSQLBuilder,
440
- usePgPongoDriver
441
- };
327
+
328
+ //#endregion
329
+ export { pgPongoDriver as pgDriver, pgPongoDriver as pongoDriver, pongoCollectionPostgreSQLMigrations, postgresSQLBuilder, usePgPongoDriver };
442
330
  //# sourceMappingURL=pg.js.map