@mielk/db 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,30 @@ Versions up to 2.1.0 were generated by standard-version and are kept unchanged.
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.2.0] - 2026-11-23
11
+
12
+ ### Added
13
+
14
+ - Public PostgreSQL error code `DB_ERROR_CODES.PG_TRANSACTION_ENDED_BY_CALLBACK` (TASK-403).
15
+
16
+ ### Fixed
17
+
18
+ - PostgreSQL `withTransaction` rejects when the callback resolves after ending the transaction itself with `ROLLBACK` or `COMMIT`. Changes already committed by the callback remain committed (TASK-403).
19
+
20
+ ### Documentation
21
+
22
+ - Clarified that PostgreSQL `withTransaction` can commit a replacement transaction and that queries after an explicit callback `COMMIT` run outside a transaction until a new one begins (TASK-408).
23
+
24
+ ## [3.1.0] - 2026-11-23
25
+
26
+ ### Added
27
+
28
+ - Public PostgreSQL error code `DB_ERROR_CODES.PG_TRANSACTION_ABORTED` (TASK-357).
29
+
30
+ ### Fixed
31
+
32
+ - PostgreSQL `withTransaction` rejects with `PG_TRANSACTION_ABORTED` when PostgreSQL responds to `COMMIT` with `ROLLBACK` (TASK-357).
33
+
10
34
  ## [3.0.0] - 2026-11-15
11
35
 
12
36
  ### Added
@@ -25,7 +49,7 @@ Versions up to 2.1.0 were generated by standard-version and are kept unchanged.
25
49
 
26
50
  ### Changed
27
51
 
28
- - **Breaking:** the package is renamed from `mielk-db` to `@mielk/db` (scope `@mielk` of the npm account `mielk`); `mielk-db` is to be deprecated and get no new versions when 3.0.0 is published. Migration: replace `mielk-db` with `@mielk/db` in `package.json` and in every import, including subpaths (e.g. `mielk-db/mssql` becomes `@mielk/db/mssql`); do not keep both packages in one application (TASK-227).
52
+ - **Breaking:** the package is renamed from `mielk-db` to `@mielk/db` (scope `@mielk` of the npm account `mielk`); `mielk-db` is deprecated and gets no new versions. Migration: replace `mielk-db` with `@mielk/db` in `package.json` and in every import, including subpaths (e.g. `mielk-db/mssql` becomes `@mielk/db/mssql`); do not keep both packages in one application (TASK-227).
29
53
  - **Breaking:** Node.js 24 or later is required (`engines.node: >=24`). Migration: run the application on Node.js 24 (TASK-189).
30
54
  - **Breaking:** the main entry point of the package (`mielk-db` without a subpath) is removed (it pointed to a file the build did not create). Migration: import from `@mielk/db/pg` or `@mielk/db/mssql` (TASK-189).
31
55
  - **Breaking:** `pg` and `msnodesqlv8` are optional peer dependencies instead of optional dependencies, so they are no longer installed with the library; `@types/pg` is an optional peer dependency too. Migration: install `pg` (and `@types/pg` in TypeScript) or `msnodesqlv8` in the application (TASK-189).
package/README.md CHANGED
@@ -5,9 +5,8 @@ asynchronous call chain (`@mielk/db/pg`), and simple queries and stored procedur
5
5
  over ODBC (`@mielk/db/mssql`). Errors of the library have stable codes, with texts in several languages for
6
6
  display. The library is written in TypeScript and published to npm as an ES module with type declarations.
7
7
 
8
- Versions up to 2.1.0 were published as `mielk-db`. Version 3.0.0 and later are to be published as `@mielk/db`
9
- (repository `mielk-db`); until that release `@mielk/db` is not yet on npm, and `mielk-db` is to be deprecated
10
- when 3.0.0 is published. The migration is described in
8
+ Versions up to 2.1.0 were published as `mielk-db`; that package is deprecated and gets no new versions.
9
+ Version 3.0.0 and later are published as `@mielk/db` (repository `mielk-db`). The migration is described in
11
10
  [CHANGELOG.md](CHANGELOG.md).
12
11
 
13
12
  ## Requirements
@@ -87,8 +86,15 @@ await closeDb();
87
86
  outer `withTransaction` then rolls back and rejects with `PG_NESTED_TRANSACTION_FAILED`, whose `cause` is the
88
87
  first error of a nested call.
89
88
  - PostgreSQL aborts a transaction after any failed statement. An error caught inside `fn` and not rethrown still
90
- leaves the transaction aborted: the next statement fails, and the commit rolls back. To continue after an
91
- expected error, let it end `withTransaction` and handle it outside, or use a `SAVEPOINT` yourself.
89
+ leaves the transaction aborted. If PostgreSQL responds to `COMMIT` with `ROLLBACK`, `withTransaction` rejects
90
+ with `PG_TRANSACTION_ABORTED`. Handle the error outside `withTransaction`, or roll back to a savepoint inside
91
+ the callback to recover from an expected statement error.
92
+ - Let `withTransaction` control the transaction boundary. If `fn` resolves after ending the transaction with
93
+ `ROLLBACK` or `COMMIT`, leaving no active transaction, `withTransaction` rejects with
94
+ `PG_TRANSACTION_ENDED_BY_CALLBACK`. Any changes committed by `fn` remain committed. Queries that `fn` runs after
95
+ an explicit `COMMIT` execute outside a transaction until a new one begins. If `fn` runs `ROLLBACK; BEGIN` or
96
+ `COMMIT; BEGIN` and leaves the replacement transaction active, `withTransaction` cannot detect the replacement
97
+ and commits it when `fn` resolves successfully. Savepoints remain supported.
92
98
  - `getQueryExecutor()` returns the transaction connection inside `withTransaction` and the pool outside it. Call it
93
99
  for each unit of work rather than keeping the result: an executor taken outside a transaction stays the pool
94
100
  also when used inside one. Most code needs only `query`.
@@ -151,17 +157,19 @@ call `closeDb` first to connect again.
151
157
  Errors of the library are `DbError` objects: `code` identifies the error (compare it with `DB_ERROR_CODES`, never
152
158
  the message), `message` is the English text for logs, and `cause` holds the original error, if there was one.
153
159
 
154
- | Code (`DB_ERROR_CODES.*`) | Thrown by | When |
155
- | ------------------------------ | ---------------------------------------------- | --------------------------------------------------------------------- |
156
- | `PG_ALREADY_INITIALIZED` | `initDb` (pg) | the pool exists; call `closeDb` first |
157
- | `PG_NOT_INITIALIZED` | `query`, `withTransaction`, `getQueryExecutor` | `initDb` has not been called |
158
- | `PG_NESTED_TRANSACTION_FAILED` | `withTransaction` | `fn` resolved although a nested `withTransaction` failed; rolled back |
159
- | `PG_TRANSACTION_ENDED` | `query`, `withTransaction`, `getQueryExecutor` | called by an operation of `fn` after its transaction ended |
160
- | `PG_UNEXPECTED_ERROR` | passed to `onError` (pg) | an idle connection of the pool failed (e.g. the server closed it) |
161
- | `MSSQL_ALREADY_INITIALIZED` | `initDb` (mssql) | the settings are stored; call `closeDb` first |
162
- | `MSSQL_NOT_INITIALIZED` | `query`, `spExecute` (mssql) | `initDb` has not been called |
163
- | `MSSQL_DRIVER_NOT_INSTALLED` | `query`, `spExecute` (mssql) | `msnodesqlv8` cannot be loaded; the import error is the `cause` |
164
- | `MSSQL_CLOSE_FAILED` | passed to `onError` (mssql) | closing the connection of `spExecute` failed |
160
+ | Code (`DB_ERROR_CODES.*`) | Thrown by | When |
161
+ | ---------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------- |
162
+ | `PG_ALREADY_INITIALIZED` | `initDb` (pg) | the pool exists; call `closeDb` first |
163
+ | `PG_NOT_INITIALIZED` | `query`, `withTransaction`, `getQueryExecutor` | `initDb` has not been called |
164
+ | `PG_NESTED_TRANSACTION_FAILED` | `withTransaction` | `fn` resolved although a nested `withTransaction` failed; rolled back |
165
+ | `PG_TRANSACTION_ABORTED` | `withTransaction` | PostgreSQL rolled back the aborted transaction in response to `COMMIT` |
166
+ | `PG_TRANSACTION_ENDED_BY_CALLBACK` | `withTransaction` | `fn` resolved after ending the transaction and left no active transaction |
167
+ | `PG_TRANSACTION_ENDED` | `query`, `withTransaction`, `getQueryExecutor` | called by an operation of `fn` after its transaction ended |
168
+ | `PG_UNEXPECTED_ERROR` | passed to `onError` (pg) | an idle connection of the pool failed (e.g. the server closed it) |
169
+ | `MSSQL_ALREADY_INITIALIZED` | `initDb` (mssql) | the settings are stored; call `closeDb` first |
170
+ | `MSSQL_NOT_INITIALIZED` | `query`, `spExecute` (mssql) | `initDb` has not been called |
171
+ | `MSSQL_DRIVER_NOT_INSTALLED` | `query`, `spExecute` (mssql) | `msnodesqlv8` cannot be loaded; the import error is the `cause` |
172
+ | `MSSQL_CLOSE_FAILED` | passed to `onError` (mssql) | closing the connection of `spExecute` failed |
165
173
 
166
174
  Asynchronous functions report these errors as rejections. Errors of the server and the driver (failed connection,
167
175
  failed query, `BEGIN`, `COMMIT`) are passed to the caller unchanged, not wrapped in `DbError`. `query` of
@@ -209,22 +217,33 @@ message text, which depends on the server language, so `@mielk/db/mssql` reports
209
217
  | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
210
218
  | `npm ci` | install dependencies from `package-lock.json` |
211
219
  | `npm test` | all unit tests (Vitest) with coverage; threshold 80% of lines and branches; the report is written to the system temp folder |
220
+ | `npm run test:pg` | PostgreSQL integration test against a temporary local database |
212
221
  | `npm run test:watch` | tests in watch mode |
213
222
  | `npm run typecheck` | TypeScript check without output |
214
223
  | `npm run lint` | ESLint with type information, no warnings allowed |
215
224
  | `npm run format` / `npm run format:check` | Prettier |
216
225
  | `npm run build` | compiles `src` to `dist` (clears the content of `dist`, keeps the folder) |
217
226
  | `npm run dev` | build in watch mode |
218
- | `npm run check:package` | `publint --strict` and `attw` on the built package |
227
+ | `npm run check:package` | `mielk-check-package` from `@mielk/lib-config`: `publint --strict`, `attw` and the package file list |
219
228
 
220
229
  `prepublishOnly` runs typecheck, lint, tests, build and the package check.
221
- Unit tests do not connect to a database: `pg` and `msnodesqlv8` are replaced by test doubles.
230
+ The TypeScript, ESLint, Prettier and Vitest configuration comes from the shared package `@mielk/lib-config`
231
+ (development dependency); the files in this repository only extend it.
232
+ Unit tests replace `pg` and `msnodesqlv8` with test doubles. Run the PostgreSQL integration test separately with
233
+ `npm run test:pg`.
234
+
235
+ Start a dedicated local PostgreSQL 16 test cluster on `127.0.0.1`. Set `MIELK_DB_TEST_PG_PORT` to its port and
236
+ `MIELK_DB_TEST_PG_USER` to a bootstrap login with `CREATEDB` and `CREATEROLE` privileges and access to the
237
+ `postgres` maintenance database. Set `MIELK_DB_TEST_PG_PASSWORD` if the login requires a password. The cluster
238
+ must allow the generated test login to connect over loopback. The suite creates a uniquely named database and
239
+ login for each run and drops both during teardown. If the port or bootstrap login is missing, the suite prints
240
+ the missing variables and skips the test.
222
241
 
223
242
  ## Releases and changes
224
243
 
225
244
  Changes are listed by hand in [CHANGELOG.md](CHANGELOG.md) under `Unreleased`; it also holds the migration notes
226
245
  between major versions. `npm version <major|minor|patch>` moves the entries to the new version
227
- (`scripts/release-changelog.ts`, run by Node.js directly) and creates the release commit and tag.
246
+ (`mielk-release-changelog` from `@mielk/lib-config`) and creates the release commit and tag.
228
247
 
229
248
  ## Documentation scope
230
249
 
@@ -12,7 +12,10 @@ export declare const DB_ERROR_CODES: {
12
12
  readonly PG_ALREADY_INITIALIZED: "db/pg/connection:alreadyInitialized";
13
13
  readonly PG_NESTED_TRANSACTION_FAILED: "db/pg/transaction:nestedFailed";
14
14
  readonly PG_NOT_INITIALIZED: "db/pg/connection:notInitialized";
15
+ /** PostgreSQL rolled back the aborted transaction in response to COMMIT. */
16
+ readonly PG_TRANSACTION_ABORTED: "db/pg/transaction:aborted";
15
17
  readonly PG_TRANSACTION_ENDED: "db/pg/transaction:ended";
18
+ readonly PG_TRANSACTION_ENDED_BY_CALLBACK: "db/pg/transaction:endedByCallback";
16
19
  readonly PG_UNEXPECTED_ERROR: "db/pg/connection:unexpectedError";
17
20
  };
18
21
  /** Code of an error thrown by the library: one of the values of {@link DB_ERROR_CODES}. */
@@ -13,7 +13,10 @@ export const DB_ERROR_CODES = {
13
13
  PG_ALREADY_INITIALIZED: 'db/pg/connection:alreadyInitialized',
14
14
  PG_NESTED_TRANSACTION_FAILED: 'db/pg/transaction:nestedFailed',
15
15
  PG_NOT_INITIALIZED: 'db/pg/connection:notInitialized',
16
+ /** PostgreSQL rolled back the aborted transaction in response to COMMIT. */
17
+ PG_TRANSACTION_ABORTED: 'db/pg/transaction:aborted',
16
18
  PG_TRANSACTION_ENDED: 'db/pg/transaction:ended',
19
+ PG_TRANSACTION_ENDED_BY_CALLBACK: 'db/pg/transaction:endedByCallback',
17
20
  PG_UNEXPECTED_ERROR: 'db/pg/connection:unexpectedError',
18
21
  };
19
22
  const ENGLISH_TEXTS = en;
@@ -11,7 +11,9 @@
11
11
  "unexpectedError": "Unexpected error of an idle PostgreSQL connection."
12
12
  },
13
13
  "db/pg/transaction": {
14
+ "aborted": "PostgreSQL rolled back the aborted transaction when asked to commit.",
14
15
  "ended": "The transaction of this call chain has already ended: a query started inside withTransaction cannot run after it.",
16
+ "endedByCallback": "The withTransaction callback ended the transaction before the library could commit it.",
15
17
  "nestedFailed": "A nested withTransaction failed and its error was caught: the whole transaction is rolled back."
16
18
  }
17
19
  }
@@ -11,7 +11,9 @@
11
11
  "unexpectedError": "Nieoczekiwany błąd bezczynnego połączenia z PostgreSQL."
12
12
  },
13
13
  "db/pg/transaction": {
14
+ "aborted": "PostgreSQL wycofał przerwaną transakcję przy próbie zatwierdzenia.",
14
15
  "ended": "Transakcja tego łańcucha wywołań już się zakończyła: zapytanie rozpoczęte wewnątrz withTransaction nie może zostać wykonane po niej.",
16
+ "endedByCallback": "Funkcja przekazana do withTransaction zakończyła transakcję, zanim biblioteka mogła ją zatwierdzić.",
15
17
  "nestedFailed": "Zagnieżdżone withTransaction nie powiodło się, a jego błąd został przechwycony: cała transakcja zostaje wycofana."
16
18
  }
17
19
  }
@@ -27,9 +27,17 @@ export declare function query<T extends QueryResultRow = QueryResultRow>(text: s
27
27
  * `fn` joins the outer transaction: it opens no transaction of its own, and its error rolls back the whole one, also
28
28
  * when `fn` catches it.
29
29
  *
30
+ * Let `withTransaction` control the transaction boundary. Queries after an explicit `COMMIT` in `fn` execute outside
31
+ * a transaction until a new one begins. If `fn` runs `ROLLBACK; BEGIN` or `COMMIT; BEGIN` and leaves the replacement
32
+ * transaction active, `withTransaction` cannot detect the replacement and commits it when `fn` resolves successfully.
33
+ *
34
+ * @param fn - The callback to run on the transaction connection.
35
+ * @returns The callback result after the transaction commits.
30
36
  * @throws The error of `fn`, of `BEGIN` or of `COMMIT`, unchanged; a failed `ROLLBACK` does not replace it.
31
37
  * @throws {DbError} `PG_NESTED_TRANSACTION_FAILED` when `fn` resolves although a nested `withTransaction` failed;
32
38
  * the transaction is rolled back and the first error of a nested call is the `cause`.
39
+ * @throws {DbError} `PG_TRANSACTION_ABORTED` when PostgreSQL rolls back in response to `COMMIT`.
40
+ * @throws {DbError} `PG_TRANSACTION_ENDED_BY_CALLBACK` when the callback leaves no active transaction.
33
41
  * @throws {DbError} `PG_TRANSACTION_ENDED` when called in the call chain of a transaction that has already ended.
34
42
  * @throws The error of the pool when no connection can be opened.
35
43
  */
@@ -62,9 +62,17 @@ async function runNested(context, fn) {
62
62
  * `fn` joins the outer transaction: it opens no transaction of its own, and its error rolls back the whole one, also
63
63
  * when `fn` catches it.
64
64
  *
65
+ * Let `withTransaction` control the transaction boundary. Queries after an explicit `COMMIT` in `fn` execute outside
66
+ * a transaction until a new one begins. If `fn` runs `ROLLBACK; BEGIN` or `COMMIT; BEGIN` and leaves the replacement
67
+ * transaction active, `withTransaction` cannot detect the replacement and commits it when `fn` resolves successfully.
68
+ *
69
+ * @param fn - The callback to run on the transaction connection.
70
+ * @returns The callback result after the transaction commits.
65
71
  * @throws The error of `fn`, of `BEGIN` or of `COMMIT`, unchanged; a failed `ROLLBACK` does not replace it.
66
72
  * @throws {DbError} `PG_NESTED_TRANSACTION_FAILED` when `fn` resolves although a nested `withTransaction` failed;
67
73
  * the transaction is rolled back and the first error of a nested call is the `cause`.
74
+ * @throws {DbError} `PG_TRANSACTION_ABORTED` when PostgreSQL rolls back in response to `COMMIT`.
75
+ * @throws {DbError} `PG_TRANSACTION_ENDED_BY_CALLBACK` when the callback leaves no active transaction.
68
76
  * @throws {DbError} `PG_TRANSACTION_ENDED` when called in the call chain of a transaction that has already ended.
69
77
  * @throws The error of the pool when no connection can be opened.
70
78
  */
@@ -75,9 +83,10 @@ export async function withTransaction(fn) {
75
83
  const client = await getPool().connect();
76
84
  const context = { client, active: true };
77
85
  let brokenConnection;
86
+ let result;
87
+ let commit;
78
88
  try {
79
89
  await client.query('BEGIN');
80
- let result;
81
90
  try {
82
91
  result = await transactionContext.run(context, fn);
83
92
  }
@@ -88,8 +97,20 @@ export async function withTransaction(fn) {
88
97
  if (context.nestedFailure) {
89
98
  throw new DbError(DB_ERROR_CODES.PG_NESTED_TRANSACTION_FAILED, { cause: context.nestedFailure.error });
90
99
  }
91
- await client.query('COMMIT');
92
- return result;
100
+ // Outside a transaction, COMMIT only warns and still reports success. SAVEPOINT fails with 25P01.
101
+ try {
102
+ await client.query('SAVEPOINT mielk_db_before_commit');
103
+ }
104
+ catch (err) {
105
+ const code = err instanceof Error && 'code' in err ? err.code : undefined;
106
+ if (code === '25P01') {
107
+ throw new DbError(DB_ERROR_CODES.PG_TRANSACTION_ENDED_BY_CALLBACK, { cause: err });
108
+ }
109
+ // Let COMMIT report ROLLBACK when the callback caught a query error (25P02).
110
+ if (code !== '25P02')
111
+ throw err;
112
+ }
113
+ commit = await client.query('COMMIT');
93
114
  }
94
115
  catch (err) {
95
116
  try {
@@ -106,4 +127,8 @@ export async function withTransaction(fn) {
106
127
  finally {
107
128
  client.release(brokenConnection);
108
129
  }
130
+ // PostgreSQL has already rolled back, so no further command is needed on the connection.
131
+ if (commit.command === 'ROLLBACK')
132
+ throw new DbError(DB_ERROR_CODES.PG_TRANSACTION_ABORTED);
133
+ return result;
109
134
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mielk/db",
3
- "version": "3.0.0",
3
+ "version": "3.2.0",
4
4
  "description": "PostgreSQL connection pool with call-chain transactions and MS SQL queries over ODBC, with coded errors, for mielk Node.js applications.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -8,6 +8,7 @@
8
8
  },
9
9
  "scripts": {
10
10
  "test": "vitest run --coverage",
11
+ "test:pg": "vitest run --config vitest.pg.config.ts",
11
12
  "build": "npm run clean && tsc -p tsconfig.build.json",
12
13
  "prepublishOnly": "npm run typecheck && npm run lint && npm test && npm run build && npm run check:package",
13
14
  "dev": "tsc -p tsconfig.build.json --watch",
@@ -16,8 +17,8 @@
16
17
  "lint": "eslint . --max-warnings 0",
17
18
  "format": "prettier --write .",
18
19
  "format:check": "prettier --check .",
19
- "check:package": "publint --strict && attw --pack . --profile esm-only && npm pack --dry-run --json | node scripts/check-pack-files.ts",
20
- "version": "node scripts/release-changelog.ts && git add CHANGELOG.md",
20
+ "check:package": "mielk-check-package",
21
+ "version": "mielk-release-changelog && git add CHANGELOG.md",
21
22
  "clean": "node -e \"const fs = require('node:fs'); for (const e of fs.existsSync('dist') ? fs.readdirSync('dist') : []) fs.rmSync('dist/' + e, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 })\""
22
23
  },
23
24
  "exports": {
@@ -33,6 +34,7 @@
33
34
  },
34
35
  "./locales/*": "./dist/locales/*.json"
35
36
  },
37
+ "prettier": "@mielk/lib-config/prettier",
36
38
  "repository": {
37
39
  "type": "git",
38
40
  "url": "git+https://github.com/mielk/mielk-db.git"
@@ -52,7 +54,7 @@
52
54
  ],
53
55
  "devDependencies": {
54
56
  "@arethetypeswrong/cli": "0.18.5",
55
- "@eslint/js": "10.0.1",
57
+ "@mielk/lib-config": "1.0.0",
56
58
  "@types/node": "24.19.2",
57
59
  "@types/pg": "8.20.0",
58
60
  "@vitest/coverage-v8": "5.1.0",
@@ -62,7 +64,6 @@
62
64
  "prettier": "3.10.1",
63
65
  "publint": "0.3.25",
64
66
  "typescript": "5.9.2",
65
- "typescript-eslint": "8.72.2",
66
67
  "vitest": "5.1.0"
67
68
  },
68
69
  "peerDependencies": {