@event-driven-io/pongo 0.17.0-beta.33 → 0.17.0-beta.35

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 (46) hide show
  1. package/dist/chunk-EQ3T4XHT.cjs +1583 -0
  2. package/dist/chunk-EQ3T4XHT.cjs.map +1 -0
  3. package/dist/{chunk-TTZGGAZV.js → chunk-H6YIW5C5.js} +69 -2
  4. package/dist/chunk-H6YIW5C5.js.map +1 -0
  5. package/dist/{chunk-A4DCNQJR.cjs → chunk-NTHMSHNG.cjs} +79 -12
  6. package/dist/chunk-NTHMSHNG.cjs.map +1 -0
  7. package/dist/{chunk-H637RRXS.js → chunk-NWYI26VT.js} +1310 -632
  8. package/dist/chunk-NWYI26VT.js.map +1 -0
  9. package/dist/cli.cjs +13 -13
  10. package/dist/cli.cjs.map +1 -1
  11. package/dist/cli.js +2 -2
  12. package/dist/cli.js.map +1 -1
  13. package/dist/cloudflare.cjs +10 -10
  14. package/dist/cloudflare.d.cts +3 -2
  15. package/dist/cloudflare.d.ts +3 -2
  16. package/dist/cloudflare.js +2 -2
  17. package/dist/{index-gHRYr05w.d.ts → index-BfBszcG4.d.ts} +1 -1
  18. package/dist/{index-DxHXL62G.d.cts → index-a-fxODW1.d.cts} +1 -1
  19. package/dist/index.cjs +26 -2
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +38 -16
  22. package/dist/index.d.ts +38 -16
  23. package/dist/index.js +25 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/pg.cjs +102 -16
  26. package/dist/pg.cjs.map +1 -1
  27. package/dist/pg.d.cts +2 -1
  28. package/dist/pg.d.ts +2 -1
  29. package/dist/pg.js +87 -1
  30. package/dist/pg.js.map +1 -1
  31. package/dist/{pongoCollectionSchemaComponent-B5Oatwu0.d.cts → pongoTransactionCache-CRuPGag3.d.cts} +155 -35
  32. package/dist/{pongoCollectionSchemaComponent-B5Oatwu0.d.ts → pongoTransactionCache-CRuPGag3.d.ts} +155 -35
  33. package/dist/shim.cjs +5 -5
  34. package/dist/shim.d.cts +2 -1
  35. package/dist/shim.d.ts +2 -1
  36. package/dist/shim.js +1 -1
  37. package/dist/sqlite3.cjs +10 -10
  38. package/dist/sqlite3.d.cts +3 -2
  39. package/dist/sqlite3.d.ts +3 -2
  40. package/dist/sqlite3.js +2 -2
  41. package/package.json +20 -18
  42. package/dist/chunk-A4DCNQJR.cjs.map +0 -1
  43. package/dist/chunk-BZRKCNRY.cjs +0 -905
  44. package/dist/chunk-BZRKCNRY.cjs.map +0 -1
  45. package/dist/chunk-H637RRXS.js.map +0 -1
  46. package/dist/chunk-TTZGGAZV.js.map +0 -1
@@ -1,905 +0,0 @@
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; }// src/core/collection/pongoCollection.ts
2
-
3
-
4
-
5
-
6
-
7
- var _dumbo = require('@event-driven-io/dumbo');
8
- var _uuid = require('uuid');
9
-
10
- // src/core/collection/pongoCollectionSchemaComponent.ts
11
-
12
-
13
-
14
- var PongoCollectionSchemaComponent = ({
15
- definition,
16
- migrationsOrSchemaComponents,
17
- sqlBuilder
18
- }) => ({
19
- ..._dumbo.schemaComponent.call(void 0,
20
- `sc:pongo:collection:${definition.name}`,
21
- migrationsOrSchemaComponents
22
- ),
23
- sqlBuilder,
24
- definition,
25
- collectionName: definition.name
26
- });
27
-
28
- // src/core/collection/query.ts
29
- var QueryOperators = {
30
- $eq: "$eq",
31
- $gt: "$gt",
32
- $gte: "$gte",
33
- $lt: "$lt",
34
- $lte: "$lte",
35
- $ne: "$ne",
36
- $in: "$in",
37
- $nin: "$nin",
38
- $elemMatch: "$elemMatch",
39
- $all: "$all",
40
- $size: "$size"
41
- };
42
- var OperatorMap = {
43
- $gt: ">",
44
- $gte: ">=",
45
- $lt: "<",
46
- $lte: "<=",
47
- $ne: "!="
48
- };
49
- var isOperator = (key) => key.startsWith("$");
50
- var hasOperators = (value) => Object.keys(value).some(isOperator);
51
-
52
- // src/core/database/pongoDatabaseCache.ts
53
-
54
-
55
-
56
- var PongoDatabaseCache = ({
57
- driver,
58
- typedSchema
59
- }) => {
60
- const dbClients = /* @__PURE__ */ new Map();
61
- const getDatabaseDefinition = (dbName) => Object.values(_nullishCoalesce(_optionalChain([typedSchema, 'optionalAccess', _ => _.dbs]), () => ( {}))).find((d) => d.name === dbName);
62
- return {
63
- getOrCreate: (createOptions) => {
64
- const metadata = _dumbo.getDatabaseMetadata.call(void 0, driver.driverType);
65
- const dbName = _nullishCoalesce(_nullishCoalesce(createOptions.databaseName, () => ( _optionalChain([metadata, 'optionalAccess', _2 => _2.parseDatabaseName, 'optionalCall', _3 => _3(
66
- "connectionString" in createOptions ? createOptions.connectionString : void 0
67
- )]))), () => ( "db:default"));
68
- const existing = dbClients.get(dbName);
69
- if (existing) return existing;
70
- const definition = getDatabaseDefinition(createOptions.databaseName);
71
- const newDb = driver.databaseFactory({
72
- ...createOptions,
73
- databaseName: dbName,
74
- schema: {
75
- ...createOptions.schema,
76
- ...definition ? { definition } : {}
77
- }
78
- });
79
- dbClients.set(dbName, newDb);
80
- return newDb;
81
- },
82
- all: () => Array.from(dbClients.values()),
83
- forAll: (func) => {
84
- return Promise.all(
85
- Array.from(dbClients.values()).map((v) => v).map(func)
86
- );
87
- }
88
- };
89
- };
90
-
91
- // src/core/database/pongoDatabaseSchemaComponent.ts
92
-
93
-
94
-
95
-
96
- // src/core/typing/entries.ts
97
- var objectEntries = (obj) => Object.entries(obj).map(([key, value]) => [key, value]);
98
-
99
- // src/core/typing/operations.ts
100
-
101
-
102
- // src/core/errors/index.ts
103
- var isNumber = (val) => typeof val === "number" && val === val;
104
- var isString = (val) => typeof val === "string";
105
- var PongoError = class _PongoError extends Error {
106
-
107
- constructor(options) {
108
- const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : 500;
109
- const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during Pongo processing`;
110
- super(message);
111
- this.errorCode = errorCode;
112
- Object.setPrototypeOf(this, _PongoError.prototype);
113
- }
114
- };
115
- var ConcurrencyError = class _ConcurrencyError extends PongoError {
116
- constructor(message) {
117
- super({
118
- errorCode: 412,
119
- message: _nullishCoalesce(message, () => ( `Expected document state does not match current one!`))
120
- });
121
- Object.setPrototypeOf(this, _ConcurrencyError.prototype);
122
- }
123
- };
124
-
125
- // src/core/typing/operations.ts
126
- var ObjectId = (value) => _nullishCoalesce(value, () => ( _uuid.v7.call(void 0, )));
127
- var DOCUMENT_EXISTS = "DOCUMENT_EXISTS";
128
- var DOCUMENT_DOES_NOT_EXIST = "DOCUMENT_DOES_NOT_EXIST";
129
- var NO_CONCURRENCY_CHECK = "NO_CONCURRENCY_CHECK";
130
- var isGeneralExpectedDocumentVersion = (version) => version === "DOCUMENT_DOES_NOT_EXIST" || version === "DOCUMENT_EXISTS" || version === "NO_CONCURRENCY_CHECK";
131
- var expectedVersionValue = (version) => version === void 0 || isGeneralExpectedDocumentVersion(version) ? null : version;
132
- var expectedVersion = (version) => {
133
- return version ? BigInt(version) : NO_CONCURRENCY_CHECK;
134
- };
135
- var operationResult = (result, options) => {
136
- const operationResult2 = {
137
- ...result,
138
- acknowledged: true,
139
- successful: result.successful,
140
- assertSuccessful: (errorMessage) => {
141
- const { successful } = result;
142
- const { operationName, collectionName } = options;
143
- if (!successful)
144
- throw new ConcurrencyError(
145
- _nullishCoalesce(errorMessage, () => ( `${operationName} on ${collectionName} failed. Expected document state does not match current one! Result: ${options.serializer.serialize(result)}!`))
146
- );
147
- }
148
- };
149
- if (_optionalChain([options, 'access', _4 => _4.errors, 'optionalAccess', _5 => _5.throwOnOperationFailures]))
150
- operationResult2.assertSuccessful();
151
- return operationResult2;
152
- };
153
-
154
- // src/core/schema/index.ts
155
- var pongoCollectionSchema = (name) => ({
156
- name
157
- });
158
- pongoCollectionSchema.from = (collectionNames) => collectionNames.reduce(
159
- (acc, collectionName) => (acc[collectionName] = pongoSchema.collection(collectionName), acc),
160
- {}
161
- );
162
- function pongoDbSchema(nameOrCollections, collections) {
163
- if (collections === void 0) {
164
- if (typeof nameOrCollections === "string") {
165
- throw new Error("You need to provide colleciton definition");
166
- }
167
- return {
168
- collections: nameOrCollections
169
- };
170
- }
171
- return nameOrCollections && typeof nameOrCollections === "string" ? {
172
- name: nameOrCollections,
173
- collections
174
- } : { collections };
175
- }
176
- pongoDbSchema.from = (databaseName, collectionNames) => databaseName ? pongoDbSchema(databaseName, pongoCollectionSchema.from(collectionNames)) : pongoDbSchema(pongoCollectionSchema.from(collectionNames));
177
- var pongoClientSchema = (dbs) => ({
178
- dbs
179
- });
180
- var pongoSchema = {
181
- client: pongoClientSchema,
182
- db: pongoDbSchema,
183
- collection: pongoCollectionSchema
184
- };
185
- var proxyPongoDbWithSchema = (pongoDb, dbSchema, collections) => {
186
- const collectionNames = Object.keys(dbSchema.collections);
187
- for (const collectionName of collectionNames) {
188
- collections.set(collectionName, pongoDb.collection(collectionName));
189
- }
190
- return new Proxy(
191
- pongoDb,
192
- {
193
- get(target, prop) {
194
- return _nullishCoalesce(collections.get(prop), () => ( target[prop]));
195
- }
196
- }
197
- );
198
- };
199
- var proxyClientWithSchema = (client, schema) => {
200
- if (!schema)
201
- return client;
202
- const dbNames = Object.keys(schema.dbs);
203
- return new Proxy(
204
- client,
205
- {
206
- get(target, prop) {
207
- if (dbNames.includes(prop)) return client.db(_optionalChain([schema, 'access', _6 => _6.dbs, 'access', _7 => _7[prop], 'optionalAccess', _8 => _8.name]));
208
- return target[prop];
209
- }
210
- }
211
- );
212
- };
213
- var toDbSchemaMetadata = (schema) => ({
214
- name: schema.name,
215
- collections: objectEntries(schema.collections).map((c) => ({
216
- name: c[1].name
217
- }))
218
- });
219
- var toClientSchemaMetadata = (schema) => {
220
- const databases = objectEntries(schema.dbs).map(
221
- (e) => toDbSchemaMetadata(e[1])
222
- );
223
- return {
224
- databases,
225
- database: (name) => databases.find((db) => db.name === name)
226
- };
227
- };
228
-
229
- // src/core/database/pongoDatabaseSchemaComponent.ts
230
- var PongoDatabaseSchemaComponent = ({
231
- definition,
232
- collectionFactory
233
- }) => {
234
- const collections = _nullishCoalesce(Object.values(definition.collections).map(collectionFactory), () => ( []));
235
- return {
236
- ..._dumbo.schemaComponent.call(void 0, `sc:dumbo:database:${definition.name}`, {
237
- components: collections
238
- }),
239
- definition,
240
- collections,
241
- collection: (schema) => {
242
- const existing = collections.find(
243
- (c) => c.collectionName === schema.name
244
- );
245
- if (existing) return existing;
246
- const newCollection = collectionFactory(
247
- pongoSchema.collection(schema.name)
248
- );
249
- collections.push(newCollection);
250
- definition.collections[schema.name] = schema;
251
- return newCollection;
252
- }
253
- };
254
- };
255
-
256
- // src/core/database/pongoDb.ts
257
-
258
-
259
-
260
- var PongoDatabase = (options) => {
261
- const { databaseName, schemaComponent: schemaComponent3, pool, serializer } = options;
262
- const collections = /* @__PURE__ */ new Map();
263
- const command = async (sql, options2) => (await transactionExecutorOrDefault(db, options2, pool.execute)).command(sql, options2);
264
- const query = async (sql, options2) => (await transactionExecutorOrDefault(db, options2, pool.execute)).query(
265
- sql,
266
- options2
267
- );
268
- const driverType = pool.driverType;
269
- const db = {
270
- driverType,
271
- databaseName,
272
- connect: () => Promise.resolve(),
273
- close: () => pool.close(),
274
- collections: () => [...collections.values()],
275
- collection: (collectionName, collectionOptions) => _nullishCoalesce(collections.get(collectionName), () => ( pongoCollection({
276
- collectionName,
277
- db,
278
- pool,
279
- schemaComponent: schemaComponent3.collection(
280
- pongoSchema.collection(collectionName)
281
- ),
282
- schema: { ...options.schema, ..._optionalChain([collectionOptions, 'optionalAccess', _9 => _9.schema]) },
283
- serializer,
284
- errors: { ...options.errors, ..._optionalChain([collectionOptions, 'optionalAccess', _10 => _10.errors]) }
285
- }))),
286
- transaction: () => pool.transaction(),
287
- withTransaction: (handle) => pool.withTransaction(handle),
288
- schema: {
289
- component: schemaComponent3,
290
- migrate: (options2) => _dumbo.runSQLMigrations.call(void 0, pool, schemaComponent3.migrations, options2)
291
- },
292
- sql: {
293
- async query(sql, options2) {
294
- const result = await query(sql, options2);
295
- return result.rows;
296
- },
297
- async command(sql, options2) {
298
- return command(sql, options2);
299
- }
300
- }
301
- };
302
- const dbSchema = _optionalChain([options, 'optionalAccess', _11 => _11.schema, 'optionalAccess', _12 => _12.definition]);
303
- if (dbSchema) {
304
- return proxyPongoDbWithSchema(db, dbSchema, collections);
305
- }
306
- return db;
307
- };
308
-
309
- // src/core/drivers/databaseDriver.ts
310
- var PongoDriverRegistry = () => {
311
- const drivers = /* @__PURE__ */ new Map();
312
- const register = (driverType, driver) => {
313
- const entry = drivers.get(driverType);
314
- if (entry && (typeof entry !== "function" || typeof driver === "function")) {
315
- return;
316
- }
317
- drivers.set(driverType, driver);
318
- };
319
- const tryResolve = async (driverType) => {
320
- const entry = drivers.get(driverType);
321
- if (!entry) return null;
322
- if (typeof entry !== "function") return entry;
323
- const driver = await entry();
324
- register(driverType, driver);
325
- return driver;
326
- };
327
- const tryGet = (driverType) => {
328
- const entry = drivers.get(driverType);
329
- return entry && typeof entry !== "function" ? entry : null;
330
- };
331
- const has = (driverType) => drivers.has(driverType);
332
- return {
333
- register,
334
- tryResolve,
335
- tryGet,
336
- has,
337
- get databaseDriverTypes() {
338
- return Array.from(drivers.keys());
339
- }
340
- };
341
- };
342
- var pongoDriverRegistry = globalThis.pongoDriverRegistry = _nullishCoalesce(globalThis.pongoDriverRegistry, () => ( PongoDriverRegistry()));
343
-
344
- // src/core/pongoClient.ts
345
-
346
-
347
- // src/core/pongoTransaction.ts
348
- var pongoTransaction = (options) => {
349
- let isCommitted = false;
350
- let isRolledBack = false;
351
- let databaseName = null;
352
- let transaction = null;
353
- return {
354
- enlistDatabase: async (db) => {
355
- if (transaction && databaseName !== db.databaseName)
356
- throw new Error(
357
- "There's already other database assigned to transaction"
358
- );
359
- if (transaction && databaseName === db.databaseName) return transaction;
360
- databaseName = db.databaseName;
361
- transaction = db.transaction();
362
- await transaction.begin();
363
- return transaction;
364
- },
365
- commit: async () => {
366
- if (!transaction) throw new Error("No database transaction started!");
367
- if (isCommitted) return;
368
- if (isRolledBack) throw new Error("Transaction is not active!");
369
- isCommitted = true;
370
- await transaction.commit();
371
- transaction = null;
372
- },
373
- rollback: async (error) => {
374
- if (!transaction) throw new Error("No database transaction started!");
375
- if (isCommitted) throw new Error("Cannot rollback commited transaction!");
376
- if (isRolledBack) return;
377
- isRolledBack = true;
378
- await transaction.rollback(error);
379
- transaction = null;
380
- },
381
- databaseName,
382
- isStarting: false,
383
- isCommitted,
384
- get isActive() {
385
- return !isCommitted && !isRolledBack;
386
- },
387
- get sqlExecutor() {
388
- if (transaction === null)
389
- throw new Error("No database transaction was started");
390
- return transaction.execute;
391
- },
392
- options
393
- };
394
- };
395
-
396
- // src/core/pongoSession.ts
397
- var isActive = (transaction) => _optionalChain([transaction, 'optionalAccess', _13 => _13.isActive]) === true;
398
- function assertInActiveTransaction(transaction) {
399
- if (!isActive(transaction)) throw new Error("No active transaction exists!");
400
- }
401
- function assertNotInActiveTransaction(transaction) {
402
- if (isActive(transaction))
403
- throw new Error("Active transaction already exists!");
404
- }
405
- var pongoSession = (options) => {
406
- const explicit = _optionalChain([options, 'optionalAccess', _14 => _14.explicit]) === true;
407
- const defaultTransactionOptions = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.defaultTransactionOptions]), () => ( {
408
- get snapshotEnabled() {
409
- return false;
410
- }
411
- }));
412
- let transaction = null;
413
- let hasEnded = false;
414
- const startTransaction = (options2) => {
415
- assertNotInActiveTransaction(transaction);
416
- transaction = pongoTransaction(_nullishCoalesce(options2, () => ( defaultTransactionOptions)));
417
- };
418
- const commitTransaction = async () => {
419
- assertInActiveTransaction(transaction);
420
- await transaction.commit();
421
- };
422
- const abortTransaction = async () => {
423
- assertInActiveTransaction(transaction);
424
- await transaction.rollback();
425
- };
426
- const endSession = async () => {
427
- if (hasEnded) return;
428
- hasEnded = true;
429
- if (isActive(transaction)) await transaction.rollback();
430
- };
431
- const session = {
432
- get hasEnded() {
433
- return hasEnded;
434
- },
435
- explicit,
436
- defaultTransactionOptions: _nullishCoalesce(defaultTransactionOptions, () => ( {
437
- get snapshotEnabled() {
438
- return false;
439
- }
440
- })),
441
- get transaction() {
442
- return transaction;
443
- },
444
- get snapshotEnabled() {
445
- return defaultTransactionOptions.snapshotEnabled;
446
- },
447
- endSession,
448
- incrementTransactionNumber: () => {
449
- },
450
- inTransaction: () => isActive(transaction),
451
- startTransaction,
452
- commitTransaction,
453
- abortTransaction,
454
- withTransaction: async (fn, options2) => {
455
- startTransaction(options2);
456
- try {
457
- const result = await fn(session);
458
- await commitTransaction();
459
- return result;
460
- } catch (error) {
461
- await abortTransaction();
462
- throw error;
463
- }
464
- }
465
- };
466
- return session;
467
- };
468
-
469
- // src/core/pongoClient.ts
470
- var pongoClient = (options) => {
471
- const { driver, schema, errors, ...connectionOptions } = options;
472
- const dbClients = PongoDatabaseCache({
473
- driver,
474
- typedSchema: _optionalChain([schema, 'optionalAccess', _16 => _16.definition])
475
- });
476
- const serializer = _dumbo.JSONSerializer.from(options);
477
- const pongoClient2 = {
478
- driverType: driver.driverType,
479
- connect: async () => {
480
- await dbClients.forAll((db) => db.connect());
481
- return pongoClient2;
482
- },
483
- close: async () => {
484
- await dbClients.forAll((db) => db.close());
485
- },
486
- db: (dbName) => {
487
- const db = dbClients.getOrCreate({
488
- ...connectionOptions,
489
- databaseName: dbName,
490
- serializer,
491
- errors
492
- });
493
- return db;
494
- },
495
- startSession: pongoSession,
496
- withSession: async (callback) => {
497
- const session = pongoSession();
498
- try {
499
- return await callback(session);
500
- } finally {
501
- await session.endSession();
502
- }
503
- }
504
- };
505
- return proxyClientWithSchema(pongoClient2, _optionalChain([schema, 'optionalAccess', _17 => _17.definition]));
506
- };
507
-
508
- // src/core/utils/deepEquals.ts
509
- var deepEquals = (left, right) => {
510
- if (isEquatable(left)) {
511
- return left.equals(right);
512
- }
513
- if (Array.isArray(left)) {
514
- return Array.isArray(right) && left.length === right.length && left.every((val, index) => deepEquals(val, right[index]));
515
- }
516
- if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) {
517
- return left === right;
518
- }
519
- if (Array.isArray(right)) return false;
520
- const keys1 = Object.keys(left);
521
- const keys2 = Object.keys(right);
522
- if (keys1.length !== keys2.length || !keys1.every((key) => keys2.includes(key)))
523
- return false;
524
- for (const key in left) {
525
- if (left[key] instanceof Function && right[key] instanceof Function)
526
- continue;
527
- const isEqual = deepEquals(left[key], right[key]);
528
- if (!isEqual) {
529
- return false;
530
- }
531
- }
532
- return true;
533
- };
534
- var isEquatable = (left) => {
535
- return left && typeof left === "object" && "equals" in left && typeof left["equals"] === "function";
536
- };
537
-
538
- // src/core/collection/pongoCollection.ts
539
- var enlistIntoTransactionIfActive = async (db, options) => {
540
- const transaction = _optionalChain([options, 'optionalAccess', _18 => _18.session, 'optionalAccess', _19 => _19.transaction]);
541
- if (!transaction || !transaction.isActive) return null;
542
- return await transaction.enlistDatabase(db);
543
- };
544
- var transactionExecutorOrDefault = async (db, options, defaultSqlExecutor) => {
545
- const existingTransaction = await enlistIntoTransactionIfActive(db, options);
546
- return _nullishCoalesce(_optionalChain([existingTransaction, 'optionalAccess', _20 => _20.execute]), () => ( defaultSqlExecutor));
547
- };
548
- var pongoCollection = ({
549
- db,
550
- collectionName,
551
- pool,
552
- schemaComponent: schemaComponent3,
553
- schema,
554
- errors,
555
- serializer
556
- }) => {
557
- const SqlFor = schemaComponent3.sqlBuilder;
558
- const sqlExecutor = pool.execute;
559
- const columnMapping = {
560
- mapping: {
561
- ..._dumbo.mapColumnToJSON.call(void 0, "data", serializer),
562
- //...mapColumnToJSON('metadata'),
563
- ..._dumbo.mapColumnToBigint.call(void 0, "_version")
564
- }
565
- };
566
- const command = async (sql, options) => (await transactionExecutorOrDefault(db, options, sqlExecutor)).command(sql, columnMapping);
567
- const query = async (sql, options) => (await transactionExecutorOrDefault(db, options, sqlExecutor)).query(
568
- sql,
569
- columnMapping
570
- );
571
- let shouldMigrate = _optionalChain([schema, 'optionalAccess', _21 => _21.autoMigration]) !== "None";
572
- const createCollection = (options) => {
573
- shouldMigrate = false;
574
- if (_optionalChain([options, 'optionalAccess', _22 => _22.session])) return command(SqlFor.createCollection(), options);
575
- else return command(SqlFor.createCollection());
576
- };
577
- const ensureCollectionCreated = (options) => {
578
- if (!shouldMigrate) {
579
- return Promise.resolve();
580
- }
581
- return createCollection(options);
582
- };
583
- const upcast = _nullishCoalesce(_optionalChain([schema, 'optionalAccess', _23 => _23.versioning, 'optionalAccess', _24 => _24.upcast]), () => ( ((doc) => doc)));
584
- const downcast = _nullishCoalesce(_optionalChain([schema, 'optionalAccess', _25 => _25.versioning, 'optionalAccess', _26 => _26.downcast]), () => ( ((doc) => doc)));
585
- const collection = {
586
- dbName: db.databaseName,
587
- collectionName,
588
- createCollection: async (options) => {
589
- await createCollection(options);
590
- },
591
- insertOne: async (document, options) => {
592
- await ensureCollectionCreated(options);
593
- const _id = _nullishCoalesce(document._id, () => ( _uuid.v7.call(void 0, )));
594
- const _version = _nullishCoalesce(document._version, () => ( 1n));
595
- const downcasted = downcast(document);
596
- const result = await command(
597
- SqlFor.insertOne({
598
- ...downcasted,
599
- _id,
600
- _version
601
- }),
602
- options
603
- );
604
- const successful = (_nullishCoalesce(result.rowCount, () => ( 0))) > 0;
605
- return operationResult(
606
- {
607
- successful,
608
- insertedId: successful ? _id : null,
609
- nextExpectedVersion: _version
610
- },
611
- { operationName: "insertOne", collectionName, serializer, errors }
612
- );
613
- },
614
- insertMany: async (documents, options) => {
615
- await ensureCollectionCreated(options);
616
- const rows = documents.map((doc) => {
617
- const downcasted = downcast(doc);
618
- return {
619
- ...downcasted,
620
- _id: _nullishCoalesce(doc._id, () => ( _uuid.v7.call(void 0, ))),
621
- _version: _nullishCoalesce(doc._version, () => ( 1n))
622
- };
623
- });
624
- const result = await command(
625
- SqlFor.insertMany(
626
- rows
627
- ),
628
- options
629
- );
630
- return operationResult(
631
- {
632
- successful: result.rowCount === rows.length,
633
- insertedCount: _nullishCoalesce(result.rowCount, () => ( 0)),
634
- insertedIds: result.rows.map((d) => d._id)
635
- },
636
- { operationName: "insertMany", collectionName, serializer, errors }
637
- );
638
- },
639
- updateOne: async (filter, update, options) => {
640
- await ensureCollectionCreated(options);
641
- const result = await command(
642
- SqlFor.updateOne(filter, update, options),
643
- options
644
- );
645
- return operationResult(
646
- {
647
- successful: result.rows.length > 0 && result.rows[0].modified === result.rows[0].matched,
648
- modifiedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _27 => _27.rows, 'access', _28 => _28[0], 'optionalAccess', _29 => _29.modified]), () => ( 0))),
649
- matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _30 => _30.rows, 'access', _31 => _31[0], 'optionalAccess', _32 => _32.matched]), () => ( 0))),
650
- nextExpectedVersion: BigInt(_nullishCoalesce(_optionalChain([result, 'access', _33 => _33.rows, 'access', _34 => _34[0], 'optionalAccess', _35 => _35.version]), () => ( 0n)))
651
- },
652
- { operationName: "updateOne", collectionName, serializer, errors }
653
- );
654
- },
655
- replaceOne: async (filter, document, options) => {
656
- await ensureCollectionCreated(options);
657
- const downcasted = downcast(document);
658
- const result = await command(
659
- SqlFor.replaceOne(filter, downcasted, options),
660
- options
661
- );
662
- return operationResult(
663
- {
664
- successful: result.rows.length > 0 && result.rows[0].modified > 0,
665
- modifiedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _36 => _36.rows, 'access', _37 => _37[0], 'optionalAccess', _38 => _38.modified]), () => ( 0))),
666
- matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _39 => _39.rows, 'access', _40 => _40[0], 'optionalAccess', _41 => _41.matched]), () => ( 0))),
667
- nextExpectedVersion: BigInt(_nullishCoalesce(_optionalChain([result, 'access', _42 => _42.rows, 'access', _43 => _43[0], 'optionalAccess', _44 => _44.version]), () => ( 0n)))
668
- },
669
- { operationName: "replaceOne", collectionName, serializer, errors }
670
- );
671
- },
672
- updateMany: async (filter, update, options) => {
673
- await ensureCollectionCreated(options);
674
- const result = await command(SqlFor.updateMany(filter, update), options);
675
- return operationResult(
676
- {
677
- successful: true,
678
- modifiedCount: _nullishCoalesce(result.rowCount, () => ( 0)),
679
- matchedCount: _nullishCoalesce(result.rowCount, () => ( 0))
680
- },
681
- { operationName: "updateMany", collectionName, serializer, errors }
682
- );
683
- },
684
- deleteOne: async (filter, options) => {
685
- await ensureCollectionCreated(options);
686
- const result = await command(
687
- SqlFor.deleteOne(_nullishCoalesce(filter, () => ( {})), options),
688
- options
689
- );
690
- return operationResult(
691
- {
692
- successful: result.rows.length > 0 && result.rows[0].deleted > 0,
693
- deletedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _45 => _45.rows, 'access', _46 => _46[0], 'optionalAccess', _47 => _47.deleted]), () => ( 0))),
694
- matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _48 => _48.rows, 'access', _49 => _49[0], 'optionalAccess', _50 => _50.matched]), () => ( 0)))
695
- },
696
- { operationName: "deleteOne", collectionName, serializer, errors }
697
- );
698
- },
699
- deleteMany: async (filter, options) => {
700
- await ensureCollectionCreated(options);
701
- const result = await command(SqlFor.deleteMany(_nullishCoalesce(filter, () => ( {}))), options);
702
- return operationResult(
703
- {
704
- successful: (_nullishCoalesce(result.rowCount, () => ( 0))) > 0,
705
- deletedCount: _nullishCoalesce(result.rowCount, () => ( 0)),
706
- matchedCount: _nullishCoalesce(result.rowCount, () => ( 0))
707
- },
708
- { operationName: "deleteMany", collectionName, serializer, errors }
709
- );
710
- },
711
- findOne: async (filter, options) => {
712
- await ensureCollectionCreated(options);
713
- const result = await query(
714
- SqlFor.findOne(_nullishCoalesce(filter, () => ( {}))),
715
- options
716
- );
717
- const row = result.rows[0];
718
- if (row === void 0 || row === null) return null;
719
- return upcast({
720
- ...row.data,
721
- _version: row._version
722
- });
723
- },
724
- findOneAndDelete: async (filter, options) => {
725
- await ensureCollectionCreated(options);
726
- const existingDoc = await collection.findOne(filter, options);
727
- if (existingDoc === null) return null;
728
- await collection.deleteOne(filter, options);
729
- return existingDoc;
730
- },
731
- findOneAndReplace: async (filter, replacement, options) => {
732
- await ensureCollectionCreated(options);
733
- const existingDoc = await collection.findOne(filter, options);
734
- if (existingDoc === null) return null;
735
- await collection.replaceOne(filter, replacement, options);
736
- return existingDoc;
737
- },
738
- findOneAndUpdate: async (filter, update, options) => {
739
- await ensureCollectionCreated(options);
740
- const existingDoc = await collection.findOne(filter, options);
741
- if (existingDoc === null) return null;
742
- await collection.updateOne(filter, update, options);
743
- return existingDoc;
744
- },
745
- handle: async (id, handle, options) => {
746
- const { expectedVersion: version, ...operationOptions } = _nullishCoalesce(options, () => ( {}));
747
- await ensureCollectionCreated(options);
748
- const byId = { _id: id };
749
- const existing = await collection.findOne(
750
- byId,
751
- options
752
- );
753
- const expectedVersion2 = expectedVersionValue(version);
754
- if (existing == null && version === "DOCUMENT_EXISTS" || existing == null && expectedVersion2 != null || existing != null && version === "DOCUMENT_DOES_NOT_EXIST" || existing != null && expectedVersion2 !== null && existing._version !== expectedVersion2) {
755
- return operationResult(
756
- {
757
- successful: false,
758
- document: existing
759
- },
760
- { operationName: "handle", collectionName, serializer, errors }
761
- );
762
- }
763
- const result = await handle(
764
- existing !== null ? { ...existing } : null
765
- );
766
- if (deepEquals(existing, result))
767
- return operationResult(
768
- {
769
- successful: true,
770
- document: existing
771
- },
772
- { operationName: "handle", collectionName, serializer, errors }
773
- );
774
- if (!existing && result) {
775
- const newDoc = { ...result, _id: id };
776
- const insertResult = await collection.insertOne(
777
- { ...newDoc, _id: id },
778
- {
779
- ...operationOptions,
780
- expectedVersion: "DOCUMENT_DOES_NOT_EXIST"
781
- }
782
- );
783
- return {
784
- ...insertResult,
785
- document: {
786
- ...newDoc,
787
- _version: insertResult.nextExpectedVersion
788
- }
789
- };
790
- }
791
- if (existing && !result) {
792
- const deleteResult = await collection.deleteOne(byId, {
793
- ...operationOptions,
794
- expectedVersion: _nullishCoalesce(expectedVersion2, () => ( "DOCUMENT_EXISTS"))
795
- });
796
- return { ...deleteResult, document: null };
797
- }
798
- if (existing && result) {
799
- const replaceResult = await collection.replaceOne(byId, result, {
800
- ...operationOptions,
801
- expectedVersion: _nullishCoalesce(expectedVersion2, () => ( "DOCUMENT_EXISTS"))
802
- });
803
- return {
804
- ...replaceResult,
805
- document: {
806
- ...result,
807
- _version: replaceResult.nextExpectedVersion
808
- }
809
- };
810
- }
811
- return operationResult(
812
- {
813
- successful: true,
814
- document: existing
815
- },
816
- { operationName: "handle", collectionName, serializer, errors }
817
- );
818
- },
819
- find: async (filter, options) => {
820
- await ensureCollectionCreated(options);
821
- const result = await query(
822
- SqlFor.find(_nullishCoalesce(filter, () => ( {})), options)
823
- );
824
- return result.rows.map(
825
- (row) => upcast({
826
- ...row.data,
827
- _version: row._version
828
- })
829
- );
830
- },
831
- countDocuments: async (filter, options) => {
832
- await ensureCollectionCreated(options);
833
- const { count } = await _dumbo.single.call(void 0,
834
- query(SqlFor.countDocuments(_nullishCoalesce(filter, () => ( {}))))
835
- );
836
- return count;
837
- },
838
- drop: async (options) => {
839
- await ensureCollectionCreated(options);
840
- const result = await command(SqlFor.drop());
841
- return (_nullishCoalesce(_optionalChain([result, 'optionalAccess', _51 => _51.rowCount]), () => ( 0))) > 0;
842
- },
843
- rename: async (newName, options) => {
844
- await ensureCollectionCreated(options);
845
- await command(SqlFor.rename(newName));
846
- collectionName = newName;
847
- return collection;
848
- },
849
- sql: {
850
- async query(sql, options) {
851
- await ensureCollectionCreated(options);
852
- const result = await query(sql, options);
853
- return result.rows;
854
- },
855
- async command(sql, options) {
856
- await ensureCollectionCreated(options);
857
- return command(sql, options);
858
- }
859
- },
860
- schema: {
861
- component: schemaComponent3,
862
- migrate: (options) => _dumbo.runSQLMigrations.call(void 0, pool, schemaComponent3.migrations, options)
863
- }
864
- };
865
- return collection;
866
- };
867
-
868
-
869
-
870
-
871
-
872
-
873
-
874
-
875
-
876
-
877
-
878
-
879
-
880
-
881
-
882
-
883
-
884
-
885
-
886
-
887
-
888
-
889
-
890
-
891
-
892
-
893
-
894
-
895
-
896
-
897
-
898
-
899
-
900
-
901
-
902
-
903
-
904
- exports.transactionExecutorOrDefault = transactionExecutorOrDefault; exports.pongoCollection = pongoCollection; exports.PongoCollectionSchemaComponent = PongoCollectionSchemaComponent; exports.QueryOperators = QueryOperators; exports.OperatorMap = OperatorMap; exports.isOperator = isOperator; exports.hasOperators = hasOperators; exports.PongoDatabaseCache = PongoDatabaseCache; exports.objectEntries = objectEntries; exports.isNumber = isNumber; exports.isString = isString; exports.PongoError = PongoError; exports.ConcurrencyError = ConcurrencyError; exports.ObjectId = ObjectId; exports.DOCUMENT_EXISTS = DOCUMENT_EXISTS; exports.DOCUMENT_DOES_NOT_EXIST = DOCUMENT_DOES_NOT_EXIST; exports.NO_CONCURRENCY_CHECK = NO_CONCURRENCY_CHECK; exports.isGeneralExpectedDocumentVersion = isGeneralExpectedDocumentVersion; exports.expectedVersionValue = expectedVersionValue; exports.expectedVersion = expectedVersion; exports.operationResult = operationResult; exports.pongoSchema = pongoSchema; exports.proxyPongoDbWithSchema = proxyPongoDbWithSchema; exports.proxyClientWithSchema = proxyClientWithSchema; exports.toDbSchemaMetadata = toDbSchemaMetadata; exports.toClientSchemaMetadata = toClientSchemaMetadata; exports.PongoDatabaseSchemaComponent = PongoDatabaseSchemaComponent; exports.PongoDatabase = PongoDatabase; exports.PongoDriverRegistry = PongoDriverRegistry; exports.pongoDriverRegistry = pongoDriverRegistry; exports.pongoTransaction = pongoTransaction; exports.pongoSession = pongoSession; exports.pongoClient = pongoClient; exports.deepEquals = deepEquals; exports.isEquatable = isEquatable;
905
- //# sourceMappingURL=chunk-BZRKCNRY.cjs.map