@event-driven-io/pongo 0.0.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -2
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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(); } } 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 _class;var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var _uuid = require('uuid');var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var d=async(n,e,...t)=>{let o=await n.connect();try{let i=_pgformat2.default.call(void 0, e,...t);return await o.query(i)}finally{o.release()}},S= exports.execute =async(n,e)=>{let t=await n.connect();try{return await e(t)}finally{t.release()}};var l=n=>Object.entries(n).map(([t,o])=>typeof o=="object"&&!Array.isArray(o)?R(t,o):h(t,o)).join(" AND "),h=(n,e)=>w(e)?_pgformat2.default.call(void 0, "(data->>'%I')::text = %L::text",n,e):O(e)?_pgformat2.default.call(void 0, "(data->>'%I')::timestamp = %L::timestamp",n,e):T(e)?_pgformat2.default.call(void 0, "(data->>'%I')::numeric = %L",n,e):_pgformat2.default.call(void 0, "(data->>'%I') = %L",n,e),R= exports.constructComplexFilterQuery =(n,e)=>Object.entries(e).map(([o,i])=>{switch(o){case"$eq":return h(n,i);case"$gt":return m(n,i,">");case"$gte":return m(n,i,">=");case"$lt":return m(n,i,"<");case"$lte":return m(n,i,"<=");case"$ne":return h(n,i).replace("=","!=");case"$in":return _pgformat2.default.call(void 0, "(data->>'%I') IN (%s)",n,i.map(s=>C(n,s)).join(", "));case"$nin":return _pgformat2.default.call(void 0, "(data->>'%I') NOT IN (%s)",n,i.map(s=>C(n,s)).join(", "));default:throw new Error(`Unsupported operator: ${o}`)}}).join(" AND "),m=(n,e,t)=>w(e)?_pgformat2.default.call(void 0, `(data->>'%I')::text ${t} %L::text`,n,e):O(e)?_pgformat2.default.call(void 0, `(data->>'%I')::timestamp ${t} %L::timestamp`,n,e):T(e)?_pgformat2.default.call(void 0, `(data->>'%I')::numeric ${t} %s`,n,e):_pgformat2.default.call(void 0, `(data->>'%I') ${t} %L`,n,e),C=(n,e)=>w(e)?_pgformat2.default.call(void 0, "%L::text",e):O(e)?_pgformat2.default.call(void 0, "%L::timestamp",e):T(e)?_pgformat2.default.call(void 0, "%L",e):_pgformat2.default.call(void 0, "%L",e),w=n=>typeof n=="string"&&/^[0-9a-fA-F-]{36}$/.test(n),O=n=>typeof n=="string"&&!isNaN(Date.parse(n)),T=n=>typeof n=="number";var p=new Map,y= exports.getPool =n=>{let e=typeof n=="string"?n:n.connectionString,t=typeof n=="string"?{connectionString:e}:n;return _nullishCoalesce(p.get(e), () => (p.set(e,new _pg2.default.Pool(t)).get(e)))},I= exports.endPool =async n=>{let e=p.get(n);e&&(await e.end(),p.delete(n))},j= exports.endAllPools =()=>Promise.all([...p.keys()].map(n=>I(n)));var D=n=>{let e="data";if("$set"in n){let t=n.$set;e=_pgformat2.default.call(void 0, "jsonb_set(%s, %L, data || %L)",e,"{}",JSON.stringify(t))}if("$unset"in n){let t=Object.keys(n.$unset);e=_pgformat2.default.call(void 0, "%s - %L",e,t.join(", "))}if("$inc"in n){let t=n.$inc;for(let[o,i]of Object.entries(t))e=_pgformat2.default.call(void 0, "jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))",e,o,o,i)}if("$push"in n){let t=n.$push;for(let[o,i]of Object.entries(t))e=_pgformat2.default.call(void 0, "jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || to_jsonb(%L)))",e,o,o,i)}return e};var F=(n,e)=>{let t=y({connectionString:n,database:e});return{connect:()=>Promise.resolve(),close:()=>I(n),collection:o=>A(o,t)}},A= exports.postgresCollection =(n,e)=>{let t=d(e,"CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)",n);return{createCollection:async()=>{await t},insertOne:async o=>{await t;let i=_uuid.v4.call(void 0, );return(await d(e,"INSERT INTO %I (_id, data) VALUES (%L, %L)",n,i,JSON.stringify({...o,_id:i}))).rowCount?{insertedId:i,acknowledged:!0}:{insertedId:null,acknowledged:!1}},updateOne:async(o,i)=>{await t;let s=l(o),g=D(i),x=await d(e,"UPDATE %I SET data = %s WHERE %s",n,g,s);return x.rowCount?{acknowledged:!0,modifiedCount:x.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async o=>{await t;let i=l(o),s=await d(e,"DELETE FROM %I WHERE %s",n,i);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async o=>{await t;let i=l(o);returnawait _asyncNullishCoalesce(await _asyncOptionalChain([(await d(e,"SELECT data FROM %I WHERE %s LIMIT 1",n,i)), 'access', async _2 => _2.rows, 'access', async _3 => _3[0], 'optionalAccess', async _4 => _4.data]), async () => (null))},find:async o=>{await t;let i=l(o);return(await d(e,"SELECT data FROM %I WHERE %s",n,i)).rows.map(g=>g.data)}}};var P=(n,e)=>F(n,e);var E=n=>{let e=P(n),t={connect:async()=>(await e.connect(),t),close:()=>e.close(),db:o=>o?P(n,o):e};return t};var u= (_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 t=await this.findDocuments();for(let o of t)e(o);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?_nullishCoalesce(e[this.index++], () => (null)):null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}}, _class);require('mongodb');var c=class{constructor(e){this.collection=e}get dbName(){throw new Error("Method not implemented.")}get collectionName(){throw new Error("Method not implemented.")}get namespace(){throw new Error("Method not implemented.")}get readConcern(){throw new Error("Method not implemented.")}get readPreference(){throw new Error("Method not implemented.")}get bsonOptions(){throw new Error("Method not implemented.")}get writeConcern(){throw new Error("Method not implemented.")}get hint(){throw new Error("Method not implemented.")}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,t){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}insertMany(e,t){throw new Error("Method not implemented.")}bulkWrite(e,t){throw new Error("Method not implemented.")}async updateOne(e,t,o){let i=await this.collection.updateOne(e,t);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,t,o){throw new Error("Method not implemented.")}updateMany(e,t,o){throw new Error("Method not implemented.")}async deleteOne(e,t){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}deleteMany(e,t){throw new Error("Method not implemented.")}rename(e,t){throw new Error("Method not implemented.")}drop(e){throw new Error("Method not implemented.")}async findOne(e,t){return this.collection.findOne(e)}find(e,t){return new u(this.collection.find(e))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,t){throw new Error("Method not implemented.")}createIndexes(e,t){throw new Error("Method not implemented.")}dropIndex(e,t){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,t){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){throw new Error("Method not implemented.")}countDocuments(e,t){throw new Error("Method not implemented.")}distinct(e,t,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,t){throw new Error("Method not implemented.")}findOneAndReplace(e,t,o){throw new Error("Method not implemented.")}findOneAndUpdate(e,t,o){throw new Error("Method not implemented.")}aggregate(e,t){throw new Error("Method not implemented.")}watch(e,t){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,t){throw new Error("Method not implemented.")}listSearchIndexes(e,t){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,t){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}};var f=class{constructor(e){this.pongoDb=e}collection(e){return new c(this.pongoDb.collection(e))}};var M=class{constructor(e){this.pongoClient=E(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new f(this.pongoClient.db(e))}};exports.Collection = c; exports.Db = f; exports.FindCursor = u; exports.MongoClient = M; exports.constructComplexFilterQuery = R; exports.constructFilterQuery = l; exports.constructUpdateQuery = D; exports.endAllPools = j; exports.endPool = I; exports.execute = S; exports.getDbClient = P; exports.getPool = y; exports.pongoClient = E; exports.postgresClient = F; exports.postgresCollection = A; exports.sql = d;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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(); } } 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 _class;var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var _uuid = require('uuid');var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var d=async(t,e,...n)=>{let o=await t.connect();try{let i=_pgformat2.default.call(void 0, e,...n);return await o.query(i)}finally{o.release()}},W= exports.execute =async(t,e)=>{let n=await t.connect();try{return await e(n)}finally{n.release()}};var P={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},R={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},E=t=>t.startsWith("$"),I=t=>Object.keys(t).some(E),a=(t,e,n)=>{switch(e){case"$eq":return _pgformat2.default.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(T(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `data #>> %L ${R[e]} %L`,`{${t.split(".").join(",")}}`,n);case"$in":return _pgformat2.default.call(void 0, "data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>_pgformat2.default.call(void 0, "%L",o)).join(", "));case"$nin":return _pgformat2.default.call(void 0, "data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>_pgformat2.default.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=Object.entries(n).map(([i,s])=>_pgformat2.default.call(void 0, '@."%s" == %s',i,JSON.stringify(s))).join(" && ");return _pgformat2.default.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return _pgformat2.default.call(void 0, "data @> %L::jsonb",JSON.stringify(T(t,n)));case"$size":return _pgformat2.default.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${e}`)}},T=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var x="AND",l= exports.constructFilterQuery =t=>Object.entries(t).map(([e,n])=>b(n)?k(e,n):a(e,"$eq",n)).join(` ${x} `),k=(t,e)=>{let n=!I(e);return Object.entries(e).map(([o,i])=>n?a(`${t}.${o}`,P.$eq,i):a(t,o,i)).join(` ${x} `)},b=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);var p=new Map,C= exports.getPool =t=>{let e=typeof t=="string"?t:t.connectionString,n=typeof t=="string"?{connectionString:e}:t;return _nullishCoalesce(p.get(e), () => (p.set(e,new _pg2.default.Pool(n)).get(e)))},h= exports.endPool =async t=>{let e=p.get(t);e&&(await e.end(),p.delete(t))},v= exports.endAllPools =()=>Promise.all([...p.keys()].map(t=>h(t)));var y=t=>{let e="data";if("$set"in t){let n=t.$set;e=_pgformat2.default.call(void 0, "jsonb_set(%s, %L, data || %L)",e,"{}",JSON.stringify(n))}if("$unset"in t){let n=Object.keys(t.$unset);e=_pgformat2.default.call(void 0, "%s - %L",e,n.join(", "))}if("$inc"in t){let n=t.$inc;for(let[o,i]of Object.entries(n))e=_pgformat2.default.call(void 0, "jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))",e,o,o,i)}if("$push"in t){let n=t.$push;for(let[o,i]of Object.entries(n))e=_pgformat2.default.call(void 0, "jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || to_jsonb(%L)))",e,o,o,i)}return e};var D=(t,e)=>{let n=C({connectionString:t,database:e});return{connect:()=>Promise.resolve(),close:()=>h(t),collection:o=>S(o,n)}},S= exports.postgresCollection =(t,e)=>{let n=d(e,"CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)",t);return{createCollection:async()=>{await n},insertOne:async o=>{await n;let i=_uuid.v4.call(void 0, );return(await d(e,"INSERT INTO %I (_id, data) VALUES (%L, %L)",t,i,JSON.stringify({...o,_id:i}))).rowCount?{insertedId:i,acknowledged:!0}:{insertedId:null,acknowledged:!1}},updateOne:async(o,i)=>{await n;let s=l(o),g=y(i),O=await d(e,"UPDATE %I SET data = %s WHERE %s",t,g,s);return O.rowCount?{acknowledged:!0,modifiedCount:O.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async o=>{await n;let i=l(o),s=await d(e,"DELETE FROM %I WHERE %s",t,i);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async o=>{await n;let i=l(o);returnawait _asyncNullishCoalesce(await _asyncOptionalChain([(await d(e,"SELECT data FROM %I WHERE %s LIMIT 1",t,i)), 'access', async _2 => _2.rows, 'access', async _3 => _3[0], 'optionalAccess', async _4 => _4.data]), async () => (null))},find:async o=>{await n;let i=l(o);return(await d(e,"SELECT data FROM %I WHERE %s",t,i)).rows.map(g=>g.data)}}};var w=(t,e)=>D(t,e);var F=t=>{let e=w(t),n={connect:async()=>(await e.connect(),n),close:()=>e.close(),db:o=>o?w(t,o):e};return n};var c= (_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 o of n)e(o);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?_nullishCoalesce(e[this.index++], () => (null)):null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}}, _class);require('mongodb');var u=class{constructor(e){this.collection=e}get dbName(){throw new Error("Method not implemented.")}get collectionName(){throw new Error("Method not implemented.")}get namespace(){throw new Error("Method not implemented.")}get readConcern(){throw new Error("Method not implemented.")}get readPreference(){throw new Error("Method not implemented.")}get bsonOptions(){throw new Error("Method not implemented.")}get writeConcern(){throw new Error("Method not implemented.")}get hint(){throw new Error("Method not implemented.")}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}insertMany(e,n){throw new Error("Method not implemented.")}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){throw new Error("Method not implemented.")}updateMany(e,n,o){throw new Error("Method not implemented.")}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}deleteMany(e,n){throw new Error("Method not implemented.")}rename(e,n){throw new Error("Method not implemented.")}drop(e){throw new Error("Method not implemented.")}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new c(this.collection.find(e))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){throw new Error("Method not implemented.")}countDocuments(e,n){throw new Error("Method not implemented.")}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){throw new Error("Method not implemented.")}findOneAndReplace(e,n,o){throw new Error("Method not implemented.")}findOneAndUpdate(e,n,o){throw new Error("Method not implemented.")}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){throw new Error("Method not implemented.")}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}};var f=class{constructor(e){this.pongoDb=e}collection(e){return new u(this.pongoDb.collection(e))}};var _=class{constructor(e){this.pongoClient=F(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new f(this.pongoClient.db(e))}};exports.Collection = u; exports.Db = f; exports.FindCursor = c; exports.MongoClient = _; exports.constructFilterQuery = l; exports.constructUpdateQuery = y; exports.endAllPools = v; exports.endPool = h; exports.execute = W; exports.getDbClient = w; exports.getPool = C; exports.pongoClient = F; exports.postgresClient = D; exports.postgresCollection = S; exports.sql = d;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/postgres/client.ts","../src/postgres/execute/index.ts","../src/postgres/filter/index.ts","../src/postgres/pool.ts","../src/postgres/update/index.ts","../src/main/dbClient.ts","../src/main/client.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"names":["uuid","format","sql","pool","sqlText","params","client","query","execute","handle","constructFilterQuery","filter","key","value","constructComplexFilterQuery","constructSimpleFilterQuery","isUUID","isDate","isNumber","operator","val","constructComparisonFilterQuery","v","constructSimpleFilterQueryValue","pg","pools","getPool","connectionStringOrOptions","connectionString","poolOptions","endPool","endAllPools","constructUpdateQuery","update","updateQuery","setUpdate","unsetUpdate","incUpdate","pushUpdate","postgresClient","database","name","postgresCollection","collectionName","createCollection","document","id","filterQuery","result","row","getDbClient","pongoClient","dbClient","dbName","FindCursor","documents","callback","docs","doc","Collection","collection","_options","_docs","_operations","_filter","_","_update","_newName","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_replacement","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","MongoClient"],"mappings":"AAAA,MAAe,KACf,OAAS,MAAMA,MAAY,OCA3B,OAAOC,MAAY,YAEZ,IAAMC,EAAM,MACjBC,EACAC,KACGC,IACiC,CACpC,IAAMC,EAAS,MAAMH,EAAK,QAAQ,EAClC,GAAI,CACF,IAAMI,EAAQN,EAAOG,EAAS,GAAGC,CAAM,EACvC,OAAO,MAAMC,EAAO,MAAcC,CAAK,CACzC,QAAE,CACAD,EAAO,QAAQ,CACjB,CACF,EAEaE,EAAU,MACrBL,EACAM,IACG,CACH,IAAMH,EAAS,MAAMH,EAAK,QAAQ,EAClC,GAAI,CACF,OAAO,MAAMM,EAAOH,CAAM,CAC5B,QAAE,CACAA,EAAO,QAAQ,CACjB,CACF,EC1BA,OAAOL,MAAY,YAGZ,IAAMS,EAA2BC,GACtB,OAAO,QAAQA,CAAM,EAAE,IAAI,CAAC,CAACC,EAAKC,CAAK,IACjD,OAAOA,GAAU,UAAY,CAAC,MAAM,QAAQA,CAAK,EAC5CC,EAA4BF,EAAKC,CAAgC,EAEjEE,EAA2BH,EAAKC,CAAK,CAE/C,EACc,KAAK,OAAO,EAGvBE,EAA6B,CAACH,EAAaC,IAC3CG,EAAOH,CAAK,EACPZ,EAAO,iCAAkCW,EAAKC,CAAK,EACjDI,EAAOJ,CAAK,EACdZ,EAAO,2CAA4CW,EAAKC,CAAK,EAC3DK,EAASL,CAAK,EAChBZ,EAAO,8BAA+BW,EAAKC,CAAK,EAEhDZ,EAAO,qBAAsBW,EAAKC,CAAK,EAIrCC,EAA8B,CACzCF,EACAC,IAEmB,OA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,OAAO,IAAIgB,EAAc,KAAK,QAAQ,WAAchB,CAAc,CAAC,CACrE,CACF,EENO,IAAMsC,EAAN,KAAkB,CACf,YAER,YAAYrD,EAA0B,CACpC,KAAK,YAAcuB,EAAYvB,CAAgB,CACjD,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGyB,EAAoB,CACrB,OAAO,IAAI0B,EAAG,KAAK,YAAY,GAAG1B,CAAM,CAAC,CAC3C,CACF","sourcesContent":["import pg from 'pg';\nimport { v4 as uuid } from 'uuid';\nimport {\n type DbClient,\n type PongoCollection,\n type PongoDeleteResult,\n type PongoFilter,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n} from '../main';\nimport { sql } from './execute';\nimport { constructFilterQuery } from './filter';\nimport { endPool, getPool } from './pool';\nimport { constructUpdateQuery } from './update';\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => Promise.resolve(),\n close: () => endPool(connectionString),\n collection: <T>(name: string) => postgresCollection<T>(name, pool),\n };\n};\n\nexport const postgresCollection = <T>(\n collectionName: string,\n pool: pg.Pool,\n): PongoCollection<T> => {\n const createCollection = sql(\n pool,\n 'CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)',\n collectionName,\n );\n return {\n createCollection: async () => {\n await createCollection;\n },\n insertOne: async (document: T): Promise<PongoInsertOneResult> => {\n await createCollection;\n\n const id = uuid();\n\n const result = await sql(\n pool,\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n id,\n JSON.stringify({ ...document, _id: id }),\n );\n\n return result.rowCount\n ? { insertedId: id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = constructUpdateQuery(update);\n\n const result = await sql(\n pool,\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'DELETE FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n return (result.rows[0]?.data ?? null) as T | null;\n },\n find: async (filter: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'SELECT data FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n\n return result.rows.map((row) => row.data as T);\n },\n };\n};\n","import type pg from 'pg';\nimport format from 'pg-format';\n\nexport const sql = async <Result extends pg.QueryResultRow = pg.QueryResultRow>(\n pool: pg.Pool,\n sqlText: string,\n ...params: unknown[]\n): Promise<pg.QueryResult<Result>> => {\n const client = await pool.connect();\n try {\n const query = format(sqlText, ...params);\n return await client.query<Result>(query);\n } finally {\n client.release();\n }\n};\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n","// src/utils.ts\nimport format from 'pg-format';\nimport type { PongoFilter } from '../../main';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string => {\n const filters = Object.entries(filter).map(([key, value]) => {\n if (typeof value === 'object' && !Array.isArray(value)) {\n return constructComplexFilterQuery(key, value as Record<string, unknown>);\n } else {\n return constructSimpleFilterQuery(key, value);\n }\n });\n return filters.join(' AND ');\n};\n\nconst constructSimpleFilterQuery = (key: string, value: unknown): string => {\n if (isUUID(value)) {\n return format(`(data->>'%I')::text = %L::text`, key, value);\n } else if (isDate(value)) {\n return format(`(data->>'%I')::timestamp = %L::timestamp`, key, value);\n } else if (isNumber(value)) {\n return format(`(data->>'%I')::numeric = %L`, key, value);\n } else {\n return format(`(data->>'%I') = %L`, key, value);\n }\n};\n\nexport const constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const subFilters = Object.entries(value).map(([operator, val]) => {\n switch (operator) {\n case '$eq':\n return constructSimpleFilterQuery(key, val);\n case '$gt':\n return constructComparisonFilterQuery(key, val, '>');\n case '$gte':\n return constructComparisonFilterQuery(key, val, '>=');\n case '$lt':\n return constructComparisonFilterQuery(key, val, '<');\n case '$lte':\n return constructComparisonFilterQuery(key, val, '<=');\n case '$ne':\n return constructSimpleFilterQuery(key, val).replace('=', '!=');\n case '$in':\n return format(\n `(data->>'%I') IN (%s)`,\n key,\n (val as unknown[])\n .map((v) => constructSimpleFilterQueryValue(key, v))\n .join(', '),\n );\n case '$nin':\n return format(\n `(data->>'%I') NOT IN (%s)`,\n key,\n (val as unknown[])\n .map((v) => constructSimpleFilterQueryValue(key, v))\n .join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n });\n return subFilters.join(' AND ');\n};\n\nconst constructComparisonFilterQuery = (\n key: string,\n value: unknown,\n operator: string,\n): string => {\n if (isUUID(value)) {\n return format(`(data->>'%I')::text ${operator} %L::text`, key, value);\n } else if (isDate(value)) {\n return format(\n `(data->>'%I')::timestamp ${operator} %L::timestamp`,\n key,\n value,\n );\n } else if (isNumber(value)) {\n return format(`(data->>'%I')::numeric ${operator} %s`, key, value);\n } else {\n return format(`(data->>'%I') ${operator} %L`, key, value);\n }\n};\n\nconst constructSimpleFilterQueryValue = (\n key: string,\n value: unknown,\n): string => {\n if (isUUID(value)) {\n return format('%L::text', value);\n } else if (isDate(value)) {\n return format('%L::timestamp', value);\n } else if (isNumber(value)) {\n return format('%L', value);\n } else {\n return format('%L', value);\n }\n};\n\nconst isUUID = (value: unknown): boolean => {\n return typeof value === 'string' && /^[0-9a-fA-F-]{36}$/.test(value);\n};\n\nconst isDate = (value: unknown): boolean => {\n return typeof value === 'string' && !isNaN(Date.parse(value));\n};\n\nconst isNumber = (value: unknown): boolean => {\n return typeof value === 'number';\n};\n","import pg from 'pg';\n\nconst pools: Map<string, pg.Pool> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n //TODO: this should include database name resolution for key\n return (\n pools.get(connectionString) ??\n pools.set(connectionString, new pg.Pool(poolOptions)).get(connectionString)!\n );\n};\n\nexport const endPool = async (connectionString: string): Promise<void> => {\n const pool = pools.get(connectionString);\n if (pool) {\n await pool.end();\n pools.delete(connectionString);\n }\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.keys()].map((connectionString) => endPool(connectionString)),\n );\n","import format from 'pg-format';\nimport type { PongoUpdate } from '../../main';\n\nexport const constructUpdateQuery = <T>(update: PongoUpdate<T>): string => {\n let updateQuery = 'data';\n\n if ('$set' in update) {\n const setUpdate = update.$set!;\n updateQuery = format(\n 'jsonb_set(%s, %L, data || %L)',\n updateQuery,\n '{}',\n JSON.stringify(setUpdate),\n );\n }\n\n if ('$unset' in update) {\n const unsetUpdate = Object.keys(update.$unset!);\n updateQuery = format('%s - %L', updateQuery, unsetUpdate.join(', '));\n }\n\n if ('$inc' in update) {\n const incUpdate = update.$inc!;\n for (const [key, value] of Object.entries(incUpdate)) {\n updateQuery = format(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))\",\n updateQuery,\n key,\n key,\n value,\n );\n }\n }\n\n if ('$push' in update) {\n const pushUpdate = update.$push!;\n for (const [key, value] of Object.entries(pushUpdate)) {\n updateQuery = format(\n \"jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || to_jsonb(%L)))\",\n updateQuery,\n key,\n key,\n value,\n );\n }\n }\n\n return updateQuery;\n};\n","import { postgresClient } from '../postgres';\nimport type { PongoCollection } from './typing';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(connectionString, database);\n};\n","import { getDbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing';\n\nexport const pongoClient = (connectionString: string): PongoClient => {\n const dbClient = getDbClient(connectionString);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: () => dbClient.close(),\n db: (dbName?: string): PongoDb =>\n dbName ? getDbClient(connectionString, dbName) : dbClient,\n };\n\n return pongoClient;\n};\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import { Collection as MongoCollection, type Document } from 'mongodb';\nimport type { PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(collectionName: string): MongoCollection<T> {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type { PongoCollection, PongoFilter, PongoUpdate } from '../main';\nimport { FindCursor } from './findCursor';\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n throw new Error('Method not implemented.');\n }\n get collectionName(): string {\n throw new Error('Method not implemented.');\n }\n get namespace(): string {\n throw new Error('Method not implemented.');\n }\n get readConcern(): ReadConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get readPreference(): ReadPreference | undefined {\n throw new Error('Method not implemented.');\n }\n get bsonOptions(): BSONSerializeOptions {\n throw new Error('Method not implemented.');\n }\n get writeConcern(): WriteConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get hint(): Hint | undefined {\n throw new Error('Method not implemented.');\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n insertMany(\n _docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n throw new Error('Method not implemented.');\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n _filter: Filter<T>,\n _: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n updateMany(\n _filter: Filter<T>,\n _update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n deleteMany(\n _filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n throw new Error('Method not implemented.');\n }\n rename(\n _newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n throw new Error('Method not implemented.');\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n _options?: unknown,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(filter as PongoFilter<T>);\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n _options?: unknown,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(filter as PongoFilter<T>),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n _options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n countDocuments(\n _filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n _filter: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n _filter: unknown,\n _replacement: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n _filter: unknown,\n _update: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n _filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n}\n","// src/MongoClientShim.ts\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string) {\n this.pongoClient = pongoClient(connectionString);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/postgres/client.ts","../src/postgres/execute/index.ts","../src/postgres/filter/queryOperators.ts","../src/postgres/filter/index.ts","../src/postgres/pool.ts","../src/postgres/update/index.ts","../src/main/dbClient.ts","../src/main/client.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"names":["uuid","format","sql","pool","sqlText","params","client","query","execute","handle","Operators","OperatorMap","isOperator","key","hasOperators","value","handleOperator","path","operator","buildNestedObject","v","subQuery","subKey","subValue","acc","AND","constructFilterQuery","filter","isRecord","constructComplexFilterQuery","isEquality","nestedKey","val","pg","pools","getPool","connectionStringOrOptions","connectionString","poolOptions","endPool","endAllPools","constructUpdateQuery","update","updateQuery","setUpdate","unsetUpdate","incUpdate","pushUpdate","postgresClient","database","name","postgresCollection","collectionName","createCollection","document","id","filterQuery","result","row","getDbClient","pongoClient","dbClient","dbName","FindCursor","documents","callback","docs","doc","Collection","collection","_options","_docs","_operations","_filter","_","_update","_newName","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_replacement","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","MongoClient"],"mappings":"AAAA,MAAe,KACf,OAAS,MAAMA,MAAY,OCA3B,OAAOC,MAAY,YAEZ,IAAMC,EAAM,MACjBC,EACAC,KACGC,IACiC,CACpC,IAAMC,EAAS,MAAMH,EAAK,QAAQ,EAClC,GAAI,CACF,IAAMI,EAAQN,EAAOG,EAAS,GAAGC,CAAM,EACvC,OAAO,MAAMC,EAAO,MAAcC,CAAK,CACzC,QAAE,CACAD,EAAO,QAAQ,CACjB,CACF,EAEaE,EAAU,MACrBL,EACAM,IACG,CACH,IAAMH,EAAS,MAAMH,EAAK,QAAQ,EAClC,GAAI,CACF,OAAO,MAAMM,EAAOH,CAAM,CAC5B,QAAE,CACAA,EAAO,QAAQ,CACjB,CACF,EC3BA,OAAOL,MAAY,YAEZ,IAAMS,EAAY,CACvB,IAAK,MACL,IAAK,MACL,KAAM,OACN,IAAK,MACL,KAAM,OACN,IAAK,MACL,IAAK,MACL,KAAM,OACN,WAAY,aACZ,K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AAyB,CAC3C,CACA,0BACEA,EACwB,CACxB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,wBACEA,EACsB,CACtB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,MACEG,EACAH,EACiB,CACjB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAQA,kBACEc,EACAd,EAC2C,CAC3C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBe,EAAuD,CACvE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,oBACEC,EACmB,CACnB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,gBAAgBF,EAA8B,CAC5C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBA,EAAeG,EAAsC,CACrE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAEA,MAAM,kBAAkC,CACtC,MAAM,KAAK,WAAW,iBAAiB,CACzC,CACF,EDvdO,IAAMC,EAAN,KAAS,CACd,YAAoBC,EAAkB,CAAlB,aAAAA,CAAmB,CAEvC,WAA+BrC,EAA4C,CACzE,OAAO,IAAIgB,EAAc,KAAK,QAAQ,WAAchB,CAAc,CAAC,CACrE,CACF,EENO,IAAMsC,EAAN,KAAkB,CACf,YAER,YAAYrD,EAA0B,CACpC,KAAK,YAAcuB,EAAYvB,CAAgB,CACjD,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGyB,EAAoB,CACrB,OAAO,IAAI0B,EAAG,KAAK,YAAY,GAAG1B,CAAM,CAAC,CAC3C,CACF","sourcesContent":["import pg from 'pg';\nimport { v4 as uuid } from 'uuid';\nimport {\n type DbClient,\n type PongoCollection,\n type PongoDeleteResult,\n type PongoFilter,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n} from '../main';\nimport { sql } from './execute';\nimport { constructFilterQuery } from './filter';\nimport { endPool, getPool } from './pool';\nimport { constructUpdateQuery } from './update';\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => Promise.resolve(),\n close: () => endPool(connectionString),\n collection: <T>(name: string) => postgresCollection<T>(name, pool),\n };\n};\n\nexport const postgresCollection = <T>(\n collectionName: string,\n pool: pg.Pool,\n): PongoCollection<T> => {\n const createCollection = sql(\n pool,\n 'CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)',\n collectionName,\n );\n return {\n createCollection: async () => {\n await createCollection;\n },\n insertOne: async (document: T): Promise<PongoInsertOneResult> => {\n await createCollection;\n\n const id = uuid();\n\n const result = await sql(\n pool,\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n id,\n JSON.stringify({ ...document, _id: id }),\n );\n\n return result.rowCount\n ? { insertedId: id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = constructUpdateQuery(update);\n\n const result = await sql(\n pool,\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'DELETE FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n return (result.rows[0]?.data ?? null) as T | null;\n },\n find: async (filter: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'SELECT data FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n\n return result.rows.map((row) => row.data as T);\n },\n };\n};\n","import type pg from 'pg';\nimport format from 'pg-format';\n\nexport const sql = async <Result extends pg.QueryResultRow = pg.QueryResultRow>(\n pool: pg.Pool,\n sqlText: string,\n ...params: unknown[]\n): Promise<pg.QueryResult<Result>> => {\n const client = await pool.connect();\n try {\n const query = format(sqlText, ...params);\n return await client.query<Result>(query);\n } finally {\n client.release();\n }\n};\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n","import format from 'pg-format';\n\nexport const Operators = {\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\nconst 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\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n switch (operator) {\n case '$eq':\n return format(\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 format(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return format(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = Object.entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n format(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return format(\n `jsonb_path_exists(data, '$.%s[*] ? (%s)')`,\n path,\n subQuery,\n );\n }\n case '$all':\n return format(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return format(\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 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 type { PongoFilter } from '../../main';\nimport { Operators, handleOperator, hasOperators } 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 Object.entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, Operators.$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 pg from 'pg';\n\nconst pools: Map<string, pg.Pool> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n //TODO: this should include database name resolution for key\n return (\n pools.get(connectionString) ??\n pools.set(connectionString, new pg.Pool(poolOptions)).get(connectionString)!\n );\n};\n\nexport const endPool = async (connectionString: string): Promise<void> => {\n const pool = pools.get(connectionString);\n if (pool) {\n await pool.end();\n pools.delete(connectionString);\n }\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.keys()].map((connectionString) => endPool(connectionString)),\n );\n","import format from 'pg-format';\nimport type { PongoUpdate } from '../../main';\n\nexport const constructUpdateQuery = <T>(update: PongoUpdate<T>): string => {\n let updateQuery = 'data';\n\n if ('$set' in update) {\n const setUpdate = update.$set!;\n updateQuery = format(\n 'jsonb_set(%s, %L, data || %L)',\n updateQuery,\n '{}',\n JSON.stringify(setUpdate),\n );\n }\n\n if ('$unset' in update) {\n const unsetUpdate = Object.keys(update.$unset!);\n updateQuery = format('%s - %L', updateQuery, unsetUpdate.join(', '));\n }\n\n if ('$inc' in update) {\n const incUpdate = update.$inc!;\n for (const [key, value] of Object.entries(incUpdate)) {\n updateQuery = format(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))\",\n updateQuery,\n key,\n key,\n value,\n );\n }\n }\n\n if ('$push' in update) {\n const pushUpdate = update.$push!;\n for (const [key, value] of Object.entries(pushUpdate)) {\n updateQuery = format(\n \"jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || to_jsonb(%L)))\",\n updateQuery,\n key,\n key,\n value,\n );\n }\n }\n\n return updateQuery;\n};\n","import { postgresClient } from '../postgres';\nimport type { PongoCollection } from './typing';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(connectionString, database);\n};\n","import { getDbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing';\n\nexport const pongoClient = (connectionString: string): PongoClient => {\n const dbClient = getDbClient(connectionString);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: () => dbClient.close(),\n db: (dbName?: string): PongoDb =>\n dbName ? getDbClient(connectionString, dbName) : dbClient,\n };\n\n return pongoClient;\n};\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import { Collection as MongoCollection, type Document } from 'mongodb';\nimport type { PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(collectionName: string): MongoCollection<T> {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type { PongoCollection, PongoFilter, PongoUpdate } from '../main';\nimport { FindCursor } from './findCursor';\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n throw new Error('Method not implemented.');\n }\n get collectionName(): string {\n throw new Error('Method not implemented.');\n }\n get namespace(): string {\n throw new Error('Method not implemented.');\n }\n get readConcern(): ReadConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get readPreference(): ReadPreference | undefined {\n throw new Error('Method not implemented.');\n }\n get bsonOptions(): BSONSerializeOptions {\n throw new Error('Method not implemented.');\n }\n get writeConcern(): WriteConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get hint(): Hint | undefined {\n throw new Error('Method not implemented.');\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n insertMany(\n _docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n throw new Error('Method not implemented.');\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n _filter: Filter<T>,\n _: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n updateMany(\n _filter: Filter<T>,\n _update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n deleteMany(\n _filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n throw new Error('Method not implemented.');\n }\n rename(\n _newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n throw new Error('Method not implemented.');\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n _options?: unknown,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(filter as PongoFilter<T>);\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n _options?: unknown,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(filter as PongoFilter<T>),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n _options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n countDocuments(\n _filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n _filter: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n _filter: unknown,\n _replacement: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n _filter: unknown,\n _update: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n _filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n}\n","// src/MongoClientShim.ts\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string) {\n this.pongoClient = pongoClient(connectionString);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -198,7 +198,6 @@ declare const sql: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool:
|
|
|
198
198
|
declare const execute: <Result = void>(pool: pg.Pool, handle: (client: pg.PoolClient) => Promise<Result>) => Promise<Result>;
|
|
199
199
|
|
|
200
200
|
declare const constructFilterQuery: <T>(filter: PongoFilter<T>) => string;
|
|
201
|
-
declare const constructComplexFilterQuery: (key: string, value: Record<string, unknown>) => string;
|
|
202
201
|
|
|
203
202
|
declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
|
|
204
203
|
declare const endPool: (connectionString: string) => Promise<void>;
|
|
@@ -206,4 +205,4 @@ declare const endAllPools: () => Promise<void[]>;
|
|
|
206
205
|
|
|
207
206
|
declare const constructUpdateQuery: <T>(update: PongoUpdate<T>) => string;
|
|
208
207
|
|
|
209
|
-
export { Collection, Db, type DbClient, FindCursor, MongoClient, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateResult,
|
|
208
|
+
export { Collection, Db, type DbClient, FindCursor, MongoClient, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateResult, constructFilterQuery, constructUpdateQuery, endAllPools, endPool, execute, getDbClient, getPool, pongoClient, postgresClient, postgresCollection, sql };
|
package/dist/index.d.ts
CHANGED
|
@@ -198,7 +198,6 @@ declare const sql: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool:
|
|
|
198
198
|
declare const execute: <Result = void>(pool: pg.Pool, handle: (client: pg.PoolClient) => Promise<Result>) => Promise<Result>;
|
|
199
199
|
|
|
200
200
|
declare const constructFilterQuery: <T>(filter: PongoFilter<T>) => string;
|
|
201
|
-
declare const constructComplexFilterQuery: (key: string, value: Record<string, unknown>) => string;
|
|
202
201
|
|
|
203
202
|
declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
|
|
204
203
|
declare const endPool: (connectionString: string) => Promise<void>;
|
|
@@ -206,4 +205,4 @@ declare const endAllPools: () => Promise<void[]>;
|
|
|
206
205
|
|
|
207
206
|
declare const constructUpdateQuery: <T>(update: PongoUpdate<T>) => string;
|
|
208
207
|
|
|
209
|
-
export { Collection, Db, type DbClient, FindCursor, MongoClient, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateResult,
|
|
208
|
+
export { Collection, Db, type DbClient, FindCursor, MongoClient, type PongoClient, type PongoCollection, type PongoDb, type PongoDeleteResult, type PongoFilter, type PongoFilterOperator, type PongoInsertOneResult, type PongoUpdate, type PongoUpdateResult, constructFilterQuery, constructUpdateQuery, endAllPools, endPool, execute, getDbClient, getPool, pongoClient, postgresClient, postgresCollection, sql };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"pg";import{v4 as
|
|
1
|
+
import"pg";import{v4 as A}from"uuid";import M from"pg-format";var d=async(t,e,...n)=>{let o=await t.connect();try{let i=M(e,...n);return await o.query(i)}finally{o.release()}},W=async(t,e)=>{let n=await t.connect();try{return await e(n)}finally{n.release()}};import r from"pg-format";var P={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},R={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},E=t=>t.startsWith("$"),I=t=>Object.keys(t).some(E),a=(t,e,n)=>{switch(e){case"$eq":return r("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(T(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return r(`data #>> %L ${R[e]} %L`,`{${t.split(".").join(",")}}`,n);case"$in":return r("data #>> %L IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>r("%L",o)).join(", "));case"$nin":return r("data #>> %L NOT IN (%s)",`{${t.split(".").join(",")}}`,n.map(o=>r("%L",o)).join(", "));case"$elemMatch":{let o=Object.entries(n).map(([i,s])=>r('@."%s" == %s',i,JSON.stringify(s))).join(" && ");return r("jsonb_path_exists(data, '$.%s[*] ? (%s)')",t,o)}case"$all":return r("data @> %L::jsonb",JSON.stringify(T(t,n)));case"$size":return r("jsonb_array_length(data #> %L) = %L",`{${t.split(".").join(",")}}`,n);default:throw new Error(`Unsupported operator: ${e}`)}},T=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var x="AND",l=t=>Object.entries(t).map(([e,n])=>b(n)?k(e,n):a(e,"$eq",n)).join(` ${x} `),k=(t,e)=>{let n=!I(e);return Object.entries(e).map(([o,i])=>n?a(`${t}.${o}`,P.$eq,i):a(t,o,i)).join(` ${x} `)},b=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);import $ from"pg";var p=new Map,C=t=>{let e=typeof t=="string"?t:t.connectionString,n=typeof t=="string"?{connectionString:e}:t;return p.get(e)??p.set(e,new $.Pool(n)).get(e)},h=async t=>{let e=p.get(t);e&&(await e.end(),p.delete(t))},v=()=>Promise.all([...p.keys()].map(t=>h(t)));import m from"pg-format";var y=t=>{let e="data";if("$set"in t){let n=t.$set;e=m("jsonb_set(%s, %L, data || %L)",e,"{}",JSON.stringify(n))}if("$unset"in t){let n=Object.keys(t.$unset);e=m("%s - %L",e,n.join(", "))}if("$inc"in t){let n=t.$inc;for(let[o,i]of Object.entries(n))e=m("jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))",e,o,o,i)}if("$push"in t){let n=t.$push;for(let[o,i]of Object.entries(n))e=m("jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || to_jsonb(%L)))",e,o,o,i)}return e};var D=(t,e)=>{let n=C({connectionString:t,database:e});return{connect:()=>Promise.resolve(),close:()=>h(t),collection:o=>S(o,n)}},S=(t,e)=>{let n=d(e,"CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)",t);return{createCollection:async()=>{await n},insertOne:async o=>{await n;let i=A();return(await d(e,"INSERT INTO %I (_id, data) VALUES (%L, %L)",t,i,JSON.stringify({...o,_id:i}))).rowCount?{insertedId:i,acknowledged:!0}:{insertedId:null,acknowledged:!1}},updateOne:async(o,i)=>{await n;let s=l(o),g=y(i),O=await d(e,"UPDATE %I SET data = %s WHERE %s",t,g,s);return O.rowCount?{acknowledged:!0,modifiedCount:O.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async o=>{await n;let i=l(o),s=await d(e,"DELETE FROM %I WHERE %s",t,i);return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async o=>{await n;let i=l(o);return(await d(e,"SELECT data FROM %I WHERE %s LIMIT 1",t,i)).rows[0]?.data??null},find:async o=>{await n;let i=l(o);return(await d(e,"SELECT data FROM %I WHERE %s",t,i)).rows.map(g=>g.data)}}};var w=(t,e)=>D(t,e);var F=t=>{let e=w(t),n={connect:async()=>(await e.connect(),n),close:()=>e.close(),db:o=>o?w(t,o):e};return n};var c=class{findDocumentsPromise;documents=null;index=0;constructor(e){this.findDocumentsPromise=e}async toArray(){return this.findDocuments()}async forEach(e){let n=await this.findDocuments();for(let o of n)e(o);return Promise.resolve()}hasNext(){if(this.documents===null)throw Error("Error while fetching documents");return this.index<this.documents.length}async next(){let e=await this.findDocuments();return this.hasNext()?e[this.index++]??null:null}async findDocuments(){return this.documents=await this.findDocumentsPromise,this.documents}};import"mongodb";var u=class{collection;constructor(e){this.collection=e}get dbName(){throw new Error("Method not implemented.")}get collectionName(){throw new Error("Method not implemented.")}get namespace(){throw new Error("Method not implemented.")}get readConcern(){throw new Error("Method not implemented.")}get readPreference(){throw new Error("Method not implemented.")}get bsonOptions(){throw new Error("Method not implemented.")}get writeConcern(){throw new Error("Method not implemented.")}get hint(){throw new Error("Method not implemented.")}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}insertMany(e,n){throw new Error("Method not implemented.")}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){throw new Error("Method not implemented.")}updateMany(e,n,o){throw new Error("Method not implemented.")}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}deleteMany(e,n){throw new Error("Method not implemented.")}rename(e,n){throw new Error("Method not implemented.")}drop(e){throw new Error("Method not implemented.")}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new c(this.collection.find(e))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){throw new Error("Method not implemented.")}countDocuments(e,n){throw new Error("Method not implemented.")}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){throw new Error("Method not implemented.")}findOneAndReplace(e,n,o){throw new Error("Method not implemented.")}findOneAndUpdate(e,n,o){throw new Error("Method not implemented.")}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){throw new Error("Method not implemented.")}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}};var f=class{constructor(e){this.pongoDb=e}collection(e){return new u(this.pongoDb.collection(e))}};var _=class{pongoClient;constructor(e){this.pongoClient=F(e)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new f(this.pongoClient.db(e))}};export{u as Collection,f as Db,c as FindCursor,_ as MongoClient,l as constructFilterQuery,y as constructUpdateQuery,v as endAllPools,h as endPool,W as execute,w as getDbClient,C as getPool,F as pongoClient,D as postgresClient,S as postgresCollection,d as sql};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/postgres/client.ts","../src/postgres/execute/index.ts","../src/postgres/filter/index.ts","../src/postgres/pool.ts","../src/postgres/update/index.ts","../src/main/dbClient.ts","../src/main/client.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"sourcesContent":["import pg from 'pg';\nimport { v4 as uuid } from 'uuid';\nimport {\n type DbClient,\n type PongoCollection,\n type PongoDeleteResult,\n type PongoFilter,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n} from '../main';\nimport { sql } from './execute';\nimport { constructFilterQuery } from './filter';\nimport { endPool, getPool } from './pool';\nimport { constructUpdateQuery } from './update';\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => Promise.resolve(),\n close: () => endPool(connectionString),\n collection: <T>(name: string) => postgresCollection<T>(name, pool),\n };\n};\n\nexport const postgresCollection = <T>(\n collectionName: string,\n pool: pg.Pool,\n): PongoCollection<T> => {\n const createCollection = sql(\n pool,\n 'CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)',\n collectionName,\n );\n return {\n createCollection: async () => {\n await createCollection;\n },\n insertOne: async (document: T): Promise<PongoInsertOneResult> => {\n await createCollection;\n\n const id = uuid();\n\n const result = await sql(\n pool,\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n id,\n JSON.stringify({ ...document, _id: id }),\n );\n\n return result.rowCount\n ? { insertedId: id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = constructUpdateQuery(update);\n\n const result = await sql(\n pool,\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'DELETE FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n return (result.rows[0]?.data ?? null) as T | null;\n },\n find: async (filter: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'SELECT data FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n\n return result.rows.map((row) => row.data as T);\n },\n };\n};\n","import type pg from 'pg';\nimport format from 'pg-format';\n\nexport const sql = async <Result extends pg.QueryResultRow = pg.QueryResultRow>(\n pool: pg.Pool,\n sqlText: string,\n ...params: unknown[]\n): Promise<pg.QueryResult<Result>> => {\n const client = await pool.connect();\n try {\n const query = format(sqlText, ...params);\n return await client.query<Result>(query);\n } finally {\n client.release();\n }\n};\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n","// src/utils.ts\nimport format from 'pg-format';\nimport type { PongoFilter } from '../../main';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string => {\n const filters = Object.entries(filter).map(([key, value]) => {\n if (typeof value === 'object' && !Array.isArray(value)) {\n return constructComplexFilterQuery(key, value as Record<string, unknown>);\n } else {\n return constructSimpleFilterQuery(key, value);\n }\n });\n return filters.join(' AND ');\n};\n\nconst constructSimpleFilterQuery = (key: string, value: unknown): string => {\n if (isUUID(value)) {\n return format(`(data->>'%I')::text = %L::text`, key, value);\n } else if (isDate(value)) {\n return format(`(data->>'%I')::timestamp = %L::timestamp`, key, value);\n } else if (isNumber(value)) {\n return format(`(data->>'%I')::numeric = %L`, key, value);\n } else {\n return format(`(data->>'%I') = %L`, key, value);\n }\n};\n\nexport const constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const subFilters = Object.entries(value).map(([operator, val]) => {\n switch (operator) {\n case '$eq':\n return constructSimpleFilterQuery(key, val);\n case '$gt':\n return constructComparisonFilterQuery(key, val, '>');\n case '$gte':\n return constructComparisonFilterQuery(key, val, '>=');\n case '$lt':\n return constructComparisonFilterQuery(key, val, '<');\n case '$lte':\n return constructComparisonFilterQuery(key, val, '<=');\n case '$ne':\n return constructSimpleFilterQuery(key, val).replace('=', '!=');\n case '$in':\n return format(\n `(data->>'%I') IN (%s)`,\n key,\n (val as unknown[])\n .map((v) => constructSimpleFilterQueryValue(key, v))\n .join(', '),\n );\n case '$nin':\n return format(\n `(data->>'%I') NOT IN (%s)`,\n key,\n (val as unknown[])\n .map((v) => constructSimpleFilterQueryValue(key, v))\n .join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n });\n return subFilters.join(' AND ');\n};\n\nconst constructComparisonFilterQuery = (\n key: string,\n value: unknown,\n operator: string,\n): string => {\n if (isUUID(value)) {\n return format(`(data->>'%I')::text ${operator} %L::text`, key, value);\n } else if (isDate(value)) {\n return format(\n `(data->>'%I')::timestamp ${operator} %L::timestamp`,\n key,\n value,\n );\n } else if (isNumber(value)) {\n return format(`(data->>'%I')::numeric ${operator} %s`, key, value);\n } else {\n return format(`(data->>'%I') ${operator} %L`, key, value);\n }\n};\n\nconst constructSimpleFilterQueryValue = (\n key: string,\n value: unknown,\n): string => {\n if (isUUID(value)) {\n return format('%L::text', value);\n } else if (isDate(value)) {\n return format('%L::timestamp', value);\n } else if (isNumber(value)) {\n return format('%L', value);\n } else {\n return format('%L', value);\n }\n};\n\nconst isUUID = (value: unknown): boolean => {\n return typeof value === 'string' && /^[0-9a-fA-F-]{36}$/.test(value);\n};\n\nconst isDate = (value: unknown): boolean => {\n return typeof value === 'string' && !isNaN(Date.parse(value));\n};\n\nconst isNumber = (value: unknown): boolean => {\n return typeof value === 'number';\n};\n","import pg from 'pg';\n\nconst pools: Map<string, pg.Pool> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n //TODO: this should include database name resolution for key\n return (\n pools.get(connectionString) ??\n pools.set(connectionString, new pg.Pool(poolOptions)).get(connectionString)!\n );\n};\n\nexport const endPool = async (connectionString: string): Promise<void> => {\n const pool = pools.get(connectionString);\n if (pool) {\n await pool.end();\n pools.delete(connectionString);\n }\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.keys()].map((connectionString) => endPool(connectionString)),\n );\n","import format from 'pg-format';\nimport type { PongoUpdate } from '../../main';\n\nexport const constructUpdateQuery = <T>(update: PongoUpdate<T>): string => {\n let updateQuery = 'data';\n\n if ('$set' in update) {\n const setUpdate = update.$set!;\n updateQuery = format(\n 'jsonb_set(%s, %L, data || %L)',\n updateQuery,\n '{}',\n JSON.stringify(setUpdate),\n );\n }\n\n if ('$unset' in update) {\n const unsetUpdate = Object.keys(update.$unset!);\n updateQuery = format('%s - %L', updateQuery, unsetUpdate.join(', '));\n }\n\n if ('$inc' in update) {\n const incUpdate = update.$inc!;\n for (const [key, value] of Object.entries(incUpdate)) {\n updateQuery = format(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))\",\n updateQuery,\n key,\n key,\n value,\n );\n }\n }\n\n if ('$push' in update) {\n const pushUpdate = update.$push!;\n for (const [key, value] of Object.entries(pushUpdate)) {\n updateQuery = format(\n \"jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || to_jsonb(%L)))\",\n updateQuery,\n key,\n key,\n value,\n );\n }\n }\n\n return updateQuery;\n};\n","import { postgresClient } from '../postgres';\nimport type { PongoCollection } from './typing';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(connectionString, database);\n};\n","import { getDbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing';\n\nexport const pongoClient = (connectionString: string): PongoClient => {\n const dbClient = getDbClient(connectionString);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: () => dbClient.close(),\n db: (dbName?: string): PongoDb =>\n dbName ? getDbClient(connectionString, dbName) : dbClient,\n };\n\n return pongoClient;\n};\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import { Collection as MongoCollection, type Document } from 'mongodb';\nimport type { PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(collectionName: string): MongoCollection<T> {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type { PongoCollection, PongoFilter, PongoUpdate } from '../main';\nimport { FindCursor } from './findCursor';\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n throw new Error('Method not implemented.');\n }\n get collectionName(): string {\n throw new Error('Method not implemented.');\n }\n get namespace(): string {\n throw new Error('Method not implemented.');\n }\n get readConcern(): ReadConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get readPreference(): ReadPreference | undefined {\n throw new Error('Method not implemented.');\n }\n get bsonOptions(): BSONSerializeOptions {\n throw new Error('Method not implemented.');\n }\n get writeConcern(): WriteConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get hint(): Hint | undefined {\n throw new Error('Method not implemented.');\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n insertMany(\n _docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n throw new Error('Method not implemented.');\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n _filter: Filter<T>,\n _: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n updateMany(\n _filter: Filter<T>,\n _update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n deleteMany(\n _filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n throw new Error('Method not implemented.');\n }\n rename(\n _newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n throw new Error('Method not implemented.');\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n _options?: unknown,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(filter as PongoFilter<T>);\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n _options?: unknown,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(filter as PongoFilter<T>),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n _options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n countDocuments(\n _filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n _filter: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n _filter: unknown,\n _replacement: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n _filter: unknown,\n _update: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n _filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n}\n","// src/MongoClientShim.ts\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string) {\n this.pongoClient = pongoClient(connectionString);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n"],"mappings":"AAAA,MAAe,KACf,OAAS,MAAMA,MAAY,OCA3B,OAAOC,MAAY,YAEZ,IAAMC,EAAM,MACjBC,EACAC,KACGC,IACiC,CACpC,IAAMC,EAAS,MAAMH,EAAK,QAAQ,EAClC,GAAI,CACF,IAAMI,EAAQN,EAAOG,EAAS,GAAGC,CAAM,EACvC,OAAO,MAAMC,EAA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EA,EACwB,CACxB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,wBACEA,EACsB,CACtB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,MACEM,EACAN,EACiB,CACjB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAQA,kBACEkB,EACAlB,EAC2C,CAC3C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBmB,EAAuD,CACvE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,oBACEC,EACmB,CACnB,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,gBAAgBF,EAA8B,CAC5C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBA,EAAeG,EAAsC,CACrE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAEA,MAAM,kBAAkC,CACtC,MAAM,KAAK,WAAW,iBAAiB,CACzC,CACF,EDvdO,IAAMC,EAAN,KAAS,CACd,YAAoBC,EAAkB,CAAlB,aAAAA,CAAmB,CAEvC,WAA+BC,EAA4C,CACzE,OAAO,IAAIC,EAAc,KAAK,QAAQ,WAAcD,CAAc,CAAC,CACrE,CACF,EENO,IAAME,EAAN,KAAkB,CACf,YAER,YAAYC,EAA0B,CACpC,KAAK,YAAcC,EAAYD,CAAgB,CACjD,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGE,EAAoB,CACrB,OAAO,IAAIC,EAAG,KAAK,YAAY,GAAGD,CAAM,CAAC,CAC3C,CACF","names":["uuid","format","sql","pool","sqlText","params","client","query","execute","handle","format","constructFilterQuery","filter","key","value","constructComplexFilterQuery","constructSimpleFilterQuery","isUUID","isDate","isNumber","operator","val","constructComparisonFilterQuery","v","constructSimpleFilterQueryValue","pg","pools","getPool","connectionStringOrOptions","connectionString","poolOptions","endPool","pool","endAllPools","format","constructUpdateQuery","update","updateQuery","setUpdate","unsetUpdate","incUpdate","key","value","pushUpdate","postgresClient","connectionString","database","pool","getPool","endPool","name","postgresCollection","collectionName","createCollection","sql","document","id","uuid","filter","update","filterQuery","constructFilterQuery","updateQuery","constructUpdateQuery","result","row","getDbClient","connectionString","database","postgresClient","pongoClient","connectionString","dbClient","getDbClient","dbName","FindCursor","documents","callback","docs","doc","Collection","collection","v","doc","_options","result","_docs","_operations","filter","update","_filter","_","_update","_newName","FindCursor","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_replacement","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","collectionName","Collection","MongoClient","connectionString","pongoClient","dbName","Db"]}
|
|
1
|
+
{"version":3,"sources":["../src/postgres/client.ts","../src/postgres/execute/index.ts","../src/postgres/filter/queryOperators.ts","../src/postgres/filter/index.ts","../src/postgres/pool.ts","../src/postgres/update/index.ts","../src/main/dbClient.ts","../src/main/client.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"sourcesContent":["import pg from 'pg';\nimport { v4 as uuid } from 'uuid';\nimport {\n type DbClient,\n type PongoCollection,\n type PongoDeleteResult,\n type PongoFilter,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n} from '../main';\nimport { sql } from './execute';\nimport { constructFilterQuery } from './filter';\nimport { endPool, getPool } from './pool';\nimport { constructUpdateQuery } from './update';\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => Promise.resolve(),\n close: () => endPool(connectionString),\n collection: <T>(name: string) => postgresCollection<T>(name, pool),\n };\n};\n\nexport const postgresCollection = <T>(\n collectionName: string,\n pool: pg.Pool,\n): PongoCollection<T> => {\n const createCollection = sql(\n pool,\n 'CREATE TABLE IF NOT EXISTS %I (_id UUID PRIMARY KEY, data JSONB)',\n collectionName,\n );\n return {\n createCollection: async () => {\n await createCollection;\n },\n insertOne: async (document: T): Promise<PongoInsertOneResult> => {\n await createCollection;\n\n const id = uuid();\n\n const result = await sql(\n pool,\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n id,\n JSON.stringify({ ...document, _id: id }),\n );\n\n return result.rowCount\n ? { insertedId: id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = constructUpdateQuery(update);\n\n const result = await sql(\n pool,\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (filter: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'DELETE FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n return (result.rows[0]?.data ?? null) as T | null;\n },\n find: async (filter: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const filterQuery = constructFilterQuery(filter);\n const result = await sql(\n pool,\n 'SELECT data FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n\n return result.rows.map((row) => row.data as T);\n },\n };\n};\n","import type pg from 'pg';\nimport format from 'pg-format';\n\nexport const sql = async <Result extends pg.QueryResultRow = pg.QueryResultRow>(\n pool: pg.Pool,\n sqlText: string,\n ...params: unknown[]\n): Promise<pg.QueryResult<Result>> => {\n const client = await pool.connect();\n try {\n const query = format(sqlText, ...params);\n return await client.query<Result>(query);\n } finally {\n client.release();\n }\n};\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n","import format from 'pg-format';\n\nexport const Operators = {\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\nconst 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\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n switch (operator) {\n case '$eq':\n return format(\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 format(\n `data #>> %L ${OperatorMap[operator]} %L`,\n `{${path.split('.').join(',')}}`,\n value,\n );\n case '$in':\n return format(\n 'data #>> %L IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n 'data #>> %L NOT IN (%s)',\n `{${path.split('.').join(',')}}`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$elemMatch': {\n const subQuery = Object.entries(value as Record<string, unknown>)\n .map(([subKey, subValue]) =>\n format(`@.\"%s\" == %s`, subKey, JSON.stringify(subValue)),\n )\n .join(' && ');\n return format(\n `jsonb_path_exists(data, '$.%s[*] ? (%s)')`,\n path,\n subQuery,\n );\n }\n case '$all':\n return format(\n 'data @> %L::jsonb',\n JSON.stringify(buildNestedObject(path, value)),\n );\n case '$size':\n return format(\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 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 type { PongoFilter } from '../../main';\nimport { Operators, handleOperator, hasOperators } 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 Object.entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, Operators.$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 pg from 'pg';\n\nconst pools: Map<string, pg.Pool> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n //TODO: this should include database name resolution for key\n return (\n pools.get(connectionString) ??\n pools.set(connectionString, new pg.Pool(poolOptions)).get(connectionString)!\n );\n};\n\nexport const endPool = async (connectionString: string): Promise<void> => {\n const pool = pools.get(connectionString);\n if (pool) {\n await pool.end();\n pools.delete(connectionString);\n }\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.keys()].map((connectionString) => endPool(connectionString)),\n );\n","import format from 'pg-format';\nimport type { PongoUpdate } from '../../main';\n\nexport const constructUpdateQuery = <T>(update: PongoUpdate<T>): string => {\n let updateQuery = 'data';\n\n if ('$set' in update) {\n const setUpdate = update.$set!;\n updateQuery = format(\n 'jsonb_set(%s, %L, data || %L)',\n updateQuery,\n '{}',\n JSON.stringify(setUpdate),\n );\n }\n\n if ('$unset' in update) {\n const unsetUpdate = Object.keys(update.$unset!);\n updateQuery = format('%s - %L', updateQuery, unsetUpdate.join(', '));\n }\n\n if ('$inc' in update) {\n const incUpdate = update.$inc!;\n for (const [key, value] of Object.entries(incUpdate)) {\n updateQuery = format(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L))\",\n updateQuery,\n key,\n key,\n value,\n );\n }\n }\n\n if ('$push' in update) {\n const pushUpdate = update.$push!;\n for (const [key, value] of Object.entries(pushUpdate)) {\n updateQuery = format(\n \"jsonb_set(%s, '{%s}', (COALESCE(data->'%s', '[]'::jsonb) || to_jsonb(%L)))\",\n updateQuery,\n key,\n key,\n value,\n );\n }\n }\n\n return updateQuery;\n};\n","import { postgresClient } from '../postgres';\nimport type { PongoCollection } from './typing';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (\n connectionString: string,\n database?: string,\n): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(connectionString, database);\n};\n","import { getDbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing';\n\nexport const pongoClient = (connectionString: string): PongoClient => {\n const dbClient = getDbClient(connectionString);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: () => dbClient.close(),\n db: (dbName?: string): PongoDb =>\n dbName ? getDbClient(connectionString, dbName) : dbClient,\n };\n\n return pongoClient;\n};\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import { Collection as MongoCollection, type Document } from 'mongodb';\nimport type { PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(collectionName: string): MongoCollection<T> {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type { PongoCollection, PongoFilter, PongoUpdate } from '../main';\nimport { FindCursor } from './findCursor';\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n throw new Error('Method not implemented.');\n }\n get collectionName(): string {\n throw new Error('Method not implemented.');\n }\n get namespace(): string {\n throw new Error('Method not implemented.');\n }\n get readConcern(): ReadConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get readPreference(): ReadPreference | undefined {\n throw new Error('Method not implemented.');\n }\n get bsonOptions(): BSONSerializeOptions {\n throw new Error('Method not implemented.');\n }\n get writeConcern(): WriteConcern | undefined {\n throw new Error('Method not implemented.');\n }\n get hint(): Hint | undefined {\n throw new Error('Method not implemented.');\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n insertMany(\n _docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n throw new Error('Method not implemented.');\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n _filter: Filter<T>,\n _: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n updateMany(\n _filter: Filter<T>,\n _update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n throw new Error('Method not implemented.');\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as unknown as PongoFilter<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n deleteMany(\n _filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n throw new Error('Method not implemented.');\n }\n rename(\n _newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n throw new Error('Method not implemented.');\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n _options?: unknown,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(filter as PongoFilter<T>);\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n _options?: unknown,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(filter as PongoFilter<T>),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n _options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n countDocuments(\n _filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n _filter: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n _filter: unknown,\n _replacement: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n _filter: unknown,\n _update: unknown,\n _options?: unknown,\n ):\n | Promise<import('mongodb').WithId<T> | null>\n | Promise<import('mongodb').ModifyResult<T>> {\n throw new Error('Method not implemented.');\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n _filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n throw new Error('Method not implemented.');\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n}\n","// src/MongoClientShim.ts\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string) {\n this.pongoClient = pongoClient(connectionString);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n"],"mappings":"AAAA,MAAe,KACf,OAAS,MAAMA,MAAY,OCA3B,OAAOC,MAAY,YAEZ,IAAMC,EAAM,MACjBC,EACAC,KACGC,IACiC,CACpC,IAAMC,EAAS,MAAMH,EAAK,QAAQ,EAClC,GAAI,CACF,IAAMI,EAAQN,EAAOG,EAAS,GAAGC,CAAM,EACvC,OAAO,MAAMC,EAAO,MAAcC,CAAK,CACzC,QAAE,CACAD,EAAO,QAAQ,CACjB,CACF,EAEaE,EAAU,MACrBL,EACAM,IACG,CACH,IAAMH,EAAS,MAAMH,EAAK,QAAQ,EAClC,GAAI,CACF,OAAO,MAAMM,EAAOH,CAAM,CAC5B,QAAE,CACAA,EAAO,QAAQ,CACjB,CACF,EC3BA,OAAOI,MAAY,YAEZ,IAAMC,EAAY,CACvB,IAAK,MACL,IAAK,MACL,KAAM,OACN,IAAK,MACL,KAAM,OACN,IAAK,MACL,IAAK,MACL,KAAM,OACN,WAAY,aACZ,KAAM,OACN,MAAO,OACT,EAEMC,EAAc,CAClB,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,KACN,IAAK,IACP,EAEaC,EAAcC,GAAgBA,EAAI,WAAW,GAAG,EAEhDC,EAAgBC,GAC3B,OAAO,KAAKA,CAAK,EAAE,KAAKH,CAAU,EAEvBI,EAAiB,CAC5BC,EACAC,EACAH,IACW,CACX,OAAQG,EAAU,CAChB,IAAK,MACH,OAAOT,EACL,wEACA,KAAK,UAAUU,EAAkBF,EAAMF,CAAK,CAAC,EAC7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A,kBAAkBA,EAAeG,EAAsC,CACrE,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CAEA,MAAM,kBAAkC,CACtC,MAAM,KAAK,WAAW,iBAAiB,CACzC,CACF,EDvdO,IAAMC,EAAN,KAAS,CACd,YAAoBC,EAAkB,CAAlB,aAAAA,CAAmB,CAEvC,WAA+BC,EAA4C,CACzE,OAAO,IAAIC,EAAc,KAAK,QAAQ,WAAcD,CAAc,CAAC,CACrE,CACF,EENO,IAAME,EAAN,KAAkB,CACf,YAER,YAAYC,EAA0B,CACpC,KAAK,YAAcC,EAAYD,CAAgB,CACjD,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGE,EAAoB,CACrB,OAAO,IAAIC,EAAG,KAAK,YAAY,GAAGD,CAAM,CAAC,CAC3C,CACF","names":["uuid","format","sql","pool","sqlText","params","client","query","execute","handle","format","Operators","OperatorMap","isOperator","key","hasOperators","value","handleOperator","path","operator","buildNestedObject","v","subQuery","subKey","subValue","acc","AND","constructFilterQuery","filter","key","value","isRecord","constructComplexFilterQuery","handleOperator","isEquality","hasOperators","nestedKey","val","Operators","pg","pools","getPool","connectionStringOrOptions","connectionString","poolOptions","endPool","pool","endAllPools","format","constructUpdateQuery","update","updateQuery","setUpdate","unsetUpdate","incUpdate","key","value","pushUpdate","postgresClient","connectionString","database","pool","getPool","endPool","name","postgresCollection","collectionName","createCollection","sql","document","id","uuid","filter","update","filterQuery","constructFilterQuery","updateQuery","constructUpdateQuery","result","row","getDbClient","connectionString","database","postgresClient","pongoClient","connectionString","dbClient","getDbClient","dbName","FindCursor","documents","callback","docs","doc","Collection","collection","v","doc","_options","result","_docs","_operations","filter","update","_filter","_","_update","_newName","FindCursor","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_replacement","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","collectionName","Collection","MongoClient","connectionString","pongoClient","dbName","Db"]}
|