@event-driven-io/dumbo 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -8,5 +8,5 @@
8
8
  WHERE
9
9
  proname = %L
10
10
  ) AS exists;
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;
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 C(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=()=>C({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:()=>C({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 C({type:"Client",connect:n,close:s=>s.end()})}})},Z= exports.nodePostgresAmbientClientPool =e=>{let{client:o}=e,t=()=>{let r=Promise.resolve(o);return C({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 P=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=q(o,n);return A(s,1),_nullishCoalesce(P.get(s), () => (P.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=q(e,o),s=P.get(n);s&&(A(n,-1)<=0||t===!0)&&await k(n,s)},k= exports.onEndPool =async(e,o)=>{try{await o.end()}catch(t){console.log(`Error while closing the connection pool: ${e}`),console.log(t)}P.delete(e)},To= exports.endAllPools =()=>Promise.all([...P.entries()].map(([e,o])=>k(e,o))),q=(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 = C; exports.nodePostgresExecute = so; exports.nodePostgresNativePool = K; exports.nodePostgresPool = v; exports.nodePostgresPoolClientConnection = G; exports.nodePostgresSQLExecutor = p; exports.nodePostgresTransaction = f; exports.onEndPool = k; exports.postgresPool = F; exports.rawSql = se; exports.single = B; exports.singleOrNull = he; exports.sql = R; exports.sqlExecutor = d; exports.sqlExecutorInNewConnection = N; exports.tableExists = _e; exports.tableExistsSQL = H; exports.toCamelCase = $; exports.transactionFactoryWithDbClient = D; exports.transactionFactoryWithNewConnection = S;
12
12
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/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,EA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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"]}
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","postgresP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O,CACd,QAAQ,IAAI,4CAA4C2E,CAAS,EAAE,EACnE,QAAQ,IAAI3E,CAAK,CACnB,CACAuE,EAAM,OAAOI,CAAS,CACxB,EAEaI,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGR,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACI,EAAWzD,CAAI,IAAM4D,EAAUH,EAAWzD,CAAI,CAAC,CAC5E,EAEIa,EAAM,CAACc,EAA0BkB,IACrC,GAAGlB,CAAgB,IAAIkB,GAAY1B,CAAyB,GAExDuC,EAAyB,CAACD,EAAmBK,IAAuB,CACxE,IAAMC,EAAiBT,EAAa,IAAIG,CAAS,GAAK,EAChDO,EAAaD,EAAiBD,EAEpC,OAAAR,EAAa,IAAIG,EAAWM,EAAiBD,CAAE,EAExCE,CACT,EClSO,IAAMC,EAAeb,ECKrB,IAAMc,GACX9F,GAGA6F,EAAa7F,CAAyC,EAE3C+F,GACX/F,GACU8F,GAAe9F,CAAO","sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import format from 'pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n connection: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n connection: () => Promise<ConnectionType>;\n },\n) => {\n const connection = await options.connection();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor {\n type: ConnectorType;\n connection: Connection<ConnectorType, DbClient>;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n transaction: () => DatabaseTransaction<ConnectorType, DbClient>;\n\n withTransaction: <Result = never>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n ) => Promise<Result>;\n}\n\nexport type TransactionResult<Result> = { success: boolean; result: Result };\n\nconst toTransactionResult = <Result>(\n transactionResult: TransactionResult<Result> | Result,\n): TransactionResult<Result> =>\n transactionResult !== undefined &&\n transactionResult !== null &&\n typeof transactionResult === 'object' &&\n 'success' in transactionResult\n ? transactionResult\n : { success: true, result: transactionResult };\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n DbClient = unknown,\n Result = void,\n>(\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = toTransactionResult(await handle(transaction));\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>,\n): DatabaseTransactionFactory<ConnectorType, DbClient> => ({\n transaction: () => initTransaction(connect()),\n withTransaction: (handle) =>\n executeInTransaction(initTransaction(connect()), handle),\n});\n\nconst wrapInConnectionClosure = async <\n ConnectionType extends Connection = Connection,\n Result = unknown,\n>(\n connection: ConnectionType,\n handle: () => Promise<Result>,\n) => {\n try {\n return await handle();\n } finally {\n await connection.close();\n }\n};\n\nexport const transactionFactoryWithNewConnection = <\n ConnectionType extends Connection = Connection,\n>(\n connect: () => ConnectionType,\n): DatabaseTransactionFactory<ConnectionType['type']> => ({\n transaction: () => {\n const connection = connect();\n const transaction = connection.transaction();\n\n return {\n ...transaction,\n commit: () =>\n wrapInConnectionClosure(connection, () => transaction.commit()),\n rollback: () =>\n wrapInConnectionClosure(connection, () => transaction.rollback()),\n };\n },\n withTransaction: (handle) => {\n const connection = connect();\n return wrapInConnectionClosure(connection, () =>\n connection.withTransaction(handle),\n );\n },\n});\n","import {\n sqlExecutor,\n type DbSQLExecutor,\n type WithSQLExecutor,\n} from '../execute';\nimport {\n transactionFactoryWithDbClient,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface Connection<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor,\n DatabaseTransactionFactory<ConnectorType> {\n type: ConnectorType;\n open: () => Promise<DbClient>;\n close: () => Promise<void>;\n}\n\nexport interface ConnectionFactory<\n ConnectionType extends Connection = Connection,\n> {\n connection: () => Promise<ConnectionType>;\n\n withConnection: <Result = unknown>(\n handle: (connection: ConnectionType) => Promise<Result>,\n ) => Promise<Result>;\n}\n\nexport type CreateConnectionOptions<\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n> = {\n type: ConnectorType;\n connect: Promise<DbClient>;\n close: (client: DbClient) => Promise<void>;\n initTransaction: (\n connection: () => ConnectionType,\n ) => (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>;\n executor: () => Executor;\n};\n\nexport const createConnection = <\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n>(\n options: CreateConnectionOptions<\n ConnectorType,\n DbClient,\n ConnectionType,\n Executor\n >,\n): ConnectionType => {\n const { type, connect, close, initTransaction, executor } = options;\n\n let client: DbClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n const connection: Connection<ConnectorType, DbClient> = {\n type: type,\n open: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(\n getClient,\n initTransaction(() => typedConnection),\n ),\n execute: sqlExecutor(executor(), { connect: getClient }),\n };\n\n const typedConnection = connection as ConnectionType;\n\n return typedConnection;\n};\n","import {\n executeInNewConnection,\n sqlExecutorInNewConnection,\n type WithSQLExecutor,\n} from '../execute';\nimport { type Connection, type ConnectionFactory } from './connection';\nimport {\n transactionFactoryWithNewConnection,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface ConnectionPool<ConnectionType extends Connection = Connection>\n extends WithSQLExecutor,\n ConnectionFactory<ConnectionType>,\n DatabaseTransactionFactory<ConnectionType['type']> {\n type: ConnectionType['type'];\n close: () => Promise<void>;\n}\n\nexport type ConnectionPoolFactory<\n ConnectionPoolType extends ConnectionPool = ConnectionPool,\n ConnectionPoolOptions = unknown,\n> = (options: ConnectionPoolOptions) => ConnectionPoolType;\n\nexport const createConnectionPool = <\n ConnectionType extends Connection,\n ConnectionPoolType extends ConnectionPool<ConnectionType>,\n>(\n pool: Pick<ConnectionPool<ConnectionType>, 'type'> &\n Partial<ConnectionPool<ConnectionType>> & {\n getConnection: () => ConnectionType;\n },\n): ConnectionPoolType => {\n const { type, getConnection } = pool;\n\n const connection =\n 'connection' in pool\n ? pool.connection\n : () => Promise.resolve(getConnection());\n\n const withConnection =\n 'withConnection' in pool\n ? pool.withConnection\n : <Result>(handle: (connection: ConnectionType) => Promise<Result>) =>\n executeInNewConnection<ConnectionType, Result>(handle, {\n connection,\n });\n\n const close = 'close' in pool ? pool.close : () => Promise.resolve();\n\n const execute =\n 'execute' in pool\n ? pool.execute\n : sqlExecutorInNewConnection({ connection });\n\n const transaction =\n 'transaction' in pool && 'withTransaction' in pool\n ? {\n transaction: pool.transaction,\n withTransaction: pool.withTransaction,\n }\n : transactionFactoryWithNewConnection(getConnection);\n\n const result: ConnectionPool<ConnectionType> = {\n type,\n connection,\n withConnection,\n close,\n execute,\n ...transaction,\n };\n\n return result as ConnectionPoolType;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport { createConnection, type Connection } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import {\n sqlExecutor,\n type Connection,\n type DatabaseTransaction,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction =\n <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(\n connection: () => Connection<NodePostgresConnector, DbClient>,\n ) =>\n (\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n ): DatabaseTransaction<NodePostgresConnector> => ({\n connection: connection(),\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), {\n connect: () => getClient,\n }),\n });\n","import pg from 'pg';\nimport { createConnectionPool, type ConnectionPool } from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresConnector,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresAmbientClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport type NodePostgresAmbientConnectionPool = ConnectionPool<\n NodePostgresPoolClientConnection | NodePostgresClientConnection\n>;\n\nexport type NodePostgresPool =\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresNativePool => {\n const { connectionString, database } = options;\n const pool = getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = () => endPool({ connectionString, database });\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport const nodePostgresAmbientNativePool = (options: {\n pool: pg.Pool;\n}): NodePostgresNativePool => {\n const { pool } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n }),\n });\n};\n\nexport const nodePostgresAmbientConnectionPool = (options: {\n connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;\n}): NodePostgresAmbientConnectionPool => {\n const { connection } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => connection,\n execute: connection.execute,\n transaction: () => connection.transaction(),\n withTransaction: (handle) => connection.withTransaction(handle),\n });\n};\n\nexport const nodePostgresClientPool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresAmbientClientPool => {\n const { connectionString, database } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => {\n const connect = Promise.resolve(\n new pg.Client({ connectionString, database }),\n ).then(async (client) => {\n await client.connect();\n return client;\n });\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => client.end(),\n });\n },\n });\n};\n\nexport const nodePostgresAmbientClientPool = (options: {\n client: pg.Client;\n}): NodePostgresAmbientClientPool => {\n const { client } = options;\n\n const getConnection = () => {\n const connect = Promise.resolve(client);\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: () => Promise.resolve(),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = () => Promise.resolve();\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n connection:\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n pooled?: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresAmbientClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n):\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool {\n const { connectionString, database } = options;\n\n if ('client' in options && options.client)\n return nodePostgresAmbientClientPool({ client: options.client });\n\n if ('pooled' in options && options.pooled === false)\n return nodePostgresClientPool({ connectionString, database });\n\n if ('connection' in options && options.connection)\n return nodePostgresAmbientConnectionPool({\n connection: options.connection,\n });\n\n if ('pool' in options && options.pool)\n return nodePostgresAmbientNativePool({ pool: options.pool });\n\n return nodePostgresNativePool({\n connectionString,\n database,\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnection,\n type NodePostgresConnector,\n type NodePostgresPool,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport type PostgresPool = NodePostgresPool;\nexport type PostgresConnection = NodePostgresConnection;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPool,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\n\nexport type PoolOptions = {\n connector?: ConnectorType;\n};\n\nexport type DumboOptions = PoolOptions & PostgresPoolOptions;\nexport type Dumbo = PostgresPool;\n\nexport const connectionPool = <PoolOptionsType extends DumboOptions>(\n options: PoolOptionsType,\n) =>\n // TODO: this should have the pattern matching and verification\n postgresPool(options as unknown as PostgresPoolOptions);\n\nexport const dumbo = <DumboOptionsType extends DumboOptions = DumboOptions>(\n options: DumboOptionsType,\n): Dumbo => connectionPool(options);\n"]}
package/dist/index.d.cts CHANGED
@@ -67,16 +67,16 @@ interface DatabaseTransaction<ConnectorType extends string = string, DbClient =
67
67
  commit: () => Promise<void>;
68
68
  rollback: (error?: unknown) => Promise<void>;
69
69
  }
70
- interface DatabaseTransactionFactory<ConnectorType extends string = string> {
71
- transaction: () => DatabaseTransaction<ConnectorType>;
72
- withTransaction: <Result = never>(handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
70
+ interface DatabaseTransactionFactory<ConnectorType extends string = string, DbClient = unknown> {
71
+ transaction: () => DatabaseTransaction<ConnectorType, DbClient>;
72
+ withTransaction: <Result = never>(handle: (transaction: DatabaseTransaction<ConnectorType, DbClient>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
73
73
  }
74
74
  type TransactionResult<Result> = {
75
75
  success: boolean;
76
76
  result: Result;
77
77
  };
78
- declare const executeInTransaction: <ConnectorType extends string = string, Result = void>(transaction: DatabaseTransaction<ConnectorType>, handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
79
- declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>) => DatabaseTransactionFactory<ConnectorType>;
78
+ declare const executeInTransaction: <ConnectorType extends string = string, DbClient = unknown, Result = void>(transaction: DatabaseTransaction<ConnectorType, DbClient>, handle: (transaction: DatabaseTransaction<ConnectorType, DbClient>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
79
+ declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType, DbClient>) => DatabaseTransactionFactory<ConnectorType, DbClient>;
80
80
  declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection<string, unknown> = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType['type']>;
81
81
 
82
82
  interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
@@ -92,7 +92,7 @@ type CreateConnectionOptions<ConnectorType extends string = string, DbClient = u
92
92
  type: ConnectorType;
93
93
  connect: Promise<DbClient>;
94
94
  close: (client: DbClient) => Promise<void>;
95
- initTransaction: (connection: () => ConnectionType) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>;
95
+ initTransaction: (connection: () => ConnectionType) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType, DbClient>;
96
96
  executor: () => Executor;
97
97
  };
98
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;
@@ -226,6 +226,7 @@ declare const nodePostgresSQLExecutor: () => NodePostgresSQLExecutor;
226
226
  type PostgresConnector = NodePostgresConnector;
227
227
  type PostgresPoolOptions = NodePostgresPoolOptions;
228
228
  type PostgresPool = NodePostgresPool;
229
+ type PostgresConnection = NodePostgresConnection;
229
230
  declare const postgresPool: typeof nodePostgresPool;
230
231
 
231
232
  type ConnectorType = PostgresConnector;
@@ -237,4 +238,4 @@ type Dumbo = PostgresPool;
237
238
  declare const connectionPool: <PoolOptionsType extends DumboOptions>(options: PoolOptionsType) => NodePostgresNativePool;
238
239
  declare const dumbo: <DumboOptionsType extends DumboOptions = DumboOptions>(options: DumboOptionsType) => Dumbo;
239
240
 
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 };
241
+ 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 PostgresConnection, 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
@@ -67,16 +67,16 @@ interface DatabaseTransaction<ConnectorType extends string = string, DbClient =
67
67
  commit: () => Promise<void>;
68
68
  rollback: (error?: unknown) => Promise<void>;
69
69
  }
70
- interface DatabaseTransactionFactory<ConnectorType extends string = string> {
71
- transaction: () => DatabaseTransaction<ConnectorType>;
72
- withTransaction: <Result = never>(handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
70
+ interface DatabaseTransactionFactory<ConnectorType extends string = string, DbClient = unknown> {
71
+ transaction: () => DatabaseTransaction<ConnectorType, DbClient>;
72
+ withTransaction: <Result = never>(handle: (transaction: DatabaseTransaction<ConnectorType, DbClient>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
73
73
  }
74
74
  type TransactionResult<Result> = {
75
75
  success: boolean;
76
76
  result: Result;
77
77
  };
78
- declare const executeInTransaction: <ConnectorType extends string = string, Result = void>(transaction: DatabaseTransaction<ConnectorType>, handle: (transaction: DatabaseTransaction<ConnectorType>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
79
- declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>) => DatabaseTransactionFactory<ConnectorType>;
78
+ declare const executeInTransaction: <ConnectorType extends string = string, DbClient = unknown, Result = void>(transaction: DatabaseTransaction<ConnectorType, DbClient>, handle: (transaction: DatabaseTransaction<ConnectorType, DbClient>) => Promise<TransactionResult<Result> | Result>) => Promise<Result>;
79
+ declare const transactionFactoryWithDbClient: <ConnectorType extends string = string, DbClient = unknown>(connect: () => Promise<DbClient>, initTransaction: (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType, DbClient>) => DatabaseTransactionFactory<ConnectorType, DbClient>;
80
80
  declare const transactionFactoryWithNewConnection: <ConnectionType extends Connection<string, unknown> = Connection<string, unknown>>(connect: () => ConnectionType) => DatabaseTransactionFactory<ConnectionType['type']>;
81
81
 
82
82
  interface Connection<ConnectorType extends string = string, DbClient = unknown> extends WithSQLExecutor, DatabaseTransactionFactory<ConnectorType> {
@@ -92,7 +92,7 @@ type CreateConnectionOptions<ConnectorType extends string = string, DbClient = u
92
92
  type: ConnectorType;
93
93
  connect: Promise<DbClient>;
94
94
  close: (client: DbClient) => Promise<void>;
95
- initTransaction: (connection: () => ConnectionType) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType>;
95
+ initTransaction: (connection: () => ConnectionType) => (client: Promise<DbClient>) => DatabaseTransaction<ConnectorType, DbClient>;
96
96
  executor: () => Executor;
97
97
  };
98
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;
@@ -226,6 +226,7 @@ declare const nodePostgresSQLExecutor: () => NodePostgresSQLExecutor;
226
226
  type PostgresConnector = NodePostgresConnector;
227
227
  type PostgresPoolOptions = NodePostgresPoolOptions;
228
228
  type PostgresPool = NodePostgresPool;
229
+ type PostgresConnection = NodePostgresConnection;
229
230
  declare const postgresPool: typeof nodePostgresPool;
230
231
 
231
232
  type ConnectorType = PostgresConnector;
@@ -237,4 +238,4 @@ type Dumbo = PostgresPool;
237
238
  declare const connectionPool: <PoolOptionsType extends DumboOptions>(options: PoolOptionsType) => NodePostgresNativePool;
238
239
  declare const dumbo: <DumboOptionsType extends DumboOptions = DumboOptions>(options: DumboOptionsType) => Dumbo;
239
240
 
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 };
241
+ 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 PostgresConnection, 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
@@ -8,5 +8,5 @@ import X from"pg-connection-string";import I from"pg-format";var R=(e,...o)=>I(e
8
8
  WHERE
9
9
  proname = %L
10
10
  ) AS exists;
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};
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 C(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=()=>C({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:()=>C({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 C({type:"Client",connect:n,close:s=>s.end()})}})},Z=e=>{let{client:o}=e,t=()=>{let r=Promise.resolve(o);return C({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 P=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=q(o,n);return A(s,1),P.get(s)??P.set(s,new O.Pool(t)).get(s)},oe=async({connectionString:e,database:o,force:t})=>{o=o??T(e);let n=q(e,o),s=P.get(n);s&&(A(n,-1)<=0||t===!0)&&await k(n,s)},k=async(e,o)=>{try{await o.end()}catch(t){console.log(`Error while closing the connection pool: ${e}`),console.log(t)}P.delete(e)},To=()=>Promise.all([...P.entries()].map(([e,o])=>k(e,o))),q=(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,C as nodePostgresConnection,so as nodePostgresExecute,K as nodePostgresNativePool,v as nodePostgresPool,G as nodePostgresPoolClientConnection,p as nodePostgresSQLExecutor,f as nodePostgresTransaction,k 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/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,MAAMI,EAAQF,CAAG,EAAGD,CAAO,EAC1E,WAAaI,GACXF,EACGC,GAAWJ,EAAY,WAAWI,EAAQC,CAAI,EAC/CJ,CACF,EACF,QAAUC,GACRC,EAAsBC,GAAWJ,EAAY,QAAQI,EAAQF,CAAG,EAAGD,CAAO,EAC5E,aAAeI,GACbF,EACGC,GAAWJ,EAAY,WAAWI,EAAQC,CAAI,EAC/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,EAAkBC,CAAQ,EAEhD,OAAAyB,EAAuBF,EAAW,CAAC,EAGjCL,EAAM,IAAIK,CAAS,GACnBL,EAAM,IAAIK,EAAW,IAAIR,EAAG,KAAKM,CAAW,CAAC,EAAE,IAAIE,CAAS,CAEhE,EAEaf,GAAU,MAAO,CAC5B,iBAAAT,EACA,SAAAC,EACA,MAAA0B,CACF,IAIqB,CACnB1B,EAAWA,GAAYsB,EAAyBvB,CAAgB,EAChE,IAAMwB,EAAYC,EAAIzB,EAAkBC,CAAQ,EAE1CC,EAAOiB,EAAM,IAAIK,CAAS,EAC5BtB,IAASwB,EAAuBF,EAAW,EAAE,GAAK,GAAKG,IAAU,KACnE,MAAMC,EAAUJ,EAAWtB,CAAI,CAEnC,EAEa0B,EAAY,MAAOJ,EAAmBtB,IAAkB,CACnE,GAAI,CACF,MAAMA,EAAK,IAAI,CACjB,OAAS2B,EAAO,CACd,QAAQ,IAAI,4CAA4CL,CAAS,EAAE,EACnE,QAAQ,IAAIK,CAAK,CACnB,CACAV,EAAM,OAAOK,CAAS,CACxB,EAEaM,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGX,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACK,EAAWtB,CAAI,IAAM0B,EAAUJ,EAAWtB,CAAI,CAAC,CAC5E,EAEIuB,EAAM,CAACzB,EAA0BC,IACrC,GAAGD,CAAgB,IAAIC,GAAY8B,CAAyB,GAExDL,EAAyB,CAACF,EAAmBQ,IAAuB,CACxE,IAAMC,EAAiBb,EAAa,IAAII,CAAS,GAAK,EAChDU,EAAaD,EAAiBD,EAEpC,OAAAZ,EAAa,IAAII,EAAWS,EAAiBD,CAAE,EAExCE,CACT,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"]}
1
+ {"version":3,"sources":["../src/postgres/core/connections/connectionString.ts","../src/core/sql/index.ts","../src/core/execute/execute.ts","../src/core/connections/transaction.ts","../src/core/connections/connection.ts","../src/core/connections/pool.ts","../src/core/query/mappers.ts","../src/core/query/selectors.ts","../src/postgres/core/schema/schema.ts","../src/postgres/pg/connections/connection.ts","../src/postgres/pg/execute/execute.ts","../src/postgres/pg/connections/transaction.ts","../src/postgres/pg/connections/pool.ts","../src/postgres/index.ts","../src/index.ts"],"sourcesContent":["import pgcs from 'pg-connection-string';\nimport { defaultPostgreSqlDatabase } from '../schema';\n\nexport const getDatabaseNameOrDefault = (connectionString: string) =>\n pgcs.parse(connectionString).database ?? defaultPostgreSqlDatabase;\n","import format from 'pg-format';\n// TODO: add core formatter, when adding other database type\n\nexport type SQL = string & { __brand: 'sql' };\n\nexport const sql = (sqlQuery: string, ...params: unknown[]): SQL => {\n return format(sqlQuery, ...params) as SQL;\n};\n\nexport const rawSql = (sqlQuery: string): SQL => {\n return sqlQuery as SQL;\n};\n","import type { Connection } from '../connections';\nimport type { QueryResult, QueryResultRow } from '../query';\nimport { type SQL } from '../sql';\n\nexport interface DbSQLExecutor<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n type: ConnectorType;\n query<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n client: DbClient,\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface SQLExecutor {\n query<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchQuery<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n command<Result extends QueryResultRow = QueryResultRow>(\n sql: SQL,\n ): Promise<QueryResult<Result>>;\n batchCommand<Result extends QueryResultRow = QueryResultRow>(\n sqls: SQL[],\n ): Promise<QueryResult<Result>[]>;\n}\n\nexport interface WithSQLExecutor {\n execute: SQLExecutor;\n}\n\nexport const sqlExecutor = <\n DbClient = unknown,\n DbExecutor extends DbSQLExecutor = DbSQLExecutor,\n>(\n sqlExecutor: DbExecutor,\n // TODO: In the longer term we should have different options for query and command\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): SQLExecutor => ({\n query: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.query(client, sql), options),\n batchQuery: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n command: (sql) =>\n executeInNewDbClient((client) => sqlExecutor.command(client, sql), options),\n batchCommand: (sqls) =>\n executeInNewDbClient(\n (client) => sqlExecutor.batchQuery(client, sqls),\n options,\n ),\n});\n\nexport const sqlExecutorInNewConnection = <\n ConnectionType extends Connection,\n>(options: {\n connection: () => Promise<ConnectionType>;\n}): SQLExecutor => ({\n query: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.query(sql),\n options,\n ),\n batchQuery: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchQuery(sqls),\n options,\n ),\n command: (sql) =>\n executeInNewConnection(\n (connection) => connection.execute.command(sql),\n options,\n ),\n batchCommand: (sqls) =>\n executeInNewConnection(\n (connection) => connection.execute.batchCommand(sqls),\n options,\n ),\n});\n\nexport const executeInNewDbClient = async <\n DbClient = unknown,\n Result = unknown,\n>(\n handle: (client: DbClient) => Promise<Result>,\n options: {\n connect: () => Promise<DbClient>;\n close?: (client: DbClient, error?: unknown) => Promise<void>;\n },\n): Promise<Result> => {\n const { connect, close } = options;\n const client = await connect();\n try {\n return await handle(client);\n } catch (error) {\n if (close) await close(client, error);\n\n throw error;\n }\n};\n\nexport const executeInNewConnection = async <\n ConnectionType extends Connection,\n Result,\n>(\n handle: (connection: ConnectionType) => Promise<Result>,\n options: {\n connection: () => Promise<ConnectionType>;\n },\n) => {\n const connection = await options.connection();\n\n try {\n return await handle(connection);\n } finally {\n await connection.close();\n }\n};\n","import type { WithSQLExecutor } from '../execute';\nimport { type Connection } from './connection';\n\nexport interface DatabaseTransaction<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor {\n type: ConnectorType;\n connection: Connection<ConnectorType, DbClient>;\n begin: () => Promise<void>;\n commit: () => Promise<void>;\n rollback: (error?: unknown) => Promise<void>;\n}\n\nexport interface DatabaseTransactionFactory<\n ConnectorType extends string = string,\n DbClient = unknown,\n> {\n transaction: () => DatabaseTransaction<ConnectorType, DbClient>;\n\n withTransaction: <Result = never>(\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n ) => Promise<Result>;\n}\n\nexport type TransactionResult<Result> = { success: boolean; result: Result };\n\nconst toTransactionResult = <Result>(\n transactionResult: TransactionResult<Result> | Result,\n): TransactionResult<Result> =>\n transactionResult !== undefined &&\n transactionResult !== null &&\n typeof transactionResult === 'object' &&\n 'success' in transactionResult\n ? transactionResult\n : { success: true, result: transactionResult };\n\nexport const executeInTransaction = async <\n ConnectorType extends string = string,\n DbClient = unknown,\n Result = void,\n>(\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n handle: (\n transaction: DatabaseTransaction<ConnectorType, DbClient>,\n ) => Promise<TransactionResult<Result> | Result>,\n): Promise<Result> => {\n await transaction.begin();\n\n try {\n const { success, result } = toTransactionResult(await handle(transaction));\n\n if (success) await transaction.commit();\n else await transaction.rollback();\n\n return result;\n } catch (e) {\n await transaction.rollback();\n throw e;\n }\n};\n\nexport const transactionFactoryWithDbClient = <\n ConnectorType extends string = string,\n DbClient = unknown,\n>(\n connect: () => Promise<DbClient>,\n initTransaction: (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>,\n): DatabaseTransactionFactory<ConnectorType, DbClient> => ({\n transaction: () => initTransaction(connect()),\n withTransaction: (handle) =>\n executeInTransaction(initTransaction(connect()), handle),\n});\n\nconst wrapInConnectionClosure = async <\n ConnectionType extends Connection = Connection,\n Result = unknown,\n>(\n connection: ConnectionType,\n handle: () => Promise<Result>,\n) => {\n try {\n return await handle();\n } finally {\n await connection.close();\n }\n};\n\nexport const transactionFactoryWithNewConnection = <\n ConnectionType extends Connection = Connection,\n>(\n connect: () => ConnectionType,\n): DatabaseTransactionFactory<ConnectionType['type']> => ({\n transaction: () => {\n const connection = connect();\n const transaction = connection.transaction();\n\n return {\n ...transaction,\n commit: () =>\n wrapInConnectionClosure(connection, () => transaction.commit()),\n rollback: () =>\n wrapInConnectionClosure(connection, () => transaction.rollback()),\n };\n },\n withTransaction: (handle) => {\n const connection = connect();\n return wrapInConnectionClosure(connection, () =>\n connection.withTransaction(handle),\n );\n },\n});\n","import {\n sqlExecutor,\n type DbSQLExecutor,\n type WithSQLExecutor,\n} from '../execute';\nimport {\n transactionFactoryWithDbClient,\n type DatabaseTransaction,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface Connection<\n ConnectorType extends string = string,\n DbClient = unknown,\n> extends WithSQLExecutor,\n DatabaseTransactionFactory<ConnectorType> {\n type: ConnectorType;\n open: () => Promise<DbClient>;\n close: () => Promise<void>;\n}\n\nexport interface ConnectionFactory<\n ConnectionType extends Connection = Connection,\n> {\n connection: () => Promise<ConnectionType>;\n\n withConnection: <Result = unknown>(\n handle: (connection: ConnectionType) => Promise<Result>,\n ) => Promise<Result>;\n}\n\nexport type CreateConnectionOptions<\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n> = {\n type: ConnectorType;\n connect: Promise<DbClient>;\n close: (client: DbClient) => Promise<void>;\n initTransaction: (\n connection: () => ConnectionType,\n ) => (\n client: Promise<DbClient>,\n ) => DatabaseTransaction<ConnectorType, DbClient>;\n executor: () => Executor;\n};\n\nexport const createConnection = <\n ConnectorType extends string = string,\n DbClient = unknown,\n ConnectionType extends Connection<ConnectorType, DbClient> = Connection<\n ConnectorType,\n DbClient\n >,\n Executor extends DbSQLExecutor = DbSQLExecutor,\n>(\n options: CreateConnectionOptions<\n ConnectorType,\n DbClient,\n ConnectionType,\n Executor\n >,\n): ConnectionType => {\n const { type, connect, close, initTransaction, executor } = options;\n\n let client: DbClient | null = null;\n\n const getClient = async () => client ?? (client = await connect);\n\n const connection: Connection<ConnectorType, DbClient> = {\n type: type,\n open: getClient,\n close: () => (client ? close(client) : Promise.resolve()),\n ...transactionFactoryWithDbClient(\n getClient,\n initTransaction(() => typedConnection),\n ),\n execute: sqlExecutor(executor(), { connect: getClient }),\n };\n\n const typedConnection = connection as ConnectionType;\n\n return typedConnection;\n};\n","import {\n executeInNewConnection,\n sqlExecutorInNewConnection,\n type WithSQLExecutor,\n} from '../execute';\nimport { type Connection, type ConnectionFactory } from './connection';\nimport {\n transactionFactoryWithNewConnection,\n type DatabaseTransactionFactory,\n} from './transaction';\n\nexport interface ConnectionPool<ConnectionType extends Connection = Connection>\n extends WithSQLExecutor,\n ConnectionFactory<ConnectionType>,\n DatabaseTransactionFactory<ConnectionType['type']> {\n type: ConnectionType['type'];\n close: () => Promise<void>;\n}\n\nexport type ConnectionPoolFactory<\n ConnectionPoolType extends ConnectionPool = ConnectionPool,\n ConnectionPoolOptions = unknown,\n> = (options: ConnectionPoolOptions) => ConnectionPoolType;\n\nexport const createConnectionPool = <\n ConnectionType extends Connection,\n ConnectionPoolType extends ConnectionPool<ConnectionType>,\n>(\n pool: Pick<ConnectionPool<ConnectionType>, 'type'> &\n Partial<ConnectionPool<ConnectionType>> & {\n getConnection: () => ConnectionType;\n },\n): ConnectionPoolType => {\n const { type, getConnection } = pool;\n\n const connection =\n 'connection' in pool\n ? pool.connection\n : () => Promise.resolve(getConnection());\n\n const withConnection =\n 'withConnection' in pool\n ? pool.withConnection\n : <Result>(handle: (connection: ConnectionType) => Promise<Result>) =>\n executeInNewConnection<ConnectionType, Result>(handle, {\n connection,\n });\n\n const close = 'close' in pool ? pool.close : () => Promise.resolve();\n\n const execute =\n 'execute' in pool\n ? pool.execute\n : sqlExecutorInNewConnection({ connection });\n\n const transaction =\n 'transaction' in pool && 'withTransaction' in pool\n ? {\n transaction: pool.transaction,\n withTransaction: pool.withTransaction,\n }\n : transactionFactoryWithNewConnection(getConnection);\n\n const result: ConnectionPool<ConnectionType> = {\n type,\n connection,\n withConnection,\n close,\n execute,\n ...transaction,\n };\n\n return result as ConnectionPoolType;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const mapRows = async <\n Result extends QueryResultRow = QueryResultRow,\n Mapped = unknown,\n>(\n getResult: Promise<QueryResult<Result>>,\n map: (row: Result) => Mapped,\n): Promise<Mapped[]> => {\n const result = await getResult;\n\n return result.rows.map(map);\n};\n\nexport const toCamelCase = (snakeStr: string): string =>\n snakeStr.replace(/_([a-z])/g, (g) => g[1]?.toUpperCase() ?? '');\n\nexport const mapToCamelCase = <T extends Record<string, unknown>>(\n obj: T,\n): T => {\n const newObj: Record<string, unknown> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n newObj[toCamelCase(key)] = obj[key];\n }\n }\n return newObj as T;\n};\n","import type { QueryResult, QueryResultRow } from './query';\n\nexport const firstOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const first = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n return result.rows[0]!;\n};\n\nexport const singleOrNull = async <\n Result extends QueryResultRow = QueryResultRow,\n>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result | null> => {\n const result = await getResult;\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows.length > 0 ? result.rows[0] ?? null : null;\n};\n\nexport const single = async <Result extends QueryResultRow = QueryResultRow>(\n getResult: Promise<QueryResult<Result>>,\n): Promise<Result> => {\n const result = await getResult;\n\n if (result.rows.length === 0)\n throw new Error(\"Query didn't return any result\");\n\n if (result.rows.length > 1) throw new Error('Query had more than one result');\n\n return result.rows[0]!;\n};\n\nexport type ExistsSQLQueryResult = { exists: boolean };\n\nexport const exists = async (\n getResult: Promise<QueryResult<ExistsSQLQueryResult>>,\n): Promise<boolean> => {\n const result = await single(getResult);\n\n return result.exists === true;\n};\n","import { exists, sql, type ConnectionPool, type SQL } from '../../../core';\nexport * from './schema';\n\nexport const defaultPostgreSqlDatabase = 'postgres';\n\nexport const tableExistsSQL = (tableName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE tablename = %L\n ) AS exists;`,\n tableName,\n );\n\nexport const tableExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(tableExistsSQL(tableName)));\n\nexport const functionExistsSQL = (functionName: string): SQL =>\n sql(\n `\n SELECT EXISTS (\n SELECT FROM pg_proc \n WHERE \n proname = %L\n ) AS exists;\n `,\n functionName,\n );\n\nexport const functionExists = async (\n pool: ConnectionPool,\n tableName: string,\n): Promise<boolean> => exists(pool.execute.query(functionExistsSQL(tableName)));\n","import pg from 'pg';\nimport { createConnection, type Connection } from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport { nodePostgresTransaction } from './transaction';\n\nexport const NodePostgresConnectorType = 'PostgreSQL:pg';\nexport type NodePostgresConnector = 'PostgreSQL:pg';\n\nexport type NodePostgresClient = pg.PoolClient | pg.Client;\n\nexport type NodePostgresPoolOrClient = pg.Pool | pg.PoolClient | pg.Client;\n\nexport type NodePostgresClientConnection = Connection<\n NodePostgresConnector,\n pg.Client\n>;\n\nexport type NodePostgresPoolClientConnection = Connection<\n NodePostgresConnector,\n pg.PoolClient\n>;\n\nexport type NodePostgresConnection =\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n\nexport type NodePostgresPoolClientOptions = {\n type: 'PoolClient';\n connect: Promise<pg.PoolClient>;\n close: (client: pg.PoolClient) => Promise<void>;\n};\n\nexport type NodePostgresClientOptions = {\n type: 'Client';\n connect: Promise<pg.Client>;\n close: (client: pg.Client) => Promise<void>;\n};\n\nexport const nodePostgresClientConnection = (\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport const nodePostgresPoolClientConnection = (\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection => {\n const { connect, close } = options;\n\n return createConnection({\n type: NodePostgresConnectorType,\n connect,\n close,\n initTransaction: (connection) => nodePostgresTransaction(connection),\n executor: nodePostgresSQLExecutor,\n });\n};\n\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions,\n): NodePostgresPoolClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresClientOptions,\n): NodePostgresClientConnection;\nexport function nodePostgresConnection(\n options: NodePostgresPoolClientOptions | NodePostgresClientOptions,\n): NodePostgresPoolClientConnection | NodePostgresClientConnection {\n return options.type === 'Client'\n ? nodePostgresClientConnection(options)\n : nodePostgresPoolClientConnection(options);\n}\n","import pg from 'pg';\nimport {\n type DbSQLExecutor,\n type QueryResult,\n type QueryResultRow,\n type SQL,\n} from '../../../core';\nimport {\n NodePostgresConnectorType,\n type NodePostgresClient,\n type NodePostgresConnector,\n} from '../connections';\n\nexport const isNodePostgresNativePool = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Pool => {\n return poolOrClient instanceof pg.Pool;\n};\n\nexport const isNodePostgresClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.Client => poolOrClient instanceof pg.Client;\n\nexport const isNodePostgresPoolClient = (\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n): poolOrClient is pg.PoolClient =>\n 'release' in poolOrClient && typeof poolOrClient.release === 'function';\n\nexport const nodePostgresExecute = async <Result = void>(\n poolOrClient: pg.Pool | pg.PoolClient | pg.Client,\n handle: (client: pg.PoolClient | pg.Client) => Promise<Result>,\n) => {\n const client = isNodePostgresNativePool(poolOrClient)\n ? await poolOrClient.connect()\n : poolOrClient;\n\n try {\n return await handle(client);\n } finally {\n // release only if client wasn't injected externally\n if (\n isNodePostgresNativePool(poolOrClient) &&\n isNodePostgresPoolClient(client)\n )\n client.release();\n }\n};\n\nexport type NodePostgresSQLExecutor = DbSQLExecutor<\n NodePostgresConnector,\n NodePostgresClient\n>;\n\nexport const nodePostgresSQLExecutor = (): NodePostgresSQLExecutor => ({\n type: NodePostgresConnectorType,\n query: batch,\n batchQuery: batch,\n command: batch,\n batchCommand: batch,\n});\n\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL,\n): Promise<QueryResult<Result>>;\nfunction batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL[],\n): Promise<QueryResult<Result>[]>;\nasync function batch<Result extends QueryResultRow = QueryResultRow>(\n client: NodePostgresClient,\n sqlOrSqls: SQL | SQL[],\n): Promise<QueryResult<Result> | QueryResult<Result>[]> {\n const sqls = Array.isArray(sqlOrSqls) ? sqlOrSqls : [sqlOrSqls];\n const results: QueryResult<Result>[] = Array<QueryResult<Result>>(\n sqls.length,\n );\n //TODO: make it smarter at some point\n for (let i = 0; i < sqls.length; i++) {\n const result = await client.query<Result>(sqls[i]!);\n results[i] = { rowCount: result.rowCount, rows: result.rows };\n }\n return Array.isArray(sqlOrSqls) ? results : results[0]!;\n}\n","import {\n sqlExecutor,\n type Connection,\n type DatabaseTransaction,\n} from '../../../core';\nimport { nodePostgresSQLExecutor } from '../execute';\nimport {\n NodePostgresConnectorType,\n type NodePostgresConnector,\n type NodePostgresPoolOrClient,\n} from './connection';\n\nexport type NodePostgresTransaction =\n DatabaseTransaction<NodePostgresConnector>;\n\nexport const nodePostgresTransaction =\n <DbClient extends NodePostgresPoolOrClient = NodePostgresPoolOrClient>(\n connection: () => Connection<NodePostgresConnector, DbClient>,\n ) =>\n (\n getClient: Promise<DbClient>,\n options?: { close: (client: DbClient, error?: unknown) => Promise<void> },\n ): DatabaseTransaction<NodePostgresConnector> => ({\n connection: connection(),\n type: NodePostgresConnectorType,\n begin: async () => {\n const client = await getClient;\n await client.query('BEGIN');\n },\n commit: async () => {\n const client = await getClient;\n\n await client.query('COMMIT');\n\n if (options?.close) await options?.close(client);\n },\n rollback: async (error?: unknown) => {\n const client = await getClient;\n await client.query('ROLLBACK');\n\n if (options?.close) await options?.close(client, error);\n },\n execute: sqlExecutor(nodePostgresSQLExecutor(), {\n connect: () => getClient,\n }),\n });\n","import pg from 'pg';\nimport { createConnectionPool, type ConnectionPool } from '../../../core';\nimport {\n defaultPostgreSqlDatabase,\n getDatabaseNameOrDefault,\n} from '../../core';\nimport {\n nodePostgresConnection,\n NodePostgresConnectorType,\n type NodePostgresClientConnection,\n type NodePostgresConnector,\n type NodePostgresPoolClientConnection,\n} from './connection';\n\nexport type NodePostgresNativePool =\n ConnectionPool<NodePostgresPoolClientConnection>;\n\nexport type NodePostgresAmbientClientPool =\n ConnectionPool<NodePostgresClientConnection>;\n\nexport type NodePostgresAmbientConnectionPool = ConnectionPool<\n NodePostgresPoolClientConnection | NodePostgresClientConnection\n>;\n\nexport type NodePostgresPool =\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool;\n\nexport const nodePostgresNativePool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresNativePool => {\n const { connectionString, database } = options;\n const pool = getPool({ connectionString, database });\n\n const getConnection = () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n });\n\n const open = () => Promise.resolve(getConnection());\n const close = () => endPool({ connectionString, database });\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport const nodePostgresAmbientNativePool = (options: {\n pool: pg.Pool;\n}): NodePostgresNativePool => {\n const { pool } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () =>\n nodePostgresConnection({\n type: 'PoolClient',\n connect: pool.connect(),\n close: (client) => Promise.resolve(client.release()),\n }),\n });\n};\n\nexport const nodePostgresAmbientConnectionPool = (options: {\n connection: NodePostgresPoolClientConnection | NodePostgresClientConnection;\n}): NodePostgresAmbientConnectionPool => {\n const { connection } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => connection,\n execute: connection.execute,\n transaction: () => connection.transaction(),\n withTransaction: (handle) => connection.withTransaction(handle),\n });\n};\n\nexport const nodePostgresClientPool = (options: {\n connectionString: string;\n database?: string | undefined;\n}): NodePostgresAmbientClientPool => {\n const { connectionString, database } = options;\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n getConnection: () => {\n const connect = Promise.resolve(\n new pg.Client({ connectionString, database }),\n ).then(async (client) => {\n await client.connect();\n return client;\n });\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: (client) => client.end(),\n });\n },\n });\n};\n\nexport const nodePostgresAmbientClientPool = (options: {\n client: pg.Client;\n}): NodePostgresAmbientClientPool => {\n const { client } = options;\n\n const getConnection = () => {\n const connect = Promise.resolve(client);\n\n return nodePostgresConnection({\n type: 'Client',\n connect,\n close: () => Promise.resolve(),\n });\n };\n\n const open = () => Promise.resolve(getConnection());\n const close = () => Promise.resolve();\n\n return createConnectionPool({\n type: NodePostgresConnectorType,\n connection: open,\n close,\n getConnection,\n });\n};\n\nexport type NodePostgresPoolPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pool: pg.Pool;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: true;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n };\n\nexport type NodePostgresPoolNotPooledOptions =\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n client: pg.Client;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n pooled: false;\n }\n | {\n connector?: NodePostgresConnector;\n connectionString: string;\n database?: string;\n connection:\n | NodePostgresPoolClientConnection\n | NodePostgresClientConnection;\n pooled?: false;\n };\n\nexport type NodePostgresPoolOptions =\n | NodePostgresPoolPooledOptions\n | NodePostgresPoolNotPooledOptions;\n\nexport function nodePostgresPool(\n options: NodePostgresPoolPooledOptions,\n): NodePostgresNativePool;\nexport function nodePostgresPool(\n options: NodePostgresPoolNotPooledOptions,\n): NodePostgresAmbientClientPool;\nexport function nodePostgresPool(\n options: NodePostgresPoolOptions,\n):\n | NodePostgresNativePool\n | NodePostgresAmbientClientPool\n | NodePostgresAmbientConnectionPool {\n const { connectionString, database } = options;\n\n if ('client' in options && options.client)\n return nodePostgresAmbientClientPool({ client: options.client });\n\n if ('pooled' in options && options.pooled === false)\n return nodePostgresClientPool({ connectionString, database });\n\n if ('connection' in options && options.connection)\n return nodePostgresAmbientConnectionPool({\n connection: options.connection,\n });\n\n if ('pool' in options && options.pool)\n return nodePostgresAmbientNativePool({ pool: options.pool });\n\n return nodePostgresNativePool({\n connectionString,\n database,\n });\n}\n\nconst pools: Map<string, pg.Pool> = new Map();\nconst usageCounter: Map<string, number> = new Map();\n\nexport const getPool = (\n connectionStringOrOptions: string | pg.PoolConfig,\n): pg.Pool => {\n const connectionString =\n typeof connectionStringOrOptions === 'string'\n ? connectionStringOrOptions\n : connectionStringOrOptions.connectionString!;\n\n const poolOptions =\n typeof connectionStringOrOptions === 'string'\n ? { connectionString }\n : connectionStringOrOptions;\n\n const database =\n poolOptions.database ??\n (poolOptions.connectionString\n ? getDatabaseNameOrDefault(poolOptions.connectionString)\n : undefined);\n\n const lookupKey = key(connectionString, database);\n\n updatePoolUsageCounter(lookupKey, 1);\n\n return (\n pools.get(lookupKey) ??\n pools.set(lookupKey, new pg.Pool(poolOptions)).get(lookupKey)!\n );\n};\n\nexport const endPool = async ({\n connectionString,\n database,\n force,\n}: {\n connectionString: string;\n database?: string | undefined;\n force?: boolean;\n}): Promise<void> => {\n database = database ?? getDatabaseNameOrDefault(connectionString);\n const lookupKey = key(connectionString, database);\n\n const pool = pools.get(lookupKey);\n if (pool && (updatePoolUsageCounter(lookupKey, -1) <= 0 || force === true)) {\n await onEndPool(lookupKey, pool);\n }\n};\n\nexport const onEndPool = async (lookupKey: string, pool: pg.Pool) => {\n try {\n await pool.end();\n } catch (error) {\n console.log(`Error while closing the connection pool: ${lookupKey}`);\n console.log(error);\n }\n pools.delete(lookupKey);\n};\n\nexport const endAllPools = () =>\n Promise.all(\n [...pools.entries()].map(([lookupKey, pool]) => onEndPool(lookupKey, pool)),\n );\n\nconst key = (connectionString: string, database: string | undefined) =>\n `${connectionString}|${database ?? defaultPostgreSqlDatabase}`;\n\nconst updatePoolUsageCounter = (lookupKey: string, by: 1 | -1): number => {\n const currentCounter = usageCounter.get(lookupKey) ?? 0;\n const newCounter = currentCounter + by;\n\n usageCounter.set(lookupKey, currentCounter + by);\n\n return newCounter;\n};\n","export * from './core';\nexport * from './pg';\nimport {\n type NodePostgresConnection,\n type NodePostgresConnector,\n type NodePostgresPool,\n type NodePostgresPoolOptions,\n nodePostgresPool,\n} from './pg';\n\nexport type PostgresConnector = NodePostgresConnector;\nexport type PostgresPoolOptions = NodePostgresPoolOptions;\nexport type PostgresPool = NodePostgresPool;\nexport type PostgresConnection = NodePostgresConnection;\nexport const postgresPool = nodePostgresPool;\n","import {\n postgresPool,\n type PostgresConnector,\n type PostgresPool,\n type PostgresPoolOptions,\n} from './postgres';\n\nexport * from './core';\nexport * from './postgres';\n\nexport type ConnectorType = PostgresConnector;\n\nexport type PoolOptions = {\n connector?: ConnectorType;\n};\n\nexport type DumboOptions = PoolOptions & PostgresPoolOptions;\nexport type Dumbo = PostgresPool;\n\nexport const connectionPool = <PoolOptionsType extends DumboOptions>(\n options: PoolOptionsType,\n) =>\n // TODO: this should have the pattern matching and verification\n postgresPool(options as unknown as PostgresPoolOptions);\n\nexport const dumbo = <DumboOptionsType extends DumboOptions = DumboOptions>(\n options: DumboOptionsType,\n): Dumbo => connectionPool(options);\n"],"mappings":"AAAA,OAAOA,MAAU,uBCAjB,OAAOC,MAAY,YAKZ,IAAMC,EAAM,CAACC,KAAqBC,IAChCH,EAAOE,EAAU,GAAGC,CAAM,EAGtBC,GAAUF,GACdA,ECoCF,IAAMG,EAAc,CAIzBA,EAEAC,KAIiB,CACjB,MAAQC,GACNC,EAAsBC,GAAWJ,EAAY,MAAMI,EAAQF,CAAG,EAAGD,CAAO,EAC1E,WAAaI,GACXF,EACGC,GAAWJ,EAAY,WAAWI,EAAQC,CAAI,EAC/CJ,CACF,EACF,QAAUC,GACRC,EAAsBC,GAAWJ,EAAY,QAAQI,EAAQF,CAAG,EAAGD,CAAO,EAC5E,aAAeI,GACbF,EACGC,GAAWJ,EAAY,WAAWI,EAAQC,CAAI,EAC/CJ,CACF,CACJ,GAEaK,EAEXL,IAEkB,CAClB,MAAQC,GACNK,EACGC,GAAeA,EAAW,QAAQ,MAAMN,CAAG,EAC5CD,CACF,EACF,WAAaI,GACXE,EACGC,GAAeA,EAAW,QAAQ,WAAWH,CAAI,EAClDJ,CACF,EACF,QAAUC,GACRK,EACGC,GAAeA,EAAW,QAAQ,QAAQN,CAAG,EAC9CD,CACF,EACF,aAAeI,GACbE,EACGC,GAAeA,EAAW,QAAQ,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YC,EAAIzB,EAAkBC,CAAQ,EAE1CC,EAAOiB,EAAM,IAAIK,CAAS,EAC5BtB,IAASwB,EAAuBF,EAAW,EAAE,GAAK,GAAKG,IAAU,KACnE,MAAMC,EAAUJ,EAAWtB,CAAI,CAEnC,EAEa0B,EAAY,MAAOJ,EAAmBtB,IAAkB,CACnE,GAAI,CACF,MAAMA,EAAK,IAAI,CACjB,OAAS2B,EAAO,CACd,QAAQ,IAAI,4CAA4CL,CAAS,EAAE,EACnE,QAAQ,IAAIK,CAAK,CACnB,CACAV,EAAM,OAAOK,CAAS,CACxB,EAEaM,GAAc,IACzB,QAAQ,IACN,CAAC,GAAGX,EAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAACK,EAAWtB,CAAI,IAAM0B,EAAUJ,EAAWtB,CAAI,CAAC,CAC5E,EAEIuB,EAAM,CAACzB,EAA0BC,IACrC,GAAGD,CAAgB,IAAIC,GAAY8B,CAAyB,GAExDL,EAAyB,CAACF,EAAmBQ,IAAuB,CACxE,IAAMC,EAAiBb,EAAa,IAAII,CAAS,GAAK,EAChDU,EAAaD,EAAiBD,EAEpC,OAAAZ,EAAa,IAAII,EAAWS,EAAiBD,CAAE,EAExCE,CACT,EClSO,IAAMC,EAAeC,ECKrB,IAAMC,GACXC,GAGAC,EAAaD,CAAyC,EAE3CE,GACXF,GACUD,GAAeC,CAAO","names":["pgcs","format","sql","sqlQuery","params","rawSql","sqlExecutor","options","sql","executeInNewDbClient","client","sqls","sqlExecutorInNewConnection","executeInNewConnection","connection","handle","connect","close","error","toTransactionResult","transactionResult","executeInTransaction","transaction","handle","success","result","e","transactionFactoryWithDbClient","connect","initTransaction","wrapInConnectionClosure","connection","transactionFactoryWithNewConnection","createConnection","options","type","connect","close","initTransaction","executor","client","getClient","typedConnection","transactionFactoryWithDbClient","sqlExecutor","createConnectionPool","pool","type","getConnection","connection","withConnection","handle","executeInNewConnection","close","execute","sqlExecutorInNewConnection","transaction","transactionFactoryWithNewConnection","mapRows","getResult","map","toCamelCase","snakeStr","g","mapToCamelCase","obj","newObj","key","firstOrNull","getResult","result","first","singleOrNull","single","exists","defaultPostgreSqlDatabase","tableExistsSQL","tableName","sql","tableExists","pool","exists","functionExistsSQL","functionName","functionExists","getDatabaseNameOrDefault","connectionString","pgcs","defaultPostgreSqlDatabase","pg","isNodePostgresNativePool","poolOrClient","pg","isNodePostgresClient","isNodePostgresPoolClient","nodePostgresExecute","handle","client","nodePostgresSQLExecutor","NodePostgresConnectorType","batch","sqlOrSqls","sqls","results","i","result","nodePostgresTransaction","connection","getClient","options","NodePostgresConnectorType","client","error","sqlExecutor","nodePostgresSQLExecutor","NodePostgresConnectorType","nodePostgresClientConnection","options","connect","close","createConnection","connection","nodePostgresTransaction","nodePostgresSQLExecutor","nodePostgresPoolClientConnection","nodePostgresConnection","pg","nodePostgresNativePool","options","connectionString","database","pool","getPool","getConnection","nodePostgresConnection","client","createConnectionPool","NodePostgresConnectorType","endPool","nodePostgresAmbientNativePool","nodePostgresAmbientConnectionPool","connection","handle","nodePostgresClientPool","connect","pg","nodePostgresAmbientClientPool","nodePostgresPool","pools","usageCounter","connectionStringOrOptions","poolOptions","getDatabaseNameOrDefault","lookupKey","key","updatePoolUsageCounter","force","onEndPool","error","endAllPools","defaultPostgreSqlDatabase","by","currentCounter","newCounter","postgresPool","nodePostgresPool","connectionPool","options","postgresPool","dumbo"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@event-driven-io/dumbo",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "Dumbo - tools for dealing with PostgreSQL",
5
5
  "type": "module",
6
6
  "scripts": {