@contember/database 2.2.0-alpha.12 → 2.2.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +3 -0
- package/dist/development/src/client/AcquiredConnection.cjs +2 -0
- package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
- package/dist/development/src/client/AcquiredConnection.js +2 -0
- package/dist/development/src/client/AcquiredConnection.js.map +1 -1
- package/dist/development/src/client/Connection.cjs +40 -4
- package/dist/development/src/client/Connection.cjs.map +1 -1
- package/dist/development/src/client/Connection.js +40 -4
- package/dist/development/src/client/Connection.js.map +1 -1
- package/dist/production/src/client/AcquiredConnection.cjs +2 -0
- package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
- package/dist/production/src/client/AcquiredConnection.js +2 -0
- package/dist/production/src/client/AcquiredConnection.js.map +1 -1
- package/dist/production/src/client/Connection.cjs +40 -4
- package/dist/production/src/client/Connection.cjs.map +1 -1
- package/dist/production/src/client/Connection.js +40 -4
- package/dist/production/src/client/Connection.js.map +1 -1
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +6 -0
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
- package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts +2 -0
- package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
- package/dist/types/client/Connection.d.ts +11 -2
- package/dist/types/client/Connection.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/src/client/AcquiredConnection.ts +2 -0
- package/src/client/Connection.ts +57 -2
- package/tests/cases/unit/connection.test.ts +45 -1
- package/tests/cases/unit/createConnectionMockAlt.ts +19 -2
- package/tests/cases/unit/staleConnectionRetry.test.ts +86 -0
|
@@ -4,18 +4,21 @@ const EventManager = require("./EventManager.cjs");
|
|
|
4
4
|
const Client = require("./Client.cjs");
|
|
5
5
|
const Pool = require("./Pool.cjs");
|
|
6
6
|
require("../Literal.cjs");
|
|
7
|
+
const errorCodes = require("./errorCodes.cjs");
|
|
8
|
+
const errors = require("./errors.cjs");
|
|
7
9
|
const ScopeLimitedConnection = require("./ScopeLimitedConnection.cjs");
|
|
8
10
|
require("node:timers");
|
|
9
11
|
require("../utils/Mutex.cjs");
|
|
10
12
|
const pgClientFactory = require("../utils/pgClientFactory.cjs");
|
|
11
13
|
const AcquiredConnection = require("./AcquiredConnection.cjs");
|
|
12
14
|
class Connection {
|
|
13
|
-
constructor(pool, eventManager = new EventManager.EventManager(null)) {
|
|
15
|
+
constructor(pool, eventManager = new EventManager.EventManager(null), options = {}) {
|
|
14
16
|
this.pool = pool;
|
|
15
17
|
this.eventManager = eventManager;
|
|
18
|
+
this.options = options;
|
|
16
19
|
}
|
|
17
|
-
static create({ pool = {}, ...config }, logError) {
|
|
18
|
-
return new Connection(new Pool.Pool(pgClientFactory.createPgClientFactory(config), { ...pool, logError }));
|
|
20
|
+
static create({ pool = {}, ...config }, logError, options = {}) {
|
|
21
|
+
return new Connection(new Pool.Pool(pgClientFactory.createPgClientFactory(config), { ...pool, logError }), new EventManager.EventManager(null), options);
|
|
19
22
|
}
|
|
20
23
|
static createSingle(config, logError) {
|
|
21
24
|
return new Connection(new Pool.Pool(pgClientFactory.createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }));
|
|
@@ -36,6 +39,14 @@ class Connection {
|
|
|
36
39
|
async scope(callback, options = {}) {
|
|
37
40
|
const eventManager = new EventManager.EventManager(options.eventManager ?? this.eventManager);
|
|
38
41
|
eventManager.memoryBudget?.check();
|
|
42
|
+
while (true) {
|
|
43
|
+
const attempt = await this.scopeOnce(callback, eventManager);
|
|
44
|
+
if (!attempt.stale) {
|
|
45
|
+
return attempt.result;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async scopeOnce(callback, eventManager) {
|
|
39
50
|
const acquired = await this.pool.acquire();
|
|
40
51
|
try {
|
|
41
52
|
eventManager.memoryBudget?.check();
|
|
@@ -43,14 +54,31 @@ class Connection {
|
|
|
43
54
|
this.pool.release(acquired);
|
|
44
55
|
throw e;
|
|
45
56
|
}
|
|
57
|
+
const reused = acquired.uses > 1;
|
|
58
|
+
let lost = false;
|
|
59
|
+
let answered = false;
|
|
60
|
+
const onError = () => {
|
|
61
|
+
lost = true;
|
|
62
|
+
};
|
|
63
|
+
const onAnswer = () => {
|
|
64
|
+
answered = true;
|
|
65
|
+
};
|
|
66
|
+
acquired.client.on("error", onError);
|
|
67
|
+
eventManager.on(EventManager.EventManager.Event.queryEnd, onAnswer);
|
|
46
68
|
try {
|
|
47
69
|
const connection = new AcquiredConnection.AcquiredConnection(acquired.client, eventManager);
|
|
48
70
|
const result = await callback(connection);
|
|
49
71
|
this.pool.release(acquired);
|
|
50
|
-
return result;
|
|
72
|
+
return { stale: false, result };
|
|
51
73
|
} catch (e) {
|
|
52
74
|
this.pool.dispose(acquired);
|
|
75
|
+
if (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {
|
|
76
|
+
return { stale: true };
|
|
77
|
+
}
|
|
53
78
|
throw e;
|
|
79
|
+
} finally {
|
|
80
|
+
acquired.client.off("error", onError);
|
|
81
|
+
eventManager.removeListener(EventManager.EventManager.Event.queryEnd, onAnswer);
|
|
54
82
|
}
|
|
55
83
|
}
|
|
56
84
|
async transaction(callback, options = {}) {
|
|
@@ -73,6 +101,14 @@ class Connection {
|
|
|
73
101
|
return this.pool.getPoolStatus();
|
|
74
102
|
}
|
|
75
103
|
}
|
|
104
|
+
const connectionLossCodes = /* @__PURE__ */ new Set([
|
|
105
|
+
errorCodes.ClientErrorCodes.CONNECTION_EXCEPTION,
|
|
106
|
+
errorCodes.ClientErrorCodes.CONNECTION_DOES_NOT_EXIST,
|
|
107
|
+
errorCodes.ClientErrorCodes.CONNECTION_FAILURE,
|
|
108
|
+
errorCodes.ClientErrorCodes.ADMIN_SHUTDOWN,
|
|
109
|
+
errorCodes.ClientErrorCodes.CRASH_SHUTDOWN
|
|
110
|
+
]);
|
|
111
|
+
const isConnectionLoss = (error) => error instanceof errors.DatabaseError && error.code !== void 0 && connectionLossCodes.has(error.code);
|
|
76
112
|
((Connection2) => {
|
|
77
113
|
Connection2.REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ";
|
|
78
114
|
})(Connection || (Connection = {}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Connection.cjs","sources":["../../../../../packages/database/src/client/Connection.ts"],"sourcesContent":["import { EventManager } from './EventManager.js'\nimport { Client } from './Client.js'\nimport { Pool, PoolConfig, PoolStatus } from './Pool.js'\nimport { createPgClientFactory } from '../utils/index.js'\nimport { DatabaseConfig } from '../types.js'\nimport { AcquiredConnection } from './AcquiredConnection.js'\nimport { ScopeLimitedConnection } from './ScopeLimitedConnection.js'\nimport { Notification } from 'pg'\n\nclass Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\tpublic readonly eventManager: EventManager = new EventManager(null),\n\t) {\n\t}\n\n\tpublic static create(\n\t\t{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }))\n\t}\n\n\tpublic static createSingle(\n\t\tconfig: DatabaseConfig,\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }))\n\t}\n\n\tpublic createClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\t/**\n\t * Returns a view of this connection that limits how many pool connections may be\n\t * acquired concurrently through it. Intended to be created per HTTP request so that\n\t * a single request cannot starve the shared pool. The returned view shares the same\n\t * underlying pool; only top-level scopes are counted (nested scopes reuse the already\n\t * acquired connection), so the limit must be at least 1.\n\t */\n\tpublic withMaxConnections(maxConnections: number): Connection.ConnectionType {\n\t\treturn new ScopeLimitedConnection(this, maxConnections)\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\tconst eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\teventManager.memoryBudget?.check()\n\t\tconst acquired = await this.pool.acquire()\n\t\t// A budget exhausted while waiting for the pool must not cost a healthy connection.\n\t\ttry {\n\t\t\teventManager.memoryBudget?.check()\n\t\t} catch (e) {\n\t\t\tthis.pool.release(acquired)\n\t\t\tthrow e\n\t\t}\n\t\ttry {\n\t\t\tconst connection = new AcquiredConnection(acquired.client, eventManager)\n\t\t\tconst result = await callback(connection)\n\t\t\tthis.pool.release(acquired)\n\n\t\t\treturn result\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\tthrow e\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\treturn await connection.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\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tasync end(): Promise<void> {\n\t\tawait this.pool.end()\n\t}\n\n\tpublic async clearPool(): Promise<void> {\n\t\tawait this.pool.closeIdle()\n\t}\n\n\tgetPoolStatus(): PoolStatus {\n\t\treturn this.pool.getPoolStatus()\n\t}\n}\n\nnamespace Connection {\n\texport interface Queryable {\n\t\treadonly eventManager: EventManager\n\n\t\tquery<Row extends Record<string, any>>(\n\t\t\tsql: string,\n\t\t\tparameters?: readonly any[],\n\t\t\tmeta?: Record<string, any>,\n\t\t): Promise<Connection.Result<Row>>\n\t}\n\n\texport interface Transactional {\n\t\ttransaction<Result>(\n\t\t\ttrx: (connection: TransactionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport type ConnectionType =\n\t\t& Connection.ConnectionLike\n\t\t& Connection.ClientFactory\n\t\t& Connection.PoolStatusProvider\n\n\texport interface ConnectionLike<T = {}> extends Transactional, Queryable {\n\t\tscope<Result>(\n\t\t\tcallback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {\n\t\ton(event: 'notification', listener: (message: Notification) => void): () => void\n\t\ton(event: 'end', listener: () => void): () => void\n\t\ton(event: 'error', listener: (error: any) => void): () => void\n\t}\n\n\texport interface ClientFactory {\n\t\tcreateClient(schema: string, queryMeta: Record<string, any>): Client\n\t}\n\n\texport interface PoolStatusProvider {\n\t\tgetPoolStatus(): PoolStatus | undefined\n\t}\n\n\texport interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {\n\t\treadonly isClosed: boolean\n\n\t\trollback(): Promise<void>\n\n\t\tcommit(): Promise<void>\n\t}\n\n\texport interface Query {\n\t\treadonly sql: string\n\t\treadonly parameters: any[]\n\t\treadonly meta: Record<string, any>\n\t}\n\n\texport interface Result<Row extends Record<string, any> = Record<string, any>> {\n\t\treadonly command?: string\n\t\treadonly rowCount: number | null\n\t\treadonly rows: Row[]\n\t\treadonly timing?: {\n\t\t\tselfDuration: number\n\t\t\t/** @deprecated both selfDuration and totalDuration now contains same number */\n\t\t\ttotalDuration: number\n\t\t}\n\t}\n\n\texport const REPEATABLE_READ = 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'\n}\n\nexport { Connection }\n"],"names":["EventManager","Pool","createPgClientFactory","Client","ScopeLimitedConnection","AcquiredConnection","Connection"],"mappings":";;;;;;;;;;;AASA,MAAM,WAAyG;AAAA,EAC9G,YACkB,MACD,eAA6B,IAAIA,aAAAA,aAAa,IAAI,GACjE;AAFgB,SAAA,OAAA;AACD,SAAA,eAAA;AAAA,EAEjB;AAAA,EAEA,OAAc,OACb,EAAE,OAAO,CAAA,GAAI,GAAG,OAAA,GAChB,UACa;AACb,WAAO,IAAI,WAAW,IAAIC,KAAAA,KAAKC,gBAAAA,sBAAsB,MAAM,GAAG,EAAE,GAAG,MAAM,SAAA,CAAU,CAAC;AAAA,EACrF;AAAA,EAEA,OAAc,aACb,QACA,UACa;AACb,WAAO,IAAI,WAAW,IAAID,UAAKC,gBAAAA,sBAAsB,MAAM,GAAG,EAAE,gBAAgB,GAAG,SAAS,GAAG,SAAA,CAAU,CAAC;AAAA,EAC3G;AAAA,EAEO,aAAa,QAAgB,WAAwC;AAC3E,WAAO,IAAIC,OAAAA,OAAO,MAAM,QAAQ,WAAW,IAAIH,aAAAA,aAAa,KAAK,YAAY,CAAC;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,mBAAmB,gBAAmD;AAC5E,WAAO,IAAII,uBAAAA,uBAAuB,MAAM,cAAc;AAAA,EACvD;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,UAAM,eAAe,IAAIJ,aAAAA,aAAa,QAAQ,gBAAgB,KAAK,YAAY;AAC/E,iBAAa,cAAc,MAAA;AAC3B,UAAM,WAAW,MAAM,KAAK,KAAK,QAAA;AAEjC,QAAI;AACH,mBAAa,cAAc,MAAA;AAAA,IAC5B,SAAS,GAAG;AACX,WAAK,KAAK,QAAQ,QAAQ;AAC1B,YAAM;AAAA,IACP;AACA,QAAI;AACH,YAAM,aAAa,IAAIK,mBAAAA,mBAAmB,SAAS,QAAQ,YAAY;AACvE,YAAM,SAAS,MAAM,SAAS,UAAU;AACxC,WAAK,KAAK,QAAQ,QAAQ;AAE1B,aAAO;AAAA,IACR,SAAS,GAAG;AACX,WAAK,KAAK,QAAQ,QAAQ;AAC1B,YAAM;AAAA,IACP;AAAA,EACD;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,YAAY,QAAQ;AAAA,IAC7C,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAClC,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,MAAM,KAAK,YAAY,IAAI;AAAA,IACpD,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,MAAqB;AAC1B,UAAM,KAAK,KAAK,IAAA;AAAA,EACjB;AAAA,EAEA,MAAa,YAA2B;AACvC,UAAM,KAAK,KAAK,UAAA;AAAA,EACjB;AAAA,EAEA,gBAA4B;AAC3B,WAAO,KAAK,KAAK,cAAA;AAAA,EAClB;AACD;AAAA,CAEA,CAAUC,gBAAV;AAqEcA,cAAA,kBAAkB;AAAA,GArEtB,eAAA,aAAA,CAAA,EAAA;;"}
|
|
1
|
+
{"version":3,"file":"Connection.cjs","sources":["../../../../../packages/database/src/client/Connection.ts"],"sourcesContent":["import { EventManager } from './EventManager.js'\nimport { Client } from './Client.js'\nimport { Pool, PoolConfig, PoolStatus } from './Pool.js'\nimport { createPgClientFactory } from '../utils/index.js'\nimport { DatabaseConfig } from '../types.js'\nimport { AcquiredConnection } from './AcquiredConnection.js'\nimport { ScopeLimitedConnection } from './ScopeLimitedConnection.js'\nimport { Notification } from 'pg'\nimport { DatabaseError } from './errors.js'\nimport { ClientErrorCodes } from './errorCodes.js'\n\nclass Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\tpublic readonly eventManager: EventManager = new EventManager(null),\n\t\tprivate readonly options: Connection.Options = {},\n\t) {\n\t}\n\n\tpublic static create(\n\t\t{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },\n\t\tlogError: (error: Error) => void,\n\t\toptions: Connection.Options = {},\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }), new EventManager(null), options)\n\t}\n\n\tpublic static createSingle(\n\t\tconfig: DatabaseConfig,\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }))\n\t}\n\n\tpublic createClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\t/**\n\t * Returns a view of this connection that limits how many pool connections may be\n\t * acquired concurrently through it. Intended to be created per HTTP request so that\n\t * a single request cannot starve the shared pool. The returned view shares the same\n\t * underlying pool; only top-level scopes are counted (nested scopes reuse the already\n\t * acquired connection), so the limit must be at least 1.\n\t */\n\tpublic withMaxConnections(maxConnections: number): Connection.ConnectionType {\n\t\treturn new ScopeLimitedConnection(this, maxConnections)\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\tconst eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\teventManager.memoryBudget?.check()\n\t\t// Each retry disposes the stale connection it got, so the loop ends once the idle connections are used up.\n\t\twhile (true) {\n\t\t\tconst attempt = await this.scopeOnce(callback, eventManager)\n\t\t\tif (!attempt.stale) {\n\t\t\t\treturn attempt.result\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async scopeOnce<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\teventManager: EventManager,\n\t): Promise<{ stale: false; result: Result } | { stale: true }> {\n\t\tconst acquired = await this.pool.acquire()\n\t\t// A budget exhausted while waiting for the pool must not cost a healthy connection.\n\t\ttry {\n\t\t\teventManager.memoryBudget?.check()\n\t\t} catch (e) {\n\t\t\tthis.pool.release(acquired)\n\t\t\tthrow e\n\t\t}\n\t\tconst reused = acquired.uses > 1\n\t\t// pg emits `error` only for a connection lost unexpectedly, not for its own end(), e.g. after an exhausted budget.\n\t\tlet lost = false\n\t\tlet answered = false\n\t\tconst onError = () => {\n\t\t\tlost = true\n\t\t}\n\t\tconst onAnswer = () => {\n\t\t\tanswered = true\n\t\t}\n\t\tacquired.client.on('error', onError)\n\t\teventManager.on(EventManager.Event.queryEnd, onAnswer)\n\t\ttry {\n\t\t\tconst connection = new AcquiredConnection(acquired.client, eventManager)\n\t\t\tconst result = await callback(connection)\n\t\t\tthis.pool.release(acquired)\n\n\t\t\treturn { stale: false, result }\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\t// The server closed a pooled connection before answering anything, e.g. a pooler or replica restart.\n\t\t\tif (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {\n\t\t\t\treturn { stale: true }\n\t\t\t}\n\t\t\tthrow e\n\t\t} finally {\n\t\t\tacquired.client.off('error', onError)\n\t\t\teventManager.removeListener(EventManager.Event.queryEnd, onAnswer)\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\treturn await connection.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\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tasync end(): Promise<void> {\n\t\tawait this.pool.end()\n\t}\n\n\tpublic async clearPool(): Promise<void> {\n\t\tawait this.pool.closeIdle()\n\t}\n\n\tgetPoolStatus(): PoolStatus {\n\t\treturn this.pool.getPoolStatus()\n\t}\n}\n\nconst connectionLossCodes = new Set<string>([\n\tClientErrorCodes.CONNECTION_EXCEPTION,\n\tClientErrorCodes.CONNECTION_DOES_NOT_EXIST,\n\tClientErrorCodes.CONNECTION_FAILURE,\n\tClientErrorCodes.ADMIN_SHUTDOWN,\n\tClientErrorCodes.CRASH_SHUTDOWN,\n])\n\nconst isConnectionLoss = (error: unknown): boolean =>\n\terror instanceof DatabaseError && error.code !== undefined && connectionLossCodes.has(error.code)\n\nnamespace Connection {\n\texport interface Options {\n\t\t/**\n\t\t * Runs a scope again on another connection when a connection taken from the pool turns out to be closed by\n\t\t * the server before it answered anything. Only for connections whose scopes may run twice, such as a read replica.\n\t\t */\n\t\tretryStaleConnection?: boolean\n\t}\n\n\texport interface Queryable {\n\t\treadonly eventManager: EventManager\n\n\t\tquery<Row extends Record<string, any>>(\n\t\t\tsql: string,\n\t\t\tparameters?: readonly any[],\n\t\t\tmeta?: Record<string, any>,\n\t\t): Promise<Connection.Result<Row>>\n\t}\n\n\texport interface Transactional {\n\t\ttransaction<Result>(\n\t\t\ttrx: (connection: TransactionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport type ConnectionType =\n\t\t& Connection.ConnectionLike\n\t\t& Connection.ClientFactory\n\t\t& Connection.PoolStatusProvider\n\n\texport interface ConnectionLike<T = {}> extends Transactional, Queryable {\n\t\tscope<Result>(\n\t\t\tcallback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {\n\t\ton(event: 'notification', listener: (message: Notification) => void): () => void\n\t\ton(event: 'end', listener: () => void): () => void\n\t\ton(event: 'error', listener: (error: any) => void): () => void\n\t}\n\n\texport interface ClientFactory {\n\t\tcreateClient(schema: string, queryMeta: Record<string, any>): Client\n\t}\n\n\texport interface PoolStatusProvider {\n\t\tgetPoolStatus(): PoolStatus | undefined\n\t}\n\n\texport interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {\n\t\treadonly isClosed: boolean\n\n\t\trollback(): Promise<void>\n\n\t\tcommit(): Promise<void>\n\t}\n\n\texport interface Query {\n\t\treadonly sql: string\n\t\treadonly parameters: any[]\n\t\treadonly meta: Record<string, any>\n\t}\n\n\texport interface Result<Row extends Record<string, any> = Record<string, any>> {\n\t\treadonly command?: string\n\t\treadonly rowCount: number | null\n\t\treadonly rows: Row[]\n\t\treadonly timing?: {\n\t\t\tselfDuration: number\n\t\t\t/** @deprecated both selfDuration and totalDuration now contains same number */\n\t\t\ttotalDuration: number\n\t\t}\n\t}\n\n\texport const REPEATABLE_READ = 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'\n}\n\nexport { Connection }\n"],"names":["EventManager","Pool","createPgClientFactory","Client","ScopeLimitedConnection","AcquiredConnection","ClientErrorCodes","DatabaseError","Connection"],"mappings":";;;;;;;;;;;;;AAWA,MAAM,WAAyG;AAAA,EAC9G,YACkB,MACD,eAA6B,IAAIA,aAAAA,aAAa,IAAI,GACjD,UAA8B,IAC9C;AAHgB,SAAA,OAAA;AACD,SAAA,eAAA;AACC,SAAA,UAAA;AAAA,EAElB;AAAA,EAEA,OAAc,OACb,EAAE,OAAO,CAAA,GAAI,GAAG,UAChB,UACA,UAA8B,IACjB;AACb,WAAO,IAAI,WAAW,IAAIC,KAAAA,KAAKC,gBAAAA,sBAAsB,MAAM,GAAG,EAAE,GAAG,MAAM,UAAU,GAAG,IAAIF,aAAAA,aAAa,IAAI,GAAG,OAAO;AAAA,EACtH;AAAA,EAEA,OAAc,aACb,QACA,UACa;AAC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C,gBAAV;AA6EcA,cAAA,kBAAkB;AAAA,GA7EtB,eAAA,aAAA,CAAA,EAAA;;"}
|
|
@@ -2,18 +2,21 @@ import { EventManager } from "./EventManager.js";
|
|
|
2
2
|
import { Client } from "./Client.js";
|
|
3
3
|
import { Pool } from "./Pool.js";
|
|
4
4
|
import "../Literal.js";
|
|
5
|
+
import { ClientErrorCodes } from "./errorCodes.js";
|
|
6
|
+
import { DatabaseError } from "./errors.js";
|
|
5
7
|
import { ScopeLimitedConnection } from "./ScopeLimitedConnection.js";
|
|
6
8
|
import "node:timers";
|
|
7
9
|
import "../utils/Mutex.js";
|
|
8
10
|
import { createPgClientFactory } from "../utils/pgClientFactory.js";
|
|
9
11
|
import { AcquiredConnection } from "./AcquiredConnection.js";
|
|
10
12
|
class Connection {
|
|
11
|
-
constructor(pool, eventManager = new EventManager(null)) {
|
|
13
|
+
constructor(pool, eventManager = new EventManager(null), options = {}) {
|
|
12
14
|
this.pool = pool;
|
|
13
15
|
this.eventManager = eventManager;
|
|
16
|
+
this.options = options;
|
|
14
17
|
}
|
|
15
|
-
static create({ pool = {}, ...config }, logError) {
|
|
16
|
-
return new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }));
|
|
18
|
+
static create({ pool = {}, ...config }, logError, options = {}) {
|
|
19
|
+
return new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }), new EventManager(null), options);
|
|
17
20
|
}
|
|
18
21
|
static createSingle(config, logError) {
|
|
19
22
|
return new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }));
|
|
@@ -34,6 +37,14 @@ class Connection {
|
|
|
34
37
|
async scope(callback, options = {}) {
|
|
35
38
|
const eventManager = new EventManager(options.eventManager ?? this.eventManager);
|
|
36
39
|
eventManager.memoryBudget?.check();
|
|
40
|
+
while (true) {
|
|
41
|
+
const attempt = await this.scopeOnce(callback, eventManager);
|
|
42
|
+
if (!attempt.stale) {
|
|
43
|
+
return attempt.result;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async scopeOnce(callback, eventManager) {
|
|
37
48
|
const acquired = await this.pool.acquire();
|
|
38
49
|
try {
|
|
39
50
|
eventManager.memoryBudget?.check();
|
|
@@ -41,14 +52,31 @@ class Connection {
|
|
|
41
52
|
this.pool.release(acquired);
|
|
42
53
|
throw e;
|
|
43
54
|
}
|
|
55
|
+
const reused = acquired.uses > 1;
|
|
56
|
+
let lost = false;
|
|
57
|
+
let answered = false;
|
|
58
|
+
const onError = () => {
|
|
59
|
+
lost = true;
|
|
60
|
+
};
|
|
61
|
+
const onAnswer = () => {
|
|
62
|
+
answered = true;
|
|
63
|
+
};
|
|
64
|
+
acquired.client.on("error", onError);
|
|
65
|
+
eventManager.on(EventManager.Event.queryEnd, onAnswer);
|
|
44
66
|
try {
|
|
45
67
|
const connection = new AcquiredConnection(acquired.client, eventManager);
|
|
46
68
|
const result = await callback(connection);
|
|
47
69
|
this.pool.release(acquired);
|
|
48
|
-
return result;
|
|
70
|
+
return { stale: false, result };
|
|
49
71
|
} catch (e) {
|
|
50
72
|
this.pool.dispose(acquired);
|
|
73
|
+
if (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {
|
|
74
|
+
return { stale: true };
|
|
75
|
+
}
|
|
51
76
|
throw e;
|
|
77
|
+
} finally {
|
|
78
|
+
acquired.client.off("error", onError);
|
|
79
|
+
eventManager.removeListener(EventManager.Event.queryEnd, onAnswer);
|
|
52
80
|
}
|
|
53
81
|
}
|
|
54
82
|
async transaction(callback, options = {}) {
|
|
@@ -71,6 +99,14 @@ class Connection {
|
|
|
71
99
|
return this.pool.getPoolStatus();
|
|
72
100
|
}
|
|
73
101
|
}
|
|
102
|
+
const connectionLossCodes = /* @__PURE__ */ new Set([
|
|
103
|
+
ClientErrorCodes.CONNECTION_EXCEPTION,
|
|
104
|
+
ClientErrorCodes.CONNECTION_DOES_NOT_EXIST,
|
|
105
|
+
ClientErrorCodes.CONNECTION_FAILURE,
|
|
106
|
+
ClientErrorCodes.ADMIN_SHUTDOWN,
|
|
107
|
+
ClientErrorCodes.CRASH_SHUTDOWN
|
|
108
|
+
]);
|
|
109
|
+
const isConnectionLoss = (error) => error instanceof DatabaseError && error.code !== void 0 && connectionLossCodes.has(error.code);
|
|
74
110
|
((Connection2) => {
|
|
75
111
|
Connection2.REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ";
|
|
76
112
|
})(Connection || (Connection = {}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Connection.js","sources":["../../../../../packages/database/src/client/Connection.ts"],"sourcesContent":["import { EventManager } from './EventManager.js'\nimport { Client } from './Client.js'\nimport { Pool, PoolConfig, PoolStatus } from './Pool.js'\nimport { createPgClientFactory } from '../utils/index.js'\nimport { DatabaseConfig } from '../types.js'\nimport { AcquiredConnection } from './AcquiredConnection.js'\nimport { ScopeLimitedConnection } from './ScopeLimitedConnection.js'\nimport { Notification } from 'pg'\n\nclass Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\tpublic readonly eventManager: EventManager = new EventManager(null),\n\t) {\n\t}\n\n\tpublic static create(\n\t\t{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }))\n\t}\n\n\tpublic static createSingle(\n\t\tconfig: DatabaseConfig,\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }))\n\t}\n\n\tpublic createClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\t/**\n\t * Returns a view of this connection that limits how many pool connections may be\n\t * acquired concurrently through it. Intended to be created per HTTP request so that\n\t * a single request cannot starve the shared pool. The returned view shares the same\n\t * underlying pool; only top-level scopes are counted (nested scopes reuse the already\n\t * acquired connection), so the limit must be at least 1.\n\t */\n\tpublic withMaxConnections(maxConnections: number): Connection.ConnectionType {\n\t\treturn new ScopeLimitedConnection(this, maxConnections)\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\tconst eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\teventManager.memoryBudget?.check()\n\t\tconst acquired = await this.pool.acquire()\n\t\t// A budget exhausted while waiting for the pool must not cost a healthy connection.\n\t\ttry {\n\t\t\teventManager.memoryBudget?.check()\n\t\t} catch (e) {\n\t\t\tthis.pool.release(acquired)\n\t\t\tthrow e\n\t\t}\n\t\ttry {\n\t\t\tconst connection = new AcquiredConnection(acquired.client, eventManager)\n\t\t\tconst result = await callback(connection)\n\t\t\tthis.pool.release(acquired)\n\n\t\t\treturn result\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\tthrow e\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\treturn await connection.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\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tasync end(): Promise<void> {\n\t\tawait this.pool.end()\n\t}\n\n\tpublic async clearPool(): Promise<void> {\n\t\tawait this.pool.closeIdle()\n\t}\n\n\tgetPoolStatus(): PoolStatus {\n\t\treturn this.pool.getPoolStatus()\n\t}\n}\n\nnamespace Connection {\n\texport interface Queryable {\n\t\treadonly eventManager: EventManager\n\n\t\tquery<Row extends Record<string, any>>(\n\t\t\tsql: string,\n\t\t\tparameters?: readonly any[],\n\t\t\tmeta?: Record<string, any>,\n\t\t): Promise<Connection.Result<Row>>\n\t}\n\n\texport interface Transactional {\n\t\ttransaction<Result>(\n\t\t\ttrx: (connection: TransactionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport type ConnectionType =\n\t\t& Connection.ConnectionLike\n\t\t& Connection.ClientFactory\n\t\t& Connection.PoolStatusProvider\n\n\texport interface ConnectionLike<T = {}> extends Transactional, Queryable {\n\t\tscope<Result>(\n\t\t\tcallback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {\n\t\ton(event: 'notification', listener: (message: Notification) => void): () => void\n\t\ton(event: 'end', listener: () => void): () => void\n\t\ton(event: 'error', listener: (error: any) => void): () => void\n\t}\n\n\texport interface ClientFactory {\n\t\tcreateClient(schema: string, queryMeta: Record<string, any>): Client\n\t}\n\n\texport interface PoolStatusProvider {\n\t\tgetPoolStatus(): PoolStatus | undefined\n\t}\n\n\texport interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {\n\t\treadonly isClosed: boolean\n\n\t\trollback(): Promise<void>\n\n\t\tcommit(): Promise<void>\n\t}\n\n\texport interface Query {\n\t\treadonly sql: string\n\t\treadonly parameters: any[]\n\t\treadonly meta: Record<string, any>\n\t}\n\n\texport interface Result<Row extends Record<string, any> = Record<string, any>> {\n\t\treadonly command?: string\n\t\treadonly rowCount: number | null\n\t\treadonly rows: Row[]\n\t\treadonly timing?: {\n\t\t\tselfDuration: number\n\t\t\t/** @deprecated both selfDuration and totalDuration now contains same number */\n\t\t\ttotalDuration: number\n\t\t}\n\t}\n\n\texport const REPEATABLE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G;AACX,WAAK,KAAK,QAAQ,QAAQ;AAC1B,YAAM;AAAA,IACP;AAAA,EACD;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,YAAY,QAAQ;AAAA,IAC7C,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAClC,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,MAAM,KAAK,YAAY,IAAI;AAAA,IACpD,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,MAAqB;AAC1B,UAAM,KAAK,KAAK,IAAA;AAAA,EACjB;AAAA,EAEA,MAAa,YAA2B;AACvC,UAAM,KAAK,KAAK,UAAA;AAAA,EACjB;AAAA,EAEA,gBAA4B;AAC3B,WAAO,KAAK,KAAK,cAAA;AAAA,EAClB;AACD;AAAA,CAEA,CAAUA,gBAAV;AAqEcA,cAAA,kBAAkB;AAAA,GArEtB,eAAA,aAAA,CAAA,EAAA;"}
|
|
1
|
+
{"version":3,"file":"Connection.js","sources":["../../../../../packages/database/src/client/Connection.ts"],"sourcesContent":["import { EventManager } from './EventManager.js'\nimport { Client } from './Client.js'\nimport { Pool, PoolConfig, PoolStatus } from './Pool.js'\nimport { createPgClientFactory } from '../utils/index.js'\nimport { DatabaseConfig } from '../types.js'\nimport { AcquiredConnection } from './AcquiredConnection.js'\nimport { ScopeLimitedConnection } from './ScopeLimitedConnection.js'\nimport { Notification } from 'pg'\nimport { DatabaseError } from './errors.js'\nimport { ClientErrorCodes } from './errorCodes.js'\n\nclass Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\tpublic readonly eventManager: EventManager = new EventManager(null),\n\t\tprivate readonly options: Connection.Options = {},\n\t) {\n\t}\n\n\tpublic static create(\n\t\t{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },\n\t\tlogError: (error: Error) => void,\n\t\toptions: Connection.Options = {},\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }), new EventManager(null), options)\n\t}\n\n\tpublic static createSingle(\n\t\tconfig: DatabaseConfig,\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }))\n\t}\n\n\tpublic createClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\t/**\n\t * Returns a view of this connection that limits how many pool connections may be\n\t * acquired concurrently through it. Intended to be created per HTTP request so that\n\t * a single request cannot starve the shared pool. The returned view shares the same\n\t * underlying pool; only top-level scopes are counted (nested scopes reuse the already\n\t * acquired connection), so the limit must be at least 1.\n\t */\n\tpublic withMaxConnections(maxConnections: number): Connection.ConnectionType {\n\t\treturn new ScopeLimitedConnection(this, maxConnections)\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\tconst eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\teventManager.memoryBudget?.check()\n\t\t// Each retry disposes the stale connection it got, so the loop ends once the idle connections are used up.\n\t\twhile (true) {\n\t\t\tconst attempt = await this.scopeOnce(callback, eventManager)\n\t\t\tif (!attempt.stale) {\n\t\t\t\treturn attempt.result\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async scopeOnce<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\teventManager: EventManager,\n\t): Promise<{ stale: false; result: Result } | { stale: true }> {\n\t\tconst acquired = await this.pool.acquire()\n\t\t// A budget exhausted while waiting for the pool must not cost a healthy connection.\n\t\ttry {\n\t\t\teventManager.memoryBudget?.check()\n\t\t} catch (e) {\n\t\t\tthis.pool.release(acquired)\n\t\t\tthrow e\n\t\t}\n\t\tconst reused = acquired.uses > 1\n\t\t// pg emits `error` only for a connection lost unexpectedly, not for its own end(), e.g. after an exhausted budget.\n\t\tlet lost = false\n\t\tlet answered = false\n\t\tconst onError = () => {\n\t\t\tlost = true\n\t\t}\n\t\tconst onAnswer = () => {\n\t\t\tanswered = true\n\t\t}\n\t\tacquired.client.on('error', onError)\n\t\teventManager.on(EventManager.Event.queryEnd, onAnswer)\n\t\ttry {\n\t\t\tconst connection = new AcquiredConnection(acquired.client, eventManager)\n\t\t\tconst result = await callback(connection)\n\t\t\tthis.pool.release(acquired)\n\n\t\t\treturn { stale: false, result }\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\t// The server closed a pooled connection before answering anything, e.g. a pooler or replica restart.\n\t\t\tif (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {\n\t\t\t\treturn { stale: true }\n\t\t\t}\n\t\t\tthrow e\n\t\t} finally {\n\t\t\tacquired.client.off('error', onError)\n\t\t\teventManager.removeListener(EventManager.Event.queryEnd, onAnswer)\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\treturn await connection.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\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tasync end(): Promise<void> {\n\t\tawait this.pool.end()\n\t}\n\n\tpublic async clearPool(): Promise<void> {\n\t\tawait this.pool.closeIdle()\n\t}\n\n\tgetPoolStatus(): PoolStatus {\n\t\treturn this.pool.getPoolStatus()\n\t}\n}\n\nconst connectionLossCodes = new Set<string>([\n\tClientErrorCodes.CONNECTION_EXCEPTION,\n\tClientErrorCodes.CONNECTION_DOES_NOT_EXIST,\n\tClientErrorCodes.CONNECTION_FAILURE,\n\tClientErrorCodes.ADMIN_SHUTDOWN,\n\tClientErrorCodes.CRASH_SHUTDOWN,\n])\n\nconst isConnectionLoss = (error: unknown): boolean =>\n\terror instanceof DatabaseError && error.code !== undefined && connectionLossCodes.has(error.code)\n\nnamespace Connection {\n\texport interface Options {\n\t\t/**\n\t\t * Runs a scope again on another connection when a connection taken from the pool turns out to be closed by\n\t\t * the server before it answered anything. Only for connections whose scopes may run twice, such as a read replica.\n\t\t */\n\t\tretryStaleConnection?: boolean\n\t}\n\n\texport interface Queryable {\n\t\treadonly eventManager: EventManager\n\n\t\tquery<Row extends Record<string, any>>(\n\t\t\tsql: string,\n\t\t\tparameters?: readonly any[],\n\t\t\tmeta?: Record<string, any>,\n\t\t): Promise<Connection.Result<Row>>\n\t}\n\n\texport interface Transactional {\n\t\ttransaction<Result>(\n\t\t\ttrx: (connection: TransactionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport type ConnectionType =\n\t\t& Connection.ConnectionLike\n\t\t& Connection.ClientFactory\n\t\t& Connection.PoolStatusProvider\n\n\texport interface ConnectionLike<T = {}> extends Transactional, Queryable {\n\t\tscope<Result>(\n\t\t\tcallback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {\n\t\ton(event: 'notification', listener: (message: Notification) => void): () => void\n\t\ton(event: 'end', listener: () => void): () => void\n\t\ton(event: 'error', listener: (error: any) => void): () => void\n\t}\n\n\texport interface ClientFactory {\n\t\tcreateClient(schema: string, queryMeta: Record<string, any>): Client\n\t}\n\n\texport interface PoolStatusProvider {\n\t\tgetPoolStatus(): PoolStatus | undefined\n\t}\n\n\texport interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {\n\t\treadonly isClosed: boolean\n\n\t\trollback(): Promise<void>\n\n\t\tcommit(): Promise<void>\n\t}\n\n\texport interface Query {\n\t\treadonly sql: string\n\t\treadonly parameters: any[]\n\t\treadonly meta: Record<string, any>\n\t}\n\n\texport interface Result<Row extends Record<string, any> = Record<string, any>> {\n\t\treadonly command?: string\n\t\treadonly rowCount: number | null\n\t\treadonly rows: Row[]\n\t\treadonly timing?: {\n\t\t\tselfDuration: number\n\t\t\t/** @deprecated both selfDuration and totalDuration now contains same number */\n\t\t\ttotalDuration: number\n\t\t}\n\t}\n\n\texport const REPEATABLE_READ = 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'\n}\n\nexport { Connection }\n"],"names":["Connection"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAyG;AAAA,EAC9G,YACkB,MACD,eAA6B,IAAI,aAAa,IAAI,GACjD,UAA8B,IAC9C;AAHgB,SAAA,OAAA;AACD,SAAA,eAAA;AACC,SAAA,UAAA;AAAA,EAElB;AAAA,EAEA,OAAc,OACb,EAAE,OAAO,CAAA,GAAI,GAAG,UAChB,UACA,UAA8B,IACjB;AACb,WAAO,IAAI,WAAW,IAAI,KAAK,sBAAsB,MAAM,GAAG,EAAE,GAAG,MAAM,UAAU,GAAG,IAAI,aAAa,IAAI,GAAG,OAAO;AAAA,EACtH;AAAA,EAEA,OAAc,aACb,QACA,UACa;AACb,WAAO,IAAI,WAAW,IAAI,KAAK,sBAAsB,MAAM,GAAG,EAAE,gBAAgB,GAAG,SAAS,GAAG,SAAA,CAAU,CAAC;AAAA,EAC3G;AAAA,EAEO,aAAa,QAAgB,WAAwC;AAC3E,WAAO,IAAI,OAAO,MAAM,QAAQ,WAAW,IAAI,aAAa,KAAK,YAAY,CAAC;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;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,eAAe,aAAa,MAAM,UAAU,QAAQ;AAAA,IAClE;AAAA,EACD;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,YAAY,QAAQ;AAAA,IAC7C,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAClC,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,MAAM,KAAK,YAAY,IAAI;AAAA,IACpD,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,MAAqB;AAC1B,UAAM,KAAK,KAAK,IAAA;AAAA,EACjB;AAAA,EAEA,MAAa,YAA2B;AACvC,UAAM,KAAK,KAAK,UAAA;AAAA,EACjB;AAAA,EAEA,gBAA4B;AAC3B,WAAO,KAAK,KAAK,cAAA;AAAA,EAClB;AACD;AAEA,MAAM,0CAA0B,IAAY;AAAA,EAC3C,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,iBAAiB;AAClB,CAAC;AAED,MAAM,mBAAmB,CAAC,UACzB,iBAAiB,iBAAiB,MAAM,SAAS,UAAa,oBAAoB,IAAI,MAAM,IAAI;AAAA,CAEjG,CAAUA,gBAAV;AA6EcA,cAAA,kBAAkB;AAAA,GA7EtB,eAAA,aAAA,CAAA,EAAA;"}
|
|
@@ -3,8 +3,14 @@ type MockQuery = {
|
|
|
3
3
|
sql: string;
|
|
4
4
|
timeout?: number;
|
|
5
5
|
result?: any;
|
|
6
|
+
error?: Error;
|
|
7
|
+
lost?: boolean;
|
|
6
8
|
};
|
|
7
9
|
export declare const createConnectionMockAlt: (...queries: MockQuery[][]) => [Connection, () => void];
|
|
8
10
|
export declare const createConnectionMockAltWithPool: (poolConfig: Partial<Omit<PoolConfig, 'logError'>>, ...queries: MockQuery[][]) => [Connection, () => void];
|
|
11
|
+
export declare const createConnectionMockAltWithOptions: ({ pool: poolConfig, connection: connectionOptions }: {
|
|
12
|
+
pool?: Partial<Omit<PoolConfig, 'logError'>>;
|
|
13
|
+
connection?: Connection.Options;
|
|
14
|
+
}, ...queries: MockQuery[][]) => [Connection, () => void];
|
|
9
15
|
export {};
|
|
10
16
|
//# sourceMappingURL=createConnectionMockAlt.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createConnectionMockAlt.d.ts","sourceRoot":"","sources":["../../../../tests/cases/unit/createConnectionMockAlt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAQ,UAAU,EAAE,MAAM,uBAAuB,CAAA;
|
|
1
|
+
{"version":3,"file":"createConnectionMockAlt.d.ts","sourceRoot":"","sources":["../../../../tests/cases/unit/createConnectionMockAlt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAQ,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAMpE,KAAK,SAAS,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,GAAG,CAAC;IAAC,KAAK,CAAC,EAAE,KAAK,CAAC;IAAC,IAAI,CAAC,EAAE,OAAO,CAAA;CAAE,CAAA;AAE/F,eAAO,MAAM,uBAAuB,eAAgB,SAAS,EAAE,EAAE,KAAG,CAAC,UAAU,EAAE,MAAM,IAAI,CAE1F,CAAA;AAED,eAAO,MAAM,+BAA+B,eAC/B,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,cACrC,SAAS,EAAE,EAAE,KACvB,CAAC,UAAU,EAAE,MAAM,IAAI,CAEzB,CAAA;AAED,eAAO,MAAM,kCAAkC,wDACiB;IAC9D,IAAI,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAAA;IAC5C,UAAU,CAAC,EAAE,UAAU,CAAC,OAAO,CAAA;CAC/B,cACW,SAAS,EAAE,EAAE,KACvB,CAAC,UAAU,EAAE,MAAM,IAAI,CAmDzB,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"staleConnectionRetry.test.d.ts","sourceRoot":"","sources":["../../../../tests/cases/unit/staleConnectionRetry.test.ts"],"names":[],"mappings":""}
|