@event-driven-io/pongo 0.16.7 → 0.16.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-D5HFWGFR.js → chunk-2YS3A7WH.js} +21 -13
- package/dist/chunk-2YS3A7WH.js.map +1 -0
- package/dist/{chunk-AH4TCORK.cjs → chunk-NA3ELYRR.cjs} +44 -36
- package/dist/chunk-NA3ELYRR.cjs.map +1 -0
- package/dist/cli.cjs +12 -12
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +8 -5
- package/dist/index.d.ts +8 -5
- package/dist/index.js +1 -1
- package/dist/{pongoClient-CF1GiWGx.d.cts → pongoClient-CML2ZSy3.d.cts} +13 -2
- package/dist/{pongoClient-CF1GiWGx.d.ts → pongoClient-CML2ZSy3.d.ts} +13 -2
- package/dist/shim.cjs +8 -6
- package/dist/shim.cjs.map +1 -1
- package/dist/shim.d.cts +33 -33
- package/dist/shim.d.ts +33 -33
- package/dist/shim.js +5 -3
- package/dist/shim.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-AH4TCORK.cjs.map +0 -1
- package/dist/chunk-D5HFWGFR.js.map +0 -1
|
@@ -42,13 +42,13 @@ var postgresDb = (options) => {
|
|
|
42
42
|
connect: () => Promise.resolve(),
|
|
43
43
|
close: () => pool.close(),
|
|
44
44
|
collections: () => [...collections.values()],
|
|
45
|
-
collection: (collectionName) => pongoCollection({
|
|
45
|
+
collection: (collectionName, collectionOptions) => pongoCollection({
|
|
46
46
|
collectionName,
|
|
47
47
|
db,
|
|
48
48
|
pool,
|
|
49
49
|
sqlBuilder: postgresSQLBuilder(collectionName),
|
|
50
|
-
schema: options.schema
|
|
51
|
-
errors: options.errors
|
|
50
|
+
schema: { ...options.schema, ...collectionOptions?.schema },
|
|
51
|
+
errors: { ...options.errors, ...collectionOptions?.errors }
|
|
52
52
|
}),
|
|
53
53
|
transaction: () => pool.transaction(),
|
|
54
54
|
withTransaction: (handle) => pool.withTransaction(handle),
|
|
@@ -129,7 +129,8 @@ var pongoCollection = ({
|
|
|
129
129
|
}
|
|
130
130
|
return createCollection2(options);
|
|
131
131
|
};
|
|
132
|
-
const upcast = schema?.upcast ?? ((doc) => doc);
|
|
132
|
+
const upcast = schema?.versioning?.upcast ?? ((doc) => doc);
|
|
133
|
+
const downcast = schema?.versioning?.downcast ?? ((doc) => doc);
|
|
133
134
|
const collection = {
|
|
134
135
|
dbName: db.databaseName,
|
|
135
136
|
collectionName,
|
|
@@ -140,9 +141,10 @@ var pongoCollection = ({
|
|
|
140
141
|
await ensureCollectionCreated(options);
|
|
141
142
|
const _id = document._id ?? uuid();
|
|
142
143
|
const _version = document._version ?? 1n;
|
|
144
|
+
const downcasted = downcast(document);
|
|
143
145
|
const result = await command(
|
|
144
146
|
SqlFor.insertOne({
|
|
145
|
-
...
|
|
147
|
+
...downcasted,
|
|
146
148
|
_id,
|
|
147
149
|
_version
|
|
148
150
|
}),
|
|
@@ -160,13 +162,18 @@ var pongoCollection = ({
|
|
|
160
162
|
},
|
|
161
163
|
insertMany: async (documents, options) => {
|
|
162
164
|
await ensureCollectionCreated(options);
|
|
163
|
-
const rows = documents.map((doc) =>
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
165
|
+
const rows = documents.map((doc) => {
|
|
166
|
+
const downcasted = downcast(doc);
|
|
167
|
+
return {
|
|
168
|
+
...downcasted,
|
|
169
|
+
_id: doc._id ?? uuid(),
|
|
170
|
+
_version: doc._version ?? 1n
|
|
171
|
+
};
|
|
172
|
+
});
|
|
168
173
|
const result = await command(
|
|
169
|
-
SqlFor.insertMany(
|
|
174
|
+
SqlFor.insertMany(
|
|
175
|
+
rows
|
|
176
|
+
),
|
|
170
177
|
options
|
|
171
178
|
);
|
|
172
179
|
return operationResult(
|
|
@@ -196,8 +203,9 @@ var pongoCollection = ({
|
|
|
196
203
|
},
|
|
197
204
|
replaceOne: async (filter, document, options) => {
|
|
198
205
|
await ensureCollectionCreated(options);
|
|
206
|
+
const downcasted = downcast(document);
|
|
199
207
|
const result = await command(
|
|
200
|
-
SqlFor.replaceOne(filter,
|
|
208
|
+
SqlFor.replaceOne(filter, downcasted, options),
|
|
201
209
|
options
|
|
202
210
|
);
|
|
203
211
|
return operationResult(
|
|
@@ -1177,4 +1185,4 @@ export {
|
|
|
1177
1185
|
deepEquals,
|
|
1178
1186
|
isEquatable
|
|
1179
1187
|
};
|
|
1180
|
-
//# sourceMappingURL=chunk-
|
|
1188
|
+
//# sourceMappingURL=chunk-2YS3A7WH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/errors/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts","../src/core/pongoTransaction.ts","../src/core/pongoSession.ts","../src/core/typing/entries.ts","../src/core/typing/operations.ts","../src/core/schema/index.ts","../src/core/utils/deepEquals.ts","../src/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/filter/index.ts","../src/postgres/sqlBuilder/update/index.ts"],"sourcesContent":["import {\n isSQL,\n JSONSerializer,\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\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 %I (\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 collectionName,\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 migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n return sql(\n 'INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;',\n collectionName,\n document._id,\n JSONSerializer.serialize(document),\n document._version ?? 1n,\n );\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = documents\n .map((doc) =>\n sql(\n '(%L, %L, %L)',\n doc._id,\n JSONSerializer.serialize(doc),\n doc._version ?? 1n,\n ),\n )\n .join(', ');\n return sql(\n `INSERT INTO %I (_id, data, _version) VALUES %s \n ON CONFLICT(_id) DO NOTHING\n RETURNING _id;`,\n collectionName,\n values,\n );\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 ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\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 %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %s || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._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 collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\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 ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\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 %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %L || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._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 collectionName,\n where(filterQuery),\n collectionName,\n JSONSerializer.serialize(document),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\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 %I \n SET \n data = %s || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n %s;`,\n collectionName,\n updateQuery,\n where(filterQuery),\n );\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 ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id\n FROM %I %s \n LIMIT 1\n ),\n deleted AS (\n DELETE FROM %I\n USING existing\n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._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 collectionName,\n where(filterQuery),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n );\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n 'SELECT data, _version FROM %I %s LIMIT 1;',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql(\n 'SELECT data, _version FROM %I %s;',\n collectionName,\n where(filterQuery),\n );\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s;',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I;', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v7 as uuid } from 'uuid';\nimport {\n deepEquals,\n expectedVersionValue,\n operationResult,\n type CollectionOperationOptions,\n type DeleteManyOptions,\n type DeleteOneOptions,\n type DocumentHandler,\n type HandleOptions,\n type InsertManyOptions,\n type InsertOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoHandleResult,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateManyResult,\n type PongoUpdateResult,\n type ReplaceOneOptions,\n type UpdateManyOptions,\n type UpdateOneOptions,\n type WithIdAndVersion,\n type WithoutId,\n type WithVersion,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<\n T extends PongoDocument = PongoDocument,\n ConnectorType extends string = string,\n Payload extends PongoDocument = T,\n> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: {\n autoMigration?: MigrationStyle;\n versioning?: {\n upcast?: (doc: Payload) => T;\n downcast?: (doc: T) => Payload;\n };\n };\n errors?: { throwOnOperationFailures?: boolean };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nexport const transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n Payload extends PongoDocument = T,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n errors,\n}: PongoCollectionOptions<T, ConnectorType, Payload>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, sqlExecutor)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const upcast =\n schema?.versioning?.upcast ?? ((doc: Payload) => doc as unknown as T);\n\n const downcast =\n schema?.versioning?.downcast ?? ((doc: T) => doc as unknown as Payload);\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredIdAndVersion<T>,\n options?: InsertOneOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n const _version = document._version ?? 1n;\n const downcasted = downcast(document as T);\n\n const result = await command(\n SqlFor.insertOne({\n ...downcasted,\n _id,\n _version,\n } as unknown as OptionalUnlessRequiredIdAndVersion<Payload>),\n options,\n );\n\n const successful = (result.rowCount ?? 0) > 0;\n\n return operationResult<PongoInsertOneResult>(\n {\n successful,\n insertedId: successful ? _id : null,\n nextExpectedVersion: _version,\n },\n { operationName: 'insertOne', collectionName, errors },\n );\n },\n insertMany: async (\n documents: OptionalUnlessRequiredIdAndVersion<T>[],\n options?: InsertManyOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => {\n const downcasted = downcast(doc as T);\n return {\n ...downcasted,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n _version: doc._version ?? 1n,\n };\n });\n\n const result = await command(\n SqlFor.insertMany(\n rows as unknown as OptionalUnlessRequiredIdAndVersion<Payload>[],\n ),\n options,\n );\n\n return operationResult<PongoInsertManyResult>(\n {\n successful: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: result.rows.map((d) => d._id as string),\n },\n { operationName: 'insertMany', collectionName, errors },\n );\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.updateOne(filter, update, options),\n options,\n );\n\n return operationResult<PongoUpdateResult>(\n {\n successful:\n result.rows.length > 0 &&\n result.rows[0]!.modified === result.rows[0]!.matched,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'updateOne', collectionName, errors },\n );\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const downcasted = downcast(document as T) as unknown as WithoutId<T>;\n\n const result = await command<UpdateSqlResult>(\n SqlFor.replaceOne(filter, downcasted, options),\n options,\n );\n return operationResult<PongoUpdateResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.modified > 0,\n modifiedCount: Number(result.rows[0]?.modified ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n nextExpectedVersion: result.rows[0]?.version ?? 0n,\n },\n { operationName: 'replaceOne', collectionName, errors },\n );\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateManyOptions,\n ): Promise<PongoUpdateManyResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n\n return operationResult<PongoUpdateManyResult>(\n {\n successful: true,\n modifiedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'updateMany', collectionName, errors },\n );\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<DeleteSqlResult>(\n SqlFor.deleteOne(filter ?? {}, options),\n options,\n );\n return operationResult<PongoDeleteResult>(\n {\n successful: result.rows.length > 0 && result.rows[0]!.deleted! > 0,\n deletedCount: Number(result.rows[0]?.deleted ?? 0),\n matchedCount: Number(result.rows[0]?.matched ?? 0),\n },\n { operationName: 'deleteOne', collectionName, errors },\n );\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: DeleteManyOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n\n return operationResult<PongoDeleteResult>(\n {\n successful: (result.rowCount ?? 0) > 0,\n deletedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'deleteMany', collectionName, errors },\n );\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query<{ data: T; _version: bigint }>(\n SqlFor.findOne(filter ?? {}),\n options,\n );\n\n const row = result.rows[0];\n if (row === undefined || row === null) return null;\n\n return upcast({\n ...row.data,\n _version: row._version,\n } as unknown as Payload) as WithIdAndVersion<T>;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: HandleOptions,\n ): Promise<PongoHandleResult<T>> => {\n const { expectedVersion: version, ...operationOptions } = options ?? {};\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = (await collection.findOne(\n byId,\n options,\n )) as WithVersion<T> | null;\n\n const expectedVersion = expectedVersionValue(version);\n\n if (\n (existing == null && version === 'DOCUMENT_EXISTS') ||\n (existing == null && expectedVersion != null) ||\n (existing != null && version === 'DOCUMENT_DOES_NOT_EXIST') ||\n (existing != null &&\n expectedVersion !== null &&\n existing._version !== expectedVersion)\n ) {\n return operationResult<PongoHandleResult<T>>(\n {\n successful: false,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n }\n\n const result = await handle(\n existing !== null ? ({ ...existing } as T) : null,\n );\n\n if (deepEquals(existing as T | null, result))\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T | null,\n },\n { operationName: 'handle', collectionName, errors },\n );\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n const insertResult = await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredIdAndVersion<T>,\n {\n ...operationOptions,\n expectedVersion: 'DOCUMENT_DOES_NOT_EXIST',\n },\n );\n return {\n ...insertResult,\n document: {\n ...newDoc,\n _version: insertResult.nextExpectedVersion,\n } as T,\n };\n }\n\n if (existing && !result) {\n const deleteResult = await collection.deleteOne(byId, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return { ...deleteResult, document: null };\n }\n\n if (existing && result) {\n const replaceResult = await collection.replaceOne(byId, result, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return {\n ...replaceResult,\n document: {\n ...result,\n _version: replaceResult.nextExpectedVersion,\n } as T,\n };\n }\n\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T>[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query<{ data: T; _version: bigint }>(\n SqlFor.find(filter ?? {}),\n );\n return result.rows.map(\n (row) =>\n upcast({\n ...row.data,\n _version: row._version,\n } as unknown as Payload) as WithIdAndVersion<T>,\n );\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n await ensureCollectionCreated(options);\n\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n await ensureCollectionCreated(options);\n\n return command(sql, options);\n },\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]) => SQL;\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ) => SQL;\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ) => SQL;\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ) => SQL;\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ) => SQL;\n deleteMany: <T>(filter: PongoFilter<T> | SQL) => SQL;\n findOne: <T>(filter: PongoFilter<T> | SQL) => SQL;\n find: <T>(filter: PongoFilter<T> | SQL) => SQL;\n countDocuments: <T>(filter: PongoFilter<T> | SQL) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n\ntype UpdateSqlResult = {\n matched: bigint;\n modified: bigint;\n version: bigint;\n};\n\ntype DeleteSqlResult = {\n matched: bigint | null;\n deleted: bigint | null;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n SQL,\n type PostgresConnector,\n type PostgresPoolOptions,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n transactionExecutorOrDefault,\n type CollectionOperationOptions,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, pool.execute)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, pool.execute)).query<T>(\n sql,\n );\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n\n collections: () => [...collections.values()],\n collection: (collectionName, collectionOptions) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n schema: { ...options.schema, ...collectionOptions?.schema },\n errors: { ...options.errors, ...collectionOptions?.errors },\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n const result = await query<Result>(sql, options);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n return command(sql, options);\n },\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","export const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport class PongoError extends Error {\n public errorCode: number;\n\n constructor(\n options?: { errorCode: number; message?: string } | string | number,\n ) {\n const errorCode =\n options && typeof options === 'object' && 'errorCode' in options\n ? options.errorCode\n : isNumber(options)\n ? options\n : 500;\n const message =\n options && typeof options === 'object' && 'message' in options\n ? options.message\n : isString(options)\n ? options\n : `Error with status code '${errorCode}' ocurred during Pongo processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, PongoError.prototype);\n }\n}\n\nexport class ConcurrencyError extends PongoError {\n constructor(message?: string) {\n super({\n errorCode: 412,\n message: message ?? `Expected document state does not match current one!`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\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\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n errors?: { throwOnOperationFailures?: boolean };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n","import type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n","import { pongoTransaction } from './pongoTransaction';\nimport type {\n PongoDbTransaction,\n PongoSession,\n PongoTransactionOptions,\n} from './typing';\n\nexport type PongoSessionOptions = {\n explicit?: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n};\n\nconst isActive = (\n transaction: PongoDbTransaction | null,\n): transaction is PongoDbTransaction => transaction?.isActive === true;\n\nfunction assertInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is PongoDbTransaction {\n if (!isActive(transaction)) throw new Error('No active transaction exists!');\n}\n\nfunction assertNotInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is null {\n if (isActive(transaction))\n throw new Error('Active transaction already exists!');\n}\n\nexport const pongoSession = (options?: PongoSessionOptions): PongoSession => {\n const explicit = options?.explicit === true;\n const defaultTransactionOptions: PongoTransactionOptions =\n options?.defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n };\n\n let transaction: PongoDbTransaction | null = null;\n let hasEnded = false;\n\n const startTransaction = (options?: PongoTransactionOptions) => {\n assertNotInActiveTransaction(transaction);\n\n transaction = pongoTransaction(options ?? defaultTransactionOptions);\n };\n const commitTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.commit();\n };\n const abortTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.rollback();\n };\n\n const endSession = async (): Promise<void> => {\n if (hasEnded) return;\n hasEnded = true;\n\n if (isActive(transaction)) await transaction.rollback();\n };\n\n const session = {\n get hasEnded() {\n return hasEnded;\n },\n explicit,\n defaultTransactionOptions: defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n },\n get transaction() {\n return transaction;\n },\n get snapshotEnabled() {\n return defaultTransactionOptions.snapshotEnabled;\n },\n endSession,\n incrementTransactionNumber: () => {},\n inTransaction: () => isActive(transaction),\n startTransaction,\n commitTransaction,\n abortTransaction,\n withTransaction: async <T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T> => {\n startTransaction(options);\n\n try {\n const result = await fn(session);\n await commitTransaction();\n return result;\n } catch (error) {\n await abortTransaction();\n throw error;\n }\n },\n };\n\n return session;\n};\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const objectEntries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import {\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n JSONSerializer,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n} from '@event-driven-io/dumbo';\nimport { v7 as uuid } from 'uuid';\nimport { ConcurrencyError } from '../errors';\n\nexport interface PongoClient {\n connect(): Promise<this>;\n\n close(): Promise<void>;\n\n db(dbName?: string): PongoDb;\n\n startSession(): PongoSession;\n\n withSession<T = unknown>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T>;\n}\n\nexport declare interface PongoTransactionOptions {\n get snapshotEnabled(): boolean;\n maxCommitTimeMS?: number;\n}\n\nexport interface PongoDbTransaction {\n get databaseName(): string | null;\n options: PongoTransactionOptions;\n enlistDatabase: (database: PongoDb) => Promise<DatabaseTransaction>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n get sqlExecutor(): SQLExecutor;\n get isStarting(): boolean;\n get isActive(): boolean;\n get isCommitted(): boolean;\n}\n\nexport interface PongoSession {\n hasEnded: boolean;\n explicit: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n transaction: PongoDbTransaction | null;\n get snapshotEnabled(): boolean;\n\n endSession(): Promise<void>;\n incrementTransactionNumber(): void;\n inTransaction(): boolean;\n startTransaction(options?: PongoTransactionOptions): void;\n commitTransaction(): Promise<void>;\n abortTransaction(): Promise<void>;\n withTransaction<T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T>;\n}\n\nexport type PongoDBCollectionOptions<\n T extends PongoDocument,\n Payload extends PongoDocument = T,\n> = {\n schema?: {\n versioning?: {\n upcast?: (document: Payload) => T;\n downcast?: (document: T) => Payload;\n };\n };\n errors?: { throwOnOperationFailures?: boolean };\n};\n\nexport interface PongoDb<ConnectorType extends string = string>\n extends DatabaseTransactionFactory<ConnectorType> {\n get connectorType(): ConnectorType;\n get databaseName(): string;\n connect(): Promise<void>;\n close(): Promise<void>;\n collection<T extends PongoDocument, Payload extends PongoDocument = T>(\n name: string,\n options?: PongoDBCollectionOptions<T, Payload>,\n ): PongoCollection<T>;\n collections(): ReadonlyArray<PongoCollection<PongoDocument>>;\n readonly schema: Readonly<{\n component: SchemaComponent;\n migrate(): Promise<void>;\n }>;\n sql: {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>>;\n };\n}\n\nexport type CollectionOperationOptions = {\n session?: PongoSession;\n};\n\nexport type InsertOneOptions = {\n expectedVersion?: Extract<\n ExpectedDocumentVersion,\n 'DOCUMENT_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK'\n >;\n} & CollectionOperationOptions;\n\nexport type InsertManyOptions = {\n expectedVersion?: Extract<\n ExpectedDocumentVersion,\n 'DOCUMENT_DOES_NOT_EXIST' | 'NO_CONCURRENCY_CHECK'\n >;\n} & CollectionOperationOptions;\n\nexport type UpdateOneOptions = {\n expectedVersion?: Exclude<ExpectedDocumentVersion, 'DOCUMENT_DOES_NOT_EXIST'>;\n} & CollectionOperationOptions;\n\nexport type UpdateManyOptions = {\n expectedVersion?: Extract<\n ExpectedDocumentVersion,\n 'DOCUMENT_EXISTS' | 'NO_CONCURRENCY_CHECK'\n >;\n} & CollectionOperationOptions;\n\nexport type HandleOptions = {\n expectedVersion?: ExpectedDocumentVersion;\n} & CollectionOperationOptions;\n\nexport type ReplaceOneOptions = {\n expectedVersion?: Exclude<ExpectedDocumentVersion, 'DOCUMENT_DOES_NOT_EXIST'>;\n} & CollectionOperationOptions;\n\nexport type DeleteOneOptions = {\n expectedVersion?: Exclude<ExpectedDocumentVersion, 'DOCUMENT_DOES_NOT_EXIST'>;\n} & CollectionOperationOptions;\n\nexport type DeleteManyOptions = {\n expectedVersion?: Extract<\n ExpectedDocumentVersion,\n 'DOCUMENT_EXISTS' | 'NO_CONCURRENCY_CHECK'\n >;\n} & CollectionOperationOptions;\n\nexport interface PongoCollection<T extends PongoDocument> {\n readonly dbName: string;\n readonly collectionName: string;\n createCollection(options?: CollectionOperationOptions): Promise<void>;\n insertOne(\n document: OptionalUnlessRequiredId<T>,\n options?: InsertOneOptions,\n ): Promise<PongoInsertOneResult>;\n insertMany(\n documents: OptionalUnlessRequiredId<T>[],\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertManyResult>;\n updateOne(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): Promise<PongoUpdateResult>;\n replaceOne(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<PongoUpdateResult>;\n updateMany(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateManyOptions,\n ): Promise<PongoUpdateManyResult>;\n deleteOne(\n filter?: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): Promise<PongoDeleteResult>;\n deleteMany(\n filter?: PongoFilter<T> | SQL,\n options?: DeleteManyOptions,\n ): Promise<PongoDeleteResult>;\n findOne(\n filter?: PongoFilter<T> | SQL,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T> | null>;\n find(\n filter?: PongoFilter<T> | SQL,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T>[]>;\n findOneAndDelete(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): Promise<WithIdAndVersion<T> | null>;\n findOneAndReplace(\n filter: PongoFilter<T> | SQL,\n replacement: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<WithIdAndVersion<T> | null>;\n findOneAndUpdate(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): Promise<WithIdAndVersion<T> | null>;\n countDocuments(\n filter?: PongoFilter<T> | SQL,\n options?: CollectionOperationOptions,\n ): Promise<number>;\n drop(options?: CollectionOperationOptions): Promise<boolean>;\n rename(\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>>;\n handle(\n id: string,\n handle: DocumentHandler<T>,\n options?: HandleOptions,\n ): Promise<PongoHandleResult<T>>;\n readonly schema: Readonly<{\n component: SchemaComponent;\n migrate(): Promise<void>;\n }>;\n sql: {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>>;\n };\n}\n\nexport type ObjectId = string & { __brandId: 'ObjectId' };\nexport const ObjectId = (value?: string) => value ?? uuid();\n\nexport type HasId = { _id: string };\n\nexport declare type InferIdType<TSchema> = TSchema extends {\n _id: infer IdType;\n}\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Record<any, never> extends IdType\n ? never\n : IdType\n : TSchema extends {\n _id?: infer IdType;\n }\n ? unknown extends IdType\n ? ObjectId\n : IdType\n : ObjectId;\n\n/** TypeScript Omit (Exclude to be specific) does not work for objects with an \"any\" indexed type, and breaks discriminated unions @public */\nexport declare type EnhancedOmit<TRecordOrUnion, KeyUnion> =\n string extends keyof TRecordOrUnion\n ? TRecordOrUnion\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TRecordOrUnion extends any\n ? Pick<TRecordOrUnion, Exclude<keyof TRecordOrUnion, KeyUnion>>\n : never;\n\nexport declare type OptionalUnlessRequiredId<TSchema> = TSchema extends {\n _id: string | ObjectId;\n}\n ? TSchema\n : OptionalId<TSchema>;\n\nexport declare type OptionalUnlessRequiredVersion<TSchema> = TSchema extends {\n _version: bigint;\n}\n ? TSchema\n : OptionalVersion<TSchema>;\n\nexport declare type OptionalUnlessRequiredIdAndVersion<TSchema> =\n OptionalUnlessRequiredId<TSchema> & OptionalUnlessRequiredVersion<TSchema>;\n\nexport declare type WithId<TSchema> = EnhancedOmit<TSchema, '_id'> & {\n _id: string | ObjectId;\n};\nexport type WithoutId<T> = Omit<T, '_id'>;\n\nexport declare type WithVersion<TSchema> = EnhancedOmit<TSchema, '_version'> & {\n _version: bigint;\n};\nexport type WithoutVersion<T> = Omit<T, '_version'>;\n\nexport type WithIdAndVersion<T> = WithId<WithVersion<T>>;\nexport type WithoutIdAndVersion<T> = WithoutId<WithoutVersion<T>>;\n\n/** @public */\nexport declare type RegExpOrString<T> = T extends string ? RegExp | T : T;\n\nexport declare interface Document {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\n\nexport declare type OptionalId<TSchema> = EnhancedOmit<TSchema, '_id'> & {\n _id?: string | ObjectId;\n};\nexport declare type OptionalVersion<TSchema> = EnhancedOmit<\n TSchema,\n '_version'\n> & {\n _version?: bigint;\n};\n\nexport declare interface ObjectIdLike {\n __id?: string | ObjectId;\n}\n\nexport declare type NonObjectIdLikeDocument = {\n [key in keyof ObjectIdLike]?: never;\n} & Document;\n\nexport declare type AlternativeType<T> =\n T extends ReadonlyArray<infer U> ? T | RegExpOrString<U> : RegExpOrString<T>;\n\nexport declare type Condition<T> =\n | AlternativeType<T>\n | PongoFilterOperator<AlternativeType<T>>;\n\nexport declare type PongoFilter<TSchema> =\n | {\n [P in keyof WithId<TSchema>]?: Condition<WithId<TSchema>[P]>;\n }\n | HasId; // TODO: & RootFilterOperators<WithId<TSchema>>;\n\nexport declare interface RootFilterOperators<TSchema> extends Document {\n $and?: PongoFilter<TSchema>[];\n $nor?: PongoFilter<TSchema>[];\n $or?: PongoFilter<TSchema>[];\n $text?: {\n $search: string;\n $language?: string;\n $caseSensitive?: boolean;\n $diacriticSensitive?: boolean;\n };\n $where?: string | ((this: TSchema) => boolean);\n $comment?: string | Document;\n}\n\nexport declare interface PongoFilterOperator<TValue>\n extends NonObjectIdLikeDocument {\n $eq?: TValue;\n $gt?: TValue;\n $gte?: TValue;\n $lt?: TValue;\n $lte?: TValue;\n $ne?: TValue;\n $in?: TValue[];\n $nin?: TValue[];\n // $eq?: TValue;\n // $gt?: TValue;\n // $gte?: TValue;\n // $in?: ReadonlyArray<TValue>;\n // $lt?: TValue;\n // $lte?: TValue;\n // $ne?: TValue;\n // $nin?: ReadonlyArray<TValue>;\n // $not?: TValue extends string ? FilterOperators<TValue> | RegExp : FilterOperators<TValue>;\n // /**\n // * When `true`, `$exists` matches the documents that contain the field,\n // * including documents where the field value is null.\n // */\n // $exists?: boolean;\n // $type?: BSONType | BSONTypeAlias;\n // $expr?: Record<string, any>;\n // $jsonSchema?: Record<string, any>;\n // $mod?: TValue extends number ? [number, number] : never;\n // $regex?: TValue extends string ? RegExp | BSONRegExp | string : never;\n // $options?: TValue extends string ? string : never;\n // $geoIntersects?: {\n // $geometry: Document;\n // };\n // $geoWithin?: Document;\n // $near?: Document;\n // $nearSphere?: Document;\n // $maxDistance?: number;\n // $all?: ReadonlyArray<any>;\n // $elemMatch?: Document;\n // $size?: TValue extends ReadonlyArray<any> ? number : never;\n // $bitsAllClear?: BitwiseFilter;\n // $bitsAllSet?: BitwiseFilter;\n // $bitsAnyClear?: BitwiseFilter;\n // $bitsAnySet?: BitwiseFilter;\n // $rand?: Record<string, never>;\n}\n\nexport type $set<T> = Partial<T>;\nexport type $unset<T> = { [P in keyof T]?: '' };\nexport type $inc<T> = { [P in keyof T]?: number | bigint };\nexport type $push<T> = { [P in keyof T]?: T[P] };\n\nexport type ExpectedDocumentVersionGeneral =\n | 'DOCUMENT_EXISTS'\n | 'DOCUMENT_DOES_NOT_EXIST'\n | 'NO_CONCURRENCY_CHECK';\n\nexport type ExpectedDocumentVersionValue = bigint & { __brand: 'sql' };\n\nexport type ExpectedDocumentVersion =\n | (bigint & { __brand: 'sql' })\n | bigint\n | ExpectedDocumentVersionGeneral;\n\nexport const DOCUMENT_EXISTS =\n 'DOCUMENT_EXISTS' as ExpectedDocumentVersionGeneral;\nexport const DOCUMENT_DOES_NOT_EXIST =\n 'DOCUMENT_DOES_NOT_EXIST' as ExpectedDocumentVersionGeneral;\nexport const NO_CONCURRENCY_CHECK =\n 'NO_CONCURRENCY_CHECK' as ExpectedDocumentVersionGeneral;\n\nexport const isGeneralExpectedDocumentVersion = (\n version: ExpectedDocumentVersion,\n): version is ExpectedDocumentVersionGeneral =>\n version === 'DOCUMENT_DOES_NOT_EXIST' ||\n version === 'DOCUMENT_EXISTS' ||\n version === 'NO_CONCURRENCY_CHECK';\n\nexport const expectedVersionValue = (\n version: ExpectedDocumentVersion | undefined,\n): ExpectedDocumentVersionValue | null =>\n version === undefined || isGeneralExpectedDocumentVersion(version)\n ? null\n : (version as ExpectedDocumentVersionValue);\n\nexport const expectedVersion = (\n version: number | bigint | string | undefined | null,\n): ExpectedDocumentVersion => {\n return version\n ? (BigInt(version) as ExpectedDocumentVersion)\n : NO_CONCURRENCY_CHECK;\n};\n\nexport type PongoUpdate<T> = {\n $set?: Partial<T>;\n $unset?: $unset<T>;\n $inc?: $inc<T>;\n $push?: $push<T>;\n};\n\nexport type OperationResult = {\n acknowledged: boolean;\n successful: boolean;\n\n assertSuccessful: (errorMessage?: string) => void;\n};\n\nexport const operationResult = <T extends OperationResult>(\n result: Omit<T, 'assertSuccess' | 'acknowledged' | 'assertSuccessful'>,\n options: {\n operationName: string;\n collectionName: string;\n errors?: { throwOnOperationFailures?: boolean } | undefined;\n },\n): T => {\n const operationResult: T = {\n ...result,\n acknowledged: true,\n successful: result.successful,\n assertSuccessful: (errorMessage?: string) => {\n const { successful } = result;\n const { operationName, collectionName } = options;\n\n if (!successful)\n throw new ConcurrencyError(\n errorMessage ??\n `${operationName} on ${collectionName} failed. Expected document state does not match current one! Result: ${JSONSerializer.serialize(result)}!`,\n );\n },\n } as T;\n\n if (options.errors?.throwOnOperationFailures)\n operationResult.assertSuccessful();\n\n return operationResult;\n};\n\nexport interface PongoInsertOneResult extends OperationResult {\n insertedId: string | null;\n nextExpectedVersion: bigint;\n}\n\nexport interface PongoInsertManyResult extends OperationResult {\n insertedIds: string[];\n insertedCount: number;\n}\n\nexport interface PongoUpdateResult extends OperationResult {\n matchedCount: number;\n modifiedCount: number;\n nextExpectedVersion: bigint;\n}\n\nexport interface PongoUpdateManyResult extends OperationResult {\n matchedCount: number;\n modifiedCount: number;\n}\n\nexport interface PongoDeleteResult extends OperationResult {\n matchedCount: number;\n deletedCount: number;\n}\n\nexport interface PongoDeleteManyResult extends OperationResult {\n deletedCount: number;\n}\n\nexport type PongoHandleResult<T> =\n | (PongoInsertOneResult & { document: T })\n | (PongoUpdateResult & { document: T })\n | (PongoDeleteResult & { document: null })\n | (OperationResult & { document: null });\n\nexport type PongoDocument = Record<string, unknown>;\n\nexport type DocumentHandler<T extends PongoDocument> =\n | ((document: T | null) => T | null)\n | ((document: T | null) => Promise<T | null>);\n","import {\n type Document,\n type PongoClient,\n type PongoCollection,\n type PongoDb,\n type PongoDocument,\n objectEntries,\n} from '../typing';\n\nexport interface PongoCollectionSchema<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n T extends PongoDocument = PongoDocument,\n> {\n name: string;\n}\n\n// Database schema interface\nexport interface PongoDbSchema<\n T extends Record<string, PongoCollectionSchema> = Record<\n string,\n PongoCollectionSchema\n >,\n> {\n name?: string;\n collections: T;\n}\n\nexport interface PongoClientSchema<\n T extends Record<string, PongoDbSchema> = Record<string, PongoDbSchema>,\n> {\n dbs: T;\n}\n\nexport type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {\n [K in keyof T]: PongoCollection<\n T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument\n >;\n};\n\nexport type PongoDbWithSchema<\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n> = CollectionsMap<T> & PongoDb<ConnectorType>;\n\nexport type DBsMap<\n T extends Record<string, PongoDbSchema>,\n ConnectorType extends string = string,\n> = {\n [K in keyof T]: CollectionsMap<T[K]['collections']> & PongoDb<ConnectorType>;\n};\n\nexport type PongoClientWithSchema<\n T extends PongoClientSchema,\n ConnectorType extends string = string,\n> = DBsMap<T['dbs'], ConnectorType> & PongoClient;\n\nconst pongoCollectionSchema = <T extends PongoDocument>(\n name: string,\n): PongoCollectionSchema<T> => ({\n name,\n});\n\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n name: string,\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n nameOrCollections: string | T,\n collections?: T,\n): PongoDbSchema<T> {\n if (collections === undefined) {\n if (typeof nameOrCollections === 'string') {\n throw new Error('You need to provide colleciton definition');\n }\n return {\n collections: nameOrCollections,\n };\n }\n\n return nameOrCollections && typeof nameOrCollections === 'string'\n ? {\n name: nameOrCollections,\n collections,\n }\n : { collections: collections };\n}\n\nconst pongoClientSchema = <T extends Record<string, PongoDbSchema>>(\n dbs: T,\n): PongoClientSchema<T> => ({\n dbs,\n});\n\nexport const pongoSchema = {\n client: pongoClientSchema,\n db: pongoDbSchema,\n collection: pongoCollectionSchema,\n};\n\n// Factory function to create DB instances\nexport const proxyPongoDbWithSchema = <\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n>(\n pongoDb: PongoDb<ConnectorType>,\n dbSchema: PongoDbSchema<T>,\n collections: Map<string, PongoCollection<Document>>,\n): PongoDbWithSchema<T, ConnectorType> => {\n const collectionNames = Object.keys(dbSchema.collections);\n\n for (const collectionName of collectionNames) {\n collections.set(collectionName, pongoDb.collection(collectionName));\n }\n\n return new Proxy(\n pongoDb as PongoDb<ConnectorType> & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n return collections.get(prop) ?? target[prop];\n },\n },\n ) as PongoDbWithSchema<T, ConnectorType>;\n};\n\nexport const proxyClientWithSchema = <\n TypedClientSchema extends PongoClientSchema,\n>(\n client: PongoClient,\n schema: TypedClientSchema | undefined,\n): PongoClientWithSchema<TypedClientSchema> => {\n if (!schema) return client as PongoClientWithSchema<TypedClientSchema>;\n\n const dbNames = Object.keys(schema.dbs);\n\n return new Proxy(\n client as PongoClient & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n if (dbNames.includes(prop)) return client.db(schema.dbs[prop]?.name);\n\n return target[prop];\n },\n },\n ) as PongoClientWithSchema<TypedClientSchema>;\n};\n\nexport type PongoCollectionSchemaMetadata = {\n name: string;\n};\n\nexport type PongoDbSchemaMetadata = {\n name?: string | undefined;\n collections: PongoCollectionSchemaMetadata[];\n};\n\nexport type PongoClientSchemaMetadata = {\n databases: PongoDbSchemaMetadata[];\n database: (name?: string) => PongoDbSchemaMetadata | undefined;\n};\n\nexport const toDbSchemaMetadata = <TypedDbSchema extends PongoDbSchema>(\n schema: TypedDbSchema,\n): PongoDbSchemaMetadata => ({\n name: schema.name,\n collections: objectEntries(schema.collections).map((c) => ({\n name: c[1].name,\n })),\n});\n\nexport const toClientSchemaMetadata = <\n TypedClientSchema extends PongoClientSchema,\n>(\n schema: TypedClientSchema,\n): PongoClientSchemaMetadata => {\n const databases = objectEntries(schema.dbs).map((e) =>\n toDbSchemaMetadata(e[1]),\n );\n\n return {\n databases,\n database: (name) => databases.find((db) => db.name === name),\n };\n};\n\nexport interface PongoSchemaConfig<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> {\n schema: TypedClientSchema;\n}\n","export const deepEquals = <T>(left: T, right: T): boolean => {\n if (isEquatable(left)) {\n return left.equals(right);\n }\n\n if (Array.isArray(left)) {\n return (\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((val, index) => deepEquals(val, right[index]))\n );\n }\n\n if (\n typeof left !== 'object' ||\n typeof right !== 'object' ||\n left === null ||\n right === null\n ) {\n return left === right;\n }\n\n if (Array.isArray(right)) return false;\n\n const keys1 = Object.keys(left);\n const keys2 = Object.keys(right);\n\n if (\n keys1.length !== keys2.length ||\n !keys1.every((key) => keys2.includes(key))\n )\n return false;\n\n for (const key in left) {\n if (left[key] instanceof Function && right[key] instanceof Function)\n continue;\n\n const isEqual = deepEquals(left[key], right[key]);\n if (!isEqual) {\n return false;\n }\n }\n\n return true;\n};\n\nexport type Equatable<T> = { equals: (right: T) => boolean } & T;\n\nexport const isEquatable = <T>(left: T): left is Equatable<T> => {\n return (\n left &&\n typeof left === 'object' &&\n 'equals' in left &&\n typeof left['equals'] === 'function'\n );\n};\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): string => {\n if (path === '_id' || path === '_version') {\n return handleMetadataOperator(path, operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return sql(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSONSerializer.serialize(buildNestedObject(path, value)),\n path,\n JSONSerializer.serialize(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return sql(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = objectEntries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n sql(`@.\"%s\" == %s`, subKey, JSONSerializer.serialize(subValue)),\n )\n .join(' && ');\n return sql(`jsonb_path_exists(data, '$.%s[*] ? (%s)')`, path, subQuery);\n }\n case '$all':\n return sql(\n 'data @> %L::jsonb',\n JSONSerializer.serialize(buildNestedObject(path, value)),\n );\n case '$size':\n return sql(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n 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): string => {\n switch (operator) {\n case '$eq':\n return sql(`${fieldName} = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(`${fieldName} ${OperatorMap[operator]} %L`, value);\n case '$in':\n return sql(\n `${fieldName} IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n `${fieldName} NOT IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\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 {\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>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return objectEntries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { JSONSerializer, sql, type 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((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 }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, JSONSerializer.serialize(set));\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL =>\n sql(\n '%s - %L',\n currentUpdateQuery,\n Object.keys(unset)\n .map((k) => `{${k}}`)\n .join(', '),\n );\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 = sql(\n typeof value === 'bigint'\n ? \"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)\"\n : \"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\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 currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)\",\n currentUpdateQuery,\n key,\n key,\n JSONSerializer.serialize([value]),\n );\n }\n return currentUpdateQuery;\n};\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA,kBAAAA;AAAA,EACA;AAAA,EACA,OAAAC;AAAA,EACA;AAAA,OAGK;;;ACRP;AAAA,EACE,2BAAAC;AAAA,EACA,mBAAAC;AAAA,EACA;AAAA,OAUK;AACP,SAAS,MAAM,YAAY;;;ACd3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAiBA,IAAM,0BAA0B,CACrC,YAEA,QAAQ,kBAAkB;AAErB,IAAM,aAAa,CACxB,YAC+B;AAC/B,QAAM,EAAE,kBAAkB,OAAO,IAAI;AACrC,QAAM,eAAe,UAAU,yBAAyB,gBAAgB;AAExE,QAAM,OAAO,MAA2B;AAAA,IACtC;AAAA,IACA,GAAG,QAAQ;AAAA,EACb,CAAC;AAED,QAAM,cAAc,oBAAI,IAAuC;AAE/D,QAAM,UAAU,OACdC,MACAC,cAGE,MAAM,6BAA6B,IAAIA,UAAS,KAAK,OAAO,GAC5D,QAAgBD,IAAG;AAEvB,QAAM,QAAQ,OACZA,MACAC,cAEC,MAAM,6BAA6B,IAAIA,UAAS,KAAK,OAAO,GAAG;AAAA,IAC9DD;AAAA,EACF;AAEF,QAAM,KAAiC;AAAA,IACrC,eAAe,QAAQ;AAAA,IACvB;AAAA,IACA,SAAS,MAAM,QAAQ,QAAQ;AAAA,IAC/B,OA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AM,QAAQ,CAAC,WACb,OAAO,SAAS,IAAIA,KAAI,YAAY,MAAM,IAAI,OAAO,EAAE;","names":["JSONSerializer","sql","runPostgreSQLMigrations","schemaComponent","sql","options","db","sql","createCollection","expectedVersion","schemaComponent","runPostgreSQLMigrations","NodePostgresConnectorType","options","uuid","uuid","operationResult","pongoClient","NodePostgresConnectorType","JSONSerializer","JSONSerializer","JSONSerializer","sql","sql","JSONSerializer","sql","JSONSerializer","expectedVersion"]}
|
|
@@ -42,13 +42,13 @@ var postgresDb = (options) => {
|
|
|
42
42
|
connect: () => Promise.resolve(),
|
|
43
43
|
close: () => pool.close(),
|
|
44
44
|
collections: () => [...collections.values()],
|
|
45
|
-
collection: (collectionName) => pongoCollection({
|
|
45
|
+
collection: (collectionName, collectionOptions) => pongoCollection({
|
|
46
46
|
collectionName,
|
|
47
47
|
db,
|
|
48
48
|
pool,
|
|
49
49
|
sqlBuilder: postgresSQLBuilder(collectionName),
|
|
50
|
-
schema: options.schema
|
|
51
|
-
errors: options.errors
|
|
50
|
+
schema: { ...options.schema, ..._optionalChain([collectionOptions, 'optionalAccess', _ => _.schema]) },
|
|
51
|
+
errors: { ...options.errors, ..._optionalChain([collectionOptions, 'optionalAccess', _2 => _2.errors]) }
|
|
52
52
|
}),
|
|
53
53
|
transaction: () => pool.transaction(),
|
|
54
54
|
withTransaction: (handle) => pool.withTransaction(handle),
|
|
@@ -78,7 +78,7 @@ var postgresDb = (options) => {
|
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
};
|
|
81
|
-
const dbsSchema = _optionalChain([options, 'optionalAccess',
|
|
81
|
+
const dbsSchema = _optionalChain([options, 'optionalAccess', _3 => _3.schema, 'optionalAccess', _4 => _4.definition, 'optionalAccess', _5 => _5.dbs]);
|
|
82
82
|
if (dbsSchema) {
|
|
83
83
|
const dbSchema = objectEntries(dbsSchema).map((e) => e[1]).find((db2) => db2.name === dbName || db2.name === databaseName);
|
|
84
84
|
if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);
|
|
@@ -96,13 +96,13 @@ var pongoDbSchemaComponent = (collections) => {
|
|
|
96
96
|
|
|
97
97
|
// src/core/collection/pongoCollection.ts
|
|
98
98
|
var enlistIntoTransactionIfActive = async (db, options) => {
|
|
99
|
-
const transaction = _optionalChain([options, 'optionalAccess',
|
|
99
|
+
const transaction = _optionalChain([options, 'optionalAccess', _6 => _6.session, 'optionalAccess', _7 => _7.transaction]);
|
|
100
100
|
if (!transaction || !transaction.isActive) return null;
|
|
101
101
|
return await transaction.enlistDatabase(db);
|
|
102
102
|
};
|
|
103
103
|
var transactionExecutorOrDefault = async (db, options, defaultSqlExecutor) => {
|
|
104
104
|
const existingTransaction = await enlistIntoTransactionIfActive(db, options);
|
|
105
|
-
return _nullishCoalesce(_optionalChain([existingTransaction, 'optionalAccess',
|
|
105
|
+
return _nullishCoalesce(_optionalChain([existingTransaction, 'optionalAccess', _8 => _8.execute]), () => ( defaultSqlExecutor));
|
|
106
106
|
};
|
|
107
107
|
var pongoCollection = ({
|
|
108
108
|
db,
|
|
@@ -117,10 +117,10 @@ var pongoCollection = ({
|
|
|
117
117
|
const query = async (sql4, options) => (await transactionExecutorOrDefault(db, options, sqlExecutor)).query(
|
|
118
118
|
sql4
|
|
119
119
|
);
|
|
120
|
-
let shouldMigrate = _optionalChain([schema, 'optionalAccess',
|
|
120
|
+
let shouldMigrate = _optionalChain([schema, 'optionalAccess', _9 => _9.autoMigration]) !== "None";
|
|
121
121
|
const createCollection2 = (options) => {
|
|
122
122
|
shouldMigrate = false;
|
|
123
|
-
if (_optionalChain([options, 'optionalAccess',
|
|
123
|
+
if (_optionalChain([options, 'optionalAccess', _10 => _10.session])) return command(SqlFor.createCollection(), options);
|
|
124
124
|
else return command(SqlFor.createCollection());
|
|
125
125
|
};
|
|
126
126
|
const ensureCollectionCreated = (options) => {
|
|
@@ -129,7 +129,8 @@ var pongoCollection = ({
|
|
|
129
129
|
}
|
|
130
130
|
return createCollection2(options);
|
|
131
131
|
};
|
|
132
|
-
const upcast = _nullishCoalesce(_optionalChain([schema, 'optionalAccess',
|
|
132
|
+
const upcast = _nullishCoalesce(_optionalChain([schema, 'optionalAccess', _11 => _11.versioning, 'optionalAccess', _12 => _12.upcast]), () => ( ((doc) => doc)));
|
|
133
|
+
const downcast = _nullishCoalesce(_optionalChain([schema, 'optionalAccess', _13 => _13.versioning, 'optionalAccess', _14 => _14.downcast]), () => ( ((doc) => doc)));
|
|
133
134
|
const collection = {
|
|
134
135
|
dbName: db.databaseName,
|
|
135
136
|
collectionName,
|
|
@@ -140,9 +141,10 @@ var pongoCollection = ({
|
|
|
140
141
|
await ensureCollectionCreated(options);
|
|
141
142
|
const _id = _nullishCoalesce(document._id, () => ( _uuid.v7.call(void 0, )));
|
|
142
143
|
const _version = _nullishCoalesce(document._version, () => ( 1n));
|
|
144
|
+
const downcasted = downcast(document);
|
|
143
145
|
const result = await command(
|
|
144
146
|
SqlFor.insertOne({
|
|
145
|
-
...
|
|
147
|
+
...downcasted,
|
|
146
148
|
_id,
|
|
147
149
|
_version
|
|
148
150
|
}),
|
|
@@ -160,13 +162,18 @@ var pongoCollection = ({
|
|
|
160
162
|
},
|
|
161
163
|
insertMany: async (documents, options) => {
|
|
162
164
|
await ensureCollectionCreated(options);
|
|
163
|
-
const rows = documents.map((doc) =>
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
165
|
+
const rows = documents.map((doc) => {
|
|
166
|
+
const downcasted = downcast(doc);
|
|
167
|
+
return {
|
|
168
|
+
...downcasted,
|
|
169
|
+
_id: _nullishCoalesce(doc._id, () => ( _uuid.v7.call(void 0, ))),
|
|
170
|
+
_version: _nullishCoalesce(doc._version, () => ( 1n))
|
|
171
|
+
};
|
|
172
|
+
});
|
|
168
173
|
const result = await command(
|
|
169
|
-
SqlFor.insertMany(
|
|
174
|
+
SqlFor.insertMany(
|
|
175
|
+
rows
|
|
176
|
+
),
|
|
170
177
|
options
|
|
171
178
|
);
|
|
172
179
|
return operationResult(
|
|
@@ -187,25 +194,26 @@ var pongoCollection = ({
|
|
|
187
194
|
return operationResult(
|
|
188
195
|
{
|
|
189
196
|
successful: result.rows.length > 0 && result.rows[0].modified === result.rows[0].matched,
|
|
190
|
-
modifiedCount: Number(_nullishCoalesce(_optionalChain([result, 'access',
|
|
191
|
-
matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access',
|
|
192
|
-
nextExpectedVersion: _nullishCoalesce(_optionalChain([result, 'access',
|
|
197
|
+
modifiedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _15 => _15.rows, 'access', _16 => _16[0], 'optionalAccess', _17 => _17.modified]), () => ( 0))),
|
|
198
|
+
matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _18 => _18.rows, 'access', _19 => _19[0], 'optionalAccess', _20 => _20.matched]), () => ( 0))),
|
|
199
|
+
nextExpectedVersion: _nullishCoalesce(_optionalChain([result, 'access', _21 => _21.rows, 'access', _22 => _22[0], 'optionalAccess', _23 => _23.version]), () => ( 0n))
|
|
193
200
|
},
|
|
194
201
|
{ operationName: "updateOne", collectionName, errors }
|
|
195
202
|
);
|
|
196
203
|
},
|
|
197
204
|
replaceOne: async (filter, document, options) => {
|
|
198
205
|
await ensureCollectionCreated(options);
|
|
206
|
+
const downcasted = downcast(document);
|
|
199
207
|
const result = await command(
|
|
200
|
-
SqlFor.replaceOne(filter,
|
|
208
|
+
SqlFor.replaceOne(filter, downcasted, options),
|
|
201
209
|
options
|
|
202
210
|
);
|
|
203
211
|
return operationResult(
|
|
204
212
|
{
|
|
205
213
|
successful: result.rows.length > 0 && result.rows[0].modified > 0,
|
|
206
|
-
modifiedCount: Number(_nullishCoalesce(_optionalChain([result, 'access',
|
|
207
|
-
matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access',
|
|
208
|
-
nextExpectedVersion: _nullishCoalesce(_optionalChain([result, 'access',
|
|
214
|
+
modifiedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _24 => _24.rows, 'access', _25 => _25[0], 'optionalAccess', _26 => _26.modified]), () => ( 0))),
|
|
215
|
+
matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _27 => _27.rows, 'access', _28 => _28[0], 'optionalAccess', _29 => _29.matched]), () => ( 0))),
|
|
216
|
+
nextExpectedVersion: _nullishCoalesce(_optionalChain([result, 'access', _30 => _30.rows, 'access', _31 => _31[0], 'optionalAccess', _32 => _32.version]), () => ( 0n))
|
|
209
217
|
},
|
|
210
218
|
{ operationName: "replaceOne", collectionName, errors }
|
|
211
219
|
);
|
|
@@ -231,8 +239,8 @@ var pongoCollection = ({
|
|
|
231
239
|
return operationResult(
|
|
232
240
|
{
|
|
233
241
|
successful: result.rows.length > 0 && result.rows[0].deleted > 0,
|
|
234
|
-
deletedCount: Number(_nullishCoalesce(_optionalChain([result, 'access',
|
|
235
|
-
matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access',
|
|
242
|
+
deletedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _33 => _33.rows, 'access', _34 => _34[0], 'optionalAccess', _35 => _35.deleted]), () => ( 0))),
|
|
243
|
+
matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _36 => _36.rows, 'access', _37 => _37[0], 'optionalAccess', _38 => _38.matched]), () => ( 0)))
|
|
236
244
|
},
|
|
237
245
|
{ operationName: "deleteOne", collectionName, errors }
|
|
238
246
|
);
|
|
@@ -379,7 +387,7 @@ var pongoCollection = ({
|
|
|
379
387
|
drop: async (options) => {
|
|
380
388
|
await ensureCollectionCreated(options);
|
|
381
389
|
const result = await command(SqlFor.drop());
|
|
382
|
-
return (_nullishCoalesce(_optionalChain([result, 'optionalAccess',
|
|
390
|
+
return (_nullishCoalesce(_optionalChain([result, 'optionalAccess', _39 => _39.rowCount]), () => ( 0))) > 0;
|
|
383
391
|
},
|
|
384
392
|
rename: async (newName, options) => {
|
|
385
393
|
await ensureCollectionCreated(options);
|
|
@@ -526,7 +534,7 @@ var pongoTransaction = (options) => {
|
|
|
526
534
|
};
|
|
527
535
|
|
|
528
536
|
// src/core/pongoSession.ts
|
|
529
|
-
var isActive = (transaction) => _optionalChain([transaction, 'optionalAccess',
|
|
537
|
+
var isActive = (transaction) => _optionalChain([transaction, 'optionalAccess', _40 => _40.isActive]) === true;
|
|
530
538
|
function assertInActiveTransaction(transaction) {
|
|
531
539
|
if (!isActive(transaction)) throw new Error("No active transaction exists!");
|
|
532
540
|
}
|
|
@@ -535,8 +543,8 @@ function assertNotInActiveTransaction(transaction) {
|
|
|
535
543
|
throw new Error("Active transaction already exists!");
|
|
536
544
|
}
|
|
537
545
|
var pongoSession = (options) => {
|
|
538
|
-
const explicit = _optionalChain([options, 'optionalAccess',
|
|
539
|
-
const defaultTransactionOptions = _nullishCoalesce(_optionalChain([options, 'optionalAccess',
|
|
546
|
+
const explicit = _optionalChain([options, 'optionalAccess', _41 => _41.explicit]) === true;
|
|
547
|
+
const defaultTransactionOptions = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _42 => _42.defaultTransactionOptions]), () => ( {
|
|
540
548
|
get snapshotEnabled() {
|
|
541
549
|
return false;
|
|
542
550
|
}
|
|
@@ -629,7 +637,7 @@ var operationResult = (result, options) => {
|
|
|
629
637
|
);
|
|
630
638
|
}
|
|
631
639
|
};
|
|
632
|
-
if (_optionalChain([options, 'access',
|
|
640
|
+
if (_optionalChain([options, 'access', _43 => _43.errors, 'optionalAccess', _44 => _44.throwOnOperationFailures]))
|
|
633
641
|
operationResult2.assertSuccessful();
|
|
634
642
|
return operationResult2;
|
|
635
643
|
};
|
|
@@ -681,7 +689,7 @@ var proxyClientWithSchema = (client, schema) => {
|
|
|
681
689
|
client,
|
|
682
690
|
{
|
|
683
691
|
get(target, prop) {
|
|
684
|
-
if (dbNames.includes(prop)) return client.db(_optionalChain([schema, 'access',
|
|
692
|
+
if (dbNames.includes(prop)) return client.db(_optionalChain([schema, 'access', _45 => _45.dbs, 'access', _46 => _46[prop], 'optionalAccess', _47 => _47.name]));
|
|
685
693
|
return target[prop];
|
|
686
694
|
}
|
|
687
695
|
}
|
|
@@ -746,7 +754,7 @@ var pongoClient = (connectionString, options = {}) => {
|
|
|
746
754
|
}
|
|
747
755
|
}
|
|
748
756
|
};
|
|
749
|
-
return proxyClientWithSchema(pongoClient2, _optionalChain([options, 'optionalAccess',
|
|
757
|
+
return proxyClientWithSchema(pongoClient2, _optionalChain([options, 'optionalAccess', _48 => _48.schema, 'optionalAccess', _49 => _49.definition]));
|
|
750
758
|
};
|
|
751
759
|
var clientToDbOptions = (options) => {
|
|
752
760
|
const postgreSQLOptions = {
|
|
@@ -981,7 +989,7 @@ var postgresSQLBuilder = (collectionName) => ({
|
|
|
981
989
|
);
|
|
982
990
|
},
|
|
983
991
|
updateOne: (filter, update, options) => {
|
|
984
|
-
const expectedVersion2 = expectedVersionValue(_optionalChain([options, 'optionalAccess',
|
|
992
|
+
const expectedVersion2 = expectedVersionValue(_optionalChain([options, 'optionalAccess', _50 => _50.expectedVersion]));
|
|
985
993
|
const expectedVersionUpdate = expectedVersion2 != null ? "AND %I._version = %L" : "";
|
|
986
994
|
const expectedVersionParams = expectedVersion2 != null ? [collectionName, expectedVersion2] : [];
|
|
987
995
|
const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
|
|
@@ -1021,7 +1029,7 @@ var postgresSQLBuilder = (collectionName) => ({
|
|
|
1021
1029
|
);
|
|
1022
1030
|
},
|
|
1023
1031
|
replaceOne: (filter, document, options) => {
|
|
1024
|
-
const expectedVersion2 = expectedVersionValue(_optionalChain([options, 'optionalAccess',
|
|
1032
|
+
const expectedVersion2 = expectedVersionValue(_optionalChain([options, 'optionalAccess', _51 => _51.expectedVersion]));
|
|
1025
1033
|
const expectedVersionUpdate = expectedVersion2 != null ? "AND %I._version = %L" : "";
|
|
1026
1034
|
const expectedVersionParams = expectedVersion2 != null ? [collectionName, expectedVersion2] : [];
|
|
1027
1035
|
const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
|
|
@@ -1074,7 +1082,7 @@ var postgresSQLBuilder = (collectionName) => ({
|
|
|
1074
1082
|
);
|
|
1075
1083
|
},
|
|
1076
1084
|
deleteOne: (filter, options) => {
|
|
1077
|
-
const expectedVersion2 = expectedVersionValue(_optionalChain([options, 'optionalAccess',
|
|
1085
|
+
const expectedVersion2 = expectedVersionValue(_optionalChain([options, 'optionalAccess', _52 => _52.expectedVersion]));
|
|
1078
1086
|
const expectedVersionUpdate = expectedVersion2 != null ? "AND %I._version = %L" : "";
|
|
1079
1087
|
const expectedVersionParams = expectedVersion2 != null ? [collectionName, expectedVersion2] : [];
|
|
1080
1088
|
const filterQuery = _dumbo.isSQL.call(void 0, filter) ? filter : constructFilterQuery(filter);
|
|
@@ -1177,4 +1185,4 @@ var where = (filter) => filter.length > 0 ? _dumbo.sql.call(void 0, "WHERE %s",
|
|
|
1177
1185
|
|
|
1178
1186
|
|
|
1179
1187
|
exports.pongoCollectionPostgreSQLMigrations = pongoCollectionPostgreSQLMigrations; exports.postgresSQLBuilder = postgresSQLBuilder; exports.isPostgresClientOptions = isPostgresClientOptions; exports.postgresDb = postgresDb; exports.pongoDbSchemaComponent = pongoDbSchemaComponent; exports.transactionExecutorOrDefault = transactionExecutorOrDefault; exports.pongoCollection = pongoCollection; exports.pongoCollectionSchemaComponent = pongoCollectionSchemaComponent; exports.QueryOperators = QueryOperators; exports.OperatorMap = OperatorMap; exports.isOperator = isOperator; exports.hasOperators = hasOperators; exports.isNumber = isNumber; exports.isString = isString; exports.PongoError = PongoError; exports.ConcurrencyError = ConcurrencyError; exports.getPongoDb = getPongoDb; exports.pongoTransaction = pongoTransaction; exports.pongoSession = pongoSession; exports.objectEntries = objectEntries; 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.pongoClient = pongoClient; exports.clientToDbOptions = clientToDbOptions; exports.deepEquals = deepEquals; exports.isEquatable = isEquatable;
|
|
1180
|
-
//# sourceMappingURL=chunk-
|
|
1188
|
+
//# sourceMappingURL=chunk-NA3ELYRR.cjs.map
|