@prairielearn/postgres 4.5.1 → 4.5.2
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/CHANGELOG.md +6 -0
- package/dist/default-pool.d.ts +18 -18
- package/dist/default-pool.d.ts.map +1 -1
- package/dist/default-pool.test.d.ts.map +1 -1
- package/dist/default-pool.test.js.map +1 -1
- package/dist/error.d.ts.map +1 -1
- package/dist/error.js.map +1 -1
- package/dist/error.test.d.ts.map +1 -1
- package/dist/error.test.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/loader.d.ts.map +1 -1
- package/dist/loader.js.map +1 -1
- package/dist/pool.d.ts +0 -4
- package/dist/pool.d.ts.map +1 -1
- package/dist/pool.js.map +1 -1
- package/dist/pool.test.d.ts.map +1 -1
- package/dist/pool.test.js.map +1 -1
- package/dist/test-utils.d.ts.map +1 -1
- package/dist/test-utils.js.map +1 -1
- package/package.json +8 -7
package/CHANGELOG.md
CHANGED
package/dist/default-pool.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { defaultPool, type CursorIterator, type QueryParams };
|
|
|
4
4
|
/**
|
|
5
5
|
* Creates a new connection pool and attempts to connect to the database.
|
|
6
6
|
*/
|
|
7
|
-
export declare const initAsync: (pgConfig: import("./pool.js").PostgresPoolConfig, idleErrorHandler: (error: Error, client: import("pg").
|
|
7
|
+
export declare const initAsync: (pgConfig: import("./pool.js").PostgresPoolConfig, idleErrorHandler: (error: Error, client: import("pg").PoolClient) => void) => Promise<void>;
|
|
8
8
|
/**
|
|
9
9
|
* Closes the connection pool.
|
|
10
10
|
*/
|
|
@@ -16,31 +16,31 @@ export declare const closeAsync: () => Promise<void>;
|
|
|
16
16
|
* destruction of the client, but this should not be used except in
|
|
17
17
|
* unusual circumstances.
|
|
18
18
|
*/
|
|
19
|
-
export declare const getClientAsync: () => Promise<import("pg").
|
|
19
|
+
export declare const getClientAsync: () => Promise<import("pg").PoolClient>;
|
|
20
20
|
/**
|
|
21
21
|
* Performs a query with the given client.
|
|
22
22
|
*/
|
|
23
|
-
export declare const queryWithClientAsync: (client: import("pg").
|
|
23
|
+
export declare const queryWithClientAsync: (client: import("pg").PoolClient, sql: string, params: QueryParams) => Promise<import("pg").default.QueryResult<any>>;
|
|
24
24
|
/**
|
|
25
25
|
* Performs a query with the given client. Errors if the query returns more
|
|
26
26
|
* than one row.
|
|
27
27
|
*/
|
|
28
|
-
export declare const queryWithClientOneRowAsync: (client: import("pg").
|
|
28
|
+
export declare const queryWithClientOneRowAsync: (client: import("pg").PoolClient, sql: string, params: QueryParams) => Promise<import("pg").default.QueryResult<any>>;
|
|
29
29
|
/**
|
|
30
30
|
* Performs a query with the given client. Errors if the query returns more
|
|
31
31
|
* than one row.
|
|
32
32
|
*/
|
|
33
|
-
export declare const queryWithClientZeroOrOneRowAsync: (client: import("pg").
|
|
33
|
+
export declare const queryWithClientZeroOrOneRowAsync: (client: import("pg").PoolClient, sql: string, params: QueryParams) => Promise<import("pg").QueryResult<any>>;
|
|
34
34
|
/**
|
|
35
35
|
* Rolls back the current transaction for the given client.
|
|
36
36
|
*/
|
|
37
|
-
export declare const rollbackWithClientAsync: (client: import("pg").
|
|
38
|
-
export declare const beginTransactionAsync: () => Promise<import("pg").
|
|
37
|
+
export declare const rollbackWithClientAsync: (client: import("pg").PoolClient) => Promise<void>;
|
|
38
|
+
export declare const beginTransactionAsync: () => Promise<import("pg").PoolClient>;
|
|
39
39
|
/**
|
|
40
40
|
* Commits the transaction if err is null, otherwise rollbacks the transaction.
|
|
41
41
|
* Also releases the client.
|
|
42
42
|
*/
|
|
43
|
-
export declare const endTransactionAsync: (client: import("pg").
|
|
43
|
+
export declare const endTransactionAsync: (client: import("pg").PoolClient, err: Error | null | undefined) => Promise<void>;
|
|
44
44
|
/**
|
|
45
45
|
* Runs the specified function inside of a transaction. The function will
|
|
46
46
|
* receive a database client as an argument, but it can also make queries
|
|
@@ -49,7 +49,7 @@ export declare const endTransactionAsync: (client: import("pg").default.PoolClie
|
|
|
49
49
|
* The transaction will be rolled back if the function throws an error, and
|
|
50
50
|
* will be committed otherwise.
|
|
51
51
|
*/
|
|
52
|
-
export declare const runInTransactionAsync: <T>(fn: (client: import("pg").
|
|
52
|
+
export declare const runInTransactionAsync: <T>(fn: (client: import("pg").PoolClient) => Promise<T>) => Promise<T>;
|
|
53
53
|
/**
|
|
54
54
|
* Executes a query with the specified parameters.
|
|
55
55
|
*
|
|
@@ -58,55 +58,55 @@ export declare const runInTransactionAsync: <T>(fn: (client: import("pg").defaul
|
|
|
58
58
|
* Using the return value of this function directly is not recommended. Instead, use
|
|
59
59
|
* {@link queryRows}, {@link queryRow}, or {@link queryOptionalRow}.
|
|
60
60
|
*/
|
|
61
|
-
export declare const queryAsync: (sql: string, params: QueryParams) => Promise<import("pg").QueryResult
|
|
61
|
+
export declare const queryAsync: (sql: string, params: QueryParams) => Promise<import("pg").QueryResult<any>>;
|
|
62
62
|
/**
|
|
63
63
|
* Executes a query with the specified parameters. Errors if the query does
|
|
64
64
|
* not return exactly one row.
|
|
65
65
|
*
|
|
66
66
|
* @deprecated Use {@link executeRow} or {@link queryRow} instead.
|
|
67
67
|
*/
|
|
68
|
-
export declare const queryOneRowAsync: (sql: string, params: QueryParams) => Promise<import("pg").default.QueryResult
|
|
68
|
+
export declare const queryOneRowAsync: (sql: string, params: QueryParams) => Promise<import("pg").default.QueryResult<any>>;
|
|
69
69
|
/**
|
|
70
70
|
* Executes a query with the specified parameters. Errors if the query
|
|
71
71
|
* returns more than one row.
|
|
72
72
|
*
|
|
73
73
|
* @deprecated Use {@link queryOptionalRow} instead.
|
|
74
74
|
*/
|
|
75
|
-
export declare const queryZeroOrOneRowAsync: (sql: string, params: QueryParams) => Promise<import("pg").default.QueryResult
|
|
75
|
+
export declare const queryZeroOrOneRowAsync: (sql: string, params: QueryParams) => Promise<import("pg").default.QueryResult<any>>;
|
|
76
76
|
/**
|
|
77
77
|
* Calls the given sproc with the specified parameters.
|
|
78
78
|
*
|
|
79
79
|
* @deprecated Use {@link callRows} instead.
|
|
80
80
|
*/
|
|
81
|
-
export declare const callAsync: (functionName: string, params: any[]) => Promise<import("pg").default.QueryResult
|
|
81
|
+
export declare const callAsync: (functionName: string, params: any[]) => Promise<import("pg").default.QueryResult<any>>;
|
|
82
82
|
/**
|
|
83
83
|
* Calls the given sproc with the specified parameters. Errors if the
|
|
84
84
|
* sproc does not return exactly one row.
|
|
85
85
|
*
|
|
86
86
|
* @deprecated Use {@link callRow} instead.
|
|
87
87
|
*/
|
|
88
|
-
export declare const callOneRowAsync: (functionName: string, params: any[]) => Promise<import("pg").default.QueryResult
|
|
88
|
+
export declare const callOneRowAsync: (functionName: string, params: any[]) => Promise<import("pg").default.QueryResult<any>>;
|
|
89
89
|
/**
|
|
90
90
|
* Calls the given sproc with the specified parameters. Errors if the
|
|
91
91
|
* sproc returns more than one row.
|
|
92
92
|
*
|
|
93
93
|
* @deprecated Use {@link callOptionalRow} instead.
|
|
94
94
|
*/
|
|
95
|
-
export declare const callZeroOrOneRowAsync: (functionName: string, params: any[]) => Promise<import("pg").default.QueryResult
|
|
95
|
+
export declare const callZeroOrOneRowAsync: (functionName: string, params: any[]) => Promise<import("pg").default.QueryResult<any>>;
|
|
96
96
|
/**
|
|
97
97
|
* Calls a sproc with the specified parameters using a specific client.
|
|
98
98
|
*/
|
|
99
|
-
export declare const callWithClientAsync: (client: import("pg").
|
|
99
|
+
export declare const callWithClientAsync: (client: import("pg").PoolClient, functionName: string, params: any[]) => Promise<import("pg").default.QueryResult<any>>;
|
|
100
100
|
/**
|
|
101
101
|
* Calls a sproc with the specified parameters using a specific client.
|
|
102
102
|
* Errors if the sproc does not return exactly one row.
|
|
103
103
|
*/
|
|
104
|
-
export declare const callWithClientOneRowAsync: (client: import("pg").
|
|
104
|
+
export declare const callWithClientOneRowAsync: (client: import("pg").PoolClient, functionName: string, params: any[]) => Promise<import("pg").default.QueryResult<any>>;
|
|
105
105
|
/**
|
|
106
106
|
* Calls a sproc with the specified parameters using a specific client.
|
|
107
107
|
* Errors if the sproc returns more than one row.
|
|
108
108
|
*/
|
|
109
|
-
export declare const callWithClientZeroOrOneRowAsync: (client: import("pg").
|
|
109
|
+
export declare const callWithClientZeroOrOneRowAsync: (client: import("pg").PoolClient, functionName: string, params: any[]) => Promise<import("pg").default.QueryResult<any>>;
|
|
110
110
|
/**
|
|
111
111
|
* Executes a query with the specified parameters. Returns an array of rows
|
|
112
112
|
* that conform to the given Zod schema.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-pool.d.ts","sourceRoot":"","sources":["../src/default-pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAEhF,QAAA,MAAM,WAAW,cAAqB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,KAAK,cAAc,EAAE,KAAK,WAAW,EAAE,CAAC;AAe9D;;GAEG;AACH,eAAO,MAAM,SAAS,wJAA0C,CAAC;AACjE;;GAEG;AACH,eAAO,MAAM,UAAU,qBAA2C,CAAC;AACnE;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,gDAA+C,CAAC;AAE3E;;GAEG;AACH,eAAO,MAAM,oBAAoB,0HAAqD,CAAC;AAEvF;;;GAGG;AACH,eAAO,MAAM,0BAA0B,0HAA2D,CAAC;AAEnG;;;GAGG;AACH,eAAO,MAAM,gCAAgC,kHACmB,CAAC;AACjE;;GAEG;AACH,eAAO,MAAM,uBAAuB,4DAAwD,CAAC;AAC7F,eAAO,MAAM,qBAAqB,gDAAsD,CAAC;AACzF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,2FAAoD,CAAC;AACrF;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,gFAAsD,CAAC;AACzF;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU,yEAA2C,CAAC;AACnE;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,iFAA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;AACjE;;;;GAIG;AACH,eAAO,MAAM,QAAQ;;;CAAyC,CAAC;AAC/D;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB;;;CAAiD,CAAC;AAC/E;;;GAGG;AACH,eAAO,MAAM,QAAQ;;;CAAyC,CAAC;AAC/D;;;GAGG;AACH,eAAO,MAAM,OAAO;;;CAAwC,CAAC;AAC7D;;;GAGG;AACH,eAAO,MAAM,eAAe;;;CAAgD,CAAC;AAE7E;;GAEG;AACH,eAAO,MAAM,OAAO,wDAAwC,CAAC;AAE7D;;GAEG;AACH,eAAO,MAAM,UAAU,sDAA2C,CAAC;AAEnE;;;;GAIG;AACH,eAAO,MAAM,WAAW;;;CAA4C,CAAC;AACrE;;;;GAIG;AACH,eAAO,MAAM,eAAe,0CAAgD,CAAC;AAC7E;;;;GAIG;AACH,eAAO,MAAM,eAAe,qBAAgD,CAAC;AAC7E;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,qCAA2D,CAAC;AAEnG;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,mCAAyD,CAAC","sourcesContent":["import { type CursorIterator, PostgresPool, type QueryParams } from './pool.js';\n\nconst defaultPool = new PostgresPool();\nexport { defaultPool, type CursorIterator, type QueryParams };\n\n// We re-expose all functions from the default pool here to account for the\n// default case of a shared global pool of clients. If someone want to create\n// their own pool, we expose the `PostgresPool` class.\n//\n// Note that we explicitly bind all functions to `defaultPool`. This ensures\n// that they'll be invoked with the correct `this` context, specifically when\n// this module is imported as `import * as db from '...'` and that import is\n// subsequently transformed by Babel to `interopRequireWildcard(...)`.\n\n// VSCode currently doesn't allow for us to use `inheritDoc` to inherit the\n// documentation from the `PostgresPool` class. We mirror the documentation\n// here for *async methods* in VSCode intellisense.\n\n/**\n * Creates a new connection pool and attempts to connect to the database.\n */\nexport const initAsync = defaultPool.initAsync.bind(defaultPool);\n/**\n * Closes the connection pool.\n */\nexport const closeAsync = defaultPool.closeAsync.bind(defaultPool);\n/**\n * Gets a new client from the connection pool. The caller MUST call `release()` to\n * release the client, whether or not errors occurred while using\n * `client`. The client can call `done(truthy_value)` to force\n * destruction of the client, but this should not be used except in\n * unusual circumstances.\n */\nexport const getClientAsync = defaultPool.getClientAsync.bind(defaultPool);\n\n/**\n * Performs a query with the given client.\n */\nexport const queryWithClientAsync = defaultPool.queryWithClientAsync.bind(defaultPool);\n\n/**\n * Performs a query with the given client. Errors if the query returns more\n * than one row.\n */\nexport const queryWithClientOneRowAsync = defaultPool.queryWithClientOneRowAsync.bind(defaultPool);\n\n/**\n * Performs a query with the given client. Errors if the query returns more\n * than one row.\n */\nexport const queryWithClientZeroOrOneRowAsync =\n defaultPool.queryWithClientZeroOrOneRowAsync.bind(defaultPool);\n/**\n * Rolls back the current transaction for the given client.\n */\nexport const rollbackWithClientAsync = defaultPool.rollbackWithClientAsync.bind(defaultPool);\nexport const beginTransactionAsync = defaultPool.beginTransactionAsync.bind(defaultPool);\n/**\n * Commits the transaction if err is null, otherwise rollbacks the transaction.\n * Also releases the client.\n */\nexport const endTransactionAsync = defaultPool.endTransactionAsync.bind(defaultPool);\n/**\n * Runs the specified function inside of a transaction. The function will\n * receive a database client as an argument, but it can also make queries\n * as usual, and the correct client will be used automatically.\n *\n * The transaction will be rolled back if the function throws an error, and\n * will be committed otherwise.\n */\nexport const runInTransactionAsync = defaultPool.runInTransactionAsync.bind(defaultPool);\n/**\n * Executes a query with the specified parameters.\n *\n * @deprecated Use {@link execute} instead.\n *\n * Using the return value of this function directly is not recommended. Instead, use\n * {@link queryRows}, {@link queryRow}, or {@link queryOptionalRow}.\n */\nexport const queryAsync = defaultPool.queryAsync.bind(defaultPool);\n/**\n * Executes a query with the specified parameters. Errors if the query does\n * not return exactly one row.\n *\n * @deprecated Use {@link executeRow} or {@link queryRow} instead.\n */\nexport const queryOneRowAsync = defaultPool.queryOneRowAsync.bind(defaultPool);\n/**\n * Executes a query with the specified parameters. Errors if the query\n * returns more than one row.\n *\n * @deprecated Use {@link queryOptionalRow} instead.\n */\nexport const queryZeroOrOneRowAsync = defaultPool.queryZeroOrOneRowAsync.bind(defaultPool);\n/**\n * Calls the given sproc with the specified parameters.\n *\n * @deprecated Use {@link callRows} instead.\n */\nexport const callAsync = defaultPool.callAsync.bind(defaultPool);\n/**\n * Calls the given sproc with the specified parameters. Errors if the\n * sproc does not return exactly one row.\n *\n * @deprecated Use {@link callRow} instead.\n */\nexport const callOneRowAsync = defaultPool.callOneRowAsync.bind(defaultPool);\n/**\n * Calls the given sproc with the specified parameters. Errors if the\n * sproc returns more than one row.\n *\n * @deprecated Use {@link callOptionalRow} instead.\n */\nexport const callZeroOrOneRowAsync = defaultPool.callZeroOrOneRowAsync.bind(defaultPool);\n/**\n * Calls a sproc with the specified parameters using a specific client.\n */\nexport const callWithClientAsync = defaultPool.callWithClientAsync.bind(defaultPool);\n/**\n * Calls a sproc with the specified parameters using a specific client.\n * Errors if the sproc does not return exactly one row.\n */\nexport const callWithClientOneRowAsync = defaultPool.callWithClientOneRowAsync.bind(defaultPool);\n/**\n * Calls a sproc with the specified parameters using a specific client.\n * Errors if the sproc returns more than one row.\n */\nexport const callWithClientZeroOrOneRowAsync =\n defaultPool.callWithClientZeroOrOneRowAsync.bind(defaultPool);\n/**\n * Executes a query with the specified parameters. Returns an array of rows\n * that conform to the given Zod schema.\n *\n * If the query returns a single column, the return value will be a list of column values.\n */\nexport const queryRows = defaultPool.queryRows.bind(defaultPool);\n/**\n * Executes a query with the specified parameters. Returns exactly one row that conforms to the given Zod schema.\n *\n * If the query returns a single column, the return value will be the column value itself.\n */\nexport const queryRow = defaultPool.queryRow.bind(defaultPool);\n/**\n * Executes a query with the specified parameters. Returns either null or a\n * single row that conforms to the given Zod schema, and errors otherwise.\n *\n * If the query returns a single column, the return value will be the column value itself.\n */\nexport const queryOptionalRow = defaultPool.queryOptionalRow.bind(defaultPool);\n/**\n * Calls the given sproc with the specified parameters.\n * Errors if the sproc does not return anything.\n */\nexport const callRows = defaultPool.callRows.bind(defaultPool);\n/**\n * Calls the given sproc with the specified parameters.\n * Returns exactly one row from the sproc that conforms to the given Zod schema.\n */\nexport const callRow = defaultPool.callRow.bind(defaultPool);\n/**\n * Calls the given sproc with the specified parameters. Returns either null\n * or a single row that conforms to the given Zod schema.\n */\nexport const callOptionalRow = defaultPool.callOptionalRow.bind(defaultPool);\n\n/**\n * Executes a query with the specified parameters. Returns the number of rows affected.\n */\nexport const execute = defaultPool.execute.bind(defaultPool);\n\n/**\n * Executes a query with the specified parameter, and errors if the query doesn't return exactly one row.\n */\nexport const executeRow = defaultPool.executeRow.bind(defaultPool);\n\n/**\n * Returns an {@link CursorIterator} that can be used to iterate over the\n * results of the query in batches, which is useful for large result sets.\n * Each row will be parsed by the given Zod schema.\n */\nexport const queryCursor = defaultPool.queryCursor.bind(defaultPool);\n/**\n * Set the schema to use for the search path.\n *\n * @param schema The schema name to use (can be \"null\" to unset the search path)\n */\nexport const setSearchSchema = defaultPool.setSearchSchema.bind(defaultPool);\n/**\n * Get the schema that is currently used for the search path.\n *\n * @returns schema in use (may be `null` to indicate no schema)\n */\nexport const getSearchSchema = defaultPool.getSearchSchema.bind(defaultPool);\n/**\n * Generate, set, and return a random schema name.\n *\n * @param prefix The prefix of the new schema, only the first 28 characters will be used (after lowercasing).\n * @returns The randomly-generated search schema.\n */\nexport const setRandomSearchSchemaAsync = defaultPool.setRandomSearchSchemaAsync.bind(defaultPool);\n\n/**\n * Deletes all schemas starting with the given prefix.\n *\n * @param prefix The prefix of the schemas to delete.\n */\nexport const clearSchemasStartingWith = defaultPool.clearSchemasStartingWith.bind(defaultPool);\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-pool.test.d.ts","sourceRoot":"","sources":["../src/default-pool.test.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"default-pool.test.d.ts","sourceRoot":"","sources":["../src/default-pool.test.ts"],"names":[],"mappings":"","sourcesContent":["import { assert, describe, it } from 'vitest';\n\nimport * as pgPool from './default-pool.js';\nimport { PostgresPool } from './pool.js';\n\n/**\n * Properties on {@link PostgresPool} that should not be available on the default\n * pool's exports.\n */\nconst HIDDEN_PROPERTIES = new Set([\n 'constructor',\n // Private members\n 'pool',\n 'alsClient',\n 'searchSchema',\n '_queryCount',\n 'queryCursorWithClient',\n 'queryCursorInternal',\n 'errorOnUnusedParameters',\n // Getters\n 'totalCount',\n 'idleCount',\n 'waitingCount',\n 'queryCount',\n]);\n\ndescribe('sqldb', () => {\n it('exports the full PostgresPool interface', () => {\n const pool = new PostgresPool();\n\n Object.getOwnPropertyNames(pool)\n .filter((n) => !HIDDEN_PROPERTIES.has(n))\n .forEach((prop) => {\n assert.property(pgPool, prop);\n assert.ok((pgPool as any)[prop]);\n });\n\n Object.getOwnPropertyNames(Object.getPrototypeOf(pool))\n .filter((n) => !HIDDEN_PROPERTIES.has(n))\n .forEach((prop) => {\n assert.property(pgPool, prop);\n assert.ok((pgPool as any)[prop]);\n });\n });\n\n it('should not have extra properties', () => {\n const pool = new PostgresPool();\n\n const knownProperties = [\n ...Object.getOwnPropertyNames(pool),\n ...Object.getOwnPropertyNames(Object.getPrototypeOf(pool)),\n 'PostgresPool',\n ];\n\n Object.getOwnPropertyNames(pool).forEach((prop) => {\n assert.include(knownProperties, prop);\n });\n });\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-pool.test.js","sourceRoot":"","sources":["../src/default-pool.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC;;;GAGG;AACH,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC;IAChC,aAAa;IACb,kBAAkB;IAClB,MAAM;IACN,WAAW;IACX,cAAc;IACd,aAAa;IACb,uBAAuB;IACvB,qBAAqB;IACrB,yB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AC,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;aACxC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YACjB,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YAC9B,MAAM,CAAC,EAAE,CAAE,MAAc,CAAC,IAAI,CAAC,CAAC,CAAC;QAAA,CAClC,CAAC,CAAC;IAAA,CACN,CAAC,CAAC;IAEH,EAAE,CAAC,kCAAkC,EAAE,GAAG,EAAE,CAAC;QAC3C,MAAM,IAAI,GAAG,IAAI,YAAY,EAAE,CAAC;QAEhC,MAAM,eAAe,GAAG;YACtB,GAAG,MAAM,CAAC,mBAAmB,CAAC,IAAI,CAAC;YACnC,GAAG,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;YAC1D,cAAc;SACf,CAAC;QAEF,MAAM,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YACjD,MAAM,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;QAAA,CACvC,CAAC,CAAC;IAAA,CACJ,CAAC,CAAC;AAAA,CACJ,CAAC,CAAC","sourcesContent":["import { assert, describe, it } from 'vitest';\n\nimport * as pgPool from './default-pool.js';\nimport { PostgresPool } from './pool.js';\n\n/**\n * Properties on {@link PostgresPool} that should not be available on the default\n * pool's exports.\n */\nconst HIDDEN_PROPERTIES = new Set([\n 'constructor',\n // Private members\n 'pool',\n 'alsClient',\n 'searchSchema',\n '_queryCount',\n 'queryCursorWithClient',\n 'queryCursorInternal',\n 'errorOnUnusedParameters',\n // Getters\n 'totalCount',\n 'idleCount',\n 'waitingCount',\n 'queryCount',\n]);\n\ndescribe('sqldb', () => {\n it('exports the full PostgresPool interface', () => {\n const pool = new PostgresPool();\n\n Object.getOwnPropertyNames(pool)\n .filter((n) => !HIDDEN_PROPERTIES.has(n))\n .forEach((prop) => {\n assert.property(pgPool, prop);\n assert.ok((pgPool as any)[prop]);\n });\n\n Object.getOwnPropertyNames(Object.getPrototypeOf(pool))\n .filter((n) => !HIDDEN_PROPERTIES.has(n))\n .forEach((prop) => {\n assert.property(pgPool, prop);\n assert.ok((pgPool as any)[prop]);\n });\n });\n\n it('should not have extra properties', () => {\n const pool = new PostgresPool();\n\n const knownProperties = [\n ...Object.getOwnPropertyNames(pool),\n ...Object.getOwnPropertyNames(Object.getPrototypeOf(pool)),\n 'PostgresPool',\n ];\n\n Object.getOwnPropertyNames(pool).forEach((prop) => {\n assert.include(knownProperties, prop);\n });\n });\n});\n"]}
|
package/dist/error.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,UAkB9F"}
|
|
1
|
+
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,UAkB9F","sourcesContent":["export function formatQueryWithErrorPosition(query: string, position: number | null | undefined) {\n if (position == null) return query;\n\n const prevNewline = Math.max(0, query.lastIndexOf('\\n', position) + 1);\n let nextNewline = query.indexOf('\\n', position);\n if (nextNewline < 0) nextNewline = query.length;\n const gap = ' '.repeat(Math.max(0, position - prevNewline - 1));\n return (\n query.slice(0, nextNewline) +\n '\\n' +\n gap +\n '^\\n' +\n gap +\n '|\\n' +\n gap +\n '+ ERROR POSITION SHOWN ABOVE\\n' +\n query.slice(nextNewline)\n );\n}\n"]}
|
package/dist/error.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,4BAA4B,CAAC,KAAa,EAAE,QAAmC;
|
|
1
|
+
{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,4BAA4B,CAAC,KAAa,EAAE,QAAmC,EAAE;IAC/F,IAAI,QAAQ,IAAI,IAAI;QAAE,OAAO,KAAK,CAAC;IAEnC,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IACvE,IAAI,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAChD,IAAI,WAAW,GAAG,CAAC;QAAE,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC;IAChD,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC;IAChE,OAAO,CACL,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,WAAW,CAAC;QAC3B,IAAI;QACJ,GAAG;QACH,KAAK;QACL,GAAG;QACH,KAAK;QACL,GAAG;QACH,gCAAgC;QAChC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CACzB,CAAC;AAAA,CACH","sourcesContent":["export function formatQueryWithErrorPosition(query: string, position: number | null | undefined) {\n if (position == null) return query;\n\n const prevNewline = Math.max(0, query.lastIndexOf('\\n', position) + 1);\n let nextNewline = query.indexOf('\\n', position);\n if (nextNewline < 0) nextNewline = query.length;\n const gap = ' '.repeat(Math.max(0, position - prevNewline - 1));\n return (\n query.slice(0, nextNewline) +\n '\\n' +\n gap +\n '^\\n' +\n gap +\n '|\\n' +\n gap +\n '+ ERROR POSITION SHOWN ABOVE\\n' +\n query.slice(nextNewline)\n );\n}\n"]}
|
package/dist/error.test.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.test.d.ts","sourceRoot":"","sources":["../src/error.test.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"error.test.d.ts","sourceRoot":"","sources":["../src/error.test.ts"],"names":[],"mappings":"","sourcesContent":["import { assert, describe, it } from 'vitest';\n\nimport { formatQueryWithErrorPosition } from './error.js';\n\ndescribe('formatQueryWithErrorPosition', () => {\n it('formats a query', () => {\n const formattedQuery = formatQueryWithErrorPosition('SELECT\\n foo bar baz\\nFROM table;', 18);\n assert.equal(\n formattedQuery,\n 'SELECT\\n foo bar baz\\n ^\\n |\\n + ERROR POSITION SHOWN ABOVE\\n\\nFROM table;',\n );\n });\n});\n"]}
|
package/dist/error.test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.test.js","sourceRoot":"","sources":["../src/error.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAE1D,QAAQ,CAAC,8BAA8B,EAAE,GAAG,EAAE;
|
|
1
|
+
{"version":3,"file":"error.test.js","sourceRoot":"","sources":["../src/error.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAE1D,QAAQ,CAAC,8BAA8B,EAAE,GAAG,EAAE,CAAC;IAC7C,EAAE,CAAC,iBAAiB,EAAE,GAAG,EAAE,CAAC;QAC1B,MAAM,cAAc,GAAG,4BAA4B,CAAC,oCAAoC,EAAE,EAAE,CAAC,CAAC;QAC9F,MAAM,CAAC,KAAK,CACV,cAAc,EACd,wGAAwG,CACzG,CAAC;IAAA,CACH,CAAC,CAAC;AAAA,CACJ,CAAC,CAAC","sourcesContent":["import { assert, describe, it } from 'vitest';\n\nimport { formatQueryWithErrorPosition } from './error.js';\n\ndescribe('formatQueryWithErrorPosition', () => {\n it('formats a query', () => {\n const formattedQuery = formatQueryWithErrorPosition('SELECT\\n foo bar baz\\nFROM table;', 18);\n assert.equal(\n formattedQuery,\n 'SELECT\\n foo bar baz\\n ^\\n |\\n + ERROR POSITION SHOWN ABOVE\\n\\nFROM table;',\n );\n });\n});\n"]}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,IAAI,CAAC;AAErC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,KAAK,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAElE,cAAc,mBAAmB,CAAC;AAElC,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EACL,qBAAqB,EACrB,KAAK,iBAAiB,EACtB,KAAK,wBAAwB,GAC9B,MAAM,iBAAiB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,IAAI,CAAC;AAErC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,KAAK,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAElE,cAAc,mBAAmB,CAAC;AAElC,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EACL,qBAAqB,EACrB,KAAK,iBAAiB,EACtB,KAAK,wBAAwB,GAC9B,MAAM,iBAAiB,CAAC","sourcesContent":["export { type PoolClient } from 'pg';\n\nexport { loadSql, loadSqlEquiv } from './loader.js';\nexport { PostgresPool, type PostgresPoolConfig } from './pool.js';\n\nexport * from './default-pool.js';\n\nexport { formatQueryWithErrorPosition } from './error.js';\n\nexport {\n makePostgresTestUtils,\n type PostgresTestUtils,\n type PostgresTestUtilsOptions,\n} from './test-utils.js';\n"]}
|
package/dist/loader.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAIA,KAAK,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAEtC,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAkBjD;AAED,wBAAgB,YAAY,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAa3D"}
|
|
1
|
+
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAIA,KAAK,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAEtC,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAkBjD;AAED,wBAAgB,YAAY,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAa3D","sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport url from 'node:url';\n\ntype SqlFile = Record<string, string>;\n\nexport function loadSql(filename: string): SqlFile {\n const sql: SqlFile = {\n all: fs.readFileSync(filename, 'utf8'),\n };\n const lines = sql.all.split(/\\r?\\n/);\n const blockRE = /^ *-- *BLOCK +([^ ]+) *$/;\n let blockName: string | null = null;\n lines.forEach((line) => {\n const result = blockRE.exec(line);\n if (result) {\n blockName = result[1];\n if (sql[blockName]) throw new Error(`${filename}: duplicate BLOCK name: ${blockName}`);\n sql[blockName] = line;\n } else if (blockName) {\n sql[blockName] += '\\n' + line;\n }\n });\n return sql;\n}\n\nexport function loadSqlEquiv(filePathOrUrl: string): SqlFile {\n let resolvedPath = filePathOrUrl;\n\n // This allows for us to pass `import.meta.url` to this function in ES Modules\n // environments where `__filename` is not available.\n if (filePathOrUrl.startsWith('file://')) {\n resolvedPath = url.fileURLToPath(filePathOrUrl);\n }\n\n const components = path.parse(resolvedPath);\n components.ext = '.sql';\n const sqlFilename = path.join(components.dir, components.name) + components.ext;\n return loadSql(sqlFilename);\n}\n"]}
|
package/dist/loader.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.js","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,GAAG,MAAM,UAAU,CAAC;AAI3B,MAAM,UAAU,OAAO,CAAC,QAAgB;
|
|
1
|
+
{"version":3,"file":"loader.js","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,GAAG,MAAM,UAAU,CAAC;AAI3B,MAAM,UAAU,OAAO,CAAC,QAAgB,EAAW;IACjD,MAAM,GAAG,GAAY;QACnB,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC;KACvC,CAAC;IACF,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,OAAO,GAAG,0BAA0B,CAAC;IAC3C,IAAI,SAAS,GAAkB,IAAI,CAAC;IACpC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QACtB,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAClC,IAAI,MAAM,EAAE,CAAC;YACX,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;YACtB,IAAI,GAAG,CAAC,SAAS,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,GAAG,QAAQ,2BAA2B,SAAS,EAAE,CAAC,CAAC;YACvF,GAAG,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC;QACxB,CAAC;aAAM,IAAI,SAAS,EAAE,CAAC;YACrB,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,GAAG,IAAI,CAAC;QAChC,CAAC;IAAA,CACF,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AAAA,CACZ;AAED,MAAM,UAAU,YAAY,CAAC,aAAqB,EAAW;IAC3D,IAAI,YAAY,GAAG,aAAa,CAAC;IAEjC,8EAA8E;IAC9E,oDAAoD;IACpD,IAAI,aAAa,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QACxC,YAAY,GAAG,GAAG,CAAC,aAAa,CAAC,aAAa,CAAC,CAAC;IAClD,CAAC;IAED,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAC5C,UAAU,CAAC,GAAG,GAAG,MAAM,CAAC;IACxB,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,UAAU,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC;IAChF,OAAO,OAAO,CAAC,WAAW,CAAC,CAAC;AAAA,CAC7B","sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport url from 'node:url';\n\ntype SqlFile = Record<string, string>;\n\nexport function loadSql(filename: string): SqlFile {\n const sql: SqlFile = {\n all: fs.readFileSync(filename, 'utf8'),\n };\n const lines = sql.all.split(/\\r?\\n/);\n const blockRE = /^ *-- *BLOCK +([^ ]+) *$/;\n let blockName: string | null = null;\n lines.forEach((line) => {\n const result = blockRE.exec(line);\n if (result) {\n blockName = result[1];\n if (sql[blockName]) throw new Error(`${filename}: duplicate BLOCK name: ${blockName}`);\n sql[blockName] = line;\n } else if (blockName) {\n sql[blockName] += '\\n' + line;\n }\n });\n return sql;\n}\n\nexport function loadSqlEquiv(filePathOrUrl: string): SqlFile {\n let resolvedPath = filePathOrUrl;\n\n // This allows for us to pass `import.meta.url` to this function in ES Modules\n // environments where `__filename` is not available.\n if (filePathOrUrl.startsWith('file://')) {\n resolvedPath = url.fileURLToPath(filePathOrUrl);\n }\n\n const components = path.parse(resolvedPath);\n components.ext = '.sql';\n const sqlFilename = path.join(components.dir, components.name) + components.ext;\n return loadSql(sqlFilename);\n}\n"]}
|
package/dist/pool.d.ts
CHANGED
|
@@ -147,10 +147,6 @@ export declare class PostgresPool {
|
|
|
147
147
|
* Executes a query with the specified parameter, and errors if the query doesn't return exactly one row.
|
|
148
148
|
*/
|
|
149
149
|
executeRow(sql: string, params?: QueryParams): Promise<void>;
|
|
150
|
-
/**
|
|
151
|
-
* Returns a {@link Cursor} for the given query. The cursor can be used to
|
|
152
|
-
* read results in batches, which is useful for large result sets.
|
|
153
|
-
*/
|
|
154
150
|
private queryCursorWithClient;
|
|
155
151
|
queryCursor<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<CursorIterator<z.infer<Model>>>;
|
|
156
152
|
queryCursor<Model extends z.ZodTypeAny>(sql: string, params: QueryParams, model: Model): Promise<CursorIterator<z.infer<Model>>>;
|
package/dist/pool.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool.d.ts","sourceRoot":"","sources":["../src/pool.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,EAAE,EAAiB,KAAK,WAAW,EAAiB,MAAM,IAAI,CAAC;AAExE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,EAAE,CAAC;AAEtD,MAAM,WAAW,cAAc,CAAC,CAAC;IAC/B,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,cAAc,CAAC,CAAC,EAAE,CAAC,CAAC;IACpD,MAAM,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AAC,CAAC,CAAC,CAAC;YAiB7B,mBAAmB;IA+EjC;;;;OAIG;IACG,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,iBAS1C;IAED;;;;OAIG;IACH,eAAe,IAAI,MAAM,GAAG,IAAI,CAE/B;IAED;;;;;OAKG;IACG,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAiBhE;IAED;;;;OAIG;IACG,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CA2B5D;IAED,6CAA6C;IAC7C,IAAI,UAAU,WAEb;IAED,sCAAsC;IACtC,IAAI,SAAS,WAEZ;IAED,0EAA0E;IAC1E,IAAI,YAAY,WAEf;IAED,wEAAwE;IACxE,IAAI,UAAU,WAEb;CACF","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { Readable, Transform } from 'node:stream';\n\nimport debugfn from 'debug';\nimport _ from 'lodash';\nimport multipipe from 'multipipe';\nimport pg, { DatabaseError, type QueryResult, escapeLiteral } from 'pg';\nimport Cursor from 'pg-cursor';\nimport { z } from 'zod';\n\nexport type QueryParams = Record<string, any> | any[];\n\nexport interface CursorIterator<T> {\n iterate: (batchSize: number) => AsyncGenerator<T[]>;\n stream: (batchSize: number) => NodeJS.ReadWriteStream;\n}\n\nexport interface PostgresPoolConfig extends pg.PoolConfig {\n errorOnUnusedParameters?: boolean;\n}\n\nconst debug = debugfn('@prairielearn/postgres');\nconst lastQueryMap = new WeakMap<pg.PoolClient, string>();\nconst searchSchemaMap = new WeakMap<pg.PoolClient, string>();\n\nfunction addDataToError(err: Error, data: Record<string, any>): Error {\n (err as any).data = {\n ...(err as any).data,\n ...data,\n };\n return err;\n}\n\nexport class PostgresError extends Error {\n public data: Record<string, any>;\n\n constructor(message: string, data: Record<string, any>) {\n super(message);\n this.data = data;\n this.name = 'PostgresError';\n }\n}\n\n/**\n * Formats a string for debugging.\n */\nfunction debugString(s: string): string {\n if (typeof s !== 'string') return 'NOT A STRING';\n s = s.replaceAll('\\n', '\\\\n');\n if (s.length > 78) s = s.slice(0, 75) + '...';\n s = '\"' + s + '\"';\n return s;\n}\n\n/**\n * Formats a set of params for debugging.\n */\nfunction debugParams(params: QueryParams): string {\n let s;\n try {\n s = JSON.stringify(params);\n } catch {\n s = 'CANNOT JSON STRINGIFY';\n }\n return debugString(s);\n}\n\n/**\n * Given an SQL string and params, creates an array of params and an SQL string\n * with any named dollar-sign placeholders replaced with parameters.\n */\nfunction paramsToArray(\n sql: string,\n params: QueryParams,\n errorOnUnusedParameters: boolean,\n): { processedSql: string; paramsArray: any } {\n if (typeof sql !== 'string') throw new Error('SQL must be a string');\n if (Array.isArray(params)) {\n return {\n processedSql: sql,\n paramsArray: params,\n };\n }\n if (params == null || typeof params !== 'object') {\n throw new Error('params must be array or object');\n }\n\n const re = /\\$([-_a-zA-Z0-9]+)/;\n let result;\n let processedSql = '';\n let remainingSql = sql;\n let nParams = 0;\n const map: Record<string, string> = {};\n let paramsArray: any[] = [];\n while ((result = re.exec(remainingSql)) !== null) {\n const v = result[1];\n if (!(v in map)) {\n if (!(v in params)) throw new Error(`Missing parameter: ${v}`);\n if (Array.isArray(params[v])) {\n map[v] = 'ARRAY[' + params[v].map((_, n) => '$' + (n + nParams + 1)).join(',') + ']';\n nParams += params[v].length;\n paramsArray = paramsArray.concat(params[v]);\n } else {\n nParams++;\n map[v] = '$' + nParams;\n paramsArray.push(params[v]);\n }\n }\n processedSql += remainingSql.slice(0, result.index) + map[v];\n remainingSql = remainingSql.slice(result.index + result[0].length);\n }\n processedSql += remainingSql;\n remainingSql = '';\n if (errorOnUnusedParameters) {\n const difference = _.difference(Object.keys(params), Object.keys(map));\n if (difference.length > 0) {\n throw new Error(`Unused parameters in SQL query: ${JSON.stringify(difference)}`);\n }\n }\n return { processedSql, paramsArray };\n}\n\n/**\n * Escapes the given identifier for use in an SQL query. Useful for preventing\n * SQL injection.\n */\nfunction escapeIdentifier(identifier: string): string {\n // Note that as of 2021-06-29 escapeIdentifier() is undocumented. See:\n // https://github.com/brianc/node-postgres/pull/396\n // https://github.com/brianc/node-postgres/issues/1978\n // https://www.postgresql.org/docs/current/sql-syntax-lexical.html\n return pg.Client.prototype.escapeIdentifier(identifier);\n}\n\nfunction enhanceError(err: Error, sql: string, params: QueryParams): Error {\n // Copy the error so we don't end up with a circular reference in the\n // final error.\n const sqlError = {\n ...err,\n // `message` is a non-enumerable property, so we need to copy it manually to\n // the error object.\n message: err.message,\n };\n\n const errorHasPosition = err instanceof DatabaseError && err.position != null;\n\n return addDataToError(err, {\n sqlError,\n // If the error has a `position` field, we need to use the processed source\n // (where e.g. `$foobar` has been replaced with `$1`) so that the position\n // is accurate.\n sql: errorHasPosition ? paramsToArray(sql, params, false).processedSql : sql,\n sqlParams: params,\n });\n}\n\nexport class PostgresPool {\n /** The pool from which clients will be acquired. */\n private pool: pg.Pool | null = null;\n /**\n * We use this to propagate the client associated with the current transaction\n * to any nested queries. In the past, we had some nasty bugs associated with\n * the fact that we tried to acquire new clients inside of transactions, which\n * ultimately lead to a deadlock.\n */\n private alsClient = new AsyncLocalStorage<pg.PoolClient>();\n private searchSchema: string | null = null;\n /** Tracks the total number of queries executed by this pool. */\n private _queryCount = 0;\n private errorOnUnusedParameters = false;\n\n /**\n * Creates a new connection pool and attempts to connect to the database.\n */\n async initAsync(\n pgConfig: PostgresPoolConfig,\n idleErrorHandler: (error: Error, client: pg.PoolClient) => void,\n ): Promise<void> {\n if (this.pool != null) {\n throw new Error('Postgres pool already initialized');\n }\n this.errorOnUnusedParameters = pgConfig.errorOnUnusedParameters ?? false;\n this.pool = new pg.Pool(pgConfig);\n this.pool.on('error', function (err, client) {\n const lastQuery = lastQueryMap.get(client);\n idleErrorHandler(addDataToError(err, { lastQuery }), client);\n });\n this.pool.on('connect', (client) => {\n client.on('error', (err) => {\n const lastQuery = lastQueryMap.get(client);\n idleErrorHandler(addDataToError(err, { lastQuery }), client);\n });\n });\n this.pool.on('remove', (client) => {\n // This shouldn't be necessary, as `pg` currently allows clients to be\n // garbage collected after they're removed. However, if `pg` someday\n // starts reusing client objects across difference connections, this\n // will ensure that we re-set the search path when the client reconnects.\n searchSchemaMap.delete(client);\n });\n\n // Attempt to connect to the database so that we can fail quickly if\n // something isn't configured correctly.\n let retryCount = 0;\n const retryTimeouts = [500, 1000, 2000, 5000, 10000];\n while (retryCount <= retryTimeouts.length) {\n try {\n const client = await this.pool.connect();\n client.release();\n return;\n } catch (err: any) {\n if (retryCount === retryTimeouts.length) {\n throw new Error(`Could not connect to Postgres after ${retryTimeouts.length} attempts`, {\n cause: err,\n });\n }\n\n const timeout = retryTimeouts[retryCount];\n retryCount++;\n await new Promise((resolve) => setTimeout(resolve, timeout));\n }\n }\n }\n\n /**\n * Closes the connection pool.\n */\n async closeAsync(): Promise<void> {\n if (!this.pool) return;\n await this.pool.end();\n this.pool = null;\n }\n\n /**\n * Gets a new client from the connection pool. The caller MUST call `release()` to\n * release the client, whether or not errors occurred while using\n * `client`. The client can call `done(truthy_value)` to force\n * destruction of the client, but this should not be used except in\n * unusual circumstances.\n */\n async getClientAsync(): Promise<pg.PoolClient> {\n if (!this.pool) {\n throw new Error('Connection pool is not open');\n }\n\n // If we're inside a transaction, we'll reuse the same client to avoid a\n // potential deadlock.\n const client = this.alsClient.getStore() ?? (await this.pool.connect());\n\n // If we're configured to use a particular schema, we'll store whether or\n // not the search path has already been configured for this particular\n // client. If we acquire a client and it's already had its search path\n // set, we can avoid setting it again since the search path will persist\n // for the life of the client.\n //\n // We do this check for each call to `getClient` instead of on\n // `pool.connect` so that we don't have to be really careful about\n // destroying old clients that were created before `setSearchSchema` was\n // called. Instead, we'll just check if the search path matches the\n // currently-desired schema, and if it's a mismatch (or doesn't exist\n // at all), we re-set it for the current client.\n //\n // Note that this accidentally supports changing the search_path on the fly,\n // although that's not something we currently do (or would be likely to do).\n // It does NOT support clearing the existing search schema - e.g.,\n // `setSearchSchema(null)` would not work as you expect. This is fine, as\n // that's not something we ever do in practice.\n const clientSearchSchema = searchSchemaMap.get(client);\n if (this.searchSchema != null && clientSearchSchema !== this.searchSchema) {\n const setSearchPathSql = `SET search_path TO ${escapeIdentifier(this.searchSchema)},public`;\n try {\n await this.queryWithClientAsync(client, setSearchPathSql, {});\n } catch (err) {\n client.release();\n throw err;\n }\n searchSchemaMap.set(client, this.searchSchema);\n }\n\n return client;\n }\n\n /**\n * Performs a query with the given client.\n */\n async queryWithClientAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<pg.QueryResult> {\n this._queryCount += 1;\n debug('queryWithClient()', 'sql:', debugString(sql));\n debug('queryWithClient()', 'params:', debugParams(params));\n const { processedSql, paramsArray } = paramsToArray(sql, params, this.errorOnUnusedParameters);\n try {\n lastQueryMap.set(client, processedSql);\n const result = await client.query(processedSql, paramsArray);\n debug('queryWithClient() success', 'rowCount:', result.rowCount);\n return result;\n } catch (err: any) {\n throw enhanceError(err, sql, params);\n }\n }\n\n /**\n * Performs a query with the given client. Errors if the query returns more\n * than one row.\n */\n async queryWithClientOneRowAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<pg.QueryResult> {\n debug('queryWithClientOneRow()', 'sql:', debugString(sql));\n debug('queryWithClientOneRow()', 'params:', debugParams(params));\n const result = await this.queryWithClientAsync(client, sql, params);\n if (result.rowCount !== 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n result,\n });\n }\n debug('queryWithClientOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Performs a query with the given client. Errors if the query returns more\n * than one row.\n */\n async queryWithClientZeroOrOneRowAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<QueryResult> {\n debug('queryWithClientZeroOrOneRow()', 'sql:', debugString(sql));\n debug('queryWithClientZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.queryWithClientAsync(client, sql, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n result,\n });\n }\n debug('queryWithClientZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Rolls back the current transaction for the given client.\n */\n async rollbackWithClientAsync(client: pg.PoolClient) {\n debug('rollbackWithClient()');\n // From https://node-postgres.com/features/transactions\n try {\n await client.query('ROLLBACK');\n // Only release the client if we weren't already inside a transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n } catch (err: any) {\n // If there was a problem rolling back the query, something is\n // seriously messed up. Return the error to the release() function to\n // close & remove this client from the pool. If you leave a client in\n // the pool with an unaborted transaction, weird and hard to diagnose\n // problems might happen.\n client.release(err);\n }\n }\n\n /**\n * Begins a new transaction.\n */\n async beginTransactionAsync(): Promise<pg.PoolClient> {\n debug('beginTransaction()');\n const client = await this.getClientAsync();\n try {\n await this.queryWithClientAsync(client, 'START TRANSACTION;', {});\n return client;\n } catch (err) {\n await this.rollbackWithClientAsync(client);\n throw err;\n }\n }\n\n /**\n * Commits the transaction if err is null, otherwise rollbacks the transaction.\n * Also releases the client.\n */\n async endTransactionAsync(client: pg.PoolClient, err: Error | null | undefined) {\n debug('endTransaction()');\n if (err) {\n try {\n await this.rollbackWithClientAsync(client);\n } catch (rollbackErr: any) {\n throw addDataToError(rollbackErr, { prevErr: err, rollback: 'fail' });\n }\n\n // Even though we successfully rolled back the transaction, there was\n // still an error in the first place that necessitated a rollback. Re-throw\n // that error here so that everything downstream of here will know about it.\n throw addDataToError(err, { rollback: 'success' });\n } else {\n try {\n await this.queryWithClientAsync(client, 'COMMIT', {});\n } finally {\n // Only release the client if we aren't nested inside another transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n }\n }\n }\n\n /**\n * Runs the specified function inside of a transaction. The function will\n * receive a database client as an argument, but it can also make queries\n * as usual, and the correct client will be used automatically.\n *\n * The transaction will be rolled back if the function throws an error, and\n * will be committed otherwise.\n */\n async runInTransactionAsync<T>(fn: (client: pg.PoolClient) => Promise<T>): Promise<T> {\n // Check if we're already inside a transaction. If so, we won't start another one,\n // as Postgres doesn't support nested transactions.\n const client = this.alsClient.getStore();\n const isNestedTransaction = client !== undefined;\n const transactionClient = client ?? (await this.beginTransactionAsync());\n\n let result: T;\n try {\n result = await this.alsClient.run(transactionClient, () => fn(transactionClient));\n } catch (err: any) {\n if (!isNestedTransaction) {\n // If we're inside another transaction, we assume that the root transaction\n // will catch this error and roll back the transaction.\n await this.endTransactionAsync(transactionClient, err);\n }\n throw err;\n }\n\n if (!isNestedTransaction) {\n // If we're inside another transaction; don't commit it prematurely. Allow\n // the root transaction to commit it instead.\n //\n // Note that we don't invoke `endTransactionAsync` inside the `try` block\n // because we don't want an error thrown by it to trigger *another* call\n // to `endTransactionAsync` in the `catch` block.\n await this.endTransactionAsync(transactionClient, null);\n }\n\n return result;\n }\n\n /**\n * Executes a query with the specified parameters.\n *\n * @deprecated Use {@link execute} instead.\n *\n * Using the return value of this function directly is not recommended. Instead, use\n * {@link queryRows}, {@link queryRow}, or {@link queryOptionalRow}.\n */\n async queryAsync(sql: string, params: QueryParams): Promise<QueryResult> {\n debug('query()', 'sql:', debugString(sql));\n debug('query()', 'params:', debugParams(params));\n const client = await this.getClientAsync();\n try {\n return await this.queryWithClientAsync(client, sql, params);\n } finally {\n // Only release if we aren't nested in a transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n }\n }\n\n /**\n * Executes a query with the specified parameters. Errors if the query does\n * not return exactly one row.\n *\n * @deprecated Use {@link executeRow} or {@link queryRow} instead.\n */\n async queryOneRowAsync(sql: string, params: QueryParams): Promise<pg.QueryResult> {\n debug('queryOneRow()', 'sql:', debugString(sql));\n debug('queryOneRow()', 'params:', debugParams(params));\n const result = await this.queryAsync(sql, params);\n if (result.rowCount !== 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n });\n }\n debug('queryOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Executes a query with the specified parameters. Errors if the query\n * returns more than one row.\n */\n async queryZeroOrOneRowAsync(sql: string, params: QueryParams): Promise<pg.QueryResult> {\n debug('queryZeroOrOneRow()', 'sql:', debugString(sql));\n debug('queryZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.queryAsync(sql, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n });\n }\n debug('queryZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters.\n */\n async callAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('call()', 'function:', functionName);\n debug('call()', 'params:', debugParams(params));\n const placeholders = params.map((_, v) => '$' + (v + 1)).join(',');\n const sql = `SELECT * FROM ${escapeIdentifier(functionName)}(${placeholders});`;\n const result = await this.queryAsync(sql, params);\n debug('call() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters. Errors if the\n * sproc does not return exactly one row.\n */\n async callOneRowAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('callOneRow()', 'function:', functionName);\n debug('callOneRow()', 'params:', debugParams(params));\n const result = await this.callAsync(functionName, params);\n if (result.rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters. Errors if the\n * sproc returns more than one row.\n */\n async callZeroOrOneRowAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('callZeroOrOneRow()', 'function:', functionName);\n debug('callZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.callAsync(functionName, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a sproc with the specified parameters using a specific client.\n */\n async callWithClientAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClient()', 'function:', functionName);\n debug('callWithClient()', 'params:', debugParams(params));\n const placeholders = params.map((_, v) => '$' + (v + 1)).join(',');\n const sql = `SELECT * FROM ${escapeIdentifier(functionName)}(${placeholders})`;\n const result = await this.queryWithClientAsync(client, sql, params);\n debug('callWithClient() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a sproc with the specified parameters using a specific client.\n * Errors if the sproc does not return exactly one row.\n */\n async callWithClientOneRowAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClientOneRow()', 'function:', functionName);\n debug('callWithClientOneRow()', 'params:', debugParams(params));\n const result = await this.callWithClientAsync(client, functionName, params);\n if (result.rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callWithClientOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a function with the specified parameters using a specific client.\n * Errors if the sproc returns more than one row.\n */\n async callWithClientZeroOrOneRowAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClientZeroOrOneRow()', 'function:', functionName);\n debug('callWithClientZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.callWithClientAsync(client, functionName, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callWithClientZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n async queryRows<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>[]>;\n async queryRows<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model>[]>;\n /**\n * Executes a query with the specified parameters. Returns an array of rows\n * that conform to the given Zod schema.\n *\n * If the query returns a single column, the return value will be a list of column values.\n */\n async queryRows<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n const rawData = results.rows.map((row) => row[columnName]);\n return z.array(model).parse(rawData);\n } else {\n return z.array(model).parse(results.rows);\n }\n }\n\n async queryRow<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>>;\n async queryRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model>>;\n /**\n * Executes a query with the specified parameters. Returns exactly one row that conforms to the given Zod schema.\n *\n * If the query returns a single column, the return value will be the column value itself.\n */\n async queryRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryOneRowAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n /**\n * Executes a query with the specified parameters. Returns either null or a\n * single row that conforms to the given Zod schema, and errors otherwise.\n *\n * If the query returns a single column, the return value will be the column value itself.\n */\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryZeroOrOneRowAsync(sql, params);\n if (results.rows.length === 0) {\n return null;\n } else if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async callRows<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>[]>;\n async callRows<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model>[]>;\n /**\n * Calls the given sproc with the specified parameters.\n * Errors if the sproc does not return anything.\n */\n async callRows<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n const rawData = results.rows.map((row) => row[columnName]);\n return z.array(model).parse(rawData);\n } else {\n return z.array(model).parse(results.rows);\n }\n }\n\n async callRow<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>>;\n async callRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model>>;\n /**\n * Calls the given sproc with the specified parameters.\n * Returns exactly one row from the sproc that conforms to the given Zod schema.\n */\n async callRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callOneRowAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model> | null>;\n /**\n * Calls the given sproc with the specified parameters. Returns either null\n * or a single row that conforms to the given Zod schema.\n */\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callZeroOrOneRowAsync(sql, params);\n if (results.rows.length === 0) {\n return null;\n } else if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n /**\n * Executes a query with the specified parameters. Returns the number of rows affected.\n */\n async execute(sql: string, params: QueryParams = {}): Promise<number> {\n const result = await this.queryAsync(sql, params);\n return result.rowCount ?? 0;\n }\n\n /**\n * Executes a query with the specified parameter, and errors if the query doesn't return exactly one row.\n */\n async executeRow(sql: string, params: QueryParams = {}) {\n const rowCount = await this.execute(sql, params);\n if (rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + rowCount, {\n sql,\n sqlParams: params,\n });\n }\n }\n\n /**\n * Returns a {@link Cursor} for the given query. The cursor can be used to\n * read results in batches, which is useful for large result sets.\n */\n private async queryCursorWithClient(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<Cursor> {\n this._queryCount += 1;\n debug('queryCursorWithClient()', 'sql:', debugString(sql));\n debug('queryCursorWithClient()', 'params:', debugParams(params));\n const { processedSql, paramsArray } = paramsToArray(sql, params, this.errorOnUnusedParameters);\n lastQueryMap.set(client, processedSql);\n return client.query(new Cursor(processedSql, paramsArray));\n }\n\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<CursorIterator<z.infer<Model>>>;\n\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<CursorIterator<z.infer<Model>>>;\n\n /**\n * Returns an {@link CursorIterator} that can be used to iterate over the\n * results of the query in batches, which is useful for large result sets.\n * Each row will be parsed by the given Zod schema.\n */\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: Model | QueryParams,\n maybeModel?: Model,\n ): Promise<CursorIterator<z.infer<Model>>> {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n return this.queryCursorInternal(sql, params, model);\n }\n\n private async queryCursorInternal<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model?: Model,\n ): Promise<CursorIterator<z.infer<Model>>> {\n const client = await this.getClientAsync();\n const cursor = await this.queryCursorWithClient(client, sql, params);\n\n let iterateCalled = false;\n let rowKeys: string[] | null = null;\n const iterator: CursorIterator<z.infer<Model>> = {\n async *iterate(batchSize: number) {\n // Safety check: if someone calls iterate multiple times, they're\n // definitely doing something wrong.\n if (iterateCalled) {\n throw new Error('iterate() called multiple times');\n }\n iterateCalled = true;\n\n try {\n while (true) {\n const rows = await cursor.read(batchSize);\n if (rows.length === 0) {\n break;\n }\n\n if (rowKeys === null) {\n rowKeys = Object.keys(rows[0] ?? {});\n }\n const flattened =\n rowKeys.length === 1 ? rows.map((row) => row[(rowKeys as string[])[0]]) : rows;\n if (model) {\n yield z.array(model).parse(flattened);\n } else {\n yield flattened;\n }\n }\n } catch (err: any) {\n throw enhanceError(err, sql, params);\n } finally {\n try {\n await cursor.close();\n } finally {\n client.release();\n }\n }\n },\n stream(batchSize: number) {\n const transform = new Transform({\n readableObjectMode: true,\n writableObjectMode: true,\n transform(chunk, _encoding, callback) {\n for (const row of chunk) {\n this.push(row);\n }\n callback();\n },\n });\n\n // TODO: use native `node:stream#compose` once it's stable.\n const generator = iterator.iterate(batchSize);\n const pipe = multipipe(Readable.from(generator), transform);\n\n // When the underlying stream is closed, we need to make sure that the\n // cursor is also closed. We do this by calling `return()` on the generator,\n // which will trigger its `finally` block, which will in turn release\n // the client and close the cursor. The fact that the stream is already\n // closed by this point means that someone reading from the stream will\n // never actually see the `null` value that's returned.\n pipe.once('close', () => {\n generator.return(null);\n });\n\n return pipe;\n },\n };\n return iterator;\n }\n\n /**\n * Set the schema to use for the search path.\n *\n * @param schema The schema name to use (can be \"null\" to unset the search path)\n */\n async setSearchSchema(schema: string | null) {\n if (schema == null) {\n this.searchSchema = schema;\n return;\n }\n\n await this.queryAsync(`CREATE SCHEMA IF NOT EXISTS ${escapeIdentifier(schema)}`, {});\n // We only set searchSchema after CREATE to avoid the above query() call using searchSchema.\n this.searchSchema = schema;\n }\n\n /**\n * Get the schema that is currently used for the search path.\n *\n * @returns schema in use (may be `null` to indicate no schema)\n */\n getSearchSchema(): string | null {\n return this.searchSchema;\n }\n\n /**\n * Generate, set, and return a random schema name.\n *\n * @param prefix The prefix of the new schema, only the first 28 characters will be used (after lowercasing).\n * @returns The randomly-generated search schema.\n */\n async setRandomSearchSchemaAsync(prefix: string): Promise<string> {\n // truncated prefix (max 28 characters)\n const truncPrefix = prefix.slice(0, 28);\n // timestamp in format YYYY-MM-DDTHH:MM:SS.SSSZ (guaranteed to not exceed 27 characters in the spec)\n const timestamp = new Date().toISOString();\n // random 6-character suffix to avoid clashes (approx 2 billion possible values)\n const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');\n const suffix = Array.from({ length: 6 })\n .map(() => chars[Math.floor(Math.random() * chars.length)])\n .join('');\n\n // Schema is guaranteed to have length at most 63 (= 28 + 1 + 27 + 1 + 6),\n // which is the default PostgreSQL identifier limit.\n // Note that this schema name will need quoting because of characters like ':', '-', etc\n const schema = `${truncPrefix}_${timestamp}_${suffix}`;\n await this.setSearchSchema(schema);\n return schema;\n }\n\n /**\n * Deletes all schemas starting with the given prefix.\n *\n * @param prefix The prefix of the schemas to delete.\n */\n async clearSchemasStartingWith(prefix: string): Promise<void> {\n // Sanity check against deleting public, pg_, information_schema, etc.\n if (prefix === 'public' || prefix.startsWith('pg_') || prefix === 'information_schema') {\n throw new Error(`Cannot clear schema starting with ${prefix}`);\n }\n // Sanity check against a bad prefix.\n if (prefix.length < 4) {\n throw new Error(`Prefix is too short: ${prefix}`);\n }\n\n await this.queryAsync(\n `DO $$\n DECLARE\n r RECORD;\n BEGIN\n FOR r IN\n SELECT nspname\n FROM pg_namespace\n WHERE nspname LIKE ${escapeLiteral(prefix + '%')}\n AND nspname NOT LIKE 'pg_temp_%'\n LOOP\n EXECUTE format('DROP SCHEMA IF EXISTS %I CASCADE;', r.nspname);\n COMMIT; -- avoid shared memory exhaustion\n END LOOP;\n END $$;`,\n {},\n );\n }\n\n /** The number of established connections. */\n get totalCount() {\n return this.pool?.totalCount ?? 0;\n }\n\n /** The number of idle connections. */\n get idleCount() {\n return this.pool?.idleCount ?? 0;\n }\n\n /** The number of queries waiting for a connection to become available. */\n get waitingCount() {\n return this.pool?.waitingCount ?? 0;\n }\n\n /** The total number of queries that have been executed by this pool. */\n get queryCount() {\n return this._queryCount;\n }\n}\n"]}
|
package/dist/pool.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool.js","sourceRoot":"","sources":["../src/pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAElD,OAAO,OAAO,MAAM,OAAO,CAAC;AAC5B,OAAO,CAAC,MAAM,QAAQ,CAAC;AACvB,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,EAAE,EAAE,aAAa,EAAoB,aAAa,EAAE,MAAM,IAAI,CAAC;AACx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AAC,MAAM,CAAC,CAAC;QACnC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,wBAAwB,CAAC,MAAc;QAC3C,sEAAsE;QACtE,IAAI,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,MAAM,KAAK,oBAAoB,EAAE,CAAC;YACvF,MAAM,IAAI,KAAK,CAAC,qCAAqC,MAAM,EAAE,CAAC,CAAC;QACjE,CAAC;QACD,qCAAqC;QACrC,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,MAAM,EAAE,CAAC,CAAC;QACpD,CAAC;QAED,MAAM,IAAI,CAAC,UAAU,CACnB;;;;;;;6BAOuB,aAAa,CAAC,MAAM,GAAG,GAAG,CAAC;;;;;;YAM5C,EACN,EAAE,CACH,CAAC;IACJ,CAAC;IAED,6CAA6C;IAC7C,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,IAAI,EAAE,UAAU,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,sCAAsC;IACtC,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,IAAI,EAAE,SAAS,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,0EAA0E;IAC1E,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,IAAI,EAAE,YAAY,IAAI,CAAC,CAAC;IACtC,CAAC;IAED,wEAAwE;IACxE,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { Readable, Transform } from 'node:stream';\n\nimport debugfn from 'debug';\nimport _ from 'lodash';\nimport multipipe from 'multipipe';\nimport pg, { DatabaseError, type QueryResult, escapeLiteral } from 'pg';\nimport Cursor from 'pg-cursor';\nimport { z } from 'zod';\n\nexport type QueryParams = Record<string, any> | any[];\n\nexport interface CursorIterator<T> {\n iterate: (batchSize: number) => AsyncGenerator<T[]>;\n stream: (batchSize: number) => NodeJS.ReadWriteStream;\n}\n\nexport interface PostgresPoolConfig extends pg.PoolConfig {\n errorOnUnusedParameters?: boolean;\n}\n\nconst debug = debugfn('@prairielearn/postgres');\nconst lastQueryMap = new WeakMap<pg.PoolClient, string>();\nconst searchSchemaMap = new WeakMap<pg.PoolClient, string>();\n\nfunction addDataToError(err: Error, data: Record<string, any>): Error {\n (err as any).data = {\n ...(err as any).data,\n ...data,\n };\n return err;\n}\n\nexport class PostgresError extends Error {\n public data: Record<string, any>;\n\n constructor(message: string, data: Record<string, any>) {\n super(message);\n this.data = data;\n this.name = 'PostgresError';\n }\n}\n\n/**\n * Formats a string for debugging.\n */\nfunction debugString(s: string): string {\n if (typeof s !== 'string') return 'NOT A STRING';\n s = s.replaceAll('\\n', '\\\\n');\n if (s.length > 78) s = s.slice(0, 75) + '...';\n s = '\"' + s + '\"';\n return s;\n}\n\n/**\n * Formats a set of params for debugging.\n */\nfunction debugParams(params: QueryParams): string {\n let s;\n try {\n s = JSON.stringify(params);\n } catch {\n s = 'CANNOT JSON STRINGIFY';\n }\n return debugString(s);\n}\n\n/**\n * Given an SQL string and params, creates an array of params and an SQL string\n * with any named dollar-sign placeholders replaced with parameters.\n */\nfunction paramsToArray(\n sql: string,\n params: QueryParams,\n errorOnUnusedParameters: boolean,\n): { processedSql: string; paramsArray: any } {\n if (typeof sql !== 'string') throw new Error('SQL must be a string');\n if (Array.isArray(params)) {\n return {\n processedSql: sql,\n paramsArray: params,\n };\n }\n if (params == null || typeof params !== 'object') {\n throw new Error('params must be array or object');\n }\n\n const re = /\\$([-_a-zA-Z0-9]+)/;\n let result;\n let processedSql = '';\n let remainingSql = sql;\n let nParams = 0;\n const map: Record<string, string> = {};\n let paramsArray: any[] = [];\n while ((result = re.exec(remainingSql)) !== null) {\n const v = result[1];\n if (!(v in map)) {\n if (!(v in params)) throw new Error(`Missing parameter: ${v}`);\n if (Array.isArray(params[v])) {\n map[v] = 'ARRAY[' + params[v].map((_, n) => '$' + (n + nParams + 1)).join(',') + ']';\n nParams += params[v].length;\n paramsArray = paramsArray.concat(params[v]);\n } else {\n nParams++;\n map[v] = '$' + nParams;\n paramsArray.push(params[v]);\n }\n }\n processedSql += remainingSql.slice(0, result.index) + map[v];\n remainingSql = remainingSql.slice(result.index + result[0].length);\n }\n processedSql += remainingSql;\n remainingSql = '';\n if (errorOnUnusedParameters) {\n const difference = _.difference(Object.keys(params), Object.keys(map));\n if (difference.length > 0) {\n throw new Error(`Unused parameters in SQL query: ${JSON.stringify(difference)}`);\n }\n }\n return { processedSql, paramsArray };\n}\n\n/**\n * Escapes the given identifier for use in an SQL query. Useful for preventing\n * SQL injection.\n */\nfunction escapeIdentifier(identifier: string): string {\n // Note that as of 2021-06-29 escapeIdentifier() is undocumented. See:\n // https://github.com/brianc/node-postgres/pull/396\n // https://github.com/brianc/node-postgres/issues/1978\n // https://www.postgresql.org/docs/current/sql-syntax-lexical.html\n return pg.Client.prototype.escapeIdentifier(identifier);\n}\n\nfunction enhanceError(err: Error, sql: string, params: QueryParams): Error {\n // Copy the error so we don't end up with a circular reference in the\n // final error.\n const sqlError = {\n ...err,\n // `message` is a non-enumerable property, so we need to copy it manually to\n // the error object.\n message: err.message,\n };\n\n const errorHasPosition = err instanceof DatabaseError && err.position != null;\n\n return addDataToError(err, {\n sqlError,\n // If the error has a `position` field, we need to use the processed source\n // (where e.g. `$foobar` has been replaced with `$1`) so that the position\n // is accurate.\n sql: errorHasPosition ? paramsToArray(sql, params, false).processedSql : sql,\n sqlParams: params,\n });\n}\n\nexport class PostgresPool {\n /** The pool from which clients will be acquired. */\n private pool: pg.Pool | null = null;\n /**\n * We use this to propagate the client associated with the current transaction\n * to any nested queries. In the past, we had some nasty bugs associated with\n * the fact that we tried to acquire new clients inside of transactions, which\n * ultimately lead to a deadlock.\n */\n private alsClient = new AsyncLocalStorage<pg.PoolClient>();\n private searchSchema: string | null = null;\n /** Tracks the total number of queries executed by this pool. */\n private _queryCount = 0;\n private errorOnUnusedParameters = false;\n\n /**\n * Creates a new connection pool and attempts to connect to the database.\n */\n async initAsync(\n pgConfig: PostgresPoolConfig,\n idleErrorHandler: (error: Error, client: pg.PoolClient) => void,\n ): Promise<void> {\n if (this.pool != null) {\n throw new Error('Postgres pool already initialized');\n }\n this.errorOnUnusedParameters = pgConfig.errorOnUnusedParameters ?? false;\n this.pool = new pg.Pool(pgConfig);\n this.pool.on('error', function (err, client) {\n const lastQuery = lastQueryMap.get(client);\n idleErrorHandler(addDataToError(err, { lastQuery }), client);\n });\n this.pool.on('connect', (client) => {\n client.on('error', (err) => {\n const lastQuery = lastQueryMap.get(client);\n idleErrorHandler(addDataToError(err, { lastQuery }), client);\n });\n });\n this.pool.on('remove', (client) => {\n // This shouldn't be necessary, as `pg` currently allows clients to be\n // garbage collected after they're removed. However, if `pg` someday\n // starts reusing client objects across difference connections, this\n // will ensure that we re-set the search path when the client reconnects.\n searchSchemaMap.delete(client);\n });\n\n // Attempt to connect to the database so that we can fail quickly if\n // something isn't configured correctly.\n let retryCount = 0;\n const retryTimeouts = [500, 1000, 2000, 5000, 10000];\n while (retryCount <= retryTimeouts.length) {\n try {\n const client = await this.pool.connect();\n client.release();\n return;\n } catch (err: any) {\n if (retryCount === retryTimeouts.length) {\n throw new Error(`Could not connect to Postgres after ${retryTimeouts.length} attempts`, {\n cause: err,\n });\n }\n\n const timeout = retryTimeouts[retryCount];\n retryCount++;\n await new Promise((resolve) => setTimeout(resolve, timeout));\n }\n }\n }\n\n /**\n * Closes the connection pool.\n */\n async closeAsync(): Promise<void> {\n if (!this.pool) return;\n await this.pool.end();\n this.pool = null;\n }\n\n /**\n * Gets a new client from the connection pool. The caller MUST call `release()` to\n * release the client, whether or not errors occurred while using\n * `client`. The client can call `done(truthy_value)` to force\n * destruction of the client, but this should not be used except in\n * unusual circumstances.\n */\n async getClientAsync(): Promise<pg.PoolClient> {\n if (!this.pool) {\n throw new Error('Connection pool is not open');\n }\n\n // If we're inside a transaction, we'll reuse the same client to avoid a\n // potential deadlock.\n const client = this.alsClient.getStore() ?? (await this.pool.connect());\n\n // If we're configured to use a particular schema, we'll store whether or\n // not the search path has already been configured for this particular\n // client. If we acquire a client and it's already had its search path\n // set, we can avoid setting it again since the search path will persist\n // for the life of the client.\n //\n // We do this check for each call to `getClient` instead of on\n // `pool.connect` so that we don't have to be really careful about\n // destroying old clients that were created before `setSearchSchema` was\n // called. Instead, we'll just check if the search path matches the\n // currently-desired schema, and if it's a mismatch (or doesn't exist\n // at all), we re-set it for the current client.\n //\n // Note that this accidentally supports changing the search_path on the fly,\n // although that's not something we currently do (or would be likely to do).\n // It does NOT support clearing the existing search schema - e.g.,\n // `setSearchSchema(null)` would not work as you expect. This is fine, as\n // that's not something we ever do in practice.\n const clientSearchSchema = searchSchemaMap.get(client);\n if (this.searchSchema != null && clientSearchSchema !== this.searchSchema) {\n const setSearchPathSql = `SET search_path TO ${escapeIdentifier(this.searchSchema)},public`;\n try {\n await this.queryWithClientAsync(client, setSearchPathSql, {});\n } catch (err) {\n client.release();\n throw err;\n }\n searchSchemaMap.set(client, this.searchSchema);\n }\n\n return client;\n }\n\n /**\n * Performs a query with the given client.\n */\n async queryWithClientAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<pg.QueryResult> {\n this._queryCount += 1;\n debug('queryWithClient()', 'sql:', debugString(sql));\n debug('queryWithClient()', 'params:', debugParams(params));\n const { processedSql, paramsArray } = paramsToArray(sql, params, this.errorOnUnusedParameters);\n try {\n lastQueryMap.set(client, processedSql);\n const result = await client.query(processedSql, paramsArray);\n debug('queryWithClient() success', 'rowCount:', result.rowCount);\n return result;\n } catch (err: any) {\n throw enhanceError(err, sql, params);\n }\n }\n\n /**\n * Performs a query with the given client. Errors if the query returns more\n * than one row.\n */\n async queryWithClientOneRowAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<pg.QueryResult> {\n debug('queryWithClientOneRow()', 'sql:', debugString(sql));\n debug('queryWithClientOneRow()', 'params:', debugParams(params));\n const result = await this.queryWithClientAsync(client, sql, params);\n if (result.rowCount !== 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n result,\n });\n }\n debug('queryWithClientOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Performs a query with the given client. Errors if the query returns more\n * than one row.\n */\n async queryWithClientZeroOrOneRowAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<QueryResult> {\n debug('queryWithClientZeroOrOneRow()', 'sql:', debugString(sql));\n debug('queryWithClientZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.queryWithClientAsync(client, sql, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n result,\n });\n }\n debug('queryWithClientZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Rolls back the current transaction for the given client.\n */\n async rollbackWithClientAsync(client: pg.PoolClient) {\n debug('rollbackWithClient()');\n // From https://node-postgres.com/features/transactions\n try {\n await client.query('ROLLBACK');\n // Only release the client if we weren't already inside a transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n } catch (err: any) {\n // If there was a problem rolling back the query, something is\n // seriously messed up. Return the error to the release() function to\n // close & remove this client from the pool. If you leave a client in\n // the pool with an unaborted transaction, weird and hard to diagnose\n // problems might happen.\n client.release(err);\n }\n }\n\n /**\n * Begins a new transaction.\n */\n async beginTransactionAsync(): Promise<pg.PoolClient> {\n debug('beginTransaction()');\n const client = await this.getClientAsync();\n try {\n await this.queryWithClientAsync(client, 'START TRANSACTION;', {});\n return client;\n } catch (err) {\n await this.rollbackWithClientAsync(client);\n throw err;\n }\n }\n\n /**\n * Commits the transaction if err is null, otherwise rollbacks the transaction.\n * Also releases the client.\n */\n async endTransactionAsync(client: pg.PoolClient, err: Error | null | undefined) {\n debug('endTransaction()');\n if (err) {\n try {\n await this.rollbackWithClientAsync(client);\n } catch (rollbackErr: any) {\n throw addDataToError(rollbackErr, { prevErr: err, rollback: 'fail' });\n }\n\n // Even though we successfully rolled back the transaction, there was\n // still an error in the first place that necessitated a rollback. Re-throw\n // that error here so that everything downstream of here will know about it.\n throw addDataToError(err, { rollback: 'success' });\n } else {\n try {\n await this.queryWithClientAsync(client, 'COMMIT', {});\n } finally {\n // Only release the client if we aren't nested inside another transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n }\n }\n }\n\n /**\n * Runs the specified function inside of a transaction. The function will\n * receive a database client as an argument, but it can also make queries\n * as usual, and the correct client will be used automatically.\n *\n * The transaction will be rolled back if the function throws an error, and\n * will be committed otherwise.\n */\n async runInTransactionAsync<T>(fn: (client: pg.PoolClient) => Promise<T>): Promise<T> {\n // Check if we're already inside a transaction. If so, we won't start another one,\n // as Postgres doesn't support nested transactions.\n const client = this.alsClient.getStore();\n const isNestedTransaction = client !== undefined;\n const transactionClient = client ?? (await this.beginTransactionAsync());\n\n let result: T;\n try {\n result = await this.alsClient.run(transactionClient, () => fn(transactionClient));\n } catch (err: any) {\n if (!isNestedTransaction) {\n // If we're inside another transaction, we assume that the root transaction\n // will catch this error and roll back the transaction.\n await this.endTransactionAsync(transactionClient, err);\n }\n throw err;\n }\n\n if (!isNestedTransaction) {\n // If we're inside another transaction; don't commit it prematurely. Allow\n // the root transaction to commit it instead.\n //\n // Note that we don't invoke `endTransactionAsync` inside the `try` block\n // because we don't want an error thrown by it to trigger *another* call\n // to `endTransactionAsync` in the `catch` block.\n await this.endTransactionAsync(transactionClient, null);\n }\n\n return result;\n }\n\n /**\n * Executes a query with the specified parameters.\n *\n * @deprecated Use {@link execute} instead.\n *\n * Using the return value of this function directly is not recommended. Instead, use\n * {@link queryRows}, {@link queryRow}, or {@link queryOptionalRow}.\n */\n async queryAsync(sql: string, params: QueryParams): Promise<QueryResult> {\n debug('query()', 'sql:', debugString(sql));\n debug('query()', 'params:', debugParams(params));\n const client = await this.getClientAsync();\n try {\n return await this.queryWithClientAsync(client, sql, params);\n } finally {\n // Only release if we aren't nested in a transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n }\n }\n\n /**\n * Executes a query with the specified parameters. Errors if the query does\n * not return exactly one row.\n *\n * @deprecated Use {@link executeRow} or {@link queryRow} instead.\n */\n async queryOneRowAsync(sql: string, params: QueryParams): Promise<pg.QueryResult> {\n debug('queryOneRow()', 'sql:', debugString(sql));\n debug('queryOneRow()', 'params:', debugParams(params));\n const result = await this.queryAsync(sql, params);\n if (result.rowCount !== 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n });\n }\n debug('queryOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Executes a query with the specified parameters. Errors if the query\n * returns more than one row.\n */\n async queryZeroOrOneRowAsync(sql: string, params: QueryParams): Promise<pg.QueryResult> {\n debug('queryZeroOrOneRow()', 'sql:', debugString(sql));\n debug('queryZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.queryAsync(sql, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n });\n }\n debug('queryZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters.\n */\n async callAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('call()', 'function:', functionName);\n debug('call()', 'params:', debugParams(params));\n const placeholders = params.map((_, v) => '$' + (v + 1)).join(',');\n const sql = `SELECT * FROM ${escapeIdentifier(functionName)}(${placeholders});`;\n const result = await this.queryAsync(sql, params);\n debug('call() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters. Errors if the\n * sproc does not return exactly one row.\n */\n async callOneRowAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('callOneRow()', 'function:', functionName);\n debug('callOneRow()', 'params:', debugParams(params));\n const result = await this.callAsync(functionName, params);\n if (result.rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters. Errors if the\n * sproc returns more than one row.\n */\n async callZeroOrOneRowAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('callZeroOrOneRow()', 'function:', functionName);\n debug('callZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.callAsync(functionName, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a sproc with the specified parameters using a specific client.\n */\n async callWithClientAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClient()', 'function:', functionName);\n debug('callWithClient()', 'params:', debugParams(params));\n const placeholders = params.map((_, v) => '$' + (v + 1)).join(',');\n const sql = `SELECT * FROM ${escapeIdentifier(functionName)}(${placeholders})`;\n const result = await this.queryWithClientAsync(client, sql, params);\n debug('callWithClient() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a sproc with the specified parameters using a specific client.\n * Errors if the sproc does not return exactly one row.\n */\n async callWithClientOneRowAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClientOneRow()', 'function:', functionName);\n debug('callWithClientOneRow()', 'params:', debugParams(params));\n const result = await this.callWithClientAsync(client, functionName, params);\n if (result.rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callWithClientOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a function with the specified parameters using a specific client.\n * Errors if the sproc returns more than one row.\n */\n async callWithClientZeroOrOneRowAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClientZeroOrOneRow()', 'function:', functionName);\n debug('callWithClientZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.callWithClientAsync(client, functionName, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callWithClientZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n async queryRows<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>[]>;\n async queryRows<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model>[]>;\n /**\n * Executes a query with the specified parameters. Returns an array of rows\n * that conform to the given Zod schema.\n *\n * If the query returns a single column, the return value will be a list of column values.\n */\n async queryRows<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n const rawData = results.rows.map((row) => row[columnName]);\n return z.array(model).parse(rawData);\n } else {\n return z.array(model).parse(results.rows);\n }\n }\n\n async queryRow<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>>;\n async queryRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model>>;\n /**\n * Executes a query with the specified parameters. Returns exactly one row that conforms to the given Zod schema.\n *\n * If the query returns a single column, the return value will be the column value itself.\n */\n async queryRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryOneRowAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n /**\n * Executes a query with the specified parameters. Returns either null or a\n * single row that conforms to the given Zod schema, and errors otherwise.\n *\n * If the query returns a single column, the return value will be the column value itself.\n */\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryZeroOrOneRowAsync(sql, params);\n if (results.rows.length === 0) {\n return null;\n } else if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async callRows<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>[]>;\n async callRows<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model>[]>;\n /**\n * Calls the given sproc with the specified parameters.\n * Errors if the sproc does not return anything.\n */\n async callRows<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n const rawData = results.rows.map((row) => row[columnName]);\n return z.array(model).parse(rawData);\n } else {\n return z.array(model).parse(results.rows);\n }\n }\n\n async callRow<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>>;\n async callRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model>>;\n /**\n * Calls the given sproc with the specified parameters.\n * Returns exactly one row from the sproc that conforms to the given Zod schema.\n */\n async callRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callOneRowAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model> | null>;\n /**\n * Calls the given sproc with the specified parameters. Returns either null\n * or a single row that conforms to the given Zod schema.\n */\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callZeroOrOneRowAsync(sql, params);\n if (results.rows.length === 0) {\n return null;\n } else if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n /**\n * Executes a query with the specified parameters. Returns the number of rows affected.\n */\n async execute(sql: string, params: QueryParams = {}): Promise<number> {\n const result = await this.queryAsync(sql, params);\n return result.rowCount ?? 0;\n }\n\n /**\n * Executes a query with the specified parameter, and errors if the query doesn't return exactly one row.\n */\n async executeRow(sql: string, params: QueryParams = {}) {\n const rowCount = await this.execute(sql, params);\n if (rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + rowCount, {\n sql,\n sqlParams: params,\n });\n }\n }\n\n /**\n * Returns a {@link Cursor} for the given query. The cursor can be used to\n * read results in batches, which is useful for large result sets.\n */\n private async queryCursorWithClient(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<Cursor> {\n this._queryCount += 1;\n debug('queryCursorWithClient()', 'sql:', debugString(sql));\n debug('queryCursorWithClient()', 'params:', debugParams(params));\n const { processedSql, paramsArray } = paramsToArray(sql, params, this.errorOnUnusedParameters);\n lastQueryMap.set(client, processedSql);\n return client.query(new Cursor(processedSql, paramsArray));\n }\n\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<CursorIterator<z.infer<Model>>>;\n\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<CursorIterator<z.infer<Model>>>;\n\n /**\n * Returns an {@link CursorIterator} that can be used to iterate over the\n * results of the query in batches, which is useful for large result sets.\n * Each row will be parsed by the given Zod schema.\n */\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: Model | QueryParams,\n maybeModel?: Model,\n ): Promise<CursorIterator<z.infer<Model>>> {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n return this.queryCursorInternal(sql, params, model);\n }\n\n private async queryCursorInternal<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model?: Model,\n ): Promise<CursorIterator<z.infer<Model>>> {\n const client = await this.getClientAsync();\n const cursor = await this.queryCursorWithClient(client, sql, params);\n\n let iterateCalled = false;\n let rowKeys: string[] | null = null;\n const iterator: CursorIterator<z.infer<Model>> = {\n async *iterate(batchSize: number) {\n // Safety check: if someone calls iterate multiple times, they're\n // definitely doing something wrong.\n if (iterateCalled) {\n throw new Error('iterate() called multiple times');\n }\n iterateCalled = true;\n\n try {\n while (true) {\n const rows = await cursor.read(batchSize);\n if (rows.length === 0) {\n break;\n }\n\n if (rowKeys === null) {\n rowKeys = Object.keys(rows[0] ?? {});\n }\n const flattened =\n rowKeys.length === 1 ? rows.map((row) => row[(rowKeys as string[])[0]]) : rows;\n if (model) {\n yield z.array(model).parse(flattened);\n } else {\n yield flattened;\n }\n }\n } catch (err: any) {\n throw enhanceError(err, sql, params);\n } finally {\n try {\n await cursor.close();\n } finally {\n client.release();\n }\n }\n },\n stream(batchSize: number) {\n const transform = new Transform({\n readableObjectMode: true,\n writableObjectMode: true,\n transform(chunk, _encoding, callback) {\n for (const row of chunk) {\n this.push(row);\n }\n callback();\n },\n });\n\n // TODO: use native `node:stream#compose` once it's stable.\n const generator = iterator.iterate(batchSize);\n const pipe = multipipe(Readable.from(generator), transform);\n\n // When the underlying stream is closed, we need to make sure that the\n // cursor is also closed. We do this by calling `return()` on the generator,\n // which will trigger its `finally` block, which will in turn release\n // the client and close the cursor. The fact that the stream is already\n // closed by this point means that someone reading from the stream will\n // never actually see the `null` value that's returned.\n pipe.once('close', () => {\n generator.return(null);\n });\n\n return pipe;\n },\n };\n return iterator;\n }\n\n /**\n * Set the schema to use for the search path.\n *\n * @param schema The schema name to use (can be \"null\" to unset the search path)\n */\n async setSearchSchema(schema: string | null) {\n if (schema == null) {\n this.searchSchema = schema;\n return;\n }\n\n await this.queryAsync(`CREATE SCHEMA IF NOT EXISTS ${escapeIdentifier(schema)}`, {});\n // We only set searchSchema after CREATE to avoid the above query() call using searchSchema.\n this.searchSchema = schema;\n }\n\n /**\n * Get the schema that is currently used for the search path.\n *\n * @returns schema in use (may be `null` to indicate no schema)\n */\n getSearchSchema(): string | null {\n return this.searchSchema;\n }\n\n /**\n * Generate, set, and return a random schema name.\n *\n * @param prefix The prefix of the new schema, only the first 28 characters will be used (after lowercasing).\n * @returns The randomly-generated search schema.\n */\n async setRandomSearchSchemaAsync(prefix: string): Promise<string> {\n // truncated prefix (max 28 characters)\n const truncPrefix = prefix.slice(0, 28);\n // timestamp in format YYYY-MM-DDTHH:MM:SS.SSSZ (guaranteed to not exceed 27 characters in the spec)\n const timestamp = new Date().toISOString();\n // random 6-character suffix to avoid clashes (approx 2 billion possible values)\n const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');\n const suffix = Array.from({ length: 6 })\n .map(() => chars[Math.floor(Math.random() * chars.length)])\n .join('');\n\n // Schema is guaranteed to have length at most 63 (= 28 + 1 + 27 + 1 + 6),\n // which is the default PostgreSQL identifier limit.\n // Note that this schema name will need quoting because of characters like ':', '-', etc\n const schema = `${truncPrefix}_${timestamp}_${suffix}`;\n await this.setSearchSchema(schema);\n return schema;\n }\n\n /**\n * Deletes all schemas starting with the given prefix.\n *\n * @param prefix The prefix of the schemas to delete.\n */\n async clearSchemasStartingWith(prefix: string): Promise<void> {\n // Sanity check against deleting public, pg_, information_schema, etc.\n if (prefix === 'public' || prefix.startsWith('pg_') || prefix === 'information_schema') {\n throw new Error(`Cannot clear schema starting with ${prefix}`);\n }\n // Sanity check against a bad prefix.\n if (prefix.length < 4) {\n throw new Error(`Prefix is too short: ${prefix}`);\n }\n\n await this.queryAsync(\n `DO $$\n DECLARE\n r RECORD;\n BEGIN\n FOR r IN\n SELECT nspname\n FROM pg_namespace\n WHERE nspname LIKE ${escapeLiteral(prefix + '%')}\n AND nspname NOT LIKE 'pg_temp_%'\n LOOP\n EXECUTE format('DROP SCHEMA IF EXISTS %I CASCADE;', r.nspname);\n COMMIT; -- avoid shared memory exhaustion\n END LOOP;\n END $$;`,\n {},\n );\n }\n\n /** The number of established connections. */\n get totalCount() {\n return this.pool?.totalCount ?? 0;\n }\n\n /** The number of idle connections. */\n get idleCount() {\n return this.pool?.idleCount ?? 0;\n }\n\n /** The number of queries waiting for a connection to become available. */\n get waitingCount() {\n return this.pool?.waitingCount ?? 0;\n }\n\n /** The total number of queries that have been executed by this pool. */\n get queryCount() {\n return this._queryCount;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pool.js","sourceRoot":"","sources":["../src/pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAElD,OAAO,OAAO,MAAM,OAAO,CAAC;AAC5B,OAAO,CAAC,MAAM,QAAQ,CAAC;AACvB,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,EAAE,EAAE,aAAa,EAAoB,aAAa,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,MAAM,MAAM,WAAW,CAAC;AAC/B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAaxB,MAAM,KAAK,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAC;AAChD,MAAM,YAAY,GAAG,IAAI,OAAO,EAAyB,CAAC;AAC1D,MAAM,eAAe,GAAG,IAAI,OAAO,EAAyB,CAAC;AAE7D,SAAS,cAAc,CAAC,GAAU,EAAE,IAAyB,EAAS;IACnE,GAAW,CAAC,IAAI,GAAG;QAClB,GAAI,GAAW,CAAC,IAAI;QACpB,GAAG,IAAI;KACR,CAAC;IACF,OAAO,GAAG,CAAC;AAAA,CACZ;AAED,MAAM,OAAO,aAAc,SAAQ,KAAK;IAC/B,IAAI,CAAsB;IAEjC,YAAY,OAAe,EAAE,IAAyB,EAAE;QACtD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAAA,CAC7B;CACF;AAED;;GAEG;AACH,SAAS,WAAW,CAAC,CAAS,EAAU;IACtC,IAAI,OAAO,CAAC,KAAK,QAAQ;QAAE,OAAO,cAAc,CAAC;IACjD,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,IAA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AAC,MAAM,GAAG,GAAG,CAAC;;;;;;YAM5C,EACN,EAAE,CACH,CAAC;IAAA,CACH;IAED,6CAA6C;IAC7C,IAAI,UAAU,GAAG;QACf,OAAO,IAAI,CAAC,IAAI,EAAE,UAAU,IAAI,CAAC,CAAC;IAAA,CACnC;IAED,sCAAsC;IACtC,IAAI,SAAS,GAAG;QACd,OAAO,IAAI,CAAC,IAAI,EAAE,SAAS,IAAI,CAAC,CAAC;IAAA,CAClC;IAED,0EAA0E;IAC1E,IAAI,YAAY,GAAG;QACjB,OAAO,IAAI,CAAC,IAAI,EAAE,YAAY,IAAI,CAAC,CAAC;IAAA,CACrC;IAED,wEAAwE;IACxE,IAAI,UAAU,GAAG;QACf,OAAO,IAAI,CAAC,WAAW,CAAC;IAAA,CACzB;CACF","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { Readable, Transform } from 'node:stream';\n\nimport debugfn from 'debug';\nimport _ from 'lodash';\nimport multipipe from 'multipipe';\nimport pg, { DatabaseError, type QueryResult, escapeLiteral } from 'pg';\nimport Cursor from 'pg-cursor';\nimport { z } from 'zod';\n\nexport type QueryParams = Record<string, any> | any[];\n\nexport interface CursorIterator<T> {\n iterate: (batchSize: number) => AsyncGenerator<T[]>;\n stream: (batchSize: number) => NodeJS.ReadWriteStream;\n}\n\nexport interface PostgresPoolConfig extends pg.PoolConfig {\n errorOnUnusedParameters?: boolean;\n}\n\nconst debug = debugfn('@prairielearn/postgres');\nconst lastQueryMap = new WeakMap<pg.PoolClient, string>();\nconst searchSchemaMap = new WeakMap<pg.PoolClient, string>();\n\nfunction addDataToError(err: Error, data: Record<string, any>): Error {\n (err as any).data = {\n ...(err as any).data,\n ...data,\n };\n return err;\n}\n\nexport class PostgresError extends Error {\n public data: Record<string, any>;\n\n constructor(message: string, data: Record<string, any>) {\n super(message);\n this.data = data;\n this.name = 'PostgresError';\n }\n}\n\n/**\n * Formats a string for debugging.\n */\nfunction debugString(s: string): string {\n if (typeof s !== 'string') return 'NOT A STRING';\n s = s.replaceAll('\\n', '\\\\n');\n if (s.length > 78) s = s.slice(0, 75) + '...';\n s = '\"' + s + '\"';\n return s;\n}\n\n/**\n * Formats a set of params for debugging.\n */\nfunction debugParams(params: QueryParams): string {\n let s;\n try {\n s = JSON.stringify(params);\n } catch {\n s = 'CANNOT JSON STRINGIFY';\n }\n return debugString(s);\n}\n\n/**\n * Given an SQL string and params, creates an array of params and an SQL string\n * with any named dollar-sign placeholders replaced with parameters.\n */\nfunction paramsToArray(\n sql: string,\n params: QueryParams,\n errorOnUnusedParameters: boolean,\n): { processedSql: string; paramsArray: any } {\n if (typeof sql !== 'string') throw new Error('SQL must be a string');\n if (Array.isArray(params)) {\n return {\n processedSql: sql,\n paramsArray: params,\n };\n }\n if (params == null || typeof params !== 'object') {\n throw new Error('params must be array or object');\n }\n\n const re = /\\$([-_a-zA-Z0-9]+)/;\n let result;\n let processedSql = '';\n let remainingSql = sql;\n let nParams = 0;\n const map: Record<string, string> = {};\n let paramsArray: any[] = [];\n while ((result = re.exec(remainingSql)) !== null) {\n const v = result[1];\n if (!(v in map)) {\n if (!(v in params)) throw new Error(`Missing parameter: ${v}`);\n if (Array.isArray(params[v])) {\n map[v] = 'ARRAY[' + params[v].map((_, n) => '$' + (n + nParams + 1)).join(',') + ']';\n nParams += params[v].length;\n paramsArray = paramsArray.concat(params[v]);\n } else {\n nParams++;\n map[v] = '$' + nParams;\n paramsArray.push(params[v]);\n }\n }\n processedSql += remainingSql.slice(0, result.index) + map[v];\n remainingSql = remainingSql.slice(result.index + result[0].length);\n }\n processedSql += remainingSql;\n remainingSql = '';\n if (errorOnUnusedParameters) {\n const difference = _.difference(Object.keys(params), Object.keys(map));\n if (difference.length > 0) {\n throw new Error(`Unused parameters in SQL query: ${JSON.stringify(difference)}`);\n }\n }\n return { processedSql, paramsArray };\n}\n\n/**\n * Escapes the given identifier for use in an SQL query. Useful for preventing\n * SQL injection.\n */\nfunction escapeIdentifier(identifier: string): string {\n // Note that as of 2021-06-29 escapeIdentifier() is undocumented. See:\n // https://github.com/brianc/node-postgres/pull/396\n // https://github.com/brianc/node-postgres/issues/1978\n // https://www.postgresql.org/docs/current/sql-syntax-lexical.html\n return pg.Client.prototype.escapeIdentifier(identifier);\n}\n\nfunction enhanceError(err: Error, sql: string, params: QueryParams): Error {\n // Copy the error so we don't end up with a circular reference in the\n // final error.\n const sqlError = {\n ...err,\n // `message` is a non-enumerable property, so we need to copy it manually to\n // the error object.\n message: err.message,\n };\n\n const errorHasPosition = err instanceof DatabaseError && err.position != null;\n\n return addDataToError(err, {\n sqlError,\n // If the error has a `position` field, we need to use the processed source\n // (where e.g. `$foobar` has been replaced with `$1`) so that the position\n // is accurate.\n sql: errorHasPosition ? paramsToArray(sql, params, false).processedSql : sql,\n sqlParams: params,\n });\n}\n\nexport class PostgresPool {\n /** The pool from which clients will be acquired. */\n private pool: pg.Pool | null = null;\n /**\n * We use this to propagate the client associated with the current transaction\n * to any nested queries. In the past, we had some nasty bugs associated with\n * the fact that we tried to acquire new clients inside of transactions, which\n * ultimately lead to a deadlock.\n */\n private alsClient = new AsyncLocalStorage<pg.PoolClient>();\n private searchSchema: string | null = null;\n /** Tracks the total number of queries executed by this pool. */\n private _queryCount = 0;\n private errorOnUnusedParameters = false;\n\n /**\n * Creates a new connection pool and attempts to connect to the database.\n */\n async initAsync(\n pgConfig: PostgresPoolConfig,\n idleErrorHandler: (error: Error, client: pg.PoolClient) => void,\n ): Promise<void> {\n if (this.pool != null) {\n throw new Error('Postgres pool already initialized');\n }\n this.errorOnUnusedParameters = pgConfig.errorOnUnusedParameters ?? false;\n this.pool = new pg.Pool(pgConfig);\n this.pool.on('error', function (err, client) {\n const lastQuery = lastQueryMap.get(client);\n idleErrorHandler(addDataToError(err, { lastQuery }), client);\n });\n this.pool.on('connect', (client) => {\n client.on('error', (err) => {\n const lastQuery = lastQueryMap.get(client);\n idleErrorHandler(addDataToError(err, { lastQuery }), client);\n });\n });\n this.pool.on('remove', (client) => {\n // This shouldn't be necessary, as `pg` currently allows clients to be\n // garbage collected after they're removed. However, if `pg` someday\n // starts reusing client objects across difference connections, this\n // will ensure that we re-set the search path when the client reconnects.\n searchSchemaMap.delete(client);\n });\n\n // Attempt to connect to the database so that we can fail quickly if\n // something isn't configured correctly.\n let retryCount = 0;\n const retryTimeouts = [500, 1000, 2000, 5000, 10000];\n while (retryCount <= retryTimeouts.length) {\n try {\n const client = await this.pool.connect();\n client.release();\n return;\n } catch (err: any) {\n if (retryCount === retryTimeouts.length) {\n throw new Error(`Could not connect to Postgres after ${retryTimeouts.length} attempts`, {\n cause: err,\n });\n }\n\n const timeout = retryTimeouts[retryCount];\n retryCount++;\n await new Promise((resolve) => setTimeout(resolve, timeout));\n }\n }\n }\n\n /**\n * Closes the connection pool.\n */\n async closeAsync(): Promise<void> {\n if (!this.pool) return;\n await this.pool.end();\n this.pool = null;\n }\n\n /**\n * Gets a new client from the connection pool. The caller MUST call `release()` to\n * release the client, whether or not errors occurred while using\n * `client`. The client can call `done(truthy_value)` to force\n * destruction of the client, but this should not be used except in\n * unusual circumstances.\n */\n async getClientAsync(): Promise<pg.PoolClient> {\n if (!this.pool) {\n throw new Error('Connection pool is not open');\n }\n\n // If we're inside a transaction, we'll reuse the same client to avoid a\n // potential deadlock.\n const client = this.alsClient.getStore() ?? (await this.pool.connect());\n\n // If we're configured to use a particular schema, we'll store whether or\n // not the search path has already been configured for this particular\n // client. If we acquire a client and it's already had its search path\n // set, we can avoid setting it again since the search path will persist\n // for the life of the client.\n //\n // We do this check for each call to `getClient` instead of on\n // `pool.connect` so that we don't have to be really careful about\n // destroying old clients that were created before `setSearchSchema` was\n // called. Instead, we'll just check if the search path matches the\n // currently-desired schema, and if it's a mismatch (or doesn't exist\n // at all), we re-set it for the current client.\n //\n // Note that this accidentally supports changing the search_path on the fly,\n // although that's not something we currently do (or would be likely to do).\n // It does NOT support clearing the existing search schema - e.g.,\n // `setSearchSchema(null)` would not work as you expect. This is fine, as\n // that's not something we ever do in practice.\n const clientSearchSchema = searchSchemaMap.get(client);\n if (this.searchSchema != null && clientSearchSchema !== this.searchSchema) {\n const setSearchPathSql = `SET search_path TO ${escapeIdentifier(this.searchSchema)},public`;\n try {\n await this.queryWithClientAsync(client, setSearchPathSql, {});\n } catch (err) {\n client.release();\n throw err;\n }\n searchSchemaMap.set(client, this.searchSchema);\n }\n\n return client;\n }\n\n /**\n * Performs a query with the given client.\n */\n async queryWithClientAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<pg.QueryResult> {\n this._queryCount += 1;\n debug('queryWithClient()', 'sql:', debugString(sql));\n debug('queryWithClient()', 'params:', debugParams(params));\n const { processedSql, paramsArray } = paramsToArray(sql, params, this.errorOnUnusedParameters);\n try {\n lastQueryMap.set(client, processedSql);\n const result = await client.query(processedSql, paramsArray);\n debug('queryWithClient() success', 'rowCount:', result.rowCount);\n return result;\n } catch (err: any) {\n throw enhanceError(err, sql, params);\n }\n }\n\n /**\n * Performs a query with the given client. Errors if the query returns more\n * than one row.\n */\n async queryWithClientOneRowAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<pg.QueryResult> {\n debug('queryWithClientOneRow()', 'sql:', debugString(sql));\n debug('queryWithClientOneRow()', 'params:', debugParams(params));\n const result = await this.queryWithClientAsync(client, sql, params);\n if (result.rowCount !== 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n result,\n });\n }\n debug('queryWithClientOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Performs a query with the given client. Errors if the query returns more\n * than one row.\n */\n async queryWithClientZeroOrOneRowAsync(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<QueryResult> {\n debug('queryWithClientZeroOrOneRow()', 'sql:', debugString(sql));\n debug('queryWithClientZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.queryWithClientAsync(client, sql, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n result,\n });\n }\n debug('queryWithClientZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Rolls back the current transaction for the given client.\n */\n async rollbackWithClientAsync(client: pg.PoolClient) {\n debug('rollbackWithClient()');\n // From https://node-postgres.com/features/transactions\n try {\n await client.query('ROLLBACK');\n // Only release the client if we weren't already inside a transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n } catch (err: any) {\n // If there was a problem rolling back the query, something is\n // seriously messed up. Return the error to the release() function to\n // close & remove this client from the pool. If you leave a client in\n // the pool with an unaborted transaction, weird and hard to diagnose\n // problems might happen.\n client.release(err);\n }\n }\n\n /**\n * Begins a new transaction.\n */\n async beginTransactionAsync(): Promise<pg.PoolClient> {\n debug('beginTransaction()');\n const client = await this.getClientAsync();\n try {\n await this.queryWithClientAsync(client, 'START TRANSACTION;', {});\n return client;\n } catch (err) {\n await this.rollbackWithClientAsync(client);\n throw err;\n }\n }\n\n /**\n * Commits the transaction if err is null, otherwise rollbacks the transaction.\n * Also releases the client.\n */\n async endTransactionAsync(client: pg.PoolClient, err: Error | null | undefined) {\n debug('endTransaction()');\n if (err) {\n try {\n await this.rollbackWithClientAsync(client);\n } catch (rollbackErr: any) {\n throw addDataToError(rollbackErr, { prevErr: err, rollback: 'fail' });\n }\n\n // Even though we successfully rolled back the transaction, there was\n // still an error in the first place that necessitated a rollback. Re-throw\n // that error here so that everything downstream of here will know about it.\n throw addDataToError(err, { rollback: 'success' });\n } else {\n try {\n await this.queryWithClientAsync(client, 'COMMIT', {});\n } finally {\n // Only release the client if we aren't nested inside another transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n }\n }\n }\n\n /**\n * Runs the specified function inside of a transaction. The function will\n * receive a database client as an argument, but it can also make queries\n * as usual, and the correct client will be used automatically.\n *\n * The transaction will be rolled back if the function throws an error, and\n * will be committed otherwise.\n */\n async runInTransactionAsync<T>(fn: (client: pg.PoolClient) => Promise<T>): Promise<T> {\n // Check if we're already inside a transaction. If so, we won't start another one,\n // as Postgres doesn't support nested transactions.\n const client = this.alsClient.getStore();\n const isNestedTransaction = client !== undefined;\n const transactionClient = client ?? (await this.beginTransactionAsync());\n\n let result: T;\n try {\n result = await this.alsClient.run(transactionClient, () => fn(transactionClient));\n } catch (err: any) {\n if (!isNestedTransaction) {\n // If we're inside another transaction, we assume that the root transaction\n // will catch this error and roll back the transaction.\n await this.endTransactionAsync(transactionClient, err);\n }\n throw err;\n }\n\n if (!isNestedTransaction) {\n // If we're inside another transaction; don't commit it prematurely. Allow\n // the root transaction to commit it instead.\n //\n // Note that we don't invoke `endTransactionAsync` inside the `try` block\n // because we don't want an error thrown by it to trigger *another* call\n // to `endTransactionAsync` in the `catch` block.\n await this.endTransactionAsync(transactionClient, null);\n }\n\n return result;\n }\n\n /**\n * Executes a query with the specified parameters.\n *\n * @deprecated Use {@link execute} instead.\n *\n * Using the return value of this function directly is not recommended. Instead, use\n * {@link queryRows}, {@link queryRow}, or {@link queryOptionalRow}.\n */\n async queryAsync(sql: string, params: QueryParams): Promise<QueryResult> {\n debug('query()', 'sql:', debugString(sql));\n debug('query()', 'params:', debugParams(params));\n const client = await this.getClientAsync();\n try {\n return await this.queryWithClientAsync(client, sql, params);\n } finally {\n // Only release if we aren't nested in a transaction.\n if (this.alsClient.getStore() === undefined) {\n client.release();\n }\n }\n }\n\n /**\n * Executes a query with the specified parameters. Errors if the query does\n * not return exactly one row.\n *\n * @deprecated Use {@link executeRow} or {@link queryRow} instead.\n */\n async queryOneRowAsync(sql: string, params: QueryParams): Promise<pg.QueryResult> {\n debug('queryOneRow()', 'sql:', debugString(sql));\n debug('queryOneRow()', 'params:', debugParams(params));\n const result = await this.queryAsync(sql, params);\n if (result.rowCount !== 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n });\n }\n debug('queryOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Executes a query with the specified parameters. Errors if the query\n * returns more than one row.\n */\n async queryZeroOrOneRowAsync(sql: string, params: QueryParams): Promise<pg.QueryResult> {\n debug('queryZeroOrOneRow()', 'sql:', debugString(sql));\n debug('queryZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.queryAsync(sql, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError(`Incorrect rowCount: ${result.rowCount}`, {\n sql,\n sqlParams: params,\n });\n }\n debug('queryZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters.\n */\n async callAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('call()', 'function:', functionName);\n debug('call()', 'params:', debugParams(params));\n const placeholders = params.map((_, v) => '$' + (v + 1)).join(',');\n const sql = `SELECT * FROM ${escapeIdentifier(functionName)}(${placeholders});`;\n const result = await this.queryAsync(sql, params);\n debug('call() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters. Errors if the\n * sproc does not return exactly one row.\n */\n async callOneRowAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('callOneRow()', 'function:', functionName);\n debug('callOneRow()', 'params:', debugParams(params));\n const result = await this.callAsync(functionName, params);\n if (result.rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls the given sproc with the specified parameters. Errors if the\n * sproc returns more than one row.\n */\n async callZeroOrOneRowAsync(functionName: string, params: any[]): Promise<pg.QueryResult> {\n debug('callZeroOrOneRow()', 'function:', functionName);\n debug('callZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.callAsync(functionName, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a sproc with the specified parameters using a specific client.\n */\n async callWithClientAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClient()', 'function:', functionName);\n debug('callWithClient()', 'params:', debugParams(params));\n const placeholders = params.map((_, v) => '$' + (v + 1)).join(',');\n const sql = `SELECT * FROM ${escapeIdentifier(functionName)}(${placeholders})`;\n const result = await this.queryWithClientAsync(client, sql, params);\n debug('callWithClient() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a sproc with the specified parameters using a specific client.\n * Errors if the sproc does not return exactly one row.\n */\n async callWithClientOneRowAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClientOneRow()', 'function:', functionName);\n debug('callWithClientOneRow()', 'params:', debugParams(params));\n const result = await this.callWithClientAsync(client, functionName, params);\n if (result.rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callWithClientOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n /**\n * Calls a function with the specified parameters using a specific client.\n * Errors if the sproc returns more than one row.\n */\n async callWithClientZeroOrOneRowAsync(\n client: pg.PoolClient,\n functionName: string,\n params: any[],\n ): Promise<pg.QueryResult> {\n debug('callWithClientZeroOrOneRow()', 'function:', functionName);\n debug('callWithClientZeroOrOneRow()', 'params:', debugParams(params));\n const result = await this.callWithClientAsync(client, functionName, params);\n if (result.rowCount == null || result.rowCount > 1) {\n throw new PostgresError('Incorrect rowCount: ' + result.rowCount, {\n functionName,\n sqlParams: params,\n });\n }\n debug('callWithClientZeroOrOneRow() success', 'rowCount:', result.rowCount);\n return result;\n }\n\n async queryRows<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>[]>;\n async queryRows<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model>[]>;\n /**\n * Executes a query with the specified parameters. Returns an array of rows\n * that conform to the given Zod schema.\n *\n * If the query returns a single column, the return value will be a list of column values.\n */\n async queryRows<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n const rawData = results.rows.map((row) => row[columnName]);\n return z.array(model).parse(rawData);\n } else {\n return z.array(model).parse(results.rows);\n }\n }\n\n async queryRow<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>>;\n async queryRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model>>;\n /**\n * Executes a query with the specified parameters. Returns exactly one row that conforms to the given Zod schema.\n *\n * If the query returns a single column, the return value will be the column value itself.\n */\n async queryRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryOneRowAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n /**\n * Executes a query with the specified parameters. Returns either null or a\n * single row that conforms to the given Zod schema, and errors otherwise.\n *\n * If the query returns a single column, the return value will be the column value itself.\n */\n async queryOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: QueryParams | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.queryZeroOrOneRowAsync(sql, params);\n if (results.rows.length === 0) {\n return null;\n } else if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async callRows<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>[]>;\n async callRows<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model>[]>;\n /**\n * Calls the given sproc with the specified parameters.\n * Errors if the sproc does not return anything.\n */\n async callRows<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n const rawData = results.rows.map((row) => row[columnName]);\n return z.array(model).parse(rawData);\n } else {\n return z.array(model).parse(results.rows);\n }\n }\n\n async callRow<Model extends z.ZodTypeAny>(sql: string, model: Model): Promise<z.infer<Model>>;\n async callRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model>>;\n /**\n * Calls the given sproc with the specified parameters.\n * Returns exactly one row from the sproc that conforms to the given Zod schema.\n */\n async callRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callOneRowAsync(sql, params);\n if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<z.infer<Model> | null>;\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n params: any[],\n model: Model,\n ): Promise<z.infer<Model> | null>;\n /**\n * Calls the given sproc with the specified parameters. Returns either null\n * or a single row that conforms to the given Zod schema.\n */\n async callOptionalRow<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: any[] | Model,\n maybeModel?: Model,\n ) {\n const params = maybeModel === undefined ? [] : (paramsOrSchema as any[]);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n const results = await this.callZeroOrOneRowAsync(sql, params);\n if (results.rows.length === 0) {\n return null;\n } else if (results.fields.length === 1) {\n const columnName = results.fields[0].name;\n return model.parse(results.rows[0][columnName]);\n } else {\n return model.parse(results.rows[0]);\n }\n }\n\n /**\n * Executes a query with the specified parameters. Returns the number of rows affected.\n */\n async execute(sql: string, params: QueryParams = {}): Promise<number> {\n const result = await this.queryAsync(sql, params);\n return result.rowCount ?? 0;\n }\n\n /**\n * Executes a query with the specified parameter, and errors if the query doesn't return exactly one row.\n */\n async executeRow(sql: string, params: QueryParams = {}) {\n const rowCount = await this.execute(sql, params);\n if (rowCount !== 1) {\n throw new PostgresError('Incorrect rowCount: ' + rowCount, {\n sql,\n sqlParams: params,\n });\n }\n }\n\n /**\n * Returns a {@link Cursor} for the given query. The cursor can be used to\n * read results in batches, which is useful for large result sets.\n */\n private async queryCursorWithClient(\n client: pg.PoolClient,\n sql: string,\n params: QueryParams,\n ): Promise<Cursor> {\n this._queryCount += 1;\n debug('queryCursorWithClient()', 'sql:', debugString(sql));\n debug('queryCursorWithClient()', 'params:', debugParams(params));\n const { processedSql, paramsArray } = paramsToArray(sql, params, this.errorOnUnusedParameters);\n lastQueryMap.set(client, processedSql);\n return client.query(new Cursor(processedSql, paramsArray));\n }\n\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n model: Model,\n ): Promise<CursorIterator<z.infer<Model>>>;\n\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model: Model,\n ): Promise<CursorIterator<z.infer<Model>>>;\n\n /**\n * Returns an {@link CursorIterator} that can be used to iterate over the\n * results of the query in batches, which is useful for large result sets.\n * Each row will be parsed by the given Zod schema.\n */\n async queryCursor<Model extends z.ZodTypeAny>(\n sql: string,\n paramsOrSchema: Model | QueryParams,\n maybeModel?: Model,\n ): Promise<CursorIterator<z.infer<Model>>> {\n const params = maybeModel === undefined ? {} : (paramsOrSchema as QueryParams);\n const model = maybeModel === undefined ? (paramsOrSchema as Model) : maybeModel;\n return this.queryCursorInternal(sql, params, model);\n }\n\n private async queryCursorInternal<Model extends z.ZodTypeAny>(\n sql: string,\n params: QueryParams,\n model?: Model,\n ): Promise<CursorIterator<z.infer<Model>>> {\n const client = await this.getClientAsync();\n const cursor = await this.queryCursorWithClient(client, sql, params);\n\n let iterateCalled = false;\n let rowKeys: string[] | null = null;\n const iterator: CursorIterator<z.infer<Model>> = {\n async *iterate(batchSize: number) {\n // Safety check: if someone calls iterate multiple times, they're\n // definitely doing something wrong.\n if (iterateCalled) {\n throw new Error('iterate() called multiple times');\n }\n iterateCalled = true;\n\n try {\n while (true) {\n const rows = await cursor.read(batchSize);\n if (rows.length === 0) {\n break;\n }\n\n if (rowKeys === null) {\n rowKeys = Object.keys(rows[0] ?? {});\n }\n const flattened =\n rowKeys.length === 1 ? rows.map((row) => row[(rowKeys as string[])[0]]) : rows;\n if (model) {\n yield z.array(model).parse(flattened);\n } else {\n yield flattened;\n }\n }\n } catch (err: any) {\n throw enhanceError(err, sql, params);\n } finally {\n try {\n await cursor.close();\n } finally {\n client.release();\n }\n }\n },\n stream(batchSize: number) {\n const transform = new Transform({\n readableObjectMode: true,\n writableObjectMode: true,\n transform(chunk, _encoding, callback) {\n for (const row of chunk) {\n this.push(row);\n }\n callback();\n },\n });\n\n // TODO: use native `node:stream#compose` once it's stable.\n const generator = iterator.iterate(batchSize);\n const pipe = multipipe(Readable.from(generator), transform);\n\n // When the underlying stream is closed, we need to make sure that the\n // cursor is also closed. We do this by calling `return()` on the generator,\n // which will trigger its `finally` block, which will in turn release\n // the client and close the cursor. The fact that the stream is already\n // closed by this point means that someone reading from the stream will\n // never actually see the `null` value that's returned.\n pipe.once('close', () => {\n generator.return(null);\n });\n\n return pipe;\n },\n };\n return iterator;\n }\n\n /**\n * Set the schema to use for the search path.\n *\n * @param schema The schema name to use (can be \"null\" to unset the search path)\n */\n async setSearchSchema(schema: string | null) {\n if (schema == null) {\n this.searchSchema = schema;\n return;\n }\n\n await this.queryAsync(`CREATE SCHEMA IF NOT EXISTS ${escapeIdentifier(schema)}`, {});\n // We only set searchSchema after CREATE to avoid the above query() call using searchSchema.\n this.searchSchema = schema;\n }\n\n /**\n * Get the schema that is currently used for the search path.\n *\n * @returns schema in use (may be `null` to indicate no schema)\n */\n getSearchSchema(): string | null {\n return this.searchSchema;\n }\n\n /**\n * Generate, set, and return a random schema name.\n *\n * @param prefix The prefix of the new schema, only the first 28 characters will be used (after lowercasing).\n * @returns The randomly-generated search schema.\n */\n async setRandomSearchSchemaAsync(prefix: string): Promise<string> {\n // truncated prefix (max 28 characters)\n const truncPrefix = prefix.slice(0, 28);\n // timestamp in format YYYY-MM-DDTHH:MM:SS.SSSZ (guaranteed to not exceed 27 characters in the spec)\n const timestamp = new Date().toISOString();\n // random 6-character suffix to avoid clashes (approx 2 billion possible values)\n const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');\n const suffix = Array.from({ length: 6 })\n .map(() => chars[Math.floor(Math.random() * chars.length)])\n .join('');\n\n // Schema is guaranteed to have length at most 63 (= 28 + 1 + 27 + 1 + 6),\n // which is the default PostgreSQL identifier limit.\n // Note that this schema name will need quoting because of characters like ':', '-', etc\n const schema = `${truncPrefix}_${timestamp}_${suffix}`;\n await this.setSearchSchema(schema);\n return schema;\n }\n\n /**\n * Deletes all schemas starting with the given prefix.\n *\n * @param prefix The prefix of the schemas to delete.\n */\n async clearSchemasStartingWith(prefix: string): Promise<void> {\n // Sanity check against deleting public, pg_, information_schema, etc.\n if (prefix === 'public' || prefix.startsWith('pg_') || prefix === 'information_schema') {\n throw new Error(`Cannot clear schema starting with ${prefix}`);\n }\n // Sanity check against a bad prefix.\n if (prefix.length < 4) {\n throw new Error(`Prefix is too short: ${prefix}`);\n }\n\n await this.queryAsync(\n `DO $$\n DECLARE\n r RECORD;\n BEGIN\n FOR r IN\n SELECT nspname\n FROM pg_namespace\n WHERE nspname LIKE ${escapeLiteral(prefix + '%')}\n AND nspname NOT LIKE 'pg_temp_%'\n LOOP\n EXECUTE format('DROP SCHEMA IF EXISTS %I CASCADE;', r.nspname);\n COMMIT; -- avoid shared memory exhaustion\n END LOOP;\n END $$;`,\n {},\n );\n }\n\n /** The number of established connections. */\n get totalCount() {\n return this.pool?.totalCount ?? 0;\n }\n\n /** The number of idle connections. */\n get idleCount() {\n return this.pool?.idleCount ?? 0;\n }\n\n /** The number of queries waiting for a connection to become available. */\n get waitingCount() {\n return this.pool?.waitingCount ?? 0;\n }\n\n /** The total number of queries that have been executed by this pool. */\n get queryCount() {\n return this._queryCount;\n }\n}\n"]}
|
package/dist/pool.test.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool.test.d.ts","sourceRoot":"","sources":["../src/pool.test.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"pool.test.d.ts","sourceRoot":"","sources":["../src/pool.test.ts"],"names":[],"mappings":"","sourcesContent":["import { Writable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\n\nimport { afterAll, assert, beforeAll, describe, expect, it } from 'vitest';\nimport { ZodError, z } from 'zod';\n\nimport {\n callOptionalRow,\n callRow,\n callRows,\n execute,\n queryAsync,\n queryCursor,\n queryOptionalRow,\n queryRow,\n queryRows,\n} from './default-pool.js';\nimport { makePostgresTestUtils } from './test-utils.js';\n\nconst postgresTestUtils = makePostgresTestUtils({\n database: 'prairielearn_postgres',\n});\n\nconst WorkspaceSchema = z.object({\n id: z.string(),\n created_at: z.date(),\n});\n\nconst SprocTwoColumnsSchema = z.object({\n id: z.string(),\n negative: z.number(),\n});\n\ndescribe('@prairielearn/postgres', function () {\n beforeAll(async () => {\n await postgresTestUtils.createDatabase();\n await execute(\n 'CREATE TABLE workspaces (id BIGSERIAL PRIMARY KEY, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP);',\n );\n await execute('INSERT INTO workspaces (id) SELECT s FROM generate_series(1, 100) AS s');\n await execute(\n 'CREATE FUNCTION test_sproc_one_column(num_entries INT) RETURNS TABLE (id BIGINT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id FROM generate_series(1, num_entries) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_two_columns(num_entries INT) RETURNS TABLE (id BIGINT, negative INT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id, -s AS negative FROM generate_series(1, num_entries) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_one_column_ten_rows() RETURNS TABLE (id BIGINT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id FROM generate_series(1, 10) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_one_column_one_row(OUT id BIGINT) AS $$ BEGIN id = 1; END; $$ LANGUAGE plpgsql;',\n );\n });\n\n afterAll(async () => {\n await postgresTestUtils.dropDatabase();\n });\n\n describe('paramsToArray', () => {\n it('enforces SQL must be a string', async () => {\n // @ts-expect-error SQL must be a string\n const rows = queryAsync({ invalid: true }, {});\n await expect(rows).rejects.toThrow('SQL must be a string');\n });\n\n it('enforces params must be array or object', async () => {\n // @ts-expect-error params must be an array or object\n const rows = queryAsync('SELECT 33;', 33);\n await expect(rows).rejects.toThrow('params must be array or object');\n });\n\n it('rejects missing parameters', async () => {\n const rows = queryAsync('SELECT $missing;', {});\n await expect(rows).rejects.toThrow('Missing parameter');\n });\n\n it('rejects unused parameters in testing', async () => {\n const rows = queryAsync('SELECT 33;', { unsed_parameter: true });\n await expect(rows).rejects.toThrow('Unused parameter');\n });\n });\n\n describe('queryRows', () => {\n it('handles single column', async () => {\n const rows = await queryRows('SELECT id FROM workspaces WHERE id <= 10;', z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const rows = await queryRows('SELECT * FROM workspaces WHERE id <= 10;', WorkspaceSchema);\n assert.lengthOf(rows, 10);\n assert.equal(rows[0].id, '1');\n assert.isNotNull(rows[0].created_at);\n });\n\n it('handles parameters', async () => {\n const rows = await queryRows(\n 'SELECT * FROM workspaces WHERE id <= $1;',\n [10],\n WorkspaceSchema,\n );\n assert.lengthOf(rows, 10);\n });\n });\n\n describe('queryRow', () => {\n it('handles single column', async () => {\n const row = await queryRow('SELECT id FROM workspaces WHERE id = 1;', z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await queryRow('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n assert.equal(row.id, '1');\n assert.isNotNull(row.created_at);\n });\n\n it('handles parameters', async () => {\n const row = await queryRow('SELECT * FROM workspaces WHERE id = $1;', [1], WorkspaceSchema);\n assert.equal(row.id, '1');\n });\n\n it('rejects results with zero rows', async () => {\n const rows = queryRow('SELECT * FROM workspaces WHERE id = -1;', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 0');\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = queryRow('SELECT * FROM workspaces', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('queryOptionalRow', () => {\n it('handles single column', async () => {\n const row = await queryRow('SELECT id FROM workspaces WHERE id = 1;', z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await queryOptionalRow('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n assert.isNotNull(row?.created_at);\n });\n\n it('handles parameters', async () => {\n const row = await queryOptionalRow(\n 'SELECT * FROM workspaces WHERE id = $1;',\n [1],\n WorkspaceSchema,\n );\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n });\n\n it('handles missing result', async () => {\n const row = await queryOptionalRow(\n 'SELECT * FROM workspaces WHERE id = -1;',\n WorkspaceSchema,\n );\n assert.isNull(row);\n });\n\n it('rejects with multiple rows', async () => {\n const rows = queryOptionalRow('SELECT * FROM workspaces', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('callRows', () => {\n it('handles single column', async () => {\n const rows = await callRows('test_sproc_one_column_ten_rows', z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles parameters', async () => {\n const rows = await callRows('test_sproc_one_column', [10], z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const rows = await callRows('test_sproc_two_columns', [20], SprocTwoColumnsSchema);\n assert.lengthOf(rows, 20);\n assert.equal(rows[0].id, '1');\n assert.equal(rows[0].negative, -1);\n assert.equal(rows[19].id, '20');\n assert.equal(rows[19].negative, -20);\n });\n });\n\n describe('callRow', () => {\n it('handles single column', async () => {\n const row = await callRow('test_sproc_one_column_one_row', z.string());\n assert.equal(row, '1');\n });\n\n it('handles parameters', async () => {\n const row = await callRow('test_sproc_one_column', [1], z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await callRow('test_sproc_two_columns', [1], SprocTwoColumnsSchema);\n assert.equal(row.id, '1');\n assert.equal(row.negative, -1);\n });\n\n it('rejects results with zero rows', async () => {\n const row = callRow('test_sproc_two_columns', [0], SprocTwoColumnsSchema);\n await expect(row).rejects.toThrow('Incorrect rowCount: 0');\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = callRow('test_sproc_two_columns', [100], SprocTwoColumnsSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('callOptionalRow', () => {\n it('handles single column', async () => {\n const row = await callOptionalRow('test_sproc_one_column_one_row', z.string());\n assert.equal(row, '1');\n });\n\n it('handles parameters', async () => {\n const row = await callOptionalRow('test_sproc_one_column', [1], z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await callOptionalRow('test_sproc_two_columns', [1], SprocTwoColumnsSchema);\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n assert.equal(row?.negative, -1);\n });\n\n it('handles results with zero rows', async () => {\n const row = await callOptionalRow('test_sproc_two_columns', [0], SprocTwoColumnsSchema);\n assert.isNull(row);\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = callOptionalRow('test_sproc_two_columns', [100], SprocTwoColumnsSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('queryCursor', () => {\n it('handles single column', async () => {\n const cursor = await queryCursor('SELECT id FROM workspaces WHERE id = 1;', z.string());\n const allRows: string[] = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.equal(allRows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n const allRows: z.infer<typeof WorkspaceSchema>[] = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.equal(allRows[0].id, '1');\n assert.isNotNull(allRows[0].created_at);\n });\n it('returns zero rows', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id = 10000;', z.unknown());\n const rowBatches = [];\n for await (const rows of cursor.iterate(10)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 0);\n });\n\n it('returns one row at a time', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id <= 2;', z.unknown());\n const rowBatches = [];\n for await (const rows of cursor.iterate(1)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 2);\n assert.lengthOf(rowBatches[0], 1);\n assert.lengthOf(rowBatches[1], 1);\n });\n\n it('returns all rows at once', async () => {\n const cursor = queryCursor('SELECT * FROM workspaces WHERE id <= 10;', z.unknown());\n const rowBatches = [];\n for await (const rows of (await cursor).iterate(10)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 1);\n assert.lengthOf(rowBatches[0], 10);\n });\n\n it('handles errors', async () => {\n const cursor = await queryCursor('NOT VALID SQL', z.unknown());\n\n async function readAllRows() {\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, Error);\n assert.match(maybeError.message, /syntax error/);\n assert.isDefined((maybeError as any).data);\n assert.equal((maybeError as any).data.sql, 'NOT VALID SQL');\n assert.deepEqual((maybeError as any).data.sqlParams, {});\n assert.isDefined((maybeError as any).data.sqlError);\n assert.equal((maybeError as any).data.sqlError.severity, 'ERROR');\n });\n });\n\n describe('queryCursor', () => {\n const WorkspaceSchema = z.object({\n id: z.string(),\n });\n\n const BadWorkspaceSchema = z.object({\n badProperty: z.string(),\n });\n\n describe('iterator', () => {\n it('validates with provided schema', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n WorkspaceSchema,\n );\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.lengthOf(allRows, 10);\n const workspace = allRows[0] as any;\n assert.equal(workspace.id, '1');\n assert.isUndefined(workspace.state);\n });\n\n it('throws error when validation fails', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n BadWorkspaceSchema,\n );\n\n async function readAllRows() {\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, ZodError);\n assert.lengthOf(maybeError.errors, 10);\n });\n });\n\n describe('stream', () => {\n it('validates with provided schema', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n WorkspaceSchema,\n );\n const stream = cursor.stream(1);\n const allRows = [];\n for await (const row of stream) {\n allRows.push(row);\n }\n\n assert.lengthOf(allRows, 10);\n });\n\n it('emits an error when validation fails', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces ORDER BY id ASC;',\n BadWorkspaceSchema,\n );\n const stream = cursor.stream(1);\n\n async function readAllRows() {\n const allRows = [];\n for await (const row of stream) {\n allRows.push(row);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, ZodError);\n assert.lengthOf(maybeError.errors, 1);\n });\n\n it('closes the cursor when the stream is closed', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces;', WorkspaceSchema);\n const stream = cursor.stream(1);\n\n const rows: any[] = [];\n const ac = new AbortController();\n const writable = new Writable({\n objectMode: true,\n write(chunk, _encoding, callback) {\n rows.push(chunk);\n\n // After receiving the first row, abort the stream. This lets us test\n // that the underlying cursor is closed. If it is *not* closed, this\n // `after` hook will fail with a timeout.\n ac.abort();\n callback();\n },\n });\n\n await expect(pipeline(stream, writable, { signal: ac.signal })).rejects.toThrow();\n assert.lengthOf(rows, 1);\n });\n });\n });\n});\n"]}
|
package/dist/pool.test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool.test.js","sourceRoot":"","sources":["../src/pool.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAEhD,OAAO,EAAE,QAAQ,EAAE,MAAM,EA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,CAAC;YAC3B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { Writable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\n\nimport { afterAll, assert, beforeAll, describe, expect, it } from 'vitest';\nimport { ZodError, z } from 'zod';\n\nimport {\n callOptionalRow,\n callRow,\n callRows,\n execute,\n queryAsync,\n queryCursor,\n queryOptionalRow,\n queryRow,\n queryRows,\n} from './default-pool.js';\nimport { makePostgresTestUtils } from './test-utils.js';\n\nconst postgresTestUtils = makePostgresTestUtils({\n database: 'prairielearn_postgres',\n});\n\nconst WorkspaceSchema = z.object({\n id: z.string(),\n created_at: z.date(),\n});\n\nconst SprocTwoColumnsSchema = z.object({\n id: z.string(),\n negative: z.number(),\n});\n\ndescribe('@prairielearn/postgres', function () {\n beforeAll(async () => {\n await postgresTestUtils.createDatabase();\n await execute(\n 'CREATE TABLE workspaces (id BIGSERIAL PRIMARY KEY, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP);',\n );\n await execute('INSERT INTO workspaces (id) SELECT s FROM generate_series(1, 100) AS s');\n await execute(\n 'CREATE FUNCTION test_sproc_one_column(num_entries INT) RETURNS TABLE (id BIGINT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id FROM generate_series(1, num_entries) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_two_columns(num_entries INT) RETURNS TABLE (id BIGINT, negative INT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id, -s AS negative FROM generate_series(1, num_entries) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_one_column_ten_rows() RETURNS TABLE (id BIGINT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id FROM generate_series(1, 10) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_one_column_one_row(OUT id BIGINT) AS $$ BEGIN id = 1; END; $$ LANGUAGE plpgsql;',\n );\n });\n\n afterAll(async () => {\n await postgresTestUtils.dropDatabase();\n });\n\n describe('paramsToArray', () => {\n it('enforces SQL must be a string', async () => {\n // @ts-expect-error SQL must be a string\n const rows = queryAsync({ invalid: true }, {});\n await expect(rows).rejects.toThrow('SQL must be a string');\n });\n\n it('enforces params must be array or object', async () => {\n // @ts-expect-error params must be an array or object\n const rows = queryAsync('SELECT 33;', 33);\n await expect(rows).rejects.toThrow('params must be array or object');\n });\n\n it('rejects missing parameters', async () => {\n const rows = queryAsync('SELECT $missing;', {});\n await expect(rows).rejects.toThrow('Missing parameter');\n });\n\n it('rejects unused parameters in testing', async () => {\n const rows = queryAsync('SELECT 33;', { unsed_parameter: true });\n await expect(rows).rejects.toThrow('Unused parameter');\n });\n });\n\n describe('queryRows', () => {\n it('handles single column', async () => {\n const rows = await queryRows('SELECT id FROM workspaces WHERE id <= 10;', z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const rows = await queryRows('SELECT * FROM workspaces WHERE id <= 10;', WorkspaceSchema);\n assert.lengthOf(rows, 10);\n assert.equal(rows[0].id, '1');\n assert.isNotNull(rows[0].created_at);\n });\n\n it('handles parameters', async () => {\n const rows = await queryRows(\n 'SELECT * FROM workspaces WHERE id <= $1;',\n [10],\n WorkspaceSchema,\n );\n assert.lengthOf(rows, 10);\n });\n });\n\n describe('queryRow', () => {\n it('handles single column', async () => {\n const row = await queryRow('SELECT id FROM workspaces WHERE id = 1;', z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await queryRow('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n assert.equal(row.id, '1');\n assert.isNotNull(row.created_at);\n });\n\n it('handles parameters', async () => {\n const row = await queryRow('SELECT * FROM workspaces WHERE id = $1;', [1], WorkspaceSchema);\n assert.equal(row.id, '1');\n });\n\n it('rejects results with zero rows', async () => {\n const rows = queryRow('SELECT * FROM workspaces WHERE id = -1;', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 0');\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = queryRow('SELECT * FROM workspaces', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('queryOptionalRow', () => {\n it('handles single column', async () => {\n const row = await queryRow('SELECT id FROM workspaces WHERE id = 1;', z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await queryOptionalRow('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n assert.isNotNull(row?.created_at);\n });\n\n it('handles parameters', async () => {\n const row = await queryOptionalRow(\n 'SELECT * FROM workspaces WHERE id = $1;',\n [1],\n WorkspaceSchema,\n );\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n });\n\n it('handles missing result', async () => {\n const row = await queryOptionalRow(\n 'SELECT * FROM workspaces WHERE id = -1;',\n WorkspaceSchema,\n );\n assert.isNull(row);\n });\n\n it('rejects with multiple rows', async () => {\n const rows = queryOptionalRow('SELECT * FROM workspaces', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('callRows', () => {\n it('handles single column', async () => {\n const rows = await callRows('test_sproc_one_column_ten_rows', z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles parameters', async () => {\n const rows = await callRows('test_sproc_one_column', [10], z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const rows = await callRows('test_sproc_two_columns', [20], SprocTwoColumnsSchema);\n assert.lengthOf(rows, 20);\n assert.equal(rows[0].id, '1');\n assert.equal(rows[0].negative, -1);\n assert.equal(rows[19].id, '20');\n assert.equal(rows[19].negative, -20);\n });\n });\n\n describe('callRow', () => {\n it('handles single column', async () => {\n const row = await callRow('test_sproc_one_column_one_row', z.string());\n assert.equal(row, '1');\n });\n\n it('handles parameters', async () => {\n const row = await callRow('test_sproc_one_column', [1], z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await callRow('test_sproc_two_columns', [1], SprocTwoColumnsSchema);\n assert.equal(row.id, '1');\n assert.equal(row.negative, -1);\n });\n\n it('rejects results with zero rows', async () => {\n const row = callRow('test_sproc_two_columns', [0], SprocTwoColumnsSchema);\n await expect(row).rejects.toThrow('Incorrect rowCount: 0');\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = callRow('test_sproc_two_columns', [100], SprocTwoColumnsSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('callOptionalRow', () => {\n it('handles single column', async () => {\n const row = await callOptionalRow('test_sproc_one_column_one_row', z.string());\n assert.equal(row, '1');\n });\n\n it('handles parameters', async () => {\n const row = await callOptionalRow('test_sproc_one_column', [1], z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await callOptionalRow('test_sproc_two_columns', [1], SprocTwoColumnsSchema);\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n assert.equal(row?.negative, -1);\n });\n\n it('handles results with zero rows', async () => {\n const row = await callOptionalRow('test_sproc_two_columns', [0], SprocTwoColumnsSchema);\n assert.isNull(row);\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = callOptionalRow('test_sproc_two_columns', [100], SprocTwoColumnsSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('queryCursor', () => {\n it('handles single column', async () => {\n const cursor = await queryCursor('SELECT id FROM workspaces WHERE id = 1;', z.string());\n const allRows: string[] = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.equal(allRows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n const allRows: z.infer<typeof WorkspaceSchema>[] = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.equal(allRows[0].id, '1');\n assert.isNotNull(allRows[0].created_at);\n });\n it('returns zero rows', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id = 10000;', z.unknown());\n const rowBatches = [];\n for await (const rows of cursor.iterate(10)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 0);\n });\n\n it('returns one row at a time', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id <= 2;', z.unknown());\n const rowBatches = [];\n for await (const rows of cursor.iterate(1)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 2);\n assert.lengthOf(rowBatches[0], 1);\n assert.lengthOf(rowBatches[1], 1);\n });\n\n it('returns all rows at once', async () => {\n const cursor = queryCursor('SELECT * FROM workspaces WHERE id <= 10;', z.unknown());\n const rowBatches = [];\n for await (const rows of (await cursor).iterate(10)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 1);\n assert.lengthOf(rowBatches[0], 10);\n });\n\n it('handles errors', async () => {\n const cursor = await queryCursor('NOT VALID SQL', z.unknown());\n\n async function readAllRows() {\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, Error);\n assert.match(maybeError.message, /syntax error/);\n assert.isDefined((maybeError as any).data);\n assert.equal((maybeError as any).data.sql, 'NOT VALID SQL');\n assert.deepEqual((maybeError as any).data.sqlParams, {});\n assert.isDefined((maybeError as any).data.sqlError);\n assert.equal((maybeError as any).data.sqlError.severity, 'ERROR');\n });\n });\n\n describe('queryCursor', () => {\n const WorkspaceSchema = z.object({\n id: z.string(),\n });\n\n const BadWorkspaceSchema = z.object({\n badProperty: z.string(),\n });\n\n describe('iterator', () => {\n it('validates with provided schema', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n WorkspaceSchema,\n );\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.lengthOf(allRows, 10);\n const workspace = allRows[0] as any;\n assert.equal(workspace.id, '1');\n assert.isUndefined(workspace.state);\n });\n\n it('throws error when validation fails', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n BadWorkspaceSchema,\n );\n\n async function readAllRows() {\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, ZodError);\n assert.lengthOf(maybeError.errors, 10);\n });\n });\n\n describe('stream', () => {\n it('validates with provided schema', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n WorkspaceSchema,\n );\n const stream = cursor.stream(1);\n const allRows = [];\n for await (const row of stream) {\n allRows.push(row);\n }\n\n assert.lengthOf(allRows, 10);\n });\n\n it('emits an error when validation fails', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces ORDER BY id ASC;',\n BadWorkspaceSchema,\n );\n const stream = cursor.stream(1);\n\n async function readAllRows() {\n const allRows = [];\n for await (const row of stream) {\n allRows.push(row);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, ZodError);\n assert.lengthOf(maybeError.errors, 1);\n });\n\n it('closes the cursor when the stream is closed', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces;', WorkspaceSchema);\n const stream = cursor.stream(1);\n\n const rows: any[] = [];\n const ac = new AbortController();\n const writable = new Writable({\n objectMode: true,\n write(chunk, _encoding, callback) {\n rows.push(chunk);\n\n // After receiving the first row, abort the stream. This lets us test\n // that the underlying cursor is closed. If it is *not* closed, this\n // `after` hook will fail with a timeout.\n ac.abort();\n callback();\n },\n });\n\n await expect(pipeline(stream, writable, { signal: ac.signal })).rejects.toThrow();\n assert.lengthOf(rows, 1);\n });\n });\n });\n});\n"]}
|
|
1
|
+
{"version":3,"file":"pool.test.js","sourceRoot":"","sources":["../src/pool.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAEhD,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAElC,OAAO,EACL,eAAe,EACf,OAAO,EACP,QAAQ,EACR,OAAO,EACP,UAAU,EACV,WAAW,EACX,gBAAgB,EAChB,QAAQ,EACR,SAAS,GACV,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAExD,MAAM,iBAAiB,GAAG,qBAAqB,CAAC;IAC9C,QAAQ,EAAE,uBAAuB;CAClC,CAAC,CAAC;AAEH,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC;IAC/B,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE;IACd,UAAU,EAAE,CAAC,CAAC,IAAI,EAAE;CACrB,CAAC,CAAC;AAEH,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IACrC,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE;IACd,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;CACrB,CAAC,CAAC;AAEH,QAAQ,CAAC,wBAAwB,EAAE,YAAY;IAC7C,SAAS,CAAC,KAAK,IAAI,EAAE,CAAC;QACpB,MAAM,iBAAiB,CAAC,cAAc,EAAE,CAAC;QACzC,MAAM,OAAO,CACX,uGAAuG,CACxG,CAAC;QACF,MAAM,OAAO,CAAC,wEAAwE,CAAC,CAAC;QACxF,MAAM,OAAO,CAC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AC,MAAM,CAAC,CAAC,CAAC,CAAC;gBAEhC,MAAM,IAAI,GAAU,EAAE,CAAC;gBACvB,MAAM,EAAE,GAAG,IAAI,eAAe,EAAE,CAAC;gBACjC,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC;oBAC5B,UAAU,EAAE,IAAI;oBAChB,KAAK,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE;wBAChC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;wBAEjB,qEAAqE;wBACrE,oEAAoE;wBACpE,yCAAyC;wBACzC,EAAE,CAAC,KAAK,EAAE,CAAC;wBACX,QAAQ,EAAE,CAAC;oBAAA,CACZ;iBACF,CAAC,CAAC;gBAEH,MAAM,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;gBAClF,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;YAAA,CAC1B,CAAC,CAAC;QAAA,CACJ,CAAC,CAAC;IAAA,CACJ,CAAC,CAAC;AAAA,CACJ,CAAC,CAAC","sourcesContent":["import { Writable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\n\nimport { afterAll, assert, beforeAll, describe, expect, it } from 'vitest';\nimport { ZodError, z } from 'zod';\n\nimport {\n callOptionalRow,\n callRow,\n callRows,\n execute,\n queryAsync,\n queryCursor,\n queryOptionalRow,\n queryRow,\n queryRows,\n} from './default-pool.js';\nimport { makePostgresTestUtils } from './test-utils.js';\n\nconst postgresTestUtils = makePostgresTestUtils({\n database: 'prairielearn_postgres',\n});\n\nconst WorkspaceSchema = z.object({\n id: z.string(),\n created_at: z.date(),\n});\n\nconst SprocTwoColumnsSchema = z.object({\n id: z.string(),\n negative: z.number(),\n});\n\ndescribe('@prairielearn/postgres', function () {\n beforeAll(async () => {\n await postgresTestUtils.createDatabase();\n await execute(\n 'CREATE TABLE workspaces (id BIGSERIAL PRIMARY KEY, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP);',\n );\n await execute('INSERT INTO workspaces (id) SELECT s FROM generate_series(1, 100) AS s');\n await execute(\n 'CREATE FUNCTION test_sproc_one_column(num_entries INT) RETURNS TABLE (id BIGINT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id FROM generate_series(1, num_entries) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_two_columns(num_entries INT) RETURNS TABLE (id BIGINT, negative INT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id, -s AS negative FROM generate_series(1, num_entries) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_one_column_ten_rows() RETURNS TABLE (id BIGINT) AS $$ BEGIN RETURN QUERY SELECT s::BIGINT AS id FROM generate_series(1, 10) AS s; END; $$ LANGUAGE plpgsql;',\n );\n await execute(\n 'CREATE FUNCTION test_sproc_one_column_one_row(OUT id BIGINT) AS $$ BEGIN id = 1; END; $$ LANGUAGE plpgsql;',\n );\n });\n\n afterAll(async () => {\n await postgresTestUtils.dropDatabase();\n });\n\n describe('paramsToArray', () => {\n it('enforces SQL must be a string', async () => {\n // @ts-expect-error SQL must be a string\n const rows = queryAsync({ invalid: true }, {});\n await expect(rows).rejects.toThrow('SQL must be a string');\n });\n\n it('enforces params must be array or object', async () => {\n // @ts-expect-error params must be an array or object\n const rows = queryAsync('SELECT 33;', 33);\n await expect(rows).rejects.toThrow('params must be array or object');\n });\n\n it('rejects missing parameters', async () => {\n const rows = queryAsync('SELECT $missing;', {});\n await expect(rows).rejects.toThrow('Missing parameter');\n });\n\n it('rejects unused parameters in testing', async () => {\n const rows = queryAsync('SELECT 33;', { unsed_parameter: true });\n await expect(rows).rejects.toThrow('Unused parameter');\n });\n });\n\n describe('queryRows', () => {\n it('handles single column', async () => {\n const rows = await queryRows('SELECT id FROM workspaces WHERE id <= 10;', z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const rows = await queryRows('SELECT * FROM workspaces WHERE id <= 10;', WorkspaceSchema);\n assert.lengthOf(rows, 10);\n assert.equal(rows[0].id, '1');\n assert.isNotNull(rows[0].created_at);\n });\n\n it('handles parameters', async () => {\n const rows = await queryRows(\n 'SELECT * FROM workspaces WHERE id <= $1;',\n [10],\n WorkspaceSchema,\n );\n assert.lengthOf(rows, 10);\n });\n });\n\n describe('queryRow', () => {\n it('handles single column', async () => {\n const row = await queryRow('SELECT id FROM workspaces WHERE id = 1;', z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await queryRow('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n assert.equal(row.id, '1');\n assert.isNotNull(row.created_at);\n });\n\n it('handles parameters', async () => {\n const row = await queryRow('SELECT * FROM workspaces WHERE id = $1;', [1], WorkspaceSchema);\n assert.equal(row.id, '1');\n });\n\n it('rejects results with zero rows', async () => {\n const rows = queryRow('SELECT * FROM workspaces WHERE id = -1;', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 0');\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = queryRow('SELECT * FROM workspaces', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('queryOptionalRow', () => {\n it('handles single column', async () => {\n const row = await queryRow('SELECT id FROM workspaces WHERE id = 1;', z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await queryOptionalRow('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n assert.isNotNull(row?.created_at);\n });\n\n it('handles parameters', async () => {\n const row = await queryOptionalRow(\n 'SELECT * FROM workspaces WHERE id = $1;',\n [1],\n WorkspaceSchema,\n );\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n });\n\n it('handles missing result', async () => {\n const row = await queryOptionalRow(\n 'SELECT * FROM workspaces WHERE id = -1;',\n WorkspaceSchema,\n );\n assert.isNull(row);\n });\n\n it('rejects with multiple rows', async () => {\n const rows = queryOptionalRow('SELECT * FROM workspaces', WorkspaceSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('callRows', () => {\n it('handles single column', async () => {\n const rows = await callRows('test_sproc_one_column_ten_rows', z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles parameters', async () => {\n const rows = await callRows('test_sproc_one_column', [10], z.string());\n assert.lengthOf(rows, 10);\n assert.equal(rows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const rows = await callRows('test_sproc_two_columns', [20], SprocTwoColumnsSchema);\n assert.lengthOf(rows, 20);\n assert.equal(rows[0].id, '1');\n assert.equal(rows[0].negative, -1);\n assert.equal(rows[19].id, '20');\n assert.equal(rows[19].negative, -20);\n });\n });\n\n describe('callRow', () => {\n it('handles single column', async () => {\n const row = await callRow('test_sproc_one_column_one_row', z.string());\n assert.equal(row, '1');\n });\n\n it('handles parameters', async () => {\n const row = await callRow('test_sproc_one_column', [1], z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await callRow('test_sproc_two_columns', [1], SprocTwoColumnsSchema);\n assert.equal(row.id, '1');\n assert.equal(row.negative, -1);\n });\n\n it('rejects results with zero rows', async () => {\n const row = callRow('test_sproc_two_columns', [0], SprocTwoColumnsSchema);\n await expect(row).rejects.toThrow('Incorrect rowCount: 0');\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = callRow('test_sproc_two_columns', [100], SprocTwoColumnsSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('callOptionalRow', () => {\n it('handles single column', async () => {\n const row = await callOptionalRow('test_sproc_one_column_one_row', z.string());\n assert.equal(row, '1');\n });\n\n it('handles parameters', async () => {\n const row = await callOptionalRow('test_sproc_one_column', [1], z.string());\n assert.equal(row, '1');\n });\n\n it('handles multiple columns', async () => {\n const row = await callOptionalRow('test_sproc_two_columns', [1], SprocTwoColumnsSchema);\n assert.isNotNull(row);\n assert.equal(row?.id, '1');\n assert.equal(row?.negative, -1);\n });\n\n it('handles results with zero rows', async () => {\n const row = await callOptionalRow('test_sproc_two_columns', [0], SprocTwoColumnsSchema);\n assert.isNull(row);\n });\n\n it('rejects results with multiple rows', async () => {\n const rows = callOptionalRow('test_sproc_two_columns', [100], SprocTwoColumnsSchema);\n await expect(rows).rejects.toThrow('Incorrect rowCount: 100');\n });\n });\n\n describe('queryCursor', () => {\n it('handles single column', async () => {\n const cursor = await queryCursor('SELECT id FROM workspaces WHERE id = 1;', z.string());\n const allRows: string[] = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.equal(allRows[0], '1');\n });\n\n it('handles multiple columns', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id = 1;', WorkspaceSchema);\n const allRows: z.infer<typeof WorkspaceSchema>[] = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.equal(allRows[0].id, '1');\n assert.isNotNull(allRows[0].created_at);\n });\n it('returns zero rows', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id = 10000;', z.unknown());\n const rowBatches = [];\n for await (const rows of cursor.iterate(10)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 0);\n });\n\n it('returns one row at a time', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces WHERE id <= 2;', z.unknown());\n const rowBatches = [];\n for await (const rows of cursor.iterate(1)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 2);\n assert.lengthOf(rowBatches[0], 1);\n assert.lengthOf(rowBatches[1], 1);\n });\n\n it('returns all rows at once', async () => {\n const cursor = queryCursor('SELECT * FROM workspaces WHERE id <= 10;', z.unknown());\n const rowBatches = [];\n for await (const rows of (await cursor).iterate(10)) {\n rowBatches.push(rows);\n }\n assert.lengthOf(rowBatches, 1);\n assert.lengthOf(rowBatches[0], 10);\n });\n\n it('handles errors', async () => {\n const cursor = await queryCursor('NOT VALID SQL', z.unknown());\n\n async function readAllRows() {\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, Error);\n assert.match(maybeError.message, /syntax error/);\n assert.isDefined((maybeError as any).data);\n assert.equal((maybeError as any).data.sql, 'NOT VALID SQL');\n assert.deepEqual((maybeError as any).data.sqlParams, {});\n assert.isDefined((maybeError as any).data.sqlError);\n assert.equal((maybeError as any).data.sqlError.severity, 'ERROR');\n });\n });\n\n describe('queryCursor', () => {\n const WorkspaceSchema = z.object({\n id: z.string(),\n });\n\n const BadWorkspaceSchema = z.object({\n badProperty: z.string(),\n });\n\n describe('iterator', () => {\n it('validates with provided schema', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n WorkspaceSchema,\n );\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n assert.lengthOf(allRows, 10);\n const workspace = allRows[0] as any;\n assert.equal(workspace.id, '1');\n assert.isUndefined(workspace.state);\n });\n\n it('throws error when validation fails', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n BadWorkspaceSchema,\n );\n\n async function readAllRows() {\n const allRows = [];\n for await (const rows of cursor.iterate(10)) {\n allRows.push(...rows);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, ZodError);\n assert.lengthOf(maybeError.errors, 10);\n });\n });\n\n describe('stream', () => {\n it('validates with provided schema', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces WHERE id <= 10 ORDER BY id ASC;',\n WorkspaceSchema,\n );\n const stream = cursor.stream(1);\n const allRows = [];\n for await (const row of stream) {\n allRows.push(row);\n }\n\n assert.lengthOf(allRows, 10);\n });\n\n it('emits an error when validation fails', async () => {\n const cursor = await queryCursor(\n 'SELECT * FROM workspaces ORDER BY id ASC;',\n BadWorkspaceSchema,\n );\n const stream = cursor.stream(1);\n\n async function readAllRows() {\n const allRows = [];\n for await (const row of stream) {\n allRows.push(row);\n }\n return allRows;\n }\n\n const maybeError = await readAllRows().catch((err) => err);\n assert.instanceOf(maybeError, ZodError);\n assert.lengthOf(maybeError.errors, 1);\n });\n\n it('closes the cursor when the stream is closed', async () => {\n const cursor = await queryCursor('SELECT * FROM workspaces;', WorkspaceSchema);\n const stream = cursor.stream(1);\n\n const rows: any[] = [];\n const ac = new AbortController();\n const writable = new Writable({\n objectMode: true,\n write(chunk, _encoding, callback) {\n rows.push(chunk);\n\n // After receiving the first row, abort the stream. This lets us test\n // that the underlying cursor is closed. If it is *not* closed, this\n // `after` hook will fail with a timeout.\n ac.abort();\n callback();\n },\n });\n\n await expect(pipeline(stream, writable, { signal: ac.signal })).rejects.toThrow();\n assert.lengthOf(rows, 1);\n });\n });\n });\n});\n"]}
|
package/dist/test-utils.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-utils.d.ts","sourceRoot":"","sources":["../src/test-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAQpB,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,IAAI,CAAC,EAAE,CAAC,UAAU,EAAE,KAAK,GAAG,mBAAmB,CAAC,CAAC;IAC9D,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,iBAAiB,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CA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ACzB,iBAAiB,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1D;AAID,UAAU,qBAAqB;IAC7B,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAChD;AAED,UAAU,mBAAmB;IAC3B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAmHD,MAAM,WAAW,iBAAiB;IAChC,cAAc,EAAE,CAAC,OAAO,CAAC,EAAE,qBAAqB,KAAK,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC;IAC5E,aAAa,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,YAAY,EAAE,CAAC,OAAO,CAAC,EAAE,mBAAmB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/D,mCAAmC,EAAE,MAAM,MAAM,CAAC;IAClD,aAAa,EAAE,MAAM,EAAE,CAAC,UAAU,CAAC;CACpC;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,wBAAwB,GAAG,iBAAiB,CAU1F","sourcesContent":["import pg from 'pg';\n\nimport * as defaultPool from './default-pool.js';\n\nconst POSTGRES_USER = 'postgres';\nconst POSTGRES_HOST = 'localhost';\nconst POSTGRES_DATABASE = 'postgres';\n\nexport interface PostgresTestUtilsOptions {\n database: string;\n user?: string;\n host?: string;\n poolConfig?: Pick<pg.PoolConfig, 'max' | 'idleTimeoutMillis'>;\n defaultDatabase?: string;\n prepareAfterReset?: (client: pg.Client) => Promise<void>;\n}\n\ntype PostgresTestPoolConfig = Required<Pick<pg.PoolConfig, 'user' | 'host' | 'database'>>;\n\ninterface CreateDatabaseOptions {\n dropExistingDatabase?: boolean;\n database?: string;\n templateDatabase?: string;\n configurePool?: boolean;\n prepare?: (client: pg.Client) => Promise<void>;\n}\n\ninterface DropDatabaseOptions {\n database?: string;\n force?: boolean;\n closePool?: boolean;\n}\n\nasync function createDatabase(\n options: PostgresTestUtilsOptions,\n {\n dropExistingDatabase = true,\n configurePool = true,\n database,\n templateDatabase,\n prepare,\n }: CreateDatabaseOptions = {},\n): Promise<PostgresTestPoolConfig> {\n const client = new pg.Client({\n ...getPoolConfig(options),\n database: options.defaultDatabase ?? POSTGRES_DATABASE,\n });\n await client.connect();\n\n const escapedDatabase = client.escapeIdentifier(\n database ?? getDatabaseNameForCurrentTestWorker(options.database),\n );\n if (dropExistingDatabase ?? true) {\n await client.query(`DROP DATABASE IF EXISTS ${escapedDatabase}`);\n }\n\n if (templateDatabase) {\n const escapedTemplateDatabase = client.escapeIdentifier(templateDatabase);\n await client.query(`CREATE DATABASE ${escapedDatabase} TEMPLATE ${escapedTemplateDatabase}`);\n } else {\n await client.query(`CREATE DATABASE ${escapedDatabase}`);\n }\n\n await client.end();\n\n await prepare?.(client);\n\n const poolConfig = getPoolConfig(options);\n\n if (configurePool) {\n await defaultPool.initAsync(\n {\n ...poolConfig,\n // Offer sensible default, but these can be overridden by `options.poolConfig`.\n max: 10,\n idleTimeoutMillis: 30000,\n errorOnUnusedParameters: true,\n ...options.poolConfig,\n },\n (err) => {\n throw err;\n },\n );\n }\n\n return poolConfig;\n}\n\nasync function resetDatabase(options: PostgresTestUtilsOptions): Promise<void> {\n const client = new pg.Client(getPoolConfig(options));\n await client.connect();\n await client.query(`\n DO\n $func$\n BEGIN\n EXECUTE (\n SELECT 'TRUNCATE TABLE ' || string_agg(oid::regclass::text, ', ') || ' RESTART IDENTITY CASCADE'\n FROM pg_class\n WHERE relkind = 'r'\n AND relnamespace = 'public'::regnamespace\n );\n END\n $func$;\n `);\n await options.prepareAfterReset?.(client);\n await client.end();\n}\n\nasync function dropDatabase(\n options: PostgresTestUtilsOptions,\n { closePool = true, force = false, database }: DropDatabaseOptions = {},\n): Promise<void> {\n if (closePool) {\n await defaultPool.closeAsync();\n }\n\n const databaseName = database ?? getDatabaseNameForCurrentTestWorker(options.database);\n if ('PL_KEEP_TEST_DB' in process.env && !force) {\n // eslint-disable-next-line no-console\n console.log(`PL_KEEP_TEST_DB environment variable set, not dropping database ${databaseName}`);\n return;\n }\n\n const client = new pg.Client({\n ...getPoolConfig(options),\n database: options.defaultDatabase ?? POSTGRES_DATABASE,\n });\n await client.connect();\n await client.query(`DROP DATABASE IF EXISTS ${client.escapeIdentifier(databaseName)}`);\n await client.end();\n}\n\nfunction getDatabaseNameForCurrentTestWorker(namespace: string): string {\n // https://playwright.dev/docs/test-parallel#isolate-test-data-between-parallel-workers\n const workerId = process.env.TEST_WORKER_INDEX ?? process.env.VITEST_POOL_ID ?? '1';\n return `${namespace}_${workerId}`;\n}\n\nfunction getPoolConfig(options: PostgresTestUtilsOptions): PostgresTestPoolConfig {\n return {\n user: options.user ?? POSTGRES_USER,\n host: options.host ?? POSTGRES_HOST,\n database: getDatabaseNameForCurrentTestWorker(options.database),\n };\n}\n\nexport interface PostgresTestUtils {\n createDatabase: (options?: CreateDatabaseOptions) => Promise<pg.PoolConfig>;\n resetDatabase: () => Promise<void>;\n dropDatabase: (options?: DropDatabaseOptions) => Promise<void>;\n getDatabaseNameForCurrentTestWorker: () => string;\n getPoolConfig: () => pg.PoolConfig;\n}\n\nexport function makePostgresTestUtils(options: PostgresTestUtilsOptions): PostgresTestUtils {\n return {\n createDatabase: (createOptions?: CreateDatabaseOptions) =>\n createDatabase(options, createOptions),\n resetDatabase: () => resetDatabase(options),\n dropDatabase: (dropOptions?: DropDatabaseOptions) => dropDatabase(options, dropOptions),\n getDatabaseNameForCurrentTestWorker: () =>\n getDatabaseNameForCurrentTestWorker(options.database),\n getPoolConfig: () => getPoolConfig(options),\n };\n}\n"]}
|
package/dist/test-utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-utils.js","sourceRoot":"","sources":["../src/test-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,KAAK,WAAW,MAAM,mBAAmB,CAAC;AAEjD,MAAM,aAAa,GAAG,UAAU,CAAC;AACjC,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,iBAAiB,GAAG,UAAU,CAAC;AA2BrC,KAAK,UAAU,cAAc,CAC3B,OAAiC,EACjC,EACE,oBAAoB,GAAG,IAAI,EAC3B,aAAa,GAAG,IAAI,EACpB,QAAQ,EACR,gBAAgB,EAChB,OAAO,
|
|
1
|
+
{"version":3,"file":"test-utils.js","sourceRoot":"","sources":["../src/test-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAEpB,OAAO,KAAK,WAAW,MAAM,mBAAmB,CAAC;AAEjD,MAAM,aAAa,GAAG,UAAU,CAAC;AACjC,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,iBAAiB,GAAG,UAAU,CAAC;AA2BrC,KAAK,UAAU,cAAc,CAC3B,OAAiC,EACjC,EACE,oBAAoB,GAAG,IAAI,EAC3B,aAAa,GAAG,IAAI,EACpB,QAAQ,EACR,gBAAgB,EAChB,OAAO,GACR,GAA0B,EAAE,EACI;IACjC,MAAM,MAAM,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC;QAC3B,GAAG,aAAa,CAAC,OAAO,CAAC;QACzB,QAAQ,EAAE,OAAO,CAAC,eAAe,IAAI,iBAAiB;KACvD,CAAC,CAAC;IACH,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IAEvB,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAC7C,QAAQ,IAAI,mCAAmC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAClE,C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QACnC,QAAQ,EAAE,mCAAmC,CAAC,OAAO,CAAC,QAAQ,CAAC;KAChE,CAAC;AAAA,CACH;AAUD,MAAM,UAAU,qBAAqB,CAAC,OAAiC,EAAqB;IAC1F,OAAO;QACL,cAAc,EAAE,CAAC,aAAqC,EAAE,EAAE,CACxD,cAAc,CAAC,OAAO,EAAE,aAAa,CAAC;QACxC,aAAa,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,OAAO,CAAC;QAC3C,YAAY,EAAE,CAAC,WAAiC,EAAE,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,WAAW,CAAC;QACvF,mCAAmC,EAAE,GAAG,EAAE,CACxC,mCAAmC,CAAC,OAAO,CAAC,QAAQ,CAAC;QACvD,aAAa,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,OAAO,CAAC;KAC5C,CAAC;AAAA,CACH","sourcesContent":["import pg from 'pg';\n\nimport * as defaultPool from './default-pool.js';\n\nconst POSTGRES_USER = 'postgres';\nconst POSTGRES_HOST = 'localhost';\nconst POSTGRES_DATABASE = 'postgres';\n\nexport interface PostgresTestUtilsOptions {\n database: string;\n user?: string;\n host?: string;\n poolConfig?: Pick<pg.PoolConfig, 'max' | 'idleTimeoutMillis'>;\n defaultDatabase?: string;\n prepareAfterReset?: (client: pg.Client) => Promise<void>;\n}\n\ntype PostgresTestPoolConfig = Required<Pick<pg.PoolConfig, 'user' | 'host' | 'database'>>;\n\ninterface CreateDatabaseOptions {\n dropExistingDatabase?: boolean;\n database?: string;\n templateDatabase?: string;\n configurePool?: boolean;\n prepare?: (client: pg.Client) => Promise<void>;\n}\n\ninterface DropDatabaseOptions {\n database?: string;\n force?: boolean;\n closePool?: boolean;\n}\n\nasync function createDatabase(\n options: PostgresTestUtilsOptions,\n {\n dropExistingDatabase = true,\n configurePool = true,\n database,\n templateDatabase,\n prepare,\n }: CreateDatabaseOptions = {},\n): Promise<PostgresTestPoolConfig> {\n const client = new pg.Client({\n ...getPoolConfig(options),\n database: options.defaultDatabase ?? POSTGRES_DATABASE,\n });\n await client.connect();\n\n const escapedDatabase = client.escapeIdentifier(\n database ?? getDatabaseNameForCurrentTestWorker(options.database),\n );\n if (dropExistingDatabase ?? true) {\n await client.query(`DROP DATABASE IF EXISTS ${escapedDatabase}`);\n }\n\n if (templateDatabase) {\n const escapedTemplateDatabase = client.escapeIdentifier(templateDatabase);\n await client.query(`CREATE DATABASE ${escapedDatabase} TEMPLATE ${escapedTemplateDatabase}`);\n } else {\n await client.query(`CREATE DATABASE ${escapedDatabase}`);\n }\n\n await client.end();\n\n await prepare?.(client);\n\n const poolConfig = getPoolConfig(options);\n\n if (configurePool) {\n await defaultPool.initAsync(\n {\n ...poolConfig,\n // Offer sensible default, but these can be overridden by `options.poolConfig`.\n max: 10,\n idleTimeoutMillis: 30000,\n errorOnUnusedParameters: true,\n ...options.poolConfig,\n },\n (err) => {\n throw err;\n },\n );\n }\n\n return poolConfig;\n}\n\nasync function resetDatabase(options: PostgresTestUtilsOptions): Promise<void> {\n const client = new pg.Client(getPoolConfig(options));\n await client.connect();\n await client.query(`\n DO\n $func$\n BEGIN\n EXECUTE (\n SELECT 'TRUNCATE TABLE ' || string_agg(oid::regclass::text, ', ') || ' RESTART IDENTITY CASCADE'\n FROM pg_class\n WHERE relkind = 'r'\n AND relnamespace = 'public'::regnamespace\n );\n END\n $func$;\n `);\n await options.prepareAfterReset?.(client);\n await client.end();\n}\n\nasync function dropDatabase(\n options: PostgresTestUtilsOptions,\n { closePool = true, force = false, database }: DropDatabaseOptions = {},\n): Promise<void> {\n if (closePool) {\n await defaultPool.closeAsync();\n }\n\n const databaseName = database ?? getDatabaseNameForCurrentTestWorker(options.database);\n if ('PL_KEEP_TEST_DB' in process.env && !force) {\n // eslint-disable-next-line no-console\n console.log(`PL_KEEP_TEST_DB environment variable set, not dropping database ${databaseName}`);\n return;\n }\n\n const client = new pg.Client({\n ...getPoolConfig(options),\n database: options.defaultDatabase ?? POSTGRES_DATABASE,\n });\n await client.connect();\n await client.query(`DROP DATABASE IF EXISTS ${client.escapeIdentifier(databaseName)}`);\n await client.end();\n}\n\nfunction getDatabaseNameForCurrentTestWorker(namespace: string): string {\n // https://playwright.dev/docs/test-parallel#isolate-test-data-between-parallel-workers\n const workerId = process.env.TEST_WORKER_INDEX ?? process.env.VITEST_POOL_ID ?? '1';\n return `${namespace}_${workerId}`;\n}\n\nfunction getPoolConfig(options: PostgresTestUtilsOptions): PostgresTestPoolConfig {\n return {\n user: options.user ?? POSTGRES_USER,\n host: options.host ?? POSTGRES_HOST,\n database: getDatabaseNameForCurrentTestWorker(options.database),\n };\n}\n\nexport interface PostgresTestUtils {\n createDatabase: (options?: CreateDatabaseOptions) => Promise<pg.PoolConfig>;\n resetDatabase: () => Promise<void>;\n dropDatabase: (options?: DropDatabaseOptions) => Promise<void>;\n getDatabaseNameForCurrentTestWorker: () => string;\n getPoolConfig: () => pg.PoolConfig;\n}\n\nexport function makePostgresTestUtils(options: PostgresTestUtilsOptions): PostgresTestUtils {\n return {\n createDatabase: (createOptions?: CreateDatabaseOptions) =>\n createDatabase(options, createOptions),\n resetDatabase: () => resetDatabase(options),\n dropDatabase: (dropOptions?: DropDatabaseOptions) => dropDatabase(options, dropOptions),\n getDatabaseNameForCurrentTestWorker: () =>\n getDatabaseNameForCurrentTestWorker(options.database),\n getPoolConfig: () => getPoolConfig(options),\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prairielearn/postgres",
|
|
3
|
-
"version": "4.5.
|
|
3
|
+
"version": "4.5.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -9,13 +9,13 @@
|
|
|
9
9
|
},
|
|
10
10
|
"main": "./dist/index.js",
|
|
11
11
|
"scripts": {
|
|
12
|
-
"build": "
|
|
13
|
-
"dev": "
|
|
12
|
+
"build": "tsgo",
|
|
13
|
+
"dev": "tsgo --watch --preserveWatchOutput",
|
|
14
14
|
"test": "vitest run --coverage"
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
17
|
"@types/debug": "^4.1.12",
|
|
18
|
-
"@types/lodash": "^4.17.
|
|
18
|
+
"@types/lodash": "^4.17.23",
|
|
19
19
|
"@types/pg-cursor": "^2.7.2",
|
|
20
20
|
"multipipe": "^4.0.0",
|
|
21
21
|
"pg": "^8.16.3",
|
|
@@ -27,10 +27,11 @@
|
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@prairielearn/tsconfig": "^0.0.0",
|
|
29
29
|
"@types/multipipe": "^3.0.5",
|
|
30
|
-
"@types/node": "^22.19.
|
|
31
|
-
"@
|
|
30
|
+
"@types/node": "^22.19.5",
|
|
31
|
+
"@typescript/native-preview": "^7.0.0-dev.20260106.1",
|
|
32
|
+
"@vitest/coverage-v8": "^4.0.17",
|
|
32
33
|
"tsx": "^4.21.0",
|
|
33
34
|
"typescript": "^5.9.3",
|
|
34
|
-
"vitest": "^4.0.
|
|
35
|
+
"vitest": "^4.0.17"
|
|
35
36
|
}
|
|
36
37
|
}
|