@event-driven-io/emmett-postgresql 0.20.1 → 0.20.2-alpha.3
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/cli.cjs.map +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +45 -45
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +45 -45
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"names":["migrateCommand","Command","options","collection","cli","program","cli_default"],"mappings":"AAAA,mNAAwB,IAeXA,CAAAA,CAAiB,IAAIC,uBAAAA,CAAQ,SAAS,CAAA,CAAE,WAAA,CACnD,4BACF,CAAA,CAEAD,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CACC,kCAAA,CACA,oCACF,CAAA,CAUC,MAAA,CAAO,eAAA,CAAiB,2CAAA,CAA6C,CAAA,CAAK,CAAA,CAC1E,MAAA,CAAQE,CAAAA,EAA+B,CAAA,kBAGpCA,CAAAA,CAAQ,gBAAA,SAAoB,OAAA,CAAQ,GAAA,CAAI,sBAAA,CAAA,EAAA,CAIxC,OAAA,CAAQ,KAAA,CACN,uJACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,+CAA+C,CAyB7D,CAAC,CAAA,CAEHF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,qCAAqC,CAAA,CAUjD,MAAA,CAAO,SAAA,CAAW,wCAAA,CAA0C,CAAA,CAAI,CAAA,CAEhE,MAAA,CAAQE,CAAAA,EAA+B,CACtC,GAAM,CAAE,UAAA,CAAAC,CAAW,CAAA,CAAID,CAAAA,CAElBC,CAAAA,EAAAA,CACH,OAAA,CAAQ,KAAA,CACN,8GACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,gDAAgD,CAe9D,CAAC,CAAA,
|
|
1
|
+
{"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"names":["migrateCommand","Command","options","collection","cli","program","cli_default"],"mappings":"AAAA,mNAAwB,IAeXA,CAAAA,CAAiB,IAAIC,uBAAAA,CAAQ,SAAS,CAAA,CAAE,WAAA,CACnD,4BACF,CAAA,CAEAD,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CACC,kCAAA,CACA,oCACF,CAAA,CAUC,MAAA,CAAO,eAAA,CAAiB,2CAAA,CAA6C,CAAA,CAAK,CAAA,CAC1E,MAAA,CAAQE,CAAAA,EAA+B,CAAA,kBAGpCA,CAAAA,CAAQ,gBAAA,SAAoB,OAAA,CAAQ,GAAA,CAAI,sBAAA,CAAA,EAAA,CAIxC,OAAA,CAAQ,KAAA,CACN,uJACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,+CAA+C,CAyB7D,CAAC,CAAA,CAEHF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,qCAAqC,CAAA,CAUjD,MAAA,CAAO,SAAA,CAAW,wCAAA,CAA0C,CAAA,CAAI,CAAA,CAEhE,MAAA,CAAQE,CAAAA,EAA+B,CACtC,GAAM,CAAE,UAAA,CAAAC,CAAW,CAAA,CAAID,CAAAA,CAElBC,CAAAA,EAAAA,CACH,OAAA,CAAQ,KAAA,CACN,8GACF,CAAA,CACA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAAA,CAGhB,OAAA,CAAQ,GAAA,CAAI,gDAAgD,CAe9D,CAAC,CAAA,CC7GH,IAAMC,CAAAA,CAAuB,CAC3B,UAAA,CAAY,KAAA,CACZ,IAAA,CAAM,mBAAA,CACN,gBAAA,CAAmBC,CAAAA,EAA8B,CAC/CA,CAAAA,CAAQ,UAAA,CAAWL,CAAc,CACnC,CACF,CAAA,CAEOM,CAAAA,mBAAQF,CAAAA,CAAAA,oBAAAA","file":"/home/runner/work/emmett/emmett/src/packages/emmett-postgresql/dist/cli.cjs","sourcesContent":["import { Command } from 'commander';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((options: MigrateRunOptions) => {\n //const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n //let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful');\n // if (options.config) {\n // const config = await loadConfigFile(options.config);\n\n // collectionNames = config.collections.map((c) => c.name);\n // } else if (collection) {\n // collectionNames = collection;\n // } else {\n // console.error(\n // 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n // );\n // process.exit(1);\n // }\n\n // const pool = dumbo({ connectionString });\n\n // const migrations = collectionNames.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // );\n\n // await runPostgreSQLMigrations(pool, migrations, {\n // dryRun,\n // });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful!');\n // const coreMigrations = migrationTableSchemaComponent.migrations({\n // connector: 'PostgreSQL:pg',\n // });\n // const migrations = [\n // ...coreMigrations,\n // ...collection.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // ),\n // ];\n\n // console.log('Printing SQL:');\n // console.log(combineMigrations(...migrations));\n });\n","import type {\n EmmettCliCommand,\n EmmettCliPlugin,\n} from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program: EmmettCliCommand) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"]}
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((options: MigrateRunOptions) => {\n //const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n //let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful');\n // if (options.config) {\n // const config = await loadConfigFile(options.config);\n\n // collectionNames = config.collections.map((c) => c.name);\n // } else if (collection) {\n // collectionNames = collection;\n // } else {\n // console.error(\n // 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n // );\n // process.exit(1);\n // }\n\n // const pool = dumbo({ connectionString });\n\n // const migrations = collectionNames.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // );\n\n // await runPostgreSQLMigrations(pool, migrations, {\n // dryRun,\n // });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful!');\n // const coreMigrations = migrationTableSchemaComponent.migrations({\n // connector: 'PostgreSQL:pg',\n // });\n // const migrations = [\n // ...coreMigrations,\n // ...collection.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // ),\n // ];\n\n // console.log('Printing SQL:');\n // console.log(combineMigrations(...migrations));\n });\n","import type {
|
|
1
|
+
{"version":3,"sources":["../src/commandLine/migrate.ts","../src/cli.ts"],"sourcesContent":["import { Command } from 'commander';\n\ninterface MigrateRunOptions {\n collection: string[];\n connectionString: string;\n config?: string;\n dryRun?: boolean;\n}\n\ninterface MigrateSqlOptions {\n print?: boolean;\n write?: string;\n collection: string[];\n}\n\nexport const migrateCommand = new Command('migrate').description(\n 'Manage database migrations',\n);\n\nmigrateCommand\n .command('run')\n .description('Run database migrations')\n .option(\n '-cs, --connectionString <string>',\n 'Connection string for the database',\n )\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('-dr, --dryRun', 'Perform dry run without commiting changes', false)\n .action((options: MigrateRunOptions) => {\n //const { collection, dryRun } = options;\n const connectionString =\n options.connectionString ?? process.env.DB_CONNECTION_STRING;\n //let collectionNames: string[];\n\n if (!connectionString) {\n console.error(\n 'Error: Connection string is required. Provide it either as a \"--connectionString\" parameter or through the DB_CONNECTION_STRING environment variable.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful');\n // if (options.config) {\n // const config = await loadConfigFile(options.config);\n\n // collectionNames = config.collections.map((c) => c.name);\n // } else if (collection) {\n // collectionNames = collection;\n // } else {\n // console.error(\n // 'Error: You need to provide at least one collection name. Provide it either through \"--config\" file or as a \"--collection\" parameter.',\n // );\n // process.exit(1);\n // }\n\n // const pool = dumbo({ connectionString });\n\n // const migrations = collectionNames.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // );\n\n // await runPostgreSQLMigrations(pool, migrations, {\n // dryRun,\n // });\n });\n\nmigrateCommand\n .command('sql')\n .description('Generate SQL for database migration')\n // .option(\n // '-col, --collection <name>',\n // 'Specify the collection name',\n // (value: string, previous: string[]) => {\n // // Accumulate collection names into an array (explicitly typing `previous` as `string[]`)\n // return previous.concat([value]);\n // },\n // [] as string[],\n // )\n .option('--print', 'Print the SQL to the console (default)', true)\n //.option('--write <filename>', 'Write the SQL to a specified file')\n .action((options: MigrateSqlOptions) => {\n const { collection } = options;\n\n if (!collection) {\n console.error(\n 'Error: You need to provide at least one collection name is required. Provide it either as a \"col\" parameter.',\n );\n process.exit(1);\n }\n\n console.log('Nothing has happened, but test was successful!');\n // const coreMigrations = migrationTableSchemaComponent.migrations({\n // connector: 'PostgreSQL:pg',\n // });\n // const migrations = [\n // ...coreMigrations,\n // ...collection.flatMap((collectionsName) =>\n // pongoCollectionSchemaComponent(collectionsName).migrations({\n // connector: 'PostgreSQL:pg', // TODO: Provide connector here\n // }),\n // ),\n // ];\n\n // console.log('Printing SQL:');\n // console.log(combineMigrations(...migrations));\n });\n","import type {\n EmmettCliCommand,\n EmmettCliPlugin,\n} from '@event-driven-io/emmett';\nimport { migrateCommand } from './commandLine';\n\nconst cli: EmmettCliPlugin = {\n pluginType: 'cli',\n name: 'emmett-postgresql',\n registerCommands: (program: EmmettCliCommand) => {\n program.addCommand(migrateCommand);\n },\n};\n\nexport default cli;\n"],"mappings":"AAAA,OAAS,WAAAA,MAAe,YAejB,IAAMC,EAAiB,IAAID,EAAQ,SAAS,EAAE,YACnD,4BACF,EAEAC,EACG,QAAQ,KAAK,EACb,YAAY,yBAAyB,EACrC,OACC,mCACA,oCACF,EAUC,OAAO,gBAAiB,4CAA6C,EAAK,EAC1E,OAAQC,GAA+B,EAGpCA,EAAQ,kBAAoB,QAAQ,IAAI,wBAIxC,QAAQ,MACN,uJACF,EACA,QAAQ,KAAK,CAAC,GAGhB,QAAQ,IAAI,+CAA+C,CAyB7D,CAAC,EAEHD,EACG,QAAQ,KAAK,EACb,YAAY,qCAAqC,EAUjD,OAAO,UAAW,yCAA0C,EAAI,EAEhE,OAAQC,GAA+B,CACtC,GAAM,CAAE,WAAAC,CAAW,EAAID,EAElBC,IACH,QAAQ,MACN,8GACF,EACA,QAAQ,KAAK,CAAC,GAGhB,QAAQ,IAAI,gDAAgD,CAe9D,CAAC,EC7GH,IAAMC,EAAuB,CAC3B,WAAY,MACZ,KAAM,oBACN,iBAAmBC,GAA8B,CAC/CA,EAAQ,WAAWC,CAAc,CACnC,CACF,EAEOC,EAAQH","names":["Command","migrateCommand","options","collection","cli","program","migrateCommand","cli_default"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function
|
|
2
|
-
${
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3;var _dumbo = require('@event-driven-io/dumbo');var k=t=>typeof t=="number"&&t===t,W=t=>typeof t=="string";var M=t=>typeof t=="function"&&t.prototype&&t.prototype.constructor===t,H=class q extends Error{constructor(e){let n=e&&typeof e=="object"&&"errorCode"in e?e.errorCode:k(e)?e:500,o=e&&typeof e=="object"&&"message"in e?e.message:W(e)?e:`Error with status code '${n}' ocurred during Emmett processing`;super(o),this.errorCode=n,Object.setPrototypeOf(this,q.prototype)}},z=class Y extends H{constructor(e,n,o){super({errorCode:412,message:_nullishCoalesce(o, () => (`Expected version ${n.toString()} does not match current ${_optionalChain([e, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))}),this.current=e,this.expected=n,Object.setPrototypeOf(this,Y.prototype)}};var _uuid = require('uuid');var _webstreamspolyfill = require('web-streams-polyfill');var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);var J=(t,e,n)=>({type:t,data:e,metadata:n});var F="STREAM_EXISTS",U="STREAM_DOES_NOT_EXIST",N="NO_CONCURRENCY_CHECK",Re=(t,e,n)=>e===N?!0:e==U?t===n:e==F?t!==n:t===e,K=(t,e,n)=>{if(e??=N,!Re(t,e,n))throw new $(t,e)},$=class Z extends z{constructor(e,n){super(_optionalChain([e, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]),_optionalChain([n, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()])),Object.setPrototypeOf(this,Z.prototype)}};var De=(t,e={})=>new ee(t,e),ee= (_class =class extends _webstreamspolyfill.TransformStream{constructor(t,e={}){super({cancel:n=>{console.log("Stream was canceled. Reason:",n),this.stopChecking()}});_class.prototype.__init.call(this);_class.prototype.__init2.call(this);,this.onNoActiveReaderCallback=t,this.streamId=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _8 => _8.streamId]), () => (_uuid.v4.call(void 0, ))),this.onNoActiveReaderCallback=t,this.startChecking(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _9 => _9.intervalCheckInMs]), () => (20)))}__init() {this.checkInterval=null}__init2() {this._isStopped=!1}get hasActiveSubscribers(){return!this._isStopped}startChecking(t){this.checkInterval=setInterval(()=>{this.checkNoActiveReader()},t)}stopChecking(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null,this._isStopped=!0,this.onNoActiveReaderCallback(this))}checkNoActiveReader(){!this.readable.locked&&!this._isStopped&&this.stopChecking()}}, _class);var T=(t,e)=>{if(xe(t))return t.equals(e);if(Array.isArray(t))return Array.isArray(e)&&t.length===e.length&&t.every((a,r)=>T(a,e[r]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return t===e;if(Array.isArray(e))return!1;let n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length||!n.every(a=>o.includes(a)))return!1;for(let a in t){if(t[a]instanceof Function&&e[a]instanceof Function)continue;if(!T(t[a],e[a]))return!1}return!0},xe=t=>t&&typeof t=="object"&&"equals"in t&&typeof t.equals=="function";var Ce=async(t,e)=>e===void 0||e.retries===0?t():_asyncretry2.default.call(void 0, async n=>{try{return await t()}catch(o){throw _optionalChain([e, 'optionalAccess', _10 => _10.shouldRetryError])&&!e.shouldRetryError(o)&&n(o),o}},_nullishCoalesce(e, () => ({retries:0})));var te=t=>t;var be=class extends Error{constructor(t){super(`Cannot parse! ${t}`)}},h={stringify:(t,e)=>JSON.stringify(_optionalChain([e, 'optionalAccess', _11 => _11.map])?e.map(t):t,(n,o)=>typeof o=="bigint"?o.toString():o),parse:(t,e)=>{let n=JSON.parse(t,_optionalChain([e, 'optionalAccess', _12 => _12.reviver]));if(_optionalChain([e, 'optionalAccess', _13 => _13.typeCheck])&&!_optionalChain([e, 'optionalAccess', _14 => _14.typeCheck, 'call', _15 => _15(n)]))throw new be(t);return _optionalChain([e, 'optionalAccess', _16 => _16.map])?e.map(n):n}};var Fe=t=>new (0, _webstreamspolyfill.TransformStream)({transform(e,n){t(e)&&n.enqueue(e)}}),$e=t=>new (0, _webstreamspolyfill.TransformStream)({transform(e,n){n.enqueue(t(e))}}),Qe=(t,e)=>new ne(t,e),ne=class extends _webstreamspolyfill.TransformStream{constructor(t,e){super({transform:n=>{this.accumulator=this.reducer(this.accumulator,n)},flush:n=>{n.enqueue(this.accumulator),n.terminate()}}),this.accumulator=e,this.reducer=t}},Xe=(t,e,n={forever:!0,minTimeout:25})=>new (0, _webstreamspolyfill.TransformStream)({start(o){Ce(()=>Ve(t,e,o),n).catch(a=>{o.error(a)})}}),Ve=async(t,e,n)=>{let a=t().getReader();try{let r;do{let l=await a.read();r=l.done,await e(l,n),r&&n.terminate()}while(!r)}finally{a.releaseLock()}},ke=t=>new oe(t),oe= (_class2 =class extends _webstreamspolyfill.TransformStream{__init3() {this.count=0}constructor(t){super({transform:(e,n)=>{this.count++,this.count>this.skip&&n.enqueue(e)}});_class2.prototype.__init3.call(this);,this.skip=t}}, _class2),He=t=>new (0, _webstreamspolyfill.TransformStream)({transform(e,n){n.enqueue(e),t(e)&&n.terminate()}}),ze=t=>new (0, _webstreamspolyfill.TransformStream)({async transform(e,n){if(!t(e)){n.enqueue(e);return}await Promise.resolve(),n.terminate()}}),Je=t=>new ae(t),ae= (_class3 =class extends _webstreamspolyfill.TransformStream{__init4() {this.count=0}constructor(t){super({transform:(e,n)=>{this.count<this.limit?(this.count++,n.enqueue(e)):n.terminate()}});_class3.prototype.__init4.call(this);,this.limit=t}}, _class3),Ze=t=>new (0, _webstreamspolyfill.TransformStream)({start(e){let n=setTimeout(()=>{e.terminate()},t),o=e.terminate.bind(e);e.terminate=()=>{clearTimeout(n),o()}},transform(e,n){n.enqueue(e)}}),et={filter:Fe,take:Je,TakeTransformStream:ae,skip:ke,SkipTransformStream:oe,map:$e,notifyAboutNoActiveReadersStream:De,NotifyAboutNoActiveReadersStream:ee,reduce:Qe,ReduceTransformStream:ne,retry:Xe,stopAfter:He,stopOn:ze,waitAtMost:Ze},{retry:rn}=et;var y=class extends Error{constructor(t){super(t)}};var re=t=>{throw new y(_nullishCoalesce(t, () => ("That should not ever happened, right?")))};var ie=(t,e,n)=>{if(!T(t,e))throw new y(_nullishCoalesce(n, () => (`subObj:
|
|
2
|
+
${h.stringify(e)}
|
|
3
3
|
is not equal to
|
|
4
|
-
${
|
|
5
|
-
Expected: ${
|
|
6
|
-
Actual:${
|
|
4
|
+
${h.stringify(t)}`)))};function _(t,e){if(!t)throw new y(_nullishCoalesce(e, () => ("Condition is false")))}function tt(t,e){if(!t)throw new y(_nullishCoalesce(e, () => ("Condition is not truthy")))}function S(t,e,n){if(t!==e)throw new y(`${_nullishCoalesce(n, () => ("Objects are not equal"))}:
|
|
5
|
+
Expected: ${h.stringify(t)}
|
|
6
|
+
Actual:${h.stringify(e)}`)}function se(t,e,n){if(t===e)throw new y(_nullishCoalesce(n, () => (`Objects are equal: ${h.stringify(t)}`)))}function j(t){se(t,null),tt(t)}var R=t=>({isEmpty:()=>S(t.length,0),isNotEmpty:()=>se(t.length,0),hasSize:e=>S(t.length,e),containsElements:(...e)=>{_(e.every(n=>e.some(o=>T(n,o))))},containsExactlyInAnyOrder:(...e)=>{S(t.length,e.length),_(t.every(n=>e.some(o=>T(n,o))))},containsExactlyInAnyOrderElementsOf:e=>{S(t.length,e.length),_(t.every(n=>e.some(o=>T(n,o))))},containsExactlyElementsOf:e=>{S(t.length,e.length);for(let n=0;n<t.length;n++)_(T(t[n],e[n]))},containsExactly:e=>{S(t.length,1),_(T(t[0],e))},contains:e=>{_(t.some(n=>T(n,e)))},containsOnlyOnceElementsOf:e=>{_(e.map(n=>t.filter(o=>T(o,n)).length).filter(n=>n===1).length===e.length)},containsAnyOf:(...e)=>{_(t.some(n=>e.some(o=>T(n,o))))},allMatch:e=>{_(t.every(e))},anyMatches:e=>{_(t.some(e))},allMatchAsync:async e=>{for(let n of t)_(await e(n))}});require('pg');var _pongo = require('@event-driven-io/pongo');var A=(t,e)=>{let{pool:n,connectionString:o,inDatabase:a,inCollection:r}=e;return n.withConnection(async l=>{let m=_pongo.pongoClient.call(void 0, o,{connectionOptions:{connection:l}});try{let p=m.db(a).collection(r);return t(p)}finally{await m.close()}})},ce=t=>{let{_id:e,_version:n,...o}=t;return o},ot=(t,e)=>("_id"in e&&S(e._id,t._id,`Document ids are not matching! Expected: ${e._id}, actual: ${t._id}`),ie(ce(t),ce(e))),at= exports.documentExists =(t,e)=>n=>A(async o=>{let a=await o.findOne("withId"in e?{_id:e.withId}:e.matchingFilter);j(a),ot(a,t)},{...e,...n}),rt= exports.documentsAreTheSame =(t,e)=>n=>A(async o=>{let a=await o.find("withId"in e?{_id:e.withId}:e.matchingFilter);S(t.length,a.length,"Different Documents Count than expected");for(let r=0;r<t.length;r++)R(a).contains(t[r])},{...e,...n}),it= exports.documentsMatchingHaveCount =(t,e)=>n=>A(async o=>{let a=await o.find("withId"in e?{_id:e.withId}:e.matchingFilter);S(t,a.length,"Different Documents Count than expected")},{...e,...n}),me= exports.documentMatchingExists =t=>e=>A(async n=>{let o=await n.find("withId"in t?{_id:t.withId}:t.matchingFilter);R(o).isNotEmpty()},{...t,...e}),de= exports.documentDoesNotExist =t=>e=>A(async n=>{let o=await n.findOne("withId"in t?{_id:t.withId}:t.matchingFilter);j(o)},{...t,...e}),gn= exports.expectPongoDocuments ={fromCollection:t=>({withId:e=>({toBeEqual:n=>at(n,{withId:e,inCollection:t}),toExist:()=>me({withId:e,inCollection:t}),notToExist:()=>de({withId:e,inCollection:t})}),matching:e=>({toBeTheSame:n=>rt(n,{matchingFilter:e,inCollection:t}),toHaveCount:n=>it(n,{matchingFilter:e,inCollection:t}),toExist:()=>me({matchingFilter:e,inCollection:t}),notToExist:()=>de({matchingFilter:e,inCollection:t})})})};var ct=({handle:t,canHandle:e})=>Q({canHandle:e,handle:async(n,o)=>{let{connectionString:a,client:r}=o,l=_pongo.pongoClient.call(void 0, a,{connectionOptions:{client:r}});await t(n,{...o,pongo:l})}}),mt= exports.pongoMultiStreamProjection =t=>{let{collectionName:e,getDocumentId:n,canHandle:o}=t;return ct({handle:async(a,{pongo:r})=>{let l=r.db().collection(e);for(let m of a)await l.handle(n(m),async p=>"initialState"in t?await t.evolve(_nullishCoalesce(p, () => (t.initialState())),m):await t.evolve(p,m))},canHandle:o})},Pn= exports.pongoSingleStreamProjection =t=>mt({...t,getDocumentId:e=>e.metadata.streamName});var wn={for:t=>{{let{projection:e,...n}=t,{connectionString:o}=n;return a=>({when:(r,l)=>{let m=[],p=async c=>{let E=0n,d=_nullishCoalesce(_optionalChain([l, 'optionalAccess', _17 => _17.numberOfTimes]), () => (1));for(let v of[...a,...Array.from({length:d}).flatMap(()=>r)])m.push({...v,metadata:{globalPosition:++E,streamPosition:E,streamName:`test-${_uuid.v4.call(void 0, )}`,eventId:_uuid.v4.call(void 0, ),..._nullishCoalesce(v.metadata, () => ({}))}});await c.withTransaction(v=>D({events:m,projections:[e],connection:{connectionString:o,transaction:v}}))};return{then:async(c,E)=>{let d=_dumbo.dumbo.call(void 0, n);try{await p(d);let v=await c({pool:d,connectionString:o});v!==void 0&&v===!1&&re(_nullishCoalesce(E, () => ("Projection specification didn't match the criteria")))}finally{await d.close()}},thenThrows:async(...c)=>{let E=_dumbo.dumbo.call(void 0, n);try{throw await p(E),new y("Handler did not fail as expected")}catch(d){if(d instanceof y)throw d;if(c.length===0)return;if(!M(c[0])){_(c[0](d),`Error didn't match the error condition: ${_optionalChain([d, 'optionalAccess', _18 => _18.toString, 'call', _19 => _19()])}`);return}_(d instanceof c[0],`Caught error is not an instance of the expected type: ${_optionalChain([d, 'optionalAccess', _20 => _20.toString, 'call', _21 => _21()])}`),c[1]&&_(c[1](d),`Error didn't match the error condition: ${_optionalChain([d, 'optionalAccess', _22 => _22.toString, 'call', _23 => _23()])}`)}finally{await E.close()}}}}})}}},dt= exports.eventInStream =(t,e)=>({...e,metadata:{..._nullishCoalesce(e.metadata, () => ({})),streamName:_nullishCoalesce(_optionalChain([e, 'access', _24 => _24.metadata, 'optionalAccess', _25 => _25.streamName]), () => (t))}}),lt= exports.eventsInStream =(t,e)=>e.map(n=>dt(t,n)),Cn= exports.newEventsInStream =lt,Et= exports.assertSQLQueryResultMatches =(t,e)=>async({pool:{execute:n}})=>{let o=await n.query(t);R(e).containsExactlyInAnyOrder(...o.rows)},bn= exports.expectSQL ={query:t=>({resultRows:{toBeTheSame:e=>Et(t,e)}})};var D=async t=>{let{projections:e,events:n,connection:{transaction:o,connectionString:a}}=t,r=n.map(p=>p.type),l=e.filter(p=>p.canHandle.some(c=>r.includes(c))),m=await o.connection.open();for(let p of l)await p.handle(n,{connectionString:a,client:m,transaction:o,execute:o.execute})},Q= exports.postgreSQLProjection =t=>te(t),pt= exports.postgreSQLRawBatchSQLProjection =(t,...e)=>Q({canHandle:e,handle:async(n,o)=>{let a=await t(n,o);await o.execute.batchCommand(a)}}),$n= exports.postgreSQLRawSQLProjection =(t,...e)=>pt(async(n,o)=>{let a=[];for(let r of n)a.push(await t(r,o));return a},...e);var x="emt",u= exports.globalTag ="global",O= exports.defaultTag ="emt:default",Xn= exports.globalNames ={module:`${x}:module:${u}`,tenant:`${x}:tenant:${u}`},w={partition:{name:"partition"},isArchived:{name:"is_archived"}},s= exports.streamsTable ={name:`${x}_streams`,columns:{partition:w.partition,isArchived:w.isArchived}},i= exports.eventsTable ={name:`${x}_events`,columns:{partition:w.partition,isArchived:w.isArchived}};var pe=_dumbo.rawSql.call(void 0, `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[],
|
|
@@ -51,7 +51,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
51
51
|
) AS event
|
|
52
52
|
),
|
|
53
53
|
all_events_insert AS (
|
|
54
|
-
INSERT INTO ${
|
|
54
|
+
INSERT INTO ${i.name}
|
|
55
55
|
(stream_id, stream_position, partition, event_data, event_metadata, event_schema_version, event_type, event_id, transaction_id)
|
|
56
56
|
SELECT
|
|
57
57
|
v_stream_id, ev.stream_position, v_partition, ev.event_data, ev.event_metadata, ev.schema_version, ev.event_type, ev.event_id, v_transaction_id
|
|
@@ -85,7 +85,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
85
85
|
RETURN QUERY SELECT TRUE, v_next_stream_position, v_last_global_position, v_transaction_id;
|
|
86
86
|
END;
|
|
87
87
|
$$;
|
|
88
|
-
`),
|
|
88
|
+
`),ve= exports.appendToStream =(t,e,n,o,a)=>t.withTransaction(async r=>{let{execute:l}=r;if(o.length===0)return{success:!1,result:{success:!1}};let m;try{let v=Tt(_optionalChain([a, 'optionalAccess', _26 => _26.expectedStreamVersion])),P=o.map((I,f)=>({...I,metadata:{streamName:e,eventId:_uuid.v4.call(void 0, ),streamPosition:BigInt(f),...I.metadata}}));m=await St(l,e,n,P,{expectedStreamVersion:v}),_optionalChain([a, 'optionalAccess', _27 => _27.preCommitHook])&&await a.preCommitHook(P,{transaction:r})}catch(v){if(!gt(v))throw v;m={success:!1,last_global_position:null,next_stream_position:null,transaction_id:null}}let{success:p,next_stream_position:c,last_global_position:E,transaction_id:d}=m;return{success:p,result:p&&c&&E&&d?{success:!0,nextStreamPosition:BigInt(c),lastGlobalPosition:BigInt(E),transactionId:d}:{success:!1}}}),Tt=t=>t===void 0||t===N||t==U||t==F?null:t,gt=t=>t instanceof Error&&"code"in t&&t.code==="23505",St=(t,e,n,o,a)=>_dumbo.single.call(void 0, t.command(_dumbo.sql.call(void 0, `SELECT * FROM emt_append_event(
|
|
89
89
|
ARRAY[%s]::text[],
|
|
90
90
|
ARRAY[%s]::jsonb[],
|
|
91
91
|
ARRAY[%s]::jsonb[],
|
|
@@ -95,22 +95,22 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
95
95
|
%L::text,
|
|
96
96
|
%s::bigint,
|
|
97
97
|
%L::text
|
|
98
|
-
)`,
|
|
98
|
+
)`,o.map(r=>_dumbo.sql.call(void 0, "%L",r.metadata.eventId)).join(","),o.map(r=>_dumbo.sql.call(void 0, "%L",h.stringify(r.data))).join(","),o.map(r=>_dumbo.sql.call(void 0, "%L",h.stringify(_nullishCoalesce(r.metadata, () => ({}))))).join(","),o.map(()=>"'1'").join(","),o.map(r=>_dumbo.sql.call(void 0, "%L",r.type)).join(","),e,n,_nullishCoalesce(_optionalChain([a, 'optionalAccess', _28 => _28.expectedStreamVersion]), () => ("NULL")),_nullishCoalesce(_optionalChain([a, 'optionalAccess', _29 => _29.partition]), () => (O)))));var ue=_dumbo.rawSql.call(void 0, `CREATE TABLE IF NOT EXISTS ${s.name}(
|
|
99
99
|
stream_id TEXT NOT NULL,
|
|
100
100
|
stream_position BIGINT NOT NULL,
|
|
101
|
-
partition TEXT NOT NULL DEFAULT '${
|
|
101
|
+
partition TEXT NOT NULL DEFAULT '${u}__${u}',
|
|
102
102
|
stream_type TEXT NOT NULL,
|
|
103
103
|
stream_metadata JSONB NOT NULL,
|
|
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);`),
|
|
107
|
+
) PARTITION BY LIST (partition);`),_e= exports.eventsTableSQL =_dumbo.rawSql.call(void 0, `
|
|
108
108
|
CREATE SEQUENCE IF NOT EXISTS emt_global_event_position;
|
|
109
109
|
|
|
110
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
110
|
+
CREATE TABLE IF NOT EXISTS ${i.name}(
|
|
111
111
|
stream_id TEXT NOT NULL,
|
|
112
112
|
stream_position BIGINT NOT NULL,
|
|
113
|
-
partition TEXT NOT NULL DEFAULT '${
|
|
113
|
+
partition TEXT NOT NULL DEFAULT '${u}',
|
|
114
114
|
event_data JSONB NOT NULL,
|
|
115
115
|
event_metadata JSONB NOT NULL,
|
|
116
116
|
event_schema_version TEXT NOT NULL,
|
|
@@ -121,7 +121,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
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);`),
|
|
124
|
+
) PARTITION BY LIST (partition);`),Te= exports.subscriptionsTableSQL =_dumbo.rawSql.call(void 0, `
|
|
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 de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
130
130
|
last_processed_position BIGINT NOT NULL,
|
|
131
131
|
last_processed_transaction_id BIGINT NOT NULL
|
|
132
132
|
);
|
|
133
|
-
`),
|
|
133
|
+
`),ge= exports.sanitizeNameSQL =_dumbo.rawSql.call(void 0, `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;`),
|
|
137
|
+
$$ LANGUAGE plpgsql;`),Se= exports.addTablePartitions =_dumbo.rawSql.call(void 0, `
|
|
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,74 +171,74 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
171
171
|
v_archived_partiton_name, v_main_partiton_name
|
|
172
172
|
);
|
|
173
173
|
END;
|
|
174
|
-
$$ LANGUAGE plpgsql;`),
|
|
174
|
+
$$ LANGUAGE plpgsql;`),fe= exports.addEventsPartitions =_dumbo.rawSql.call(void 0, `
|
|
175
175
|
CREATE OR REPLACE FUNCTION emt_add_partition(partition_name TEXT) RETURNS void AS $$
|
|
176
176
|
BEGIN
|
|
177
|
-
PERFORM emt_add_table_partition('${
|
|
177
|
+
PERFORM emt_add_table_partition('${i.name}', partition_name);
|
|
178
178
|
PERFORM emt_add_table_partition('${s.name}', partition_name);
|
|
179
179
|
END;
|
|
180
|
-
$$ LANGUAGE plpgsql;`),
|
|
180
|
+
$$ LANGUAGE plpgsql;`),ye= exports.addModuleSQL =_dumbo.rawSql.call(void 0, `
|
|
181
181
|
CREATE OR REPLACE FUNCTION add_module(new_module TEXT) RETURNS void AS $$
|
|
182
182
|
BEGIN
|
|
183
|
-
-- For ${
|
|
183
|
+
-- For ${i.name} table
|
|
184
184
|
EXECUTE format('
|
|
185
185
|
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
186
186
|
FOR VALUES IN (emt_sanitize_name(%L || ''__'' || %L)) PARTITION BY LIST (is_archived);',
|
|
187
|
-
emt_sanitize_name('${
|
|
187
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}'), '${i.name}', new_module, '${u}'
|
|
188
188
|
);
|
|
189
189
|
|
|
190
190
|
EXECUTE format('
|
|
191
191
|
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
192
192
|
FOR VALUES IN (FALSE);',
|
|
193
|
-
emt_sanitize_name('${
|
|
193
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}' || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}')
|
|
194
194
|
);
|
|
195
195
|
|
|
196
196
|
EXECUTE format('
|
|
197
197
|
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
198
198
|
FOR VALUES IN (TRUE);',
|
|
199
|
-
emt_sanitize_name('${
|
|
199
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}' || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || '${u}')
|
|
200
200
|
);
|
|
201
201
|
|
|
202
202
|
-- For ${s.name} table
|
|
203
203
|
EXECUTE format('
|
|
204
204
|
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
205
205
|
FOR VALUES IN (emt_sanitize_name(%L || ''__'' || %L)) PARTITION BY LIST (is_archived);',
|
|
206
|
-
emt_sanitize_name('${s.name}_' || new_module || '__' || '${
|
|
206
|
+
emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}'), '${s.name}', new_module, '${u}'
|
|
207
207
|
);
|
|
208
208
|
|
|
209
209
|
EXECUTE format('
|
|
210
210
|
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
211
211
|
FOR VALUES IN (FALSE);',
|
|
212
|
-
emt_sanitize_name('${s.name}_' || new_module || '__' || '${
|
|
212
|
+
emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}' || '_active'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}')
|
|
213
213
|
);
|
|
214
214
|
|
|
215
215
|
EXECUTE format('
|
|
216
216
|
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
217
217
|
FOR VALUES IN (TRUE);',
|
|
218
|
-
emt_sanitize_name('${s.name}_' || new_module || '__' || '${
|
|
218
|
+
emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}' || '_archived'), emt_sanitize_name('${s.name}_' || new_module || '__' || '${u}')
|
|
219
219
|
);
|
|
220
220
|
END;
|
|
221
221
|
$$ LANGUAGE plpgsql;
|
|
222
|
-
`),
|
|
222
|
+
`),he= exports.addTenantSQL =_dumbo.rawSql.call(void 0, `
|
|
223
223
|
CREATE OR REPLACE FUNCTION add_tenant(new_module TEXT, new_tenant TEXT) RETURNS void AS $$
|
|
224
224
|
BEGIN
|
|
225
|
-
-- For ${
|
|
225
|
+
-- For ${i.name} table
|
|
226
226
|
EXECUTE format('
|
|
227
227
|
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
228
228
|
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
229
|
-
emt_sanitize_name('${
|
|
229
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant), '${i.name}', new_module, new_tenant
|
|
230
230
|
);
|
|
231
231
|
|
|
232
232
|
EXECUTE format('
|
|
233
233
|
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
234
234
|
FOR VALUES IN (FALSE);',
|
|
235
|
-
emt_sanitize_name('${
|
|
235
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant)
|
|
236
236
|
);
|
|
237
237
|
|
|
238
238
|
EXECUTE format('
|
|
239
239
|
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
240
240
|
FOR VALUES IN (TRUE);',
|
|
241
|
-
emt_sanitize_name('${
|
|
241
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || new_tenant)
|
|
242
242
|
);
|
|
243
243
|
|
|
244
244
|
-- For ${s.name} table
|
|
@@ -261,32 +261,32 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
261
261
|
);
|
|
262
262
|
END;
|
|
263
263
|
$$ LANGUAGE plpgsql;
|
|
264
|
-
`),
|
|
264
|
+
`),Pe= exports.addModuleForAllTenantsSQL =_dumbo.rawSql.call(void 0, `
|
|
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;
|
|
268
268
|
BEGIN
|
|
269
269
|
PERFORM add_module(new_module);
|
|
270
270
|
|
|
271
|
-
FOR tenant_record IN SELECT DISTINCT tenant FROM ${
|
|
271
|
+
FOR tenant_record IN SELECT DISTINCT tenant FROM ${i.name}
|
|
272
272
|
LOOP
|
|
273
|
-
-- For ${
|
|
273
|
+
-- For ${i.name} table
|
|
274
274
|
EXECUTE format('
|
|
275
275
|
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
276
276
|
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
277
|
-
emt_sanitize_name('${
|
|
277
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant), '${i.name}', new_module, tenant_record.tenant
|
|
278
278
|
);
|
|
279
279
|
|
|
280
280
|
EXECUTE format('
|
|
281
281
|
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
282
282
|
FOR VALUES IN (FALSE);',
|
|
283
|
-
emt_sanitize_name('${
|
|
283
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant || '_active'), emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant)
|
|
284
284
|
);
|
|
285
285
|
|
|
286
286
|
EXECUTE format('
|
|
287
287
|
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
288
288
|
FOR VALUES IN (TRUE);',
|
|
289
|
-
emt_sanitize_name('${
|
|
289
|
+
emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant || '_archived'), emt_sanitize_name('${i.name}_' || new_module || '__' || tenant_record.tenant)
|
|
290
290
|
);
|
|
291
291
|
|
|
292
292
|
-- For ${s.name} table
|
|
@@ -310,30 +310,30 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
310
310
|
END LOOP;
|
|
311
311
|
END;
|
|
312
312
|
$$ LANGUAGE plpgsql;
|
|
313
|
-
`),
|
|
313
|
+
`),Ie= exports.addTenantForAllModulesSQL =_dumbo.rawSql.call(void 0, `
|
|
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;
|
|
317
317
|
BEGIN
|
|
318
|
-
FOR module_record IN SELECT DISTINCT partitionname FROM pg_partman.part_config WHERE parent_table = '${
|
|
318
|
+
FOR module_record IN SELECT DISTINCT partitionname FROM pg_partman.part_config WHERE parent_table = '${i.name}'
|
|
319
319
|
LOOP
|
|
320
|
-
-- For ${
|
|
320
|
+
-- For ${i.name} table
|
|
321
321
|
EXECUTE format('
|
|
322
322
|
CREATE TABLE IF NOT EXISTS %I PARTITION OF %I
|
|
323
323
|
FOR VALUES IN (emt_sanitize_name(''%s__%s'')) PARTITION BY LIST (is_archived);',
|
|
324
|
-
emt_sanitize_name('${
|
|
324
|
+
emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant), '${i.name}', module_record.partitionname, new_tenant
|
|
325
325
|
);
|
|
326
326
|
|
|
327
327
|
EXECUTE format('
|
|
328
328
|
CREATE TABLE IF NOT EXISTS %I_active PARTITION OF %I
|
|
329
329
|
FOR VALUES IN (FALSE);',
|
|
330
|
-
emt_sanitize_name('${
|
|
330
|
+
emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant || '_active'), emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant)
|
|
331
331
|
);
|
|
332
332
|
|
|
333
333
|
EXECUTE format('
|
|
334
334
|
CREATE TABLE IF NOT EXISTS %I_archived PARTITION OF %I
|
|
335
335
|
FOR VALUES IN (TRUE);',
|
|
336
|
-
emt_sanitize_name('${
|
|
336
|
+
emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant || '_archived'), emt_sanitize_name('${i.name}_' || module_record.partitionname || '__' || new_tenant)
|
|
337
337
|
);
|
|
338
338
|
|
|
339
339
|
-- For ${s.name} table
|
|
@@ -357,7 +357,7 @@ Actual:${P.stringify(t)}`)}function de(e,t,n){if(e===t)throw new h(_nullishCoale
|
|
|
357
357
|
END LOOP;
|
|
358
358
|
END;
|
|
359
359
|
$$ LANGUAGE plpgsql;
|
|
360
|
-
`),
|
|
361
|
-
FROM ${
|
|
362
|
-
WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${
|
|
360
|
+
`),Ne= exports.addDefaultPartition =_dumbo.rawSql.call(void 0, `SELECT emt_add_partition('${O}');`);var Oe=async(t,e,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),r=isNaN(a)?"":`AND stream_position <= ${a}`,l=await _dumbo.mapRows.call(void 0, t.query(_dumbo.sql.call(void 0, `SELECT stream_id, stream_position, global_position, event_data, event_metadata, event_schema_version, event_type, event_id
|
|
361
|
+
FROM ${i.name}
|
|
362
|
+
WHERE stream_id = %L AND partition = %L AND is_archived = FALSE ${o} ${r}`,e,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _30 => _30.partition]), () => (O)))),m=>{let p=J(m.event_type,m.event_data,m.event_metadata);return{...p,metadata:{...p.metadata,eventId:m.event_id,streamName:e,streamPosition:BigInt(m.stream_position),globalPosition:BigInt(m.global_position)}}});return l.length>0?{currentStreamVersion:l[l.length-1].metadata.streamPosition,events:l,streamExists:!0}:{currentStreamVersion:B,events:[],streamExists:!1}};var C=[ue,_e,Te,ge,Se,fe,ye,he,Pe,Ie,pe,Ne],X= exports.createEventStoreSchema =async t=>{await t.withTransaction(({execute:e})=>e.batchCommand(C))};var Pt={projections:[],schema:{autoMigration:"CreateOrUpdate"}},B= exports.PostgreSQLEventStoreDefaultStreamVersion =0n,It= exports.getPostgreSQLEventStore =(t,e=Pt)=>{let n={connectionString:t,...e.connectionOptions?e.connectionOptions:{}},o="dumbo"in n?n.dumbo:_dumbo.dumbo.call(void 0, n),a,r=_optionalChain([e, 'access', _31 => _31.schema, 'optionalAccess', _32 => _32.autoMigration])===void 0||_optionalChain([e, 'access', _33 => _33.schema, 'optionalAccess', _34 => _34.autoMigration])!=="None",l=()=>r?(a||(a=X(o)),a):Promise.resolve(),m=(_nullishCoalesce(e.projections, () => ([]))).filter(({type:c})=>c==="inline").map(({projection:c})=>c),p=m.length>0?(c,{transaction:E})=>D({projections:m,connection:{connectionString:t,transaction:E},events:c}):void 0;return{schema:{sql:()=>C.join(""),print:()=>console.log(C.join("")),migrate:async()=>{await(a=X(o))}},async aggregateStream(c,E){let{evolve:d,initialState:v,read:P}=E,I=_optionalChain([P, 'optionalAccess', _35 => _35.expectedStreamVersion]),f=v(),b=await this.readStream(c,E.read),V=b.currentStreamVersion;K(V,I,B);for(let G of b.events)G&&(f=d(f,G));return{currentStreamVersion:V,state:f,streamExists:b.streamExists}},readStream:async(c,E)=>(await l(),Oe(o.execute,c,E)),appendToStream:async(c,E,d)=>{await l();let[v,...P]=c.split("-"),I=v&&P.length>0?v:"emt:unknown",f=await ve(o,c,I,E,{...d,preCommitHook:p});if(!f.success)throw new $(-1n,_nullishCoalesce(_optionalChain([d, 'optionalAccess', _36 => _36.expectedStreamVersion]), () => (N)));return{nextExpectedStreamVersion:f.nextStreamPosition,createdNewStream:f.nextStreamPosition>=BigInt(E.length)}},close:()=>o.close(),async withSession(c){return await o.withConnection(async E=>{let d={...e,connectionOptions:{connection:E}},v=It(t,d);return c({eventStore:v,close:()=>Promise.resolve()})})}}};exports.PostgreSQLEventStoreDefaultStreamVersion = B; exports.PostgreSQLProjectionSpec = wn; exports.addDefaultPartition = Ne; exports.addEventsPartitions = fe; exports.addModuleForAllTenantsSQL = Pe; exports.addModuleSQL = ye; exports.addTablePartitions = Se; exports.addTenantForAllModulesSQL = Ie; exports.addTenantSQL = he; exports.appendEventsSQL = pe; exports.appendToStream = ve; exports.assertSQLQueryResultMatches = Et; exports.createEventStoreSchema = X; exports.defaultPostgreSQLOptions = Pt; exports.defaultTag = O; exports.documentDoesNotExist = de; exports.documentExists = at; exports.documentMatchingExists = me; exports.documentsAreTheSame = rt; exports.documentsMatchingHaveCount = it; exports.emmettPrefix = x; exports.eventInStream = dt; exports.eventsInStream = lt; exports.eventsTable = i; exports.eventsTableSQL = _e; exports.expectPongoDocuments = gn; exports.expectSQL = bn; exports.getPostgreSQLEventStore = It; exports.globalNames = Xn; exports.globalTag = u; exports.handleProjections = D; exports.newEventsInStream = Cn; exports.pongoMultiStreamProjection = mt; exports.pongoProjection = ct; exports.pongoSingleStreamProjection = Pn; exports.postgreSQLProjection = Q; exports.postgreSQLRawBatchSQLProjection = pt; exports.postgreSQLRawSQLProjection = $n; exports.readStream = Oe; exports.sanitizeNameSQL = ge; exports.schemaSQL = C; exports.streamsTable = s; exports.streamsTableSQL = ue; exports.subscriptionsTableSQL = Te;
|
|
363
363
|
//# sourceMappingURL=index.cjs.map
|