@event-driven-io/dumbo 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +7 -8
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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 _pgconnectionstring = require('pg-connection-string'); var _pgconnectionstring2 = _interopRequireDefault(_pgconnectionstring);var
|
|
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 _pgconnectionstring = require('pg-connection-string'); var _pgconnectionstring2 = _interopRequireDefault(_pgconnectionstring);var j={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},h=j;var l={ident:"I",literal:"L",string:"s"},w=e=>(e=e.replace("T"," "),e=e.replace("Z","+00"),e),X=e=>!!h[e.toUpperCase()],I=(e,t,o)=>{let n="";n+=e?" (":"(";for(let r=0;r<t.length;r++)n+=(r===0?"":", ")+o(t[r]);return n+=")",n},b=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'"'+w(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 b(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)&&!X(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},R=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"'"+w(e.toISOString())+"'";if(e instanceof Buffer)return"E'\\\\x"+e.toString("hex")+"'";if(Array.isArray(e))return e.map((i,s)=>Array.isArray(i)?I(s!==0,i,R):R(i)).toString();e===Object(e)?(o="jsonb",t=JSON.stringify(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},x=e=>e==null?"":e===!1?"f":e===!0?"t":e instanceof Date?w(e.toISOString()):e instanceof Buffer?"\\x"+e.toString("hex"):Array.isArray(e)?e.map((t,o)=>t!=null?Array.isArray(t)?I(o!==0,t,x):x(t):"").filter(t=>t!=="").toString():e===Object(e)?JSON.stringify(e):e.toString().slice(0),V=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))},k=(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,P=s.split("$");if(P.length>1&&(c=parseInt(P[0],10)-1,s=P[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 b(n[c]);if(s===l.literal)return R(n[c]);if(s===l.string)return x(n[c])})},a=(e,...t)=>k(e,t);a.config=V;a.format=a;a.ident=b;a.literal=R;a.string=x;a.withArray=k;var F=a;var S=(e,...t)=>F(e,...t),xe= exports.rawSql =e=>e;var f=(e,t)=>({query:o=>T(n=>e.query(n,o),t),batchQuery:o=>T(n=>e.batchQuery(n,o),t),command:o=>T(n=>e.command(n,o),t),batchCommand:o=>T(n=>e.batchQuery(n,o),t)}),q= 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)}),T= 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 J=e=>e!=null&&typeof e=="object"&&"success"in e?e:{success:!0,result:e},z= exports.executeInTransaction =async(e,t)=>{await e.begin();try{let{success:o,result:n}=J(await t(e));return o?await e.commit():await e.rollback(),n}catch(o){throw await e.rollback(),o}},U= exports.transactionFactoryWithDbClient =(e,t)=>({transaction:()=>t(e()),withTransaction:o=>z(t(e()),o)}),L=async(e,t)=>{try{return await t()}finally{await e.close()}},M= exports.transactionFactoryWithNewConnection =e=>({transaction:()=>{let t=e(),o=t.transaction();return{...o,commit:()=>L(t,()=>o.commit()),rollback:()=>L(t,()=>o.rollback())}},withTransaction:t=>{let o=e();return L(o,()=>o.withTransaction(t))}});var Q=e=>{let{type:t,connect:o,close:n,initTransaction:r,executor:i}=e,s=null,c=async()=>await _asyncNullishCoalesce(s, async () => ((s=await o))),m={type:t,open:c,close:()=>s?n(s):Promise.resolve(),...U(c,r(()=>m)),execute:f(i(),{connect:c})};return m};var C=e=>{let{type:t,getConnection:o}=e,n="connection"in e?e.connection:()=>Promise.resolve(o()),r="withConnection"in e?e.withConnection:m=>p(m,{connection:n}),i="close"in e?e.close:()=>Promise.resolve(),s="execute"in e?e.execute:q({connection:n}),c="transaction"in e&&"withTransaction"in e?{transaction:e.transaction,withTransaction:e.withTransaction}:M(o);return{type:t,connection:n,withConnection:r,close:i,execute:s,...c}};var Me=async(e,t)=>(await e).rows.map(t),v= exports.toCamelCase =e=>e.replace(/_([a-z])/g,t=>_nullishCoalesce(_optionalChain([t, 'access', _2 => _2[1], 'optionalAccess', _3 => _3.toUpperCase, 'call', _4 => _4()]), () => (""))),We= exports.mapToCamelCase =e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[v(o)]=e[o]);return t};var Ye=async e=>{let t=await e;return t.rows.length>0?_nullishCoalesce(t.rows[0], () => (null)):null},Ge= 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]},_e= 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},ee= 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]},D= exports.exists =async e=>(await ee(e)).exists===!0;var N="postgres",te= exports.tableExistsSQL =e=>S(`
|
|
2
2
|
SELECT EXISTS (
|
|
3
3
|
SELECT FROM pg_tables
|
|
4
4
|
WHERE tablename = %L
|
|
5
|
-
) AS exists;`,e),
|
|
5
|
+
) AS exists;`,e),tt= exports.tableExists =async(e,t)=>D(e.execute.query(te(t))),oe= exports.functionExistsSQL =e=>S(`
|
|
6
6
|
SELECT EXISTS (
|
|
7
7
|
SELECT FROM pg_proc
|
|
8
8
|
WHERE
|
|
9
9
|
proname = %L
|
|
10
10
|
) AS exists;
|
|
11
|
-
`,e)
|
|
11
|
+
`,e),ot= exports.functionExists =async(e,t)=>D(e.execute.query(oe(t)));var O=e=>_nullishCoalesce(_pgconnectionstring2.default.parse(e).database, () => (N));var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var W=e=>e instanceof _pg2.default.Pool,Rt= exports.isNodePostgresClient =e=>e instanceof _pg2.default.Client,re= exports.isNodePostgresPoolClient =e=>"release"in e&&typeof e.release=="function",xt= exports.nodePostgresExecute =async(e,t)=>{let o=W(e)?await e.connect():e;try{return await t(o)}finally{W(e)&&re(o)&&o.release()}},g= exports.nodePostgresSQLExecutor =()=>({type:u,query:E,batchQuery:E,command:E,batchCommand:E});async function E(e,t){let o=Array.isArray(t)?t:[t],n=Array(o.length);for(let r=0;r<o.length;r++){let i=await e.query(o[r]);n[r]={rowCount:i.rowCount,rows:i.rows}}return Array.isArray(t)?n:n[0]}var A=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', _5 => _5.close])&&await _optionalChain([o, 'optionalAccess', _6 => _6.close, 'call', _7 => _7(n)])},rollback:async n=>{let r=await t;await r.query("ROLLBACK"),_optionalChain([o, 'optionalAccess', _8 => _8.close])&&await _optionalChain([o, 'optionalAccess', _9 => _9.close, 'call', _10 => _10(r,n)])},execute:f(g(),{connect:()=>t})});var u="PostgreSQL:pg",se= exports.nodePostgresClientConnection =e=>{let{connect:t,close:o}=e;return Q({type:u,connect:t,close:o,initTransaction:n=>A(n),executor:g})},ie= exports.nodePostgresPoolClientConnection =e=>{let{connect:t,close:o}=e;return Q({type:u,connect:t,close:o,initTransaction:n=>A(n),executor:g})};function y(e){return e.type==="Client"?se(e):ie(e)}var ce=e=>{let{connectionString:t,database:o}=e,n=Ce({connectionString:t,database:o}),r=()=>y({type:"PoolClient",connect:n.connect(),close:c=>Promise.resolve(c.release())});return C({type:u,connection:()=>Promise.resolve(r()),close:()=>Pe({connectionString:t,database:o}),getConnection:r})},le= exports.nodePostgresAmbientNativePool =e=>{let{pool:t}=e;return C({type:u,getConnection:()=>y({type:"PoolClient",connect:t.connect(),close:o=>Promise.resolve(o.release())})})},ue= exports.nodePostgresAmbientConnectionPool =e=>{let{connection:t}=e;return C({type:u,getConnection:()=>t,execute:t.execute,transaction:()=>t.transaction(),withTransaction:o=>t.withTransaction(o)})},ae= exports.nodePostgresClientPool =e=>{let{connectionString:t,database:o}=e;return C({type:u,getConnection:()=>{let n=Promise.resolve(new _pg2.default.Client({connectionString:t,database:o})).then(async r=>(await r.connect(),r));return y({type:"Client",connect:n,close:r=>r.end()})}})},pe= exports.nodePostgresAmbientClientPool =e=>{let{client:t}=e,o=()=>{let i=Promise.resolve(t);return y({type:"Client",connect:i,close:()=>Promise.resolve()})};return C({type:u,connection:()=>Promise.resolve(o()),close:()=>Promise.resolve(),getConnection:o})};function _(e){let{connectionString:t,database:o}=e;return"client"in e&&e.client?pe({client:e.client}):"connection"in e&&e.connection?ue({connection:e.connection}):"pooled"in e&&e.pooled===!1?ae({connectionString:t,database:o}):"pool"in e&&e.pool?le({pool:e.pool}):ce({connectionString:t,database:o})}var d=new Map,Y=new Map,Ce= exports.getPool =e=>{let t=typeof e=="string"?e:e.connectionString,o=typeof e=="string"?{connectionString:t}:e,n=_nullishCoalesce(o.database, () => ((o.connectionString?O(o.connectionString):void 0))),r=K(t,n);return Z(r,1),_nullishCoalesce(d.get(r), () => (d.set(r,new _pg2.default.Pool(o)).get(r)))},Pe= exports.endPool =async({connectionString:e,database:t,force:o})=>{t=_nullishCoalesce(t, () => (O(e)));let n=K(e,t),r=d.get(n);r&&(Z(n,-1)<=0||o===!0)&&await H(n,r)},H= exports.onEndPool =async(e,t)=>{try{await t.end()}catch(o){console.log(`Error while closing the connection pool: ${e}`),console.log(o)}d.delete(e)},Ut= exports.endAllPools =()=>Promise.all([...d.entries()].map(([e,t])=>H(e,t))),K=(e,t)=>`${e}|${_nullishCoalesce(t, () => (N))}`,Z=(e,t)=>{let o=_nullishCoalesce(Y.get(e), () => (0)),n=o+t;return Y.set(e,o+t),n};var $=_;var ge=e=>$(e),Jt= exports.dumbo =e=>ge(e);exports.NodePostgresConnectorType = u; exports.connectionPool = ge; exports.createConnection = Q; exports.createConnectionPool = C; exports.defaultPostgreSqlDatabase = N; exports.dumbo = Jt; exports.endAllPools = Ut; exports.endPool = Pe; exports.executeInNewConnection = p; exports.executeInNewDbClient = T; exports.executeInTransaction = z; exports.exists = D; exports.first = Ge; exports.firstOrNull = Ye; exports.functionExists = ot; exports.functionExistsSQL = oe; exports.getDatabaseNameOrDefault = O; exports.getPool = Ce; exports.isNodePostgresClient = Rt; exports.isNodePostgresNativePool = W; exports.isNodePostgresPoolClient = re; exports.mapRows = Me; exports.mapToCamelCase = We; exports.nodePostgresAmbientClientPool = pe; exports.nodePostgresAmbientConnectionPool = ue; exports.nodePostgresAmbientNativePool = le; exports.nodePostgresClientConnection = se; exports.nodePostgresClientPool = ae; exports.nodePostgresConnection = y; exports.nodePostgresExecute = xt; exports.nodePostgresNativePool = ce; exports.nodePostgresPool = _; exports.nodePostgresPoolClientConnection = ie; exports.nodePostgresSQLExecutor = g; exports.nodePostgresTransaction = A; exports.onEndPool = H; exports.postgresPool = $; exports.rawSql = xe; exports.single = ee; exports.singleOrNull = _e; exports.sql = S; exports.sqlExecutor = f; exports.sqlExecutorInNewConnection = q; exports.tableExists = tt; exports.tableExistsSQL = te; exports.toCamelCase = v; exports.transactionFactoryWithDbClient = U; exports.transactionFactoryWithNewConnection = M;
|
|
12
12
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/sql/index.ts","../src/core/execute/execute.ts","../src/core/connections/transaction.ts","../src/core/connections/connection.ts","../src/core/connections/pool.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"names":["pgcs","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","toTransactionResult","transactionResult","executeInTransaction","transaction","success","result","e","transactionFactoryWithDbClient","initTransaction","wrapInConnectionClosure","transactionFactoryWithNewConnection","createConnection","type","executor","getClient","typedConnection","createConnectionPool","pool","getConnection","withConnection","execute","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","tableExists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pg","isNodePostgresNativePool","poolOrClient","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","results","i","nodePostgresTransaction","nodePostgresClientConnection","nodePostgresPoolClientConnection","nodePostgresConnection","nodePostgresNativePool","database","getPool","endPool","nodePostgresAmbientNativePool","nodePostgresAmbientConnectionPool","nodePostgresClientPool","nodePostgresAmbientClientPool","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","lookupKey","updatePoolUsageCounter","force","onEndPool","endAllPools","by","currentCounter","newCounter","postgresPool","connectionPool","dumbo"],"mappings":"AAAA,OAAOA,MAAU,uBCAjB,OAAOC,MAAY,YAKZ,IAAMC,EAAM,CAACC,KAAqBC,IAChCH,EAAOE,EAAU,GAAGC,CAAM,EAGtBC,GAAUF,GACdA,ECoCF,IAAMG,EAAc,CAIzBA,EAEAC,KAIiB,CACjB,MAAQL,GACNM,EAAsBC,GAAWH,EAAY,MAAMG,EAAQP,CAAG,EAAGK,CAAO,EAC1E,WAAaG,GACXF,EACGC,GAAWH,EAAY,WAAWG,EAAQC,CAAI,EAC/CH,CACF,EACF,QAAUL,GACRM,EAAsBC,GAAWH,EAAY,QAAQG,EAAQP,CAAG,EAAGK,CAAO,EAC5E,aAAeG,GACbF,EACGC,GAAWH,EAAY,WAAWG,EAAQC,CAAI,EAC/CH,CACF,CACJ,GAEaI,EAEXJ,IAEkB,CAClB,MAAQL,GACNU,EACGC,GAAeA,EAAW,QAAQ,MAAMX,CAAG,EAC5CK,CACF,EACF,WAAaG,GACXE,EACGC,GAAeA,EAAW,QAAQ,WAAWH,CAAI,EAClDH,CACF,EACF,QAAUL,GACRU,EACGC,GAAeA,EAAW,QAAQ,QAAQX,CAAG,EAC9CK,CACF,EACF,aAAeG,GACbE,EACGC,GAAeA,EAAW,QAAQ,aAAaH,CAAI,EACpDH,CACF,CACJ,GAEaC,EAAuB,MAIlCM,EACAP,IAIoB,CACpB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V,GAAU,MAAO,CAC5B,iBAAApB,EACA,SAAAkB,EACA,MAAAc,CACF,IAIqB,CACnBd,EAAWA,GAAYnB,EAAyBC,CAAgB,EAChE,IAAM8B,EAAY5C,EAAIc,EAAkBkB,CAAQ,EAE1C7C,EAAOqD,EAAM,IAAII,CAAS,EAC5BzD,IAAS0D,EAAuBD,EAAW,EAAE,GAAK,GAAKE,IAAU,KACnE,MAAMC,EAAUH,EAAWzD,CAAI,CAEnC,EAEa4D,EAAY,MAAOH,EAAmBzD,IAAkB,CACnE,GAAI,CACF,MAAMA,EAAK,IAAI,CACjB,OAASlB,EAAO,CACd,QAAQ,IAAI,4CAA4C2E,CAAS,EAAE,EACnE,QAAQ,IAAI3E,CAAK,CACnB,CACAuE,EAAM,OAAOI,CAAS,CACxB,EAEaI,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGR,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACI,EAAWzD,CAAI,IAAM4D,EAAUH,EAAWzD,CAAI,CAAC,CAC5E,EAEIa,EAAM,CAACc,EAA0BkB,IACrC,GAAGlB,CAAgB,IAAIkB,GAAY1B,CAAyB,GAExDuC,EAAyB,CAACD,EAAmBK,IAAuB,CACxE,IAAMC,EAAiBT,EAAa,IAAIG,CAAS,GAAK,EAChDO,EAAaD,EAAiBD,EAEpC,OAAAR,EAAa,IAAIG,EAAWM,EAAiBD,CAAE,EAExCE,CACT,EClSO,IAAMC,EAAeb,ECKrB,IAAMc,GACX9F,GAGA6F,EAAa7F,CAAyC,EAE3C+F,GACX/F,GACU8F,GAAe9F,CAAO","sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import format from 'pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n connection: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n connection: () => Promise<ConnectionType>;\n },\n) => {\n const connection = await options.connection();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor {\n type: ConnectorType;\n connection: Connection<ConnectorType, DbClient>;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n transaction: () => DatabaseTransaction<ConnectorType, DbClient>;\n\n withTransaction: <Result = never>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n ) => Promise<Result>;\n}\n\nexport type TransactionResult<Result> = { success: boolean; result: Result };\n\nconst toTransactionResult = <Result>(\n transactionResult: TransactionResult<Result> | Result,\n): TransactionResult<Result> =>\n transactionResult !== undefined &&\n transactionResult !== null &&\n typeof transactionResult === 'object' &&\n 'success' in transactionResult\n ? transactionResult\n : { success: true, result: transactionResult };\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n DbClient = unknown,\n Result = void,\n>(\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = toTransactionResult(await handle(transaction));\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>,\n): DatabaseTransactionFactory<ConnectorType, DbClient> => ({\n transaction: () => initTransaction(connect()),\n withTransaction: (handle) =>\n executeInTransaction(initTransaction(connect()), handle),\n});\n\nconst wrapInConnectionClosure = async <\n ConnectionType extends Connection = Connection,\n Result = unknown,\n>(\n connection: ConnectionType,\n handle: () => Promise<Result>,\n) => {\n try {\n return await handle();\n } finally {\n await connection.close();\n }\n};\n\nexport const transactionFactoryWithNewConnection = <\n ConnectionType extends Connection = Connection,\n>(\n connect: () => ConnectionType,\n): DatabaseTransactionFactory<ConnectionType['type']> => ({\n transaction: () => {\n const connection = connect();\n const transaction = connection.transaction();\n\n return {\n ...transaction,\n commit: () =>\n wrapInConnectionClosure(connection, () => transaction.commit()),\n rollback: () =>\n wrapInConnectionClosure(connection, () => transaction.rollback()),\n };\n },\n withTransaction: (handle) => {\n const connection = connect();\n return wrapInConnectionClosure(connection, () =>\n connection.withTransaction(handle),\n );\n },\n});\n","import {\n sqlExecutor,\n type DbSQLExecutor,\n type WithSQLExecutor,\n} from '../execute';\nimport {\n transactionFactoryWithDbClient,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface Connection<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor,\n DatabaseTransactionFactory<ConnectorType> {\n type: ConnectorType;\n open: () => Promise<DbClient>;\n close: () => Promise<void>;\n}\n\nexport interface ConnectionFactory<\n ConnectionType extends Connection = Connection,\n> {\n connection: () => Promise<ConnectionType>;\n\n withConnection: <Result = unknown>(\n handle: (connection: ConnectionType) => Promise<Result>,\n ) => Promise<Result>;\n}\n\nexport type CreateConnectionOptions<\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n> = {\n type: ConnectorType;\n connect: Promise<DbClient>;\n close: (client: DbClient) => Promise<void>;\n initTransaction: (\n connection: () => ConnectionType,\n ) => (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>;\n executor: () => Executor;\n};\n\nexport const createConnection = <\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n>(\n options: CreateConnectionOptions<\n ConnectorType,\n DbClient,\n ConnectionType,\n Executor\n >,\n): ConnectionType => {\n const { type, connect, close, initTransaction, executor } = options;\n\n let client: DbClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n const connection: Connection<ConnectorType, DbClient> = {\n type: type,\n open: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(\n getClient,\n initTransaction(() => typedConnection),\n ),\n execute: sqlExecutor(executor(), { connect: getClient }),\n };\n\n const typedConnection = connection as ConnectionType;\n\n return typedConnection;\n};\n","import {\n executeInNewConnection,\n sqlExecutorInNewConnection,\n type WithSQLExecutor,\n} from '../execute';\nimport { type Connection, type ConnectionFactory } from './connection';\nimport {\n transactionFactoryWithNewConnection,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface ConnectionPool<ConnectionType extends Connection = Connection>\n extends WithSQLExecutor,\n ConnectionFactory<ConnectionType>,\n DatabaseTransactionFactory<ConnectionType['type']> {\n type: ConnectionType['type'];\n close: () => Promise<void>;\n}\n\nexport type ConnectionPoolFactory<\n ConnectionPoolType extends ConnectionPool = ConnectionPool,\n ConnectionPoolOptions = unknown,\n> = (options: ConnectionPoolOptions) => ConnectionPoolType;\n\nexport const createConnectionPool = <\n ConnectionType extends Connection,\n ConnectionPoolType extends ConnectionPool<ConnectionType>,\n>(\n pool: Pick<ConnectionPool<ConnectionType>, 'type'> &\n Partial<ConnectionPool<ConnectionType>> & {\n getConnection: () => ConnectionType;\n },\n): ConnectionPoolType => {\n const { type, getConnection } = pool;\n\n const connection =\n 'connection' in pool\n ? pool.connection\n : () => Promise.resolve(getConnection());\n\n const withConnection =\n 'withConnection' in pool\n ? pool.withConnection\n : <Result>(handle: (connection: ConnectionType) => Promise<Result>) =>\n executeInNewConnection<ConnectionType, Result>(handle, {\n connection,\n });\n\n const close = 'close' in pool ? pool.close : () => Promise.resolve();\n\n const execute =\n 'execute' in pool\n ? pool.execute\n : sqlExecutorInNewConnection({ connection });\n\n const transaction =\n 'transaction' in pool && 'withTransaction' in pool\n ? {\n transaction: pool.transaction,\n withTransaction: pool.withTransaction,\n }\n : transactionFactoryWithNewConnection(getConnection);\n\n const result: ConnectionPool<ConnectionType> = {\n type,\n connection,\n withConnection,\n close,\n execute,\n ...transaction,\n };\n\n return result as ConnectionPoolType;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport { createConnection, type Connection } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import {\n sqlExecutor,\n type Connection,\n type DatabaseTransaction,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction =\n <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(\n connection: () => Connection<NodePostgresConnector, DbClient>,\n ) =>\n (\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n ): DatabaseTransaction<NodePostgresConnector> => ({\n connection: connection(),\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), {\n connect: () => getClient,\n }),\n });\n","import pg from 'pg';\nimport { createConnectionPool, type ConnectionPool } from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresConnector,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresAmbientClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport type NodePostgresAmbientConnectionPool = ConnectionPool<\n NodePostgresPoolClientConnection | NodePostgresClientConnection\n>;\n\nexport type NodePostgresPool =\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresNativePool => {\n const { connectionString, database } = options;\n const pool = getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = () => endPool({ connectionString, database });\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport const nodePostgresAmbientNativePool = (options: {\n pool: pg.Pool;\n}): NodePostgresNativePool => {\n const { pool } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n }),\n });\n};\n\nexport const nodePostgresAmbientConnectionPool = (options: {\n connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;\n}): NodePostgresAmbientConnectionPool => {\n const { connection } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => connection,\n execute: connection.execute,\n transaction: () => connection.transaction(),\n withTransaction: (handle) => connection.withTransaction(handle),\n });\n};\n\nexport const nodePostgresClientPool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresAmbientClientPool => {\n const { connectionString, database } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => {\n const connect = Promise.resolve(\n new pg.Client({ connectionString, database }),\n ).then(async (client) => {\n await client.connect();\n return client;\n });\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => client.end(),\n });\n },\n });\n};\n\nexport const nodePostgresAmbientClientPool = (options: {\n client: pg.Client;\n}): NodePostgresAmbientClientPool => {\n const { client } = options;\n\n const getConnection = () => {\n const connect = Promise.resolve(client);\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: () => Promise.resolve(),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = () => Promise.resolve();\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n connection:\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n pooled?: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresAmbientClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n):\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool {\n const { connectionString, database } = options;\n\n if ('client' in options && options.client)\n return nodePostgresAmbientClientPool({ client: options.client });\n\n if ('pooled' in options && options.pooled === false)\n return nodePostgresClientPool({ connectionString, database });\n\n if ('connection' in options && options.connection)\n return nodePostgresAmbientConnectionPool({\n connection: options.connection,\n });\n\n if ('pool' in options && options.pool)\n return nodePostgresAmbientNativePool({ pool: options.pool });\n\n return nodePostgresNativePool({\n connectionString,\n database,\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnection,\n type NodePostgresConnector,\n type NodePostgresPool,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport type PostgresPool = NodePostgresPool;\nexport type PostgresConnection = NodePostgresConnection;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPool,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\n\nexport type PoolOptions = {\n connector?: ConnectorType;\n};\n\nexport type DumboOptions = PoolOptions & PostgresPoolOptions;\nexport type Dumbo = PostgresPool;\n\nexport const connectionPool = <PoolOptionsType extends DumboOptions>(\n options: PoolOptionsType,\n) =>\n // TODO: this should have the pattern matching and verification\n postgresPool(options as unknown as PostgresPoolOptions);\n\nexport const dumbo = <DumboOptionsType extends DumboOptions = DumboOptions>(\n options: DumboOptionsType,\n): Dumbo => connectionPool(options);\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/sql/pg-format/reserved.ts","../src/core/sql/pg-format/index.ts","../src/core/sql/index.ts","../src/core/execute/execute.ts","../src/core/connections/transaction.ts","../src/core/connections/connection.ts","../src/core/connections/pool.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts"],"names":["reservedMap","reserved_default","fmtPattern","formatDate","date","isReserved","value","arrayToList","useSpace","array","formatter","sql","i","quoteIdent","v","ident","quoted","c","quoteLiteral","literal","explicitCast","hasBackslash","quoteString","config","cfg","formatWithArray","fmt","parameters","index","params","re","_","type","position","tokens","format","args","pg_format_default","sqlQuery","rawSql","sqlExecutor","options","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","toTransactionResult","transactionResult","executeInTransaction","transaction","success","result","e","transactionFactoryWithDbClient","initTransaction","wrapInConnectionClosure","transactionFactoryWithNewConnection","createConnection","executor","getClient","typedConnection","createConnectionPool","pool","getConnection","withConnection","execute","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","tableExists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pgcs","isNodePostgresNativePool","poolOrClient","pg","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","results","nodePostgresTransaction","nodePostgresClientConnection","nodePostgresPoolClientConnection","nodePostgresConnection","nodePostgresNativePool","database","getPool","endPool","nodePostgresAmbientNativePool","nodePostgresAmbientConnectionPool","nodePostgresClientPool","nodePostgresAmbientClientPool","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","lookupKey","updatePoolU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S,CAAA,CAAA","file":"/home/runner/work/Pongo/Pongo/src/packages/dumbo/dist/index.cjs","sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","// Ported from: https://github.com/datalanche/node-pg-format/blob/master/lib/reserved.js\n//\n// PostgreSQL reserved words\n//\nconst reservedMap: { [key: string]: boolean } = {\n AES128: true,\n AES256: true,\n ALL: true,\n ALLOWOVERWRITE: true,\n ANALYSE: true,\n ANALYZE: true,\n AND: true,\n ANY: true,\n ARRAY: true,\n AS: true,\n ASC: true,\n AUTHORIZATION: true,\n BACKUP: true,\n BETWEEN: true,\n BINARY: true,\n BLANKSASNULL: true,\n BOTH: true,\n BYTEDICT: true,\n CASE: true,\n CAST: true,\n CHECK: true,\n COLLATE: true,\n COLUMN: true,\n CONSTRAINT: true,\n CREATE: true,\n CREDENTIALS: true,\n CROSS: true,\n CURRENT_DATE: true,\n CURRENT_TIME: true,\n CURRENT_TIMESTAMP: true,\n CURRENT_USER: true,\n CURRENT_USER_ID: true,\n DEFAULT: true,\n DEFERRABLE: true,\n DEFLATE: true,\n DEFRAG: true,\n DELTA: true,\n DELTA32K: true,\n DESC: true,\n DISABLE: true,\n DISTINCT: true,\n DO: true,\n ELSE: true,\n EMPTYASNULL: true,\n ENABLE: true,\n ENCODE: true,\n ENCRYPT: true,\n ENCRYPTION: true,\n END: true,\n EXCEPT: true,\n EXPLICIT: true,\n FALSE: true,\n FOR: true,\n FOREIGN: true,\n FREEZE: true,\n FROM: true,\n FULL: true,\n GLOBALDICT256: true,\n GLOBALDICT64K: true,\n GRANT: true,\n GROUP: true,\n GZIP: true,\n HAVING: true,\n IDENTITY: true,\n IGNORE: true,\n ILIKE: true,\n IN: true,\n INITIALLY: true,\n INNER: true,\n INTERSECT: true,\n INTO: true,\n IS: true,\n ISNULL: true,\n JOIN: true,\n LEADING: true,\n LEFT: true,\n LIKE: true,\n LIMIT: true,\n LOCALTIME: true,\n LOCALTIMESTAMP: true,\n LUN: true,\n LUNS: true,\n LZO: true,\n LZOP: true,\n MINUS: true,\n MOSTLY13: true,\n MOSTLY32: true,\n MOSTLY8: true,\n NATURAL: true,\n NEW: true,\n NOT: true,\n NOTNULL: true,\n NULL: true,\n NULLS: true,\n OFF: true,\n OFFLINE: true,\n OFFSET: true,\n OLD: true,\n ON: true,\n ONLY: true,\n OPEN: true,\n OR: true,\n ORDER: true,\n OUTER: true,\n OVERLAPS: true,\n PARALLEL: true,\n PARTITION: true,\n PERCENT: true,\n PLACING: true,\n PRIMARY: true,\n RAW: true,\n READRATIO: true,\n RECOVER: true,\n REFERENCES: true,\n REJECTLOG: true,\n RESORT: true,\n RESTORE: true,\n RIGHT: true,\n SELECT: true,\n SESSION_USER: true,\n SIMILAR: true,\n SOME: true,\n SYSDATE: true,\n SYSTEM: true,\n TABLE: true,\n TAG: true,\n TDES: true,\n TEXT255: true,\n TEXT32K: true,\n THEN: true,\n TO: true,\n TOP: true,\n TRAILING: true,\n TRUE: true,\n TRUNCATECOLUMNS: true,\n UNION: true,\n UNIQUE: true,\n USER: true,\n USING: true,\n VERBOSE: true,\n WALLET: true,\n WHEN: true,\n WHERE: true,\n WITH: true,\n WITHOUT: true,\n};\n\nexport default reservedMap;\n","// Ported from: https://github.com/datalanche/node-pg-format/blob/master/lib/index.js\nimport reservedMap from './reserved.js';\n\ntype FormatterConfig = {\n pattern?: {\n ident?: string;\n literal?: string;\n string?: string;\n };\n};\n\ntype FormatterFunction = (value: unknown) => string;\n\nconst fmtPattern = {\n ident: 'I',\n literal: 'L',\n string: 's',\n};\n\n// convert to Postgres default ISO 8601 format\nconst formatDate = (date: string): string => {\n date = date.replace('T', ' ');\n date = date.replace('Z', '+00');\n return date;\n};\n\nconst isReserved = (value: string): boolean => {\n return !!reservedMap[value.toUpperCase()];\n};\n\nconst arrayToList = (\n useSpace: boolean,\n array: unknown[],\n formatter: FormatterFunction,\n): string => {\n let sql = '';\n sql += useSpace ? ' (' : '(';\n for (let i = 0; i < array.length; i++) {\n sql += (i === 0 ? '' : ', ') + formatter(array[i]);\n }\n sql += ')';\n return sql;\n};\n\n// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c\nconst quoteIdent = (value: unknown): string => {\n if (value === undefined || value === null) {\n throw new Error('SQL identifier cannot be null or undefined');\n } else if (value === false) {\n return '\"f\"';\n } else if (value === true) {\n return '\"t\"';\n } else if (value instanceof Date) {\n return '\"' + formatDate(value.toISOString()) + '\"';\n } else if (value instanceof Buffer) {\n throw new Error('SQL identifier cannot be a buffer');\n } else if (Array.isArray(value)) {\n return value\n .map((v) => {\n if (Array.isArray(v)) {\n throw new Error(\n 'Nested array to grouped list conversion is not supported for SQL identifier',\n );\n }\n return quoteIdent(v);\n })\n .toString();\n } else if (value === Object(value)) {\n throw new Error('SQL identifier cannot be an object');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n const ident = value.toString().slice(0); // create copy\n\n // do not quote a valid, unquoted identifier\n if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident)) {\n return ident;\n }\n\n let quoted = '\"';\n for (let i = 0; i < ident.length; i++) {\n const c = ident[i];\n quoted += c === '\"' ? c + c : c;\n }\n quoted += '\"';\n return quoted;\n};\n\n// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c\nconst quoteLiteral = (value: unknown): string => {\n let literal: string | null = null;\n let explicitCast: string | null = null;\n\n if (value === undefined || value === null) {\n return 'NULL';\n } else if (value === false) {\n return \"'f'\";\n } else if (value === true) {\n return \"'t'\";\n } else if (value instanceof Date) {\n return \"'\" + formatDate(value.toISOString()) + \"'\";\n } else if (value instanceof Buffer) {\n return \"E'\\\\\\\\x\" + value.toString('hex') + \"'\";\n } else if (Array.isArray(value)) {\n return value\n .map((v, i) => {\n if (Array.isArray(v)) {\n return arrayToList(i !== 0, v, quoteLiteral);\n }\n return quoteLiteral(v);\n })\n .toString();\n } else if (value === Object(value)) {\n explicitCast = 'jsonb';\n literal = JSON.stringify(value);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n literal = value.toString().slice(0); // create copy\n }\n\n let hasBackslash = false;\n let quoted = \"'\";\n\n for (let i = 0; i < literal.length; i++) {\n const c = literal[i];\n if (c === \"'\") {\n quoted += c + c;\n } else if (c === '\\\\') {\n quoted += c + c;\n hasBackslash = true;\n } else {\n quoted += c;\n }\n }\n\n quoted += \"'\";\n\n if (hasBackslash) {\n quoted = 'E' + quoted;\n }\n\n if (explicitCast) {\n quoted += '::' + explicitCast;\n }\n\n return quoted;\n};\n\nconst quoteString = (value: unknown): string => {\n if (value === undefined || value === null) {\n return '';\n } else if (value === false) {\n return 'f';\n } else if (value === true) {\n return 't';\n } else if (value instanceof Date) {\n return formatDate(value.toISOString());\n } else if (value instanceof Buffer) {\n return '\\\\x' + value.toString('hex');\n } else if (Array.isArray(value)) {\n return value\n .map((v, i) => {\n if (v !== null && v !== undefined) {\n if (Array.isArray(v)) {\n return arrayToList(i !== 0, v, quoteString);\n }\n return quoteString(v);\n }\n return ''; // Handle undefined or null values properly within arrays\n })\n .filter((v) => v !== '') // Filter out empty strings to avoid extra commas\n .toString();\n } else if (value === Object(value)) {\n return JSON.stringify(value);\n }\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return value.toString().slice(0); // return copy\n};\n\nconst config = (cfg: FormatterConfig): void => {\n // default\n fmtPattern.ident = 'I';\n fmtPattern.literal = 'L';\n fmtPattern.string = 's';\n\n if (cfg && cfg.pattern) {\n if (cfg.pattern.ident) {\n fmtPattern.ident = cfg.pattern.ident;\n }\n if (cfg.pattern.literal) {\n fmtPattern.literal = cfg.pattern.literal;\n }\n if (cfg.pattern.string) {\n fmtPattern.string = cfg.pattern.string;\n }\n }\n};\n\nconst formatWithArray = (fmt: string, parameters: unknown[]): string => {\n let index = 0;\n const params = parameters;\n\n let re: string | RegExp = '%(%|(\\\\d+\\\\$)?[';\n re += fmtPattern.ident;\n re += fmtPattern.literal;\n re += fmtPattern.string;\n re += '])';\n re = new RegExp(re, 'g');\n\n return fmt.replace(re, (_, type) => {\n if (type === '%') {\n return '%';\n }\n\n let position = index;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access\n const tokens = type.split('$');\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (tokens.length > 1) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n position = parseInt(tokens[0], 10) - 1;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n type = tokens[1];\n }\n\n if (position < 0) {\n throw new Error('specified argument 0 but arguments start at 1');\n } else if (position > params.length - 1) {\n throw new Error('too few arguments');\n }\n\n index = position + 1;\n\n if (type === fmtPattern.ident) {\n return quoteIdent(params[position]);\n } else if (type === fmtPattern.literal) {\n return quoteLiteral(params[position]);\n } else if (type === fmtPattern.string) {\n return quoteString(params[position]);\n }\n\n return undefined!;\n });\n};\n\nconst format = (fmt: string, ...args: unknown[]): string => {\n return formatWithArray(fmt, args);\n};\n\nformat.config = config;\nformat.format = format;\nformat.ident = quoteIdent;\nformat.literal = quoteLiteral;\nformat.string = quoteString;\nformat.withArray = formatWithArray;\n\nexport default format;\n","import format from './pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n connection: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n connection: () => Promise<ConnectionType>;\n },\n) => {\n const connection = await options.connection();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor {\n type: ConnectorType;\n connection: Connection<ConnectorType, DbClient>;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n transaction: () => DatabaseTransaction<ConnectorType, DbClient>;\n\n withTransaction: <Result = never>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n ) => Promise<Result>;\n}\n\nexport type TransactionResult<Result> = { success: boolean; result: Result };\n\nconst toTransactionResult = <Result>(\n transactionResult: TransactionResult<Result> | Result,\n): TransactionResult<Result> =>\n transactionResult !== undefined &&\n transactionResult !== null &&\n typeof transactionResult === 'object' &&\n 'success' in transactionResult\n ? transactionResult\n : { success: true, result: transactionResult };\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n DbClient = unknown,\n Result = void,\n>(\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = toTransactionResult(await handle(transaction));\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>,\n): DatabaseTransactionFactory<ConnectorType, DbClient> => ({\n transaction: () => initTransaction(connect()),\n withTransaction: (handle) =>\n executeInTransaction(initTransaction(connect()), handle),\n});\n\nconst wrapInConnectionClosure = async <\n ConnectionType extends Connection = Connection,\n Result = unknown,\n>(\n connection: ConnectionType,\n handle: () => Promise<Result>,\n) => {\n try {\n return await handle();\n } finally {\n await connection.close();\n }\n};\n\nexport const transactionFactoryWithNewConnection = <\n ConnectionType extends Connection = Connection,\n>(\n connect: () => ConnectionType,\n): DatabaseTransactionFactory<ConnectionType['type']> => ({\n transaction: () => {\n const connection = connect();\n const transaction = connection.transaction();\n\n return {\n ...transaction,\n commit: () =>\n wrapInConnectionClosure(connection, () => transaction.commit()),\n rollback: () =>\n wrapInConnectionClosure(connection, () => transaction.rollback()),\n };\n },\n withTransaction: (handle) => {\n const connection = connect();\n return wrapInConnectionClosure(connection, () =>\n connection.withTransaction(handle),\n );\n },\n});\n","import {\n sqlExecutor,\n type DbSQLExecutor,\n type WithSQLExecutor,\n} from '../execute';\nimport {\n transactionFactoryWithDbClient,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface Connection<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor,\n DatabaseTransactionFactory<ConnectorType> {\n type: ConnectorType;\n open: () => Promise<DbClient>;\n close: () => Promise<void>;\n}\n\nexport interface ConnectionFactory<\n ConnectionType extends Connection = Connection,\n> {\n connection: () => Promise<ConnectionType>;\n\n withConnection: <Result = unknown>(\n handle: (connection: ConnectionType) => Promise<Result>,\n ) => Promise<Result>;\n}\n\nexport type CreateConnectionOptions<\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n> = {\n type: ConnectorType;\n connect: Promise<DbClient>;\n close: (client: DbClient) => Promise<void>;\n initTransaction: (\n connection: () => ConnectionType,\n ) => (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>;\n executor: () => Executor;\n};\n\nexport const createConnection = <\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n>(\n options: CreateConnectionOptions<\n ConnectorType,\n DbClient,\n ConnectionType,\n Executor\n >,\n): ConnectionType => {\n const { type, connect, close, initTransaction, executor } = options;\n\n let client: DbClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n const connection: Connection<ConnectorType, DbClient> = {\n type: type,\n open: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(\n getClient,\n initTransaction(() => typedConnection),\n ),\n execute: sqlExecutor(executor(), { connect: getClient }),\n };\n\n const typedConnection = connection as ConnectionType;\n\n return typedConnection;\n};\n","import {\n executeInNewConnection,\n sqlExecutorInNewConnection,\n type WithSQLExecutor,\n} from '../execute';\nimport { type Connection, type ConnectionFactory } from './connection';\nimport {\n transactionFactoryWithNewConnection,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface ConnectionPool<ConnectionType extends Connection = Connection>\n extends WithSQLExecutor,\n ConnectionFactory<ConnectionType>,\n DatabaseTransactionFactory<ConnectionType['type']> {\n type: ConnectionType['type'];\n close: () => Promise<void>;\n}\n\nexport type ConnectionPoolFactory<\n ConnectionPoolType extends ConnectionPool = ConnectionPool,\n ConnectionPoolOptions = unknown,\n> = (options: ConnectionPoolOptions) => ConnectionPoolType;\n\nexport const createConnectionPool = <\n ConnectionType extends Connection,\n ConnectionPoolType extends ConnectionPool<ConnectionType>,\n>(\n pool: Pick<ConnectionPool<ConnectionType>, 'type'> &\n Partial<ConnectionPool<ConnectionType>> & {\n getConnection: () => ConnectionType;\n },\n): ConnectionPoolType => {\n const { type, getConnection } = pool;\n\n const connection =\n 'connection' in pool\n ? pool.connection\n : () => Promise.resolve(getConnection());\n\n const withConnection =\n 'withConnection' in pool\n ? pool.withConnection\n : <Result>(handle: (connection: ConnectionType) => Promise<Result>) =>\n executeInNewConnection<ConnectionType, Result>(handle, {\n connection,\n });\n\n const close = 'close' in pool ? pool.close : () => Promise.resolve();\n\n const execute =\n 'execute' in pool\n ? pool.execute\n : sqlExecutorInNewConnection({ connection });\n\n const transaction =\n 'transaction' in pool && 'withTransaction' in pool\n ? {\n transaction: pool.transaction,\n withTransaction: pool.withTransaction,\n }\n : transactionFactoryWithNewConnection(getConnection);\n\n const result: ConnectionPool<ConnectionType> = {\n type,\n connection,\n withConnection,\n close,\n execute,\n ...transaction,\n };\n\n return result as ConnectionPoolType;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? (result.rows[0] ?? null) : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? (result.rows[0] ?? null) : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport { createConnection, type Connection } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import {\n sqlExecutor,\n type Connection,\n type DatabaseTransaction,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction =\n <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(\n connection: () => Connection<NodePostgresConnector, DbClient>,\n ) =>\n (\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n ): DatabaseTransaction<NodePostgresConnector> => ({\n connection: connection(),\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), {\n connect: () => getClient,\n }),\n });\n","import pg from 'pg';\nimport { createConnectionPool, type ConnectionPool } from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresConnector,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresAmbientClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport type NodePostgresAmbientConnectionPool = ConnectionPool<\n NodePostgresPoolClientConnection | NodePostgresClientConnection\n>;\n\nexport type NodePostgresPool =\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresNativePool => {\n const { connectionString, database } = options;\n const pool = getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = () => endPool({ connectionString, database });\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport const nodePostgresAmbientNativePool = (options: {\n pool: pg.Pool;\n}): NodePostgresNativePool => {\n const { pool } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n }),\n });\n};\n\nexport const nodePostgresAmbientConnectionPool = (options: {\n connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;\n}): NodePostgresAmbientConnectionPool => {\n const { connection } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => connection,\n execute: connection.execute,\n transaction: () => connection.transaction(),\n withTransaction: (handle) => connection.withTransaction(handle),\n });\n};\n\nexport const nodePostgresClientPool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresAmbientClientPool => {\n const { connectionString, database } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => {\n const connect = Promise.resolve(\n new pg.Client({ connectionString, database }),\n ).then(async (client) => {\n await client.connect();\n return client;\n });\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => client.end(),\n });\n },\n });\n};\n\nexport const nodePostgresAmbientClientPool = (options: {\n client: pg.Client;\n}): NodePostgresAmbientClientPool => {\n const { client } = options;\n\n const getConnection = () => {\n const connect = Promise.resolve(client);\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: () => Promise.resolve(),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = () => Promise.resolve();\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n connection:\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n pooled?: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresAmbientClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n):\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool {\n const { connectionString, database } = options;\n\n if ('client' in options && options.client)\n return nodePostgresAmbientClientPool({ client: options.client });\n\n if ('connection' in options && options.connection)\n return nodePostgresAmbientConnectionPool({\n connection: options.connection,\n });\n\n if ('pooled' in options && options.pooled === false)\n return nodePostgresClientPool({ connectionString, database });\n\n if ('pool' in options && options.pool)\n return nodePostgresAmbientNativePool({ pool: options.pool });\n\n return nodePostgresNativePool({\n connectionString,\n database,\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -45,18 +45,18 @@ interface SQLExecutor {
|
|
|
45
45
|
interface WithSQLExecutor {
|
|
46
46
|
execute: SQLExecutor;
|
|
47
47
|
}
|
|
48
|
-
declare const sqlExecutor: <DbClient = unknown, DbExecutor extends DbSQLExecutor
|
|
48
|
+
declare const sqlExecutor: <DbClient = unknown, DbExecutor extends DbSQLExecutor = DbSQLExecutor<string, unknown>>(sqlExecutor: DbExecutor, options: {
|
|
49
49
|
connect: () => Promise<DbClient>;
|
|
50
50
|
close?: (client: DbClient, error?: unknown) => Promise<void>;
|
|
51
51
|
}) => SQLExecutor;
|
|
52
|
-
declare const sqlExecutorInNewConnection: <ConnectionType extends Connection
|
|
52
|
+
declare const sqlExecutorInNewConnection: <ConnectionType extends Connection>(options: {
|
|
53
53
|
connection: () => Promise<ConnectionType>;
|
|
54
54
|
}) => SQLExecutor;
|
|
55
55
|
declare const executeInNewDbClient: <DbClient = unknown, Result = unknown>(handle: (client: DbClient) => Promise<Result>, options: {
|
|
56
56
|
connect: () => Promise<DbClient>;
|
|
57
57
|
close?: (client: DbClient, error?: unknown) => Promise<void>;
|
|
58
58
|
}) => Promise<Result>;
|
|
59
|
-
declare const executeInNewConnection: <ConnectionType extends Connection
|
|
59
|
+
declare const executeInNewConnection: <ConnectionType extends Connection, Result>(handle: (connection: ConnectionType) => Promise<Result>, options: {
|
|
60
60
|
connection: () => Promise<ConnectionType>;
|
|
61
61
|
}) => Promise<Result>;
|
|
62
62
|
|
|
@@ -77,7 +77,7 @@ type TransactionResult<Result> = {
|
|
|
77
77
|
};
|
|
78
78
|
declare const executeInTransaction: <ConnectorType extends string = string, DbClient = unknown, Result = void>(transaction: DatabaseTransaction<ConnectorType, DbClient>, handle: (transaction: DatabaseTransaction<ConnectorType, DbClient>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
|
|
79
79
|
declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType, DbClient>) => DatabaseTransactionFactory<ConnectorType, DbClient>;
|
|
80
|
-
declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection
|
|
80
|
+
declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType["type"]>;
|
|
81
81
|
|
|
82
82
|
interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
|
|
83
83
|
type: ConnectorType;
|
|
@@ -95,14 +95,14 @@ type CreateConnectionOptions<ConnectorType extends string = string, DbClient = u
|
|
|
95
95
|
initTransaction: (connection: () => ConnectionType) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType, DbClient>;
|
|
96
96
|
executor: () => Executor;
|
|
97
97
|
};
|
|
98
|
-
declare const createConnection: <ConnectorType extends string = string, DbClient = unknown, ConnectionType extends Connection<ConnectorType, DbClient> = Connection<ConnectorType, DbClient>, Executor extends DbSQLExecutor
|
|
98
|
+
declare const createConnection: <ConnectorType extends string = string, DbClient = unknown, ConnectionType extends Connection<ConnectorType, DbClient> = Connection<ConnectorType, DbClient>, Executor extends DbSQLExecutor = DbSQLExecutor<string, unknown>>(options: CreateConnectionOptions<ConnectorType, DbClient, ConnectionType, Executor>) => ConnectionType;
|
|
99
99
|
|
|
100
100
|
interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, ConnectionFactory<ConnectionType>, DatabaseTransactionFactory<ConnectionType['type']> {
|
|
101
101
|
type: ConnectionType['type'];
|
|
102
102
|
close: () => Promise<void>;
|
|
103
103
|
}
|
|
104
104
|
type ConnectionPoolFactory<ConnectionPoolType extends ConnectionPool = ConnectionPool, ConnectionPoolOptions = unknown> = (options: ConnectionPoolOptions) => ConnectionPoolType;
|
|
105
|
-
declare const createConnectionPool: <ConnectionType extends Connection
|
|
105
|
+
declare const createConnectionPool: <ConnectionType extends Connection, ConnectionPoolType extends ConnectionPool<ConnectionType>>(pool: Pick<ConnectionPool<ConnectionType>, "type"> & Partial<ConnectionPool<ConnectionType>> & {
|
|
106
106
|
getConnection: () => ConnectionType;
|
|
107
107
|
}) => ConnectionPoolType;
|
|
108
108
|
|
|
@@ -214,7 +214,7 @@ declare const endAllPools: () => Promise<void[]>;
|
|
|
214
214
|
type NodePostgresTransaction = DatabaseTransaction<NodePostgresConnector>;
|
|
215
215
|
declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(connection: () => Connection<NodePostgresConnector, DbClient>) => (getClient: Promise<DbClient>, options?: {
|
|
216
216
|
close: (client: DbClient, error?: unknown) => Promise<void>;
|
|
217
|
-
}
|
|
217
|
+
}) => DatabaseTransaction<NodePostgresConnector>;
|
|
218
218
|
|
|
219
219
|
declare const isNodePostgresNativePool: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Pool;
|
|
220
220
|
declare const isNodePostgresClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Client;
|
package/dist/index.d.ts
CHANGED
|
@@ -45,18 +45,18 @@ interface SQLExecutor {
|
|
|
45
45
|
interface WithSQLExecutor {
|
|
46
46
|
execute: SQLExecutor;
|
|
47
47
|
}
|
|
48
|
-
declare const sqlExecutor: <DbClient = unknown, DbExecutor extends DbSQLExecutor
|
|
48
|
+
declare const sqlExecutor: <DbClient = unknown, DbExecutor extends DbSQLExecutor = DbSQLExecutor<string, unknown>>(sqlExecutor: DbExecutor, options: {
|
|
49
49
|
connect: () => Promise<DbClient>;
|
|
50
50
|
close?: (client: DbClient, error?: unknown) => Promise<void>;
|
|
51
51
|
}) => SQLExecutor;
|
|
52
|
-
declare const sqlExecutorInNewConnection: <ConnectionType extends Connection
|
|
52
|
+
declare const sqlExecutorInNewConnection: <ConnectionType extends Connection>(options: {
|
|
53
53
|
connection: () => Promise<ConnectionType>;
|
|
54
54
|
}) => SQLExecutor;
|
|
55
55
|
declare const executeInNewDbClient: <DbClient = unknown, Result = unknown>(handle: (client: DbClient) => Promise<Result>, options: {
|
|
56
56
|
connect: () => Promise<DbClient>;
|
|
57
57
|
close?: (client: DbClient, error?: unknown) => Promise<void>;
|
|
58
58
|
}) => Promise<Result>;
|
|
59
|
-
declare const executeInNewConnection: <ConnectionType extends Connection
|
|
59
|
+
declare const executeInNewConnection: <ConnectionType extends Connection, Result>(handle: (connection: ConnectionType) => Promise<Result>, options: {
|
|
60
60
|
connection: () => Promise<ConnectionType>;
|
|
61
61
|
}) => Promise<Result>;
|
|
62
62
|
|
|
@@ -77,7 +77,7 @@ type TransactionResult<Result> = {
|
|
|
77
77
|
};
|
|
78
78
|
declare const executeInTransaction: <ConnectorType extends string = string, DbClient = unknown, Result = void>(transaction: DatabaseTransaction<ConnectorType, DbClient>, handle: (transaction: DatabaseTransaction<ConnectorType, DbClient>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
|
|
79
79
|
declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType, DbClient>) => DatabaseTransactionFactory<ConnectorType, DbClient>;
|
|
80
|
-
declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection
|
|
80
|
+
declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType["type"]>;
|
|
81
81
|
|
|
82
82
|
interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
|
|
83
83
|
type: ConnectorType;
|
|
@@ -95,14 +95,14 @@ type CreateConnectionOptions<ConnectorType extends string = string, DbClient = u
|
|
|
95
95
|
initTransaction: (connection: () => ConnectionType) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType, DbClient>;
|
|
96
96
|
executor: () => Executor;
|
|
97
97
|
};
|
|
98
|
-
declare const createConnection: <ConnectorType extends string = string, DbClient = unknown, ConnectionType extends Connection<ConnectorType, DbClient> = Connection<ConnectorType, DbClient>, Executor extends DbSQLExecutor
|
|
98
|
+
declare const createConnection: <ConnectorType extends string = string, DbClient = unknown, ConnectionType extends Connection<ConnectorType, DbClient> = Connection<ConnectorType, DbClient>, Executor extends DbSQLExecutor = DbSQLExecutor<string, unknown>>(options: CreateConnectionOptions<ConnectorType, DbClient, ConnectionType, Executor>) => ConnectionType;
|
|
99
99
|
|
|
100
100
|
interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, ConnectionFactory<ConnectionType>, DatabaseTransactionFactory<ConnectionType['type']> {
|
|
101
101
|
type: ConnectionType['type'];
|
|
102
102
|
close: () => Promise<void>;
|
|
103
103
|
}
|
|
104
104
|
type ConnectionPoolFactory<ConnectionPoolType extends ConnectionPool = ConnectionPool, ConnectionPoolOptions = unknown> = (options: ConnectionPoolOptions) => ConnectionPoolType;
|
|
105
|
-
declare const createConnectionPool: <ConnectionType extends Connection
|
|
105
|
+
declare const createConnectionPool: <ConnectionType extends Connection, ConnectionPoolType extends ConnectionPool<ConnectionType>>(pool: Pick<ConnectionPool<ConnectionType>, "type"> & Partial<ConnectionPool<ConnectionType>> & {
|
|
106
106
|
getConnection: () => ConnectionType;
|
|
107
107
|
}) => ConnectionPoolType;
|
|
108
108
|
|
|
@@ -214,7 +214,7 @@ declare const endAllPools: () => Promise<void[]>;
|
|
|
214
214
|
type NodePostgresTransaction = DatabaseTransaction<NodePostgresConnector>;
|
|
215
215
|
declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(connection: () => Connection<NodePostgresConnector, DbClient>) => (getClient: Promise<DbClient>, options?: {
|
|
216
216
|
close: (client: DbClient, error?: unknown) => Promise<void>;
|
|
217
|
-
}
|
|
217
|
+
}) => DatabaseTransaction<NodePostgresConnector>;
|
|
218
218
|
|
|
219
219
|
declare const isNodePostgresNativePool: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Pool;
|
|
220
220
|
declare const isNodePostgresClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Client;
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import
|
|
1
|
+
import ne from"pg-connection-string";var j={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},h=j;var l={ident:"I",literal:"L",string:"s"},w=e=>(e=e.replace("T"," "),e=e.replace("Z","+00"),e),X=e=>!!h[e.toUpperCase()],I=(e,t,o)=>{let n="";n+=e?" (":"(";for(let r=0;r<t.length;r++)n+=(r===0?"":", ")+o(t[r]);return n+=")",n},b=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'"'+w(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 b(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)&&!X(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},R=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"'"+w(e.toISOString())+"'";if(e instanceof Buffer)return"E'\\\\x"+e.toString("hex")+"'";if(Array.isArray(e))return e.map((i,s)=>Array.isArray(i)?I(s!==0,i,R):R(i)).toString();e===Object(e)?(o="jsonb",t=JSON.stringify(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},x=e=>e==null?"":e===!1?"f":e===!0?"t":e instanceof Date?w(e.toISOString()):e instanceof Buffer?"\\x"+e.toString("hex"):Array.isArray(e)?e.map((t,o)=>t!=null?Array.isArray(t)?I(o!==0,t,x):x(t):"").filter(t=>t!=="").toString():e===Object(e)?JSON.stringify(e):e.toString().slice(0),V=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))},k=(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,P=s.split("$");if(P.length>1&&(c=parseInt(P[0],10)-1,s=P[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 b(n[c]);if(s===l.literal)return R(n[c]);if(s===l.string)return x(n[c])})},a=(e,...t)=>k(e,t);a.config=V;a.format=a;a.ident=b;a.literal=R;a.string=x;a.withArray=k;var F=a;var S=(e,...t)=>F(e,...t),xe=e=>e;var f=(e,t)=>({query:o=>T(n=>e.query(n,o),t),batchQuery:o=>T(n=>e.batchQuery(n,o),t),command:o=>T(n=>e.command(n,o),t),batchCommand:o=>T(n=>e.batchQuery(n,o),t)}),q=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)}),T=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 J=e=>e!=null&&typeof e=="object"&&"success"in e?e:{success:!0,result:e},z=async(e,t)=>{await e.begin();try{let{success:o,result:n}=J(await t(e));return o?await e.commit():await e.rollback(),n}catch(o){throw await e.rollback(),o}},U=(e,t)=>({transaction:()=>t(e()),withTransaction:o=>z(t(e()),o)}),L=async(e,t)=>{try{return await t()}finally{await e.close()}},M=e=>({transaction:()=>{let t=e(),o=t.transaction();return{...o,commit:()=>L(t,()=>o.commit()),rollback:()=>L(t,()=>o.rollback())}},withTransaction:t=>{let o=e();return L(o,()=>o.withTransaction(t))}});var Q=e=>{let{type:t,connect:o,close:n,initTransaction:r,executor:i}=e,s=null,c=async()=>s??(s=await o),m={type:t,open:c,close:()=>s?n(s):Promise.resolve(),...U(c,r(()=>m)),execute:f(i(),{connect:c})};return m};var C=e=>{let{type:t,getConnection:o}=e,n="connection"in e?e.connection:()=>Promise.resolve(o()),r="withConnection"in e?e.withConnection:m=>p(m,{connection:n}),i="close"in e?e.close:()=>Promise.resolve(),s="execute"in e?e.execute:q({connection:n}),c="transaction"in e&&"withTransaction"in e?{transaction:e.transaction,withTransaction:e.withTransaction}:M(o);return{type:t,connection:n,withConnection:r,close:i,execute:s,...c}};var Me=async(e,t)=>(await e).rows.map(t),v=e=>e.replace(/_([a-z])/g,t=>t[1]?.toUpperCase()??""),We=e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[v(o)]=e[o]);return t};var Ye=async e=>{let t=await e;return t.rows.length>0?t.rows[0]??null:null},Ge=async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");return t.rows[0]},_e=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},ee=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]},D=async e=>(await ee(e)).exists===!0;var N="postgres",te=e=>S(`
|
|
2
2
|
SELECT EXISTS (
|
|
3
3
|
SELECT FROM pg_tables
|
|
4
4
|
WHERE tablename = %L
|
|
5
|
-
) AS exists;`,e),
|
|
5
|
+
) AS exists;`,e),tt=async(e,t)=>D(e.execute.query(te(t))),oe=e=>S(`
|
|
6
6
|
SELECT EXISTS (
|
|
7
7
|
SELECT FROM pg_proc
|
|
8
8
|
WHERE
|
|
9
9
|
proname = %L
|
|
10
10
|
) AS exists;
|
|
11
|
-
`,e)
|
|
11
|
+
`,e),ot=async(e,t)=>D(e.execute.query(oe(t)));var O=e=>ne.parse(e).database??N;import"pg";import B from"pg";var W=e=>e instanceof B.Pool,Rt=e=>e instanceof B.Client,re=e=>"release"in e&&typeof e.release=="function",xt=async(e,t)=>{let o=W(e)?await e.connect():e;try{return await t(o)}finally{W(e)&&re(o)&&o.release()}},g=()=>({type:u,query:E,batchQuery:E,command:E,batchCommand:E});async function E(e,t){let o=Array.isArray(t)?t:[t],n=Array(o.length);for(let r=0;r<o.length;r++){let i=await e.query(o[r]);n[r]={rowCount:i.rowCount,rows:i.rows}}return Array.isArray(t)?n:n[0]}var A=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:f(g(),{connect:()=>t})});var u="PostgreSQL:pg",se=e=>{let{connect:t,close:o}=e;return Q({type:u,connect:t,close:o,initTransaction:n=>A(n),executor:g})},ie=e=>{let{connect:t,close:o}=e;return Q({type:u,connect:t,close:o,initTransaction:n=>A(n),executor:g})};function y(e){return e.type==="Client"?se(e):ie(e)}import G from"pg";var ce=e=>{let{connectionString:t,database:o}=e,n=Ce({connectionString:t,database:o}),r=()=>y({type:"PoolClient",connect:n.connect(),close:c=>Promise.resolve(c.release())});return C({type:u,connection:()=>Promise.resolve(r()),close:()=>Pe({connectionString:t,database:o}),getConnection:r})},le=e=>{let{pool:t}=e;return C({type:u,getConnection:()=>y({type:"PoolClient",connect:t.connect(),close:o=>Promise.resolve(o.release())})})},ue=e=>{let{connection:t}=e;return C({type:u,getConnection:()=>t,execute:t.execute,transaction:()=>t.transaction(),withTransaction:o=>t.withTransaction(o)})},ae=e=>{let{connectionString:t,database:o}=e;return C({type:u,getConnection:()=>{let n=Promise.resolve(new G.Client({connectionString:t,database:o})).then(async r=>(await r.connect(),r));return y({type:"Client",connect:n,close:r=>r.end()})}})},pe=e=>{let{client:t}=e,o=()=>{let i=Promise.resolve(t);return y({type:"Client",connect:i,close:()=>Promise.resolve()})};return C({type:u,connection:()=>Promise.resolve(o()),close:()=>Promise.resolve(),getConnection:o})};function _(e){let{connectionString:t,database:o}=e;return"client"in e&&e.client?pe({client:e.client}):"connection"in e&&e.connection?ue({connection:e.connection}):"pooled"in e&&e.pooled===!1?ae({connectionString:t,database:o}):"pool"in e&&e.pool?le({pool:e.pool}):ce({connectionString:t,database:o})}var d=new Map,Y=new Map,Ce=e=>{let t=typeof e=="string"?e:e.connectionString,o=typeof e=="string"?{connectionString:t}:e,n=o.database??(o.connectionString?O(o.connectionString):void 0),r=K(t,n);return Z(r,1),d.get(r)??d.set(r,new G.Pool(o)).get(r)},Pe=async({connectionString:e,database:t,force:o})=>{t=t??O(e);let n=K(e,t),r=d.get(n);r&&(Z(n,-1)<=0||o===!0)&&await H(n,r)},H=async(e,t)=>{try{await t.end()}catch(o){console.log(`Error while closing the connection pool: ${e}`),console.log(o)}d.delete(e)},Ut=()=>Promise.all([...d.entries()].map(([e,t])=>H(e,t))),K=(e,t)=>`${e}|${t??N}`,Z=(e,t)=>{let o=Y.get(e)??0,n=o+t;return Y.set(e,o+t),n};var $=_;var ge=e=>$(e),Jt=e=>ge(e);export{u as NodePostgresConnectorType,ge as connectionPool,Q as createConnection,C as createConnectionPool,N as defaultPostgreSqlDatabase,Jt as dumbo,Ut as endAllPools,Pe as endPool,p as executeInNewConnection,T as executeInNewDbClient,z as executeInTransaction,D as exists,Ge as first,Ye as firstOrNull,ot as functionExists,oe as functionExistsSQL,O as getDatabaseNameOrDefault,Ce as getPool,Rt as isNodePostgresClient,W as isNodePostgresNativePool,re as isNodePostgresPoolClient,Me as mapRows,We as mapToCamelCase,pe as nodePostgresAmbientClientPool,ue as nodePostgresAmbientConnectionPool,le as nodePostgresAmbientNativePool,se as nodePostgresClientConnection,ae as nodePostgresClientPool,y as nodePostgresConnection,xt as nodePostgresExecute,ce as nodePostgresNativePool,_ as nodePostgresPool,ie as nodePostgresPoolClientConnection,g as nodePostgresSQLExecutor,A as nodePostgresTransaction,H as onEndPool,$ as postgresPool,xe as rawSql,ee as single,_e as singleOrNull,S as sql,f as sqlExecutor,q as sqlExecutorInNewConnection,tt as tableExists,te as tableExistsSQL,v as toCamelCase,U as transactionFactoryWithDbClient,M as transactionFactoryWithNewConnection};
|
|
12
12
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/sql/index.ts","../src/core/execute/execute.ts","../src/core/connections/transaction.ts","../src/core/connections/connection.ts","../src/core/connections/pool.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import format from 'pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n connection: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n connection: () => Promise<ConnectionType>;\n },\n) => {\n const connection = await options.connection();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor {\n type: ConnectorType;\n connection: Connection<ConnectorType, DbClient>;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n transaction: () => DatabaseTransaction<ConnectorType, DbClient>;\n\n withTransaction: <Result = never>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n ) => Promise<Result>;\n}\n\nexport type TransactionResult<Result> = { success: boolean; result: Result };\n\nconst toTransactionResult = <Result>(\n transactionResult: TransactionResult<Result> | Result,\n): TransactionResult<Result> =>\n transactionResult !== undefined &&\n transactionResult !== null &&\n typeof transactionResult === 'object' &&\n 'success' in transactionResult\n ? transactionResult\n : { success: true, result: transactionResult };\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n DbClient = unknown,\n Result = void,\n>(\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = toTransactionResult(await handle(transaction));\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>,\n): DatabaseTransactionFactory<ConnectorType, DbClient> => ({\n transaction: () => initTransaction(connect()),\n withTransaction: (handle) =>\n executeInTransaction(initTransaction(connect()), handle),\n});\n\nconst wrapInConnectionClosure = async <\n ConnectionType extends Connection = Connection,\n Result = unknown,\n>(\n connection: ConnectionType,\n handle: () => Promise<Result>,\n) => {\n try {\n return await handle();\n } finally {\n await connection.close();\n }\n};\n\nexport const transactionFactoryWithNewConnection = <\n ConnectionType extends Connection = Connection,\n>(\n connect: () => ConnectionType,\n): DatabaseTransactionFactory<ConnectionType['type']> => ({\n transaction: () => {\n const connection = connect();\n const transaction = connection.transaction();\n\n return {\n ...transaction,\n commit: () =>\n wrapInConnectionClosure(connection, () => transaction.commit()),\n rollback: () =>\n wrapInConnectionClosure(connection, () => transaction.rollback()),\n };\n },\n withTransaction: (handle) => {\n const connection = connect();\n return wrapInConnectionClosure(connection, () =>\n connection.withTransaction(handle),\n );\n },\n});\n","import {\n sqlExecutor,\n type DbSQLExecutor,\n type WithSQLExecutor,\n} from '../execute';\nimport {\n transactionFactoryWithDbClient,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface Connection<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor,\n DatabaseTransactionFactory<ConnectorType> {\n type: ConnectorType;\n open: () => Promise<DbClient>;\n close: () => Promise<void>;\n}\n\nexport interface ConnectionFactory<\n ConnectionType extends Connection = Connection,\n> {\n connection: () => Promise<ConnectionType>;\n\n withConnection: <Result = unknown>(\n handle: (connection: ConnectionType) => Promise<Result>,\n ) => Promise<Result>;\n}\n\nexport type CreateConnectionOptions<\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n> = {\n type: ConnectorType;\n connect: Promise<DbClient>;\n close: (client: DbClient) => Promise<void>;\n initTransaction: (\n connection: () => ConnectionType,\n ) => (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>;\n executor: () => Executor;\n};\n\nexport const createConnection = <\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n>(\n options: CreateConnectionOptions<\n ConnectorType,\n DbClient,\n ConnectionType,\n Executor\n >,\n): ConnectionType => {\n const { type, connect, close, initTransaction, executor } = options;\n\n let client: DbClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n const connection: Connection<ConnectorType, DbClient> = {\n type: type,\n open: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(\n getClient,\n initTransaction(() => typedConnection),\n ),\n execute: sqlExecutor(executor(), { connect: getClient }),\n };\n\n const typedConnection = connection as ConnectionType;\n\n return typedConnection;\n};\n","import {\n executeInNewConnection,\n sqlExecutorInNewConnection,\n type WithSQLExecutor,\n} from '../execute';\nimport { type Connection, type ConnectionFactory } from './connection';\nimport {\n transactionFactoryWithNewConnection,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface ConnectionPool<ConnectionType extends Connection = Connection>\n extends WithSQLExecutor,\n ConnectionFactory<ConnectionType>,\n DatabaseTransactionFactory<ConnectionType['type']> {\n type: ConnectionType['type'];\n close: () => Promise<void>;\n}\n\nexport type ConnectionPoolFactory<\n ConnectionPoolType extends ConnectionPool = ConnectionPool,\n ConnectionPoolOptions = unknown,\n> = (options: ConnectionPoolOptions) => ConnectionPoolType;\n\nexport const createConnectionPool = <\n ConnectionType extends Connection,\n ConnectionPoolType extends ConnectionPool<ConnectionType>,\n>(\n pool: Pick<ConnectionPool<ConnectionType>, 'type'> &\n Partial<ConnectionPool<ConnectionType>> & {\n getConnection: () => ConnectionType;\n },\n): ConnectionPoolType => {\n const { type, getConnection } = pool;\n\n const connection =\n 'connection' in pool\n ? pool.connection\n : () => Promise.resolve(getConnection());\n\n const withConnection =\n 'withConnection' in pool\n ? pool.withConnection\n : <Result>(handle: (connection: ConnectionType) => Promise<Result>) =>\n executeInNewConnection<ConnectionType, Result>(handle, {\n connection,\n });\n\n const close = 'close' in pool ? pool.close : () => Promise.resolve();\n\n const execute =\n 'execute' in pool\n ? pool.execute\n : sqlExecutorInNewConnection({ connection });\n\n const transaction =\n 'transaction' in pool && 'withTransaction' in pool\n ? {\n transaction: pool.transaction,\n withTransaction: pool.withTransaction,\n }\n : transactionFactoryWithNewConnection(getConnection);\n\n const result: ConnectionPool<ConnectionType> = {\n type,\n connection,\n withConnection,\n close,\n execute,\n ...transaction,\n };\n\n return result as ConnectionPoolType;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport { createConnection, type Connection } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import {\n sqlExecutor,\n type Connection,\n type DatabaseTransaction,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction =\n <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(\n connection: () => Connection<NodePostgresConnector, DbClient>,\n ) =>\n (\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n ): DatabaseTransaction<NodePostgresConnector> => ({\n connection: connection(),\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), {\n connect: () => getClient,\n }),\n });\n","import pg from 'pg';\nimport { createConnectionPool, type ConnectionPool } from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresConnector,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresAmbientClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport type NodePostgresAmbientConnectionPool = ConnectionPool<\n NodePostgresPoolClientConnection | NodePostgresClientConnection\n>;\n\nexport type NodePostgresPool =\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresNativePool => {\n const { connectionString, database } = options;\n const pool = getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = () => endPool({ connectionString, database });\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport const nodePostgresAmbientNativePool = (options: {\n pool: pg.Pool;\n}): NodePostgresNativePool => {\n const { pool } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n }),\n });\n};\n\nexport const nodePostgresAmbientConnectionPool = (options: {\n connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;\n}): NodePostgresAmbientConnectionPool => {\n const { connection } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => connection,\n execute: connection.execute,\n transaction: () => connection.transaction(),\n withTransaction: (handle) => connection.withTransaction(handle),\n });\n};\n\nexport const nodePostgresClientPool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresAmbientClientPool => {\n const { connectionString, database } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => {\n const connect = Promise.resolve(\n new pg.Client({ connectionString, database }),\n ).then(async (client) => {\n await client.connect();\n return client;\n });\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => client.end(),\n });\n },\n });\n};\n\nexport const nodePostgresAmbientClientPool = (options: {\n client: pg.Client;\n}): NodePostgresAmbientClientPool => {\n const { client } = options;\n\n const getConnection = () => {\n const connect = Promise.resolve(client);\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: () => Promise.resolve(),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = () => Promise.resolve();\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n connection:\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n pooled?: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresAmbientClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n):\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool {\n const { connectionString, database } = options;\n\n if ('client' in options && options.client)\n return nodePostgresAmbientClientPool({ client: options.client });\n\n if ('pooled' in options && options.pooled === false)\n return nodePostgresClientPool({ connectionString, database });\n\n if ('connection' in options && options.connection)\n return nodePostgresAmbientConnectionPool({\n connection: options.connection,\n });\n\n if ('pool' in options && options.pool)\n return nodePostgresAmbientNativePool({ pool: options.pool });\n\n return nodePostgresNativePool({\n connectionString,\n database,\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnection,\n type NodePostgresConnector,\n type NodePostgresPool,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport type PostgresPool = NodePostgresPool;\nexport type PostgresConnection = NodePostgresConnection;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPool,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\n\nexport type PoolOptions = {\n connector?: ConnectorType;\n};\n\nexport type DumboOptions = PoolOptions & PostgresPoolOptions;\nexport type Dumbo = PostgresPool;\n\nexport const connectionPool = <PoolOptionsType extends DumboOptions>(\n options: PoolOptionsType,\n) =>\n // TODO: this should have the pattern matching and verification\n postgresPool(options as unknown as PostgresPoolOptions);\n\nexport const dumbo = <DumboOptionsType extends DumboOptions = DumboOptions>(\n options: DumboOptionsType,\n): Dumbo => connectionPool(options);\n"],"mappings":"AAAA,OAAOA,MAAU,uBCAjB,OAAOC,MAAY,YAKZ,IAAMC,EAAM,CAACC,KAAqBC,IAChCH,EAAOE,EAAU,GAAGC,CAAM,EAGtBC,GAAUF,GACdA,ECoCF,IAAMG,EAAc,CAIzBA,EAEAC,KAIiB,CACjB,MAAQC,GACNC,EAAsBC,GAAWJ,EAAY,MAAMI,EAAQF,CAAG,EAAGD,CAAO,EAC1E,WAAaI,GACXF,EACGC,GAAWJ,EAAY,WAAWI,EAAQC,CAAI,EAC/CJ,CACF,EACF,QAAUC,GACRC,EAAsBC,GAAWJ,EAAY,QAAQI,EAAQF,CAAG,EAAGD,CAAO,EAC5E,aAAeI,GACbF,EACGC,GAAWJ,EAAY,WAAWI,EAAQC,CAAI,EAC/CJ,CACF,CACJ,GAEaK,EAEXL,IAEkB,CAClB,MAAQC,GACNK,EACGC,GAAeA,EAAW,QAAQ,MAAMN,CAAG,EAC5CD,CACF,EACF,WAAaI,GACXE,EACGC,GAAeA,EAAW,QAAQ,WAAWH,CAAI,EAClDJ,CACF,EACF,QAAUC,GACRK,EACGC,GAAeA,EAAW,QAAQ,QAAQN,CAAG,EAC9CD,CACF,EACF,aAAeI,GACbE,EACGC,GAAeA,EAAW,QAAQ,aAAaH,CAAI,EACpDJ,CACF,CACJ,GAEaE,EAAuB,MAIlCM,EACAR,I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,EAC5BtB,IAASwB,EAAuBF,EAAW,EAAE,GAAK,GAAKG,IAAU,KACnE,MAAMC,EAAUJ,EAAWtB,CAAI,CAEnC,EAEa0B,EAAY,MAAOJ,EAAmBtB,IAAkB,CACnE,GAAI,CACF,MAAMA,EAAK,IAAI,CACjB,OAAS2B,EAAO,CACd,QAAQ,IAAI,4CAA4CL,CAAS,EAAE,EACnE,QAAQ,IAAIK,CAAK,CACnB,CACAV,EAAM,OAAOK,CAAS,CACxB,EAEaM,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGX,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACK,EAAWtB,CAAI,IAAM0B,EAAUJ,EAAWtB,CAAI,CAAC,CAC5E,EAEIuB,EAAM,CAACzB,EAA0BC,IACrC,GAAGD,CAAgB,IAAIC,GAAY8B,CAAyB,GAExDL,EAAyB,CAACF,EAAmBQ,IAAuB,CACxE,IAAMC,EAAiBb,EAAa,IAAII,CAAS,GAAK,EAChDU,EAAaD,EAAiBD,EAEpC,OAAAZ,EAAa,IAAII,EAAWS,EAAiBD,CAAE,EAExCE,CACT,EClSO,IAAMC,EAAeC,ECKrB,IAAMC,GACXC,GAGAC,EAAaD,CAAyC,EAE3CE,GACXF,GACUD,GAAeC,CAAO","names":["pgcs","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","sql","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","toTransactionResult","transactionResult","executeInTransaction","transaction","handle","success","result","e","transactionFactoryWithDbClient","connect","initTransaction","wrapInConnectionClosure","connection","transactionFactoryWithNewConnection","createConnection","options","type","connect","close","initTransaction","executor","client","getClient","typedConnection","transactionFactoryWithDbClient","sqlExecutor","createConnectionPool","pool","type","getConnection","connection","withConnection","handle","executeInNewConnection","close","execute","sqlExecutorInNewConnection","transaction","transactionFactoryWithNewConnection","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","getResult","result","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","sql","tableExists","pool","exists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pgcs","defaultPostgreSqlDatabase","pg","isNodePostgresNativePool","poolOrClient","pg","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","handle","client","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","sqls","results","i","result","nodePostgresTransaction","connection","getClient","options","NodePostgresConnectorType","client","error","sqlExecutor","nodePostgresSQLExecutor","NodePostgresConnectorType","nodePostgresClientConnection","options","connect","close","createConnection","connection","nodePostgresTransaction","nodePostgresSQLExecutor","nodePostgresPoolClientConnection","nodePostgresConnection","pg","nodePostgresNativePool","options","connectionString","database","pool","getPool","getConnection","nodePostgresConnection","client","createConnectionPool","NodePostgresConnectorType","endPool","nodePostgresAmbientNativePool","nodePostgresAmbientConnectionPool","connection","handle","nodePostgresClientPool","connect","pg","nodePostgresAmbientClientPool","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","getDatabaseNameOrDefault","lookupKey","key","updatePoolUsageCounter","force","onEndPool","error","endAllPools","defaultPostgreSqlDatabase","by","currentCounter","newCounter","postgresPool","nodePostgresPool","connectionPool","options","postgresPool","dumbo"]}
|
|
1
|
+
{"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/sql/pg-format/reserved.ts","../src/core/sql/pg-format/index.ts","../src/core/sql/index.ts","../src/core/execute/execute.ts","../src/core/connections/transaction.ts","../src/core/connections/connection.ts","../src/core/connections/pool.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","// Ported from: https://github.com/datalanche/node-pg-format/blob/master/lib/reserved.js\n//\n// PostgreSQL reserved words\n//\nconst reservedMap: { [key: string]: boolean } = {\n AES128: true,\n AES256: true,\n ALL: true,\n ALLOWOVERWRITE: true,\n ANALYSE: true,\n ANALYZE: true,\n AND: true,\n ANY: true,\n ARRAY: true,\n AS: true,\n ASC: true,\n AUTHORIZATION: true,\n BACKUP: true,\n BETWEEN: true,\n BINARY: true,\n BLANKSASNULL: true,\n BOTH: true,\n BYTEDICT: true,\n CASE: true,\n CAST: true,\n CHECK: true,\n COLLATE: true,\n COLUMN: true,\n CONSTRAINT: true,\n CREATE: true,\n CREDENTIALS: true,\n CROSS: true,\n CURRENT_DATE: true,\n CURRENT_TIME: true,\n CURRENT_TIMESTAMP: true,\n CURRENT_USER: true,\n CURRENT_USER_ID: true,\n DEFAULT: true,\n DEFERRABLE: true,\n DEFLATE: true,\n DEFRAG: true,\n DELTA: true,\n DELTA32K: true,\n DESC: true,\n DISABLE: true,\n DISTINCT: true,\n DO: true,\n ELSE: true,\n EMPTYASNULL: true,\n ENABLE: true,\n ENCODE: true,\n ENCRYPT: true,\n ENCRYPTION: true,\n END: true,\n EXCEPT: true,\n EXPLICIT: true,\n FALSE: true,\n FOR: true,\n FOREIGN: true,\n FREEZE: true,\n FROM: true,\n FULL: true,\n GLOBALDICT256: true,\n GLOBALDICT64K: true,\n GRANT: true,\n GROUP: true,\n GZIP: true,\n HAVING: true,\n IDENTITY: true,\n IGNORE: true,\n ILIKE: true,\n IN: true,\n INITIALLY: true,\n INNER: true,\n INTERSECT: true,\n INTO: true,\n IS: true,\n ISNULL: true,\n JOIN: true,\n LEADING: true,\n LEFT: true,\n LIKE: true,\n LIMIT: true,\n LOCALTIME: true,\n LOCALTIMESTAMP: true,\n LUN: true,\n LUNS: true,\n LZO: true,\n LZOP: true,\n MINUS: true,\n MOSTLY13: true,\n MOSTLY32: true,\n MOSTLY8: true,\n NATURAL: true,\n NEW: true,\n NOT: true,\n NOTNULL: true,\n NULL: true,\n NULLS: true,\n OFF: true,\n OFFLINE: true,\n OFFSET: true,\n OLD: true,\n ON: true,\n ONLY: true,\n OPEN: true,\n OR: true,\n ORDER: true,\n OUTER: true,\n OVERLAPS: true,\n PARALLEL: true,\n PARTITION: true,\n PERCENT: true,\n PLACING: true,\n PRIMARY: true,\n RAW: true,\n READRATIO: true,\n RECOVER: true,\n REFERENCES: true,\n REJECTLOG: true,\n RESORT: true,\n RESTORE: true,\n RIGHT: true,\n SELECT: true,\n SESSION_USER: true,\n SIMILAR: true,\n SOME: true,\n SYSDATE: true,\n SYSTEM: true,\n TABLE: true,\n TAG: true,\n TDES: true,\n TEXT255: true,\n TEXT32K: true,\n THEN: true,\n TO: true,\n TOP: true,\n TRAILING: true,\n TRUE: true,\n TRUNCATECOLUMNS: true,\n UNION: true,\n UNIQUE: true,\n USER: true,\n USING: true,\n VERBOSE: true,\n WALLET: true,\n WHEN: true,\n WHERE: true,\n WITH: true,\n WITHOUT: true,\n};\n\nexport default reservedMap;\n","// Ported from: https://github.com/datalanche/node-pg-format/blob/master/lib/index.js\nimport reservedMap from './reserved.js';\n\ntype FormatterConfig = {\n pattern?: {\n ident?: string;\n literal?: string;\n string?: string;\n };\n};\n\ntype FormatterFunction = (value: unknown) => string;\n\nconst fmtPattern = {\n ident: 'I',\n literal: 'L',\n string: 's',\n};\n\n// convert to Postgres default ISO 8601 format\nconst formatDate = (date: string): string => {\n date = date.replace('T', ' ');\n date = date.replace('Z', '+00');\n return date;\n};\n\nconst isReserved = (value: string): boolean => {\n return !!reservedMap[value.toUpperCase()];\n};\n\nconst arrayToList = (\n useSpace: boolean,\n array: unknown[],\n formatter: FormatterFunction,\n): string => {\n let sql = '';\n sql += useSpace ? ' (' : '(';\n for (let i = 0; i < array.length; i++) {\n sql += (i === 0 ? '' : ', ') + formatter(array[i]);\n }\n sql += ')';\n return sql;\n};\n\n// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c\nconst quoteIdent = (value: unknown): string => {\n if (value === undefined || value === null) {\n throw new Error('SQL identifier cannot be null or undefined');\n } else if (value === false) {\n return '\"f\"';\n } else if (value === true) {\n return '\"t\"';\n } else if (value instanceof Date) {\n return '\"' + formatDate(value.toISOString()) + '\"';\n } else if (value instanceof Buffer) {\n throw new Error('SQL identifier cannot be a buffer');\n } else if (Array.isArray(value)) {\n return value\n .map((v) => {\n if (Array.isArray(v)) {\n throw new Error(\n 'Nested array to grouped list conversion is not supported for SQL identifier',\n );\n }\n return quoteIdent(v);\n })\n .toString();\n } else if (value === Object(value)) {\n throw new Error('SQL identifier cannot be an object');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n const ident = value.toString().slice(0); // create copy\n\n // do not quote a valid, unquoted identifier\n if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident)) {\n return ident;\n }\n\n let quoted = '\"';\n for (let i = 0; i < ident.length; i++) {\n const c = ident[i];\n quoted += c === '\"' ? c + c : c;\n }\n quoted += '\"';\n return quoted;\n};\n\n// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c\nconst quoteLiteral = (value: unknown): string => {\n let literal: string | null = null;\n let explicitCast: string | null = null;\n\n if (value === undefined || value === null) {\n return 'NULL';\n } else if (value === false) {\n return \"'f'\";\n } else if (value === true) {\n return \"'t'\";\n } else if (value instanceof Date) {\n return \"'\" + formatDate(value.toISOString()) + \"'\";\n } else if (value instanceof Buffer) {\n return \"E'\\\\\\\\x\" + value.toString('hex') + \"'\";\n } else if (Array.isArray(value)) {\n return value\n .map((v, i) => {\n if (Array.isArray(v)) {\n return arrayToList(i !== 0, v, quoteLiteral);\n }\n return quoteLiteral(v);\n })\n .toString();\n } else if (value === Object(value)) {\n explicitCast = 'jsonb';\n literal = JSON.stringify(value);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n literal = value.toString().slice(0); // create copy\n }\n\n let hasBackslash = false;\n let quoted = \"'\";\n\n for (let i = 0; i < literal.length; i++) {\n const c = literal[i];\n if (c === \"'\") {\n quoted += c + c;\n } else if (c === '\\\\') {\n quoted += c + c;\n hasBackslash = true;\n } else {\n quoted += c;\n }\n }\n\n quoted += \"'\";\n\n if (hasBackslash) {\n quoted = 'E' + quoted;\n }\n\n if (explicitCast) {\n quoted += '::' + explicitCast;\n }\n\n return quoted;\n};\n\nconst quoteString = (value: unknown): string => {\n if (value === undefined || value === null) {\n return '';\n } else if (value === false) {\n return 'f';\n } else if (value === true) {\n return 't';\n } else if (value instanceof Date) {\n return formatDate(value.toISOString());\n } else if (value instanceof Buffer) {\n return '\\\\x' + value.toString('hex');\n } else if (Array.isArray(value)) {\n return value\n .map((v, i) => {\n if (v !== null && v !== undefined) {\n if (Array.isArray(v)) {\n return arrayToList(i !== 0, v, quoteString);\n }\n return quoteString(v);\n }\n return ''; // Handle undefined or null values properly within arrays\n })\n .filter((v) => v !== '') // Filter out empty strings to avoid extra commas\n .toString();\n } else if (value === Object(value)) {\n return JSON.stringify(value);\n }\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return value.toString().slice(0); // return copy\n};\n\nconst config = (cfg: FormatterConfig): void => {\n // default\n fmtPattern.ident = 'I';\n fmtPattern.literal = 'L';\n fmtPattern.string = 's';\n\n if (cfg && cfg.pattern) {\n if (cfg.pattern.ident) {\n fmtPattern.ident = cfg.pattern.ident;\n }\n if (cfg.pattern.literal) {\n fmtPattern.literal = cfg.pattern.literal;\n }\n if (cfg.pattern.string) {\n fmtPattern.string = cfg.pattern.string;\n }\n }\n};\n\nconst formatWithArray = (fmt: string, parameters: unknown[]): string => {\n let index = 0;\n const params = parameters;\n\n let re: string | RegExp = '%(%|(\\\\d+\\\\$)?[';\n re += fmtPattern.ident;\n re += fmtPattern.literal;\n re += fmtPattern.string;\n re += '])';\n re = new RegExp(re, 'g');\n\n return fmt.replace(re, (_, type) => {\n if (type === '%') {\n return '%';\n }\n\n let position = index;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access\n const tokens = type.split('$');\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (tokens.length > 1) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n position = parseInt(tokens[0], 10) - 1;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n type = tokens[1];\n }\n\n if (position < 0) {\n throw new Error('specified argument 0 but arguments start at 1');\n } else if (position > params.length - 1) {\n throw new Error('too few arguments');\n }\n\n index = position + 1;\n\n if (type === fmtPattern.ident) {\n return quoteIdent(params[position]);\n } else if (type === fmtPattern.literal) {\n return quoteLiteral(params[position]);\n } else if (type === fmtPattern.string) {\n return quoteString(params[position]);\n }\n\n return undefined!;\n });\n};\n\nconst format = (fmt: string, ...args: unknown[]): string => {\n return formatWithArray(fmt, args);\n};\n\nformat.config = config;\nformat.format = format;\nformat.ident = quoteIdent;\nformat.literal = quoteLiteral;\nformat.string = quoteString;\nformat.withArray = formatWithArray;\n\nexport default format;\n","import format from './pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n connection: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n connection: () => Promise<ConnectionType>;\n },\n) => {\n const connection = await options.connection();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor {\n type: ConnectorType;\n connection: Connection<ConnectorType, DbClient>;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n transaction: () => DatabaseTransaction<ConnectorType, DbClient>;\n\n withTransaction: <Result = never>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n ) => Promise<Result>;\n}\n\nexport type TransactionResult<Result> = { success: boolean; result: Result };\n\nconst toTransactionResult = <Result>(\n transactionResult: TransactionResult<Result> | Result,\n): TransactionResult<Result> =>\n transactionResult !== undefined &&\n transactionResult !== null &&\n typeof transactionResult === 'object' &&\n 'success' in transactionResult\n ? transactionResult\n : { success: true, result: transactionResult };\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n DbClient = unknown,\n Result = void,\n>(\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = toTransactionResult(await handle(transaction));\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>,\n): DatabaseTransactionFactory<ConnectorType, DbClient> => ({\n transaction: () => initTransaction(connect()),\n withTransaction: (handle) =>\n executeInTransaction(initTransaction(connect()), handle),\n});\n\nconst wrapInConnectionClosure = async <\n ConnectionType extends Connection = Connection,\n Result = unknown,\n>(\n connection: ConnectionType,\n handle: () => Promise<Result>,\n) => {\n try {\n return await handle();\n } finally {\n await connection.close();\n }\n};\n\nexport const transactionFactoryWithNewConnection = <\n ConnectionType extends Connection = Connection,\n>(\n connect: () => ConnectionType,\n): DatabaseTransactionFactory<ConnectionType['type']> => ({\n transaction: () => {\n const connection = connect();\n const transaction = connection.transaction();\n\n return {\n ...transaction,\n commit: () =>\n wrapInConnectionClosure(connection, () => transaction.commit()),\n rollback: () =>\n wrapInConnectionClosure(connection, () => transaction.rollback()),\n };\n },\n withTransaction: (handle) => {\n const connection = connect();\n return wrapInConnectionClosure(connection, () =>\n connection.withTransaction(handle),\n );\n },\n});\n","import {\n sqlExecutor,\n type DbSQLExecutor,\n type WithSQLExecutor,\n} from '../execute';\nimport {\n transactionFactoryWithDbClient,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface Connection<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor,\n DatabaseTransactionFactory<ConnectorType> {\n type: ConnectorType;\n open: () => Promise<DbClient>;\n close: () => Promise<void>;\n}\n\nexport interface ConnectionFactory<\n ConnectionType extends Connection = Connection,\n> {\n connection: () => Promise<ConnectionType>;\n\n withConnection: <Result = unknown>(\n handle: (connection: ConnectionType) => Promise<Result>,\n ) => Promise<Result>;\n}\n\nexport type CreateConnectionOptions<\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n> = {\n type: ConnectorType;\n connect: Promise<DbClient>;\n close: (client: DbClient) => Promise<void>;\n initTransaction: (\n connection: () => ConnectionType,\n ) => (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>;\n executor: () => Executor;\n};\n\nexport const createConnection = <\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n>(\n options: CreateConnectionOptions<\n ConnectorType,\n DbClient,\n ConnectionType,\n Executor\n >,\n): ConnectionType => {\n const { type, connect, close, initTransaction, executor } = options;\n\n let client: DbClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n const connection: Connection<ConnectorType, DbClient> = {\n type: type,\n open: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(\n getClient,\n initTransaction(() => typedConnection),\n ),\n execute: sqlExecutor(executor(), { connect: getClient }),\n };\n\n const typedConnection = connection as ConnectionType;\n\n return typedConnection;\n};\n","import {\n executeInNewConnection,\n sqlExecutorInNewConnection,\n type WithSQLExecutor,\n} from '../execute';\nimport { type Connection, type ConnectionFactory } from './connection';\nimport {\n transactionFactoryWithNewConnection,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface ConnectionPool<ConnectionType extends Connection = Connection>\n extends WithSQLExecutor,\n ConnectionFactory<ConnectionType>,\n DatabaseTransactionFactory<ConnectionType['type']> {\n type: ConnectionType['type'];\n close: () => Promise<void>;\n}\n\nexport type ConnectionPoolFactory<\n ConnectionPoolType extends ConnectionPool = ConnectionPool,\n ConnectionPoolOptions = unknown,\n> = (options: ConnectionPoolOptions) => ConnectionPoolType;\n\nexport const createConnectionPool = <\n ConnectionType extends Connection,\n ConnectionPoolType extends ConnectionPool<ConnectionType>,\n>(\n pool: Pick<ConnectionPool<ConnectionType>, 'type'> &\n Partial<ConnectionPool<ConnectionType>> & {\n getConnection: () => ConnectionType;\n },\n): ConnectionPoolType => {\n const { type, getConnection } = pool;\n\n const connection =\n 'connection' in pool\n ? pool.connection\n : () => Promise.resolve(getConnection());\n\n const withConnection =\n 'withConnection' in pool\n ? pool.withConnection\n : <Result>(handle: (connection: ConnectionType) => Promise<Result>) =>\n executeInNewConnection<ConnectionType, Result>(handle, {\n connection,\n });\n\n const close = 'close' in pool ? pool.close : () => Promise.resolve();\n\n const execute =\n 'execute' in pool\n ? pool.execute\n : sqlExecutorInNewConnection({ connection });\n\n const transaction =\n 'transaction' in pool && 'withTransaction' in pool\n ? {\n transaction: pool.transaction,\n withTransaction: pool.withTransaction,\n }\n : transactionFactoryWithNewConnection(getConnection);\n\n const result: ConnectionPool<ConnectionType> = {\n type,\n connection,\n withConnection,\n close,\n execute,\n ...transaction,\n };\n\n return result as ConnectionPoolType;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? (result.rows[0] ?? null) : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? (result.rows[0] ?? null) : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport { createConnection, type Connection } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import {\n sqlExecutor,\n type Connection,\n type DatabaseTransaction,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction =\n <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(\n connection: () => Connection<NodePostgresConnector, DbClient>,\n ) =>\n (\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n ): DatabaseTransaction<NodePostgresConnector> => ({\n connection: connection(),\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), {\n connect: () => getClient,\n }),\n });\n","import pg from 'pg';\nimport { createConnectionPool, type ConnectionPool } from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresConnector,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresAmbientClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport type NodePostgresAmbientConnectionPool = ConnectionPool<\n NodePostgresPoolClientConnection | NodePostgresClientConnection\n>;\n\nexport type NodePostgresPool =\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresNativePool => {\n const { connectionString, database } = options;\n const pool = getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = () => endPool({ connectionString, database });\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport const nodePostgresAmbientNativePool = (options: {\n pool: pg.Pool;\n}): NodePostgresNativePool => {\n const { pool } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n }),\n });\n};\n\nexport const nodePostgresAmbientConnectionPool = (options: {\n connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;\n}): NodePostgresAmbientConnectionPool => {\n const { connection } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => connection,\n execute: connection.execute,\n transaction: () => connection.transaction(),\n withTransaction: (handle) => connection.withTransaction(handle),\n });\n};\n\nexport const nodePostgresClientPool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresAmbientClientPool => {\n const { connectionString, database } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => {\n const connect = Promise.resolve(\n new pg.Client({ connectionString, database }),\n ).then(async (client) => {\n await client.connect();\n return client;\n });\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => client.end(),\n });\n },\n });\n};\n\nexport const nodePostgresAmbientClientPool = (options: {\n client: pg.Client;\n}): NodePostgresAmbientClientPool => {\n const { client } = options;\n\n const getConnection = () => {\n const connect = Promise.resolve(client);\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: () => Promise.resolve(),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = () => Promise.resolve();\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n connection:\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n pooled?: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresAmbientClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n):\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool {\n const { connectionString, database } = options;\n\n if ('client' in options && options.client)\n return nodePostgresAmbientClientPool({ client: options.client });\n\n if ('connection' in options && options.connection)\n return nodePostgresAmbientConnectionPool({\n connection: options.connection,\n });\n\n if ('pooled' in options && options.pooled === false)\n return nodePostgresClientPool({ connectionString, database });\n\n if ('pool' in options && options.pool)\n return nodePostgresAmbientNativePool({ pool: options.pool });\n\n return nodePostgresNativePool({\n connectionString,\n database,\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnection,\n type NodePostgresConnector,\n type NodePostgresPool,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport type PostgresPool = NodePostgresPool;\nexport type PostgresConnection = NodePostgresConnection;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPool,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\n\nexport type PoolOptions = {\n connector?: ConnectorType;\n};\n\nexport type DumboOptions = PoolOptions & PostgresPoolOptions;\nexport type Dumbo = PostgresPool;\n\nexport const connectionPool = <PoolOptionsType extends DumboOptions>(\n options: PoolOptionsType,\n) =>\n // TODO: this should have the pattern matching and verification\n postgresPool(options as unknown as PostgresPoolOptions);\n\nexport const dumbo = <DumboOptionsType extends DumboOptions = DumboOptions>(\n options: DumboOptionsType,\n): Dumbo => connectionPool(options);\n"],"mappings":"AAAA,OAAOA,OAAU,uBCIjB,IAAMC,EAA0C,CAC9C,OAAQ,GACR,OAAQ,GACR,IAAK,GACL,eAAgB,GAChB,QAAS,GACT,QAAS,GACT,IAAK,GACL,IAAK,GACL,MAAO,GACP,GAAI,GACJ,IAAK,GACL,cAAe,GACf,OAAQ,GACR,QAAS,GACT,OAAQ,GACR,aAAc,GACd,KAAM,GACN,SAAU,GACV,KAAM,GACN,KAAM,GACN,MAAO,GACP,QAAS,GACT,OAAQ,GACR,WAAY,GACZ,OAAQ,GACR,YAAa,GACb,MAAO,GACP,aAAc,GACd,aAAc,GACd,kBAA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AAS2B,EAAO,CACd,QAAQ,IAAI,4CAA4CL,CAAS,EAAE,EACnE,QAAQ,IAAIK,CAAK,CACnB,CACAV,EAAM,OAAOK,CAAS,CACxB,EAEaM,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGX,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACK,EAAWtB,CAAI,IAAM0B,EAAUJ,EAAWtB,CAAI,CAAC,CAC5E,EAEIuB,EAAM,CAACzB,EAA0BC,IACrC,GAAGD,CAAgB,IAAIC,GAAY8B,CAAyB,GAExDL,EAAyB,CAACF,EAAmBQ,IAAuB,CACxE,IAAMC,EAAiBb,EAAa,IAAII,CAAS,GAAK,EAChDU,EAAaD,EAAiBD,EAEpC,OAAAZ,EAAa,IAAII,EAAWS,EAAiBD,CAAE,EAExCE,CACT,EClSO,IAAMC,EAAeC,ECKrB,IAAMC,GACXC,GAGAC,EAAaD,CAAyC,EAE3CE,GACXF,GACUD,GAAeC,CAAO","names":["pgcs","reservedMap","reserved_default","fmtPattern","formatDate","date","isReserved","value","reserved_default","arrayToList","useSpace","array","formatter","sql","i","quoteIdent","v","ident","quoted","c","quoteLiteral","literal","explicitCast","hasBackslash","quoteString","config","cfg","formatWithArray","fmt","parameters","index","params","re","_","type","position","tokens","format","args","pg_format_default","sql","sqlQuery","params","pg_format_default","rawSql","sqlExecutor","options","sql","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","toTransactionResult","transactionResult","executeInTransaction","transaction","handle","success","result","e","transactionFactoryWithDbClient","connect","initTransaction","wrapInConnectionClosure","connection","transactionFactoryWithNewConnection","createConnection","options","type","connect","close","initTransaction","executor","client","getClient","typedConnection","transactionFactoryWithDbClient","sqlExecutor","createConnectionPool","pool","type","getConnection","connection","withConnection","handle","executeInNewConnection","close","execute","sqlExecutorInNewConnection","transaction","transactionFactoryWithNewConnection","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","getResult","result","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","sql","tableExists","pool","exists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pgcs","defaultPostgreSqlDatabase","pg","isNodePostgresNativePool","poolOrClient","pg","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","handle","client","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","sqls","results","i","result","nodePostgresTransaction","connection","getClient","options","NodePostgresConnectorType","client","error","sqlExecutor","nodePostgresSQLExecutor","NodePostgresConnectorType","nodePostgresClientConnection","options","connect","close","createConnection","connection","nodePostgresTransaction","nodePostgresSQLExecutor","nodePostgresPoolClientConnection","nodePostgresConnection","pg","nodePostgresNativePool","options","connectionString","database","pool","getPool","getConnection","nodePostgresConnection","client","createConnectionPool","NodePostgresConnectorType","endPool","nodePostgresAmbientNativePool","nodePostgresAmbientConnectionPool","connection","handle","nodePostgresClientPool","connect","pg","nodePostgresAmbientClientPool","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","getDatabaseNameOrDefault","lookupKey","key","updatePoolUsageCounter","force","onEndPool","error","endAllPools","defaultPostgreSqlDatabase","by","currentCounter","newCounter","postgresPool","nodePostgresPool","connectionPool","options","postgresPool","dumbo"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@event-driven-io/dumbo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Dumbo - tools for dealing with PostgreSQL",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
@@ -14,7 +14,9 @@
|
|
|
14
14
|
"test:watch": "node --import tsx --test --watch",
|
|
15
15
|
"test:unit:watch": "glob -c \"node --import tsx --test --watch\" **/*.unit.spec.ts",
|
|
16
16
|
"test:int:watch": "glob -c \"node --import tsx --test --watch\" **/*.int.spec.ts",
|
|
17
|
-
"test:e2e:watch": "glob -c \"node --import tsx --test --watch\" **/*.e2e.spec.ts"
|
|
17
|
+
"test:e2e:watch": "glob -c \"node --import tsx --test --watch\" **/*.e2e.spec.ts",
|
|
18
|
+
"benchmark": "node --import tsx src/benchmarks/index.ts",
|
|
19
|
+
"flamegraph": "0x -D \"0x/{pid}\" -- node --import tsx src/benchmarks/ox.ts"
|
|
18
20
|
},
|
|
19
21
|
"repository": {
|
|
20
22
|
"type": "git",
|
|
@@ -48,15 +50,12 @@
|
|
|
48
50
|
],
|
|
49
51
|
"peerDependencies": {
|
|
50
52
|
"@types/pg": "^8.11.6",
|
|
51
|
-
"@types/
|
|
52
|
-
"@types/pg-format": "^1.0.5",
|
|
53
|
-
"@types/uuid": "^9.0.8",
|
|
53
|
+
"@types/uuid": "^10.0.0",
|
|
54
54
|
"pg": "^8.12.0",
|
|
55
55
|
"pg-connection-string": "^2.6.4",
|
|
56
|
-
"
|
|
57
|
-
"uuid": "^9.0.1"
|
|
56
|
+
"uuid": "^10.0.0"
|
|
58
57
|
},
|
|
59
58
|
"devDependencies": {
|
|
60
|
-
"@types/node": "
|
|
59
|
+
"@types/node": "22.4.1"
|
|
61
60
|
}
|
|
62
61
|
}
|