@event-driven-io/pongo 0.14.1 → 0.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-UGDQF6CW.js +14 -0
- package/dist/chunk-UGDQF6CW.js.map +1 -0
- package/dist/chunk-YQPKY7LN.cjs +14 -0
- package/dist/chunk-YQPKY7LN.cjs.map +1 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +3 -3
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -10
- package/dist/index.d.ts +6 -10
- package/dist/index.js +1 -1
- package/dist/{pongoClient-BdiZsK3b.d.cts → pongoClient-CajnU47o.d.cts} +27 -1
- package/dist/{pongoClient-BdiZsK3b.d.ts → pongoClient-CajnU47o.d.ts} +27 -1
- package/dist/shim.cjs +1 -1
- package/dist/shim.d.cts +1 -1
- package/dist/shim.d.ts +1 -1
- package/dist/shim.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-74UAYOAE.cjs +0 -14
- package/dist/chunk-74UAYOAE.cjs.map +0 -1
- package/dist/chunk-JEFOWKG5.js +0 -14
- package/dist/chunk-JEFOWKG5.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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 OptionalUnlessRequiredId, c as PongoFilter, d as PongoUpdate, W as WithoutId, e as
|
|
3
|
-
export {
|
|
2
|
+
import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredId, c as PongoFilter, d as PongoUpdate, W as WithoutId, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-CajnU47o.cjs';
|
|
3
|
+
export { Z as $inc, _ as $push, $ as $set, Y as $unset, A as AllowedDbClientOptions, T as AlternativeType, F as CollectionOperationOptions, C as CollectionsMap, U as Condition, D as DBsMap, L as Document, a6 as DocumentHandler, J as EnhancedOmit, H as HasId, I as InferIdType, S as NonObjectIdLikeDocument, N as NotPooledPongoOptions, G as ObjectId, Q as ObjectIdLike, M as OptionalId, E as PongoClient, w as PongoClientOptions, j as PongoClientSchema, r as PongoClientSchemaMetadata, l as PongoClientWithSchema, h as PongoCollectionSchema, o as PongoCollectionSchemaMetadata, z as PongoDbClientOptions, i as PongoDbSchema, q as PongoDbSchemaMetadata, k as PongoDbWithSchema, a5 as PongoDeleteManyResult, a4 as PongoDeleteResult, X as PongoFilterOperator, a1 as PongoInsertManyResult, a0 as PongoInsertOneResult, u as PongoSchemaConfig, a3 as PongoUpdateManyResult, a2 as PongoUpdateResult, v as PooledPongoClientOptions, a7 as PostgresDbClientOptions, R as RegExpOrString, V as RootFilterOperators, K as WithId, y as clientToDbOptions, B as getPongoDb, a8 as isPostgresClientOptions, x as pongoClient, aa as pongoDbSchemaComponent, p as pongoSchema, a9 as postgresDb, n as proxyClientWithSchema, m as proxyPongoDbWithSchema, s as toClientSchemaMetadata, t as toDbSchemaMetadata } from './pongoClient-CajnU47o.cjs';
|
|
4
4
|
import 'pg';
|
|
5
5
|
|
|
6
6
|
type PongoCollectionOptions<ConnectorType extends string = string> = {
|
|
@@ -54,13 +54,6 @@ declare const OperatorMap: {
|
|
|
54
54
|
declare const isOperator: (key: string) => boolean;
|
|
55
55
|
declare const hasOperators: (value: Record<string, unknown>) => boolean;
|
|
56
56
|
|
|
57
|
-
interface PongoSchemaConfig<TypedClientSchema extends PongoClientSchema = PongoClientSchema> {
|
|
58
|
-
schema: TypedClientSchema;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
declare const pongoCollectionPostgreSQLMigrations: (collectionName: string) => SQLMigration[];
|
|
62
|
-
declare const postgresSQLBuilder: (collectionName: string) => PongoCollectionSQLBuilder;
|
|
63
|
-
|
|
64
57
|
type Entry<T> = {
|
|
65
58
|
[K in keyof Required<T>]: [K, Required<T>[K]];
|
|
66
59
|
}[keyof Required<T>];
|
|
@@ -72,6 +65,9 @@ type NonPartial<T> = {
|
|
|
72
65
|
[K in keyof Required<T>]: T[K];
|
|
73
66
|
};
|
|
74
67
|
|
|
68
|
+
declare const pongoCollectionPostgreSQLMigrations: (collectionName: string) => SQLMigration[];
|
|
69
|
+
declare const postgresSQLBuilder: (collectionName: string) => PongoCollectionSQLBuilder;
|
|
70
|
+
|
|
75
71
|
type PongoSessionOptions = {
|
|
76
72
|
explicit?: boolean;
|
|
77
73
|
defaultTransactionOptions: PongoTransactionOptions;
|
|
@@ -80,4 +76,4 @@ declare const pongoSession: (options?: PongoSessionOptions) => PongoSession;
|
|
|
80
76
|
|
|
81
77
|
declare const pongoTransaction: (options: PongoTransactionOptions) => PongoDbTransaction;
|
|
82
78
|
|
|
83
|
-
export { type NonPartial, OperatorMap, OptionalUnlessRequiredId, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoFilter,
|
|
79
|
+
export { type NonPartial, OperatorMap, OptionalUnlessRequiredId, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, WithoutId, hasOperators, isOperator, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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 OptionalUnlessRequiredId, c as PongoFilter, d as PongoUpdate, W as WithoutId, e as
|
|
3
|
-
export {
|
|
2
|
+
import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredId, c as PongoFilter, d as PongoUpdate, W as WithoutId, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-CajnU47o.js';
|
|
3
|
+
export { Z as $inc, _ as $push, $ as $set, Y as $unset, A as AllowedDbClientOptions, T as AlternativeType, F as CollectionOperationOptions, C as CollectionsMap, U as Condition, D as DBsMap, L as Document, a6 as DocumentHandler, J as EnhancedOmit, H as HasId, I as InferIdType, S as NonObjectIdLikeDocument, N as NotPooledPongoOptions, G as ObjectId, Q as ObjectIdLike, M as OptionalId, E as PongoClient, w as PongoClientOptions, j as PongoClientSchema, r as PongoClientSchemaMetadata, l as PongoClientWithSchema, h as PongoCollectionSchema, o as PongoCollectionSchemaMetadata, z as PongoDbClientOptions, i as PongoDbSchema, q as PongoDbSchemaMetadata, k as PongoDbWithSchema, a5 as PongoDeleteManyResult, a4 as PongoDeleteResult, X as PongoFilterOperator, a1 as PongoInsertManyResult, a0 as PongoInsertOneResult, u as PongoSchemaConfig, a3 as PongoUpdateManyResult, a2 as PongoUpdateResult, v as PooledPongoClientOptions, a7 as PostgresDbClientOptions, R as RegExpOrString, V as RootFilterOperators, K as WithId, y as clientToDbOptions, B as getPongoDb, a8 as isPostgresClientOptions, x as pongoClient, aa as pongoDbSchemaComponent, p as pongoSchema, a9 as postgresDb, n as proxyClientWithSchema, m as proxyPongoDbWithSchema, s as toClientSchemaMetadata, t as toDbSchemaMetadata } from './pongoClient-CajnU47o.js';
|
|
4
4
|
import 'pg';
|
|
5
5
|
|
|
6
6
|
type PongoCollectionOptions<ConnectorType extends string = string> = {
|
|
@@ -54,13 +54,6 @@ declare const OperatorMap: {
|
|
|
54
54
|
declare const isOperator: (key: string) => boolean;
|
|
55
55
|
declare const hasOperators: (value: Record<string, unknown>) => boolean;
|
|
56
56
|
|
|
57
|
-
interface PongoSchemaConfig<TypedClientSchema extends PongoClientSchema = PongoClientSchema> {
|
|
58
|
-
schema: TypedClientSchema;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
declare const pongoCollectionPostgreSQLMigrations: (collectionName: string) => SQLMigration[];
|
|
62
|
-
declare const postgresSQLBuilder: (collectionName: string) => PongoCollectionSQLBuilder;
|
|
63
|
-
|
|
64
57
|
type Entry<T> = {
|
|
65
58
|
[K in keyof Required<T>]: [K, Required<T>[K]];
|
|
66
59
|
}[keyof Required<T>];
|
|
@@ -72,6 +65,9 @@ type NonPartial<T> = {
|
|
|
72
65
|
[K in keyof Required<T>]: T[K];
|
|
73
66
|
};
|
|
74
67
|
|
|
68
|
+
declare const pongoCollectionPostgreSQLMigrations: (collectionName: string) => SQLMigration[];
|
|
69
|
+
declare const postgresSQLBuilder: (collectionName: string) => PongoCollectionSQLBuilder;
|
|
70
|
+
|
|
75
71
|
type PongoSessionOptions = {
|
|
76
72
|
explicit?: boolean;
|
|
77
73
|
defaultTransactionOptions: PongoTransactionOptions;
|
|
@@ -80,4 +76,4 @@ declare const pongoSession: (options?: PongoSessionOptions) => PongoSession;
|
|
|
80
76
|
|
|
81
77
|
declare const pongoTransaction: (options: PongoTransactionOptions) => PongoDbTransaction;
|
|
82
78
|
|
|
83
|
-
export { type NonPartial, OperatorMap, OptionalUnlessRequiredId, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoFilter,
|
|
79
|
+
export { type NonPartial, OperatorMap, OptionalUnlessRequiredId, PongoCollection, type PongoCollectionOptions, type PongoCollectionSQLBuilder, PongoDb, PongoDbTransaction, PongoDocument, PongoFilter, PongoSession, type PongoSessionOptions, PongoTransactionOptions, PongoUpdate, QueryOperators, WithoutId, hasOperators, isOperator, objectEntries, pongoCollection, pongoCollectionPostgreSQLMigrations, pongoCollectionSchemaComponent, pongoSession, pongoTransaction, postgresSQLBuilder };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as o,
|
|
1
|
+
import{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}from"./chunk-UGDQF6CW.js";export{a as OperatorMap,x as QueryOperators,u as clientToDbOptions,l as getPongoDb,c as hasOperators,b as isOperator,e as isPostgresClientOptions,d as objectEntries,s as pongoClient,p as pongoCollection,o as pongoCollectionPostgreSQLMigrations,t as pongoCollectionSchemaComponent,m as pongoDbSchemaComponent,g as pongoSchema,q as pongoSession,n as pongoTransaction,f as postgresDb,r as postgresSQLBuilder,i as proxyClientWithSchema,h as proxyPongoDbWithSchema,k as toClientSchemaMetadata,j as toDbSchemaMetadata};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -195,10 +195,36 @@ interface PongoClientSchema<T extends Record<string, PongoDbSchema> = Record<str
|
|
|
195
195
|
type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {
|
|
196
196
|
[K in keyof T]: PongoCollection<T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument>;
|
|
197
197
|
};
|
|
198
|
+
type PongoDbWithSchema<T extends Record<string, PongoCollectionSchema>, ConnectorType extends string = string> = CollectionsMap<T> & PongoDb<ConnectorType>;
|
|
198
199
|
type DBsMap<T extends Record<string, PongoDbSchema>> = {
|
|
199
200
|
[K in keyof T]: CollectionsMap<T[K]['collections']>;
|
|
200
201
|
};
|
|
201
202
|
type PongoClientWithSchema<T extends PongoClientSchema> = DBsMap<T['dbs']> & PongoClient;
|
|
203
|
+
declare function pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(collections: T): PongoDbSchema<T>;
|
|
204
|
+
declare function pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(name: string, collections: T): PongoDbSchema<T>;
|
|
205
|
+
declare const pongoSchema: {
|
|
206
|
+
client: <T extends Record<string, PongoDbSchema>>(dbs: T) => PongoClientSchema<T>;
|
|
207
|
+
db: typeof pongoDbSchema;
|
|
208
|
+
collection: <T extends PongoDocument>(name: string) => PongoCollectionSchema<T>;
|
|
209
|
+
};
|
|
210
|
+
declare const proxyPongoDbWithSchema: <T extends Record<string, PongoCollectionSchema>, ConnectorType extends string = string>(pongoDb: PongoDb<ConnectorType>, dbSchema: PongoDbSchema<T>, collections: Map<string, PongoCollection<Document>>) => PongoDbWithSchema<T, ConnectorType>;
|
|
211
|
+
declare const proxyClientWithSchema: <TypedClientSchema extends PongoClientSchema>(client: PongoClient, schema: TypedClientSchema | undefined) => PongoClientWithSchema<TypedClientSchema>;
|
|
212
|
+
type PongoCollectionSchemaMetadata = {
|
|
213
|
+
name: string;
|
|
214
|
+
};
|
|
215
|
+
type PongoDbSchemaMetadata = {
|
|
216
|
+
name?: string | undefined;
|
|
217
|
+
collections: PongoCollectionSchemaMetadata[];
|
|
218
|
+
};
|
|
219
|
+
type PongoClientSchemaMetadata = {
|
|
220
|
+
databases: PongoDbSchemaMetadata[];
|
|
221
|
+
database: (name?: string) => PongoDbSchemaMetadata | undefined;
|
|
222
|
+
};
|
|
223
|
+
declare const toDbSchemaMetadata: <TypedDbSchema extends PongoDbSchema>(schema: TypedDbSchema) => PongoDbSchemaMetadata;
|
|
224
|
+
declare const toClientSchemaMetadata: <TypedClientSchema extends PongoClientSchema>(schema: TypedClientSchema) => PongoClientSchemaMetadata;
|
|
225
|
+
interface PongoSchemaConfig<TypedClientSchema extends PongoClientSchema = PongoClientSchema> {
|
|
226
|
+
schema: TypedClientSchema;
|
|
227
|
+
}
|
|
202
228
|
|
|
203
229
|
type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;
|
|
204
230
|
declare const isPostgresClientOptions: (options: PongoDbClientOptions) => options is PostgresDbClientOptions;
|
|
@@ -246,4 +272,4 @@ declare const clientToDbOptions: <DbClientOptions extends AllowedDbClientOptions
|
|
|
246
272
|
clientOptions: PongoClientOptions;
|
|
247
273
|
}) => DbClientOptions;
|
|
248
274
|
|
|
249
|
-
export { type $set as $, type AllowedDbClientOptions as A,
|
|
275
|
+
export { type $set as $, type AllowedDbClientOptions as A, getPongoDb as B, type CollectionsMap as C, type DBsMap as D, type PongoClient as E, type CollectionOperationOptions as F, type ObjectId as G, type HasId as H, type InferIdType as I, type EnhancedOmit as J, type WithId as K, type Document as L, type OptionalId as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredId as O, type PongoDb as P, type ObjectIdLike as Q, type RegExpOrString as R, type NonObjectIdLikeDocument as S, type AlternativeType as T, type Condition as U, type RootFilterOperators as V, type WithoutId as W, type PongoFilterOperator as X, type $unset as Y, type $inc as Z, type $push as _, type PongoDocument as a, type PongoInsertOneResult as a0, type PongoInsertManyResult as a1, type PongoUpdateResult as a2, type PongoUpdateManyResult as a3, type PongoDeleteResult as a4, type PongoDeleteManyResult as a5, type DocumentHandler as a6, type PostgresDbClientOptions as a7, isPostgresClientOptions as a8, postgresDb as a9, pongoDbSchemaComponent as aa, 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 PongoCollectionSchema as h, type PongoDbSchema as i, type PongoClientSchema as j, type PongoDbWithSchema as k, type PongoClientWithSchema as l, proxyPongoDbWithSchema as m, proxyClientWithSchema as n, type PongoCollectionSchemaMetadata as o, pongoSchema as p, type PongoDbSchemaMetadata as q, type PongoClientSchemaMetadata as r, toClientSchemaMetadata as s, toDbSchemaMetadata as t, type PongoSchemaConfig as u, type PooledPongoClientOptions as v, type PongoClientOptions as w, pongoClient as x, clientToDbOptions as y, type PongoDbClientOptions as z };
|
|
@@ -195,10 +195,36 @@ interface PongoClientSchema<T extends Record<string, PongoDbSchema> = Record<str
|
|
|
195
195
|
type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {
|
|
196
196
|
[K in keyof T]: PongoCollection<T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument>;
|
|
197
197
|
};
|
|
198
|
+
type PongoDbWithSchema<T extends Record<string, PongoCollectionSchema>, ConnectorType extends string = string> = CollectionsMap<T> & PongoDb<ConnectorType>;
|
|
198
199
|
type DBsMap<T extends Record<string, PongoDbSchema>> = {
|
|
199
200
|
[K in keyof T]: CollectionsMap<T[K]['collections']>;
|
|
200
201
|
};
|
|
201
202
|
type PongoClientWithSchema<T extends PongoClientSchema> = DBsMap<T['dbs']> & PongoClient;
|
|
203
|
+
declare function pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(collections: T): PongoDbSchema<T>;
|
|
204
|
+
declare function pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(name: string, collections: T): PongoDbSchema<T>;
|
|
205
|
+
declare const pongoSchema: {
|
|
206
|
+
client: <T extends Record<string, PongoDbSchema>>(dbs: T) => PongoClientSchema<T>;
|
|
207
|
+
db: typeof pongoDbSchema;
|
|
208
|
+
collection: <T extends PongoDocument>(name: string) => PongoCollectionSchema<T>;
|
|
209
|
+
};
|
|
210
|
+
declare const proxyPongoDbWithSchema: <T extends Record<string, PongoCollectionSchema>, ConnectorType extends string = string>(pongoDb: PongoDb<ConnectorType>, dbSchema: PongoDbSchema<T>, collections: Map<string, PongoCollection<Document>>) => PongoDbWithSchema<T, ConnectorType>;
|
|
211
|
+
declare const proxyClientWithSchema: <TypedClientSchema extends PongoClientSchema>(client: PongoClient, schema: TypedClientSchema | undefined) => PongoClientWithSchema<TypedClientSchema>;
|
|
212
|
+
type PongoCollectionSchemaMetadata = {
|
|
213
|
+
name: string;
|
|
214
|
+
};
|
|
215
|
+
type PongoDbSchemaMetadata = {
|
|
216
|
+
name?: string | undefined;
|
|
217
|
+
collections: PongoCollectionSchemaMetadata[];
|
|
218
|
+
};
|
|
219
|
+
type PongoClientSchemaMetadata = {
|
|
220
|
+
databases: PongoDbSchemaMetadata[];
|
|
221
|
+
database: (name?: string) => PongoDbSchemaMetadata | undefined;
|
|
222
|
+
};
|
|
223
|
+
declare const toDbSchemaMetadata: <TypedDbSchema extends PongoDbSchema>(schema: TypedDbSchema) => PongoDbSchemaMetadata;
|
|
224
|
+
declare const toClientSchemaMetadata: <TypedClientSchema extends PongoClientSchema>(schema: TypedClientSchema) => PongoClientSchemaMetadata;
|
|
225
|
+
interface PongoSchemaConfig<TypedClientSchema extends PongoClientSchema = PongoClientSchema> {
|
|
226
|
+
schema: TypedClientSchema;
|
|
227
|
+
}
|
|
202
228
|
|
|
203
229
|
type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;
|
|
204
230
|
declare const isPostgresClientOptions: (options: PongoDbClientOptions) => options is PostgresDbClientOptions;
|
|
@@ -246,4 +272,4 @@ declare const clientToDbOptions: <DbClientOptions extends AllowedDbClientOptions
|
|
|
246
272
|
clientOptions: PongoClientOptions;
|
|
247
273
|
}) => DbClientOptions;
|
|
248
274
|
|
|
249
|
-
export { type $set as $, type AllowedDbClientOptions as A,
|
|
275
|
+
export { type $set as $, type AllowedDbClientOptions as A, getPongoDb as B, type CollectionsMap as C, type DBsMap as D, type PongoClient as E, type CollectionOperationOptions as F, type ObjectId as G, type HasId as H, type InferIdType as I, type EnhancedOmit as J, type WithId as K, type Document as L, type OptionalId as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredId as O, type PongoDb as P, type ObjectIdLike as Q, type RegExpOrString as R, type NonObjectIdLikeDocument as S, type AlternativeType as T, type Condition as U, type RootFilterOperators as V, type WithoutId as W, type PongoFilterOperator as X, type $unset as Y, type $inc as Z, type $push as _, type PongoDocument as a, type PongoInsertOneResult as a0, type PongoInsertManyResult as a1, type PongoUpdateResult as a2, type PongoUpdateManyResult as a3, type PongoDeleteResult as a4, type PongoDeleteManyResult as a5, type DocumentHandler as a6, type PostgresDbClientOptions as a7, isPostgresClientOptions as a8, postgresDb as a9, pongoDbSchemaComponent as aa, 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 PongoCollectionSchema as h, type PongoDbSchema as i, type PongoClientSchema as j, type PongoDbWithSchema as k, type PongoClientWithSchema as l, proxyPongoDbWithSchema as m, proxyClientWithSchema as n, type PongoCollectionSchemaMetadata as o, pongoSchema as p, type PongoDbSchemaMetadata as q, type PongoClientSchemaMetadata as r, toClientSchemaMetadata as s, toDbSchemaMetadata as t, type PongoSchemaConfig as u, type PooledPongoClientOptions as v, type PongoClientOptions as w, pongoClient as x, clientToDbOptions as y, type PongoDbClientOptions 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
|
|
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 _chunkYQPKY7LNcjs = require('./chunk-YQPKY7LN.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 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){return this.collection.handle(e.toString(),n)}};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=_chunkYQPKY7LNcjs.u.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 _chunkYQPKY7LNcjs.t.call(void 0, )}async withSession(e,n){let t=typeof e=="function"?e:n,i=_chunkYQPKY7LNcjs.t.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,
|
|
3
|
+
import { P as PongoDb, a6 as DocumentHandler, w as PongoClientOptions, b as PongoCollection } from './pongoClient-CajnU47o.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,
|
|
3
|
+
import { P as PongoDb, a6 as DocumentHandler, w as PongoClientOptions, b as PongoCollection } from './pongoClient-CajnU47o.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{
|
|
1
|
+
import{t as a,u as p}from"./chunk-UGDQF6CW.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 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){return this.collection.handle(e.toString(),n)}};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
package/dist/chunk-74UAYOAE.cjs
DELETED
|
@@ -1,14 +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 y=n=>Object.entries(n).map(([t,e])=>[t,e]);var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var M=(n,t,e)=>{let o=Object.keys(t.collections);for(let r of o)e.set(r,n.collection(r));return new Proxy(n,{get(r,c){return _nullishCoalesce(e.get(c), () => (r[c]))}})},R=(n,t)=>{if(!t)return n;let e=Object.keys(t.dbs);return new Proxy(n,{get(o,r){return e.includes(r)?n.db(_optionalChain([t, 'access', _2 => _2.dbs, 'access', _3 => _3[r], 'optionalAccess', _4 => _4.name])):o[r]}})},On= exports.b =n=>({name:n.name,collections:y(n.collections).map(t=>({name:t[1].name}))});var A=n=>n.connectorType===_dumbo.NodePostgresConnectorType,U= exports.f =n=>{let{connectionString:t,dbName:e}=n,o=_nullishCoalesce(e, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, t))),r=_dumbo.dumbo.call(void 0, {connectionString:t,...n.connectionOptions}),c=new Map,p={connectorType:n.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>r.close(),collection:u=>j({collectionName:u,db:p,pool:r,sqlBuilder:N(u),...n.schema?n.schema:{}}),transaction:()=>r.transaction(),withTransaction:u=>r.withTransaction(u),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongoDb",{components:[...c.values()].map(u=>u.schema.component)})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, r,[...c.values()].flatMap(u=>u.schema.component.migrations({connector:"PostgreSQL:pg"})))}},C=_optionalChain([n, 'optionalAccess', _5 => _5.schema, 'optionalAccess', _6 => _6.definition, 'optionalAccess', _7 => _7.dbs]);if(C){let u=y(C).map(P=>P[1]).find(P=>P.name===e||P.name===o);if(u)return M(p,u,c)}return p},Dn= exports.g =n=>{let t=n.length>0&&typeof n[0]=="string"?n.map(e=>_(e)):n;return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:db",{components:t})};var on=async(n,t)=>{let e=_optionalChain([t, 'optionalAccess', _8 => _8.session, 'optionalAccess', _9 => _9.transaction]);return!e||!e.isActive?null:await e.enlistDatabase(n)},W=async(n,t,e)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await on(n,t)), 'optionalAccess', async _10 => _10.execute]), async () => (e)),j= exports.h =({db:n,collectionName:t,pool:e,sqlBuilder:o,schema:r})=>{let c=e.execute,p=async(i,a)=>(await W(n,a,c)).command(i),C=async(i,a)=>(await W(n,a,c)).query(i),u=_optionalChain([r, 'optionalAccess', _11 => _11.autoMigration])!=="None",P=i=>(u=!1,_optionalChain([i, 'optionalAccess', _12 => _12.session])?p(o.createCollection(),i):p(o.createCollection())),g=i=>u?P(i):Promise.resolve(),T={dbName:n.databaseName,collectionName:t,createCollection:async i=>{await P(i)},insertOne:async(i,a)=>{await g(a);let s=_nullishCoalesce(i._id, () => (_uuid.v4.call(void 0, )));return(await p(o.insertOne({...i,_id:s}),a)).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async(i,a)=>{await g(a);let s=i.map(O=>({...O,_id:_nullishCoalesce(O._id, () => (_uuid.v4.call(void 0, )))})),l=await p(o.insertMany(s),a);return{acknowledged:l.rowCount===s.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:s.map(O=>O._id)}},updateOne:async(i,a,s)=>{await g(s);let l=await p(o.updateOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(i,a,s)=>{await g(s);let l=await p(o.replaceOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(i,a,s)=>{await g(s);let l=await p(o.updateMany(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async(i,a)=>{await g(a);let s=await p(o.deleteOne(_nullishCoalesce(i, () => ({}))),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async(i,a)=>{await g(a);let s=await p(o.deleteMany(_nullishCoalesce(i, () => ({}))),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async(i,a)=>(await g(a),await _asyncNullishCoalesce(await _asyncOptionalChain([(await C(o.findOne(_nullishCoalesce(i, () => ({}))),a)), 'access', async _13 => _13.rows, 'access', async _14 => _14[0], 'optionalAccess', async _15 => _15.data]), async () => (null))),findOneAndDelete:async(i,a)=>{await g(a);let s=await T.findOne(i,a);return s===null?null:(await T.deleteOne(i,a),s)},findOneAndReplace:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.replaceOne(i,a,s),l)},findOneAndUpdate:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.updateOne(i,a,s),l)},handle:async(i,a,s)=>{await g(s);let l={_id:i},O=await T.findOne(l,s),S=await a(O);if(!O&&S){let I={...S,_id:i};return await T.insertOne({...I,_id:i},s),I}return O&&!S?(await T.deleteOne(l,s),null):(O&&S&&await T.replaceOne(l,S,s),S)},find:async(i,a)=>(await g(a),(await C(o.find(_nullishCoalesce(i, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(i,a)=>{await g(a);let{count:s}=await _dumbo.single.call(void 0, C(o.countDocuments(_nullishCoalesce(i, () => ({})))));return s},drop:async i=>(await g(i),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await p(o.drop())), 'optionalAccess', async _16 => _16.rowCount]), async () => (0)))>0),rename:async(i,a)=>(await g(a),await p(o.rename(i)),t=i,T),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, e,o.migrations())}};return T},_= exports.i =n=>_dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:()=>x(n)});var B={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},L= exports.k ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},rn= exports.l =n=>n.startsWith("$"),J= exports.m =n=>Object.keys(n).some(rn);require('pg');var E=n=>{let{connectorType:t}=n;if(!A(n))throw new Error(`Unsupported db type: ${t}`);return U(n)};var K=n=>{let t=!1,e=!1,o=null,r=null;return{enlistDatabase:async c=>{if(r&&o!==c.databaseName)throw new Error("There's already other database assigned to transaction");return r&&o===c.databaseName||(o=c.databaseName,r=c.transaction(),await r.begin()),r},commit:async()=>{if(!r)throw new Error("No database transaction started!");if(!t){if(e)throw new Error("Transaction is not active!");t=!0,await r.commit(),r=null}},rollback:async c=>{if(!r)throw new Error("No database transaction started!");if(t)throw new Error("Cannot rollback commited transaction!");e||(e=!0,await r.rollback(c),r=null)},databaseName:o,isStarting:!1,isCommitted:t,get isActive(){return!t&&!e},get sqlExecutor(){if(r===null)throw new Error("No database transaction was started");return r.execute},options:n}};var w=n=>_optionalChain([n, 'optionalAccess', _17 => _17.isActive])===!0;function v(n){if(!w(n))throw new Error("No active transaction exists!")}function sn(n){if(w(n))throw new Error("Active transaction already exists!")}var Q=n=>{let t=_optionalChain([n, 'optionalAccess', _18 => _18.explicit])===!0,e=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _19 => _19.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,r=!1,c=g=>{sn(o),o=K(_nullishCoalesce(g, () => (e)))},p=async()=>{v(o),await o.commit()},C=async()=>{v(o),await o.rollback()},P={get hasEnded(){return r},explicit:t,defaultTransactionOptions:_nullishCoalesce(e, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return e.snapshotEnabled},endSession:async()=>{r||(r=!0,w(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>w(o),startTransaction:c,commitTransaction:p,abortTransaction:C,withTransaction:async(g,T)=>{c(T);try{let i=await g(P);return await p(),i}catch(i){throw await C(),i}}};return P};var Yn=(n,t={})=>{let e=new Map,o=E(H({connectionString:n,clientOptions:t}));e.set(o.databaseName,o);let r={connect:async()=>(await o.connect(),r),close:async()=>{for(let c of e.values())await c.close()},db:c=>c?_nullishCoalesce(e.get(c), () => (e.set(c,E(H({connectionString:n,dbName:c,clientOptions:t}))).get(c))):o,startSession:Q,withSession:async c=>{let p=Q();try{return await c(p)}finally{await p.endSession()}}};return R(r,_optionalChain([t, 'optionalAccess', _20 => _20.schema, 'optionalAccess', _21 => _21.definition]))},H= exports.r =n=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:n.connectionString,dbName:n.dbName,...n.clientOptions});var D=(n,t,e)=>{if(n==="_id")return cn(t,e);switch(t){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(X(n,e)),n,JSON.stringify(e));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${L[t]} %L`,`{${n.split(".").join(",")}}`,e);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${n.split(".").join(",")}}`,e.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "data #>> %L NOT IN (%s)",`{${n.split(".").join(",")}}`,e.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=y(e).map(([r,c])=>_dumbo.sql.call(void 0, '@."%s" == %s',r,JSON.stringify(c))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",n,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",JSON.stringify(X(n,e)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${n.split(".").join(",")}}`,e);default:throw new Error(`Unsupported operator: ${t}`)}},cn=(n,t)=>{switch(n){case"$eq":return _dumbo.sql.call(void 0, "_id = %L",t);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `_id ${L[n]} %L`,t);case"$in":return _dumbo.sql.call(void 0, "_id IN (%s)",t.map(e=>_dumbo.sql.call(void 0, "%L",e)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "_id NOT IN (%s)",t.map(e=>_dumbo.sql.call(void 0, "%L",e)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},X=(n,t)=>n.split(".").reverse().reduce((e,o)=>({[o]:e}),t);var z="AND",f=n=>Object.entries(n).map(([t,e])=>pn(e)?ln(t,e):D(t,"$eq",e)).join(` ${z} `),ln=(n,t)=>{let e=!J(t);return y(t).map(([o,r])=>e?D(`${n}.${o}`,B.$eq,r):D(n,o,r)).join(` ${z} `)},pn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);var $=n=>y(n).reduce((t,[e,o])=>{switch(e){case"$set":return gn(o,t);case"$unset":return dn(o,t);case"$inc":return un(o,t);case"$push":return mn(o,t);default:return t}},_dumbo.sql.call(void 0, "data")),gn=(n,t)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",t,JSON.stringify(n)),dn=(n,t)=>_dumbo.sql.call(void 0, "%s - %L",t,Object.keys(n).map(e=>`{${e}}`).join(", ")),un=(n,t)=>{for(let[e,o]of Object.entries(n))t=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",t,e,e,o);return t},mn=(n,t)=>{for(let[e,o]of Object.entries(n))t=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",t,e,e,JSON.stringify([o]));return t};var Y=n=>_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
|
-
)`,n),x= exports.c =n=>[_dumbo.sqlMigration.call(void 0, `pongoCollection:${n}:001:createtable`,[Y(n)])],N= exports.d =n=>({migrations:()=>x(n),createCollection:()=>Y(n),insertOne:t=>_dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES (%L, %L)",n,t._id,JSON.stringify(t)),insertMany:t=>{let e=t.map(o=>_dumbo.sql.call(void 0, "(%L, %L)",o._id,JSON.stringify(o))).join(", ");return _dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES %s",n,e)},updateOne:(t,e)=>{let o=f(t),r=$(e);return _dumbo.sql.call(void 0, `WITH cte AS (
|
|
11
|
-
SELECT _id FROM %I %s LIMIT 1
|
|
12
|
-
)
|
|
13
|
-
UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,n,b(o),n,r,n)},replaceOne:(t,e)=>{let o=f(t);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s",n,JSON.stringify(e),b(o))},updateMany:(t,e)=>{let o=f(t),r=$(e);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %s %s",n,r,b(o))},deleteOne:t=>{let e=f(t);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",n,b(e))},deleteMany:t=>{let e=f(t);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",n,b(e))},findOne:t=>{let e=f(t);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1",n,b(e))},find:t=>{let e=f(t);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s",n,b(e))},countDocuments:t=>{let e=f(t);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s",n,b(e))},rename:t=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I",n,t),drop:(t=n)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",t)}),b=n=>n.length>0?_dumbo.sql.call(void 0, "WHERE %s",n):_dumbo.rawSql.call(void 0, "");exports.a = y; exports.b = On; exports.c = x; exports.d = N; exports.e = A; exports.f = U; exports.g = Dn; exports.h = j; exports.i = _; exports.j = B; exports.k = L; exports.l = rn; exports.m = J; exports.n = E; exports.o = K; exports.p = Q; exports.q = Yn; exports.r = H;
|
|
14
|
-
//# sourceMappingURL=chunk-74UAYOAE.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/typing/entries.ts","../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/core/typing/schema.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts"],"names":["objectEntries","obj","key","value","proxyPongoDbWithSchema","pongoDb","dbSchema","collections","collectionNames","collectionName","target","prop","proxyClientWithSchema","client","schema","dbNames","toDbSchemaMetadata","c","isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","db","pongoCollection","postgresSQLBuilder","handle","schemaComponent","runPostgreSQLMigrations","dbsSchema","e","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","transaction","transactionExecutorOrDefault","defaultSqlExecutor","SqlFor","sqlExecutor","command","sql","query","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","byId","existing","newDoc","row","count","single","newName","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","hasOperators","getPongoDb","type"],"mappings":"AAQO,q0CAAMA,CAAAA,CAAmCC,CAAAA,EAC9C,MAAA,CAAO,OAAA,CAAQA,CAAG,CAAA,CAAE,GAAA,CAAI,CAAC,CAACC,CAAAA,CAAKC,CAAK,CAAA,CAAA,EAAM,CAACD,CAAAA,CAAgBC,CAAK,CAAC,CAAA,CCTnE,+CAMO,4BCOoB,ICuFdC,CAAAA,CAAyB,CAIpCC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAAA,EACwC,CACxC,IAAMC,CAAAA,CAAkB,MAAA,CAAO,IAAA,CAAKF,CAAAA,CAAS,WAAW,CAAA,CAExD,GAAA,CAAA,IAAWG,EAAAA,GAAkBD,CAAAA,CAC3BD,CAAAA,CAAY,GAAA,CAAIE,CAAAA,CAAgBJ,CAAAA,CAAQ,UAAA,CAAWI,CAAc,CAAC,CAAA,CAGpE,OAAO,IAAI,KAAA,CACTJ,CAAAA,CAGA,CACE,GAAA,CAAIK,CAAAA,CAAQC,CAAAA,CAAc,CACxB,wBAAOJ,CAAAA,CAAY,GAAA,CAAII,CAAI,CAAA,SAAKD,CAAAA,CAAOC,CAAI,GAC7C,CACF,CACF,CACF,CAAA,CAGaC,CAAAA,CAAwB,CAGnCC,CAAAA,CACAC,CAAAA,CAAAA,EAC6C,CAC7C,EAAA,CAAI,CAACA,CAAAA,CAAQ,OAAOD,CAAAA,CAEpB,IAAME,CAAAA,CAAU,MAAA,CAAO,IAAA,CAAKD,CAAAA,CAAO,GAAG,CAAA,CAEtC,OAAO,IAAI,KAAA,CACTD,CAAAA,CAGA,CACE,GAAA,CAAIH,CAAAA,CAAQC,CAAAA,CAAc,CACxB,OAAII,CAAAA,CAAQ,QAAA,CAASJ,CAAI,CAAA,CAAUE,CAAAA,CAAO,EAAA,i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AYOAE.cjs","sourcesContent":["type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const objectEntries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import {\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n type OptionalUnlessRequiredId,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\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: OptionalUnlessRequiredId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]): SQL => {\n const values = documents\n .map((doc) => sql('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n\n return sql(\n `UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s`,\n collectionName,\n JSON.stringify(document),\n where(filterQuery),\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s %s',\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\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 => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = 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 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 type CollectionOperationOptions,\n type DocumentHandler,\n type OptionalUnlessRequiredId,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithoutId,\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};\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}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async (sql: SQL, options?: CollectionOperationOptions) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).command(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: OptionalUnlessRequiredId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n\n const result = await command(\n SqlFor.insertOne({ ...document, _id } as OptionalUnlessRequiredId<T>),\n options,\n );\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (\n documents: OptionalUnlessRequiredId<T>[],\n options?: CollectionOperationOptions,\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 }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredId<T>[]),\n options,\n );\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id as string),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateOne(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(\n SqlFor.replaceOne(filter, document),\n options,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteOne(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as T | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<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?: CollectionOperationOptions,\n ): Promise<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?: CollectionOperationOptions,\n ): Promise<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?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = await collection.findOne(byId, options);\n\n const result = await handle(existing);\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredId<T>,\n options,\n );\n return newDoc;\n }\n\n if (existing && !result) {\n await collection.deleteOne(byId, options);\n return null;\n }\n\n if (existing && result)\n await collection.replaceOne(byId, result, options);\n\n return result;\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as 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 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: OptionalUnlessRequiredId<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]) => SQL;\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>) => SQL;\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n deleteOne: <T>(filter: PongoFilter<T>) => SQL;\n deleteMany: <T>(filter: PongoFilter<T>) => SQL;\n findOne: <T>(filter: PongoFilter<T>) => SQL;\n find: <T>(filter: PongoFilter<T>) => SQL;\n countDocuments: <T>(filter: PongoFilter<T>) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n","import { objectEntries } from './entries';\nimport {\n type Document,\n type PongoClient,\n type PongoCollection,\n type PongoDb,\n type PongoDocument,\n} from './operations';\n\nexport interface PongoCollectionSchema<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n T extends PongoDocument = PongoDocument,\n> {\n name: string;\n}\n\n// Database schema interface\nexport interface PongoDbSchema<\n T extends Record<string, PongoCollectionSchema> = Record<\n string,\n PongoCollectionSchema\n >,\n> {\n name?: string;\n collections: T;\n}\n\nexport interface PongoClientSchema<\n T extends Record<string, PongoDbSchema> = Record<string, PongoDbSchema>,\n> {\n dbs: T;\n}\n\nexport type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {\n [K in keyof T]: PongoCollection<\n T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument\n >;\n};\n\nexport type PongoDbWithSchema<\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n> = CollectionsMap<T> & PongoDb<ConnectorType>;\n\nexport type DBsMap<T extends Record<string, PongoDbSchema>> = {\n [K in keyof T]: CollectionsMap<T[K]['collections']>;\n};\n\nexport type PongoClientWithSchema<T extends PongoClientSchema> = DBsMap<\n T['dbs']\n> &\n PongoClient;\n\nconst pongoCollectionSchema = <T extends PongoDocument>(\n name: string,\n): PongoCollectionSchema<T> => ({\n name,\n});\n\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n name: string,\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n nameOrCollections: string | T,\n collections?: T | undefined,\n): PongoDbSchema<T> {\n if (collections === undefined) {\n if (typeof nameOrCollections === 'string') {\n throw new Error('You need to provide colleciton definition');\n }\n return {\n collections: nameOrCollections,\n };\n }\n\n return nameOrCollections && typeof nameOrCollections === 'string'\n ? {\n name: nameOrCollections,\n collections,\n }\n : { collections: collections };\n}\n\nconst pongoClientSchema = <T extends Record<string, PongoDbSchema>>(\n dbs: T,\n): PongoClientSchema<T> => ({\n dbs,\n});\n\nexport const pongoSchema = {\n client: pongoClientSchema,\n db: pongoDbSchema,\n collection: pongoCollectionSchema,\n};\n\n// Factory function to create DB instances\nexport const proxyPongoDbWithSchema = <\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n>(\n pongoDb: PongoDb<ConnectorType>,\n dbSchema: PongoDbSchema<T>,\n collections: Map<string, PongoCollection<Document>>,\n): PongoDbWithSchema<T, ConnectorType> => {\n const collectionNames = Object.keys(dbSchema.collections);\n\n for (const collectionName of collectionNames) {\n collections.set(collectionName, pongoDb.collection(collectionName));\n }\n\n return new Proxy(\n pongoDb as PongoDb<ConnectorType> & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n return collections.get(prop) ?? target[prop];\n },\n },\n ) as PongoDbWithSchema<T, ConnectorType>;\n};\n\n// Factory function to create Client instances\nexport const proxyClientWithSchema = <\n TypedClientSchema extends PongoClientSchema,\n>(\n client: PongoClient,\n schema: TypedClientSchema | undefined,\n): PongoClientWithSchema<TypedClientSchema> => {\n if (!schema) return client as PongoClientWithSchema<TypedClientSchema>;\n\n const dbNames = Object.keys(schema.dbs);\n\n return new Proxy(\n client as PongoClient & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n if (dbNames.includes(prop)) return client.db(schema.dbs[prop]?.name);\n\n return target[prop];\n },\n },\n ) as PongoClientWithSchema<TypedClientSchema>;\n};\n\nexport type PongoCollectionSchemaMetadata = {\n name: string;\n};\n\nexport type PongoDbSchemaMetadata = {\n name?: string | undefined;\n collections: PongoCollectionSchemaMetadata[];\n};\n\nexport type PongoClientSchemaMetadata = {\n databases: PongoDbSchemaMetadata[];\n database: (name?: string) => PongoDbSchemaMetadata | undefined;\n};\n\nexport const toDbSchemaMetadata = <TypedDbSchema extends PongoDbSchema>(\n schema: TypedDbSchema,\n): PongoDbSchemaMetadata => ({\n name: schema.name,\n collections: objectEntries(schema.collections).map((c) => ({\n name: c[1].name,\n })),\n});\n\nexport const toClientSchemaMetadata = <\n TypedClientSchema extends PongoClientSchema,\n>(\n schema: TypedClientSchema,\n): PongoClientSchemaMetadata => {\n const databases = objectEntries(schema.dbs).map((e) =>\n toDbSchemaMetadata(e[1]),\n );\n\n return {\n databases,\n database: (name) => databases.find((db) => db.name === name),\n };\n};\n","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 type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { proxyPongoDbWithSchema } from '../core/typing/schema';\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 }),\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","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 type { PongoClient, PongoDb, PongoSession } from './typing/operations';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './typing/schema';\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 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"]}
|
package/dist/chunk-JEFOWKG5.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
var y=n=>Object.entries(n).map(([t,e])=>[t,e]);import{rawSql as Tn,sql as m,sqlMigration as Pn}from"@event-driven-io/dumbo";import{runPostgreSQLMigrations as tn,schemaComponent as q,single as en}from"@event-driven-io/dumbo";import{v4 as F}from"uuid";import{dumbo as V,getDatabaseNameOrDefault as Z,NodePostgresConnectorType as G,runPostgreSQLMigrations as nn,schemaComponent as k}from"@event-driven-io/dumbo";var M=(n,t,e)=>{let o=Object.keys(t.collections);for(let r of o)e.set(r,n.collection(r));return new Proxy(n,{get(r,c){return e.get(c)??r[c]}})},R=(n,t)=>{if(!t)return n;let e=Object.keys(t.dbs);return new Proxy(n,{get(o,r){return e.includes(r)?n.db(t.dbs[r]?.name):o[r]}})},On=n=>({name:n.name,collections:y(n.collections).map(t=>({name:t[1].name}))});var A=n=>n.connectorType===G,U=n=>{let{connectionString:t,dbName:e}=n,o=e??Z(t),r=V({connectionString:t,...n.connectionOptions}),c=new Map,p={connectorType:n.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>r.close(),collection:u=>j({collectionName:u,db:p,pool:r,sqlBuilder:N(u),...n.schema?n.schema:{}}),transaction:()=>r.transaction(),withTransaction:u=>r.withTransaction(u),schema:{get component(){return k("pongoDb",{components:[...c.values()].map(u=>u.schema.component)})},migrate:()=>nn(r,[...c.values()].flatMap(u=>u.schema.component.migrations({connector:"PostgreSQL:pg"})))}},C=n?.schema?.definition?.dbs;if(C){let u=y(C).map(P=>P[1]).find(P=>P.name===e||P.name===o);if(u)return M(p,u,c)}return p},Dn=n=>{let t=n.length>0&&typeof n[0]=="string"?n.map(e=>_(e)):n;return k("pongo:schema_component:db",{components:t})};var on=async(n,t)=>{let e=t?.session?.transaction;return!e||!e.isActive?null:await e.enlistDatabase(n)},W=async(n,t,e)=>(await on(n,t))?.execute??e,j=({db:n,collectionName:t,pool:e,sqlBuilder:o,schema:r})=>{let c=e.execute,p=async(i,a)=>(await W(n,a,c)).command(i),C=async(i,a)=>(await W(n,a,c)).query(i),u=r?.autoMigration!=="None",P=i=>(u=!1,i?.session?p(o.createCollection(),i):p(o.createCollection())),g=i=>u?P(i):Promise.resolve(),T={dbName:n.databaseName,collectionName:t,createCollection:async i=>{await P(i)},insertOne:async(i,a)=>{await g(a);let s=i._id??F();return(await p(o.insertOne({...i,_id:s}),a)).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async(i,a)=>{await g(a);let s=i.map(O=>({...O,_id:O._id??F()})),l=await p(o.insertMany(s),a);return{acknowledged:l.rowCount===s.length,insertedCount:l.rowCount??0,insertedIds:s.map(O=>O._id)}},updateOne:async(i,a,s)=>{await g(s);let l=await p(o.updateOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(i,a,s)=>{await g(s);let l=await p(o.replaceOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(i,a,s)=>{await g(s);let l=await p(o.updateMany(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async(i,a)=>{await g(a);let s=await p(o.deleteOne(i??{}),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async(i,a)=>{await g(a);let s=await p(o.deleteMany(i??{}),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async(i,a)=>(await g(a),(await C(o.findOne(i??{}),a)).rows[0]?.data??null),findOneAndDelete:async(i,a)=>{await g(a);let s=await T.findOne(i,a);return s===null?null:(await T.deleteOne(i,a),s)},findOneAndReplace:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.replaceOne(i,a,s),l)},findOneAndUpdate:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.updateOne(i,a,s),l)},handle:async(i,a,s)=>{await g(s);let l={_id:i},O=await T.findOne(l,s),S=await a(O);if(!O&&S){let I={...S,_id:i};return await T.insertOne({...I,_id:i},s),I}return O&&!S?(await T.deleteOne(l,s),null):(O&&S&&await T.replaceOne(l,S,s),S)},find:async(i,a)=>(await g(a),(await C(o.find(i??{}))).rows.map(l=>l.data)),countDocuments:async(i,a)=>{await g(a);let{count:s}=await en(C(o.countDocuments(i??{})));return s},drop:async i=>(await g(i),((await p(o.drop()))?.rowCount??0)>0),rename:async(i,a)=>(await g(a),await p(o.rename(i)),t=i,T),schema:{get component(){return q("pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>tn(e,o.migrations())}};return T},_=n=>q("pongo:schema_component:collection",{migrations:()=>x(n)});var B={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},L={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},rn=n=>n.startsWith("$"),J=n=>Object.keys(n).some(rn);import{NodePostgresConnectorType as an}from"@event-driven-io/dumbo";import"pg";var E=n=>{let{connectorType:t}=n;if(!A(n))throw new Error(`Unsupported db type: ${t}`);return U(n)};var K=n=>{let t=!1,e=!1,o=null,r=null;return{enlistDatabase:async c=>{if(r&&o!==c.databaseName)throw new Error("There's already other database assigned to transaction");return r&&o===c.databaseName||(o=c.databaseName,r=c.transaction(),await r.begin()),r},commit:async()=>{if(!r)throw new Error("No database transaction started!");if(!t){if(e)throw new Error("Transaction is not active!");t=!0,await r.commit(),r=null}},rollback:async c=>{if(!r)throw new Error("No database transaction started!");if(t)throw new Error("Cannot rollback commited transaction!");e||(e=!0,await r.rollback(c),r=null)},databaseName:o,isStarting:!1,isCommitted:t,get isActive(){return!t&&!e},get sqlExecutor(){if(r===null)throw new Error("No database transaction was started");return r.execute},options:n}};var w=n=>n?.isActive===!0;function v(n){if(!w(n))throw new Error("No active transaction exists!")}function sn(n){if(w(n))throw new Error("Active transaction already exists!")}var Q=n=>{let t=n?.explicit===!0,e=n?.defaultTransactionOptions??{get snapshotEnabled(){return!1}},o=null,r=!1,c=g=>{sn(o),o=K(g??e)},p=async()=>{v(o),await o.commit()},C=async()=>{v(o),await o.rollback()},P={get hasEnded(){return r},explicit:t,defaultTransactionOptions:e??{get snapshotEnabled(){return!1}},get transaction(){return o},get snapshotEnabled(){return e.snapshotEnabled},endSession:async()=>{r||(r=!0,w(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>w(o),startTransaction:c,commitTransaction:p,abortTransaction:C,withTransaction:async(g,T)=>{c(T);try{let i=await g(P);return await p(),i}catch(i){throw await C(),i}}};return P};var Yn=(n,t={})=>{let e=new Map,o=E(H({connectionString:n,clientOptions:t}));e.set(o.databaseName,o);let r={connect:async()=>(await o.connect(),r),close:async()=>{for(let c of e.values())await c.close()},db:c=>c?e.get(c)??e.set(c,E(H({connectionString:n,dbName:c,clientOptions:t}))).get(c):o,startSession:Q,withSession:async c=>{let p=Q();try{return await c(p)}finally{await p.endSession()}}};return R(r,t?.schema?.definition)},H=n=>({connectorType:an,connectionString:n.connectionString,dbName:n.dbName,...n.clientOptions});import{sql as d}from"@event-driven-io/dumbo";var D=(n,t,e)=>{if(n==="_id")return cn(t,e);switch(t){case"$eq":return d("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(X(n,e)),n,JSON.stringify(e));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`data #>> %L ${L[t]} %L`,`{${n.split(".").join(",")}}`,e);case"$in":return d("data #>> %L IN (%s)",`{${n.split(".").join(",")}}`,e.map(o=>d("%L",o)).join(", "));case"$nin":return d("data #>> %L NOT IN (%s)",`{${n.split(".").join(",")}}`,e.map(o=>d("%L",o)).join(", "));case"$elemMatch":{let o=y(e).map(([r,c])=>d('@."%s" == %s',r,JSON.stringify(c))).join(" && ");return d("jsonb_path_exists(data, '$.%s[*] ? (%s)')",n,o)}case"$all":return d("data @> %L::jsonb",JSON.stringify(X(n,e)));case"$size":return d("jsonb_array_length(data #> %L) = %L",`{${n.split(".").join(",")}}`,e);default:throw new Error(`Unsupported operator: ${t}`)}},cn=(n,t)=>{switch(n){case"$eq":return d("_id = %L",t);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`_id ${L[n]} %L`,t);case"$in":return d("_id IN (%s)",t.map(e=>d("%L",e)).join(", "));case"$nin":return d("_id NOT IN (%s)",t.map(e=>d("%L",e)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},X=(n,t)=>n.split(".").reverse().reduce((e,o)=>({[o]:e}),t);var z="AND",f=n=>Object.entries(n).map(([t,e])=>pn(e)?ln(t,e):D(t,"$eq",e)).join(` ${z} `),ln=(n,t)=>{let e=!J(t);return y(t).map(([o,r])=>e?D(`${n}.${o}`,B.$eq,r):D(n,o,r)).join(` ${z} `)},pn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);import{sql as h}from"@event-driven-io/dumbo";var $=n=>y(n).reduce((t,[e,o])=>{switch(e){case"$set":return gn(o,t);case"$unset":return dn(o,t);case"$inc":return un(o,t);case"$push":return mn(o,t);default:return t}},h("data")),gn=(n,t)=>h("%s || %L::jsonb",t,JSON.stringify(n)),dn=(n,t)=>h("%s - %L",t,Object.keys(n).map(e=>`{${e}}`).join(", ")),un=(n,t)=>{for(let[e,o]of Object.entries(n))t=h("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",t,e,e,o);return t},mn=(n,t)=>{for(let[e,o]of Object.entries(n))t=h("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",t,e,e,JSON.stringify([o]));return t};var Y=n=>m(`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
|
-
)`,n),x=n=>[Pn(`pongoCollection:${n}:001:createtable`,[Y(n)])],N=n=>({migrations:()=>x(n),createCollection:()=>Y(n),insertOne:t=>m("INSERT INTO %I (_id, data) VALUES (%L, %L)",n,t._id,JSON.stringify(t)),insertMany:t=>{let e=t.map(o=>m("(%L, %L)",o._id,JSON.stringify(o))).join(", ");return m("INSERT INTO %I (_id, data) VALUES %s",n,e)},updateOne:(t,e)=>{let o=f(t),r=$(e);return m(`WITH cte AS (
|
|
11
|
-
SELECT _id FROM %I %s LIMIT 1
|
|
12
|
-
)
|
|
13
|
-
UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,n,b(o),n,r,n)},replaceOne:(t,e)=>{let o=f(t);return m("UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s",n,JSON.stringify(e),b(o))},updateMany:(t,e)=>{let o=f(t),r=$(e);return m("UPDATE %I SET data = %s %s",n,r,b(o))},deleteOne:t=>{let e=f(t);return m("DELETE FROM %I %s",n,b(e))},deleteMany:t=>{let e=f(t);return m("DELETE FROM %I %s",n,b(e))},findOne:t=>{let e=f(t);return m("SELECT data FROM %I %s LIMIT 1",n,b(e))},find:t=>{let e=f(t);return m("SELECT data FROM %I %s",n,b(e))},countDocuments:t=>{let e=f(t);return m("SELECT COUNT(1) as count FROM %I %s",n,b(e))},rename:t=>m("ALTER TABLE %I RENAME TO %I",n,t),drop:(t=n)=>m("DROP TABLE IF EXISTS %I",t)}),b=n=>n.length>0?m("WHERE %s",n):Tn("");export{y as a,On as b,x as c,N as d,A as e,U as f,Dn as g,j as h,_ as i,B as j,L as k,rn as l,J as m,E as n,K as o,Q as p,Yn as q,H as r};
|
|
14
|
-
//# sourceMappingURL=chunk-JEFOWKG5.js.map
|