@event-driven-io/pongo 0.2.4 → 0.4.0

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/index.d.cts CHANGED
@@ -1,5 +1,58 @@
1
- import { Document, Collection as Collection$1, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId as WithId$1, 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';
2
1
  import pg from 'pg';
2
+ import { Document, Collection as Collection$1, ObjectId as ObjectId$1, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId as WithoutId$1, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId as WithId$1, 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 { SQL } from '@event-driven-io/dumbo';
4
+
5
+ type PongoClientOptions = {
6
+ connectionString: string;
7
+ dbName?: string | undefined;
8
+ client?: pg.PoolClient;
9
+ };
10
+ declare const postgresClient: (options: PongoClientOptions) => DbClient;
11
+
12
+ declare const Operators: {
13
+ $eq: string;
14
+ $gt: string;
15
+ $gte: string;
16
+ $lt: string;
17
+ $lte: string;
18
+ $ne: string;
19
+ $in: string;
20
+ $nin: string;
21
+ $elemMatch: string;
22
+ $all: string;
23
+ $size: string;
24
+ };
25
+ declare const isOperator: (key: string) => boolean;
26
+ declare const hasOperators: (value: Record<string, unknown>) => boolean;
27
+ declare const handleOperator: (path: string, operator: string, value: unknown) => string;
28
+
29
+ declare const constructFilterQuery: <T>(filter: PongoFilter<T>) => string;
30
+
31
+ declare const postgresCollection: <T extends PongoDocument>(collectionName: string, { dbName, poolOrClient: clientOrPool, }: {
32
+ dbName: string;
33
+ poolOrClient: pg.Pool | pg.PoolClient;
34
+ }) => PongoCollection<T>;
35
+ declare const collectionSQLBuilder: (collectionName: string) => {
36
+ createCollection: () => SQL;
37
+ insertOne: <T>(document: WithId<T>) => SQL;
38
+ insertMany: <T_1>(documents: WithId<T_1>[]) => SQL;
39
+ updateOne: <T_2>(filter: PongoFilter<T_2>, update: PongoUpdate<T_2>) => SQL;
40
+ replaceOne: <T_3>(filter: PongoFilter<T_3>, document: WithoutId<T_3>) => SQL;
41
+ updateMany: <T_4>(filter: PongoFilter<T_4>, update: PongoUpdate<T_4>) => SQL;
42
+ deleteOne: <T_5>(filter: PongoFilter<T_5>) => SQL;
43
+ deleteMany: <T_6>(filter: PongoFilter<T_6>) => SQL;
44
+ findOne: <T_7>(filter: PongoFilter<T_7>) => SQL;
45
+ find: <T_8>(filter: PongoFilter<T_8>) => SQL;
46
+ countDocuments: <T_9>(filter: PongoFilter<T_9>) => SQL;
47
+ rename: (newName: string) => SQL;
48
+ drop: (targetName?: string) => SQL;
49
+ };
50
+
51
+ declare const buildUpdateQuery: <T>(update: PongoUpdate<T>) => SQL;
52
+ declare const buildSetQuery: <T>(set: $set<T>, currentUpdateQuery: SQL) => SQL;
53
+ declare const buildUnsetQuery: <T>(unset: $unset<T>, currentUpdateQuery: SQL) => SQL;
54
+ declare const buildIncQuery: <T>(inc: $inc<T>, currentUpdateQuery: SQL) => SQL;
55
+ declare const buildPushQuery: <T>(push: $push<T>, currentUpdateQuery: SQL) => SQL;
3
56
 
4
57
  interface PongoClient {
5
58
  connect(): Promise<this>;
@@ -7,23 +60,34 @@ interface PongoClient {
7
60
  db(dbName?: string): PongoDb;
8
61
  }
9
62
  interface PongoDb {
10
- collection<T>(name: string): PongoCollection<T>;
63
+ collection<T extends PongoDocument>(name: string): PongoCollection<T>;
11
64
  }
12
- interface PongoCollection<T> {
65
+ interface PongoCollection<T extends PongoDocument> {
66
+ readonly dbName: string;
67
+ readonly collectionName: string;
13
68
  createCollection(): Promise<void>;
14
69
  insertOne(document: T): Promise<PongoInsertOneResult>;
15
70
  insertMany(documents: T[]): Promise<PongoInsertManyResult>;
16
71
  updateOne(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<PongoUpdateResult>;
72
+ replaceOne(filter: PongoFilter<T>, document: WithoutId<T>): Promise<PongoUpdateResult>;
17
73
  updateMany(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<PongoUpdateResult>;
18
- deleteOne(filter: PongoFilter<T>): Promise<PongoDeleteResult>;
19
- deleteMany(filter: PongoFilter<T>): Promise<PongoDeleteResult>;
20
- findOne(filter: PongoFilter<T>): Promise<T | null>;
21
- find(filter: PongoFilter<T>): Promise<T[]>;
74
+ deleteOne(filter?: PongoFilter<T>): Promise<PongoDeleteResult>;
75
+ deleteMany(filter?: PongoFilter<T>): Promise<PongoDeleteResult>;
76
+ findOne(filter?: PongoFilter<T>): Promise<T | null>;
77
+ find(filter?: PongoFilter<T>): Promise<T[]>;
78
+ findOneAndDelete(filter: PongoFilter<T>): Promise<T | null>;
79
+ findOneAndReplace(filter: PongoFilter<T>, replacement: WithoutId<T>): Promise<T | null>;
80
+ findOneAndUpdate(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<T | null>;
81
+ countDocuments(filter?: PongoFilter<T>): Promise<number>;
82
+ drop(): Promise<boolean>;
83
+ rename(newName: string): Promise<PongoCollection<T>>;
84
+ handle(id: string, handle: DocumentHandler<T>): Promise<T | null>;
22
85
  }
23
86
  type HasId = {
24
87
  _id: string;
25
88
  };
26
89
  type WithId<T> = T & HasId;
90
+ type WithoutId<T> = Omit<T, '_id'>;
27
91
  type PongoFilter<T> = {
28
92
  [P in keyof T]?: T[P] | PongoFilterOperator<T[P]>;
29
93
  } | HasId;
@@ -78,15 +142,17 @@ interface PongoDeleteManyResult {
78
142
  acknowledged: boolean;
79
143
  deletedCount: number;
80
144
  }
81
-
82
- declare const pongoClient: (connectionString: string) => PongoClient;
145
+ type PongoDocument = Record<string, unknown>;
146
+ type DocumentHandler<T extends PongoDocument> = ((document: T | null) => T | null) | ((document: T | null) => Promise<T | null>);
83
147
 
84
148
  interface DbClient {
85
149
  connect(): Promise<void>;
86
150
  close(): Promise<void>;
87
- collection: <T>(name: string) => PongoCollection<T>;
151
+ collection: <T extends PongoDocument>(name: string) => PongoCollection<T>;
88
152
  }
89
- declare const getDbClient: (connectionString: string, database?: string) => DbClient;
153
+ declare const getDbClient: (options: PongoClientOptions) => DbClient;
154
+
155
+ declare const pongoClient: (connectionString: string) => PongoClient;
90
156
 
91
157
  type Entry<T> = {
92
158
  [K in keyof Required<T>]: [K, Required<T>[K]];
@@ -114,7 +180,9 @@ declare class FindCursor<T> {
114
180
  declare class Db {
115
181
  private pongoDb;
116
182
  constructor(pongoDb: PongoDb);
117
- collection<T extends Document>(collectionName: string): Collection$1<T>;
183
+ collection<T extends Document>(collectionName: string): Collection$1<T> & {
184
+ handle(id: ObjectId$1, handle: DocumentHandler<T>): Promise<T | null>;
185
+ };
118
186
  }
119
187
 
120
188
  declare class MongoClient {
@@ -141,11 +209,11 @@ declare class Collection<T extends Document> implements Collection$1<T> {
141
209
  insertMany(docs: OptionalUnlessRequiredId<T>[], _options?: BulkWriteOptions | undefined): Promise<InsertManyResult<T>>;
142
210
  bulkWrite(_operations: AnyBulkWriteOperation<T>[], _options?: BulkWriteOptions | undefined): Promise<BulkWriteResult>;
143
211
  updateOne(filter: Filter<T>, update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
144
- replaceOne(_filter: Filter<T>, _: WithoutId<T>, _options?: ReplaceOptions | undefined): Promise<Document | UpdateResult<T>>;
212
+ replaceOne(filter: Filter<T>, document: WithoutId$1<T>, _options?: ReplaceOptions | undefined): Promise<Document | UpdateResult<T>>;
145
213
  updateMany(filter: Filter<T>, update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
146
214
  deleteOne(filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
147
215
  deleteMany(filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
148
- rename(_newName: string, _options?: RenameOptions | undefined): Promise<Collection<Document>>;
216
+ rename(newName: string, _options?: RenameOptions | undefined): Promise<Collection<Document>>;
149
217
  drop(_options?: DropCollectionOptions | undefined): Promise<boolean>;
150
218
  findOne(): Promise<WithId$1<T> | null>;
151
219
  findOne(filter: Filter<T>): Promise<WithId$1<T> | null>;
@@ -173,7 +241,7 @@ declare class Collection<T extends Document> implements Collection$1<T> {
173
241
  indexInformation(options: IndexInformationOptions): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;
174
242
  indexInformation(): Promise<IndexDescriptionCompact>;
175
243
  estimatedDocumentCount(_options?: EstimatedDocumentCountOptions | undefined): Promise<number>;
176
- countDocuments(_filter?: Filter<T> | undefined, _options?: CountDocumentsOptions | undefined): Promise<number>;
244
+ countDocuments(filter?: Filter<T> | undefined, _options?: CountDocumentsOptions | undefined): Promise<number>;
177
245
  distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key): Promise<Flatten<WithId$1<T>[Key]>[]>;
178
246
  distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>): Promise<Flatten<WithId$1<T>[Key]>[]>;
179
247
  distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>, options: CommandOperationOptions): Promise<Flatten<WithId$1<T>[Key]>[]>;
@@ -196,14 +264,14 @@ declare class Collection<T extends Document> implements Collection$1<T> {
196
264
  }): Promise<WithId$1<T> | null>;
197
265
  findOneAndDelete(filter: Filter<T>, options: FindOneAndDeleteOptions): Promise<WithId$1<T> | null>;
198
266
  findOneAndDelete(filter: Filter<T>): Promise<WithId$1<T> | null>;
199
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions & {
267
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId$1<T>, options: FindOneAndReplaceOptions & {
200
268
  includeResultMetadata: true;
201
269
  }): Promise<ModifyResult<T>>;
202
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions & {
270
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId$1<T>, options: FindOneAndReplaceOptions & {
203
271
  includeResultMetadata: false;
204
272
  }): Promise<WithId$1<T> | null>;
205
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions): Promise<WithId$1<T> | null>;
206
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>): Promise<WithId$1<T> | null>;
273
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId$1<T>, options: FindOneAndReplaceOptions): Promise<WithId$1<T> | null>;
274
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId$1<T>): Promise<WithId$1<T> | null>;
207
275
  findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions & {
208
276
  includeResultMetadata: true;
209
277
  }): Promise<ModifyResult<T>>;
@@ -216,7 +284,7 @@ declare class Collection<T extends Document> implements Collection$1<T> {
216
284
  watch<TLocal extends Document = T, TChange extends Document = ChangeStreamDocument<TLocal>>(_pipeline?: Document[] | undefined, _options?: ChangeStreamOptions | undefined): ChangeStream<TLocal, TChange>;
217
285
  initializeUnorderedBulkOp(_options?: BulkWriteOptions | undefined): UnorderedBulkOperation;
218
286
  initializeOrderedBulkOp(_options?: BulkWriteOptions | undefined): OrderedBulkOperation;
219
- count(_filter?: Filter<T> | undefined, _options?: CountOptions | undefined): Promise<number>;
287
+ count(filter?: Filter<T> | undefined, _options?: CountOptions | undefined): Promise<number>;
220
288
  listSearchIndexes(options?: ListSearchIndexesOptions | undefined): ListSearchIndexesCursor;
221
289
  listSearchIndexes(name: string, options?: ListSearchIndexesOptions | undefined): ListSearchIndexesCursor;
222
290
  createSearchIndex(_description: SearchIndexDescription): Promise<string>;
@@ -224,62 +292,11 @@ declare class Collection<T extends Document> implements Collection$1<T> {
224
292
  dropSearchIndex(_name: string): Promise<void>;
225
293
  updateSearchIndex(_name: string, _definition: Document): Promise<void>;
226
294
  createCollection(): Promise<void>;
295
+ handle(id: ObjectId$1, handle: DocumentHandler<T>): Promise<T | null>;
227
296
  }
228
297
 
229
298
  type ObjectId = string & {
230
299
  __brandId: 'ObjectId';
231
300
  };
232
301
 
233
- declare const postgresClient: (connectionString: string, database?: string) => DbClient;
234
-
235
- type SQL = string & {
236
- __brand: 'sql';
237
- };
238
- declare const sql: (sqlQuery: string, ...params: unknown[]) => SQL;
239
-
240
- declare const execute: <Result = void>(pool: pg.Pool, handle: (client: pg.PoolClient) => Promise<Result>) => Promise<Result>;
241
- declare const executeSQL: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool, sql: SQL) => Promise<pg.QueryResult<Result>>;
242
-
243
- declare const Operators: {
244
- $eq: string;
245
- $gt: string;
246
- $gte: string;
247
- $lt: string;
248
- $lte: string;
249
- $ne: string;
250
- $in: string;
251
- $nin: string;
252
- $elemMatch: string;
253
- $all: string;
254
- $size: string;
255
- };
256
- declare const isOperator: (key: string) => boolean;
257
- declare const hasOperators: (value: Record<string, unknown>) => boolean;
258
- declare const handleOperator: (path: string, operator: string, value: unknown) => string;
259
-
260
- declare const constructFilterQuery: <T>(filter: PongoFilter<T>) => string;
261
-
262
- declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
263
- declare const endPool: (connectionString: string) => Promise<void>;
264
- declare const endAllPools: () => Promise<void[]>;
265
-
266
- declare const postgresCollection: <T>(collectionName: string, pool: pg.Pool) => PongoCollection<T>;
267
- declare const collectionSQLBuilder: (collectionName: string) => {
268
- createCollection: () => SQL;
269
- insertOne: <T>(document: WithId<T>) => SQL;
270
- insertMany: <T_1>(documents: WithId<T_1>[]) => SQL;
271
- updateOne: <T_2>(filter: PongoFilter<T_2>, update: PongoUpdate<T_2>) => SQL;
272
- updateMany: <T_3>(filter: PongoFilter<T_3>, update: PongoUpdate<T_3>) => SQL;
273
- deleteOne: <T_4>(filter: PongoFilter<T_4>) => SQL;
274
- deleteMany: <T_5>(filter: PongoFilter<T_5>) => SQL;
275
- findOne: <T_6>(filter: PongoFilter<T_6>) => SQL;
276
- find: <T_7>(filter: PongoFilter<T_7>) => SQL;
277
- };
278
-
279
- declare const buildUpdateQuery: <T>(update: PongoUpdate<T>) => SQL;
280
- declare const buildSetQuery: <T>(set: $set<T>, currentUpdateQuery: SQL) => SQL;
281
- declare const buildUnsetQuery: <T>(unset: $unset<T>, currentUpdateQuery: SQL) => SQL;
282
- declare const buildIncQuery: <T>(inc: $inc<T>, currentUpdateQuery: SQL) => SQL;
283
- declare const buildPushQuery: <T>(push: $push<T>, currentUpdateQuery: SQL) => SQL;
284
-
285
- export { type $inc, type $push, type $set, type $unset, Collection, Db, type DbClient, FindCursor, type HasId, MongoClient, type NonPartial, type ObjectId, Operators, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteManyResult, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertManyResult, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateManyResult, type PongoUpdateResult, type SQL, type WithId, buildIncQuery, buildPushQuery, buildSetQuery, buildUnsetQuery, buildUpdateQuery, collectionSQLBuilder, constructFilterQuery, endAllPools, endPool, entries, execute, executeSQL, getDbClient, getPool, handleOperator, hasOperators, isOperator, pongoClient, postgresClient, postgresCollection, sql };
302
+ export { type $inc, type $push, type $set, type $unset, Collection, Db, type DbClient, type DocumentHandler, FindCursor, type HasId, MongoClient, type NonPartial, type ObjectId, Operators, type PongoClient, type PongoClientOptions, type PongoCollection, type PongoDb, type PongoDeleteManyResult, type PongoDeleteResult, type PongoDocument, type PongoFilter, type PongoFilterOperator, type PongoInsertManyResult, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateManyResult, type PongoUpdateResult, type WithId, type WithoutId, buildIncQuery, buildPushQuery, buildSetQuery, buildUnsetQuery, buildUpdateQuery, collectionSQLBuilder, constructFilterQuery, entries, getDbClient, handleOperator, hasOperators, isOperator, pongoClient, postgresClient, postgresCollection };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,58 @@
1
- import { Document, Collection as Collection$1, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId as WithId$1, 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';
2
1
  import pg from 'pg';
2
+ import { Document, Collection as Collection$1, ObjectId as ObjectId$1, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId as WithoutId$1, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId as WithId$1, 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 { SQL } from '@event-driven-io/dumbo';
4
+
5
+ type PongoClientOptions = {
6
+ connectionString: string;
7
+ dbName?: string | undefined;
8
+ client?: pg.PoolClient;
9
+ };
10
+ declare const postgresClient: (options: PongoClientOptions) => DbClient;
11
+
12
+ declare const Operators: {
13
+ $eq: string;
14
+ $gt: string;
15
+ $gte: string;
16
+ $lt: string;
17
+ $lte: string;
18
+ $ne: string;
19
+ $in: string;
20
+ $nin: string;
21
+ $elemMatch: string;
22
+ $all: string;
23
+ $size: string;
24
+ };
25
+ declare const isOperator: (key: string) => boolean;
26
+ declare const hasOperators: (value: Record<string, unknown>) => boolean;
27
+ declare const handleOperator: (path: string, operator: string, value: unknown) => string;
28
+
29
+ declare const constructFilterQuery: <T>(filter: PongoFilter<T>) => string;
30
+
31
+ declare const postgresCollection: <T extends PongoDocument>(collectionName: string, { dbName, poolOrClient: clientOrPool, }: {
32
+ dbName: string;
33
+ poolOrClient: pg.Pool | pg.PoolClient;
34
+ }) => PongoCollection<T>;
35
+ declare const collectionSQLBuilder: (collectionName: string) => {
36
+ createCollection: () => SQL;
37
+ insertOne: <T>(document: WithId<T>) => SQL;
38
+ insertMany: <T_1>(documents: WithId<T_1>[]) => SQL;
39
+ updateOne: <T_2>(filter: PongoFilter<T_2>, update: PongoUpdate<T_2>) => SQL;
40
+ replaceOne: <T_3>(filter: PongoFilter<T_3>, document: WithoutId<T_3>) => SQL;
41
+ updateMany: <T_4>(filter: PongoFilter<T_4>, update: PongoUpdate<T_4>) => SQL;
42
+ deleteOne: <T_5>(filter: PongoFilter<T_5>) => SQL;
43
+ deleteMany: <T_6>(filter: PongoFilter<T_6>) => SQL;
44
+ findOne: <T_7>(filter: PongoFilter<T_7>) => SQL;
45
+ find: <T_8>(filter: PongoFilter<T_8>) => SQL;
46
+ countDocuments: <T_9>(filter: PongoFilter<T_9>) => SQL;
47
+ rename: (newName: string) => SQL;
48
+ drop: (targetName?: string) => SQL;
49
+ };
50
+
51
+ declare const buildUpdateQuery: <T>(update: PongoUpdate<T>) => SQL;
52
+ declare const buildSetQuery: <T>(set: $set<T>, currentUpdateQuery: SQL) => SQL;
53
+ declare const buildUnsetQuery: <T>(unset: $unset<T>, currentUpdateQuery: SQL) => SQL;
54
+ declare const buildIncQuery: <T>(inc: $inc<T>, currentUpdateQuery: SQL) => SQL;
55
+ declare const buildPushQuery: <T>(push: $push<T>, currentUpdateQuery: SQL) => SQL;
3
56
 
4
57
  interface PongoClient {
5
58
  connect(): Promise<this>;
@@ -7,23 +60,34 @@ interface PongoClient {
7
60
  db(dbName?: string): PongoDb;
8
61
  }
9
62
  interface PongoDb {
10
- collection<T>(name: string): PongoCollection<T>;
63
+ collection<T extends PongoDocument>(name: string): PongoCollection<T>;
11
64
  }
12
- interface PongoCollection<T> {
65
+ interface PongoCollection<T extends PongoDocument> {
66
+ readonly dbName: string;
67
+ readonly collectionName: string;
13
68
  createCollection(): Promise<void>;
14
69
  insertOne(document: T): Promise<PongoInsertOneResult>;
15
70
  insertMany(documents: T[]): Promise<PongoInsertManyResult>;
16
71
  updateOne(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<PongoUpdateResult>;
72
+ replaceOne(filter: PongoFilter<T>, document: WithoutId<T>): Promise<PongoUpdateResult>;
17
73
  updateMany(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<PongoUpdateResult>;
18
- deleteOne(filter: PongoFilter<T>): Promise<PongoDeleteResult>;
19
- deleteMany(filter: PongoFilter<T>): Promise<PongoDeleteResult>;
20
- findOne(filter: PongoFilter<T>): Promise<T | null>;
21
- find(filter: PongoFilter<T>): Promise<T[]>;
74
+ deleteOne(filter?: PongoFilter<T>): Promise<PongoDeleteResult>;
75
+ deleteMany(filter?: PongoFilter<T>): Promise<PongoDeleteResult>;
76
+ findOne(filter?: PongoFilter<T>): Promise<T | null>;
77
+ find(filter?: PongoFilter<T>): Promise<T[]>;
78
+ findOneAndDelete(filter: PongoFilter<T>): Promise<T | null>;
79
+ findOneAndReplace(filter: PongoFilter<T>, replacement: WithoutId<T>): Promise<T | null>;
80
+ findOneAndUpdate(filter: PongoFilter<T>, update: PongoUpdate<T>): Promise<T | null>;
81
+ countDocuments(filter?: PongoFilter<T>): Promise<number>;
82
+ drop(): Promise<boolean>;
83
+ rename(newName: string): Promise<PongoCollection<T>>;
84
+ handle(id: string, handle: DocumentHandler<T>): Promise<T | null>;
22
85
  }
23
86
  type HasId = {
24
87
  _id: string;
25
88
  };
26
89
  type WithId<T> = T & HasId;
90
+ type WithoutId<T> = Omit<T, '_id'>;
27
91
  type PongoFilter<T> = {
28
92
  [P in keyof T]?: T[P] | PongoFilterOperator<T[P]>;
29
93
  } | HasId;
@@ -78,15 +142,17 @@ interface PongoDeleteManyResult {
78
142
  acknowledged: boolean;
79
143
  deletedCount: number;
80
144
  }
81
-
82
- declare const pongoClient: (connectionString: string) => PongoClient;
145
+ type PongoDocument = Record<string, unknown>;
146
+ type DocumentHandler<T extends PongoDocument> = ((document: T | null) => T | null) | ((document: T | null) => Promise<T | null>);
83
147
 
84
148
  interface DbClient {
85
149
  connect(): Promise<void>;
86
150
  close(): Promise<void>;
87
- collection: <T>(name: string) => PongoCollection<T>;
151
+ collection: <T extends PongoDocument>(name: string) => PongoCollection<T>;
88
152
  }
89
- declare const getDbClient: (connectionString: string, database?: string) => DbClient;
153
+ declare const getDbClient: (options: PongoClientOptions) => DbClient;
154
+
155
+ declare const pongoClient: (connectionString: string) => PongoClient;
90
156
 
91
157
  type Entry<T> = {
92
158
  [K in keyof Required<T>]: [K, Required<T>[K]];
@@ -114,7 +180,9 @@ declare class FindCursor<T> {
114
180
  declare class Db {
115
181
  private pongoDb;
116
182
  constructor(pongoDb: PongoDb);
117
- collection<T extends Document>(collectionName: string): Collection$1<T>;
183
+ collection<T extends Document>(collectionName: string): Collection$1<T> & {
184
+ handle(id: ObjectId$1, handle: DocumentHandler<T>): Promise<T | null>;
185
+ };
118
186
  }
119
187
 
120
188
  declare class MongoClient {
@@ -141,11 +209,11 @@ declare class Collection<T extends Document> implements Collection$1<T> {
141
209
  insertMany(docs: OptionalUnlessRequiredId<T>[], _options?: BulkWriteOptions | undefined): Promise<InsertManyResult<T>>;
142
210
  bulkWrite(_operations: AnyBulkWriteOperation<T>[], _options?: BulkWriteOptions | undefined): Promise<BulkWriteResult>;
143
211
  updateOne(filter: Filter<T>, update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
144
- replaceOne(_filter: Filter<T>, _: WithoutId<T>, _options?: ReplaceOptions | undefined): Promise<Document | UpdateResult<T>>;
212
+ replaceOne(filter: Filter<T>, document: WithoutId$1<T>, _options?: ReplaceOptions | undefined): Promise<Document | UpdateResult<T>>;
145
213
  updateMany(filter: Filter<T>, update: Document[] | UpdateFilter<T>, _options?: UpdateOptions | undefined): Promise<UpdateResult<T>>;
146
214
  deleteOne(filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
147
215
  deleteMany(filter?: Filter<T> | undefined, _options?: DeleteOptions | undefined): Promise<DeleteResult>;
148
- rename(_newName: string, _options?: RenameOptions | undefined): Promise<Collection<Document>>;
216
+ rename(newName: string, _options?: RenameOptions | undefined): Promise<Collection<Document>>;
149
217
  drop(_options?: DropCollectionOptions | undefined): Promise<boolean>;
150
218
  findOne(): Promise<WithId$1<T> | null>;
151
219
  findOne(filter: Filter<T>): Promise<WithId$1<T> | null>;
@@ -173,7 +241,7 @@ declare class Collection<T extends Document> implements Collection$1<T> {
173
241
  indexInformation(options: IndexInformationOptions): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;
174
242
  indexInformation(): Promise<IndexDescriptionCompact>;
175
243
  estimatedDocumentCount(_options?: EstimatedDocumentCountOptions | undefined): Promise<number>;
176
- countDocuments(_filter?: Filter<T> | undefined, _options?: CountDocumentsOptions | undefined): Promise<number>;
244
+ countDocuments(filter?: Filter<T> | undefined, _options?: CountDocumentsOptions | undefined): Promise<number>;
177
245
  distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key): Promise<Flatten<WithId$1<T>[Key]>[]>;
178
246
  distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>): Promise<Flatten<WithId$1<T>[Key]>[]>;
179
247
  distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(key: Key, filter: Filter<T>, options: CommandOperationOptions): Promise<Flatten<WithId$1<T>[Key]>[]>;
@@ -196,14 +264,14 @@ declare class Collection<T extends Document> implements Collection$1<T> {
196
264
  }): Promise<WithId$1<T> | null>;
197
265
  findOneAndDelete(filter: Filter<T>, options: FindOneAndDeleteOptions): Promise<WithId$1<T> | null>;
198
266
  findOneAndDelete(filter: Filter<T>): Promise<WithId$1<T> | null>;
199
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions & {
267
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId$1<T>, options: FindOneAndReplaceOptions & {
200
268
  includeResultMetadata: true;
201
269
  }): Promise<ModifyResult<T>>;
202
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions & {
270
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId$1<T>, options: FindOneAndReplaceOptions & {
203
271
  includeResultMetadata: false;
204
272
  }): Promise<WithId$1<T> | null>;
205
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>, options: FindOneAndReplaceOptions): Promise<WithId$1<T> | null>;
206
- findOneAndReplace(filter: Filter<T>, replacement: WithoutId<T>): Promise<WithId$1<T> | null>;
273
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId$1<T>, options: FindOneAndReplaceOptions): Promise<WithId$1<T> | null>;
274
+ findOneAndReplace(filter: Filter<T>, replacement: WithoutId$1<T>): Promise<WithId$1<T> | null>;
207
275
  findOneAndUpdate(filter: Filter<T>, update: UpdateFilter<T>, options: FindOneAndUpdateOptions & {
208
276
  includeResultMetadata: true;
209
277
  }): Promise<ModifyResult<T>>;
@@ -216,7 +284,7 @@ declare class Collection<T extends Document> implements Collection$1<T> {
216
284
  watch<TLocal extends Document = T, TChange extends Document = ChangeStreamDocument<TLocal>>(_pipeline?: Document[] | undefined, _options?: ChangeStreamOptions | undefined): ChangeStream<TLocal, TChange>;
217
285
  initializeUnorderedBulkOp(_options?: BulkWriteOptions | undefined): UnorderedBulkOperation;
218
286
  initializeOrderedBulkOp(_options?: BulkWriteOptions | undefined): OrderedBulkOperation;
219
- count(_filter?: Filter<T> | undefined, _options?: CountOptions | undefined): Promise<number>;
287
+ count(filter?: Filter<T> | undefined, _options?: CountOptions | undefined): Promise<number>;
220
288
  listSearchIndexes(options?: ListSearchIndexesOptions | undefined): ListSearchIndexesCursor;
221
289
  listSearchIndexes(name: string, options?: ListSearchIndexesOptions | undefined): ListSearchIndexesCursor;
222
290
  createSearchIndex(_description: SearchIndexDescription): Promise<string>;
@@ -224,62 +292,11 @@ declare class Collection<T extends Document> implements Collection$1<T> {
224
292
  dropSearchIndex(_name: string): Promise<void>;
225
293
  updateSearchIndex(_name: string, _definition: Document): Promise<void>;
226
294
  createCollection(): Promise<void>;
295
+ handle(id: ObjectId$1, handle: DocumentHandler<T>): Promise<T | null>;
227
296
  }
228
297
 
229
298
  type ObjectId = string & {
230
299
  __brandId: 'ObjectId';
231
300
  };
232
301
 
233
- declare const postgresClient: (connectionString: string, database?: string) => DbClient;
234
-
235
- type SQL = string & {
236
- __brand: 'sql';
237
- };
238
- declare const sql: (sqlQuery: string, ...params: unknown[]) => SQL;
239
-
240
- declare const execute: <Result = void>(pool: pg.Pool, handle: (client: pg.PoolClient) => Promise<Result>) => Promise<Result>;
241
- declare const executeSQL: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool, sql: SQL) => Promise<pg.QueryResult<Result>>;
242
-
243
- declare const Operators: {
244
- $eq: string;
245
- $gt: string;
246
- $gte: string;
247
- $lt: string;
248
- $lte: string;
249
- $ne: string;
250
- $in: string;
251
- $nin: string;
252
- $elemMatch: string;
253
- $all: string;
254
- $size: string;
255
- };
256
- declare const isOperator: (key: string) => boolean;
257
- declare const hasOperators: (value: Record<string, unknown>) => boolean;
258
- declare const handleOperator: (path: string, operator: string, value: unknown) => string;
259
-
260
- declare const constructFilterQuery: <T>(filter: PongoFilter<T>) => string;
261
-
262
- declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
263
- declare const endPool: (connectionString: string) => Promise<void>;
264
- declare const endAllPools: () => Promise<void[]>;
265
-
266
- declare const postgresCollection: <T>(collectionName: string, pool: pg.Pool) => PongoCollection<T>;
267
- declare const collectionSQLBuilder: (collectionName: string) => {
268
- createCollection: () => SQL;
269
- insertOne: <T>(document: WithId<T>) => SQL;
270
- insertMany: <T_1>(documents: WithId<T_1>[]) => SQL;
271
- updateOne: <T_2>(filter: PongoFilter<T_2>, update: PongoUpdate<T_2>) => SQL;
272
- updateMany: <T_3>(filter: PongoFilter<T_3>, update: PongoUpdate<T_3>) => SQL;
273
- deleteOne: <T_4>(filter: PongoFilter<T_4>) => SQL;
274
- deleteMany: <T_5>(filter: PongoFilter<T_5>) => SQL;
275
- findOne: <T_6>(filter: PongoFilter<T_6>) => SQL;
276
- find: <T_7>(filter: PongoFilter<T_7>) => SQL;
277
- };
278
-
279
- declare const buildUpdateQuery: <T>(update: PongoUpdate<T>) => SQL;
280
- declare const buildSetQuery: <T>(set: $set<T>, currentUpdateQuery: SQL) => SQL;
281
- declare const buildUnsetQuery: <T>(unset: $unset<T>, currentUpdateQuery: SQL) => SQL;
282
- declare const buildIncQuery: <T>(inc: $inc<T>, currentUpdateQuery: SQL) => SQL;
283
- declare const buildPushQuery: <T>(push: $push<T>, currentUpdateQuery: SQL) => SQL;
284
-
285
- export { type $inc, type $push, type $set, type $unset, Collection, Db, type DbClient, FindCursor, type HasId, MongoClient, type NonPartial, type ObjectId, Operators, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteManyResult, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertManyResult, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateManyResult, type PongoUpdateResult, type SQL, type WithId, buildIncQuery, buildPushQuery, buildSetQuery, buildUnsetQuery, buildUpdateQuery, collectionSQLBuilder, constructFilterQuery, endAllPools, endPool, entries, execute, executeSQL, getDbClient, getPool, handleOperator, hasOperators, isOperator, pongoClient, postgresClient, postgresCollection, sql };
302
+ export { type $inc, type $push, type $set, type $unset, Collection, Db, type DbClient, type DocumentHandler, FindCursor, type HasId, MongoClient, type NonPartial, type ObjectId, Operators, type PongoClient, type PongoClientOptions, type PongoCollection, type PongoDb, type PongoDeleteManyResult, type PongoDeleteResult, type PongoDocument, type PongoFilter, type PongoFilterOperator, type PongoInsertManyResult, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateManyResult, type PongoUpdateResult, type WithId, type WithoutId, buildIncQuery, buildPushQuery, buildSetQuery, buildUnsetQuery, buildUpdateQuery, collectionSQLBuilder, constructFilterQuery, entries, getDbClient, handleOperator, hasOperators, isOperator, pongoClient, postgresClient, postgresCollection };
package/dist/index.js CHANGED
@@ -1,5 +1,14 @@
1
- import b from"pg";var m=new Map,I=t=>{let e=typeof t=="string"?t:t.connectionString,n=typeof t=="string"?{connectionString:e}:t;return m.get(e)??m.set(e,new b.Pool(n)).get(e)},h=async t=>{let e=m.get(t);e&&(await e.end(),m.delete(t))},z=()=>Promise.all([...m.keys()].map(t=>h(t)));import"pg";import K from"pg-format";import{v4 as E}from"uuid";var $=async(t,e)=>{let n=await t.connect();try{return await e(n)}finally{n.release()}},y=async(t,e)=>$(t,n=>n.query(e));var u=t=>Object.entries(t).map(([e,n])=>[e,n]);import d from"pg-format";var x={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},D={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},L=t=>t.startsWith("$"),F=t=>Object.keys(t).some(L),c=(t,e,n)=>{if(t==="_id")return W(e,n);switch(e){case"$eq":return d("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(C(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`data #>> %L ${D[e]} %L`,`{${t.split(".").join(",")}}`,n);case"$in":return d("data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>d("%L",o)).join(", "));case"$nin":return d("data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>d("%L",o)).join(", "));case"$elemMatch":{let o=u(n).map(([i,r])=>d('@."%s" == %s',i,JSON.stringify(r))).join(" && ");return d("jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return d("data @> %L::jsonb",JSON.stringify(C(t,n)));case"$size":return d("jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${e}`)}},W=(t,e)=>{switch(t){case"$eq":return d("_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`_id ${D[t]} %L`,e);case"$in":return d("_id IN (%s)",e.map(n=>d("%L",n)).join(", "));case"$nin":return d("_id NOT IN (%s)",e.map(n=>d("%L",n)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},C=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var k="AND",p=t=>Object.entries(t).map(([e,n])=>U(n)?A(e,n):c(e,"$eq",n)).join(` ${k} `),A=(t,e)=>{let n=!F(e);return u(e).map(([o,i])=>n?c(`${t}.${o}`,x.$eq,i):c(t,o,i)).join(` ${k} `)},U=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);import Q from"pg-format";var l=(t,...e)=>Q(t,...e);var O=t=>u(t).reduce((e,[n,o])=>{switch(n){case"$set":return j(o,e);case"$unset":return q(o,e);case"$inc":return N(o,e);case"$push":return B(o,e);default:return e}},l("data")),j=(t,e)=>l("%s || %L::jsonb",e,JSON.stringify(t)),q=(t,e)=>l("%s - %L",e,Object.keys(t).map(n=>`{${n}}`).join(", ")),N=(t,e)=>{for(let[n,o]of Object.entries(t))e=l("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",e,n,n,o);return e},B=(t,e)=>{for(let[n,o]of Object.entries(t))e=l("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",e,n,n,JSON.stringify([o]));return e};var M=(t,e)=>{let n=r=>y(e,r),o=H(t),i=n(o.createCollection());return{createCollection:async()=>{await i},insertOne:async r=>{await i;let s=E();return(await n(o.insertOne({_id:s,...r}))).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async r=>{await i;let s=r.map(w=>({_id:E(),...w})),a=await n(o.insertMany(s));return{acknowledged:a.rowCount===s.length,insertedCount:a.rowCount??0,insertedIds:s.map(w=>w._id)}},updateOne:async(r,s)=>{await i;let a=await n(o.updateOne(r,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(r,s)=>{await i;let a=await n(o.updateMany(r,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async r=>{await i;let s=await n(o.deleteOne(r));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async r=>{await i;let s=await n(o.deleteMany(r));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async r=>(await i,(await n(o.findOne(r))).rows[0]?.data??null),find:async r=>(await i,(await n(o.find(r))).rows.map(a=>a.data))}},H=t=>({createCollection:()=>l("CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)",t),insertOne:e=>l("INSERT INTO %I (_id, data) VALUES (%L, %L)",t,e._id,JSON.stringify(e)),insertMany:e=>{let n=e.map(o=>K("(%L, %L)",o._id,JSON.stringify(o))).join(", ");return l("INSERT INTO %I (_id, data) VALUES %s",t,n)},updateOne:(e,n)=>{let o=p(e),i=O(n);return l(`WITH cte AS (
1
+ import{endPool as J,getDatabaseNameOrDefault as v,getPool as z}from"@event-driven-io/dumbo";import"pg";import{executeSQL as B,single as H,sql as p}from"@event-driven-io/dumbo";import"pg";import q from"pg-format";import{v4 as S}from"uuid";var T=t=>Object.entries(t).map(([e,n])=>[e,n]);import l from"pg-format";var D={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},F={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},M=t=>t.startsWith("$"),E=t=>Object.keys(t).some(M),O=(t,e,n)=>{if(t==="_id")return $(e,n);switch(e){case"$eq":return l("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(x(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return l(`data #>> %L ${F[e]} %L`,`{${t.split(".").join(",")}}`,n);case"$in":return l("data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>l("%L",o)).join(", "));case"$nin":return l("data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>l("%L",o)).join(", "));case"$elemMatch":{let o=T(n).map(([r,d])=>l('@."%s" == %s',r,JSON.stringify(d))).join(" && ");return l("jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return l("data @> %L::jsonb",JSON.stringify(x(t,n)));case"$size":return l("jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${e}`)}},$=(t,e)=>{switch(t){case"$eq":return l("_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return l(`_id ${F[t]} %L`,e);case"$in":return l("_id IN (%s)",e.map(n=>l("%L",n)).join(", "));case"$nin":return l("_id NOT IN (%s)",e.map(n=>l("%L",n)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},x=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var b="AND",c=t=>Object.entries(t).map(([e,n])=>W(n)?A(e,n):O(e,"$eq",n)).join(` ${b} `),A=(t,e)=>{let n=!E(e);return T(e).map(([o,r])=>n?O(`${t}.${o}`,D.$eq,r):O(t,o,r)).join(` ${b} `)},W=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);import{sql as g}from"@event-driven-io/dumbo";var h=t=>T(t).reduce((e,[n,o])=>{switch(n){case"$set":return U(o,e);case"$unset":return N(o,e);case"$inc":return Q(o,e);case"$push":return j(o,e);default:return e}},g("data")),U=(t,e)=>g("%s || %L::jsonb",e,JSON.stringify(t)),N=(t,e)=>g("%s - %L",e,Object.keys(t).map(n=>`{${n}}`).join(", ")),Q=(t,e)=>{for(let[n,o]of Object.entries(t))e=g("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",e,n,n,o);return e},j=(t,e)=>{for(let[n,o]of Object.entries(t))e=g("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",e,n,n,JSON.stringify([o]));return e};var k=(t,{dbName:e,poolOrClient:n})=>{let o=i=>B(n,i),r=K(t),d=o(r.createCollection()),u={dbName:e,collectionName:t,createCollection:async()=>{await d},insertOne:async i=>{await d;let s=S();return(await o(r.insertOne({_id:s,...i}))).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async i=>{await d;let s=i.map(m=>({_id:S(),...m})),a=await o(r.insertMany(s));return{acknowledged:a.rowCount===s.length,insertedCount:a.rowCount??0,insertedIds:s.map(m=>m._id)}},updateOne:async(i,s)=>{await d;let a=await o(r.updateOne(i,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(i,s)=>{await d;let a=await o(r.replaceOne(i,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(i,s)=>{await d;let a=await o(r.updateMany(i,s));return a.rowCount?{acknowledged:!0,modifiedCount:a.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async i=>{await d;let s=await o(r.deleteOne(i??{}));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async i=>{await d;let s=await o(r.deleteMany(i??{}));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async i=>(await d,(await o(r.findOne(i??{}))).rows[0]?.data??null),findOneAndDelete:async i=>{await d;let s=await u.findOne(i);return s===null?null:(await u.deleteOne(i),s)},findOneAndReplace:async(i,s)=>{await d;let a=await u.findOne(i);return a===null?null:(await u.replaceOne(i,s),a)},findOneAndUpdate:async(i,s)=>{await d;let a=await u.findOne(i);return a===null?null:(await u.updateOne(i,s),a)},handle:async(i,s)=>{await d;let a={_id:i},m=await u.findOne(a),f=await s(m);if(!m&&f){let y={...f,_id:i};return await u.insertOne({...y,_id:i}),y}return m&&!f?(await u.deleteOne(a),null):(m&&f&&await u.replaceOne(a,f),f)},find:async i=>(await d,(await o(r.find(i??{}))).rows.map(a=>a.data)),countDocuments:async i=>{await d;let{count:s}=await H(o(r.countDocuments(i??{})));return s},drop:async()=>(await d,((await o(r.drop()))?.rowCount??0)>0),rename:async i=>(await d,await o(r.rename(i)),t=i,u)};return u},K=t=>({createCollection:()=>p(`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
+ )`,t),insertOne:e=>p("INSERT INTO %I (_id, data) VALUES (%L, %L)",t,e._id,JSON.stringify(e)),insertMany:e=>{let n=e.map(o=>q("(%L, %L)",o._id,JSON.stringify(o))).join(", ");return p("INSERT INTO %I (_id, data) VALUES %s",t,n)},updateOne:(e,n)=>{let o=c(e),r=h(n);return p(`WITH cte AS (
2
11
  SELECT _id FROM %I WHERE %s LIMIT 1
3
12
  )
4
- UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,o,t,i,t)},updateMany:(e,n)=>{let o=p(e),i=O(n);return l("UPDATE %I SET data = %s WHERE %s",t,i,o)},deleteOne:e=>{let n=p(e);return l("DELETE FROM %I WHERE %s",t,n)},deleteMany:e=>{let n=p(e);return l("DELETE FROM %I WHERE %s",t,n)},findOne:e=>{let n=p(e);return l("SELECT data FROM %I WHERE %s LIMIT 1",t,n)},find:e=>{let n=p(e);return l("SELECT data FROM %I WHERE %s",t,n)}});var R=(t,e)=>{let n=I({connectionString:t,database:e});return{connect:()=>Promise.resolve(),close:()=>h(t),collection:o=>M(o,n)}};var P=(t,e)=>R(t,e);var _=t=>{let e=P(t),n={connect:async()=>(await e.connect(),n),close:()=>e.close(),db:o=>o?P(t,o):e};return n};var f=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 o of n)e(o);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 g=class{collection;constructor(e){this.collection=e}get dbName(){throw new Error("Method not implemented.")}get collectionName(){throw new Error("Method not implemented.")}get namespace(){throw new Error("Method not implemented.")}get readConcern(){throw new Error("Method not implemented.")}get readPreference(){throw new Error("Method not implemented.")}get bsonOptions(){throw new Error("Method not implemented.")}get writeConcern(){throw new Error("Method not implemented.")}get hint(){throw new Error("Method not implemented.")}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}async insertMany(e,n){let o=await this.collection.insertMany(e);return{acknowledged:o.acknowledged,insertedIds:o.insertedIds,insertedCount:o.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){throw new Error("Method not implemented.")}async updateMany(e,n,o){let i=await this.collection.updateMany(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async deleteMany(e,n){let o=await this.collection.deleteMany(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}rename(e,n){throw new Error("Method not implemented.")}drop(e){throw new Error("Method not implemented.")}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new f(this.collection.find(e))}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){throw new Error("Method not implemented.")}countDocuments(e,n){throw new Error("Method not implemented.")}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){throw new Error("Method not implemented.")}findOneAndReplace(e,n,o){throw new Error("Method not implemented.")}findOneAndUpdate(e,n,o){throw new Error("Method not implemented.")}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){throw new Error("Method not implemented.")}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()}};var T=class{constructor(e){this.pongoDb=e}collection(e){return new g(this.pongoDb.collection(e))}};var S=class{pongoClient;constructor(e){this.pongoClient=_(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new T(this.pongoClient.db(e))}};export{g as Collection,T as Db,f as FindCursor,S as MongoClient,x as Operators,N as buildIncQuery,B as buildPushQuery,j as buildSetQuery,q as buildUnsetQuery,O as buildUpdateQuery,H as collectionSQLBuilder,p as constructFilterQuery,z as endAllPools,h as endPool,u as entries,$ as execute,y as executeSQL,P as getDbClient,I as getPool,c as handleOperator,F as hasOperators,L as isOperator,_ as pongoClient,R as postgresClient,M as postgresCollection,l as sql};
13
+ UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,o,t,r,t)},replaceOne:(e,n)=>{let o=c(e);return p("UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') WHERE %s",t,JSON.stringify(n),o)},updateMany:(e,n)=>{let o=c(e),r=h(n);return p("UPDATE %I SET data = %s WHERE %s",t,r,o)},deleteOne:e=>{let n=c(e);return p("DELETE FROM %I WHERE %s",t,n)},deleteMany:e=>{let n=c(e);return p("DELETE FROM %I WHERE %s",t,n)},findOne:e=>{let n=c(e);return p("SELECT data FROM %I WHERE %s LIMIT 1",t,n)},find:e=>{let n=c(e);return p("SELECT data FROM %I WHERE %s",t,n)},countDocuments:e=>{let n=c(e);return p("SELECT COUNT(1) as count FROM %I WHERE %s",t,n)},rename:e=>p("ALTER TABLE %I RENAME TO %I",t,e),drop:(e=t)=>p("DROP TABLE IF EXISTS %I",e)});var L=t=>{let{connectionString:e,dbName:n,client:o}=t,r=!o,d=o??z({connectionString:e,database:n});return{connect:()=>Promise.resolve(),close:()=>r?J({connectionString:e,database:n}):Promise.resolve(),collection:u=>k(u,{dbName:n??v(e),poolOrClient:d})}};var C=t=>L(t);import{getDatabaseNameOrDefault as X}from"@event-driven-io/dumbo";var R=t=>{let e=X(t),n=new Map,o=C({connectionString:t});n.set(e,o);let r={connect:async()=>(await o.connect(),r),close:async()=>{for(let d of n.values())await d.close()},db:d=>d?n.get(d)??n.set(d,C({connectionString:t,dbName:d})).get(d):o};return r};var P=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 o of n)e(o);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 w=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 o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}async insertMany(e,n){let o=await this.collection.insertMany(e);return{acknowledged:o.acknowledged,insertedIds:o.insertedIds,insertedCount:o.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let r=await this.collection.updateOne(e,n);return{acknowledged:r.acknowledged,matchedCount:r.modifiedCount,modifiedCount:r.modifiedCount,upsertedCount:r.modifiedCount,upsertedId:null}}replaceOne(e,n,o){return this.collection.replaceOne(e,n)}async updateMany(e,n,o){let r=await this.collection.updateMany(e,n);return{acknowledged:r.acknowledged,matchedCount:r.modifiedCount,modifiedCount:r.modifiedCount,upsertedCount:r.modifiedCount,upsertedId:null}}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async deleteMany(e,n){let o=await this.collection.deleteMany(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async rename(e,n){return await this.collection.rename(e),this}drop(e){return this.collection.drop()}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new P(this.collection.find(e))}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()}countDocuments(e,n){return this.collection.countDocuments(e)}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e)}findOneAndReplace(e,n,o){return this.collection.findOneAndReplace(e,n)}findOneAndUpdate(e,n,o){return this.collection.findOneAndUpdate(e,n)}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??{})}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 I=class{constructor(e){this.pongoDb=e}collection(e){return new w(this.pongoDb.collection(e))}};var _=class{pongoClient;constructor(e){this.pongoClient=R(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new I(this.pongoClient.db(e))}};export{w as Collection,I as Db,P as FindCursor,_ as MongoClient,D as Operators,Q as buildIncQuery,j as buildPushQuery,U as buildSetQuery,N as buildUnsetQuery,h as buildUpdateQuery,K as collectionSQLBuilder,c as constructFilterQuery,T as entries,C as getDbClient,O as handleOperator,E as hasOperators,M as isOperator,R as pongoClient,L as postgresClient,k as postgresCollection};
5
14
  //# sourceMappingURL=index.js.map