@event-driven-io/dumbo 0.11.0-alpha.1 → 0.11.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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } 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 Se=(e,t)=>typeof t=="bigint"?t.toString():t,fe=(e,t)=>typeof t=="string"&&/^[+-]?\d+n?$/.test(t)?BigInt(t):t,Oe= exports.composeJSONReplacers =(...e)=>(t,o)=>e.reduce((n,r)=>r(t,n),o),Le= exports.composeJSONRevivers =(...e)=>(t,o)=>e.reduce((n,r)=>r(t,n),o),G= exports.JSONReplacer =e=>_optionalChain([e, 'optionalAccess', _2 => _2.disableBigIntSerialization])==!0?e.replacer?e.replacer:void 0:_optionalChain([e, 'optionalAccess', _3 => _3.replacer])?Oe(j.bigInt,e.replacer):j.bigInt,H= exports.JSONReviver =e=>_optionalChain([e, 'optionalAccess', _4 => _4.disableBigIntSerialization])==!0?e.reviver?e.reviver:void 0:_optionalChain([e, 'optionalAccess', _5 => _5.reviver])?Le(Y.bigInt,e.reviver):Y.bigInt,j= exports.JSONReplacers ={bigInt:Se},Y= exports.JSONRevivers ={bigInt:fe},V= exports.jsonSerializer =e=>{let t=G(e),o=H(e);return{serialize:(n,r)=>JSON.stringify(n,r?G(r):t),deserialize:(n,r)=>JSON.parse(n,r?H(r):o)}},p= exports.JSONSerializer =V({disableBigIntSerialization:!1}),Ke= exports.RawJSONSerializer =V({disableBigIntSerialization:!0});var xe={AES128:!0,AES256:!0,ALL:!0,ALLOWOVERWRITE:!0,ANALYSE:!0,ANALYZE:!0,AND:!0,ANY:!0,ARRAY:!0,AS:!0,ASC:!0,AUTHORIZATION:!0,BACKUP:!0,BETWEEN:!0,BINARY:!0,BLANKSASNULL:!0,BOTH:!0,BYTEDICT:!0,CASE:!0,CAST:!0,CHECK:!0,COLLATE:!0,COLUMN:!0,CONSTRAINT:!0,CREATE:!0,CREDENTIALS:!0,CROSS:!0,CURRENT_DATE:!0,CURRENT_TIME:!0,CURRENT_TIMESTAMP:!0,CURRENT_USER:!0,CURRENT_USER_ID:!0,DEFAULT:!0,DEFERRABLE:!0,DEFLATE:!0,DEFRAG:!0,DELTA:!0,DELTA32K:!0,DESC:!0,DISABLE:!0,DISTINCT:!0,DO:!0,ELSE:!0,EMPTYASNULL:!0,ENABLE:!0,ENCODE:!0,ENCRYPT:!0,ENCRYPTION:!0,END:!0,EXCEPT:!0,EXPLICIT:!0,FALSE:!0,FOR:!0,FOREIGN:!0,FREEZE:!0,FROM:!0,FULL:!0,GLOBALDICT256:!0,GLOBALDICT64K:!0,GRANT:!0,GROUP:!0,GZIP:!0,HAVING:!0,IDENTITY:!0,IGNORE:!0,ILIKE:!0,IN:!0,INITIALLY:!0,INNER:!0,INTERSECT:!0,INTO:!0,IS:!0,ISNULL:!0,JOIN:!0,LEADING:!0,LEFT:!0,LIKE:!0,LIMIT:!0,LOCALTIME:!0,LOCALTIMESTAMP:!0,LUN:!0,LUNS:!0,LZO:!0,LZOP:!0,MINUS:!0,MOSTLY13:!0,MOSTLY32:!0,MOSTLY8:!0,NATURAL:!0,NEW:!0,NOT:!0,NOTNULL:!0,NULL:!0,NULLS:!0,OFF:!0,OFFLINE:!0,OFFSET:!0,OLD:!0,ON:!0,ONLY:!0,OPEN:!0,OR:!0,ORDER:!0,OUTER:!0,OVERLAPS:!0,PARALLEL:!0,PARTITION:!0,PERCENT:!0,PLACING:!0,PRIMARY:!0,RAW:!0,READRATIO:!0,RECOVER:!0,REFERENCES:!0,REJECTLOG:!0,RESORT:!0,RESTORE:!0,RIGHT:!0,SELECT:!0,SESSION_USER:!0,SIMILAR:!0,SOME:!0,SYSDATE:!0,SYSTEM:!0,TABLE:!0,TAG:!0,TDES:!0,TEXT255:!0,TEXT32K:!0,THEN:!0,TO:!0,TOP:!0,TRAILING:!0,TRUE:!0,TRUNCATECOLUMNS:!0,UNION:!0,UNIQUE:!0,USER:!0,USING:!0,VERBOSE:!0,WALLET:!0,WHEN:!0,WHERE:!0,WITH:!0,WITHOUT:!0},K=xe;var l={ident:"I",literal:"L",string:"s"},I=e=>(e=e.replace("T"," "),e=e.replace("Z","+00"),e),be=e=>!!K[e.toUpperCase()],$=(e,t,o)=>{let n="";n+=e?" (":"(";for(let r=0;r<t.length;r++)n+=(r===0?"":", ")+o(t[r]);return n+=")",n},q=e=>{if(e==null)throw new Error("SQL identifier cannot be null or undefined");if(e===!1)return'"f"';if(e===!0)return'"t"';if(e instanceof Date)return'"'+I(e.toISOString())+'"';if(e instanceof Buffer)throw new Error("SQL identifier cannot be a buffer");if(Array.isArray(e))return e.map(n=>{if(Array.isArray(n))throw new Error("Nested array to grouped list conversion is not supported for SQL identifier");return q(n)}).toString();if(e===Object(e))throw new Error("SQL identifier cannot be an object");let t=e.toString().slice(0);if(/^[a-z_][a-z0-9_$]*$/.test(t)&&!be(t))return t;let o='"';for(let n=0;n<t.length;n++){let r=t[n];o+=r==='"'?r+r:r}return o+='"',o},N=e=>{let t=null,o=null;if(e==null)return"NULL";if(e===!1)return"'f'";if(e===!0)return"'t'";if(e instanceof Date)return"'"+I(e.toISOString())+"'";if(e instanceof Buffer)return"E'\\\\x"+e.toString("hex")+"'";if(Array.isArray(e))return e.map((i,s)=>Array.isArray(i)?$(s!==0,i,N):N(i)).toString();e===Object(e)?(o="jsonb",t=p.serialize(e)):t=e.toString().slice(0);let n=!1,r="'";for(let i=0;i<t.length;i++){let s=t[i];s==="'"?r+=s+s:s==="\\"?(r+=s+s,n=!0):r+=s}return r+="'",n&&(r="E"+r),o&&(r+="::"+o),r},T=e=>e==null?"":e===!1?"f":e===!0?"t":e instanceof Date?I(e.toISOString()):e instanceof Buffer?"\\x"+e.toString("hex"):Array.isArray(e)?e.map((t,o)=>t!=null?Array.isArray(t)?$(o!==0,t,T):T(t):"").filter(t=>t!=="").toString():e===Object(e)?p.serialize(e):e.toString().slice(0),Ne=e=>{l.ident="I",l.literal="L",l.string="s",e&&e.pattern&&(e.pattern.ident&&(l.ident=e.pattern.ident),e.pattern.literal&&(l.literal=e.pattern.literal),e.pattern.string&&(l.string=e.pattern.string))},X=(e,t)=>{let o=0,n=t,r="%(%|(\\d+\\$)?[";return r+=l.ident,r+=l.literal,r+=l.string,r+="])",r=new RegExp(r,"g"),e.replace(r,(i,s)=>{if(s==="%")return"%";let c=o,y=s.split("$");if(y.length>1&&(c=parseInt(y[0],10)-1,s=y[1]),c<0)throw new Error("specified argument 0 but arguments start at 1");if(c>n.length-1)throw new Error("too few arguments");if(o=c+1,s===l.ident)return q(n[c]);if(s===l.literal)return N(n[c]);if(s===l.string)return T(n[c])})},m=(e,...t)=>X(e,t);m.config=Ne;m.format=m;m.ident=q;m.literal=N;m.string=T;m.withArray=X;var g=m;var d=(e,...t)=>g(e,...t),f= exports.rawSql =e=>e,it= exports.isSQL =e=>e!=null&&typeof e=="string",st= exports.literal =e=>({type:"literal",value:e}),at= exports.identifier =e=>({type:"identifier",value:e}),ct= exports.plainString =e=>({type:"plainString",value:e}),Te=e=>typeof e=="string"?g("%L",e):typeof e=="number"?e.toString():typeof e=="bigint"?g("%L",e):e instanceof Date?g("%L",e):Array.isArray(e)?g("(%L)",e):g("%L",e);function lt(e,...t){return e.map((o,n)=>{let r="";if(n<t.length){let i=t[n];if(i&&typeof i=="object"&&"type"in i&&"value"in i){let s=i;switch(s.type){case"literal":r=g("%L",s.value);break;case"identifier":r=g("%I",s.value);break;case"plainString":r=s.value;break}}else r=Te(i)}return o+r}).join("")}var w=(e,t)=>({query:(o,n)=>E(r=>e.query(r,o,n),t),batchQuery:(o,n)=>E(r=>e.batchQuery(r,o,n),t),command:(o,n)=>E(r=>e.command(r,o,n),t),batchCommand:(o,n)=>E(r=>e.batchQuery(r,o,n),t)}),Z= exports.sqlExecutorInNewConnection =e=>({query:t=>P(o=>o.execute.query(t),e),batchQuery:t=>P(o=>o.execute.batchQuery(t),e),command:t=>P(o=>o.execute.command(t),e),batchCommand:t=>P(o=>o.execute.batchCommand(t),e)}),E= exports.executeInNewDbClient =async(e,t)=>{let{connect:o,close:n}=t,r=await o();try{return await e(r)}catch(i){throw n&&await n(r,i),i}},P= exports.executeInNewConnection =async(e,t)=>{let o=await t.connection();try{return await e(o)}finally{await o.close()}};var Ee=e=>e!=null&&typeof e=="object"&&"success"in e?e:{success:!0,result:e},we= exports.executeInTransaction =async(e,t)=>{await e.begin();try{let{success:o,result:n}=Ee(await t(e));return o?await e.commit():await e.rollback(),n}catch(o){throw await e.rollback(),o}},ee= exports.transactionFactoryWithDbClient =(e,t)=>({transaction:()=>t(e()),withTransaction:o=>we(t(e()),o)}),M=async(e,t)=>{try{return await t()}finally{await e.close()}},te= exports.transactionFactoryWithNewConnection =e=>({transaction:()=>{let t=e(),o=t.transaction();return{...o,commit:()=>M(t,()=>o.commit()),rollback:()=>M(t,()=>o.rollback())}},withTransaction:t=>{let o=e();return M(o,()=>o.withTransaction(t))}});var z=e=>{let{type:t,connect:o,close:n,initTransaction:r,executor:i}=e,s=null,c=async()=>await _asyncNullishCoalesce(s, async () => ((s=await o))),C={type:t,open:c,close:()=>s?n(s):Promise.resolve(),...ee(c,r(()=>C)),execute:w(i(),{connect:c})};return C};var R=e=>{let{type:t,getConnection:o}=e,n="connection"in e?e.connection:()=>Promise.resolve(o()),r="withConnection"in e?e.withConnection:C=>P(C,{connection:n}),i="close"in e?e.close:()=>Promise.resolve(),s="execute"in e?e.execute:Z({connection:n}),c="transaction"in e&&"withTransaction"in e?{transaction:e.transaction,withTransaction:e.withTransaction}:te(o);return{type:t,connection:n,withConnection:r,close:i,execute:s,...c}};var wt=async(e,t)=>(await e).rows.map(t),De= exports.toCamelCase =e=>e.replace(/_([a-z])/g,t=>_nullishCoalesce(_optionalChain([t, 'access', _6 => _6[1], 'optionalAccess', _7 => _7.toUpperCase, 'call', _8 => _8()]), () => (""))),oe= exports.mapToCamelCase =e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[De(o)]=e[o]);return t};var Qt=async e=>{let t=await e;return t.rows.length>0?_nullishCoalesce(t.rows[0], () => (null)):null},At= exports.first =async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");return t.rows[0]},ne= exports.singleOrNull =async e=>{let t=await e;if(t.rows.length>1)throw new Error("Query had more than one result");return t.rows.length>0?_nullishCoalesce(t.rows[0], () => (null)):null},O= exports.single =async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");if(t.rows.length>1)throw new Error("Query had more than one result");return t.rows[0]},ht= exports.count =async e=>(await O(e)).count,J= exports.exists =async e=>(await O(e)).exists===!0;var re=(e,t)=>({name:e,sqls:t}),F= exports.MIGRATIONS_LOCK_ID =999956789,ie= exports.runSQLMigrations =(e,t,o)=>e.withTransaction(async({execute:n})=>{let{databaseLock:r,...i}=o.lock,s={lockId:F,...i},c=o.schema.migrationTable.migrations({connector:"PostgreSQL:pg"});return await r.withAcquire(n,async()=>{for(let y of c){let C=se(y);await n.command(f(C))}for(let y of t)await Qe(n,y)},s),{success:!o.dryRun,result:void 0}}),Qe=async(e,t)=>{let o=se(t),n=await Ae(o);try{let r={name:t.name,sqlHash:n};if(await he(e,r))return;await e.command(f(o)),await ke(e,r)}catch(r){throw console.error(`Failed to apply migration "${t.name}":`,r),r}},Ae=async e=>{let o=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")},se= exports.combineMigrations =(...e)=>e.flatMap(t=>t.sqls).join(`
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var Se=(e,t)=>typeof t=="bigint"?t.toString():t,fe=(e,t)=>typeof t=="string"&&/^[+-]?\d+n?$/.test(t)?BigInt(t):t,Oe= exports.composeJSONReplacers =(...e)=>(t,o)=>e.reduce((n,r)=>r(t,n),o),Le= exports.composeJSONRevivers =(...e)=>(t,o)=>e.reduce((n,r)=>r(t,n),o),G= exports.JSONReplacer =e=>_optionalChain([e, 'optionalAccess', _2 => _2.disableBigIntSerialization])==!0?e.replacer?e.replacer:void 0:_optionalChain([e, 'optionalAccess', _3 => _3.replacer])?Oe(j.bigInt,e.replacer):j.bigInt,H= exports.JSONReviver =e=>_optionalChain([e, 'optionalAccess', _4 => _4.disableBigIntSerialization])==!0?e.reviver?e.reviver:void 0:_optionalChain([e, 'optionalAccess', _5 => _5.reviver])?Le(Y.bigInt,e.reviver):Y.bigInt,j= exports.JSONReplacers ={bigInt:Se},Y= exports.JSONRevivers ={bigInt:fe},V= exports.jsonSerializer =e=>{let t=G(e),o=H(e);return{serialize:(n,r)=>JSON.stringify(n,r?G(r):t),deserialize:(n,r)=>JSON.parse(n,r?H(r):o)}},p= exports.JSONSerializer =V({disableBigIntSerialization:!1}),Ke= exports.RawJSONSerializer =V({disableBigIntSerialization:!0});var xe={AES128:!0,AES256:!0,ALL:!0,ALLOWOVERWRITE:!0,ANALYSE:!0,ANALYZE:!0,AND:!0,ANY:!0,ARRAY:!0,AS:!0,ASC:!0,AUTHORIZATION:!0,BACKUP:!0,BETWEEN:!0,BINARY:!0,BLANKSASNULL:!0,BOTH:!0,BYTEDICT:!0,CASE:!0,CAST:!0,CHECK:!0,COLLATE:!0,COLUMN:!0,CONSTRAINT:!0,CREATE:!0,CREDENTIALS:!0,CROSS:!0,CURRENT_DATE:!0,CURRENT_TIME:!0,CURRENT_TIMESTAMP:!0,CURRENT_USER:!0,CURRENT_USER_ID:!0,DEFAULT:!0,DEFERRABLE:!0,DEFLATE:!0,DEFRAG:!0,DELTA:!0,DELTA32K:!0,DESC:!0,DISABLE:!0,DISTINCT:!0,DO:!0,ELSE:!0,EMPTYASNULL:!0,ENABLE:!0,ENCODE:!0,ENCRYPT:!0,ENCRYPTION:!0,END:!0,EXCEPT:!0,EXPLICIT:!0,FALSE:!0,FOR:!0,FOREIGN:!0,FREEZE:!0,FROM:!0,FULL:!0,GLOBALDICT256:!0,GLOBALDICT64K:!0,GRANT:!0,GROUP:!0,GZIP:!0,HAVING:!0,IDENTITY:!0,IGNORE:!0,ILIKE:!0,IN:!0,INITIALLY:!0,INNER:!0,INTERSECT:!0,INTO:!0,IS:!0,ISNULL:!0,JOIN:!0,LEADING:!0,LEFT:!0,LIKE:!0,LIMIT:!0,LOCALTIME:!0,LOCALTIMESTAMP:!0,LUN:!0,LUNS:!0,LZO:!0,LZOP:!0,MINUS:!0,MOSTLY13:!0,MOSTLY32:!0,MOSTLY8:!0,NATURAL:!0,NEW:!0,NOT:!0,NOTNULL:!0,NULL:!0,NULLS:!0,OFF:!0,OFFLINE:!0,OFFSET:!0,OLD:!0,ON:!0,ONLY:!0,OPEN:!0,OR:!0,ORDER:!0,OUTER:!0,OVERLAPS:!0,PARALLEL:!0,PARTITION:!0,PERCENT:!0,PLACING:!0,PRIMARY:!0,RAW:!0,READRATIO:!0,RECOVER:!0,REFERENCES:!0,REJECTLOG:!0,RESORT:!0,RESTORE:!0,RIGHT:!0,SELECT:!0,SESSION_USER:!0,SIMILAR:!0,SOME:!0,SYSDATE:!0,SYSTEM:!0,TABLE:!0,TAG:!0,TDES:!0,TEXT255:!0,TEXT32K:!0,THEN:!0,TO:!0,TOP:!0,TRAILING:!0,TRUE:!0,TRUNCATECOLUMNS:!0,UNION:!0,UNIQUE:!0,USER:!0,USING:!0,VERBOSE:!0,WALLET:!0,WHEN:!0,WHERE:!0,WITH:!0,WITHOUT:!0},K=xe;var l={ident:"I",literal:"L",string:"s"},I=e=>(e=e.replace("T"," "),e=e.replace("Z","+00"),e),Ne=e=>!!K[e.toUpperCase()],$=(e,t,o)=>{let n="";n+=e?" (":"(";for(let r=0;r<t.length;r++)n+=(r===0?"":", ")+o(t[r]);return n+=")",n},q=e=>{if(e==null)throw new Error("SQL identifier cannot be null or undefined");if(e===!1)return'"f"';if(e===!0)return'"t"';if(e instanceof Date)return'"'+I(e.toISOString())+'"';if(e instanceof Buffer)throw new Error("SQL identifier cannot be a buffer");if(Array.isArray(e))return e.map(n=>{if(Array.isArray(n))throw new Error("Nested array to grouped list conversion is not supported for SQL identifier");return q(n)}).toString();if(e===Object(e))throw new Error("SQL identifier cannot be an object");let t=e.toString().slice(0);if(/^[a-z_][a-z0-9_$]*$/.test(t)&&!Ne(t))return t;let o='"';for(let n=0;n<t.length;n++){let r=t[n];o+=r==='"'?r+r:r}return o+='"',o},T=e=>{let t=null,o=null;if(e==null)return"NULL";if(e===!1)return"'f'";if(e===!0)return"'t'";if(e instanceof Date)return"'"+I(e.toISOString())+"'";if(e instanceof Buffer)return"E'\\\\x"+e.toString("hex")+"'";if(Array.isArray(e))return e.map((i,s)=>Array.isArray(i)?$(s!==0,i,T):T(i)).toString();e===Object(e)?(o="jsonb",t=p.serialize(e)):t=e.toString().slice(0);let n=!1,r="'";for(let i=0;i<t.length;i++){let s=t[i];s==="'"?r+=s+s:s==="\\"?(r+=s+s,n=!0):r+=s}return r+="'",n&&(r="E"+r),o&&(r+="::"+o),r},b=e=>e==null?"":e===!1?"f":e===!0?"t":e instanceof Date?I(e.toISOString()):e instanceof Buffer?"\\x"+e.toString("hex"):Array.isArray(e)?e.map((t,o)=>t!=null?Array.isArray(t)?$(o!==0,t,b):b(t):"").filter(t=>t!=="").toString():e===Object(e)?p.serialize(e):e.toString().slice(0),Te=e=>{l.ident="I",l.literal="L",l.string="s",e&&e.pattern&&(e.pattern.ident&&(l.ident=e.pattern.ident),e.pattern.literal&&(l.literal=e.pattern.literal),e.pattern.string&&(l.string=e.pattern.string))},X=(e,t)=>{let o=0,n=t,r="%(%|(\\d+\\$)?[";return r+=l.ident,r+=l.literal,r+=l.string,r+="])",r=new RegExp(r,"g"),e.replace(r,(i,s)=>{if(s==="%")return"%";let c=o,y=s.split("$");if(y.length>1&&(c=parseInt(y[0],10)-1,s=y[1]),c<0)throw new Error("specified argument 0 but arguments start at 1");if(c>n.length-1)throw new Error("too few arguments");if(o=c+1,s===l.ident)return q(n[c]);if(s===l.literal)return T(n[c]);if(s===l.string)return b(n[c])})},m=(e,...t)=>X(e,t);m.config=Te;m.format=m;m.ident=q;m.literal=T;m.string=b;m.withArray=X;var g=m;var d=(e,...t)=>g(e,...t),f= exports.rawSql =e=>e,it= exports.isSQL =e=>e!=null&&typeof e=="string",st= exports.literal =e=>({type:"literal",value:e}),at= exports.identifier =e=>({type:"identifier",value:e}),ct= exports.plainString =e=>({type:"plainString",value:e}),be=e=>typeof e=="string"?g("%L",e):typeof e=="number"?e.toString():typeof e=="bigint"?g("%L",e):e instanceof Date?g("%L",e):Array.isArray(e)?g("(%L)",e):g("%L",e);function lt(e,...t){return e.map((o,n)=>{let r="";if(n<t.length){let i=t[n];if(i&&typeof i=="object"&&"type"in i&&"value"in i){let s=i;switch(s.type){case"literal":r=g("%L",s.value);break;case"identifier":r=g("%I",s.value);break;case"plainString":r=s.value;break}}else r=be(i)}return o+r}).join("")}var w=(e,t)=>({query:(o,n)=>E(r=>e.query(r,o,n),t),batchQuery:(o,n)=>E(r=>e.batchQuery(r,o,n),t),command:(o,n)=>E(r=>e.command(r,o,n),t),batchCommand:(o,n)=>E(r=>e.batchQuery(r,o,n),t)}),Z= exports.sqlExecutorInNewConnection =e=>({query:t=>P(o=>o.execute.query(t),e),batchQuery:t=>P(o=>o.execute.batchQuery(t),e),command:t=>P(o=>o.execute.command(t),e),batchCommand:t=>P(o=>o.execute.batchCommand(t),e)}),E= exports.executeInNewDbClient =async(e,t)=>{let{connect:o,close:n}=t,r=await o();try{return await e(r)}catch(i){throw n&&await n(r,i),i}},P= exports.executeInNewConnection =async(e,t)=>{let o=await t.connection();try{return await e(o)}finally{await o.close()}};var Ee=e=>e!=null&&typeof e=="object"&&"success"in e?e:{success:!0,result:e},we= exports.executeInTransaction =async(e,t)=>{await e.begin();try{let{success:o,result:n}=Ee(await t(e));return o?await e.commit():await e.rollback(),n}catch(o){throw await e.rollback(),o}},ee= exports.transactionFactoryWithDbClient =(e,t)=>({transaction:()=>t(e()),withTransaction:o=>we(t(e()),o)}),M=async(e,t)=>{try{return await t()}finally{await e.close()}},te= exports.transactionFactoryWithNewConnection =e=>({transaction:()=>{let t=e(),o=t.transaction();return{...o,commit:()=>M(t,()=>o.commit()),rollback:()=>M(t,()=>o.rollback())}},withTransaction:t=>{let o=e();return M(o,()=>o.withTransaction(t))}});var z=e=>{let{type:t,connect:o,close:n,initTransaction:r,executor:i}=e,s=null,c=async()=>await _asyncNullishCoalesce(s, async () => ((s=await o))),C={type:t,open:c,close:()=>s?n(s):Promise.resolve(),...ee(c,r(()=>C)),execute:w(i(),{connect:c})};return C};var R=e=>{let{type:t,getConnection:o}=e,n="connection"in e?e.connection:()=>Promise.resolve(o()),r="withConnection"in e?e.withConnection:C=>P(C,{connection:n}),i="close"in e?e.close:()=>Promise.resolve(),s="execute"in e?e.execute:Z({connection:n}),c="transaction"in e&&"withTransaction"in e?{transaction:e.transaction,withTransaction:e.withTransaction}:te(o);return{type:t,connection:n,withConnection:r,close:i,execute:s,...c}};var wt=async(e,t)=>(await e).rows.map(t),De= exports.toCamelCase =e=>e.replace(/_([a-z])/g,t=>_nullishCoalesce(_optionalChain([t, 'access', _6 => _6[1], 'optionalAccess', _7 => _7.toUpperCase, 'call', _8 => _8()]), () => (""))),oe= exports.mapToCamelCase =e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[De(o)]=e[o]);return t};var Qt=async e=>{let t=await e;return t.rows.length>0?_nullishCoalesce(t.rows[0], () => (null)):null},At= exports.first =async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");return t.rows[0]},ne= exports.singleOrNull =async e=>{let t=await e;if(t.rows.length>1)throw new Error("Query had more than one result");return t.rows.length>0?_nullishCoalesce(t.rows[0], () => (null)):null},O= exports.single =async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");if(t.rows.length>1)throw new Error("Query had more than one result");return t.rows[0]},ht= exports.count =async e=>(await O(e)).count,J= exports.exists =async e=>(await O(e)).exists===!0;var re=(e,t)=>({name:e,sqls:t}),F= exports.MIGRATIONS_LOCK_ID =999956789,ie= exports.runSQLMigrations =(e,t,o)=>e.withTransaction(async({execute:n})=>{let{databaseLock:r,...i}=o.lock,s={lockId:F,...i},c=o.schema.migrationTable.migrations({connector:"PostgreSQL:pg"});return await r.withAcquire(n,async()=>{for(let y of c){let C=se(y);await n.command(f(C))}for(let y of t)await Qe(n,y)},s),{success:!o.dryRun,result:void 0}}),Qe=async(e,t)=>{let o=se(t),n=await Ae(o);try{let r={name:t.name,sqlHash:n};if(await he(e,r))return;await e.command(f(o)),await ke(e,r)}catch(r){throw console.error(`Failed to apply migration "${t.name}":`,r),r}},Ae=async e=>{let o=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")},se= exports.combineMigrations =(...e)=>e.flatMap(t=>t.sqls).join(`
2
2
  `),he=async(e,t)=>{let o=await ne(e.query(d("SELECT sql_hash FROM migrations WHERE name = %L",t.name)));if(o===null)return!1;let{sqlHash:n}=oe(o);if(n!==t.sqlHash)throw new Error(`Migration hash mismatch for "${t.name}". Aborting migration.`);return!0},ke=async(e,t)=>{await e.command(d(`
3
3
  INSERT INTO migrations (name, sql_hash)
4
4
  VALUES (%L, %L)
@@ -20,5 +20,5 @@
20
20
  WHERE
21
21
  proname = %L
22
22
  ) AS exists;
23
- `,e),go= exports.functionExists =async(e,t)=>J(e.execute.query(ze(t)));var Lo="postgresql://postgres@localhost:5432/postgres",v= exports.getDatabaseNameOrDefault =e=>_nullishCoalesce(_pgconnectionstring2.default.parse(e).database, () => (Q));var B=async(e,t)=>{let o=_nullishCoalesce(t.timeoutMs, () => (U.timeoutMs)),n=t.mode==="Permanent"?"pg_advisory_lock":"pg_advisory_xact_lock";try{return await O(e.query(d("SELECT %s(%s) AS locked",n,t.lockId),{timeoutMs:o})),!0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="57014")return!1;throw r}},A= exports.releaseAdvisoryLock =async(e,t)=>{let o=_nullishCoalesce(t.timeoutMs, () => (U.timeoutMs));try{return await O(e.query(d("SELECT pg_advisory_unlock(%s) AS locked",t.lockId),{timeoutMs:o})),!0}catch(n){if(n instanceof Error&&"code"in n&&n.code==="57014")return!1;throw n}},h= exports.acquireAdvisoryLock =async(e,t)=>{if(!await B(e,t))throw new Error("Failed to acquire advisory lock within the specified timeout. Migration aborted.")},ce= exports.AdvisoryLock ={acquire:h,tryAcquire:B,release:A,withAcquire:async(e,t,o)=>{await h(e,o);try{return await t()}finally{o.mode==="Permanent"&&await A(e,o)}}},ho= exports.advisoryLock =(e,t)=>({acquire:o=>h(e,{...t,..._nullishCoalesce(o, () => ({}))}),tryAcquire:o=>B(e,{...t,..._nullishCoalesce(o, () => ({}))}),release:()=>A(e,t),withAcquire:async(o,n)=>{await h(e,{...t,..._nullishCoalesce(n, () => ({}))});try{return await o()}finally{await A(e,t)}}});var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var le=e=>e instanceof _pg2.default.Pool,Fo= exports.isNodePostgresClient =e=>e instanceof _pg2.default.Client,Fe= exports.isNodePostgresPoolClient =e=>"release"in e&&typeof e.release=="function",Uo= exports.nodePostgresExecute =async(e,t)=>{let o=le(e)?await e.connect():e;try{return await t(o)}finally{le(e)&&Fe(o)&&o.release()}},L= exports.nodePostgresSQLExecutor =()=>({type:u,query:k,batchQuery:k,command:k,batchCommand:k});async function k(e,t,o){let n=Array.isArray(t)?t:[t],r=Array(n.length);_optionalChain([o, 'optionalAccess', _10 => _10.timeoutMs])&&await e.query(`SET statement_timeout = ${_optionalChain([o, 'optionalAccess', _11 => _11.timeoutMs])}`);for(let i=0;i<n.length;i++){let s=await e.query(n[i]);S.info("db:sql:query",{sql:n[i]}),r[i]={rowCount:s.rowCount,rows:s.rows}}return Array.isArray(t)?r:r[0]}var _=e=>(t,o)=>({connection:e(),type:u,begin:async()=>{await(await t).query("BEGIN")},commit:async()=>{let n=await t;await n.query("COMMIT"),_optionalChain([o, 'optionalAccess', _12 => _12.close])&&await _optionalChain([o, 'optionalAccess', _13 => _13.close, 'call', _14 => _14(n)])},rollback:async n=>{let r=await t;await r.query("ROLLBACK"),_optionalChain([o, 'optionalAccess', _15 => _15.close])&&await _optionalChain([o, 'optionalAccess', _16 => _16.close, 'call', _17 => _17(r,n)])},execute:w(L(),{connect:()=>t})});var u="PostgreSQL:pg",Ue= exports.nodePostgresClientConnection =e=>{let{connect:t,close:o}=e;return z({type:u,connect:t,close:o,initTransaction:n=>_(n),executor:L})},ve= exports.nodePostgresPoolClientConnection =e=>{let{connect:t,close:o}=e;return z({type:u,connect:t,close:o,initTransaction:n=>_(n),executor:L})};function x(e){return e.type==="Client"?Ue(e):ve(e)}var pe=e=>{_pg2.default.types.setTypeParser(20,t=>BigInt(t)),_pg2.default.types.setTypeParser(3802,t=>e.deserialize(t)),_pg2.default.types.setTypeParser(114,t=>e.deserialize(t))};var Be=e=>{let{connectionString:t,database:o}=e,n=je({connectionString:t,database:o}),r=()=>x({type:"PoolClient",connect:n.connect(),close:c=>Promise.resolve(c.release())});return R({type:u,connection:()=>Promise.resolve(r()),close:()=>Ye({connectionString:t,database:o}),getConnection:r})},_e= exports.nodePostgresAmbientNativePool =e=>{let{pool:t}=e;return R({type:u,getConnection:()=>x({type:"PoolClient",connect:t.connect(),close:o=>Promise.resolve(o.release())})})},We= exports.nodePostgresAmbientConnectionPool =e=>{let{connection:t}=e;return R({type:u,getConnection:()=>t,execute:t.execute,transaction:()=>t.transaction(),withTransaction:o=>t.withTransaction(o)})},Ge= exports.nodePostgresClientPool =e=>{let{connectionString:t,database:o}=e;return R({type:u,getConnection:()=>{let n=Promise.resolve(new _pg2.default.Client({connectionString:t,database:o})).then(async r=>(await r.connect(),r));return x({type:"Client",connect:n,close:r=>r.end()})}})},He= exports.nodePostgresAmbientClientPool =e=>{let{client:t}=e,o=()=>{let i=Promise.resolve(t);return x({type:"Client",connect:i,close:()=>Promise.resolve()})};return R({type:u,connection:()=>Promise.resolve(o()),close:()=>Promise.resolve(),getConnection:o})};function de(e){let{connectionString:t,database:o,serializer:n}=e;return pe(_nullishCoalesce(n, () => (p))),"client"in e&&e.client?He({client:e.client}):"connection"in e&&e.connection?We({connection:e.connection}):"pooled"in e&&e.pooled===!1?Ge({connectionString:t,database:o}):"pool"in e&&e.pool?_e({pool:e.pool}):Be({connectionString:t,database:o})}var b=new Map,ye=new Map,je= exports.getPool =e=>{let t=typeof e=="string"?e:e.connectionString,o=typeof e=="string"?{connectionString:t}:e,n=_nullishCoalesce(o.database, () => ((o.connectionString?v(o.connectionString):void 0))),r=Ce(t,n);return Pe(r,1),_nullishCoalesce(b.get(r), () => (b.set(r,new _pg2.default.Pool(o)).get(r)))},Ye= exports.endPool =async({connectionString:e,database:t,force:o})=>{t=_nullishCoalesce(t, () => (v(e)));let n=Ce(e,t),r=b.get(n);r&&(Pe(n,-1)<=0||o===!0)&&await me(n,r)},me= exports.onEndPool =async(e,t)=>{try{await t.end()}catch(o){console.log(`Error while closing the connection pool: ${e}`),console.log(o)}b.delete(e)},un= exports.endAllPools =()=>Promise.all([...b.entries()].map(([e,t])=>me(e,t))),Ce=(e,t)=>`${e}|${_nullishCoalesce(t, () => (Q))}`,Pe=(e,t)=>{let o=_nullishCoalesce(ye.get(e), () => (0)),n=o+t;return ye.set(e,o+t),n};var Re=de;var Ve=e=>Re(e),Tn= exports.dumbo =e=>Ve(e);exports.AdvisoryLock = ce; exports.JSONReplacer = G; exports.JSONReplacers = j; exports.JSONReviver = H; exports.JSONRevivers = Y; exports.JSONSerializer = p; exports.LogLevel = a; exports.MIGRATIONS_LOCK_ID = F; exports.NodePostgresConnectorType = u; exports.RawJSONSerializer = Ke; exports.SQL = lt; exports.acquireAdvisoryLock = h; exports.advisoryLock = ho; exports.combineMigrations = se; exports.composeJSONReplacers = Oe; exports.composeJSONRevivers = Le; exports.connectionPool = Ve; exports.count = ht; exports.createConnection = z; exports.createConnectionPool = R; exports.defaultDatabaseLockOptions = U; exports.defaultPostgreSQLConenctionString = Lo; exports.defaultPostgreSqlDatabase = Q; exports.dumbo = Tn; exports.endAllPools = un; exports.endPool = Ye; exports.executeInNewConnection = P; exports.executeInNewDbClient = E; exports.executeInTransaction = we; exports.exists = J; exports.first = At; exports.firstOrNull = Qt; exports.functionExists = go; exports.functionExistsSQL = ze; exports.getDatabaseNameOrDefault = v; exports.getPool = je; exports.identifier = at; exports.isNodePostgresClient = Fo; exports.isNodePostgresNativePool = le; exports.isNodePostgresPoolClient = Fe; exports.isSQL = it; exports.jsonSerializer = V; exports.literal = st; exports.mapRows = wt; exports.mapToCamelCase = oe; exports.migrationTableSchemaComponent = qe; exports.nodePostgresAmbientClientPool = He; exports.nodePostgresAmbientConnectionPool = We; exports.nodePostgresAmbientNativePool = _e; exports.nodePostgresClientConnection = Ue; exports.nodePostgresClientPool = Ge; exports.nodePostgresConnection = x; exports.nodePostgresExecute = Uo; exports.nodePostgresNativePool = Be; exports.nodePostgresPool = de; exports.nodePostgresPoolClientConnection = ve; exports.nodePostgresSQLExecutor = L; exports.nodePostgresTransaction = _; exports.onEndPool = me; exports.plainString = ct; exports.postgresPool = Re; exports.rawSql = f; exports.releaseAdvisoryLock = A; exports.runPostgreSQLMigrations = lo; exports.runSQLMigrations = ie; exports.schemaComponent = ae; exports.setNodePostgresTypeParser = pe; exports.single = O; exports.singleOrNull = ne; exports.sql = d; exports.sqlExecutor = w; exports.sqlExecutorInNewConnection = Z; exports.sqlMigration = re; exports.tableExists = yo; exports.tableExistsSQL = Me; exports.toCamelCase = De; exports.tracer = S; exports.transactionFactoryWithDbClient = ee; exports.transactionFactoryWithNewConnection = te; exports.tryAcquireAdvisoryLock = B;
23
+ `,e),go= exports.functionExists =async(e,t)=>J(e.execute.query(ze(t)));var Lo="postgresql://postgres@localhost:5432/postgres",v= exports.getDatabaseNameOrDefault =e=>_nullishCoalesce(_pgconnectionstring2.default.parse(e).database, () => (Q));var B=async(e,t)=>{let o=_nullishCoalesce(t.timeoutMs, () => (U.timeoutMs)),n=t.mode==="Permanent"?"pg_advisory_lock":"pg_advisory_xact_lock";try{return await O(e.query(d("SELECT %s(%s) AS locked",n,t.lockId),{timeoutMs:o})),!0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="57014")return!1;throw r}},A= exports.releaseAdvisoryLock =async(e,t)=>{let o=_nullishCoalesce(t.timeoutMs, () => (U.timeoutMs));try{return await O(e.query(d("SELECT pg_advisory_unlock(%s) AS locked",t.lockId),{timeoutMs:o})),!0}catch(n){if(n instanceof Error&&"code"in n&&n.code==="57014")return!1;throw n}},h= exports.acquireAdvisoryLock =async(e,t)=>{if(!await B(e,t))throw new Error("Failed to acquire advisory lock within the specified timeout. Migration aborted.")},ce= exports.AdvisoryLock ={acquire:h,tryAcquire:B,release:A,withAcquire:async(e,t,o)=>{await h(e,o);try{return await t()}finally{o.mode==="Permanent"&&await A(e,o)}}},ho= exports.advisoryLock =(e,t)=>({acquire:o=>h(e,{...t,..._nullishCoalesce(o, () => ({}))}),tryAcquire:o=>B(e,{...t,..._nullishCoalesce(o, () => ({}))}),release:()=>A(e,t),withAcquire:async(o,n)=>{await h(e,{...t,..._nullishCoalesce(n, () => ({}))});try{return await o()}finally{await A(e,t)}}});var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var le=e=>e instanceof _pg2.default.Pool,Fo= exports.isNodePostgresClient =e=>e instanceof _pg2.default.Client,Fe= exports.isNodePostgresPoolClient =e=>"release"in e&&typeof e.release=="function",Uo= exports.nodePostgresExecute =async(e,t)=>{let o=le(e)?await e.connect():e;try{return await t(o)}finally{le(e)&&Fe(o)&&o.release()}},L= exports.nodePostgresSQLExecutor =()=>({type:u,query:k,batchQuery:k,command:k,batchCommand:k});async function k(e,t,o){let n=Array.isArray(t)?t:[t],r=Array(n.length);_optionalChain([o, 'optionalAccess', _10 => _10.timeoutMs])&&await e.query(`SET statement_timeout = ${_optionalChain([o, 'optionalAccess', _11 => _11.timeoutMs])}`);for(let i=0;i<n.length;i++){let s=await e.query(n[i]);S.info("db:sql:query",{sql:n[i]}),r[i]={rowCount:s.rowCount,rows:s.rows}}return Array.isArray(t)?r:r[0]}var _=e=>(t,o)=>({connection:e(),type:u,begin:async()=>{await(await t).query("BEGIN")},commit:async()=>{let n=await t;await n.query("COMMIT"),_optionalChain([o, 'optionalAccess', _12 => _12.close])&&await _optionalChain([o, 'optionalAccess', _13 => _13.close, 'call', _14 => _14(n)])},rollback:async n=>{let r=await t;await r.query("ROLLBACK"),_optionalChain([o, 'optionalAccess', _15 => _15.close])&&await _optionalChain([o, 'optionalAccess', _16 => _16.close, 'call', _17 => _17(r,n)])},execute:w(L(),{connect:()=>t})});var u="PostgreSQL:pg",Ue= exports.nodePostgresClientConnection =e=>{let{connect:t,close:o}=e;return z({type:u,connect:t,close:o,initTransaction:n=>_(n),executor:L})},ve= exports.nodePostgresPoolClientConnection =e=>{let{connect:t,close:o}=e;return z({type:u,connect:t,close:o,initTransaction:n=>_(n),executor:L})};function x(e){return e.type==="Client"?Ue(e):ve(e)}var pe=e=>{_pg2.default.types.setTypeParser(20,t=>BigInt(t)),_pg2.default.types.setTypeParser(3802,t=>e.deserialize(t)),_pg2.default.types.setTypeParser(114,t=>e.deserialize(t))};var Be=e=>{let{connectionString:t,database:o}=e,n=je({connectionString:t,database:o}),r=()=>x({type:"PoolClient",connect:n.connect(),close:c=>Promise.resolve(c.release())});return R({type:u,connection:()=>Promise.resolve(r()),close:()=>Ye({connectionString:t,database:o}),getConnection:r})},_e= exports.nodePostgresAmbientNativePool =e=>{let{pool:t}=e;return R({type:u,getConnection:()=>x({type:"PoolClient",connect:t.connect(),close:o=>Promise.resolve(o.release())})})},We= exports.nodePostgresAmbientConnectionPool =e=>{let{connection:t}=e;return R({type:u,getConnection:()=>t,execute:t.execute,transaction:()=>t.transaction(),withTransaction:o=>t.withTransaction(o)})},Ge= exports.nodePostgresClientPool =e=>{let{connectionString:t,database:o}=e;return R({type:u,getConnection:()=>{let n=Promise.resolve(new _pg2.default.Client({connectionString:t,database:o})).then(async r=>(await r.connect(),r));return x({type:"Client",connect:n,close:r=>r.end()})}})},He= exports.nodePostgresAmbientClientPool =e=>{let{client:t}=e,o=()=>{let i=Promise.resolve(t);return x({type:"Client",connect:i,close:()=>Promise.resolve()})};return R({type:u,connection:()=>Promise.resolve(o()),close:()=>Promise.resolve(),getConnection:o})};function de(e){let{connectionString:t,database:o,serializer:n}=e;return pe(_nullishCoalesce(n, () => (p))),"client"in e&&e.client?He({client:e.client}):"connection"in e&&e.connection?We({connection:e.connection}):"pooled"in e&&e.pooled===!1?Ge({connectionString:t,database:o}):"pool"in e&&e.pool?_e({pool:e.pool}):Be({connectionString:t,database:o})}var N=new Map,ye=new Map,je= exports.getPool =e=>{let t=typeof e=="string"?e:e.connectionString,o=typeof e=="string"?{connectionString:t}:e,n=_nullishCoalesce(o.database, () => ((o.connectionString?v(o.connectionString):void 0))),r=Ce(t,n);return Pe(r,1),_nullishCoalesce(N.get(r), () => (N.set(r,new _pg2.default.Pool(o)).get(r)))},Ye= exports.endPool =async({connectionString:e,database:t,force:o})=>{t=_nullishCoalesce(t, () => (v(e)));let n=Ce(e,t),r=N.get(n);r&&(Pe(n,-1)<=0||o===!0)&&await me(n,r)},me= exports.onEndPool =async(e,t)=>{try{await t.end()}catch(o){console.log(`Error while closing the connection pool: ${e}`),console.log(o)}N.delete(e)},un= exports.endAllPools =()=>Promise.all([...N.entries()].map(([e,t])=>me(e,t))),Ce=(e,t)=>`${e}|${_nullishCoalesce(t, () => (Q))}`,Pe=(e,t)=>{let o=_nullishCoalesce(ye.get(e), () => (0)),n=o+t;return ye.set(e,o+t),n};var Re=de;var Ve=e=>Re(e),bn= exports.dumbo =e=>Ve(e);exports.AdvisoryLock = ce; exports.JSONReplacer = G; exports.JSONReplacers = j; exports.JSONReviver = H; exports.JSONRevivers = Y; exports.JSONSerializer = p; exports.LogLevel = a; exports.MIGRATIONS_LOCK_ID = F; exports.NodePostgresConnectorType = u; exports.RawJSONSerializer = Ke; exports.SQL = lt; exports.acquireAdvisoryLock = h; exports.advisoryLock = ho; exports.combineMigrations = se; exports.composeJSONReplacers = Oe; exports.composeJSONRevivers = Le; exports.connectionPool = Ve; exports.count = ht; exports.createConnection = z; exports.createConnectionPool = R; exports.defaultDatabaseLockOptions = U; exports.defaultPostgreSQLConenctionString = Lo; exports.defaultPostgreSqlDatabase = Q; exports.dumbo = bn; exports.endAllPools = un; exports.endPool = Ye; exports.executeInNewConnection = P; exports.executeInNewDbClient = E; exports.executeInTransaction = we; exports.exists = J; exports.first = At; exports.firstOrNull = Qt; exports.functionExists = go; exports.functionExistsSQL = ze; exports.getDatabaseNameOrDefault = v; exports.getPool = je; exports.identifier = at; exports.isNodePostgresClient = Fo; exports.isNodePostgresNativePool = le; exports.isNodePostgresPoolClient = Fe; exports.isSQL = it; exports.jsonSerializer = V; exports.literal = st; exports.mapRows = wt; exports.mapToCamelCase = oe; exports.migrationTableSchemaComponent = qe; exports.nodePostgresAmbientClientPool = He; exports.nodePostgresAmbientConnectionPool = We; exports.nodePostgresAmbientNativePool = _e; exports.nodePostgresClientConnection = Ue; exports.nodePostgresClientPool = Ge; exports.nodePostgresConnection = x; exports.nodePostgresExecute = Uo; exports.nodePostgresNativePool = Be; exports.nodePostgresPool = de; exports.nodePostgresPoolClientConnection = ve; exports.nodePostgresSQLExecutor = L; exports.nodePostgresTransaction = _; exports.onEndPool = me; exports.plainString = ct; exports.postgresPool = Re; exports.rawSql = f; exports.releaseAdvisoryLock = A; exports.runPostgreSQLMigrations = lo; exports.runSQLMigrations = ie; exports.schemaComponent = ae; exports.setNodePostgresTypeParser = pe; exports.single = O; exports.singleOrNull = ne; exports.sql = d; exports.sqlExecutor = w; exports.sqlExecutorInNewConnection = Z; exports.sqlMigration = re; exports.tableExists = yo; exports.tableExistsSQL = Me; exports.toCamelCase = De; exports.tracer = S; exports.transactionFactoryWithDbClient = ee; exports.transactionFactoryWithNewConnection = te; exports.tryAcquireAdvisoryLock = B;
24
24
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var Se=(e,t)=>typeof t=="bigint"?t.toString():t,fe=(e,t)=>typeof t=="string"&&/^[+-]?\d+n?$/.test(t)?BigInt(t):t,Oe=(...e)=>(t,o)=>e.reduce((n,r)=>r(t,n),o),Le=(...e)=>(t,o)=>e.reduce((n,r)=>r(t,n),o),G=e=>e?.disableBigIntSerialization==!0?e.replacer?e.replacer:void 0:e?.replacer?Oe(j.bigInt,e.replacer):j.bigInt,H=e=>e?.disableBigIntSerialization==!0?e.reviver?e.reviver:void 0:e?.reviver?Le(Y.bigInt,e.reviver):Y.bigInt,j={bigInt:Se},Y={bigInt:fe},V=e=>{let t=G(e),o=H(e);return{serialize:(n,r)=>JSON.stringify(n,r?G(r):t),deserialize:(n,r)=>JSON.parse(n,r?H(r):o)}},p=V({disableBigIntSerialization:!1}),Ke=V({disableBigIntSerialization:!0});var xe={AES128:!0,AES256:!0,ALL:!0,ALLOWOVERWRITE:!0,ANALYSE:!0,ANALYZE:!0,AND:!0,ANY:!0,ARRAY:!0,AS:!0,ASC:!0,AUTHORIZATION:!0,BACKUP:!0,BETWEEN:!0,BINARY:!0,BLANKSASNULL:!0,BOTH:!0,BYTEDICT:!0,CASE:!0,CAST:!0,CHECK:!0,COLLATE:!0,COLUMN:!0,CONSTRAINT:!0,CREATE:!0,CREDENTIALS:!0,CROSS:!0,CURRENT_DATE:!0,CURRENT_TIME:!0,CURRENT_TIMESTAMP:!0,CURRENT_USER:!0,CURRENT_USER_ID:!0,DEFAULT:!0,DEFERRABLE:!0,DEFLATE:!0,DEFRAG:!0,DELTA:!0,DELTA32K:!0,DESC:!0,DISABLE:!0,DISTINCT:!0,DO:!0,ELSE:!0,EMPTYASNULL:!0,ENABLE:!0,ENCODE:!0,ENCRYPT:!0,ENCRYPTION:!0,END:!0,EXCEPT:!0,EXPLICIT:!0,FALSE:!0,FOR:!0,FOREIGN:!0,FREEZE:!0,FROM:!0,FULL:!0,GLOBALDICT256:!0,GLOBALDICT64K:!0,GRANT:!0,GROUP:!0,GZIP:!0,HAVING:!0,IDENTITY:!0,IGNORE:!0,ILIKE:!0,IN:!0,INITIALLY:!0,INNER:!0,INTERSECT:!0,INTO:!0,IS:!0,ISNULL:!0,JOIN:!0,LEADING:!0,LEFT:!0,LIKE:!0,LIMIT:!0,LOCALTIME:!0,LOCALTIMESTAMP:!0,LUN:!0,LUNS:!0,LZO:!0,LZOP:!0,MINUS:!0,MOSTLY13:!0,MOSTLY32:!0,MOSTLY8:!0,NATURAL:!0,NEW:!0,NOT:!0,NOTNULL:!0,NULL:!0,NULLS:!0,OFF:!0,OFFLINE:!0,OFFSET:!0,OLD:!0,ON:!0,ONLY:!0,OPEN:!0,OR:!0,ORDER:!0,OUTER:!0,OVERLAPS:!0,PARALLEL:!0,PARTITION:!0,PERCENT:!0,PLACING:!0,PRIMARY:!0,RAW:!0,READRATIO:!0,RECOVER:!0,REFERENCES:!0,REJECTLOG:!0,RESORT:!0,RESTORE:!0,RIGHT:!0,SELECT:!0,SESSION_USER:!0,SIMILAR:!0,SOME:!0,SYSDATE:!0,SYSTEM:!0,TABLE:!0,TAG:!0,TDES:!0,TEXT255:!0,TEXT32K:!0,THEN:!0,TO:!0,TOP:!0,TRAILING:!0,TRUE:!0,TRUNCATECOLUMNS:!0,UNION:!0,UNIQUE:!0,USER:!0,USING:!0,VERBOSE:!0,WALLET:!0,WHEN:!0,WHERE:!0,WITH:!0,WITHOUT:!0},K=xe;var l={ident:"I",literal:"L",string:"s"},I=e=>(e=e.replace("T"," "),e=e.replace("Z","+00"),e),be=e=>!!K[e.toUpperCase()],$=(e,t,o)=>{let n="";n+=e?" (":"(";for(let r=0;r<t.length;r++)n+=(r===0?"":", ")+o(t[r]);return n+=")",n},q=e=>{if(e==null)throw new Error("SQL identifier cannot be null or undefined");if(e===!1)return'"f"';if(e===!0)return'"t"';if(e instanceof Date)return'"'+I(e.toISOString())+'"';if(e instanceof Buffer)throw new Error("SQL identifier cannot be a buffer");if(Array.isArray(e))return e.map(n=>{if(Array.isArray(n))throw new Error("Nested array to grouped list conversion is not supported for SQL identifier");return q(n)}).toString();if(e===Object(e))throw new Error("SQL identifier cannot be an object");let t=e.toString().slice(0);if(/^[a-z_][a-z0-9_$]*$/.test(t)&&!be(t))return t;let o='"';for(let n=0;n<t.length;n++){let r=t[n];o+=r==='"'?r+r:r}return o+='"',o},N=e=>{let t=null,o=null;if(e==null)return"NULL";if(e===!1)return"'f'";if(e===!0)return"'t'";if(e instanceof Date)return"'"+I(e.toISOString())+"'";if(e instanceof Buffer)return"E'\\\\x"+e.toString("hex")+"'";if(Array.isArray(e))return e.map((i,s)=>Array.isArray(i)?$(s!==0,i,N):N(i)).toString();e===Object(e)?(o="jsonb",t=p.serialize(e)):t=e.toString().slice(0);let n=!1,r="'";for(let i=0;i<t.length;i++){let s=t[i];s==="'"?r+=s+s:s==="\\"?(r+=s+s,n=!0):r+=s}return r+="'",n&&(r="E"+r),o&&(r+="::"+o),r},T=e=>e==null?"":e===!1?"f":e===!0?"t":e instanceof Date?I(e.toISOString()):e instanceof Buffer?"\\x"+e.toString("hex"):Array.isArray(e)?e.map((t,o)=>t!=null?Array.isArray(t)?$(o!==0,t,T):T(t):"").filter(t=>t!=="").toString():e===Object(e)?p.serialize(e):e.toString().slice(0),Ne=e=>{l.ident="I",l.literal="L",l.string="s",e&&e.pattern&&(e.pattern.ident&&(l.ident=e.pattern.ident),e.pattern.literal&&(l.literal=e.pattern.literal),e.pattern.string&&(l.string=e.pattern.string))},X=(e,t)=>{let o=0,n=t,r="%(%|(\\d+\\$)?[";return r+=l.ident,r+=l.literal,r+=l.string,r+="])",r=new RegExp(r,"g"),e.replace(r,(i,s)=>{if(s==="%")return"%";let c=o,y=s.split("$");if(y.length>1&&(c=parseInt(y[0],10)-1,s=y[1]),c<0)throw new Error("specified argument 0 but arguments start at 1");if(c>n.length-1)throw new Error("too few arguments");if(o=c+1,s===l.ident)return q(n[c]);if(s===l.literal)return N(n[c]);if(s===l.string)return T(n[c])})},m=(e,...t)=>X(e,t);m.config=Ne;m.format=m;m.ident=q;m.literal=N;m.string=T;m.withArray=X;var g=m;var d=(e,...t)=>g(e,...t),f=e=>e,it=e=>e!=null&&typeof e=="string",st=e=>({type:"literal",value:e}),at=e=>({type:"identifier",value:e}),ct=e=>({type:"plainString",value:e}),Te=e=>typeof e=="string"?g("%L",e):typeof e=="number"?e.toString():typeof e=="bigint"?g("%L",e):e instanceof Date?g("%L",e):Array.isArray(e)?g("(%L)",e):g("%L",e);function lt(e,...t){return e.map((o,n)=>{let r="";if(n<t.length){let i=t[n];if(i&&typeof i=="object"&&"type"in i&&"value"in i){let s=i;switch(s.type){case"literal":r=g("%L",s.value);break;case"identifier":r=g("%I",s.value);break;case"plainString":r=s.value;break}}else r=Te(i)}return o+r}).join("")}var w=(e,t)=>({query:(o,n)=>E(r=>e.query(r,o,n),t),batchQuery:(o,n)=>E(r=>e.batchQuery(r,o,n),t),command:(o,n)=>E(r=>e.command(r,o,n),t),batchCommand:(o,n)=>E(r=>e.batchQuery(r,o,n),t)}),Z=e=>({query:t=>P(o=>o.execute.query(t),e),batchQuery:t=>P(o=>o.execute.batchQuery(t),e),command:t=>P(o=>o.execute.command(t),e),batchCommand:t=>P(o=>o.execute.batchCommand(t),e)}),E=async(e,t)=>{let{connect:o,close:n}=t,r=await o();try{return await e(r)}catch(i){throw n&&await n(r,i),i}},P=async(e,t)=>{let o=await t.connection();try{return await e(o)}finally{await o.close()}};var Ee=e=>e!=null&&typeof e=="object"&&"success"in e?e:{success:!0,result:e},we=async(e,t)=>{await e.begin();try{let{success:o,result:n}=Ee(await t(e));return o?await e.commit():await e.rollback(),n}catch(o){throw await e.rollback(),o}},ee=(e,t)=>({transaction:()=>t(e()),withTransaction:o=>we(t(e()),o)}),M=async(e,t)=>{try{return await t()}finally{await e.close()}},te=e=>({transaction:()=>{let t=e(),o=t.transaction();return{...o,commit:()=>M(t,()=>o.commit()),rollback:()=>M(t,()=>o.rollback())}},withTransaction:t=>{let o=e();return M(o,()=>o.withTransaction(t))}});var z=e=>{let{type:t,connect:o,close:n,initTransaction:r,executor:i}=e,s=null,c=async()=>s??(s=await o),C={type:t,open:c,close:()=>s?n(s):Promise.resolve(),...ee(c,r(()=>C)),execute:w(i(),{connect:c})};return C};var R=e=>{let{type:t,getConnection:o}=e,n="connection"in e?e.connection:()=>Promise.resolve(o()),r="withConnection"in e?e.withConnection:C=>P(C,{connection:n}),i="close"in e?e.close:()=>Promise.resolve(),s="execute"in e?e.execute:Z({connection:n}),c="transaction"in e&&"withTransaction"in e?{transaction:e.transaction,withTransaction:e.withTransaction}:te(o);return{type:t,connection:n,withConnection:r,close:i,execute:s,...c}};var wt=async(e,t)=>(await e).rows.map(t),De=e=>e.replace(/_([a-z])/g,t=>t[1]?.toUpperCase()??""),oe=e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[De(o)]=e[o]);return t};var Qt=async e=>{let t=await e;return t.rows.length>0?t.rows[0]??null:null},At=async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");return t.rows[0]},ne=async e=>{let t=await e;if(t.rows.length>1)throw new Error("Query had more than one result");return t.rows.length>0?t.rows[0]??null:null},O=async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");if(t.rows.length>1)throw new Error("Query had more than one result");return t.rows[0]},ht=async e=>(await O(e)).count,J=async e=>(await O(e)).exists===!0;var re=(e,t)=>({name:e,sqls:t}),F=999956789,ie=(e,t,o)=>e.withTransaction(async({execute:n})=>{let{databaseLock:r,...i}=o.lock,s={lockId:F,...i},c=o.schema.migrationTable.migrations({connector:"PostgreSQL:pg"});return await r.withAcquire(n,async()=>{for(let y of c){let C=se(y);await n.command(f(C))}for(let y of t)await Qe(n,y)},s),{success:!o.dryRun,result:void 0}}),Qe=async(e,t)=>{let o=se(t),n=await Ae(o);try{let r={name:t.name,sqlHash:n};if(await he(e,r))return;await e.command(f(o)),await ke(e,r)}catch(r){throw console.error(`Failed to apply migration "${t.name}":`,r),r}},Ae=async e=>{let o=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")},se=(...e)=>e.flatMap(t=>t.sqls).join(`
1
+ var Se=(e,t)=>typeof t=="bigint"?t.toString():t,fe=(e,t)=>typeof t=="string"&&/^[+-]?\d+n?$/.test(t)?BigInt(t):t,Oe=(...e)=>(t,o)=>e.reduce((n,r)=>r(t,n),o),Le=(...e)=>(t,o)=>e.reduce((n,r)=>r(t,n),o),G=e=>e?.disableBigIntSerialization==!0?e.replacer?e.replacer:void 0:e?.replacer?Oe(j.bigInt,e.replacer):j.bigInt,H=e=>e?.disableBigIntSerialization==!0?e.reviver?e.reviver:void 0:e?.reviver?Le(Y.bigInt,e.reviver):Y.bigInt,j={bigInt:Se},Y={bigInt:fe},V=e=>{let t=G(e),o=H(e);return{serialize:(n,r)=>JSON.stringify(n,r?G(r):t),deserialize:(n,r)=>JSON.parse(n,r?H(r):o)}},p=V({disableBigIntSerialization:!1}),Ke=V({disableBigIntSerialization:!0});var xe={AES128:!0,AES256:!0,ALL:!0,ALLOWOVERWRITE:!0,ANALYSE:!0,ANALYZE:!0,AND:!0,ANY:!0,ARRAY:!0,AS:!0,ASC:!0,AUTHORIZATION:!0,BACKUP:!0,BETWEEN:!0,BINARY:!0,BLANKSASNULL:!0,BOTH:!0,BYTEDICT:!0,CASE:!0,CAST:!0,CHECK:!0,COLLATE:!0,COLUMN:!0,CONSTRAINT:!0,CREATE:!0,CREDENTIALS:!0,CROSS:!0,CURRENT_DATE:!0,CURRENT_TIME:!0,CURRENT_TIMESTAMP:!0,CURRENT_USER:!0,CURRENT_USER_ID:!0,DEFAULT:!0,DEFERRABLE:!0,DEFLATE:!0,DEFRAG:!0,DELTA:!0,DELTA32K:!0,DESC:!0,DISABLE:!0,DISTINCT:!0,DO:!0,ELSE:!0,EMPTYASNULL:!0,ENABLE:!0,ENCODE:!0,ENCRYPT:!0,ENCRYPTION:!0,END:!0,EXCEPT:!0,EXPLICIT:!0,FALSE:!0,FOR:!0,FOREIGN:!0,FREEZE:!0,FROM:!0,FULL:!0,GLOBALDICT256:!0,GLOBALDICT64K:!0,GRANT:!0,GROUP:!0,GZIP:!0,HAVING:!0,IDENTITY:!0,IGNORE:!0,ILIKE:!0,IN:!0,INITIALLY:!0,INNER:!0,INTERSECT:!0,INTO:!0,IS:!0,ISNULL:!0,JOIN:!0,LEADING:!0,LEFT:!0,LIKE:!0,LIMIT:!0,LOCALTIME:!0,LOCALTIMESTAMP:!0,LUN:!0,LUNS:!0,LZO:!0,LZOP:!0,MINUS:!0,MOSTLY13:!0,MOSTLY32:!0,MOSTLY8:!0,NATURAL:!0,NEW:!0,NOT:!0,NOTNULL:!0,NULL:!0,NULLS:!0,OFF:!0,OFFLINE:!0,OFFSET:!0,OLD:!0,ON:!0,ONLY:!0,OPEN:!0,OR:!0,ORDER:!0,OUTER:!0,OVERLAPS:!0,PARALLEL:!0,PARTITION:!0,PERCENT:!0,PLACING:!0,PRIMARY:!0,RAW:!0,READRATIO:!0,RECOVER:!0,REFERENCES:!0,REJECTLOG:!0,RESORT:!0,RESTORE:!0,RIGHT:!0,SELECT:!0,SESSION_USER:!0,SIMILAR:!0,SOME:!0,SYSDATE:!0,SYSTEM:!0,TABLE:!0,TAG:!0,TDES:!0,TEXT255:!0,TEXT32K:!0,THEN:!0,TO:!0,TOP:!0,TRAILING:!0,TRUE:!0,TRUNCATECOLUMNS:!0,UNION:!0,UNIQUE:!0,USER:!0,USING:!0,VERBOSE:!0,WALLET:!0,WHEN:!0,WHERE:!0,WITH:!0,WITHOUT:!0},K=xe;var l={ident:"I",literal:"L",string:"s"},I=e=>(e=e.replace("T"," "),e=e.replace("Z","+00"),e),Ne=e=>!!K[e.toUpperCase()],$=(e,t,o)=>{let n="";n+=e?" (":"(";for(let r=0;r<t.length;r++)n+=(r===0?"":", ")+o(t[r]);return n+=")",n},q=e=>{if(e==null)throw new Error("SQL identifier cannot be null or undefined");if(e===!1)return'"f"';if(e===!0)return'"t"';if(e instanceof Date)return'"'+I(e.toISOString())+'"';if(e instanceof Buffer)throw new Error("SQL identifier cannot be a buffer");if(Array.isArray(e))return e.map(n=>{if(Array.isArray(n))throw new Error("Nested array to grouped list conversion is not supported for SQL identifier");return q(n)}).toString();if(e===Object(e))throw new Error("SQL identifier cannot be an object");let t=e.toString().slice(0);if(/^[a-z_][a-z0-9_$]*$/.test(t)&&!Ne(t))return t;let o='"';for(let n=0;n<t.length;n++){let r=t[n];o+=r==='"'?r+r:r}return o+='"',o},T=e=>{let t=null,o=null;if(e==null)return"NULL";if(e===!1)return"'f'";if(e===!0)return"'t'";if(e instanceof Date)return"'"+I(e.toISOString())+"'";if(e instanceof Buffer)return"E'\\\\x"+e.toString("hex")+"'";if(Array.isArray(e))return e.map((i,s)=>Array.isArray(i)?$(s!==0,i,T):T(i)).toString();e===Object(e)?(o="jsonb",t=p.serialize(e)):t=e.toString().slice(0);let n=!1,r="'";for(let i=0;i<t.length;i++){let s=t[i];s==="'"?r+=s+s:s==="\\"?(r+=s+s,n=!0):r+=s}return r+="'",n&&(r="E"+r),o&&(r+="::"+o),r},b=e=>e==null?"":e===!1?"f":e===!0?"t":e instanceof Date?I(e.toISOString()):e instanceof Buffer?"\\x"+e.toString("hex"):Array.isArray(e)?e.map((t,o)=>t!=null?Array.isArray(t)?$(o!==0,t,b):b(t):"").filter(t=>t!=="").toString():e===Object(e)?p.serialize(e):e.toString().slice(0),Te=e=>{l.ident="I",l.literal="L",l.string="s",e&&e.pattern&&(e.pattern.ident&&(l.ident=e.pattern.ident),e.pattern.literal&&(l.literal=e.pattern.literal),e.pattern.string&&(l.string=e.pattern.string))},X=(e,t)=>{let o=0,n=t,r="%(%|(\\d+\\$)?[";return r+=l.ident,r+=l.literal,r+=l.string,r+="])",r=new RegExp(r,"g"),e.replace(r,(i,s)=>{if(s==="%")return"%";let c=o,y=s.split("$");if(y.length>1&&(c=parseInt(y[0],10)-1,s=y[1]),c<0)throw new Error("specified argument 0 but arguments start at 1");if(c>n.length-1)throw new Error("too few arguments");if(o=c+1,s===l.ident)return q(n[c]);if(s===l.literal)return T(n[c]);if(s===l.string)return b(n[c])})},m=(e,...t)=>X(e,t);m.config=Te;m.format=m;m.ident=q;m.literal=T;m.string=b;m.withArray=X;var g=m;var d=(e,...t)=>g(e,...t),f=e=>e,it=e=>e!=null&&typeof e=="string",st=e=>({type:"literal",value:e}),at=e=>({type:"identifier",value:e}),ct=e=>({type:"plainString",value:e}),be=e=>typeof e=="string"?g("%L",e):typeof e=="number"?e.toString():typeof e=="bigint"?g("%L",e):e instanceof Date?g("%L",e):Array.isArray(e)?g("(%L)",e):g("%L",e);function lt(e,...t){return e.map((o,n)=>{let r="";if(n<t.length){let i=t[n];if(i&&typeof i=="object"&&"type"in i&&"value"in i){let s=i;switch(s.type){case"literal":r=g("%L",s.value);break;case"identifier":r=g("%I",s.value);break;case"plainString":r=s.value;break}}else r=be(i)}return o+r}).join("")}var w=(e,t)=>({query:(o,n)=>E(r=>e.query(r,o,n),t),batchQuery:(o,n)=>E(r=>e.batchQuery(r,o,n),t),command:(o,n)=>E(r=>e.command(r,o,n),t),batchCommand:(o,n)=>E(r=>e.batchQuery(r,o,n),t)}),Z=e=>({query:t=>P(o=>o.execute.query(t),e),batchQuery:t=>P(o=>o.execute.batchQuery(t),e),command:t=>P(o=>o.execute.command(t),e),batchCommand:t=>P(o=>o.execute.batchCommand(t),e)}),E=async(e,t)=>{let{connect:o,close:n}=t,r=await o();try{return await e(r)}catch(i){throw n&&await n(r,i),i}},P=async(e,t)=>{let o=await t.connection();try{return await e(o)}finally{await o.close()}};var Ee=e=>e!=null&&typeof e=="object"&&"success"in e?e:{success:!0,result:e},we=async(e,t)=>{await e.begin();try{let{success:o,result:n}=Ee(await t(e));return o?await e.commit():await e.rollback(),n}catch(o){throw await e.rollback(),o}},ee=(e,t)=>({transaction:()=>t(e()),withTransaction:o=>we(t(e()),o)}),M=async(e,t)=>{try{return await t()}finally{await e.close()}},te=e=>({transaction:()=>{let t=e(),o=t.transaction();return{...o,commit:()=>M(t,()=>o.commit()),rollback:()=>M(t,()=>o.rollback())}},withTransaction:t=>{let o=e();return M(o,()=>o.withTransaction(t))}});var z=e=>{let{type:t,connect:o,close:n,initTransaction:r,executor:i}=e,s=null,c=async()=>s??(s=await o),C={type:t,open:c,close:()=>s?n(s):Promise.resolve(),...ee(c,r(()=>C)),execute:w(i(),{connect:c})};return C};var R=e=>{let{type:t,getConnection:o}=e,n="connection"in e?e.connection:()=>Promise.resolve(o()),r="withConnection"in e?e.withConnection:C=>P(C,{connection:n}),i="close"in e?e.close:()=>Promise.resolve(),s="execute"in e?e.execute:Z({connection:n}),c="transaction"in e&&"withTransaction"in e?{transaction:e.transaction,withTransaction:e.withTransaction}:te(o);return{type:t,connection:n,withConnection:r,close:i,execute:s,...c}};var wt=async(e,t)=>(await e).rows.map(t),De=e=>e.replace(/_([a-z])/g,t=>t[1]?.toUpperCase()??""),oe=e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[De(o)]=e[o]);return t};var Qt=async e=>{let t=await e;return t.rows.length>0?t.rows[0]??null:null},At=async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");return t.rows[0]},ne=async e=>{let t=await e;if(t.rows.length>1)throw new Error("Query had more than one result");return t.rows.length>0?t.rows[0]??null:null},O=async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");if(t.rows.length>1)throw new Error("Query had more than one result");return t.rows[0]},ht=async e=>(await O(e)).count,J=async e=>(await O(e)).exists===!0;var re=(e,t)=>({name:e,sqls:t}),F=999956789,ie=(e,t,o)=>e.withTransaction(async({execute:n})=>{let{databaseLock:r,...i}=o.lock,s={lockId:F,...i},c=o.schema.migrationTable.migrations({connector:"PostgreSQL:pg"});return await r.withAcquire(n,async()=>{for(let y of c){let C=se(y);await n.command(f(C))}for(let y of t)await Qe(n,y)},s),{success:!o.dryRun,result:void 0}}),Qe=async(e,t)=>{let o=se(t),n=await Ae(o);try{let r={name:t.name,sqlHash:n};if(await he(e,r))return;await e.command(f(o)),await ke(e,r)}catch(r){throw console.error(`Failed to apply migration "${t.name}":`,r),r}},Ae=async e=>{let o=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")},se=(...e)=>e.flatMap(t=>t.sqls).join(`
2
2
  `),he=async(e,t)=>{let o=await ne(e.query(d("SELECT sql_hash FROM migrations WHERE name = %L",t.name)));if(o===null)return!1;let{sqlHash:n}=oe(o);if(n!==t.sqlHash)throw new Error(`Migration hash mismatch for "${t.name}". Aborting migration.`);return!0},ke=async(e,t)=>{await e.command(d(`
3
3
  INSERT INTO migrations (name, sql_hash)
4
4
  VALUES (%L, %L)
@@ -20,5 +20,5 @@ var Se=(e,t)=>typeof t=="bigint"?t.toString():t,fe=(e,t)=>typeof t=="string"&&/^
20
20
  WHERE
21
21
  proname = %L
22
22
  ) AS exists;
23
- `,e),go=async(e,t)=>J(e.execute.query(ze(t)));var Lo="postgresql://postgres@localhost:5432/postgres",v=e=>Je.parse(e).database??Q;var B=async(e,t)=>{let o=t.timeoutMs??U.timeoutMs,n=t.mode==="Permanent"?"pg_advisory_lock":"pg_advisory_xact_lock";try{return await O(e.query(d("SELECT %s(%s) AS locked",n,t.lockId),{timeoutMs:o})),!0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="57014")return!1;throw r}},A=async(e,t)=>{let o=t.timeoutMs??U.timeoutMs;try{return await O(e.query(d("SELECT pg_advisory_unlock(%s) AS locked",t.lockId),{timeoutMs:o})),!0}catch(n){if(n instanceof Error&&"code"in n&&n.code==="57014")return!1;throw n}},h=async(e,t)=>{if(!await B(e,t))throw new Error("Failed to acquire advisory lock within the specified timeout. Migration aborted.")},ce={acquire:h,tryAcquire:B,release:A,withAcquire:async(e,t,o)=>{await h(e,o);try{return await t()}finally{o.mode==="Permanent"&&await A(e,o)}}},ho=(e,t)=>({acquire:o=>h(e,{...t,...o??{}}),tryAcquire:o=>B(e,{...t,...o??{}}),release:()=>A(e,t),withAcquire:async(o,n)=>{await h(e,{...t,...n??{}});try{return await o()}finally{await A(e,t)}}});import"pg";import ue from"pg";var le=e=>e instanceof ue.Pool,Fo=e=>e instanceof ue.Client,Fe=e=>"release"in e&&typeof e.release=="function",Uo=async(e,t)=>{let o=le(e)?await e.connect():e;try{return await t(o)}finally{le(e)&&Fe(o)&&o.release()}},L=()=>({type:u,query:k,batchQuery:k,command:k,batchCommand:k});async function k(e,t,o){let n=Array.isArray(t)?t:[t],r=Array(n.length);o?.timeoutMs&&await e.query(`SET statement_timeout = ${o?.timeoutMs}`);for(let i=0;i<n.length;i++){let s=await e.query(n[i]);S.info("db:sql:query",{sql:n[i]}),r[i]={rowCount:s.rowCount,rows:s.rows}}return Array.isArray(t)?r:r[0]}var _=e=>(t,o)=>({connection:e(),type:u,begin:async()=>{await(await t).query("BEGIN")},commit:async()=>{let n=await t;await n.query("COMMIT"),o?.close&&await o?.close(n)},rollback:async n=>{let r=await t;await r.query("ROLLBACK"),o?.close&&await o?.close(r,n)},execute:w(L(),{connect:()=>t})});var u="PostgreSQL:pg",Ue=e=>{let{connect:t,close:o}=e;return z({type:u,connect:t,close:o,initTransaction:n=>_(n),executor:L})},ve=e=>{let{connect:t,close:o}=e;return z({type:u,connect:t,close:o,initTransaction:n=>_(n),executor:L})};function x(e){return e.type==="Client"?Ue(e):ve(e)}import ge from"pg";import W from"pg";var pe=e=>{W.types.setTypeParser(20,t=>BigInt(t)),W.types.setTypeParser(3802,t=>e.deserialize(t)),W.types.setTypeParser(114,t=>e.deserialize(t))};var Be=e=>{let{connectionString:t,database:o}=e,n=je({connectionString:t,database:o}),r=()=>x({type:"PoolClient",connect:n.connect(),close:c=>Promise.resolve(c.release())});return R({type:u,connection:()=>Promise.resolve(r()),close:()=>Ye({connectionString:t,database:o}),getConnection:r})},_e=e=>{let{pool:t}=e;return R({type:u,getConnection:()=>x({type:"PoolClient",connect:t.connect(),close:o=>Promise.resolve(o.release())})})},We=e=>{let{connection:t}=e;return R({type:u,getConnection:()=>t,execute:t.execute,transaction:()=>t.transaction(),withTransaction:o=>t.withTransaction(o)})},Ge=e=>{let{connectionString:t,database:o}=e;return R({type:u,getConnection:()=>{let n=Promise.resolve(new ge.Client({connectionString:t,database:o})).then(async r=>(await r.connect(),r));return x({type:"Client",connect:n,close:r=>r.end()})}})},He=e=>{let{client:t}=e,o=()=>{let i=Promise.resolve(t);return x({type:"Client",connect:i,close:()=>Promise.resolve()})};return R({type:u,connection:()=>Promise.resolve(o()),close:()=>Promise.resolve(),getConnection:o})};function de(e){let{connectionString:t,database:o,serializer:n}=e;return pe(n??p),"client"in e&&e.client?He({client:e.client}):"connection"in e&&e.connection?We({connection:e.connection}):"pooled"in e&&e.pooled===!1?Ge({connectionString:t,database:o}):"pool"in e&&e.pool?_e({pool:e.pool}):Be({connectionString:t,database:o})}var b=new Map,ye=new Map,je=e=>{let t=typeof e=="string"?e:e.connectionString,o=typeof e=="string"?{connectionString:t}:e,n=o.database??(o.connectionString?v(o.connectionString):void 0),r=Ce(t,n);return Pe(r,1),b.get(r)??b.set(r,new ge.Pool(o)).get(r)},Ye=async({connectionString:e,database:t,force:o})=>{t=t??v(e);let n=Ce(e,t),r=b.get(n);r&&(Pe(n,-1)<=0||o===!0)&&await me(n,r)},me=async(e,t)=>{try{await t.end()}catch(o){console.log(`Error while closing the connection pool: ${e}`),console.log(o)}b.delete(e)},un=()=>Promise.all([...b.entries()].map(([e,t])=>me(e,t))),Ce=(e,t)=>`${e}|${t??Q}`,Pe=(e,t)=>{let o=ye.get(e)??0,n=o+t;return ye.set(e,o+t),n};var Re=de;var Ve=e=>Re(e),Tn=e=>Ve(e);export{ce as AdvisoryLock,G as JSONReplacer,j as JSONReplacers,H as JSONReviver,Y as JSONRevivers,p as JSONSerializer,a as LogLevel,F as MIGRATIONS_LOCK_ID,u as NodePostgresConnectorType,Ke as RawJSONSerializer,lt as SQL,h as acquireAdvisoryLock,ho as advisoryLock,se as combineMigrations,Oe as composeJSONReplacers,Le as composeJSONRevivers,Ve as connectionPool,ht as count,z as createConnection,R as createConnectionPool,U as defaultDatabaseLockOptions,Lo as defaultPostgreSQLConenctionString,Q as defaultPostgreSqlDatabase,Tn as dumbo,un as endAllPools,Ye as endPool,P as executeInNewConnection,E as executeInNewDbClient,we as executeInTransaction,J as exists,At as first,Qt as firstOrNull,go as functionExists,ze as functionExistsSQL,v as getDatabaseNameOrDefault,je as getPool,at as identifier,Fo as isNodePostgresClient,le as isNodePostgresNativePool,Fe as isNodePostgresPoolClient,it as isSQL,V as jsonSerializer,st as literal,wt as mapRows,oe as mapToCamelCase,qe as migrationTableSchemaComponent,He as nodePostgresAmbientClientPool,We as nodePostgresAmbientConnectionPool,_e as nodePostgresAmbientNativePool,Ue as nodePostgresClientConnection,Ge as nodePostgresClientPool,x as nodePostgresConnection,Uo as nodePostgresExecute,Be as nodePostgresNativePool,de as nodePostgresPool,ve as nodePostgresPoolClientConnection,L as nodePostgresSQLExecutor,_ as nodePostgresTransaction,me as onEndPool,ct as plainString,Re as postgresPool,f as rawSql,A as releaseAdvisoryLock,lo as runPostgreSQLMigrations,ie as runSQLMigrations,ae as schemaComponent,pe as setNodePostgresTypeParser,O as single,ne as singleOrNull,d as sql,w as sqlExecutor,Z as sqlExecutorInNewConnection,re as sqlMigration,yo as tableExists,Me as tableExistsSQL,De as toCamelCase,S as tracer,ee as transactionFactoryWithDbClient,te as transactionFactoryWithNewConnection,B as tryAcquireAdvisoryLock};
23
+ `,e),go=async(e,t)=>J(e.execute.query(ze(t)));var Lo="postgresql://postgres@localhost:5432/postgres",v=e=>Je.parse(e).database??Q;var B=async(e,t)=>{let o=t.timeoutMs??U.timeoutMs,n=t.mode==="Permanent"?"pg_advisory_lock":"pg_advisory_xact_lock";try{return await O(e.query(d("SELECT %s(%s) AS locked",n,t.lockId),{timeoutMs:o})),!0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="57014")return!1;throw r}},A=async(e,t)=>{let o=t.timeoutMs??U.timeoutMs;try{return await O(e.query(d("SELECT pg_advisory_unlock(%s) AS locked",t.lockId),{timeoutMs:o})),!0}catch(n){if(n instanceof Error&&"code"in n&&n.code==="57014")return!1;throw n}},h=async(e,t)=>{if(!await B(e,t))throw new Error("Failed to acquire advisory lock within the specified timeout. Migration aborted.")},ce={acquire:h,tryAcquire:B,release:A,withAcquire:async(e,t,o)=>{await h(e,o);try{return await t()}finally{o.mode==="Permanent"&&await A(e,o)}}},ho=(e,t)=>({acquire:o=>h(e,{...t,...o??{}}),tryAcquire:o=>B(e,{...t,...o??{}}),release:()=>A(e,t),withAcquire:async(o,n)=>{await h(e,{...t,...n??{}});try{return await o()}finally{await A(e,t)}}});import"pg";import ue from"pg";var le=e=>e instanceof ue.Pool,Fo=e=>e instanceof ue.Client,Fe=e=>"release"in e&&typeof e.release=="function",Uo=async(e,t)=>{let o=le(e)?await e.connect():e;try{return await t(o)}finally{le(e)&&Fe(o)&&o.release()}},L=()=>({type:u,query:k,batchQuery:k,command:k,batchCommand:k});async function k(e,t,o){let n=Array.isArray(t)?t:[t],r=Array(n.length);o?.timeoutMs&&await e.query(`SET statement_timeout = ${o?.timeoutMs}`);for(let i=0;i<n.length;i++){let s=await e.query(n[i]);S.info("db:sql:query",{sql:n[i]}),r[i]={rowCount:s.rowCount,rows:s.rows}}return Array.isArray(t)?r:r[0]}var _=e=>(t,o)=>({connection:e(),type:u,begin:async()=>{await(await t).query("BEGIN")},commit:async()=>{let n=await t;await n.query("COMMIT"),o?.close&&await o?.close(n)},rollback:async n=>{let r=await t;await r.query("ROLLBACK"),o?.close&&await o?.close(r,n)},execute:w(L(),{connect:()=>t})});var u="PostgreSQL:pg",Ue=e=>{let{connect:t,close:o}=e;return z({type:u,connect:t,close:o,initTransaction:n=>_(n),executor:L})},ve=e=>{let{connect:t,close:o}=e;return z({type:u,connect:t,close:o,initTransaction:n=>_(n),executor:L})};function x(e){return e.type==="Client"?Ue(e):ve(e)}import ge from"pg";import W from"pg";var pe=e=>{W.types.setTypeParser(20,t=>BigInt(t)),W.types.setTypeParser(3802,t=>e.deserialize(t)),W.types.setTypeParser(114,t=>e.deserialize(t))};var Be=e=>{let{connectionString:t,database:o}=e,n=je({connectionString:t,database:o}),r=()=>x({type:"PoolClient",connect:n.connect(),close:c=>Promise.resolve(c.release())});return R({type:u,connection:()=>Promise.resolve(r()),close:()=>Ye({connectionString:t,database:o}),getConnection:r})},_e=e=>{let{pool:t}=e;return R({type:u,getConnection:()=>x({type:"PoolClient",connect:t.connect(),close:o=>Promise.resolve(o.release())})})},We=e=>{let{connection:t}=e;return R({type:u,getConnection:()=>t,execute:t.execute,transaction:()=>t.transaction(),withTransaction:o=>t.withTransaction(o)})},Ge=e=>{let{connectionString:t,database:o}=e;return R({type:u,getConnection:()=>{let n=Promise.resolve(new ge.Client({connectionString:t,database:o})).then(async r=>(await r.connect(),r));return x({type:"Client",connect:n,close:r=>r.end()})}})},He=e=>{let{client:t}=e,o=()=>{let i=Promise.resolve(t);return x({type:"Client",connect:i,close:()=>Promise.resolve()})};return R({type:u,connection:()=>Promise.resolve(o()),close:()=>Promise.resolve(),getConnection:o})};function de(e){let{connectionString:t,database:o,serializer:n}=e;return pe(n??p),"client"in e&&e.client?He({client:e.client}):"connection"in e&&e.connection?We({connection:e.connection}):"pooled"in e&&e.pooled===!1?Ge({connectionString:t,database:o}):"pool"in e&&e.pool?_e({pool:e.pool}):Be({connectionString:t,database:o})}var N=new Map,ye=new Map,je=e=>{let t=typeof e=="string"?e:e.connectionString,o=typeof e=="string"?{connectionString:t}:e,n=o.database??(o.connectionString?v(o.connectionString):void 0),r=Ce(t,n);return Pe(r,1),N.get(r)??N.set(r,new ge.Pool(o)).get(r)},Ye=async({connectionString:e,database:t,force:o})=>{t=t??v(e);let n=Ce(e,t),r=N.get(n);r&&(Pe(n,-1)<=0||o===!0)&&await me(n,r)},me=async(e,t)=>{try{await t.end()}catch(o){console.log(`Error while closing the connection pool: ${e}`),console.log(o)}N.delete(e)},un=()=>Promise.all([...N.entries()].map(([e,t])=>me(e,t))),Ce=(e,t)=>`${e}|${t??Q}`,Pe=(e,t)=>{let o=ye.get(e)??0,n=o+t;return ye.set(e,o+t),n};var Re=de;var Ve=e=>Re(e),bn=e=>Ve(e);export{ce as AdvisoryLock,G as JSONReplacer,j as JSONReplacers,H as JSONReviver,Y as JSONRevivers,p as JSONSerializer,a as LogLevel,F as MIGRATIONS_LOCK_ID,u as NodePostgresConnectorType,Ke as RawJSONSerializer,lt as SQL,h as acquireAdvisoryLock,ho as advisoryLock,se as combineMigrations,Oe as composeJSONReplacers,Le as composeJSONRevivers,Ve as connectionPool,ht as count,z as createConnection,R as createConnectionPool,U as defaultDatabaseLockOptions,Lo as defaultPostgreSQLConenctionString,Q as defaultPostgreSqlDatabase,bn as dumbo,un as endAllPools,Ye as endPool,P as executeInNewConnection,E as executeInNewDbClient,we as executeInTransaction,J as exists,At as first,Qt as firstOrNull,go as functionExists,ze as functionExistsSQL,v as getDatabaseNameOrDefault,je as getPool,at as identifier,Fo as isNodePostgresClient,le as isNodePostgresNativePool,Fe as isNodePostgresPoolClient,it as isSQL,V as jsonSerializer,st as literal,wt as mapRows,oe as mapToCamelCase,qe as migrationTableSchemaComponent,He as nodePostgresAmbientClientPool,We as nodePostgresAmbientConnectionPool,_e as nodePostgresAmbientNativePool,Ue as nodePostgresClientConnection,Ge as nodePostgresClientPool,x as nodePostgresConnection,Uo as nodePostgresExecute,Be as nodePostgresNativePool,de as nodePostgresPool,ve as nodePostgresPoolClientConnection,L as nodePostgresSQLExecutor,_ as nodePostgresTransaction,me as onEndPool,ct as plainString,Re as postgresPool,f as rawSql,A as releaseAdvisoryLock,lo as runPostgreSQLMigrations,ie as runSQLMigrations,ae as schemaComponent,pe as setNodePostgresTypeParser,O as single,ne as singleOrNull,d as sql,w as sqlExecutor,Z as sqlExecutorInNewConnection,re as sqlMigration,yo as tableExists,Me as tableExistsSQL,De as toCamelCase,S as tracer,ee as transactionFactoryWithDbClient,te as transactionFactoryWithNewConnection,B as tryAcquireAdvisoryLock};
24
24
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@event-driven-io/dumbo",
3
- "version": "0.11.0-alpha.1",
3
+ "version": "0.11.0-alpha.2",
4
4
  "description": "Dumbo - tools for dealing with PostgreSQL",
5
5
  "type": "module",
6
6
  "scripts": {