@event-driven-io/dumbo 0.6.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 +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +67 -26
- package/dist/index.d.ts +67 -26
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _pgconnectionstring = require('pg-connection-string'); var _pgconnectionstring2 = _interopRequireDefault(_pgconnectionstring);var M=async(e,o)=>{await e.begin();try{let{success:t,result:n}=await o(e);return t?await e.commit():await e.rollback(),n}catch(t){throw await e.rollback(),t}},
|
|
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),
|
|
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)
|
|
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
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/connections/transaction.ts","../src/core/sql/index.ts","../src/core/execute/execute.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"names":["pgcs","executeInTransaction","transaction","handle","success","result","e","transactionFactoryWithDbClient","connect","initTransaction","wrapInConnectionClosure","connection","transactionFactoryWithNewConnection","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","close","error","open","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","tableExists","pool","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pg","isNodePostgresNativePool","poolOrClient","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","results","i","nodePostgresTransaction","getClient","nodePostgresClientConnection","nodePostgresPoolClientConnection","nodePostgresConnection","nodePostgresNativePool","database","ambientPool","getPool","getConnection","endPool","nodePostgresExplicitClientPool","ambientClient","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","lookupKey","updatePoolUsageCounter","force","onEndPool","endAllPools","by","currentCounter","newCounter","postgresPool","connectionPool","_type"],"mappings":"AAAA,OAAOA,MAAU,uBCuBV,IAAMC,EAAuB,MAIlCC,EACAC,IAGoB,CACpB,MAAMD,EAAY,MAAM,EAExB,GAAI,CACF,GAAM,CAAE,QAAAE,EAAS,OAAAC,CAAO,EAAI,MAAMF,EAAOD,CAAW,EAEpD,OAAIE,EAAS,MAAMF,EAAY,OAAO,EACjC,MAAMA,EAAY,SAAS,EAEzBG,CACT,OAASC,EAAG,CACV,YAAMJ,EAAY,SAAS,EACrBI,CACR,CACF,EAEaC,EAAiC,CAI5CC,EACAC,KAG+C,CAC/C,YAAa,IAAMA,EAAgBD,EAAQ,CAAC,EAC5C,gBAAkB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,EAAeb,ECErB,IAAMc,GAAiB,CAACC,EAAsB1E,IACnDwE,EAAaxE,CAAO","sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<ConnectorType extends string = string>\n extends WithSQLExecutor {\n type: ConnectorType;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n> {\n transaction: () => DatabaseTransaction<ConnectorType>;\n\n withTransaction: <Result = unknown>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<{ success: boolean; result: Result }>,\n ) => Promise<Result>;\n}\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n Result = unknown,\n>(\n transaction: DatabaseTransaction<ConnectorType>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<{ success: boolean; result: Result }>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = await handle(transaction);\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType>,\n): DatabaseTransactionFactory<ConnectorType> => ({\n transaction: () => initTransaction(connect()),\n withTransaction: (handle) =>\n executeInTransaction(initTransaction(connect()), handle),\n});\n\nconst wrapInConnectionClosure = async <\n ConnectionType extends Connection = Connection,\n Result = unknown,\n>(\n connection: ConnectionType,\n handle: () => Promise<Result>,\n) => {\n try {\n return await handle();\n } finally {\n await connection.close();\n }\n};\n\nexport const transactionFactoryWithNewConnection = <\n ConnectionType extends Connection = Connection,\n>(\n connect: () => ConnectionType,\n): DatabaseTransactionFactory<ConnectionType['type']> => ({\n transaction: () => {\n const connection = connect();\n const transaction = connection.transaction();\n\n return {\n ...transaction,\n commit: () =>\n wrapInConnectionClosure(connection, () => transaction.commit()),\n rollback: () =>\n wrapInConnectionClosure(connection, () => transaction.rollback()),\n };\n },\n withTransaction: (handle) => {\n const connection = connect();\n return wrapInConnectionClosure(connection, () =>\n connection.withTransaction(handle),\n );\n },\n});\n","import format from 'pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n open: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result extends QueryResultRow = QueryResultRow,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n open: () => Promise<ConnectionType>;\n },\n) => {\n const { open } = options;\n const connection = await open();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport {\n sqlExecutor,\n transactionFactoryWithDbClient,\n type Connection,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n let client: pg.Client | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n return {\n type: NodePostgresConnectorType,\n connect: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(getClient, nodePostgresTransaction),\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: getClient }),\n };\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n let client: pg.PoolClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n return {\n type: NodePostgresConnectorType,\n connect: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(getClient, nodePostgresTransaction),\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: getClient }),\n };\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import { sqlExecutor, type DatabaseTransaction } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction = <\n DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient,\n>(\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n): DatabaseTransaction<NodePostgresConnector> => ({\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: () => getClient }),\n});\n","import pg from 'pg';\nimport {\n sqlExecutorInNewConnection,\n transactionFactoryWithNewConnection,\n type ConnectionPool,\n} from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresExplicitClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string;\n pool?: pg.Pool;\n}): NodePostgresNativePool => {\n const { connectionString, database, pool: ambientPool } = options;\n const pool = ambientPool\n ? ambientPool\n : getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = async () => {\n if (!ambientPool) await endPool({ connectionString, database });\n };\n\n return {\n type: NodePostgresConnectorType,\n open,\n close,\n execute: sqlExecutorInNewConnection({ open }),\n ...transactionFactoryWithNewConnection(getConnection),\n };\n};\n\nexport const nodePostgresExplicitClientPool = (options: {\n connectionString: string;\n database?: string;\n client?: pg.Client;\n}): NodePostgresExplicitClientPool => {\n const { connectionString, database, client: ambientClient } = options;\n\n const getConnection = () => {\n const connect = ambientClient\n ? Promise.resolve(ambientClient)\n : Promise.resolve(new pg.Client({ connectionString, database })).then(\n async (client) => {\n await client.connect();\n return client;\n },\n );\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => (ambientClient ? Promise.resolve() : client.end()),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = async () => {\n if (!ambientClient) await endPool({ connectionString, database });\n };\n\n return {\n type: NodePostgresConnectorType,\n open,\n close,\n execute: sqlExecutorInNewConnection({ open }),\n ...transactionFactoryWithNewConnection(getConnection),\n };\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connectionString: string;\n database?: string;\n pooled: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresExplicitClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n): NodePostgresNativePool | NodePostgresExplicitClientPool {\n const { connectionString, database } = options;\n\n if (('pooled' in options && options.pooled === false) || 'client' in options)\n return nodePostgresExplicitClientPool({\n connectionString,\n ...(database ? { database } : {}),\n ...('client' in options && options.client\n ? { client: options.client }\n : {}),\n });\n\n return nodePostgresNativePool({\n connectionString,\n ...(database ? { database } : {}),\n ...('pool' in options && options.pool ? { pool: options.pool } : {}),\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnector,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\nexport type PoolOptions = PostgresPoolOptions;\n\nexport const connectionPool = (_type: ConnectorType, options: PoolOptions) =>\n postgresPool(options);\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/sql/index.ts","../src/core/execute/execute.ts","../src/core/connections/transaction.ts","../src/core/connections/connection.ts","../src/core/connections/pool.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"names":["pgcs","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","toTransactionResult","transactionResult","executeInTransaction","transaction","success","result","e","transactionFactoryWithDbClient","initTransaction","wrapInConnectionClosure","transactionFactoryWithNewConnection","createConnection","type","executor","getClient","typedConnection","createConnectionPool","pool","getConnection","withConnection","execute","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","tableExists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pg","isNodePostgresNativePool","poolOrClient","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","results","i","nodePostgresTransaction","nodePostgresClientConnection","nodePostgresPoolClientConnection","nodePostgresConnection","nodePostgresNativePool","database","getPool","endPool","nodePostgresAmbientNativePool","nodePostgresAmbientConnectionPool","nodePostgresClientPool","nodePostgresAmbientClientPool","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","lookupKey","updatePoolUsageCounter","force","onEndPool","endAllPools","by","currentCounter","newCounter","postgresPool","connectionPool","dumbo"],"mappings":"AAAA,OAAOA,MAAU,uBCAjB,OAAOC,MAAY,YAKZ,IAAMC,EAAM,CAACC,KAAqBC,IAChCH,EAAOE,EAAU,GAAGC,CAAM,EAGtBC,GAAUF,GACdA,ECoCF,IAAMG,EAAc,CAIzBA,EAEAC,KAIiB,CACjB,MAAQL,GACNM,EAAsBC,GAAWH,EAAY,MAAMG,EAAQP,CAAG,EAAGK,CAAO,EAC1E,WAAaG,GACXF,EACGC,GAAWH,EAAY,WAAWG,EAAQC,CAAI,EAC/CH,CACF,EACF,QAAUL,GACRM,EAAsBC,GAAWH,EAAY,QAAQG,EAAQP,CAAG,EAAGK,CAAO,EAC5E,aAAeG,GACbF,EACGC,GAAWH,EAAY,WAAWG,EAAQC,CAAI,EAC/CH,CACF,CACJ,GAEaI,EAEXJ,IAEkB,CAClB,MAAQL,GACNU,EACGC,GAAeA,EAAW,QAAQ,MAAMX,CAAG,EAC5CK,CACF,EACF,WAAaG,GACXE,EACGC,GAAeA,EAAW,QAAQ,WAAWH,CAAI,EAClDH,CACF,EACF,QAAUL,GACRU,EACGC,GAAeA,EAAW,QAAQ,QAAQX,CAAG,EAC9CK,CACF,EACF,aAAeG,GACbE,EACGC,GAAeA,EAAW,QAAQ,aAAaH,CAAI,EACpDH,CACF,CACJ,GAEaC,EAAuB,MAIlCM,EACAP,IAIoB,CACpB,GAAM,CAAE,QAAAQ,EAAS,MAAAC,CAAM,EAAIT,EACrBE,EAAS,MAAMM,EAAQ,EAC7B,GAAI,CACF,OAAO,MAAMD,E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AChE,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
|
@@ -50,48 +50,61 @@ declare const sqlExecutor: <DbClient = unknown, DbExecutor extends DbSQLExecutor
|
|
|
50
50
|
close?: (client: DbClient, error?: unknown) => Promise<void>;
|
|
51
51
|
}) => SQLExecutor;
|
|
52
52
|
declare const sqlExecutorInNewConnection: <ConnectionType extends Connection<string, unknown>>(options: {
|
|
53
|
-
|
|
53
|
+
connection: () => Promise<ConnectionType>;
|
|
54
54
|
}) => SQLExecutor;
|
|
55
55
|
declare const executeInNewDbClient: <DbClient = unknown, Result = unknown>(handle: (client: DbClient) => Promise<Result>, options: {
|
|
56
56
|
connect: () => Promise<DbClient>;
|
|
57
57
|
close?: (client: DbClient, error?: unknown) => Promise<void>;
|
|
58
58
|
}) => Promise<Result>;
|
|
59
|
-
declare const executeInNewConnection: <ConnectionType extends Connection<string, unknown>, Result
|
|
60
|
-
|
|
59
|
+
declare const executeInNewConnection: <ConnectionType extends Connection<string, unknown>, Result>(handle: (connection: ConnectionType) => Promise<Result>, options: {
|
|
60
|
+
connection: () => Promise<ConnectionType>;
|
|
61
61
|
}) => Promise<Result>;
|
|
62
62
|
|
|
63
|
-
interface DatabaseTransaction<ConnectorType extends string = string> extends WithSQLExecutor {
|
|
63
|
+
interface DatabaseTransaction<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor {
|
|
64
64
|
type: ConnectorType;
|
|
65
|
+
connection: Connection<ConnectorType, DbClient>;
|
|
65
66
|
begin: () => Promise<void>;
|
|
66
67
|
commit: () => Promise<void>;
|
|
67
68
|
rollback: (error?: unknown) => Promise<void>;
|
|
68
69
|
}
|
|
69
70
|
interface DatabaseTransactionFactory<ConnectorType extends string = string> {
|
|
70
71
|
transaction: () => DatabaseTransaction<ConnectorType>;
|
|
71
|
-
withTransaction: <Result =
|
|
72
|
-
success: boolean;
|
|
73
|
-
result: Result;
|
|
74
|
-
}>) => Promise<Result>;
|
|
72
|
+
withTransaction: <Result = never>(handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
|
|
75
73
|
}
|
|
76
|
-
|
|
74
|
+
type TransactionResult<Result> = {
|
|
77
75
|
success: boolean;
|
|
78
76
|
result: Result;
|
|
79
|
-
}
|
|
77
|
+
};
|
|
78
|
+
declare const executeInTransaction: <ConnectorType extends string = string, Result = void>(transaction: DatabaseTransaction<ConnectorType>, handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
|
|
80
79
|
declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>) => DatabaseTransactionFactory<ConnectorType>;
|
|
81
80
|
declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection<string, unknown> = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType['type']>;
|
|
82
81
|
|
|
83
82
|
interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
|
|
84
83
|
type: ConnectorType;
|
|
85
|
-
|
|
84
|
+
open: () => Promise<DbClient>;
|
|
86
85
|
close: () => Promise<void>;
|
|
87
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;
|
|
88
99
|
|
|
89
|
-
interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectionType['type']> {
|
|
100
|
+
interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, ConnectionFactory<ConnectionType>, DatabaseTransactionFactory<ConnectionType['type']> {
|
|
90
101
|
type: ConnectionType['type'];
|
|
91
|
-
open: () => Promise<ConnectionType>;
|
|
92
102
|
close: () => Promise<void>;
|
|
93
103
|
}
|
|
94
|
-
type
|
|
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;
|
|
95
108
|
|
|
96
109
|
declare const defaultPostgreSqlDatabase = "postgres";
|
|
97
110
|
declare const tableExistsSQL: (tableName: string) => SQL;
|
|
@@ -122,51 +135,73 @@ declare function nodePostgresConnection(options: NodePostgresPoolClientOptions):
|
|
|
122
135
|
declare function nodePostgresConnection(options: NodePostgresClientOptions): NodePostgresClientConnection;
|
|
123
136
|
|
|
124
137
|
type NodePostgresNativePool = ConnectionPool<NodePostgresPoolClientConnection>;
|
|
125
|
-
type
|
|
138
|
+
type NodePostgresAmbientClientPool = ConnectionPool<NodePostgresClientConnection>;
|
|
139
|
+
type NodePostgresAmbientConnectionPool = ConnectionPool<NodePostgresPoolClientConnection | NodePostgresClientConnection>;
|
|
140
|
+
type NodePostgresPool = NodePostgresNativePool | NodePostgresAmbientClientPool | NodePostgresAmbientConnectionPool;
|
|
126
141
|
declare const nodePostgresNativePool: (options: {
|
|
127
142
|
connectionString: string;
|
|
128
|
-
database?: string;
|
|
129
|
-
|
|
143
|
+
database?: string | undefined;
|
|
144
|
+
}) => NodePostgresNativePool;
|
|
145
|
+
declare const nodePostgresAmbientNativePool: (options: {
|
|
146
|
+
pool: pg.Pool;
|
|
130
147
|
}) => NodePostgresNativePool;
|
|
131
|
-
declare const
|
|
148
|
+
declare const nodePostgresAmbientConnectionPool: (options: {
|
|
149
|
+
connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;
|
|
150
|
+
}) => NodePostgresAmbientConnectionPool;
|
|
151
|
+
declare const nodePostgresClientPool: (options: {
|
|
132
152
|
connectionString: string;
|
|
133
|
-
database?: string;
|
|
134
|
-
|
|
135
|
-
|
|
153
|
+
database?: string | undefined;
|
|
154
|
+
}) => NodePostgresAmbientClientPool;
|
|
155
|
+
declare const nodePostgresAmbientClientPool: (options: {
|
|
156
|
+
client: pg.Client;
|
|
157
|
+
}) => NodePostgresAmbientClientPool;
|
|
136
158
|
type NodePostgresPoolPooledOptions = {
|
|
159
|
+
connector?: NodePostgresConnector;
|
|
137
160
|
connectionString: string;
|
|
138
161
|
database?: string;
|
|
139
162
|
pooled: true;
|
|
140
163
|
pool: pg.Pool;
|
|
141
164
|
} | {
|
|
165
|
+
connector?: NodePostgresConnector;
|
|
142
166
|
connectionString: string;
|
|
143
167
|
database?: string;
|
|
144
168
|
pool: pg.Pool;
|
|
145
169
|
} | {
|
|
170
|
+
connector?: NodePostgresConnector;
|
|
146
171
|
connectionString: string;
|
|
147
172
|
database?: string;
|
|
148
173
|
pooled: true;
|
|
149
174
|
} | {
|
|
175
|
+
connector?: NodePostgresConnector;
|
|
150
176
|
connectionString: string;
|
|
151
177
|
database?: string;
|
|
152
178
|
};
|
|
153
179
|
type NodePostgresPoolNotPooledOptions = {
|
|
180
|
+
connector?: NodePostgresConnector;
|
|
154
181
|
connectionString: string;
|
|
155
182
|
database?: string;
|
|
156
183
|
pooled: false;
|
|
157
184
|
client: pg.Client;
|
|
158
185
|
} | {
|
|
186
|
+
connector?: NodePostgresConnector;
|
|
159
187
|
connectionString: string;
|
|
160
188
|
database?: string;
|
|
161
189
|
client: pg.Client;
|
|
162
190
|
} | {
|
|
191
|
+
connector?: NodePostgresConnector;
|
|
163
192
|
connectionString: string;
|
|
164
193
|
database?: string;
|
|
165
194
|
pooled: false;
|
|
195
|
+
} | {
|
|
196
|
+
connector?: NodePostgresConnector;
|
|
197
|
+
connectionString: string;
|
|
198
|
+
database?: string;
|
|
199
|
+
connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;
|
|
200
|
+
pooled?: false;
|
|
166
201
|
};
|
|
167
202
|
type NodePostgresPoolOptions = NodePostgresPoolPooledOptions | NodePostgresPoolNotPooledOptions;
|
|
168
203
|
declare function nodePostgresPool(options: NodePostgresPoolPooledOptions): NodePostgresNativePool;
|
|
169
|
-
declare function nodePostgresPool(options: NodePostgresPoolNotPooledOptions):
|
|
204
|
+
declare function nodePostgresPool(options: NodePostgresPoolNotPooledOptions): NodePostgresAmbientClientPool;
|
|
170
205
|
declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
|
|
171
206
|
declare const endPool: ({ connectionString, database, force, }: {
|
|
172
207
|
connectionString: string;
|
|
@@ -177,7 +212,7 @@ declare const onEndPool: (lookupKey: string, pool: pg.Pool) => Promise<void>;
|
|
|
177
212
|
declare const endAllPools: () => Promise<void[]>;
|
|
178
213
|
|
|
179
214
|
type NodePostgresTransaction = DatabaseTransaction<NodePostgresConnector>;
|
|
180
|
-
declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(getClient: Promise<DbClient>, options?: {
|
|
215
|
+
declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(connection: () => Connection<NodePostgresConnector, DbClient>) => (getClient: Promise<DbClient>, options?: {
|
|
181
216
|
close: (client: DbClient, error?: unknown) => Promise<void>;
|
|
182
217
|
} | undefined) => DatabaseTransaction<NodePostgresConnector>;
|
|
183
218
|
|
|
@@ -190,10 +225,16 @@ declare const nodePostgresSQLExecutor: () => NodePostgresSQLExecutor;
|
|
|
190
225
|
|
|
191
226
|
type PostgresConnector = NodePostgresConnector;
|
|
192
227
|
type PostgresPoolOptions = NodePostgresPoolOptions;
|
|
228
|
+
type PostgresPool = NodePostgresPool;
|
|
193
229
|
declare const postgresPool: typeof nodePostgresPool;
|
|
194
230
|
|
|
195
231
|
type ConnectorType = PostgresConnector;
|
|
196
|
-
type PoolOptions =
|
|
197
|
-
|
|
232
|
+
type PoolOptions = {
|
|
233
|
+
connector?: ConnectorType;
|
|
234
|
+
};
|
|
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;
|
|
198
239
|
|
|
199
|
-
export { type Connection, type ConnectionPool, type
|
|
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
|
@@ -50,48 +50,61 @@ declare const sqlExecutor: <DbClient = unknown, DbExecutor extends DbSQLExecutor
|
|
|
50
50
|
close?: (client: DbClient, error?: unknown) => Promise<void>;
|
|
51
51
|
}) => SQLExecutor;
|
|
52
52
|
declare const sqlExecutorInNewConnection: <ConnectionType extends Connection<string, unknown>>(options: {
|
|
53
|
-
|
|
53
|
+
connection: () => Promise<ConnectionType>;
|
|
54
54
|
}) => SQLExecutor;
|
|
55
55
|
declare const executeInNewDbClient: <DbClient = unknown, Result = unknown>(handle: (client: DbClient) => Promise<Result>, options: {
|
|
56
56
|
connect: () => Promise<DbClient>;
|
|
57
57
|
close?: (client: DbClient, error?: unknown) => Promise<void>;
|
|
58
58
|
}) => Promise<Result>;
|
|
59
|
-
declare const executeInNewConnection: <ConnectionType extends Connection<string, unknown>, Result
|
|
60
|
-
|
|
59
|
+
declare const executeInNewConnection: <ConnectionType extends Connection<string, unknown>, Result>(handle: (connection: ConnectionType) => Promise<Result>, options: {
|
|
60
|
+
connection: () => Promise<ConnectionType>;
|
|
61
61
|
}) => Promise<Result>;
|
|
62
62
|
|
|
63
|
-
interface DatabaseTransaction<ConnectorType extends string = string> extends WithSQLExecutor {
|
|
63
|
+
interface DatabaseTransaction<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor {
|
|
64
64
|
type: ConnectorType;
|
|
65
|
+
connection: Connection<ConnectorType, DbClient>;
|
|
65
66
|
begin: () => Promise<void>;
|
|
66
67
|
commit: () => Promise<void>;
|
|
67
68
|
rollback: (error?: unknown) => Promise<void>;
|
|
68
69
|
}
|
|
69
70
|
interface DatabaseTransactionFactory<ConnectorType extends string = string> {
|
|
70
71
|
transaction: () => DatabaseTransaction<ConnectorType>;
|
|
71
|
-
withTransaction: <Result =
|
|
72
|
-
success: boolean;
|
|
73
|
-
result: Result;
|
|
74
|
-
}>) => Promise<Result>;
|
|
72
|
+
withTransaction: <Result = never>(handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
|
|
75
73
|
}
|
|
76
|
-
|
|
74
|
+
type TransactionResult<Result> = {
|
|
77
75
|
success: boolean;
|
|
78
76
|
result: Result;
|
|
79
|
-
}
|
|
77
|
+
};
|
|
78
|
+
declare const executeInTransaction: <ConnectorType extends string = string, Result = void>(transaction: DatabaseTransaction<ConnectorType>, handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
|
|
80
79
|
declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>) => DatabaseTransactionFactory<ConnectorType>;
|
|
81
80
|
declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection<string, unknown> = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType['type']>;
|
|
82
81
|
|
|
83
82
|
interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
|
|
84
83
|
type: ConnectorType;
|
|
85
|
-
|
|
84
|
+
open: () => Promise<DbClient>;
|
|
86
85
|
close: () => Promise<void>;
|
|
87
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;
|
|
88
99
|
|
|
89
|
-
interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectionType['type']> {
|
|
100
|
+
interface ConnectionPool<ConnectionType extends Connection = Connection> extends WithSQLExecutor, ConnectionFactory<ConnectionType>, DatabaseTransactionFactory<ConnectionType['type']> {
|
|
90
101
|
type: ConnectionType['type'];
|
|
91
|
-
open: () => Promise<ConnectionType>;
|
|
92
102
|
close: () => Promise<void>;
|
|
93
103
|
}
|
|
94
|
-
type
|
|
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;
|
|
95
108
|
|
|
96
109
|
declare const defaultPostgreSqlDatabase = "postgres";
|
|
97
110
|
declare const tableExistsSQL: (tableName: string) => SQL;
|
|
@@ -122,51 +135,73 @@ declare function nodePostgresConnection(options: NodePostgresPoolClientOptions):
|
|
|
122
135
|
declare function nodePostgresConnection(options: NodePostgresClientOptions): NodePostgresClientConnection;
|
|
123
136
|
|
|
124
137
|
type NodePostgresNativePool = ConnectionPool<NodePostgresPoolClientConnection>;
|
|
125
|
-
type
|
|
138
|
+
type NodePostgresAmbientClientPool = ConnectionPool<NodePostgresClientConnection>;
|
|
139
|
+
type NodePostgresAmbientConnectionPool = ConnectionPool<NodePostgresPoolClientConnection | NodePostgresClientConnection>;
|
|
140
|
+
type NodePostgresPool = NodePostgresNativePool | NodePostgresAmbientClientPool | NodePostgresAmbientConnectionPool;
|
|
126
141
|
declare const nodePostgresNativePool: (options: {
|
|
127
142
|
connectionString: string;
|
|
128
|
-
database?: string;
|
|
129
|
-
|
|
143
|
+
database?: string | undefined;
|
|
144
|
+
}) => NodePostgresNativePool;
|
|
145
|
+
declare const nodePostgresAmbientNativePool: (options: {
|
|
146
|
+
pool: pg.Pool;
|
|
130
147
|
}) => NodePostgresNativePool;
|
|
131
|
-
declare const
|
|
148
|
+
declare const nodePostgresAmbientConnectionPool: (options: {
|
|
149
|
+
connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;
|
|
150
|
+
}) => NodePostgresAmbientConnectionPool;
|
|
151
|
+
declare const nodePostgresClientPool: (options: {
|
|
132
152
|
connectionString: string;
|
|
133
|
-
database?: string;
|
|
134
|
-
|
|
135
|
-
|
|
153
|
+
database?: string | undefined;
|
|
154
|
+
}) => NodePostgresAmbientClientPool;
|
|
155
|
+
declare const nodePostgresAmbientClientPool: (options: {
|
|
156
|
+
client: pg.Client;
|
|
157
|
+
}) => NodePostgresAmbientClientPool;
|
|
136
158
|
type NodePostgresPoolPooledOptions = {
|
|
159
|
+
connector?: NodePostgresConnector;
|
|
137
160
|
connectionString: string;
|
|
138
161
|
database?: string;
|
|
139
162
|
pooled: true;
|
|
140
163
|
pool: pg.Pool;
|
|
141
164
|
} | {
|
|
165
|
+
connector?: NodePostgresConnector;
|
|
142
166
|
connectionString: string;
|
|
143
167
|
database?: string;
|
|
144
168
|
pool: pg.Pool;
|
|
145
169
|
} | {
|
|
170
|
+
connector?: NodePostgresConnector;
|
|
146
171
|
connectionString: string;
|
|
147
172
|
database?: string;
|
|
148
173
|
pooled: true;
|
|
149
174
|
} | {
|
|
175
|
+
connector?: NodePostgresConnector;
|
|
150
176
|
connectionString: string;
|
|
151
177
|
database?: string;
|
|
152
178
|
};
|
|
153
179
|
type NodePostgresPoolNotPooledOptions = {
|
|
180
|
+
connector?: NodePostgresConnector;
|
|
154
181
|
connectionString: string;
|
|
155
182
|
database?: string;
|
|
156
183
|
pooled: false;
|
|
157
184
|
client: pg.Client;
|
|
158
185
|
} | {
|
|
186
|
+
connector?: NodePostgresConnector;
|
|
159
187
|
connectionString: string;
|
|
160
188
|
database?: string;
|
|
161
189
|
client: pg.Client;
|
|
162
190
|
} | {
|
|
191
|
+
connector?: NodePostgresConnector;
|
|
163
192
|
connectionString: string;
|
|
164
193
|
database?: string;
|
|
165
194
|
pooled: false;
|
|
195
|
+
} | {
|
|
196
|
+
connector?: NodePostgresConnector;
|
|
197
|
+
connectionString: string;
|
|
198
|
+
database?: string;
|
|
199
|
+
connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;
|
|
200
|
+
pooled?: false;
|
|
166
201
|
};
|
|
167
202
|
type NodePostgresPoolOptions = NodePostgresPoolPooledOptions | NodePostgresPoolNotPooledOptions;
|
|
168
203
|
declare function nodePostgresPool(options: NodePostgresPoolPooledOptions): NodePostgresNativePool;
|
|
169
|
-
declare function nodePostgresPool(options: NodePostgresPoolNotPooledOptions):
|
|
204
|
+
declare function nodePostgresPool(options: NodePostgresPoolNotPooledOptions): NodePostgresAmbientClientPool;
|
|
170
205
|
declare const getPool: (connectionStringOrOptions: string | pg.PoolConfig) => pg.Pool;
|
|
171
206
|
declare const endPool: ({ connectionString, database, force, }: {
|
|
172
207
|
connectionString: string;
|
|
@@ -177,7 +212,7 @@ declare const onEndPool: (lookupKey: string, pool: pg.Pool) => Promise<void>;
|
|
|
177
212
|
declare const endAllPools: () => Promise<void[]>;
|
|
178
213
|
|
|
179
214
|
type NodePostgresTransaction = DatabaseTransaction<NodePostgresConnector>;
|
|
180
|
-
declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(getClient: Promise<DbClient>, options?: {
|
|
215
|
+
declare const nodePostgresTransaction: <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(connection: () => Connection<NodePostgresConnector, DbClient>) => (getClient: Promise<DbClient>, options?: {
|
|
181
216
|
close: (client: DbClient, error?: unknown) => Promise<void>;
|
|
182
217
|
} | undefined) => DatabaseTransaction<NodePostgresConnector>;
|
|
183
218
|
|
|
@@ -190,10 +225,16 @@ declare const nodePostgresSQLExecutor: () => NodePostgresSQLExecutor;
|
|
|
190
225
|
|
|
191
226
|
type PostgresConnector = NodePostgresConnector;
|
|
192
227
|
type PostgresPoolOptions = NodePostgresPoolOptions;
|
|
228
|
+
type PostgresPool = NodePostgresPool;
|
|
193
229
|
declare const postgresPool: typeof nodePostgresPool;
|
|
194
230
|
|
|
195
231
|
type ConnectorType = PostgresConnector;
|
|
196
|
-
type PoolOptions =
|
|
197
|
-
|
|
232
|
+
type PoolOptions = {
|
|
233
|
+
connector?: ConnectorType;
|
|
234
|
+
};
|
|
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;
|
|
198
239
|
|
|
199
|
-
export { type Connection, type ConnectionPool, type
|
|
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
|
|
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),
|
|
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)
|
|
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/postgres/core/connections/connectionString.ts","../src/core/connections/transaction.ts","../src/core/sql/index.ts","../src/core/execute/execute.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<ConnectorType extends string = string>\n extends WithSQLExecutor {\n type: ConnectorType;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n> {\n transaction: () => DatabaseTransaction<ConnectorType>;\n\n withTransaction: <Result = unknown>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<{ success: boolean; result: Result }>,\n ) => Promise<Result>;\n}\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n Result = unknown,\n>(\n transaction: DatabaseTransaction<ConnectorType>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType>,\n ) => Promise<{ success: boolean; result: Result }>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = await handle(transaction);\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType>,\n): DatabaseTransactionFactory<ConnectorType> => ({\n transaction: () => initTransaction(connect()),\n withTransaction: (handle) =>\n executeInTransaction(initTransaction(connect()), handle),\n});\n\nconst wrapInConnectionClosure = async <\n ConnectionType extends Connection = Connection,\n Result = unknown,\n>(\n connection: ConnectionType,\n handle: () => Promise<Result>,\n) => {\n try {\n return await handle();\n } finally {\n await connection.close();\n }\n};\n\nexport const transactionFactoryWithNewConnection = <\n ConnectionType extends Connection = Connection,\n>(\n connect: () => ConnectionType,\n): DatabaseTransactionFactory<ConnectionType['type']> => ({\n transaction: () => {\n const connection = connect();\n const transaction = connection.transaction();\n\n return {\n ...transaction,\n commit: () =>\n wrapInConnectionClosure(connection, () => transaction.commit()),\n rollback: () =>\n wrapInConnectionClosure(connection, () => transaction.rollback()),\n };\n },\n withTransaction: (handle) => {\n const connection = connect();\n return wrapInConnectionClosure(connection, () =>\n connection.withTransaction(handle),\n );\n },\n});\n","import format from 'pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n open: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result extends QueryResultRow = QueryResultRow,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n open: () => Promise<ConnectionType>;\n },\n) => {\n const { open } = options;\n const connection = await open();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport {\n sqlExecutor,\n transactionFactoryWithDbClient,\n type Connection,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n let client: pg.Client | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n return {\n type: NodePostgresConnectorType,\n connect: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(getClient, nodePostgresTransaction),\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: getClient }),\n };\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n let client: pg.PoolClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n return {\n type: NodePostgresConnectorType,\n connect: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(getClient, nodePostgresTransaction),\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: getClient }),\n };\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import { sqlExecutor, type DatabaseTransaction } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction = <\n DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient,\n>(\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n): DatabaseTransaction<NodePostgresConnector> => ({\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), { connect: () => getClient }),\n});\n","import pg from 'pg';\nimport {\n sqlExecutorInNewConnection,\n transactionFactoryWithNewConnection,\n type ConnectionPool,\n} from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresExplicitClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string;\n pool?: pg.Pool;\n}): NodePostgresNativePool => {\n const { connectionString, database, pool: ambientPool } = options;\n const pool = ambientPool\n ? ambientPool\n : getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = async () => {\n if (!ambientPool) await endPool({ connectionString, database });\n };\n\n return {\n type: NodePostgresConnectorType,\n open,\n close,\n execute: sqlExecutorInNewConnection({ open }),\n ...transactionFactoryWithNewConnection(getConnection),\n };\n};\n\nexport const nodePostgresExplicitClientPool = (options: {\n connectionString: string;\n database?: string;\n client?: pg.Client;\n}): NodePostgresExplicitClientPool => {\n const { connectionString, database, client: ambientClient } = options;\n\n const getConnection = () => {\n const connect = ambientClient\n ? Promise.resolve(ambientClient)\n : Promise.resolve(new pg.Client({ connectionString, database })).then(\n async (client) => {\n await client.connect();\n return client;\n },\n );\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => (ambientClient ? Promise.resolve() : client.end()),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = async () => {\n if (!ambientClient) await endPool({ connectionString, database });\n };\n\n return {\n type: NodePostgresConnectorType,\n open,\n close,\n execute: sqlExecutorInNewConnection({ open }),\n ...transactionFactoryWithNewConnection(getConnection),\n };\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connectionString: string;\n database?: string;\n pooled: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresExplicitClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n): NodePostgresNativePool | NodePostgresExplicitClientPool {\n const { connectionString, database } = options;\n\n if (('pooled' in options && options.pooled === false) || 'client' in options)\n return nodePostgresExplicitClientPool({\n connectionString,\n ...(database ? { database } : {}),\n ...('client' in options && options.client\n ? { client: options.client }\n : {}),\n });\n\n return nodePostgresNativePool({\n connectionString,\n ...(database ? { database } : {}),\n ...('pool' in options && options.pool ? { pool: options.pool } : {}),\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnector,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\nexport type PoolOptions = PostgresPoolOptions;\n\nexport const connectionPool = (_type: ConnectorType, options: PoolOptions) =>\n postgresPool(options);\n"],"mappings":"AAAA,OAAOA,MAAU,uBCuBV,IAAMC,EAAuB,MAIlCC,EACAC,IAGoB,CACpB,MAAMD,EAAY,MAAM,EAExB,GAAI,CACF,GAAM,CAAE,QAAAE,EAAS,OAAAC,CAAO,EAAI,MAAMF,EAAOD,CAAW,EAEpD,OAAIE,EAAS,MAAMF,EAAY,OAAO,EACjC,MAAMA,EAAY,SAAS,EAEzBG,CACT,OAASC,EAAG,CACV,YAAMJ,EAAY,SAAS,EACrBI,CACR,CACF,EAEaC,EAAiC,CAI5CC,EACAC,KAG+C,CAC/C,YAAa,IAAMA,EAAgBD,EAAQ,CAAC,EAC5C,gBAAkBL,GAChBF,EAAqBQ,EAAgBD,EAAQ,CAAC,EAAGL,CAAM,CAC3D,GAEMO,EAA0B,MAI9BC,EACAR,IACG,CACH,GAAI,CACF,OAAO,MAAMA,EAAO,CACtB,QAAE,CACA,MAAMQ,EAAW,MAAM,CACzB,CACF,EAEaC,EAGXJ,IACwD,CACxD,YAAa,IAAM,CACjB,IAAMG,EAAaH,EAAQ,EACrBN,EAAcS,EAAW,YAAY,EAE3C,MAAO,CACL,GAAGT,EACH,OAAQ,IACNQ,EAAwBC,EAAY,IAAMT,EAAY,OAAO,CAAC,EAChE,SAAU,IACRQ,EAAwBC,EAAY,IAAMT,EAAY,SAAS,CAA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BF,EAAW,EAAE,GAAK,GAAKG,IAAU,KACnE,MAAMC,EAAUJ,EAAWpB,CAAI,CAEnC,EAEawB,EAAY,MAAOJ,EAAmBpB,IAAkB,CACnE,GAAI,CACF,MAAMA,EAAK,IAAI,CACjB,OAASyB,EAAO,CACd,QAAQ,IAAI,4CAA4CL,CAAS,EAAE,EACnE,QAAQ,IAAIK,CAAK,CACnB,CACAV,EAAM,OAAOK,CAAS,CACxB,EAEaM,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGX,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACK,EAAWpB,CAAI,IAAMwB,EAAUJ,EAAWpB,CAAI,CAAC,CAC5E,EAEIqB,EAAM,CAACxB,EAA0BC,IACrC,GAAGD,CAAgB,IAAIC,GAAY6B,CAAyB,GAExDL,EAAyB,CAACF,EAAmBQ,IAAuB,CACxE,IAAMC,EAAiBb,EAAa,IAAII,CAAS,GAAK,EAChDU,EAAaD,EAAiBD,EAEpC,OAAAZ,EAAa,IAAII,EAAWS,EAAiBD,CAAE,EAExCE,CACT,ECpOO,IAAMC,EAAeC,ECErB,IAAMC,GAAiB,CAACC,EAAsBC,IACnDC,EAAaD,CAAO","names":["pgcs","executeInTransaction","transaction","handle","success","result","e","transactionFactoryWithDbClient","connect","initTransaction","wrapInConnectionClosure","connection","transactionFactoryWithNewConnection","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","sql","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","open","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","getResult","result","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","sql","tableExists","pool","exists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pgcs","defaultPostgreSqlDatabase","pg","isNodePostgresNativePool","poolOrClient","pg","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","handle","client","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","sqls","results","i","result","nodePostgresTransaction","getClient","options","NodePostgresConnectorType","client","error","sqlExecutor","nodePostgresSQLExecutor","NodePostgresConnectorType","nodePostgresClientConnection","options","connect","close","client","getClient","transactionFactoryWithDbClient","nodePostgresTransaction","sqlExecutor","nodePostgresSQLExecutor","nodePostgresPoolClientConnection","nodePostgresConnection","pg","nodePostgresNativePool","options","connectionString","database","ambientPool","pool","getPool","getConnection","nodePostgresConnection","client","open","NodePostgresConnectorType","endPool","sqlExecutorInNewConnection","transactionFactoryWithNewConnection","nodePostgresExplicitClientPool","ambientClient","connect","pg","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","getDatabaseNameOrDefault","lookupKey","key","updatePoolUsageCounter","force","onEndPool","error","endAllPools","defaultPostgreSqlDatabase","by","currentCounter","newCounter","postgresPool","nodePostgresPool","connectionPool","_type","options","postgresPool"]}
|
|
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,MAAU,uBCAjB,OAAOC,MAAY,YAKZ,IAAMC,EAAM,CAACC,KAAqBC,IAChCH,EAAOE,EAAU,GAAGC,CAAM,EAGtBC,GAAUF,GACdA,ECoCF,IAAMG,EAAc,CAIzBA,EAEAC,KAIiB,CACjB,MAAQC,GACNC,EAAsBC,GAAWJ,EAAY,MAAM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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"]}
|