@event-driven-io/pongo 0.15.0 → 0.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-7GQ5BP22.cjs → chunk-2FFAJEOI.cjs} +7 -7
- package/dist/chunk-2FFAJEOI.cjs.map +1 -0
- package/dist/{chunk-QO7XUM5F.js → chunk-AG3WMJNZ.js} +7 -7
- package/dist/chunk-AG3WMJNZ.js.map +1 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{pongoClient-BY509WFi.d.cts → pongoClient-DkAUSd1N.d.cts} +15 -13
- package/dist/{pongoClient-BY509WFi.d.ts → pongoClient-DkAUSd1N.d.ts} +15 -13
- package/dist/shim.cjs +1 -1
- package/dist/shim.cjs.map +1 -1
- package/dist/shim.d.cts +1 -1
- package/dist/shim.d.ts +1 -1
- package/dist/shim.js +1 -1
- package/dist/shim.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-7GQ5BP22.cjs.map +0 -1
- package/dist/chunk-QO7XUM5F.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var X=e=>e.connectorType===_dumbo.NodePostgresConnectorType,B= exports.d =e=>{let{connectionString:n,dbName:t}=e,o=_nullishCoalesce(t, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, n))),i=_dumbo.dumbo.call(void 0, {connectionString:n,...e.connectionOptions}),r=new Map,d={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collection:g=>K({collectionName:g,db:d,pool:i,sqlBuilder:W(g),...e.schema?e.schema:{},...e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:g=>i.withTransaction(g),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongoDb",{components:[...r.values()].map(g=>g.schema.component)})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, i,[...r.values()].flatMap(g=>g.schema.component.migrations({connector:"PostgreSQL:pg"})))}},p=_optionalChain([e, 'optionalAccess', _2 => _2.schema, 'optionalAccess', _3 => _3.definition, 'optionalAccess', _4 => _4.dbs]);if(p){let g=P(p).map(S=>S[1]).find(S=>S.name===t||S.name===o);if(g)return G(d,g,r)}return d},je= exports.e =e=>{let n=e.length>0&&typeof e[0]=="string"?e.map(t=>z(t)):e;return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:db",{components:n})};var Oe=async(e,n)=>{let t=_optionalChain([n, 'optionalAccess', _5 => _5.session, 'optionalAccess', _6 => _6.transaction]);return!t||!t.isActive?null:await t.enlistDatabase(e)},J=async(e,n,t)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await Oe(e,n)), 'optionalAccess', async _7 => _7.execute]), async () => (t)),K= exports.f =({db:e,collectionName:n,pool:t,sqlBuilder:o,schema:i,errors:r})=>{let d=t.execute,p=async(s,a)=>(await J(e,a,d)).command(s),g=async(s,a)=>(await J(e,a,d)).query(s),S=_optionalChain([i, 'optionalAccess', _8 => _8.autoMigration])!=="None",E=s=>(S=!1,_optionalChain([s, 'optionalAccess', _9 => _9.session])?p(o.createCollection(),s):p(o.createCollection())),u=s=>S?E(s):Promise.resolve(),m={dbName:e.databaseName,collectionName:n,createCollection:async s=>{await E(s)},insertOne:async(s,a)=>{await u(a);let c=_nullishCoalesce(s._id, () => (_uuid.v4.call(void 0, ))),l=_nullishCoalesce(s._version, () => (1n)),R=(await _asyncNullishCoalesce((await p(o.insertOne({...s,_id:c,_version:l}),a)).rowCount, async () => (0)))>0;return C({successful:R,insertedId:R?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:n,errors:r})},insertMany:async(s,a)=>{await u(a);let c=s.map(x=>({...x,_id:_nullishCoalesce(x._id, () => (_uuid.v4.call(void 0, ))),_version:_nullishCoalesce(x._version, () => (1n))})),l=await p(o.insertMany(c),a);return C({successful:l.rowCount===c.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:n,errors:r})},updateOne:async(s,a,c)=>{await u(c);let l=await p(o.updateOne(s,a,c),c);return C({successful:l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"updateOne",collectionName:n,errors:r})},replaceOne:async(s,a,c)=>{await u(c);let l=await p(o.replaceOne(s,a,c),c);return C({successful:l.rows[0].modified>0,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"replaceOne",collectionName:n,errors:r})},updateMany:async(s,a,c)=>{await u(c);let l=await p(o.updateMany(s,a),c);return C({successful:!0,modifiedCount:_nullishCoalesce(l.rowCount, () => (0)),matchedCount:_nullishCoalesce(l.rowCount, () => (0))},{operationName:"updateMany",collectionName:n,errors:r})},deleteOne:async(s,a)=>{await u(a);let c=await p(o.deleteOne(_nullishCoalesce(s, () => ({})),a),a);return C({successful:c.rows[0].deleted>0,deletedCount:Number(c.rows[0].deleted),matchedCount:Number(c.rows[0].matched)},{operationName:"deleteOne",collectionName:n,errors:r})},deleteMany:async(s,a)=>{await u(a);let c=await p(o.deleteMany(_nullishCoalesce(s, () => ({}))),a);return C({successful:(_nullishCoalesce(c.rowCount, () => (0)))>0,deletedCount:_nullishCoalesce(c.rowCount, () => (0)),matchedCount:_nullishCoalesce(c.rowCount, () => (0))},{operationName:"deleteMany",collectionName:n,errors:r})},findOne:async(s,a)=>(await u(a),await _asyncNullishCoalesce(await _asyncOptionalChain([(await g(o.findOne(_nullishCoalesce(s, () => ({}))),a)), 'access', async _10 => _10.rows, 'access', async _11 => _11[0], 'optionalAccess', async _12 => _12.data]), async () => (null))),findOneAndDelete:async(s,a)=>{await u(a);let c=await m.findOne(s,a);return c===null?null:(await m.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await u(c);let l=await m.findOne(s,c);return l===null?null:(await m.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await u(c);let l=await m.findOne(s,c);return l===null?null:(await m.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=_nullishCoalesce(c, () => ({}));await u(c);let R={_id:s},y=await m.findOne(R,c),I=w(l);if(y==null&&l==="DOCUMENT_EXISTS"||y==null&&I!=null||y!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||y!=null&&I!==null&&y._version!==I)return C({successful:!1,document:y},{operationName:"handle",collectionName:n,errors:r});let D=await a(y);if(y===D)return C({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r});if(!y&&D){let _={...D,_id:s},q=await m.insertOne({..._,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...q,document:{..._,_version:q.nextExpectedVersion}}}if(y&&!D)return{...await m.deleteOne(R,{...x,expectedVersion:_nullishCoalesce(I, () => ("DOCUMENT_EXISTS"))}),document:null};if(y&&D){let _=await m.replaceOne(R,D,{...x,expectedVersion:_nullishCoalesce(I, () => ("DOCUMENT_EXISTS"))});return{..._,document:{...D,_version:_.nextExpectedVersion}}}return C({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r})},find:async(s,a)=>(await u(a),(await g(o.find(_nullishCoalesce(s, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await u(a);let{count:c}=await _dumbo.single.call(void 0, g(o.countDocuments(_nullishCoalesce(s, () => ({})))));return c},drop:async s=>(await u(s),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await p(o.drop())), 'optionalAccess', async _13 => _13.rowCount]), async () => (0)))>0),rename:async(s,a)=>(await u(a),await p(o.rename(s)),n=s,m),sql:{async query(s,a){return await u(a),(await g(s)).rows},async command(s,a){return await u(a),p(s)}},schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, t,o.migrations())}};return m},z= exports.g =e=>_dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:()=>$(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},V= exports.i ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye= exports.j =e=>e.startsWith("$"),ne= exports.k =e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Ce= exports.m =e=>typeof e=="string",A= exports.n =class e extends Error{constructor(n){let t=n&&typeof n=="object"&&"errorCode"in n?n.errorCode:Pe(n)?n:500,o=n&&typeof n=="object"&&"message"in n?n.message:Ce(n)?n:`Error with status code '${t}' ocurred during Pongo processing`;super(o),this.errorCode=t,Object.setPrototypeOf(this,e.prototype)}},N= exports.o =class e extends A{constructor(n){super({errorCode:412,message:_nullishCoalesce(n, () => ("Expected document state does not match current one!"))}),Object.setPrototypeOf(this,e.prototype)}};require('pg');var v=e=>{let{connectorType:n}=e;if(!X(e))throw new Error(`Unsupported db type: ${n}`);return B(e)};var te=e=>{let n=!1,t=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!n){if(t)throw new Error("Transaction is not active!");n=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");t||(t=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!t},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>_optionalChain([e, 'optionalAccess', _14 => _14.isActive])===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Se(e){if(U(e))throw new Error("Active transaction already exists!")}var F=e=>{let n=_optionalChain([e, 'optionalAccess', _15 => _15.explicit])===!0,t=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _16 => _16.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,i=!1,r=E=>{Se(o),o=te(_nullishCoalesce(E, () => (t)))},d=async()=>{oe(o),await o.commit()},p=async()=>{oe(o),await o.rollback()},S={get hasEnded(){return i},explicit:n,defaultTransactionOptions:_nullishCoalesce(t, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return t.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:d,abortTransaction:p,withTransaction:async(E,u)=>{r(u);try{let m=await E(S);return await d(),m}catch(m){throw await p(),m}}};return S};var P=e=>Object.entries(e).map(([n,t])=>[n,t]);var dn="DOCUMENT_EXISTS",un= exports.u ="DOCUMENT_DOES_NOT_EXIST",be= exports.v ="NO_CONCURRENCY_CHECK",he= exports.w =e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",w= exports.x =e=>e===void 0||he(e)?null:e,gn= exports.y =e=>e?BigInt(e):be,C= exports.z =(e,n)=>{let t={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:d}=n;if(!i)throw new N(_nullishCoalesce(o, () => (`${r} on ${d} failed. Expected document state does not match current one! Result: ${_dumbo.JSONSerializer.serialize(e)}!`)))}};return _optionalChain([n, 'access', _17 => _17.errors, 'optionalAccess', _18 => _18.throwOnOperationFailures])&&t.assertSuccessful(),t};var fe=e=>({name:e});function De(e,n){if(n===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:n}:{collections:n}}var Ee=e=>({dbs:e}),Cn= exports.A ={client:Ee,db:De,collection:fe},G= exports.B =(e,n,t)=>{let o=Object.keys(n.collections);for(let i of o)t.set(i,e.collection(i));return new Proxy(e,{get(i,r){return _nullishCoalesce(t.get(r), () => (i[r]))}})},ie= exports.C =(e,n)=>{if(!n)return e;let t=Object.keys(n.dbs);return new Proxy(e,{get(o,i){return t.includes(i)?e.db(_optionalChain([n, 'access', _19 => _19.dbs, 'access', _20 => _20[i], 'optionalAccess', _21 => _21.name])):o[i]}})},Re= exports.D =e=>({name:e.name,collections:P(e.collections).map(n=>({name:n[1].name}))}),Sn= exports.E =e=>{let n=P(e.dbs).map(t=>Re(t[1]));return{databases:n,database:t=>n.find(o=>o.name===t)}};var _n=(e,n={})=>{let t=new Map,o=v(se({connectionString:e,clientOptions:n}));t.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of t.values())await r.close()},db:r=>r?_nullishCoalesce(t.get(r), () => (t.set(r,v(se({connectionString:e,dbName:r,clientOptions:n}))).get(r))):o,startSession:F,withSession:async r=>{let d=F();try{return await r(d)}finally{await d.endSession()}}};return ie(i,_optionalChain([n, 'optionalAccess', _22 => _22.schema, 'optionalAccess', _23 => _23.definition]))},se= exports.G =e=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});var Q=(e,n,t)=>{if(e==="_id"||e==="_version")return we(e,n,t);switch(n){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",_dumbo.JSONSerializer.serialize(re(e,t)),e,_dumbo.JSONSerializer.serialize(t));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${V[n]} %L`,`{${e.split(".").join(",")}}`,t);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=P(t).map(([i,r])=>_dumbo.sql.call(void 0, '@."%s" == %s',i,_dumbo.JSONSerializer.serialize(r))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",_dumbo.JSONSerializer.serialize(re(e,t)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,t);default:throw new Error(`Unsupported operator: ${n}`)}},we=(e,n,t)=>{switch(n){case"$eq":return _dumbo.sql.call(void 0, `${e} = %L`,t);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `${e} ${V[n]} %L`,t);case"$in":return _dumbo.sql.call(void 0, `${e} IN (%s)`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, `${e} NOT IN (%s)`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},re=(e,n)=>e.split(".").reverse().reduce((t,o)=>({[o]:t}),n);var ae="AND",h=e=>Object.entries(e).map(([n,t])=>Le(t)?Ie(n,t):Q(n,"$eq",t)).join(` ${ae} `),Ie=(e,n)=>{let t=!ne(n);return P(n).map(([o,i])=>t?Q(`${e}.${o}`,ee.$eq,i):Q(e,o,i)).join(` ${ae} `)},Le=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);var j=e=>P(e).reduce((n,[t,o])=>{switch(t){case"$set":return Ne(o,n);case"$unset":return Ue(o,n);case"$inc":return Me(o,n);case"$push":return Qe(o,n);default:return n}},_dumbo.sql.call(void 0, "data")),Ne=(e,n)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",n,_dumbo.JSONSerializer.serialize(e)),Ue=(e,n)=>_dumbo.sql.call(void 0, "%s - %L",n,Object.keys(e).map(t=>`{${t}}`).join(", ")),Me=(e,n)=>{for(let[t,o]of Object.entries(e))n=_dumbo.sql.call(void 0, typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",n,t,t,o);return n},Qe=(e,n)=>{for(let[t,o]of Object.entries(e))n=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",n,t,t,_dumbo.JSONSerializer.serialize([o]));return n};var le=e=>_dumbo.sql.call(void 0, `CREATE TABLE IF NOT EXISTS %I (
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var X=e=>e.connectorType===_dumbo.NodePostgresConnectorType,B= exports.d =e=>{let{connectionString:n,dbName:t}=e,o=_nullishCoalesce(t, () => (_dumbo.getDatabaseNameOrDefault.call(void 0, n))),i=_dumbo.dumbo.call(void 0, {connectionString:n,...e.connectionOptions}),r=new Map,d={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collection:g=>K({collectionName:g,db:d,pool:i,sqlBuilder:q(g),...e.schema?e.schema:{},...e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:g=>i.withTransaction(g),schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongoDb",{components:[...r.values()].map(g=>g.schema.component)})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, i,[...r.values()].flatMap(g=>g.schema.component.migrations({connector:"PostgreSQL:pg"})))}},p=_optionalChain([e, 'optionalAccess', _2 => _2.schema, 'optionalAccess', _3 => _3.definition, 'optionalAccess', _4 => _4.dbs]);if(p){let g=P(p).map(C=>C[1]).find(C=>C.name===t||C.name===o);if(g)return G(d,g,r)}return d},je= exports.e =e=>{let n=e.length>0&&typeof e[0]=="string"?e.map(t=>z(t)):e;return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:db",{components:n})};var Oe=async(e,n)=>{let t=_optionalChain([n, 'optionalAccess', _5 => _5.session, 'optionalAccess', _6 => _6.transaction]);return!t||!t.isActive?null:await t.enlistDatabase(e)},J=async(e,n,t)=>await _asyncNullishCoalesce(await _asyncOptionalChain([(await Oe(e,n)), 'optionalAccess', async _7 => _7.execute]), async () => (t)),K= exports.f =({db:e,collectionName:n,pool:t,sqlBuilder:o,schema:i,errors:r})=>{let d=t.execute,p=async(s,a)=>(await J(e,a,d)).command(s),g=async(s,a)=>(await J(e,a,d)).query(s),C=_optionalChain([i, 'optionalAccess', _8 => _8.autoMigration])!=="None",E=s=>(C=!1,_optionalChain([s, 'optionalAccess', _9 => _9.session])?p(o.createCollection(),s):p(o.createCollection())),u=s=>C?E(s):Promise.resolve(),T={dbName:e.databaseName,collectionName:n,createCollection:async s=>{await E(s)},insertOne:async(s,a)=>{await u(a);let c=_nullishCoalesce(s._id, () => (_uuid.v4.call(void 0, ))),l=_nullishCoalesce(s._version, () => (1n)),R=(await _asyncNullishCoalesce((await p(o.insertOne({...s,_id:c,_version:l}),a)).rowCount, async () => (0)))>0;return S({successful:R,insertedId:R?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:n,errors:r})},insertMany:async(s,a)=>{await u(a);let c=s.map(x=>({...x,_id:_nullishCoalesce(x._id, () => (_uuid.v4.call(void 0, ))),_version:_nullishCoalesce(x._version, () => (1n))})),l=await p(o.insertMany(c),a);return S({successful:l.rowCount===c.length,insertedCount:_nullishCoalesce(l.rowCount, () => (0)),insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:n,errors:r})},updateOne:async(s,a,c)=>{await u(c);let l=await p(o.updateOne(s,a,c),c);return S({successful:l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"updateOne",collectionName:n,errors:r})},replaceOne:async(s,a,c)=>{await u(c);let l=await p(o.replaceOne(s,a,c),c);return S({successful:l.rows[0].modified>0,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"replaceOne",collectionName:n,errors:r})},updateMany:async(s,a,c)=>{await u(c);let l=await p(o.updateMany(s,a),c);return S({successful:!0,modifiedCount:_nullishCoalesce(l.rowCount, () => (0)),matchedCount:_nullishCoalesce(l.rowCount, () => (0))},{operationName:"updateMany",collectionName:n,errors:r})},deleteOne:async(s,a)=>{await u(a);let c=await p(o.deleteOne(_nullishCoalesce(s, () => ({})),a),a);return S({successful:c.rows[0].deleted>0,deletedCount:Number(c.rows[0].deleted),matchedCount:Number(c.rows[0].matched)},{operationName:"deleteOne",collectionName:n,errors:r})},deleteMany:async(s,a)=>{await u(a);let c=await p(o.deleteMany(_nullishCoalesce(s, () => ({}))),a);return S({successful:(_nullishCoalesce(c.rowCount, () => (0)))>0,deletedCount:_nullishCoalesce(c.rowCount, () => (0)),matchedCount:_nullishCoalesce(c.rowCount, () => (0))},{operationName:"deleteMany",collectionName:n,errors:r})},findOne:async(s,a)=>(await u(a),await _asyncNullishCoalesce(await _asyncOptionalChain([(await g(o.findOne(_nullishCoalesce(s, () => ({}))),a)), 'access', async _10 => _10.rows, 'access', async _11 => _11[0], 'optionalAccess', async _12 => _12.data]), async () => (null))),findOneAndDelete:async(s,a)=>{await u(a);let c=await T.findOne(s,a);return c===null?null:(await T.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await u(c);let l=await T.findOne(s,c);return l===null?null:(await T.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await u(c);let l=await T.findOne(s,c);return l===null?null:(await T.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=_nullishCoalesce(c, () => ({}));await u(c);let R={_id:s},y=await T.findOne(R,c),L=_(l);if(y==null&&l==="DOCUMENT_EXISTS"||y==null&&L!=null||y!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||y!=null&&L!==null&&y._version!==L)return S({successful:!1,document:y},{operationName:"handle",collectionName:n,errors:r});let D=await a(y);if(y===D)return S({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r});if(!y&&D){let I={...D,_id:s},W=await T.insertOne({...I,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...W,document:{...I,_version:W.nextExpectedVersion}}}if(y&&!D)return{...await T.deleteOne(R,{...x,expectedVersion:_nullishCoalesce(L, () => ("DOCUMENT_EXISTS"))}),document:null};if(y&&D){let I=await T.replaceOne(R,D,{...x,expectedVersion:_nullishCoalesce(L, () => ("DOCUMENT_EXISTS"))});return{...I,document:{...D,_version:I.nextExpectedVersion}}}return S({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r})},find:async(s,a)=>(await u(a),(await g(o.find(_nullishCoalesce(s, () => ({}))))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await u(a);let{count:c}=await _dumbo.single.call(void 0, g(o.countDocuments(_nullishCoalesce(s, () => ({})))));return c},drop:async s=>(await u(s),(await _asyncNullishCoalesce(await _asyncOptionalChain([(await p(o.drop())), 'optionalAccess', async _13 => _13.rowCount]), async () => (0)))>0),rename:async(s,a)=>(await u(a),await p(o.rename(s)),n=s,T),sql:{async query(s,a){return await u(a),(await g(s)).rows},async command(s,a){return await u(a),p(s)}},schema:{get component(){return _dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>_dumbo.runPostgreSQLMigrations.call(void 0, t,o.migrations())}};return T},z= exports.g =e=>_dumbo.schemaComponent.call(void 0, "pongo:schema_component:collection",{migrations:()=>$(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},V= exports.i ={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye= exports.j =e=>e.startsWith("$"),ne= exports.k =e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Se= exports.m =e=>typeof e=="string",A= exports.n =class e extends Error{constructor(n){let t=n&&typeof n=="object"&&"errorCode"in n?n.errorCode:Pe(n)?n:500,o=n&&typeof n=="object"&&"message"in n?n.message:Se(n)?n:`Error with status code '${t}' ocurred during Pongo processing`;super(o),this.errorCode=t,Object.setPrototypeOf(this,e.prototype)}},N= exports.o =class e extends A{constructor(n){super({errorCode:412,message:_nullishCoalesce(n, () => ("Expected document state does not match current one!"))}),Object.setPrototypeOf(this,e.prototype)}};require('pg');var v=e=>{let{connectorType:n}=e;if(!X(e))throw new Error(`Unsupported db type: ${n}`);return B(e)};var te=e=>{let n=!1,t=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!n){if(t)throw new Error("Transaction is not active!");n=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");t||(t=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!t},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>_optionalChain([e, 'optionalAccess', _14 => _14.isActive])===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Ce(e){if(U(e))throw new Error("Active transaction already exists!")}var F=e=>{let n=_optionalChain([e, 'optionalAccess', _15 => _15.explicit])===!0,t=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _16 => _16.defaultTransactionOptions]), () => ({get snapshotEnabled(){return!1}})),o=null,i=!1,r=E=>{Ce(o),o=te(_nullishCoalesce(E, () => (t)))},d=async()=>{oe(o),await o.commit()},p=async()=>{oe(o),await o.rollback()},C={get hasEnded(){return i},explicit:n,defaultTransactionOptions:_nullishCoalesce(t, () => ({get snapshotEnabled(){return!1}})),get transaction(){return o},get snapshotEnabled(){return t.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:d,abortTransaction:p,withTransaction:async(E,u)=>{r(u);try{let T=await E(C);return await d(),T}catch(T){throw await p(),T}}};return C};var P=e=>Object.entries(e).map(([n,t])=>[n,t]);var dn="DOCUMENT_EXISTS",un= exports.u ="DOCUMENT_DOES_NOT_EXIST",be= exports.v ="NO_CONCURRENCY_CHECK",he= exports.w =e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",_= exports.x =e=>e===void 0||he(e)?null:e,gn= exports.y =e=>e?BigInt(e):be,S= exports.z =(e,n)=>{let t={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:d}=n;if(!i)throw new N(_nullishCoalesce(o, () => (`${r} on ${d} failed. Expected document state does not match current one! Result: ${_dumbo.JSONSerializer.serialize(e)}!`)))}};return _optionalChain([n, 'access', _17 => _17.errors, 'optionalAccess', _18 => _18.throwOnOperationFailures])&&t.assertSuccessful(),t};var fe=e=>({name:e});function De(e,n){if(n===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:n}:{collections:n}}var Ee=e=>({dbs:e}),Sn= exports.A ={client:Ee,db:De,collection:fe},G= exports.B =(e,n,t)=>{let o=Object.keys(n.collections);for(let i of o)t.set(i,e.collection(i));return new Proxy(e,{get(i,r){return _nullishCoalesce(t.get(r), () => (i[r]))}})},ie= exports.C =(e,n)=>{if(!n)return e;let t=Object.keys(n.dbs);return new Proxy(e,{get(o,i){return t.includes(i)?e.db(_optionalChain([n, 'access', _19 => _19.dbs, 'access', _20 => _20[i], 'optionalAccess', _21 => _21.name])):o[i]}})},Re= exports.D =e=>({name:e.name,collections:P(e.collections).map(n=>({name:n[1].name}))}),Cn= exports.E =e=>{let n=P(e.dbs).map(t=>Re(t[1]));return{databases:n,database:t=>n.find(o=>o.name===t)}};var In=(e,n={})=>{let t=new Map,o=v(se({connectionString:e,clientOptions:n}));t.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of t.values())await r.close()},db:r=>r?_nullishCoalesce(t.get(r), () => (t.set(r,v(se({connectionString:e,dbName:r,clientOptions:n}))).get(r))):o,startSession:F,withSession:async r=>{let d=F();try{return await r(d)}finally{await d.endSession()}}};return ie(i,_optionalChain([n, 'optionalAccess', _22 => _22.schema, 'optionalAccess', _23 => _23.definition]))},se= exports.G =e=>({connectorType:_dumbo.NodePostgresConnectorType,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});var M=(e,n,t)=>{if(e==="_id"||e==="_version")return _e(e,n,t);switch(n){case"$eq":return _dumbo.sql.call(void 0, "(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",_dumbo.JSONSerializer.serialize(re(e,t)),e,_dumbo.JSONSerializer.serialize(t));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `data #>> %L ${V[n]} %L`,`{${e.split(".").join(",")}}`,t);case"$in":return _dumbo.sql.call(void 0, "data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, "data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$elemMatch":{let o=P(t).map(([i,r])=>_dumbo.sql.call(void 0, '@."%s" == %s',i,_dumbo.JSONSerializer.serialize(r))).join(" && ");return _dumbo.sql.call(void 0, "jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return _dumbo.sql.call(void 0, "data @> %L::jsonb",_dumbo.JSONSerializer.serialize(re(e,t)));case"$size":return _dumbo.sql.call(void 0, "jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,t);default:throw new Error(`Unsupported operator: ${n}`)}},_e=(e,n,t)=>{switch(n){case"$eq":return _dumbo.sql.call(void 0, `${e} = %L`,t);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return _dumbo.sql.call(void 0, `${e} ${V[n]} %L`,t);case"$in":return _dumbo.sql.call(void 0, `${e} IN (%s)`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));case"$nin":return _dumbo.sql.call(void 0, `${e} NOT IN (%s)`,t.map(o=>_dumbo.sql.call(void 0, "%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},re=(e,n)=>e.split(".").reverse().reduce((t,o)=>({[o]:t}),n);var ae="AND",h=e=>Object.entries(e).map(([n,t])=>we(t)?Le(n,t):M(n,"$eq",t)).join(` ${ae} `),Le=(e,n)=>{let t=!ne(n);return P(n).map(([o,i])=>t?M(`${e}.${o}`,ee.$eq,i):M(e,o,i)).join(` ${ae} `)},we=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);var j=e=>P(e).reduce((n,[t,o])=>{switch(t){case"$set":return Ne(o,n);case"$unset":return Ue(o,n);case"$inc":return Qe(o,n);case"$push":return Me(o,n);default:return n}},_dumbo.sql.call(void 0, "data")),Ne=(e,n)=>_dumbo.sql.call(void 0, "%s || %L::jsonb",n,_dumbo.JSONSerializer.serialize(e)),Ue=(e,n)=>_dumbo.sql.call(void 0, "%s - %L",n,Object.keys(e).map(t=>`{${t}}`).join(", ")),Qe=(e,n)=>{for(let[t,o]of Object.entries(e))n=_dumbo.sql.call(void 0, typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",n,t,t,o);return n},Me=(e,n)=>{for(let[t,o]of Object.entries(e))n=_dumbo.sql.call(void 0, "jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",n,t,t,_dumbo.JSONSerializer.serialize([o]));return n};var le=e=>_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,9 +7,9 @@
|
|
|
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
|
-
)`,e),$= exports.a =e=>[_dumbo.sqlMigration.call(void 0, `pongoCollection:${e}:001:createtable`,[le(e)])],
|
|
10
|
+
)`,e),$= exports.a =e=>[_dumbo.sqlMigration.call(void 0, `pongoCollection:${e}:001:createtable`,[le(e)])],q= exports.b =e=>({migrations:()=>$(e),createCollection:()=>le(e),insertOne:n=>_dumbo.sql.call(void 0, "INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;",e,n._id,_dumbo.JSONSerializer.serialize(n),_nullishCoalesce(n._version, () => (1n))),insertMany:n=>{let t=n.map(o=>_dumbo.sql.call(void 0, "(%L, %L, %L)",o._id,_dumbo.JSONSerializer.serialize(o),_nullishCoalesce(o._version, () => (1n)))).join(", ");return _dumbo.sql.call(void 0, `INSERT INTO %I (_id, data, _version) VALUES %s
|
|
11
11
|
ON CONFLICT(_id) DO NOTHING
|
|
12
|
-
RETURNING _id;`,e,t)},updateOne:(n,t,o)=>{let i=
|
|
12
|
+
RETURNING _id;`,e,t)},updateOne:(n,t,o)=>{let i=_(_optionalChain([o, 'optionalAccess', _24 => _24.expectedVersion])),r=i!=null?"AND %I._version = %L":"",d=i!=null?[e,i]:[],p=_dumbo.isSQL.call(void 0, n)?n:h(n),g=_dumbo.isSQL.call(void 0, t)?n:j(t);return _dumbo.sql.call(void 0, `WITH existing AS (
|
|
13
13
|
SELECT _id, _version as current_version
|
|
14
14
|
FROM %I %s
|
|
15
15
|
LIMIT 1
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
COUNT(updated._id) over() AS modified
|
|
31
31
|
FROM existing
|
|
32
32
|
LEFT JOIN updated
|
|
33
|
-
ON existing._id = updated._id;`,e,f(p),e,g,e,e,...d,e,e)},replaceOne:(n,t,o)=>{let i=
|
|
33
|
+
ON existing._id = updated._id;`,e,f(p),e,g,e,e,...d,e,e)},replaceOne:(n,t,o)=>{let i=_(_optionalChain([o, 'optionalAccess', _25 => _25.expectedVersion])),r=i!=null?"AND %I._version = %L":"",d=i!=null?[e,i]:[],p=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, `WITH existing AS (
|
|
34
34
|
SELECT _id, _version as current_version
|
|
35
35
|
FROM %I %s
|
|
36
36
|
LIMIT 1
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
SET
|
|
56
56
|
data = %s || jsonb_build_object('_version', (_version + 1)::text),
|
|
57
57
|
_version = _version + 1
|
|
58
|
-
%s;`,e,i,f(o))},deleteOne:(n,t)=>{let o=
|
|
58
|
+
%s;`,e,i,f(o))},deleteOne:(n,t)=>{let o=_(_optionalChain([t, 'optionalAccess', _26 => _26.expectedVersion])),i=o!=null?"AND %I._version = %L":"",r=o!=null?[e,o]:[],d=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, `WITH existing AS (
|
|
59
59
|
SELECT _id
|
|
60
60
|
FROM %I %s
|
|
61
61
|
LIMIT 1
|
|
@@ -72,5 +72,5 @@
|
|
|
72
72
|
COUNT(deleted._id) over() AS deleted
|
|
73
73
|
FROM existing
|
|
74
74
|
LEFT JOIN deleted
|
|
75
|
-
ON existing._id = deleted._id;`,e,f(d),e,e,...r,e)},deleteMany:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",e,f(t))},findOne:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1;",e,f(t))},find:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s;",e,f(t))},countDocuments:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s;",e,f(t))},rename:n=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I;",e,n),drop:(n=e)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",n)}),f=e=>e.length>0?_dumbo.sql.call(void 0, "WHERE %s",e):_dumbo.rawSql.call(void 0, "");exports.a = $; exports.b =
|
|
76
|
-
//# sourceMappingURL=chunk-
|
|
75
|
+
ON existing._id = deleted._id;`,e,f(d),e,e,...r,e)},deleteMany:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "DELETE FROM %I %s",e,f(t))},findOne:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s LIMIT 1;",e,f(t))},find:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT data FROM %I %s;",e,f(t))},countDocuments:n=>{let t=_dumbo.isSQL.call(void 0, n)?n:h(n);return _dumbo.sql.call(void 0, "SELECT COUNT(1) as count FROM %I %s;",e,f(t))},rename:n=>_dumbo.sql.call(void 0, "ALTER TABLE %I RENAME TO %I;",e,n),drop:(n=e)=>_dumbo.sql.call(void 0, "DROP TABLE IF EXISTS %I",n)}),f=e=>e.length>0?_dumbo.sql.call(void 0, "WHERE %s",e):_dumbo.rawSql.call(void 0, "");exports.a = $; exports.b = q; exports.c = X; exports.d = B; exports.e = je; exports.f = K; exports.g = z; exports.h = ee; exports.i = V; exports.j = ye; exports.k = ne; exports.l = Pe; exports.m = Se; exports.n = A; exports.o = N; exports.p = v; exports.q = te; exports.r = F; exports.s = P; exports.t = dn; exports.u = un; exports.v = be; exports.w = he; exports.x = _; exports.y = gn; exports.z = S; exports.A = Sn; exports.B = G; exports.C = ie; exports.D = Re; exports.E = Cn; exports.F = In; exports.G = se;
|
|
76
|
+
//# sourceMappingURL=chunk-2FFAJEOI.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/postgres/sqlBuilder/index.ts","../src/core/collection/pongoCollection.ts","../src/postgres/dbClient.ts","../src/core/collection/query.ts","../src/core/errors/index.ts","../src/core/pongoClient.ts","../src/core/pongoDb.ts"],"names":["isPostgresClientOptions","options","NodePostgresConnectorType","postgresDb","connectionString","dbName","databaseName","getDatabaseNameOrDefault","pool","dumbo","collections","db","collectionName","pongoCollection","postgresSQLBuilder","handle","schemaComponent","c","runPostgreSQLMigrations","dbsSchema","dbSchema","objectEntries","e","proxyPongoDbWithSchema","pongoDbSchemaComponent","components","pongoCollectionSchemaComponent","enlistIntoTransactionIfActive","transaction","transactionExecutorOrDefault","defaultSqlExecutor","SqlFor","schema","errors","sqlExecutor","command","sql","query","shouldMigrate","createCollection","ensureCollectionCreated","collection","document","_id","uuid","_version","successful","operationResult","documents","rows","doc","result","d","filter","update","existingDoc","replacement","id","version","operationOptions","byId","existing","expectedVersion","expectedVersionValue","newDoc","insertResult","replaceResult","row","count","single","newName","pongoCollectionPostgreSQLMigrations","QueryOperators","OperatorMap","isOperator","key","hasOperators","value","isNumber","val","isString","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,cAKe,ICWFC,CAAAA,CAGXtF,CAAAA,EACY,CACZ,GAAM,CAAE,aAAA,CAAeuF,CAAK,CAAA,CAAIvF,CAAAA,CAEhC,EAAA,CAAI,CAACD,CAAAA,CAAwBC,CAAO,CAAA,CAClC,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBuF,CAAI,CAAA,CAAA;ANC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8CE,GAAA;AAAA;AAsBA,oBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoCrD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BrD,oCAAA;AAAA;AAAA;AAAA;AAuBA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQqD,oCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmDF,oCAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/pongo/dist/chunk-2FFAJEOI.cjs","sourcesContent":["import {\n isSQL,\n JSONSerializer,\n rawSql,\n sql,\n sqlMigration,\n type SQL,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport {\n expectedVersionValue,\n type DeleteOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollectionSQLBuilder,\n type PongoFilter,\n type PongoUpdate,\n type ReplaceOneOptions,\n type UpdateOneOptions,\n type WithoutId,\n} from '../../core';\nimport { constructFilterQuery } from './filter';\nimport { buildUpdateQuery } from './update';\n\nconst createCollection = (collectionName: string): SQL =>\n sql(\n `CREATE TABLE IF NOT EXISTS %I (\n _id TEXT PRIMARY KEY, \n data JSONB NOT NULL, \n metadata JSONB NOT NULL DEFAULT '{}',\n _version BIGINT NOT NULL DEFAULT 1,\n _partition TEXT NOT NULL DEFAULT 'png_global',\n _archived BOOLEAN NOT NULL DEFAULT FALSE,\n _created TIMESTAMPTZ NOT NULL DEFAULT now(),\n _updated TIMESTAMPTZ NOT NULL DEFAULT now()\n )`,\n collectionName,\n );\n\nexport const pongoCollectionPostgreSQLMigrations = (collectionName: string) => [\n sqlMigration(`pongoCollection:${collectionName}:001:createtable`, [\n createCollection(collectionName),\n ]),\n];\n\nexport const postgresSQLBuilder = (\n collectionName: string,\n): PongoCollectionSQLBuilder => ({\n migrations: (): SQLMigration[] =>\n pongoCollectionPostgreSQLMigrations(collectionName),\n createCollection: (): SQL => createCollection(collectionName),\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>): SQL => {\n return sql(\n 'INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;',\n collectionName,\n document._id,\n JSONSerializer.serialize(document),\n document._version ?? 1n,\n );\n },\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]): SQL => {\n const values = documents\n .map((doc) =>\n sql(\n '(%L, %L, %L)',\n doc._id,\n JSONSerializer.serialize(doc),\n doc._version ?? 1n,\n ),\n )\n .join(', ');\n return sql(\n `INSERT INTO %I (_id, data, _version) VALUES %s \n ON CONFLICT(_id) DO NOTHING\n RETURNING _id;`,\n collectionName,\n values,\n );\n },\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? filter : buildUpdateQuery(update);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %s || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n updateQuery,\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id, _version as current_version\n FROM %I %s \n LIMIT 1\n ),\n updated AS (\n UPDATE %I \n SET \n data = %L || jsonb_build_object('_id', %I._id) || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n FROM existing \n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id, %I._version\n )\n SELECT \n existing._id,\n COALESCE(updated._version, existing.current_version) AS version,\n COUNT(existing._id) over() AS matched,\n COUNT(updated._id) over() AS modified\n FROM existing\n LEFT JOIN updated \n ON existing._id = updated._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n JSONSerializer.serialize(document),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n collectionName,\n );\n },\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n const updateQuery = isSQL(update) ? filter : buildUpdateQuery(update);\n\n return sql(\n `UPDATE %I \n SET \n data = %s || jsonb_build_object('_version', (_version + 1)::text),\n _version = _version + 1\n %s;`,\n collectionName,\n updateQuery,\n where(filterQuery),\n );\n },\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ): SQL => {\n const expectedVersion = expectedVersionValue(options?.expectedVersion);\n const expectedVersionUpdate =\n expectedVersion != null ? 'AND %I._version = %L' : '';\n const expectedVersionParams =\n expectedVersion != null ? [collectionName, expectedVersion] : [];\n\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n `WITH existing AS (\n SELECT _id\n FROM %I %s \n LIMIT 1\n ),\n deleted AS (\n DELETE FROM %I\n USING existing\n WHERE %I._id = existing._id ${expectedVersionUpdate}\n RETURNING %I._id\n )\n SELECT \n existing._id,\n COUNT(existing._id) over() AS matched,\n COUNT(deleted._id) over() AS deleted\n FROM existing\n LEFT JOIN deleted \n ON existing._id = deleted._id;`,\n collectionName,\n where(filterQuery),\n collectionName,\n collectionName,\n ...expectedVersionParams,\n collectionName,\n );\n },\n deleteMany: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql('DELETE FROM %I %s', collectionName, where(filterQuery));\n },\n findOne: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n\n return sql(\n 'SELECT data FROM %I %s LIMIT 1;',\n collectionName,\n where(filterQuery),\n );\n },\n find: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql('SELECT data FROM %I %s;', collectionName, where(filterQuery));\n },\n countDocuments: <T>(filter: PongoFilter<T> | SQL): SQL => {\n const filterQuery = isSQL(filter) ? filter : constructFilterQuery(filter);\n return sql(\n 'SELECT COUNT(1) as count FROM %I %s;',\n collectionName,\n where(filterQuery),\n );\n },\n rename: (newName: string): SQL =>\n sql('ALTER TABLE %I RENAME TO %I;', collectionName, newName),\n drop: (targetName: string = collectionName): SQL =>\n sql('DROP TABLE IF EXISTS %I', targetName),\n});\n\nconst where = (filter: string): SQL =>\n filter.length > 0 ? sql('WHERE %s', filter) : rawSql('');\n","import {\n runPostgreSQLMigrations,\n schemaComponent,\n single,\n type DatabaseTransaction,\n type Dumbo,\n type MigrationStyle,\n type QueryResult,\n type QueryResultRow,\n type SchemaComponent,\n type SQL,\n type SQLExecutor,\n type SQLMigration,\n} from '@event-driven-io/dumbo';\nimport { v4 as uuid } from 'uuid';\nimport {\n expectedVersionValue,\n operationResult,\n type CollectionOperationOptions,\n type DeleteManyOptions,\n type DeleteOneOptions,\n type DocumentHandler,\n type HandleOptions,\n type InsertManyOptions,\n type InsertOneOptions,\n type OptionalUnlessRequiredIdAndVersion,\n type PongoCollection,\n type PongoDb,\n type PongoDeleteResult,\n type PongoDocument,\n type PongoFilter,\n type PongoHandleResult,\n type PongoInsertManyResult,\n type PongoInsertOneResult,\n type PongoUpdate,\n type PongoUpdateManyResult,\n type PongoUpdateResult,\n type ReplaceOneOptions,\n type UpdateManyOptions,\n type UpdateOneOptions,\n type WithIdAndVersion,\n type WithoutId,\n type WithVersion,\n} from '..';\nimport { pongoCollectionPostgreSQLMigrations } from '../../postgres';\n\nexport type PongoCollectionOptions<ConnectorType extends string = string> = {\n db: PongoDb<ConnectorType>;\n collectionName: string;\n pool: Dumbo;\n sqlBuilder: PongoCollectionSQLBuilder;\n schema?: { autoMigration?: MigrationStyle };\n errors?: { throwOnOperationFailures?: boolean };\n};\n\nconst enlistIntoTransactionIfActive = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n): Promise<DatabaseTransaction | null> => {\n const transaction = options?.session?.transaction;\n\n if (!transaction || !transaction.isActive) return null;\n\n return await transaction.enlistDatabase(db);\n};\n\nconst transactionExecutorOrDefault = async <\n ConnectorType extends string = string,\n>(\n db: PongoDb<ConnectorType>,\n options: CollectionOperationOptions | undefined,\n defaultSqlExecutor: SQLExecutor,\n): Promise<SQLExecutor> => {\n const existingTransaction = await enlistIntoTransactionIfActive(db, options);\n return existingTransaction?.execute ?? defaultSqlExecutor;\n};\n\nexport const pongoCollection = <\n T extends PongoDocument,\n ConnectorType extends string = string,\n>({\n db,\n collectionName,\n pool,\n sqlBuilder: SqlFor,\n schema,\n errors,\n}: PongoCollectionOptions<ConnectorType>): PongoCollection<T> => {\n const sqlExecutor = pool.execute;\n const command = async <Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (\n await transactionExecutorOrDefault(db, options, sqlExecutor)\n ).command<Result>(sql);\n\n const query = async <T extends QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ) =>\n (await transactionExecutorOrDefault(db, options, sqlExecutor)).query<T>(\n sql,\n );\n\n let shouldMigrate = schema?.autoMigration !== 'None';\n\n const createCollection = (options?: CollectionOperationOptions) => {\n shouldMigrate = false;\n\n if (options?.session) return command(SqlFor.createCollection(), options);\n else return command(SqlFor.createCollection());\n };\n\n const ensureCollectionCreated = (options?: CollectionOperationOptions) => {\n if (!shouldMigrate) {\n return Promise.resolve();\n }\n\n return createCollection(options);\n };\n\n const collection = {\n dbName: db.databaseName,\n collectionName,\n createCollection: async (options?: CollectionOperationOptions) => {\n await createCollection(options);\n },\n insertOne: async (\n document: OptionalUnlessRequiredIdAndVersion<T>,\n options?: InsertOneOptions,\n ): Promise<PongoInsertOneResult> => {\n await ensureCollectionCreated(options);\n\n const _id = (document._id as string | undefined | null) ?? uuid();\n const _version = document._version ?? 1n;\n\n const result = await command(\n SqlFor.insertOne({\n ...document,\n _id,\n _version,\n } as OptionalUnlessRequiredIdAndVersion<T>),\n options,\n );\n\n const successful = (result.rowCount ?? 0) > 0;\n\n return operationResult<PongoInsertOneResult>(\n {\n successful,\n insertedId: successful ? _id : null,\n nextExpectedVersion: _version,\n },\n { operationName: 'insertOne', collectionName, errors },\n );\n },\n insertMany: async (\n documents: OptionalUnlessRequiredIdAndVersion<T>[],\n options?: InsertManyOptions,\n ): Promise<PongoInsertManyResult> => {\n await ensureCollectionCreated(options);\n\n const rows = documents.map((doc) => ({\n ...doc,\n _id: (doc._id as string | undefined | null) ?? uuid(),\n _version: doc._version ?? 1n,\n }));\n\n const result = await command(\n SqlFor.insertMany(rows as OptionalUnlessRequiredIdAndVersion<T>[]),\n options,\n );\n\n return operationResult<PongoInsertManyResult>(\n {\n successful: result.rowCount === rows.length,\n insertedCount: result.rowCount ?? 0,\n insertedIds: result.rows.map((d) => d._id as string),\n },\n { operationName: 'insertMany', collectionName, errors },\n );\n },\n updateOne: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.updateOne(filter, update, options),\n options,\n );\n\n return operationResult<PongoUpdateResult>(\n {\n successful: result.rows[0]!.modified === result.rows[0]!.matched,\n modifiedCount: Number(result.rows[0]!.modified),\n matchedCount: Number(result.rows[0]!.matched),\n nextExpectedVersion: result.rows[0]!.version,\n },\n { operationName: 'updateOne', collectionName, errors },\n );\n },\n replaceOne: async (\n filter: PongoFilter<T>,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<PongoUpdateResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<UpdateSqlResult>(\n SqlFor.replaceOne(filter, document, options),\n options,\n );\n return operationResult<PongoUpdateResult>(\n {\n successful: result.rows[0]!.modified > 0,\n modifiedCount: Number(result.rows[0]!.modified),\n matchedCount: Number(result.rows[0]!.matched),\n nextExpectedVersion: result.rows[0]!.version,\n },\n { operationName: 'replaceOne', collectionName, errors },\n );\n },\n updateMany: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateManyOptions,\n ): Promise<PongoUpdateManyResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.updateMany(filter, update), options);\n\n return operationResult<PongoUpdateManyResult>(\n {\n successful: true,\n modifiedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'updateMany', collectionName, errors },\n );\n },\n deleteOne: async (\n filter?: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command<DeleteSqlResult>(\n SqlFor.deleteOne(filter ?? {}, options),\n options,\n );\n return operationResult<PongoDeleteResult>(\n {\n successful: result.rows[0]!.deleted! > 0,\n deletedCount: Number(result.rows[0]!.deleted!),\n matchedCount: Number(result.rows[0]!.matched!),\n },\n { operationName: 'deleteOne', collectionName, errors },\n );\n },\n deleteMany: async (\n filter?: PongoFilter<T>,\n options?: DeleteManyOptions,\n ): Promise<PongoDeleteResult> => {\n await ensureCollectionCreated(options);\n\n const result = await command(SqlFor.deleteMany(filter ?? {}), options);\n\n return operationResult<PongoDeleteResult>(\n {\n successful: (result.rowCount ?? 0) > 0,\n deletedCount: result.rowCount ?? 0,\n matchedCount: result.rowCount ?? 0,\n },\n { operationName: 'deleteMany', collectionName, errors },\n );\n },\n findOne: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.findOne(filter ?? {}), options);\n return (result.rows[0]?.data ?? null) as WithIdAndVersion<T> | null;\n },\n findOneAndDelete: async (\n filter: PongoFilter<T>,\n options?: DeleteOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.deleteOne(filter, options);\n return existingDoc;\n },\n findOneAndReplace: async (\n filter: PongoFilter<T>,\n replacement: WithoutId<T>,\n options?: ReplaceOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.replaceOne(filter, replacement, options);\n\n return existingDoc;\n },\n findOneAndUpdate: async (\n filter: PongoFilter<T>,\n update: PongoUpdate<T>,\n options?: UpdateOneOptions,\n ): Promise<WithIdAndVersion<T> | null> => {\n await ensureCollectionCreated(options);\n\n const existingDoc = await collection.findOne(filter, options);\n\n if (existingDoc === null) return null;\n\n await collection.updateOne(filter, update, options);\n\n return existingDoc;\n },\n handle: async (\n id: string,\n handle: DocumentHandler<T>,\n options?: HandleOptions,\n ): Promise<PongoHandleResult<T>> => {\n const { expectedVersion: version, ...operationOptions } = options ?? {};\n await ensureCollectionCreated(options);\n\n const byId: PongoFilter<T> = { _id: id };\n\n const existing = (await collection.findOne(\n byId,\n options,\n )) as WithVersion<T>;\n\n const expectedVersion = expectedVersionValue(version);\n\n if (\n (existing == null && version === 'DOCUMENT_EXISTS') ||\n (existing == null && expectedVersion != null) ||\n (existing != null && version === 'DOCUMENT_DOES_NOT_EXIST') ||\n (existing != null &&\n expectedVersion !== null &&\n existing._version !== expectedVersion)\n ) {\n return operationResult<PongoHandleResult<T>>(\n {\n successful: false,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n }\n\n const result = await handle(existing as T);\n\n if (existing === result)\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n\n if (!existing && result) {\n const newDoc = { ...result, _id: id };\n const insertResult = await collection.insertOne(\n { ...newDoc, _id: id } as OptionalUnlessRequiredIdAndVersion<T>,\n {\n ...operationOptions,\n expectedVersion: 'DOCUMENT_DOES_NOT_EXIST',\n },\n );\n return {\n ...insertResult,\n document: {\n ...newDoc,\n _version: insertResult.nextExpectedVersion,\n } as T,\n };\n }\n\n if (existing && !result) {\n const deleteResult = await collection.deleteOne(byId, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return { ...deleteResult, document: null };\n }\n\n if (existing && result) {\n const replaceResult = await collection.replaceOne(byId, result, {\n ...operationOptions,\n expectedVersion: expectedVersion ?? 'DOCUMENT_EXISTS',\n });\n return {\n ...replaceResult,\n document: {\n ...result,\n _version: replaceResult.nextExpectedVersion,\n } as T,\n };\n }\n\n return operationResult<PongoHandleResult<T>>(\n {\n successful: true,\n document: existing as T,\n },\n { operationName: 'handle', collectionName, errors },\n );\n },\n find: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<WithIdAndVersion<T>[]> => {\n await ensureCollectionCreated(options);\n\n const result = await query(SqlFor.find(filter ?? {}));\n return result.rows.map((row) => row.data as WithIdAndVersion<T>);\n },\n countDocuments: async (\n filter?: PongoFilter<T>,\n options?: CollectionOperationOptions,\n ): Promise<number> => {\n await ensureCollectionCreated(options);\n\n const { count } = await single(\n query<{ count: number }>(SqlFor.countDocuments(filter ?? {})),\n );\n return count;\n },\n drop: async (options?: CollectionOperationOptions): Promise<boolean> => {\n await ensureCollectionCreated(options);\n const result = await command(SqlFor.drop());\n return (result?.rowCount ?? 0) > 0;\n },\n rename: async (\n newName: string,\n options?: CollectionOperationOptions,\n ): Promise<PongoCollection<T>> => {\n await ensureCollectionCreated(options);\n await command(SqlFor.rename(newName));\n collectionName = newName;\n return collection;\n },\n\n sql: {\n async query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<Result[]> {\n await ensureCollectionCreated(options);\n\n const result = await query<Result>(sql);\n return result.rows;\n },\n async command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n options?: CollectionOperationOptions,\n ): Promise<QueryResult<Result>> {\n await ensureCollectionCreated(options);\n\n return command(sql);\n },\n },\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongo:schema_component:collection', {\n migrations: SqlFor.migrations,\n });\n },\n migrate: () => runPostgreSQLMigrations(pool, SqlFor.migrations()), // TODO: This needs to change to support more connectors\n },\n };\n\n return collection;\n};\n\nexport const pongoCollectionSchemaComponent = (collectionName: string) =>\n schemaComponent('pongo:schema_component:collection', {\n migrations: () => pongoCollectionPostgreSQLMigrations(collectionName), // TODO: This needs to change to support more connectors\n });\n\nexport type PongoCollectionSQLBuilder = {\n migrations: () => SQLMigration[];\n createCollection: () => SQL;\n insertOne: <T>(document: OptionalUnlessRequiredIdAndVersion<T>) => SQL;\n insertMany: <T>(documents: OptionalUnlessRequiredIdAndVersion<T>[]) => SQL;\n updateOne: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n options?: UpdateOneOptions,\n ) => SQL;\n replaceOne: <T>(\n filter: PongoFilter<T> | SQL,\n document: WithoutId<T>,\n options?: ReplaceOneOptions,\n ) => SQL;\n updateMany: <T>(\n filter: PongoFilter<T> | SQL,\n update: PongoUpdate<T> | SQL,\n ) => SQL;\n deleteOne: <T>(\n filter: PongoFilter<T> | SQL,\n options?: DeleteOneOptions,\n ) => SQL;\n deleteMany: <T>(filter: PongoFilter<T> | SQL) => SQL;\n findOne: <T>(filter: PongoFilter<T> | SQL) => SQL;\n find: <T>(filter: PongoFilter<T> | SQL) => SQL;\n countDocuments: <T>(filter: PongoFilter<T> | SQL) => SQL;\n rename: (newName: string) => SQL;\n drop: () => SQL;\n};\n\ntype UpdateSqlResult = {\n matched: bigint;\n modified: bigint;\n version: bigint;\n};\n\ntype DeleteSqlResult = {\n matched: bigint | null;\n deleted: bigint | null;\n};\n","import {\n dumbo,\n getDatabaseNameOrDefault,\n NodePostgresConnectorType,\n runPostgreSQLMigrations,\n schemaComponent,\n type PostgresConnector,\n type PostgresPoolOptions,\n type SchemaComponent,\n} from '@event-driven-io/dumbo';\nimport type { Document } from 'mongodb';\nimport {\n objectEntries,\n pongoCollection,\n pongoCollectionSchemaComponent,\n proxyPongoDbWithSchema,\n type PongoCollection,\n type PongoDb,\n type PongoDbClientOptions,\n} from '../core';\nimport { postgresSQLBuilder } from './sqlBuilder';\n\nexport type PostgresDbClientOptions = PongoDbClientOptions<PostgresConnector>;\n\nexport const isPostgresClientOptions = (\n options: PongoDbClientOptions,\n): options is PostgresDbClientOptions =>\n options.connectorType === NodePostgresConnectorType;\n\nexport const postgresDb = (\n options: PostgresDbClientOptions,\n): PongoDb<PostgresConnector> => {\n const { connectionString, dbName } = options;\n const databaseName = dbName ?? getDatabaseNameOrDefault(connectionString);\n\n const pool = dumbo<PostgresPoolOptions>({\n connectionString,\n ...options.connectionOptions,\n });\n\n const collections = new Map<string, PongoCollection<Document>>();\n\n const db: PongoDb<PostgresConnector> = {\n connectorType: options.connectorType,\n databaseName,\n connect: () => Promise.resolve(),\n close: () => pool.close(),\n collection: (collectionName) =>\n pongoCollection({\n collectionName,\n db,\n pool,\n sqlBuilder: postgresSQLBuilder(collectionName),\n ...(options.schema ? options.schema : {}),\n ...(options.errors ? options.errors : {}),\n }),\n transaction: () => pool.transaction(),\n withTransaction: (handle) => pool.withTransaction(handle),\n\n schema: {\n get component(): SchemaComponent {\n return schemaComponent('pongoDb', {\n components: [...collections.values()].map((c) => c.schema.component),\n });\n },\n migrate: () =>\n runPostgreSQLMigrations(\n pool,\n [...collections.values()].flatMap((c) =>\n // TODO: This needs to change to support more connectors\n c.schema.component.migrations({ connector: 'PostgreSQL:pg' }),\n ),\n ),\n },\n };\n\n const dbsSchema = options?.schema?.definition?.dbs;\n\n if (dbsSchema) {\n const dbSchema = objectEntries(dbsSchema)\n .map((e) => e[1])\n .find((db) => db.name === dbName || db.name === databaseName);\n\n if (dbSchema) return proxyPongoDbWithSchema(db, dbSchema, collections);\n }\n\n return db;\n};\n\nexport const pongoDbSchemaComponent = (\n collections: string[] | SchemaComponent[],\n) => {\n const components =\n collections.length > 0 && typeof collections[0] === 'string'\n ? collections.map((collectionName) =>\n pongoCollectionSchemaComponent(collectionName as string),\n )\n : (collections as SchemaComponent[]);\n\n return schemaComponent('pongo:schema_component:db', {\n components,\n });\n};\n","export const QueryOperators = {\n $eq: '$eq',\n $gt: '$gt',\n $gte: '$gte',\n $lt: '$lt',\n $lte: '$lte',\n $ne: '$ne',\n $in: '$in',\n $nin: '$nin',\n $elemMatch: '$elemMatch',\n $all: '$all',\n $size: '$size',\n};\n\nexport const OperatorMap = {\n $gt: '>',\n $gte: '>=',\n $lt: '<',\n $lte: '<=',\n $ne: '!=',\n};\n\nexport const isOperator = (key: string) => key.startsWith('$');\n\nexport const hasOperators = (value: Record<string, unknown>) =>\n Object.keys(value).some(isOperator);\n","export const isNumber = (val: unknown): val is number =>\n typeof val === 'number' && val === val;\n\nexport const isString = (val: unknown): val is string =>\n typeof val === 'string';\n\nexport class PongoError extends Error {\n public errorCode: number;\n\n constructor(\n options?: { errorCode: number; message?: string } | string | number,\n ) {\n const errorCode =\n options && typeof options === 'object' && 'errorCode' in options\n ? options.errorCode\n : isNumber(options)\n ? options\n : 500;\n const message =\n options && typeof options === 'object' && 'message' in options\n ? options.message\n : isString(options)\n ? options\n : `Error with status code '${errorCode}' ocurred during Pongo processing`;\n\n super(message);\n this.errorCode = errorCode;\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, PongoError.prototype);\n }\n}\n\nexport class ConcurrencyError extends PongoError {\n constructor(message?: string) {\n super({\n errorCode: 412,\n message: message ?? `Expected document state does not match current one!`,\n });\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, ConcurrencyError.prototype);\n }\n}\n","import {\n NodePostgresConnectorType,\n type MigrationStyle,\n type NodePostgresConnection,\n} from '@event-driven-io/dumbo';\nimport pg from 'pg';\nimport type { PostgresDbClientOptions } from '../postgres';\nimport { getPongoDb, type AllowedDbClientOptions } from './pongoDb';\nimport { pongoSession } from './pongoSession';\nimport {\n proxyClientWithSchema,\n type PongoClientSchema,\n type PongoClientWithSchema,\n} from './schema';\nimport type { PongoClient, PongoDb, PongoSession } from './typing';\n\nexport type PooledPongoClientOptions =\n | {\n pool: pg.Pool;\n }\n | {\n pooled: true;\n }\n | {\n pool: pg.Pool;\n pooled: true;\n }\n | object;\n\nexport type NotPooledPongoOptions =\n | {\n client: pg.Client;\n }\n | {\n pooled: false;\n }\n | {\n client: pg.Client;\n pooled: false;\n }\n | {\n connection: NodePostgresConnection;\n pooled?: false;\n };\n\nexport type PongoClientOptions<\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n> = {\n schema?: { autoMigration?: MigrationStyle; definition?: TypedClientSchema };\n errors?: { throwOnOperationFailures?: boolean };\n connectionOptions?: PooledPongoClientOptions | NotPooledPongoOptions;\n};\n\nexport const pongoClient = <\n TypedClientSchema extends PongoClientSchema = PongoClientSchema,\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n connectionString: string,\n options: PongoClientOptions<TypedClientSchema> = {},\n): PongoClient & PongoClientWithSchema<TypedClientSchema> => {\n const dbClients = new Map<string, PongoDb>();\n\n const dbClient = getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n clientOptions: options,\n }),\n );\n dbClients.set(dbClient.databaseName, dbClient);\n\n const pongoClient: PongoClient = {\n connect: async () => {\n await dbClient.connect();\n return pongoClient;\n },\n close: async () => {\n for (const db of dbClients.values()) {\n await db.close();\n }\n },\n db: (dbName?: string): PongoDb => {\n if (!dbName) return dbClient;\n\n return (\n dbClients.get(dbName) ??\n dbClients\n .set(\n dbName,\n getPongoDb<DbClientOptions>(\n clientToDbOptions({\n connectionString,\n dbName,\n clientOptions: options,\n }),\n ),\n )\n .get(dbName)!\n );\n },\n startSession: pongoSession,\n withSession: async <T>(\n callback: (session: PongoSession) => Promise<T>,\n ): Promise<T> => {\n const session = pongoSession();\n\n try {\n return await callback(session);\n } finally {\n await session.endSession();\n }\n },\n };\n\n return proxyClientWithSchema(pongoClient, options?.schema?.definition);\n};\n\nexport const clientToDbOptions = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(options: {\n connectionString: string;\n dbName?: string;\n clientOptions: PongoClientOptions;\n}): DbClientOptions => {\n const postgreSQLOptions: PostgresDbClientOptions = {\n connectorType: NodePostgresConnectorType,\n connectionString: options.connectionString,\n dbName: options.dbName,\n ...options.clientOptions,\n };\n\n return postgreSQLOptions as DbClientOptions;\n};\n","import {\n isPostgresClientOptions,\n postgresDb,\n type PostgresDbClientOptions,\n} from '../postgres';\nimport type { PongoClientOptions } from './pongoClient';\nimport type { PongoDb } from './typing';\n\nexport type PongoDbClientOptions<ConnectorType extends string = string> = {\n connectorType: ConnectorType;\n connectionString: string;\n dbName: string | undefined;\n} & PongoClientOptions;\n\nexport type AllowedDbClientOptions = PostgresDbClientOptions;\n\nexport const getPongoDb = <\n DbClientOptions extends AllowedDbClientOptions = AllowedDbClientOptions,\n>(\n options: DbClientOptions,\n): PongoDb => {\n const { connectorType: type } = options;\n // This is the place where in the future could come resolution of other database types\n if (!isPostgresClientOptions(options))\n throw new Error(`Unsupported db type: ${type}`);\n\n return postgresDb(options);\n};\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{isSQL as b,JSONSerializer as k,rawSql as $e,sql as O,sqlMigration as Ve}from"@event-driven-io/dumbo";import{runPostgreSQLMigrations as me,schemaComponent as Z,single as Te}from"@event-driven-io/dumbo";import{v4 as Y}from"uuid";import{dumbo as pe,getDatabaseNameOrDefault as de,NodePostgresConnectorType as ue,runPostgreSQLMigrations as ge,schemaComponent as H}from"@event-driven-io/dumbo";var X=e=>e.connectorType===ue,B=e=>{let{connectionString:n,dbName:t}=e,o=t??de(n),i=pe({connectionString:n,...e.connectionOptions}),r=new Map,d={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collection:g=>K({collectionName:g,db:d,pool:i,sqlBuilder:W(g),...e.schema?e.schema:{},...e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:g=>i.withTransaction(g),schema:{get component(){return H("pongoDb",{components:[...r.values()].map(g=>g.schema.component)})},migrate:()=>ge(i,[...r.values()].flatMap(g=>g.schema.component.migrations({connector:"PostgreSQL:pg"})))}},p=e?.schema?.definition?.dbs;if(p){let g=P(p).map(S=>S[1]).find(S=>S.name===t||S.name===o);if(g)return G(d,g,r)}return d},je=e=>{let n=e.length>0&&typeof e[0]=="string"?e.map(t=>z(t)):e;return H("pongo:schema_component:db",{components:n})};var Oe=async(e,n)=>{let t=n?.session?.transaction;return!t||!t.isActive?null:await t.enlistDatabase(e)},J=async(e,n,t)=>(await Oe(e,n))?.execute??t,K=({db:e,collectionName:n,pool:t,sqlBuilder:o,schema:i,errors:r})=>{let d=t.execute,p=async(s,a)=>(await J(e,a,d)).command(s),g=async(s,a)=>(await J(e,a,d)).query(s),S=i?.autoMigration!=="None",E=s=>(S=!1,s?.session?p(o.createCollection(),s):p(o.createCollection())),u=s=>S?E(s):Promise.resolve(),m={dbName:e.databaseName,collectionName:n,createCollection:async s=>{await E(s)},insertOne:async(s,a)=>{await u(a);let c=s._id??Y(),l=s._version??1n,R=((await p(o.insertOne({...s,_id:c,_version:l}),a)).rowCount??0)>0;return C({successful:R,insertedId:R?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:n,errors:r})},insertMany:async(s,a)=>{await u(a);let c=s.map(x=>({...x,_id:x._id??Y(),_version:x._version??1n})),l=await p(o.insertMany(c),a);return C({successful:l.rowCount===c.length,insertedCount:l.rowCount??0,insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:n,errors:r})},updateOne:async(s,a,c)=>{await u(c);let l=await p(o.updateOne(s,a,c),c);return C({successful:l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"updateOne",collectionName:n,errors:r})},replaceOne:async(s,a,c)=>{await u(c);let l=await p(o.replaceOne(s,a,c),c);return C({successful:l.rows[0].modified>0,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"replaceOne",collectionName:n,errors:r})},updateMany:async(s,a,c)=>{await u(c);let l=await p(o.updateMany(s,a),c);return C({successful:!0,modifiedCount:l.rowCount??0,matchedCount:l.rowCount??0},{operationName:"updateMany",collectionName:n,errors:r})},deleteOne:async(s,a)=>{await u(a);let c=await p(o.deleteOne(s??{},a),a);return C({successful:c.rows[0].deleted>0,deletedCount:Number(c.rows[0].deleted),matchedCount:Number(c.rows[0].matched)},{operationName:"deleteOne",collectionName:n,errors:r})},deleteMany:async(s,a)=>{await u(a);let c=await p(o.deleteMany(s??{}),a);return C({successful:(c.rowCount??0)>0,deletedCount:c.rowCount??0,matchedCount:c.rowCount??0},{operationName:"deleteMany",collectionName:n,errors:r})},findOne:async(s,a)=>(await u(a),(await g(o.findOne(s??{}),a)).rows[0]?.data??null),findOneAndDelete:async(s,a)=>{await u(a);let c=await m.findOne(s,a);return c===null?null:(await m.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await u(c);let l=await m.findOne(s,c);return l===null?null:(await m.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await u(c);let l=await m.findOne(s,c);return l===null?null:(await m.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=c??{};await u(c);let R={_id:s},y=await m.findOne(R,c),I=w(l);if(y==null&&l==="DOCUMENT_EXISTS"||y==null&&I!=null||y!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||y!=null&&I!==null&&y._version!==I)return C({successful:!1,document:y},{operationName:"handle",collectionName:n,errors:r});let D=await a(y);if(y===D)return C({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r});if(!y&&D){let _={...D,_id:s},q=await m.insertOne({..._,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...q,document:{..._,_version:q.nextExpectedVersion}}}if(y&&!D)return{...await m.deleteOne(R,{...x,expectedVersion:I??"DOCUMENT_EXISTS"}),document:null};if(y&&D){let _=await m.replaceOne(R,D,{...x,expectedVersion:I??"DOCUMENT_EXISTS"});return{..._,document:{...D,_version:_.nextExpectedVersion}}}return C({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r})},find:async(s,a)=>(await u(a),(await g(o.find(s??{}))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await u(a);let{count:c}=await Te(g(o.countDocuments(s??{})));return c},drop:async s=>(await u(s),((await p(o.drop()))?.rowCount??0)>0),rename:async(s,a)=>(await u(a),await p(o.rename(s)),n=s,m),sql:{async query(s,a){return await u(a),(await g(s)).rows},async command(s,a){return await u(a),p(s)}},schema:{get component(){return Z("pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>me(t,o.migrations())}};return m},z=e=>Z("pongo:schema_component:collection",{migrations:()=>$(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},V={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye=e=>e.startsWith("$"),ne=e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Ce=e=>typeof e=="string",A=class e extends Error{errorCode;constructor(n){let t=n&&typeof n=="object"&&"errorCode"in n?n.errorCode:Pe(n)?n:500,o=n&&typeof n=="object"&&"message"in n?n.message:Ce(n)?n:`Error with status code '${t}' ocurred during Pongo processing`;super(o),this.errorCode=t,Object.setPrototypeOf(this,e.prototype)}},N=class e extends A{constructor(n){super({errorCode:412,message:n??"Expected document state does not match current one!"}),Object.setPrototypeOf(this,e.prototype)}};import{NodePostgresConnectorType as _e}from"@event-driven-io/dumbo";import"pg";var v=e=>{let{connectorType:n}=e;if(!X(e))throw new Error(`Unsupported db type: ${n}`);return B(e)};var te=e=>{let n=!1,t=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!n){if(t)throw new Error("Transaction is not active!");n=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");t||(t=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!t},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>e?.isActive===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Se(e){if(U(e))throw new Error("Active transaction already exists!")}var F=e=>{let n=e?.explicit===!0,t=e?.defaultTransactionOptions??{get snapshotEnabled(){return!1}},o=null,i=!1,r=E=>{Se(o),o=te(E??t)},d=async()=>{oe(o),await o.commit()},p=async()=>{oe(o),await o.rollback()},S={get hasEnded(){return i},explicit:n,defaultTransactionOptions:t??{get snapshotEnabled(){return!1}},get transaction(){return o},get snapshotEnabled(){return t.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:d,abortTransaction:p,withTransaction:async(E,u)=>{r(u);try{let m=await E(S);return await d(),m}catch(m){throw await p(),m}}};return S};var P=e=>Object.entries(e).map(([n,t])=>[n,t]);import{JSONSerializer as xe}from"@event-driven-io/dumbo";var dn="DOCUMENT_EXISTS",un="DOCUMENT_DOES_NOT_EXIST",be="NO_CONCURRENCY_CHECK",he=e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",w=e=>e===void 0||he(e)?null:e,gn=e=>e?BigInt(e):be,C=(e,n)=>{let t={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:d}=n;if(!i)throw new N(o??`${r} on ${d} failed. Expected document state does not match current one! Result: ${xe.serialize(e)}!`)}};return n.errors?.throwOnOperationFailures&&t.assertSuccessful(),t};var fe=e=>({name:e});function De(e,n){if(n===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:n}:{collections:n}}var Ee=e=>({dbs:e}),Cn={client:Ee,db:De,collection:fe},G=(e,n,t)=>{let o=Object.keys(n.collections);for(let i of o)t.set(i,e.collection(i));return new Proxy(e,{get(i,r){return t.get(r)??i[r]}})},ie=(e,n)=>{if(!n)return e;let t=Object.keys(n.dbs);return new Proxy(e,{get(o,i){return t.includes(i)?e.db(n.dbs[i]?.name):o[i]}})},Re=e=>({name:e.name,collections:P(e.collections).map(n=>({name:n[1].name}))}),Sn=e=>{let n=P(e.dbs).map(t=>Re(t[1]));return{databases:n,database:t=>n.find(o=>o.name===t)}};var _n=(e,n={})=>{let t=new Map,o=v(se({connectionString:e,clientOptions:n}));t.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of t.values())await r.close()},db:r=>r?t.get(r)??t.set(r,v(se({connectionString:e,dbName:r,clientOptions:n}))).get(r):o,startSession:F,withSession:async r=>{let d=F();try{return await r(d)}finally{await d.endSession()}}};return ie(i,n?.schema?.definition)},se=e=>({connectorType:_e,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});import{JSONSerializer as M,sql as T}from"@event-driven-io/dumbo";var Q=(e,n,t)=>{if(e==="_id"||e==="_version")return we(e,n,t);switch(n){case"$eq":return T("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",M.serialize(re(e,t)),e,M.serialize(t));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return T(`data #>> %L ${V[n]} %L`,`{${e.split(".").join(",")}}`,t);case"$in":return T("data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>T("%L",o)).join(", "));case"$nin":return T("data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>T("%L",o)).join(", "));case"$elemMatch":{let o=P(t).map(([i,r])=>T('@."%s" == %s',i,M.serialize(r))).join(" && ");return T("jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return T("data @> %L::jsonb",M.serialize(re(e,t)));case"$size":return T("jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,t);default:throw new Error(`Unsupported operator: ${n}`)}},we=(e,n,t)=>{switch(n){case"$eq":return T(`${e} = %L`,t);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return T(`${e} ${V[n]} %L`,t);case"$in":return T(`${e} IN (%s)`,t.map(o=>T("%L",o)).join(", "));case"$nin":return T(`${e} NOT IN (%s)`,t.map(o=>T("%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},re=(e,n)=>e.split(".").reverse().reduce((t,o)=>({[o]:t}),n);var ae="AND",h=e=>Object.entries(e).map(([n,t])=>Le(t)?Ie(n,t):Q(n,"$eq",t)).join(` ${ae} `),Ie=(e,n)=>{let t=!ne(n);return P(n).map(([o,i])=>t?Q(`${e}.${o}`,ee.$eq,i):Q(e,o,i)).join(` ${ae} `)},Le=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);import{JSONSerializer as ce,sql as L}from"@event-driven-io/dumbo";var j=e=>P(e).reduce((n,[t,o])=>{switch(t){case"$set":return Ne(o,n);case"$unset":return Ue(o,n);case"$inc":return Me(o,n);case"$push":return Qe(o,n);default:return n}},L("data")),Ne=(e,n)=>L("%s || %L::jsonb",n,ce.serialize(e)),Ue=(e,n)=>L("%s - %L",n,Object.keys(e).map(t=>`{${t}}`).join(", ")),Me=(e,n)=>{for(let[t,o]of Object.entries(e))n=L(typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",n,t,t,o);return n},Qe=(e,n)=>{for(let[t,o]of Object.entries(e))n=L("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",n,t,t,ce.serialize([o]));return n};var le=e=>O(`CREATE TABLE IF NOT EXISTS %I (
|
|
1
|
+
import{isSQL as b,JSONSerializer as k,rawSql as $e,sql as O,sqlMigration as Ve}from"@event-driven-io/dumbo";import{runPostgreSQLMigrations as Te,schemaComponent as Z,single as me}from"@event-driven-io/dumbo";import{v4 as Y}from"uuid";import{dumbo as pe,getDatabaseNameOrDefault as de,NodePostgresConnectorType as ue,runPostgreSQLMigrations as ge,schemaComponent as H}from"@event-driven-io/dumbo";var X=e=>e.connectorType===ue,B=e=>{let{connectionString:n,dbName:t}=e,o=t??de(n),i=pe({connectionString:n,...e.connectionOptions}),r=new Map,d={connectorType:e.connectorType,databaseName:o,connect:()=>Promise.resolve(),close:()=>i.close(),collection:g=>K({collectionName:g,db:d,pool:i,sqlBuilder:q(g),...e.schema?e.schema:{},...e.errors?e.errors:{}}),transaction:()=>i.transaction(),withTransaction:g=>i.withTransaction(g),schema:{get component(){return H("pongoDb",{components:[...r.values()].map(g=>g.schema.component)})},migrate:()=>ge(i,[...r.values()].flatMap(g=>g.schema.component.migrations({connector:"PostgreSQL:pg"})))}},p=e?.schema?.definition?.dbs;if(p){let g=P(p).map(C=>C[1]).find(C=>C.name===t||C.name===o);if(g)return G(d,g,r)}return d},je=e=>{let n=e.length>0&&typeof e[0]=="string"?e.map(t=>z(t)):e;return H("pongo:schema_component:db",{components:n})};var Oe=async(e,n)=>{let t=n?.session?.transaction;return!t||!t.isActive?null:await t.enlistDatabase(e)},J=async(e,n,t)=>(await Oe(e,n))?.execute??t,K=({db:e,collectionName:n,pool:t,sqlBuilder:o,schema:i,errors:r})=>{let d=t.execute,p=async(s,a)=>(await J(e,a,d)).command(s),g=async(s,a)=>(await J(e,a,d)).query(s),C=i?.autoMigration!=="None",E=s=>(C=!1,s?.session?p(o.createCollection(),s):p(o.createCollection())),u=s=>C?E(s):Promise.resolve(),T={dbName:e.databaseName,collectionName:n,createCollection:async s=>{await E(s)},insertOne:async(s,a)=>{await u(a);let c=s._id??Y(),l=s._version??1n,R=((await p(o.insertOne({...s,_id:c,_version:l}),a)).rowCount??0)>0;return S({successful:R,insertedId:R?c:null,nextExpectedVersion:l},{operationName:"insertOne",collectionName:n,errors:r})},insertMany:async(s,a)=>{await u(a);let c=s.map(x=>({...x,_id:x._id??Y(),_version:x._version??1n})),l=await p(o.insertMany(c),a);return S({successful:l.rowCount===c.length,insertedCount:l.rowCount??0,insertedIds:l.rows.map(x=>x._id)},{operationName:"insertMany",collectionName:n,errors:r})},updateOne:async(s,a,c)=>{await u(c);let l=await p(o.updateOne(s,a,c),c);return S({successful:l.rows[0].modified===l.rows[0].matched,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"updateOne",collectionName:n,errors:r})},replaceOne:async(s,a,c)=>{await u(c);let l=await p(o.replaceOne(s,a,c),c);return S({successful:l.rows[0].modified>0,modifiedCount:Number(l.rows[0].modified),matchedCount:Number(l.rows[0].matched),nextExpectedVersion:l.rows[0].version},{operationName:"replaceOne",collectionName:n,errors:r})},updateMany:async(s,a,c)=>{await u(c);let l=await p(o.updateMany(s,a),c);return S({successful:!0,modifiedCount:l.rowCount??0,matchedCount:l.rowCount??0},{operationName:"updateMany",collectionName:n,errors:r})},deleteOne:async(s,a)=>{await u(a);let c=await p(o.deleteOne(s??{},a),a);return S({successful:c.rows[0].deleted>0,deletedCount:Number(c.rows[0].deleted),matchedCount:Number(c.rows[0].matched)},{operationName:"deleteOne",collectionName:n,errors:r})},deleteMany:async(s,a)=>{await u(a);let c=await p(o.deleteMany(s??{}),a);return S({successful:(c.rowCount??0)>0,deletedCount:c.rowCount??0,matchedCount:c.rowCount??0},{operationName:"deleteMany",collectionName:n,errors:r})},findOne:async(s,a)=>(await u(a),(await g(o.findOne(s??{}),a)).rows[0]?.data??null),findOneAndDelete:async(s,a)=>{await u(a);let c=await T.findOne(s,a);return c===null?null:(await T.deleteOne(s,a),c)},findOneAndReplace:async(s,a,c)=>{await u(c);let l=await T.findOne(s,c);return l===null?null:(await T.replaceOne(s,a,c),l)},findOneAndUpdate:async(s,a,c)=>{await u(c);let l=await T.findOne(s,c);return l===null?null:(await T.updateOne(s,a,c),l)},handle:async(s,a,c)=>{let{expectedVersion:l,...x}=c??{};await u(c);let R={_id:s},y=await T.findOne(R,c),L=_(l);if(y==null&&l==="DOCUMENT_EXISTS"||y==null&&L!=null||y!=null&&l==="DOCUMENT_DOES_NOT_EXIST"||y!=null&&L!==null&&y._version!==L)return S({successful:!1,document:y},{operationName:"handle",collectionName:n,errors:r});let D=await a(y);if(y===D)return S({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r});if(!y&&D){let I={...D,_id:s},W=await T.insertOne({...I,_id:s},{...x,expectedVersion:"DOCUMENT_DOES_NOT_EXIST"});return{...W,document:{...I,_version:W.nextExpectedVersion}}}if(y&&!D)return{...await T.deleteOne(R,{...x,expectedVersion:L??"DOCUMENT_EXISTS"}),document:null};if(y&&D){let I=await T.replaceOne(R,D,{...x,expectedVersion:L??"DOCUMENT_EXISTS"});return{...I,document:{...D,_version:I.nextExpectedVersion}}}return S({successful:!0,document:y},{operationName:"handle",collectionName:n,errors:r})},find:async(s,a)=>(await u(a),(await g(o.find(s??{}))).rows.map(l=>l.data)),countDocuments:async(s,a)=>{await u(a);let{count:c}=await me(g(o.countDocuments(s??{})));return c},drop:async s=>(await u(s),((await p(o.drop()))?.rowCount??0)>0),rename:async(s,a)=>(await u(a),await p(o.rename(s)),n=s,T),sql:{async query(s,a){return await u(a),(await g(s)).rows},async command(s,a){return await u(a),p(s)}},schema:{get component(){return Z("pongo:schema_component:collection",{migrations:o.migrations})},migrate:()=>Te(t,o.migrations())}};return T},z=e=>Z("pongo:schema_component:collection",{migrations:()=>$(e)});var ee={$eq:"$eq",$gt:"$gt",$gte:"$gte",$lt:"$lt",$lte:"$lte",$ne:"$ne",$in:"$in",$nin:"$nin",$elemMatch:"$elemMatch",$all:"$all",$size:"$size"},V={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="},ye=e=>e.startsWith("$"),ne=e=>Object.keys(e).some(ye);var Pe=e=>typeof e=="number"&&e===e,Se=e=>typeof e=="string",A=class e extends Error{errorCode;constructor(n){let t=n&&typeof n=="object"&&"errorCode"in n?n.errorCode:Pe(n)?n:500,o=n&&typeof n=="object"&&"message"in n?n.message:Se(n)?n:`Error with status code '${t}' ocurred during Pongo processing`;super(o),this.errorCode=t,Object.setPrototypeOf(this,e.prototype)}},N=class e extends A{constructor(n){super({errorCode:412,message:n??"Expected document state does not match current one!"}),Object.setPrototypeOf(this,e.prototype)}};import{NodePostgresConnectorType as Ie}from"@event-driven-io/dumbo";import"pg";var v=e=>{let{connectorType:n}=e;if(!X(e))throw new Error(`Unsupported db type: ${n}`);return B(e)};var te=e=>{let n=!1,t=!1,o=null,i=null;return{enlistDatabase:async r=>{if(i&&o!==r.databaseName)throw new Error("There's already other database assigned to transaction");return i&&o===r.databaseName||(o=r.databaseName,i=r.transaction(),await i.begin()),i},commit:async()=>{if(!i)throw new Error("No database transaction started!");if(!n){if(t)throw new Error("Transaction is not active!");n=!0,await i.commit(),i=null}},rollback:async r=>{if(!i)throw new Error("No database transaction started!");if(n)throw new Error("Cannot rollback commited transaction!");t||(t=!0,await i.rollback(r),i=null)},databaseName:o,isStarting:!1,isCommitted:n,get isActive(){return!n&&!t},get sqlExecutor(){if(i===null)throw new Error("No database transaction was started");return i.execute},options:e}};var U=e=>e?.isActive===!0;function oe(e){if(!U(e))throw new Error("No active transaction exists!")}function Ce(e){if(U(e))throw new Error("Active transaction already exists!")}var F=e=>{let n=e?.explicit===!0,t=e?.defaultTransactionOptions??{get snapshotEnabled(){return!1}},o=null,i=!1,r=E=>{Ce(o),o=te(E??t)},d=async()=>{oe(o),await o.commit()},p=async()=>{oe(o),await o.rollback()},C={get hasEnded(){return i},explicit:n,defaultTransactionOptions:t??{get snapshotEnabled(){return!1}},get transaction(){return o},get snapshotEnabled(){return t.snapshotEnabled},endSession:async()=>{i||(i=!0,U(o)&&await o.rollback())},incrementTransactionNumber:()=>{},inTransaction:()=>U(o),startTransaction:r,commitTransaction:d,abortTransaction:p,withTransaction:async(E,u)=>{r(u);try{let T=await E(C);return await d(),T}catch(T){throw await p(),T}}};return C};var P=e=>Object.entries(e).map(([n,t])=>[n,t]);import{JSONSerializer as xe}from"@event-driven-io/dumbo";var dn="DOCUMENT_EXISTS",un="DOCUMENT_DOES_NOT_EXIST",be="NO_CONCURRENCY_CHECK",he=e=>e==="DOCUMENT_DOES_NOT_EXIST"||e==="DOCUMENT_EXISTS"||e==="NO_CONCURRENCY_CHECK",_=e=>e===void 0||he(e)?null:e,gn=e=>e?BigInt(e):be,S=(e,n)=>{let t={...e,acknowledged:!0,successful:e.successful,assertSuccessful:o=>{let{successful:i}=e,{operationName:r,collectionName:d}=n;if(!i)throw new N(o??`${r} on ${d} failed. Expected document state does not match current one! Result: ${xe.serialize(e)}!`)}};return n.errors?.throwOnOperationFailures&&t.assertSuccessful(),t};var fe=e=>({name:e});function De(e,n){if(n===void 0){if(typeof e=="string")throw new Error("You need to provide colleciton definition");return{collections:e}}return e&&typeof e=="string"?{name:e,collections:n}:{collections:n}}var Ee=e=>({dbs:e}),Sn={client:Ee,db:De,collection:fe},G=(e,n,t)=>{let o=Object.keys(n.collections);for(let i of o)t.set(i,e.collection(i));return new Proxy(e,{get(i,r){return t.get(r)??i[r]}})},ie=(e,n)=>{if(!n)return e;let t=Object.keys(n.dbs);return new Proxy(e,{get(o,i){return t.includes(i)?e.db(n.dbs[i]?.name):o[i]}})},Re=e=>({name:e.name,collections:P(e.collections).map(n=>({name:n[1].name}))}),Cn=e=>{let n=P(e.dbs).map(t=>Re(t[1]));return{databases:n,database:t=>n.find(o=>o.name===t)}};var In=(e,n={})=>{let t=new Map,o=v(se({connectionString:e,clientOptions:n}));t.set(o.databaseName,o);let i={connect:async()=>(await o.connect(),i),close:async()=>{for(let r of t.values())await r.close()},db:r=>r?t.get(r)??t.set(r,v(se({connectionString:e,dbName:r,clientOptions:n}))).get(r):o,startSession:F,withSession:async r=>{let d=F();try{return await r(d)}finally{await d.endSession()}}};return ie(i,n?.schema?.definition)},se=e=>({connectorType:Ie,connectionString:e.connectionString,dbName:e.dbName,...e.clientOptions});import{JSONSerializer as Q,sql as m}from"@event-driven-io/dumbo";var M=(e,n,t)=>{if(e==="_id"||e==="_version")return _e(e,n,t);switch(n){case"$eq":return m("(data @> %L::jsonb OR jsonb_path_exists(data, '$.%s[*] ? (@ == %s)'))",Q.serialize(re(e,t)),e,Q.serialize(t));case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return m(`data #>> %L ${V[n]} %L`,`{${e.split(".").join(",")}}`,t);case"$in":return m("data #>> %L IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>m("%L",o)).join(", "));case"$nin":return m("data #>> %L NOT IN (%s)",`{${e.split(".").join(",")}}`,t.map(o=>m("%L",o)).join(", "));case"$elemMatch":{let o=P(t).map(([i,r])=>m('@."%s" == %s',i,Q.serialize(r))).join(" && ");return m("jsonb_path_exists(data, '$.%s[*] ? (%s)')",e,o)}case"$all":return m("data @> %L::jsonb",Q.serialize(re(e,t)));case"$size":return m("jsonb_array_length(data #> %L) = %L",`{${e.split(".").join(",")}}`,t);default:throw new Error(`Unsupported operator: ${n}`)}},_e=(e,n,t)=>{switch(n){case"$eq":return m(`${e} = %L`,t);case"$gt":case"$gte":case"$lt":case"$lte":case"$ne":return m(`${e} ${V[n]} %L`,t);case"$in":return m(`${e} IN (%s)`,t.map(o=>m("%L",o)).join(", "));case"$nin":return m(`${e} NOT IN (%s)`,t.map(o=>m("%L",o)).join(", "));default:throw new Error(`Unsupported operator: ${n}`)}},re=(e,n)=>e.split(".").reverse().reduce((t,o)=>({[o]:t}),n);var ae="AND",h=e=>Object.entries(e).map(([n,t])=>we(t)?Le(n,t):M(n,"$eq",t)).join(` ${ae} `),Le=(e,n)=>{let t=!ne(n);return P(n).map(([o,i])=>t?M(`${e}.${o}`,ee.$eq,i):M(e,o,i)).join(` ${ae} `)},we=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);import{JSONSerializer as ce,sql as w}from"@event-driven-io/dumbo";var j=e=>P(e).reduce((n,[t,o])=>{switch(t){case"$set":return Ne(o,n);case"$unset":return Ue(o,n);case"$inc":return Qe(o,n);case"$push":return Me(o,n);default:return n}},w("data")),Ne=(e,n)=>w("%s || %L::jsonb",n,ce.serialize(e)),Ue=(e,n)=>w("%s - %L",n,Object.keys(e).map(t=>`{${t}}`).join(", ")),Qe=(e,n)=>{for(let[t,o]of Object.entries(e))n=w(typeof o=="bigint"?"jsonb_set(%s, '{%s}', to_jsonb((COALESCE((data->>'%s')::BIGINT, 0) + %L)::TEXT), true)":"jsonb_set(%s, '{%s}', to_jsonb(COALESCE((data->>'%s')::NUMERIC, 0) + %L), true)",n,t,t,o);return n},Me=(e,n)=>{for(let[t,o]of Object.entries(e))n=w("jsonb_set(%s, '{%s}', (coalesce(data->'%s', '[]'::jsonb) || %L::jsonb), true)",n,t,t,ce.serialize([o]));return n};var le=e=>O(`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,9 +7,9 @@ import{isSQL as b,JSONSerializer as k,rawSql as $e,sql as O,sqlMigration as Ve}f
|
|
|
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
|
-
)`,e),$=e=>[Ve(`pongoCollection:${e}:001:createtable`,[le(e)])],
|
|
10
|
+
)`,e),$=e=>[Ve(`pongoCollection:${e}:001:createtable`,[le(e)])],q=e=>({migrations:()=>$(e),createCollection:()=>le(e),insertOne:n=>O("INSERT INTO %I (_id, data, _version) VALUES (%L, %L, %L) ON CONFLICT(_id) DO NOTHING;",e,n._id,k.serialize(n),n._version??1n),insertMany:n=>{let t=n.map(o=>O("(%L, %L, %L)",o._id,k.serialize(o),o._version??1n)).join(", ");return O(`INSERT INTO %I (_id, data, _version) VALUES %s
|
|
11
11
|
ON CONFLICT(_id) DO NOTHING
|
|
12
|
-
RETURNING _id;`,e,t)},updateOne:(n,t,o)=>{let i=
|
|
12
|
+
RETURNING _id;`,e,t)},updateOne:(n,t,o)=>{let i=_(o?.expectedVersion),r=i!=null?"AND %I._version = %L":"",d=i!=null?[e,i]:[],p=b(n)?n:h(n),g=b(t)?n:j(t);return O(`WITH existing AS (
|
|
13
13
|
SELECT _id, _version as current_version
|
|
14
14
|
FROM %I %s
|
|
15
15
|
LIMIT 1
|
|
@@ -30,7 +30,7 @@ import{isSQL as b,JSONSerializer as k,rawSql as $e,sql as O,sqlMigration as Ve}f
|
|
|
30
30
|
COUNT(updated._id) over() AS modified
|
|
31
31
|
FROM existing
|
|
32
32
|
LEFT JOIN updated
|
|
33
|
-
ON existing._id = updated._id;`,e,f(p),e,g,e,e,...d,e,e)},replaceOne:(n,t,o)=>{let i=
|
|
33
|
+
ON existing._id = updated._id;`,e,f(p),e,g,e,e,...d,e,e)},replaceOne:(n,t,o)=>{let i=_(o?.expectedVersion),r=i!=null?"AND %I._version = %L":"",d=i!=null?[e,i]:[],p=b(n)?n:h(n);return O(`WITH existing AS (
|
|
34
34
|
SELECT _id, _version as current_version
|
|
35
35
|
FROM %I %s
|
|
36
36
|
LIMIT 1
|
|
@@ -55,7 +55,7 @@ import{isSQL as b,JSONSerializer as k,rawSql as $e,sql as O,sqlMigration as Ve}f
|
|
|
55
55
|
SET
|
|
56
56
|
data = %s || jsonb_build_object('_version', (_version + 1)::text),
|
|
57
57
|
_version = _version + 1
|
|
58
|
-
%s;`,e,i,f(o))},deleteOne:(n,t)=>{let o=
|
|
58
|
+
%s;`,e,i,f(o))},deleteOne:(n,t)=>{let o=_(t?.expectedVersion),i=o!=null?"AND %I._version = %L":"",r=o!=null?[e,o]:[],d=b(n)?n:h(n);return O(`WITH existing AS (
|
|
59
59
|
SELECT _id
|
|
60
60
|
FROM %I %s
|
|
61
61
|
LIMIT 1
|
|
@@ -72,5 +72,5 @@ import{isSQL as b,JSONSerializer as k,rawSql as $e,sql as O,sqlMigration as Ve}f
|
|
|
72
72
|
COUNT(deleted._id) over() AS deleted
|
|
73
73
|
FROM existing
|
|
74
74
|
LEFT JOIN deleted
|
|
75
|
-
ON existing._id = deleted._id;`,e,f(d),e,e,...r,e)},deleteMany:n=>{let t=b(n)?n:h(n);return O("DELETE FROM %I %s",e,f(t))},findOne:n=>{let t=b(n)?n:h(n);return O("SELECT data FROM %I %s LIMIT 1;",e,f(t))},find:n=>{let t=b(n)?n:h(n);return O("SELECT data FROM %I %s;",e,f(t))},countDocuments:n=>{let t=b(n)?n:h(n);return O("SELECT COUNT(1) as count FROM %I %s;",e,f(t))},rename:n=>O("ALTER TABLE %I RENAME TO %I;",e,n),drop:(n=e)=>O("DROP TABLE IF EXISTS %I",n)}),f=e=>e.length>0?O("WHERE %s",e):$e("");export{$ as a,
|
|
76
|
-
//# sourceMappingURL=chunk-
|
|
75
|
+
ON existing._id = deleted._id;`,e,f(d),e,e,...r,e)},deleteMany:n=>{let t=b(n)?n:h(n);return O("DELETE FROM %I %s",e,f(t))},findOne:n=>{let t=b(n)?n:h(n);return O("SELECT data FROM %I %s LIMIT 1;",e,f(t))},find:n=>{let t=b(n)?n:h(n);return O("SELECT data FROM %I %s;",e,f(t))},countDocuments:n=>{let t=b(n)?n:h(n);return O("SELECT COUNT(1) as count FROM %I %s;",e,f(t))},rename:n=>O("ALTER TABLE %I RENAME TO %I;",e,n),drop:(n=e)=>O("DROP TABLE IF EXISTS %I",n)}),f=e=>e.length>0?O("WHERE %s",e):$e("");export{$ as a,q as b,X as c,B as d,je as e,K as f,z as g,ee as h,V as i,ye as j,ne as k,Pe as l,Se as m,A as n,N as o,v as p,te as q,F as r,P as s,dn as t,un as u,be as v,he as w,_ as x,gn as y,S as z,Sn as A,G as B,ie as C,Re as D,Cn as E,In as F,se as G};
|
|
76
|
+
//# sourceMappingURL=chunk-AG3WMJNZ.js.map
|