@event-driven-io/pongo 0.15.3 → 0.16.0-alpha.10

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"],"names":[],"mappings":"AAAA,iIAA2N,0kDAAyvB","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"}
1
+ {"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"],"names":[],"mappings":"AAAA,iIAA6N,soDAA2xB","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { Dumbo, MigrationStyle, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
2
- import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-DkAUSd1N.cjs';
3
- export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType, G as CollectionOperationOptions, C as CollectionsMap, a8 as Condition, r as DBsMap, aj as DOCUMENT_DOES_NOT_EXIST, ai as DOCUMENT_EXISTS, L as DeleteManyOptions, a2 as Document, ax as DocumentHandler, T as EnhancedOmit, ah as ExpectedDocumentVersion, af as ExpectedDocumentVersionGeneral, ag as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ak as NO_CONCURRENCY_CHECK, a6 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a5 as ObjectIdLike, ao as OperationResult, a3 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a4 as OptionalVersion, F as PongoClient, i as PongoClientOptions, o as PongoClientSchema, y as PongoClientSchemaMetadata, s as PongoClientWithSchema, m as PongoCollectionSchema, w as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, x as PongoDbSchemaMetadata, q as PongoDbWithSchema, av as PongoDeleteManyResult, au as PongoDeleteResult, aa as PongoFilterOperator, aw as PongoHandleResult, ar as PongoInsertManyResult, aq as PongoInsertOneResult, E as PongoSchemaConfig, at as PongoUpdateManyResult, as as PongoUpdateResult, h as PooledPongoClientOptions, ay as PostgresDbClientOptions, a1 as RegExpOrString, a9 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, $ as WithIdAndVersion, Z as WithVersion, a0 as WithoutIdAndVersion, _ as WithoutVersion, j as clientToDbOptions, an as expectedVersion, am as expectedVersionValue, l as getPongoDb, al as isGeneralExpectedDocumentVersion, az as isPostgresClientOptions, ap as operationResult, p as pongoClient, aB as pongoDbSchemaComponent, t as pongoSchema, aA as postgresDb, v as proxyClientWithSchema, u as proxyPongoDbWithSchema, B as toClientSchemaMetadata, z as toDbSchemaMetadata } from './pongoClient-DkAUSd1N.cjs';
1
+ import { Dumbo, MigrationStyle, SQLExecutor, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
2
+ import { P as PongoDb, C as CollectionOperationOptions, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-CjXGu-SC.cjs';
3
+ export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType, q as CollectionsMap, a8 as Condition, s as DBsMap, aj as DOCUMENT_DOES_NOT_EXIST, ai as DOCUMENT_EXISTS, L as DeleteManyOptions, a2 as Document, ax as DocumentHandler, T as EnhancedOmit, ah as ExpectedDocumentVersion, af as ExpectedDocumentVersionGeneral, ag as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ak as NO_CONCURRENCY_CHECK, a6 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a5 as ObjectIdLike, ao as OperationResult, a3 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a4 as OptionalVersion, G as PongoClient, i as PongoClientOptions, o as PongoClientSchema, z as PongoClientSchemaMetadata, t as PongoClientWithSchema, m as PongoCollectionSchema, x as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, y as PongoDbSchemaMetadata, r as PongoDbWithSchema, av as PongoDeleteManyResult, au as PongoDeleteResult, aa as PongoFilterOperator, aw as PongoHandleResult, ar as PongoInsertManyResult, aq as PongoInsertOneResult, F as PongoSchemaConfig, at as PongoUpdateManyResult, as as PongoUpdateResult, h as PooledPongoClientOptions, ay as PostgresDbClientOptions, a1 as RegExpOrString, a9 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, $ as WithIdAndVersion, Z as WithVersion, a0 as WithoutIdAndVersion, _ as WithoutVersion, j as clientToDbOptions, an as expectedVersion, am as expectedVersionValue, l as getPongoDb, al as isGeneralExpectedDocumentVersion, az as isPostgresClientOptions, ap as operationResult, p as pongoClient, aB as pongoDbSchemaComponent, u as pongoSchema, aA as postgresDb, w as proxyClientWithSchema, v as proxyPongoDbWithSchema, E as toClientSchemaMetadata, B as toDbSchemaMetadata } from './pongoClient-CjXGu-SC.cjs';
4
4
  import 'pg';
5
5
 
6
6
  type PongoCollectionOptions<ConnectorType extends string = string> = {
@@ -15,6 +15,7 @@ type PongoCollectionOptions<ConnectorType extends string = string> = {
15
15
  throwOnOperationFailures?: boolean;
16
16
  };
17
17
  };
18
+ declare const transactionExecutorOrDefault: <ConnectorType extends string = string>(db: PongoDb<ConnectorType>, options: CollectionOperationOptions | undefined, defaultSqlExecutor: SQLExecutor) => Promise<SQLExecutor>;
18
19
  declare const pongoCollection: <T extends PongoDocument, ConnectorType extends string = string>({ db, collectionName, pool, sqlBuilder: SqlFor, schema, errors, }: PongoCollectionOptions<ConnectorType>) => PongoCollection<T>;
19
20
  declare const pongoCollectionSchemaComponent: (collectionName: string) => SchemaComponent;
20
21
  type PongoCollectionSQLBuilder = {
@@ -92,4 +93,4 @@ declare const pongoSession: (options?: PongoSessionOptions) => PongoSession;
92
93
 
93
94
  declare const pongoTransaction: (options: PongoTransactionOptions) => PongoDbTransaction;
94
95
 
95
- export { ConcurrencyError, DeleteOneOptions, type NonPartial, OperatorMap, OptionalUnlessRequiredIdAndVersion, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoError, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, ReplaceOneOptions, UpdateOneOptions, WithoutId, hasOperators, isNumber, isOperator, isString, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder };
96
+ export { CollectionOperationOptions, ConcurrencyError, DeleteOneOptions, type NonPartial, OperatorMap, OptionalUnlessRequiredIdAndVersion, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoError, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, ReplaceOneOptions, UpdateOneOptions, WithoutId, hasOperators, isNumber, isOperator, isString, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder, transactionExecutorOrDefault };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Dumbo, MigrationStyle, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
2
- import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-DkAUSd1N.js';
3
- export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType, G as CollectionOperationOptions, C as CollectionsMap, a8 as Condition, r as DBsMap, aj as DOCUMENT_DOES_NOT_EXIST, ai as DOCUMENT_EXISTS, L as DeleteManyOptions, a2 as Document, ax as DocumentHandler, T as EnhancedOmit, ah as ExpectedDocumentVersion, af as ExpectedDocumentVersionGeneral, ag as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ak as NO_CONCURRENCY_CHECK, a6 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a5 as ObjectIdLike, ao as OperationResult, a3 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a4 as OptionalVersion, F as PongoClient, i as PongoClientOptions, o as PongoClientSchema, y as PongoClientSchemaMetadata, s as PongoClientWithSchema, m as PongoCollectionSchema, w as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, x as PongoDbSchemaMetadata, q as PongoDbWithSchema, av as PongoDeleteManyResult, au as PongoDeleteResult, aa as PongoFilterOperator, aw as PongoHandleResult, ar as PongoInsertManyResult, aq as PongoInsertOneResult, E as PongoSchemaConfig, at as PongoUpdateManyResult, as as PongoUpdateResult, h as PooledPongoClientOptions, ay as PostgresDbClientOptions, a1 as RegExpOrString, a9 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, $ as WithIdAndVersion, Z as WithVersion, a0 as WithoutIdAndVersion, _ as WithoutVersion, j as clientToDbOptions, an as expectedVersion, am as expectedVersionValue, l as getPongoDb, al as isGeneralExpectedDocumentVersion, az as isPostgresClientOptions, ap as operationResult, p as pongoClient, aB as pongoDbSchemaComponent, t as pongoSchema, aA as postgresDb, v as proxyClientWithSchema, u as proxyPongoDbWithSchema, B as toClientSchemaMetadata, z as toDbSchemaMetadata } from './pongoClient-DkAUSd1N.js';
1
+ import { Dumbo, MigrationStyle, SQLExecutor, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
2
+ import { P as PongoDb, C as CollectionOperationOptions, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredIdAndVersion, c as PongoFilter, d as PongoUpdate, U as UpdateOneOptions, W as WithoutId, R as ReplaceOneOptions, D as DeleteOneOptions, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-CjXGu-SC.js';
3
+ export { ad as $inc, ae as $push, ab as $set, ac as $unset, A as AllowedDbClientOptions, a7 as AlternativeType, q as CollectionsMap, a8 as Condition, s as DBsMap, aj as DOCUMENT_DOES_NOT_EXIST, ai as DOCUMENT_EXISTS, L as DeleteManyOptions, a2 as Document, ax as DocumentHandler, T as EnhancedOmit, ah as ExpectedDocumentVersion, af as ExpectedDocumentVersionGeneral, ag as ExpectedDocumentVersionValue, K as HandleOptions, Q as HasId, S as InferIdType, H as InsertManyOptions, I as InsertOneOptions, ak as NO_CONCURRENCY_CHECK, a6 as NonObjectIdLikeDocument, N as NotPooledPongoOptions, M as ObjectId, a5 as ObjectIdLike, ao as OperationResult, a3 as OptionalId, V as OptionalUnlessRequiredId, X as OptionalUnlessRequiredVersion, a4 as OptionalVersion, G as PongoClient, i as PongoClientOptions, o as PongoClientSchema, z as PongoClientSchemaMetadata, t as PongoClientWithSchema, m as PongoCollectionSchema, x as PongoCollectionSchemaMetadata, k as PongoDbClientOptions, n as PongoDbSchema, y as PongoDbSchemaMetadata, r as PongoDbWithSchema, av as PongoDeleteManyResult, au as PongoDeleteResult, aa as PongoFilterOperator, aw as PongoHandleResult, ar as PongoInsertManyResult, aq as PongoInsertOneResult, F as PongoSchemaConfig, at as PongoUpdateManyResult, as as PongoUpdateResult, h as PooledPongoClientOptions, ay as PostgresDbClientOptions, a1 as RegExpOrString, a9 as RootFilterOperators, J as UpdateManyOptions, Y as WithId, $ as WithIdAndVersion, Z as WithVersion, a0 as WithoutIdAndVersion, _ as WithoutVersion, j as clientToDbOptions, an as expectedVersion, am as expectedVersionValue, l as getPongoDb, al as isGeneralExpectedDocumentVersion, az as isPostgresClientOptions, ap as operationResult, p as pongoClient, aB as pongoDbSchemaComponent, u as pongoSchema, aA as postgresDb, w as proxyClientWithSchema, v as proxyPongoDbWithSchema, E as toClientSchemaMetadata, B as toDbSchemaMetadata } from './pongoClient-CjXGu-SC.js';
4
4
  import 'pg';
5
5
 
6
6
  type PongoCollectionOptions<ConnectorType extends string = string> = {
@@ -15,6 +15,7 @@ type PongoCollectionOptions<ConnectorType extends string = string> = {
15
15
  throwOnOperationFailures?: boolean;
16
16
  };
17
17
  };
18
+ declare const transactionExecutorOrDefault: <ConnectorType extends string = string>(db: PongoDb<ConnectorType>, options: CollectionOperationOptions | undefined, defaultSqlExecutor: SQLExecutor) => Promise<SQLExecutor>;
18
19
  declare const pongoCollection: <T extends PongoDocument, ConnectorType extends string = string>({ db, collectionName, pool, sqlBuilder: SqlFor, schema, errors, }: PongoCollectionOptions<ConnectorType>) => PongoCollection<T>;
19
20
  declare const pongoCollectionSchemaComponent: (collectionName: string) => SchemaComponent;
20
21
  type PongoCollectionSQLBuilder = {
@@ -92,4 +93,4 @@ declare const pongoSession: (options?: PongoSessionOptions) => PongoSession;
92
93
 
93
94
  declare const pongoTransaction: (options: PongoTransactionOptions) => PongoDbTransaction;
94
95
 
95
- export { ConcurrencyError, DeleteOneOptions, type NonPartial, OperatorMap, OptionalUnlessRequiredIdAndVersion, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoError, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, ReplaceOneOptions, UpdateOneOptions, WithoutId, hasOperators, isNumber, isOperator, isString, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder };
96
+ export { CollectionOperationOptions, ConcurrencyError, DeleteOneOptions, type NonPartial, OperatorMap, OptionalUnlessRequiredIdAndVersion, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoError, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, ReplaceOneOptions, UpdateOneOptions, WithoutId, hasOperators, isNumber, isOperator, isString, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder, transactionExecutorOrDefault };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{A,B,C,D,E,F,G,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunk-S6SSZQB7.js";export{i as ConcurrencyError,s as DOCUMENT_DOES_NOT_EXIST,q as DOCUMENT_EXISTS,u as NO_CONCURRENCY_CHECK,a as OperatorMap,h as PongoError,x as QueryOperators,G as clientToDbOptions,y as expectedVersion,w as expectedVersionValue,j as getPongoDb,c as hasOperators,v as isGeneralExpectedDocumentVersion,d as isNumber,b as isOperator,e as isPostgresClientOptions,g as isString,n as objectEntries,z as operationResult,F as pongoClient,p as pongoCollection,o as pongoCollectionPostgreSQLMigrations,t as pongoCollectionSchemaComponent,m as pongoDbSchemaComponent,A as pongoSchema,l as pongoSession,k as pongoTransaction,f as postgresDb,r as postgresSQLBuilder,C as proxyClientWithSchema,B as proxyPongoDbWithSchema,E as toClientSchemaMetadata,D as toDbSchemaMetadata};
1
+ import{A,B,C,D,E,F,G,H,a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u,w as v,x as w,y,z}from"./chunk-GFYGFSLO.js";export{j as ConcurrencyError,u as DOCUMENT_DOES_NOT_EXIST,s as DOCUMENT_EXISTS,v as NO_CONCURRENCY_CHECK,b as OperatorMap,i as PongoError,a as QueryOperators,H as clientToDbOptions,z as expectedVersion,y as expectedVersionValue,k as getPongoDb,d as hasOperators,w as isGeneralExpectedDocumentVersion,g as isNumber,c as isOperator,e as isPostgresClientOptions,h as isString,q as objectEntries,A as operationResult,G as pongoClient,t as pongoCollection,o as pongoCollectionPostgreSQLMigrations,x as pongoCollectionSchemaComponent,m as pongoDbSchemaComponent,B as pongoSchema,n as pongoSession,l as pongoTransaction,f as postgresDb,r as postgresSQLBuilder,D as proxyClientWithSchema,C as proxyPongoDbWithSchema,F as toClientSchemaMetadata,E as toDbSchemaMetadata,p as transactionExecutorOrDefault};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { DatabaseTransaction, SQLExecutor, DatabaseTransactionFactory, SchemaComponent, SQL, QueryResultRow, QueryResult, PostgresConnector, NodePostgresConnection, MigrationStyle } from '@event-driven-io/dumbo';
1
+ import { DatabaseTransaction, SQLExecutor, DatabaseTransactionFactory, SchemaComponent, QueryResultRow, SQL, QueryResult, PostgresConnector, NodePostgresConnection, MigrationStyle } from '@event-driven-io/dumbo';
2
2
  import pg from 'pg';
3
3
 
4
4
  interface PongoClient {
@@ -43,10 +43,15 @@ interface PongoDb<ConnectorType extends string = string> extends DatabaseTransac
43
43
  connect(): Promise<void>;
44
44
  close(): Promise<void>;
45
45
  collection<T extends PongoDocument>(name: string): PongoCollection<T>;
46
+ collections(): ReadonlyArray<PongoCollection<PongoDocument>>;
46
47
  readonly schema: Readonly<{
47
48
  component: SchemaComponent;
48
49
  migrate(): Promise<void>;
49
50
  }>;
51
+ sql: {
52
+ query<Result extends QueryResultRow = QueryResultRow>(sql: SQL, options?: CollectionOperationOptions): Promise<Result[]>;
53
+ command<Result extends QueryResultRow = QueryResultRow>(sql: SQL, options?: CollectionOperationOptions): Promise<QueryResult<Result>>;
54
+ };
50
55
  }
51
56
  type CollectionOperationOptions = {
52
57
  session?: PongoSession;
@@ -349,4 +354,4 @@ declare const clientToDbOptions: <DbClientOptions extends AllowedDbClientOptions
349
354
  clientOptions: PongoClientOptions;
350
355
  }) => DbClientOptions;
351
356
 
352
- export { type WithIdAndVersion as $, type AllowedDbClientOptions as A, toClientSchemaMetadata as B, type CollectionsMap as C, type DeleteOneOptions as D, type PongoSchemaConfig as E, type PongoClient as F, type CollectionOperationOptions as G, type InsertManyOptions as H, type InsertOneOptions as I, type UpdateManyOptions as J, type HandleOptions as K, type DeleteManyOptions as L, type ObjectId as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredIdAndVersion as O, type PongoDb as P, type HasId as Q, type ReplaceOneOptions as R, type InferIdType as S, type EnhancedOmit as T, type UpdateOneOptions as U, type OptionalUnlessRequiredId as V, type WithoutId as W, type OptionalUnlessRequiredVersion as X, type WithId as Y, type WithVersion as Z, type WithoutVersion as _, type PongoDocument as a, type WithoutIdAndVersion as a0, type RegExpOrString as a1, type Document as a2, type OptionalId as a3, type OptionalVersion as a4, type ObjectIdLike as a5, type NonObjectIdLikeDocument as a6, type AlternativeType as a7, type Condition as a8, type RootFilterOperators as a9, postgresDb as aA, pongoDbSchemaComponent as aB, type PongoFilterOperator as aa, type $set as ab, type $unset as ac, type $inc as ad, type $push as ae, type ExpectedDocumentVersionGeneral as af, type ExpectedDocumentVersionValue as ag, type ExpectedDocumentVersion as ah, DOCUMENT_EXISTS as ai, DOCUMENT_DOES_NOT_EXIST as aj, NO_CONCURRENCY_CHECK as ak, isGeneralExpectedDocumentVersion as al, expectedVersionValue as am, expectedVersion as an, type OperationResult as ao, operationResult as ap, type PongoInsertOneResult as aq, type PongoInsertManyResult as ar, type PongoUpdateResult as as, type PongoUpdateManyResult as at, type PongoDeleteResult as au, type PongoDeleteManyResult as av, type PongoHandleResult as aw, type DocumentHandler as ax, type PostgresDbClientOptions as ay, isPostgresClientOptions as az, type PongoCollection as b, type PongoFilter as c, type PongoUpdate as d, type PongoTransactionOptions as e, type PongoSession as f, type PongoDbTransaction as g, type PooledPongoClientOptions as h, type PongoClientOptions as i, clientToDbOptions as j, type PongoDbClientOptions as k, getPongoDb as l, type PongoCollectionSchema as m, type PongoDbSchema as n, type PongoClientSchema as o, pongoClient as p, type PongoDbWithSchema as q, type DBsMap as r, type PongoClientWithSchema as s, pongoSchema as t, proxyPongoDbWithSchema as u, proxyClientWithSchema as v, type PongoCollectionSchemaMetadata as w, type PongoDbSchemaMetadata as x, type PongoClientSchemaMetadata as y, toDbSchemaMetadata as z };
357
+ export { type WithIdAndVersion as $, type AllowedDbClientOptions as A, toDbSchemaMetadata as B, type CollectionOperationOptions as C, type DeleteOneOptions as D, toClientSchemaMetadata as E, type PongoSchemaConfig as F, type PongoClient as G, type InsertManyOptions as H, type InsertOneOptions as I, type UpdateManyOptions as J, type HandleOptions as K, type DeleteManyOptions as L, type ObjectId as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredIdAndVersion as O, type PongoDb as P, type HasId as Q, type ReplaceOneOptions as R, type InferIdType as S, type EnhancedOmit as T, type UpdateOneOptions as U, type OptionalUnlessRequiredId as V, type WithoutId as W, type OptionalUnlessRequiredVersion as X, type WithId as Y, type WithVersion as Z, type WithoutVersion as _, type PongoDocument as a, type WithoutIdAndVersion as a0, type RegExpOrString as a1, type Document as a2, type OptionalId as a3, type OptionalVersion as a4, type ObjectIdLike as a5, type NonObjectIdLikeDocument as a6, type AlternativeType as a7, type Condition as a8, type RootFilterOperators as a9, postgresDb as aA, pongoDbSchemaComponent as aB, type PongoFilterOperator as aa, type $set as ab, type $unset as ac, type $inc as ad, type $push as ae, type ExpectedDocumentVersionGeneral as af, type ExpectedDocumentVersionValue as ag, type ExpectedDocumentVersion as ah, DOCUMENT_EXISTS as ai, DOCUMENT_DOES_NOT_EXIST as aj, NO_CONCURRENCY_CHECK as ak, isGeneralExpectedDocumentVersion as al, expectedVersionValue as am, expectedVersion as an, type OperationResult as ao, operationResult as ap, type PongoInsertOneResult as aq, type PongoInsertManyResult as ar, type PongoUpdateResult as as, type PongoUpdateManyResult as at, type PongoDeleteResult as au, type PongoDeleteManyResult as av, type PongoHandleResult as aw, type DocumentHandler as ax, type PostgresDbClientOptions as ay, isPostgresClientOptions as az, type PongoCollection as b, type PongoFilter as c, type PongoUpdate as d, type PongoTransactionOptions as e, type PongoSession as f, type PongoDbTransaction as g, type PooledPongoClientOptions as h, type PongoClientOptions as i, clientToDbOptions as j, type PongoDbClientOptions as k, getPongoDb as l, type PongoCollectionSchema as m, type PongoDbSchema as n, type PongoClientSchema as o, pongoClient as p, type CollectionsMap as q, type PongoDbWithSchema as r, type DBsMap as s, type PongoClientWithSchema as t, pongoSchema as u, proxyPongoDbWithSchema as v, proxyClientWithSchema as w, type PongoCollectionSchemaMetadata as x, type PongoDbSchemaMetadata as y, type PongoClientSchemaMetadata as z };
@@ -1,4 +1,4 @@
1
- import { DatabaseTransaction, SQLExecutor, DatabaseTransactionFactory, SchemaComponent, SQL, QueryResultRow, QueryResult, PostgresConnector, NodePostgresConnection, MigrationStyle } from '@event-driven-io/dumbo';
1
+ import { DatabaseTransaction, SQLExecutor, DatabaseTransactionFactory, SchemaComponent, QueryResultRow, SQL, QueryResult, PostgresConnector, NodePostgresConnection, MigrationStyle } from '@event-driven-io/dumbo';
2
2
  import pg from 'pg';
3
3
 
4
4
  interface PongoClient {
@@ -43,10 +43,15 @@ interface PongoDb<ConnectorType extends string = string> extends DatabaseTransac
43
43
  connect(): Promise<void>;
44
44
  close(): Promise<void>;
45
45
  collection<T extends PongoDocument>(name: string): PongoCollection<T>;
46
+ collections(): ReadonlyArray<PongoCollection<PongoDocument>>;
46
47
  readonly schema: Readonly<{
47
48
  component: SchemaComponent;
48
49
  migrate(): Promise<void>;
49
50
  }>;
51
+ sql: {
52
+ query<Result extends QueryResultRow = QueryResultRow>(sql: SQL, options?: CollectionOperationOptions): Promise<Result[]>;
53
+ command<Result extends QueryResultRow = QueryResultRow>(sql: SQL, options?: CollectionOperationOptions): Promise<QueryResult<Result>>;
54
+ };
50
55
  }
51
56
  type CollectionOperationOptions = {
52
57
  session?: PongoSession;
@@ -349,4 +354,4 @@ declare const clientToDbOptions: <DbClientOptions extends AllowedDbClientOptions
349
354
  clientOptions: PongoClientOptions;
350
355
  }) => DbClientOptions;
351
356
 
352
- export { type WithIdAndVersion as $, type AllowedDbClientOptions as A, toClientSchemaMetadata as B, type CollectionsMap as C, type DeleteOneOptions as D, type PongoSchemaConfig as E, type PongoClient as F, type CollectionOperationOptions as G, type InsertManyOptions as H, type InsertOneOptions as I, type UpdateManyOptions as J, type HandleOptions as K, type DeleteManyOptions as L, type ObjectId as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredIdAndVersion as O, type PongoDb as P, type HasId as Q, type ReplaceOneOptions as R, type InferIdType as S, type EnhancedOmit as T, type UpdateOneOptions as U, type OptionalUnlessRequiredId as V, type WithoutId as W, type OptionalUnlessRequiredVersion as X, type WithId as Y, type WithVersion as Z, type WithoutVersion as _, type PongoDocument as a, type WithoutIdAndVersion as a0, type RegExpOrString as a1, type Document as a2, type OptionalId as a3, type OptionalVersion as a4, type ObjectIdLike as a5, type NonObjectIdLikeDocument as a6, type AlternativeType as a7, type Condition as a8, type RootFilterOperators as a9, postgresDb as aA, pongoDbSchemaComponent as aB, type PongoFilterOperator as aa, type $set as ab, type $unset as ac, type $inc as ad, type $push as ae, type ExpectedDocumentVersionGeneral as af, type ExpectedDocumentVersionValue as ag, type ExpectedDocumentVersion as ah, DOCUMENT_EXISTS as ai, DOCUMENT_DOES_NOT_EXIST as aj, NO_CONCURRENCY_CHECK as ak, isGeneralExpectedDocumentVersion as al, expectedVersionValue as am, expectedVersion as an, type OperationResult as ao, operationResult as ap, type PongoInsertOneResult as aq, type PongoInsertManyResult as ar, type PongoUpdateResult as as, type PongoUpdateManyResult as at, type PongoDeleteResult as au, type PongoDeleteManyResult as av, type PongoHandleResult as aw, type DocumentHandler as ax, type PostgresDbClientOptions as ay, isPostgresClientOptions as az, type PongoCollection as b, type PongoFilter as c, type PongoUpdate as d, type PongoTransactionOptions as e, type PongoSession as f, type PongoDbTransaction as g, type PooledPongoClientOptions as h, type PongoClientOptions as i, clientToDbOptions as j, type PongoDbClientOptions as k, getPongoDb as l, type PongoCollectionSchema as m, type PongoDbSchema as n, type PongoClientSchema as o, pongoClient as p, type PongoDbWithSchema as q, type DBsMap as r, type PongoClientWithSchema as s, pongoSchema as t, proxyPongoDbWithSchema as u, proxyClientWithSchema as v, type PongoCollectionSchemaMetadata as w, type PongoDbSchemaMetadata as x, type PongoClientSchemaMetadata as y, toDbSchemaMetadata as z };
357
+ export { type WithIdAndVersion as $, type AllowedDbClientOptions as A, toDbSchemaMetadata as B, type CollectionOperationOptions as C, type DeleteOneOptions as D, toClientSchemaMetadata as E, type PongoSchemaConfig as F, type PongoClient as G, type InsertManyOptions as H, type InsertOneOptions as I, type UpdateManyOptions as J, type HandleOptions as K, type DeleteManyOptions as L, type ObjectId as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredIdAndVersion as O, type PongoDb as P, type HasId as Q, type ReplaceOneOptions as R, type InferIdType as S, type EnhancedOmit as T, type UpdateOneOptions as U, type OptionalUnlessRequiredId as V, type WithoutId as W, type OptionalUnlessRequiredVersion as X, type WithId as Y, type WithVersion as Z, type WithoutVersion as _, type PongoDocument as a, type WithoutIdAndVersion as a0, type RegExpOrString as a1, type Document as a2, type OptionalId as a3, type OptionalVersion as a4, type ObjectIdLike as a5, type NonObjectIdLikeDocument as a6, type AlternativeType as a7, type Condition as a8, type RootFilterOperators as a9, postgresDb as aA, pongoDbSchemaComponent as aB, type PongoFilterOperator as aa, type $set as ab, type $unset as ac, type $inc as ad, type $push as ae, type ExpectedDocumentVersionGeneral as af, type ExpectedDocumentVersionValue as ag, type ExpectedDocumentVersion as ah, DOCUMENT_EXISTS as ai, DOCUMENT_DOES_NOT_EXIST as aj, NO_CONCURRENCY_CHECK as ak, isGeneralExpectedDocumentVersion as al, expectedVersionValue as am, expectedVersion as an, type OperationResult as ao, operationResult as ap, type PongoInsertOneResult as aq, type PongoInsertManyResult as ar, type PongoUpdateResult as as, type PongoUpdateManyResult as at, type PongoDeleteResult as au, type PongoDeleteManyResult as av, type PongoHandleResult as aw, type DocumentHandler as ax, type PostgresDbClientOptions as ay, isPostgresClientOptions as az, type PongoCollection as b, type PongoFilter as c, type PongoUpdate as d, type PongoTransactionOptions as e, type PongoSession as f, type PongoDbTransaction as g, type PooledPongoClientOptions as h, type PongoClientOptions as i, clientToDbOptions as j, type PongoDbClientOptions as k, getPongoDb as l, type PongoCollectionSchema as m, type PongoDbSchema as n, type PongoClientSchema as o, pongoClient as p, type CollectionsMap as q, type PongoDbWithSchema as r, type DBsMap as s, type PongoClientWithSchema as t, pongoSchema as u, proxyPongoDbWithSchema as v, proxyClientWithSchema as w, type PongoCollectionSchemaMetadata as x, type PongoDbSchemaMetadata as y, type PongoClientSchemaMetadata as z };
package/dist/shim.cjs CHANGED
@@ -1,2 +1,2 @@
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; } var _class;var _chunkP5Y6AANFcjs = require('./chunk-P5Y6AANF.cjs');var s= (_class =class{__init() {this.documents=null}__init2() {this.index=0}constructor(e){;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?_nullishCoalesce(e[this.index++], () => (null)):null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}}, _class);require('mongodb');var o=r=>_optionalChain([r, 'optionalAccess', _ => _.session])?{session:r.session}:void 0,d= exports.Collection =class{constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return await this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(_nullishCoalesce(e, () => ({})),o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n,t){return this.collection.handle(e.toString(),n,t)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{constructor(e,n={}){this.pongoClient=_chunkP5Y6AANFcjs.F.call(void 0, e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return _chunkP5Y6AANFcjs.r.call(void 0, )}async withSession(e,n){let t=typeof e=="function"?e:n,i=_chunkP5Y6AANFcjs.r.call(void 0, );try{return await t(i)}finally{await i.endSession()}}};exports.Collection = d; exports.Db = l; exports.FindCursor = s; exports.MongoClient = u;
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; } var _class;var _chunkFJ56KM7Mcjs = require('./chunk-FJ56KM7M.cjs');var s= (_class =class{__init() {this.documents=null}__init2() {this.index=0}constructor(e){;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?_nullishCoalesce(e[this.index++], () => (null)):null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}}, _class);require('mongodb');var o=r=>_optionalChain([r, 'optionalAccess', _ => _.session])?{session:r.session}:void 0,d= exports.Collection =class{constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return await this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(_nullishCoalesce(e, () => ({})),o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n,t){return this.collection.handle(e.toString(),n,t)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{constructor(e,n={}){this.pongoClient=_chunkFJ56KM7Mcjs.G.call(void 0, e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return _chunkFJ56KM7Mcjs.s.call(void 0, )}async withSession(e,n){let t=typeof e=="function"?e:n,i=_chunkFJ56KM7Mcjs.s.call(void 0, );try{return await t(i)}finally{await i.endSession()}}};exports.Collection = d; exports.Db = l; exports.FindCursor = s; exports.MongoClient = u;
2
2
  //# sourceMappingURL=shim.cjs.map
package/dist/shim.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ClientSessionOptions } from 'http2';
2
2
  import { Document, Collection as Collection$1, ObjectId, ClientSession, WithSessionCallback, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
3
- import { P as PongoDb, ax as DocumentHandler, K as HandleOptions, aw as PongoHandleResult, i as PongoClientOptions, b as PongoCollection } from './pongoClient-DkAUSd1N.cjs';
3
+ import { P as PongoDb, ax as DocumentHandler, K as HandleOptions, aw as PongoHandleResult, i as PongoClientOptions, b as PongoCollection } from './pongoClient-CjXGu-SC.cjs';
4
4
  import '@event-driven-io/dumbo';
5
5
  import 'pg';
6
6
 
package/dist/shim.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ClientSessionOptions } from 'http2';
2
2
  import { Document, Collection as Collection$1, ObjectId, ClientSession, WithSessionCallback, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
3
- import { P as PongoDb, ax as DocumentHandler, K as HandleOptions, aw as PongoHandleResult, i as PongoClientOptions, b as PongoCollection } from './pongoClient-DkAUSd1N.js';
3
+ import { P as PongoDb, ax as DocumentHandler, K as HandleOptions, aw as PongoHandleResult, i as PongoClientOptions, b as PongoCollection } from './pongoClient-CjXGu-SC.js';
4
4
  import '@event-driven-io/dumbo';
5
5
  import 'pg';
6
6
 
package/dist/shim.js CHANGED
@@ -1,2 +1,2 @@
1
- import{F as p,r as a}from"./chunk-S6SSZQB7.js";var s=class{findDocumentsPromise;documents=null;index=0;constructor(e){this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?e[this.index++]??null:null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}};import"mongodb";var o=r=>r?.session?{session:r.session}:void 0,d=class{collection;constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return await this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(e??{},o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n,t){return this.collection.handle(e.toString(),n,t)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{pongoClient;constructor(e,n={}){this.pongoClient=p(e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return a()}async withSession(e,n){let t=typeof e=="function"?e:n,i=a();try{return await t(i)}finally{await i.endSession()}}};export{d as Collection,l as Db,s as FindCursor,u as MongoClient};
1
+ import{G as p,s as a}from"./chunk-GFYGFSLO.js";var s=class{findDocumentsPromise;documents=null;index=0;constructor(e){this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?e[this.index++]??null:null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}};import"mongodb";var o=r=>r?.session?{session:r.session}:void 0,d=class{collection;constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return await this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(e??{},o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n,t){return this.collection.handle(e.toString(),n,t)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{pongoClient;constructor(e,n={}){this.pongoClient=p(e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return a()}async withSession(e,n){let t=typeof e=="function"?e:n,i=a();try{return await t(i)}finally{await i.endSession()}}};export{d as Collection,l as Db,s as FindCursor,u as MongoClient};
2
2
  //# sourceMappingURL=shim.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@event-driven-io/pongo",
3
- "version": "0.15.3",
3
+ "version": "0.16.0-alpha.10",
4
4
  "description": "Pongo - Mongo with strong consistency on top of Postgres",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -87,7 +87,7 @@
87
87
  "pongo": "./dist/cli.js"
88
88
  },
89
89
  "peerDependencies": {
90
- "@event-driven-io/dumbo": "0.11.1",
90
+ "@event-driven-io/dumbo": "0.12.0-alpha.10",
91
91
  "@types/mongodb": "^4.0.7",
92
92
  "@types/pg": "^8.11.6",
93
93
  "@types/uuid": "^10.0.0",
@@ -1,76 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await 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; } async function _asyncOptionalChain(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 = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var X=e=>e.connectorType===_dumbo.NodePostgresConnectorType,B= exports.d =e=>{let{connectionString:n,dbName:t}=e,o=_nullishCoalesce(t, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, n))),i=_dumbo.dumbo.call(void 0, {connectionString:n,...e.connectionOptions}),r=new Map,d={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collection:g=>K({collectionName:g,db:d,pool:i,sqlBuilder:q(g),...e.schema?e.schema:{},...e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:g=>i.withTransaction(g),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongoDb",{components:[...r.values()].map(g=>g.schema.component)})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, i,[...r.values()].flatMap(g=>g.schema.component.migrations({connector:"PostgreSQL:pg"})))}},p=_optionalChain([e, 'optionalAccess', _2 => _2.schema, 'optionalAccess', _3 => _3.definition, 'optionalAccess', _4 => _4.dbs]);if(p){let g=P(p).map(C=>C[1]).find(C=>C.name===t||C.name===o);if(g)return G(d,g,r)}return d},je= exports.e =e=>{let n=e.length>0&&typeof e[0]=="string"?e.map(t=>z(t)):e;return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:db",{components:n})};var Oe=async(e,n)=>{let t=_optionalChain([n, 'optionalAccess', _5 => _5.session, 'optionalAccess', _6 => _6.transaction]);return!t||!t.isActive?null:await t.enlistDatabase(e)},J=async(e,n,t)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await Oe(e,n)), 'optionalAccess', async _7 => _7.execute]), async () => (t)),K= exports.f =({db:e,collectionName:n,pool:t,sqlBuilder:o,schema:i,errors:r})=>{let d=t.execute,p=async(s,a)=>(await J(e,a,d)).command(s),g=async(s,a)=>(await J(e,a,d)).query(s),C=_optionalChain([i, 'optionalAccess', _8 => _8.autoMigration])!=="None",E=s=>(C=!1,_optionalChain([s, 'optionalAccess', _9 => _9.session])?p(o.createCollection(),s):p(o.createCollection())),u=s=>C?E(s):Promise.resolve(),T={dbName:e.databaseName,collectionName:n,createCollection:async s=>{await E(s)},insertOne:async(s,a)=>{await u(a);let c=_nullishCoalesce(s._id, () => (_uuid.v4.call(void 0, ))),l=_nullishCoalesce(s._version, () => (1n)),R=(await _asyncNullishCoalesce((await p(o.insertOne({...s,_id:c,_version:l}),a)).rowCount, async () => (0)))>0;return S({successful:R,insertedId:R?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:n,errors:r})},insertMany:async(s,a)=>{await u(a);let c=s.map(x=>({...x,_id:_nullishCoalesce(x._id, () => (_uuid.v4.call(void 0, ))),_version:_nullishCoalesce(x._version, () => (1n))})),l=await p(o.insertMany(c),a);return S({successful:l.rowCount===c.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:n,errors:r})},updateOne:async(s,a,c)=>{await u(c);let l=await p(o.updateOne(s,a,c),c);return S({successful:l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"updateOne",collectionName:n,errors:r})},replaceOne:async(s,a,c)=>{await u(c);let l=await p(o.replaceOne(s,a,c),c);return S({successful:l.rows[0].modified>0,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"replaceOne",collectionName:n,errors:r})},updateMany:async(s,a,c)=>{await u(c);let l=await p(o.updateMany(s,a),c);return S({successful:!0,modifiedCount:_nullishCoalesce(l.rowCount, () => (0)),matchedCount:_nullishCoalesce(l.rowCount, () => (0))},{operationName:"updateMany",collectionName:n,errors:r})},deleteOne:async(s,a)=>{await u(a);let c=await p(o.deleteOne(_nullishCoalesce(s, () => ({})),a),a);return S({successful:c.rows[0].deleted>0,deletedCount:Number(c.rows[0].deleted),matchedCount:Number(c.rows[0].matched)},{operationName:"deleteOne",collectionName:n,errors:r})},deleteMany:async(s,a)=>{await u(a);let c=await p(o.deleteMany(_nullishCoalesce(s, () => ({}))),a);return S({successful:(_nullishCoalesce(c.rowCount, () => (0)))>0,deletedCount:_nullishCoalesce(c.rowCount, () => (0)),matchedCount:_nullishCoalesce(c.rowCount, () => (0))},{operationName:"deleteMany",collectionName:n,errors:r})},findOne:async(s,a)=>(await u(a),await _asyncNullishCoalesce(await _asyncOptionalChain([(await g(o.findOne(_nullishCoalesce(s, () => ({}))),a)), 'access', async _10 => _10.rows, 'access', async _11 => _11[0], 'optionalAccess', async _12 => _12.data]), async () => (null))),findOneAndDelete:async(s,a)=>{await u(a);let c=await T.findOne(s,a);return c===null?null:(await T.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await u(c);let l=await T.findOne(s,c);return l===null?null:(await T.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await u(c);let l=await T.findOne(s,c);return l===null?null:(await T.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=_nullishCoalesce(c, () => ({}));await u(c);let R={_id:s},y=await T.findOne(R,c),L=_(l);if(y==null&&l==="DOCUMENT_EXISTS"||y==null&&L!=null||y!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||y!=null&&L!==null&&y._version!==L)return S({successful:!1,document:y},{operationName:"handle",collectionName:n,errors:r});let D=await a(y);if(y===D)return S({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r});if(!y&&D){let I={...D,_id:s},W=await T.insertOne({...I,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...W,document:{...I,_version:W.nextExpectedVersion}}}if(y&&!D)return{...await T.deleteOne(R,{...x,expectedVersion:_nullishCoalesce(L, () => ("DOCUMENT_EXISTS"))}),document:null};if(y&&D){let I=await T.replaceOne(R,D,{...x,expectedVersion:_nullishCoalesce(L, () => ("DOCUMENT_EXISTS"))});return{...I,document:{...D,_version:I.nextExpectedVersion}}}return S({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r})},find:async(s,a)=>(await u(a),(await g(o.find(_nullishCoalesce(s, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await u(a);let{count:c}=await _dumbo.single.call(void 0, g(o.countDocuments(_nullishCoalesce(s, () => ({})))));return c},drop:async s=>(await u(s),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await p(o.drop())), 'optionalAccess', async _13 => _13.rowCount]), async () => (0)))>0),rename:async(s,a)=>(await u(a),await p(o.rename(s)),n=s,T),sql:{async query(s,a){return await u(a),(await g(s)).rows},async command(s,a){return await u(a),p(s)}},schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, t,o.migrations())}};return T},z= exports.g =e=>_dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:()=>$(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},V= exports.i ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye= exports.j =e=>e.startsWith("$"),ne= exports.k =e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Se= exports.m =e=>typeof e=="string",A= exports.n =class e extends Error{constructor(n){let t=n&&typeof n=="object"&&"errorCode"in n?n.errorCode:Pe(n)?n:500,o=n&&typeof n=="object"&&"message"in n?n.message:Se(n)?n:`Error with status code '${t}' ocurred during Pongo processing`;super(o),this.errorCode=t,Object.setPrototypeOf(this,e.prototype)}},N= exports.o =class e extends A{constructor(n){super({errorCode:412,message:_nullishCoalesce(n, () => ("Expected document state does not match current one!"))}),Object.setPrototypeOf(this,e.prototype)}};require('pg');var v=e=>{let{connectorType:n}=e;if(!X(e))throw new Error(`Unsupported db type: ${n}`);return B(e)};var te=e=>{let n=!1,t=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!n){if(t)throw new Error("Transaction is not active!");n=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");t||(t=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!t},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>_optionalChain([e, 'optionalAccess', _14 => _14.isActive])===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Ce(e){if(U(e))throw new Error("Active transaction already exists!")}var F=e=>{let n=_optionalChain([e, 'optionalAccess', _15 => _15.explicit])===!0,t=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _16 => _16.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,i=!1,r=E=>{Ce(o),o=te(_nullishCoalesce(E, () => (t)))},d=async()=>{oe(o),await o.commit()},p=async()=>{oe(o),await o.rollback()},C={get hasEnded(){return i},explicit:n,defaultTransactionOptions:_nullishCoalesce(t, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return t.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:d,abortTransaction:p,withTransaction:async(E,u)=>{r(u);try{let T=await E(C);return await d(),T}catch(T){throw await p(),T}}};return C};var P=e=>Object.entries(e).map(([n,t])=>[n,t]);var dn="DOCUMENT_EXISTS",un= exports.u ="DOCUMENT_DOES_NOT_EXIST",be= exports.v ="NO_CONCURRENCY_CHECK",he= exports.w =e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",_= exports.x =e=>e===void 0||he(e)?null:e,gn= exports.y =e=>e?BigInt(e):be,S= exports.z =(e,n)=>{let t={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:d}=n;if(!i)throw new N(_nullishCoalesce(o, () => (`${r} on ${d} failed. Expected document state does not match current one! Result: ${_dumbo.JSONSerializer.serialize(e)}!`)))}};return _optionalChain([n, 'access', _17 => _17.errors, 'optionalAccess', _18 => _18.throwOnOperationFailures])&&t.assertSuccessful(),t};var fe=e=>({name:e});function De(e,n){if(n===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:n}:{collections:n}}var Ee=e=>({dbs:e}),Sn= exports.A ={client:Ee,db:De,collection:fe},G= exports.B =(e,n,t)=>{let o=Object.keys(n.collections);for(let i of o)t.set(i,e.collection(i));return new Proxy(e,{get(i,r){return _nullishCoalesce(t.get(r), () => (i[r]))}})},ie= exports.C =(e,n)=>{if(!n)return e;let t=Object.keys(n.dbs);return new Proxy(e,{get(o,i){return t.includes(i)?e.db(_optionalChain([n, 'access', _19 => _19.dbs, 'access', _20 => _20[i], 'optionalAccess', _21 => _21.name])):o[i]}})},Re= exports.D =e=>({name:e.name,collections:P(e.collections).map(n=>({name:n[1].name}))}),Cn= exports.E =e=>{let n=P(e.dbs).map(t=>Re(t[1]));return{databases:n,database:t=>n.find(o=>o.name===t)}};var In=(e,n={})=>{let t=new Map,o=v(se({connectionString:e,clientOptions:n}));t.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of t.values())await r.close()},db:r=>r?_nullishCoalesce(t.get(r), () => (t.set(r,v(se({connectionString:e,dbName:r,clientOptions:n}))).get(r))):o,startSession:F,withSession:async r=>{let d=F();try{return await r(d)}finally{await d.endSession()}}};return ie(i,_optionalChain([n, 'optionalAccess', _22 => _22.schema, 'optionalAccess', _23 => _23.definition]))},se= exports.G =e=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});var M=(e,n,t)=>{if(e==="_id"||e==="_version")return _e(e,n,t);switch(n){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",_dumbo.JSONSerializer.serialize(re(e,t)),e,_dumbo.JSONSerializer.serialize(t));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${V[n]} %L`,`{${e.split(".").join(",")}}`,t);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=P(t).map(([i,r])=>_dumbo.sql.call(void 0, '@."%s" == %s',i,_dumbo.JSONSerializer.serialize(r))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",_dumbo.JSONSerializer.serialize(re(e,t)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,t);default:throw new Error(`Unsupported operator: ${n}`)}},_e=(e,n,t)=>{switch(n){case"$eq":return _dumbo.sql.call(void 0, `${e} = %L`,t);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `${e} ${V[n]} %L`,t);case"$in":return _dumbo.sql.call(void 0, `${e} IN (%s)`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, `${e} NOT IN (%s)`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},re=(e,n)=>e.split(".").reverse().reduce((t,o)=>({[o]:t}),n);var ae="AND",h=e=>Object.entries(e).map(([n,t])=>we(t)?Le(n,t):M(n,"$eq",t)).join(` ${ae} `),Le=(e,n)=>{let t=!ne(n);return P(n).map(([o,i])=>t?M(`${e}.${o}`,ee.$eq,i):M(e,o,i)).join(` ${ae} `)},we=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);var j=e=>P(e).reduce((n,[t,o])=>{switch(t){case"$set":return Ne(o,n);case"$unset":return Ue(o,n);case"$inc":return Qe(o,n);case"$push":return Me(o,n);default:return n}},_dumbo.sql.call(void 0, "data")),Ne=(e,n)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",n,_dumbo.JSONSerializer.serialize(e)),Ue=(e,n)=>_dumbo.sql.call(void 0, "%s - %L",n,Object.keys(e).map(t=>`{${t}}`).join(", ")),Qe=(e,n)=>{for(let[t,o]of Object.entries(e))n=_dumbo.sql.call(void 0, typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",n,t,t,o);return n},Me=(e,n)=>{for(let[t,o]of Object.entries(e))n=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",n,t,t,_dumbo.JSONSerializer.serialize([o]));return n};var le=e=>_dumbo.sql.call(void 0, `CREATE TABLE IF NOT EXISTS %I (
2
- _id TEXT PRIMARY KEY,
3
- data JSONB NOT NULL,
4
- metadata JSONB NOT NULL DEFAULT '{}',
5
- _version BIGINT NOT NULL DEFAULT 1,
6
- _partition TEXT NOT NULL DEFAULT 'png_global',
7
- _archived BOOLEAN NOT NULL DEFAULT FALSE,
8
- _created TIMESTAMPTZ NOT NULL DEFAULT now(),
9
- _updated TIMESTAMPTZ NOT NULL DEFAULT now()
10
- )`,e),$= exports.a =e=>[_dumbo.sqlMigration.call(void 0, `pongoCollection:${e}:001:createtable`,[le(e)])],q= exports.b =e=>({migrations:()=>$(e),createCollection:()=>le(e),insertOne:n=>_dumbo.sql.call(void 0, "INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;",e,n._id,_dumbo.JSONSerializer.serialize(n),_nullishCoalesce(n._version, () => (1n))),insertMany:n=>{let t=n.map(o=>_dumbo.sql.call(void 0, "(%L, %L, %L)",o._id,_dumbo.JSONSerializer.serialize(o),_nullishCoalesce(o._version, () => (1n)))).join(", ");return _dumbo.sql.call(void 0, `INSERT INTO %I (_id, data, _version) VALUES %s
11
- ON CONFLICT(_id) DO NOTHING
12
- RETURNING _id;`,e,t)},updateOne:(n,t,o)=>{let i=_(_optionalChain([o, 'optionalAccess', _24 => _24.expectedVersion])),r=i!=null?"AND %I._version = %L":"",d=i!=null?[e,i]:[],p=_dumbo.isSQL.call(void 0, n)?n:h(n),g=_dumbo.isSQL.call(void 0, t)?t:j(t);return _dumbo.sql.call(void 0, `WITH existing AS (
13
- SELECT _id, _version as current_version
14
- FROM %I %s
15
- LIMIT 1
16
- ),
17
- updated AS (
18
- UPDATE %I
19
- SET
20
- data = %s || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),
21
- _version = _version + 1
22
- FROM existing
23
- WHERE %I._id = existing._id ${r}
24
- RETURNING %I._id, %I._version
25
- )
26
- SELECT
27
- existing._id,
28
- COALESCE(updated._version, existing.current_version) AS version,
29
- COUNT(existing._id) over() AS matched,
30
- COUNT(updated._id) over() AS modified
31
- FROM existing
32
- LEFT JOIN updated
33
- ON existing._id = updated._id;`,e,f(p),e,g,e,e,...d,e,e)},replaceOne:(n,t,o)=>{let i=_(_optionalChain([o, 'optionalAccess', _25 => _25.expectedVersion])),r=i!=null?"AND %I._version = %L":"",d=i!=null?[e,i]:[],p=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, `WITH existing AS (
34
- SELECT _id, _version as current_version
35
- FROM %I %s
36
- LIMIT 1
37
- ),
38
- updated AS (
39
- UPDATE %I
40
- SET
41
- data = %L || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),
42
- _version = _version + 1
43
- FROM existing
44
- WHERE %I._id = existing._id ${r}
45
- RETURNING %I._id, %I._version
46
- )
47
- SELECT
48
- existing._id,
49
- COALESCE(updated._version, existing.current_version) AS version,
50
- COUNT(existing._id) over() AS matched,
51
- COUNT(updated._id) over() AS modified
52
- FROM existing
53
- LEFT JOIN updated
54
- ON existing._id = updated._id;`,e,f(p),e,_dumbo.JSONSerializer.serialize(t),e,e,...d,e,e)},updateMany:(n,t)=>{let o=_dumbo.isSQL.call(void 0, n)?n:h(n),i=_dumbo.isSQL.call(void 0, t)?t:j(t);return _dumbo.sql.call(void 0, `UPDATE %I
55
- SET
56
- data = %s || jsonb_build_object('_version', (_version + 1)::text),
57
- _version = _version + 1
58
- %s;`,e,i,f(o))},deleteOne:(n,t)=>{let o=_(_optionalChain([t, 'optionalAccess', _26 => _26.expectedVersion])),i=o!=null?"AND %I._version = %L":"",r=o!=null?[e,o]:[],d=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, `WITH existing AS (
59
- SELECT _id
60
- FROM %I %s
61
- LIMIT 1
62
- ),
63
- deleted AS (
64
- DELETE FROM %I
65
- USING existing
66
- WHERE %I._id = existing._id ${i}
67
- RETURNING %I._id
68
- )
69
- SELECT
70
- existing._id,
71
- COUNT(existing._id) over() AS matched,
72
- COUNT(deleted._id) over() AS deleted
73
- FROM existing
74
- LEFT JOIN deleted
75
- ON existing._id = deleted._id;`,e,f(d),e,e,...r,e)},deleteMany:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",e,f(t))},findOne:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1;",e,f(t))},find:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s;",e,f(t))},countDocuments:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s;",e,f(t))},rename:n=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I;",e,n),drop:(n=e)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",n)}),f=e=>e.length>0?_dumbo.sql.call(void 0, "WHERE %s",e):_dumbo.rawSql.call(void 0, "");exports.a = $; exports.b = q; exports.c = X; exports.d = B; exports.e = je; exports.f = K; exports.g = z; exports.h = ee; exports.i = V; exports.j = ye; exports.k = ne; exports.l = Pe; exports.m = Se; exports.n = A; exports.o = N; exports.p = v; exports.q = te; exports.r = F; exports.s = P; exports.t = dn; exports.u = un; exports.v = be; exports.w = he; exports.x = _; exports.y = gn; exports.z = S; exports.A = Sn; exports.B = G; exports.C = ie; exports.D = Re; exports.E = Cn; exports.F = In; exports.G = se;
76
- //# sourceMappingURL=chunk-P5Y6AANF.cjs.map
@@ -1 +0,0 @@
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"],"names":["isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","db","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","transaction","transactionExecutorOrDefault","defaultSqlExecutor","SqlFor","schema","errors","sqlExecutor","command","sql","query","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","_version","successful","operationResult","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","version","operationOptions","byId","existing","expectedVersion","expectedVersionValue","newDoc","insertResult","replaceResult","row","count","single","newName","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","isNumber","val","isString","PongoError","_PongoError","errorCode","message","ConcurrencyError","_ConcurrencyError","getPongoDb","type"],"mappings":"AAAA,g3CAQO,4BCMoB,ICUdA,CAAAA,CACXC,CAAAA,EAEAA,CAAAA,CAAQ,aAAA,GAAkBC,gCAAAA,CAEfC,CAAAA,aACXF,CAAAA,EAC+B,CAC/B,GAAM,CAAE,gBAAA,CAAAG,CAAAA,CAAkB,MAAA,CAAAC,CAAO,CAAA,CAAIJ,CAAAA,CAC/BK,CAAAA,kBAAeD,CAAAA,SAAUE,6CAAAA,CAAyC,GAAA,CAElEC,CAAAA,CAAOC,0BAAAA,CACX,gBAAA,CAAAL,CAAAA,CACA,GAAGH,CAAAA,CAAQ,iBACb,CAAC,CAAA,CAEKS,CAAAA,CAAc,IAAI,GAAA,CAElBC,CAAAA,CAAiC,CACrC,aAAA,CAAeV,CAAAA,CAAQ,aAAA,CACvB,YAAA,CAAAK,CAAAA,CACA,OAAA,CAAS,CAAA,CAAA,EAAM,OAAA,CAAQ,OAAA,CAAQ,CAAA,CAC/B,KAAA,CAAO,CAAA,CAAA,EAAME,CAAAA,CAAK,KAAA,CAAM,CAAA,CACxB,UAAA,CAAaI,CAAAA,EACXC,CAAAA,CAAgB,CACd,cAAA,CAAAD,CAAAA,CACA,EAAA,CAAAD,CAAAA,CACA,IAAA,CAAAH,CAAAA,CACA,UAAA,CAAYM,CAAAA,CAAmBF,CAAc,CAAA,CAC7C,GAAIX,CAAAA,CAAQ,MAAA,CAASA,CAAAA,CAAQ,MAAA,CAAS,CAAC,CAAA,CACvC,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ClD,CACF,CAAA,CAEaG,CAAAA,aAAN,MAAMC,EAAAA,QAAyBL,CAAW,CAC/C,WAAA,CAAYG,CAAAA,CAAkB,CAC5B,KAAA,CAAM,CACJ,SAAA,CAAW,GAAA,CACX,OAAA,kBAASA,CAAAA,SAAW,uDACtB,CAAC,CAAA,CAGD,MAAA,CAAO,cAAA,CAAe,IAAA,CAAME,CAAAA,CAAiB,SAAS,CACxD,CACF,CAAA,CC3CA,cAKe,ICWFC,CAAAA,CAGXtF,CAAAA,EACY,CACZ,GAAM,CAAE,aAAA,CAAeuF,CAAK,CAAA,CAAIvF,CAAAA,CAEhC,EAAA,CAAI,CAACD,CAAAA,CAAwBC,CAAO,CAAA,CAClC,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBuF,CAAI,CAAA,CAAA;ANC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8CE,GAAA;AAAA;AAsBA,oBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoCrD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BrD,oCAAA;AAAA;AAAA;AAAA;AAuBA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDF,oCAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-P5Y6AANF.cjs","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 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('SELECT data FROM %I %s;', collectionName, where(filterQuery));\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 { v4 as uuid } from 'uuid';\nimport {\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<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\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\nconst 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>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n errors,\n}: PongoCollectionOptions<ConnectorType>): 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 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\n const result = await command(\n SqlFor.insertOne({\n ...document,\n _id,\n _version,\n } as OptionalUnlessRequiredIdAndVersion<T>),\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 ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n _version: doc._version ?? 1n,\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredIdAndVersion<T>[]),\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: result.rows[0]!.modified === result.rows[0]!.matched,\n modifiedCount: Number(result.rows[0]!.modified),\n matchedCount: Number(result.rows[0]!.matched),\n nextExpectedVersion: result.rows[0]!.version,\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 result = await command<UpdateSqlResult>(\n SqlFor.replaceOne(filter, document, options),\n options,\n );\n return operationResult<PongoUpdateResult>(\n {\n successful: result.rows[0]!.modified > 0,\n modifiedCount: Number(result.rows[0]!.modified),\n matchedCount: Number(result.rows[0]!.matched),\n nextExpectedVersion: result.rows[0]!.version,\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[0]!.deleted! > 0,\n deletedCount: Number(result.rows[0]!.deleted!),\n matchedCount: Number(result.rows[0]!.matched!),\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(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as WithIdAndVersion<T> | null;\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>;\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(existing as T);\n\n if (existing === result)\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\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(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as WithIdAndVersion<T>);\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);\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);\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 type PostgresConnector,\n type PostgresPoolOptions,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\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 db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n ...(options.schema ? options.schema : {}),\n ...(options.errors ? options.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\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"]}