@contember/database 2.2.0-alpha.18 → 2.2.0-alpha.19

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.
Files changed (42) hide show
  1. package/CLAUDE.md +1 -1
  2. package/dist/development/index.cjs +1 -0
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +2 -1
  5. package/dist/development/src/client/AcquiredConnection.cjs +2 -0
  6. package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
  7. package/dist/development/src/client/AcquiredConnection.js +3 -1
  8. package/dist/development/src/client/AcquiredConnection.js.map +1 -1
  9. package/dist/development/src/client/errors.cjs +6 -1
  10. package/dist/development/src/client/errors.cjs.map +1 -1
  11. package/dist/development/src/client/errors.js +6 -1
  12. package/dist/development/src/client/errors.js.map +1 -1
  13. package/dist/development/src/utils/pgClientFactory.cjs.map +1 -1
  14. package/dist/development/src/utils/pgClientFactory.js.map +1 -1
  15. package/dist/production/index.cjs +1 -0
  16. package/dist/production/index.cjs.map +1 -1
  17. package/dist/production/index.js +2 -1
  18. package/dist/production/src/client/AcquiredConnection.cjs +2 -0
  19. package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
  20. package/dist/production/src/client/AcquiredConnection.js +3 -1
  21. package/dist/production/src/client/AcquiredConnection.js.map +1 -1
  22. package/dist/production/src/client/errors.cjs +6 -1
  23. package/dist/production/src/client/errors.cjs.map +1 -1
  24. package/dist/production/src/client/errors.js +6 -1
  25. package/dist/production/src/client/errors.js.map +1 -1
  26. package/dist/production/src/utils/pgClientFactory.cjs.map +1 -1
  27. package/dist/production/src/utils/pgClientFactory.js.map +1 -1
  28. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  29. package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
  30. package/dist/types/client/PgClient.d.ts +1 -1
  31. package/dist/types/client/PgClient.d.ts.map +1 -1
  32. package/dist/types/client/errors.d.ts +2 -0
  33. package/dist/types/client/errors.d.ts.map +1 -1
  34. package/dist/types/tsconfig.tsbuildinfo +1 -1
  35. package/dist/types/utils/pgClientFactory.d.ts +1 -2
  36. package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
  37. package/package.json +4 -3
  38. package/src/client/AcquiredConnection.ts +3 -0
  39. package/src/client/PgClient.ts +2 -1
  40. package/src/client/errors.ts +9 -3
  41. package/src/utils/pgClientFactory.ts +1 -3
  42. package/tests/cases/unit/acquiredConnection.test.ts +40 -0
package/CLAUDE.md CHANGED
@@ -51,7 +51,7 @@ This is invisible to a mapper unit test; cover a new raw jsonb write with an e2e
51
51
 
52
52
  ## Error Translation
53
53
 
54
- PostgreSQL error codes are mapped to typed errors: `NotNullViolationError`, `ForeignKeyViolationError`, `UniqueViolationError`, `SerializationFailureError`, `InvalidDataError`, `TransactionAbortedError`
54
+ PostgreSQL error codes are mapped to typed errors: `NotNullViolationError`, `ForeignKeyViolationError`, `UniqueViolationError`, `CheckViolationError` (`23514`, also raised by DOMAIN checks such as enums), `SerializationFailureError`, `InvalidDataError`, `TransactionAbortedError`
55
55
 
56
56
  A deadlock (`40P01`) maps to `SerializationFailureError` like a serialization failure (`40001`): both abort the transaction, and `retryTransaction` retries only that class.
57
57
 
@@ -41,6 +41,7 @@ const RequestMemoryBudget = require("./src/client/RequestMemoryBudget.cjs");
41
41
  exports.Client = Client.Client;
42
42
  exports.ClientErrorCodes = errorCodes.ClientErrorCodes;
43
43
  exports.CannotCommitError = errors.CannotCommitError;
44
+ exports.CheckViolationError = errors.CheckViolationError;
44
45
  exports.ClientError = errors.ClientError;
45
46
  exports.DatabaseError = errors.DatabaseError;
46
47
  exports.ForeignKeyViolationError = errors.ForeignKeyViolationError;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -1,6 +1,6 @@
1
1
  import { Client } from "./src/client/Client.js";
2
2
  import { ClientErrorCodes } from "./src/client/errorCodes.js";
3
- import { CannotCommitError, ClientError, DatabaseError, ForeignKeyViolationError, InvalidDataError, NotNullViolationError, QueryError, SerializationFailureError, TerminatedConnectionError, TransactionAbortedError, UniqueViolationError } from "./src/client/errors.js";
3
+ import { CannotCommitError, CheckViolationError, ClientError, DatabaseError, ForeignKeyViolationError, InvalidDataError, NotNullViolationError, QueryError, SerializationFailureError, TerminatedConnectionError, TransactionAbortedError, UniqueViolationError } from "./src/client/errors.js";
4
4
  import { Connection } from "./src/client/Connection.js";
5
5
  import { ScopeLimitedConnection } from "./src/client/ScopeLimitedConnection.js";
6
6
  import { EventManager } from "./src/client/EventManager.js";
@@ -41,6 +41,7 @@ export {
41
41
  AcquiringListener,
42
42
  CannotCommitError,
43
43
  CaseStatement,
44
+ CheckViolationError,
44
45
  Client,
45
46
  ClientError,
46
47
  ClientErrorCodes,
@@ -75,6 +75,8 @@ class AcquiredConnection {
75
75
  throw new errors.ForeignKeyViolationError(sql, parameters, error);
76
76
  case errorCodes.ClientErrorCodes.UNIQUE_VIOLATION:
77
77
  throw new errors.UniqueViolationError(sql, parameters, error);
78
+ case errorCodes.ClientErrorCodes.CHECK_VIOLATION:
79
+ throw new errors.CheckViolationError(sql, parameters, error);
78
80
  // both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike
79
81
  case errorCodes.ClientErrorCodes.T_R_SERIALIZATION_FAILURE:
80
82
  case errorCodes.ClientErrorCodes.T_R_DEADLOCK_DETECTED:
@@ -1 +1 @@
1
- {"version":3,"file":"AcquiredConnection.cjs","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex, MutexDeadlockError } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTerminatedConnectionError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { cancelRunningStatement } from './cancelRunningStatement.js'\nimport { Notification, Query, QueryResult, QueryResultRow } from 'pg'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t\tprivate readonly physicalConnection = { terminated: false },\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\t// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.\n\t\tthis.refuseExhaustedOrTerminated()\n\n\t\tconst query: Connection.Query = { sql, parameters, meta }\n\n\t\ttry {\n\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, query)\n\n\t\t\tconst result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {\n\t\t\t\t// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.\n\t\t\t\tthis.refuseExhaustedOrTerminated()\n\t\t\t\tconst memoryBudget = this.eventManager.memoryBudget\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tconst pgResult = memoryBudget && this.eventManager.chargesMemoryBudget\n\t\t\t\t\t? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)\n\t\t\t\t\t: await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\n\t\t\t\treturn {\n\t\t\t\t\t...pgResult,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, query, result)\n\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.eventManager.fire(EventManager.Event.queryError, query, error)\n\n\t\t\t// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated\n\t\t\tif (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tswitch ((error as any).code) {\n\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\t// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike\n\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\tcase ClientErrorCodes.T_R_DEADLOCK_DETECTED:\n\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\tcase ClientErrorCodes.INVALID_DATETIME_FORMAT:\n\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate refuseExhaustedOrTerminated(): void {\n\t\t// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.\n\t\tthis.eventManager.memoryBudget?.check()\n\t\tif (this.physicalConnection.terminated) {\n\t\t\tthrow new TerminatedConnectionError()\n\t\t}\n\t}\n\n\tprivate async queryWithMemoryBudget<Row extends QueryResultRow>(\n\t\tsql: string,\n\t\tparameters: unknown[],\n\t\tbudget: RequestMemoryBudget,\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await new Promise<Connection.Result<Row>>((resolve, reject) => {\n\t\t\tlet rows: Row[] | undefined\n\t\t\tlet failure: Error | undefined\n\t\t\tlet cleanup = () => {}\n\t\t\tconst stop = (error: Error) => {\n\t\t\t\tfailure = error\n\t\t\t\tif (rows) {\n\t\t\t\t\trows.length = 0\n\t\t\t\t}\n\t\t\t\tcleanup()\n\t\t\t\t// A budget failure invalidates this connection; the enclosing pool scope disposes it.\n\t\t\t\tthis.physicalConnection.terminated = true\n\t\t\t\t// Ending the socket alone leaves a statement still waiting for its first row running on the server.\n\t\t\t\t// Cancelling is best effort and must not mask the budget error.\n\t\t\t\tvoid cancelRunningStatement(this.pgClient).catch(() => {})\n\t\t\t\tvoid this.pgClient.end().catch(reject)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst config = {\n\t\t\t\ttext: sql,\n\t\t\t\tvalues: parameters,\n\t\t\t\tcallback: (error: Error | null, result?: QueryResult<Row>) => {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tif (failure || error) {\n\t\t\t\t\t\treject(failure || error)\n\t\t\t\t\t} else if (result) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error('PostgreSQL query completed without a result'))\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst query = new Query<Row>(config)\n\t\t\t// A sibling query of the request may exhaust the budget while this one still waits for its first row.\n\t\t\tcleanup = budget.onExceeded(stop)\n\t\t\tquery.on('row', (row, result) => {\n\t\t\t\trows = result?.rows\n\t\t\t\tif (failure) {\n\t\t\t\t\tif (rows) {\n\t\t\t\t\t\trows.length = 0\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tbudget.addDatabaseRow(row)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!failure) {\n\t\t\t\t\t\tstop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tthis.pgClient.query(query)\n\t\t\t} catch (error) {\n\t\t\t\tcleanup()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":["Mutex","Transaction","executeTransaction","EventManager","MutexDeadlockError","RequestMemoryBudgetExceededError","TerminatedConnectionError","ClientErrorCodes","NotNullViolationError","ForeignKeyViolationError","UniqueViolationError","SerializationFailureError","InvalidDataError","TransactionAbortedError","QueryError","cancelRunningStatement","Query"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACC,qBAAqB,EAAE,YAAY,SACnD;AAHgB,SAAA,WAAA;AACD,SAAA,eAAA;AACC,SAAA,qBAAA;AALlB,kBAAA,MAAQ,SAAQ,IAAIA,MAAAA,MAAA,CAAM;AAAA,EAO1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,QAAQ,YAAY;AAC3C,aAAO,MAAM,SAAS,IAAI,mBAAmB,KAAK,UAAU,QAAQ,gBAAgB,KAAK,cAAc,KAAK,kBAAkB,CAAC;AAAA,IAChI,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,YAAM,WAAW,MAAM,SAAS,EAAE;AAClC,YAAM,cAAc,IAAIC,YAAAA,YAAY,UAAU;AAC9C,aAAO,MAAMC,YAAAA,mBAAmB,aAAa,QAAQ;AAAA,IACtD,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAElC,SAAK,4BAAA;AAEL,UAAM,QAA0B,EAAE,KAAK,YAAY,KAAA;AAEnD,QAAI;AACH,WAAK,aAAa,KAAKC,aAAAA,aAA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AAA,UAChE;AAAA,QACD;AAAA,MAAA;AAED,YAAM,QAAQ,IAAIC,GAAAA,MAAW,MAAM;AAEnC,gBAAU,OAAO,WAAW,IAAI;AAChC,YAAM,GAAG,OAAO,CAAC,KAAK,WAAW;AAChC,eAAO,QAAQ;AACf,YAAI,SAAS;AACZ,cAAI,MAAM;AACT,iBAAK,SAAS;AAAA,UACf;AACA;AAAA,QACD;AACA,YAAI;AACH,iBAAO,eAAe,GAAG;AAAA,QAC1B,SAAS,OAAO;AACf,cAAI,CAAC,SAAS;AACb,iBAAK,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,sCAAsC,EAAE,OAAO,MAAA,CAAO,CAAC;AAAA,UACxG;AAAA,QACD;AAAA,MACD,CAAC;AACD,UAAI;AACH,aAAK,SAAS,MAAM,KAAK;AAAA,MAC1B,SAAS,OAAO;AACf,gBAAA;AACA,eAAO,KAAK;AAAA,MACb;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,GAAG,OAAyC,IAAoF;AAC/H,SAAK,SAAS,GAAG,OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;;"}
1
+ {"version":3,"file":"AcquiredConnection.cjs","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex, MutexDeadlockError } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tCheckViolationError,\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTerminatedConnectionError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { cancelRunningStatement } from './cancelRunningStatement.js'\nimport { Notification, Query, QueryResult, QueryResultRow } from 'pg'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t\tprivate readonly physicalConnection = { terminated: false },\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\t// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.\n\t\tthis.refuseExhaustedOrTerminated()\n\n\t\tconst query: Connection.Query = { sql, parameters, meta }\n\n\t\ttry {\n\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, query)\n\n\t\t\tconst result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {\n\t\t\t\t// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.\n\t\t\t\tthis.refuseExhaustedOrTerminated()\n\t\t\t\tconst memoryBudget = this.eventManager.memoryBudget\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tconst pgResult = memoryBudget && this.eventManager.chargesMemoryBudget\n\t\t\t\t\t? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)\n\t\t\t\t\t: await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\n\t\t\t\treturn {\n\t\t\t\t\t...pgResult,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, query, result)\n\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.eventManager.fire(EventManager.Event.queryError, query, error)\n\n\t\t\t// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated\n\t\t\tif (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tswitch ((error as any).code) {\n\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.CHECK_VIOLATION:\n\t\t\t\t\tthrow new CheckViolationError(sql, parameters, error)\n\t\t\t\t// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike\n\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\tcase ClientErrorCodes.T_R_DEADLOCK_DETECTED:\n\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\tcase ClientErrorCodes.INVALID_DATETIME_FORMAT:\n\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate refuseExhaustedOrTerminated(): void {\n\t\t// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.\n\t\tthis.eventManager.memoryBudget?.check()\n\t\tif (this.physicalConnection.terminated) {\n\t\t\tthrow new TerminatedConnectionError()\n\t\t}\n\t}\n\n\tprivate async queryWithMemoryBudget<Row extends QueryResultRow>(\n\t\tsql: string,\n\t\tparameters: unknown[],\n\t\tbudget: RequestMemoryBudget,\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await new Promise<Connection.Result<Row>>((resolve, reject) => {\n\t\t\tlet rows: Row[] | undefined\n\t\t\tlet failure: Error | undefined\n\t\t\tlet cleanup = () => {}\n\t\t\tconst stop = (error: Error) => {\n\t\t\t\tfailure = error\n\t\t\t\tif (rows) {\n\t\t\t\t\trows.length = 0\n\t\t\t\t}\n\t\t\t\tcleanup()\n\t\t\t\t// A budget failure invalidates this connection; the enclosing pool scope disposes it.\n\t\t\t\tthis.physicalConnection.terminated = true\n\t\t\t\t// Ending the socket alone leaves a statement still waiting for its first row running on the server.\n\t\t\t\t// Cancelling is best effort and must not mask the budget error.\n\t\t\t\tvoid cancelRunningStatement(this.pgClient).catch(() => {})\n\t\t\t\tvoid this.pgClient.end().catch(reject)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst config = {\n\t\t\t\ttext: sql,\n\t\t\t\tvalues: parameters,\n\t\t\t\tcallback: (error: Error | null, result?: QueryResult<Row>) => {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tif (failure || error) {\n\t\t\t\t\t\treject(failure || error)\n\t\t\t\t\t} else if (result) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error('PostgreSQL query completed without a result'))\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst query = new Query<Row>(config)\n\t\t\t// A sibling query of the request may exhaust the budget while this one still waits for its first row.\n\t\t\tcleanup = budget.onExceeded(stop)\n\t\t\tquery.on('row', (row, result) => {\n\t\t\t\trows = result?.rows\n\t\t\t\tif (failure) {\n\t\t\t\t\tif (rows) {\n\t\t\t\t\t\trows.length = 0\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tbudget.addDatabaseRow(row)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!failure) {\n\t\t\t\t\t\tstop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tthis.pgClient.query(query)\n\t\t\t} catch (error) {\n\t\t\t\tcleanup()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":["Mutex","Transaction","executeTransaction","EventManager","MutexDeadlockError","RequestMemoryBudgetExceededError","TerminatedConnectionError","ClientErrorCodes","NotNullViolationError","ForeignKeyViolationError","UniqueViolationError","CheckViolationError","SerializationFailureError","InvalidDataError","TransactionAbortedError","QueryError","cancelRunningStatement","Query"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACC,qBAAqB,EAAE,YAAY,SACnD;AAHgB,SAAA,WAAA;AACD,SAAA,eAAA;AACC,SAAA,qBAAA;AALlB,kBAAA,MAAQ,SAAQ,IAAIA,MAAAA,MAAA,CAAM;AAAA,EAO1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,QAAQ,YAAY;AAC3C,aAAO,MAAM,SAAS,IAAI,mBAAmB,KAAK,UAAU,QAAQ,gBAAgB,KAAK,cAAc,KAAK,kBAAkB,CAAC;AAAA,IAChI,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,YAAM,WAAW,MAAM,SAAS,EAAE;AAClC,YAAM,cAAc,IAAIC,YAAAA,YAAY,UAAU;AAC9C,aAAO,MAAMC,YAAAA,mBAAmB,aAAa,QAAQ;AAAA,IACtD,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAElC,SAAK,4BAAA;AAEL,UAAM,QAA0B,EAAE,KAAK,YAAY,KAAA;AAEnD,QAAI;AACH,WAAK,aAAa,KAAKC,aAAAA,aAAa,MAAM,YAAY,KAAK;AAE3D,YAAM,SAAS,MAAM,KAAK,MAAM,QAAQ,YAA6C;AAEpF,aAAK,4BAAA;AACL,cAAM,eAAe,KAAK,aAAa;AACvC,cAAM,cAAc,QAAQ,OAAO,OAAA;AAEnC,cAAM,WAAW,gBAAgB,KAAK,aAAa,sBACh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,YAAM,GAAG,OAAO,CAAC,KAAK,WAAW;AAChC,eAAO,QAAQ;AACf,YAAI,SAAS;AACZ,cAAI,MAAM;AACT,iBAAK,SAAS;AAAA,UACf;AACA;AAAA,QACD;AACA,YAAI;AACH,iBAAO,eAAe,GAAG;AAAA,QAC1B,SAAS,OAAO;AACf,cAAI,CAAC,SAAS;AACb,iBAAK,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,sCAAsC,EAAE,OAAO,MAAA,CAAO,CAAC;AAAA,UACxG;AAAA,QACD;AAAA,MACD,CAAC;AACD,UAAI;AACH,aAAK,SAAS,MAAM,KAAK;AAAA,MAC1B,SAAS,OAAO;AACf,gBAAA;AACA,eAAO,KAAK;AAAA,MACb;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,GAAG,OAAyC,IAAoF;AAC/H,SAAK,SAAS,GAAG,OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;;"}
@@ -6,7 +6,7 @@ import "../builders/internal/With.js";
6
6
  import "../builders/internal/Where.js";
7
7
  import "@contember/queryable";
8
8
  import { ClientErrorCodes } from "./errorCodes.js";
9
- import { TerminatedConnectionError, QueryError, TransactionAbortedError, InvalidDataError, SerializationFailureError, UniqueViolationError, ForeignKeyViolationError, NotNullViolationError } from "./errors.js";
9
+ import { TerminatedConnectionError, QueryError, TransactionAbortedError, InvalidDataError, SerializationFailureError, CheckViolationError, UniqueViolationError, ForeignKeyViolationError, NotNullViolationError } from "./errors.js";
10
10
  import "./Connection.js";
11
11
  import { Transaction, executeTransaction } from "./Transaction.js";
12
12
  import "node:timers";
@@ -73,6 +73,8 @@ class AcquiredConnection {
73
73
  throw new ForeignKeyViolationError(sql, parameters, error);
74
74
  case ClientErrorCodes.UNIQUE_VIOLATION:
75
75
  throw new UniqueViolationError(sql, parameters, error);
76
+ case ClientErrorCodes.CHECK_VIOLATION:
77
+ throw new CheckViolationError(sql, parameters, error);
76
78
  // both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike
77
79
  case ClientErrorCodes.T_R_SERIALIZATION_FAILURE:
78
80
  case ClientErrorCodes.T_R_DEADLOCK_DETECTED:
@@ -1 +1 @@
1
- {"version":3,"file":"AcquiredConnection.js","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex, MutexDeadlockError } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTerminatedConnectionError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { cancelRunningStatement } from './cancelRunningStatement.js'\nimport { Notification, Query, QueryResult, QueryResultRow } from 'pg'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t\tprivate readonly physicalConnection = { terminated: false },\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\t// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.\n\t\tthis.refuseExhaustedOrTerminated()\n\n\t\tconst query: Connection.Query = { sql, parameters, meta }\n\n\t\ttry {\n\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, query)\n\n\t\t\tconst result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {\n\t\t\t\t// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.\n\t\t\t\tthis.refuseExhaustedOrTerminated()\n\t\t\t\tconst memoryBudget = this.eventManager.memoryBudget\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tconst pgResult = memoryBudget && this.eventManager.chargesMemoryBudget\n\t\t\t\t\t? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)\n\t\t\t\t\t: await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\n\t\t\t\treturn {\n\t\t\t\t\t...pgResult,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, query, result)\n\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.eventManager.fire(EventManager.Event.queryError, query, error)\n\n\t\t\t// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated\n\t\t\tif (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tswitch ((error as any).code) {\n\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\t// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike\n\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\tcase ClientErrorCodes.T_R_DEADLOCK_DETECTED:\n\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\tcase ClientErrorCodes.INVALID_DATETIME_FORMAT:\n\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate refuseExhaustedOrTerminated(): void {\n\t\t// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.\n\t\tthis.eventManager.memoryBudget?.check()\n\t\tif (this.physicalConnection.terminated) {\n\t\t\tthrow new TerminatedConnectionError()\n\t\t}\n\t}\n\n\tprivate async queryWithMemoryBudget<Row extends QueryResultRow>(\n\t\tsql: string,\n\t\tparameters: unknown[],\n\t\tbudget: RequestMemoryBudget,\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await new Promise<Connection.Result<Row>>((resolve, reject) => {\n\t\t\tlet rows: Row[] | undefined\n\t\t\tlet failure: Error | undefined\n\t\t\tlet cleanup = () => {}\n\t\t\tconst stop = (error: Error) => {\n\t\t\t\tfailure = error\n\t\t\t\tif (rows) {\n\t\t\t\t\trows.length = 0\n\t\t\t\t}\n\t\t\t\tcleanup()\n\t\t\t\t// A budget failure invalidates this connection; the enclosing pool scope disposes it.\n\t\t\t\tthis.physicalConnection.terminated = true\n\t\t\t\t// Ending the socket alone leaves a statement still waiting for its first row running on the server.\n\t\t\t\t// Cancelling is best effort and must not mask the budget error.\n\t\t\t\tvoid cancelRunningStatement(this.pgClient).catch(() => {})\n\t\t\t\tvoid this.pgClient.end().catch(reject)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst config = {\n\t\t\t\ttext: sql,\n\t\t\t\tvalues: parameters,\n\t\t\t\tcallback: (error: Error | null, result?: QueryResult<Row>) => {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tif (failure || error) {\n\t\t\t\t\t\treject(failure || error)\n\t\t\t\t\t} else if (result) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error('PostgreSQL query completed without a result'))\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst query = new Query<Row>(config)\n\t\t\t// A sibling query of the request may exhaust the budget while this one still waits for its first row.\n\t\t\tcleanup = budget.onExceeded(stop)\n\t\t\tquery.on('row', (row, result) => {\n\t\t\t\trows = result?.rows\n\t\t\t\tif (failure) {\n\t\t\t\t\tif (rows) {\n\t\t\t\t\t\trows.length = 0\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tbudget.addDatabaseRow(row)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!failure) {\n\t\t\t\t\t\tstop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tthis.pgClient.query(query)\n\t\t\t} catch (error) {\n\t\t\t\tcleanup()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAoBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACC,qBAAqB,EAAE,YAAY,SACnD;AAHgB,SAAA,WAAA;AACD,SAAA,eAAA;AACC,SAAA,qBAAA;AALlB,kBAAA,MAAQ,SAAQ,IAAI,MAAA,CAAM;AAAA,EAO1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,QAAQ,YAAY;AAC3C,aAAO,MAAM,SAAS,IAAI,mBAAmB,KAAK,UAAU,QAAQ,gBAAgB,KAAK,cAAc,KAAK,kBAAkB,CAAC;AAAA,IAChI,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,YAAM,WAAW,MAAM,SAAS,EAAE;AAClC,YAAM,cAAc,IAAI,YAAY,UAAU;AAC9C,aAAO,MAAM,mBAAmB,aAAa,QAAQ;AAAA,IACtD,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B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U,OAAO,WAAW,IAAI;AAChC,YAAM,GAAG,OAAO,CAAC,KAAK,WAAW;AAChC,eAAO,QAAQ;AACf,YAAI,SAAS;AACZ,cAAI,MAAM;AACT,iBAAK,SAAS;AAAA,UACf;AACA;AAAA,QACD;AACA,YAAI;AACH,iBAAO,eAAe,GAAG;AAAA,QAC1B,SAAS,OAAO;AACf,cAAI,CAAC,SAAS;AACb,iBAAK,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,sCAAsC,EAAE,OAAO,MAAA,CAAO,CAAC;AAAA,UACxG;AAAA,QACD;AAAA,MACD,CAAC;AACD,UAAI;AACH,aAAK,SAAS,MAAM,KAAK;AAAA,MAC1B,SAAS,OAAO;AACf,gBAAA;AACA,eAAO,KAAK;AAAA,MACb;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,GAAG,OAAyC,IAAoF;AAC/H,SAAK,SAAS,GAAG,OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;"}
1
+ {"version":3,"file":"AcquiredConnection.js","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex, MutexDeadlockError } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tCheckViolationError,\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTerminatedConnectionError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { cancelRunningStatement } from './cancelRunningStatement.js'\nimport { Notification, Query, QueryResult, QueryResultRow } from 'pg'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t\tprivate readonly physicalConnection = { terminated: false },\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\t// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.\n\t\tthis.refuseExhaustedOrTerminated()\n\n\t\tconst query: Connection.Query = { sql, parameters, meta }\n\n\t\ttry {\n\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, query)\n\n\t\t\tconst result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {\n\t\t\t\t// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.\n\t\t\t\tthis.refuseExhaustedOrTerminated()\n\t\t\t\tconst memoryBudget = this.eventManager.memoryBudget\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tconst pgResult = memoryBudget && this.eventManager.chargesMemoryBudget\n\t\t\t\t\t? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)\n\t\t\t\t\t: await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\n\t\t\t\treturn {\n\t\t\t\t\t...pgResult,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, query, result)\n\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.eventManager.fire(EventManager.Event.queryError, query, error)\n\n\t\t\t// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated\n\t\t\tif (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tswitch ((error as any).code) {\n\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.CHECK_VIOLATION:\n\t\t\t\t\tthrow new CheckViolationError(sql, parameters, error)\n\t\t\t\t// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike\n\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\tcase ClientErrorCodes.T_R_DEADLOCK_DETECTED:\n\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\tcase ClientErrorCodes.INVALID_DATETIME_FORMAT:\n\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate refuseExhaustedOrTerminated(): void {\n\t\t// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.\n\t\tthis.eventManager.memoryBudget?.check()\n\t\tif (this.physicalConnection.terminated) {\n\t\t\tthrow new TerminatedConnectionError()\n\t\t}\n\t}\n\n\tprivate async queryWithMemoryBudget<Row extends QueryResultRow>(\n\t\tsql: string,\n\t\tparameters: unknown[],\n\t\tbudget: RequestMemoryBudget,\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await new Promise<Connection.Result<Row>>((resolve, reject) => {\n\t\t\tlet rows: Row[] | undefined\n\t\t\tlet failure: Error | undefined\n\t\t\tlet cleanup = () => {}\n\t\t\tconst stop = (error: Error) => {\n\t\t\t\tfailure = error\n\t\t\t\tif (rows) {\n\t\t\t\t\trows.length = 0\n\t\t\t\t}\n\t\t\t\tcleanup()\n\t\t\t\t// A budget failure invalidates this connection; the enclosing pool scope disposes it.\n\t\t\t\tthis.physicalConnection.terminated = true\n\t\t\t\t// Ending the socket alone leaves a statement still waiting for its first row running on the server.\n\t\t\t\t// Cancelling is best effort and must not mask the budget error.\n\t\t\t\tvoid cancelRunningStatement(this.pgClient).catch(() => {})\n\t\t\t\tvoid this.pgClient.end().catch(reject)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst config = {\n\t\t\t\ttext: sql,\n\t\t\t\tvalues: parameters,\n\t\t\t\tcallback: (error: Error | null, result?: QueryResult<Row>) => {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tif (failure || error) {\n\t\t\t\t\t\treject(failure || error)\n\t\t\t\t\t} else if (result) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error('PostgreSQL query completed without a result'))\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst query = new Query<Row>(config)\n\t\t\t// A sibling query of the request may exhaust the budget while this one still waits for its first row.\n\t\t\tcleanup = budget.onExceeded(stop)\n\t\t\tquery.on('row', (row, result) => {\n\t\t\t\trows = result?.rows\n\t\t\t\tif (failure) {\n\t\t\t\t\tif (rows) {\n\t\t\t\t\t\trows.length = 0\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tbudget.addDatabaseRow(row)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!failure) {\n\t\t\t\t\t\tstop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tthis.pgClient.query(query)\n\t\t\t} catch (error) {\n\t\t\t\tcleanup()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAqBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACC,qBAAqB,EAAE,YAAY,SACnD;AAHgB,SA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OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;"}
@@ -24,10 +24,12 @@ class ClientError extends DatabaseError {
24
24
  this.type = type;
25
25
  }
26
26
  }
27
+ const formatDiagnosticField = (label, value) => typeof value === "string" && value !== "" ? `
28
+ ${label}: ${value}` : "";
27
29
  class QueryError extends DatabaseError {
28
30
  constructor(sql, parameters, previous) {
29
31
  super(
30
- `Database query error: ${"message" in previous && previous.message ? previous.message : JSON.stringify(previous)}
32
+ ("message" in previous && previous.message ? `Database query error: ${previous.message}` + formatDiagnosticField("Detail", previous.detail) + formatDiagnosticField("Hint", previous.hint) : `Database query error: ${JSON.stringify(previous)}`) + `
31
33
  SQL: ${sql}
32
34
  parameters: ${parameters}`,
33
35
  previous
@@ -47,6 +49,8 @@ class ForeignKeyViolationError extends QueryError {
47
49
  }
48
50
  class UniqueViolationError extends QueryError {
49
51
  }
52
+ class CheckViolationError extends QueryError {
53
+ }
50
54
  class SerializationFailureError extends QueryError {
51
55
  }
52
56
  class InvalidDataError extends QueryError {
@@ -61,6 +65,7 @@ class TerminatedConnectionError extends DatabaseError {
61
65
  }
62
66
  }
63
67
  exports.CannotCommitError = CannotCommitError;
68
+ exports.CheckViolationError = CheckViolationError;
64
69
  exports.ClientError = ClientError;
65
70
  exports.DatabaseError = DatabaseError;
66
71
  exports.ForeignKeyViolationError = ForeignKeyViolationError;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","sources":["../../../../../packages/database/src/client/errors.ts"],"sourcesContent":["export class DatabaseError extends Error {\n\tpublic readonly code?: string\n\tpublic readonly originalMessage?: string\n\tpublic readonly previous: any\n\n\tconstructor(errMessage: string, previous?: Error | any) {\n\t\tsuper(errMessage)\n\t\tif (previous) {\n\t\t\tconst { message, stack, ...other } = previous\n\t\t\tconst otherDefined = Object.fromEntries(Object.entries(other).filter(it => it[1] !== undefined))\n\t\t\tthis.previous = { message, ...otherDefined }\n\t\t\tthis.code = previous.code\n\t\t\tthis.originalMessage = previous.message\n\t\t}\n\t}\n}\n\nexport type ClientErrorType =\n\t| 'recoverable connection error'\n\t| 'connection error'\n\t| 'runtime error'\n\t| 'disposal error'\n\nexport class ClientError extends DatabaseError {\n\tconstructor(previous: Error | any, public readonly type: ClientErrorType) {\n\t\tsuper(`Database client ${type}: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}`, previous)\n\t}\n}\n\nexport class QueryError extends DatabaseError {\n\tpublic readonly constraint?: string\n\tpublic readonly table?: string\n\n\tconstructor(public readonly sql: string, public readonly parameters: any, public override readonly previous: Error | any) {\n\t\tsuper(\n\t\t\t`Database query error: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}\nSQL: ${sql}\nparameters: ${parameters}`,\n\t\t\tprevious,\n\t\t)\n\t\tthis.constraint = previous.constraint\n\t\tthis.table = previous.table\n\t}\n}\n\nexport class NotNullViolationError extends QueryError {}\n\nexport class ForeignKeyViolationError extends QueryError {}\n\nexport class UniqueViolationError extends QueryError {}\n\nexport class SerializationFailureError extends QueryError {}\n\nexport class InvalidDataError extends QueryError {}\n\nexport class TransactionAbortedError extends QueryError {}\n\nexport class CannotCommitError extends DatabaseError {}\n\nexport class TerminatedConnectionError extends DatabaseError {\n\tconstructor() {\n\t\tsuper('Database connection was terminated')\n\t}\n}\n"],"names":[],"mappings":";;;;;AAAO,MAAM,sBAAsB,MAAM;AAAA,EAKxC,YAAY,YAAoB,UAAwB;AACvD,UAAM,UAAU;AALjB,kBAAA,MAAgB,MAAA;AAChB,kBAAA,MAAgB,iBAAA;AAChB,kBAAA,MAAgB,UAAA;AAIf,QAAI,UAAU;AACb,YAAM,EAAE,SAAS,OAAO,GAAG,UAAU;AACrC,YAAM,eAAe,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,OAAO,CAAA,OAAM,GAAG,CAAC,MAAM,MAAS,CAAC;AAC/F,WAAK,WAAW,EAAE,SAAS,GAAG,aAAA;AAC9B,WAAK,OAAO,SAAS;AACrB,WAAK,kBAAkB,SAAS;AAAA,IACjC;AAAA,EACD;AACD;AAQO,MAAM,oBAAoB,cAAc;AAAA,EAC9C,YAAY,UAAuC,MAAuB;AACzE,UAAM,mBAAmB,IAAI,KAAK,aAAa,YAAY,SAAS,UAAU,SAAS,UAAU,KAAK,UAAU,QAAQ,CAAC,IAAI,QAAQ;AADnF,SAAA,OAAA;AAAA,EAEnD;AACD;AAEO,MAAM,mBAAmB,cAAc;AAAA,EAI7C,YAA4B,KAA6B,YAA0C,UAAuB;AACzH;AAAA,MACC,yBAAyB,aAAa,YAAY,SAAS,UAAU,SAAS,UAAU,KAAK,UAAU,QAAQ,CAAC;AAAA,OAC5G,GAAG;AAAA,cACI,UAAU;AAAA,MACrB;AAAA,IAAA;AAL0B,SAAA,MAAA;AAA6B,SAAA,aAAA;AAA0C,SAAA,WAAA;AAHnG,kBAAA,MAAgB,YAAA;AAChB,kBAAA,MAAgB,OAAA;AASf,SAAK,aAAa,SAAS;AAC3B,SAAK,QAAQ,SAAS;AAAA,EACvB;AACD;AAEO,MAAM,8BAA8B,WAAW;AAAC;AAEhD,MAAM,iCAAiC,WAAW;AAAC;AAEnD,MAAM,6BAA6B,WAAW;AAAC;AAE/C,MAAM,kCAAkC,WAAW;AAAC;AAEpD,MAAM,yBAAyB,WAAW;AAAC;AAE3C,MAAM,gCAAgC,WAAW;AAAC;AAElD,MAAM,0BAA0B,cAAc;AAAC;AAE/C,MAAM,kCAAkC,cAAc;AAAA,EAC5D,cAAc;AACb,UAAM,oCAAoC;AAAA,EAC3C;AACD;;;;;;;;;;;;"}
1
+ {"version":3,"file":"errors.cjs","sources":["../../../../../packages/database/src/client/errors.ts"],"sourcesContent":["export class DatabaseError extends Error {\n\tpublic readonly code?: string\n\tpublic readonly originalMessage?: string\n\tpublic readonly previous: any\n\n\tconstructor(errMessage: string, previous?: Error | any) {\n\t\tsuper(errMessage)\n\t\tif (previous) {\n\t\t\tconst { message, stack, ...other } = previous\n\t\t\tconst otherDefined = Object.fromEntries(Object.entries(other).filter(it => it[1] !== undefined))\n\t\t\tthis.previous = { message, ...otherDefined }\n\t\t\tthis.code = previous.code\n\t\t\tthis.originalMessage = previous.message\n\t\t}\n\t}\n}\n\nexport type ClientErrorType =\n\t| 'recoverable connection error'\n\t| 'connection error'\n\t| 'runtime error'\n\t| 'disposal error'\n\nexport class ClientError extends DatabaseError {\n\tconstructor(previous: Error | any, public readonly type: ClientErrorType) {\n\t\tsuper(`Database client ${type}: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}`, previous)\n\t}\n}\n\n// PostgreSQL often puts the actionable part of an error (e.g. which objects block a DROP) into DETAIL and HINT.\nconst formatDiagnosticField = (label: string, value: unknown): string => typeof value === 'string' && value !== '' ? `\\n${label}: ${value}` : ''\n\nexport class QueryError extends DatabaseError {\n\tpublic readonly constraint?: string\n\tpublic readonly table?: string\n\n\tconstructor(public readonly sql: string, public readonly parameters: any, public override readonly previous: Error | any) {\n\t\tsuper(\n\t\t\t('message' in previous && previous.message\n\t\t\t\t? `Database query error: ${previous.message}` + formatDiagnosticField('Detail', previous.detail) + formatDiagnosticField('Hint', previous.hint)\n\t\t\t\t: `Database query error: ${JSON.stringify(previous)}`)\n\t\t\t\t+ `\\nSQL: ${sql}\\nparameters: ${parameters}`,\n\t\t\tprevious,\n\t\t)\n\t\tthis.constraint = previous.constraint\n\t\tthis.table = previous.table\n\t}\n}\n\nexport class NotNullViolationError extends QueryError {}\n\nexport class ForeignKeyViolationError extends QueryError {}\n\nexport class UniqueViolationError extends QueryError {}\n\nexport class CheckViolationError extends QueryError {}\n\nexport class SerializationFailureError extends QueryError {}\n\nexport class InvalidDataError extends QueryError {}\n\nexport class TransactionAbortedError extends QueryError {}\n\nexport class CannotCommitError extends DatabaseError {}\n\nexport class TerminatedConnectionError extends DatabaseError {\n\tconstructor() {\n\t\tsuper('Database connection was terminated')\n\t}\n}\n"],"names":[],"mappings":";;;;;AAAO,MAAM,sBAAsB,MAAM;AAAA,EAKxC,YAAY,YAAoB,UAAwB;AACvD,UAAM,UAAU;AALjB,kBAAA,MAAgB,MAAA;AAChB,kBAAA,MAAgB,iBAAA;AAChB,kBAAA,MAAgB,UAAA;AAIf,QAAI,UAAU;AACb,YAAM,EAAE,SAAS,OAAO,GAAG,UAAU;AACrC,YAAM,eAAe,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,OAAO,CAAA,OAAM,GAAG,CAAC,MAAM,MAAS,CAAC;AAC/F,WAAK,WAAW,EAAE,SAAS,GAAG,aAAA;AAC9B,WAAK,OAAO,SAAS;AACrB,WAAK,kBAAkB,SAAS;AAAA,IACjC;AAAA,EACD;AACD;AAQO,MAAM,oBAAoB,cAAc;AAAA,EAC9C,YAAY,UAAuC,MAAuB;AACzE,UAAM,mBAAmB,IAAI,KAAK,aAAa,YAAY,SAAS,UAAU,SAAS,UAAU,KAAK,UAAU,QAAQ,CAAC,IAAI,QAAQ;AADnF,SAAA,OAAA;AAAA,EAEnD;AACD;AAGA,MAAM,wBAAwB,CAAC,OAAe,UAA2B,OAAO,UAAU,YAAY,UAAU,KAAK;AAAA,EAAK,KAAK,KAAK,KAAK,KAAK;AAEvI,MAAM,mBAAmB,cAAc;AAAA,EAI7C,YAA4B,KAA6B,YAA0C,UAAuB;AACzH;AAAA,OACE,aAAa,YAAY,SAAS,UAChC,yBAAyB,SAAS,OAAO,KAAK,sBAAsB,UAAU,SAAS,MAAM,IAAI,sBAAsB,QAAQ,SAAS,IAAI,IAC5I,yBAAyB,KAAK,UAAU,QAAQ,CAAC,MACjD;AAAA,OAAU,GAAG;AAAA,cAAiB,UAAU;AAAA,MAC3C;AAAA,IAAA;AAN0B,SAAA,MAAA;AAA6B,SAAA,aAAA;AAA0C,SAAA,WAAA;AAHnG,kBAAA,MAAgB,YAAA;AAChB,kBAAA,MAAgB,OAAA;AAUf,SAAK,aAAa,SAAS;AAC3B,SAAK,QAAQ,SAAS;AAAA,EACvB;AACD;AAEO,MAAM,8BAA8B,WAAW;AAAC;AAEhD,MAAM,iCAAiC,WAAW;AAAC;AAEnD,MAAM,6BAA6B,WAAW;AAAC;AAE/C,MAAM,4BAA4B,WAAW;AAAC;AAE9C,MAAM,kCAAkC,WAAW;AAAC;AAEpD,MAAM,yBAAyB,WAAW;AAAC;AAE3C,MAAM,gCAAgC,WAAW;AAAC;AAElD,MAAM,0BAA0B,cAAc;AAAC;AAE/C,MAAM,kCAAkC,cAAc;AAAA,EAC5D,cAAc;AACb,UAAM,oCAAoC;AAAA,EAC3C;AACD;;;;;;;;;;;;;"}
@@ -22,10 +22,12 @@ class ClientError extends DatabaseError {
22
22
  this.type = type;
23
23
  }
24
24
  }
25
+ const formatDiagnosticField = (label, value) => typeof value === "string" && value !== "" ? `
26
+ ${label}: ${value}` : "";
25
27
  class QueryError extends DatabaseError {
26
28
  constructor(sql, parameters, previous) {
27
29
  super(
28
- `Database query error: ${"message" in previous && previous.message ? previous.message : JSON.stringify(previous)}
30
+ ("message" in previous && previous.message ? `Database query error: ${previous.message}` + formatDiagnosticField("Detail", previous.detail) + formatDiagnosticField("Hint", previous.hint) : `Database query error: ${JSON.stringify(previous)}`) + `
29
31
  SQL: ${sql}
30
32
  parameters: ${parameters}`,
31
33
  previous
@@ -45,6 +47,8 @@ class ForeignKeyViolationError extends QueryError {
45
47
  }
46
48
  class UniqueViolationError extends QueryError {
47
49
  }
50
+ class CheckViolationError extends QueryError {
51
+ }
48
52
  class SerializationFailureError extends QueryError {
49
53
  }
50
54
  class InvalidDataError extends QueryError {
@@ -60,6 +64,7 @@ class TerminatedConnectionError extends DatabaseError {
60
64
  }
61
65
  export {
62
66
  CannotCommitError,
67
+ CheckViolationError,
63
68
  ClientError,
64
69
  DatabaseError,
65
70
  ForeignKeyViolationError,
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sources":["../../../../../packages/database/src/client/errors.ts"],"sourcesContent":["export class DatabaseError extends Error {\n\tpublic readonly code?: string\n\tpublic readonly originalMessage?: string\n\tpublic readonly previous: any\n\n\tconstructor(errMessage: string, previous?: Error | any) {\n\t\tsuper(errMessage)\n\t\tif (previous) {\n\t\t\tconst { message, stack, ...other } = previous\n\t\t\tconst otherDefined = Object.fromEntries(Object.entries(other).filter(it => it[1] !== undefined))\n\t\t\tthis.previous = { message, ...otherDefined }\n\t\t\tthis.code = previous.code\n\t\t\tthis.originalMessage = previous.message\n\t\t}\n\t}\n}\n\nexport type ClientErrorType =\n\t| 'recoverable connection error'\n\t| 'connection error'\n\t| 'runtime error'\n\t| 'disposal error'\n\nexport class ClientError extends DatabaseError {\n\tconstructor(previous: Error | any, public readonly type: ClientErrorType) {\n\t\tsuper(`Database client ${type}: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}`, previous)\n\t}\n}\n\nexport class QueryError extends DatabaseError {\n\tpublic readonly constraint?: string\n\tpublic readonly table?: string\n\n\tconstructor(public readonly sql: string, public readonly parameters: any, public override readonly previous: Error | any) {\n\t\tsuper(\n\t\t\t`Database query error: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}\nSQL: ${sql}\nparameters: ${parameters}`,\n\t\t\tprevious,\n\t\t)\n\t\tthis.constraint = previous.constraint\n\t\tthis.table = previous.table\n\t}\n}\n\nexport class NotNullViolationError extends QueryError {}\n\nexport class ForeignKeyViolationError extends QueryError {}\n\nexport class UniqueViolationError extends QueryError {}\n\nexport class SerializationFailureError extends QueryError {}\n\nexport class InvalidDataError extends QueryError {}\n\nexport class TransactionAbortedError extends QueryError {}\n\nexport class CannotCommitError extends DatabaseError {}\n\nexport class TerminatedConnectionError extends DatabaseError {\n\tconstructor() {\n\t\tsuper('Database connection was terminated')\n\t}\n}\n"],"names":[],"mappings":";;;AAAO,MAAM,sBAAsB,MAAM;AA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,cAAc;AAAC;AAE/C,MAAM,kCAAkC,cAAc;AAAA,EAC5D,cAAc;AACb,UAAM,oCAAoC;AAAA,EAC3C;AACD;"}
1
+ {"version":3,"file":"errors.js","sources":["../../../../../packages/database/src/client/errors.ts"],"sourcesContent":["export class DatabaseError extends Error {\n\tpublic readonly code?: string\n\tpublic readonly originalMessage?: string\n\tpublic readonly previous: any\n\n\tconstructor(errMessage: string, previous?: Error | any) {\n\t\tsuper(errMessage)\n\t\tif (previous) {\n\t\t\tconst { message, stack, ...other } = previous\n\t\t\tconst otherDefined = Object.fromEntries(Object.entries(other).filter(it => it[1] !== undefined))\n\t\t\tthis.previous = { message, ...otherDefined }\n\t\t\tthis.code = previous.code\n\t\t\tthis.originalMessage = previous.message\n\t\t}\n\t}\n}\n\nexport type ClientErrorType =\n\t| 'recoverable connection error'\n\t| 'connection error'\n\t| 'runtime error'\n\t| 'disposal error'\n\nexport class ClientError extends DatabaseError {\n\tconstructor(previous: Error | any, public readonly type: ClientErrorType) {\n\t\tsuper(`Database client ${type}: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}`, previous)\n\t}\n}\n\n// PostgreSQL often puts the actionable part of an error (e.g. which objects block a DROP) into DETAIL and HINT.\nconst formatDiagnosticField = (label: string, value: unknown): string => typeof value === 'string' && value !== '' ? `\\n${label}: ${value}` : ''\n\nexport class QueryError extends DatabaseError {\n\tpublic readonly constraint?: string\n\tpublic readonly table?: string\n\n\tconstructor(public readonly sql: string, public readonly parameters: any, public override readonly previous: Error | any) {\n\t\tsuper(\n\t\t\t('message' in previous && previous.message\n\t\t\t\t? `Database query error: ${previous.message}` + formatDiagnosticField('Detail', previous.detail) + formatDiagnosticField('Hint', previous.hint)\n\t\t\t\t: `Database query error: ${JSON.stringify(previous)}`)\n\t\t\t\t+ `\\nSQL: ${sql}\\nparameters: ${parameters}`,\n\t\t\tprevious,\n\t\t)\n\t\tthis.constraint = previous.constraint\n\t\tthis.table = previous.table\n\t}\n}\n\nexport class NotNullViolationError extends QueryError {}\n\nexport class ForeignKeyViolationError extends QueryError {}\n\nexport class UniqueViolationError extends QueryError {}\n\nexport class CheckViolationError extends QueryError {}\n\nexport class SerializationFailureError extends QueryError {}\n\nexport class InvalidDataError extends QueryError {}\n\nexport class TransactionAbortedError extends QueryError {}\n\nexport class CannotCommitError extends DatabaseError {}\n\nexport class TerminatedConnectionError extends DatabaseError {\n\tconstructor() {\n\t\tsuper('Database connection was terminated')\n\t}\n}\n"],"names":[],"mappings":";;;AAAO,MAAM,sBAAsB,MAAM;AAAA,EAKxC,YAAY,YAAoB,UAAwB;AACvD,UAAM,UAAU;AALjB,kBAAA,MAAgB,MAAA;AAChB,kBAAA,MAAgB,iBAAA;AAChB,kBAAA,MAAgB,UAAA;AAIf,QAAI,UAAU;AACb,YAAM,EAAE,SAAS,OAAO,GAAG,UAAU;AACrC,YAAM,eAAe,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,OAAO,CAAA,OAAM,GAAG,CAAC,MAAM,MAAS,CAAC;AAC/F,WAAK,WAAW,EAAE,SAAS,GAAG,aAAA;AAC9B,WAAK,OAAO,SAAS;AACrB,WAAK,kBAAkB,SAAS;AAAA,IACjC;AAAA,EACD;AACD;AAQO,MAAM,oBAAoB,cAAc;AAAA,EAC9C,YAAY,UAAuC,MAAuB;AACzE,UAAM,mBAAmB,IAAI,KAAK,aAAa,YAAY,SAAS,UAAU,SAAS,UAAU,KAAK,UAAU,QAAQ,CAAC,IAAI,QAAQ;AADnF,SAAA,OAAA;AAAA,EAEnD;AACD;AAGA,MAAM,wBAAwB,CAAC,OAAe,UAA2B,OAAO,UAAU,YAAY,UAAU,KAAK;AAAA,EAAK,KAAK,KAAK,KAAK,KAAK;AAEvI,MAAM,mBAAmB,cAAc;AAAA,EAI7C,YAA4B,KAA6B,YAA0C,UAAuB;AACzH;AAAA,OACE,aAAa,YAAY,SAAS,UAChC,yBAAyB,SAAS,OAAO,KAAK,sBAAsB,UAAU,SAAS,MAAM,IAAI,sBAAsB,QAAQ,SAAS,IAAI,IAC5I,yBAAyB,KAAK,UAAU,QAAQ,CAAC,MACjD;AAAA,OAAU,GAAG;AAAA,cAAiB,UAAU;AAAA,MAC3C;AAAA,IAAA;AAN0B,SAAA,MAAA;AAA6B,SAAA,aAAA;AAA0C,SAAA,WAAA;AAHnG,kBAAA,MAAgB,YAAA;AAChB,kBAAA,MAAgB,OAAA;AAUf,SAAK,aAAa,SAAS;AAC3B,SAAK,QAAQ,SAAS;AAAA,EACvB;AACD;AAEO,MAAM,8BAA8B,WAAW;AAAC;AAEhD,MAAM,iCAAiC,WAAW;AAAC;AAEnD,MAAM,6BAA6B,WAAW;AAAC;AAE/C,MAAM,4BAA4B,WAAW;AAAC;AAE9C,MAAM,kCAAkC,WAAW;AAAC;AAEpD,MAAM,yBAAyB,WAAW;AAAC;AAE3C,MAAM,gCAAgC,WAAW;AAAC;AAElD,MAAM,0BAA0B,cAAc;AAAC;AAE/C,MAAM,kCAAkC,cAAc;AAAA,EAC5D,cAAc;AACb,UAAM,oCAAoC;AAAA,EAC3C;AACD;"}
@@ -1 +1 @@
1
- {"version":3,"file":"pgClientFactory.cjs","sources":["../../../../../packages/database/src/utils/pgClientFactory.ts"],"sourcesContent":["import pg from 'pg'\nimport { DatabaseConfig } from '../types.js'\nimport { PgClient } from '../client/PgClient.js'\n\nexport type PgClientFactory = () => PgClient\nexport const createPgClientFactory =\n\t({ queryTimeoutMs, statementTimeoutMs, lockTimeoutMs, connectionTimeoutMs, ...config }: DatabaseConfig) => () => {\n\t\t// `lock_timeout` is supported by pg at runtime but missing from the installed @types/pg version,\n\t\t// so it is typed explicitly here.\n\t\tconst { keepAlive, keepAliveInitialDelayMs, ...connectionConfig } = config\n\t\tconst clientConfig: pg.ClientConfig & { lock_timeout?: number } = {\n\t\t\tquery_timeout: queryTimeoutMs,\n\t\t\tstatement_timeout: statementTimeoutMs,\n\t\t\tlock_timeout: lockTimeoutMs,\n\t\t\tconnectionTimeoutMillis: connectionTimeoutMs,\n\t\t\tkeepAlive: keepAlive ?? false,\n\t\t\tkeepAliveInitialDelayMillis: keepAliveInitialDelayMs,\n\t\t\t...connectionConfig,\n\t\t}\n\t\treturn new pg.Client(clientConfig)\n\t}\n"],"names":[],"mappings":";;;AAKO,MAAM,wBACZ,CAAC,EAAE,gBAAgB,oBAAoB,eAAe,qBAAqB,GAAG,OAAA,MAA6B,MAAM;AAGhH,QAAM,EAAE,WAAW,yBAAyB,GAAG,qBAAqB;AACpE,QAAM,eAA4D;AAAA,IACjE,eAAe;AAAA,IACf,mBAAmB;AAAA,IACnB,cAAc;AAAA,IACd,yBAAyB;AAAA,IACzB,WAAW,aAAa;AAAA,IACxB,6BAA6B;AAAA,IAC7B,GAAG;AAAA,EAAA;AAEJ,SAAO,IAAI,GAAG,OAAO,YAAY;AAClC;;"}
1
+ {"version":3,"file":"pgClientFactory.cjs","sources":["../../../../../packages/database/src/utils/pgClientFactory.ts"],"sourcesContent":["import pg from 'pg'\nimport { DatabaseConfig } from '../types.js'\nimport { PgClient } from '../client/PgClient.js'\n\nexport type PgClientFactory = () => PgClient\nexport const createPgClientFactory =\n\t({ queryTimeoutMs, statementTimeoutMs, lockTimeoutMs, connectionTimeoutMs, ...config }: DatabaseConfig) => () => {\n\t\tconst { keepAlive, keepAliveInitialDelayMs, ...connectionConfig } = config\n\t\tconst clientConfig: pg.ClientConfig = {\n\t\t\tquery_timeout: queryTimeoutMs,\n\t\t\tstatement_timeout: statementTimeoutMs,\n\t\t\tlock_timeout: lockTimeoutMs,\n\t\t\tconnectionTimeoutMillis: connectionTimeoutMs,\n\t\t\tkeepAlive: keepAlive ?? false,\n\t\t\tkeepAliveInitialDelayMillis: keepAliveInitialDelayMs,\n\t\t\t...connectionConfig,\n\t\t}\n\t\treturn new pg.Client(clientConfig)\n\t}\n"],"names":[],"mappings":";;;AAKO,MAAM,wBACZ,CAAC,EAAE,gBAAgB,oBAAoB,eAAe,qBAAqB,GAAG,OAAA,MAA6B,MAAM;AAChH,QAAM,EAAE,WAAW,yBAAyB,GAAG,qBAAqB;AACpE,QAAM,eAAgC;AAAA,IACrC,eAAe;AAAA,IACf,mBAAmB;AAAA,IACnB,cAAc;AAAA,IACd,yBAAyB;AAAA,IACzB,WAAW,aAAa;AAAA,IACxB,6BAA6B;AAAA,IAC7B,GAAG;AAAA,EAAA;AAEJ,SAAO,IAAI,GAAG,OAAO,YAAY;AAClC;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"pgClientFactory.js","sources":["../../../../../packages/database/src/utils/pgClientFactory.ts"],"sourcesContent":["import pg from 'pg'\nimport { DatabaseConfig } from '../types.js'\nimport { PgClient } from '../client/PgClient.js'\n\nexport type PgClientFactory = () => PgClient\nexport const createPgClientFactory =\n\t({ queryTimeoutMs, statementTimeoutMs, lockTimeoutMs, connectionTimeoutMs, ...config }: DatabaseConfig) => () => {\n\t\t// `lock_timeout` is supported by pg at runtime but missing from the installed @types/pg version,\n\t\t// so it is typed explicitly here.\n\t\tconst { keepAlive, keepAliveInitialDelayMs, ...connectionConfig } = config\n\t\tconst clientConfig: pg.ClientConfig & { lock_timeout?: number } = {\n\t\t\tquery_timeout: queryTimeoutMs,\n\t\t\tstatement_timeout: statementTimeoutMs,\n\t\t\tlock_timeout: lockTimeoutMs,\n\t\t\tconnectionTimeoutMillis: connectionTimeoutMs,\n\t\t\tkeepAlive: keepAlive ?? false,\n\t\t\tkeepAliveInitialDelayMillis: keepAliveInitialDelayMs,\n\t\t\t...connectionConfig,\n\t\t}\n\t\treturn new pg.Client(clientConfig)\n\t}\n"],"names":[],"mappings":";AAKO,MAAM,wBACZ,CAAC,EAAE,gBAAgB,oBAAoB,eAAe,qBAAqB,GAAG,OAAA,MAA6B,MAAM;AAGhH,QAAM,EAAE,WAAW,yBAAyB,GAAG,qBAAqB;AACpE,QAAM,eAA4D;AAAA,IACjE,eAAe;AAAA,IACf,mBAAmB;AAAA,IACnB,cAAc;AAAA,IACd,yBAAyB;AAAA,IACzB,WAAW,aAAa;AAAA,IACxB,6BAA6B;AAAA,IAC7B,GAAG;AAAA,EAAA;AAEJ,SAAO,IAAI,GAAG,OAAO,YAAY;AAClC;"}
1
+ {"version":3,"file":"pgClientFactory.js","sources":["../../../../../packages/database/src/utils/pgClientFactory.ts"],"sourcesContent":["import pg from 'pg'\nimport { DatabaseConfig } from '../types.js'\nimport { PgClient } from '../client/PgClient.js'\n\nexport type PgClientFactory = () => PgClient\nexport const createPgClientFactory =\n\t({ queryTimeoutMs, statementTimeoutMs, lockTimeoutMs, connectionTimeoutMs, ...config }: DatabaseConfig) => () => {\n\t\tconst { keepAlive, keepAliveInitialDelayMs, ...connectionConfig } = config\n\t\tconst clientConfig: pg.ClientConfig = {\n\t\t\tquery_timeout: queryTimeoutMs,\n\t\t\tstatement_timeout: statementTimeoutMs,\n\t\t\tlock_timeout: lockTimeoutMs,\n\t\t\tconnectionTimeoutMillis: connectionTimeoutMs,\n\t\t\tkeepAlive: keepAlive ?? false,\n\t\t\tkeepAliveInitialDelayMillis: keepAliveInitialDelayMs,\n\t\t\t...connectionConfig,\n\t\t}\n\t\treturn new pg.Client(clientConfig)\n\t}\n"],"names":[],"mappings":";AAKO,MAAM,wBACZ,CAAC,EAAE,gBAAgB,oBAAoB,eAAe,qBAAqB,GAAG,OAAA,MAA6B,MAAM;AAChH,QAAM,EAAE,WAAW,yBAAyB,GAAG,qBAAqB;AACpE,QAAM,eAAgC;AAAA,IACrC,eAAe;AAAA,IACf,mBAAmB;AAAA,IACnB,cAAc;AAAA,IACd,yBAAyB;AAAA,IACzB,WAAW,aAAa;AAAA,IACxB,6BAA6B;AAAA,IAC7B,GAAG;AAAA,EAAA;AAEJ,SAAO,IAAI,GAAG,OAAO,YAAY;AAClC;"}
@@ -41,6 +41,7 @@ const RequestMemoryBudget = require("./src/client/RequestMemoryBudget.cjs");
41
41
  exports.Client = Client.Client;
42
42
  exports.ClientErrorCodes = errorCodes.ClientErrorCodes;
43
43
  exports.CannotCommitError = errors.CannotCommitError;
44
+ exports.CheckViolationError = errors.CheckViolationError;
44
45
  exports.ClientError = errors.ClientError;
45
46
  exports.DatabaseError = errors.DatabaseError;
46
47
  exports.ForeignKeyViolationError = errors.ForeignKeyViolationError;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -1,6 +1,6 @@
1
1
  import { Client } from "./src/client/Client.js";
2
2
  import { ClientErrorCodes } from "./src/client/errorCodes.js";
3
- import { CannotCommitError, ClientError, DatabaseError, ForeignKeyViolationError, InvalidDataError, NotNullViolationError, QueryError, SerializationFailureError, TerminatedConnectionError, TransactionAbortedError, UniqueViolationError } from "./src/client/errors.js";
3
+ import { CannotCommitError, CheckViolationError, ClientError, DatabaseError, ForeignKeyViolationError, InvalidDataError, NotNullViolationError, QueryError, SerializationFailureError, TerminatedConnectionError, TransactionAbortedError, UniqueViolationError } from "./src/client/errors.js";
4
4
  import { Connection } from "./src/client/Connection.js";
5
5
  import { ScopeLimitedConnection } from "./src/client/ScopeLimitedConnection.js";
6
6
  import { EventManager } from "./src/client/EventManager.js";
@@ -41,6 +41,7 @@ export {
41
41
  AcquiringListener,
42
42
  CannotCommitError,
43
43
  CaseStatement,
44
+ CheckViolationError,
44
45
  Client,
45
46
  ClientError,
46
47
  ClientErrorCodes,
@@ -75,6 +75,8 @@ class AcquiredConnection {
75
75
  throw new errors.ForeignKeyViolationError(sql, parameters, error);
76
76
  case errorCodes.ClientErrorCodes.UNIQUE_VIOLATION:
77
77
  throw new errors.UniqueViolationError(sql, parameters, error);
78
+ case errorCodes.ClientErrorCodes.CHECK_VIOLATION:
79
+ throw new errors.CheckViolationError(sql, parameters, error);
78
80
  // both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike
79
81
  case errorCodes.ClientErrorCodes.T_R_SERIALIZATION_FAILURE:
80
82
  case errorCodes.ClientErrorCodes.T_R_DEADLOCK_DETECTED:
@@ -1 +1 @@
1
- {"version":3,"file":"AcquiredConnection.cjs","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex, MutexDeadlockError } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTerminatedConnectionError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { cancelRunningStatement } from './cancelRunningStatement.js'\nimport { Notification, Query, QueryResult, QueryResultRow } from 'pg'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t\tprivate readonly physicalConnection = { terminated: false },\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\t// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.\n\t\tthis.refuseExhaustedOrTerminated()\n\n\t\tconst query: Connection.Query = { sql, parameters, meta }\n\n\t\ttry {\n\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, query)\n\n\t\t\tconst result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {\n\t\t\t\t// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.\n\t\t\t\tthis.refuseExhaustedOrTerminated()\n\t\t\t\tconst memoryBudget = this.eventManager.memoryBudget\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tconst pgResult = memoryBudget && this.eventManager.chargesMemoryBudget\n\t\t\t\t\t? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)\n\t\t\t\t\t: await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\n\t\t\t\treturn {\n\t\t\t\t\t...pgResult,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, query, result)\n\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.eventManager.fire(EventManager.Event.queryError, query, error)\n\n\t\t\t// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated\n\t\t\tif (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tswitch ((error as any).code) {\n\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\t// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike\n\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\tcase ClientErrorCodes.T_R_DEADLOCK_DETECTED:\n\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\tcase ClientErrorCodes.INVALID_DATETIME_FORMAT:\n\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate refuseExhaustedOrTerminated(): void {\n\t\t// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.\n\t\tthis.eventManager.memoryBudget?.check()\n\t\tif (this.physicalConnection.terminated) {\n\t\t\tthrow new TerminatedConnectionError()\n\t\t}\n\t}\n\n\tprivate async queryWithMemoryBudget<Row extends QueryResultRow>(\n\t\tsql: string,\n\t\tparameters: unknown[],\n\t\tbudget: RequestMemoryBudget,\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await new Promise<Connection.Result<Row>>((resolve, reject) => {\n\t\t\tlet rows: Row[] | undefined\n\t\t\tlet failure: Error | undefined\n\t\t\tlet cleanup = () => {}\n\t\t\tconst stop = (error: Error) => {\n\t\t\t\tfailure = error\n\t\t\t\tif (rows) {\n\t\t\t\t\trows.length = 0\n\t\t\t\t}\n\t\t\t\tcleanup()\n\t\t\t\t// A budget failure invalidates this connection; the enclosing pool scope disposes it.\n\t\t\t\tthis.physicalConnection.terminated = true\n\t\t\t\t// Ending the socket alone leaves a statement still waiting for its first row running on the server.\n\t\t\t\t// Cancelling is best effort and must not mask the budget error.\n\t\t\t\tvoid cancelRunningStatement(this.pgClient).catch(() => {})\n\t\t\t\tvoid this.pgClient.end().catch(reject)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst config = {\n\t\t\t\ttext: sql,\n\t\t\t\tvalues: parameters,\n\t\t\t\tcallback: (error: Error | null, result?: QueryResult<Row>) => {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tif (failure || error) {\n\t\t\t\t\t\treject(failure || error)\n\t\t\t\t\t} else if (result) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error('PostgreSQL query completed without a result'))\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst query = new Query<Row>(config)\n\t\t\t// A sibling query of the request may exhaust the budget while this one still waits for its first row.\n\t\t\tcleanup = budget.onExceeded(stop)\n\t\t\tquery.on('row', (row, result) => {\n\t\t\t\trows = result?.rows\n\t\t\t\tif (failure) {\n\t\t\t\t\tif (rows) {\n\t\t\t\t\t\trows.length = 0\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tbudget.addDatabaseRow(row)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!failure) {\n\t\t\t\t\t\tstop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tthis.pgClient.query(query)\n\t\t\t} catch (error) {\n\t\t\t\tcleanup()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":["Mutex","Transaction","executeTransaction","EventManager","MutexDeadlockError","RequestMemoryBudgetExceededError","TerminatedConnectionError","ClientErrorCodes","NotNullViolationError","ForeignKeyViolationError","UniqueViolationError","SerializationFailureError","InvalidDataError","TransactionAbortedError","QueryError","cancelRunningStatement","Query"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACC,qBAAqB,EAAE,YAAY,SACnD;AAHgB,SAAA,WAAA;AACD,SAAA,eAAA;AACC,SAAA,qBAAA;AALlB,kBAAA,MAAQ,SAAQ,IAAIA,MAAAA,MAAA,CAAM;AAAA,EAO1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,QAAQ,YAAY;AAC3C,aAAO,MAAM,SAAS,IAAI,mBAAmB,KAAK,UAAU,QAAQ,gBAAgB,KAAK,cAAc,KAAK,kBAAkB,CAAC;AAAA,IAChI,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,YAAM,WAA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cquiredConnection.cjs","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex, MutexDeadlockError } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tCheckViolationError,\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTerminatedConnectionError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { cancelRunningStatement } from './cancelRunningStatement.js'\nimport { Notification, Query, QueryResult, QueryResultRow } from 'pg'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t\tprivate readonly physicalConnection = { terminated: false },\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\t// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.\n\t\tthis.refuseExhaustedOrTerminated()\n\n\t\tconst query: Connection.Query = { sql, parameters, meta }\n\n\t\ttry {\n\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, query)\n\n\t\t\tconst result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {\n\t\t\t\t// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.\n\t\t\t\tthis.refuseExhaustedOrTerminated()\n\t\t\t\tconst memoryBudget = this.eventManager.memoryBudget\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tconst pgResult = memoryBudget && this.eventManager.chargesMemoryBudget\n\t\t\t\t\t? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)\n\t\t\t\t\t: await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\n\t\t\t\treturn {\n\t\t\t\t\t...pgResult,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, query, result)\n\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.eventManager.fire(EventManager.Event.queryError, query, error)\n\n\t\t\t// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated\n\t\t\tif (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tswitch ((error as any).code) {\n\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.CHECK_VIOLATION:\n\t\t\t\t\tthrow new CheckViolationError(sql, parameters, error)\n\t\t\t\t// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike\n\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\tcase ClientErrorCodes.T_R_DEADLOCK_DETECTED:\n\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\tcase ClientErrorCodes.INVALID_DATETIME_FORMAT:\n\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate refuseExhaustedOrTerminated(): void {\n\t\t// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.\n\t\tthis.eventManager.memoryBudget?.check()\n\t\tif (this.physicalConnection.terminated) {\n\t\t\tthrow new TerminatedConnectionError()\n\t\t}\n\t}\n\n\tprivate async queryWithMemoryBudget<Row extends QueryResultRow>(\n\t\tsql: string,\n\t\tparameters: unknown[],\n\t\tbudget: RequestMemoryBudget,\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await new Promise<Connection.Result<Row>>((resolve, reject) => {\n\t\t\tlet rows: Row[] | undefined\n\t\t\tlet failure: Error | undefined\n\t\t\tlet cleanup = () => {}\n\t\t\tconst stop = (error: Error) => {\n\t\t\t\tfailure = error\n\t\t\t\tif (rows) {\n\t\t\t\t\trows.length = 0\n\t\t\t\t}\n\t\t\t\tcleanup()\n\t\t\t\t// A budget failure invalidates this connection; the enclosing pool scope disposes it.\n\t\t\t\tthis.physicalConnection.terminated = true\n\t\t\t\t// Ending the socket alone leaves a statement still waiting for its first row running on the server.\n\t\t\t\t// Cancelling is best effort and must not mask the budget error.\n\t\t\t\tvoid cancelRunningStatement(this.pgClient).catch(() => {})\n\t\t\t\tvoid this.pgClient.end().catch(reject)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst config = {\n\t\t\t\ttext: sql,\n\t\t\t\tvalues: parameters,\n\t\t\t\tcallback: (error: Error | null, result?: QueryResult<Row>) => {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tif (failure || error) {\n\t\t\t\t\t\treject(failure || error)\n\t\t\t\t\t} else if (result) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error('PostgreSQL query completed without a result'))\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst query = new Query<Row>(config)\n\t\t\t// A sibling query of the request may exhaust the budget while this one still waits for its first row.\n\t\t\tcleanup = budget.onExceeded(stop)\n\t\t\tquery.on('row', (row, result) => {\n\t\t\t\trows = result?.rows\n\t\t\t\tif (failure) {\n\t\t\t\t\tif (rows) {\n\t\t\t\t\t\trows.length = 0\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tbudget.addDatabaseRow(row)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!failure) {\n\t\t\t\t\t\tstop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tthis.pgClient.query(query)\n\t\t\t} catch (error) {\n\t\t\t\tcleanup()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":["Mutex","Transaction","executeTransaction","EventManager","MutexDeadlockError","RequestMemoryBudgetExceededError","TerminatedConnectionError","ClientErrorCodes","NotNullViolationError","ForeignKeyViolationError","UniqueViolationError","CheckViolationError","SerializationFailureError","InvalidDataError","TransactionAbortedError","QueryError","cancelRunningStatement","Query"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACC,qBAAqB,EAAE,YAAY,SACnD;AAHgB,SAAA,WAAA;AACD,SAAA,eAAA;AACC,SAAA,qBAAA;AALlB,kBAAA,MAAQ,SAAQ,IAAIA,MAAAA,MAAA,CAAM;AAAA,EAO1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,QAAQ,YAAY;AAC3C,aAAO,MAAM,SAAS,IAAI,mBAAmB,KAAK,UAAU,QAAQ,gBAAgB,KAAK,cAAc,KAAK,kBAAkB,CAAC;AAAA,IAChI,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,YAAM,WAAW,MAAM,SAAS,EAAE;AAClC,YAAM,cAAc,IAAIC,YAAAA,YAAY,UAAU;AAC9C,aAAO,MAAMC,YAAAA,mBAAmB,aAAa,QAAQ;AAAA,IACtD,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,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QAAQ;AAAA,QACR,UAAU,CAAC,OAAqB,WAA8B;AAC7D,kBAAA;AACA,cAAI,WAAW,OAAO;AACrB,mBAAO,WAAW,KAAK;AAAA,UACxB,WAAW,QAAQ;AAClB,oBAAQ,MAAM;AAAA,UACf,OAAO;AACN,mBAAO,IAAI,MAAM,6CAA6C,CAAC;AAAA,UAChE;AAAA,QACD;AAAA,MAAA;AAED,YAAM,QAAQ,IAAIC,GAAAA,MAAW,MAAM;AAEnC,gBAAU,OAAO,WAAW,IAAI;AAChC,YAAM,GAAG,OAAO,CAAC,KAAK,WAAW;AAChC,eAAO,QAAQ;AACf,YAAI,SAAS;AACZ,cAAI,MAAM;AACT,iBAAK,SAAS;AAAA,UACf;AACA;AAAA,QACD;AACA,YAAI;AACH,iBAAO,eAAe,GAAG;AAAA,QAC1B,SAAS,OAAO;AACf,cAAI,CAAC,SAAS;AACb,iBAAK,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,sCAAsC,EAAE,OAAO,MAAA,CAAO,CAAC;AAAA,UACxG;AAAA,QACD;AAAA,MACD,CAAC;AACD,UAAI;AACH,aAAK,SAAS,MAAM,KAAK;AAAA,MAC1B,SAAS,OAAO;AACf,gBAAA;AACA,eAAO,KAAK;AAAA,MACb;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,GAAG,OAAyC,IAAoF;AAC/H,SAAK,SAAS,GAAG,OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;;"}
@@ -6,7 +6,7 @@ import "../builders/internal/With.js";
6
6
  import "../builders/internal/Where.js";
7
7
  import "@contember/queryable";
8
8
  import { ClientErrorCodes } from "./errorCodes.js";
9
- import { TerminatedConnectionError, QueryError, TransactionAbortedError, InvalidDataError, SerializationFailureError, UniqueViolationError, ForeignKeyViolationError, NotNullViolationError } from "./errors.js";
9
+ import { TerminatedConnectionError, QueryError, TransactionAbortedError, InvalidDataError, SerializationFailureError, CheckViolationError, UniqueViolationError, ForeignKeyViolationError, NotNullViolationError } from "./errors.js";
10
10
  import "./Connection.js";
11
11
  import { Transaction, executeTransaction } from "./Transaction.js";
12
12
  import "node:timers";
@@ -73,6 +73,8 @@ class AcquiredConnection {
73
73
  throw new ForeignKeyViolationError(sql, parameters, error);
74
74
  case ClientErrorCodes.UNIQUE_VIOLATION:
75
75
  throw new UniqueViolationError(sql, parameters, error);
76
+ case ClientErrorCodes.CHECK_VIOLATION:
77
+ throw new CheckViolationError(sql, parameters, error);
76
78
  // both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike
77
79
  case ClientErrorCodes.T_R_SERIALIZATION_FAILURE:
78
80
  case ClientErrorCodes.T_R_DEADLOCK_DETECTED:
@@ -1 +1 @@
1
- {"version":3,"file":"AcquiredConnection.js","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex, MutexDeadlockError } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTerminatedConnectionError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { cancelRunningStatement } from './cancelRunningStatement.js'\nimport { Notification, Query, QueryResult, QueryResultRow } from 'pg'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t\tprivate readonly physicalConnection = { terminated: false },\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\t// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.\n\t\tthis.refuseExhaustedOrTerminated()\n\n\t\tconst query: Connection.Query = { sql, parameters, meta }\n\n\t\ttry {\n\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, query)\n\n\t\t\tconst result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {\n\t\t\t\t// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.\n\t\t\t\tthis.refuseExhaustedOrTerminated()\n\t\t\t\tconst memoryBudget = this.eventManager.memoryBudget\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tconst pgResult = memoryBudget && this.eventManager.chargesMemoryBudget\n\t\t\t\t\t? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)\n\t\t\t\t\t: await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\n\t\t\t\treturn {\n\t\t\t\t\t...pgResult,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, query, result)\n\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.eventManager.fire(EventManager.Event.queryError, query, error)\n\n\t\t\t// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated\n\t\t\tif (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tswitch ((error as any).code) {\n\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\t// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike\n\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\tcase ClientErrorCodes.T_R_DEADLOCK_DETECTED:\n\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\tcase ClientErrorCodes.INVALID_DATETIME_FORMAT:\n\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate refuseExhaustedOrTerminated(): void {\n\t\t// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.\n\t\tthis.eventManager.memoryBudget?.check()\n\t\tif (this.physicalConnection.terminated) {\n\t\t\tthrow new TerminatedConnectionError()\n\t\t}\n\t}\n\n\tprivate async queryWithMemoryBudget<Row extends QueryResultRow>(\n\t\tsql: string,\n\t\tparameters: unknown[],\n\t\tbudget: RequestMemoryBudget,\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await new Promise<Connection.Result<Row>>((resolve, reject) => {\n\t\t\tlet rows: Row[] | undefined\n\t\t\tlet failure: Error | undefined\n\t\t\tlet cleanup = () => {}\n\t\t\tconst stop = (error: Error) => {\n\t\t\t\tfailure = error\n\t\t\t\tif (rows) {\n\t\t\t\t\trows.length = 0\n\t\t\t\t}\n\t\t\t\tcleanup()\n\t\t\t\t// A budget failure invalidates this connection; the enclosing pool scope disposes it.\n\t\t\t\tthis.physicalConnection.terminated = true\n\t\t\t\t// Ending the socket alone leaves a statement still waiting for its first row running on the server.\n\t\t\t\t// Cancelling is best effort and must not mask the budget error.\n\t\t\t\tvoid cancelRunningStatement(this.pgClient).catch(() => {})\n\t\t\t\tvoid this.pgClient.end().catch(reject)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst config = {\n\t\t\t\ttext: sql,\n\t\t\t\tvalues: parameters,\n\t\t\t\tcallback: (error: Error | null, result?: QueryResult<Row>) => {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tif (failure || error) {\n\t\t\t\t\t\treject(failure || error)\n\t\t\t\t\t} else if (result) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error('PostgreSQL query completed without a result'))\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst query = new Query<Row>(config)\n\t\t\t// A sibling query of the request may exhaust the budget while this one still waits for its first row.\n\t\t\tcleanup = budget.onExceeded(stop)\n\t\t\tquery.on('row', (row, result) => {\n\t\t\t\trows = result?.rows\n\t\t\t\tif (failure) {\n\t\t\t\t\tif (rows) {\n\t\t\t\t\t\trows.length = 0\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tbudget.addDatabaseRow(row)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!failure) {\n\t\t\t\t\t\tstop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tthis.pgClient.query(query)\n\t\t\t} catch (error) {\n\t\t\t\tcleanup()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAoBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACC,qBAAqB,EAAE,YAAY,SACnD;AAHgB,SAAA,WAAA;AACD,SAAA,eAAA;AACC,SAAA,qBAAA;AALlB,kBAAA,MAAQ,SAAQ,IAAI,MAAA,CAAM;AAAA,EAO1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,QAAQ,YAAY;AAC3C,aAAO,MAAM,SAAS,IAAI,mBAAmB,KAAK,UAAU,QAAQ,gBAAgB,KAAK,cAAc,KAAK,kBA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SAAS;AAAA,QACd,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,UAAU,CAAC,OAAqB,WAA8B;AAC7D,kBAAA;AACA,cAAI,WAAW,OAAO;AACrB,mBAAO,WAAW,KAAK;AAAA,UACxB,WAAW,QAAQ;AAClB,oBAAQ,MAAM;AAAA,UACf,OAAO;AACN,mBAAO,IAAI,MAAM,6CAA6C,CAAC;AAAA,UAChE;AAAA,QACD;AAAA,MAAA;AAED,YAAM,QAAQ,IAAI,MAAW,MAAM;AAEnC,gBAAU,OAAO,WAAW,IAAI;AAChC,YAAM,GAAG,OAAO,CAAC,KAAK,WAAW;AAChC,eAAO,QAAQ;AACf,YAAI,SAAS;AACZ,cAAI,MAAM;AACT,iBAAK,SAAS;AAAA,UACf;AACA;AAAA,QACD;AACA,YAAI;AACH,iBAAO,eAAe,GAAG;AAAA,QAC1B,SAAS,OAAO;AACf,cAAI,CAAC,SAAS;AACb,iBAAK,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,sCAAsC,EAAE,OAAO,MAAA,CAAO,CAAC;AAAA,UACxG;AAAA,QACD;AAAA,MACD,CAAC;AACD,UAAI;AACH,aAAK,SAAS,MAAM,KAAK;AAAA,MAC1B,SAAS,OAAO;AACf,gBAAA;AACA,eAAO,KAAK;AAAA,MACb;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,GAAG,OAAyC,IAAoF;AAC/H,SAAK,SAAS,GAAG,OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;"}
1
+ {"version":3,"file":"AcquiredConnection.js","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex, MutexDeadlockError } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tCheckViolationError,\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTerminatedConnectionError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { cancelRunningStatement } from './cancelRunningStatement.js'\nimport { Notification, Query, QueryResult, QueryResultRow } from 'pg'\nimport { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t\tprivate readonly physicalConnection = { terminated: false },\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\t// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.\n\t\tthis.refuseExhaustedOrTerminated()\n\n\t\tconst query: Connection.Query = { sql, parameters, meta }\n\n\t\ttry {\n\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, query)\n\n\t\t\tconst result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {\n\t\t\t\t// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.\n\t\t\t\tthis.refuseExhaustedOrTerminated()\n\t\t\t\tconst memoryBudget = this.eventManager.memoryBudget\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tconst pgResult = memoryBudget && this.eventManager.chargesMemoryBudget\n\t\t\t\t\t? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)\n\t\t\t\t\t: await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\n\t\t\t\treturn {\n\t\t\t\t\t...pgResult,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, query, result)\n\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthis.eventManager.fire(EventManager.Event.queryError, query, error)\n\n\t\t\t// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated\n\t\t\tif (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tswitch ((error as any).code) {\n\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.CHECK_VIOLATION:\n\t\t\t\t\tthrow new CheckViolationError(sql, parameters, error)\n\t\t\t\t// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike\n\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\tcase ClientErrorCodes.T_R_DEADLOCK_DETECTED:\n\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\tcase ClientErrorCodes.INVALID_DATETIME_FORMAT:\n\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate refuseExhaustedOrTerminated(): void {\n\t\t// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.\n\t\tthis.eventManager.memoryBudget?.check()\n\t\tif (this.physicalConnection.terminated) {\n\t\t\tthrow new TerminatedConnectionError()\n\t\t}\n\t}\n\n\tprivate async queryWithMemoryBudget<Row extends QueryResultRow>(\n\t\tsql: string,\n\t\tparameters: unknown[],\n\t\tbudget: RequestMemoryBudget,\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await new Promise<Connection.Result<Row>>((resolve, reject) => {\n\t\t\tlet rows: Row[] | undefined\n\t\t\tlet failure: Error | undefined\n\t\t\tlet cleanup = () => {}\n\t\t\tconst stop = (error: Error) => {\n\t\t\t\tfailure = error\n\t\t\t\tif (rows) {\n\t\t\t\t\trows.length = 0\n\t\t\t\t}\n\t\t\t\tcleanup()\n\t\t\t\t// A budget failure invalidates this connection; the enclosing pool scope disposes it.\n\t\t\t\tthis.physicalConnection.terminated = true\n\t\t\t\t// Ending the socket alone leaves a statement still waiting for its first row running on the server.\n\t\t\t\t// Cancelling is best effort and must not mask the budget error.\n\t\t\t\tvoid cancelRunningStatement(this.pgClient).catch(() => {})\n\t\t\t\tvoid this.pgClient.end().catch(reject)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst config = {\n\t\t\t\ttext: sql,\n\t\t\t\tvalues: parameters,\n\t\t\t\tcallback: (error: Error | null, result?: QueryResult<Row>) => {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tif (failure || error) {\n\t\t\t\t\t\treject(failure || error)\n\t\t\t\t\t} else if (result) {\n\t\t\t\t\t\tresolve(result)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error('PostgreSQL query completed without a result'))\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t\tconst query = new Query<Row>(config)\n\t\t\t// A sibling query of the request may exhaust the budget while this one still waits for its first row.\n\t\t\tcleanup = budget.onExceeded(stop)\n\t\t\tquery.on('row', (row, result) => {\n\t\t\t\trows = result?.rows\n\t\t\t\tif (failure) {\n\t\t\t\t\tif (rows) {\n\t\t\t\t\t\trows.length = 0\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tbudget.addDatabaseRow(row)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!failure) {\n\t\t\t\t\t\tstop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tthis.pgClient.query(query)\n\t\t\t} catch (error) {\n\t\t\t\tcleanup()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAqBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACC,qBAAqB,EAAE,YAAY,SACnD;AAHgB,SAAA,WAAA;AACD,SAAA,eAAA;AACC,SAAA,qBAAA;AALlB,kBAAA,MAAQ,SAAQ,IAAI,MAAA,CAAM;AAAA,EAO1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,QAAQ,YAAY;AAC3C,aAAO,MAAM,SAAS,IAAI,mBAAmB,KAAK,UAAU,QAAQ,gBAAgB,KAAK,cAAc,KAAK,kBAAkB,CAAC;AAAA,IAChI,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,YAAM,WAAW,MAAM,SAAS,EAAE;AAClC,YAAM,cAAc,IAAI,YAAY,UAAU;AAC9C,aAAO,MAAM,mBAAmB,aAAa,QAAQ;AAAA,IACtD,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAElC,SAAK,4BAAA;AAEL,UAAM,QAA0B,EAAE,KAAK,YAAY,KAAA;AAEnD,QAAI;AACH,WAAK,aAAa,KAAK,aAAa,MAAM,YAAY,KAAK;AAE3D,YAAM,SAAS,MAAM,KAAK,MAAM,QAAQ,YAA6C;AAEpF,aAAK,4BAAA;AACL,cAAM,eAAe,KAAK,aAAa;AACvC,cAAM,cAAc,QAAQ,OAAO,OAAA;AAEnC,cAAM,WAAW,gBAAgB,KAAK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AC,SAAS;AACb,iBAAK,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,sCAAsC,EAAE,OAAO,MAAA,CAAO,CAAC;AAAA,UACxG;AAAA,QACD;AAAA,MACD,CAAC;AACD,UAAI;AACH,aAAK,SAAS,MAAM,KAAK;AAAA,MAC1B,SAAS,OAAO;AACf,gBAAA;AACA,eAAO,KAAK;AAAA,MACb;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,GAAG,OAAyC,IAAoF;AAC/H,SAAK,SAAS,GAAG,OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;"}
@@ -24,10 +24,12 @@ class ClientError extends DatabaseError {
24
24
  this.type = type;
25
25
  }
26
26
  }
27
+ const formatDiagnosticField = (label, value) => typeof value === "string" && value !== "" ? `
28
+ ${label}: ${value}` : "";
27
29
  class QueryError extends DatabaseError {
28
30
  constructor(sql, parameters, previous) {
29
31
  super(
30
- `Database query error: ${"message" in previous && previous.message ? previous.message : JSON.stringify(previous)}
32
+ ("message" in previous && previous.message ? `Database query error: ${previous.message}` + formatDiagnosticField("Detail", previous.detail) + formatDiagnosticField("Hint", previous.hint) : `Database query error: ${JSON.stringify(previous)}`) + `
31
33
  SQL: ${sql}
32
34
  parameters: ${parameters}`,
33
35
  previous
@@ -47,6 +49,8 @@ class ForeignKeyViolationError extends QueryError {
47
49
  }
48
50
  class UniqueViolationError extends QueryError {
49
51
  }
52
+ class CheckViolationError extends QueryError {
53
+ }
50
54
  class SerializationFailureError extends QueryError {
51
55
  }
52
56
  class InvalidDataError extends QueryError {
@@ -61,6 +65,7 @@ class TerminatedConnectionError extends DatabaseError {
61
65
  }
62
66
  }
63
67
  exports.CannotCommitError = CannotCommitError;
68
+ exports.CheckViolationError = CheckViolationError;
64
69
  exports.ClientError = ClientError;
65
70
  exports.DatabaseError = DatabaseError;
66
71
  exports.ForeignKeyViolationError = ForeignKeyViolationError;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","sources":["../../../../../packages/database/src/client/errors.ts"],"sourcesContent":["export class DatabaseError extends Error {\n\tpublic readonly code?: string\n\tpublic readonly originalMessage?: string\n\tpublic readonly previous: any\n\n\tconstructor(errMessage: string, previous?: Error | any) {\n\t\tsuper(errMessage)\n\t\tif (previous) {\n\t\t\tconst { message, stack, ...other } = previous\n\t\t\tconst otherDefined = Object.fromEntries(Object.entries(other).filter(it => it[1] !== undefined))\n\t\t\tthis.previous = { message, ...otherDefined }\n\t\t\tthis.code = previous.code\n\t\t\tthis.originalMessage = previous.message\n\t\t}\n\t}\n}\n\nexport type ClientErrorType =\n\t| 'recoverable connection error'\n\t| 'connection error'\n\t| 'runtime error'\n\t| 'disposal error'\n\nexport class ClientError extends DatabaseError {\n\tconstructor(previous: Error | any, public readonly type: ClientErrorType) {\n\t\tsuper(`Database client ${type}: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}`, previous)\n\t}\n}\n\nexport class QueryError extends DatabaseError {\n\tpublic readonly constraint?: string\n\tpublic readonly table?: string\n\n\tconstructor(public readonly sql: string, public readonly parameters: any, public override readonly previous: Error | any) {\n\t\tsuper(\n\t\t\t`Database query error: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}\nSQL: ${sql}\nparameters: ${parameters}`,\n\t\t\tprevious,\n\t\t)\n\t\tthis.constraint = previous.constraint\n\t\tthis.table = previous.table\n\t}\n}\n\nexport class NotNullViolationError extends QueryError {}\n\nexport class ForeignKeyViolationError extends QueryError {}\n\nexport class UniqueViolationError extends QueryError {}\n\nexport class SerializationFailureError extends QueryError {}\n\nexport class InvalidDataError extends QueryError {}\n\nexport class TransactionAbortedError extends QueryError {}\n\nexport class CannotCommitError extends DatabaseError {}\n\nexport class TerminatedConnectionError extends DatabaseError {\n\tconstructor() {\n\t\tsuper('Database connection was terminated')\n\t}\n}\n"],"names":[],"mappings":";;;;;AAAO,MAAM,sBAAsB,MAAM;AAAA,EAKxC,YAAY,YAAoB,UAAwB;AACvD,UAAM,UAAU;AALjB,kBAAA,MAAgB,MAAA;AAChB,kBAAA,MAAgB,iBAAA;AAChB,kBAAA,MAAgB,UAAA;AAIf,QAAI,UAAU;AACb,YAAM,EAAE,SAAS,OAAO,GAAG,UAAU;AACrC,YAAM,eAAe,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,OAAO,CAAA,OAAM,GAAG,CAAC,MAAM,MAAS,CAAC;AAC/F,WAAK,WAAW,EAAE,SAAS,GAAG,aAAA;AAC9B,WAAK,OAAO,SAAS;AACrB,WAAK,kBAAkB,SAAS;AAAA,IACjC;AAAA,EACD;AACD;AAQO,MAAM,oBAAoB,cAAc;AAAA,EAC9C,YAAY,UAAuC,MAAuB;AACzE,UAAM,mBAAmB,IAAI,KAAK,aAAa,YAAY,SAAS,UAAU,SAAS,UAAU,KAAK,UAAU,QAAQ,CAAC,IAAI,QAAQ;AADnF,SAAA,OAAA;AAAA,EAEnD;AACD;AAEO,MAAM,mBAAmB,cAAc;AAAA,EAI7C,YAA4B,KAA6B,YAA0C,UAAuB;AACzH;AAAA,MACC,yBAAyB,aAAa,YAAY,SAAS,UAAU,SAAS,UAAU,KAAK,UAAU,QAAQ,CAAC;AAAA,OAC5G,GAAG;AAAA,cACI,UAAU;AAAA,MACrB;AAAA,IAAA;AAL0B,SAAA,MAAA;AAA6B,SAAA,aAAA;AAA0C,SAAA,WAAA;AAHnG,kBAAA,MAAgB,YAAA;AAChB,kBAAA,MAAgB,OAAA;AASf,SAAK,aAAa,SAAS;AAC3B,SAAK,QAAQ,SAAS;AAAA,EACvB;AACD;AAEO,MAAM,8BAA8B,WAAW;AAAC;AAEhD,MAAM,iCAAiC,WAAW;AAAC;AAEnD,MAAM,6BAA6B,WAAW;AAAC;AAE/C,MAAM,kCAAkC,WAAW;AAAC;AAEpD,MAAM,yBAAyB,WAAW;AAAC;AAE3C,MAAM,gCAAgC,WAAW;AAAC;AAElD,MAAM,0BAA0B,cAAc;AAAC;AAE/C,MAAM,kCAAkC,cAAc;AAAA,EAC5D,cAAc;AACb,UAAM,oCAAoC;AAAA,EAC3C;AACD;;;;;;;;;;;;"}
1
+ {"version":3,"file":"errors.cjs","sources":["../../../../../packages/database/src/client/errors.ts"],"sourcesContent":["export class DatabaseError extends Error {\n\tpublic readonly code?: string\n\tpublic readonly originalMessage?: string\n\tpublic readonly previous: any\n\n\tconstructor(errMessage: string, previous?: Error | any) {\n\t\tsuper(errMessage)\n\t\tif (previous) {\n\t\t\tconst { message, stack, ...other } = previous\n\t\t\tconst otherDefined = Object.fromEntries(Object.entries(other).filter(it => it[1] !== undefined))\n\t\t\tthis.previous = { message, ...otherDefined }\n\t\t\tthis.code = previous.code\n\t\t\tthis.originalMessage = previous.message\n\t\t}\n\t}\n}\n\nexport type ClientErrorType =\n\t| 'recoverable connection error'\n\t| 'connection error'\n\t| 'runtime error'\n\t| 'disposal error'\n\nexport class ClientError extends DatabaseError {\n\tconstructor(previous: Error | any, public readonly type: ClientErrorType) {\n\t\tsuper(`Database client ${type}: ${'message' in previous && previous.message ? previous.message : JSON.stringify(previous)}`, previous)\n\t}\n}\n\n// PostgreSQL often puts the actionable part of an error (e.g. which objects block a DROP) into DETAIL and HINT.\nconst formatDiagnosticField = (label: string, value: unknown): string => typeof value === 'string' && value !== '' ? `\\n${label}: ${value}` : ''\n\nexport class QueryError extends DatabaseError {\n\tpublic readonly constraint?: string\n\tpublic readonly table?: string\n\n\tconstructor(public readonly sql: string, public readonly parameters: any, public override readonly previous: Error | any) {\n\t\tsuper(\n\t\t\t('message' in previous && previous.message\n\t\t\t\t? `Database query error: ${previous.message}` + formatDiagnosticField('Detail', previous.detail) + formatDiagnosticField('Hint', previous.hint)\n\t\t\t\t: `Database query error: ${JSON.stringify(previous)}`)\n\t\t\t\t+ `\\nSQL: ${sql}\\nparameters: ${parameters}`,\n\t\t\tprevious,\n\t\t)\n\t\tthis.constraint = previous.constraint\n\t\tthis.table = previous.table\n\t}\n}\n\nexport class NotNullViolationError extends QueryError {}\n\nexport class ForeignKeyViolationError extends QueryError {}\n\nexport class UniqueViolationError extends QueryError {}\n\nexport class CheckViolationError extends QueryError {}\n\nexport class SerializationFailureError extends QueryError {}\n\nexport class InvalidDataError extends QueryError {}\n\nexport class TransactionAbortedError extends QueryError {}\n\nexport class CannotCommitError extends DatabaseError {}\n\nexport class TerminatedConnectionError extends DatabaseError {\n\tconstructor() {\n\t\tsuper('Database connection was terminated')\n\t}\n}\n"],"names":[],"mappings":";;;;;AAAO,MAAM,sBAAsB,MAAM;AAAA,EAKxC,YAAY,YAAoB,UAAwB;AACvD,UAAM,UAAU;AALjB,kBAAA,MAAgB,MAAA;AAChB,kBAAA,MAAgB,iBAAA;AAChB,kBAAA,MAAgB,UAAA;AAIf,QAAI,UAAU;AACb,YAAM,EAAE,SAAS,OAAO,GAAG,UAAU;AACrC,YAAM,eAAe,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,OAAO,CAAA,OAAM,GAAG,CAAC,MAAM,MAAS,CAAC;AAC/F,WAAK,WAAW,EAAE,SAAS,GAAG,aAAA;AAC9B,WAAK,OAAO,SAAS;AACrB,WAAK,kBAAkB,SAAS;AAAA,IACjC;AAAA,EACD;AACD;AAQO,MAAM,oBAAoB,cAAc;AAAA,EAC9C,YAAY,UAAuC,MAAuB;AACzE,UAAM,mBAAmB,IAAI,KAAK,aAAa,YAAY,SAAS,UAAU,SAAS,UAAU,KAAK,UAAU,QAAQ,CAAC,IAAI,QAAQ;AADnF,SAAA,OAAA;AAAA,EAEnD;AACD;AAGA,MAAM,wBAAwB,CAAC,OAAe,UAA2B,OAAO,UAAU,YAAY,UAAU,KAAK;AAAA,EAAK,KAAK,KAAK,KAAK,KAAK;AAEvI,MAAM,mBAAmB,cAAc;AAAA,EAI7C,YAA4B,KAA6B,YAA0C,UAAuB;AACzH;AAAA,OACE,aAAa,YAAY,SAAS,UAChC,yBAAyB,SAAS,OAAO,KAAK,sBAAsB,UAAU,SAAS,MAAM,IAAI,sBAAsB,QAAQ,SAAS,IAAI,IAC5I,yBAAyB,KAAK,UAAU,QAAQ,CAAC,MACjD;AAAA,OAAU,GAAG;AAAA,cAAiB,UAAU;AAAA,MAC3C;AAAA,IAAA;AAN0B,SAAA,MAAA;AAA6B,SAAA,aAAA;AAA0C,SAAA,WAAA;AAHnG,kBAAA,MAAgB,YAAA;AAChB,kBAAA,MAAgB,OAAA;AAUf,SAAK,aAAa,SAAS;AAC3B,SAAK,QAAQ,SAAS;AAAA,EACvB;AACD;AAEO,MAAM,8BAA8B,WAAW;AAAC;AAEhD,MAAM,iCAAiC,WAAW;AAAC;AAEnD,MAAM,6BAA6B,WAAW;AAAC;AAE/C,MAAM,4BAA4B,WAAW;AAAC;AAE9C,MAAM,kCAAkC,WAAW;AAAC;AAEpD,MAAM,yBAAyB,WAAW;AAAC;AAE3C,MAAM,gCAAgC,WAAW;AAAC;AAElD,MAAM,0BAA0B,cAAc;AAAC;AAE/C,MAAM,kCAAkC,cAAc;AAAA,EAC5D,cAAc;AACb,UAAM,oCAAoC;AAAA,EAC3C;AACD;;;;;;;;;;;;;"}
@@ -22,10 +22,12 @@ class ClientError extends DatabaseError {
22
22
  this.type = type;
23
23
  }
24
24
  }
25
+ const formatDiagnosticField = (label, value) => typeof value === "string" && value !== "" ? `
26
+ ${label}: ${value}` : "";
25
27
  class QueryError extends DatabaseError {
26
28
  constructor(sql, parameters, previous) {
27
29
  super(
28
- `Database query error: ${"message" in previous && previous.message ? previous.message : JSON.stringify(previous)}
30
+ ("message" in previous && previous.message ? `Database query error: ${previous.message}` + formatDiagnosticField("Detail", previous.detail) + formatDiagnosticField("Hint", previous.hint) : `Database query error: ${JSON.stringify(previous)}`) + `
29
31
  SQL: ${sql}
30
32
  parameters: ${parameters}`,
31
33
  previous
@@ -45,6 +47,8 @@ class ForeignKeyViolationError extends QueryError {
45
47
  }
46
48
  class UniqueViolationError extends QueryError {
47
49
  }
50
+ class CheckViolationError extends QueryError {
51
+ }
48
52
  class SerializationFailureError extends QueryError {
49
53
  }
50
54
  class InvalidDataError extends QueryError {
@@ -60,6 +64,7 @@ class TerminatedConnectionError extends DatabaseError {
60
64
  }
61
65
  export {
62
66
  CannotCommitError,
67
+ CheckViolationError,
63
68
  ClientError,
64
69
  DatabaseError,
65
70
  ForeignKeyViolationError,