@event-driven-io/emmett-postgresql 0.18.0 → 0.19.0-alpha.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/index.js CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _dumbo = require('@event-driven-io/dumbo');var _uuid = require('uuid');var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var _webstreamspolyfill = require('web-streams-polyfill');var ue=(e=>(e.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",e.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",e.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",e))(ue||{}),ge=e=>typeof e=="number"&&e===e,Se=e=>typeof e=="string";var V=e=>typeof e=="function"&&e.prototype&&e.prototype.constructor===e,ye=class G extends Error{constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:ge(t)?t:500,o=t&&typeof t=="object"&&"message"in t?t.message:Se(t)?t:`Error with status code '${n}' ocurred during Emmett processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,G.prototype)}},fe=class W extends ye{constructor(t,n,o){super({errorCode:412,message:_nullishCoalesce(o, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([t, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))}),this.current=t,this.expected=n,Object.setPrototypeOf(this,W.prototype)}};var D="STREAM_EXISTS",x="STREAM_DOES_NOT_EXIST",O="NO_CONCURRENCY_CHECK";var U=class z extends fe{constructor(t,n){super(_optionalChain([t, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]),_optionalChain([n, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()])),Object.setPrototypeOf(this,z.prototype)}};var H=(e,t,n)=>({type:e,data:t,metadata:n});var k=e=>e;var Pe=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},P={stringify:(e,t)=>JSON.stringify(_optionalChain([t, 'optionalAccess', _8 => _8.map])?t.map(e):e,(n,o)=>typeof o=="bigint"?o.toString():o),parse:(e,t)=>{let n=JSON.parse(e,_optionalChain([t, 'optionalAccess', _9 => _9.reviver]));if(_optionalChain([t, 'optionalAccess', _10 => _10.typeCheck])&&!_optionalChain([t, 'optionalAccess', _11 => _11.typeCheck, 'call', _12 => _12(n)]))throw new Pe(e);return _optionalChain([t, 'optionalAccess', _13 => _13.map])?t.map(n):n}};var u=(e,t)=>{if(he(e))return e.equals(t);if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((a,s)=>u(a,t[s]));if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e===t;if(Array.isArray(t))return!1;let n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length||!n.every(a=>o.includes(a)))return!1;for(let a in e)if(!(e[a]instanceof Function&&t[a]instanceof Function)&&!u(e[a],t[a]))return!1;return!0},he=e=>e&&typeof e=="object"&&"equals"in e&&typeof e.equals=="function";var y=class extends Error{constructor(e){super(e)}};var q=e=>{throw new y(_nullishCoalesce(e, () => ("That should not ever happened, right?")))};var Y=(e,t,n)=>{if(!u(e,t))throw new y(_nullishCoalesce(n, () => (`subObj:
1
+ import{dumbo as We}from"@event-driven-io/dumbo";import"commander";var G=(e=>(e.NOT_A_NONEMPTY_STRING="NOT_A_NONEMPTY_STRING",e.NOT_A_POSITIVE_NUMBER="NOT_A_POSITIVE_NUMBER",e.NOT_AN_UNSIGNED_BIGINT="NOT_AN_UNSIGNED_BIGINT",e))(G||{}),W=e=>typeof e=="number"&&e===e,z=e=>typeof e=="string";var U=e=>typeof e=="function"&&e.prototype&&e.prototype.constructor===e,H=class k extends Error{errorCode;constructor(t){let n=t&&typeof t=="object"&&"errorCode"in t?t.errorCode:W(t)?t:500,o=t&&typeof t=="object"&&"message"in t?t.message:z(t)?t:`Error with status code '${n}' ocurred during Emmett processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,k.prototype)}},q=class Y extends H{constructor(t,n,o){super({errorCode:412,message:o??`Expected version ${n.toString()} does not match current ${t?.toString()}`}),this.current=t,this.expected=n,Object.setPrototypeOf(this,Y.prototype)}};import{v4 as dt}from"uuid";import Et from"async-retry";import{TransformStream as _t}from"web-streams-polyfill";var D="STREAM_EXISTS",x="STREAM_DOES_NOT_EXIST",O="NO_CONCURRENCY_CHECK";var $=class J extends q{constructor(t,n){super(t?.toString(),n?.toString()),Object.setPrototypeOf(this,J.prototype)}};var K=(e,t,n)=>({type:e,data:t,metadata:n});var Z=e=>e;var Pe=class extends Error{constructor(e){super(`Cannot parse! ${e}`)}},P={stringify:(e,t)=>JSON.stringify(t?.map?t.map(e):e,(n,o)=>typeof o=="bigint"?o.toString():o),parse:(e,t)=>{let n=JSON.parse(e,t?.reviver);if(t?.typeCheck&&!t?.typeCheck(n))throw new Pe(e);return t?.map?t.map(n):n}};var u=(e,t)=>{if(he(e))return e.equals(t);if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((a,s)=>u(a,t[s]));if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e===t;if(Array.isArray(t))return!1;let n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length||!n.every(a=>o.includes(a)))return!1;for(let a in e)if(!(e[a]instanceof Function&&t[a]instanceof Function)&&!u(e[a],t[a]))return!1;return!0},he=e=>e&&typeof e=="object"&&"equals"in e&&typeof e.equals=="function";var y=class extends Error{constructor(e){super(e)}};var ee=e=>{throw new y(e??"That should not ever happened, right?")};var te=(e,t,n)=>{if(!u(e,t))throw new y(n??`subObj:
2
2
  ${P.stringify(t)}
3
3
  is not equal to
4
- ${P.stringify(e)}`)))};function T(e,t){if(!e)throw new y(_nullishCoalesce(t, () => ("Condition is false")))}function Ie(e,t){if(!e)throw new y(_nullishCoalesce(t, () => ("Condition is not truthy")))}function S(e,t,n){if(e!==t)throw new y(`${_nullishCoalesce(n, () => ("Objects are not equal"))}:
4
+ ${P.stringify(e)}`)};function T(e,t){if(!e)throw new y(t??"Condition is false")}function Ie(e,t){if(!e)throw new y(t??"Condition is not truthy")}function S(e,t,n){if(e!==t)throw new y(`${n??"Objects are not equal"}:
5
5
  Expected: ${P.stringify(e)}
6
- Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoalesce(n, () => (`Objects are equal: ${P.stringify(e)}`)))}function $(e){J(e,null),Ie(e)}var R=e=>({isEmpty:()=>S(e.length,0),isNotEmpty:()=>J(e.length,0),hasSize:t=>S(e.length,t),containsElements:(...t)=>{T(t.every(n=>t.some(o=>u(n,o))))},containsExactlyInAnyOrder:(...t)=>{S(e.length,t.length),T(e.every(n=>t.some(o=>u(n,o))))},containsExactlyInAnyOrderElementsOf:t=>{S(e.length,t.length),T(e.every(n=>t.some(o=>u(n,o))))},containsExactlyElementsOf:t=>{S(e.length,t.length);for(let n=0;n<e.length;n++)T(u(e[n],t[n]))},containsExactly:t=>{S(e.length,1),T(u(e[0],t))},contains:t=>{T(e.some(n=>u(n,t)))},containsOnlyOnceElementsOf:t=>{T(t.map(n=>e.filter(o=>u(o,n)).length).filter(n=>n===1).length===t.length)},containsAnyOf:(...t)=>{T(e.some(n=>t.some(o=>u(n,o))))},allMatch:t=>{T(e.every(t))},anyMatches:t=>{T(e.some(t))},allMatchAsync:async t=>{for(let n of e)T(await t(n))}});require('pg');var _pongo = require('@event-driven-io/pongo');var A=(e,t)=>{let{pool:n,connectionString:o,inDatabase:a,inCollection:s}=t;return n.withConnection(async p=>{let m=_pongo.pongoClient.call(void 0, o,{connection:p});try{let E=m.db(a).collection(s);return e(E)}finally{await m.close()}})},K=e=>{let{_id:t,...n}=e;return n},Ne=(e,t)=>("_id"in t&&S(t._id,e._id,`Document ids are not matching! Expected: ${t._id}, actual: ${e._id}`),Y(K(e),K(t))),Re= exports.documentExists =(e,t)=>n=>A(async o=>{let a=await o.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);$(a),Ne(a,e)},{...t,...n}),Ae= exports.documentsAreTheSame =(e,t)=>n=>A(async o=>{let a=await o.find("withId"in t?{_id:t.withId}:t.matchingFilter);S(e.length,a.length,"Different Documents Count than expected");for(let s=0;s<e.length;s++)R(a).contains(e[s])},{...t,...n}),Le= exports.documentsMatchingHaveCount =(e,t)=>n=>A(async o=>{let a=await o.find("withId"in t?{_id:t.withId}:t.matchingFilter);S(e,a.length,"Different Documents Count than expected")},{...t,...n}),Z= exports.documentMatchingExists =e=>t=>A(async n=>{let o=await n.find("withId"in e?{_id:e.withId}:e.matchingFilter);R(o).isNotEmpty()},{...e,...t}),ee= exports.documentDoesNotExist =e=>t=>A(async n=>{let o=await n.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);$(o)},{...e,...t}),dt= exports.expectPongoDocuments ={fromCollection:e=>({withId:t=>({toBeEqual:n=>Re(n,{withId:t,inCollection:e}),toExist:()=>Z({withId:t,inCollection:e}),notToExist:()=>ee({withId:t,inCollection:e})}),matching:t=>({toBeTheSame:n=>Ae(n,{matchingFilter:t,inCollection:e}),toHaveCount:n=>Le(n,{matchingFilter:t,inCollection:e}),toExist:()=>Z({matchingFilter:t,inCollection:e}),notToExist:()=>ee({matchingFilter:t,inCollection:e})})})};var xe=({handle:e,canHandle:t})=>j({canHandle:t,handle:async(n,o)=>{let{connectionString:a,client:s}=o,p=_pongo.pongoClient.call(void 0, a,{client:s});await e(n,{...o,pongo:p})}}),Ce= exports.pongoMultiStreamProjection =e=>{let{collectionName:t,getDocumentId:n,canHandle:o}=e;return xe({handle:async(a,{pongo:s})=>{let p=s.db().collection(t);for(let m of a)await p.handle(n(m),async E=>"initialState"in e?await e.evolve(_nullishCoalesce(E, () => (e.initialState())),m):await e.evolve(E,m))},canHandle:o})},vt= exports.pongoSingleStreamProjection =e=>Ce({...e,getDocumentId:t=>t.metadata.streamName});var It={for:e=>{{let{projection:t,...n}=e,{connectionString:o}=n;return a=>({when:(s,p)=>{let m=[],E=async c=>{let l=0n,d=_nullishCoalesce(_optionalChain([p, 'optionalAccess', _14 => _14.numberOfTimes]), () => (1));for(let _ of[...a,...Array.from({length:d}).flatMap(()=>s)])m.push({..._,metadata:{globalPosition:++l,streamPosition:l,streamName:`test-${_uuid.v4.call(void 0, )}`,eventId:_uuid.v4.call(void 0, ),..._nullishCoalesce(_.metadata, () => ({}))}});await c.withTransaction(_=>C({events:m,projections:[t],connection:{connectionString:o,transaction:_}}))};return{then:async(c,l)=>{let d=_dumbo.dumbo.call(void 0, n);try{await E(d);let _=await c({pool:d,connectionString:o});_!==void 0&&_===!1&&q(_nullishCoalesce(l, () => ("Projection specification didn't match the criteria")))}finally{await d.close()}},thenThrows:async(...c)=>{let l=_dumbo.dumbo.call(void 0, n);try{throw await E(l),new y("Handler did not fail as expected")}catch(d){if(d instanceof y)throw d;if(c.length===0)return;if(!V(c[0])){T(c[0](d),`Error didn't match the error condition: ${_optionalChain([d, 'optionalAccess', _15 => _15.toString, 'call', _16 => _16()])}`);return}T(d instanceof c[0],`Caught error is not an instance of the expected type: ${_optionalChain([d, 'optionalAccess', _17 => _17.toString, 'call', _18 => _18()])}`),c[1]&&T(c[1](d),`Error didn't match the error condition: ${_optionalChain([d, 'optionalAccess', _19 => _19.toString, 'call', _20 => _20()])}`)}finally{await l.close()}}}}})}}},we= exports.eventInStream =(e,t)=>({...t,metadata:{..._nullishCoalesce(t.metadata, () => ({})),streamName:_nullishCoalesce(_optionalChain([t, 'access', _21 => _21.metadata, 'optionalAccess', _22 => _22.streamName]), () => (e))}}),be= exports.eventsInStream =(e,t)=>t.map(n=>we(e,n)),Ot= exports.newEventsInStream =be,Me= exports.assertSQLQueryResultMatches =(e,t)=>async({pool:{execute:n}})=>{let o=await n.query(e);R(t).containsExactlyInAnyOrder(...o.rows)},Nt= exports.expectSQL ={query:e=>({resultRows:{toBeTheSame:t=>Me(e,t)}})};var C=async e=>{let{projections:t,events:n,connection:{transaction:o,connectionString:a}}=e,s=n.map(E=>E.type),p=t.filter(E=>E.canHandle.some(c=>s.includes(c))),m=await o.connection.open();for(let E of p)await E.handle(n,{connectionString:a,client:m,transaction:o,execute:o.execute})},j= exports.postgreSQLProjection =e=>k(e),Fe= exports.postgreSQLRawBatchSQLProjection =(e,...t)=>j({canHandle:t,handle:async(n,o)=>{let a=await e(n,o);await o.execute.batchCommand(a)}}),Dt= exports.postgreSQLRawSQLProjection =(e,...t)=>Fe(async(n,o)=>{let a=[];for(let s of n)a.push(await e(s,o));return a},...t);var w="emt",v= exports.globalTag ="global",N= exports.defaultTag ="emt:default",bt= exports.globalNames ={module:`${w}:module:${v}`,tenant:`${w}:tenant:${v}`},b={partition:{name:"partition"},isArchived:{name:"is_archived"}},i= exports.streamsTable ={name:`${w}_streams`,columns:{partition:b.partition,isArchived:b.isArchived}},r= exports.eventsTable ={name:`${w}_events`,columns:{partition:b.partition,isArchived:b.isArchived}};var oe=_dumbo.rawSql.call(void 0, `CREATE OR REPLACE FUNCTION emt_append_event(
6
+ Actual:${P.stringify(t)}`)}function ne(e,t,n){if(e===t)throw new y(n??`Objects are equal: ${P.stringify(e)}`)}function j(e){ne(e,null),Ie(e)}var R=e=>({isEmpty:()=>S(e.length,0),isNotEmpty:()=>ne(e.length,0),hasSize:t=>S(e.length,t),containsElements:(...t)=>{T(t.every(n=>t.some(o=>u(n,o))))},containsExactlyInAnyOrder:(...t)=>{S(e.length,t.length),T(e.every(n=>t.some(o=>u(n,o))))},containsExactlyInAnyOrderElementsOf:t=>{S(e.length,t.length),T(e.every(n=>t.some(o=>u(n,o))))},containsExactlyElementsOf:t=>{S(e.length,t.length);for(let n=0;n<e.length;n++)T(u(e[n],t[n]))},containsExactly:t=>{S(e.length,1),T(u(e[0],t))},contains:t=>{T(e.some(n=>u(n,t)))},containsOnlyOnceElementsOf:t=>{T(t.map(n=>e.filter(o=>u(o,n)).length).filter(n=>n===1).length===t.length)},containsAnyOf:(...t)=>{T(e.some(n=>t.some(o=>u(n,o))))},allMatch:t=>{T(e.every(t))},anyMatches:t=>{T(e.some(t))},allMatchAsync:async t=>{for(let n of e)T(await t(n))}});import"pg";import"@event-driven-io/dumbo";import"@event-driven-io/dumbo";import{pongoClient as Oe}from"@event-driven-io/pongo";var A=(e,t)=>{let{pool:n,connectionString:o,inDatabase:a,inCollection:s}=t;return n.withConnection(async p=>{let m=Oe(o,{connectionOptions:{connection:p}});try{let l=m.db(a).collection(s);return e(l)}finally{await m.close()}})},oe=e=>{let{_id:t,...n}=e;return n},Ne=(e,t)=>("_id"in t&&S(t._id,e._id,`Document ids are not matching! Expected: ${t._id}, actual: ${e._id}`),te(oe(e),oe(t))),Re=(e,t)=>n=>A(async o=>{let a=await o.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);j(a),Ne(a,e)},{...t,...n}),Ae=(e,t)=>n=>A(async o=>{let a=await o.find("withId"in t?{_id:t.withId}:t.matchingFilter);S(e.length,a.length,"Different Documents Count than expected");for(let s=0;s<e.length;s++)R(a).contains(e[s])},{...t,...n}),Le=(e,t)=>n=>A(async o=>{let a=await o.find("withId"in t?{_id:t.withId}:t.matchingFilter);S(e,a.length,"Different Documents Count than expected")},{...t,...n}),ae=e=>t=>A(async n=>{let o=await n.find("withId"in e?{_id:e.withId}:e.matchingFilter);R(o).isNotEmpty()},{...e,...t}),re=e=>t=>A(async n=>{let o=await n.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);j(o)},{...e,...t}),Pt={fromCollection:e=>({withId:t=>({toBeEqual:n=>Re(n,{withId:t,inCollection:e}),toExist:()=>ae({withId:t,inCollection:e}),notToExist:()=>re({withId:t,inCollection:e})}),matching:t=>({toBeTheSame:n=>Ae(n,{matchingFilter:t,inCollection:e}),toHaveCount:n=>Le(n,{matchingFilter:t,inCollection:e}),toExist:()=>ae({matchingFilter:t,inCollection:e}),notToExist:()=>re({matchingFilter:t,inCollection:e})})})};import{pongoClient as De}from"@event-driven-io/pongo";var xe=({handle:e,canHandle:t})=>Q({canHandle:t,handle:async(n,o)=>{let{connectionString:a,client:s}=o,p=De(a,{connectionOptions:{client:s}});await e(n,{...o,pongo:p})}}),Ce=e=>{let{collectionName:t,getDocumentId:n,canHandle:o}=e;return xe({handle:async(a,{pongo:s})=>{let p=s.db().collection(t);for(let m of a)await p.handle(n(m),async l=>"initialState"in e?await e.evolve(l??e.initialState(),m):await e.evolve(l,m))},canHandle:o})},Rt=e=>Ce({...e,getDocumentId:t=>t.metadata.streamName});import{dumbo as ie}from"@event-driven-io/dumbo";import{v4 as se}from"uuid";var Ft={for:e=>{{let{projection:t,...n}=e,{connectionString:o}=n;return a=>({when:(s,p)=>{let m=[],l=async c=>{let E=0n,d=p?.numberOfTimes??1;for(let _ of[...a,...Array.from({length:d}).flatMap(()=>s)])m.push({..._,metadata:{globalPosition:++E,streamPosition:E,streamName:`test-${se()}`,eventId:se(),..._.metadata??{}}});await c.withTransaction(_=>C({events:m,projections:[t],connection:{connectionString:o,transaction:_}}))};return{then:async(c,E)=>{let d=ie(n);try{await l(d);let _=await c({pool:d,connectionString:o});_!==void 0&&_===!1&&ee(E??"Projection specification didn't match the criteria")}finally{await d.close()}},thenThrows:async(...c)=>{let E=ie(n);try{throw await l(E),new y("Handler did not fail as expected")}catch(d){if(d instanceof y)throw d;if(c.length===0)return;if(!U(c[0])){T(c[0](d),`Error didn't match the error condition: ${d?.toString()}`);return}T(d instanceof c[0],`Caught error is not an instance of the expected type: ${d?.toString()}`),c[1]&&T(c[1](d),`Error didn't match the error condition: ${d?.toString()}`)}finally{await E.close()}}}}})}}},we=(e,t)=>({...t,metadata:{...t.metadata??{},streamName:t.metadata?.streamName??e}}),be=(e,t)=>t.map(n=>we(e,n)),Ut=be,Me=(e,t)=>async({pool:{execute:n}})=>{let o=await n.query(e);R(t).containsExactlyInAnyOrder(...o.rows)},$t={query:e=>({resultRows:{toBeTheSame:t=>Me(e,t)}})};var C=async e=>{let{projections:t,events:n,connection:{transaction:o,connectionString:a}}=e,s=n.map(l=>l.type),p=t.filter(l=>l.canHandle.some(c=>s.includes(c))),m=await o.connection.open();for(let l of p)await l.handle(n,{connectionString:a,client:m,transaction:o,execute:o.execute})},Q=e=>Z(e),Fe=(e,...t)=>Q({canHandle:t,handle:async(n,o)=>{let a=await e(n,o);await o.execute.batchCommand(a)}}),Xt=(e,...t)=>Fe(async(n,o)=>{let a=[];for(let s of n)a.push(await e(s,o));return a},...t);import"@event-driven-io/dumbo";import{rawSql as Ue,single as $e,sql as L}from"@event-driven-io/dumbo";import{v4 as je}from"uuid";var w="emt",v="global",N="emt:default",zt={module:`${w}:module:${v}`,tenant:`${w}:tenant:${v}`},b={partition:{name:"partition"},isArchived:{name:"is_archived"}},i={name:`${w}_streams`,columns:{partition:b.partition,isArchived:b.isArchived}},r={name:`${w}_events`,columns:{partition:b.partition,isArchived:b.isArchived}};var ce=Ue(`CREATE OR REPLACE FUNCTION emt_append_event(
7
7
  v_event_ids text[],
8
8
  v_events_data jsonb[],
9
9
  v_events_metadata jsonb[],
@@ -85,7 +85,7 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
85
85
  RETURN QUERY SELECT TRUE, v_next_stream_position, v_last_global_position, v_transaction_id;
86
86
  END;
87
87
  $$;
88
- `),ae= exports.appendToStream =(e,t,n,o,a)=>e.withTransaction(async s=>{let{execute:p}=s;if(o.length===0)return{success:!1,result:{success:!1}};let m;try{let _=Qe(_optionalChain([a, 'optionalAccess', _23 => _23.expectedStreamVersion])),h=o.map((I,f)=>({...I,metadata:{streamName:t,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(f),...I.metadata}}));m=await Xe(p,t,n,h,{expectedStreamVersion:_}),_optionalChain([a, 'optionalAccess', _24 => _24.preCommitHook])&&await a.preCommitHook(h,{transaction:s})}catch(_){if(!Be(_))throw _;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:E,next_stream_position:c,last_global_position:l,transaction_id:d}=m;return{success:E,result:E&&c&&l&&d?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(l),transactionId:d}:{success:!1}}}),Qe=e=>e===void 0||e===O||e==x||e==D?null:e,Be=e=>e instanceof Error&&"code"in e&&e.code==="23505",Xe=(e,t,n,o,a)=>_dumbo.single.call(void 0, e.command(_dumbo.sql.call(void 0, `SELECT * FROM emt_append_event(
88
+ `),me=(e,t,n,o,a)=>e.withTransaction(async s=>{let{execute:p}=s;if(o.length===0)return{success:!1,result:{success:!1}};let m;try{let _=Qe(a?.expectedStreamVersion),h=o.map((I,f)=>({...I,metadata:{streamName:t,eventId:je(),streamPosition:BigInt(f),...I.metadata}}));m=await Xe(p,t,n,h,{expectedStreamVersion:_}),a?.preCommitHook&&await a.preCommitHook(h,{transaction:s})}catch(_){if(!Be(_))throw _;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:l,next_stream_position:c,last_global_position:E,transaction_id:d}=m;return{success:l,result:l&&c&&E&&d?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(E),transactionId:d}:{success:!1}}}),Qe=e=>e===void 0||e===O||e==x||e==D?null:e,Be=e=>e instanceof Error&&"code"in e&&e.code==="23505",Xe=(e,t,n,o,a)=>$e(e.command(L(`SELECT * FROM emt_append_event(
89
89
  ARRAY[%s]::text[],
90
90
  ARRAY[%s]::jsonb[],
91
91
  ARRAY[%s]::jsonb[],
@@ -95,7 +95,7 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
95
95
  %L::text,
96
96
  %s::bigint,
97
97
  %L::text
98
- )`,o.map(s=>_dumbo.sql.call(void 0, "%L",s.metadata.eventId)).join(","),o.map(s=>_dumbo.sql.call(void 0, "%L",P.stringify(s.data))).join(","),o.map(s=>_dumbo.sql.call(void 0, "%L",P.stringify(_nullishCoalesce(s.metadata, () => ({}))))).join(","),o.map(()=>"'1'").join(","),o.map(s=>_dumbo.sql.call(void 0, "%L",s.type)).join(","),t,n,_nullishCoalesce(_optionalChain([a, 'optionalAccess', _25 => _25.expectedStreamVersion]), () => ("NULL")),_nullishCoalesce(_optionalChain([a, 'optionalAccess', _26 => _26.partition]), () => (N)))));var re=_dumbo.rawSql.call(void 0, `CREATE TABLE IF NOT EXISTS ${i.name}(
98
+ )`,o.map(s=>L("%L",s.metadata.eventId)).join(","),o.map(s=>L("%L",P.stringify(s.data))).join(","),o.map(s=>L("%L",P.stringify(s.metadata??{}))).join(","),o.map(()=>"'1'").join(","),o.map(s=>L("%L",s.type)).join(","),t,n,a?.expectedStreamVersion??"NULL",a?.partition??N)));import{rawSql as g}from"@event-driven-io/dumbo";var de=g(`CREATE TABLE IF NOT EXISTS ${i.name}(
99
99
  stream_id TEXT NOT NULL,
100
100
  stream_position BIGINT NOT NULL,
101
101
  partition TEXT NOT NULL DEFAULT '${v}__${v}',
@@ -104,7 +104,7 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
104
104
  is_archived BOOLEAN NOT NULL DEFAULT FALSE,
105
105
  PRIMARY KEY (stream_id, stream_position, partition, is_archived),
106
106
  UNIQUE (stream_id, partition, is_archived)
107
- ) PARTITION BY LIST (partition);`),ie= exports.eventsTableSQL =_dumbo.rawSql.call(void 0, `
107
+ ) PARTITION BY LIST (partition);`),le=g(`
108
108
  CREATE SEQUENCE IF NOT EXISTS emt_global_event_position;
109
109
 
110
110
  CREATE TABLE IF NOT EXISTS ${r.name}(
@@ -121,7 +121,7 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
121
121
  transaction_id XID8 NOT NULL,
122
122
  created TIMESTAMPTZ NOT NULL DEFAULT now(),
123
123
  PRIMARY KEY (stream_id, stream_position, partition, is_archived)
124
- ) PARTITION BY LIST (partition);`),se= exports.subscriptionsTableSQL =_dumbo.rawSql.call(void 0, `
124
+ ) PARTITION BY LIST (partition);`),Ee=g(`
125
125
  CREATE TABLE IF NOT EXISTS emt_subscriptions(
126
126
  subscription_id TEXT NOT NULL PRIMARY KEY,
127
127
  version INT NOT NULL DEFAULT 1,
@@ -130,11 +130,11 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
130
130
  last_processed_position BIGINT NOT NULL,
131
131
  last_processed_transaction_id BIGINT NOT NULL
132
132
  );
133
- `),ce= exports.sanitizeNameSQL =_dumbo.rawSql.call(void 0, `CREATE OR REPLACE FUNCTION emt_sanitize_name(input_name TEXT) RETURNS TEXT AS $$
133
+ `),pe=g(`CREATE OR REPLACE FUNCTION emt_sanitize_name(input_name TEXT) RETURNS TEXT AS $$
134
134
  BEGIN
135
135
  RETURN REGEXP_REPLACE(input_name, '[^a-zA-Z0-9_]', '_', 'g');
136
136
  END;
137
- $$ LANGUAGE plpgsql;`),me= exports.addTablePartitions =_dumbo.rawSql.call(void 0, `
137
+ $$ LANGUAGE plpgsql;`),_e=g(`
138
138
  CREATE OR REPLACE FUNCTION emt_add_table_partition(tableName TEXT, partition_name TEXT) RETURNS void AS $$
139
139
  DECLARE
140
140
  v_main_partiton_name TEXT;
@@ -171,13 +171,13 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
171
171
  v_archived_partiton_name, v_main_partiton_name
172
172
  );
173
173
  END;
174
- $$ LANGUAGE plpgsql;`),de= exports.addEventsPartitions =_dumbo.rawSql.call(void 0, `
174
+ $$ LANGUAGE plpgsql;`),ve=g(`
175
175
  CREATE OR REPLACE FUNCTION emt_add_partition(partition_name TEXT) RETURNS void AS $$
176
176
  BEGIN
177
177
  PERFORM emt_add_table_partition('${r.name}', partition_name);
178
178
  PERFORM emt_add_table_partition('${i.name}', partition_name);
179
179
  END;
180
- $$ LANGUAGE plpgsql;`),Ee= exports.addModuleSQL =_dumbo.rawSql.call(void 0, `
180
+ $$ LANGUAGE plpgsql;`),Te=g(`
181
181
  CREATE OR REPLACE FUNCTION add_module(new_module TEXT) RETURNS void AS $$
182
182
  BEGIN
183
183
  -- For ${r.name} table
@@ -219,7 +219,7 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
219
219
  );
220
220
  END;
221
221
  $$ LANGUAGE plpgsql;
222
- `),le= exports.addTenantSQL =_dumbo.rawSql.call(void 0, `
222
+ `),ue=g(`
223
223
  CREATE OR REPLACE FUNCTION add_tenant(new_module TEXT, new_tenant TEXT) RETURNS void AS $$
224
224
  BEGIN
225
225
  -- For ${r.name} table
@@ -261,7 +261,7 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
261
261
  );
262
262
  END;
263
263
  $$ LANGUAGE plpgsql;
264
- `),pe= exports.addModuleForAllTenantsSQL =_dumbo.rawSql.call(void 0, `
264
+ `),ge=g(`
265
265
  CREATE OR REPLACE FUNCTION add_module_for_all_tenants(new_module TEXT) RETURNS void AS $$
266
266
  DECLARE
267
267
  tenant_record RECORD;
@@ -310,7 +310,7 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
310
310
  END LOOP;
311
311
  END;
312
312
  $$ LANGUAGE plpgsql;
313
- `),_e= exports.addTenantForAllModulesSQL =_dumbo.rawSql.call(void 0, `
313
+ `),Se=g(`
314
314
  CREATE OR REPLACE FUNCTION add_tenant_for_all_modules(new_tenant TEXT) RETURNS void AS $$
315
315
  DECLARE
316
316
  module_record RECORD;
@@ -357,7 +357,7 @@ Actual:${P.stringify(t)}`)}function J(e,t,n){if(e===t)throw new y(_nullishCoales
357
357
  END LOOP;
358
358
  END;
359
359
  $$ LANGUAGE plpgsql;
360
- `),ve= exports.addDefaultPartition =_dumbo.rawSql.call(void 0, `SELECT emt_add_partition('${N}');`);var Te=async(e,t,n)=>{let o=n&&"from"in n?`AND stream_position >= ${n.from}`:"",a=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:NaN),s=isNaN(a)?"":`AND stream_position <= ${a}`,p=await _dumbo.mapRows.call(void 0, e.query(_dumbo.sql.call(void 0, `SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
360
+ `),ye=g(`SELECT emt_add_partition('${N}');`);import{mapRows as Ve,sql as Ge}from"@event-driven-io/dumbo";var fe=async(e,t,n)=>{let o=n&&"from"in n?`AND stream_position >= ${n.from}`:"",a=Number(n&&"to"in n?n.to:n&&"maxCount"in n&&n.maxCount?n.from+n.maxCount:NaN),s=isNaN(a)?"":`AND stream_position <= ${a}`,p=await Ve(e.query(Ge(`SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
361
361
  FROM ${r.name}
362
- WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${o} ${s}`,t,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _27 => _27.partition]), () => (N)))),m=>{let E=H(m.event_type,m.event_data,m.event_metadata);return{...E,metadata:{...E.metadata,eventId:m.event_id,streamName:t,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return p.length>0?{currentStreamVersion:p[p.length-1].metadata.streamPosition,events:p}:null};var M=[re,ie,se,ce,me,de,Ee,le,pe,_e,oe,ve],Q= exports.createEventStoreSchema =async e=>{await e.withTransaction(({execute:t})=>t.batchCommand(M))};var ze=(n=>(n.None="None",n.CreateOrUpdate="CreateOrUpdate",n))(ze||{}),He= exports.defaultPostgreSQLOptions ={projections:[],schema:{autoMigration:"CreateOrUpdate"}},ke= exports.getPostgreSQLEventStore =(e,t=He)=>{let n={connectionString:e,...t.connectionOptions?t.connectionOptions:{}},o="dumbo"in n?n.dumbo:_dumbo.dumbo.call(void 0, n),a,s=_optionalChain([t, 'access', _28 => _28.schema, 'optionalAccess', _29 => _29.autoMigration])===void 0||_optionalChain([t, 'access', _30 => _30.schema, 'optionalAccess', _31 => _31.autoMigration])!=="None",p=()=>s?(a||(a=Q(o)),a):Promise.resolve(),m=(_nullishCoalesce(t.projections, () => ([]))).filter(({type:c})=>c==="inline").map(({projection:c})=>c),E=m.length>0?(c,{transaction:l})=>C({projections:m,connection:{connectionString:e,transaction:l},events:c}):void 0;return{schema:{sql:()=>M.join(""),print:()=>console.log(M.join("")),migrate:async()=>{await(a=Q(o))}},async aggregateStream(c,l){let{evolve:d,initialState:_,read:h}=l,I=_optionalChain([h, 'optionalAccess', _32 => _32.expectedStreamVersion]),f=_(),F=await this.readStream(c,l.read);if(F===null)return null;let B=F.currentStreamVersion;Ye(B,I);for(let X of F.events)X&&(f=d(f,X));return{currentStreamVersion:B,state:f}},readStream:async(c,l)=>(await p(),Te(o.execute,c,l)),appendToStream:async(c,l,d)=>{await p();let[_,...h]=c.split("-"),I=_&&h.length>0?_:"emt:unknown",f=await ae(o,c,I,l,{...d,preCommitHook:E});if(!f.success)throw new U(-1n,_nullishCoalesce(_optionalChain([d, 'optionalAccess', _33 => _33.expectedStreamVersion]), () => (O)));return{nextExpectedStreamVersion:f.nextStreamPosition}},close:()=>o.close(),async withSession(c){return await o.withConnection(async l=>{let d={...t,connectionOptions:{connection:l}},_=ke(e,d);return c({eventStore:_,close:()=>Promise.resolve()})})}}},qe=(e,t)=>t===O?!0:t==x?e===void 0:t==D?e!==void 0:e===t,Ye=(e,t)=>{if(t??=O,!qe(e,t))throw new U(e,t)};exports.PostgreSQLProjectionSpec = It; exports.SchemaMigration = ze; exports.addDefaultPartition = ve; exports.addEventsPartitions = de; exports.addModuleForAllTenantsSQL = pe; exports.addModuleSQL = Ee; exports.addTablePartitions = me; exports.addTenantForAllModulesSQL = _e; exports.addTenantSQL = le; exports.appendEventsSQL = oe; exports.appendToStream = ae; exports.assertSQLQueryResultMatches = Me; exports.createEventStoreSchema = Q; exports.defaultPostgreSQLOptions = He; exports.defaultTag = N; exports.documentDoesNotExist = ee; exports.documentExists = Re; exports.documentMatchingExists = Z; exports.documentsAreTheSame = Ae; exports.documentsMatchingHaveCount = Le; exports.emmettPrefix = w; exports.eventInStream = we; exports.eventsInStream = be; exports.eventsTable = r; exports.eventsTableSQL = ie; exports.expectPongoDocuments = dt; exports.expectSQL = Nt; exports.getPostgreSQLEventStore = ke; exports.globalNames = bt; exports.globalTag = v; exports.handleProjections = C; exports.newEventsInStream = Ot; exports.pongoMultiStreamProjection = Ce; exports.pongoProjection = xe; exports.pongoSingleStreamProjection = vt; exports.postgreSQLProjection = j; exports.postgreSQLRawBatchSQLProjection = Fe; exports.postgreSQLRawSQLProjection = Dt; exports.readStream = Te; exports.sanitizeNameSQL = ce; exports.schemaSQL = M; exports.streamsTable = i; exports.streamsTableSQL = re; exports.subscriptionsTableSQL = se;
362
+ WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${o} ${s}`,t,n?.partition??N)),m=>{let l=K(m.event_type,m.event_data,m.event_metadata);return{...l,metadata:{...l.metadata,eventId:m.event_id,streamName:t,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return p.length>0?{currentStreamVersion:p[p.length-1].metadata.streamPosition,events:p}:null};var M=[de,le,Ee,pe,_e,ve,Te,ue,ge,Se,ce,ye],B=async e=>{await e.withTransaction(({execute:t})=>t.batchCommand(M))};var ze={projections:[],schema:{autoMigration:"CreateOrUpdate"}},He=(e,t=ze)=>{let n={connectionString:e,...t.connectionOptions?t.connectionOptions:{}},o="dumbo"in n?n.dumbo:We(n),a,s=t.schema?.autoMigration===void 0||t.schema?.autoMigration!=="None",p=()=>s?(a||(a=B(o)),a):Promise.resolve(),m=(t.projections??[]).filter(({type:c})=>c==="inline").map(({projection:c})=>c),l=m.length>0?(c,{transaction:E})=>C({projections:m,connection:{connectionString:e,transaction:E},events:c}):void 0;return{schema:{sql:()=>M.join(""),print:()=>console.log(M.join("")),migrate:async()=>{await(a=B(o))}},async aggregateStream(c,E){let{evolve:d,initialState:_,read:h}=E,I=h?.expectedStreamVersion,f=_(),F=await this.readStream(c,E.read);if(F===null)return null;let X=F.currentStreamVersion;qe(X,I);for(let V of F.events)V&&(f=d(f,V));return{currentStreamVersion:X,state:f}},readStream:async(c,E)=>(await p(),fe(o.execute,c,E)),appendToStream:async(c,E,d)=>{await p();let[_,...h]=c.split("-"),I=_&&h.length>0?_:"emt:unknown",f=await me(o,c,I,E,{...d,preCommitHook:l});if(!f.success)throw new $(-1n,d?.expectedStreamVersion??O);return{nextExpectedStreamVersion:f.nextStreamPosition}},close:()=>o.close(),async withSession(c){return await o.withConnection(async E=>{let d={...t,connectionOptions:{connection:E}},_=He(e,d);return c({eventStore:_,close:()=>Promise.resolve()})})}}},ke=(e,t)=>t===O?!0:t==x?e===void 0:t==D?e!==void 0:e===t,qe=(e,t)=>{if(t??=O,!ke(e,t))throw new $(e,t)};export{Ft as PostgreSQLProjectionSpec,ye as addDefaultPartition,ve as addEventsPartitions,ge as addModuleForAllTenantsSQL,Te as addModuleSQL,_e as addTablePartitions,Se as addTenantForAllModulesSQL,ue as addTenantSQL,ce as appendEventsSQL,me as appendToStream,Me as assertSQLQueryResultMatches,B as createEventStoreSchema,ze as defaultPostgreSQLOptions,N as defaultTag,re as documentDoesNotExist,Re as documentExists,ae as documentMatchingExists,Ae as documentsAreTheSame,Le as documentsMatchingHaveCount,w as emmettPrefix,we as eventInStream,be as eventsInStream,r as eventsTable,le as eventsTableSQL,Pt as expectPongoDocuments,$t as expectSQL,He as getPostgreSQLEventStore,zt as globalNames,v as globalTag,C as handleProjections,Ut as newEventsInStream,Ce as pongoMultiStreamProjection,xe as pongoProjection,Rt as pongoSingleStreamProjection,Q as postgreSQLProjection,Fe as postgreSQLRawBatchSQLProjection,Xt as postgreSQLRawSQLProjection,fe as readStream,pe as sanitizeNameSQL,M as schemaSQL,i as streamsTable,de as streamsTableSQL,Ee as subscriptionsTableSQL};
363
363
  //# sourceMappingURL=index.js.map