@event-driven-io/dumbo 0.4.1 → 0.6.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 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(); } } 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 _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var _pgconnectionstring = require('pg-connection-string'); var _pgconnectionstring2 = _interopRequireDefault(_pgconnectionstring);var l="postgres",u= exports.getDatabaseNameOrDefault =e=>_nullishCoalesce(_pgconnectionstring2.default.parse(e).database, () => (l));var n=new Map,i=new Map,c= exports.getPool =e=>{let t=typeof e=="string"?e:e.connectionString,o=typeof e=="string"?{connectionString:t}:e,s=_nullishCoalesce(o.database, () => ((o.connectionString?u(o.connectionString):void 0))),r=y(t,s);return w(r,1),_nullishCoalesce(n.get(r), () => (n.set(r,new _pg2.default.Pool(o)).get(r)))},g= exports.endPool =async({connectionString:e,database:t,force:o})=>{t=_nullishCoalesce(t, () => (u(e)));let s=y(e,t),r=n.get(s);r&&(w(s,-1)<=0||o===!0)&&await R(s,r)},R= exports.onEndPool =async(e,t)=>{try{await t.end(),n.delete(e)}catch(o){console.log(`Error while closing the connection pool: ${e}`),console.log(o)}},M= exports.endAllPools =()=>Promise.all([...n.entries()].map(([e,t])=>R(e,t))),y=(e,t)=>`${e}|${_nullishCoalesce(t, () => (l))}`,w=(e,t)=>{let o=_nullishCoalesce(i.get(e), () => (0)),s=o+t;return i.set(e,o+t),s};var N=(e,t)=>{let o=c({connectionString:e,database:t});return{connect:()=>o.connect(),close:()=>g({connectionString:e,database:t})}};var m=async(e,t)=>{let o=await e.connect();try{return await t(o)}finally{o.release()}},x= exports.executeInTransaction =async(e,t)=>m(e,async o=>{try{await o.query("BEGIN");let{success:s,result:r}=await t(o);return s?await o.query("COMMIT"):await o.query("ROLLBACK"),r}catch(s){throw await o.query("ROLLBACK"),s}}),Q= exports.executeSQL =async(e,t)=>"totalCount"in e?m(e,o=>o.query(t)):e.query(t),F= exports.executeSQLInTransaction =async(e,t)=>(console.log(t),x(e,async o=>({success:!0,result:await o.query(t)}))),H= exports.executeSQLBatchInTransaction =async(e,...t)=>x(e,async o=>{for(let s of t)await o.query(s);return{success:!0,result:void 0}}),K= exports.firstOrNull =async e=>{let t=await e;return t.rows.length>0?_nullishCoalesce(t.rows[0], () => (null)):null},U= 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]},W= 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},d= 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]},X= exports.mapRows =async(e,t)=>(await e).rows.map(t),S= exports.toCamelCase =e=>e.replace(/_([a-z])/g,t=>_nullishCoalesce(_optionalChain([t, 'access', _ => _[1], 'optionalAccess', _2 => _2.toUpperCase, 'call', _3 => _3()]), () => (""))),z= exports.mapToCamelCase =e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[S(o)]=e[o]);return t},a= exports.exists =async(e,t)=>(await d(Q(e,t))).exists===!0;var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var L=e=>p(`
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 M=async(e,o)=>{await e.begin();try{let{success:t,result:n}=await o(e);return t?await e.commit():await e.rollback(),n}catch(t){throw await e.rollback(),t}},m= exports.transactionFactoryWithDbClient =(e,o)=>({transaction:()=>o(e()),withTransaction:t=>M(o(e()),t)}),d=async(e,o)=>{try{return await o()}finally{await e.close()}},x= exports.transactionFactoryWithNewConnection =e=>({transaction:()=>{let o=e(),t=o.transaction();return{...t,commit:()=>d(o,()=>t.commit()),rollback:()=>d(o,()=>t.rollback())}},withTransaction:o=>{let t=e();return d(t,()=>t.withTransaction(o))}});var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var R=(e,...o)=>_pgformat2.default.call(void 0, e,...o),oe= exports.rawSql =e=>e;var c=(e,o)=>({query:t=>p(n=>e.query(n,t),o),batchQuery:t=>p(n=>e.batchQuery(n,t),o),command:t=>p(n=>e.command(n,t),o),batchCommand:t=>p(n=>e.batchQuery(n,t),o)}),w= exports.sqlExecutorInNewConnection =e=>({query:o=>P(t=>t.execute.query(o),e),batchQuery:o=>P(t=>t.execute.batchQuery(o),e),command:o=>P(t=>t.execute.command(o),e),batchCommand:o=>P(t=>t.execute.batchCommand(o),e)}),p= exports.executeInNewDbClient =async(e,o)=>{let{connect:t,close:n}=o,r=await t();try{return await e(r)}catch(s){throw n&&await n(r,s),s}},P= exports.executeInNewConnection =async(e,o)=>{let{open:t}=o,n=await t();try{return await e(n)}finally{await n.close()}};var le=async(e,o)=>(await e).rows.map(o),I= exports.toCamelCase =e=>e.replace(/_([a-z])/g,o=>_nullishCoalesce(_optionalChain([o, 'access', _2 => _2[1], 'optionalAccess', _3 => _3.toUpperCase, 'call', _4 => _4()]), () => (""))),ce= exports.mapToCamelCase =e=>{let o={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(o[I(t)]=e[t]);return o};var ue=async e=>{let o=await e;return o.rows.length>0?_nullishCoalesce(o.rows[0], () => (null)):null},pe= exports.first =async e=>{let o=await e;if(o.rows.length===0)throw new Error("Query didn't return any result");return o.rows[0]},Pe= exports.singleOrNull =async e=>{let o=await e;if(o.rows.length>1)throw new Error("Query had more than one result");return o.rows.length>0?_nullishCoalesce(o.rows[0], () => (null)):null},A= exports.single =async e=>{let o=await e;if(o.rows.length===0)throw new Error("Query didn't return any result");if(o.rows.length>1)throw new Error("Query had more than one result");return o.rows[0]},Q= exports.exists =async e=>(await A(e)).exists===!0;var y="postgres",_= exports.tableExistsSQL =e=>R(`
2
2
  SELECT EXISTS (
3
3
  SELECT FROM pg_tables
4
4
  WHERE tablename = %L
5
- ) AS exists;`,e),Z= exports.tableExists =async(e,t)=>a(e,L(t)),E= exports.functionExistsSQL =e=>p(`
5
+ ) AS exists;`,e),Ne= exports.tableExists =async(e,o)=>Q(e.execute.query(_(o))),$= exports.functionExistsSQL =e=>R(`
6
6
  SELECT EXISTS (
7
7
  SELECT FROM pg_proc
8
8
  WHERE
9
9
  proname = %L
10
10
  ) AS exists;
11
- `,e),ee= exports.functionExists =async(e,t)=>a(e,E(t));var p=(e,...t)=>_pgformat2.default.call(void 0, e,...t),re= exports.rawSql =e=>e;exports.defaultPostgreSqlDatabase = l; exports.endAllPools = M; exports.endPool = g; exports.execute = m; exports.executeInTransaction = x; exports.executeSQL = Q; exports.executeSQLBatchInTransaction = H; exports.executeSQLInTransaction = F; exports.exists = a; exports.first = U; exports.firstOrNull = K; exports.functionExists = ee; exports.functionExistsSQL = E; exports.getDatabaseNameOrDefault = u; exports.getPool = c; exports.mapRows = X; exports.mapToCamelCase = z; exports.onEndPool = R; exports.postgresClient = N; exports.rawSql = re; exports.single = d; exports.singleOrNull = W; exports.sql = p; exports.tableExists = Z; exports.tableExistsSQL = L; exports.toCamelCase = S;
11
+ `,e),Se= exports.functionExists =async(e,o)=>Q(e.execute.query($(o)));var f=e=>_nullishCoalesce(_pgconnectionstring2.default.parse(e).database, () => (y));var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var T=e=>e instanceof _pg2.default.Pool,$e= exports.isNodePostgresClient =e=>e instanceof _pg2.default.Client,H= exports.isNodePostgresPoolClient =e=>"release"in e&&typeof e.release=="function",Be= exports.nodePostgresExecute =async(e,o)=>{let t=T(e)?await e.connect():e;try{return await o(t)}finally{T(e)&&H(t)&&t.release()}},a= exports.nodePostgresSQLExecutor =()=>({type:i,query:g,batchQuery:g,command:g,batchCommand:g});async function g(e,o){let t=Array.isArray(o)?o:[o],n=Array(t.length);for(let r=0;r<t.length;r++){let s=await e.query(t[r]);n[r]={rowCount:s.rowCount,rows:s.rows}}return Array.isArray(o)?n:n[0]}var b=(e,o)=>({type:i,begin:async()=>{await(await e).query("BEGIN")},commit:async()=>{let t=await e;await t.query("COMMIT"),_optionalChain([o, 'optionalAccess', _5 => _5.close])&&await _optionalChain([o, 'optionalAccess', _6 => _6.close, 'call', _7 => _7(t)])},rollback:async t=>{let n=await e;await n.query("ROLLBACK"),_optionalChain([o, 'optionalAccess', _8 => _8.close])&&await _optionalChain([o, 'optionalAccess', _9 => _9.close, 'call', _10 => _10(n,t)])},execute:c(a(),{connect:()=>e})});var i="PostgreSQL:pg",U= exports.nodePostgresClientConnection =e=>{let{connect:o,close:t}=e,n=null,r=async()=>await _asyncNullishCoalesce(n, async () => ((n=await o)));return{type:i,connect:r,close:()=>n?t(n):Promise.resolve(),...m(r,b),execute:c(a(),{connect:r})}},X= exports.nodePostgresPoolClientConnection =e=>{let{connect:o,close:t}=e,n=null,r=async()=>await _asyncNullishCoalesce(n, async () => ((n=await o)));return{type:i,connect:r,close:()=>n?t(n):Promise.resolve(),...m(r,b),execute:c(a(),{connect:r})}};function N(e){return e.type==="Client"?U(e):X(e)}var z=e=>{let{connectionString:o,database:t,pool:n}=e,r=n||K({connectionString:o,database:t}),s=()=>N({type:"PoolClient",connect:r.connect(),close:l=>Promise.resolve(l.release())}),C=()=>Promise.resolve(s());return{type:i,open:C,close:async()=>{n||await q({connectionString:o,database:t})},execute:w({open:C}),...x(s)}},G= exports.nodePostgresExplicitClientPool =e=>{let{connectionString:o,database:t,client:n}=e,r=()=>{let S=n?Promise.resolve(n):Promise.resolve(new _pg2.default.Client({connectionString:o,database:t})).then(async l=>(await l.connect(),l));return N({type:"Client",connect:S,close:l=>n?Promise.resolve():l.end()})},s=()=>Promise.resolve(r());return{type:i,open:s,close:async()=>{n||await q({connectionString:o,database:t})},execute:w({open:s}),...x(r)}};function D(e){let{connectionString:o,database:t}=e;return"pooled"in e&&e.pooled===!1||"client"in e?G({connectionString:o,...t?{database:t}:{},..."client"in e&&e.client?{client:e.client}:{}}):z({connectionString:o,...t?{database:t}:{},..."pool"in e&&e.pool?{pool:e.pool}:{}})}var u=new Map,E=new Map,K= exports.getPool =e=>{let o=typeof e=="string"?e:e.connectionString,t=typeof e=="string"?{connectionString:o}:e,n=_nullishCoalesce(t.database, () => ((t.connectionString?f(t.connectionString):void 0))),r=k(o,n);return v(r,1),_nullishCoalesce(u.get(r), () => (u.set(r,new _pg2.default.Pool(t)).get(r)))},q= exports.endPool =async({connectionString:e,database:o,force:t})=>{o=_nullishCoalesce(o, () => (f(e)));let n=k(e,o),r=u.get(n);r&&(v(n,-1)<=0||t===!0)&&await O(n,r)},O= exports.onEndPool =async(e,o)=>{try{await o.end()}catch(t){console.log(`Error while closing the connection pool: ${e}`),console.log(t)}u.delete(e)},io= exports.endAllPools =()=>Promise.all([...u.entries()].map(([e,o])=>O(e,o))),k=(e,o)=>`${e}|${_nullishCoalesce(o, () => (y))}`,v=(e,o)=>{let t=_nullishCoalesce(E.get(e), () => (0)),n=t+o;return E.set(e,t+o),n};var F=D;var Qo=(e,o)=>F(o);exports.NodePostgresConnectorType = i; exports.connectionPool = Qo; exports.defaultPostgreSqlDatabase = y; exports.endAllPools = io; exports.endPool = q; exports.executeInNewConnection = P; exports.executeInNewDbClient = p; exports.executeInTransaction = M; exports.exists = Q; exports.first = pe; exports.firstOrNull = ue; exports.functionExists = Se; exports.functionExistsSQL = $; exports.getDatabaseNameOrDefault = f; exports.getPool = K; exports.isNodePostgresClient = $e; exports.isNodePostgresNativePool = T; exports.isNodePostgresPoolClient = H; exports.mapRows = le; exports.mapToCamelCase = ce; exports.nodePostgresClientConnection = U; exports.nodePostgresConnection = N; exports.nodePostgresExecute = Be; exports.nodePostgresExplicitClientPool = G; exports.nodePostgresNativePool = z; exports.nodePostgresPool = D; exports.nodePostgresPoolClientConnection = X; exports.nodePostgresSQLExecutor = a; exports.nodePostgresTransaction = b; exports.onEndPool = O; exports.postgresPool = F; exports.rawSql = oe; exports.single = A; exports.singleOrNull = Pe; exports.sql = R; exports.sqlExecutor = c; exports.sqlExecutorInNewConnection = w; exports.tableExists = Ne; exports.tableExistsSQL = _; exports.toCamelCase = I; exports.transactionFactoryWithDbClient = m; exports.transactionFactoryWithNewConnection = x;
12
12
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/connections/client.ts","../src/connections/pool.ts","../src/connections/connectionString.ts","../src/execute/index.ts","../src/sql/index.ts","../src/sql/schema.ts"],"names":["pg","pgcs","defaultPostgreSqlDatabase","getDatabaseNameOrDefault","connectionString","pools","usageCounter","getPool","connectionStringOrOptions","poolOptions","database","lookupKey","key","updatePoolUsageCounter","endPool","force","pool","onEndPool","error","endAllPools","by","currentCounter","newCounter","postgresClient","execute","handle","client","executeInTransaction","success","result","e","executeSQL","poolOrClient","sql","executeSQLInTransaction","executeSQLBatchInTransaction","sqls","firstOrNull","getResult","first","singleOrNull","single","mapRows","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","exists","format","tableExistsSQL","tableName","tableExists","functionExistsSQL","functionName","functionExists","sqlQuery","params","rawSql"],"mappings":"AAAA,MAAe,KCAf,OAAOA,MAAQ,KCAf,OAAOC,MAAU,uBAEV,IAAMC,EAA4B,WAE5BC,EAA4BC,GACvCH,EAAK,MAAMG,CAAgB,EAAE,UAAYF,EDC3C,IAAMG,EAA8B,IAAI,IAClCC,EAAoC,IAAI,IAEjCC,EACXC,GACY,CACZ,IAAMJ,EACJ,OAAOI,GAA8B,SACjCA,EACAA,EAA0B,iBAE1BC,EACJ,OAAOD,GAA8B,SACjC,CAAE,iBAAAJ,CAAiB,EACnBI,EAEAE,EACJD,EAAY,WACXA,EAAY,iBACTN,EAAyBM,EAAY,gBAAgB,EACrD,QAEAE,EAAYC,EAAIR,EAAkBM,CAAQ,EAEhD,OAAAG,EAAuBF,EAAW,CAAC,EAGjCN,EAAM,IAAIM,CAAS,GACnBN,EAAM,IAAIM,EAAW,IAAIX,EAAG,KAAKS,CAAW,CAAC,EAAE,IAAIE,CAAS,CAEhE,EAEaG,EAAU,MAAO,CAC5B,iBAAAV,EACA,SAAAM,EACA,MAAAK,CACF,IAIqB,CACnBL,EAAWA,GAAYP,EAAyBC,CAAgB,EAChE,IAAMO,EAAYC,EAAIR,EAAkBM,CAAQ,EAE1CM,EAAOX,EAAM,IAAIM,CAAS,EAC5BK,IAASH,EAAuBF,EAAW,EAAE,GAAK,GAAKI,IAAU,KACnE,MAAME,EAAUN,EAAWK,CAAI,CAEnC,EAEaC,EAAY,MAAON,EAAmBK,IAAkB,CACnE,GAAI,CACF,MAAMA,EAAK,IAAI,E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GfC,EAAeC,GAC1BA,EAAS,QAAQ,YAAcC,GAAMA,EAAE,CAAC,GAAG,YAAY,GAAK,EAAE,EAEnDC,EACXC,GACM,CACN,IAAMC,EAAkC,CAAC,EACzC,QAAWrC,KAAOoC,EACZ,OAAO,UAAU,eAAe,KAAKA,EAAKpC,CAAG,IAC/CqC,EAAOL,EAAYhC,CAAG,CAAC,EAAIoC,EAAIpC,CAAG,GAGtC,OAAOqC,CACT,EAIaC,EAAS,MAAOlC,EAAeiB,KAC3B,MAAMQ,EAAOV,EAAiCf,EAAMiB,CAAG,CAAC,GAEzD,SAAW,GC5J3B,OAAOkB,MAAY,YCAnB,MAAe,KAKR,IAAMC,EAAkBC,GAC7BpB,EACE;AAAA;AAAA;AAAA;AAAA,gBAKAoB,CACF,EAEWC,EAAc,MACzBtC,EACAqC,IACqBH,EAAOlC,EAAMoC,EAAeC,CAAS,CAAC,EAEhDE,EAAqBC,GAChCvB,EACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOAuB,CACF,EAEWC,GAAiB,MAC5BzC,EACAwC,IACqBN,EAAOlC,EAAMuC,EAAkBC,CAAY,CAAC,ED9B5D,IAAMvB,EAAM,CAACyB,KAAqBC,IAChCR,EAAOO,EAAU,GAAGC,CAAM,EAGtBC,GAAUF,GACdA","sourcesContent":["import pg from 'pg';\nimport { endPool, getPool } from './pool';\n\nexport interface PostgresClient {\n connect(): Promise<pg.PoolClient>;\n close(): Promise<void>;\n}\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): PostgresClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => pool.connect(),\n close: () => endPool({ connectionString, database }),\n };\n};\n","import pg from 'pg';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from './connectionString';\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 pools.delete(lookupKey);\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\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","import pgcs from 'pg-connection-string';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import type pg from 'pg';\nimport type { SQL } from '../sql';\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n\nexport const executeInTransaction = async <Result = void>(\n pool: pg.Pool,\n handle: (\n client: pg.PoolClient,\n ) => Promise<{ success: boolean; result: Result }>,\n): Promise<Result> =>\n execute(pool, async (client) => {\n try {\n await client.query('BEGIN');\n\n const { success, result } = await handle(client);\n\n if (success) await client.query('COMMIT');\n else await client.query('ROLLBACK');\n\n return result;\n } catch (e) {\n await client.query('ROLLBACK');\n throw e;\n }\n });\n\nexport const executeSQL = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n poolOrClient: pg.Pool | pg.PoolClient,\n sql: SQL,\n): Promise<pg.QueryResult<Result>> =>\n 'totalCount' in poolOrClient\n ? execute(poolOrClient, (client) => client.query<Result>(sql))\n : poolOrClient.query<Result>(sql);\n\nexport const executeSQLInTransaction = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool,\n sql: SQL,\n) => {\n console.log(sql);\n return executeInTransaction(pool, async (client) => ({\n success: true,\n result: await client.query<Result>(sql),\n }));\n};\n\nexport const executeSQLBatchInTransaction = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool,\n ...sqls: SQL[]\n) =>\n executeInTransaction(pool, async (client) => {\n for (const sql of sqls) {\n await client.query<Result>(sql);\n }\n\n return { success: true, result: undefined };\n });\n\nexport const firstOrNull = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n getResult: Promise<pg.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 <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n getResult: Promise<pg.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 pg.QueryResultRow = pg.QueryResultRow,\n>(\n getResult: Promise<pg.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 <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n getResult: Promise<pg.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 const mapRows = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<pg.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\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (pool: pg.Pool, sql: SQL): Promise<boolean> => {\n const result = await single(executeSQL<ExistsSQLQueryResult>(pool, sql));\n\n return result.exists === true;\n};\n","import format from 'pg-format';\nexport * from './schema';\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 pg from 'pg';\nimport { sql, type SQL } from '.';\nimport { exists } from '../execute';\nexport * from './schema';\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: pg.Pool,\n tableName: string,\n): Promise<boolean> => exists(pool, 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: pg.Pool,\n functionName: string,\n): Promise<boolean> => exists(pool, functionExistsSQL(functionName));\n"]}
1
+ {"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/connections/transaction.ts","../src/core/sql/index.ts","../src/core/execute/execute.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","executeInTransaction","transaction","handle","success","result","e","transactionFactoryWithDbClient","connect","initTransaction","wrapInConnectionClosure","connection","transactionFactoryWithNewConnection","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","close","error","open","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","tableExists","pool","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pg","isNodePostgresNativePool","poolOrClient","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","results","i","nodePostgresTransaction","getClient","nodePostgresClientConnection","nodePostgresPoolClientConnection","nodePostgresConnection","nodePostgresNativePool","database","ambientPool","getPool","getConnection","endPool","nodePostgresExplicitClientPool","ambientClient","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","lookupKey","updatePoolUsageCounter","force","onEndPool","endAllPools","by","currentCounter","newCounter","postgresPool","connectionPool","_type"],"mappings":"AAAA,OAAOA,MAAU,uBCuBV,IAAMC,EAAuB,MAIlCC,EACAC,IAGoB,CACpB,MAAMD,EAAY,MAAM,EAExB,GAAI,CACF,GAAM,CAAE,QAAAE,EAAS,OAAAC,CAAO,EAAI,MAAMF,EAAOD,CAAW,EAEpD,OAAIE,EAAS,MAAMF,EAAY,OAAO,EACjC,MAAMA,EAAY,SAAS,EAEzBG,CACT,OAASC,EAAG,CACV,YAAMJ,EAAY,SAAS,EACrBI,CACR,CACF,EAEaC,EAAiC,CAI5CC,EACAC,KAG+C,CAC/C,YAAa,IAAMA,EAAgBD,EAAQ,CAAC,EAC5C,gBAAkBL,GAChBF,EAAqBQ,EAAgBD,EAAQ,CAAC,EAAGL,CAAM,CAC3D,GAEMO,EAA0B,MAI9BC,EACAR,IACG,CACH,GAAI,CACF,OAAO,MAAMA,EAAO,CACtB,QAAE,CACA,MAAMQ,EAAW,MAAM,CACzB,CACF,EAEaC,EAGXJ,IACwD,CACxD,YAAa,IAAM,CACjB,IAAMG,EAAaH,EAAQ,EACrBN,EAAcS,EAAW,YAAY,EAE3C,MAAO,CACL,GAAGT,EACH,OAAQ,IACNQ,EAAwBC,EAAY,IAAMT,EAAY,OAAO,CAAC,EAChE,SAAU,IACRQ,EAAwBC,EAAY,IAAMT,EAAY,SAAS,CAAC,CACpE,CACF,EACA,gBAAkBC,GAAW,CAC3B,IAAMQ,EAAaH,EAAQ,EAC3B,OAAOE,EAAwBC,EAAY,IACzCA,EAAW,gBAAgBR,CAAM,CACnC,CACF,CACF,GClGA,OAAOU,MAAY,YAKZ,IAAMC,EAAM,CAACC,KAAqBC,IAChCH,EAAOE,EAAU,GAAGC,CAAM,EAGtBC,GAAUF,GACdA,ECoCF,IAAMG,EAAc,CAIzBA,EAEAC,KAIiB,CACjB,MAAQL,GACNM,EAA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ACd,QAAQ,IAAI,4CAA4CyD,CAAS,EAAE,EACnE,QAAQ,IAAIzD,CAAK,CACnB,CACAqD,EAAM,OAAOI,CAAS,CACxB,EAEaI,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGR,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACI,EAAWpC,CAAI,IAAMuC,EAAUH,EAAWpC,CAAI,CAAC,CAC5E,EAEIV,EAAM,CAACe,EAA0BmB,IACrC,GAAGnB,CAAgB,IAAImB,GAAY5B,CAAyB,GAExDyC,EAAyB,CAACD,EAAmBK,IAAuB,CACxE,IAAMC,EAAiBT,EAAa,IAAIG,CAAS,GAAK,EAChDO,EAAaD,EAAiBD,EAEpC,OAAAR,EAAa,IAAIG,EAAWM,EAAiBD,CAAE,EAExCE,CACT,ECpOO,IAAMC,EAAeb,ECErB,IAAMc,GAAiB,CAACC,EAAsB1E,IACnDwE,EAAaxE,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 type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<ConnectorType extends string = string>\n extends WithSQLExecutor {\n type: ConnectorType;\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> {\n transaction: () => DatabaseTransaction<ConnectorType>;\n\n withTransaction: <Result = unknown>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<{ success: boolean; result: Result }>,\n ) => Promise<Result>;\n}\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n Result = unknown,\n>(\n transaction: DatabaseTransaction<ConnectorType>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<{ success: boolean; result: Result }>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = 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>,\n): DatabaseTransactionFactory<ConnectorType> => ({\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 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 open: () => 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 extends QueryResultRow = QueryResultRow,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n open: () => Promise<ConnectionType>;\n },\n) => {\n const { open } = options;\n const connection = await open();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\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 {\n sqlExecutor,\n transactionFactoryWithDbClient,\n type Connection,\n} 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 let client: pg.Client | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n return {\n type: NodePostgresConnectorType,\n connect: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(getClient, nodePostgresTransaction),\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: getClient }),\n };\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n let client: pg.PoolClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n return {\n type: NodePostgresConnectorType,\n connect: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(getClient, nodePostgresTransaction),\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: getClient }),\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 { sqlExecutor, type DatabaseTransaction } 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>(\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n): DatabaseTransaction<NodePostgresConnector> => ({\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(), { connect: () => getClient }),\n});\n","import pg from 'pg';\nimport {\n sqlExecutorInNewConnection,\n transactionFactoryWithNewConnection,\n type ConnectionPool,\n} from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresExplicitClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string;\n pool?: pg.Pool;\n}): NodePostgresNativePool => {\n const { connectionString, database, pool: ambientPool } = options;\n const pool = ambientPool\n ? ambientPool\n : 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 = async () => {\n if (!ambientPool) await endPool({ connectionString, database });\n };\n\n return {\n type: NodePostgresConnectorType,\n open,\n close,\n execute: sqlExecutorInNewConnection({ open }),\n ...transactionFactoryWithNewConnection(getConnection),\n };\n};\n\nexport const nodePostgresExplicitClientPool = (options: {\n connectionString: string;\n database?: string;\n client?: pg.Client;\n}): NodePostgresExplicitClientPool => {\n const { connectionString, database, client: ambientClient } = options;\n\n const getConnection = () => {\n const connect = ambientClient\n ? Promise.resolve(ambientClient)\n : Promise.resolve(new pg.Client({ connectionString, database })).then(\n async (client) => {\n await client.connect();\n return client;\n },\n );\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => (ambientClient ? Promise.resolve() : client.end()),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = async () => {\n if (!ambientClient) await endPool({ connectionString, database });\n };\n\n return {\n type: NodePostgresConnectorType,\n open,\n close,\n execute: sqlExecutorInNewConnection({ open }),\n ...transactionFactoryWithNewConnection(getConnection),\n };\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connectionString: string;\n database?: string;\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): NodePostgresExplicitClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n): NodePostgresNativePool | NodePostgresExplicitClientPool {\n const { connectionString, database } = options;\n\n if (('pooled' in options && options.pooled === false) || 'client' in options)\n return nodePostgresExplicitClientPool({\n connectionString,\n ...(database ? { database } : {}),\n ...('client' in options && options.client\n ? { client: options.client }\n : {}),\n });\n\n return nodePostgresNativePool({\n connectionString,\n ...(database ? { database } : {}),\n ...('pool' in options && options.pool ? { pool: options.pool } : {}),\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 NodePostgresConnector,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\nexport type PoolOptions = PostgresPoolOptions;\n\nexport const connectionPool = (_type: ConnectorType, options: PoolOptions) =>\n postgresPool(options);\n"]}
package/dist/index.d.cts CHANGED
@@ -1,14 +1,172 @@
1
1
  import pg from 'pg';
2
2
 
3
- interface PostgresClient {
4
- connect(): Promise<pg.PoolClient>;
5
- close(): Promise<void>;
3
+ declare const getDatabaseNameOrDefault: (connectionString: string) => string;
4
+
5
+ interface QueryResultRow {
6
+ [column: string]: any;
7
+ }
8
+ type QueryResult<Result extends QueryResultRow = QueryResultRow> = {
9
+ rowCount: number | null;
10
+ rows: Result[];
11
+ };
12
+
13
+ declare const mapRows: <Result extends QueryResultRow = QueryResultRow, Mapped = unknown>(getResult: Promise<QueryResult<Result>>, map: (row: Result) => Mapped) => Promise<Mapped[]>;
14
+ declare const toCamelCase: (snakeStr: string) => string;
15
+ declare const mapToCamelCase: <T extends Record<string, unknown>>(obj: T) => T;
16
+
17
+ declare const firstOrNull: <Result extends QueryResultRow = QueryResultRow>(getResult: Promise<QueryResult<Result>>) => Promise<Result | null>;
18
+ declare const first: <Result extends QueryResultRow = QueryResultRow>(getResult: Promise<QueryResult<Result>>) => Promise<Result>;
19
+ declare const singleOrNull: <Result extends QueryResultRow = QueryResultRow>(getResult: Promise<QueryResult<Result>>) => Promise<Result | null>;
20
+ declare const single: <Result extends QueryResultRow = QueryResultRow>(getResult: Promise<QueryResult<Result>>) => Promise<Result>;
21
+ type ExistsSQLQueryResult = {
22
+ exists: boolean;
23
+ };
24
+ declare const exists: (getResult: Promise<QueryResult<ExistsSQLQueryResult>>) => Promise<boolean>;
25
+
26
+ type SQL = string & {
27
+ __brand: 'sql';
28
+ };
29
+ declare const sql: (sqlQuery: string, ...params: unknown[]) => SQL;
30
+ declare const rawSql: (sqlQuery: string) => SQL;
31
+
32
+ interface DbSQLExecutor<ConnectorType extends string = string, DbClient = unknown> {
33
+ type: ConnectorType;
34
+ query<Result extends QueryResultRow = QueryResultRow>(client: DbClient, sql: SQL): Promise<QueryResult<Result>>;
35
+ batchQuery<Result extends QueryResultRow = QueryResultRow>(client: DbClient, sqls: SQL[]): Promise<QueryResult<Result>[]>;
36
+ command<Result extends QueryResultRow = QueryResultRow>(client: DbClient, sql: SQL): Promise<QueryResult<Result>>;
37
+ batchCommand<Result extends QueryResultRow = QueryResultRow>(client: DbClient, sqls: SQL[]): Promise<QueryResult<Result>[]>;
38
+ }
39
+ interface SQLExecutor {
40
+ query<Result extends QueryResultRow = QueryResultRow>(sql: SQL): Promise<QueryResult<Result>>;
41
+ batchQuery<Result extends QueryResultRow = QueryResultRow>(sqls: SQL[]): Promise<QueryResult<Result>[]>;
42
+ command<Result extends QueryResultRow = QueryResultRow>(sql: SQL): Promise<QueryResult<Result>>;
43
+ batchCommand<Result extends QueryResultRow = QueryResultRow>(sqls: SQL[]): Promise<QueryResult<Result>[]>;
44
+ }
45
+ interface WithSQLExecutor {
46
+ execute: SQLExecutor;
47
+ }
48
+ declare const sqlExecutor: <DbClient = unknown, DbExecutor extends DbSQLExecutor<string, unknown> = DbSQLExecutor<string, unknown>>(sqlExecutor: DbExecutor, options: {
49
+ connect: () => Promise<DbClient>;
50
+ close?: (client: DbClient, error?: unknown) => Promise<void>;
51
+ }) => SQLExecutor;
52
+ declare const sqlExecutorInNewConnection: <ConnectionType extends Connection<string, unknown>>(options: {
53
+ open: () => Promise<ConnectionType>;
54
+ }) => SQLExecutor;
55
+ declare const executeInNewDbClient: <DbClient = unknown, Result = unknown>(handle: (client: DbClient) => Promise<Result>, options: {
56
+ connect: () => Promise<DbClient>;
57
+ close?: (client: DbClient, error?: unknown) => Promise<void>;
58
+ }) => Promise<Result>;
59
+ declare const executeInNewConnection: <ConnectionType extends Connection<string, unknown>, Result extends QueryResultRow = QueryResultRow>(handle: (connection: ConnectionType) => Promise<Result>, options: {
60
+ open: () => Promise<ConnectionType>;
61
+ }) => Promise<Result>;
62
+
63
+ interface DatabaseTransaction<ConnectorType extends string = string> extends WithSQLExecutor {
64
+ type: ConnectorType;
65
+ begin: () => Promise<void>;
66
+ commit: () => Promise<void>;
67
+ rollback: (error?: unknown) => Promise<void>;
68
+ }
69
+ interface DatabaseTransactionFactory<ConnectorType extends string = string> {
70
+ transaction: () => DatabaseTransaction<ConnectorType>;
71
+ withTransaction: <Result = unknown>(handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<{
72
+ success: boolean;
73
+ result: Result;
74
+ }>) => Promise<Result>;
75
+ }
76
+ declare const executeInTransaction: <ConnectorType extends string = string, Result = unknown>(transaction: DatabaseTransaction<ConnectorType>, handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<{
77
+ success: boolean;
78
+ result: Result;
79
+ }>) => Promise<Result>;
80
+ declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>) => DatabaseTransactionFactory<ConnectorType>;
81
+ declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection<string, unknown> = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType['type']>;
82
+
83
+ interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
84
+ type: ConnectorType;
85
+ connect: () => Promise<DbClient>;
86
+ close: () => Promise<void>;
6
87
  }
7
- declare const postgresClient: (connectionString: string, database?: string) => PostgresClient;
88
+
89
+ interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectionType['type']> {
90
+ type: ConnectionType['type'];
91
+ open: () => Promise<ConnectionType>;
92
+ close: () => Promise<void>;
93
+ }
94
+ type ConnectionPoolProvider<ConnectionPoolType extends ConnectionPool = ConnectionPool, ConnectionPoolOptions = unknown> = (options: ConnectionPoolOptions) => ConnectionPoolType;
8
95
 
9
96
  declare const defaultPostgreSqlDatabase = "postgres";
10
- declare const getDatabaseNameOrDefault: (connectionString: string) => string;
97
+ declare const tableExistsSQL: (tableName: string) => SQL;
98
+ declare const tableExists: (pool: ConnectionPool, tableName: string) => Promise<boolean>;
99
+ declare const functionExistsSQL: (functionName: string) => SQL;
100
+ declare const functionExists: (pool: ConnectionPool, tableName: string) => Promise<boolean>;
101
+
102
+ declare const NodePostgresConnectorType = "PostgreSQL:pg";
103
+ type NodePostgresConnector = 'PostgreSQL:pg';
104
+ type NodePostgresClient = pg.PoolClient | pg.Client;
105
+ type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;
106
+ type NodePostgresClientConnection = Connection<NodePostgresConnector, pg.Client>;
107
+ type NodePostgresPoolClientConnection = Connection<NodePostgresConnector, pg.PoolClient>;
108
+ type NodePostgresConnection = NodePostgresPoolClientConnection | NodePostgresClientConnection;
109
+ type NodePostgresPoolClientOptions = {
110
+ type: 'PoolClient';
111
+ connect: Promise<pg.PoolClient>;
112
+ close: (client: pg.PoolClient) => Promise<void>;
113
+ };
114
+ type NodePostgresClientOptions = {
115
+ type: 'Client';
116
+ connect: Promise<pg.Client>;
117
+ close: (client: pg.Client) => Promise<void>;
118
+ };
119
+ declare const nodePostgresClientConnection: (options: NodePostgresClientOptions) => NodePostgresClientConnection;
120
+ declare const nodePostgresPoolClientConnection: (options: NodePostgresPoolClientOptions) => NodePostgresPoolClientConnection;
121
+ declare function nodePostgresConnection(options: NodePostgresPoolClientOptions): NodePostgresPoolClientConnection;
122
+ declare function nodePostgresConnection(options: NodePostgresClientOptions): NodePostgresClientConnection;
11
123
 
124
+ type NodePostgresNativePool = ConnectionPool<NodePostgresPoolClientConnection>;
125
+ type NodePostgresExplicitClientPool = ConnectionPool<NodePostgresClientConnection>;
126
+ declare const nodePostgresNativePool: (options: {
127
+ connectionString: string;
128
+ database?: string;
129
+ pool?: pg.Pool;
130
+ }) => NodePostgresNativePool;
131
+ declare const nodePostgresExplicitClientPool: (options: {
132
+ connectionString: string;
133
+ database?: string;
134
+ client?: pg.Client;
135
+ }) => NodePostgresExplicitClientPool;
136
+ type NodePostgresPoolPooledOptions = {
137
+ connectionString: string;
138
+ database?: string;
139
+ pooled: true;
140
+ pool: pg.Pool;
141
+ } | {
142
+ connectionString: string;
143
+ database?: string;
144
+ pool: pg.Pool;
145
+ } | {
146
+ connectionString: string;
147
+ database?: string;
148
+ pooled: true;
149
+ } | {
150
+ connectionString: string;
151
+ database?: string;
152
+ };
153
+ type NodePostgresPoolNotPooledOptions = {
154
+ connectionString: string;
155
+ database?: string;
156
+ pooled: false;
157
+ client: pg.Client;
158
+ } | {
159
+ connectionString: string;
160
+ database?: string;
161
+ client: pg.Client;
162
+ } | {
163
+ connectionString: string;
164
+ database?: string;
165
+ pooled: false;
166
+ };
167
+ type NodePostgresPoolOptions = NodePostgresPoolPooledOptions | NodePostgresPoolNotPooledOptions;
168
+ declare function nodePostgresPool(options: NodePostgresPoolPooledOptions): NodePostgresNativePool;
169
+ declare function nodePostgresPool(options: NodePostgresPoolNotPooledOptions): NodePostgresExplicitClientPool;
12
170
  declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
13
171
  declare const endPool: ({ connectionString, database, force, }: {
14
172
  connectionString: string;
@@ -18,35 +176,24 @@ declare const endPool: ({ connectionString, database, force, }: {
18
176
  declare const onEndPool: (lookupKey: string, pool: pg.Pool) => Promise<void>;
19
177
  declare const endAllPools: () => Promise<void[]>;
20
178
 
21
- declare const tableExistsSQL: (tableName: string) => SQL;
22
- declare const tableExists: (pool: pg.Pool, tableName: string) => Promise<boolean>;
23
- declare const functionExistsSQL: (functionName: string) => SQL;
24
- declare const functionExists: (pool: pg.Pool, functionName: string) => Promise<boolean>;
179
+ type NodePostgresTransaction = DatabaseTransaction<NodePostgresConnector>;
180
+ declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(getClient: Promise<DbClient>, options?: {
181
+ close: (client: DbClient, error?: unknown) => Promise<void>;
182
+ } | undefined) => DatabaseTransaction<NodePostgresConnector>;
25
183
 
26
- type SQL = string & {
27
- __brand: 'sql';
28
- };
29
- declare const sql: (sqlQuery: string, ...params: unknown[]) => SQL;
30
- declare const rawSql: (sqlQuery: string) => SQL;
184
+ declare const isNodePostgresNativePool: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Pool;
185
+ declare const isNodePostgresClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Client;
186
+ declare const isNodePostgresPoolClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.PoolClient;
187
+ declare const nodePostgresExecute: <Result = void>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, handle: (client: pg.PoolClient | pg.Client) => Promise<Result>) => Promise<Result>;
188
+ type NodePostgresSQLExecutor = DbSQLExecutor<NodePostgresConnector, NodePostgresClient>;
189
+ declare const nodePostgresSQLExecutor: () => NodePostgresSQLExecutor;
31
190
 
32
- declare const execute: <Result = void>(pool: pg.Pool, handle: (client: pg.PoolClient) => Promise<Result>) => Promise<Result>;
33
- declare const executeInTransaction: <Result = void>(pool: pg.Pool, handle: (client: pg.PoolClient) => Promise<{
34
- success: boolean;
35
- result: Result;
36
- }>) => Promise<Result>;
37
- declare const executeSQL: <Result extends pg.QueryResultRow = pg.QueryResultRow>(poolOrClient: pg.Pool | pg.PoolClient, sql: SQL) => Promise<pg.QueryResult<Result>>;
38
- declare const executeSQLInTransaction: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool, sql: SQL) => Promise<pg.QueryResult<Result>>;
39
- declare const executeSQLBatchInTransaction: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool, ...sqls: SQL[]) => Promise<undefined>;
40
- declare const firstOrNull: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result | null>;
41
- declare const first: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result>;
42
- declare const singleOrNull: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result | null>;
43
- declare const single: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result>;
44
- declare const mapRows: <Result extends pg.QueryResultRow = pg.QueryResultRow, Mapped = unknown>(getResult: Promise<pg.QueryResult<Result>>, map: (row: Result) => Mapped) => Promise<Mapped[]>;
45
- declare const toCamelCase: (snakeStr: string) => string;
46
- declare const mapToCamelCase: <T extends Record<string, unknown>>(obj: T) => T;
47
- type ExistsSQLQueryResult = {
48
- exists: boolean;
49
- };
50
- declare const exists: (pool: pg.Pool, sql: SQL) => Promise<boolean>;
191
+ type PostgresConnector = NodePostgresConnector;
192
+ type PostgresPoolOptions = NodePostgresPoolOptions;
193
+ declare const postgresPool: typeof nodePostgresPool;
194
+
195
+ type ConnectorType = PostgresConnector;
196
+ type PoolOptions = PostgresPoolOptions;
197
+ declare const connectionPool: (_type: ConnectorType, options: PoolOptions) => NodePostgresNativePool;
51
198
 
52
- export { type ExistsSQLQueryResult, type PostgresClient, type SQL, defaultPostgreSqlDatabase, endAllPools, endPool, execute, executeInTransaction, executeSQL, executeSQLBatchInTransaction, executeSQLInTransaction, exists, first, firstOrNull, functionExists, functionExistsSQL, getDatabaseNameOrDefault, getPool, mapRows, mapToCamelCase, onEndPool, postgresClient, rawSql, single, singleOrNull, sql, tableExists, tableExistsSQL, toCamelCase };
199
+ export { type Connection, type ConnectionPool, type ConnectionPoolProvider, type ConnectorType, type DatabaseTransaction, type DatabaseTransactionFactory, type DbSQLExecutor, type ExistsSQLQueryResult, type NodePostgresClient, type NodePostgresClientConnection, type NodePostgresClientOptions, type NodePostgresConnection, type NodePostgresConnector, NodePostgresConnectorType, type NodePostgresExplicitClientPool, type NodePostgresNativePool, type NodePostgresPoolClientConnection, type NodePostgresPoolClientOptions, type NodePostgresPoolNotPooledOptions, type NodePostgresPoolOptions, type NodePostgresPoolOrClient, type NodePostgresPoolPooledOptions, type NodePostgresSQLExecutor, type NodePostgresTransaction, type PoolOptions, type PostgresConnector, type PostgresPoolOptions, type QueryResult, type QueryResultRow, type SQL, type SQLExecutor, type WithSQLExecutor, connectionPool, defaultPostgreSqlDatabase, endAllPools, endPool, executeInNewConnection, executeInNewDbClient, executeInTransaction, exists, first, firstOrNull, functionExists, functionExistsSQL, getDatabaseNameOrDefault, getPool, isNodePostgresClient, isNodePostgresNativePool, isNodePostgresPoolClient, mapRows, mapToCamelCase, nodePostgresClientConnection, nodePostgresConnection, nodePostgresExecute, nodePostgresExplicitClientPool, nodePostgresNativePool, nodePostgresPool, nodePostgresPoolClientConnection, nodePostgresSQLExecutor, nodePostgresTransaction, onEndPool, postgresPool, rawSql, single, singleOrNull, sql, sqlExecutor, sqlExecutorInNewConnection, tableExists, tableExistsSQL, toCamelCase, transactionFactoryWithDbClient, transactionFactoryWithNewConnection };
package/dist/index.d.ts CHANGED
@@ -1,14 +1,172 @@
1
1
  import pg from 'pg';
2
2
 
3
- interface PostgresClient {
4
- connect(): Promise<pg.PoolClient>;
5
- close(): Promise<void>;
3
+ declare const getDatabaseNameOrDefault: (connectionString: string) => string;
4
+
5
+ interface QueryResultRow {
6
+ [column: string]: any;
7
+ }
8
+ type QueryResult<Result extends QueryResultRow = QueryResultRow> = {
9
+ rowCount: number | null;
10
+ rows: Result[];
11
+ };
12
+
13
+ declare const mapRows: <Result extends QueryResultRow = QueryResultRow, Mapped = unknown>(getResult: Promise<QueryResult<Result>>, map: (row: Result) => Mapped) => Promise<Mapped[]>;
14
+ declare const toCamelCase: (snakeStr: string) => string;
15
+ declare const mapToCamelCase: <T extends Record<string, unknown>>(obj: T) => T;
16
+
17
+ declare const firstOrNull: <Result extends QueryResultRow = QueryResultRow>(getResult: Promise<QueryResult<Result>>) => Promise<Result | null>;
18
+ declare const first: <Result extends QueryResultRow = QueryResultRow>(getResult: Promise<QueryResult<Result>>) => Promise<Result>;
19
+ declare const singleOrNull: <Result extends QueryResultRow = QueryResultRow>(getResult: Promise<QueryResult<Result>>) => Promise<Result | null>;
20
+ declare const single: <Result extends QueryResultRow = QueryResultRow>(getResult: Promise<QueryResult<Result>>) => Promise<Result>;
21
+ type ExistsSQLQueryResult = {
22
+ exists: boolean;
23
+ };
24
+ declare const exists: (getResult: Promise<QueryResult<ExistsSQLQueryResult>>) => Promise<boolean>;
25
+
26
+ type SQL = string & {
27
+ __brand: 'sql';
28
+ };
29
+ declare const sql: (sqlQuery: string, ...params: unknown[]) => SQL;
30
+ declare const rawSql: (sqlQuery: string) => SQL;
31
+
32
+ interface DbSQLExecutor<ConnectorType extends string = string, DbClient = unknown> {
33
+ type: ConnectorType;
34
+ query<Result extends QueryResultRow = QueryResultRow>(client: DbClient, sql: SQL): Promise<QueryResult<Result>>;
35
+ batchQuery<Result extends QueryResultRow = QueryResultRow>(client: DbClient, sqls: SQL[]): Promise<QueryResult<Result>[]>;
36
+ command<Result extends QueryResultRow = QueryResultRow>(client: DbClient, sql: SQL): Promise<QueryResult<Result>>;
37
+ batchCommand<Result extends QueryResultRow = QueryResultRow>(client: DbClient, sqls: SQL[]): Promise<QueryResult<Result>[]>;
38
+ }
39
+ interface SQLExecutor {
40
+ query<Result extends QueryResultRow = QueryResultRow>(sql: SQL): Promise<QueryResult<Result>>;
41
+ batchQuery<Result extends QueryResultRow = QueryResultRow>(sqls: SQL[]): Promise<QueryResult<Result>[]>;
42
+ command<Result extends QueryResultRow = QueryResultRow>(sql: SQL): Promise<QueryResult<Result>>;
43
+ batchCommand<Result extends QueryResultRow = QueryResultRow>(sqls: SQL[]): Promise<QueryResult<Result>[]>;
44
+ }
45
+ interface WithSQLExecutor {
46
+ execute: SQLExecutor;
47
+ }
48
+ declare const sqlExecutor: <DbClient = unknown, DbExecutor extends DbSQLExecutor<string, unknown> = DbSQLExecutor<string, unknown>>(sqlExecutor: DbExecutor, options: {
49
+ connect: () => Promise<DbClient>;
50
+ close?: (client: DbClient, error?: unknown) => Promise<void>;
51
+ }) => SQLExecutor;
52
+ declare const sqlExecutorInNewConnection: <ConnectionType extends Connection<string, unknown>>(options: {
53
+ open: () => Promise<ConnectionType>;
54
+ }) => SQLExecutor;
55
+ declare const executeInNewDbClient: <DbClient = unknown, Result = unknown>(handle: (client: DbClient) => Promise<Result>, options: {
56
+ connect: () => Promise<DbClient>;
57
+ close?: (client: DbClient, error?: unknown) => Promise<void>;
58
+ }) => Promise<Result>;
59
+ declare const executeInNewConnection: <ConnectionType extends Connection<string, unknown>, Result extends QueryResultRow = QueryResultRow>(handle: (connection: ConnectionType) => Promise<Result>, options: {
60
+ open: () => Promise<ConnectionType>;
61
+ }) => Promise<Result>;
62
+
63
+ interface DatabaseTransaction<ConnectorType extends string = string> extends WithSQLExecutor {
64
+ type: ConnectorType;
65
+ begin: () => Promise<void>;
66
+ commit: () => Promise<void>;
67
+ rollback: (error?: unknown) => Promise<void>;
68
+ }
69
+ interface DatabaseTransactionFactory<ConnectorType extends string = string> {
70
+ transaction: () => DatabaseTransaction<ConnectorType>;
71
+ withTransaction: <Result = unknown>(handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<{
72
+ success: boolean;
73
+ result: Result;
74
+ }>) => Promise<Result>;
75
+ }
76
+ declare const executeInTransaction: <ConnectorType extends string = string, Result = unknown>(transaction: DatabaseTransaction<ConnectorType>, handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<{
77
+ success: boolean;
78
+ result: Result;
79
+ }>) => Promise<Result>;
80
+ declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>) => DatabaseTransactionFactory<ConnectorType>;
81
+ declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection<string, unknown> = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType['type']>;
82
+
83
+ interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
84
+ type: ConnectorType;
85
+ connect: () => Promise<DbClient>;
86
+ close: () => Promise<void>;
6
87
  }
7
- declare const postgresClient: (connectionString: string, database?: string) => PostgresClient;
88
+
89
+ interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectionType['type']> {
90
+ type: ConnectionType['type'];
91
+ open: () => Promise<ConnectionType>;
92
+ close: () => Promise<void>;
93
+ }
94
+ type ConnectionPoolProvider<ConnectionPoolType extends ConnectionPool = ConnectionPool, ConnectionPoolOptions = unknown> = (options: ConnectionPoolOptions) => ConnectionPoolType;
8
95
 
9
96
  declare const defaultPostgreSqlDatabase = "postgres";
10
- declare const getDatabaseNameOrDefault: (connectionString: string) => string;
97
+ declare const tableExistsSQL: (tableName: string) => SQL;
98
+ declare const tableExists: (pool: ConnectionPool, tableName: string) => Promise<boolean>;
99
+ declare const functionExistsSQL: (functionName: string) => SQL;
100
+ declare const functionExists: (pool: ConnectionPool, tableName: string) => Promise<boolean>;
101
+
102
+ declare const NodePostgresConnectorType = "PostgreSQL:pg";
103
+ type NodePostgresConnector = 'PostgreSQL:pg';
104
+ type NodePostgresClient = pg.PoolClient | pg.Client;
105
+ type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;
106
+ type NodePostgresClientConnection = Connection<NodePostgresConnector, pg.Client>;
107
+ type NodePostgresPoolClientConnection = Connection<NodePostgresConnector, pg.PoolClient>;
108
+ type NodePostgresConnection = NodePostgresPoolClientConnection | NodePostgresClientConnection;
109
+ type NodePostgresPoolClientOptions = {
110
+ type: 'PoolClient';
111
+ connect: Promise<pg.PoolClient>;
112
+ close: (client: pg.PoolClient) => Promise<void>;
113
+ };
114
+ type NodePostgresClientOptions = {
115
+ type: 'Client';
116
+ connect: Promise<pg.Client>;
117
+ close: (client: pg.Client) => Promise<void>;
118
+ };
119
+ declare const nodePostgresClientConnection: (options: NodePostgresClientOptions) => NodePostgresClientConnection;
120
+ declare const nodePostgresPoolClientConnection: (options: NodePostgresPoolClientOptions) => NodePostgresPoolClientConnection;
121
+ declare function nodePostgresConnection(options: NodePostgresPoolClientOptions): NodePostgresPoolClientConnection;
122
+ declare function nodePostgresConnection(options: NodePostgresClientOptions): NodePostgresClientConnection;
11
123
 
124
+ type NodePostgresNativePool = ConnectionPool<NodePostgresPoolClientConnection>;
125
+ type NodePostgresExplicitClientPool = ConnectionPool<NodePostgresClientConnection>;
126
+ declare const nodePostgresNativePool: (options: {
127
+ connectionString: string;
128
+ database?: string;
129
+ pool?: pg.Pool;
130
+ }) => NodePostgresNativePool;
131
+ declare const nodePostgresExplicitClientPool: (options: {
132
+ connectionString: string;
133
+ database?: string;
134
+ client?: pg.Client;
135
+ }) => NodePostgresExplicitClientPool;
136
+ type NodePostgresPoolPooledOptions = {
137
+ connectionString: string;
138
+ database?: string;
139
+ pooled: true;
140
+ pool: pg.Pool;
141
+ } | {
142
+ connectionString: string;
143
+ database?: string;
144
+ pool: pg.Pool;
145
+ } | {
146
+ connectionString: string;
147
+ database?: string;
148
+ pooled: true;
149
+ } | {
150
+ connectionString: string;
151
+ database?: string;
152
+ };
153
+ type NodePostgresPoolNotPooledOptions = {
154
+ connectionString: string;
155
+ database?: string;
156
+ pooled: false;
157
+ client: pg.Client;
158
+ } | {
159
+ connectionString: string;
160
+ database?: string;
161
+ client: pg.Client;
162
+ } | {
163
+ connectionString: string;
164
+ database?: string;
165
+ pooled: false;
166
+ };
167
+ type NodePostgresPoolOptions = NodePostgresPoolPooledOptions | NodePostgresPoolNotPooledOptions;
168
+ declare function nodePostgresPool(options: NodePostgresPoolPooledOptions): NodePostgresNativePool;
169
+ declare function nodePostgresPool(options: NodePostgresPoolNotPooledOptions): NodePostgresExplicitClientPool;
12
170
  declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
13
171
  declare const endPool: ({ connectionString, database, force, }: {
14
172
  connectionString: string;
@@ -18,35 +176,24 @@ declare const endPool: ({ connectionString, database, force, }: {
18
176
  declare const onEndPool: (lookupKey: string, pool: pg.Pool) => Promise<void>;
19
177
  declare const endAllPools: () => Promise<void[]>;
20
178
 
21
- declare const tableExistsSQL: (tableName: string) => SQL;
22
- declare const tableExists: (pool: pg.Pool, tableName: string) => Promise<boolean>;
23
- declare const functionExistsSQL: (functionName: string) => SQL;
24
- declare const functionExists: (pool: pg.Pool, functionName: string) => Promise<boolean>;
179
+ type NodePostgresTransaction = DatabaseTransaction<NodePostgresConnector>;
180
+ declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(getClient: Promise<DbClient>, options?: {
181
+ close: (client: DbClient, error?: unknown) => Promise<void>;
182
+ } | undefined) => DatabaseTransaction<NodePostgresConnector>;
25
183
 
26
- type SQL = string & {
27
- __brand: 'sql';
28
- };
29
- declare const sql: (sqlQuery: string, ...params: unknown[]) => SQL;
30
- declare const rawSql: (sqlQuery: string) => SQL;
184
+ declare const isNodePostgresNativePool: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Pool;
185
+ declare const isNodePostgresClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Client;
186
+ declare const isNodePostgresPoolClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.PoolClient;
187
+ declare const nodePostgresExecute: <Result = void>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, handle: (client: pg.PoolClient | pg.Client) => Promise<Result>) => Promise<Result>;
188
+ type NodePostgresSQLExecutor = DbSQLExecutor<NodePostgresConnector, NodePostgresClient>;
189
+ declare const nodePostgresSQLExecutor: () => NodePostgresSQLExecutor;
31
190
 
32
- declare const execute: <Result = void>(pool: pg.Pool, handle: (client: pg.PoolClient) => Promise<Result>) => Promise<Result>;
33
- declare const executeInTransaction: <Result = void>(pool: pg.Pool, handle: (client: pg.PoolClient) => Promise<{
34
- success: boolean;
35
- result: Result;
36
- }>) => Promise<Result>;
37
- declare const executeSQL: <Result extends pg.QueryResultRow = pg.QueryResultRow>(poolOrClient: pg.Pool | pg.PoolClient, sql: SQL) => Promise<pg.QueryResult<Result>>;
38
- declare const executeSQLInTransaction: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool, sql: SQL) => Promise<pg.QueryResult<Result>>;
39
- declare const executeSQLBatchInTransaction: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool, ...sqls: SQL[]) => Promise<undefined>;
40
- declare const firstOrNull: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result | null>;
41
- declare const first: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result>;
42
- declare const singleOrNull: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result | null>;
43
- declare const single: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result>;
44
- declare const mapRows: <Result extends pg.QueryResultRow = pg.QueryResultRow, Mapped = unknown>(getResult: Promise<pg.QueryResult<Result>>, map: (row: Result) => Mapped) => Promise<Mapped[]>;
45
- declare const toCamelCase: (snakeStr: string) => string;
46
- declare const mapToCamelCase: <T extends Record<string, unknown>>(obj: T) => T;
47
- type ExistsSQLQueryResult = {
48
- exists: boolean;
49
- };
50
- declare const exists: (pool: pg.Pool, sql: SQL) => Promise<boolean>;
191
+ type PostgresConnector = NodePostgresConnector;
192
+ type PostgresPoolOptions = NodePostgresPoolOptions;
193
+ declare const postgresPool: typeof nodePostgresPool;
194
+
195
+ type ConnectorType = PostgresConnector;
196
+ type PoolOptions = PostgresPoolOptions;
197
+ declare const connectionPool: (_type: ConnectorType, options: PoolOptions) => NodePostgresNativePool;
51
198
 
52
- export { type ExistsSQLQueryResult, type PostgresClient, type SQL, defaultPostgreSqlDatabase, endAllPools, endPool, execute, executeInTransaction, executeSQL, executeSQLBatchInTransaction, executeSQLInTransaction, exists, first, firstOrNull, functionExists, functionExistsSQL, getDatabaseNameOrDefault, getPool, mapRows, mapToCamelCase, onEndPool, postgresClient, rawSql, single, singleOrNull, sql, tableExists, tableExistsSQL, toCamelCase };
199
+ export { type Connection, type ConnectionPool, type ConnectionPoolProvider, type ConnectorType, type DatabaseTransaction, type DatabaseTransactionFactory, type DbSQLExecutor, type ExistsSQLQueryResult, type NodePostgresClient, type NodePostgresClientConnection, type NodePostgresClientOptions, type NodePostgresConnection, type NodePostgresConnector, NodePostgresConnectorType, type NodePostgresExplicitClientPool, type NodePostgresNativePool, type NodePostgresPoolClientConnection, type NodePostgresPoolClientOptions, type NodePostgresPoolNotPooledOptions, type NodePostgresPoolOptions, type NodePostgresPoolOrClient, type NodePostgresPoolPooledOptions, type NodePostgresSQLExecutor, type NodePostgresTransaction, type PoolOptions, type PostgresConnector, type PostgresPoolOptions, type QueryResult, type QueryResultRow, type SQL, type SQLExecutor, type WithSQLExecutor, connectionPool, defaultPostgreSqlDatabase, endAllPools, endPool, executeInNewConnection, executeInNewDbClient, executeInTransaction, exists, first, firstOrNull, functionExists, functionExistsSQL, getDatabaseNameOrDefault, getPool, isNodePostgresClient, isNodePostgresNativePool, isNodePostgresPoolClient, mapRows, mapToCamelCase, nodePostgresClientConnection, nodePostgresConnection, nodePostgresExecute, nodePostgresExplicitClientPool, nodePostgresNativePool, nodePostgresPool, nodePostgresPoolClientConnection, nodePostgresSQLExecutor, nodePostgresTransaction, onEndPool, postgresPool, rawSql, single, singleOrNull, sql, sqlExecutor, sqlExecutorInNewConnection, tableExists, tableExistsSQL, toCamelCase, transactionFactoryWithDbClient, transactionFactoryWithNewConnection };
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import"pg";import f from"pg";import P from"pg-connection-string";var l="postgres",u=e=>P.parse(e).database??l;var n=new Map,i=new Map,c=e=>{let t=typeof e=="string"?e:e.connectionString,o=typeof e=="string"?{connectionString:t}:e,s=o.database??(o.connectionString?u(o.connectionString):void 0),r=y(t,s);return w(r,1),n.get(r)??n.set(r,new f.Pool(o)).get(r)},g=async({connectionString:e,database:t,force:o})=>{t=t??u(e);let s=y(e,t),r=n.get(s);r&&(w(s,-1)<=0||o===!0)&&await R(s,r)},R=async(e,t)=>{try{await t.end(),n.delete(e)}catch(o){console.log(`Error while closing the connection pool: ${e}`),console.log(o)}},M=()=>Promise.all([...n.entries()].map(([e,t])=>R(e,t))),y=(e,t)=>`${e}|${t??l}`,w=(e,t)=>{let o=i.get(e)??0,s=o+t;return i.set(e,o+t),s};var N=(e,t)=>{let o=c({connectionString:e,database:t});return{connect:()=>o.connect(),close:()=>g({connectionString:e,database:t})}};var m=async(e,t)=>{let o=await e.connect();try{return await t(o)}finally{o.release()}},x=async(e,t)=>m(e,async o=>{try{await o.query("BEGIN");let{success:s,result:r}=await t(o);return s?await o.query("COMMIT"):await o.query("ROLLBACK"),r}catch(s){throw await o.query("ROLLBACK"),s}}),Q=async(e,t)=>"totalCount"in e?m(e,o=>o.query(t)):e.query(t),F=async(e,t)=>(console.log(t),x(e,async o=>({success:!0,result:await o.query(t)}))),H=async(e,...t)=>x(e,async o=>{for(let s of t)await o.query(s);return{success:!0,result:void 0}}),K=async e=>{let t=await e;return t.rows.length>0?t.rows[0]??null:null},U=async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");return t.rows[0]},W=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},d=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]},X=async(e,t)=>(await e).rows.map(t),S=e=>e.replace(/_([a-z])/g,t=>t[1]?.toUpperCase()??""),z=e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[S(o)]=e[o]);return t},a=async(e,t)=>(await d(Q(e,t))).exists===!0;import C from"pg-format";import"pg";var L=e=>p(`
1
+ import B from"pg-connection-string";var M=async(e,o)=>{await e.begin();try{let{success:t,result:n}=await o(e);return t?await e.commit():await e.rollback(),n}catch(t){throw await e.rollback(),t}},m=(e,o)=>({transaction:()=>o(e()),withTransaction:t=>M(o(e()),t)}),d=async(e,o)=>{try{return await o()}finally{await e.close()}},x=e=>({transaction:()=>{let o=e(),t=o.transaction();return{...t,commit:()=>d(o,()=>t.commit()),rollback:()=>d(o,()=>t.rollback())}},withTransaction:o=>{let t=e();return d(t,()=>t.withTransaction(o))}});import W from"pg-format";var R=(e,...o)=>W(e,...o),oe=e=>e;var c=(e,o)=>({query:t=>p(n=>e.query(n,t),o),batchQuery:t=>p(n=>e.batchQuery(n,t),o),command:t=>p(n=>e.command(n,t),o),batchCommand:t=>p(n=>e.batchQuery(n,t),o)}),w=e=>({query:o=>P(t=>t.execute.query(o),e),batchQuery:o=>P(t=>t.execute.batchQuery(o),e),command:o=>P(t=>t.execute.command(o),e),batchCommand:o=>P(t=>t.execute.batchCommand(o),e)}),p=async(e,o)=>{let{connect:t,close:n}=o,r=await t();try{return await e(r)}catch(s){throw n&&await n(r,s),s}},P=async(e,o)=>{let{open:t}=o,n=await t();try{return await e(n)}finally{await n.close()}};var le=async(e,o)=>(await e).rows.map(o),I=e=>e.replace(/_([a-z])/g,o=>o[1]?.toUpperCase()??""),ce=e=>{let o={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(o[I(t)]=e[t]);return o};var ue=async e=>{let o=await e;return o.rows.length>0?o.rows[0]??null:null},pe=async e=>{let o=await e;if(o.rows.length===0)throw new Error("Query didn't return any result");return o.rows[0]},Pe=async e=>{let o=await e;if(o.rows.length>1)throw new Error("Query had more than one result");return o.rows.length>0?o.rows[0]??null:null},A=async e=>{let o=await e;if(o.rows.length===0)throw new Error("Query didn't return any result");if(o.rows.length>1)throw new Error("Query had more than one result");return o.rows[0]},Q=async e=>(await A(e)).exists===!0;var y="postgres",_=e=>R(`
2
2
  SELECT EXISTS (
3
3
  SELECT FROM pg_tables
4
4
  WHERE tablename = %L
5
- ) AS exists;`,e),Z=async(e,t)=>a(e,L(t)),E=e=>p(`
5
+ ) AS exists;`,e),Ne=async(e,o)=>Q(e.execute.query(_(o))),$=e=>R(`
6
6
  SELECT EXISTS (
7
7
  SELECT FROM pg_proc
8
8
  WHERE
9
9
  proname = %L
10
10
  ) AS exists;
11
- `,e),ee=async(e,t)=>a(e,E(t));var p=(e,...t)=>C(e,...t),re=e=>e;export{l as defaultPostgreSqlDatabase,M as endAllPools,g as endPool,m as execute,x as executeInTransaction,Q as executeSQL,H as executeSQLBatchInTransaction,F as executeSQLInTransaction,a as exists,U as first,K as firstOrNull,ee as functionExists,E as functionExistsSQL,u as getDatabaseNameOrDefault,c as getPool,X as mapRows,z as mapToCamelCase,R as onEndPool,N as postgresClient,re as rawSql,d as single,W as singleOrNull,p as sql,Z as tableExists,L as tableExistsSQL,S as toCamelCase};
11
+ `,e),Se=async(e,o)=>Q(e.execute.query($(o)));var f=e=>B.parse(e).database??y;import"pg";import h from"pg";var T=e=>e instanceof h.Pool,$e=e=>e instanceof h.Client,H=e=>"release"in e&&typeof e.release=="function",Be=async(e,o)=>{let t=T(e)?await e.connect():e;try{return await o(t)}finally{T(e)&&H(t)&&t.release()}},a=()=>({type:i,query:g,batchQuery:g,command:g,batchCommand:g});async function g(e,o){let t=Array.isArray(o)?o:[o],n=Array(t.length);for(let r=0;r<t.length;r++){let s=await e.query(t[r]);n[r]={rowCount:s.rowCount,rows:s.rows}}return Array.isArray(o)?n:n[0]}var b=(e,o)=>({type:i,begin:async()=>{await(await e).query("BEGIN")},commit:async()=>{let t=await e;await t.query("COMMIT"),o?.close&&await o?.close(t)},rollback:async t=>{let n=await e;await n.query("ROLLBACK"),o?.close&&await o?.close(n,t)},execute:c(a(),{connect:()=>e})});var i="PostgreSQL:pg",U=e=>{let{connect:o,close:t}=e,n=null,r=async()=>n??(n=await o);return{type:i,connect:r,close:()=>n?t(n):Promise.resolve(),...m(r,b),execute:c(a(),{connect:r})}},X=e=>{let{connect:o,close:t}=e,n=null,r=async()=>n??(n=await o);return{type:i,connect:r,close:()=>n?t(n):Promise.resolve(),...m(r,b),execute:c(a(),{connect:r})}};function N(e){return e.type==="Client"?U(e):X(e)}import L from"pg";var z=e=>{let{connectionString:o,database:t,pool:n}=e,r=n||K({connectionString:o,database:t}),s=()=>N({type:"PoolClient",connect:r.connect(),close:l=>Promise.resolve(l.release())}),C=()=>Promise.resolve(s());return{type:i,open:C,close:async()=>{n||await q({connectionString:o,database:t})},execute:w({open:C}),...x(s)}},G=e=>{let{connectionString:o,database:t,client:n}=e,r=()=>{let S=n?Promise.resolve(n):Promise.resolve(new L.Client({connectionString:o,database:t})).then(async l=>(await l.connect(),l));return N({type:"Client",connect:S,close:l=>n?Promise.resolve():l.end()})},s=()=>Promise.resolve(r());return{type:i,open:s,close:async()=>{n||await q({connectionString:o,database:t})},execute:w({open:s}),...x(r)}};function D(e){let{connectionString:o,database:t}=e;return"pooled"in e&&e.pooled===!1||"client"in e?G({connectionString:o,...t?{database:t}:{},..."client"in e&&e.client?{client:e.client}:{}}):z({connectionString:o,...t?{database:t}:{},..."pool"in e&&e.pool?{pool:e.pool}:{}})}var u=new Map,E=new Map,K=e=>{let o=typeof e=="string"?e:e.connectionString,t=typeof e=="string"?{connectionString:o}:e,n=t.database??(t.connectionString?f(t.connectionString):void 0),r=k(o,n);return v(r,1),u.get(r)??u.set(r,new L.Pool(t)).get(r)},q=async({connectionString:e,database:o,force:t})=>{o=o??f(e);let n=k(e,o),r=u.get(n);r&&(v(n,-1)<=0||t===!0)&&await O(n,r)},O=async(e,o)=>{try{await o.end()}catch(t){console.log(`Error while closing the connection pool: ${e}`),console.log(t)}u.delete(e)},io=()=>Promise.all([...u.entries()].map(([e,o])=>O(e,o))),k=(e,o)=>`${e}|${o??y}`,v=(e,o)=>{let t=E.get(e)??0,n=t+o;return E.set(e,t+o),n};var F=D;var Qo=(e,o)=>F(o);export{i as NodePostgresConnectorType,Qo as connectionPool,y as defaultPostgreSqlDatabase,io as endAllPools,q as endPool,P as executeInNewConnection,p as executeInNewDbClient,M as executeInTransaction,Q as exists,pe as first,ue as firstOrNull,Se as functionExists,$ as functionExistsSQL,f as getDatabaseNameOrDefault,K as getPool,$e as isNodePostgresClient,T as isNodePostgresNativePool,H as isNodePostgresPoolClient,le as mapRows,ce as mapToCamelCase,U as nodePostgresClientConnection,N as nodePostgresConnection,Be as nodePostgresExecute,G as nodePostgresExplicitClientPool,z as nodePostgresNativePool,D as nodePostgresPool,X as nodePostgresPoolClientConnection,a as nodePostgresSQLExecutor,b as nodePostgresTransaction,O as onEndPool,F as postgresPool,oe as rawSql,A as single,Pe as singleOrNull,R as sql,c as sqlExecutor,w as sqlExecutorInNewConnection,Ne as tableExists,_ as tableExistsSQL,I as toCamelCase,m as transactionFactoryWithDbClient,x as transactionFactoryWithNewConnection};
12
12
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/connections/client.ts","../src/connections/pool.ts","../src/connections/connectionString.ts","../src/execute/index.ts","../src/sql/index.ts","../src/sql/schema.ts"],"sourcesContent":["import pg from 'pg';\nimport { endPool, getPool } from './pool';\n\nexport interface PostgresClient {\n connect(): Promise<pg.PoolClient>;\n close(): Promise<void>;\n}\n\nexport const postgresClient = (\n connectionString: string,\n database?: string,\n): PostgresClient => {\n const pool = getPool({ connectionString, database });\n\n return {\n connect: () => pool.connect(),\n close: () => endPool({ connectionString, database }),\n };\n};\n","import pg from 'pg';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from './connectionString';\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 pools.delete(lookupKey);\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\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","import pgcs from 'pg-connection-string';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import type pg from 'pg';\nimport type { SQL } from '../sql';\n\nexport const execute = async <Result = void>(\n pool: pg.Pool,\n handle: (client: pg.PoolClient) => Promise<Result>,\n) => {\n const client = await pool.connect();\n try {\n return await handle(client);\n } finally {\n client.release();\n }\n};\n\nexport const executeInTransaction = async <Result = void>(\n pool: pg.Pool,\n handle: (\n client: pg.PoolClient,\n ) => Promise<{ success: boolean; result: Result }>,\n): Promise<Result> =>\n execute(pool, async (client) => {\n try {\n await client.query('BEGIN');\n\n const { success, result } = await handle(client);\n\n if (success) await client.query('COMMIT');\n else await client.query('ROLLBACK');\n\n return result;\n } catch (e) {\n await client.query('ROLLBACK');\n throw e;\n }\n });\n\nexport const executeSQL = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n poolOrClient: pg.Pool | pg.PoolClient,\n sql: SQL,\n): Promise<pg.QueryResult<Result>> =>\n 'totalCount' in poolOrClient\n ? execute(poolOrClient, (client) => client.query<Result>(sql))\n : poolOrClient.query<Result>(sql);\n\nexport const executeSQLInTransaction = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool,\n sql: SQL,\n) => {\n console.log(sql);\n return executeInTransaction(pool, async (client) => ({\n success: true,\n result: await client.query<Result>(sql),\n }));\n};\n\nexport const executeSQLBatchInTransaction = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool,\n ...sqls: SQL[]\n) =>\n executeInTransaction(pool, async (client) => {\n for (const sql of sqls) {\n await client.query<Result>(sql);\n }\n\n return { success: true, result: undefined };\n });\n\nexport const firstOrNull = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n getResult: Promise<pg.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 <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n getResult: Promise<pg.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 pg.QueryResultRow = pg.QueryResultRow,\n>(\n getResult: Promise<pg.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 <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n getResult: Promise<pg.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 const mapRows = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<pg.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\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (pool: pg.Pool, sql: SQL): Promise<boolean> => {\n const result = await single(executeSQL<ExistsSQLQueryResult>(pool, sql));\n\n return result.exists === true;\n};\n","import format from 'pg-format';\nexport * from './schema';\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 pg from 'pg';\nimport { sql, type SQL } from '.';\nimport { exists } from '../execute';\nexport * from './schema';\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: pg.Pool,\n tableName: string,\n): Promise<boolean> => exists(pool, 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: pg.Pool,\n functionName: string,\n): Promise<boolean> => exists(pool, functionExistsSQL(functionName));\n"],"mappings":"AAAA,MAAe,KCAf,OAAOA,MAAQ,KCAf,OAAOC,MAAU,uBAEV,IAAMC,EAA4B,WAE5BC,EAA4BC,GACvCH,EAAK,MAAMG,CAAgB,EAAE,UAAYF,EDC3C,IAAMG,E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A;AAAA,gBAKAD,CACF,EAEWE,EAAc,MACzBC,EACAH,IACqBI,EAAOD,EAAMJ,EAAeC,CAAS,CAAC,EAEhDK,EAAqBC,GAChCL,EACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOAK,CACF,EAEWC,GAAiB,MAC5BJ,EACAG,IACqBF,EAAOD,EAAME,EAAkBC,CAAY,CAAC,ED9B5D,IAAME,EAAM,CAACC,KAAqBC,IAChCC,EAAOF,EAAU,GAAGC,CAAM,EAGtBE,GAAUH,GACdA","names":["pg","pgcs","defaultPostgreSqlDatabase","getDatabaseNameOrDefault","connectionString","pools","usageCounter","getPool","connectionStringOrOptions","connectionString","poolOptions","database","getDatabaseNameOrDefault","lookupKey","key","updatePoolUsageCounter","pg","endPool","force","pool","onEndPool","error","endAllPools","defaultPostgreSqlDatabase","by","currentCounter","newCounter","postgresClient","connectionString","database","pool","getPool","endPool","execute","pool","handle","client","executeInTransaction","success","result","e","executeSQL","poolOrClient","sql","executeSQLInTransaction","executeSQLBatchInTransaction","sqls","firstOrNull","getResult","first","singleOrNull","single","mapRows","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","exists","format","tableExistsSQL","tableName","sql","tableExists","pool","exists","functionExistsSQL","functionName","functionExists","sql","sqlQuery","params","format","rawSql"]}
1
+ {"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/connections/transaction.ts","../src/core/sql/index.ts","../src/core/execute/execute.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 type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<ConnectorType extends string = string>\n extends WithSQLExecutor {\n type: ConnectorType;\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> {\n transaction: () => DatabaseTransaction<ConnectorType>;\n\n withTransaction: <Result = unknown>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<{ success: boolean; result: Result }>,\n ) => Promise<Result>;\n}\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n Result = unknown,\n>(\n transaction: DatabaseTransaction<ConnectorType>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<{ success: boolean; result: Result }>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = 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>,\n): DatabaseTransactionFactory<ConnectorType> => ({\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 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 open: () => 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 extends QueryResultRow = QueryResultRow,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n open: () => Promise<ConnectionType>;\n },\n) => {\n const { open } = options;\n const connection = await open();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\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 {\n sqlExecutor,\n transactionFactoryWithDbClient,\n type Connection,\n} 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 let client: pg.Client | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n return {\n type: NodePostgresConnectorType,\n connect: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(getClient, nodePostgresTransaction),\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: getClient }),\n };\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n let client: pg.PoolClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n return {\n type: NodePostgresConnectorType,\n connect: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(getClient, nodePostgresTransaction),\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: getClient }),\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 { sqlExecutor, type DatabaseTransaction } 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>(\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n): DatabaseTransaction<NodePostgresConnector> => ({\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(), { connect: () => getClient }),\n});\n","import pg from 'pg';\nimport {\n sqlExecutorInNewConnection,\n transactionFactoryWithNewConnection,\n type ConnectionPool,\n} from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresExplicitClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string;\n pool?: pg.Pool;\n}): NodePostgresNativePool => {\n const { connectionString, database, pool: ambientPool } = options;\n const pool = ambientPool\n ? ambientPool\n : 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 = async () => {\n if (!ambientPool) await endPool({ connectionString, database });\n };\n\n return {\n type: NodePostgresConnectorType,\n open,\n close,\n execute: sqlExecutorInNewConnection({ open }),\n ...transactionFactoryWithNewConnection(getConnection),\n };\n};\n\nexport const nodePostgresExplicitClientPool = (options: {\n connectionString: string;\n database?: string;\n client?: pg.Client;\n}): NodePostgresExplicitClientPool => {\n const { connectionString, database, client: ambientClient } = options;\n\n const getConnection = () => {\n const connect = ambientClient\n ? Promise.resolve(ambientClient)\n : Promise.resolve(new pg.Client({ connectionString, database })).then(\n async (client) => {\n await client.connect();\n return client;\n },\n );\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => (ambientClient ? Promise.resolve() : client.end()),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = async () => {\n if (!ambientClient) await endPool({ connectionString, database });\n };\n\n return {\n type: NodePostgresConnectorType,\n open,\n close,\n execute: sqlExecutorInNewConnection({ open }),\n ...transactionFactoryWithNewConnection(getConnection),\n };\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connectionString: string;\n database?: string;\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): NodePostgresExplicitClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n): NodePostgresNativePool | NodePostgresExplicitClientPool {\n const { connectionString, database } = options;\n\n if (('pooled' in options && options.pooled === false) || 'client' in options)\n return nodePostgresExplicitClientPool({\n connectionString,\n ...(database ? { database } : {}),\n ...('client' in options && options.client\n ? { client: options.client }\n : {}),\n });\n\n return nodePostgresNativePool({\n connectionString,\n ...(database ? { database } : {}),\n ...('pool' in options && options.pool ? { pool: options.pool } : {}),\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 NodePostgresConnector,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\nexport type PoolOptions = PostgresPoolOptions;\n\nexport const connectionPool = (_type: ConnectorType, options: PoolOptions) =>\n postgresPool(options);\n"],"mappings":"AAAA,OAAOA,MAAU,uBCuBV,IAAMC,EAAuB,MAIlCC,EACAC,IAGoB,CACpB,MAAMD,EAAY,MAAM,EAExB,GAAI,CACF,GAAM,CAAE,QAAAE,EAAS,OAAAC,CAAO,EAAI,MAAMF,EAAOD,CAAW,EAEpD,OAAIE,EAAS,MAAMF,EAAY,OAAO,EACjC,MAAMA,EAAY,SAAS,EAEzBG,CACT,OAASC,EAAG,CACV,YAAMJ,EAAY,SAAS,EACrBI,CACR,CACF,EAEaC,EAAiC,CAI5CC,EACAC,KAG+C,CAC/C,YAAa,IAAMA,EAAgBD,EAAQ,CAAC,EAC5C,gBAAkBL,GAChBF,EAAqBQ,EAAgBD,EAAQ,CAAC,EAAGL,CAAM,CAC3D,GAEMO,EAA0B,MAI9BC,EACAR,IACG,CACH,GAAI,CACF,OAAO,MAAMA,EAAO,CACtB,QAAE,CACA,MAAMQ,EAAW,MAAM,CACzB,CACF,EAEaC,EAGXJ,IACwD,CACxD,YAAa,IAAM,CACjB,IAAMG,EAAaH,EAAQ,EACrBN,EAAcS,EAAW,YAAY,EAE3C,MAAO,CACL,GAAGT,EACH,OAAQ,IACNQ,EAAwBC,EAAY,IAAMT,EAAY,OAAO,CAAC,EAChE,SAAU,IACRQ,EAAwBC,EAAY,IAAMT,EAAY,SAAS,CAAC,CACpE,CACF,EACA,gBAAkBC,GAAW,CAC3B,IAAMQ,EAAaH,EAAQ,EAC3B,OAAOE,EAAwBC,EAAY,IACzCA,EAAW,gBAAgBR,CAAM,CACnC,CACF,CACF,GClGA,OAAOU,MAAY,YAKZ,IAAMC,EAAM,CAACC,KAAqBC,IAChCH,EAAOE,EAAU,GAAGC,CAAM,EAGtBC,GA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K,CACnB,CACAV,EAAM,OAAOK,CAAS,CACxB,EAEaM,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGX,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACK,EAAWpB,CAAI,IAAMwB,EAAUJ,EAAWpB,CAAI,CAAC,CAC5E,EAEIqB,EAAM,CAACxB,EAA0BC,IACrC,GAAGD,CAAgB,IAAIC,GAAY6B,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,ECpOO,IAAMC,EAAeC,ECErB,IAAMC,GAAiB,CAACC,EAAsBC,IACnDC,EAAaD,CAAO","names":["pgcs","executeInTransaction","transaction","handle","success","result","e","transactionFactoryWithDbClient","connect","initTransaction","wrapInConnectionClosure","connection","transactionFactoryWithNewConnection","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","sql","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","open","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","getClient","options","NodePostgresConnectorType","client","error","sqlExecutor","nodePostgresSQLExecutor","NodePostgresConnectorType","nodePostgresClientConnection","options","connect","close","client","getClient","transactionFactoryWithDbClient","nodePostgresTransaction","sqlExecutor","nodePostgresSQLExecutor","nodePostgresPoolClientConnection","nodePostgresConnection","pg","nodePostgresNativePool","options","connectionString","database","ambientPool","pool","getPool","getConnection","nodePostgresConnection","client","open","NodePostgresConnectorType","endPool","sqlExecutorInNewConnection","transactionFactoryWithNewConnection","nodePostgresExplicitClientPool","ambientClient","connect","pg","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","getDatabaseNameOrDefault","lookupKey","key","updatePoolUsageCounter","force","onEndPool","error","endAllPools","defaultPostgreSqlDatabase","by","currentCounter","newCounter","postgresPool","nodePostgresPool","connectionPool","_type","options","postgresPool"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@event-driven-io/dumbo",
3
- "version": "0.4.1",
3
+ "version": "0.6.0",
4
4
  "description": "Dumbo - tools for dealing with PostgreSQL",
5
5
  "type": "module",
6
6
  "scripts": {