@event-driven-io/pongo 0.12.5 → 0.13.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/{chunk-ONUSCYXL.js → chunk-G2D34XRD.js} +3 -3
- package/dist/chunk-G2D34XRD.js.map +1 -0
- package/dist/{chunk-XNYYBA3K.cjs → chunk-M74CIMXY.cjs} +3 -3
- package/dist/chunk-M74CIMXY.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{pongoDb-DOU_94ei.d.cts → pongoClient-BXyaQhyS.d.cts} +11 -11
- package/dist/{pongoDb-DOU_94ei.d.ts → pongoClient-BXyaQhyS.d.ts} +11 -11
- package/dist/shim.cjs +1 -1
- package/dist/shim.cjs.map +1 -1
- package/dist/shim.d.cts +1 -1
- package/dist/shim.d.ts +1 -1
- package/dist/shim.js +1 -1
- package/dist/shim.js.map +1 -1
- package/package.json +5 -6
- package/dist/chunk-ONUSCYXL.js.map +0 -1
- package/dist/chunk-XNYYBA3K.cjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{single as nt}from"@event-driven-io/dumbo";import{v4 as
|
|
1
|
+
import{single as nt}from"@event-driven-io/dumbo";import{v4 as j}from"uuid";var $={$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:"!="},q=t=>t.startsWith("$"),I=t=>Object.keys(t).some(q);import{NodePostgresConnectorType as tt}from"@event-driven-io/dumbo";import"pg";import{dumbo as V,getDatabaseNameOrDefault as Y,NodePostgresConnectorType as Z}from"@event-driven-io/dumbo";import{rawSql as z,sql as u}from"@event-driven-io/dumbo";import{sql as d}from"@event-driven-io/dumbo";var C=(t,n,e)=>{if(t==="_id")return B(n,e);switch(n){case"$eq":return d("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(Q(t,e)),t,JSON.stringify(e));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`data #>> %L ${L[n]} %L`,`{${t.split(".").join(",")}}`,e);case"$in":return d("data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,e.map(o=>d("%L",o)).join(", "));case"$nin":return d("data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,e.map(o=>d("%L",o)).join(", "));case"$elemMatch":{let o=f(e).map(([s,l])=>d('@."%s" == %s',s,JSON.stringify(l))).join(" && ");return d("jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return d("data @> %L::jsonb",JSON.stringify(Q(t,e)));case"$size":return d("jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,e);default:throw new Error(`Unsupported operator: ${n}`)}},B=(t,n)=>{switch(t){case"$eq":return d("_id = %L",n);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`_id ${L[t]} %L`,n);case"$in":return d("_id IN (%s)",n.map(e=>d("%L",e)).join(", "));case"$nin":return d("_id NOT IN (%s)",n.map(e=>d("%L",e)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},Q=(t,n)=>t.split(".").reverse().reduce((e,o)=>({[o]:e}),n);var R="AND",P=t=>Object.entries(t).map(([n,e])=>W(e)?J(n,e):C(n,"$eq",e)).join(` ${R} `),J=(t,n)=>{let e=!I(n);return f(n).map(([o,s])=>e?C(`${t}.${o}`,$.$eq,s):C(t,o,s)).join(` ${R} `)},W=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);import{sql as w}from"@event-driven-io/dumbo";var D=t=>f(t).reduce((n,[e,o])=>{switch(e){case"$set":return H(o,n);case"$unset":return K(o,n);case"$inc":return X(o,n);case"$push":return v(o,n);default:return n}},w("data")),H=(t,n)=>w("%s || %L::jsonb",n,JSON.stringify(t)),K=(t,n)=>w("%s - %L",n,Object.keys(t).map(e=>`{${e}}`).join(", ")),X=(t,n)=>{for(let[e,o]of Object.entries(t))n=w("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",n,e,e,o);return n},v=(t,n)=>{for(let[e,o]of Object.entries(t))n=w("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",n,e,e,JSON.stringify([o]));return n};var N=t=>({createCollection:()=>u(`CREATE TABLE IF NOT EXISTS %I (
|
|
2
2
|
_id TEXT PRIMARY KEY,
|
|
3
3
|
data JSONB NOT NULL,
|
|
4
4
|
metadata JSONB NOT NULL DEFAULT '{}',
|
|
@@ -10,5 +10,5 @@ import{single as nt}from"@event-driven-io/dumbo";import{v4 as M}from"uuid";var $
|
|
|
10
10
|
)`,t),insertOne:n=>u("INSERT INTO %I (_id, data) VALUES (%L, %L)",t,n._id,JSON.stringify(n)),insertMany:n=>{let e=n.map(o=>u("(%L, %L)",o._id,JSON.stringify(o))).join(", ");return u("INSERT INTO %I (_id, data) VALUES %s",t,e)},updateOne:(n,e)=>{let o=P(n),s=D(e);return u(`WITH cte AS (
|
|
11
11
|
SELECT _id FROM %I %s LIMIT 1
|
|
12
12
|
)
|
|
13
|
-
UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,y(o),t,s,t)},replaceOne:(n,e)=>{let o=P(n);return u("UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s",t,JSON.stringify(e),y(o))},updateMany:(n,e)=>{let o=P(n),s=D(e);return u("UPDATE %I SET data = %s %s",t,s,y(o))},deleteOne:n=>{let e=P(n);return u("DELETE FROM %I %s",t,y(e))},deleteMany:n=>{let e=P(n);return u("DELETE FROM %I %s",t,y(e))},findOne:n=>{let e=P(n);return u("SELECT data FROM %I %s LIMIT 1",t,y(e))},find:n=>{let e=P(n);return u("SELECT data FROM %I %s",t,y(e))},countDocuments:n=>{let e=P(n);return u("SELECT COUNT(1) as count FROM %I %s",t,y(e))},rename:n=>u("ALTER TABLE %I RENAME TO %I",t,n),drop:(n=t)=>u("DROP TABLE IF EXISTS %I",n)}),y=t=>t.length>0?u("WHERE %s",t):z("");var A=t=>t.connectorType===Z,U=t=>{let{connectionString:n,dbName:e}=t,o=e??Y(n),s=V(t),l={connectorType:t.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>s.close(),collection:T=>h({collectionName:T,db:l,sqlExecutor:s.execute,sqlBuilder:N(T)}),transaction:()=>s.transaction(),withTransaction:T=>s.withTransaction(T)};return l};var S=t=>{let{connectorType:n}=t;if(!A(t))throw new Error(`Unsupported db type: ${n}`);return U(t)};var k=t=>{let n=!1,e=!1,o=null,s=null;return{enlistDatabase:async l=>{if(s&&o!==l.databaseName)throw new Error("There's already other database assigned to transaction");return s&&o===l.databaseName||(o=l.databaseName,s=l.transaction(),await s.begin()),s},commit:async()=>{if(!s)throw new Error("No database transaction started!");if(!n){if(e)throw new Error("Transaction is not active!");n=!0,await s.commit(),s=null}},rollback:async l=>{if(!s)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");e||(e=!0,await s.rollback(l),s=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!e},get sqlExecutor(){if(s===null)throw new Error("No database transaction was started");return s.execute},options:t}};var b=t=>t?.isActive===!0;function _(t){if(!b(t))throw new Error("No active transaction exists!")}function G(t){if(b(t))throw new Error("Active transaction already exists!")}var E=t=>{let n=t?.explicit===!0,e=t?.defaultTransactionOptions??{get snapshotEnabled(){return!1}},o=null,s=!1,l=i=>{G(o),o=k(i??e)},T=async()=>{_(o),await o.commit()},p=async()=>{_(o),await o.rollback()},r={get hasEnded(){return s},explicit:n,defaultTransactionOptions:e??{get snapshotEnabled(){return!1}},get transaction(){return o},get snapshotEnabled(){return e.snapshotEnabled},endSession:async()=>{s||(s=!0,b(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>b(o),startTransaction:l,commitTransaction:T,abortTransaction:p,withTransaction:async(i,a)=>{l(a);try{let c=await i(r);return await T(),c}catch(c){throw await p(),c}}};return r};var
|
|
14
|
-
//# sourceMappingURL=chunk-
|
|
13
|
+
UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,y(o),t,s,t)},replaceOne:(n,e)=>{let o=P(n);return u("UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s",t,JSON.stringify(e),y(o))},updateMany:(n,e)=>{let o=P(n),s=D(e);return u("UPDATE %I SET data = %s %s",t,s,y(o))},deleteOne:n=>{let e=P(n);return u("DELETE FROM %I %s",t,y(e))},deleteMany:n=>{let e=P(n);return u("DELETE FROM %I %s",t,y(e))},findOne:n=>{let e=P(n);return u("SELECT data FROM %I %s LIMIT 1",t,y(e))},find:n=>{let e=P(n);return u("SELECT data FROM %I %s",t,y(e))},countDocuments:n=>{let e=P(n);return u("SELECT COUNT(1) as count FROM %I %s",t,y(e))},rename:n=>u("ALTER TABLE %I RENAME TO %I",t,n),drop:(n=t)=>u("DROP TABLE IF EXISTS %I",n)}),y=t=>t.length>0?u("WHERE %s",t):z("");var A=t=>t.connectorType===Z,U=t=>{let{connectionString:n,dbName:e}=t,o=e??Y(n),s=V(t),l={connectorType:t.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>s.close(),collection:T=>h({collectionName:T,db:l,sqlExecutor:s.execute,sqlBuilder:N(T)}),transaction:()=>s.transaction(),withTransaction:T=>s.withTransaction(T)};return l};var S=t=>{let{connectorType:n}=t;if(!A(t))throw new Error(`Unsupported db type: ${n}`);return U(t)};var k=t=>{let n=!1,e=!1,o=null,s=null;return{enlistDatabase:async l=>{if(s&&o!==l.databaseName)throw new Error("There's already other database assigned to transaction");return s&&o===l.databaseName||(o=l.databaseName,s=l.transaction(),await s.begin()),s},commit:async()=>{if(!s)throw new Error("No database transaction started!");if(!n){if(e)throw new Error("Transaction is not active!");n=!0,await s.commit(),s=null}},rollback:async l=>{if(!s)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");e||(e=!0,await s.rollback(l),s=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!e},get sqlExecutor(){if(s===null)throw new Error("No database transaction was started");return s.execute},options:t}};var b=t=>t?.isActive===!0;function _(t){if(!b(t))throw new Error("No active transaction exists!")}function G(t){if(b(t))throw new Error("Active transaction already exists!")}var E=t=>{let n=t?.explicit===!0,e=t?.defaultTransactionOptions??{get snapshotEnabled(){return!1}},o=null,s=!1,l=i=>{G(o),o=k(i??e)},T=async()=>{_(o),await o.commit()},p=async()=>{_(o),await o.rollback()},r={get hasEnded(){return s},explicit:n,defaultTransactionOptions:e??{get snapshotEnabled(){return!1}},get transaction(){return o},get snapshotEnabled(){return e.snapshotEnabled},endSession:async()=>{s||(s=!0,b(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>b(o),startTransaction:l,commitTransaction:T,abortTransaction:p,withTransaction:async(i,a)=>{l(a);try{let c=await i(r);return await T(),c}catch(c){throw await p(),c}}};return r};var jt=(t,n={})=>{let e=new Map,o=S(F({connectionString:t,clientOptions:n}));e.set(o.databaseName,o);let s={connect:async()=>(await o.connect(),s),close:async()=>{for(let l of e.values())await l.close()},db:l=>l?e.get(l)??e.set(l,S(F({connectionString:t,dbName:l,clientOptions:n}))).get(l):o,startSession:E,withSession:async l=>{let T=E();try{return await l(T)}finally{await T.endSession()}}};return s},F=t=>({connectorType:tt,connectionString:t.connectionString,dbName:t.dbName,...t.clientOptions});var f=t=>Object.entries(t).map(([n,e])=>[n,e]);var et=async(t,n)=>{let e=n?.session?.transaction;return!e||!e.isActive?null:await e.enlistDatabase(t)},M=async(t,n,e)=>(await et(t,n))?.execute??e,h=({db:t,collectionName:n,sqlExecutor:e,sqlBuilder:o})=>{let s=async(r,i)=>(await M(t,i,e)).command(r),l=async(r,i)=>(await M(t,i,e)).query(r),T=s(o.createCollection()),p=r=>r?.session?s(o.createCollection(),r):T,g={dbName:t.databaseName,collectionName:n,createCollection:async r=>{await p(r)},insertOne:async(r,i)=>{await p(i);let a=r._id??j();return(await s(o.insertOne({...r,_id:a}),i)).rowCount?{insertedId:a,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async(r,i)=>{await p(i);let a=r.map(O=>({...O,_id:O._id??j()})),c=await s(o.insertMany(a),i);return{acknowledged:c.rowCount===a.length,insertedCount:c.rowCount??0,insertedIds:a.map(O=>O._id)}},updateOne:async(r,i,a)=>{await p(a);let c=await s(o.updateOne(r,i),a);return c.rowCount?{acknowledged:!0,modifiedCount:c.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(r,i,a)=>{await p(a);let c=await s(o.replaceOne(r,i),a);return c.rowCount?{acknowledged:!0,modifiedCount:c.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(r,i,a)=>{await p(a);let c=await s(o.updateMany(r,i),a);return c.rowCount?{acknowledged:!0,modifiedCount:c.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async(r,i)=>{await p(i);let a=await s(o.deleteOne(r??{}),i);return a.rowCount?{acknowledged:!0,deletedCount:a.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async(r,i)=>{await p(i);let a=await s(o.deleteMany(r??{}),i);return a.rowCount?{acknowledged:!0,deletedCount:a.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async(r,i)=>(await p(i),(await l(o.findOne(r??{}),i)).rows[0]?.data??null),findOneAndDelete:async(r,i)=>{await p(i);let a=await g.findOne(r,i);return a===null?null:(await g.deleteOne(r,i),a)},findOneAndReplace:async(r,i,a)=>{await p(a);let c=await g.findOne(r,a);return c===null?null:(await g.replaceOne(r,i,a),c)},findOneAndUpdate:async(r,i,a)=>{await p(a);let c=await g.findOne(r,a);return c===null?null:(await g.updateOne(r,i,a),c)},handle:async(r,i,a)=>{await p(a);let c={_id:r},O=await g.findOne(c,a),m=await i(O);if(!O&&m){let x={...m,_id:r};return await g.insertOne({...x,_id:r},a),x}return O&&!m?(await g.deleteOne(c,a),null):(O&&m&&await g.replaceOne(c,m,a),m)},find:async(r,i)=>(await p(i),(await l(o.find(r??{}))).rows.map(c=>c.data)),countDocuments:async(r,i)=>{await p(i);let{count:a}=await nt(l(o.countDocuments(r??{})));return a},drop:async r=>(await p(r),((await s(o.drop()))?.rowCount??0)>0),rename:async(r,i)=>(await p(i),await s(o.rename(r)),n=r,g)};return g};export{h as a,$ as b,L as c,q as d,I as e,N as f,A as g,U as h,S as i,k as j,E as k,jt as l,F as m,f as n};
|
|
14
|
+
//# sourceMappingURL=chunk-G2D34XRD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/collection/pongoCollection.ts","../src/core/collection/query.ts","../src/core/pongoClient.ts","../src/postgres/dbClient.ts","../src/postgres/sqlBuilder/index.ts","../src/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/filter/index.ts","../src/postgres/sqlBuilder/update/index.ts","../src/core/pongoDb.ts","../src/core/pongoTransaction.ts","../src/core/pongoSession.ts","../src/core/typing/entries.ts"],"sourcesContent":["import {\n single,\n type DatabaseTransaction,\n type QueryResultRow,\n type SQL,\n type SQLExecutor,\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 '..';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n sqlExecutor: SQLExecutor;\n sqlBuilder: PongoCollectionSQLBuilder;\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 sqlExecutor,\n sqlBuilder: SqlFor,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\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 const createCollectionPromise = command(SqlFor.createCollection());\n const createCollection = (options?: CollectionOperationOptions) =>\n options?.session\n ? command(SqlFor.createCollection(), options)\n : createCollectionPromise;\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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n };\n\n return collection;\n};\n\nexport type PongoCollectionSQLBuilder = {\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","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 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';\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 | PooledPongoClientOptions\n | NotPooledPongoOptions;\n\nexport const pongoClient = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions = {},\n): PongoClient => {\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 pongoClient;\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 dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from '@event-driven-io/dumbo';\nimport {\n pongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector> &\n PostgresPoolOptions;\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>(options);\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 sqlExecutor: pool.execute,\n sqlBuilder: postgresSQLBuilder(collectionName),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n };\n\n return db;\n};\n","import { rawSql, sql, type SQL } 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\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n createCollection: (): 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 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 { sql } from '@event-driven-io/dumbo';\nimport { entries, OperatorMap } from '../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return sql(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSON.stringify(buildNestedObject(path, value)),\n path,\n JSON.stringify(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return sql(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n sql(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return sql(`jsonb_path_exists(data, '$.%s[*] ? (%s)')`, path, subQuery);\n }\n case '$all':\n return sql(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return sql(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return sql(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return sql(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import {\n entries,\n hasOperators,\n QueryOperators,\n type PongoFilter,\n} from '../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { sql, type SQL } from '@event-driven-io/dumbo';\nimport {\n entries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../core';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, JSON.stringify(set));\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL =>\n sql(\n '%s - %L',\n currentUpdateQuery,\n Object.keys(unset)\n .map((k) => `{${k}}`)\n .join(', '),\n );\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify([value]),\n );\n }\n return currentUpdateQuery;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n};\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n","import type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n","import { pongoTransaction } from './pongoTransaction';\nimport type {\n PongoDbTransaction,\n PongoSession,\n PongoTransactionOptions,\n} from './typing';\n\nexport type PongoSessionOptions = {\n explicit?: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n};\n\nconst isActive = (\n transaction: PongoDbTransaction | null,\n): transaction is PongoDbTransaction => transaction?.isActive === true;\n\nfunction assertInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is PongoDbTransaction {\n if (!isActive(transaction)) throw new Error('No active transaction exists!');\n}\n\nfunction assertNotInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is null {\n if (isActive(transaction))\n throw new Error('Active transaction already exists!');\n}\n\nexport const pongoSession = (options?: PongoSessionOptions): PongoSession => {\n const explicit = options?.explicit === true;\n const defaultTransactionOptions: PongoTransactionOptions =\n options?.defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n };\n\n let transaction: PongoDbTransaction | null = null;\n let hasEnded = false;\n\n const startTransaction = (options?: PongoTransactionOptions) => {\n assertNotInActiveTransaction(transaction);\n\n transaction = pongoTransaction(options ?? defaultTransactionOptions);\n };\n const commitTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.commit();\n };\n const abortTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.rollback();\n };\n\n const endSession = async (): Promise<void> => {\n if (hasEnded) return;\n hasEnded = true;\n\n if (isActive(transaction)) await transaction.rollback();\n };\n\n const session = {\n get hasEnded() {\n return hasEnded;\n },\n explicit,\n defaultTransactionOptions: defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n },\n get transaction() {\n return transaction;\n },\n get snapshotEnabled() {\n return defaultTransactionOptions.snapshotEnabled;\n },\n endSession,\n incrementTransactionNumber: () => {},\n inTransaction: () => isActive(transaction),\n startTransaction,\n commitTransaction,\n abortTransaction,\n withTransaction: async <T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T> => {\n startTransaction(options);\n\n try {\n const result = await fn(session);\n await commitTransaction();\n return result;\n } catch (error) {\n await abortTransaction();\n throw error;\n }\n },\n };\n\n return session;\n};\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <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"],"mappings":"AAAA,OACE,UAAAA,OAKK,yBACP,OAAS,MAAMC,MAAY,OCPpB,IAAMC,EAAiB,CAC5B,IAAK,MACL,IAAK,MACL,KAAM,OACN,IAAK,MACL,KAAM,OACN,IAAK,MACL,IAAK,MACL,KAAM,OACN,WAAY,aACZ,KAAM,OACN,MAAO,OACT,EAEaC,EAAc,CACzB,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,KACN,IAAK,IACP,EAEaC,EAAcC,GAAgBA,EAAI,WAAW,GAAG,EAEhDC,EAAgBC,GAC3B,OAAO,KAAKA,CAAK,EAAE,KAAKH,CAAU,ECzBpC,OACE,6BAAAI,OAEK,yBACP,MAAe,KCJf,OACE,SAAAC,EACA,4BAAAC,EACA,6BAAAC,MAGK,yBCNP,OAAS,UAAAC,EAAQ,OAAAC,MAAqB,yBCAtC,OAAS,OAAAC,MAAW,yBAGb,IAAMC,EAAiB,CAC5BC,EACAC,EACAC,IACW,CACX,GAAIF,IAAS,MACX,OAAOG,EAAiBF,EAAUC,CAAK,EAGzC,OAAQD,EAAU,CAChB,IAAK,MACH,OAAOG,EACL,wEACA,KAAK,UAAUC,EAAkBL,EAAME,CAAK,CAAC,EAC7CF,EACA,KAAK,UAAUE,CAAK,CACtB,EACF,IAAK,MACL,IAAK,OACL,IAAK,MACL,IAAK,OACL,IAAK,MACH,OAAOE,EACL,eAAeE,EAAYL,CAAQ,CAAC,MACpC,IAAID,EAAK,MAAM,GAAG,EAAE,KAAK,GAAG,CAAC,IAC7BE,CACF,EACF,IAAK,MACH,OAAOE,EACL,sBACA,IAAIJ,EAAK,MAAM,GAAG,EAAE,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ACtC,KAAK,IAAKS,GAAQA,EAAI,IAAS,GAE/C,eAAgB,MACdT,EACAtB,IACoB,CACpB,MAAMY,EAAiBZ,CAAO,EAE9B,GAAM,CAAE,MAAAgC,CAAM,EAAI,MAAMC,GACtBvB,EAAyBH,EAAO,eAAee,GAAU,CAAC,CAAC,CAAC,CAC9D,EACA,OAAOU,CACT,EACA,KAAM,MAAOhC,IACX,MAAMY,EAAiBZ,CAAO,IACf,MAAMQ,EAAQD,EAAO,KAAK,CAAC,IAC1B,UAAY,GAAK,GAEnC,OAAQ,MACN2B,EACAlC,KAEA,MAAMY,EAAiBZ,CAAO,EAC9B,MAAMQ,EAAQD,EAAO,OAAO2B,CAAO,CAAC,EACpC7B,EAAiB6B,EACVrB,EAEX,EAEA,OAAOA,CACT","names":["single","uuid","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","NodePostgresConnectorType","dumbo","getDatabaseNameOrDefault","NodePostgresConnectorType","rawSql","sql","sql","handleOperator","path","operator","value","handleIdOperator","sql","buildNestedObject","OperatorMap","v","subQuery","entries","subKey","subValue","acc","key","AND","constructFilterQuery","filter","key","value","isRecord","constructComplexFilterQuery","handleOperator","isEquality","hasOperators","entries","nestedKey","val","QueryOperators","sql","buildUpdateQuery","update","entries","currentUpdateQuery","op","value","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","sql","set","unset","k","inc","key","push","postgresSQLBuilder","collectionName","sql","document","documents","values","doc","filter","update","filterQuery","constructFilterQuery","updateQuery","buildUpdateQuery","where","newName","targetName","rawSql","isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","db","collectionName","pongoCollection","postgresSQLBuilder","handle","getPongoDb","options","type","isPostgresClientOptions","postgresDb","pongoTransaction","options","isCommitted","isRolledBack","databaseName","transaction","db","error","isActive","transaction","assertInActiveTransaction","assertNotInActiveTransaction","pongoSession","options","explicit","defaultTransactionOptions","hasEnded","startTransaction","pongoTransaction","commitTransaction","abortTransaction","session","fn","result","error","pongoClient","connectionString","options","dbClients","dbClient","getPongoDb","clientToDbOptions","db","dbName","pongoSession","callback","session","NodePostgresConnectorType","entries","obj","key","value","enlistIntoTransactionIfActive","db","options","transaction","transactionExecutorOrDefault","defaultSqlExecutor","pongoCollection","collectionName","sqlExecutor","SqlFor","command","sql","query","createCollectionPromise","createCollection","collection","document","_id","uuid","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","handle","byId","existing","newDoc","row","count","single","newName"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var $={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},L= exports.c ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},q= exports.d =t=>t.startsWith("$"),I= exports.e =t=>Object.keys(t).some(q);require('pg');var C=(t,n,e)=>{if(t==="_id")return B(n,e);switch(n){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(Q(t,e)),t,JSON.stringify(e));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${L[n]} %L`,`{${t.split(".").join(",")}}`,e);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${t.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)",`{${t.split(".").join(",")}}`,e.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var $={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},L= exports.c ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},q= exports.d =t=>t.startsWith("$"),I= exports.e =t=>Object.keys(t).some(q);require('pg');var C=(t,n,e)=>{if(t==="_id")return B(n,e);switch(n){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(Q(t,e)),t,JSON.stringify(e));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${L[n]} %L`,`{${t.split(".").join(",")}}`,e);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${t.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)",`{${t.split(".").join(",")}}`,e.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=f(e).map(([s,l])=>_dumbo.sql.call(void 0, '@."%s" == %s',s,JSON.stringify(l))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",JSON.stringify(Q(t,e)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,e);default:throw new Error(`Unsupported operator: ${n}`)}},B=(t,n)=>{switch(t){case"$eq":return _dumbo.sql.call(void 0, "_id = %L",n);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `_id ${L[t]} %L`,n);case"$in":return _dumbo.sql.call(void 0, "_id IN (%s)",n.map(e=>_dumbo.sql.call(void 0, "%L",e)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "_id NOT IN (%s)",n.map(e=>_dumbo.sql.call(void 0, "%L",e)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},Q=(t,n)=>t.split(".").reverse().reduce((e,o)=>({[o]:e}),n);var R="AND",P=t=>Object.entries(t).map(([n,e])=>W(e)?J(n,e):C(n,"$eq",e)).join(` ${R} `),J=(t,n)=>{let e=!I(n);return f(n).map(([o,s])=>e?C(`${t}.${o}`,$.$eq,s):C(t,o,s)).join(` ${R} `)},W=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);var D=t=>f(t).reduce((n,[e,o])=>{switch(e){case"$set":return H(o,n);case"$unset":return K(o,n);case"$inc":return X(o,n);case"$push":return v(o,n);default:return n}},_dumbo.sql.call(void 0, "data")),H=(t,n)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",n,JSON.stringify(t)),K=(t,n)=>_dumbo.sql.call(void 0, "%s - %L",n,Object.keys(t).map(e=>`{${e}}`).join(", ")),X=(t,n)=>{for(let[e,o]of Object.entries(t))n=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",n,e,e,o);return n},v=(t,n)=>{for(let[e,o]of Object.entries(t))n=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",n,e,e,JSON.stringify([o]));return n};var N=t=>({createCollection:()=>_dumbo.sql.call(void 0, `CREATE TABLE IF NOT EXISTS %I (
|
|
2
2
|
_id TEXT PRIMARY KEY,
|
|
3
3
|
data JSONB NOT NULL,
|
|
4
4
|
metadata JSONB NOT NULL DEFAULT '{}',
|
|
@@ -10,5 +10,5 @@
|
|
|
10
10
|
)`,t),insertOne:n=>_dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES (%L, %L)",t,n._id,JSON.stringify(n)),insertMany:n=>{let e=n.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",t,e)},updateOne:(n,e)=>{let o=P(n),s=D(e);return _dumbo.sql.call(void 0, `WITH cte AS (
|
|
11
11
|
SELECT _id FROM %I %s LIMIT 1
|
|
12
12
|
)
|
|
13
|
-
UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,y(o),t,s,t)},replaceOne:(n,e)=>{let o=P(n);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s",t,JSON.stringify(e),y(o))},updateMany:(n,e)=>{let o=P(n),s=D(e);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %s %s",t,s,y(o))},deleteOne:n=>{let e=P(n);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",t,y(e))},deleteMany:n=>{let e=P(n);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",t,y(e))},findOne:n=>{let e=P(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1",t,y(e))},find:n=>{let e=P(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s",t,y(e))},countDocuments:n=>{let e=P(n);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s",t,y(e))},rename:n=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I",t,n),drop:(n=t)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",n)}),y=t=>t.length>0?_dumbo.sql.call(void 0, "WHERE %s",t):_dumbo.rawSql.call(void 0, "");var A=t=>t.connectorType===_dumbo.NodePostgresConnectorType,U= exports.h =t=>{let{connectionString:n,dbName:e}=t,o=_nullishCoalesce(e, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, n))),s=_dumbo.dumbo.call(void 0, t),l={connectorType:t.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>s.close(),collection:T=>h({collectionName:T,db:l,sqlExecutor:s.execute,sqlBuilder:N(T)}),transaction:()=>s.transaction(),withTransaction:T=>s.withTransaction(T)};return l};var S=t=>{let{connectorType:n}=t;if(!A(t))throw new Error(`Unsupported db type: ${n}`);return U(t)};var k=t=>{let n=!1,e=!1,o=null,s=null;return{enlistDatabase:async l=>{if(s&&o!==l.databaseName)throw new Error("There's already other database assigned to transaction");return s&&o===l.databaseName||(o=l.databaseName,s=l.transaction(),await s.begin()),s},commit:async()=>{if(!s)throw new Error("No database transaction started!");if(!n){if(e)throw new Error("Transaction is not active!");n=!0,await s.commit(),s=null}},rollback:async l=>{if(!s)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");e||(e=!0,await s.rollback(l),s=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!e},get sqlExecutor(){if(s===null)throw new Error("No database transaction was started");return s.execute},options:t}};var b=t=>_optionalChain([t, 'optionalAccess', _2 => _2.isActive])===!0;function _(t){if(!b(t))throw new Error("No active transaction exists!")}function G(t){if(b(t))throw new Error("Active transaction already exists!")}var E=t=>{let n=_optionalChain([t, 'optionalAccess', _3 => _3.explicit])===!0,e=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _4 => _4.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,s=!1,l=i=>{G(o),o=k(_nullishCoalesce(i, () => (e)))},T=async()=>{_(o),await o.commit()},p=async()=>{_(o),await o.rollback()},r={get hasEnded(){return s},explicit:n,defaultTransactionOptions:_nullishCoalesce(e, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return e.snapshotEnabled},endSession:async()=>{s||(s=!0,b(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>b(o),startTransaction:l,commitTransaction:T,abortTransaction:p,withTransaction:async(i,a)=>{l(a);try{let c=await i(r);return await T(),c}catch(c){throw await p(),c}}};return r};var
|
|
14
|
-
//# sourceMappingURL=chunk-
|
|
13
|
+
UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,y(o),t,s,t)},replaceOne:(n,e)=>{let o=P(n);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s",t,JSON.stringify(e),y(o))},updateMany:(n,e)=>{let o=P(n),s=D(e);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %s %s",t,s,y(o))},deleteOne:n=>{let e=P(n);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",t,y(e))},deleteMany:n=>{let e=P(n);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",t,y(e))},findOne:n=>{let e=P(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1",t,y(e))},find:n=>{let e=P(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s",t,y(e))},countDocuments:n=>{let e=P(n);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s",t,y(e))},rename:n=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I",t,n),drop:(n=t)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",n)}),y=t=>t.length>0?_dumbo.sql.call(void 0, "WHERE %s",t):_dumbo.rawSql.call(void 0, "");var A=t=>t.connectorType===_dumbo.NodePostgresConnectorType,U= exports.h =t=>{let{connectionString:n,dbName:e}=t,o=_nullishCoalesce(e, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, n))),s=_dumbo.dumbo.call(void 0, t),l={connectorType:t.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>s.close(),collection:T=>h({collectionName:T,db:l,sqlExecutor:s.execute,sqlBuilder:N(T)}),transaction:()=>s.transaction(),withTransaction:T=>s.withTransaction(T)};return l};var S=t=>{let{connectorType:n}=t;if(!A(t))throw new Error(`Unsupported db type: ${n}`);return U(t)};var k=t=>{let n=!1,e=!1,o=null,s=null;return{enlistDatabase:async l=>{if(s&&o!==l.databaseName)throw new Error("There's already other database assigned to transaction");return s&&o===l.databaseName||(o=l.databaseName,s=l.transaction(),await s.begin()),s},commit:async()=>{if(!s)throw new Error("No database transaction started!");if(!n){if(e)throw new Error("Transaction is not active!");n=!0,await s.commit(),s=null}},rollback:async l=>{if(!s)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");e||(e=!0,await s.rollback(l),s=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!e},get sqlExecutor(){if(s===null)throw new Error("No database transaction was started");return s.execute},options:t}};var b=t=>_optionalChain([t, 'optionalAccess', _2 => _2.isActive])===!0;function _(t){if(!b(t))throw new Error("No active transaction exists!")}function G(t){if(b(t))throw new Error("Active transaction already exists!")}var E=t=>{let n=_optionalChain([t, 'optionalAccess', _3 => _3.explicit])===!0,e=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _4 => _4.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,s=!1,l=i=>{G(o),o=k(_nullishCoalesce(i, () => (e)))},T=async()=>{_(o),await o.commit()},p=async()=>{_(o),await o.rollback()},r={get hasEnded(){return s},explicit:n,defaultTransactionOptions:_nullishCoalesce(e, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return e.snapshotEnabled},endSession:async()=>{s||(s=!0,b(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>b(o),startTransaction:l,commitTransaction:T,abortTransaction:p,withTransaction:async(i,a)=>{l(a);try{let c=await i(r);return await T(),c}catch(c){throw await p(),c}}};return r};var jt=(t,n={})=>{let e=new Map,o=S(F({connectionString:t,clientOptions:n}));e.set(o.databaseName,o);let s={connect:async()=>(await o.connect(),s),close:async()=>{for(let l of e.values())await l.close()},db:l=>l?_nullishCoalesce(e.get(l), () => (e.set(l,S(F({connectionString:t,dbName:l,clientOptions:n}))).get(l))):o,startSession:E,withSession:async l=>{let T=E();try{return await l(T)}finally{await T.endSession()}}};return s},F= exports.m =t=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:t.connectionString,dbName:t.dbName,...t.clientOptions});var f=t=>Object.entries(t).map(([n,e])=>[n,e]);var et=async(t,n)=>{let e=_optionalChain([n, 'optionalAccess', _5 => _5.session, 'optionalAccess', _6 => _6.transaction]);return!e||!e.isActive?null:await e.enlistDatabase(t)},M=async(t,n,e)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await et(t,n)), 'optionalAccess', async _7 => _7.execute]), async () => (e)),h= exports.a =({db:t,collectionName:n,sqlExecutor:e,sqlBuilder:o})=>{let s=async(r,i)=>(await M(t,i,e)).command(r),l=async(r,i)=>(await M(t,i,e)).query(r),T=s(o.createCollection()),p=r=>_optionalChain([r, 'optionalAccess', _8 => _8.session])?s(o.createCollection(),r):T,g={dbName:t.databaseName,collectionName:n,createCollection:async r=>{await p(r)},insertOne:async(r,i)=>{await p(i);let a=_nullishCoalesce(r._id, () => (_uuid.v4.call(void 0, )));return(await s(o.insertOne({...r,_id:a}),i)).rowCount?{insertedId:a,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async(r,i)=>{await p(i);let a=r.map(O=>({...O,_id:_nullishCoalesce(O._id, () => (_uuid.v4.call(void 0, )))})),c=await s(o.insertMany(a),i);return{acknowledged:c.rowCount===a.length,insertedCount:_nullishCoalesce(c.rowCount, () => (0)),insertedIds:a.map(O=>O._id)}},updateOne:async(r,i,a)=>{await p(a);let c=await s(o.updateOne(r,i),a);return c.rowCount?{acknowledged:!0,modifiedCount:c.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(r,i,a)=>{await p(a);let c=await s(o.replaceOne(r,i),a);return c.rowCount?{acknowledged:!0,modifiedCount:c.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(r,i,a)=>{await p(a);let c=await s(o.updateMany(r,i),a);return c.rowCount?{acknowledged:!0,modifiedCount:c.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async(r,i)=>{await p(i);let a=await s(o.deleteOne(_nullishCoalesce(r, () => ({}))),i);return a.rowCount?{acknowledged:!0,deletedCount:a.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async(r,i)=>{await p(i);let a=await s(o.deleteMany(_nullishCoalesce(r, () => ({}))),i);return a.rowCount?{acknowledged:!0,deletedCount:a.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async(r,i)=>(await p(i),await _asyncNullishCoalesce(await _asyncOptionalChain([(await l(o.findOne(_nullishCoalesce(r, () => ({}))),i)), 'access', async _9 => _9.rows, 'access', async _10 => _10[0], 'optionalAccess', async _11 => _11.data]), async () => (null))),findOneAndDelete:async(r,i)=>{await p(i);let a=await g.findOne(r,i);return a===null?null:(await g.deleteOne(r,i),a)},findOneAndReplace:async(r,i,a)=>{await p(a);let c=await g.findOne(r,a);return c===null?null:(await g.replaceOne(r,i,a),c)},findOneAndUpdate:async(r,i,a)=>{await p(a);let c=await g.findOne(r,a);return c===null?null:(await g.updateOne(r,i,a),c)},handle:async(r,i,a)=>{await p(a);let c={_id:r},O=await g.findOne(c,a),m=await i(O);if(!O&&m){let x={...m,_id:r};return await g.insertOne({...x,_id:r},a),x}return O&&!m?(await g.deleteOne(c,a),null):(O&&m&&await g.replaceOne(c,m,a),m)},find:async(r,i)=>(await p(i),(await l(o.find(_nullishCoalesce(r, () => ({}))))).rows.map(c=>c.data)),countDocuments:async(r,i)=>{await p(i);let{count:a}=await _dumbo.single.call(void 0, l(o.countDocuments(_nullishCoalesce(r, () => ({})))));return a},drop:async r=>(await p(r),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await s(o.drop())), 'optionalAccess', async _12 => _12.rowCount]), async () => (0)))>0),rename:async(r,i)=>(await p(i),await s(o.rename(r)),n=r,g)};return g};exports.a = h; exports.b = $; exports.c = L; exports.d = q; exports.e = I; exports.f = N; exports.g = A; exports.h = U; exports.i = S; exports.j = k; exports.k = E; exports.l = jt; exports.m = F; exports.n = f;
|
|
14
|
+
//# sourceMappingURL=chunk-M74CIMXY.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/collection/pongoCollection.ts","../src/core/collection/query.ts","../src/core/pongoClient.ts","../src/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/index.ts","../src/core/pongoTransaction.ts"],"names":["QueryOperators","OperatorMap","isOperator","key","hasOperators","value","handleOperator","path","operator","handleIdOperator","sql","buildNestedObject","v","subQuery","entries","subKey","subValue"],"mappings":"AAAA,g3CAMO,4BACoB,ICPdA,CAAAA,CAAiB,CAC5B,GAAA,CAAK,KAAA,CACL,GAAA,CAAK,KAAA,CACL,IAAA,CAAM,MAAA,CACN,GAAA,CAAK,KAAA,CACL,IAAA,CAAM,MAAA,CACN,GAAA,CAAK,KAAA,CACL,GAAA,CAAK,KAAA,CACL,IAAA,CAAM,MAAA,CACN,UAAA,CAAY,YAAA,CACZ,IAAA,CAAM,MAAA,CACN,KAAA,CAAO,OACT,CAAA,CAEaC,CAAAA,aAAc,CACzB,GAAA,CAAK,GAAA,CACL,IAAA,CAAM,IAAA,CACN,GAAA,CAAK,GAAA,CACL,IAAA,CAAM,IAAA,CACN,GAAA,CAAK,IACP,CAAA,CAEaC,CAAAA,aAAcC,CAAAA,EAAgBA,CAAAA,CAAI,UAAA,CAAW,GAAG,CAAA,CAEhDC,CAAAA,aAAgBC,CAAAA,EAC3B,MAAA,CAAO,IAAA,CAAKA,CAAK,CAAA,CAAE,IAAA,CAAKH,CAAU,CAAA,CCzBpC,cAIe,ICDFI,CAAAA,CAAiB,CAC5BC,CAAAA,CACAC,CAAAA,CACAH,CAAAA,CAAAA,EACW,CACX,EAAA,CAAIE,CAAAA,GAAS,KAAA,CACX,OAAOE,CAAAA,CAAiBD,CAAAA,CAAUH,CAAK,CAAA,CAGzC,MAAA,CAAQG,CAAAA,CAAU,CAChB,IAAK,KAAA,CACH,OAAOE,wBAAAA,uEACL,CACA,IAAA,CAAK,SAAA,CAAUC,CAAAA,CAAkBJ,CAAAA,CAAMF,CAAK,CAAC,CAAA,CA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AQ,CACxE,CACA,IAAK,MAAA,CACH,OAAOH,wBAAAA,mBACL,CACA,IAAA,CAAK,SAAA,CAAUC,CAAAA,CAAkBJ,CAAAA,CAAMF,CAAK,CAAC,CAC/C,CAAA,CACF,IAAK,OAAA,CACH,OAAOK,wBAAAA,qCACL,CACA,CAAA,CAAA,EAAIH,CAAAA,CAAK,KAAA,CAAM,GAAG,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAA,CAC7BF,CACF,CAAA,CACF,OAAA,CACE,MAAM,IAAI,KAAA,CAAM,CAAA,sBAAA,EAAyBG,CAAQ,CAAA,CAAA;AC9CjD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BA,KAAA;AAAA;AAAA;AChBF,6DAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-M74CIMXY.cjs","sourcesContent":["import {\n single,\n type DatabaseTransaction,\n type QueryResultRow,\n type SQL,\n type SQLExecutor,\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 '..';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n sqlExecutor: SQLExecutor;\n sqlBuilder: PongoCollectionSQLBuilder;\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 sqlExecutor,\n sqlBuilder: SqlFor,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\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 const createCollectionPromise = command(SqlFor.createCollection());\n const createCollection = (options?: CollectionOperationOptions) =>\n options?.session\n ? command(SqlFor.createCollection(), options)\n : createCollectionPromise;\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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n };\n\n return collection;\n};\n\nexport type PongoCollectionSQLBuilder = {\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","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 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';\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 | PooledPongoClientOptions\n | NotPooledPongoOptions;\n\nexport const pongoClient = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions = {},\n): PongoClient => {\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 pongoClient;\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 { sql } from '@event-driven-io/dumbo';\nimport { entries, OperatorMap } from '../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return sql(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSON.stringify(buildNestedObject(path, value)),\n path,\n JSON.stringify(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return sql(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n sql(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return sql(`jsonb_path_exists(data, '$.%s[*] ? (%s)')`, path, subQuery);\n }\n case '$all':\n return sql(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return sql(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return sql(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return sql(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import { rawSql, sql, type SQL } 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\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n createCollection: (): 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 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 type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkM74CIMXYcjs = require('./chunk-M74CIMXY.cjs');exports.OperatorMap = _chunkM74CIMXYcjs.c; exports.QueryOperators = _chunkM74CIMXYcjs.b; exports.clientToDbOptions = _chunkM74CIMXYcjs.m; exports.entries = _chunkM74CIMXYcjs.n; exports.getPongoDb = _chunkM74CIMXYcjs.i; exports.hasOperators = _chunkM74CIMXYcjs.e; exports.isOperator = _chunkM74CIMXYcjs.d; exports.isPostgresClientOptions = _chunkM74CIMXYcjs.g; exports.pongoClient = _chunkM74CIMXYcjs.l; exports.pongoCollection = _chunkM74CIMXYcjs.a; exports.pongoSession = _chunkM74CIMXYcjs.k; exports.pongoTransaction = _chunkM74CIMXYcjs.j; exports.postgresDb = _chunkM74CIMXYcjs.h; exports.postgresSQLBuilder = _chunkM74CIMXYcjs.f;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"],"names":[],"mappings":"AAAA,iIAAmI,ynBAAsR","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/index.cjs"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { SQLExecutor, 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 PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './
|
|
3
|
-
export { y as $inc, z as $push, $ as $set, x as $unset, A as AllowedDbClientOptions, t as AlternativeType, C as CollectionOperationOptions, u as Condition, D as Document, M as DocumentHandler, E as EnhancedOmit, H as HasId, I as InferIdType, s as NonObjectIdLikeDocument, N as NotPooledPongoOptions, n as ObjectId, r as ObjectIdLike, q as OptionalId, m as PongoClient, i as PongoClientOptions, k as PongoDbClientOptions, L as PongoDeleteManyResult, K as PongoDeleteResult, w as PongoFilterOperator, F as PongoInsertManyResult, B as PongoInsertOneResult, J as PongoUpdateManyResult, G as PongoUpdateResult, h as PooledPongoClientOptions, Q as PostgresDbClientOptions, R as RegExpOrString, v as RootFilterOperators, o as WithId, j as clientToDbOptions, l as getPongoDb, S as isPostgresClientOptions, p as pongoClient, T as postgresDb } from './
|
|
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-BXyaQhyS.cjs';
|
|
3
|
+
export { y as $inc, z as $push, $ as $set, x as $unset, A as AllowedDbClientOptions, t as AlternativeType, C as CollectionOperationOptions, u as Condition, D as Document, M as DocumentHandler, E as EnhancedOmit, H as HasId, I as InferIdType, s as NonObjectIdLikeDocument, N as NotPooledPongoOptions, n as ObjectId, r as ObjectIdLike, q as OptionalId, m as PongoClient, i as PongoClientOptions, k as PongoDbClientOptions, L as PongoDeleteManyResult, K as PongoDeleteResult, w as PongoFilterOperator, F as PongoInsertManyResult, B as PongoInsertOneResult, J as PongoUpdateManyResult, G as PongoUpdateResult, h as PooledPongoClientOptions, Q as PostgresDbClientOptions, R as RegExpOrString, v as RootFilterOperators, o as WithId, j as clientToDbOptions, l as getPongoDb, S as isPostgresClientOptions, p as pongoClient, T as postgresDb } from './pongoClient-BXyaQhyS.cjs';
|
|
4
4
|
import 'pg';
|
|
5
5
|
|
|
6
6
|
type PongoCollectionOptions<ConnectorType extends string = string> = {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { SQLExecutor, 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 PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './
|
|
3
|
-
export { y as $inc, z as $push, $ as $set, x as $unset, A as AllowedDbClientOptions, t as AlternativeType, C as CollectionOperationOptions, u as Condition, D as Document, M as DocumentHandler, E as EnhancedOmit, H as HasId, I as InferIdType, s as NonObjectIdLikeDocument, N as NotPooledPongoOptions, n as ObjectId, r as ObjectIdLike, q as OptionalId, m as PongoClient, i as PongoClientOptions, k as PongoDbClientOptions, L as PongoDeleteManyResult, K as PongoDeleteResult, w as PongoFilterOperator, F as PongoInsertManyResult, B as PongoInsertOneResult, J as PongoUpdateManyResult, G as PongoUpdateResult, h as PooledPongoClientOptions, Q as PostgresDbClientOptions, R as RegExpOrString, v as RootFilterOperators, o as WithId, j as clientToDbOptions, l as getPongoDb, S as isPostgresClientOptions, p as pongoClient, T as postgresDb } from './
|
|
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-BXyaQhyS.js';
|
|
3
|
+
export { y as $inc, z as $push, $ as $set, x as $unset, A as AllowedDbClientOptions, t as AlternativeType, C as CollectionOperationOptions, u as Condition, D as Document, M as DocumentHandler, E as EnhancedOmit, H as HasId, I as InferIdType, s as NonObjectIdLikeDocument, N as NotPooledPongoOptions, n as ObjectId, r as ObjectIdLike, q as OptionalId, m as PongoClient, i as PongoClientOptions, k as PongoDbClientOptions, L as PongoDeleteManyResult, K as PongoDeleteResult, w as PongoFilterOperator, F as PongoInsertManyResult, B as PongoInsertOneResult, J as PongoUpdateManyResult, G as PongoUpdateResult, h as PooledPongoClientOptions, Q as PostgresDbClientOptions, R as RegExpOrString, v as RootFilterOperators, o as WithId, j as clientToDbOptions, l as getPongoDb, S as isPostgresClientOptions, p as pongoClient, T as postgresDb } from './pongoClient-BXyaQhyS.js';
|
|
4
4
|
import 'pg';
|
|
5
5
|
|
|
6
6
|
type PongoCollectionOptions<ConnectorType extends string = string> = {
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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}from"./chunk-
|
|
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}from"./chunk-G2D34XRD.js";export{e as OperatorMap,r as QueryOperators,g as clientToDbOptions,h as entries,a as getPongoDb,m as hasOperators,f as isOperator,t as isPostgresClientOptions,d as pongoClient,o as pongoCollection,c as pongoSession,b as pongoTransaction,x as postgresDb,p as postgresSQLBuilder};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -178,6 +178,14 @@ interface PongoDeleteManyResult {
|
|
|
178
178
|
type PongoDocument = Record<string, unknown>;
|
|
179
179
|
type DocumentHandler<T extends PongoDocument> = ((document: T | null) => T | null) | ((document: T | null) => Promise<T | null>);
|
|
180
180
|
|
|
181
|
+
type PongoDbClientOptions<ConnectorType extends string = string> = {
|
|
182
|
+
connectorType: ConnectorType;
|
|
183
|
+
connectionString: string;
|
|
184
|
+
dbName: string | undefined;
|
|
185
|
+
};
|
|
186
|
+
type AllowedDbClientOptions = PostgresDbClientOptions;
|
|
187
|
+
declare const getPongoDb: <DbClientOptions extends AllowedDbClientOptions = PostgresDbClientOptions>(options: DbClientOptions) => PongoDb;
|
|
188
|
+
|
|
181
189
|
type PooledPongoClientOptions = {
|
|
182
190
|
pool: pg.Pool;
|
|
183
191
|
} | {
|
|
@@ -185,7 +193,7 @@ type PooledPongoClientOptions = {
|
|
|
185
193
|
} | {
|
|
186
194
|
pool: pg.Pool;
|
|
187
195
|
pooled: true;
|
|
188
|
-
} |
|
|
196
|
+
} | object;
|
|
189
197
|
type NotPooledPongoOptions = {
|
|
190
198
|
client: pg.Client;
|
|
191
199
|
} | {
|
|
@@ -198,19 +206,11 @@ type NotPooledPongoOptions = {
|
|
|
198
206
|
pooled?: false;
|
|
199
207
|
};
|
|
200
208
|
type PongoClientOptions = PooledPongoClientOptions | NotPooledPongoOptions;
|
|
201
|
-
declare const pongoClient: <DbClientOptions extends
|
|
202
|
-
declare const clientToDbOptions: <DbClientOptions extends
|
|
209
|
+
declare const pongoClient: <DbClientOptions extends AllowedDbClientOptions = PostgresDbClientOptions>(connectionString: string, options?: PongoClientOptions) => PongoClient;
|
|
210
|
+
declare const clientToDbOptions: <DbClientOptions extends AllowedDbClientOptions = PostgresDbClientOptions>(options: {
|
|
203
211
|
connectionString: string;
|
|
204
212
|
dbName?: string;
|
|
205
213
|
clientOptions: PongoClientOptions;
|
|
206
214
|
}) => DbClientOptions;
|
|
207
215
|
|
|
208
|
-
type PongoDbClientOptions<ConnectorType extends string = string> = {
|
|
209
|
-
connectorType: ConnectorType;
|
|
210
|
-
connectionString: string;
|
|
211
|
-
dbName: string | undefined;
|
|
212
|
-
};
|
|
213
|
-
type AllowedDbClientOptions = PostgresDbClientOptions;
|
|
214
|
-
declare const getPongoDb: <DbClientOptions extends PostgresDbClientOptions = PostgresDbClientOptions>(options: DbClientOptions) => PongoDb;
|
|
215
|
-
|
|
216
216
|
export { type $set as $, type AllowedDbClientOptions as A, type PongoInsertOneResult as B, type CollectionOperationOptions as C, type Document as D, type EnhancedOmit as E, type PongoInsertManyResult as F, type PongoUpdateResult as G, type HasId as H, type InferIdType as I, type PongoUpdateManyResult as J, type PongoDeleteResult as K, type PongoDeleteManyResult as L, type DocumentHandler as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredId as O, type PongoDb as P, type PostgresDbClientOptions as Q, type RegExpOrString as R, isPostgresClientOptions as S, postgresDb as T, type WithoutId as W, type PongoDocument as a, type PongoCollection as b, type PongoFilter as c, type PongoUpdate as d, type PongoTransactionOptions as e, type PongoSession as f, type PongoDbTransaction as g, type PooledPongoClientOptions as h, type PongoClientOptions as i, clientToDbOptions as j, type PongoDbClientOptions as k, getPongoDb as l, type PongoClient as m, type ObjectId as n, type WithId as o, pongoClient as p, type OptionalId as q, type ObjectIdLike as r, type NonObjectIdLikeDocument as s, type AlternativeType as t, type Condition as u, type RootFilterOperators as v, type PongoFilterOperator as w, type $unset as x, type $inc as y, type $push as z };
|
|
@@ -178,6 +178,14 @@ interface PongoDeleteManyResult {
|
|
|
178
178
|
type PongoDocument = Record<string, unknown>;
|
|
179
179
|
type DocumentHandler<T extends PongoDocument> = ((document: T | null) => T | null) | ((document: T | null) => Promise<T | null>);
|
|
180
180
|
|
|
181
|
+
type PongoDbClientOptions<ConnectorType extends string = string> = {
|
|
182
|
+
connectorType: ConnectorType;
|
|
183
|
+
connectionString: string;
|
|
184
|
+
dbName: string | undefined;
|
|
185
|
+
};
|
|
186
|
+
type AllowedDbClientOptions = PostgresDbClientOptions;
|
|
187
|
+
declare const getPongoDb: <DbClientOptions extends AllowedDbClientOptions = PostgresDbClientOptions>(options: DbClientOptions) => PongoDb;
|
|
188
|
+
|
|
181
189
|
type PooledPongoClientOptions = {
|
|
182
190
|
pool: pg.Pool;
|
|
183
191
|
} | {
|
|
@@ -185,7 +193,7 @@ type PooledPongoClientOptions = {
|
|
|
185
193
|
} | {
|
|
186
194
|
pool: pg.Pool;
|
|
187
195
|
pooled: true;
|
|
188
|
-
} |
|
|
196
|
+
} | object;
|
|
189
197
|
type NotPooledPongoOptions = {
|
|
190
198
|
client: pg.Client;
|
|
191
199
|
} | {
|
|
@@ -198,19 +206,11 @@ type NotPooledPongoOptions = {
|
|
|
198
206
|
pooled?: false;
|
|
199
207
|
};
|
|
200
208
|
type PongoClientOptions = PooledPongoClientOptions | NotPooledPongoOptions;
|
|
201
|
-
declare const pongoClient: <DbClientOptions extends
|
|
202
|
-
declare const clientToDbOptions: <DbClientOptions extends
|
|
209
|
+
declare const pongoClient: <DbClientOptions extends AllowedDbClientOptions = PostgresDbClientOptions>(connectionString: string, options?: PongoClientOptions) => PongoClient;
|
|
210
|
+
declare const clientToDbOptions: <DbClientOptions extends AllowedDbClientOptions = PostgresDbClientOptions>(options: {
|
|
203
211
|
connectionString: string;
|
|
204
212
|
dbName?: string;
|
|
205
213
|
clientOptions: PongoClientOptions;
|
|
206
214
|
}) => DbClientOptions;
|
|
207
215
|
|
|
208
|
-
type PongoDbClientOptions<ConnectorType extends string = string> = {
|
|
209
|
-
connectorType: ConnectorType;
|
|
210
|
-
connectionString: string;
|
|
211
|
-
dbName: string | undefined;
|
|
212
|
-
};
|
|
213
|
-
type AllowedDbClientOptions = PostgresDbClientOptions;
|
|
214
|
-
declare const getPongoDb: <DbClientOptions extends PostgresDbClientOptions = PostgresDbClientOptions>(options: DbClientOptions) => PongoDb;
|
|
215
|
-
|
|
216
216
|
export { type $set as $, type AllowedDbClientOptions as A, type PongoInsertOneResult as B, type CollectionOperationOptions as C, type Document as D, type EnhancedOmit as E, type PongoInsertManyResult as F, type PongoUpdateResult as G, type HasId as H, type InferIdType as I, type PongoUpdateManyResult as J, type PongoDeleteResult as K, type PongoDeleteManyResult as L, type DocumentHandler as M, type NotPooledPongoOptions as N, type OptionalUnlessRequiredId as O, type PongoDb as P, type PostgresDbClientOptions as Q, type RegExpOrString as R, isPostgresClientOptions as S, postgresDb as T, type WithoutId as W, type PongoDocument as a, type PongoCollection as b, type PongoFilter as c, type PongoUpdate as d, type PongoTransactionOptions as e, type PongoSession as f, type PongoDbTransaction as g, type PooledPongoClientOptions as h, type PongoClientOptions as i, clientToDbOptions as j, type PongoDbClientOptions as k, getPongoDb as l, type PongoClient as m, type ObjectId as n, type WithId as o, pongoClient as p, type OptionalId as q, type ObjectIdLike as r, type NonObjectIdLikeDocument as s, type AlternativeType as t, type Condition as u, type RootFilterOperators as v, type PongoFilterOperator as w, type $unset as x, type $inc as y, type $push 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 _chunkM74CIMXYcjs = require('./chunk-M74CIMXY.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=_chunkM74CIMXYcjs.l.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 _chunkM74CIMXYcjs.k.call(void 0, )}async withSession(e,n){let t=typeof e=="function"?e:n,i=_chunkM74CIMXYcjs.k.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.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"names":["FindCursor","documents","callback","docs","doc","toCollectionOperationOptions","options","Collection","collection","v","result","_operations","_options","filter","update","document","newName","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_filter","replacement","_pipeline","_name","_description","_descriptions","_definition","id","handle","Db","pongoDb","collectionName","MongoClient","connectionString","pongoClient","dbName","pongoSession","optionsOrExecutor","executor","session"],"mappings":"gDAAO,IAAMA,EAAN,KAAoB,CACjB,qBACA,UAAwB,KACxB,MAAgB,EAExB,YAAYC,EAAyB,CACnC,KAAK,qBAAuBA,CAC9B,CAEA,MAAM,SAAwB,CAC5B,OAAO,KAAK,cAAc,CAC5B,CAEA,MAAM,QAAQC,EAA2C,CACvD,IAAMC,EAAO,MAAM,KAAK,cAAc,EAEtC,QAAWC,KAAOD,EAChBD,EAASE,CAAG,EAEd,OAAO,QAAQ,QAAQ,CACzB,CAEA,SAAmB,CACjB,GAAI,KAAK,YAAc,KAAM,MAAM,MAAM,gCAAgC,EACzE,OAAO,KAAK,MAAQ,KAAK,UAAU,MACrC,CAEA,MAAM,MAA0B,CAC9B,IAAMD,E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Z,IAAMtC,EACJ,OAAOqC,GAAsB,WAAaA,EAAoBC,EAE1DC,EAAUH,EAAa,EAE7B,GAAI,CACF,OAAO,MAAMpC,EAASuC,CAAO,CAC/B,QAAE,CACA,MAAMA,EAAQ,WAAW,CAC3B,CACF,CACF","sourcesContent":["export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import {\n Collection as MongoCollection,\n ObjectId,\n type Document,\n} from 'mongodb';\nimport type { DocumentHandler, PongoDb } from '../core';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n get databaseName(): string {\n return this.pongoDb.databaseName;\n }\n\n collection<T extends Document>(\n collectionName: string,\n ): MongoCollection<T> & {\n handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null>;\n } {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n ObjectId,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type {\n CollectionOperationOptions,\n DocumentHandler,\n PongoCollection,\n PongoFilter,\n OptionalUnlessRequiredId as PongoOptionalUnlessRequiredId,\n PongoSession,\n PongoUpdate,\n} from '../core';\nimport { FindCursor } from './findCursor';\n\nconst toCollectionOperationOptions = (\n options: OperationOptions | undefined,\n): CollectionOperationOptions | undefined =>\n options?.session\n ? { session: options.session as unknown as PongoSession }\n : undefined;\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n return this.collection.dbName;\n }\n get collectionName(): string {\n return this.collection.collectionName;\n }\n get namespace(): string {\n return `${this.dbName}.${this.collectionName}`;\n }\n get readConcern(): ReadConcern | undefined {\n return undefined;\n }\n get readPreference(): ReadPreference | undefined {\n return undefined;\n }\n get bsonOptions(): BSONSerializeOptions {\n return {};\n }\n get writeConcern(): WriteConcern | undefined {\n return undefined;\n }\n get hint(): Hint | undefined {\n return undefined;\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(\n doc as unknown as PongoOptionalUnlessRequiredId<T>,\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n async insertMany(\n docs: OptionalUnlessRequiredId<T>[],\n options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n const result = await this.collection.insertMany(\n docs as unknown as PongoOptionalUnlessRequiredId<T>[],\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedIds: result.insertedIds as unknown as InferIdType<T>[],\n insertedCount: result.insertedCount,\n };\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n filter: Filter<T>,\n document: WithoutId<T>,\n options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n return this.collection.replaceOne(\n filter as unknown as PongoFilter<T>,\n document,\n toCollectionOperationOptions(options),\n );\n }\n async updateMany(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateMany(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async deleteMany(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteMany(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async rename(\n newName: string,\n options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n await this.collection.rename(\n newName,\n toCollectionOperationOptions(options),\n );\n\n return this as unknown as Collection<Document>;\n }\n drop(options?: DropCollectionOptions | undefined): Promise<boolean> {\n return this.collection.drop(toCollectionOperationOptions(options));\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n {},\n toCollectionOperationOptions(options),\n );\n }\n countDocuments(\n filter?: Filter<T> | undefined,\n options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: unknown,\n options?: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndDelete(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: unknown,\n replacement: unknown,\n options?: FindOneAndReplaceOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndReplace(\n filter as PongoFilter<T>,\n replacement as WithoutId<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: unknown,\n update: unknown,\n options?: FindOneAndUpdateOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndUpdate(\n filter as PongoFilter<T>,\n update as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n filter?: Filter<T> | undefined,\n options?: CountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n (filter as PongoFilter<T>) ?? {},\n toCollectionOperationOptions(options),\n );\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n async handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null> {\n return this.collection.handle(id.toString(), handle);\n }\n}\n","import type { ClientSessionOptions } from 'http2';\nimport type { ClientSession, WithSessionCallback } from 'mongodb';\nimport {\n pongoClient,\n pongoSession,\n type PongoClient,\n type PongoClientOptions,\n} from '../core';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string, options: PongoClientOptions = {}) {\n this.pongoClient = pongoClient(connectionString, options);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName?: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n startSession(_options?: ClientSessionOptions): ClientSession {\n return pongoSession() as unknown as ClientSession;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withSession<T = any>(_executor: WithSessionCallback<T>): Promise<T>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withSession<T = any>(\n _options: ClientSessionOptions,\n _executor: WithSessionCallback<T>,\n ): Promise<T>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async withSession<T = any>(\n optionsOrExecutor: ClientSessionOptions | WithSessionCallback<T>,\n executor?: WithSessionCallback<T>,\n ): Promise<T> {\n const callback =\n typeof optionsOrExecutor === 'function' ? optionsOrExecutor : executor!;\n\n const session = pongoSession() as unknown as ClientSession;\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/shim.cjs","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts"],"names":["FindCursor","documents","callback","docs","doc","toCollectionOperationOptions","options","Collection","collection"],"mappings":"AAAA,qvBAA+C,ICAlCA,CAAAA,WAAN,KAAoB,CACjB,eACA,SAAA,CAAwB,KAAA,gBACxB,KAAA,CAAgB,EAAA,WAExB,CAAYC,CAAAA,CAAyB,yEACnC,IAAA,CAAK,oBAAA,CAAuBA,CAC9B,CAEA,MAAM,OAAA,CAAA,CAAwB,CAC5B,OAAO,IAAA,CAAK,aAAA,CAAc,CAC5B,CAEA,MAAM,OAAA,CAAQC,CAAAA,CAA2C,CACvD,IAAMC,CAAAA,CAAO,MAAM,IAAA,CAAK,aAAA,CAAc,CAAA,CAEtC,GAAA,CAAA,IAAWC,EAAAA,GAAOD,CAAAA,CAChBD,CAAAA,CAASE,CAAG,CAAA,CAEd,OAAO,OAAA,CAAQ,OAAA,CAAQ,CACzB,CAEA,OAAA,CAAA,CAAmB,CACjB,EAAA,CAAI,IAAA,CAAK,SAAA,GAAc,IAAA,CAAM,MAAM,KAAA,CAAM,gCAAgC,CAAA,CACzE,OAAO,IAAA,CAAK,KAAA,CAAQ,IAAA,CAAK,SAAA,CAAU,MACrC,CAEA,MAAM,IAAA,CAAA,CAA0B,CAC9B,IAAMD,CAAAA,CAAO,MAAM,IAAA,CAAK,aAAA,CAAc,CAAA,CACtC,OAAO,IAAA,CAAK,OAAA,CAAQ,CAAA,kBAAKA,CAAAA,CAAK,IAAA,CAAK,KAAA,EAAO,CAAA,SAAK,MAAA,CAAQ,IACzD,CAEA,MAAc,aAAA,CAAA,CAA8B,CAC1C,OAAA,IAAA,CAAK,SAAA,CAAY,MAAM,IAAA,CAAK,oBAAA,CACrB,IAAA,CAAK,SACd,CACF,UAAA,CCpCA,mBAIO,ICoEDE,CAAAA,CACJC,CAAAA,kBAEAA,CAAAA,2BAAS,SAAA,CACL,CAAE,OAAA,CAASA,CAAAA,CAAQ,OAAmC,CAAA,CACtD,KAAA,CAAA,CAEOC,CAAAA,sBAAN,KAAmE,CAChE,WAER,CAAYC,CAAAA,CAAgC,CAC1C,IAAA,CAAK,UAAA,CAAaA,CACpB,CACA,IAAI,MAAA,CAAA,CAAiB,CACnB,OAAO,IAAA,CAAK,UAAA,CAAW,MACzB,CACA,IAAI,cAAA,CAAA,CAAyB,CAC3B,OAAO,IAAA,CAAK,UAAA,CAAW,cACzB,CACA,IAAI,SAAA,CAAA,CAAoB,CACtB,MAAO,CAAA,EAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/shim.cjs","sourcesContent":[null,"export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? (docs[this.index++] ?? null) : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import {\n Collection as MongoCollection,\n ObjectId,\n type Document,\n} from 'mongodb';\nimport type { DocumentHandler, PongoDb } from '../core';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n get databaseName(): string {\n return this.pongoDb.databaseName;\n }\n\n collection<T extends Document>(\n collectionName: string,\n ): MongoCollection<T> & {\n handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null>;\n } {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n ObjectId,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type {\n CollectionOperationOptions,\n DocumentHandler,\n PongoCollection,\n PongoFilter,\n OptionalUnlessRequiredId as PongoOptionalUnlessRequiredId,\n PongoSession,\n PongoUpdate,\n} from '../core';\nimport { FindCursor } from './findCursor';\n\nconst toCollectionOperationOptions = (\n options: OperationOptions | undefined,\n): CollectionOperationOptions | undefined =>\n options?.session\n ? { session: options.session as unknown as PongoSession }\n : undefined;\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n return this.collection.dbName;\n }\n get collectionName(): string {\n return this.collection.collectionName;\n }\n get namespace(): string {\n return `${this.dbName}.${this.collectionName}`;\n }\n get readConcern(): ReadConcern | undefined {\n return undefined;\n }\n get readPreference(): ReadPreference | undefined {\n return undefined;\n }\n get bsonOptions(): BSONSerializeOptions {\n return {};\n }\n get writeConcern(): WriteConcern | undefined {\n return undefined;\n }\n get hint(): Hint | undefined {\n return undefined;\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(\n doc as unknown as PongoOptionalUnlessRequiredId<T>,\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n async insertMany(\n docs: OptionalUnlessRequiredId<T>[],\n options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n const result = await this.collection.insertMany(\n docs as unknown as PongoOptionalUnlessRequiredId<T>[],\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedIds: result.insertedIds as unknown as InferIdType<T>[],\n insertedCount: result.insertedCount,\n };\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n filter: Filter<T>,\n document: WithoutId<T>,\n options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n return this.collection.replaceOne(\n filter as unknown as PongoFilter<T>,\n document,\n toCollectionOperationOptions(options),\n );\n }\n async updateMany(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateMany(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async deleteMany(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteMany(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async rename(\n newName: string,\n options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n await this.collection.rename(\n newName,\n toCollectionOperationOptions(options),\n );\n\n return this as unknown as Collection<Document>;\n }\n drop(options?: DropCollectionOptions | undefined): Promise<boolean> {\n return this.collection.drop(toCollectionOperationOptions(options));\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n {},\n toCollectionOperationOptions(options),\n );\n }\n countDocuments(\n filter?: Filter<T> | undefined,\n options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: unknown,\n options?: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndDelete(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: unknown,\n replacement: unknown,\n options?: FindOneAndReplaceOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndReplace(\n filter as PongoFilter<T>,\n replacement as WithoutId<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: unknown,\n update: unknown,\n options?: FindOneAndUpdateOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndUpdate(\n filter as PongoFilter<T>,\n update as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n filter?: Filter<T> | undefined,\n options?: CountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n (filter as PongoFilter<T>) ?? {},\n toCollectionOperationOptions(options),\n );\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n async handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null> {\n return this.collection.handle(id.toString(), handle);\n }\n}\n"]}
|
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, M as DocumentHandler, i as PongoClientOptions, b as PongoCollection } from './
|
|
3
|
+
import { P as PongoDb, M as DocumentHandler, i as PongoClientOptions, b as PongoCollection } from './pongoClient-BXyaQhyS.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, M as DocumentHandler, i as PongoClientOptions, b as PongoCollection } from './
|
|
3
|
+
import { P as PongoDb, M as DocumentHandler, i as PongoClientOptions, b as PongoCollection } from './pongoClient-BXyaQhyS.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{k as a,l as p}from"./chunk-
|
|
1
|
+
import{k as a,l as p}from"./chunk-G2D34XRD.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/dist/shim.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"sourcesContent":["export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import {\n Collection as MongoCollection,\n ObjectId,\n type Document,\n} from 'mongodb';\nimport type { DocumentHandler, PongoDb } from '../core';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n get databaseName(): string {\n return this.pongoDb.databaseName;\n }\n\n collection<T extends Document>(\n collectionName: string,\n ): MongoCollection<T> & {\n handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null>;\n } {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n ObjectId,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type {\n CollectionOperationOptions,\n DocumentHandler,\n PongoCollection,\n PongoFilter,\n OptionalUnlessRequiredId as PongoOptionalUnlessRequiredId,\n PongoSession,\n PongoUpdate,\n} from '../core';\nimport { FindCursor } from './findCursor';\n\nconst toCollectionOperationOptions = (\n options: OperationOptions | undefined,\n): CollectionOperationOptions | undefined =>\n options?.session\n ? { session: options.session as unknown as PongoSession }\n : undefined;\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n return this.collection.dbName;\n }\n get collectionName(): string {\n return this.collection.collectionName;\n }\n get namespace(): string {\n return `${this.dbName}.${this.collectionName}`;\n }\n get readConcern(): ReadConcern | undefined {\n return undefined;\n }\n get readPreference(): ReadPreference | undefined {\n return undefined;\n }\n get bsonOptions(): BSONSerializeOptions {\n return {};\n }\n get writeConcern(): WriteConcern | undefined {\n return undefined;\n }\n get hint(): Hint | undefined {\n return undefined;\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(\n doc as unknown as PongoOptionalUnlessRequiredId<T>,\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n async insertMany(\n docs: OptionalUnlessRequiredId<T>[],\n options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n const result = await this.collection.insertMany(\n docs as unknown as PongoOptionalUnlessRequiredId<T>[],\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedIds: result.insertedIds as unknown as InferIdType<T>[],\n insertedCount: result.insertedCount,\n };\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n filter: Filter<T>,\n document: WithoutId<T>,\n options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n return this.collection.replaceOne(\n filter as unknown as PongoFilter<T>,\n document,\n toCollectionOperationOptions(options),\n );\n }\n async updateMany(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateMany(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async deleteMany(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteMany(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async rename(\n newName: string,\n options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n await this.collection.rename(\n newName,\n toCollectionOperationOptions(options),\n );\n\n return this as unknown as Collection<Document>;\n }\n drop(options?: DropCollectionOptions | undefined): Promise<boolean> {\n return this.collection.drop(toCollectionOperationOptions(options));\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n {},\n toCollectionOperationOptions(options),\n );\n }\n countDocuments(\n filter?: Filter<T> | undefined,\n options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: unknown,\n options?: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndDelete(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: unknown,\n replacement: unknown,\n options?: FindOneAndReplaceOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndReplace(\n filter as PongoFilter<T>,\n replacement as WithoutId<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: unknown,\n update: unknown,\n options?: FindOneAndUpdateOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndUpdate(\n filter as PongoFilter<T>,\n update as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n filter?: Filter<T> | undefined,\n options?: CountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n (filter as PongoFilter<T>) ?? {},\n toCollectionOperationOptions(options),\n );\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n async handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null> {\n return this.collection.handle(id.toString(), handle);\n }\n}\n","import type { ClientSessionOptions } from 'http2';\nimport type { ClientSession, WithSessionCallback } from 'mongodb';\nimport {\n pongoClient,\n pongoSession,\n type PongoClient,\n type PongoClientOptions,\n} from '../core';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string, options: PongoClientOptions = {}) {\n this.pongoClient = pongoClient(connectionString, options);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName?: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n startSession(_options?: ClientSessionOptions): ClientSession {\n return pongoSession() as unknown as ClientSession;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withSession<T = any>(_executor: WithSessionCallback<T>): Promise<T>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withSession<T = any>(\n _options: ClientSessionOptions,\n _executor: WithSessionCallback<T>,\n ): Promise<T>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async withSession<T = any>(\n optionsOrExecutor: ClientSessionOptions | WithSessionCallback<T>,\n executor?: WithSessionCallback<T>,\n ): Promise<T> {\n const callback =\n typeof optionsOrExecutor === 'function' ? optionsOrExecutor : executor!;\n\n const session = pongoSession() as unknown as ClientSession;\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n }\n}\n"],"mappings":"+CAAO,IAAMA,EAAN,KAAoB,CACjB,qBACA,UAAwB,KACxB,MAAgB,EAExB,YAAYC,EAAyB,CACn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EAA8B,CAAC,EAAG,CACtE,KAAK,YAAcC,EAAYF,EAAkBC,CAAO,CAC1D,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGE,EAAqB,CACtB,OAAO,IAAIC,EAAG,KAAK,YAAY,GAAGD,CAAM,CAAC,CAC3C,CACA,aAAaE,EAAgD,CAC3D,OAAOC,EAAa,CACtB,CASA,MAAM,YACJC,EACAC,EACY,CACZ,IAAMC,EACJ,OAAOF,GAAsB,WAAaA,EAAoBC,EAE1DE,EAAUJ,EAAa,EAE7B,GAAI,CACF,OAAO,MAAMG,EAASC,CAAO,CAC/B,QAAE,CACA,MAAMA,EAAQ,WAAW,CAC3B,CACF,CACF","names":["FindCursor","documents","callback","docs","doc","toCollectionOperationOptions","options","Collection","collection","v","doc","result","docs","_operations","_options","filter","update","document","newName","FindCursor","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_filter","replacement","_pipeline","_name","_description","_descriptions","_definition","id","handle","Db","pongoDb","collectionName","Collection","MongoClient","connectionString","options","pongoClient","dbName","Db","_options","pongoSession","optionsOrExecutor","executor","callback","session"]}
|
|
1
|
+
{"version":3,"sources":["../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"sourcesContent":["export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? (docs[this.index++] ?? null) : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import {\n Collection as MongoCollection,\n ObjectId,\n type Document,\n} from 'mongodb';\nimport type { DocumentHandler, PongoDb } from '../core';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n get databaseName(): string {\n return this.pongoDb.databaseName;\n }\n\n collection<T extends Document>(\n collectionName: string,\n ): MongoCollection<T> & {\n handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null>;\n } {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n ObjectId,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type {\n CollectionOperationOptions,\n DocumentHandler,\n PongoCollection,\n PongoFilter,\n OptionalUnlessRequiredId as PongoOptionalUnlessRequiredId,\n PongoSession,\n PongoUpdate,\n} from '../core';\nimport { FindCursor } from './findCursor';\n\nconst toCollectionOperationOptions = (\n options: OperationOptions | undefined,\n): CollectionOperationOptions | undefined =>\n options?.session\n ? { session: options.session as unknown as PongoSession }\n : undefined;\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n return this.collection.dbName;\n }\n get collectionName(): string {\n return this.collection.collectionName;\n }\n get namespace(): string {\n return `${this.dbName}.${this.collectionName}`;\n }\n get readConcern(): ReadConcern | undefined {\n return undefined;\n }\n get readPreference(): ReadPreference | undefined {\n return undefined;\n }\n get bsonOptions(): BSONSerializeOptions {\n return {};\n }\n get writeConcern(): WriteConcern | undefined {\n return undefined;\n }\n get hint(): Hint | undefined {\n return undefined;\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(\n doc as unknown as PongoOptionalUnlessRequiredId<T>,\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n async insertMany(\n docs: OptionalUnlessRequiredId<T>[],\n options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n const result = await this.collection.insertMany(\n docs as unknown as PongoOptionalUnlessRequiredId<T>[],\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedIds: result.insertedIds as unknown as InferIdType<T>[],\n insertedCount: result.insertedCount,\n };\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n filter: Filter<T>,\n document: WithoutId<T>,\n options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n return this.collection.replaceOne(\n filter as unknown as PongoFilter<T>,\n document,\n toCollectionOperationOptions(options),\n );\n }\n async updateMany(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateMany(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async deleteMany(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteMany(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async rename(\n newName: string,\n options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n await this.collection.rename(\n newName,\n toCollectionOperationOptions(options),\n );\n\n return this as unknown as Collection<Document>;\n }\n drop(options?: DropCollectionOptions | undefined): Promise<boolean> {\n return this.collection.drop(toCollectionOperationOptions(options));\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n {},\n toCollectionOperationOptions(options),\n );\n }\n countDocuments(\n filter?: Filter<T> | undefined,\n options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: unknown,\n options?: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndDelete(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: unknown,\n replacement: unknown,\n options?: FindOneAndReplaceOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndReplace(\n filter as PongoFilter<T>,\n replacement as WithoutId<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: unknown,\n update: unknown,\n options?: FindOneAndUpdateOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndUpdate(\n filter as PongoFilter<T>,\n update as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n filter?: Filter<T> | undefined,\n options?: CountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n (filter as PongoFilter<T>) ?? {},\n toCollectionOperationOptions(options),\n );\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n async handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null> {\n return this.collection.handle(id.toString(), handle);\n }\n}\n","import type { ClientSessionOptions } from 'http2';\nimport type { ClientSession, WithSessionCallback } from 'mongodb';\nimport {\n pongoClient,\n pongoSession,\n type PongoClient,\n type PongoClientOptions,\n} from '../core';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string, options: PongoClientOptions = {}) {\n this.pongoClient = pongoClient(connectionString, options);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName?: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n startSession(_options?: ClientSessionOptions): ClientSession {\n return pongoSession() as unknown as ClientSession;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withSession<T = any>(_executor: WithSessionCallback<T>): Promise<T>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withSession<T = any>(\n _options: ClientSessionOptions,\n _executor: WithSessionCallback<T>,\n ): Promise<T>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async withSession<T = any>(\n optionsOrExecutor: ClientSessionOptions | WithSessionCallback<T>,\n executor?: WithSessionCallback<T>,\n ): Promise<T> {\n const callback =\n typeof optionsOrExecutor === 'function' ? optionsOrExecutor : executor!;\n\n const session = pongoSession() as unknown as ClientSession;\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n }\n}\n"],"mappings":"+CAAO,IAAMA,EAAN,KAAoB,CACjB,qBACA,UAAwB,KACxB,MAAgB,EAExB,YAAYC,EAAyB,CACnC,KAAK,qBAAuBA,CAC9B,CAEA,MAAM,SAAwB,CAC5B,OAAO,KAAK,cAAc,CAC5B,CAEA,MAAM,QAAQC,EAA2C,CACvD,IAAMC,EAAO,MAAM,KAAK,cAAc,EAEtC,QAAWC,KAAOD,EAChBD,EAASE,CAAG,EAEd,OAAO,QAAQ,QAAQ,CACzB,CAEA,SAAmB,CACjB,GAAI,KAAK,YAAc,KAAM,MAAM,MAAM,gCAAgC,EACzE,OAAO,KAAK,MAAQ,KAAK,UAAU,MACrC,CAEA,MAAM,MAA0B,CAC9B,IAAMD,EAAO,MAAM,KAAK,cAAc,EACtC,OAAO,KAAK,QAAQ,EAAKA,EAAK,KAAK,OAAO,GAAK,KAAQ,IACzD,CAEA,MAAc,eAA8B,CAC1C,YAAK,UAAY,MAAM,KAAK,qBACrB,KAAK,SACd,CACF,ECpCA,MAIO,UCoEP,IA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perationOptions","options","Collection","collection","v","doc","result","docs","_operations","_options","filter","update","document","newName","FindCursor","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_filter","replacement","_pipeline","_name","_description","_descriptions","_definition","id","handle","Db","pongoDb","collectionName","Collection","MongoClient","connectionString","options","pongoClient","dbName","Db","_options","pongoSession","optionsOrExecutor","executor","callback","session"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@event-driven-io/pongo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"description": "Pongo - Mongo with strong consistency on top of Postgres",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
@@ -67,18 +67,17 @@
|
|
|
67
67
|
"dist"
|
|
68
68
|
],
|
|
69
69
|
"peerDependencies": {
|
|
70
|
-
"@event-driven-io/dumbo": "0.
|
|
70
|
+
"@event-driven-io/dumbo": "0.9.0",
|
|
71
71
|
"@types/mongodb": "^4.0.7",
|
|
72
72
|
"@types/pg": "^8.11.6",
|
|
73
|
-
"@types/uuid": "^
|
|
73
|
+
"@types/uuid": "^10.0.0",
|
|
74
74
|
"pg": "^8.12.0",
|
|
75
|
-
"uuid": "^
|
|
75
|
+
"uuid": "^10.0.0"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
|
-
"@types/node": "
|
|
78
|
+
"@types/node": "22.4.1"
|
|
79
79
|
},
|
|
80
80
|
"dependencies": {
|
|
81
|
-
"@types/pg-connection-string": "^2.0.0",
|
|
82
81
|
"pg-connection-string": "^2.6.4"
|
|
83
82
|
}
|
|
84
83
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/collection/pongoCollection.ts","../src/core/collection/query.ts","../src/core/pongoClient.ts","../src/postgres/dbClient.ts","../src/postgres/sqlBuilder/index.ts","../src/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/filter/index.ts","../src/postgres/sqlBuilder/update/index.ts","../src/core/pongoDb.ts","../src/core/pongoTransaction.ts","../src/core/pongoSession.ts","../src/core/typing/entries.ts"],"sourcesContent":["import {\n single,\n type DatabaseTransaction,\n type QueryResultRow,\n type SQL,\n type SQLExecutor,\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 '..';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n sqlExecutor: SQLExecutor;\n sqlBuilder: PongoCollectionSQLBuilder;\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 sqlExecutor,\n sqlBuilder: SqlFor,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\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 const createCollectionPromise = command(SqlFor.createCollection());\n const createCollection = (options?: CollectionOperationOptions) =>\n options?.session\n ? command(SqlFor.createCollection(), options)\n : createCollectionPromise;\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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n };\n\n return collection;\n};\n\nexport type PongoCollectionSQLBuilder = {\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","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 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';\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 // eslint-disable-next-line @typescript-eslint/ban-types\n | {};\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 | PooledPongoClientOptions\n | NotPooledPongoOptions;\n\nexport const pongoClient = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions = {},\n): PongoClient => {\n const dbClients: Map<string, PongoDb> = new Map();\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 = unknown>(\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 pongoClient;\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 dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from '@event-driven-io/dumbo';\nimport {\n pongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector> &\n PostgresPoolOptions;\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>(options);\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 sqlExecutor: pool.execute,\n sqlBuilder: postgresSQLBuilder(collectionName),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n };\n\n return db;\n};\n","import { rawSql, sql, type SQL } 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\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n createCollection: (): 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 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 { sql } from '@event-driven-io/dumbo';\nimport { entries, OperatorMap } from '../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return sql(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSON.stringify(buildNestedObject(path, value)),\n path,\n JSON.stringify(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return sql(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n sql(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return sql(`jsonb_path_exists(data, '$.%s[*] ? (%s)')`, path, subQuery);\n }\n case '$all':\n return sql(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return sql(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return sql(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return sql(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import {\n entries,\n hasOperators,\n QueryOperators,\n type PongoFilter,\n} from '../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { sql, type SQL } from '@event-driven-io/dumbo';\nimport {\n entries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../core';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, JSON.stringify(set));\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL =>\n sql(\n '%s - %L',\n currentUpdateQuery,\n Object.keys(unset)\n .map((k) => `{${k}}`)\n .join(', '),\n );\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify([value]),\n );\n }\n return currentUpdateQuery;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n};\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n","import type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n","import { pongoTransaction } from './pongoTransaction';\nimport type {\n PongoDbTransaction,\n PongoSession,\n PongoTransactionOptions,\n} from './typing';\n\nexport type PongoSessionOptions = {\n explicit?: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n};\n\nconst isActive = (\n transaction: PongoDbTransaction | null,\n): transaction is PongoDbTransaction => transaction?.isActive === true;\n\nfunction assertInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is PongoDbTransaction {\n if (!isActive(transaction)) throw new Error('No active transaction exists!');\n}\n\nfunction assertNotInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is null {\n if (isActive(transaction))\n throw new Error('Active transaction already exists!');\n}\n\nexport const pongoSession = (options?: PongoSessionOptions): PongoSession => {\n const explicit = options?.explicit === true;\n const defaultTransactionOptions: PongoTransactionOptions =\n options?.defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n };\n\n let transaction: PongoDbTransaction | null = null;\n let hasEnded = false;\n\n const startTransaction = (options?: PongoTransactionOptions) => {\n assertNotInActiveTransaction(transaction);\n\n transaction = pongoTransaction(options ?? defaultTransactionOptions);\n };\n const commitTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.commit();\n };\n const abortTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.rollback();\n };\n\n const endSession = async (): Promise<void> => {\n if (hasEnded) return;\n hasEnded = true;\n\n if (isActive(transaction)) await transaction.rollback();\n };\n\n const session = {\n get hasEnded() {\n return hasEnded;\n },\n explicit,\n defaultTransactionOptions: defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n },\n get transaction() {\n return transaction;\n },\n get snapshotEnabled() {\n return defaultTransactionOptions.snapshotEnabled;\n },\n endSession,\n incrementTransactionNumber: () => {},\n inTransaction: () => isActive(transaction),\n startTransaction,\n commitTransaction,\n abortTransaction,\n withTransaction: async <T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T> => {\n startTransaction(options);\n\n try {\n const result = await fn(session);\n await commitTransaction();\n return result;\n } catch (error) {\n await abortTransaction();\n throw error;\n }\n },\n };\n\n return session;\n};\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <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"],"mappings":"AAAA,OACE,UAAAA,OAKK,yBACP,OAAS,MAAMC,MAAY,OCPpB,IAAMC,EAAiB,CAC5B,IAAK,MACL,IAAK,MACL,KAAM,OACN,IAAK,MACL,KAAM,OACN,IAAK,MACL,IAAK,MACL,KAAM,OACN,WAAY,aACZ,KAAM,OACN,MAAO,OACT,EAEaC,EAAc,CACzB,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,KACN,IAAK,IACP,EAEaC,EAAcC,GAAgBA,EAAI,WAAW,GAAG,EAEhDC,EAAgB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AW,UAAUS,EAAQC,EAAQvB,CAAO,EAE3CwB,EACT,EACA,OAAQ,MACNE,EACAC,EACA3B,IACsB,CACtB,MAAMY,EAAiBZ,CAAO,EAE9B,IAAM4B,EAAuB,CAAE,IAAKF,CAAG,EAEjCG,EAAW,MAAMhB,EAAW,QAAQe,EAAM5B,CAAO,EAEjDoB,EAAS,MAAMO,EAAOE,CAAQ,EAEpC,GAAI,CAACA,GAAYT,EAAQ,CACvB,IAAMU,EAAS,CAAE,GAAGV,EAAQ,IAAKM,CAAG,EACpC,aAAMb,EAAW,UACf,CAAE,GAAGiB,EAAQ,IAAKJ,CAAG,EACrB1B,CACF,EACO8B,CACT,CAEA,OAAID,GAAY,CAACT,GACf,MAAMP,EAAW,UAAUe,EAAM5B,CAAO,EACjC,OAGL6B,GAAYT,GACd,MAAMP,EAAW,WAAWe,EAAMR,EAAQpB,CAAO,EAE5CoB,EACT,EACA,KAAM,MACJE,EACAtB,KAEA,MAAMY,EAAiBZ,CAAO,GAEf,MAAMU,EAAMH,EAAO,KAAKe,GAAU,CAAC,CAAC,CAAC,GACtC,KAAK,IAAKS,GAAQA,EAAI,IAAS,GAE/C,eAAgB,MACdT,EACAtB,IACoB,CACpB,MAAMY,EAAiBZ,CAAO,EAE9B,GAAM,CAAE,MAAAgC,CAAM,EAAI,MAAMC,GACtBvB,EAAyBH,EAAO,eAAee,GAAU,CAAC,CAAC,CAAC,CAC9D,EACA,OAAOU,CACT,EACA,KAAM,MAAOhC,IACX,MAAMY,EAAiBZ,CAAO,IACf,MAAMQ,EAAQD,EAAO,KAAK,CAAC,IAC1B,UAAY,GAAK,GAEnC,OAAQ,MACN2B,EACAlC,KAEA,MAAMY,EAAiBZ,CAAO,EAC9B,MAAMQ,EAAQD,EAAO,OAAO2B,CAAO,CAAC,EACpC7B,EAAiB6B,EACVrB,EAEX,EAEA,OAAOA,CACT","names":["single","uuid","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","NodePostgresConnectorType","dumbo","getDatabaseNameOrDefault","NodePostgresConnectorType","rawSql","sql","sql","handleOperator","path","operator","value","handleIdOperator","sql","buildNestedObject","OperatorMap","v","subQuery","entries","subKey","subValue","acc","key","AND","constructFilterQuery","filter","key","value","isRecord","constructComplexFilterQuery","handleOperator","isEquality","hasOperators","entries","nestedKey","val","QueryOperators","sql","buildUpdateQuery","update","entries","currentUpdateQuery","op","value","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","sql","set","unset","k","inc","key","push","postgresSQLBuilder","collectionName","sql","document","documents","values","doc","filter","update","filterQuery","constructFilterQuery","updateQuery","buildUpdateQuery","where","newName","targetName","rawSql","isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","db","collectionName","pongoCollection","postgresSQLBuilder","handle","getPongoDb","options","type","isPostgresClientOptions","postgresDb","pongoTransaction","options","isCommitted","isRolledBack","databaseName","transaction","db","error","isActive","transaction","assertInActiveTransaction","assertNotInActiveTransaction","pongoSession","options","explicit","defaultTransactionOptions","hasEnded","startTransaction","pongoTransaction","commitTransaction","abortTransaction","session","fn","result","error","pongoClient","connectionString","options","dbClients","dbClient","getPongoDb","clientToDbOptions","db","dbName","pongoSession","callback","session","NodePostgresConnectorType","entries","obj","key","value","enlistIntoTransactionIfActive","db","options","transaction","transactionExecutorOrDefault","defaultSqlExecutor","pongoCollection","collectionName","sqlExecutor","SqlFor","command","sql","query","createCollectionPromise","createCollection","collection","document","_id","uuid","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","handle","byId","existing","newDoc","row","count","single","newName"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/collection/pongoCollection.ts","../src/core/collection/query.ts","../src/core/pongoClient.ts","../src/postgres/dbClient.ts","../src/postgres/sqlBuilder/index.ts","../src/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/filter/index.ts","../src/postgres/sqlBuilder/update/index.ts","../src/core/pongoDb.ts","../src/core/pongoTransaction.ts","../src/core/pongoSession.ts","../src/core/typing/entries.ts"],"names":["single","uuid","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","NodePostgresConnectorType","dumbo","getDatabaseNameOrDefault","rawSql","sql","handleOperator","path","operator","handleIdOperator","buildNestedObject","v","subQuery","entries","subKey","subValue","acc","AND","constructFilterQuery","filter","isRecord","constructComplexFilterQuery","isEquality","nestedKey","val","buildUpdateQuery","update","currentUpdateQuery","op","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","set","unset","k","inc","push","postgresSQLBuilder","collectionName","document","documents","values","doc","filterQuery","updateQuery","where","newName","targetName","isPostgresClientOptions","options","postgresDb","connectionString","dbName","databaseName","pool","db","pongoCollection","handle","getPongoDb","type","pongoTransaction","isCommitted","isRolledBack","transaction","error","isActive","assertInActiveTransaction","assertNotInActiveTransaction","pongoSession","explicit","defaultTransactionOptions","hasEnded","startTransaction","commitTransaction","abortTransaction","session","fn","result","pongoClient","dbClients","dbClient","clientToDbOptions","callback","obj","enlistIntoTransactionIfActive","transactionExecutorOrDefault","defaultSqlExecutor","sqlExecutor","SqlFor","command","query","createCollectionPromise","createCollection","collection","_id","rows","d","existingDoc","replacement","id","byId","existing","newDoc","row","count"],"mappings":"AAAA,OACE,UAAAA,OAKK,yBACP,OAAS,MAAMC,MAAY,OCPpB,IAAMC,EAAiB,CAC5B,IAAK,MACL,IAAK,MACL,KAAM,OACN,IAAK,MACL,KAAM,OACN,IAAK,MACL,IAAK,MACL,KAAM,OACN,WAAY,aACZ,KAAM,OACN,MAAO,OACT,EAEaC,EAAc,CACzB,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,KACN,IAAK,IACP,EAEaC,EAAcC,GAAgBA,EAAI,WAAW,GAAG,EAEhDC,EAAgBC,GAC3B,OAAO,KAAKA,CAAK,EAAE,KAAKH,CAAU,ECzBpC,OACE,6BAAAI,OAEK,yBACP,MAAe,KCJf,OACE,SAAAC,EACA,4BAAAC,E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MwC,EAAQD,EAAO,OAAO1C,CAAO,CAAC,EACpCR,EAAiBQ,EACV+C,EAEX,EAEA,OAAOA,CACT","sourcesContent":["import {\n single,\n type DatabaseTransaction,\n type QueryResultRow,\n type SQL,\n type SQLExecutor,\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 '..';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n sqlExecutor: SQLExecutor;\n sqlBuilder: PongoCollectionSQLBuilder;\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 sqlExecutor,\n sqlBuilder: SqlFor,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\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 const createCollectionPromise = command(SqlFor.createCollection());\n const createCollection = (options?: CollectionOperationOptions) =>\n options?.session\n ? command(SqlFor.createCollection(), options)\n : createCollectionPromise;\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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(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 createCollection(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n };\n\n return collection;\n};\n\nexport type PongoCollectionSQLBuilder = {\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","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 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';\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 // eslint-disable-next-line @typescript-eslint/ban-types\n | {};\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 | PooledPongoClientOptions\n | NotPooledPongoOptions;\n\nexport const pongoClient = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions = {},\n): PongoClient => {\n const dbClients: Map<string, PongoDb> = new Map();\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 = unknown>(\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 pongoClient;\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 dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from '@event-driven-io/dumbo';\nimport {\n pongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector> &\n PostgresPoolOptions;\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>(options);\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 sqlExecutor: pool.execute,\n sqlBuilder: postgresSQLBuilder(collectionName),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n };\n\n return db;\n};\n","import { rawSql, sql, type SQL } 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\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n createCollection: (): 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 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 { sql } from '@event-driven-io/dumbo';\nimport { entries, OperatorMap } from '../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return sql(\n `(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))`,\n JSON.stringify(buildNestedObject(path, value)),\n path,\n JSON.stringify(value),\n );\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return sql(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n sql(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return sql(`jsonb_path_exists(data, '$.%s[*] ? (%s)')`, path, subQuery);\n }\n case '$all':\n return sql(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return sql(\n 'jsonb_array_length(data #> %L) = %L',\n `{${path.split('.').join(',')}}`,\n value,\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return sql(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return sql(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return sql(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n case '$nin':\n return sql(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => sql('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import {\n entries,\n hasOperators,\n QueryOperators,\n type PongoFilter,\n} from '../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { sql, type SQL } from '@event-driven-io/dumbo';\nimport {\n entries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../core';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, JSON.stringify(set));\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL =>\n sql(\n '%s - %L',\n currentUpdateQuery,\n Object.keys(unset)\n .map((k) => `{${k}}`)\n .join(', '),\n );\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify([value]),\n );\n }\n return currentUpdateQuery;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n};\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n","import type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n","import { pongoTransaction } from './pongoTransaction';\nimport type {\n PongoDbTransaction,\n PongoSession,\n PongoTransactionOptions,\n} from './typing';\n\nexport type PongoSessionOptions = {\n explicit?: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n};\n\nconst isActive = (\n transaction: PongoDbTransaction | null,\n): transaction is PongoDbTransaction => transaction?.isActive === true;\n\nfunction assertInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is PongoDbTransaction {\n if (!isActive(transaction)) throw new Error('No active transaction exists!');\n}\n\nfunction assertNotInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is null {\n if (isActive(transaction))\n throw new Error('Active transaction already exists!');\n}\n\nexport const pongoSession = (options?: PongoSessionOptions): PongoSession => {\n const explicit = options?.explicit === true;\n const defaultTransactionOptions: PongoTransactionOptions =\n options?.defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n };\n\n let transaction: PongoDbTransaction | null = null;\n let hasEnded = false;\n\n const startTransaction = (options?: PongoTransactionOptions) => {\n assertNotInActiveTransaction(transaction);\n\n transaction = pongoTransaction(options ?? defaultTransactionOptions);\n };\n const commitTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.commit();\n };\n const abortTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.rollback();\n };\n\n const endSession = async (): Promise<void> => {\n if (hasEnded) return;\n hasEnded = true;\n\n if (isActive(transaction)) await transaction.rollback();\n };\n\n const session = {\n get hasEnded() {\n return hasEnded;\n },\n explicit,\n defaultTransactionOptions: defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n },\n get transaction() {\n return transaction;\n },\n get snapshotEnabled() {\n return defaultTransactionOptions.snapshotEnabled;\n },\n endSession,\n incrementTransactionNumber: () => {},\n inTransaction: () => isActive(transaction),\n startTransaction,\n commitTransaction,\n abortTransaction,\n withTransaction: async <T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T> => {\n startTransaction(options);\n\n try {\n const result = await fn(session);\n await commitTransaction();\n return result;\n } catch (error) {\n await abortTransaction();\n throw error;\n }\n },\n };\n\n return session;\n};\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <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"]}
|