@event-driven-io/dumbo 0.5.0 → 0.7.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,a=new Map,g= 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 P(r,1),_nullishCoalesce(n.get(r), () => (n.set(r,new _pg2.default.Pool(o)).get(r)))},c= exports.endPool =async({connectionString:e,database:t,force:o})=>{t=_nullishCoalesce(t, () => (u(e)));let s=y(e,t),r=n.get(s);r&&(P(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)}},D= exports.endAllPools =()=>Promise.all([...n.entries()].map(([e,t])=>R(e,t))),y=(e,t)=>`${e}|${_nullishCoalesce(t, () => (l))}`,P=(e,t)=>{let o=_nullishCoalesce(a.get(e), () => (0)),s=o+t;return a.set(e,o+t),s};var B=(e,t)=>{let o=g({connectionString:e,database:t});return{connect:()=>o.connect(),close:()=>c({connectionString:e,database:t})}};var w=e=>e instanceof _pg2.default.Pool,W= exports.isPgClient =e=>e instanceof _pg2.default.Client,d= exports.isPgPoolClient =e=>"release"in e&&typeof e.release=="function",x= exports.execute =async(e,t)=>{let o=w(e)?await e.connect():e;try{return await t(o)}finally{w(e)&&d(o)&&o.release()}},f= exports.executeInTransaction =async(e,t)=>x(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}}),S= exports.executeSQL =async(e,t)=>x(e,o=>o.query(t)),X= exports.executeSQLInTransaction =async(e,t)=>(console.log(t),f(e,async o=>({success:!0,result:await o.query(t)}))),z= exports.executeSQLBatchInTransaction =async(e,...t)=>f(e,async o=>{for(let s of t)await o.query(s);return{success:!0,result:void 0}}),G= exports.firstOrNull =async e=>{let t=await e;return t.rows.length>0?_nullishCoalesce(t.rows[0], () => (null)):null},j= 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]},J= 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},L= 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]},V= exports.mapRows =async(e,t)=>(await e).rows.map(t),E= exports.toCamelCase =e=>e.replace(/_([a-z])/g,t=>_nullishCoalesce(_optionalChain([t, 'access', _ => _[1], 'optionalAccess', _2 => _2.toUpperCase, 'call', _3 => _3()]), () => (""))),Y= exports.mapToCamelCase =e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[E(o)]=e[o]);return t},i= exports.exists =async(e,t)=>(await L(S(e,t))).exists===!0;var _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var h=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 _pgformat = require('pg-format'); var _pgformat2 = _interopRequireDefault(_pgformat);var R=(e,...o)=>_pgformat2.default.call(void 0, e,...o),se= exports.rawSql =e=>e;var d=(e,o)=>({query:t=>g(n=>e.query(n,t),o),batchQuery:t=>g(n=>e.batchQuery(n,t),o),command:t=>g(n=>e.command(n,t),o),batchCommand:t=>g(n=>e.batchQuery(n,t),o)}),N= exports.sqlExecutorInNewConnection =e=>({query:o=>a(t=>t.execute.query(o),e),batchQuery:o=>a(t=>t.execute.batchQuery(o),e),command:o=>a(t=>t.execute.command(o),e),batchCommand:o=>a(t=>t.execute.batchCommand(o),e)}),g= exports.executeInNewDbClient =async(e,o)=>{let{connect:t,close:n}=o,s=await t();try{return await e(s)}catch(r){throw n&&await n(s,r),r}},a= exports.executeInNewConnection =async(e,o)=>{let t=await o.connection();try{return await e(t)}finally{await t.close()}};var M=e=>e!=null&&typeof e=="object"&&"success"in e?e:{success:!0,result:e},_= exports.executeInTransaction =async(e,o)=>{await e.begin();try{let{success:t,result:n}=M(await o(e));return t?await e.commit():await e.rollback(),n}catch(t){throw await e.rollback(),t}},D= exports.transactionFactoryWithDbClient =(e,o)=>({transaction:()=>o(e()),withTransaction:t=>_(o(e()),t)}),b=async(e,o)=>{try{return await o()}finally{await e.close()}},S= exports.transactionFactoryWithNewConnection =e=>({transaction:()=>{let o=e(),t=o.transaction();return{...t,commit:()=>b(o,()=>t.commit()),rollback:()=>b(o,()=>t.rollback())}},withTransaction:o=>{let t=e();return b(t,()=>t.withTransaction(o))}});var w=e=>{let{type:o,connect:t,close:n,initTransaction:s,executor:r}=e,c=null,l=async()=>await _asyncNullishCoalesce(c, async () => ((c=await t))),y={type:o,open:l,close:()=>c?n(c):Promise.resolve(),...D(l,s(()=>y)),execute:d(r(),{connect:l})};return y};var u=e=>{let{type:o,getConnection:t}=e,n="connection"in e?e.connection:()=>Promise.resolve(t()),s="withConnection"in e?e.withConnection:y=>a(y,{connection:n}),r="close"in e?e.close:()=>Promise.resolve(),c="execute"in e?e.execute:N({connection:n}),l="transaction"in e&&"withTransaction"in e?{transaction:e.transaction,withTransaction:e.withTransaction}:S(t);return{type:o,connection:n,withConnection:s,close:r,execute:c,...l}};var Te=async(e,o)=>(await e).rows.map(o),$= exports.toCamelCase =e=>e.replace(/_([a-z])/g,o=>_nullishCoalesce(_optionalChain([o, 'access', _2 => _2[1], 'optionalAccess', _3 => _3.toUpperCase, 'call', _4 => _4()]), () => (""))),fe= exports.mapToCamelCase =e=>{let o={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(o[$(t)]=e[t]);return o};var De=async e=>{let o=await e;return o.rows.length>0?_nullishCoalesce(o.rows[0], () => (null)):null},Se= 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]},he= 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},B= 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 B(e)).exists===!0;var m="postgres",H= exports.tableExistsSQL =e=>R(`
2
2
  SELECT EXISTS (
3
3
  SELECT FROM pg_tables
4
4
  WHERE tablename = %L
5
- ) AS exists;`,e),re= exports.tableExists =async(e,t)=>i(e,h(t)),b= exports.functionExistsSQL =e=>p(`
5
+ ) AS exists;`,e),_e= exports.tableExists =async(e,o)=>Q(e.execute.query(H(o))),U= 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),ne= exports.functionExists =async(e,t)=>i(e,b(t));var p=(e,...t)=>_pgformat2.default.call(void 0, e,...t),pe= exports.rawSql =e=>e;exports.defaultPostgreSqlDatabase = l; exports.endAllPools = D; exports.endPool = c; exports.execute = x; exports.executeInTransaction = f; exports.executeSQL = S; exports.executeSQLBatchInTransaction = z; exports.executeSQLInTransaction = X; exports.exists = i; exports.first = j; exports.firstOrNull = G; exports.functionExists = ne; exports.functionExistsSQL = b; exports.getDatabaseNameOrDefault = u; exports.getPool = g; exports.isPgClient = W; exports.isPgPool = w; exports.isPgPoolClient = d; exports.mapRows = V; exports.mapToCamelCase = Y; exports.onEndPool = R; exports.postgresClient = B; exports.rawSql = pe; exports.single = L; exports.singleOrNull = J; exports.sql = p; exports.tableExists = re; exports.tableExistsSQL = h; exports.toCamelCase = E;
11
+ `,e),$e= exports.functionExists =async(e,o)=>Q(e.execute.query(U(o)));var T=e=>_nullishCoalesce(_pgconnectionstring2.default.parse(e).database, () => (m));var _pg = require('pg'); var _pg2 = _interopRequireDefault(_pg);var h=e=>e instanceof _pg2.default.Pool,no= exports.isNodePostgresClient =e=>e instanceof _pg2.default.Client,j= exports.isNodePostgresPoolClient =e=>"release"in e&&typeof e.release=="function",so= exports.nodePostgresExecute =async(e,o)=>{let t=h(e)?await e.connect():e;try{return await o(t)}finally{h(e)&&j(t)&&t.release()}},p= exports.nodePostgresSQLExecutor =()=>({type:i,query:x,batchQuery:x,command:x,batchCommand:x});async function x(e,o){let t=Array.isArray(o)?o:[o],n=Array(t.length);for(let s=0;s<t.length;s++){let r=await e.query(t[s]);n[s]={rowCount:r.rowCount,rows:r.rows}}return Array.isArray(o)?n:n[0]}var f=e=>(o,t)=>({connection:e(),type:i,begin:async()=>{await(await o).query("BEGIN")},commit:async()=>{let n=await o;await n.query("COMMIT"),_optionalChain([t, 'optionalAccess', _5 => _5.close])&&await _optionalChain([t, 'optionalAccess', _6 => _6.close, 'call', _7 => _7(n)])},rollback:async n=>{let s=await o;await s.query("ROLLBACK"),_optionalChain([t, 'optionalAccess', _8 => _8.close])&&await _optionalChain([t, 'optionalAccess', _9 => _9.close, 'call', _10 => _10(s,n)])},execute:d(p(),{connect:()=>o})});var i="PostgreSQL:pg",z= exports.nodePostgresClientConnection =e=>{let{connect:o,close:t}=e;return w({type:i,connect:o,close:t,initTransaction:n=>f(n),executor:p})},G= exports.nodePostgresPoolClientConnection =e=>{let{connect:o,close:t}=e;return w({type:i,connect:o,close:t,initTransaction:n=>f(n),executor:p})};function P(e){return e.type==="Client"?z(e):G(e)}var K=e=>{let{connectionString:o,database:t}=e,n=ee({connectionString:o,database:t}),s=()=>P({type:"PoolClient",connect:n.connect(),close:l=>Promise.resolve(l.release())});return u({type:i,connection:()=>Promise.resolve(s()),close:()=>oe({connectionString:o,database:t}),getConnection:s})},J= exports.nodePostgresAmbientNativePool =e=>{let{pool:o}=e;return u({type:i,getConnection:()=>P({type:"PoolClient",connect:o.connect(),close:t=>Promise.resolve(t.release())})})},V= exports.nodePostgresAmbientConnectionPool =e=>{let{connection:o}=e;return u({type:i,getConnection:()=>o,execute:o.execute,transaction:()=>o.transaction(),withTransaction:t=>o.withTransaction(t)})},Y= exports.nodePostgresClientPool =e=>{let{connectionString:o,database:t}=e;return u({type:i,getConnection:()=>{let n=Promise.resolve(new _pg2.default.Client({connectionString:o,database:t})).then(async s=>(await s.connect(),s));return P({type:"Client",connect:n,close:s=>s.end()})}})},Z= exports.nodePostgresAmbientClientPool =e=>{let{client:o}=e,t=()=>{let r=Promise.resolve(o);return P({type:"Client",connect:r,close:()=>Promise.resolve()})};return u({type:i,connection:()=>Promise.resolve(t()),close:()=>Promise.resolve(),getConnection:t})};function v(e){let{connectionString:o,database:t}=e;return"client"in e&&e.client?Z({client:e.client}):"pooled"in e&&e.pooled===!1?Y({connectionString:o,database:t}):"connection"in e&&e.connection?V({connection:e.connection}):"pool"in e&&e.pool?J({pool:e.pool}):K({connectionString:o,database:t})}var C=new Map,L=new Map,ee= exports.getPool =e=>{let o=typeof e=="string"?e:e.connectionString,t=typeof e=="string"?{connectionString:o}:e,n=_nullishCoalesce(t.database, () => ((t.connectionString?T(t.connectionString):void 0))),s=k(o,n);return A(s,1),_nullishCoalesce(C.get(s), () => (C.set(s,new _pg2.default.Pool(t)).get(s)))},oe= exports.endPool =async({connectionString:e,database:o,force:t})=>{o=_nullishCoalesce(o, () => (T(e)));let n=k(e,o),s=C.get(n);s&&(A(n,-1)<=0||t===!0)&&await q(n,s)},q= exports.onEndPool =async(e,o)=>{try{await o.end()}catch(t){console.log(`Error while closing the connection pool: ${e}`),console.log(t)}C.delete(e)},To= exports.endAllPools =()=>Promise.all([...C.entries()].map(([e,o])=>q(e,o))),k=(e,o)=>`${e}|${_nullishCoalesce(o, () => (m))}`,A=(e,o)=>{let t=_nullishCoalesce(L.get(e), () => (0)),n=t+o;return L.set(e,t+o),n};var F=v;var te=e=>F(e),Wo= exports.dumbo =e=>te(e);exports.NodePostgresConnectorType = i; exports.connectionPool = te; exports.createConnection = w; exports.createConnectionPool = u; exports.defaultPostgreSqlDatabase = m; exports.dumbo = Wo; exports.endAllPools = To; exports.endPool = oe; exports.executeInNewConnection = a; exports.executeInNewDbClient = g; exports.executeInTransaction = _; exports.exists = Q; exports.first = Se; exports.firstOrNull = De; exports.functionExists = $e; exports.functionExistsSQL = U; exports.getDatabaseNameOrDefault = T; exports.getPool = ee; exports.isNodePostgresClient = no; exports.isNodePostgresNativePool = h; exports.isNodePostgresPoolClient = j; exports.mapRows = Te; exports.mapToCamelCase = fe; exports.nodePostgresAmbientClientPool = Z; exports.nodePostgresAmbientConnectionPool = V; exports.nodePostgresAmbientNativePool = J; exports.nodePostgresClientConnection = z; exports.nodePostgresClientPool = Y; exports.nodePostgresConnection = P; exports.nodePostgresExecute = so; exports.nodePostgresNativePool = K; exports.nodePostgresPool = v; exports.nodePostgresPoolClientConnection = G; exports.nodePostgresSQLExecutor = p; exports.nodePostgresTransaction = f; exports.onEndPool = q; exports.postgresPool = F; exports.rawSql = se; exports.single = B; exports.singleOrNull = he; exports.sql = R; exports.sqlExecutor = d; exports.sqlExecutorInNewConnection = N; exports.tableExists = _e; exports.tableExistsSQL = H; exports.toCamelCase = $; exports.transactionFactoryWithDbClient = D; exports.transactionFactoryWithNewConnection = S;
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","isPgPool","poolOrClient","isPgClient","isPgPoolClient","execute","handle","client","executeInTransaction","success","result","e","executeSQL","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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EACZ,OAAO,UAAU,eAAe,KAAKA,EAAKvC,CAAG,IAC/CwC,EAAOL,EAAYnC,CAAG,CAAC,EAAIuC,EAAIvC,CAAG,GAGtC,OAAOwC,CACT,EAIaC,EAAS,MAAOrC,EAAeoB,KAC3B,MAAMQ,EAAOT,EAAiCnB,EAAMoB,CAAG,CAAC,GAEzD,SAAW,GC7K3B,OAAOkB,MAAY,YCAnB,MAAe,KAKR,IAAMC,EAAkBC,GAC7BpB,EACE;AAAA;AAAA;AAAA;AAAA,gBAKAoB,CACF,EAEWC,GAAc,MACzBzC,EACAwC,IACqBH,EAAOrC,EAAMuC,EAAeC,CAAS,CAAC,EAEhDE,EAAqBC,GAChCvB,EACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOAuB,CACF,EAEWC,GAAiB,MAC5B5C,EACA2C,IACqBN,EAAOrC,EAAM0C,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 pg from 'pg';\nimport type { SQL } from '../sql';\n\nexport const isPgPool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isPgClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isPgPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const execute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isPgPool(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 (isPgPool(poolOrClient) && isPgPoolClient(client)) client.release();\n }\n};\n\nexport const executeInTransaction = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (\n client: pg.PoolClient | pg.Client,\n ) => Promise<{ success: boolean; result: Result }>,\n): Promise<Result> =>\n execute(poolOrClient, 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 | pg.Client,\n sql: SQL,\n): Promise<pg.QueryResult<Result>> =>\n execute(poolOrClient, (client) => client.query<Result>(sql));\n\nexport const executeSQLInTransaction = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool | pg.PoolClient | pg.Client,\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 | pg.PoolClient | pg.Client,\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/sql/index.ts","../src/core/execute/execute.ts","../src/core/connections/transaction.ts","../src/core/connections/connection.ts","../src/core/connections/pool.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"names":["pgcs","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","toTransactionResult","transactionResult","executeInTransaction","transaction","success","result","e","transactionFactoryWithDbClient","initTransaction","wrapInConnectionClosure","transactionFactoryWithNewConnection","createConnection","type","executor","getClient","typedConnection","createConnectionPool","pool","getConnection","withConnection","execute","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","tableExists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pg","isNodePostgresNativePool","poolOrClient","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","results","i","nodePostgresTransaction","nodePostgresClientConnection","nodePostgresPoolClientConnection","nodePostgresConnection","nodePostgresNativePool","database","getPool","endPool","nodePostgresAmbientNativePool","nodePostgresAmbientConnectionPool","nodePostgresClientPool","nodePostgresAmbientClientPool","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","lookupKey","updatePoolUsageCounter","force","onEndPool","endAllPools","by","currentCounter","newCounter","postgresPool","connectionPool","dumbo"],"mappings":"AAAA,OAAOA,MAAU,uBCAjB,OAAOC,MAAY,YAKZ,IAAMC,EAAM,CAACC,KAAqBC,IAChCH,EAAOE,EAAU,GAAGC,CAAM,EAGtBC,GAAUF,GACdA,ECoCF,IAAMG,EAAc,CAIzBA,EAEAC,KAIiB,CACjB,MAAQL,GACNM,EAAsBC,GAAWH,EAAY,MAAMG,EAAQP,CAAG,EAAGK,CAAO,EAC1E,WAAaG,GACXF,EACGC,GAAWH,EAAY,WAAWG,EAAQC,CAAI,EAC/CH,CACF,EACF,QAAUL,GACRM,EAAsBC,GAAWH,EAAY,QAAQG,EAAQP,CAAG,EAAGK,CAAO,EAC5E,aAAeG,GACbF,EACGC,GAAWH,EAAY,WAAWG,EAAQC,CAAI,EAC/CH,CACF,CACJ,GAEaI,EAEXJ,IAEkB,CAClB,MAAQL,GACNU,EACGC,GAAeA,EAAW,QAAQ,MAAMX,CAAG,EAC5CK,CACF,EACF,WAAaG,GACXE,EACGC,GAAeA,EAAW,QAAQ,WAAWH,CAAI,EAClDH,CACF,EACF,QAAUL,GACRU,EACGC,GAAeA,EAAW,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hD,OAAAa,EAAuBD,EAAW,CAAC,EAGjCJ,EAAM,IAAII,CAAS,GACnBJ,EAAM,IAAII,EAAW,IAAI7B,EAAG,KAAK4B,CAAW,CAAC,EAAE,IAAIC,CAAS,CAEhE,EAEaV,GAAU,MAAO,CAC5B,iBAAApB,EACA,SAAAkB,EACA,MAAAc,CACF,IAIqB,CACnBd,EAAWA,GAAYnB,EAAyBC,CAAgB,EAChE,IAAM8B,EAAY5C,EAAIc,EAAkBkB,CAAQ,EAE1C7C,EAAOqD,EAAM,IAAII,CAAS,EAC5BzD,IAAS0D,EAAuBD,EAAW,EAAE,GAAK,GAAKE,IAAU,KACnE,MAAMC,EAAUH,EAAWzD,CAAI,CAEnC,EAEa4D,EAAY,MAAOH,EAAmBzD,IAAkB,CACnE,GAAI,CACF,MAAMA,EAAK,IAAI,CACjB,OAASlB,EAAO,CACd,QAAQ,IAAI,4CAA4C2E,CAAS,EAAE,EACnE,QAAQ,IAAI3E,CAAK,CACnB,CACAuE,EAAM,OAAOI,CAAS,CACxB,EAEaI,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGR,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACI,EAAWzD,CAAI,IAAM4D,EAAUH,EAAWzD,CAAI,CAAC,CAC5E,EAEIa,EAAM,CAACc,EAA0BkB,IACrC,GAAGlB,CAAgB,IAAIkB,GAAY1B,CAAyB,GAExDuC,EAAyB,CAACD,EAAmBK,IAAuB,CACxE,IAAMC,EAAiBT,EAAa,IAAIG,CAAS,GAAK,EAChDO,EAAaD,EAAiBD,EAEpC,OAAAR,EAAa,IAAIG,EAAWM,EAAiBD,CAAE,EAExCE,CACT,ECpSO,IAAMC,EAAeb,ECOrB,IAAMc,GACX9F,GAGA6F,EAAa7F,CAAyC,EAE3C+F,GACX/F,GACU8F,GAAe9F,CAAO","sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import format from 'pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n connection: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n connection: () => Promise<ConnectionType>;\n },\n) => {\n const connection = await options.connection();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor {\n type: ConnectorType;\n connection: Connection<ConnectorType, DbClient>;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n> {\n transaction: () => DatabaseTransaction<ConnectorType>;\n\n withTransaction: <Result = never>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<TransactionResult<Result> | Result>,\n ) => Promise<Result>;\n}\n\nexport type TransactionResult<Result> = { success: boolean; result: Result };\n\nconst toTransactionResult = <Result>(\n transactionResult: TransactionResult<Result> | Result,\n): TransactionResult<Result> =>\n transactionResult !== undefined &&\n transactionResult !== null &&\n typeof transactionResult === 'object' &&\n 'success' in transactionResult\n ? transactionResult\n : { success: true, result: transactionResult };\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n Result = void,\n>(\n transaction: DatabaseTransaction<ConnectorType>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<TransactionResult<Result> | Result>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = toTransactionResult(await handle(transaction));\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType>,\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 {\n sqlExecutor,\n type DbSQLExecutor,\n type WithSQLExecutor,\n} from '../execute';\nimport {\n transactionFactoryWithDbClient,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface Connection<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor,\n DatabaseTransactionFactory<ConnectorType> {\n type: ConnectorType;\n open: () => Promise<DbClient>;\n close: () => Promise<void>;\n}\n\nexport interface ConnectionFactory<\n ConnectionType extends Connection = Connection,\n> {\n connection: () => Promise<ConnectionType>;\n\n withConnection: <Result = unknown>(\n handle: (connection: ConnectionType) => Promise<Result>,\n ) => Promise<Result>;\n}\n\nexport type CreateConnectionOptions<\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n> = {\n type: ConnectorType;\n connect: Promise<DbClient>;\n close: (client: DbClient) => Promise<void>;\n initTransaction: (\n connection: () => ConnectionType,\n ) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>;\n executor: () => Executor;\n};\n\nexport const createConnection = <\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n>(\n options: CreateConnectionOptions<\n ConnectorType,\n DbClient,\n ConnectionType,\n Executor\n >,\n): ConnectionType => {\n const { type, connect, close, initTransaction, executor } = options;\n\n let client: DbClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n const connection: Connection<ConnectorType, DbClient> = {\n type: type,\n open: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(\n getClient,\n initTransaction(() => typedConnection),\n ),\n execute: sqlExecutor(executor(), { connect: getClient }),\n };\n\n const typedConnection = connection as ConnectionType;\n\n return typedConnection;\n};\n","import {\n executeInNewConnection,\n sqlExecutorInNewConnection,\n type WithSQLExecutor,\n} from '../execute';\nimport { type Connection, type ConnectionFactory } from './connection';\nimport {\n transactionFactoryWithNewConnection,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface ConnectionPool<ConnectionType extends Connection = Connection>\n extends WithSQLExecutor,\n ConnectionFactory<ConnectionType>,\n DatabaseTransactionFactory<ConnectionType['type']> {\n type: ConnectionType['type'];\n close: () => Promise<void>;\n}\n\nexport type ConnectionPoolFactory<\n ConnectionPoolType extends ConnectionPool = ConnectionPool,\n ConnectionPoolOptions = unknown,\n> = (options: ConnectionPoolOptions) => ConnectionPoolType;\n\nexport const createConnectionPool = <\n ConnectionType extends Connection,\n ConnectionPoolType extends ConnectionPool<ConnectionType>,\n>(\n pool: Pick<ConnectionPool<ConnectionType>, 'type'> &\n Partial<ConnectionPool<ConnectionType>> & {\n getConnection: () => ConnectionType;\n },\n): ConnectionPoolType => {\n const { type, getConnection } = pool;\n\n const connection =\n 'connection' in pool\n ? pool.connection\n : () => Promise.resolve(getConnection());\n\n const withConnection =\n 'withConnection' in pool\n ? pool.withConnection\n : <Result>(handle: (connection: ConnectionType) => Promise<Result>) =>\n executeInNewConnection<ConnectionType, Result>(handle, {\n connection,\n });\n\n const close = 'close' in pool ? pool.close : () => Promise.resolve();\n\n const execute =\n 'execute' in pool\n ? pool.execute\n : sqlExecutorInNewConnection({ connection });\n\n const transaction =\n 'transaction' in pool && 'withTransaction' in pool\n ? {\n transaction: pool.transaction,\n withTransaction: pool.withTransaction,\n }\n : transactionFactoryWithNewConnection(getConnection);\n\n const result: ConnectionPool<ConnectionType> = {\n type,\n connection,\n withConnection,\n close,\n execute,\n ...transaction,\n };\n\n return result as ConnectionPoolType;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport { createConnection, type Connection } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import {\n sqlExecutor,\n type Connection,\n type DatabaseTransaction,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction =\n <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(\n connection: () => Connection<NodePostgresConnector, DbClient>,\n ) =>\n (\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n ): DatabaseTransaction<NodePostgresConnector> => ({\n connection: connection(),\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), {\n connect: () => getClient,\n }),\n });\n","import pg from 'pg';\nimport { createConnectionPool, type ConnectionPool } from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresConnector,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresAmbientClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport type NodePostgresAmbientConnectionPool = ConnectionPool<\n NodePostgresPoolClientConnection | NodePostgresClientConnection\n>;\n\nexport type NodePostgresPool =\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresNativePool => {\n const { connectionString, database } = options;\n const pool = getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = () => endPool({ connectionString, database });\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport const nodePostgresAmbientNativePool = (options: {\n pool: pg.Pool;\n}): NodePostgresNativePool => {\n const { pool } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n }),\n });\n};\n\nexport const nodePostgresAmbientConnectionPool = (options: {\n connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;\n}): NodePostgresAmbientConnectionPool => {\n const { connection } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => connection,\n execute: connection.execute,\n transaction: () => connection.transaction(),\n withTransaction: (handle) => connection.withTransaction(handle),\n });\n};\n\nexport const nodePostgresClientPool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresAmbientClientPool => {\n const { connectionString, database } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => {\n const connect = Promise.resolve(\n new pg.Client({ connectionString, database }),\n ).then(async (client) => {\n await client.connect();\n return client;\n });\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => client.end(),\n });\n },\n });\n};\n\nexport const nodePostgresAmbientClientPool = (options: {\n client: pg.Client;\n}): NodePostgresAmbientClientPool => {\n const { client } = options;\n\n const getConnection = () => {\n const connect = Promise.resolve(client);\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: () => Promise.resolve(),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = () => Promise.resolve();\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n connection:\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n pooled?: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresAmbientClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n):\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool {\n const { connectionString, database } = options;\n\n if ('client' in options && options.client)\n return nodePostgresAmbientClientPool({ client: options.client });\n\n if ('pooled' in options && options.pooled === false)\n return nodePostgresClientPool({ connectionString, database });\n\n if ('connection' in options && options.connection)\n return nodePostgresAmbientConnectionPool({\n connection: options.connection,\n });\n\n if ('pool' in options && options.pool)\n return nodePostgresAmbientNativePool({ pool: options.pool });\n\n return nodePostgresNativePool({\n connectionString,\n database,\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnector,\n type NodePostgresPool,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport type PostgresPool = NodePostgresPool;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPool,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\n\nexport type PoolOptions = {\n connector?: ConnectorType;\n};\n\nexport type DumboOptions = PoolOptions & PostgresPoolOptions;\nexport type Dumbo = PostgresPool;\n\nexport const connectionPool = <PoolOptionsType extends DumboOptions>(\n options: PoolOptionsType,\n) =>\n // TODO: this should have the pattern matching and verification\n postgresPool(options as unknown as PostgresPoolOptions);\n\nexport const dumbo = <DumboOptionsType extends DumboOptions = DumboOptions>(\n options: DumboOptionsType,\n): Dumbo => connectionPool(options);\n"]}
package/dist/index.d.cts CHANGED
@@ -1,14 +1,207 @@
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;
6
7
  }
7
- declare const postgresClient: (connectionString: string, database?: string) => PostgresClient;
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
+ connection: () => 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>(handle: (connection: ConnectionType) => Promise<Result>, options: {
60
+ connection: () => Promise<ConnectionType>;
61
+ }) => Promise<Result>;
62
+
63
+ interface DatabaseTransaction<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor {
64
+ type: ConnectorType;
65
+ connection: Connection<ConnectorType, DbClient>;
66
+ begin: () => Promise<void>;
67
+ commit: () => Promise<void>;
68
+ rollback: (error?: unknown) => Promise<void>;
69
+ }
70
+ interface DatabaseTransactionFactory<ConnectorType extends string = string> {
71
+ transaction: () => DatabaseTransaction<ConnectorType>;
72
+ withTransaction: <Result = never>(handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
73
+ }
74
+ type TransactionResult<Result> = {
75
+ success: boolean;
76
+ result: Result;
77
+ };
78
+ declare const executeInTransaction: <ConnectorType extends string = string, Result = void>(transaction: DatabaseTransaction<ConnectorType>, handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
79
+ declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>) => DatabaseTransactionFactory<ConnectorType>;
80
+ declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection<string, unknown> = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType['type']>;
81
+
82
+ interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
83
+ type: ConnectorType;
84
+ open: () => Promise<DbClient>;
85
+ close: () => Promise<void>;
86
+ }
87
+ interface ConnectionFactory<ConnectionType extends Connection = Connection> {
88
+ connection: () => Promise<ConnectionType>;
89
+ withConnection: <Result = unknown>(handle: (connection: ConnectionType) => Promise<Result>) => Promise<Result>;
90
+ }
91
+ type CreateConnectionOptions<ConnectorType extends string = string, DbClient = unknown, ConnectionType extends Connection<ConnectorType, DbClient> = Connection<ConnectorType, DbClient>, Executor extends DbSQLExecutor = DbSQLExecutor> = {
92
+ type: ConnectorType;
93
+ connect: Promise<DbClient>;
94
+ close: (client: DbClient) => Promise<void>;
95
+ initTransaction: (connection: () => ConnectionType) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>;
96
+ executor: () => Executor;
97
+ };
98
+ declare const createConnection: <ConnectorType extends string = string, DbClient = unknown, ConnectionType extends Connection<ConnectorType, DbClient> = Connection<ConnectorType, DbClient>, Executor extends DbSQLExecutor<string, unknown> = DbSQLExecutor<string, unknown>>(options: CreateConnectionOptions<ConnectorType, DbClient, ConnectionType, Executor>) => ConnectionType;
99
+
100
+ interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, ConnectionFactory<ConnectionType>, DatabaseTransactionFactory<ConnectionType['type']> {
101
+ type: ConnectionType['type'];
102
+ close: () => Promise<void>;
103
+ }
104
+ type ConnectionPoolFactory<ConnectionPoolType extends ConnectionPool = ConnectionPool, ConnectionPoolOptions = unknown> = (options: ConnectionPoolOptions) => ConnectionPoolType;
105
+ declare const createConnectionPool: <ConnectionType extends Connection<string, unknown>, ConnectionPoolType extends ConnectionPool<ConnectionType>>(pool: Pick<ConnectionPool<ConnectionType>, 'type'> & Partial<ConnectionPool<ConnectionType>> & {
106
+ getConnection: () => ConnectionType;
107
+ }) => ConnectionPoolType;
8
108
 
9
109
  declare const defaultPostgreSqlDatabase = "postgres";
10
- declare const getDatabaseNameOrDefault: (connectionString: string) => string;
110
+ declare const tableExistsSQL: (tableName: string) => SQL;
111
+ declare const tableExists: (pool: ConnectionPool, tableName: string) => Promise<boolean>;
112
+ declare const functionExistsSQL: (functionName: string) => SQL;
113
+ declare const functionExists: (pool: ConnectionPool, tableName: string) => Promise<boolean>;
114
+
115
+ declare const NodePostgresConnectorType = "PostgreSQL:pg";
116
+ type NodePostgresConnector = 'PostgreSQL:pg';
117
+ type NodePostgresClient = pg.PoolClient | pg.Client;
118
+ type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;
119
+ type NodePostgresClientConnection = Connection<NodePostgresConnector, pg.Client>;
120
+ type NodePostgresPoolClientConnection = Connection<NodePostgresConnector, pg.PoolClient>;
121
+ type NodePostgresConnection = NodePostgresPoolClientConnection | NodePostgresClientConnection;
122
+ type NodePostgresPoolClientOptions = {
123
+ type: 'PoolClient';
124
+ connect: Promise<pg.PoolClient>;
125
+ close: (client: pg.PoolClient) => Promise<void>;
126
+ };
127
+ type NodePostgresClientOptions = {
128
+ type: 'Client';
129
+ connect: Promise<pg.Client>;
130
+ close: (client: pg.Client) => Promise<void>;
131
+ };
132
+ declare const nodePostgresClientConnection: (options: NodePostgresClientOptions) => NodePostgresClientConnection;
133
+ declare const nodePostgresPoolClientConnection: (options: NodePostgresPoolClientOptions) => NodePostgresPoolClientConnection;
134
+ declare function nodePostgresConnection(options: NodePostgresPoolClientOptions): NodePostgresPoolClientConnection;
135
+ declare function nodePostgresConnection(options: NodePostgresClientOptions): NodePostgresClientConnection;
11
136
 
137
+ type NodePostgresNativePool = ConnectionPool<NodePostgresPoolClientConnection>;
138
+ type NodePostgresAmbientClientPool = ConnectionPool<NodePostgresClientConnection>;
139
+ type NodePostgresAmbientConnectionPool = ConnectionPool<NodePostgresPoolClientConnection | NodePostgresClientConnection>;
140
+ type NodePostgresPool = NodePostgresNativePool | NodePostgresAmbientClientPool | NodePostgresAmbientConnectionPool;
141
+ declare const nodePostgresNativePool: (options: {
142
+ connectionString: string;
143
+ database?: string | undefined;
144
+ }) => NodePostgresNativePool;
145
+ declare const nodePostgresAmbientNativePool: (options: {
146
+ pool: pg.Pool;
147
+ }) => NodePostgresNativePool;
148
+ declare const nodePostgresAmbientConnectionPool: (options: {
149
+ connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;
150
+ }) => NodePostgresAmbientConnectionPool;
151
+ declare const nodePostgresClientPool: (options: {
152
+ connectionString: string;
153
+ database?: string | undefined;
154
+ }) => NodePostgresAmbientClientPool;
155
+ declare const nodePostgresAmbientClientPool: (options: {
156
+ client: pg.Client;
157
+ }) => NodePostgresAmbientClientPool;
158
+ type NodePostgresPoolPooledOptions = {
159
+ connector?: NodePostgresConnector;
160
+ connectionString: string;
161
+ database?: string;
162
+ pooled: true;
163
+ pool: pg.Pool;
164
+ } | {
165
+ connector?: NodePostgresConnector;
166
+ connectionString: string;
167
+ database?: string;
168
+ pool: pg.Pool;
169
+ } | {
170
+ connector?: NodePostgresConnector;
171
+ connectionString: string;
172
+ database?: string;
173
+ pooled: true;
174
+ } | {
175
+ connector?: NodePostgresConnector;
176
+ connectionString: string;
177
+ database?: string;
178
+ };
179
+ type NodePostgresPoolNotPooledOptions = {
180
+ connector?: NodePostgresConnector;
181
+ connectionString: string;
182
+ database?: string;
183
+ pooled: false;
184
+ client: pg.Client;
185
+ } | {
186
+ connector?: NodePostgresConnector;
187
+ connectionString: string;
188
+ database?: string;
189
+ client: pg.Client;
190
+ } | {
191
+ connector?: NodePostgresConnector;
192
+ connectionString: string;
193
+ database?: string;
194
+ pooled: false;
195
+ } | {
196
+ connector?: NodePostgresConnector;
197
+ connectionString: string;
198
+ database?: string;
199
+ connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;
200
+ pooled?: false;
201
+ };
202
+ type NodePostgresPoolOptions = NodePostgresPoolPooledOptions | NodePostgresPoolNotPooledOptions;
203
+ declare function nodePostgresPool(options: NodePostgresPoolPooledOptions): NodePostgresNativePool;
204
+ declare function nodePostgresPool(options: NodePostgresPoolNotPooledOptions): NodePostgresAmbientClientPool;
12
205
  declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
13
206
  declare const endPool: ({ connectionString, database, force, }: {
14
207
  connectionString: string;
@@ -18,38 +211,30 @@ declare const endPool: ({ connectionString, database, force, }: {
18
211
  declare const onEndPool: (lookupKey: string, pool: pg.Pool) => Promise<void>;
19
212
  declare const endAllPools: () => Promise<void[]>;
20
213
 
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>;
214
+ type NodePostgresTransaction = DatabaseTransaction<NodePostgresConnector>;
215
+ declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(connection: () => Connection<NodePostgresConnector, DbClient>) => (getClient: Promise<DbClient>, options?: {
216
+ close: (client: DbClient, error?: unknown) => Promise<void>;
217
+ } | undefined) => DatabaseTransaction<NodePostgresConnector>;
25
218
 
26
- type SQL = string & {
27
- __brand: 'sql';
28
- };
29
- declare const sql: (sqlQuery: string, ...params: unknown[]) => SQL;
30
- declare const rawSql: (sqlQuery: string) => SQL;
219
+ declare const isNodePostgresNativePool: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Pool;
220
+ declare const isNodePostgresClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Client;
221
+ declare const isNodePostgresPoolClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.PoolClient;
222
+ declare const nodePostgresExecute: <Result = void>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, handle: (client: pg.PoolClient | pg.Client) => Promise<Result>) => Promise<Result>;
223
+ type NodePostgresSQLExecutor = DbSQLExecutor<NodePostgresConnector, NodePostgresClient>;
224
+ declare const nodePostgresSQLExecutor: () => NodePostgresSQLExecutor;
31
225
 
32
- declare const isPgPool: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Pool;
33
- declare const isPgClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Client;
34
- declare const isPgPoolClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.PoolClient;
35
- declare const execute: <Result = void>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, handle: (client: pg.PoolClient | pg.Client) => Promise<Result>) => Promise<Result>;
36
- declare const executeInTransaction: <Result = void>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, handle: (client: pg.PoolClient | pg.Client) => Promise<{
37
- success: boolean;
38
- result: Result;
39
- }>) => Promise<Result>;
40
- declare const executeSQL: <Result extends pg.QueryResultRow = pg.QueryResultRow>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, sql: SQL) => Promise<pg.QueryResult<Result>>;
41
- declare const executeSQLInTransaction: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool | pg.PoolClient | pg.Client, sql: SQL) => Promise<pg.QueryResult<Result>>;
42
- declare const executeSQLBatchInTransaction: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool | pg.PoolClient | pg.Client, ...sqls: SQL[]) => Promise<undefined>;
43
- declare const firstOrNull: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result | null>;
44
- declare const first: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result>;
45
- declare const singleOrNull: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result | null>;
46
- declare const single: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result>;
47
- declare const mapRows: <Result extends pg.QueryResultRow = pg.QueryResultRow, Mapped = unknown>(getResult: Promise<pg.QueryResult<Result>>, map: (row: Result) => Mapped) => Promise<Mapped[]>;
48
- declare const toCamelCase: (snakeStr: string) => string;
49
- declare const mapToCamelCase: <T extends Record<string, unknown>>(obj: T) => T;
50
- type ExistsSQLQueryResult = {
51
- exists: boolean;
226
+ type PostgresConnector = NodePostgresConnector;
227
+ type PostgresPoolOptions = NodePostgresPoolOptions;
228
+ type PostgresPool = NodePostgresPool;
229
+ declare const postgresPool: typeof nodePostgresPool;
230
+
231
+ type ConnectorType = PostgresConnector;
232
+ type PoolOptions = {
233
+ connector?: ConnectorType;
52
234
  };
53
- declare const exists: (pool: pg.Pool, sql: SQL) => Promise<boolean>;
235
+ type DumboOptions = PoolOptions & PostgresPoolOptions;
236
+ type Dumbo = PostgresPool;
237
+ declare const connectionPool: <PoolOptionsType extends DumboOptions>(options: PoolOptionsType) => NodePostgresNativePool;
238
+ declare const dumbo: <DumboOptionsType extends DumboOptions = DumboOptions>(options: DumboOptionsType) => Dumbo;
54
239
 
55
- export { type ExistsSQLQueryResult, type PostgresClient, type SQL, defaultPostgreSqlDatabase, endAllPools, endPool, execute, executeInTransaction, executeSQL, executeSQLBatchInTransaction, executeSQLInTransaction, exists, first, firstOrNull, functionExists, functionExistsSQL, getDatabaseNameOrDefault, getPool, isPgClient, isPgPool, isPgPoolClient, mapRows, mapToCamelCase, onEndPool, postgresClient, rawSql, single, singleOrNull, sql, tableExists, tableExistsSQL, toCamelCase };
240
+ export { type Connection, type ConnectionFactory, type ConnectionPool, type ConnectionPoolFactory, type ConnectorType, type CreateConnectionOptions, type DatabaseTransaction, type DatabaseTransactionFactory, type DbSQLExecutor, type Dumbo, type DumboOptions, type ExistsSQLQueryResult, type NodePostgresAmbientClientPool, type NodePostgresAmbientConnectionPool, type NodePostgresClient, type NodePostgresClientConnection, type NodePostgresClientOptions, type NodePostgresConnection, type NodePostgresConnector, NodePostgresConnectorType, type NodePostgresNativePool, type NodePostgresPool, type NodePostgresPoolClientConnection, type NodePostgresPoolClientOptions, type NodePostgresPoolNotPooledOptions, type NodePostgresPoolOptions, type NodePostgresPoolOrClient, type NodePostgresPoolPooledOptions, type NodePostgresSQLExecutor, type NodePostgresTransaction, type PoolOptions, type PostgresConnector, type PostgresPool, type PostgresPoolOptions, type QueryResult, type QueryResultRow, type SQL, type SQLExecutor, type TransactionResult, type WithSQLExecutor, connectionPool, createConnection, createConnectionPool, defaultPostgreSqlDatabase, dumbo, endAllPools, endPool, executeInNewConnection, executeInNewDbClient, executeInTransaction, exists, first, firstOrNull, functionExists, functionExistsSQL, getDatabaseNameOrDefault, getPool, isNodePostgresClient, isNodePostgresNativePool, isNodePostgresPoolClient, mapRows, mapToCamelCase, nodePostgresAmbientClientPool, nodePostgresAmbientConnectionPool, nodePostgresAmbientNativePool, nodePostgresClientConnection, nodePostgresClientPool, nodePostgresConnection, nodePostgresExecute, 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,207 @@
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;
6
7
  }
7
- declare const postgresClient: (connectionString: string, database?: string) => PostgresClient;
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
+ connection: () => 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>(handle: (connection: ConnectionType) => Promise<Result>, options: {
60
+ connection: () => Promise<ConnectionType>;
61
+ }) => Promise<Result>;
62
+
63
+ interface DatabaseTransaction<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor {
64
+ type: ConnectorType;
65
+ connection: Connection<ConnectorType, DbClient>;
66
+ begin: () => Promise<void>;
67
+ commit: () => Promise<void>;
68
+ rollback: (error?: unknown) => Promise<void>;
69
+ }
70
+ interface DatabaseTransactionFactory<ConnectorType extends string = string> {
71
+ transaction: () => DatabaseTransaction<ConnectorType>;
72
+ withTransaction: <Result = never>(handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
73
+ }
74
+ type TransactionResult<Result> = {
75
+ success: boolean;
76
+ result: Result;
77
+ };
78
+ declare const executeInTransaction: <ConnectorType extends string = string, Result = void>(transaction: DatabaseTransaction<ConnectorType>, handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
79
+ declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>) => DatabaseTransactionFactory<ConnectorType>;
80
+ declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection<string, unknown> = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType['type']>;
81
+
82
+ interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
83
+ type: ConnectorType;
84
+ open: () => Promise<DbClient>;
85
+ close: () => Promise<void>;
86
+ }
87
+ interface ConnectionFactory<ConnectionType extends Connection = Connection> {
88
+ connection: () => Promise<ConnectionType>;
89
+ withConnection: <Result = unknown>(handle: (connection: ConnectionType) => Promise<Result>) => Promise<Result>;
90
+ }
91
+ type CreateConnectionOptions<ConnectorType extends string = string, DbClient = unknown, ConnectionType extends Connection<ConnectorType, DbClient> = Connection<ConnectorType, DbClient>, Executor extends DbSQLExecutor = DbSQLExecutor> = {
92
+ type: ConnectorType;
93
+ connect: Promise<DbClient>;
94
+ close: (client: DbClient) => Promise<void>;
95
+ initTransaction: (connection: () => ConnectionType) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>;
96
+ executor: () => Executor;
97
+ };
98
+ declare const createConnection: <ConnectorType extends string = string, DbClient = unknown, ConnectionType extends Connection<ConnectorType, DbClient> = Connection<ConnectorType, DbClient>, Executor extends DbSQLExecutor<string, unknown> = DbSQLExecutor<string, unknown>>(options: CreateConnectionOptions<ConnectorType, DbClient, ConnectionType, Executor>) => ConnectionType;
99
+
100
+ interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, ConnectionFactory<ConnectionType>, DatabaseTransactionFactory<ConnectionType['type']> {
101
+ type: ConnectionType['type'];
102
+ close: () => Promise<void>;
103
+ }
104
+ type ConnectionPoolFactory<ConnectionPoolType extends ConnectionPool = ConnectionPool, ConnectionPoolOptions = unknown> = (options: ConnectionPoolOptions) => ConnectionPoolType;
105
+ declare const createConnectionPool: <ConnectionType extends Connection<string, unknown>, ConnectionPoolType extends ConnectionPool<ConnectionType>>(pool: Pick<ConnectionPool<ConnectionType>, 'type'> & Partial<ConnectionPool<ConnectionType>> & {
106
+ getConnection: () => ConnectionType;
107
+ }) => ConnectionPoolType;
8
108
 
9
109
  declare const defaultPostgreSqlDatabase = "postgres";
10
- declare const getDatabaseNameOrDefault: (connectionString: string) => string;
110
+ declare const tableExistsSQL: (tableName: string) => SQL;
111
+ declare const tableExists: (pool: ConnectionPool, tableName: string) => Promise<boolean>;
112
+ declare const functionExistsSQL: (functionName: string) => SQL;
113
+ declare const functionExists: (pool: ConnectionPool, tableName: string) => Promise<boolean>;
114
+
115
+ declare const NodePostgresConnectorType = "PostgreSQL:pg";
116
+ type NodePostgresConnector = 'PostgreSQL:pg';
117
+ type NodePostgresClient = pg.PoolClient | pg.Client;
118
+ type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;
119
+ type NodePostgresClientConnection = Connection<NodePostgresConnector, pg.Client>;
120
+ type NodePostgresPoolClientConnection = Connection<NodePostgresConnector, pg.PoolClient>;
121
+ type NodePostgresConnection = NodePostgresPoolClientConnection | NodePostgresClientConnection;
122
+ type NodePostgresPoolClientOptions = {
123
+ type: 'PoolClient';
124
+ connect: Promise<pg.PoolClient>;
125
+ close: (client: pg.PoolClient) => Promise<void>;
126
+ };
127
+ type NodePostgresClientOptions = {
128
+ type: 'Client';
129
+ connect: Promise<pg.Client>;
130
+ close: (client: pg.Client) => Promise<void>;
131
+ };
132
+ declare const nodePostgresClientConnection: (options: NodePostgresClientOptions) => NodePostgresClientConnection;
133
+ declare const nodePostgresPoolClientConnection: (options: NodePostgresPoolClientOptions) => NodePostgresPoolClientConnection;
134
+ declare function nodePostgresConnection(options: NodePostgresPoolClientOptions): NodePostgresPoolClientConnection;
135
+ declare function nodePostgresConnection(options: NodePostgresClientOptions): NodePostgresClientConnection;
11
136
 
137
+ type NodePostgresNativePool = ConnectionPool<NodePostgresPoolClientConnection>;
138
+ type NodePostgresAmbientClientPool = ConnectionPool<NodePostgresClientConnection>;
139
+ type NodePostgresAmbientConnectionPool = ConnectionPool<NodePostgresPoolClientConnection | NodePostgresClientConnection>;
140
+ type NodePostgresPool = NodePostgresNativePool | NodePostgresAmbientClientPool | NodePostgresAmbientConnectionPool;
141
+ declare const nodePostgresNativePool: (options: {
142
+ connectionString: string;
143
+ database?: string | undefined;
144
+ }) => NodePostgresNativePool;
145
+ declare const nodePostgresAmbientNativePool: (options: {
146
+ pool: pg.Pool;
147
+ }) => NodePostgresNativePool;
148
+ declare const nodePostgresAmbientConnectionPool: (options: {
149
+ connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;
150
+ }) => NodePostgresAmbientConnectionPool;
151
+ declare const nodePostgresClientPool: (options: {
152
+ connectionString: string;
153
+ database?: string | undefined;
154
+ }) => NodePostgresAmbientClientPool;
155
+ declare const nodePostgresAmbientClientPool: (options: {
156
+ client: pg.Client;
157
+ }) => NodePostgresAmbientClientPool;
158
+ type NodePostgresPoolPooledOptions = {
159
+ connector?: NodePostgresConnector;
160
+ connectionString: string;
161
+ database?: string;
162
+ pooled: true;
163
+ pool: pg.Pool;
164
+ } | {
165
+ connector?: NodePostgresConnector;
166
+ connectionString: string;
167
+ database?: string;
168
+ pool: pg.Pool;
169
+ } | {
170
+ connector?: NodePostgresConnector;
171
+ connectionString: string;
172
+ database?: string;
173
+ pooled: true;
174
+ } | {
175
+ connector?: NodePostgresConnector;
176
+ connectionString: string;
177
+ database?: string;
178
+ };
179
+ type NodePostgresPoolNotPooledOptions = {
180
+ connector?: NodePostgresConnector;
181
+ connectionString: string;
182
+ database?: string;
183
+ pooled: false;
184
+ client: pg.Client;
185
+ } | {
186
+ connector?: NodePostgresConnector;
187
+ connectionString: string;
188
+ database?: string;
189
+ client: pg.Client;
190
+ } | {
191
+ connector?: NodePostgresConnector;
192
+ connectionString: string;
193
+ database?: string;
194
+ pooled: false;
195
+ } | {
196
+ connector?: NodePostgresConnector;
197
+ connectionString: string;
198
+ database?: string;
199
+ connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;
200
+ pooled?: false;
201
+ };
202
+ type NodePostgresPoolOptions = NodePostgresPoolPooledOptions | NodePostgresPoolNotPooledOptions;
203
+ declare function nodePostgresPool(options: NodePostgresPoolPooledOptions): NodePostgresNativePool;
204
+ declare function nodePostgresPool(options: NodePostgresPoolNotPooledOptions): NodePostgresAmbientClientPool;
12
205
  declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
13
206
  declare const endPool: ({ connectionString, database, force, }: {
14
207
  connectionString: string;
@@ -18,38 +211,30 @@ declare const endPool: ({ connectionString, database, force, }: {
18
211
  declare const onEndPool: (lookupKey: string, pool: pg.Pool) => Promise<void>;
19
212
  declare const endAllPools: () => Promise<void[]>;
20
213
 
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>;
214
+ type NodePostgresTransaction = DatabaseTransaction<NodePostgresConnector>;
215
+ declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(connection: () => Connection<NodePostgresConnector, DbClient>) => (getClient: Promise<DbClient>, options?: {
216
+ close: (client: DbClient, error?: unknown) => Promise<void>;
217
+ } | undefined) => DatabaseTransaction<NodePostgresConnector>;
25
218
 
26
- type SQL = string & {
27
- __brand: 'sql';
28
- };
29
- declare const sql: (sqlQuery: string, ...params: unknown[]) => SQL;
30
- declare const rawSql: (sqlQuery: string) => SQL;
219
+ declare const isNodePostgresNativePool: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Pool;
220
+ declare const isNodePostgresClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Client;
221
+ declare const isNodePostgresPoolClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.PoolClient;
222
+ declare const nodePostgresExecute: <Result = void>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, handle: (client: pg.PoolClient | pg.Client) => Promise<Result>) => Promise<Result>;
223
+ type NodePostgresSQLExecutor = DbSQLExecutor<NodePostgresConnector, NodePostgresClient>;
224
+ declare const nodePostgresSQLExecutor: () => NodePostgresSQLExecutor;
31
225
 
32
- declare const isPgPool: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Pool;
33
- declare const isPgClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.Client;
34
- declare const isPgPoolClient: (poolOrClient: pg.Pool | pg.PoolClient | pg.Client) => poolOrClient is pg.PoolClient;
35
- declare const execute: <Result = void>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, handle: (client: pg.PoolClient | pg.Client) => Promise<Result>) => Promise<Result>;
36
- declare const executeInTransaction: <Result = void>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, handle: (client: pg.PoolClient | pg.Client) => Promise<{
37
- success: boolean;
38
- result: Result;
39
- }>) => Promise<Result>;
40
- declare const executeSQL: <Result extends pg.QueryResultRow = pg.QueryResultRow>(poolOrClient: pg.Pool | pg.PoolClient | pg.Client, sql: SQL) => Promise<pg.QueryResult<Result>>;
41
- declare const executeSQLInTransaction: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool | pg.PoolClient | pg.Client, sql: SQL) => Promise<pg.QueryResult<Result>>;
42
- declare const executeSQLBatchInTransaction: <Result extends pg.QueryResultRow = pg.QueryResultRow>(pool: pg.Pool | pg.PoolClient | pg.Client, ...sqls: SQL[]) => Promise<undefined>;
43
- declare const firstOrNull: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result | null>;
44
- declare const first: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result>;
45
- declare const singleOrNull: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result | null>;
46
- declare const single: <Result extends pg.QueryResultRow = pg.QueryResultRow>(getResult: Promise<pg.QueryResult<Result>>) => Promise<Result>;
47
- declare const mapRows: <Result extends pg.QueryResultRow = pg.QueryResultRow, Mapped = unknown>(getResult: Promise<pg.QueryResult<Result>>, map: (row: Result) => Mapped) => Promise<Mapped[]>;
48
- declare const toCamelCase: (snakeStr: string) => string;
49
- declare const mapToCamelCase: <T extends Record<string, unknown>>(obj: T) => T;
50
- type ExistsSQLQueryResult = {
51
- exists: boolean;
226
+ type PostgresConnector = NodePostgresConnector;
227
+ type PostgresPoolOptions = NodePostgresPoolOptions;
228
+ type PostgresPool = NodePostgresPool;
229
+ declare const postgresPool: typeof nodePostgresPool;
230
+
231
+ type ConnectorType = PostgresConnector;
232
+ type PoolOptions = {
233
+ connector?: ConnectorType;
52
234
  };
53
- declare const exists: (pool: pg.Pool, sql: SQL) => Promise<boolean>;
235
+ type DumboOptions = PoolOptions & PostgresPoolOptions;
236
+ type Dumbo = PostgresPool;
237
+ declare const connectionPool: <PoolOptionsType extends DumboOptions>(options: PoolOptionsType) => NodePostgresNativePool;
238
+ declare const dumbo: <DumboOptionsType extends DumboOptions = DumboOptions>(options: DumboOptionsType) => Dumbo;
54
239
 
55
- export { type ExistsSQLQueryResult, type PostgresClient, type SQL, defaultPostgreSqlDatabase, endAllPools, endPool, execute, executeInTransaction, executeSQL, executeSQLBatchInTransaction, executeSQLInTransaction, exists, first, firstOrNull, functionExists, functionExistsSQL, getDatabaseNameOrDefault, getPool, isPgClient, isPgPool, isPgPoolClient, mapRows, mapToCamelCase, onEndPool, postgresClient, rawSql, single, singleOrNull, sql, tableExists, tableExistsSQL, toCamelCase };
240
+ export { type Connection, type ConnectionFactory, type ConnectionPool, type ConnectionPoolFactory, type ConnectorType, type CreateConnectionOptions, type DatabaseTransaction, type DatabaseTransactionFactory, type DbSQLExecutor, type Dumbo, type DumboOptions, type ExistsSQLQueryResult, type NodePostgresAmbientClientPool, type NodePostgresAmbientConnectionPool, type NodePostgresClient, type NodePostgresClientConnection, type NodePostgresClientOptions, type NodePostgresConnection, type NodePostgresConnector, NodePostgresConnectorType, type NodePostgresNativePool, type NodePostgresPool, type NodePostgresPoolClientConnection, type NodePostgresPoolClientOptions, type NodePostgresPoolNotPooledOptions, type NodePostgresPoolOptions, type NodePostgresPoolOrClient, type NodePostgresPoolPooledOptions, type NodePostgresSQLExecutor, type NodePostgresTransaction, type PoolOptions, type PostgresConnector, type PostgresPool, type PostgresPoolOptions, type QueryResult, type QueryResultRow, type SQL, type SQLExecutor, type TransactionResult, type WithSQLExecutor, connectionPool, createConnection, createConnectionPool, defaultPostgreSqlDatabase, dumbo, endAllPools, endPool, executeInNewConnection, executeInNewDbClient, executeInTransaction, exists, first, firstOrNull, functionExists, functionExistsSQL, getDatabaseNameOrDefault, getPool, isNodePostgresClient, isNodePostgresNativePool, isNodePostgresPoolClient, mapRows, mapToCamelCase, nodePostgresAmbientClientPool, nodePostgresAmbientConnectionPool, nodePostgresAmbientNativePool, nodePostgresClientConnection, nodePostgresClientPool, nodePostgresConnection, nodePostgresExecute, 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 C from"pg";import Q from"pg-connection-string";var l="postgres",u=e=>Q.parse(e).database??l;var n=new Map,a=new Map,g=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 P(r,1),n.get(r)??n.set(r,new C.Pool(o)).get(r)},c=async({connectionString:e,database:t,force:o})=>{t=t??u(e);let s=y(e,t),r=n.get(s);r&&(P(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)}},D=()=>Promise.all([...n.entries()].map(([e,t])=>R(e,t))),y=(e,t)=>`${e}|${t??l}`,P=(e,t)=>{let o=a.get(e)??0,s=o+t;return a.set(e,o+t),s};var B=(e,t)=>{let o=g({connectionString:e,database:t});return{connect:()=>o.connect(),close:()=>c({connectionString:e,database:t})}};import m from"pg";var w=e=>e instanceof m.Pool,W=e=>e instanceof m.Client,d=e=>"release"in e&&typeof e.release=="function",x=async(e,t)=>{let o=w(e)?await e.connect():e;try{return await t(o)}finally{w(e)&&d(o)&&o.release()}},f=async(e,t)=>x(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}}),S=async(e,t)=>x(e,o=>o.query(t)),X=async(e,t)=>(console.log(t),f(e,async o=>({success:!0,result:await o.query(t)}))),z=async(e,...t)=>f(e,async o=>{for(let s of t)await o.query(s);return{success:!0,result:void 0}}),G=async e=>{let t=await e;return t.rows.length>0?t.rows[0]??null:null},j=async e=>{let t=await e;if(t.rows.length===0)throw new Error("Query didn't return any result");return t.rows[0]},J=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},L=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]},V=async(e,t)=>(await e).rows.map(t),E=e=>e.replace(/_([a-z])/g,t=>t[1]?.toUpperCase()??""),Y=e=>{let t={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[E(o)]=e[o]);return t},i=async(e,t)=>(await L(S(e,t))).exists===!0;import T from"pg-format";import"pg";var h=e=>p(`
1
+ import X from"pg-connection-string";import I from"pg-format";var R=(e,...o)=>I(e,...o),se=e=>e;var d=(e,o)=>({query:t=>g(n=>e.query(n,t),o),batchQuery:t=>g(n=>e.batchQuery(n,t),o),command:t=>g(n=>e.command(n,t),o),batchCommand:t=>g(n=>e.batchQuery(n,t),o)}),N=e=>({query:o=>a(t=>t.execute.query(o),e),batchQuery:o=>a(t=>t.execute.batchQuery(o),e),command:o=>a(t=>t.execute.command(o),e),batchCommand:o=>a(t=>t.execute.batchCommand(o),e)}),g=async(e,o)=>{let{connect:t,close:n}=o,s=await t();try{return await e(s)}catch(r){throw n&&await n(s,r),r}},a=async(e,o)=>{let t=await o.connection();try{return await e(t)}finally{await t.close()}};var M=e=>e!=null&&typeof e=="object"&&"success"in e?e:{success:!0,result:e},_=async(e,o)=>{await e.begin();try{let{success:t,result:n}=M(await o(e));return t?await e.commit():await e.rollback(),n}catch(t){throw await e.rollback(),t}},D=(e,o)=>({transaction:()=>o(e()),withTransaction:t=>_(o(e()),t)}),b=async(e,o)=>{try{return await o()}finally{await e.close()}},S=e=>({transaction:()=>{let o=e(),t=o.transaction();return{...t,commit:()=>b(o,()=>t.commit()),rollback:()=>b(o,()=>t.rollback())}},withTransaction:o=>{let t=e();return b(t,()=>t.withTransaction(o))}});var w=e=>{let{type:o,connect:t,close:n,initTransaction:s,executor:r}=e,c=null,l=async()=>c??(c=await t),y={type:o,open:l,close:()=>c?n(c):Promise.resolve(),...D(l,s(()=>y)),execute:d(r(),{connect:l})};return y};var u=e=>{let{type:o,getConnection:t}=e,n="connection"in e?e.connection:()=>Promise.resolve(t()),s="withConnection"in e?e.withConnection:y=>a(y,{connection:n}),r="close"in e?e.close:()=>Promise.resolve(),c="execute"in e?e.execute:N({connection:n}),l="transaction"in e&&"withTransaction"in e?{transaction:e.transaction,withTransaction:e.withTransaction}:S(t);return{type:o,connection:n,withConnection:s,close:r,execute:c,...l}};var Te=async(e,o)=>(await e).rows.map(o),$=e=>e.replace(/_([a-z])/g,o=>o[1]?.toUpperCase()??""),fe=e=>{let o={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(o[$(t)]=e[t]);return o};var De=async e=>{let o=await e;return o.rows.length>0?o.rows[0]??null:null},Se=async e=>{let o=await e;if(o.rows.length===0)throw new Error("Query didn't return any result");return o.rows[0]},he=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},B=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 B(e)).exists===!0;var m="postgres",H=e=>R(`
2
2
  SELECT EXISTS (
3
3
  SELECT FROM pg_tables
4
4
  WHERE tablename = %L
5
- ) AS exists;`,e),re=async(e,t)=>i(e,h(t)),b=e=>p(`
5
+ ) AS exists;`,e),_e=async(e,o)=>Q(e.execute.query(H(o))),U=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),ne=async(e,t)=>i(e,b(t));var p=(e,...t)=>T(e,...t),pe=e=>e;export{l as defaultPostgreSqlDatabase,D as endAllPools,c as endPool,x as execute,f as executeInTransaction,S as executeSQL,z as executeSQLBatchInTransaction,X as executeSQLInTransaction,i as exists,j as first,G as firstOrNull,ne as functionExists,b as functionExistsSQL,u as getDatabaseNameOrDefault,g as getPool,W as isPgClient,w as isPgPool,d as isPgPoolClient,V as mapRows,Y as mapToCamelCase,R as onEndPool,B as postgresClient,pe as rawSql,L as single,J as singleOrNull,p as sql,re as tableExists,h as tableExistsSQL,E as toCamelCase};
11
+ `,e),$e=async(e,o)=>Q(e.execute.query(U(o)));var T=e=>X.parse(e).database??m;import"pg";import E from"pg";var h=e=>e instanceof E.Pool,no=e=>e instanceof E.Client,j=e=>"release"in e&&typeof e.release=="function",so=async(e,o)=>{let t=h(e)?await e.connect():e;try{return await o(t)}finally{h(e)&&j(t)&&t.release()}},p=()=>({type:i,query:x,batchQuery:x,command:x,batchCommand:x});async function x(e,o){let t=Array.isArray(o)?o:[o],n=Array(t.length);for(let s=0;s<t.length;s++){let r=await e.query(t[s]);n[s]={rowCount:r.rowCount,rows:r.rows}}return Array.isArray(o)?n:n[0]}var f=e=>(o,t)=>({connection:e(),type:i,begin:async()=>{await(await o).query("BEGIN")},commit:async()=>{let n=await o;await n.query("COMMIT"),t?.close&&await t?.close(n)},rollback:async n=>{let s=await o;await s.query("ROLLBACK"),t?.close&&await t?.close(s,n)},execute:d(p(),{connect:()=>o})});var i="PostgreSQL:pg",z=e=>{let{connect:o,close:t}=e;return w({type:i,connect:o,close:t,initTransaction:n=>f(n),executor:p})},G=e=>{let{connect:o,close:t}=e;return w({type:i,connect:o,close:t,initTransaction:n=>f(n),executor:p})};function P(e){return e.type==="Client"?z(e):G(e)}import O from"pg";var K=e=>{let{connectionString:o,database:t}=e,n=ee({connectionString:o,database:t}),s=()=>P({type:"PoolClient",connect:n.connect(),close:l=>Promise.resolve(l.release())});return u({type:i,connection:()=>Promise.resolve(s()),close:()=>oe({connectionString:o,database:t}),getConnection:s})},J=e=>{let{pool:o}=e;return u({type:i,getConnection:()=>P({type:"PoolClient",connect:o.connect(),close:t=>Promise.resolve(t.release())})})},V=e=>{let{connection:o}=e;return u({type:i,getConnection:()=>o,execute:o.execute,transaction:()=>o.transaction(),withTransaction:t=>o.withTransaction(t)})},Y=e=>{let{connectionString:o,database:t}=e;return u({type:i,getConnection:()=>{let n=Promise.resolve(new O.Client({connectionString:o,database:t})).then(async s=>(await s.connect(),s));return P({type:"Client",connect:n,close:s=>s.end()})}})},Z=e=>{let{client:o}=e,t=()=>{let r=Promise.resolve(o);return P({type:"Client",connect:r,close:()=>Promise.resolve()})};return u({type:i,connection:()=>Promise.resolve(t()),close:()=>Promise.resolve(),getConnection:t})};function v(e){let{connectionString:o,database:t}=e;return"client"in e&&e.client?Z({client:e.client}):"pooled"in e&&e.pooled===!1?Y({connectionString:o,database:t}):"connection"in e&&e.connection?V({connection:e.connection}):"pool"in e&&e.pool?J({pool:e.pool}):K({connectionString:o,database:t})}var C=new Map,L=new Map,ee=e=>{let o=typeof e=="string"?e:e.connectionString,t=typeof e=="string"?{connectionString:o}:e,n=t.database??(t.connectionString?T(t.connectionString):void 0),s=k(o,n);return A(s,1),C.get(s)??C.set(s,new O.Pool(t)).get(s)},oe=async({connectionString:e,database:o,force:t})=>{o=o??T(e);let n=k(e,o),s=C.get(n);s&&(A(n,-1)<=0||t===!0)&&await q(n,s)},q=async(e,o)=>{try{await o.end()}catch(t){console.log(`Error while closing the connection pool: ${e}`),console.log(t)}C.delete(e)},To=()=>Promise.all([...C.entries()].map(([e,o])=>q(e,o))),k=(e,o)=>`${e}|${o??m}`,A=(e,o)=>{let t=L.get(e)??0,n=t+o;return L.set(e,t+o),n};var F=v;var te=e=>F(e),Wo=e=>te(e);export{i as NodePostgresConnectorType,te as connectionPool,w as createConnection,u as createConnectionPool,m as defaultPostgreSqlDatabase,Wo as dumbo,To as endAllPools,oe as endPool,a as executeInNewConnection,g as executeInNewDbClient,_ as executeInTransaction,Q as exists,Se as first,De as firstOrNull,$e as functionExists,U as functionExistsSQL,T as getDatabaseNameOrDefault,ee as getPool,no as isNodePostgresClient,h as isNodePostgresNativePool,j as isNodePostgresPoolClient,Te as mapRows,fe as mapToCamelCase,Z as nodePostgresAmbientClientPool,V as nodePostgresAmbientConnectionPool,J as nodePostgresAmbientNativePool,z as nodePostgresClientConnection,Y as nodePostgresClientPool,P as nodePostgresConnection,so as nodePostgresExecute,K as nodePostgresNativePool,v as nodePostgresPool,G as nodePostgresPoolClientConnection,p as nodePostgresSQLExecutor,f as nodePostgresTransaction,q as onEndPool,F as postgresPool,se as rawSql,B as single,he as singleOrNull,R as sql,d as sqlExecutor,N as sqlExecutorInNewConnection,_e as tableExists,H as tableExistsSQL,$ as toCamelCase,D as transactionFactoryWithDbClient,S 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 pg from 'pg';\nimport type { SQL } from '../sql';\n\nexport const isPgPool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isPgClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isPgPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const execute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isPgPool(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 (isPgPool(poolOrClient) && isPgPoolClient(client)) client.release();\n }\n};\n\nexport const executeInTransaction = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (\n client: pg.PoolClient | pg.Client,\n ) => Promise<{ success: boolean; result: Result }>,\n): Promise<Result> =>\n execute(poolOrClient, 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 | pg.Client,\n sql: SQL,\n): Promise<pg.QueryResult<Result>> =>\n execute(poolOrClient, (client) => client.query<Result>(sql));\n\nexport const executeSQLInTransaction = async <\n Result extends pg.QueryResultRow = pg.QueryResultRow,\n>(\n pool: pg.Pool | pg.PoolClient | pg.Client,\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 | pg.PoolClient | pg.Client,\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,EAA8B,IAAI,IAClCC,EAAoC,IAAI,IAEjCC,EACXC,GACY,CACZ,IAAMC,EACJ,OAAOD,GAA8B,SACjCA,EACAA,EAA0B,iBAE1BE,EACJ,OAAOF,GAA8B,SACjC,CAAE,iBAAAC,CAAiB,EACnBD,EAEAG,EACJD,EAAY,WACXA,EAAY,iBACTE,EAAyBF,E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H,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","pg","isPgPool","poolOrClient","isPgClient","isPgPoolClient","execute","handle","client","executeInTransaction","success","result","e","executeSQL","sql","executeSQLInTransaction","pool","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/sql/index.ts","../src/core/execute/execute.ts","../src/core/connections/transaction.ts","../src/core/connections/connection.ts","../src/core/connections/pool.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import format from 'pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n connection: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n connection: () => Promise<ConnectionType>;\n },\n) => {\n const connection = await options.connection();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor {\n type: ConnectorType;\n connection: Connection<ConnectorType, DbClient>;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n> {\n transaction: () => DatabaseTransaction<ConnectorType>;\n\n withTransaction: <Result = never>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<TransactionResult<Result> | Result>,\n ) => Promise<Result>;\n}\n\nexport type TransactionResult<Result> = { success: boolean; result: Result };\n\nconst toTransactionResult = <Result>(\n transactionResult: TransactionResult<Result> | Result,\n): TransactionResult<Result> =>\n transactionResult !== undefined &&\n transactionResult !== null &&\n typeof transactionResult === 'object' &&\n 'success' in transactionResult\n ? transactionResult\n : { success: true, result: transactionResult };\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n Result = void,\n>(\n transaction: DatabaseTransaction<ConnectorType>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<TransactionResult<Result> | Result>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = toTransactionResult(await handle(transaction));\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType>,\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 {\n sqlExecutor,\n type DbSQLExecutor,\n type WithSQLExecutor,\n} from '../execute';\nimport {\n transactionFactoryWithDbClient,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface Connection<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor,\n DatabaseTransactionFactory<ConnectorType> {\n type: ConnectorType;\n open: () => Promise<DbClient>;\n close: () => Promise<void>;\n}\n\nexport interface ConnectionFactory<\n ConnectionType extends Connection = Connection,\n> {\n connection: () => Promise<ConnectionType>;\n\n withConnection: <Result = unknown>(\n handle: (connection: ConnectionType) => Promise<Result>,\n ) => Promise<Result>;\n}\n\nexport type CreateConnectionOptions<\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n> = {\n type: ConnectorType;\n connect: Promise<DbClient>;\n close: (client: DbClient) => Promise<void>;\n initTransaction: (\n connection: () => ConnectionType,\n ) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>;\n executor: () => Executor;\n};\n\nexport const createConnection = <\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n>(\n options: CreateConnectionOptions<\n ConnectorType,\n DbClient,\n ConnectionType,\n Executor\n >,\n): ConnectionType => {\n const { type, connect, close, initTransaction, executor } = options;\n\n let client: DbClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n const connection: Connection<ConnectorType, DbClient> = {\n type: type,\n open: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(\n getClient,\n initTransaction(() => typedConnection),\n ),\n execute: sqlExecutor(executor(), { connect: getClient }),\n };\n\n const typedConnection = connection as ConnectionType;\n\n return typedConnection;\n};\n","import {\n executeInNewConnection,\n sqlExecutorInNewConnection,\n type WithSQLExecutor,\n} from '../execute';\nimport { type Connection, type ConnectionFactory } from './connection';\nimport {\n transactionFactoryWithNewConnection,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface ConnectionPool<ConnectionType extends Connection = Connection>\n extends WithSQLExecutor,\n ConnectionFactory<ConnectionType>,\n DatabaseTransactionFactory<ConnectionType['type']> {\n type: ConnectionType['type'];\n close: () => Promise<void>;\n}\n\nexport type ConnectionPoolFactory<\n ConnectionPoolType extends ConnectionPool = ConnectionPool,\n ConnectionPoolOptions = unknown,\n> = (options: ConnectionPoolOptions) => ConnectionPoolType;\n\nexport const createConnectionPool = <\n ConnectionType extends Connection,\n ConnectionPoolType extends ConnectionPool<ConnectionType>,\n>(\n pool: Pick<ConnectionPool<ConnectionType>, 'type'> &\n Partial<ConnectionPool<ConnectionType>> & {\n getConnection: () => ConnectionType;\n },\n): ConnectionPoolType => {\n const { type, getConnection } = pool;\n\n const connection =\n 'connection' in pool\n ? pool.connection\n : () => Promise.resolve(getConnection());\n\n const withConnection =\n 'withConnection' in pool\n ? pool.withConnection\n : <Result>(handle: (connection: ConnectionType) => Promise<Result>) =>\n executeInNewConnection<ConnectionType, Result>(handle, {\n connection,\n });\n\n const close = 'close' in pool ? pool.close : () => Promise.resolve();\n\n const execute =\n 'execute' in pool\n ? pool.execute\n : sqlExecutorInNewConnection({ connection });\n\n const transaction =\n 'transaction' in pool && 'withTransaction' in pool\n ? {\n transaction: pool.transaction,\n withTransaction: pool.withTransaction,\n }\n : transactionFactoryWithNewConnection(getConnection);\n\n const result: ConnectionPool<ConnectionType> = {\n type,\n connection,\n withConnection,\n close,\n execute,\n ...transaction,\n };\n\n return result as ConnectionPoolType;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport { createConnection, type Connection } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import {\n sqlExecutor,\n type Connection,\n type DatabaseTransaction,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction =\n <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(\n connection: () => Connection<NodePostgresConnector, DbClient>,\n ) =>\n (\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n ): DatabaseTransaction<NodePostgresConnector> => ({\n connection: connection(),\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), {\n connect: () => getClient,\n }),\n });\n","import pg from 'pg';\nimport { createConnectionPool, type ConnectionPool } from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresConnector,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresAmbientClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport type NodePostgresAmbientConnectionPool = ConnectionPool<\n NodePostgresPoolClientConnection | NodePostgresClientConnection\n>;\n\nexport type NodePostgresPool =\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresNativePool => {\n const { connectionString, database } = options;\n const pool = getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = () => endPool({ connectionString, database });\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport const nodePostgresAmbientNativePool = (options: {\n pool: pg.Pool;\n}): NodePostgresNativePool => {\n const { pool } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n }),\n });\n};\n\nexport const nodePostgresAmbientConnectionPool = (options: {\n connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;\n}): NodePostgresAmbientConnectionPool => {\n const { connection } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => connection,\n execute: connection.execute,\n transaction: () => connection.transaction(),\n withTransaction: (handle) => connection.withTransaction(handle),\n });\n};\n\nexport const nodePostgresClientPool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresAmbientClientPool => {\n const { connectionString, database } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => {\n const connect = Promise.resolve(\n new pg.Client({ connectionString, database }),\n ).then(async (client) => {\n await client.connect();\n return client;\n });\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => client.end(),\n });\n },\n });\n};\n\nexport const nodePostgresAmbientClientPool = (options: {\n client: pg.Client;\n}): NodePostgresAmbientClientPool => {\n const { client } = options;\n\n const getConnection = () => {\n const connect = Promise.resolve(client);\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: () => Promise.resolve(),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = () => Promise.resolve();\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n connection:\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n pooled?: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresAmbientClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n):\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool {\n const { connectionString, database } = options;\n\n if ('client' in options && options.client)\n return nodePostgresAmbientClientPool({ client: options.client });\n\n if ('pooled' in options && options.pooled === false)\n return nodePostgresClientPool({ connectionString, database });\n\n if ('connection' in options && options.connection)\n return nodePostgresAmbientConnectionPool({\n connection: options.connection,\n });\n\n if ('pool' in options && options.pool)\n return nodePostgresAmbientNativePool({ pool: options.pool });\n\n return nodePostgresNativePool({\n connectionString,\n database,\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnector,\n type NodePostgresPool,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport type PostgresPool = NodePostgresPool;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPool,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\n\nexport type PoolOptions = {\n connector?: ConnectorType;\n};\n\nexport type DumboOptions = PoolOptions & PostgresPoolOptions;\nexport type Dumbo = PostgresPool;\n\nexport const connectionPool = <PoolOptionsType extends DumboOptions>(\n options: PoolOptionsType,\n) =>\n // TODO: this should have the pattern matching and verification\n postgresPool(options as unknown as PostgresPoolOptions);\n\nexport const dumbo = <DumboOptionsType extends DumboOptions = DumboOptions>(\n options: DumboOptionsType,\n): Dumbo => connectionPool(options);\n"],"mappings":"AAAA,OAAOA,M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EAAWtB,CAAI,CAAC,CAC5E,EAEIuB,EAAM,CAACzB,EAA0BC,IACrC,GAAGD,CAAgB,IAAIC,GAAY8B,CAAyB,GAExDL,EAAyB,CAACF,EAAmBQ,IAAuB,CACxE,IAAMC,EAAiBb,EAAa,IAAII,CAAS,GAAK,EAChDU,EAAaD,EAAiBD,EAEpC,OAAAZ,EAAa,IAAII,EAAWS,EAAiBD,CAAE,EAExCE,CACT,ECpSO,IAAMC,EAAeC,ECOrB,IAAMC,GACXC,GAGAC,EAAaD,CAAyC,EAE3CE,GACXF,GACUD,GAAeC,CAAO","names":["pgcs","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","sql","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","toTransactionResult","transactionResult","executeInTransaction","transaction","handle","success","result","e","transactionFactoryWithDbClient","connect","initTransaction","wrapInConnectionClosure","connection","transactionFactoryWithNewConnection","createConnection","options","type","connect","close","initTransaction","executor","client","getClient","typedConnection","transactionFactoryWithDbClient","sqlExecutor","createConnectionPool","pool","type","getConnection","connection","withConnection","handle","executeInNewConnection","close","execute","sqlExecutorInNewConnection","transaction","transactionFactoryWithNewConnection","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","getResult","result","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","sql","tableExists","pool","exists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pgcs","defaultPostgreSqlDatabase","pg","isNodePostgresNativePool","poolOrClient","pg","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","handle","client","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","sqls","results","i","result","nodePostgresTransaction","connection","getClient","options","NodePostgresConnectorType","client","error","sqlExecutor","nodePostgresSQLExecutor","NodePostgresConnectorType","nodePostgresClientConnection","options","connect","close","createConnection","connection","nodePostgresTransaction","nodePostgresSQLExecutor","nodePostgresPoolClientConnection","nodePostgresConnection","pg","nodePostgresNativePool","options","connectionString","database","pool","getPool","getConnection","nodePostgresConnection","client","createConnectionPool","NodePostgresConnectorType","endPool","nodePostgresAmbientNativePool","nodePostgresAmbientConnectionPool","connection","handle","nodePostgresClientPool","connect","pg","nodePostgresAmbientClientPool","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","getDatabaseNameOrDefault","lookupKey","key","updatePoolUsageCounter","force","onEndPool","error","endAllPools","defaultPostgreSqlDatabase","by","currentCounter","newCounter","postgresPool","nodePostgresPool","connectionPool","options","postgresPool","dumbo"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@event-driven-io/dumbo",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Dumbo - tools for dealing with PostgreSQL",
5
5
  "type": "module",
6
6
  "scripts": {