@event-driven-io/pongo 0.14.2 → 0.14.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-UGDQF6CW.js → chunk-MAHDZ7ZR.js} +4 -4
- package/dist/chunk-MAHDZ7ZR.js.map +1 -0
- package/dist/{chunk-YQPKY7LN.cjs → chunk-OOCCQKUB.cjs} +4 -4
- package/dist/chunk-OOCCQKUB.cjs.map +1 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{pongoClient-CajnU47o.d.cts → pongoClient-BsMs5Zc7.d.cts} +3 -3
- package/dist/{pongoClient-CajnU47o.d.ts → pongoClient-BsMs5Zc7.d.ts} +3 -3
- package/dist/shim.cjs +1 -1
- package/dist/shim.d.cts +1 -1
- package/dist/shim.d.ts +1 -1
- package/dist/shim.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-UGDQF6CW.js.map +0 -1
- package/dist/chunk-YQPKY7LN.cjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{rawSql as On,sql as m,sqlMigration as fn}from"@event-driven-io/dumbo";import{runPostgreSQLMigrations as
|
|
1
|
+
import{rawSql as On,sql as m,sqlMigration as fn}from"@event-driven-io/dumbo";import{runPostgreSQLMigrations as en,schemaComponent as W,single as tn}from"@event-driven-io/dumbo";import{v4 as _}from"uuid";import{dumbo as V,getDatabaseNameOrDefault as Z,NodePostgresConnectorType as G,runPostgreSQLMigrations as nn,schemaComponent as R}from"@event-driven-io/dumbo";var N=n=>n.connectorType===G,k=n=>{let{connectionString:e,dbName:t}=n,o=t??Z(e),r=V({connectionString:e,...n.connectionOptions}),c=new Map,p={connectorType:n.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>r.close(),collection:u=>A({collectionName:u,db:p,pool:r,sqlBuilder:M(u),...n.schema?n.schema:{}}),transaction:()=>r.transaction(),withTransaction:u=>r.withTransaction(u),schema:{get component(){return R("pongoDb",{components:[...c.values()].map(u=>u.schema.component)})},migrate:()=>nn(r,[...c.values()].flatMap(u=>u.schema.component.migrations({connector:"PostgreSQL:pg"})))}},C=n?.schema?.definition?.dbs;if(C){let u=P(C).map(y=>y[1]).find(y=>y.name===t||y.name===o);if(u)return j(p,u,c)}return p},wn=n=>{let e=n.length>0&&typeof n[0]=="string"?n.map(t=>U(t)):n;return R("pongo:schema_component:db",{components:e})};var on=async(n,e)=>{let t=e?.session?.transaction;return!t||!t.isActive?null:await t.enlistDatabase(n)},F=async(n,e,t)=>(await on(n,e))?.execute??t,A=({db:n,collectionName:e,pool:t,sqlBuilder:o,schema:r})=>{let c=t.execute,p=async(i,a)=>(await F(n,a,c)).command(i),C=async(i,a)=>(await F(n,a,c)).query(i),u=r?.autoMigration!=="None",y=i=>(u=!1,i?.session?p(o.createCollection(),i):p(o.createCollection())),g=i=>u?y(i):Promise.resolve(),T={dbName:n.databaseName,collectionName:e,createCollection:async i=>{await y(i)},insertOne:async(i,a)=>{await g(a);let s=i._id??_();return(await p(o.insertOne({...i,_id:s}),a)).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async(i,a)=>{await g(a);let s=i.map(O=>({...O,_id:O._id??_()})),l=await p(o.insertMany(s),a);return{acknowledged:l.rowCount===s.length,insertedCount:l.rowCount??0,insertedIds:s.map(O=>O._id)}},updateOne:async(i,a,s)=>{await g(s);let l=await p(o.updateOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(i,a,s)=>{await g(s);let l=await p(o.replaceOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(i,a,s)=>{await g(s);let l=await p(o.updateMany(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async(i,a)=>{await g(a);let s=await p(o.deleteOne(i??{}),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async(i,a)=>{await g(a);let s=await p(o.deleteMany(i??{}),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async(i,a)=>(await g(a),(await C(o.findOne(i??{}),a)).rows[0]?.data??null),findOneAndDelete:async(i,a)=>{await g(a);let s=await T.findOne(i,a);return s===null?null:(await T.deleteOne(i,a),s)},findOneAndReplace:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.replaceOne(i,a,s),l)},findOneAndUpdate:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.updateOne(i,a,s),l)},handle:async(i,a,s)=>{await g(s);let l={_id:i},O=await T.findOne(l,s),b=await a(O);if(!O&&b){let I={...b,_id:i};return await T.insertOne({...I,_id:i},s),I}return O&&!b?(await T.deleteOne(l,s),null):(O&&b&&await T.replaceOne(l,b,s),b)},find:async(i,a)=>(await g(a),(await C(o.find(i??{}))).rows.map(l=>l.data)),countDocuments:async(i,a)=>{await g(a);let{count:s}=await tn(C(o.countDocuments(i??{})));return s},drop:async i=>(await g(i),((await p(o.drop()))?.rowCount??0)>0),rename:async(i,a)=>(await g(a),await p(o.rename(i)),e=i,T),schema:{get component(){return W("pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>en(t,o.migrations())}};return T},U=n=>W("pongo:schema_component:collection",{migrations:()=>x(n)});var q={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},L={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},rn=n=>n.startsWith("$"),B=n=>Object.keys(n).some(rn);var P=n=>Object.entries(n).map(([e,t])=>[e,t]);var sn=n=>({name:n});function an(n,e){if(e===void 0){if(typeof n=="string")throw new Error("You need to provide colleciton definition");return{collections:n}}return n&&typeof n=="string"?{name:n,collections:e}:{collections:e}}var cn=n=>({dbs:n}),Bn={client:cn,db:an,collection:sn},j=(n,e,t)=>{let o=Object.keys(e.collections);for(let r of o)t.set(r,n.collection(r));return new Proxy(n,{get(r,c){return t.get(c)??r[c]}})},J=(n,e)=>{if(!e)return n;let t=Object.keys(e.dbs);return new Proxy(n,{get(o,r){return t.includes(r)?n.db(e.dbs[r]?.name):o[r]}})},ln=n=>({name:n.name,collections:P(n.collections).map(e=>({name:e[1].name}))}),Jn=n=>{let e=P(n.dbs).map(t=>ln(t[1]));return{databases:e,database:t=>e.find(o=>o.name===t)}};import{NodePostgresConnectorType as gn}from"@event-driven-io/dumbo";import"pg";var E=n=>{let{connectorType:e}=n;if(!N(n))throw new Error(`Unsupported db type: ${e}`);return k(n)};var K=n=>{let e=!1,t=!1,o=null,r=null;return{enlistDatabase:async c=>{if(r&&o!==c.databaseName)throw new Error("There's already other database assigned to transaction");return r&&o===c.databaseName||(o=c.databaseName,r=c.transaction(),await r.begin()),r},commit:async()=>{if(!r)throw new Error("No database transaction started!");if(!e){if(t)throw new Error("Transaction is not active!");e=!0,await r.commit(),r=null}},rollback:async c=>{if(!r)throw new Error("No database transaction started!");if(e)throw new Error("Cannot rollback commited transaction!");t||(t=!0,await r.rollback(c),r=null)},databaseName:o,isStarting:!1,isCommitted:e,get isActive(){return!e&&!t},get sqlExecutor(){if(r===null)throw new Error("No database transaction was started");return r.execute},options:n}};var w=n=>n?.isActive===!0;function v(n){if(!w(n))throw new Error("No active transaction exists!")}function pn(n){if(w(n))throw new Error("Active transaction already exists!")}var Q=n=>{let e=n?.explicit===!0,t=n?.defaultTransactionOptions??{get snapshotEnabled(){return!1}},o=null,r=!1,c=g=>{pn(o),o=K(g??t)},p=async()=>{v(o),await o.commit()},C=async()=>{v(o),await o.rollback()},y={get hasEnded(){return r},explicit:e,defaultTransactionOptions:t??{get snapshotEnabled(){return!1}},get transaction(){return o},get snapshotEnabled(){return t.snapshotEnabled},endSession:async()=>{r||(r=!0,w(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>w(o),startTransaction:c,commitTransaction:p,abortTransaction:C,withTransaction:async(g,T)=>{c(T);try{let i=await g(y);return await p(),i}catch(i){throw await C(),i}}};return y};var oe=(n,e={})=>{let t=new Map,o=E(H({connectionString:n,clientOptions:e}));t.set(o.databaseName,o);let r={connect:async()=>(await o.connect(),r),close:async()=>{for(let c of t.values())await c.close()},db:c=>c?t.get(c)??t.set(c,E(H({connectionString:n,dbName:c,clientOptions:e}))).get(c):o,startSession:Q,withSession:async c=>{let p=Q();try{return await c(p)}finally{await p.endSession()}}};return J(r,e?.schema?.definition)},H=n=>({connectorType:gn,connectionString:n.connectionString,dbName:n.dbName,...n.clientOptions});import{sql as d}from"@event-driven-io/dumbo";var D=(n,e,t)=>{if(n==="_id")return dn(e,t);switch(e){case"$eq":return d("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(X(n,t)),n,JSON.stringify(t));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`data #>> %L ${L[e]} %L`,`{${n.split(".").join(",")}}`,t);case"$in":return d("data #>> %L IN (%s)",`{${n.split(".").join(",")}}`,t.map(o=>d("%L",o)).join(", "));case"$nin":return d("data #>> %L NOT IN (%s)",`{${n.split(".").join(",")}}`,t.map(o=>d("%L",o)).join(", "));case"$elemMatch":{let o=P(t).map(([r,c])=>d('@."%s" == %s',r,JSON.stringify(c))).join(" && ");return d("jsonb_path_exists(data, '$.%s[*] ? (%s)')",n,o)}case"$all":return d("data @> %L::jsonb",JSON.stringify(X(n,t)));case"$size":return d("jsonb_array_length(data #> %L) = %L",`{${n.split(".").join(",")}}`,t);default:throw new Error(`Unsupported operator: ${e}`)}},dn=(n,e)=>{switch(n){case"$eq":return d("_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return d(`_id ${L[n]} %L`,e);case"$in":return d("_id IN (%s)",e.map(t=>d("%L",t)).join(", "));case"$nin":return d("_id NOT IN (%s)",e.map(t=>d("%L",t)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},X=(n,e)=>n.split(".").reverse().reduce((t,o)=>({[o]:t}),e);var z="AND",f=n=>Object.entries(n).map(([e,t])=>mn(t)?un(e,t):D(e,"$eq",t)).join(` ${z} `),un=(n,e)=>{let t=!B(e);return P(e).map(([o,r])=>t?D(`${n}.${o}`,q.$eq,r):D(n,o,r)).join(` ${z} `)},mn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);import{sql as h}from"@event-driven-io/dumbo";var $=n=>P(n).reduce((e,[t,o])=>{switch(t){case"$set":return Tn(o,e);case"$unset":return Pn(o,e);case"$inc":return yn(o,e);case"$push":return Cn(o,e);default:return e}},h("data")),Tn=(n,e)=>h("%s || %L::jsonb",e,JSON.stringify(n)),Pn=(n,e)=>h("%s - %L",e,Object.keys(n).map(t=>`{${t}}`).join(", ")),yn=(n,e)=>{for(let[t,o]of Object.entries(n))e=h("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",e,t,t,o);return e},Cn=(n,e)=>{for(let[t,o]of Object.entries(n))e=h("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",e,t,t,JSON.stringify([o]));return e};var Y=n=>m(`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 '{}',
|
|
@@ -7,8 +7,8 @@ import{rawSql as On,sql as m,sqlMigration as fn}from"@event-driven-io/dumbo";imp
|
|
|
7
7
|
_archived BOOLEAN NOT NULL DEFAULT FALSE,
|
|
8
8
|
_created TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
9
9
|
_updated TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
10
|
-
)`,n),x=n=>[fn(`pongoCollection:${n}:001:createtable`,[Y(n)])],M=n=>({migrations:()=>x(n),createCollection:()=>Y(n),insertOne:
|
|
10
|
+
)`,n),x=n=>[fn(`pongoCollection:${n}:001:createtable`,[Y(n)])],M=n=>({migrations:()=>x(n),createCollection:()=>Y(n),insertOne:e=>m("INSERT INTO %I (_id, data) VALUES (%L, %L)",n,e._id,JSON.stringify(e)),insertMany:e=>{let t=e.map(o=>m("(%L, %L)",o._id,JSON.stringify(o))).join(", ");return m("INSERT INTO %I (_id, data) VALUES %s",n,t)},updateOne:(e,t)=>{let o=f(e),r=$(t);return m(`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`,n,S(o),n,r,n)},replaceOne:(t
|
|
14
|
-
//# sourceMappingURL=chunk-
|
|
13
|
+
UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,n,S(o),n,r,n)},replaceOne:(e,t)=>{let o=f(e);return m("UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s",n,JSON.stringify(t),S(o))},updateMany:(e,t)=>{let o=f(e),r=$(t);return m("UPDATE %I SET data = %s %s",n,r,S(o))},deleteOne:e=>{let t=f(e);return m("DELETE FROM %I %s",n,S(t))},deleteMany:e=>{let t=f(e);return m("DELETE FROM %I %s",n,S(t))},findOne:e=>{let t=f(e);return m("SELECT data FROM %I %s LIMIT 1",n,S(t))},find:e=>{let t=f(e);return m("SELECT data FROM %I %s",n,S(t))},countDocuments:e=>{let t=f(e);return m("SELECT COUNT(1) as count FROM %I %s",n,S(t))},rename:e=>m("ALTER TABLE %I RENAME TO %I",n,e),drop:(e=n)=>m("DROP TABLE IF EXISTS %I",e)}),S=n=>n.length>0?m("WHERE %s",n):On("");export{x as a,M as b,N as c,k as d,wn as e,A as f,U as g,q as h,L as i,rn as j,B as k,P as l,Bn as m,j as n,J as o,ln as p,Jn as q,E as r,K as s,Q as t,oe as u,H as v};
|
|
14
|
+
//# sourceMappingURL=chunk-MAHDZ7ZR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/typing/entries.ts","../src/core/schema/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts","../src/core/pongoTransaction.ts","../src/core/pongoSession.ts","../src/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/filter/index.ts","../src/postgres/sqlBuilder/update/index.ts"],"sourcesContent":["import {\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n type OptionalUnlessRequiredId,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]): SQL => {\n const values = documents\n .map((doc) => sql('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n\n return sql(\n `UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s`,\n collectionName,\n JSON.stringify(document),\n where(filterQuery),\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s %s',\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I %s LIMIT 1',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v4 as uuid } from 'uuid';\nimport {\n type CollectionOperationOptions,\n type DocumentHandler,\n type OptionalUnlessRequiredId,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithoutId,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nconst transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async (sql: SQL, options?: CollectionOperationOptions) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).command(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n\n const result = await command(\n SqlFor.insertOne({ ...document, _id } as OptionalUnlessRequiredId<T>),\n options,\n );\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (\n documents: OptionalUnlessRequiredId<T>[],\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredId<T>[]),\n options,\n );\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id as string),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateOne(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(\n SqlFor.replaceOne(filter, document),\n options,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteOne(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as T | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = await collection.findOne(byId, options);\n\n const result = await handle(existing);\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredId<T>,\n options,\n );\n return newDoc;\n }\n\n if (existing && !result) {\n await collection.deleteOne(byId, options);\n return null;\n }\n\n if (existing && result)\n await collection.replaceOne(byId, result, options);\n\n return result;\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as T);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredId<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]) => SQL;\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>) => SQL;\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n deleteOne: <T>(filter: PongoFilter<T>) => SQL;\n deleteMany: <T>(filter: PongoFilter<T>) => SQL;\n findOne: <T>(filter: PongoFilter<T>) => SQL;\n find: <T>(filter: PongoFilter<T>) => SQL;\n countDocuments: <T>(filter: PongoFilter<T>) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n type PostgresConnector,\n type PostgresPoolOptions,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n ...(options.schema ? options.schema : {}),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const objectEntries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import {\n type Document,\n type PongoClient,\n type PongoCollection,\n type PongoDb,\n type PongoDocument,\n objectEntries,\n} from '../typing';\n\nexport interface PongoCollectionSchema<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n T extends PongoDocument = PongoDocument,\n> {\n name: string;\n}\n\n// Database schema interface\nexport interface PongoDbSchema<\n T extends Record<string, PongoCollectionSchema> = Record<\n string,\n PongoCollectionSchema\n >,\n> {\n name?: string;\n collections: T;\n}\n\nexport interface PongoClientSchema<\n T extends Record<string, PongoDbSchema> = Record<string, PongoDbSchema>,\n> {\n dbs: T;\n}\n\nexport type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {\n [K in keyof T]: PongoCollection<\n T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument\n >;\n};\n\nexport type PongoDbWithSchema<\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n> = CollectionsMap<T> & PongoDb<ConnectorType>;\n\nexport type DBsMap<\n T extends Record<string, PongoDbSchema>,\n ConnectorType extends string = string,\n> = {\n [K in keyof T]: CollectionsMap<T[K]['collections']> & PongoDb<ConnectorType>;\n};\n\nexport type PongoClientWithSchema<\n T extends PongoClientSchema,\n ConnectorType extends string = string,\n> = DBsMap<T['dbs'], ConnectorType> & PongoClient;\n\nconst pongoCollectionSchema = <T extends PongoDocument>(\n name: string,\n): PongoCollectionSchema<T> => ({\n name,\n});\n\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n name: string,\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n nameOrCollections: string | T,\n collections?: T | undefined,\n): PongoDbSchema<T> {\n if (collections === undefined) {\n if (typeof nameOrCollections === 'string') {\n throw new Error('You need to provide colleciton definition');\n }\n return {\n collections: nameOrCollections,\n };\n }\n\n return nameOrCollections && typeof nameOrCollections === 'string'\n ? {\n name: nameOrCollections,\n collections,\n }\n : { collections: collections };\n}\n\nconst pongoClientSchema = <T extends Record<string, PongoDbSchema>>(\n dbs: T,\n): PongoClientSchema<T> => ({\n dbs,\n});\n\nexport const pongoSchema = {\n client: pongoClientSchema,\n db: pongoDbSchema,\n collection: pongoCollectionSchema,\n};\n\n// Factory function to create DB instances\nexport const proxyPongoDbWithSchema = <\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n>(\n pongoDb: PongoDb<ConnectorType>,\n dbSchema: PongoDbSchema<T>,\n collections: Map<string, PongoCollection<Document>>,\n): PongoDbWithSchema<T, ConnectorType> => {\n const collectionNames = Object.keys(dbSchema.collections);\n\n for (const collectionName of collectionNames) {\n collections.set(collectionName, pongoDb.collection(collectionName));\n }\n\n return new Proxy(\n pongoDb as PongoDb<ConnectorType> & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n return collections.get(prop) ?? target[prop];\n },\n },\n ) as PongoDbWithSchema<T, ConnectorType>;\n};\n\nexport const proxyClientWithSchema = <\n TypedClientSchema extends PongoClientSchema,\n>(\n client: PongoClient,\n schema: TypedClientSchema | undefined,\n): PongoClientWithSchema<TypedClientSchema> => {\n if (!schema) return client as PongoClientWithSchema<TypedClientSchema>;\n\n const dbNames = Object.keys(schema.dbs);\n\n return new Proxy(\n client as PongoClient & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n if (dbNames.includes(prop)) return client.db(schema.dbs[prop]?.name);\n\n return target[prop];\n },\n },\n ) as PongoClientWithSchema<TypedClientSchema>;\n};\n\nexport type PongoCollectionSchemaMetadata = {\n name: string;\n};\n\nexport type PongoDbSchemaMetadata = {\n name?: string | undefined;\n collections: PongoCollectionSchemaMetadata[];\n};\n\nexport type PongoClientSchemaMetadata = {\n databases: PongoDbSchemaMetadata[];\n database: (name?: string) => PongoDbSchemaMetadata | undefined;\n};\n\nexport const toDbSchemaMetadata = <TypedDbSchema extends PongoDbSchema>(\n schema: TypedDbSchema,\n): PongoDbSchemaMetadata => ({\n name: schema.name,\n collections: objectEntries(schema.collections).map((c) => ({\n name: c[1].name,\n })),\n});\n\nexport const toClientSchemaMetadata = <\n TypedClientSchema extends PongoClientSchema,\n>(\n schema: TypedClientSchema,\n): PongoClientSchemaMetadata => {\n const databases = objectEntries(schema.dbs).map((e) =>\n toDbSchemaMetadata(e[1]),\n );\n\n return {\n databases,\n database: (name) => databases.find((db) => db.name === name),\n };\n};\n\nexport interface PongoSchemaConfig<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> {\n schema: TypedClientSchema;\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n","import type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n","import { pongoTransaction } from './pongoTransaction';\nimport type {\n PongoDbTransaction,\n PongoSession,\n PongoTransactionOptions,\n} from './typing';\n\nexport type PongoSessionOptions = {\n explicit?: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n};\n\nconst isActive = (\n transaction: PongoDbTransaction | null,\n): transaction is PongoDbTransaction => transaction?.isActive === true;\n\nfunction assertInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is PongoDbTransaction {\n if (!isActive(transaction)) throw new Error('No active transaction exists!');\n}\n\nfunction assertNotInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is null {\n if (isActive(transaction))\n throw new Error('Active transaction already exists!');\n}\n\nexport const pongoSession = (options?: PongoSessionOptions): PongoSession => {\n const explicit = options?.explicit === true;\n const defaultTransactionOptions: PongoTransactionOptions =\n options?.defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n };\n\n let transaction: PongoDbTransaction | null = null;\n let hasEnded = false;\n\n const startTransaction = (options?: PongoTransactionOptions) => {\n assertNotInActiveTransaction(transaction);\n\n transaction = pongoTransaction(options ?? defaultTransactionOptions);\n };\n const commitTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.commit();\n };\n const abortTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.rollback();\n };\n\n const endSession = async (): Promise<void> => {\n if (hasEnded) return;\n hasEnded = true;\n\n if (isActive(transaction)) await transaction.rollback();\n };\n\n const session = {\n get hasEnded() {\n return hasEnded;\n },\n explicit,\n defaultTransactionOptions: defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n },\n get transaction() {\n return transaction;\n },\n get snapshotEnabled() {\n return defaultTransactionOptions.snapshotEnabled;\n },\n endSession,\n incrementTransactionNumber: () => {},\n inTransaction: () => isActive(transaction),\n startTransaction,\n commitTransaction,\n abortTransaction,\n withTransaction: async <T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T> => {\n startTransaction(options);\n\n try {\n const result = await fn(session);\n await commitTransaction();\n return result;\n } catch (error) {\n await abortTransaction();\n throw error;\n }\n },\n };\n\n return session;\n};\n","import { sql } from '@event-driven-io/dumbo';\nimport { objectEntries, OperatorMap } from '../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\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 = objectEntries(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 hasOperators,\n objectEntries,\n QueryOperators,\n type PongoFilter,\n} from '../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return objectEntries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { sql, type SQL } from '@event-driven-io/dumbo';\nimport {\n objectEntries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../core';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n objectEntries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, 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"],"mappings":"AAAA,OACE,UAAAA,GACA,OAAAC,EACA,gBAAAC,OAGK,yBCNP,OACE,2BAAAC,GACA,mBA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GAAgC,CAC3C,IAAME,EAAcC,EAAqBH,CAAM,EAC/C,OAAOR,EACL,iCACAD,EACAe,EAAMJ,CAAW,CACnB,CACF,EACA,KAAUF,GAAgC,CACxC,IAAME,EAAcC,EAAqBH,CAAM,EAC/C,OAAOR,EAAI,yBAA0BD,EAAgBe,EAAMJ,CAAW,CAAC,CACzE,EACA,eAAoBF,GAAgC,CAClD,IAAME,EAAcC,EAAqBH,CAAM,EAC/C,OAAOR,EACL,sCACAD,EACAe,EAAMJ,CAAW,CACnB,CACF,EACA,OAASK,GACPf,EAAI,8BAA+BD,EAAgBgB,CAAO,EAC5D,KAAM,CAACC,EAAqBjB,IAC1BC,EAAI,0BAA2BgB,CAAU,CAC7C,GAEMF,EAASN,GACbA,EAAO,OAAS,EAAIR,EAAI,WAAYQ,CAAM,EAAIS,GAAO,EAAE","names":["rawSql","sql","sqlMigration","runPostgreSQLMigrations","schemaComponent","single","uuid","dumbo","getDatabaseNameOrDefault","NodePostgresConnectorType","runPostgreSQLMigrations","schemaComponent","isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","db","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","db","options","transaction","transactionExecutorOrDefault","defaultSqlExecutor","pongoCollection","collectionName","pool","SqlFor","schema","sqlExecutor","command","sql","query","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","handle","byId","existing","newDoc","row","count","single","newName","schemaComponent","runPostgreSQLMigrations","pongoCollectionSchemaComponent","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","objectEntries","obj","key","value","pongoCollectionSchema","name","pongoDbSchema","nameOrCollections","collections","pongoClientSchema","dbs","pongoSchema","proxyPongoDbWithSchema","pongoDb","dbSchema","collectionNames","collectionName","target","prop","proxyClientWithSchema","client","schema","dbNames","toDbSchemaMetadata","objectEntries","c","toClientSchemaMetadata","databases","e","db","NodePostgresConnectorType","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","proxyClientWithSchema","NodePostgresConnectorType","sql","handleOperator","path","operator","value","handleIdOperator","sql","buildNestedObject","OperatorMap","v","subQuery","objectEntries","subKey","subValue","acc","key","AND","constructFilterQuery","filter","key","value","isRecord","constructComplexFilterQuery","handleOperator","isEquality","hasOperators","objectEntries","nestedKey","val","QueryOperators","sql","buildUpdateQuery","update","objectEntries","currentUpdateQuery","op","value","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","sql","set","unset","k","inc","key","push","createCollection","collectionName","sql","pongoCollectionPostgreSQLMigrations","sqlMigration","postgresSQLBuilder","document","documents","values","doc","filter","update","filterQuery","constructFilterQuery","updateQuery","buildUpdateQuery","where","newName","targetName","rawSql"]}
|
|
@@ -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 N=n=>n.connectorType===_dumbo.NodePostgresConnectorType,k= exports.d =n=>{let{connectionString:t,dbName:e}=n,o=_nullishCoalesce(e, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, t))),r=_dumbo.dumbo.call(void 0, {connectionString:t,...n.connectionOptions}),c=new Map,p={connectorType:n.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>r.close(),collection:u=>A({collectionName:u,db:p,pool:r,sqlBuilder:M(u),...n.schema?n.schema:{}}),transaction:()=>r.transaction(),withTransaction:u=>r.withTransaction(u),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongoDb",{components:[...c.values()].map(u=>u.schema.component)})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, r,[...c.values()].flatMap(u=>u.schema.component.migrations({connector:"PostgreSQL:pg"})))}},C=_optionalChain([n, 'optionalAccess', _2 => _2.schema, 'optionalAccess', _3 => _3.definition, 'optionalAccess', _4 => _4.dbs]);if(C){let u=P(C).map(y=>y[1]).find(y=>y.name===e||y.name===o);if(u)return j(p,u,c)}return p},wn= exports.e =n=>{let t=n.length>0&&typeof n[0]=="string"?n.map(e=>U(e)):n;return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:db",{components:t})};var on=async(n,t)=>{let e=_optionalChain([t, 'optionalAccess', _5 => _5.session, 'optionalAccess', _6 => _6.transaction]);return!e||!e.isActive?null:await e.enlistDatabase(n)},F=async(n,t,e)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await on(n,t)), 'optionalAccess', async _7 => _7.execute]), async () => (e)),A= exports.f =({db:n,collectionName:t,pool:e,sqlBuilder:o,schema:r})=>{let c=e.execute,p=async(i,a)=>(await F(n,a,c)).command(i),C=async(i,a)=>(await F(n,a,c)).query(i),u=_optionalChain([r, 'optionalAccess', _8 => _8.autoMigration])!=="None",y=i=>(u=!1,_optionalChain([i, 'optionalAccess', _9 => _9.session])?p(o.createCollection(),i):p(o.createCollection())),g=i=>u?y(i):Promise.resolve(),T={dbName:n.databaseName,collectionName:t,createCollection:async i=>{await y(i)},insertOne:async(i,a)=>{await g(a);let s=_nullishCoalesce(i._id, () => (_uuid.v4.call(void 0, )));return(await p(o.insertOne({...i,_id:s}),a)).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async(i,a)=>{await g(a);let s=i.map(O=>({...O,_id:_nullishCoalesce(O._id, () => (_uuid.v4.call(void 0, )))})),l=await p(o.insertMany(s),a);return{acknowledged:l.rowCount===s.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:s.map(O=>O._id)}},updateOne:async(i,a,s)=>{await g(s);let l=await p(o.updateOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(i,a,s)=>{await g(s);let l=await p(o.replaceOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(i,a,s)=>{await g(s);let l=await p(o.updateMany(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async(i,a)=>{await g(a);let s=await p(o.deleteOne(_nullishCoalesce(i, () => ({}))),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async(i,a)=>{await g(a);let s=await p(o.deleteMany(_nullishCoalesce(i, () => ({}))),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async(i,a)=>(await g(a),await _asyncNullishCoalesce(await _asyncOptionalChain([(await C(o.findOne(_nullishCoalesce(i, () => ({}))),a)), 'access', async _10 => _10.rows, 'access', async _11 => _11[0], 'optionalAccess', async _12 => _12.data]), async () => (null))),findOneAndDelete:async(i,a)=>{await g(a);let s=await T.findOne(i,a);return s===null?null:(await T.deleteOne(i,a),s)},findOneAndReplace:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.replaceOne(i,a,s),l)},findOneAndUpdate:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.updateOne(i,a,s),l)},handle:async(i,a,s)=>{await g(s);let l={_id:i},O=await T.findOne(l,s),b=await a(O);if(!O&&b){let I={...b,_id:i};return await T.insertOne({...I,_id:i},s),I}return O&&!b?(await T.deleteOne(l,s),null):(O&&b&&await T.replaceOne(l,b,s),b)},find:async(i,a)=>(await g(a),(await C(o.find(_nullishCoalesce(i, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(i,a)=>{await g(a);let{count:s}=await _dumbo.single.call(void 0, C(o.countDocuments(_nullishCoalesce(i, () => ({})))));return s},drop:async i=>(await g(i),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await p(o.drop())), 'optionalAccess', async _13 => _13.rowCount]), async () => (0)))>0),rename:async(i,a)=>(await g(a),await p(o.rename(i)),t=i,T),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, e,o.migrations())}};return T},U= exports.g =n=>_dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:()=>x(n)});var q={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},L= exports.i ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},rn= exports.j =n=>n.startsWith("$"),B= exports.k =n=>Object.keys(n).some(rn);var P=n=>Object.entries(n).map(([t,e])=>[t,e]);var sn=n=>({name:n});function an(n,t){if(t===void 0){if(typeof n=="string")throw new Error("You need to provide colleciton definition");return{collections:n}}return n&&typeof n=="string"?{name:n,collections:t}:{collections:t}}var cn=n=>({dbs:n}),Bn= exports.m ={client:cn,db:an,collection:sn},j= exports.n =(n,t,e)=>{let o=Object.keys(t.collections);for(let r of o)e.set(r,n.collection(r));return new Proxy(n,{get(r,c){return _nullishCoalesce(e.get(c), () => (r[c]))}})},J= exports.o =(n,t)=>{if(!t)return n;let e=Object.keys(t.dbs);return new Proxy(n,{get(o,r){return e.includes(r)?n.db(_optionalChain([t, 'access', _14 => _14.dbs, 'access', _15 => _15[r], 'optionalAccess', _16 => _16.name])):o[r]}})},ln= exports.p =n=>({name:n.name,collections:P(n.collections).map(t=>({name:t[1].name}))}),Jn= exports.q =n=>{let t=P(n.dbs).map(e=>ln(e[1]));return{databases:t,database:e=>t.find(o=>o.name===e)}};require('pg');var E=n=>{let{connectorType:t}=n;if(!N(n))throw new Error(`Unsupported db type: ${t}`);return k(n)};var K=n=>{let t=!1,e=!1,o=null,r=null;return{enlistDatabase:async c=>{if(r&&o!==c.databaseName)throw new Error("There's already other database assigned to transaction");return r&&o===c.databaseName||(o=c.databaseName,r=c.transaction(),await r.begin()),r},commit:async()=>{if(!r)throw new Error("No database transaction started!");if(!t){if(e)throw new Error("Transaction is not active!");t=!0,await r.commit(),r=null}},rollback:async c=>{if(!r)throw new Error("No database transaction started!");if(t)throw new Error("Cannot rollback commited transaction!");e||(e=!0,await r.rollback(c),r=null)},databaseName:o,isStarting:!1,isCommitted:t,get isActive(){return!t&&!e},get sqlExecutor(){if(r===null)throw new Error("No database transaction was started");return r.execute},options:n}};var w=n=>_optionalChain([n, 'optionalAccess', _17 => _17.isActive])===!0;function v(n){if(!w(n))throw new Error("No active transaction exists!")}function pn(n){if(w(n))throw new Error("Active transaction already exists!")}var Q=n=>{let t=_optionalChain([n, 'optionalAccess', _18 => _18.explicit])===!0,e=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _19 => _19.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,r=!1,c=g=>{pn(o),o=K(_nullishCoalesce(g, () => (e)))},p=async()=>{v(o),await o.commit()},C=async()=>{v(o),await o.rollback()},y={get hasEnded(){return r},explicit:t,defaultTransactionOptions:_nullishCoalesce(e, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return e.snapshotEnabled},endSession:async()=>{r||(r=!0,w(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>w(o),startTransaction:c,commitTransaction:p,abortTransaction:C,withTransaction:async(g,T)=>{c(T);try{let i=await g(y);return await p(),i}catch(i){throw await C(),i}}};return y};var ot=(n,t={})=>{let e=new Map,o=E(H({connectionString:n,clientOptions:t}));e.set(o.databaseName,o);let r={connect:async()=>(await o.connect(),r),close:async()=>{for(let c of e.values())await c.close()},db:c=>c?_nullishCoalesce(e.get(c), () => (e.set(c,E(H({connectionString:n,dbName:c,clientOptions:t}))).get(c))):o,startSession:Q,withSession:async c=>{let p=Q();try{return await c(p)}finally{await p.endSession()}}};return J(r,_optionalChain([t, 'optionalAccess', _20 => _20.schema, 'optionalAccess', _21 => _21.definition]))},H= exports.v =n=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:n.connectionString,dbName:n.dbName,...n.clientOptions});var D=(n,t,e)=>{if(n==="_id")return dn(t,e);switch(t){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(X(n,e)),n,JSON.stringify(e));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${L[t]} %L`,`{${n.split(".").join(",")}}`,e);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${n.split(".").join(",")}}`,e.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "data #>> %L NOT IN (%s)",`{${n.split(".").join(",")}}`,e.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=P(e).map(([r,c])=>_dumbo.sql.call(void 0, '@."%s" == %s',r,JSON.stringify(c))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",n,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",JSON.stringify(X(n,e)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${n.split(".").join(",")}}`,e);default:throw new Error(`Unsupported operator: ${t}`)}},dn=(n,t)=>{switch(n){case"$eq":return _dumbo.sql.call(void 0, "_id = %L",t);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `_id ${L[n]} %L`,t);case"$in":return _dumbo.sql.call(void 0, "_id IN (%s)",t.map(e=>_dumbo.sql.call(void 0, "%L",e)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "_id NOT IN (%s)",t.map(e=>_dumbo.sql.call(void 0, "%L",e)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},X=(n,t)=>n.split(".").reverse().reduce((e,o)=>({[o]:e}),t);var z="AND",f=n=>Object.entries(n).map(([t,e])=>mn(e)?un(t,e):D(t,"$eq",e)).join(` ${z} `),un=(n,t)=>{let e=!B(t);return P(t).map(([o,r])=>e?D(`${n}.${o}`,q.$eq,r):D(n,o,r)).join(` ${z} `)},mn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);var $=n=>P(n).reduce((t,[e,o])=>{switch(e){case"$set":return Tn(o,t);case"$unset":return Pn(o,t);case"$inc":return yn(o,t);case"$push":return Cn(o,t);default:return t}},_dumbo.sql.call(void 0, "data")),Tn=(n,t)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",t,JSON.stringify(n)),Pn=(n,t)=>_dumbo.sql.call(void 0, "%s - %L",t,Object.keys(n).map(e=>`{${e}}`).join(", ")),yn=(n,t)=>{for(let[e,o]of Object.entries(n))t=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",t,e,e,o);return t},Cn=(n,t)=>{for(let[e,o]of Object.entries(n))t=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",t,e,e,JSON.stringify([o]));return t};var Y=n=>_dumbo.sql.call(void 0, `CREATE TABLE IF NOT EXISTS %I (
|
|
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 N=n=>n.connectorType===_dumbo.NodePostgresConnectorType,k= exports.d =n=>{let{connectionString:e,dbName:t}=n,o=_nullishCoalesce(t, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, e))),r=_dumbo.dumbo.call(void 0, {connectionString:e,...n.connectionOptions}),c=new Map,p={connectorType:n.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>r.close(),collection:u=>A({collectionName:u,db:p,pool:r,sqlBuilder:M(u),...n.schema?n.schema:{}}),transaction:()=>r.transaction(),withTransaction:u=>r.withTransaction(u),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongoDb",{components:[...c.values()].map(u=>u.schema.component)})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, r,[...c.values()].flatMap(u=>u.schema.component.migrations({connector:"PostgreSQL:pg"})))}},C=_optionalChain([n, 'optionalAccess', _2 => _2.schema, 'optionalAccess', _3 => _3.definition, 'optionalAccess', _4 => _4.dbs]);if(C){let u=P(C).map(y=>y[1]).find(y=>y.name===t||y.name===o);if(u)return j(p,u,c)}return p},wn= exports.e =n=>{let e=n.length>0&&typeof n[0]=="string"?n.map(t=>U(t)):n;return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:db",{components:e})};var on=async(n,e)=>{let t=_optionalChain([e, 'optionalAccess', _5 => _5.session, 'optionalAccess', _6 => _6.transaction]);return!t||!t.isActive?null:await t.enlistDatabase(n)},F=async(n,e,t)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await on(n,e)), 'optionalAccess', async _7 => _7.execute]), async () => (t)),A= exports.f =({db:n,collectionName:e,pool:t,sqlBuilder:o,schema:r})=>{let c=t.execute,p=async(i,a)=>(await F(n,a,c)).command(i),C=async(i,a)=>(await F(n,a,c)).query(i),u=_optionalChain([r, 'optionalAccess', _8 => _8.autoMigration])!=="None",y=i=>(u=!1,_optionalChain([i, 'optionalAccess', _9 => _9.session])?p(o.createCollection(),i):p(o.createCollection())),g=i=>u?y(i):Promise.resolve(),T={dbName:n.databaseName,collectionName:e,createCollection:async i=>{await y(i)},insertOne:async(i,a)=>{await g(a);let s=_nullishCoalesce(i._id, () => (_uuid.v4.call(void 0, )));return(await p(o.insertOne({...i,_id:s}),a)).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async(i,a)=>{await g(a);let s=i.map(O=>({...O,_id:_nullishCoalesce(O._id, () => (_uuid.v4.call(void 0, )))})),l=await p(o.insertMany(s),a);return{acknowledged:l.rowCount===s.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:s.map(O=>O._id)}},updateOne:async(i,a,s)=>{await g(s);let l=await p(o.updateOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(i,a,s)=>{await g(s);let l=await p(o.replaceOne(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(i,a,s)=>{await g(s);let l=await p(o.updateMany(i,a),s);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async(i,a)=>{await g(a);let s=await p(o.deleteOne(_nullishCoalesce(i, () => ({}))),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async(i,a)=>{await g(a);let s=await p(o.deleteMany(_nullishCoalesce(i, () => ({}))),a);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async(i,a)=>(await g(a),await _asyncNullishCoalesce(await _asyncOptionalChain([(await C(o.findOne(_nullishCoalesce(i, () => ({}))),a)), 'access', async _10 => _10.rows, 'access', async _11 => _11[0], 'optionalAccess', async _12 => _12.data]), async () => (null))),findOneAndDelete:async(i,a)=>{await g(a);let s=await T.findOne(i,a);return s===null?null:(await T.deleteOne(i,a),s)},findOneAndReplace:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.replaceOne(i,a,s),l)},findOneAndUpdate:async(i,a,s)=>{await g(s);let l=await T.findOne(i,s);return l===null?null:(await T.updateOne(i,a,s),l)},handle:async(i,a,s)=>{await g(s);let l={_id:i},O=await T.findOne(l,s),b=await a(O);if(!O&&b){let I={...b,_id:i};return await T.insertOne({...I,_id:i},s),I}return O&&!b?(await T.deleteOne(l,s),null):(O&&b&&await T.replaceOne(l,b,s),b)},find:async(i,a)=>(await g(a),(await C(o.find(_nullishCoalesce(i, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(i,a)=>{await g(a);let{count:s}=await _dumbo.single.call(void 0, C(o.countDocuments(_nullishCoalesce(i, () => ({})))));return s},drop:async i=>(await g(i),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await p(o.drop())), 'optionalAccess', async _13 => _13.rowCount]), async () => (0)))>0),rename:async(i,a)=>(await g(a),await p(o.rename(i)),e=i,T),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, t,o.migrations())}};return T},U= exports.g =n=>_dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:()=>x(n)});var q={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},L= exports.i ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},rn= exports.j =n=>n.startsWith("$"),B= exports.k =n=>Object.keys(n).some(rn);var P=n=>Object.entries(n).map(([e,t])=>[e,t]);var sn=n=>({name:n});function an(n,e){if(e===void 0){if(typeof n=="string")throw new Error("You need to provide colleciton definition");return{collections:n}}return n&&typeof n=="string"?{name:n,collections:e}:{collections:e}}var cn=n=>({dbs:n}),Bn= exports.m ={client:cn,db:an,collection:sn},j= exports.n =(n,e,t)=>{let o=Object.keys(e.collections);for(let r of o)t.set(r,n.collection(r));return new Proxy(n,{get(r,c){return _nullishCoalesce(t.get(c), () => (r[c]))}})},J= exports.o =(n,e)=>{if(!e)return n;let t=Object.keys(e.dbs);return new Proxy(n,{get(o,r){return t.includes(r)?n.db(_optionalChain([e, 'access', _14 => _14.dbs, 'access', _15 => _15[r], 'optionalAccess', _16 => _16.name])):o[r]}})},ln= exports.p =n=>({name:n.name,collections:P(n.collections).map(e=>({name:e[1].name}))}),Jn= exports.q =n=>{let e=P(n.dbs).map(t=>ln(t[1]));return{databases:e,database:t=>e.find(o=>o.name===t)}};require('pg');var E=n=>{let{connectorType:e}=n;if(!N(n))throw new Error(`Unsupported db type: ${e}`);return k(n)};var K=n=>{let e=!1,t=!1,o=null,r=null;return{enlistDatabase:async c=>{if(r&&o!==c.databaseName)throw new Error("There's already other database assigned to transaction");return r&&o===c.databaseName||(o=c.databaseName,r=c.transaction(),await r.begin()),r},commit:async()=>{if(!r)throw new Error("No database transaction started!");if(!e){if(t)throw new Error("Transaction is not active!");e=!0,await r.commit(),r=null}},rollback:async c=>{if(!r)throw new Error("No database transaction started!");if(e)throw new Error("Cannot rollback commited transaction!");t||(t=!0,await r.rollback(c),r=null)},databaseName:o,isStarting:!1,isCommitted:e,get isActive(){return!e&&!t},get sqlExecutor(){if(r===null)throw new Error("No database transaction was started");return r.execute},options:n}};var w=n=>_optionalChain([n, 'optionalAccess', _17 => _17.isActive])===!0;function v(n){if(!w(n))throw new Error("No active transaction exists!")}function pn(n){if(w(n))throw new Error("Active transaction already exists!")}var Q=n=>{let e=_optionalChain([n, 'optionalAccess', _18 => _18.explicit])===!0,t=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _19 => _19.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,r=!1,c=g=>{pn(o),o=K(_nullishCoalesce(g, () => (t)))},p=async()=>{v(o),await o.commit()},C=async()=>{v(o),await o.rollback()},y={get hasEnded(){return r},explicit:e,defaultTransactionOptions:_nullishCoalesce(t, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return t.snapshotEnabled},endSession:async()=>{r||(r=!0,w(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>w(o),startTransaction:c,commitTransaction:p,abortTransaction:C,withTransaction:async(g,T)=>{c(T);try{let i=await g(y);return await p(),i}catch(i){throw await C(),i}}};return y};var oe=(n,e={})=>{let t=new Map,o=E(H({connectionString:n,clientOptions:e}));t.set(o.databaseName,o);let r={connect:async()=>(await o.connect(),r),close:async()=>{for(let c of t.values())await c.close()},db:c=>c?_nullishCoalesce(t.get(c), () => (t.set(c,E(H({connectionString:n,dbName:c,clientOptions:e}))).get(c))):o,startSession:Q,withSession:async c=>{let p=Q();try{return await c(p)}finally{await p.endSession()}}};return J(r,_optionalChain([e, 'optionalAccess', _20 => _20.schema, 'optionalAccess', _21 => _21.definition]))},H= exports.v =n=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:n.connectionString,dbName:n.dbName,...n.clientOptions});var D=(n,e,t)=>{if(n==="_id")return dn(e,t);switch(e){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(X(n,t)),n,JSON.stringify(t));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${L[e]} %L`,`{${n.split(".").join(",")}}`,t);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${n.split(".").join(",")}}`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "data #>> %L NOT IN (%s)",`{${n.split(".").join(",")}}`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=P(t).map(([r,c])=>_dumbo.sql.call(void 0, '@."%s" == %s',r,JSON.stringify(c))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",n,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",JSON.stringify(X(n,t)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${n.split(".").join(",")}}`,t);default:throw new Error(`Unsupported operator: ${e}`)}},dn=(n,e)=>{switch(n){case"$eq":return _dumbo.sql.call(void 0, "_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `_id ${L[n]} %L`,e);case"$in":return _dumbo.sql.call(void 0, "_id IN (%s)",e.map(t=>_dumbo.sql.call(void 0, "%L",t)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "_id NOT IN (%s)",e.map(t=>_dumbo.sql.call(void 0, "%L",t)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},X=(n,e)=>n.split(".").reverse().reduce((t,o)=>({[o]:t}),e);var z="AND",f=n=>Object.entries(n).map(([e,t])=>mn(t)?un(e,t):D(e,"$eq",t)).join(` ${z} `),un=(n,e)=>{let t=!B(e);return P(e).map(([o,r])=>t?D(`${n}.${o}`,q.$eq,r):D(n,o,r)).join(` ${z} `)},mn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);var $=n=>P(n).reduce((e,[t,o])=>{switch(t){case"$set":return Tn(o,e);case"$unset":return Pn(o,e);case"$inc":return yn(o,e);case"$push":return Cn(o,e);default:return e}},_dumbo.sql.call(void 0, "data")),Tn=(n,e)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",e,JSON.stringify(n)),Pn=(n,e)=>_dumbo.sql.call(void 0, "%s - %L",e,Object.keys(n).map(t=>`{${t}}`).join(", ")),yn=(n,e)=>{for(let[t,o]of Object.entries(n))e=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",e,t,t,o);return e},Cn=(n,e)=>{for(let[t,o]of Object.entries(n))e=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",e,t,t,JSON.stringify([o]));return e};var Y=n=>_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 '{}',
|
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
_archived BOOLEAN NOT NULL DEFAULT FALSE,
|
|
8
8
|
_created TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
9
9
|
_updated TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
10
|
-
)`,n),x= exports.a =n=>[_dumbo.sqlMigration.call(void 0, `pongoCollection:${n}:001:createtable`,[Y(n)])],M= exports.b =n=>({migrations:()=>x(n),createCollection:()=>Y(n),insertOne:
|
|
10
|
+
)`,n),x= exports.a =n=>[_dumbo.sqlMigration.call(void 0, `pongoCollection:${n}:001:createtable`,[Y(n)])],M= exports.b =n=>({migrations:()=>x(n),createCollection:()=>Y(n),insertOne:e=>_dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES (%L, %L)",n,e._id,JSON.stringify(e)),insertMany:e=>{let t=e.map(o=>_dumbo.sql.call(void 0, "(%L, %L)",o._id,JSON.stringify(o))).join(", ");return _dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES %s",n,t)},updateOne:(e,t)=>{let o=f(e),r=$(t);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`,n,S(o),n,r,n)},replaceOne:(t
|
|
14
|
-
//# sourceMappingURL=chunk-
|
|
13
|
+
UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,n,S(o),n,r,n)},replaceOne:(e,t)=>{let o=f(e);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s",n,JSON.stringify(t),S(o))},updateMany:(e,t)=>{let o=f(e),r=$(t);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %s %s",n,r,S(o))},deleteOne:e=>{let t=f(e);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",n,S(t))},deleteMany:e=>{let t=f(e);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",n,S(t))},findOne:e=>{let t=f(e);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1",n,S(t))},find:e=>{let t=f(e);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s",n,S(t))},countDocuments:e=>{let t=f(e);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s",n,S(t))},rename:e=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I",n,e),drop:(e=n)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",e)}),S=n=>n.length>0?_dumbo.sql.call(void 0, "WHERE %s",n):_dumbo.rawSql.call(void 0, "");exports.a = x; exports.b = M; exports.c = N; exports.d = k; exports.e = wn; exports.f = A; exports.g = U; exports.h = q; exports.i = L; exports.j = rn; exports.k = B; exports.l = P; exports.m = Bn; exports.n = j; exports.o = J; exports.p = ln; exports.q = Jn; exports.r = E; exports.s = K; exports.t = Q; exports.u = oe; exports.v = H;
|
|
14
|
+
//# sourceMappingURL=chunk-OOCCQKUB.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/typing/entries.ts","../src/core/schema/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts"],"names":["isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","db","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","transaction","transactionExecutorOrDefault","defaultSqlExecutor","SqlFor","schema","sqlExecutor","command","sql","query","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","byId","existing","newDoc","row","count","single","newName","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","obj","pongoCollectionSchema","name","pongoDbSchema","nameOrCollections","pongoClientSchema","dbs","pongoSchema","pongoDb","collectionNames","target","prop","proxyClientWithSchema","client","dbNames","toDbSchemaMetadata","toClientSchemaMetadata","databases","getPongoDb","type"],"mappings":"AAAA,g3CAMO,4BCOoB,ICWdA,CAAAA,CACXC,CAAAA,EAEAA,CAAAA,CAAQ,aAAA,GAAkBC,gCAAAA,CAEfC,CAAAA,aACXF,CAAAA,EAC+B,CAC/B,GAAM,CAAE,gBAAA,CAAAG,CAAAA,CAAkB,MAAA,CAAAC,CAAO,CAAA,CAAIJ,CAAAA,CAC/BK,CAAAA,kBAAeD,CAAAA,SAAUE,6CAAAA,CAAyC,GAAA,CAElEC,CAAAA,CAAOC,0BAAAA,CACX,gBAAA,CAAAL,CAAAA,CACA,GAAGH,CAAAA,CAAQ,iBACb,CAAC,CAAA,CAEKS,CAAAA,CAAc,IAAI,GAAA,CAElBC,CAAAA,CAAiC,CACrC,aAAA,CAAeV,CAAAA,CAAQ,aAAA,CACvB,YAAA,CAAAK,CAAAA,CACA,OAAA,CAAS,CAAA,CAAA,EAAM,OAAA,CAAQ,OAAA,CAAQ,CAAA,CAC/B,KAAA,CAAO,CAAA,CAAA,EAAME,CAAAA,CAAK,KAAA,CAAM,CAAA,CACxB,UAAA,CAAaI,CAAAA,EACXC,CAAAA,CAAgB,CACd,cAAA,CAAAD,CAAAA,CACA,EAAA,CAAAD,CAAAA,CACA,IAAA,CAAAH,CAAAA,CACA,UAAA,CAAYM,CAAAA,CAAmBF,CAAc,CAAA,CAC7C,GAAI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/Pongo/Pongo/src/packages/pongo/dist/chunk-OOCCQKUB.cjs","sourcesContent":["import {\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n type OptionalUnlessRequiredId,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]): SQL => {\n const values = documents\n .map((doc) => sql('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n\n return sql(\n `UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s`,\n collectionName,\n JSON.stringify(document),\n where(filterQuery),\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s %s',\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I %s LIMIT 1',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v4 as uuid } from 'uuid';\nimport {\n type CollectionOperationOptions,\n type DocumentHandler,\n type OptionalUnlessRequiredId,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithoutId,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nconst transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async (sql: SQL, options?: CollectionOperationOptions) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).command(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n\n const result = await command(\n SqlFor.insertOne({ ...document, _id } as OptionalUnlessRequiredId<T>),\n options,\n );\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (\n documents: OptionalUnlessRequiredId<T>[],\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredId<T>[]),\n options,\n );\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id as string),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateOne(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(\n SqlFor.replaceOne(filter, document),\n options,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteOne(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as T | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = await collection.findOne(byId, options);\n\n const result = await handle(existing);\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredId<T>,\n options,\n );\n return newDoc;\n }\n\n if (existing && !result) {\n await collection.deleteOne(byId, options);\n return null;\n }\n\n if (existing && result)\n await collection.replaceOne(byId, result, options);\n\n return result;\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as T);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredId<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]) => SQL;\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>) => SQL;\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n deleteOne: <T>(filter: PongoFilter<T>) => SQL;\n deleteMany: <T>(filter: PongoFilter<T>) => SQL;\n findOne: <T>(filter: PongoFilter<T>) => SQL;\n find: <T>(filter: PongoFilter<T>) => SQL;\n countDocuments: <T>(filter: PongoFilter<T>) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n type PostgresConnector,\n type PostgresPoolOptions,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n ...(options.schema ? options.schema : {}),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const objectEntries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import {\n type Document,\n type PongoClient,\n type PongoCollection,\n type PongoDb,\n type PongoDocument,\n objectEntries,\n} from '../typing';\n\nexport interface PongoCollectionSchema<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n T extends PongoDocument = PongoDocument,\n> {\n name: string;\n}\n\n// Database schema interface\nexport interface PongoDbSchema<\n T extends Record<string, PongoCollectionSchema> = Record<\n string,\n PongoCollectionSchema\n >,\n> {\n name?: string;\n collections: T;\n}\n\nexport interface PongoClientSchema<\n T extends Record<string, PongoDbSchema> = Record<string, PongoDbSchema>,\n> {\n dbs: T;\n}\n\nexport type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {\n [K in keyof T]: PongoCollection<\n T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument\n >;\n};\n\nexport type PongoDbWithSchema<\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n> = CollectionsMap<T> & PongoDb<ConnectorType>;\n\nexport type DBsMap<\n T extends Record<string, PongoDbSchema>,\n ConnectorType extends string = string,\n> = {\n [K in keyof T]: CollectionsMap<T[K]['collections']> & PongoDb<ConnectorType>;\n};\n\nexport type PongoClientWithSchema<\n T extends PongoClientSchema,\n ConnectorType extends string = string,\n> = DBsMap<T['dbs'], ConnectorType> & PongoClient;\n\nconst pongoCollectionSchema = <T extends PongoDocument>(\n name: string,\n): PongoCollectionSchema<T> => ({\n name,\n});\n\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n name: string,\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n nameOrCollections: string | T,\n collections?: T | undefined,\n): PongoDbSchema<T> {\n if (collections === undefined) {\n if (typeof nameOrCollections === 'string') {\n throw new Error('You need to provide colleciton definition');\n }\n return {\n collections: nameOrCollections,\n };\n }\n\n return nameOrCollections && typeof nameOrCollections === 'string'\n ? {\n name: nameOrCollections,\n collections,\n }\n : { collections: collections };\n}\n\nconst pongoClientSchema = <T extends Record<string, PongoDbSchema>>(\n dbs: T,\n): PongoClientSchema<T> => ({\n dbs,\n});\n\nexport const pongoSchema = {\n client: pongoClientSchema,\n db: pongoDbSchema,\n collection: pongoCollectionSchema,\n};\n\n// Factory function to create DB instances\nexport const proxyPongoDbWithSchema = <\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n>(\n pongoDb: PongoDb<ConnectorType>,\n dbSchema: PongoDbSchema<T>,\n collections: Map<string, PongoCollection<Document>>,\n): PongoDbWithSchema<T, ConnectorType> => {\n const collectionNames = Object.keys(dbSchema.collections);\n\n for (const collectionName of collectionNames) {\n collections.set(collectionName, pongoDb.collection(collectionName));\n }\n\n return new Proxy(\n pongoDb as PongoDb<ConnectorType> & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n return collections.get(prop) ?? target[prop];\n },\n },\n ) as PongoDbWithSchema<T, ConnectorType>;\n};\n\nexport const proxyClientWithSchema = <\n TypedClientSchema extends PongoClientSchema,\n>(\n client: PongoClient,\n schema: TypedClientSchema | undefined,\n): PongoClientWithSchema<TypedClientSchema> => {\n if (!schema) return client as PongoClientWithSchema<TypedClientSchema>;\n\n const dbNames = Object.keys(schema.dbs);\n\n return new Proxy(\n client as PongoClient & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n if (dbNames.includes(prop)) return client.db(schema.dbs[prop]?.name);\n\n return target[prop];\n },\n },\n ) as PongoClientWithSchema<TypedClientSchema>;\n};\n\nexport type PongoCollectionSchemaMetadata = {\n name: string;\n};\n\nexport type PongoDbSchemaMetadata = {\n name?: string | undefined;\n collections: PongoCollectionSchemaMetadata[];\n};\n\nexport type PongoClientSchemaMetadata = {\n databases: PongoDbSchemaMetadata[];\n database: (name?: string) => PongoDbSchemaMetadata | undefined;\n};\n\nexport const toDbSchemaMetadata = <TypedDbSchema extends PongoDbSchema>(\n schema: TypedDbSchema,\n): PongoDbSchemaMetadata => ({\n name: schema.name,\n collections: objectEntries(schema.collections).map((c) => ({\n name: c[1].name,\n })),\n});\n\nexport const toClientSchemaMetadata = <\n TypedClientSchema extends PongoClientSchema,\n>(\n schema: TypedClientSchema,\n): PongoClientSchemaMetadata => {\n const databases = objectEntries(schema.dbs).map((e) =>\n toDbSchemaMetadata(e[1]),\n );\n\n return {\n databases,\n database: (name) => databases.find((db) => db.name === name),\n };\n};\n\nexport interface PongoSchemaConfig<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> {\n schema: TypedClientSchema;\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n"]}
|
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var
|
|
2
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkOOCCQKUBcjs = require('./chunk-OOCCQKUB.cjs');var _commander = require('commander');var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var p=o=>{if(o.length===0)return o;let e=o.charAt(0).toUpperCase()+o.slice(1);return e.endsWith("s")&&(e=e.slice(0,-1)),e},i=(o=["users"])=>{let e=o.map(n=>`type ${p(n)} = { name: string; description: string; date: Date }`).join(`
|
|
3
3
|
`),t=o.map(n=>` ${n}: pongoSchema.collection<${p(n)}>('${n}'),`).join(`
|
|
4
4
|
`);return`import { pongoSchema } from '@event-driven-io/pongo';
|
|
5
5
|
|
|
@@ -21,7 +21,7 @@ ${i()}`,E=`Error: Config should have a default database defined (without name or
|
|
|
21
21
|
|
|
22
22
|
${i()}`,d=`Error: Database should have defined at least one collection, e.g.
|
|
23
23
|
|
|
24
|
-
${i()}`,u=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(e.href))),n=$(t);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch (e2){console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},M=(o,e)=>{try{_fs2.default.writeFileSync(o,i(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},$=o=>{if(!o.default)return y;if(!o.default.schema)return x;if(!o.default.schema.dbs)return v;let t=
|
|
24
|
+
${i()}`,u=async o=>{let e=new URL(o,`file://${process.cwd()}/`);try{let t=await Promise.resolve().then(() => _interopRequireWildcard(require(e.href))),n=$(t);return typeof n=="string"&&(console.error(n),process.exit(1)),n}catch (e2){console.error(`Error: Couldn't load file: ${e.href}`),process.exit(1)}},M=(o,e)=>{try{_fs2.default.writeFileSync(o,i(e),"utf8"),console.log(`Configuration file stored at: ${o}`)}catch(t){console.error(`Error: Couldn't store config file: ${o}!`),console.error(t),process.exit(1)}},$=o=>{if(!o.default)return y;if(!o.default.schema)return x;if(!o.default.schema.dbs)return v;let t=_chunkOOCCQKUBcjs.l.call(void 0, o.default.schema.dbs).map(r=>r[1]).find(r=>r.name===void 0);return t?!t.collections||_chunkOOCCQKUBcjs.l.call(void 0, t.collections).map(r=>r[1]).length===0?d:_chunkOOCCQKUBcjs.p.call(void 0, t):E},g=new (0, _commander.Command)("config").description("Manage Pongo configuration"),w=g.command("sample").description("Generate or print sample configuration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --file <path>","Path to configuration file with collection list").option("-g, --generate","Generate sample config file").option("-p, --print","Print sample config file").action(o=>{let e=o.collection.length>0?o.collection:["users"];!("print"in o)&&!("generate"in o)&&(console.error(`Error: Please provide either:
|
|
25
25
|
--print param to print sample config or
|
|
26
|
-
--generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${i(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),M(o.file,e))});w.command("generate");var _dumbo = require('@event-driven-io/dumbo');var c=new (0, _commander.Command)("migrate").description("Manage database migrations");c.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:t}=o,n=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)),r;n||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await u(o.config)).collections.map(S=>S.name):e?r=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let h=_dumbo.dumbo.call(void 0, {connectionString:n}),C=r.flatMap(m=>
|
|
26
|
+
--generate to generate sample config file`),process.exit(1)),"print"in o?console.log(`${i(e)}`):"generate"in o&&(o.file||(console.error("Error: You need to provide a config file through a --file"),process.exit(1)),M(o.file,e))});w.command("generate");var _dumbo = require('@event-driven-io/dumbo');var c=new (0, _commander.Command)("migrate").description("Manage database migrations");c.command("run").description("Run database migrations").option("-cs, --connectionString <string>","Connection string for the database").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("-f, --config <path>","Path to configuration file with Pongo config").option("-dr, --dryRun","Perform dry run without commiting changes",!1).action(async o=>{let{collection:e,dryRun:t}=o,n=_nullishCoalesce(o.connectionString, () => (process.env.DB_CONNECTION_STRING)),r;n||(console.error('Error: Connection string is required. Provide it either as a "--connectionString" parameter or through the DB_CONNECTION_STRING environment variable.'),process.exit(1)),o.config?r=(await u(o.config)).collections.map(S=>S.name):e?r=e:(console.error('Error: You need to provide at least one collection name. Provide it either through "--config" file or as a "--collection" parameter.'),process.exit(1));let h=_dumbo.dumbo.call(void 0, {connectionString:n}),C=r.flatMap(m=>_chunkOOCCQKUBcjs.g.call(void 0, m).migrations({connector:"PostgreSQL:pg"}));await _dumbo.runPostgreSQLMigrations.call(void 0, h,C,{dryRun:t})});c.command("sql").description("Generate SQL for database migration").option("-col, --collection <name>","Specify the collection name",(o,e)=>e.concat([o]),[]).option("--print","Print the SQL to the console (default)",!0).action(o=>{let{collection:e}=o;e||(console.error('Error: You need to provide at least one collection name is required. Provide it either as a "col" parameter.'),process.exit(1));let n=[..._dumbo.migrationTableSchemaComponent.migrations({connector:"PostgreSQL:pg"}),...e.flatMap(r=>_chunkOOCCQKUBcjs.g.call(void 0, r).migrations({connector:"PostgreSQL:pg"}))];console.log("Printing SQL:"),console.log(_dumbo.combineMigrations.call(void 0, ...n))});var a=new _commander.Command;a.name("pongo").description("CLI tool for Pongo");a.addCommand(g);a.addCommand(c);a.parse(process.argv);var H=a;exports.default = H;
|
|
27
27
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","../src/cli.ts","../src/commandLine/configFile.ts"],"names":["formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport"],"mappings":"AAAA;AACA,ulBAAiD,sCCAzB,gECAT,IAQTA,CAAAA,CAAkBC,CAAAA,EAA0B,CAChD,EAAA,CAAIA,CAAAA,CAAM,MAAA,GAAW,CAAA,CACnB,OAAOA,CAAAA,CAGT,IAAIC,CAAAA,CAAYD,CAAAA,CAAM,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,CAAY,CAAA,CAAIA,CAAAA,CAAM,KAAA,CAAM,CAAC,CAAA,CAE7D,OAAIC,CAAAA,CAAU,QAAA,CAAS,GAAG,CAAA,EAAA,CACxBA,CAAAA,CAAYA,CAAAA,CAAU,KAAA,CAAM,CAAA,CAAG,CAAA,CAAE,CAAA,CAAA,CAG5BA,CACT,CAAA,CAEMC,CAAAA,CAAe,CAACC,CAAAA,CAA4B,CAAC,OAAO,CAAA,CAAA,EAAM,CAC9D,IAAMC,CAAAA,CAAQD,CAAAA,CACX,GAAA,CACEE,CAAAA,EACC,CAAA,KAAA,EAAQN,CAAAA,CAAeM,CAAI,CAAC,CAAA,oDAAA,CAChC,CAAA,CACC,IAAA,CAAK,CAAA;AAAA,CAAI,CAAA,CAENC,CAAAA,CAAcH,CAAAA,CACjB,GAAA,CACEE,CAAAA,EACC,CAAA,MAAA,EAASA,CAAI,CAAA,yBAAA,EAA4BN,CAAAA,CAAeM,CAAI,CAAC,CAAA,GAAA,EAAMA,CAAI,CAAA,GAAA,CAC3E,CAAA,CACC,IAAA,CAAK,CAAA;AAAA,CAAI,CAAA,CAEZ,MAAO,CAAA;AAAA;AAAA,EAEPD,CAAK,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKLE,CAAW,CAAA;AAAA;AAAA;AAAA,EAAA,CAIb,CAAA,CAEMC,CAAAA,CAAuB,CAAA;AAAA;AAAA,EAAwDL,CAAAA,CAAa,CAAC,CAAA,CAAA;AAC7E;AAAuE;AAC1E;AAAuF;AACjF;AAA+H;AAC7H;AAAsF;AAmHzG;AAAA,yCAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `type ${formatTypeName(name)} = { name: string
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","../src/cli.ts","../src/commandLine/configFile.ts"],"names":["formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport"],"mappings":"AAAA;AACA,ulBAAiD,sCCAzB,gECAT,IAQTA,CAAAA,CAAkBC,CAAAA,EAA0B,CAChD,EAAA,CAAIA,CAAAA,CAAM,MAAA,GAAW,CAAA,CACnB,OAAOA,CAAAA,CAGT,IAAIC,CAAAA,CAAYD,CAAAA,CAAM,MAAA,CAAO,CAAC,CAAA,CAAE,WAAA,CAAY,CAAA,CAAIA,CAAAA,CAAM,KAAA,CAAM,CAAC,CAAA,CAE7D,OAAIC,CAAAA,CAAU,QAAA,CAAS,GAAG,CAAA,EAAA,CACxBA,CAAAA,CAAYA,CAAAA,CAAU,KAAA,CAAM,CAAA,CAAG,CAAA,CAAE,CAAA,CAAA,CAG5BA,CACT,CAAA,CAEMC,CAAAA,CAAe,CAACC,CAAAA,CAA4B,CAAC,OAAO,CAAA,CAAA,EAAM,CAC9D,IAAMC,CAAAA,CAAQD,CAAAA,CACX,GAAA,CACEE,CAAAA,EACC,CAAA,KAAA,EAAQN,CAAAA,CAAeM,CAAI,CAAC,CAAA,oDAAA,CAChC,CAAA,CACC,IAAA,CAAK,CAAA;AAAA,CAAI,CAAA,CAENC,CAAAA,CAAcH,CAAAA,CACjB,GAAA,CACEE,CAAAA,EACC,CAAA,MAAA,EAASA,CAAI,CAAA,yBAAA,EAA4BN,CAAAA,CAAeM,CAAI,CAAC,CAAA,GAAA,EAAMA,CAAI,CAAA,GAAA,CAC3E,CAAA,CACC,IAAA,CAAK,CAAA;AAAA,CAAI,CAAA,CAEZ,MAAO,CAAA;AAAA;AAAA,EAEPD,CAAK,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKLE,CAAW,CAAA;AAAA;AAAA;AAAA,EAAA,CAIb,CAAA,CAEMC,CAAAA,CAAuB,CAAA;AAAA;AAAA,EAAwDL,CAAAA,CAAa,CAAC,CAAA,CAAA;AAC7E;AAAuE;AAC1E;AAAuF;AACjF;AAA+H;AAC7H;AAAsF;AAmHzG;AAAA,yCAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/cli.cjs","sourcesContent":[null,"#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconst sampleConfigCommand = configCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n\nsampleConfigCommand.command('generate');\n"]}
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{g as s,l,p as f}from"./chunk-
|
|
2
|
+
import{g as s,l,p as f}from"./chunk-MAHDZ7ZR.js";import{Command as Q}from"commander";import{Command as b}from"commander";import P from"node:fs";var p=o=>{if(o.length===0)return o;let e=o.charAt(0).toUpperCase()+o.slice(1);return e.endsWith("s")&&(e=e.slice(0,-1)),e},i=(o=["users"])=>{let e=o.map(n=>`type ${p(n)} = { name: string; description: string; date: Date }`).join(`
|
|
3
3
|
`),t=o.map(n=>` ${n}: pongoSchema.collection<${p(n)}>('${n}'),`).join(`
|
|
4
4
|
`);return`import { pongoSchema } from '@event-driven-io/pongo';
|
|
5
5
|
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `type ${formatTypeName(name)} = { name: string, description: string, date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconst sampleConfigCommand = configCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n\nsampleConfigCommand.command('generate');\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collection.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n"],"mappings":";iDACA,OAAS,WAAAA,MAAe,YCDxB,OAAS,WAAAC,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C,EAAI,EAEhE,OAAQE,GAA+B,CACtC,GAAM,CAAE,WAAAC,CAAW,EAAID,EAElBC,IACH,QAAQ,MACN,8GACF,EACA,QAAQ,KAAK,CAAC,GAKhB,IAAMQ,EAAa,CACjB,GAJqBI,EAA8B,WAAW,CAC9D,UAAW,eACb,CAAC,EAGC,GAAGZ,EAAW,QAASS,GACrBC,EAA+BD,CAAe,EAAE,WAAW,CACzD,UAAW,eACb,CAAC,CACH,CACF,EAEA,QAAQ,IAAI,eAAe,EAC3B,QAAQ,IAAII,EAAkB,GAAGL,CAAU,CAAC,CAC9C,CAAC,EFrHH,IAAMM,EAAU,IAAIC,EAEpBD,EAAQ,KAAK,OAAO,EAAE,YAAY,oBAAoB,EAEtDA,EAAQ,WAAWE,CAAa,EAChCF,EAAQ,WAAWG,CAAc,EAEjCH,EAAQ,MAAM,QAAQ,IAAI,EAE1B,IAAOI,EAAQJ","names":["Command","Command","fs","formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport","missingSchema","missingDbs","missingDefaultDb","missingCollections","loadConfigFile","configPath","configUrl","imported","parsed","parseDefaultDbSchema","generateConfigFile","fs","error","defaultDb","objectEntries","db","col","toDbSchemaMetadata","configCommand","Command","sampleConfigCommand","value","previous","options","combineMigrations","dumbo","migrationTableSchemaComponent","runPostgreSQLMigrations","Command","migrateCommand","Command","value","previous","options","collection","dryRun","connectionString","collectionNames","loadConfigFile","c","pool","dumbo","migrations","collectionsName","pongoCollectionSchemaComponent","runPostgreSQLMigrations","migrationTableSchemaComponent","combineMigrations","program","Command","configCommand","migrateCommand","cli_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/commandLine/configFile.ts","../src/commandLine/migrate.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { configCommand, migrateCommand } from './commandLine';\n\nconst program = new Command();\n\nprogram.name('pongo').description('CLI tool for Pongo');\n\nprogram.addCommand(configCommand);\nprogram.addCommand(migrateCommand);\n\nprogram.parse(process.argv);\n\nexport default program;\n","import { Command } from 'commander';\nimport fs from 'node:fs';\nimport {\n objectEntries,\n toDbSchemaMetadata,\n type PongoDbSchemaMetadata,\n type PongoSchemaConfig,\n} from '../core';\n\nconst formatTypeName = (input: string): string => {\n if (input.length === 0) {\n return input;\n }\n\n let formatted = input.charAt(0).toUpperCase() + input.slice(1);\n\n if (formatted.endsWith('s')) {\n formatted = formatted.slice(0, -1);\n }\n\n return formatted;\n};\n\nconst sampleConfig = (collectionNames: string[] = ['users']) => {\n const types = collectionNames\n .map(\n (name) =>\n `type ${formatTypeName(name)} = { name: string; description: string; date: Date }`,\n )\n .join('\\n');\n\n const collections = collectionNames\n .map(\n (name) =>\n ` ${name}: pongoSchema.collection<${formatTypeName(name)}>('${name}'),`,\n )\n .join('\\n');\n\n return `import { pongoSchema } from '@event-driven-io/pongo';\n\n${types}\n\nexport default {\n schema: pongoSchema.client({\n database: pongoSchema.db({\n${collections}\n }),\n }),\n};`;\n};\n\nconst missingDefaultExport = `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`;\nconst missingSchema = `Error: Config should contain schema property, e.g.\\n\\n${sampleConfig()}`;\nconst missingDbs = `Error: Config should have at least a single database defined, e.g.\\n\\n${sampleConfig()}`;\nconst missingDefaultDb = `Error: Config should have a default database defined (without name or or with default database name), e.g.\\n\\n${sampleConfig()}`;\nconst missingCollections = `Error: Database should have defined at least one collection, e.g.\\n\\n${sampleConfig()}`;\n\nexport const loadConfigFile = async (\n configPath: string,\n): Promise<PongoDbSchemaMetadata> => {\n const configUrl = new URL(configPath, `file://${process.cwd()}/`);\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const imported: Partial<{ default: PongoSchemaConfig }> = await import(\n configUrl.href\n );\n\n const parsed = parseDefaultDbSchema(imported);\n\n if (typeof parsed === 'string') {\n console.error(parsed);\n process.exit(1);\n }\n\n return parsed;\n } catch {\n console.error(`Error: Couldn't load file: ${configUrl.href}`);\n process.exit(1);\n }\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n fs.writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const parseDefaultDbSchema = (\n imported: Partial<{ default: PongoSchemaConfig }>,\n): PongoDbSchemaMetadata | string => {\n if (!imported.default) {\n return missingDefaultExport;\n }\n\n if (!imported.default.schema) {\n return missingSchema;\n }\n\n if (!imported.default.schema.dbs) {\n return missingDbs;\n }\n\n const dbs = objectEntries(imported.default.schema.dbs).map((db) => db[1]);\n\n const defaultDb = dbs.find((db) => db.name === undefined);\n\n if (!defaultDb) {\n return missingDefaultDb;\n }\n\n if (!defaultDb.collections) {\n return missingCollections;\n }\n\n const collections = objectEntries(defaultDb.collections).map((col) => col[1]);\n\n if (collections.length === 0) {\n return missingCollections;\n }\n\n return toDbSchemaMetadata(defaultDb);\n};\n\ntype SampleConfigOptions =\n | {\n collection: string[];\n print?: boolean;\n }\n | {\n collection: string[];\n generate?: boolean;\n file?: string;\n };\n\nexport const configCommand = new Command('config').description(\n 'Manage Pongo configuration',\n);\n\nconst sampleConfigCommand = configCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const collectionNames =\n options.collection.length > 0 ? options.collection : ['users'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n process.exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(collectionNames)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n process.exit(1);\n }\n\n generateConfigFile(options.file, collectionNames);\n }\n });\n\nsampleConfigCommand.command('generate');\n","import {\n combineMigrations,\n dumbo,\n migrationTableSchemaComponent,\n runPostgreSQLMigrations,\n} from '@event-driven-io/dumbo';\nimport { Command } from 'commander';\nimport { pongoCollectionSchemaComponent } from '../core';\nimport { loadConfigFile } from './configFile';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('-f, --config <path>', 'Path to configuration file with Pongo config')\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action(async (options: MigrateRunOptions) => {\n const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n if (options.config) {\n const config = await loadConfigFile(options.config);\n\n collectionNames = config.collections.map((c) => c.name);\n } else if (collection) {\n collectionNames = collection;\n } else {\n console.error(\n 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n );\n process.exit(1);\n }\n\n const pool = dumbo({ connectionString });\n\n const migrations = collectionNames.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n );\n\n await runPostgreSQLMigrations(pool, migrations, {\n dryRun,\n });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n .option(\n '-col, --collection <name>',\n 'Specify the collection name',\n (value: string, previous: string[]) => {\n // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n const coreMigrations = migrationTableSchemaComponent.migrations({\n connector: 'PostgreSQL:pg',\n });\n const migrations = [\n ...coreMigrations,\n ...collection.flatMap((collectionsName) =>\n pongoCollectionSchemaComponent(collectionsName).migrations({\n connector: 'PostgreSQL:pg', // TODO: Provide connector here\n }),\n ),\n ];\n\n console.log('Printing SQL:');\n console.log(combineMigrations(...migrations));\n });\n"],"mappings":";iDACA,OAAS,WAAAA,MAAe,YCDxB,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAQ,UAQf,IAAMC,EAAkBC,GAA0B,CAChD,GAAIA,EAAM,SAAW,EACnB,OAAOA,EAGT,IAAIC,EAAYD,EAAM,OAAO,CAAC,EAAE,YAAY,EAAIA,EAAM,MAAM,CAAC,EAE7D,OAAIC,EAAU,SAAS,GAAG,IACxBA,EAAYA,EAAU,MAAM,EAAG,EAAE,GAG5BA,CACT,EAEMC,EAAe,CAACC,EAA4B,CAAC,OAAO,IAAM,CAC9D,IAAMC,EAAQD,EACX,IACEE,GACC,QAAQN,EAAeM,CAAI,CAAC,sDAChC,EACC,KAAK;AAAA,CAAI,EAENC,EAAcH,EACjB,IACEE,GACC,SAASA,CAAI,4BAA4BN,EAAeM,CAAI,CAAC,MAAMA,CAAI,KAC3E,EACC,KAAK;AAAA,CAA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,EAEjCH,EAAQ,MAAM,QAAQ,IAAI,EAE1B,IAAOI,EAAQJ","names":["Command","Command","fs","formatTypeName","input","formatted","sampleConfig","collectionNames","types","name","collections","missingDefaultExport","missingSchema","missingDbs","missingDefaultDb","missingCollections","loadConfigFile","configPath","configUrl","imported","parsed","parseDefaultDbSchema","generateConfigFile","fs","error","defaultDb","objectEntries","db","col","toDbSchemaMetadata","configCommand","Command","sampleConfigCommand","value","previous","options","combineMigrations","dumbo","migrationTableSchemaComponent","runPostgreSQLMigrations","Command","migrateCommand","Command","value","previous","options","collection","dryRun","connectionString","collectionNames","loadConfigFile","c","pool","dumbo","migrations","collectionsName","pongoCollectionSchemaComponent","runPostgreSQLMigrations","migrationTableSchemaComponent","combineMigrations","program","Command","configCommand","migrateCommand","cli_default"]}
|
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 _chunkOOCCQKUBcjs = require('./chunk-OOCCQKUB.cjs');exports.OperatorMap = _chunkOOCCQKUBcjs.i; exports.QueryOperators = _chunkOOCCQKUBcjs.h; exports.clientToDbOptions = _chunkOOCCQKUBcjs.v; exports.getPongoDb = _chunkOOCCQKUBcjs.r; exports.hasOperators = _chunkOOCCQKUBcjs.k; exports.isOperator = _chunkOOCCQKUBcjs.j; exports.isPostgresClientOptions = _chunkOOCCQKUBcjs.c; exports.objectEntries = _chunkOOCCQKUBcjs.l; exports.pongoClient = _chunkOOCCQKUBcjs.u; exports.pongoCollection = _chunkOOCCQKUBcjs.f; exports.pongoCollectionPostgreSQLMigrations = _chunkOOCCQKUBcjs.a; exports.pongoCollectionSchemaComponent = _chunkOOCCQKUBcjs.g; exports.pongoDbSchemaComponent = _chunkOOCCQKUBcjs.e; exports.pongoSchema = _chunkOOCCQKUBcjs.m; exports.pongoSession = _chunkOOCCQKUBcjs.t; exports.pongoTransaction = _chunkOOCCQKUBcjs.s; exports.postgresDb = _chunkOOCCQKUBcjs.d; exports.postgresSQLBuilder = _chunkOOCCQKUBcjs.b; exports.proxyClientWithSchema = _chunkOOCCQKUBcjs.o; exports.proxyPongoDbWithSchema = _chunkOOCCQKUBcjs.n; exports.toClientSchemaMetadata = _chunkOOCCQKUBcjs.q; exports.toDbSchemaMetadata = _chunkOOCCQKUBcjs.p;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Dumbo, MigrationStyle, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
|
|
2
|
-
import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredId, c as PongoFilter, d as PongoUpdate, W as WithoutId, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-
|
|
3
|
-
export { Z as $inc, _ as $push, $ as $set, Y as $unset, A as AllowedDbClientOptions, T as AlternativeType, F as CollectionOperationOptions, C as CollectionsMap, U as Condition, D as DBsMap, L as Document, a6 as DocumentHandler, J as EnhancedOmit, H as HasId, I as InferIdType, S as NonObjectIdLikeDocument, N as NotPooledPongoOptions, G as ObjectId, Q as ObjectIdLike, M as OptionalId, E as PongoClient, w as PongoClientOptions, j as PongoClientSchema, r as PongoClientSchemaMetadata, l as PongoClientWithSchema, h as PongoCollectionSchema, o as PongoCollectionSchemaMetadata, z as PongoDbClientOptions, i as PongoDbSchema, q as PongoDbSchemaMetadata, k as PongoDbWithSchema, a5 as PongoDeleteManyResult, a4 as PongoDeleteResult, X as PongoFilterOperator, a1 as PongoInsertManyResult, a0 as PongoInsertOneResult, u as PongoSchemaConfig, a3 as PongoUpdateManyResult, a2 as PongoUpdateResult, v as PooledPongoClientOptions, a7 as PostgresDbClientOptions, R as RegExpOrString, V as RootFilterOperators, K as WithId, y as clientToDbOptions, B as getPongoDb, a8 as isPostgresClientOptions, x as pongoClient, aa as pongoDbSchemaComponent, p as pongoSchema, a9 as postgresDb, n as proxyClientWithSchema, m as proxyPongoDbWithSchema, s as toClientSchemaMetadata, t as toDbSchemaMetadata } from './pongoClient-
|
|
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-BsMs5Zc7.cjs';
|
|
3
|
+
export { Z as $inc, _ as $push, $ as $set, Y as $unset, A as AllowedDbClientOptions, T as AlternativeType, F as CollectionOperationOptions, C as CollectionsMap, U as Condition, D as DBsMap, L as Document, a6 as DocumentHandler, J as EnhancedOmit, H as HasId, I as InferIdType, S as NonObjectIdLikeDocument, N as NotPooledPongoOptions, G as ObjectId, Q as ObjectIdLike, M as OptionalId, E as PongoClient, w as PongoClientOptions, j as PongoClientSchema, r as PongoClientSchemaMetadata, l as PongoClientWithSchema, h as PongoCollectionSchema, o as PongoCollectionSchemaMetadata, z as PongoDbClientOptions, i as PongoDbSchema, q as PongoDbSchemaMetadata, k as PongoDbWithSchema, a5 as PongoDeleteManyResult, a4 as PongoDeleteResult, X as PongoFilterOperator, a1 as PongoInsertManyResult, a0 as PongoInsertOneResult, u as PongoSchemaConfig, a3 as PongoUpdateManyResult, a2 as PongoUpdateResult, v as PooledPongoClientOptions, a7 as PostgresDbClientOptions, R as RegExpOrString, V as RootFilterOperators, K as WithId, y as clientToDbOptions, B as getPongoDb, a8 as isPostgresClientOptions, x as pongoClient, aa as pongoDbSchemaComponent, p as pongoSchema, a9 as postgresDb, n as proxyClientWithSchema, m as proxyPongoDbWithSchema, s as toClientSchemaMetadata, t as toDbSchemaMetadata } from './pongoClient-BsMs5Zc7.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 { Dumbo, MigrationStyle, SchemaComponent, SQLMigration, SQL } from '@event-driven-io/dumbo';
|
|
2
|
-
import { P as PongoDb, a as PongoDocument, b as PongoCollection, O as OptionalUnlessRequiredId, c as PongoFilter, d as PongoUpdate, W as WithoutId, e as PongoTransactionOptions, f as PongoSession, g as PongoDbTransaction } from './pongoClient-
|
|
3
|
-
export { Z as $inc, _ as $push, $ as $set, Y as $unset, A as AllowedDbClientOptions, T as AlternativeType, F as CollectionOperationOptions, C as CollectionsMap, U as Condition, D as DBsMap, L as Document, a6 as DocumentHandler, J as EnhancedOmit, H as HasId, I as InferIdType, S as NonObjectIdLikeDocument, N as NotPooledPongoOptions, G as ObjectId, Q as ObjectIdLike, M as OptionalId, E as PongoClient, w as PongoClientOptions, j as PongoClientSchema, r as PongoClientSchemaMetadata, l as PongoClientWithSchema, h as PongoCollectionSchema, o as PongoCollectionSchemaMetadata, z as PongoDbClientOptions, i as PongoDbSchema, q as PongoDbSchemaMetadata, k as PongoDbWithSchema, a5 as PongoDeleteManyResult, a4 as PongoDeleteResult, X as PongoFilterOperator, a1 as PongoInsertManyResult, a0 as PongoInsertOneResult, u as PongoSchemaConfig, a3 as PongoUpdateManyResult, a2 as PongoUpdateResult, v as PooledPongoClientOptions, a7 as PostgresDbClientOptions, R as RegExpOrString, V as RootFilterOperators, K as WithId, y as clientToDbOptions, B as getPongoDb, a8 as isPostgresClientOptions, x as pongoClient, aa as pongoDbSchemaComponent, p as pongoSchema, a9 as postgresDb, n as proxyClientWithSchema, m as proxyPongoDbWithSchema, s as toClientSchemaMetadata, t as toDbSchemaMetadata } from './pongoClient-
|
|
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-BsMs5Zc7.js';
|
|
3
|
+
export { Z as $inc, _ as $push, $ as $set, Y as $unset, A as AllowedDbClientOptions, T as AlternativeType, F as CollectionOperationOptions, C as CollectionsMap, U as Condition, D as DBsMap, L as Document, a6 as DocumentHandler, J as EnhancedOmit, H as HasId, I as InferIdType, S as NonObjectIdLikeDocument, N as NotPooledPongoOptions, G as ObjectId, Q as ObjectIdLike, M as OptionalId, E as PongoClient, w as PongoClientOptions, j as PongoClientSchema, r as PongoClientSchemaMetadata, l as PongoClientWithSchema, h as PongoCollectionSchema, o as PongoCollectionSchemaMetadata, z as PongoDbClientOptions, i as PongoDbSchema, q as PongoDbSchemaMetadata, k as PongoDbWithSchema, a5 as PongoDeleteManyResult, a4 as PongoDeleteResult, X as PongoFilterOperator, a1 as PongoInsertManyResult, a0 as PongoInsertOneResult, u as PongoSchemaConfig, a3 as PongoUpdateManyResult, a2 as PongoUpdateResult, v as PooledPongoClientOptions, a7 as PostgresDbClientOptions, R as RegExpOrString, V as RootFilterOperators, K as WithId, y as clientToDbOptions, B as getPongoDb, a8 as isPostgresClientOptions, x as pongoClient, aa as pongoDbSchemaComponent, p as pongoSchema, a9 as postgresDb, n as proxyClientWithSchema, m as proxyPongoDbWithSchema, s as toClientSchemaMetadata, t as toDbSchemaMetadata } from './pongoClient-BsMs5Zc7.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,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u}from"./chunk-
|
|
1
|
+
import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g,n as h,o as i,p as j,q as k,r as l,s as n,t as q,u as s,v as u}from"./chunk-MAHDZ7ZR.js";export{a as OperatorMap,x as QueryOperators,u as clientToDbOptions,l as getPongoDb,c as hasOperators,b as isOperator,e as isPostgresClientOptions,d as objectEntries,s as pongoClient,p as pongoCollection,o as pongoCollectionPostgreSQLMigrations,t as pongoCollectionSchemaComponent,m as pongoDbSchemaComponent,g as pongoSchema,q as pongoSession,n as pongoTransaction,f as postgresDb,r as postgresSQLBuilder,i as proxyClientWithSchema,h as proxyPongoDbWithSchema,k as toClientSchemaMetadata,j as toDbSchemaMetadata};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -196,10 +196,10 @@ type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {
|
|
|
196
196
|
[K in keyof T]: PongoCollection<T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument>;
|
|
197
197
|
};
|
|
198
198
|
type PongoDbWithSchema<T extends Record<string, PongoCollectionSchema>, ConnectorType extends string = string> = CollectionsMap<T> & PongoDb<ConnectorType>;
|
|
199
|
-
type DBsMap<T extends Record<string, PongoDbSchema
|
|
200
|
-
[K in keyof T]: CollectionsMap<T[K]['collections']>;
|
|
199
|
+
type DBsMap<T extends Record<string, PongoDbSchema>, ConnectorType extends string = string> = {
|
|
200
|
+
[K in keyof T]: CollectionsMap<T[K]['collections']> & PongoDb<ConnectorType>;
|
|
201
201
|
};
|
|
202
|
-
type PongoClientWithSchema<T extends PongoClientSchema> = DBsMap<T['dbs']> & PongoClient;
|
|
202
|
+
type PongoClientWithSchema<T extends PongoClientSchema, ConnectorType extends string = string> = DBsMap<T['dbs'], ConnectorType> & PongoClient;
|
|
203
203
|
declare function pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(collections: T): PongoDbSchema<T>;
|
|
204
204
|
declare function pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(name: string, collections: T): PongoDbSchema<T>;
|
|
205
205
|
declare const pongoSchema: {
|
|
@@ -196,10 +196,10 @@ type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {
|
|
|
196
196
|
[K in keyof T]: PongoCollection<T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument>;
|
|
197
197
|
};
|
|
198
198
|
type PongoDbWithSchema<T extends Record<string, PongoCollectionSchema>, ConnectorType extends string = string> = CollectionsMap<T> & PongoDb<ConnectorType>;
|
|
199
|
-
type DBsMap<T extends Record<string, PongoDbSchema
|
|
200
|
-
[K in keyof T]: CollectionsMap<T[K]['collections']>;
|
|
199
|
+
type DBsMap<T extends Record<string, PongoDbSchema>, ConnectorType extends string = string> = {
|
|
200
|
+
[K in keyof T]: CollectionsMap<T[K]['collections']> & PongoDb<ConnectorType>;
|
|
201
201
|
};
|
|
202
|
-
type PongoClientWithSchema<T extends PongoClientSchema> = DBsMap<T['dbs']> & PongoClient;
|
|
202
|
+
type PongoClientWithSchema<T extends PongoClientSchema, ConnectorType extends string = string> = DBsMap<T['dbs'], ConnectorType> & PongoClient;
|
|
203
203
|
declare function pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(collections: T): PongoDbSchema<T>;
|
|
204
204
|
declare function pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(name: string, collections: T): PongoDbSchema<T>;
|
|
205
205
|
declare const pongoSchema: {
|
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 _chunkOOCCQKUBcjs = require('./chunk-OOCCQKUB.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=_chunkOOCCQKUBcjs.u.call(void 0, e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return _chunkOOCCQKUBcjs.t.call(void 0, )}async withSession(e,n){let t=typeof e=="function"?e:n,i=_chunkOOCCQKUBcjs.t.call(void 0, );try{return await t(i)}finally{await i.endSession()}}};exports.Collection = d; exports.Db = l; exports.FindCursor = s; exports.MongoClient = u;
|
|
2
2
|
//# sourceMappingURL=shim.cjs.map
|
package/dist/shim.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ClientSessionOptions } from 'http2';
|
|
2
2
|
import { Document, Collection as Collection$1, ObjectId, ClientSession, WithSessionCallback, ReadConcern, ReadPreference, BSONSerializeOptions, WriteConcern, Hint, OptionalUnlessRequiredId, InsertOneOptions, InsertOneResult, BulkWriteOptions, InsertManyResult, AnyBulkWriteOperation, BulkWriteResult, Filter, UpdateFilter, UpdateOptions, UpdateResult, WithoutId, ReplaceOptions, DeleteOptions, DeleteResult, RenameOptions, DropCollectionOptions, WithId, FindOptions, FindCursor as FindCursor$1, OperationOptions, IndexSpecification, CreateIndexesOptions, IndexDescription, CommandOperationOptions, AbstractCursorOptions, ListIndexesCursor, IndexInformationOptions, IndexDescriptionInfo, IndexDescriptionCompact, EstimatedDocumentCountOptions, CountDocumentsOptions, EnhancedOmit, Flatten, FindOneAndDeleteOptions, ModifyResult, FindOneAndReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, AggregationCursor, ChangeStreamDocument, ChangeStreamOptions, ChangeStream, UnorderedBulkOperation, OrderedBulkOperation, CountOptions, ListSearchIndexesOptions, ListSearchIndexesCursor, SearchIndexDescription } from 'mongodb';
|
|
3
|
-
import { P as PongoDb, a6 as DocumentHandler, w as PongoClientOptions, b as PongoCollection } from './pongoClient-
|
|
3
|
+
import { P as PongoDb, a6 as DocumentHandler, w as PongoClientOptions, b as PongoCollection } from './pongoClient-BsMs5Zc7.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, a6 as DocumentHandler, w as PongoClientOptions, b as PongoCollection } from './pongoClient-
|
|
3
|
+
import { P as PongoDb, a6 as DocumentHandler, w as PongoClientOptions, b as PongoCollection } from './pongoClient-BsMs5Zc7.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{t as a,u as p}from"./chunk-
|
|
1
|
+
import{t as a,u as p}from"./chunk-MAHDZ7ZR.js";var s=class{findDocumentsPromise;documents=null;index=0;constructor(e){this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let t of n)e(t);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?e[this.index++]??null:null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}};import"mongodb";var o=r=>r?.session?{session:r.session}:void 0,d=class{collection;constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let t=await this.collection.insertOne(e,o(n));return{acknowledged:t.acknowledged,insertedId:t.insertedId}}async insertMany(e,n){let t=await this.collection.insertMany(e,o(n));return{acknowledged:t.acknowledged,insertedIds:t.insertedIds,insertedCount:t.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,t){let i=await this.collection.updateOne(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,t){return this.collection.replaceOne(e,n,o(t))}async updateMany(e,n,t){let i=await this.collection.updateMany(e,n,o(t));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let t=await this.collection.deleteOne(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async deleteMany(e,n){let t=await this.collection.deleteMany(e,o(n));return{acknowledged:t.acknowledged,deletedCount:t.deletedCount}}async rename(e,n){return await this.collection.rename(e,o(n)),this}drop(e){return this.collection.drop(o(e))}async findOne(e,n){return this.collection.findOne(e,o(n))}find(e,n){return new s(this.collection.find(e,o(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},o(e))}countDocuments(e,n){return this.collection.countDocuments(e,o(n))}distinct(e,n,t){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,o(n))}findOneAndReplace(e,n,t){return this.collection.findOneAndReplace(e,n,o(t))}findOneAndUpdate(e,n,t){return this.collection.findOneAndUpdate(e,n,o(t))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(e??{},o(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n){return this.collection.handle(e.toString(),n)}};var l=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new d(this.pongoDb.collection(e))}};var u=class{pongoClient;constructor(e,n={}){this.pongoClient=p(e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new l(this.pongoClient.db(e))}startSession(e){return a()}async withSession(e,n){let t=typeof e=="function"?e:n,i=a();try{return await t(i)}finally{await i.endSession()}}};export{d as Collection,l as Db,s as FindCursor,u as MongoClient};
|
|
2
2
|
//# sourceMappingURL=shim.js.map
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/typing/entries.ts","../src/core/schema/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts","../src/core/pongoTransaction.ts","../src/core/pongoSession.ts","../src/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/filter/index.ts","../src/postgres/sqlBuilder/update/index.ts"],"sourcesContent":["import {\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n type OptionalUnlessRequiredId,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]): SQL => {\n const values = documents\n .map((doc) => sql('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n\n return sql(\n `UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s`,\n collectionName,\n JSON.stringify(document),\n where(filterQuery),\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s %s',\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I %s LIMIT 1',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v4 as uuid } from 'uuid';\nimport {\n type CollectionOperationOptions,\n type DocumentHandler,\n type OptionalUnlessRequiredId,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithoutId,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nconst transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async (sql: SQL, options?: CollectionOperationOptions) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).command(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n\n const result = await command(\n SqlFor.insertOne({ ...document, _id } as OptionalUnlessRequiredId<T>),\n options,\n );\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (\n documents: OptionalUnlessRequiredId<T>[],\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredId<T>[]),\n options,\n );\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id as string),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateOne(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(\n SqlFor.replaceOne(filter, document),\n options,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteOne(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as T | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = await collection.findOne(byId, options);\n\n const result = await handle(existing);\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredId<T>,\n options,\n );\n return newDoc;\n }\n\n if (existing && !result) {\n await collection.deleteOne(byId, options);\n return null;\n }\n\n if (existing && result)\n await collection.replaceOne(byId, result, options);\n\n return result;\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as T);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredId<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]) => SQL;\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>) => SQL;\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n deleteOne: <T>(filter: PongoFilter<T>) => SQL;\n deleteMany: <T>(filter: PongoFilter<T>) => SQL;\n findOne: <T>(filter: PongoFilter<T>) => SQL;\n find: <T>(filter: PongoFilter<T>) => SQL;\n countDocuments: <T>(filter: PongoFilter<T>) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n type PostgresConnector,\n type PostgresPoolOptions,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n ...(options.schema ? options.schema : {}),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const objectEntries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import {\n type Document,\n type PongoClient,\n type PongoCollection,\n type PongoDb,\n type PongoDocument,\n objectEntries,\n} from '../typing';\n\nexport interface PongoCollectionSchema<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n T extends PongoDocument = PongoDocument,\n> {\n name: string;\n}\n\n// Database schema interface\nexport interface PongoDbSchema<\n T extends Record<string, PongoCollectionSchema> = Record<\n string,\n PongoCollectionSchema\n >,\n> {\n name?: string;\n collections: T;\n}\n\nexport interface PongoClientSchema<\n T extends Record<string, PongoDbSchema> = Record<string, PongoDbSchema>,\n> {\n dbs: T;\n}\n\nexport type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {\n [K in keyof T]: PongoCollection<\n T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument\n >;\n};\n\nexport type PongoDbWithSchema<\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n> = CollectionsMap<T> & PongoDb<ConnectorType>;\n\nexport type DBsMap<T extends Record<string, PongoDbSchema>> = {\n [K in keyof T]: CollectionsMap<T[K]['collections']>;\n};\n\nexport type PongoClientWithSchema<T extends PongoClientSchema> = DBsMap<\n T['dbs']\n> &\n PongoClient;\n\nconst pongoCollectionSchema = <T extends PongoDocument>(\n name: string,\n): PongoCollectionSchema<T> => ({\n name,\n});\n\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n name: string,\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n nameOrCollections: string | T,\n collections?: T | undefined,\n): PongoDbSchema<T> {\n if (collections === undefined) {\n if (typeof nameOrCollections === 'string') {\n throw new Error('You need to provide colleciton definition');\n }\n return {\n collections: nameOrCollections,\n };\n }\n\n return nameOrCollections && typeof nameOrCollections === 'string'\n ? {\n name: nameOrCollections,\n collections,\n }\n : { collections: collections };\n}\n\nconst pongoClientSchema = <T extends Record<string, PongoDbSchema>>(\n dbs: T,\n): PongoClientSchema<T> => ({\n dbs,\n});\n\nexport const pongoSchema = {\n client: pongoClientSchema,\n db: pongoDbSchema,\n collection: pongoCollectionSchema,\n};\n\n// Factory function to create DB instances\nexport const proxyPongoDbWithSchema = <\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n>(\n pongoDb: PongoDb<ConnectorType>,\n dbSchema: PongoDbSchema<T>,\n collections: Map<string, PongoCollection<Document>>,\n): PongoDbWithSchema<T, ConnectorType> => {\n const collectionNames = Object.keys(dbSchema.collections);\n\n for (const collectionName of collectionNames) {\n collections.set(collectionName, pongoDb.collection(collectionName));\n }\n\n return new Proxy(\n pongoDb as PongoDb<ConnectorType> & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n return collections.get(prop) ?? target[prop];\n },\n },\n ) as PongoDbWithSchema<T, ConnectorType>;\n};\n\n// Factory function to create Client instances\nexport const proxyClientWithSchema = <\n TypedClientSchema extends PongoClientSchema,\n>(\n client: PongoClient,\n schema: TypedClientSchema | undefined,\n): PongoClientWithSchema<TypedClientSchema> => {\n if (!schema) return client as PongoClientWithSchema<TypedClientSchema>;\n\n const dbNames = Object.keys(schema.dbs);\n\n return new Proxy(\n client as PongoClient & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n if (dbNames.includes(prop)) return client.db(schema.dbs[prop]?.name);\n\n return target[prop];\n },\n },\n ) as PongoClientWithSchema<TypedClientSchema>;\n};\n\nexport type PongoCollectionSchemaMetadata = {\n name: string;\n};\n\nexport type PongoDbSchemaMetadata = {\n name?: string | undefined;\n collections: PongoCollectionSchemaMetadata[];\n};\n\nexport type PongoClientSchemaMetadata = {\n databases: PongoDbSchemaMetadata[];\n database: (name?: string) => PongoDbSchemaMetadata | undefined;\n};\n\nexport const toDbSchemaMetadata = <TypedDbSchema extends PongoDbSchema>(\n schema: TypedDbSchema,\n): PongoDbSchemaMetadata => ({\n name: schema.name,\n collections: objectEntries(schema.collections).map((c) => ({\n name: c[1].name,\n })),\n});\n\nexport const toClientSchemaMetadata = <\n TypedClientSchema extends PongoClientSchema,\n>(\n schema: TypedClientSchema,\n): PongoClientSchemaMetadata => {\n const databases = objectEntries(schema.dbs).map((e) =>\n toDbSchemaMetadata(e[1]),\n );\n\n return {\n databases,\n database: (name) => databases.find((db) => db.name === name),\n };\n};\n\nexport interface PongoSchemaConfig<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> {\n schema: TypedClientSchema;\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n","import type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n","import { pongoTransaction } from './pongoTransaction';\nimport type {\n PongoDbTransaction,\n PongoSession,\n PongoTransactionOptions,\n} from './typing';\n\nexport type PongoSessionOptions = {\n explicit?: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n};\n\nconst isActive = (\n transaction: PongoDbTransaction | null,\n): transaction is PongoDbTransaction => transaction?.isActive === true;\n\nfunction assertInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is PongoDbTransaction {\n if (!isActive(transaction)) throw new Error('No active transaction exists!');\n}\n\nfunction assertNotInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is null {\n if (isActive(transaction))\n throw new Error('Active transaction already exists!');\n}\n\nexport const pongoSession = (options?: PongoSessionOptions): PongoSession => {\n const explicit = options?.explicit === true;\n const defaultTransactionOptions: PongoTransactionOptions =\n options?.defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n };\n\n let transaction: PongoDbTransaction | null = null;\n let hasEnded = false;\n\n const startTransaction = (options?: PongoTransactionOptions) => {\n assertNotInActiveTransaction(transaction);\n\n transaction = pongoTransaction(options ?? defaultTransactionOptions);\n };\n const commitTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.commit();\n };\n const abortTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.rollback();\n };\n\n const endSession = async (): Promise<void> => {\n if (hasEnded) return;\n hasEnded = true;\n\n if (isActive(transaction)) await transaction.rollback();\n };\n\n const session = {\n get hasEnded() {\n return hasEnded;\n },\n explicit,\n defaultTransactionOptions: defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n },\n get transaction() {\n return transaction;\n },\n get snapshotEnabled() {\n return defaultTransactionOptions.snapshotEnabled;\n },\n endSession,\n incrementTransactionNumber: () => {},\n inTransaction: () => isActive(transaction),\n startTransaction,\n commitTransaction,\n abortTransaction,\n withTransaction: async <T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T> => {\n startTransaction(options);\n\n try {\n const result = await fn(session);\n await commitTransaction();\n return result;\n } catch (error) {\n await abortTransaction();\n throw error;\n }\n },\n };\n\n return session;\n};\n","import { sql } from '@event-driven-io/dumbo';\nimport { objectEntries, OperatorMap } from '../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\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 = objectEntries(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 hasOperators,\n objectEntries,\n QueryOperators,\n type PongoFilter,\n} from '../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return objectEntries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { sql, type SQL } from '@event-driven-io/dumbo';\nimport {\n objectEntries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../core';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n objectEntries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, 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"],"mappings":"AAAA,OACE,UAAAA,GACA,OAAAC,EACA,gBAAAC,OAGK,yBCNP,OACE,2BAAAC,GACA,mBAAAC,EACA,UAAAC,OASK,yBACP,OAAS,MAAMC,MAAY,OCb3B,OACE,SAAAC,EACA,4BAAAC,EACA,6BAAAC,EACA,2BAAAC,GACA,mBAAAC,MAIK,yBAeA,IAAMC,EACXC,GAEAA,EAAQ,gBAAkBC,EAE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BAA0BD,EAAgBe,EAAMJ,CAAW,CAAC,CACzE,EACA,eAAoBF,GAAgC,CAClD,IAAME,EAAcC,EAAqBH,CAAM,EAC/C,OAAOR,EACL,sCACAD,EACAe,EAAMJ,CAAW,CACnB,CACF,EACA,OAASK,GACPf,EAAI,8BAA+BD,EAAgBgB,CAAO,EAC5D,KAAM,CAACC,EAAqBjB,IAC1BC,EAAI,0BAA2BgB,CAAU,CAC7C,GAEMF,EAASN,GACbA,EAAO,OAAS,EAAIR,EAAI,WAAYQ,CAAM,EAAIS,GAAO,EAAE","names":["rawSql","sql","sqlMigration","runPostgreSQLMigrations","schemaComponent","single","uuid","dumbo","getDatabaseNameOrDefault","NodePostgresConnectorType","runPostgreSQLMigrations","schemaComponent","isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","db","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","db","options","transaction","transactionExecutorOrDefault","defaultSqlExecutor","pongoCollection","collectionName","pool","SqlFor","schema","sqlExecutor","command","sql","query","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","handle","byId","existing","newDoc","row","count","single","newName","schemaComponent","runPostgreSQLMigrations","pongoCollectionSchemaComponent","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","objectEntries","obj","key","value","pongoCollectionSchema","name","pongoDbSchema","nameOrCollections","collections","pongoClientSchema","dbs","pongoSchema","proxyPongoDbWithSchema","pongoDb","dbSchema","collectionNames","collectionName","target","prop","proxyClientWithSchema","client","schema","dbNames","toDbSchemaMetadata","objectEntries","c","toClientSchemaMetadata","databases","db","NodePostgresConnectorType","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","proxyClientWithSchema","NodePostgresConnectorType","sql","handleOperator","path","operator","value","handleIdOperator","sql","buildNestedObject","OperatorMap","v","subQuery","objectEntries","subKey","subValue","acc","key","AND","constructFilterQuery","filter","key","value","isRecord","constructComplexFilterQuery","handleOperator","isEquality","hasOperators","objectEntries","nestedKey","val","QueryOperators","sql","buildUpdateQuery","update","objectEntries","currentUpdateQuery","op","value","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","sql","set","unset","k","inc","key","push","createCollection","collectionName","sql","pongoCollectionPostgreSQLMigrations","sqlMigration","postgresSQLBuilder","document","documents","values","doc","filter","update","filterQuery","constructFilterQuery","updateQuery","buildUpdateQuery","where","newName","targetName","rawSql"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/typing/entries.ts","../src/core/schema/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts"],"names":["isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","db","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","transaction","transactionExecutorOrDefault","defaultSqlExecutor","SqlFor","schema","sqlExecutor","command","sql","query","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","byId","existing","newDoc","row","count","single","newName","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","obj","pongoCollectionSchema","name","pongoDbSchema","nameOrCollections","pongoClientSchema","dbs","pongoSchema","pongoDb","collectionNames","target","prop","proxyClientWithSchema","client","dbNames","toDbSchemaMetadata","toClientSchemaMetadata","databases","getPongoDb","type"],"mappings":"AAAA,g3CAMO,4BCOoB,ICWdA,CAAAA,CACXC,CAAAA,EAEAA,CAAAA,CAAQ,aAAA,GAAkBC,gCAAAA,CAEfC,CAAAA,aACXF,CAAAA,EAC+B,CAC/B,GAAM,CAAE,gBAAA,CAAAG,CAAAA,CAAkB,MAAA,CAAAC,CAAO,CAAA,CAAIJ,CAAAA,CAC/BK,CAAAA,kBAAeD,CAAAA,SAAUE,6CAAAA,CAAyC,GAAA,CAElEC,CAAAA,CAAOC,0BAAAA,CACX,gBAAA,CAAAL,CAAAA,CACA,GAAGH,CAAAA,CAAQ,iBACb,CAAC,CAAA,CAEKS,CAAAA,CAAc,IAAI,GAAA,CAElBC,CAAAA,CAAiC,CACrC,aAAA,CAAeV,CAAAA,CAAQ,aAAA,CACvB,YAAA,CAAAK,CAAAA,CACA,OAAA,CAAS,CAAA,CAAA,EAAM,OAAA,CAAQ,OAAA,CAAQ,CAAA,CAC/B,KAAA,CAAO,CAAA,CAAA,EAAME,CAAAA,CAAK,KAAA,CAAM,CAAA,CACxB,UAAA,CAAaI,CAAAA,EACXC,CAAAA,CAAgB,CACd,cAAA,CAAAD,CAAAA,CACA,EAAA,CAAAD,CAAAA,CACA,IAAA,CAAAH,CAAAA,CACA,UAAA,CAAYM,CAAAA,CAAmBF,CAAc,CAAA,CAC7C,GAAIX,CAAAA,CAAQ,MAAA,CAASA,CAAAA,CAAQ,MAAA,CAAS,CAAC,CACzC,CAAC,CAAA,CACH,WAAA,CAAa,CAAA,CAAA,EAAMO,CAAAA,CAAK,WAAA,CAAY,CAAA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BAAGjD,CAAAA,uBAAO,GAAA,uBAAI+C,CAAI,CAAA,+BAAG,MAAI,CAAA,CAE5DD,CAAAA,CAAOC,CAAI,CACpB,CACF,CACF,CACF,CAAA,CAgBaI,EAAAA,aACXnD,CAAAA,EAAAA,CAC2B,CAC3B,IAAA,CAAMA,CAAAA,CAAO,IAAA,CACb,WAAA,CAAaX,CAAAA,CAAcW,CAAAA,CAAO,WAAW,CAAA,CAAE,GAAA,CAAKf,CAAAA,EAAAA,CAAO,CACzD,IAAA,CAAMA,CAAAA,CAAE,CAAC,CAAA,CAAE,IACb,CAAA,CAAE,CACJ,CAAA,CAAA,CAEamE,EAAAA,aAGXpD,CAAAA,EAC8B,CAC9B,IAAMqD,CAAAA,CAAYhE,CAAAA,CAAcW,CAAAA,CAAO,GAAG,CAAA,CAAE,GAAA,CAAK,CAAA,EAC/CmD,EAAAA,CAAmB,CAAA,CAAE,CAAC,CAAC,CACzB,CAAA,CAEA,MAAO,CACL,SAAA,CAAAE,CAAAA,CACA,QAAA,CAAWf,CAAAA,EAASe,CAAAA,CAAU,IAAA,CAAM1E,CAAAA,EAAOA,CAAAA,CAAG,IAAA,GAAS2D,CAAI,CAC7D,CACF,CAAA,CC3LA,cAKe,ICWFgB,CAAAA,CAGXrF,CAAAA,EACY,CACZ,GAAM,CAAE,aAAA,CAAesF,CAAK,CAAA,CAAItF,CAAAA,CAEhC,EAAA,CAAI,CAACD,CAAAA,CAAwBC,CAAO,CAAA,CAClC,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBsF,CAAI,CAAA,CAAA;APL5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CE,GAAA;AAAA;AAAA;AAmEmD,6DAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-YQPKY7LN.cjs","sourcesContent":["import {\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n type OptionalUnlessRequiredId,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]): SQL => {\n const values = documents\n .map((doc) => sql('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n\n return sql(\n `UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') %s`,\n collectionName,\n JSON.stringify(document),\n where(filterQuery),\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s %s',\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I %s LIMIT 1',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v4 as uuid } from 'uuid';\nimport {\n type CollectionOperationOptions,\n type DocumentHandler,\n type OptionalUnlessRequiredId,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithoutId,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nconst transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async (sql: SQL, options?: CollectionOperationOptions) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).command(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n\n const result = await command(\n SqlFor.insertOne({ ...document, _id } as OptionalUnlessRequiredId<T>),\n options,\n );\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (\n documents: OptionalUnlessRequiredId<T>[],\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredId<T>[]),\n options,\n );\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id as string),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateOne(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(\n SqlFor.replaceOne(filter, document),\n options,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteOne(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as T | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = await collection.findOne(byId, options);\n\n const result = await handle(existing);\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredId<T>,\n options,\n );\n return newDoc;\n }\n\n if (existing && !result) {\n await collection.deleteOne(byId, options);\n return null;\n }\n\n if (existing && result)\n await collection.replaceOne(byId, result, options);\n\n return result;\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as T);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredId<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredId<T>[]) => SQL;\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>) => SQL;\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n deleteOne: <T>(filter: PongoFilter<T>) => SQL;\n deleteMany: <T>(filter: PongoFilter<T>) => SQL;\n findOne: <T>(filter: PongoFilter<T>) => SQL;\n find: <T>(filter: PongoFilter<T>) => SQL;\n countDocuments: <T>(filter: PongoFilter<T>) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n type PostgresConnector,\n type PostgresPoolOptions,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n ...(options.schema ? options.schema : {}),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const objectEntries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import {\n type Document,\n type PongoClient,\n type PongoCollection,\n type PongoDb,\n type PongoDocument,\n objectEntries,\n} from '../typing';\n\nexport interface PongoCollectionSchema<\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n T extends PongoDocument = PongoDocument,\n> {\n name: string;\n}\n\n// Database schema interface\nexport interface PongoDbSchema<\n T extends Record<string, PongoCollectionSchema> = Record<\n string,\n PongoCollectionSchema\n >,\n> {\n name?: string;\n collections: T;\n}\n\nexport interface PongoClientSchema<\n T extends Record<string, PongoDbSchema> = Record<string, PongoDbSchema>,\n> {\n dbs: T;\n}\n\nexport type CollectionsMap<T extends Record<string, PongoCollectionSchema>> = {\n [K in keyof T]: PongoCollection<\n T[K] extends PongoCollectionSchema<infer U> ? U : PongoDocument\n >;\n};\n\nexport type PongoDbWithSchema<\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n> = CollectionsMap<T> & PongoDb<ConnectorType>;\n\nexport type DBsMap<T extends Record<string, PongoDbSchema>> = {\n [K in keyof T]: CollectionsMap<T[K]['collections']>;\n};\n\nexport type PongoClientWithSchema<T extends PongoClientSchema> = DBsMap<\n T['dbs']\n> &\n PongoClient;\n\nconst pongoCollectionSchema = <T extends PongoDocument>(\n name: string,\n): PongoCollectionSchema<T> => ({\n name,\n});\n\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n name: string,\n collections: T,\n): PongoDbSchema<T>;\nfunction pongoDbSchema<T extends Record<string, PongoCollectionSchema>>(\n nameOrCollections: string | T,\n collections?: T | undefined,\n): PongoDbSchema<T> {\n if (collections === undefined) {\n if (typeof nameOrCollections === 'string') {\n throw new Error('You need to provide colleciton definition');\n }\n return {\n collections: nameOrCollections,\n };\n }\n\n return nameOrCollections && typeof nameOrCollections === 'string'\n ? {\n name: nameOrCollections,\n collections,\n }\n : { collections: collections };\n}\n\nconst pongoClientSchema = <T extends Record<string, PongoDbSchema>>(\n dbs: T,\n): PongoClientSchema<T> => ({\n dbs,\n});\n\nexport const pongoSchema = {\n client: pongoClientSchema,\n db: pongoDbSchema,\n collection: pongoCollectionSchema,\n};\n\n// Factory function to create DB instances\nexport const proxyPongoDbWithSchema = <\n T extends Record<string, PongoCollectionSchema>,\n ConnectorType extends string = string,\n>(\n pongoDb: PongoDb<ConnectorType>,\n dbSchema: PongoDbSchema<T>,\n collections: Map<string, PongoCollection<Document>>,\n): PongoDbWithSchema<T, ConnectorType> => {\n const collectionNames = Object.keys(dbSchema.collections);\n\n for (const collectionName of collectionNames) {\n collections.set(collectionName, pongoDb.collection(collectionName));\n }\n\n return new Proxy(\n pongoDb as PongoDb<ConnectorType> & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n return collections.get(prop) ?? target[prop];\n },\n },\n ) as PongoDbWithSchema<T, ConnectorType>;\n};\n\n// Factory function to create Client instances\nexport const proxyClientWithSchema = <\n TypedClientSchema extends PongoClientSchema,\n>(\n client: PongoClient,\n schema: TypedClientSchema | undefined,\n): PongoClientWithSchema<TypedClientSchema> => {\n if (!schema) return client as PongoClientWithSchema<TypedClientSchema>;\n\n const dbNames = Object.keys(schema.dbs);\n\n return new Proxy(\n client as PongoClient & {\n [key: string]: unknown;\n },\n {\n get(target, prop: string) {\n if (dbNames.includes(prop)) return client.db(schema.dbs[prop]?.name);\n\n return target[prop];\n },\n },\n ) as PongoClientWithSchema<TypedClientSchema>;\n};\n\nexport type PongoCollectionSchemaMetadata = {\n name: string;\n};\n\nexport type PongoDbSchemaMetadata = {\n name?: string | undefined;\n collections: PongoCollectionSchemaMetadata[];\n};\n\nexport type PongoClientSchemaMetadata = {\n databases: PongoDbSchemaMetadata[];\n database: (name?: string) => PongoDbSchemaMetadata | undefined;\n};\n\nexport const toDbSchemaMetadata = <TypedDbSchema extends PongoDbSchema>(\n schema: TypedDbSchema,\n): PongoDbSchemaMetadata => ({\n name: schema.name,\n collections: objectEntries(schema.collections).map((c) => ({\n name: c[1].name,\n })),\n});\n\nexport const toClientSchemaMetadata = <\n TypedClientSchema extends PongoClientSchema,\n>(\n schema: TypedClientSchema,\n): PongoClientSchemaMetadata => {\n const databases = objectEntries(schema.dbs).map((e) =>\n toDbSchemaMetadata(e[1]),\n );\n\n return {\n databases,\n database: (name) => databases.find((db) => db.name === name),\n };\n};\n\nexport interface PongoSchemaConfig<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> {\n schema: TypedClientSchema;\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n"]}
|