@event-driven-io/pongo 0.7.0 → 0.9.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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- [![](https://dcbadge.vercel.app/api/server/fTpqUTMmVa?style=flat)](https://discord.gg/kHkSThjG) [<img src="https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white" height="20px" />](https://www.linkedin.com/in/oskardudycz/) [![Github Sponsors](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&link=https://github.com/sponsors/oskardudycz/)](https://github.com/sponsors/oskardudycz/) [![blog](https://img.shields.io/badge/blog-event--driven.io-brightgreen)](https://event-driven.io/?utm_source=event_sourcing_nodejs) [![blog](https://img.shields.io/badge/%F0%9F%9A%80-Architecture%20Weekly-important)](https://www.architecture-weekly.com/?utm_source=event_sourcing_nodejs)
1
+ [![](https://dcbadge.vercel.app/api/server/fTpqUTMmVa?style=flat)](https://discord.gg/VzvxR5Rb38) [<img src="https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white" height="20px" />](https://www.linkedin.com/in/oskardudycz/) [![Github Sponsors](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&link=https://github.com/sponsors/oskardudycz/)](https://github.com/sponsors/oskardudycz/) [![blog](https://img.shields.io/badge/blog-event--driven.io-brightgreen)](https://event-driven.io/?utm_source=event_sourcing_nodejs) [![blog](https://img.shields.io/badge/%F0%9F%9A%80-Architecture%20Weekly-important)](https://www.architecture-weekly.com/?utm_source=event_sourcing_nodejs)
2
2
 
3
3
  ![](./src/docs/public/social.png)
4
4
 
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
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 _dumbo = require('@event-driven-io/dumbo');require('pg');var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var _uuid = require('uuid');var T=t=>Object.entries(t).map(([e,n])=>[e,n]);var D={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},F={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},M= exports.isOperator =t=>t.startsWith("$"),E= exports.hasOperators =t=>Object.keys(t).some(M),O= exports.handleOperator =(t,e,n)=>{if(t==="_id")return $(e,n);switch(e){case"$eq":return _pgformat2.default.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",JSON.stringify(x(t,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `data #>> %L ${F[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=T(n).map(([i,d])=>_pgformat2.default.call(void 0, '@."%s" == %s',i,JSON.stringify(d))).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(x(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,e)=>{switch(t){case"$eq":return _pgformat2.default.call(void 0, "_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `_id ${F[t]} %L`,e);case"$in":return _pgformat2.default.call(void 0, "_id IN (%s)",e.map(n=>_pgformat2.default.call(void 0, "%L",n)).join(", "));case"$nin":return _pgformat2.default.call(void 0, "_id NOT IN (%s)",e.map(n=>_pgformat2.default.call(void 0, "%L",n)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},x=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var b="AND",c= exports.constructFilterQuery =t=>Object.entries(t).map(([e,n])=>W(n)?A(e,n):O(e,"$eq",n)).join(` ${b} `),A=(t,e)=>{let n=!E(e);return T(e).map(([o,i])=>n?O(`${t}.${o}`,D.$eq,i):O(t,o,i)).join(` ${b} `)},W=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);var h=t=>T(t).reduce((e,[n,o])=>{switch(n){case"$set":return U(o,e);case"$unset":return N(o,e);case"$inc":return Q(o,e);case"$push":return j(o,e);default:return e}},_dumbo.sql.call(void 0, "data")),U= exports.buildSetQuery =(t,e)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",e,JSON.stringify(t)),N= exports.buildUnsetQuery =(t,e)=>_dumbo.sql.call(void 0, "%s - %L",e,Object.keys(t).map(n=>`{${n}}`).join(", ")),Q= exports.buildIncQuery =(t,e)=>{for(let[n,o]of Object.entries(t))e=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",e,n,n,o);return e},j= exports.buildPushQuery =(t,e)=>{for(let[n,o]of Object.entries(t))e=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",e,n,n,JSON.stringify([o]));return e};var k=(t,{dbName:e,poolOrClient:n})=>{let o=r=>_dumbo.executeSQL.call(void 0, n,r),i=K(t),d=o(i.createCollection()),a={dbName:e,collectionName:t,createCollection:async()=>{await d},insertOne:async r=>{await d;let s=_uuid.v4.call(void 0, );return(await o(i.insertOne({_id:s,...r}))).rowCount?{insertedId:s,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async r=>{await d;let s=r.map(m=>({_id:_uuid.v4.call(void 0, ),...m})),l=await o(i.insertMany(s));return{acknowledged:l.rowCount===s.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:s.map(m=>m._id)}},updateOne:async(r,s)=>{await d;let l=await o(i.updateOne(r,s));return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(r,s)=>{await d;let l=await o(i.replaceOne(r,s));return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(r,s)=>{await d;let l=await o(i.updateMany(r,s));return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async r=>{await d;let s=await o(i.deleteOne(_nullishCoalesce(r, () => ({}))));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async r=>{await d;let s=await o(i.deleteMany(_nullishCoalesce(r, () => ({}))));return s.rowCount?{acknowledged:!0,deletedCount:s.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async r=>(await d,await _asyncNullishCoalesce(await _asyncOptionalChain([(await o(i.findOne(_nullishCoalesce(r, () => ({}))))), 'access', async _2 => _2.rows, 'access', async _3 => _3[0], 'optionalAccess', async _4 => _4.data]), async () => (null))),findOneAndDelete:async r=>{await d;let s=await a.findOne(r);return s===null?null:(await a.deleteOne(r),s)},findOneAndReplace:async(r,s)=>{await d;let l=await a.findOne(r);return l===null?null:(await a.replaceOne(r,s),l)},findOneAndUpdate:async(r,s)=>{await d;let l=await a.findOne(r);return l===null?null:(await a.updateOne(r,s),l)},handle:async(r,s)=>{await d;let l={_id:r},m=await a.findOne(l),f=await s(m);if(!m&&f){let y={...f,_id:r};return await a.insertOne({...y,_id:r}),y}return m&&!f?(await a.deleteOne(l),null):(m&&f&&await a.replaceOne(l,f),f)},find:async r=>(await d,(await o(i.find(_nullishCoalesce(r, () => ({}))))).rows.map(l=>l.data)),countDocuments:async r=>{await d;let{count:s}=await _dumbo.single.call(void 0, o(i.countDocuments(_nullishCoalesce(r, () => ({})))));return s},drop:async()=>(await d,(await _asyncNullishCoalesce(await _asyncOptionalChain([(await o(i.drop())), 'optionalAccess', async _5 => _5.rowCount]), async () => (0)))>0),rename:async r=>(await d,await o(i.rename(r)),t=r,a)};return a},K= exports.collectionSQLBuilder =t=>({createCollection:()=>_dumbo.sql.call(void 0, `CREATE TABLE IF NOT EXISTS %I (
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(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var q=async(t,e)=>{let n=_optionalChain([e, 'optionalAccess', _2 => _2.session, 'optionalAccess', _3 => _3.transaction]);return!n||!n.isActive?null:await n.enlistDatabase(t)},R=async(t,e,n)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await q(t,e)), 'optionalAccess', async _4 => _4.execute]), async () => (n)),A= exports.pongoCollection =({db:t,collectionName:e,sqlExecutor:n,sqlBuilder:o})=>{let i=async(r,s)=>(await R(t,s,n)).command(r),d=async(r,s)=>(await R(t,s,n)).query(r),T=i(o.createCollection()),c=r=>_optionalChain([r, 'optionalAccess', _5 => _5.session])?i(o.createCollection(),r):T,m={dbName:t.databaseName,collectionName:e,createCollection:async r=>{await c(r)},insertOne:async(r,s)=>{await c(s);let a=_uuid.v4.call(void 0, );return(await i(o.insertOne({_id:a,...r}),s)).rowCount?{insertedId:a,acknowledged:!0}:{insertedId:null,acknowledged:!1}},insertMany:async(r,s)=>{await c(s);let a=r.map(f=>({_id:_uuid.v4.call(void 0, ),...f})),l=await i(o.insertMany(a),s);return{acknowledged:l.rowCount===a.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:a.map(f=>f._id)}},updateOne:async(r,s,a)=>{await c(a);let l=await i(o.updateOne(r,s),a);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},replaceOne:async(r,s,a)=>{await c(a);let l=await i(o.replaceOne(r,s),a);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},updateMany:async(r,s,a)=>{await c(a);let l=await i(o.updateMany(r,s),a);return l.rowCount?{acknowledged:!0,modifiedCount:l.rowCount}:{acknowledged:!1,modifiedCount:0}},deleteOne:async(r,s)=>{await c(s);let a=await i(o.deleteOne(_nullishCoalesce(r, () => ({}))),s);return a.rowCount?{acknowledged:!0,deletedCount:a.rowCount}:{acknowledged:!1,deletedCount:0}},deleteMany:async(r,s)=>{await c(s);let a=await i(o.deleteMany(_nullishCoalesce(r, () => ({}))),s);return a.rowCount?{acknowledged:!0,deletedCount:a.rowCount}:{acknowledged:!1,deletedCount:0}},findOne:async(r,s)=>(await c(s),await _asyncNullishCoalesce(await _asyncOptionalChain([(await d(o.findOne(_nullishCoalesce(r, () => ({}))),s)), 'access', async _6 => _6.rows, 'access', async _7 => _7[0], 'optionalAccess', async _8 => _8.data]), async () => (null))),findOneAndDelete:async(r,s)=>{await c(s);let a=await m.findOne(r,s);return a===null?null:(await m.deleteOne(r,s),a)},findOneAndReplace:async(r,s,a)=>{await c(a);let l=await m.findOne(r,a);return l===null?null:(await m.replaceOne(r,s,a),l)},findOneAndUpdate:async(r,s,a)=>{await c(a);let l=await m.findOne(r,a);return l===null?null:(await m.updateOne(r,s,a),l)},handle:async(r,s,a)=>{await c(a);let l={_id:r},f=await m.findOne(l,a),P=await s(f);if(!f&&P){let L={...P,_id:r};return await m.insertOne({...L,_id:r},a),L}return f&&!P?(await m.deleteOne(l,a),null):(f&&P&&await m.replaceOne(l,P,a),P)},find:async(r,s)=>(await c(s),(await d(o.find(_nullishCoalesce(r, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(r,s)=>{await c(s);let{count:a}=await _dumbo.single.call(void 0, d(o.countDocuments(_nullishCoalesce(r, () => ({})))));return a},drop:async r=>(await c(r),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await i(o.drop())), 'optionalAccess', async _9 => _9.rowCount]), async () => (0)))>0),rename:async(r,s)=>(await c(s),await i(o.rename(r)),e=r,m)};return m};var M={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},S= exports.OperatorMap ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},z= exports.isOperator =t=>t.startsWith("$"),_= exports.hasOperators =t=>Object.keys(t).some(z);require('pg');var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var h=(t,e,n)=>{if(t==="_id")return X(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,n)),t,JSON.stringify(n));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `data #>> %L ${S[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=w(n).map(([i,d])=>_pgformat2.default.call(void 0, '@."%s" == %s',i,JSON.stringify(d))).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,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}`)}},X=(t,e)=>{switch(t){case"$eq":return _pgformat2.default.call(void 0, "_id = %L",e);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _pgformat2.default.call(void 0, `_id ${S[t]} %L`,e);case"$in":return _pgformat2.default.call(void 0, "_id IN (%s)",e.map(n=>_pgformat2.default.call(void 0, "%L",n)).join(", "));case"$nin":return _pgformat2.default.call(void 0, "_id NOT IN (%s)",e.map(n=>_pgformat2.default.call(void 0, "%L",n)).join(", "));default:throw new Error(`Unsupported operator: ${t}`)}},$=(t,e)=>t.split(".").reverse().reduce((n,o)=>({[o]:n}),e);var W="AND",O=t=>Object.entries(t).map(([e,n])=>Y(n)?V(e,n):h(e,"$eq",n)).join(` ${W} `),V=(t,e)=>{let n=!_(e);return w(e).map(([o,i])=>n?h(`${t}.${o}`,M.$eq,i):h(t,o,i)).join(` ${W} `)},Y=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);var E=t=>w(t).reduce((e,[n,o])=>{switch(n){case"$set":return Z(o,e);case"$unset":return G(o,e);case"$inc":return ee(o,e);case"$push":return ne(o,e);default:return e}},_dumbo.sql.call(void 0, "data")),Z=(t,e)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",e,JSON.stringify(t)),G=(t,e)=>_dumbo.sql.call(void 0, "%s - %L",e,Object.keys(t).map(n=>`{${n}}`).join(", ")),ee=(t,e)=>{for(let[n,o]of Object.entries(t))e=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)",e,n,n,o);return e},ne=(t,e)=>{for(let[n,o]of Object.entries(t))e=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",e,n,n,JSON.stringify([o]));return e};var Q=t=>({createCollection:()=>_dumbo.sql.call(void 0, `CREATE TABLE IF NOT EXISTS %I (
2
2
  _id TEXT PRIMARY KEY,
3
3
  data JSONB NOT NULL,
4
4
  metadata JSONB NOT NULL DEFAULT '{}',
@@ -7,8 +7,8 @@
7
7
  _archived BOOLEAN NOT NULL DEFAULT FALSE,
8
8
  _created TIMESTAMPTZ NOT NULL DEFAULT now(),
9
9
  _updated TIMESTAMPTZ NOT NULL DEFAULT now()
10
- )`,t),insertOne:e=>_dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES (%L, %L)",t,e._id,JSON.stringify(e)),insertMany:e=>{let n=e.map(o=>_pgformat2.default.call(void 0, "(%L, %L)",o._id,JSON.stringify(o))).join(", ");return _dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES %s",t,n)},updateOne:(e,n)=>{let o=c(e),i=h(n);return _dumbo.sql.call(void 0, `WITH cte AS (
10
+ )`,t),insertOne:e=>_dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES (%L, %L)",t,e._id,JSON.stringify(e)),insertMany:e=>{let n=e.map(o=>_pgformat2.default.call(void 0, "(%L, %L)",o._id,JSON.stringify(o))).join(", ");return _dumbo.sql.call(void 0, "INSERT INTO %I (_id, data) VALUES %s",t,n)},updateOne:(e,n)=>{let o=O(e),i=E(n);return _dumbo.sql.call(void 0, `WITH cte AS (
11
11
  SELECT _id FROM %I WHERE %s LIMIT 1
12
12
  )
13
- UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,o,t,i,t)},replaceOne:(e,n)=>{let o=c(e);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') WHERE %s",t,JSON.stringify(n),o)},updateMany:(e,n)=>{let o=c(e),i=h(n);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %s WHERE %s",t,i,o)},deleteOne:e=>{let n=c(e);return _dumbo.sql.call(void 0, "DELETE FROM %I WHERE %s",t,n)},deleteMany:e=>{let n=c(e);return _dumbo.sql.call(void 0, "DELETE FROM %I WHERE %s",t,n)},findOne:e=>{let n=c(e);return _dumbo.sql.call(void 0, "SELECT data FROM %I WHERE %s LIMIT 1",t,n)},find:e=>{let n=c(e);return _dumbo.sql.call(void 0, "SELECT data FROM %I WHERE %s",t,n)},countDocuments:e=>{let n=c(e);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I WHERE %s",t,n)},rename:e=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I",t,e),drop:(e=t)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",e)});var L=t=>{let{connectionString:e,dbName:n,client:o}=t,i=!o,d=_nullishCoalesce(o, () => (_dumbo.getPool.call(void 0, {connectionString:e,database:n})));return{connect:()=>Promise.resolve(),close:()=>i?_dumbo.endPool.call(void 0, {connectionString:e,database:n}):Promise.resolve(),collection:a=>k(a,{dbName:_nullishCoalesce(n, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, e))),poolOrClient:d})}};var C=t=>L(t);var R=(t,e={})=>{let n=_dumbo.getDatabaseNameOrDefault.call(void 0, t),o=new Map,i=C({connectionString:t,client:e.client});o.set(n,i);let d={connect:async()=>(await i.connect(),d),close:async()=>{for(let a of o.values())await a.close()},db:a=>a?_nullishCoalesce(o.get(a), () => (o.set(a,C({connectionString:t,dbName:a,client:e.client})).get(a))):i};return d};var P= (_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 w=class{constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e);return{acknowledged:o.acknowledged,insertedId:o.insertedId}}async insertMany(e,n){let o=await this.collection.insertMany(e);return{acknowledged:o.acknowledged,insertedIds:o.insertedIds,insertedCount:o.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){return this.collection.replaceOne(e,n)}async updateMany(e,n,o){let i=await this.collection.updateMany(e,n);return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let o=await this.collection.deleteOne(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async deleteMany(e,n){let o=await this.collection.deleteMany(e);return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async rename(e,n){return await this.collection.rename(e),this}drop(e){return this.collection.drop()}async findOne(e,n){return this.collection.findOne(e)}find(e,n){return new P(this.collection.find(e))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments()}countDocuments(e,n){return this.collection.countDocuments(e)}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e)}findOneAndReplace(e,n,o){return this.collection.findOneAndReplace(e,n)}findOneAndUpdate(e,n,o){return this.collection.findOneAndUpdate(e,n)}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(_nullishCoalesce(e, () => ({})))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n){return this.collection.handle(e.toString(),n)}};var I=class{constructor(e){this.pongoDb=e}collection(e){return new w(this.pongoDb.collection(e))}};var _=class{constructor(e,n={}){this.pongoClient=R(e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new I(this.pongoClient.db(e))}};exports.Collection = w; exports.Db = I; exports.FindCursor = P; exports.MongoClient = _; exports.Operators = D; exports.buildIncQuery = Q; exports.buildPushQuery = j; exports.buildSetQuery = U; exports.buildUnsetQuery = N; exports.buildUpdateQuery = h; exports.collectionSQLBuilder = K; exports.constructFilterQuery = c; exports.entries = T; exports.getDbClient = C; exports.handleOperator = O; exports.hasOperators = E; exports.isOperator = M; exports.pongoClient = R; exports.postgresClient = L; exports.postgresCollection = k;
13
+ UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,t,o,t,i,t)},replaceOne:(e,n)=>{let o=O(e);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') WHERE %s",t,JSON.stringify(n),o)},updateMany:(e,n)=>{let o=O(e),i=E(n);return _dumbo.sql.call(void 0, "UPDATE %I SET data = %s WHERE %s",t,i,o)},deleteOne:e=>{let n=O(e);return _dumbo.sql.call(void 0, "DELETE FROM %I WHERE %s",t,n)},deleteMany:e=>{let n=O(e);return _dumbo.sql.call(void 0, "DELETE FROM %I WHERE %s",t,n)},findOne:e=>{let n=O(e);return _dumbo.sql.call(void 0, "SELECT data FROM %I WHERE %s LIMIT 1",t,n)},find:e=>{let n=O(e);return _dumbo.sql.call(void 0, "SELECT data FROM %I WHERE %s",t,n)},countDocuments:e=>{let n=O(e);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I WHERE %s",t,n)},rename:e=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I",t,e),drop:(e=t)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",e)});var U=t=>t.connectorType===_dumbo.NodePostgresConnectorType,N= exports.postgresDb =t=>{let{connectionString:e,dbName:n}=t,o=_nullishCoalesce(n, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, e))),i=_dumbo.postgresPool.call(void 0, t),d={connectorType:t.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collection:T=>A({collectionName:T,db:d,sqlExecutor:i.execute,sqlBuilder:Q(T)}),transaction:()=>i.transaction(),withTransaction:T=>i.withTransaction(T)};return d};var F=t=>{let{connectorType:e}=t;if(!U(t))throw new Error(`Unsupported db type: ${e}`);return N(t)};var j=t=>{let e=!1,n=!1,o=null,i=null;return{enlistDatabase:async d=>{if(i&&o!==d.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===d.databaseName||(o=d.databaseName,i=d.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!e){if(n)throw new Error("Transaction is not active!");e=!0,await i.commit(),i=null}},rollback:async d=>{if(!i)throw new Error("No database transaction started!");if(e)throw new Error("Cannot rollback commited transaction!");n||(n=!0,await i.rollback(d),i=null)},databaseName:o,isStarting:!1,isCommitted:e,get isActive(){return!e&&!n},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:t}};var I=t=>_optionalChain([t, 'optionalAccess', _10 => _10.isActive])===!0;function B(t){if(!I(t))throw new Error("No active transaction exists!")}function se(t){if(I(t))throw new Error("Active transaction already exists!")}var C=t=>{let e=_optionalChain([t, 'optionalAccess', _11 => _11.explicit])===!0,n=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _12 => _12.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,i=!1,d=s=>{se(o),o=j(_nullishCoalesce(s, () => (n)))},T=async()=>{B(o),await o.commit()},c=async()=>{B(o),await o.rollback()},r={get hasEnded(){return i},explicit:e,defaultTransactionOptions:_nullishCoalesce(n, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return n.snapshotEnabled},endSession:async()=>{i||(i=!0,I(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>I(o),startTransaction:d,commitTransaction:T,abortTransaction:c,withTransaction:async(s,a)=>{d(a);try{let l=await s(r);return await T(),l}catch(l){throw await c(),l}}};return r};var v=(t,e={})=>{let n=new Map,o=F(H({connectionString:t,clientOptions:e}));n.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let d of n.values())await d.close()},db:d=>d?_nullishCoalesce(n.get(d), () => (n.set(d,F(H({connectionString:t,dbName:d,clientOptions:e}))).get(d))):o,startSession:C,withSession:async d=>{let T=C();try{return await d(T)}finally{await T.endSession()}}};return i},H= exports.clientToDbOptions =t=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:t.connectionString,dbName:t.dbName,...t.clientOptions});var w=t=>Object.entries(t).map(([e,n])=>[e,n]);var D= (_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 p=t=>_optionalChain([t, 'optionalAccess', _13 => _13.session])?{session:t.session}:void 0,b= exports.Collection =class{constructor(e){this.collection=e}get dbName(){return this.collection.dbName}get collectionName(){return this.collection.collectionName}get namespace(){return`${this.dbName}.${this.collectionName}`}get readConcern(){}get readPreference(){}get bsonOptions(){return{}}get writeConcern(){}get hint(){}set hint(e){throw new Error("Method not implemented.")}async insertOne(e,n){let o=await this.collection.insertOne(e,p(n));return{acknowledged:o.acknowledged,insertedId:o.insertedId}}async insertMany(e,n){let o=await this.collection.insertMany(e,p(n));return{acknowledged:o.acknowledged,insertedIds:o.insertedIds,insertedCount:o.insertedCount}}bulkWrite(e,n){throw new Error("Method not implemented.")}async updateOne(e,n,o){let i=await this.collection.updateOne(e,n,p(o));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}replaceOne(e,n,o){return this.collection.replaceOne(e,n,p(o))}async updateMany(e,n,o){let i=await this.collection.updateMany(e,n,p(o));return{acknowledged:i.acknowledged,matchedCount:i.modifiedCount,modifiedCount:i.modifiedCount,upsertedCount:i.modifiedCount,upsertedId:null}}async deleteOne(e,n){let o=await this.collection.deleteOne(e,p(n));return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async deleteMany(e,n){let o=await this.collection.deleteMany(e,p(n));return{acknowledged:o.acknowledged,deletedCount:o.deletedCount}}async rename(e,n){return await this.collection.rename(e,p(n)),this}drop(e){return this.collection.drop(p(e))}async findOne(e,n){return this.collection.findOne(e,p(n))}find(e,n){return new D(this.collection.find(e,p(n)))}options(e){throw new Error("Method not implemented.")}isCapped(e){throw new Error("Method not implemented.")}createIndex(e,n){throw new Error("Method not implemented.")}createIndexes(e,n){throw new Error("Method not implemented.")}dropIndex(e,n){throw new Error("Method not implemented.")}dropIndexes(e){throw new Error("Method not implemented.")}listIndexes(e){throw new Error("Method not implemented.")}indexExists(e,n){throw new Error("Method not implemented.")}indexInformation(e){throw new Error("Method not implemented.")}estimatedDocumentCount(e){return this.collection.countDocuments({},p(e))}countDocuments(e,n){return this.collection.countDocuments(e,p(n))}distinct(e,n,o){throw new Error("Method not implemented.")}indexes(e){throw new Error("Method not implemented.")}findOneAndDelete(e,n){return this.collection.findOneAndDelete(e,p(n))}findOneAndReplace(e,n,o){return this.collection.findOneAndReplace(e,n,p(o))}findOneAndUpdate(e,n,o){return this.collection.findOneAndUpdate(e,n,p(o))}aggregate(e,n){throw new Error("Method not implemented.")}watch(e,n){throw new Error("Method not implemented.")}initializeUnorderedBulkOp(e){throw new Error("Method not implemented.")}initializeOrderedBulkOp(e){throw new Error("Method not implemented.")}count(e,n){return this.collection.countDocuments(_nullishCoalesce(e, () => ({})),p(n))}listSearchIndexes(e,n){throw new Error("Method not implemented.")}createSearchIndex(e){throw new Error("Method not implemented.")}createSearchIndexes(e){throw new Error("Method not implemented.")}dropSearchIndex(e){throw new Error("Method not implemented.")}updateSearchIndex(e,n){throw new Error("Method not implemented.")}async createCollection(){await this.collection.createCollection()}async handle(e,n){return this.collection.handle(e.toString(),n)}};var x=class{constructor(e){this.pongoDb=e}get databaseName(){return this.pongoDb.databaseName}collection(e){return new b(this.pongoDb.collection(e))}};var K=class{constructor(e,n={}){this.pongoClient=v(e,n)}async connect(){return await this.pongoClient.connect(),this}async close(){await this.pongoClient.close()}db(e){return new x(this.pongoClient.db(e))}startSession(e){return C()}async withSession(e,n){let o=typeof e=="function"?e:n,i=C();try{return await o(i)}finally{await i.endSession()}}};exports.Collection = b; exports.Db = x; exports.FindCursor = D; exports.MongoClient = K; exports.OperatorMap = S; exports.QueryOperators = M; exports.clientToDbOptions = H; exports.entries = w; exports.getPongoDb = F; exports.hasOperators = _; exports.isOperator = z; exports.isPostgresClientOptions = U; exports.pongoClient = v; exports.pongoCollection = A; exports.pongoSession = C; exports.pongoTransaction = j; exports.postgresDb = N; exports.postgresSQLBuilder = Q;
14
14
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/postgres/client.ts","../src/postgres/postgresCollection.ts","../src/main/typing/entries.ts","../src/postgres/filter/queryOperators.ts","../src/postgres/filter/index.ts","../src/postgres/update/index.ts","../src/main/dbClient.ts","../src/main/pongoClient.ts","../src/mongo/findCursor.ts","../src/mongo/mongoClient.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts"],"names":["endPool","getDatabaseNameOrDefault","getPool","executeSQL","single","sql","format","uuid","entries","obj","key","value","Operators","OperatorMap","isOperator","hasOperators","handleOperator","path","operator","handleIdOperator","buildNestedObject","v","subQuery","subKey","subValue","acc","AND","constructFilterQuery","filter","isRecord","constructComplexFilterQuery","isEquality","nestedKey","val","buildUpdateQuery","update","currentUpdateQuery","op","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","set","unset","k","inc","push","postgresCollection","collectionName","dbName","clientOrPool","execute","SqlFor","collectionSQLBuilder","createCollection","collection","document","_id","documents","rows","doc","result","d","existingDoc","replacement","id","handle","byId","existing","newDoc","row","count","newName","values","filterQuery","updateQuery","targetName","postgresClient","options","connectionString","client","managesPoolLifetime","poolOrClient","name","getDbClient","pongoClient","defaultDbName","dbClients","dbClient","db","FindCursor","callback","docs","Collection","_options","_operations","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_filter","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","MongoClient"],"mappings":"AAAA,OACE,WAAAA,EACA,4BAAAC,EACA,WAAAC,MACK,yBACP,MAAe,KCLf,OAAS,cAAAC,EAAY,UAAAC,EAAQ,OAAAC,MAAqB,yBAClD,MAAe,KACf,OAAOC,MAAY,YACnB,OAAS,MAAMC,MAAY,OCKpB,IAAMC,EAA6BC,GACxC,OAAO,QAAQA,CAAG,EAAE,IAAI,CAAC,CAACC,EAAKC,CAAK,IAAM,CAACD,EAAgBC,CAAK,CAAC,ECTnE,OAAOL,MAAY,YAGZ,IAAMM,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,EAAcJ,GAAgBA,EAAI,WAAW,GAAG,EAEhDK,EAAgBJ,GAC3B,OAAO,KAAKA,CAAK,EAAE,KAAKG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CAQA,kBACE2E,EACAT,EAC2C,CAC3C,MAAM,IAAI,MAAM,yBAAyB,CAC3C,CACA,kBAAkBU,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,CACA,MAAM,OAAOzC,EAAcC,EAA+C,CACxE,OAAO,KAAK,WAAW,OAAOD,EAAG,SAAS,EAAGC,CAAM,CACrD,CACF,EDtfO,IAAMyC,EAAN,KAAS,CACd,YAAoBC,EAAkB,CAAlB,aAAAA,CAAmB,CAEvC,WACE5D,EAGA,CACA,OAAO,IAAI6C,EAAc,KAAK,QAAQ,WAAc7C,CAAc,CAAC,CACrE,CACF,EDbO,IAAM6D,EAAN,KAAkB,CACf,YAER,YACE9B,EACAD,EAAsC,CAAC,EACvC,CACA,KAAK,YAAcO,EAAYN,EAAkBD,CAAO,CAC1D,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAG7B,EAAqB,CACtB,OAAO,IAAI0D,EAAG,KAAK,YAAY,GAAG1D,CAAM,CAAC,CAC3C,CACF","sourcesContent":["import {\n endPool,\n getDatabaseNameOrDefault,\n getPool,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport { type DbClient, type PongoDocument } from '../main';\nimport { postgresCollection } from './postgresCollection';\n\nexport type PongoClientOptions = {\n connectionString: string;\n dbName?: string | undefined;\n client?: pg.PoolClient | undefined;\n};\n\nexport const postgresClient = (options: PongoClientOptions): DbClient => {\n const { connectionString, dbName, client } = options;\n const managesPoolLifetime = !client;\n const poolOrClient =\n client ?? getPool({ connectionString, database: dbName });\n\n return {\n connect: () => Promise.resolve(),\n close: () =>\n managesPoolLifetime\n ? endPool({ connectionString, database: dbName })\n : Promise.resolve(),\n collection: <T extends PongoDocument>(name: string) =>\n postgresCollection<T>(name, {\n dbName: dbName ?? getDatabaseNameOrDefault(connectionString),\n poolOrClient,\n }),\n };\n};\n","import { executeSQL, single, sql, type SQL } from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport format from 'pg-format';\nimport { v4 as uuid } from 'uuid';\nimport {\n type DocumentHandler,\n type PongoCollection,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithId,\n type WithoutId,\n} from '../main';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nexport const postgresCollection = <T extends PongoDocument>(\n collectionName: string,\n {\n dbName,\n poolOrClient: clientOrPool,\n }: { dbName: string; poolOrClient: pg.Pool | pg.PoolClient },\n): PongoCollection<T> => {\n const execute = <T extends pg.QueryResultRow = pg.QueryResultRow>(sql: SQL) =>\n executeSQL<T>(clientOrPool, sql);\n const SqlFor = collectionSQLBuilder(collectionName);\n\n const createCollection = execute(SqlFor.createCollection());\n\n const collection = {\n dbName,\n collectionName,\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 execute(SqlFor.insertOne({ _id, ...document }));\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (documents: T[]): Promise<PongoInsertManyResult> => {\n await createCollection;\n\n const rows = documents.map((doc) => ({\n _id: uuid(),\n ...doc,\n }));\n\n const result = await execute(SqlFor.insertMany(rows));\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.updateOne(filter, update));\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.replaceOne(filter, document));\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<PongoUpdateResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.updateMany(filter, update));\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 result = await execute(SqlFor.deleteOne(filter ?? {}));\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (filter?: PongoFilter<T>): Promise<PongoDeleteResult> => {\n await createCollection;\n\n const result = await execute(SqlFor.deleteMany(filter ?? {}));\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 result = await execute(SqlFor.findOne(filter ?? {}));\n return (result.rows[0]?.data ?? null) as T | null;\n },\n findOneAndDelete: async (filter: PongoFilter<T>): Promise<T | null> => {\n await createCollection;\n\n const existingDoc = await collection.findOne(filter);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n ): Promise<T | null> => {\n await createCollection;\n\n const existingDoc = await collection.findOne(filter);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n ): Promise<T | null> => {\n await createCollection;\n\n const existingDoc = await collection.findOne(filter);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n ): Promise<T | null> => {\n await createCollection;\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = await collection.findOne(byId);\n\n const result = await handle(existing);\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n await collection.insertOne({ ...newDoc, _id: id });\n return newDoc;\n }\n\n if (existing && !result) {\n await collection.deleteOne(byId);\n return null;\n }\n\n if (existing && result) await collection.replaceOne(byId, result);\n\n return result;\n },\n find: async (filter?: PongoFilter<T>): Promise<T[]> => {\n await createCollection;\n\n const result = await execute(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as T);\n },\n countDocuments: async (filter?: PongoFilter<T>): Promise<number> => {\n await createCollection;\n\n const { count } = await single(\n execute<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (): Promise<boolean> => {\n await createCollection;\n const result = await execute(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (newName: string): Promise<PongoCollection<T>> => {\n await createCollection;\n await execute(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n };\n\n return collection;\n};\n\nexport const collectionSQLBuilder = (collectionName: string) => ({\n createCollection: (): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n ),\n insertOne: <T>(document: WithId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: WithId<T>[]): SQL => {\n const values = documents\n .map((doc) => format('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I WHERE %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n filterQuery,\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n\n return sql(\n `UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') WHERE %s`,\n collectionName,\n JSON.stringify(document),\n filterQuery,\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I WHERE %s', collectionName, filterQuery);\n },\n countDocuments: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","import format from 'pg-format';\nimport { entries } from '../../main/typing';\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 if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\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 = 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 handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return format(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return format(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import type { PongoFilter } from '../../main';\nimport { entries } from '../../main/typing';\nimport { Operators, handleOperator, hasOperators } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, 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 { sql, type SQL } from '@event-driven-io/dumbo';\nimport type { $inc, $push, $set, $unset, PongoUpdate } from '../../main';\nimport { entries } from '../../main/typing';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, JSON.stringify(set));\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL =>\n sql(\n '%s - %L',\n currentUpdateQuery,\n Object.keys(unset)\n .map((k) => `{${k}}`)\n .join(', '),\n );\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify([value]),\n );\n }\n return currentUpdateQuery;\n};\n","import { postgresClient, type PongoClientOptions } from '../postgres';\nimport type { PongoCollection, PongoDocument } from './typing/operations';\n\nexport interface DbClient {\n connect(): Promise<void>;\n close(): Promise<void>;\n collection: <T extends PongoDocument>(name: string) => PongoCollection<T>;\n}\n\nexport const getDbClient = (options: PongoClientOptions): DbClient => {\n // This is the place where in the future could come resolution of other database types\n return postgresClient(options);\n};\n","import { getDatabaseNameOrDefault } from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport { getDbClient, type DbClient } from './dbClient';\nimport type { PongoClient, PongoDb } from './typing/operations';\n\nexport const pongoClient = (\n connectionString: string,\n options: { client?: pg.PoolClient } = {},\n): PongoClient => {\n const defaultDbName = getDatabaseNameOrDefault(connectionString);\n const dbClients: Map<string, DbClient> = new Map();\n\n const dbClient = getDbClient({ connectionString, client: options.client });\n dbClients.set(defaultDbName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getDbClient({\n connectionString,\n dbName: dbName,\n client: options.client,\n }),\n )\n .get(dbName)!\n );\n },\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","// src/MongoClientShim.ts\nimport pg from 'pg';\nimport { pongoClient, type PongoClient } from '../main';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(\n connectionString: string,\n options: { client?: pg.PoolClient } = {},\n ) {\n this.pongoClient = pongoClient(connectionString, options);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName?: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n}\n","import {\n Collection as MongoCollection,\n ObjectId,\n type Document,\n} from 'mongodb';\nimport type { DocumentHandler, PongoDb } from '../main';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n collection<T extends Document>(\n collectionName: string,\n ): MongoCollection<T> & {\n handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null>;\n } {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n ObjectId,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type {\n DocumentHandler,\n PongoCollection,\n PongoFilter,\n PongoUpdate,\n} 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 return this.collection.dbName;\n }\n get collectionName(): string {\n return this.collection.collectionName;\n }\n get namespace(): string {\n return `${this.dbName}.${this.collectionName}`;\n }\n get readConcern(): ReadConcern | undefined {\n return undefined;\n }\n get readPreference(): ReadPreference | undefined {\n return undefined;\n }\n get bsonOptions(): BSONSerializeOptions {\n return {};\n }\n get writeConcern(): WriteConcern | undefined {\n return undefined;\n }\n get hint(): Hint | undefined {\n return undefined;\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n _options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(doc as T);\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n async insertMany(\n docs: OptionalUnlessRequiredId<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n const result = await this.collection.insertMany(docs as T[]);\n return {\n acknowledged: result.acknowledged,\n insertedIds: result.insertedIds as unknown as InferIdType<T>[],\n insertedCount: result.insertedCount,\n };\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n filter: Filter<T>,\n document: WithoutId<T>,\n _options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n return this.collection.replaceOne(\n filter as unknown as PongoFilter<T>,\n document,\n );\n }\n async updateMany(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n _options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateMany(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(filter as PongoFilter<T>);\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async deleteMany(\n filter?: Filter<T> | undefined,\n _options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteMany(filter as PongoFilter<T>);\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async rename(\n newName: string,\n _options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n await this.collection.rename(newName);\n\n return this as unknown as Collection<Document>;\n }\n drop(_options?: DropCollectionOptions | undefined): Promise<boolean> {\n return this.collection.drop();\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 return this.collection.countDocuments();\n }\n countDocuments(\n filter?: Filter<T> | undefined,\n _options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(filter as PongoFilter<T>);\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 ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndDelete(\n filter as PongoFilter<T>,\n ) as Promise<WithId<T> | null>;\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: unknown,\n replacement: unknown,\n _options?: unknown,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndReplace(\n filter as PongoFilter<T>,\n replacement as WithoutId<T>,\n ) as Promise<WithId<T> | null>;\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: unknown,\n update: unknown,\n _options?: unknown,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndUpdate(\n filter as PongoFilter<T>,\n update as PongoUpdate<T>,\n ) as Promise<WithId<T> | null>;\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n filter?: Filter<T> | undefined,\n _options?: CountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments((filter as PongoFilter<T>) ?? {});\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n async handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null> {\n return this.collection.handle(id.toString(), handle);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/core/collection/pongoCollection.ts","../src/core/collection/query.ts","../src/core/pongoClient.ts","../src/postgres/dbClient.ts","../src/postgres/sqlBuilder/index.ts","../src/postgres/sqlBuilder/filter/queryOperators.ts","../src/postgres/sqlBuilder/filter/index.ts","../src/postgres/sqlBuilder/update/index.ts","../src/core/pongoDb.ts","../src/core/pongoTransaction.ts","../src/core/pongoSession.ts","../src/core/typing/entries.ts","../src/mongo/findCursor.ts","../src/mongo/mongoDb.ts","../src/mongo/mongoCollection.ts","../src/mongo/mongoClient.ts"],"names":["single","uuid","enlistIntoTransactionIfActive","db","options","transaction","transactionExecutorOrDefault","defaultSqlExecutor","pongoCollection","collectionName","sqlExecutor","SqlFor","command","sql","query","createCollectionPromise","createCollection","collection","document","_id","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","handle","byId","existing","newDoc","row","count","newName","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","NodePostgresConnectorType","getDatabaseNameOrDefault","postgresPool","format","handleOperator","path","operator","handleIdOperator","buildNestedObject","v","subQuery","entries","subKey","subValue","acc","AND","constructFilterQuery","isRecord","constructComplexFilterQuery","isEquality","nestedKey","val","buildUpdateQuery","currentUpdateQuery","op","buildSetQuery","buildUnsetQuery","buildIncQuery","buildPushQuery","set","unset","k","inc","push","postgresSQLBuilder","values","filterQuery","updateQuery","targetName","isPostgresClientOptions","postgresDb","connectionString","dbName","databaseName","pool","getPongoDb","type","pongoTransaction","isCommitted","isRolledBack","error","isActive","assertInActiveTransaction","assertNotInActiveTransaction","pongoSession","explicit","defaultTransactionOptions","hasEnded","startTransaction","commitTransaction","abortTransaction","session","fn","pongoClient","dbClients","dbClient","clientToDbOptions","callback","obj","FindCursor","docs","toCollectionOperationOptions","Collection","_operations","_options","_indexSpec","_indexSpecs","_indexName","_indexes","_key","_filter","_pipeline","_name","_description","_descriptions","_definition","Db","pongoDb","MongoClient","optionsOrExecutor","executor"],"mappings":"AAAA,OACE,UAAAA,MAKK,yBACP,OAAS,MAAMC,MAAY,OAwB3B,IAAMC,EAAgC,MAGpCC,EACAC,IACwC,CACxC,IAAMC,EAAcD,GAAS,SAAS,YAEtC,MAAI,CAACC,GAAe,CAACA,EAAY,SAAiB,KAE3C,MAAMA,EAAY,eAAeF,CAAE,CAC5C,EAEMG,EAA+B,MAGnCH,EACAC,EACAG,KAE4B,MAAML,EAA8BC,EAAIC,CAAO,IAC/C,SAAWG,EAG5BC,EAAkB,CAG7B,CACA,GAAAL,EACA,eAAAM,EACA,YAAAC,EACA,WAAYC,CACd,IAAiE,CAC/D,IAAMC,EAAU,MAAOC,EAAUT,KAC9B,MAAME,EAA6BH,EAAIC,EAASM,CAA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EZO,IAAM0H,EAAN,KAAkB,CACf,YAER,YAAY/C,EAA0BhF,EAA8B,CAAC,EAAG,CACtE,KAAK,YAAcsG,EAAYtB,EAAkBhF,CAAO,CAC1D,CAEA,MAAM,SAAU,CACd,aAAM,KAAK,YAAY,QAAQ,EACxB,IACT,CAEA,MAAM,OAAQ,CACZ,MAAM,KAAK,YAAY,MAAM,CAC/B,CAEA,GAAGiF,EAAqB,CACtB,OAAO,IAAI4C,EAAG,KAAK,YAAY,GAAG5C,CAAM,CAAC,CAC3C,CACA,aAAagC,EAAgD,CAC3D,OAAOpB,EAAa,CACtB,CASA,MAAM,YACJmC,EACAC,EACY,CACZ,IAAMvB,EACJ,OAAOsB,GAAsB,WAAaA,EAAoBC,EAE1D7B,EAAUP,EAAa,EAE7B,GAAI,CACF,OAAO,MAAMa,EAASN,CAAO,CAC/B,QAAE,CACA,MAAMA,EAAQ,WAAW,CAC3B,CACF,CACF","sourcesContent":["import {\n single,\n type DatabaseTransaction,\n type QueryResultRow,\n type SQL,\n type SQLExecutor,\n} from '@event-driven-io/dumbo';\nimport { v4 as uuid } from 'uuid';\nimport {\n type CollectionOperationOptions,\n type DocumentHandler,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateResult,\n type WithId,\n type WithoutId,\n} from '..';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n sqlExecutor: SQLExecutor;\n sqlBuilder: PongoCollectionSQLBuilder;\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nconst transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n sqlExecutor,\n sqlBuilder: SqlFor,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const command = async (sql: SQL, options?: CollectionOperationOptions) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).command(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n const createCollectionPromise = command(SqlFor.createCollection());\n const createCollection = (options?: CollectionOperationOptions) =>\n options?.session\n ? command(SqlFor.createCollection(), options)\n : createCollectionPromise;\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: T,\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertOneResult> => {\n await createCollection(options);\n\n const _id = uuid();\n\n const result = await command(\n SqlFor.insertOne({ _id, ...document }),\n options,\n );\n\n return result.rowCount\n ? { insertedId: _id, acknowledged: true }\n : { insertedId: null, acknowledged: false };\n },\n insertMany: async (\n documents: T[],\n options?: CollectionOperationOptions,\n ): Promise<PongoInsertManyResult> => {\n await createCollection(options);\n\n const rows = documents.map((doc) => ({\n _id: uuid(),\n ...doc,\n }));\n\n const result = await command(SqlFor.insertMany(rows), options);\n\n return {\n acknowledged: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: rows.map((d) => d._id),\n };\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await createCollection(options);\n\n const result = await command(SqlFor.updateOne(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await createCollection(options);\n\n const result = await command(\n SqlFor.replaceOne(filter, document),\n options,\n );\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoUpdateResult> => {\n await createCollection(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n return result.rowCount\n ? { acknowledged: true, modifiedCount: result.rowCount }\n : { acknowledged: false, modifiedCount: 0 };\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await createCollection(options);\n\n const result = await command(SqlFor.deleteOne(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<PongoDeleteResult> => {\n await createCollection(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n return result.rowCount\n ? { acknowledged: true, deletedCount: result.rowCount }\n : { acknowledged: false, deletedCount: 0 };\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await createCollection(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as T | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await createCollection(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await createCollection(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await createCollection(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: CollectionOperationOptions,\n ): Promise<T | null> => {\n await createCollection(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = await collection.findOne(byId, options);\n\n const result = await handle(existing);\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n await collection.insertOne({ ...newDoc, _id: id }, options);\n return newDoc;\n }\n\n if (existing && !result) {\n await collection.deleteOne(byId, options);\n return null;\n }\n\n if (existing && result)\n await collection.replaceOne(byId, result, options);\n\n return result;\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<T[]> => {\n await createCollection(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as T);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await createCollection(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await createCollection(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await createCollection(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n };\n\n return collection;\n};\n\nexport type PongoCollectionSQLBuilder = {\n createCollection: () => SQL;\n insertOne: <T>(document: WithId<T>) => SQL;\n insertMany: <T>(documents: WithId<T>[]) => SQL;\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>) => SQL;\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>) => SQL;\n deleteOne: <T>(filter: PongoFilter<T>) => SQL;\n deleteMany: <T>(filter: PongoFilter<T>) => SQL;\n findOne: <T>(filter: PongoFilter<T>) => SQL;\n find: <T>(filter: PongoFilter<T>) => SQL;\n countDocuments: <T>(filter: PongoFilter<T>) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","import { NodePostgresConnectorType } from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport type { PongoClient, PongoDb, PongoSession } from './typing/operations';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n // eslint-disable-next-line @typescript-eslint/ban-types\n | {};\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n };\n\nexport type PongoClientOptions =\n | PooledPongoClientOptions\n | NotPooledPongoOptions;\n\nexport const pongoClient = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions = {},\n): PongoClient => {\n const dbClients: Map<string, PongoDb> = new Map();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T = unknown>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return pongoClient;\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n postgresPool,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from '@event-driven-io/dumbo';\nimport {\n pongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector> &\n PostgresPoolOptions;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = postgresPool(options);\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n sqlExecutor: pool.execute,\n sqlBuilder: postgresSQLBuilder(collectionName),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n };\n\n return db;\n};\n","import { sql, type SQL } from '@event-driven-io/dumbo';\nimport format from 'pg-format';\nimport {\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type WithId,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n createCollection: (): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n ),\n insertOne: <T>(document: WithId<T>): SQL =>\n sql(\n 'INSERT INTO %I (_id, data) VALUES (%L, %L)',\n collectionName,\n document._id,\n JSON.stringify(document),\n ),\n insertMany: <T>(documents: WithId<T>[]): SQL => {\n const values = documents\n .map((doc) => format('(%L, %L)', doc._id, JSON.stringify(doc)))\n .join(', ');\n return sql('INSERT INTO %I (_id, data) VALUES %s', collectionName, values);\n },\n updateOne: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n `WITH cte AS (\n SELECT _id FROM %I WHERE %s LIMIT 1\n )\n UPDATE %I SET data = %s FROM cte WHERE %I._id = cte._id`,\n collectionName,\n filterQuery,\n collectionName,\n updateQuery,\n collectionName,\n );\n },\n replaceOne: <T>(filter: PongoFilter<T>, document: WithoutId<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n\n return sql(\n `UPDATE %I SET data = %L || jsonb_build_object('_id', data->>'_id') WHERE %s`,\n collectionName,\n JSON.stringify(document),\n filterQuery,\n );\n },\n updateMany: <T>(filter: PongoFilter<T>, update: PongoUpdate<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n const updateQuery = buildUpdateQuery(update);\n\n return sql(\n 'UPDATE %I SET data = %s WHERE %s',\n collectionName,\n updateQuery,\n filterQuery,\n );\n },\n deleteOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n deleteMany: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('DELETE FROM %I WHERE %s', collectionName, filterQuery);\n },\n findOne: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT data FROM %I WHERE %s LIMIT 1',\n collectionName,\n filterQuery,\n );\n },\n find: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql('SELECT data FROM %I WHERE %s', collectionName, filterQuery);\n },\n countDocuments: <T>(filter: PongoFilter<T>): SQL => {\n const filterQuery = constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I WHERE %s',\n collectionName,\n filterQuery,\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n","import format from 'pg-format';\nimport { entries, OperatorMap } from '../../../core';\n\nexport const handleOperator = (\n path: string,\n operator: string,\n value: unknown,\n): string => {\n if (path === '_id') {\n return handleIdOperator(operator, value);\n }\n\n switch (operator) {\n case '$eq':\n return 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 = 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 handleIdOperator = (operator: string, value: unknown): string => {\n switch (operator) {\n case '$eq':\n return format(`_id = %L`, value);\n case '$gt':\n case '$gte':\n case '$lt':\n case '$lte':\n case '$ne':\n return format(`_id ${OperatorMap[operator]} %L`, value);\n case '$in':\n return format(\n `_id IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n case '$nin':\n return format(\n `_id NOT IN (%s)`,\n (value as unknown[]).map((v) => format('%L', v)).join(', '),\n );\n default:\n throw new Error(`Unsupported operator: ${operator}`);\n }\n};\n\nconst buildNestedObject = (\n path: string,\n value: unknown,\n): Record<string, unknown> =>\n path\n .split('.')\n .reverse()\n .reduce((acc, key) => ({ [key]: acc }), value as Record<string, unknown>);\n","import {\n entries,\n hasOperators,\n QueryOperators,\n type PongoFilter,\n} from '../../../core';\nimport { handleOperator } from './queryOperators';\n\nexport * from './queryOperators';\n\nconst AND = 'AND';\n\nexport const constructFilterQuery = <T>(filter: PongoFilter<T>): string =>\n Object.entries(filter)\n .map(([key, value]) =>\n isRecord(value)\n ? constructComplexFilterQuery(key, value)\n : handleOperator(key, '$eq', value),\n )\n .join(` ${AND} `);\n\nconst constructComplexFilterQuery = (\n key: string,\n value: Record<string, unknown>,\n): string => {\n const isEquality = !hasOperators(value);\n\n return entries(value)\n .map(\n ([nestedKey, val]) =>\n isEquality\n ? handleOperator(`${key}.${nestedKey}`, QueryOperators.$eq, val) // regular value\n : handleOperator(key, nestedKey, val), // operator\n )\n .join(` ${AND} `);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n","import { sql, type SQL } from '@event-driven-io/dumbo';\nimport {\n entries,\n type $inc,\n type $push,\n type $set,\n type $unset,\n type PongoUpdate,\n} from '../../../core';\n\nexport const buildUpdateQuery = <T>(update: PongoUpdate<T>): SQL =>\n entries(update).reduce((currentUpdateQuery, [op, value]) => {\n switch (op) {\n case '$set':\n return buildSetQuery(value, currentUpdateQuery);\n case '$unset':\n return buildUnsetQuery(value, currentUpdateQuery);\n case '$inc':\n return buildIncQuery(value, currentUpdateQuery);\n case '$push':\n return buildPushQuery(value, currentUpdateQuery);\n default:\n return currentUpdateQuery;\n }\n }, sql('data'));\n\nexport const buildSetQuery = <T>(set: $set<T>, currentUpdateQuery: SQL): SQL =>\n sql('%s || %L::jsonb', currentUpdateQuery, JSON.stringify(set));\n\nexport const buildUnsetQuery = <T>(\n unset: $unset<T>,\n currentUpdateQuery: SQL,\n): SQL =>\n sql(\n '%s - %L',\n currentUpdateQuery,\n Object.keys(unset)\n .map((k) => `{${k}}`)\n .join(', '),\n );\n\nexport const buildIncQuery = <T>(\n inc: $inc<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(inc)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', to_jsonb((data->>'%s')::numeric + %L), true)\",\n currentUpdateQuery,\n key,\n key,\n value,\n );\n }\n return currentUpdateQuery;\n};\n\nexport const buildPushQuery = <T>(\n push: $push<T>,\n currentUpdateQuery: SQL,\n): SQL => {\n for (const [key, value] of Object.entries(push)) {\n currentUpdateQuery = sql(\n \"jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)\",\n currentUpdateQuery,\n key,\n key,\n JSON.stringify([value]),\n );\n }\n return currentUpdateQuery;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n};\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n","import type { DatabaseTransaction } from '@event-driven-io/dumbo';\nimport type {\n PongoDb,\n PongoDbTransaction,\n PongoTransactionOptions,\n} from './typing';\n\nexport const pongoTransaction = (\n options: PongoTransactionOptions,\n): PongoDbTransaction => {\n let isCommitted = false;\n let isRolledBack = false;\n let databaseName: string | null = null;\n let transaction: DatabaseTransaction | null = null;\n\n return {\n enlistDatabase: async (db: PongoDb): Promise<DatabaseTransaction> => {\n if (transaction && databaseName !== db.databaseName)\n throw new Error(\n \"There's already other database assigned to transaction\",\n );\n\n if (transaction && databaseName === db.databaseName) return transaction;\n\n databaseName = db.databaseName;\n transaction = db.transaction();\n await transaction.begin();\n\n return transaction;\n },\n commit: async () => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) return;\n if (isRolledBack) throw new Error('Transaction is not active!');\n\n isCommitted = true;\n\n await transaction.commit();\n\n transaction = null;\n },\n rollback: async (error?: unknown) => {\n if (!transaction) throw new Error('No database transaction started!');\n if (isCommitted) throw new Error('Cannot rollback commited transaction!');\n if (isRolledBack) return;\n\n isRolledBack = true;\n\n await transaction.rollback(error);\n\n transaction = null;\n },\n databaseName,\n isStarting: false,\n isCommitted,\n get isActive() {\n return !isCommitted && !isRolledBack;\n },\n get sqlExecutor() {\n if (transaction === null)\n throw new Error('No database transaction was started');\n\n return transaction.execute;\n },\n options,\n };\n};\n","import { pongoTransaction } from './pongoTransaction';\nimport type {\n PongoDbTransaction,\n PongoSession,\n PongoTransactionOptions,\n} from './typing';\n\nexport type PongoSessionOptions = {\n explicit?: boolean;\n defaultTransactionOptions: PongoTransactionOptions;\n};\n\nconst isActive = (\n transaction: PongoDbTransaction | null,\n): transaction is PongoDbTransaction => transaction?.isActive === true;\n\nfunction assertInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is PongoDbTransaction {\n if (!isActive(transaction)) throw new Error('No active transaction exists!');\n}\n\nfunction assertNotInActiveTransaction(\n transaction: PongoDbTransaction | null,\n): asserts transaction is null {\n if (isActive(transaction))\n throw new Error('Active transaction already exists!');\n}\n\nexport const pongoSession = (options?: PongoSessionOptions): PongoSession => {\n const explicit = options?.explicit === true;\n const defaultTransactionOptions: PongoTransactionOptions =\n options?.defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n };\n\n let transaction: PongoDbTransaction | null = null;\n let hasEnded = false;\n\n const startTransaction = (options?: PongoTransactionOptions) => {\n assertNotInActiveTransaction(transaction);\n\n transaction = pongoTransaction(options ?? defaultTransactionOptions);\n };\n const commitTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.commit();\n };\n const abortTransaction = async () => {\n assertInActiveTransaction(transaction);\n\n await transaction.rollback();\n };\n\n const endSession = async (): Promise<void> => {\n if (hasEnded) return;\n hasEnded = true;\n\n if (isActive(transaction)) await transaction.rollback();\n };\n\n const session = {\n get hasEnded() {\n return hasEnded;\n },\n explicit,\n defaultTransactionOptions: defaultTransactionOptions ?? {\n get snapshotEnabled() {\n return false;\n },\n },\n get transaction() {\n return transaction;\n },\n get snapshotEnabled() {\n return defaultTransactionOptions.snapshotEnabled;\n },\n endSession,\n incrementTransactionNumber: () => {},\n inTransaction: () => isActive(transaction),\n startTransaction,\n commitTransaction,\n abortTransaction,\n withTransaction: async <T = unknown>(\n fn: (session: PongoSession) => Promise<T>,\n options?: PongoTransactionOptions,\n ): Promise<T> => {\n startTransaction(options);\n\n try {\n const result = await fn(session);\n await commitTransaction();\n return result;\n } catch (error) {\n await abortTransaction();\n throw error;\n }\n },\n };\n\n return session;\n};\n","type Entry<T> = {\n [K in keyof Required<T>]: [K, Required<T>[K]];\n}[keyof Required<T>];\n\ntype IterableEntry<T> = Entry<T> & {\n [Symbol.iterator](): Iterator<Entry<T>>;\n};\n\nexport const entries = <T extends object>(obj: T): IterableEntry<T>[] =>\n Object.entries(obj).map(([key, value]) => [key as keyof T, value]);\n\nexport type NonPartial<T> = { [K in keyof Required<T>]: T[K] };\n","export class FindCursor<T> {\n private findDocumentsPromise: Promise<T[]>;\n private documents: T[] | null = null;\n private index: number = 0;\n\n constructor(documents: Promise<T[]>) {\n this.findDocumentsPromise = documents;\n }\n\n async toArray(): Promise<T[]> {\n return this.findDocuments();\n }\n\n async forEach(callback: (doc: T) => void): Promise<void> {\n const docs = await this.findDocuments();\n\n for (const doc of docs) {\n callback(doc);\n }\n return Promise.resolve();\n }\n\n hasNext(): boolean {\n if (this.documents === null) throw Error('Error while fetching documents');\n return this.index < this.documents.length;\n }\n\n async next(): Promise<T | null> {\n const docs = await this.findDocuments();\n return this.hasNext() ? docs[this.index++] ?? null : null;\n }\n\n private async findDocuments(): Promise<T[]> {\n this.documents = await this.findDocumentsPromise;\n return this.documents;\n }\n}\n","import {\n Collection as MongoCollection,\n ObjectId,\n type Document,\n} from 'mongodb';\nimport type { DocumentHandler, PongoDb } from '../core';\nimport { Collection } from './mongoCollection';\n\nexport class Db {\n constructor(private pongoDb: PongoDb) {}\n\n get databaseName(): string {\n return this.pongoDb.databaseName;\n }\n\n collection<T extends Document>(\n collectionName: string,\n ): MongoCollection<T> & {\n handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null>;\n } {\n return new Collection<T>(this.pongoDb.collection<T>(collectionName));\n }\n}\n","import type {\n AbstractCursorOptions,\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BSONSerializeOptions,\n BulkWriteOptions,\n BulkWriteResult,\n ChangeStream,\n ChangeStreamDocument,\n ChangeStreamOptions,\n CommandOperationOptions,\n CountDocumentsOptions,\n CountOptions,\n CreateIndexesOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n DropCollectionOptions,\n EnhancedOmit,\n EstimatedDocumentCountOptions,\n Filter,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n FindOptions,\n Flatten,\n Hint,\n IndexDescription,\n IndexDescriptionCompact,\n IndexDescriptionInfo,\n IndexInformationOptions,\n IndexSpecification,\n InferIdType,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListSearchIndexesCursor,\n ListSearchIndexesOptions,\n ModifyResult,\n Collection as MongoCollection,\n FindCursor as MongoFindCursor,\n ObjectId,\n OperationOptions,\n OptionalUnlessRequiredId,\n OrderedBulkOperation,\n ReadConcern,\n ReadPreference,\n RenameOptions,\n ReplaceOptions,\n SearchIndexDescription,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n WithId,\n WithoutId,\n WriteConcern,\n} from 'mongodb';\nimport type { Key } from 'readline';\nimport type {\n CollectionOperationOptions,\n DocumentHandler,\n PongoCollection,\n PongoFilter,\n PongoSession,\n PongoUpdate,\n} from '../core';\nimport { FindCursor } from './findCursor';\n\nconst toCollectionOperationOptions = (\n options: OperationOptions | undefined,\n): CollectionOperationOptions | undefined =>\n options?.session\n ? { session: options.session as unknown as PongoSession }\n : undefined;\n\nexport class Collection<T extends Document> implements MongoCollection<T> {\n private collection: PongoCollection<T>;\n\n constructor(collection: PongoCollection<T>) {\n this.collection = collection;\n }\n get dbName(): string {\n return this.collection.dbName;\n }\n get collectionName(): string {\n return this.collection.collectionName;\n }\n get namespace(): string {\n return `${this.dbName}.${this.collectionName}`;\n }\n get readConcern(): ReadConcern | undefined {\n return undefined;\n }\n get readPreference(): ReadPreference | undefined {\n return undefined;\n }\n get bsonOptions(): BSONSerializeOptions {\n return {};\n }\n get writeConcern(): WriteConcern | undefined {\n return undefined;\n }\n get hint(): Hint | undefined {\n return undefined;\n }\n set hint(v: Hint | undefined) {\n throw new Error('Method not implemented.');\n }\n async insertOne(\n doc: OptionalUnlessRequiredId<T>,\n options?: InsertOneOptions | undefined,\n ): Promise<InsertOneResult<T>> {\n const result = await this.collection.insertOne(\n doc as T,\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedId: result.insertedId as unknown as InferIdType<T>,\n };\n }\n async insertMany(\n docs: OptionalUnlessRequiredId<T>[],\n options?: BulkWriteOptions | undefined,\n ): Promise<InsertManyResult<T>> {\n const result = await this.collection.insertMany(\n docs as T[],\n toCollectionOperationOptions(options),\n );\n return {\n acknowledged: result.acknowledged,\n insertedIds: result.insertedIds as unknown as InferIdType<T>[],\n insertedCount: result.insertedCount,\n };\n }\n bulkWrite(\n _operations: AnyBulkWriteOperation<T>[],\n _options?: BulkWriteOptions | undefined,\n ): Promise<BulkWriteResult> {\n throw new Error('Method not implemented.');\n }\n async updateOne(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateOne(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n replaceOne(\n filter: Filter<T>,\n document: WithoutId<T>,\n options?: ReplaceOptions | undefined,\n ): Promise<Document | UpdateResult<T>> {\n return this.collection.replaceOne(\n filter as unknown as PongoFilter<T>,\n document,\n toCollectionOperationOptions(options),\n );\n }\n async updateMany(\n filter: Filter<T>,\n update: Document[] | UpdateFilter<T>,\n options?: UpdateOptions | undefined,\n ): Promise<UpdateResult<T>> {\n const result = await this.collection.updateMany(\n filter as unknown as PongoFilter<T>,\n update as unknown as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n matchedCount: result.modifiedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.modifiedCount,\n upsertedId: null,\n };\n }\n async deleteOne(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async deleteMany(\n filter?: Filter<T> | undefined,\n options?: DeleteOptions | undefined,\n ): Promise<DeleteResult> {\n const result = await this.collection.deleteMany(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n\n return {\n acknowledged: result.acknowledged,\n deletedCount: result.deletedCount,\n };\n }\n async rename(\n newName: string,\n options?: RenameOptions | undefined,\n ): Promise<Collection<Document>> {\n await this.collection.rename(\n newName,\n toCollectionOperationOptions(options),\n );\n\n return this as unknown as Collection<Document>;\n }\n drop(options?: DropCollectionOptions | undefined): Promise<boolean> {\n return this.collection.drop(toCollectionOperationOptions(options));\n }\n findOne(): Promise<WithId<T> | null>;\n findOne(filter: Filter<T>): Promise<WithId<T> | null>;\n findOne(\n filter: Filter<T>,\n options: FindOptions<Document>,\n ): Promise<WithId<T> | null>;\n findOne<TS = T>(): Promise<TS | null>;\n findOne<TS = T>(filter: Filter<TS>): Promise<TS | null>;\n findOne<TS = T>(\n filter: Filter<TS>,\n options?: FindOptions<Document> | undefined,\n ): Promise<TS | null>;\n async findOne(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): Promise<import('mongodb').WithId<T> | T | null> {\n return this.collection.findOne(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n find(): MongoFindCursor<WithId<T>>;\n find(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>>;\n find<T extends Document>(\n filter: Filter<T>,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<T>;\n find(\n filter?: unknown,\n options?: FindOptions<Document> | undefined,\n ): MongoFindCursor<WithId<T>> | MongoFindCursor<T> {\n return new FindCursor(\n this.collection.find(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ),\n ) as unknown as MongoFindCursor<T>;\n }\n options(_options?: OperationOptions | undefined): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n isCapped(_options?: OperationOptions | undefined): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n createIndex(\n _indexSpec: IndexSpecification,\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createIndexes(\n _indexSpecs: IndexDescription[],\n _options?: CreateIndexesOptions | undefined,\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropIndex(\n _indexName: string,\n _options?: CommandOperationOptions | undefined,\n ): Promise<Document> {\n throw new Error('Method not implemented.');\n }\n dropIndexes(\n _options?: CommandOperationOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n listIndexes(_options?: AbstractCursorOptions | undefined): ListIndexesCursor {\n throw new Error('Method not implemented.');\n }\n indexExists(\n _indexes: string | string[],\n _options?: AbstractCursorOptions | undefined,\n ): Promise<boolean> {\n throw new Error('Method not implemented.');\n }\n indexInformation(\n options: IndexInformationOptions & { full: true },\n ): Promise<IndexDescriptionInfo[]>;\n indexInformation(\n options: IndexInformationOptions & { full?: false | undefined },\n ): Promise<IndexDescriptionCompact>;\n indexInformation(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexInformation(): Promise<IndexDescriptionCompact>;\n indexInformation(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n estimatedDocumentCount(\n options?: EstimatedDocumentCountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n {},\n toCollectionOperationOptions(options),\n );\n }\n countDocuments(\n filter?: Filter<T> | undefined,\n options?: CountDocumentsOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n );\n }\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n distinct<Key extends '_id' | keyof EnhancedOmit<T, '_id'>>(\n key: Key,\n filter: Filter<T>,\n options: CommandOperationOptions,\n ): Promise<Flatten<WithId<T>[Key]>[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string): Promise<any[]>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n distinct(key: string, filter: Filter<T>): Promise<any[]>;\n distinct(\n key: string,\n filter: Filter<T>,\n options: CommandOperationOptions, // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any[]>;\n distinct(\n _key: unknown,\n _filter?: unknown,\n _options?: unknown,\n ): // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Promise<any[]>\n | Promise<import('mongodb').Flatten<import('mongodb').WithId<T>[Key]>[]> {\n throw new Error('Method not implemented.');\n }\n indexes(\n options: IndexInformationOptions & { full?: true | undefined },\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n options: IndexInformationOptions & { full: false },\n ): Promise<IndexDescriptionCompact>;\n indexes(\n options: IndexInformationOptions,\n ): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;\n indexes(\n options?: AbstractCursorOptions | undefined,\n ): Promise<IndexDescriptionInfo[]>;\n indexes(\n _options?: unknown,\n ):\n | Promise<import('mongodb').IndexDescriptionInfo[]>\n | Promise<import('mongodb').IndexDescriptionCompact>\n | Promise<\n | import('mongodb').IndexDescriptionCompact\n | import('mongodb').IndexDescriptionInfo[]\n > {\n throw new Error('Method not implemented.');\n }\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: Filter<T>,\n options: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null>;\n findOneAndDelete(filter: Filter<T>): Promise<WithId<T> | null>;\n findOneAndDelete(\n filter: unknown,\n options?: FindOneAndDeleteOptions,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndDelete(\n filter as PongoFilter<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n options: FindOneAndReplaceOptions,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: Filter<T>,\n replacement: WithoutId<T>,\n ): Promise<WithId<T> | null>;\n findOneAndReplace(\n filter: unknown,\n replacement: unknown,\n options?: FindOneAndReplaceOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndReplace(\n filter as PongoFilter<T>,\n replacement as WithoutId<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: true },\n ): Promise<ModifyResult<T>>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions & { includeResultMetadata: false },\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n options: FindOneAndUpdateOptions,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: Filter<T>,\n update: UpdateFilter<T>,\n ): Promise<WithId<T> | null>;\n findOneAndUpdate(\n filter: unknown,\n update: unknown,\n options?: FindOneAndUpdateOptions | undefined,\n ): Promise<WithId<T> | null | ModifyResult<T>> {\n return this.collection.findOneAndUpdate(\n filter as PongoFilter<T>,\n update as PongoUpdate<T>,\n toCollectionOperationOptions(options),\n ) as Promise<WithId<T> | null>;\n }\n aggregate<T extends Document = Document>(\n _pipeline?: Document[] | undefined,\n _options?: AggregateOptions | undefined,\n ): AggregationCursor<T> {\n throw new Error('Method not implemented.');\n }\n watch<\n TLocal extends Document = T,\n TChange extends Document = ChangeStreamDocument<TLocal>,\n >(\n _pipeline?: Document[] | undefined,\n _options?: ChangeStreamOptions | undefined,\n ): ChangeStream<TLocal, TChange> {\n throw new Error('Method not implemented.');\n }\n initializeUnorderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): UnorderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n initializeOrderedBulkOp(\n _options?: BulkWriteOptions | undefined,\n ): OrderedBulkOperation {\n throw new Error('Method not implemented.');\n }\n count(\n filter?: Filter<T> | undefined,\n options?: CountOptions | undefined,\n ): Promise<number> {\n return this.collection.countDocuments(\n (filter as PongoFilter<T>) ?? {},\n toCollectionOperationOptions(options),\n );\n }\n listSearchIndexes(\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n name: string,\n options?: ListSearchIndexesOptions | undefined,\n ): ListSearchIndexesCursor;\n listSearchIndexes(\n _name?: unknown,\n _options?: unknown,\n ): import('mongodb').ListSearchIndexesCursor {\n throw new Error('Method not implemented.');\n }\n createSearchIndex(_description: SearchIndexDescription): Promise<string> {\n throw new Error('Method not implemented.');\n }\n createSearchIndexes(\n _descriptions: SearchIndexDescription[],\n ): Promise<string[]> {\n throw new Error('Method not implemented.');\n }\n dropSearchIndex(_name: string): Promise<void> {\n throw new Error('Method not implemented.');\n }\n updateSearchIndex(_name: string, _definition: Document): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async createCollection(): Promise<void> {\n await this.collection.createCollection();\n }\n async handle(id: ObjectId, handle: DocumentHandler<T>): Promise<T | null> {\n return this.collection.handle(id.toString(), handle);\n }\n}\n","import type { ClientSessionOptions } from 'http2';\nimport type { ClientSession, WithSessionCallback } from 'mongodb';\nimport {\n pongoClient,\n pongoSession,\n type PongoClient,\n type PongoClientOptions,\n} from '../core';\nimport { Db } from './mongoDb';\n\nexport class MongoClient {\n private pongoClient: PongoClient;\n\n constructor(connectionString: string, options: PongoClientOptions = {}) {\n this.pongoClient = pongoClient(connectionString, options);\n }\n\n async connect() {\n await this.pongoClient.connect();\n return this;\n }\n\n async close() {\n await this.pongoClient.close();\n }\n\n db(dbName?: string): Db {\n return new Db(this.pongoClient.db(dbName));\n }\n startSession(_options?: ClientSessionOptions): ClientSession {\n return pongoSession() as unknown as ClientSession;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withSession<T = any>(_executor: WithSessionCallback<T>): Promise<T>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withSession<T = any>(\n _options: ClientSessionOptions,\n _executor: WithSessionCallback<T>,\n ): Promise<T>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async withSession<T = any>(\n optionsOrExecutor: ClientSessionOptions | WithSessionCallback<T>,\n executor?: WithSessionCallback<T>,\n ): Promise<T> {\n const callback =\n typeof optionsOrExecutor === 'function' ? optionsOrExecutor : executor!;\n\n const session = pongoSession() as unknown as ClientSession;\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n }\n}\n"]}