@mielk/db 0.0.0-stage → 3.1.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 ADDED
@@ -0,0 +1,77 @@
1
+ # Changelog
2
+
3
+ All notable changes to this library are documented in this file. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the library uses [Semantic Versioning](https://semver.org/).
5
+ Entries are written by hand; `npm version` moves them from Unreleased to the released version.
6
+ Versions up to 2.1.0 were generated by standard-version and are kept unchanged.
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [3.1.0] - 2026-11-23
11
+
12
+ ### Added
13
+
14
+ - Public PostgreSQL error code `DB_ERROR_CODES.PG_TRANSACTION_ABORTED` (TASK-357).
15
+
16
+ ### Fixed
17
+
18
+ - PostgreSQL `withTransaction` rejects with `PG_TRANSACTION_ABORTED` when PostgreSQL responds to `COMMIT` with `ROLLBACK` (TASK-357).
19
+
20
+ ## [3.0.0] - 2026-11-15
21
+
22
+ ### Added
23
+
24
+ - `query(text, params?)` in `@mielk/db/pg`: runs a query in the transaction of the current call chain, otherwise on the pool (TASK-189).
25
+ - `closeDb()` in `@mielk/db/pg` and `@mielk/db/mssql`; `initDb` can be called again after it (TASK-189).
26
+ - `DbError` with `code`, English `message` and `cause`, the constant `DB_ERROR_CODES` and the type `DbErrorCode`, exported from both entry points (TASK-189).
27
+ - Texts of the error codes in English and Polish, in the entry point `@mielk/db/locales/<language>` (TASK-189).
28
+ - `getDbErrorKind(err)` and the type `DbErrorKind` in both entry points: unique, foreign key, not null and check violations, serialization failure and deadlock for PostgreSQL; unique, constraint and not null violations and deadlock for MS SQL. `isUniqueViolation` in `@mielk/db/mssql` (TASK-189).
29
+ - `onError` in `PgConfig` and `MsSqlConfig`: receives errors that the library cannot pass to a caller (TASK-189).
30
+ - `PgConfig` accepts every setting of `PoolConfig` from `pg` (e.g. `ssl`, `statement_timeout`) (TASK-189).
31
+ - `query` of `@mielk/db/mssql` takes query parameters: `query(text, params?)` with `?` placeholders (TASK-189).
32
+ - Type `MsSqlRow` for the rows returned by `query` of `@mielk/db/mssql` (TASK-189).
33
+ - README, MIT license file and TSDoc comments for every export (TASK-189).
34
+ - The package contains `CHANGELOG.md`, so the migration notes are available after installation (TASK-189).
35
+
36
+ ### Changed
37
+
38
+ - **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).
39
+ - **Breaking:** Node.js 24 or later is required (`engines.node: >=24`). Migration: run the application on Node.js 24 (TASK-189).
40
+ - **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).
41
+ - **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).
42
+ - **Breaking:** the library has no dependencies of its own: `mielk-fn` and `tunnel-ssh` are removed, and so are the peer dependencies `express` and `zod` and the optional dependency `mysql2`, which the code did not use. Migration: install them in the application if it uses them directly (TASK-189).
43
+ - **Breaking:** the types `PostgreDbConfig` and `MsSqlDbConfig` are renamed to `PgConfig` and `MsSqlConfig`, and the `provider` field is removed from both. Migration: rename the imports and remove `provider` (TASK-189).
44
+ - **Breaking:** errors of the library are `DbError` objects with a `code` from `DB_ERROR_CODES`; before, they were `Error` objects whose message was a message key (`Msg`). Migration: compare `error.code` with `DB_ERROR_CODES` instead of the message (TASK-189).
45
+ - **Breaking:** `UniqueKeyViolationError` is removed; the library never threw it. Migration: recognise the error with `isUniqueViolation(err)` or `getDbErrorKind(err)` (TASK-189).
46
+ - **Breaking:** `getQueryExecutor()` of `@mielk/db/pg` returns the executor directly instead of a promise, and throws `PG_NOT_INITIALIZED` instead of rejecting. Migration: remove `await` before `getQueryExecutor()`, or use `query` (TASK-189).
47
+ - **Breaking:** a second `initDb` throws `PG_ALREADY_INITIALIZED` or `MSSQL_ALREADY_INITIALIZED`, also with the same settings; before, the later settings silently replaced the earlier ones. `initDb` of `@mielk/db/pg` creates the pool at once instead of on the first query. Migration: call `initDb` once, or `closeDb` before connecting again (TASK-189).
48
+ - **Breaking:** a `withTransaction` called inside another joins the outer transaction; before, it failed with an error that a transaction was already active. Every asynchronous call chain has its own transaction: before, a `withTransaction` started while another was running failed and rolled back the other one, and a query outside `withTransaction` could run in another call's transaction. The error of a nested `withTransaction` rolls back the whole transaction also when the caller catches it: the outer `withTransaction` rejects with `PG_NESTED_TRANSACTION_FAILED`. An operation started inside `fn` and run after the transaction ended fails with `PG_TRANSACTION_ENDED` instead of using the released connection. Migration: none needed for code without nested or parallel transactions (TASK-189).
49
+ - **Breaking:** `query` of `@mielk/db/mssql` returns `MsSqlRow[]` (`Record<string, unknown>[]`) instead of `any[]`. Migration: validate the rows before use, or cast them where the shape is known (TASK-189).
50
+ - **Breaking:** `MsSqlConfig.driver` is the name of the ODBC driver without braces (e.g. `ODBC Driver 18 for SQL Server`); the library quotes every value of the connection string. Migration: remove the braces from `driver` (TASK-189).
51
+ - `withTransaction` rejects with the original error when `ROLLBACK` also fails, and destroys the connection instead of returning it to the pool (TASK-189).
52
+ - An error of an idle PostgreSQL connection goes to `onError` instead of the console (TASK-189).
53
+
54
+ ### Removed
55
+
56
+ - **Breaking:** the SSH tunnel: the `ssh` option of the PostgreSQL configuration and the `ssh` module. Migration: open the tunnel outside the application, e.g. with a script, and connect to its local port (TASK-189).
57
+
58
+ ### Fixed
59
+
60
+ - `initDb` of `@mielk/db/mssql` no longer writes the connection string, with the password, to the console (TASK-189).
61
+ - `spExecute` closes its connection after the statement, also when it fails; before, every call left a connection open (TASK-189).
62
+ - `query` of `@mielk/db/mssql` rejects once with the error of the driver; before, a failed query could reject without an error (TASK-189).
63
+ - A `;`, `=` or brace in a value of the MS SQL configuration (e.g. in the password) can no longer change the connection string (TASK-189).
64
+
65
+ ## [2.1.0](https://github.com/mielk/mielk-db/compare/v2.0.1...v2.1.0) (2026-04-19)
66
+
67
+ ### [2.0.1](https://github.com/mielk/mielk-db/compare/v2.0.0...v2.0.1) (2026-04-19)
68
+
69
+ ## 2.0.0 (2026-04-19)
70
+
71
+ ### ⚠ BREAKING CHANGES
72
+
73
+ - Change library purpose.
74
+
75
+ ### Features
76
+
77
+ - Change library purpose. ([8f3b3b3](https://github.com/mielk/mielk-db/commit/8f3b3b3fa1c8799abac0bc1577050228feb53f34))
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mielk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,251 @@
1
- # Temporary Holding Version
1
+ # @mielk/db
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Database access for mielk applications on Node.js: a PostgreSQL connection pool with transactions that follow the
4
+ asynchronous call chain (`@mielk/db/pg`), and simple queries and stored procedure calls on Microsoft SQL Server
5
+ over ODBC (`@mielk/db/mssql`). Errors of the library have stable codes, with texts in several languages for
6
+ display. The library is written in TypeScript and published to npm as an ES module with type declarations.
7
+
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
10
+ [CHANGELOG.md](CHANGELOG.md).
11
+
12
+ ## Requirements
13
+
14
+ - Node.js 24 or later (`engines.node: >=24`); development uses the version in `.nvmrc` (24.13.0).
15
+ - Optional peer dependencies, each needed only by the entry point that uses it:
16
+
17
+ | Peer dependency | Range | Needed by |
18
+ | --------------- | ----- | ------------------------------------------------------------------------------------------------ |
19
+ | `pg` | `^8` | `@mielk/db/pg` |
20
+ | `@types/pg` | `^8` | `@mielk/db/pg` in a TypeScript application (its types, e.g. `QueryResult`, are part of the API) |
21
+ | `msnodesqlv8` | `^5` | `@mielk/db/mssql` (native module; needs an ODBC driver for SQL Server installed on the computer) |
22
+
23
+ - ES modules: the package has no CommonJS build (`require` works only through dynamic `import()`).
24
+
25
+ ## Installation
26
+
27
+ ```bash
28
+ # PostgreSQL (TypeScript application):
29
+ npm install @mielk/db pg @types/pg
30
+ # PostgreSQL (JavaScript application):
31
+ npm install @mielk/db pg
32
+ # MS SQL:
33
+ npm install @mielk/db msnodesqlv8
34
+ ```
35
+
36
+ ## Entry points
37
+
38
+ | Entry point | Purpose | Environments |
39
+ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- |
40
+ | `@mielk/db/pg` | `initDb`, `closeDb`, `query`, `withTransaction`, `getQueryExecutor`, `getDbErrorKind`, `isUniqueViolation`, `DbError`, `DB_ERROR_CODES`; types `PgConfig`, `QueryExecutor`, `DbErrorKind`, `DbErrorCode` | Node.js only |
41
+ | `@mielk/db/mssql` | `initDb`, `closeDb`, `query`, `spExecute`, `getDbErrorKind`, `isUniqueViolation`, `DbError`, `DB_ERROR_CODES`; types `MsSqlConfig`, `MsSqlRow`, `DbErrorKind`, `DbErrorCode` | Node.js only |
42
+ | `@mielk/db/locales/<language>` | Texts of the error codes as JSON (`en`, `pl`), without any driver | all (data only) |
43
+
44
+ The package has no main entry point: import from `@mielk/db/pg` or `@mielk/db/mssql`. Each export is documented
45
+ with TSDoc in the source; editors show the description, parameters and errors.
46
+
47
+ ## Usage: PostgreSQL
48
+
49
+ ```ts
50
+ import { closeDb, initDb, query, withTransaction } from '@mielk/db/pg';
51
+
52
+ // Once, at application start-up.
53
+ initDb({
54
+ host: 'localhost',
55
+ port: 5432,
56
+ user: 'app',
57
+ password: secret,
58
+ database: 'shop',
59
+ onError: (error) => logger.error(error),
60
+ });
61
+
62
+ const { rows } = await query<{ id: number; name: string }>('SELECT id, name FROM product WHERE id = $1', [42]);
63
+
64
+ await withTransaction(async () => {
65
+ await query('UPDATE stock SET quantity = quantity - $1 WHERE product_id = $2', [1, 42]);
66
+ await query('INSERT INTO order_line (product_id, quantity) VALUES ($1, $2)', [42, 1]);
67
+ });
68
+
69
+ // When the application shuts down.
70
+ await closeDb();
71
+ ```
72
+
73
+ ### Transactions
74
+
75
+ - `withTransaction(fn)` takes a connection from the pool, runs `BEGIN`, then `fn`, and commits when `fn` resolves.
76
+ When `fn` or the commit rejects, it rolls back and rejects with the original error. A connection whose
77
+ `ROLLBACK` fails is destroyed instead of returned to the pool.
78
+ - The transaction belongs to the asynchronous call chain of `fn` (`AsyncLocalStorage`): `query` and
79
+ `getQueryExecutor` called anywhere inside `fn`, also in other modules, use the transaction connection. Parallel
80
+ requests of a server each get their own transaction, and code outside `withTransaction` always uses the pool.
81
+ - The transaction ends when `fn` settles. An operation that `fn` started without awaiting it and that calls `query`,
82
+ `getQueryExecutor` or `withTransaction` later fails with `PG_TRANSACTION_ENDED`: it never runs on the connection,
83
+ which then goes back to the pool, and never silently outside the transaction. Await all work of `fn`.
84
+ - A `withTransaction` called inside another joins the outer transaction: it opens no transaction of its own, and
85
+ an error anywhere rolls back the whole one. This holds also when `fn` catches the error of a nested call: the
86
+ outer `withTransaction` then rolls back and rejects with `PG_NESTED_TRANSACTION_FAILED`, whose `cause` is the
87
+ first error of a nested call.
88
+ - PostgreSQL aborts a transaction after any failed statement. An error caught inside `fn` and not rethrown still
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
+ - `getQueryExecutor()` returns the transaction connection inside `withTransaction` and the pool outside it. Call it
93
+ for each unit of work rather than keeping the result: an executor taken outside a transaction stays the pool
94
+ also when used inside one. Most code needs only `query`.
95
+
96
+ ## Usage: MS SQL
97
+
98
+ ```ts
99
+ import { closeDb, initDb, query, spExecute } from '@mielk/db/mssql';
100
+
101
+ initDb({
102
+ host: 'localhost\\SQLEXPRESS',
103
+ database: 'shop',
104
+ user: 'app',
105
+ password: secret,
106
+ driver: 'ODBC Driver 18 for SQL Server', // without braces
107
+ onError: (error) => logger.error(error),
108
+ });
109
+
110
+ const rows = await query('SELECT id, name FROM dbo.product WHERE id = ?', [42]);
111
+ const result = await spExecute('EXEC dbo.saveOrder ?, ?', [42, 1]);
112
+
113
+ await closeDb();
114
+ ```
115
+
116
+ - Every `query` and `spExecute` opens its own connection and closes it afterwards; there is no pool and no
117
+ transaction across calls.
118
+ - `query` returns the rows of the first result set as `MsSqlRow[]` (`Record<string, unknown>`): the driver does not
119
+ know the shape of a row, so the application validates it before use.
120
+ - `spExecute` returns the first result set in the raw form of the driver (column metadata and rows as arrays), or
121
+ `undefined` when the statement returns none.
122
+ - Values of the connection string are quoted, so a `;`, `=` or brace in a password cannot change the connection.
123
+ - `msnodesqlv8` is loaded on the first query, so an application that uses only `@mielk/db/pg` does not need it.
124
+
125
+ ## Configuration
126
+
127
+ The library reads no environment variables and no files; configuration is passed to `initDb`.
128
+
129
+ - `PgConfig`: required `host`, `port`, `user`, `password`, `database`; optional `onError` and every other setting
130
+ of `PoolConfig` from `pg` (e.g. `ssl`, `application_name`, `statement_timeout`), passed to the pool unchanged.
131
+ Pool defaults: `max` 10, `min` 0, `idleTimeoutMillis` 30 000, `connectionTimeoutMillis` 10 000.
132
+ - `MsSqlConfig`: required `host`, `database`, `user`, `password`, `driver` (name of the installed ODBC driver,
133
+ without braces); optional `onError`.
134
+ - `onError` receives errors that the library cannot pass to a caller, as a `DbError` with the driver error as
135
+ `cause`: an error of an idle PostgreSQL connection (`PG_UNEXPECTED_ERROR`) and a failure to close an MS SQL
136
+ connection after `spExecute` (`MSSQL_CLOSE_FAILED`). Without `onError` they are ignored.
137
+
138
+ `initDb` is called once per process. A second call throws `*_ALREADY_INITIALIZED`, also with the same settings;
139
+ call `closeDb` first to connect again.
140
+
141
+ ## Side effects
142
+
143
+ - `@mielk/db/pg` opens network connections to the PostgreSQL server: the pool opens them when a query needs one
144
+ and closes idle ones after `idleTimeoutMillis`. `closeDb` closes all of them.
145
+ - `@mielk/db/mssql` opens one connection per call through the ODBC driver and closes it afterwards.
146
+ - The library writes nothing to the console or to files, and changes no global state when imported. The state of
147
+ the connection (pool or settings) is kept in the module, once per process and entry point.
148
+
149
+ ## Errors
150
+
151
+ Errors of the library are `DbError` objects: `code` identifies the error (compare it with `DB_ERROR_CODES`, never
152
+ the message), `message` is the English text for logs, and `cause` holds the original error, if there was one.
153
+
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_ABORTED` | `withTransaction` | PostgreSQL rolled back the aborted transaction in response to `COMMIT` |
160
+ | `PG_TRANSACTION_ENDED` | `query`, `withTransaction`, `getQueryExecutor` | called by an operation of `fn` after its transaction ended |
161
+ | `PG_UNEXPECTED_ERROR` | passed to `onError` (pg) | an idle connection of the pool failed (e.g. the server closed it) |
162
+ | `MSSQL_ALREADY_INITIALIZED` | `initDb` (mssql) | the settings are stored; call `closeDb` first |
163
+ | `MSSQL_NOT_INITIALIZED` | `query`, `spExecute` (mssql) | `initDb` has not been called |
164
+ | `MSSQL_DRIVER_NOT_INSTALLED` | `query`, `spExecute` (mssql) | `msnodesqlv8` cannot be loaded; the import error is the `cause` |
165
+ | `MSSQL_CLOSE_FAILED` | passed to `onError` (mssql) | closing the connection of `spExecute` failed |
166
+
167
+ Asynchronous functions report these errors as rejections. Errors of the server and the driver (failed connection,
168
+ failed query, `BEGIN`, `COMMIT`) are passed to the caller unchanged, not wrapped in `DbError`. `query` of
169
+ `@mielk/db/mssql` rejects with a `TypeError` when the driver returns a result row that is not an object. When the
170
+ driver reports a failed statement of `spExecute` with an object that is not an `Error`, `spExecute` rejects with an
171
+ `Error` that has the same fields (`code`, `sqlstate`, ...) and the original object as `cause`, so `getDbErrorKind`
172
+ recognises it.
173
+
174
+ ### Texts of the error codes
175
+
176
+ A code has the form `<namespace>:<key>`, which is also the i18next key of its text in `@mielk/db/locales/<language>`
177
+ (English and Polish), so an application can show a translated message:
178
+
179
+ ```ts
180
+ import i18next from 'i18next';
181
+ import pl from '@mielk/db/locales/pl' with { type: 'json' };
182
+
183
+ for (const [namespace, texts] of Object.entries(pl)) i18next.addResourceBundle('pl', namespace, texts);
184
+
185
+ i18next.t(error.code); // 'Połączenie z PostgreSQL nie jest zainicjowane: najpierw wywołaj initDb.'
186
+ ```
187
+
188
+ ### Recognising server errors
189
+
190
+ `getDbErrorKind(err)` maps a server error to a kind that an application usually handles differently from a generic
191
+ error: with a message for the user (constraint violations) or by retrying the transaction. It returns `undefined`
192
+ for any other value. `isUniqueViolation(err)` is a shorthand for `getDbErrorKind(err) === 'uniqueViolation'`.
193
+
194
+ | Kind | PostgreSQL (SQLSTATE) | MS SQL (error number) |
195
+ | ---------------------- | --------------------- | --------------------- |
196
+ | `uniqueViolation` | `23505` | 2627, 2601 |
197
+ | `foreignKeyViolation` | `23503` | — |
198
+ | `checkViolation` | `23514` | — |
199
+ | `constraintViolation` | — | 547 |
200
+ | `notNullViolation` | `23502` | 515 |
201
+ | `serializationFailure` | `40001` | — |
202
+ | `deadlock` | `40P01` | 1205 |
203
+
204
+ SQL Server reports foreign key and CHECK violations with the same number 547 and tells them apart only in the
205
+ message text, which depends on the server language, so `@mielk/db/mssql` reports both as `constraintViolation`.
206
+
207
+ ## Development
208
+
209
+ | Command | Purpose |
210
+ | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
211
+ | `npm ci` | install dependencies from `package-lock.json` |
212
+ | `npm test` | all unit tests (Vitest) with coverage; threshold 80% of lines and branches; the report is written to the system temp folder |
213
+ | `npm run test:pg` | PostgreSQL integration test against a temporary local database |
214
+ | `npm run test:watch` | tests in watch mode |
215
+ | `npm run typecheck` | TypeScript check without output |
216
+ | `npm run lint` | ESLint with type information, no warnings allowed |
217
+ | `npm run format` / `npm run format:check` | Prettier |
218
+ | `npm run build` | compiles `src` to `dist` (clears the content of `dist`, keeps the folder) |
219
+ | `npm run dev` | build in watch mode |
220
+ | `npm run check:package` | `mielk-check-package` from `@mielk/lib-config`: `publint --strict`, `attw` and the package file list |
221
+
222
+ `prepublishOnly` runs typecheck, lint, tests, build and the package check.
223
+ The TypeScript, ESLint, Prettier and Vitest configuration comes from the shared package `@mielk/lib-config`
224
+ (development dependency); the files in this repository only extend it.
225
+ Unit tests replace `pg` and `msnodesqlv8` with test doubles. Run the PostgreSQL integration test separately with
226
+ `npm run test:pg`.
227
+
228
+ Start a dedicated local PostgreSQL 16 test cluster on `127.0.0.1`. Set `MIELK_DB_TEST_PG_PORT` to its port and
229
+ `MIELK_DB_TEST_PG_USER` to a bootstrap login with `CREATEDB` and `CREATEROLE` privileges and access to the
230
+ `postgres` maintenance database. Set `MIELK_DB_TEST_PG_PASSWORD` if the login requires a password. The cluster
231
+ must allow the generated test login to connect over loopback. The suite creates a uniquely named database and
232
+ login for each run and drops both during teardown. If the port or bootstrap login is missing, the suite prints
233
+ the missing variables and skips the test.
234
+
235
+ ## Releases and changes
236
+
237
+ Changes are listed by hand in [CHANGELOG.md](CHANGELOG.md) under `Unreleased`; it also holds the migration notes
238
+ between major versions. `npm version <major|minor|patch>` moves the entries to the new version
239
+ (`mielk-release-changelog` from `@mielk/lib-config`) and creates the release commit and tag.
240
+
241
+ ## Documentation scope
242
+
243
+ Deviation from the documentation standard (`doc:SCP-1`, `doc:SCP-4`), as approved by the user for the mielk
244
+ libraries on 2026-11-13 (TASK-188) and applied to this library in TASK-189: the library has no generated user and
245
+ technical documentation sites, API reference or agent documentation (`doc/agent/CORE.md`), because the
246
+ documentation generator for TypeScript (TASK-197) is not finished yet. Until it is, this README, the TSDoc
247
+ comments of every export and [CHANGELOG.md](CHANGELOG.md) are the complete documentation.
248
+
249
+ ## License
250
+
251
+ [MIT](LICENSE)
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Codes of the errors thrown by the library, shared by `@mielk/db/pg` and `@mielk/db/mssql`.
3
+ *
4
+ * A code has the form `<namespace>:<key>`, which is also the i18next key of its text in the
5
+ * `@mielk/db/locales/<language>` files, so an application can show a translated text for an error code.
6
+ */
7
+ export declare const DB_ERROR_CODES: {
8
+ readonly MSSQL_ALREADY_INITIALIZED: "db/mssql/connection:alreadyInitialized";
9
+ readonly MSSQL_CLOSE_FAILED: "db/mssql/connection:closeFailed";
10
+ readonly MSSQL_DRIVER_NOT_INSTALLED: "db/mssql/connection:driverNotInstalled";
11
+ readonly MSSQL_NOT_INITIALIZED: "db/mssql/connection:notInitialized";
12
+ readonly PG_ALREADY_INITIALIZED: "db/pg/connection:alreadyInitialized";
13
+ readonly PG_NESTED_TRANSACTION_FAILED: "db/pg/transaction:nestedFailed";
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";
17
+ readonly PG_TRANSACTION_ENDED: "db/pg/transaction:ended";
18
+ readonly PG_UNEXPECTED_ERROR: "db/pg/connection:unexpectedError";
19
+ };
20
+ /** Code of an error thrown by the library: one of the values of {@link DB_ERROR_CODES}. */
21
+ export type DbErrorCode = (typeof DB_ERROR_CODES)[keyof typeof DB_ERROR_CODES];
22
+ /**
23
+ * Error thrown by the library. `code` identifies the error (compare it with {@link DB_ERROR_CODES}, never the
24
+ * message); `message` is the English text for logs; `cause` holds the original error, if there was one.
25
+ */
26
+ export declare class DbError extends Error {
27
+ readonly name = "DbError";
28
+ readonly code: DbErrorCode;
29
+ constructor(code: DbErrorCode, options?: ErrorOptions);
30
+ }
@@ -0,0 +1,43 @@
1
+ import en from '../locales/en.json' with { type: 'json' };
2
+ /**
3
+ * Codes of the errors thrown by the library, shared by `@mielk/db/pg` and `@mielk/db/mssql`.
4
+ *
5
+ * A code has the form `<namespace>:<key>`, which is also the i18next key of its text in the
6
+ * `@mielk/db/locales/<language>` files, so an application can show a translated text for an error code.
7
+ */
8
+ export const DB_ERROR_CODES = {
9
+ MSSQL_ALREADY_INITIALIZED: 'db/mssql/connection:alreadyInitialized',
10
+ MSSQL_CLOSE_FAILED: 'db/mssql/connection:closeFailed',
11
+ MSSQL_DRIVER_NOT_INSTALLED: 'db/mssql/connection:driverNotInstalled',
12
+ MSSQL_NOT_INITIALIZED: 'db/mssql/connection:notInitialized',
13
+ PG_ALREADY_INITIALIZED: 'db/pg/connection:alreadyInitialized',
14
+ PG_NESTED_TRANSACTION_FAILED: 'db/pg/transaction:nestedFailed',
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',
18
+ PG_TRANSACTION_ENDED: 'db/pg/transaction:ended',
19
+ PG_UNEXPECTED_ERROR: 'db/pg/connection:unexpectedError',
20
+ };
21
+ const ENGLISH_TEXTS = en;
22
+ /**
23
+ * Returns the English text of an error code from `locales/en.json`, or the code itself when the text is missing
24
+ * (a unit test keeps every code covered, so the fallback only guards against a broken build).
25
+ */
26
+ const getEnglishText = (code) => {
27
+ const separator = code.indexOf(':');
28
+ const namespace = code.slice(0, separator);
29
+ const key = code.slice(separator + 1);
30
+ return ENGLISH_TEXTS[namespace]?.[key] ?? code;
31
+ };
32
+ /**
33
+ * Error thrown by the library. `code` identifies the error (compare it with {@link DB_ERROR_CODES}, never the
34
+ * message); `message` is the English text for logs; `cause` holds the original error, if there was one.
35
+ */
36
+ export class DbError extends Error {
37
+ name = 'DbError';
38
+ code;
39
+ constructor(code, options) {
40
+ super(getEnglishText(code), options);
41
+ this.code = code;
42
+ }
43
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "db/mssql/connection": {
3
+ "alreadyInitialized": "The MS SQL connection is already initialised: call closeDb before calling initDb again.",
4
+ "closeFailed": "Closing an MS SQL connection failed.",
5
+ "driverNotInstalled": "The MS SQL driver (msnodesqlv8) is not installed.",
6
+ "notInitialized": "The MS SQL connection is not initialised: call initDb first."
7
+ },
8
+ "db/pg/connection": {
9
+ "alreadyInitialized": "The PostgreSQL connection is already initialised: call closeDb before calling initDb again.",
10
+ "notInitialized": "The PostgreSQL connection is not initialised: call initDb first.",
11
+ "unexpectedError": "Unexpected error of an idle PostgreSQL connection."
12
+ },
13
+ "db/pg/transaction": {
14
+ "aborted": "PostgreSQL rolled back the aborted transaction when asked to commit.",
15
+ "ended": "The transaction of this call chain has already ended: a query started inside withTransaction cannot run after it.",
16
+ "nestedFailed": "A nested withTransaction failed and its error was caught: the whole transaction is rolled back."
17
+ }
18
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "db/mssql/connection": {
3
+ "alreadyInitialized": "Połączenie z MS SQL jest już zainicjowane: przed ponownym initDb wywołaj closeDb.",
4
+ "closeFailed": "Nie udało się zamknąć połączenia z MS SQL.",
5
+ "driverNotInstalled": "Sterownik MS SQL (msnodesqlv8) nie jest zainstalowany.",
6
+ "notInitialized": "Połączenie z MS SQL nie jest zainicjowane: najpierw wywołaj initDb."
7
+ },
8
+ "db/pg/connection": {
9
+ "alreadyInitialized": "Połączenie z PostgreSQL jest już zainicjowane: przed ponownym initDb wywołaj closeDb.",
10
+ "notInitialized": "Połączenie z PostgreSQL nie jest zainicjowane: najpierw wywołaj initDb.",
11
+ "unexpectedError": "Nieoczekiwany błąd bezczynnego połączenia z PostgreSQL."
12
+ },
13
+ "db/pg/transaction": {
14
+ "aborted": "PostgreSQL wycofał przerwaną transakcję przy próbie zatwierdzenia.",
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
+ "nestedFailed": "Zagnieżdżone withTransaction nie powiodło się, a jego błąd został przechwycony: cała transakcja zostaje wycofana."
17
+ }
18
+ }
@@ -0,0 +1,48 @@
1
+ import type { RawData, SqlClient, sqlQueryParamType } from 'msnodesqlv8/types';
2
+ import type { MsSqlConfig } from '../types/db-config.js';
3
+ /**
4
+ * A row of a query result: column name to value. The driver does not know the shape of the row, so the
5
+ * application validates it before use.
6
+ */
7
+ export type MsSqlRow = Record<string, unknown>;
8
+ /**
9
+ * Loads the optional `msnodesqlv8` driver on first use, so that an application using only `@mielk/db/pg` does
10
+ * not need it installed.
11
+ *
12
+ * @throws {DbError} `MSSQL_DRIVER_NOT_INSTALLED` with the import error as `cause`.
13
+ */
14
+ export declare const getMsSql: () => Promise<SqlClient>;
15
+ /**
16
+ * Stores the connection settings. Opens no connection: every query opens its own.
17
+ *
18
+ * @throws {DbError} `MSSQL_ALREADY_INITIALIZED` when called again before {@link closeDb}.
19
+ */
20
+ export declare const initDb: (config: MsSqlConfig) => void;
21
+ /**
22
+ * Forgets the connection settings; {@link initDb} can be called again afterwards. There is no pool to close: the
23
+ * function exists so that `@mielk/db/mssql` and `@mielk/db/pg` are used the same way.
24
+ */
25
+ export declare const closeDb: () => Promise<void>;
26
+ /**
27
+ * Runs a query on its own connection, which the driver closes afterwards, and returns the rows of the first
28
+ * result set.
29
+ *
30
+ * @param text SQL text with `?` placeholders.
31
+ * @param params Values of the placeholders, passed to the server separately from the text.
32
+ * @throws {DbError} `MSSQL_NOT_INITIALIZED` (as a rejection) when {@link initDb} has not been called.
33
+ * @throws {DbError} `MSSQL_DRIVER_NOT_INSTALLED` when `msnodesqlv8` is not installed.
34
+ * @throws The error of the driver when the connection or the query fails.
35
+ */
36
+ export declare function query(text: string, params?: sqlQueryParamType[]): Promise<MsSqlRow[]>;
37
+ /**
38
+ * Runs a statement (typically a stored procedure call) on its own connection and returns the first result set
39
+ * in the raw form of the driver (column metadata and rows as arrays). The connection is closed afterwards, also
40
+ * when the statement fails.
41
+ *
42
+ * @param sqlText SQL text with `?` placeholders, e.g. `EXEC dbo.saveOrder ?, ?`.
43
+ * @param params Values of the placeholders.
44
+ * @returns The first result set, or `undefined` when the statement returns none.
45
+ * @throws {DbError} `MSSQL_NOT_INITIALIZED` (as a rejection) when {@link initDb} has not been called.
46
+ * @throws The error of the driver when the connection or the statement fails.
47
+ */
48
+ export declare function spExecute(sqlText: string, params?: sqlQueryParamType[]): Promise<RawData | undefined>;
@@ -0,0 +1,122 @@
1
+ import { DB_ERROR_CODES, DbError } from '../../errors/db-error.js';
2
+ let sql = null;
3
+ let active = null;
4
+ /**
5
+ * Loads the optional `msnodesqlv8` driver on first use, so that an application using only `@mielk/db/pg` does
6
+ * not need it installed.
7
+ *
8
+ * @throws {DbError} `MSSQL_DRIVER_NOT_INSTALLED` with the import error as `cause`.
9
+ */
10
+ export const getMsSql = async () => {
11
+ if (!sql) {
12
+ try {
13
+ sql = await import('msnodesqlv8');
14
+ }
15
+ catch (err) {
16
+ throw new DbError(DB_ERROR_CODES.MSSQL_DRIVER_NOT_INSTALLED, { cause: err });
17
+ }
18
+ }
19
+ return sql;
20
+ };
21
+ /**
22
+ * Quotes a value of an ODBC connection string: in braces, with every `}` doubled, so that a `;`, `=` or brace in a
23
+ * value (e.g. in the password) cannot end the value or add parameters.
24
+ */
25
+ const quoteOdbcValue = (value) => `{${value.replaceAll('}', '}}')}}`;
26
+ /**
27
+ * Stores the connection settings. Opens no connection: every query opens its own.
28
+ *
29
+ * @throws {DbError} `MSSQL_ALREADY_INITIALIZED` when called again before {@link closeDb}.
30
+ */
31
+ export const initDb = (config) => {
32
+ if (active)
33
+ throw new DbError(DB_ERROR_CODES.MSSQL_ALREADY_INITIALIZED);
34
+ const { host, database, user, password, driver, onError } = config;
35
+ const parameters = [
36
+ ['Driver', driver],
37
+ ['Server', host],
38
+ ['Database', database],
39
+ ['UID', user],
40
+ ['PWD', password],
41
+ ];
42
+ const connectionString = parameters.map(([name, value]) => `${name}=${quoteOdbcValue(value)}`).join(';');
43
+ active = { connectionString, onError };
44
+ };
45
+ /**
46
+ * Forgets the connection settings; {@link initDb} can be called again afterwards. There is no pool to close: the
47
+ * function exists so that `@mielk/db/mssql` and `@mielk/db/pg` are used the same way.
48
+ */
49
+ export const closeDb = () => {
50
+ active = null;
51
+ return Promise.resolve();
52
+ };
53
+ const getActive = () => {
54
+ if (active === null)
55
+ throw new DbError(DB_ERROR_CODES.MSSQL_NOT_INITIALIZED);
56
+ return active;
57
+ };
58
+ const isRow = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
59
+ /**
60
+ * Runs a query on its own connection, which the driver closes afterwards, and returns the rows of the first
61
+ * result set.
62
+ *
63
+ * @param text SQL text with `?` placeholders.
64
+ * @param params Values of the placeholders, passed to the server separately from the text.
65
+ * @throws {DbError} `MSSQL_NOT_INITIALIZED` (as a rejection) when {@link initDb} has not been called.
66
+ * @throws {DbError} `MSSQL_DRIVER_NOT_INSTALLED` when `msnodesqlv8` is not installed.
67
+ * @throws The error of the driver when the connection or the query fails.
68
+ */
69
+ export async function query(text, params = []) {
70
+ const { connectionString } = getActive();
71
+ const client = await getMsSql();
72
+ const results = await client.promises.query(connectionString, text, params);
73
+ const rows = results.first ?? [];
74
+ return rows.map((row) => {
75
+ if (!isRow(row))
76
+ throw new TypeError('msnodesqlv8 returned a result row that is not an object');
77
+ return row;
78
+ });
79
+ }
80
+ /**
81
+ * Runs a statement (typically a stored procedure call) on its own connection and returns the first result set
82
+ * in the raw form of the driver (column metadata and rows as arrays). The connection is closed afterwards, also
83
+ * when the statement fails.
84
+ *
85
+ * @param sqlText SQL text with `?` placeholders, e.g. `EXEC dbo.saveOrder ?, ?`.
86
+ * @param params Values of the placeholders.
87
+ * @returns The first result set, or `undefined` when the statement returns none.
88
+ * @throws {DbError} `MSSQL_NOT_INITIALIZED` (as a rejection) when {@link initDb} has not been called.
89
+ * @throws The error of the driver when the connection or the statement fails.
90
+ */
91
+ export async function spExecute(sqlText, params = []) {
92
+ const { connectionString, onError } = getActive();
93
+ const client = await getMsSql();
94
+ const connection = await client.promises.open(connectionString);
95
+ try {
96
+ return await new Promise((resolve, reject) => {
97
+ let first;
98
+ // The driver calls back once per result set; `more` is false on the last one. The callback is typed
99
+ // explicitly: the overloads of queryRaw leave its parameters without a contextual type.
100
+ const onResultSet = (err, raw, more) => {
101
+ if (err) {
102
+ // The driver types its errors with its own Error interface; at run time they are Error objects.
103
+ // Any other object is wrapped with its fields copied (`code` is the SQL Server error number,
104
+ // also `sqlstate`, `severity`, ...), so that getDbErrorKind and isUniqueViolation recognise it.
105
+ reject(err instanceof Error ? err : Object.assign(new Error(err.message, { cause: err }), err));
106
+ return;
107
+ }
108
+ first ??= raw;
109
+ if (!more)
110
+ resolve(first);
111
+ };
112
+ connection.queryRaw(sqlText, params, onResultSet);
113
+ });
114
+ }
115
+ finally {
116
+ // The result, or the error of the statement, matters more to the caller than a failed close, so the close
117
+ // error is only reported.
118
+ await connection.promises
119
+ .close()
120
+ .catch((err) => onError?.(new DbError(DB_ERROR_CODES.MSSQL_CLOSE_FAILED, { cause: err })));
121
+ }
122
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Kind of an MS SQL error that an application usually handles differently from a generic server error:
3
+ * with a message for the user (constraint violations) or by retrying the transaction (`deadlock`).
4
+ *
5
+ * `constraintViolation` covers both a foreign key and a CHECK constraint: SQL Server reports both with error
6
+ * number 547 and tells them apart only in the message text, which depends on the server language.
7
+ */
8
+ export type DbErrorKind = 'uniqueViolation' | 'constraintViolation' | 'notNullViolation' | 'deadlock';
9
+ /**
10
+ * Recognises an error of the `msnodesqlv8` driver by its SQL Server error number (the `code` property).
11
+ *
12
+ * @param err Any value caught in a `catch` block.
13
+ * @returns The kind of the error, or `undefined` for any other error, for a value without an error number
14
+ * and for `null` or `undefined`.
15
+ */
16
+ export declare const getDbErrorKind: (err: unknown) => DbErrorKind | undefined;
17
+ /**
18
+ * Checks whether an error of the `msnodesqlv8` driver is a unique constraint or unique index violation
19
+ * (error numbers 2627 and 2601); shorthand for `getDbErrorKind(err) === 'uniqueViolation'`.
20
+ *
21
+ * @param err Any value caught in a `catch` block.
22
+ */
23
+ export declare const isUniqueViolation: (err: unknown) => boolean;
@@ -0,0 +1,27 @@
1
+ // Error numbers: https://learn.microsoft.com/sql/relational-databases/errors-events/database-engine-events-and-errors
2
+ const KINDS_BY_ERROR_NUMBER = new Map([
3
+ [2627, 'uniqueViolation'], // violation of a PRIMARY KEY or UNIQUE constraint
4
+ [2601, 'uniqueViolation'], // duplicate key in a unique index
5
+ [547, 'constraintViolation'],
6
+ [515, 'notNullViolation'],
7
+ [1205, 'deadlock'],
8
+ ]);
9
+ /**
10
+ * Recognises an error of the `msnodesqlv8` driver by its SQL Server error number (the `code` property).
11
+ *
12
+ * @param err Any value caught in a `catch` block.
13
+ * @returns The kind of the error, or `undefined` for any other error, for a value without an error number
14
+ * and for `null` or `undefined`.
15
+ */
16
+ export const getDbErrorKind = (err) => {
17
+ if (typeof err !== 'object' || err === null || !('code' in err))
18
+ return undefined;
19
+ return typeof err.code === 'number' ? KINDS_BY_ERROR_NUMBER.get(err.code) : undefined;
20
+ };
21
+ /**
22
+ * Checks whether an error of the `msnodesqlv8` driver is a unique constraint or unique index violation
23
+ * (error numbers 2627 and 2601); shorthand for `getDbErrorKind(err) === 'uniqueViolation'`.
24
+ *
25
+ * @param err Any value caught in a `catch` block.
26
+ */
27
+ export const isUniqueViolation = (err) => getDbErrorKind(err) === 'uniqueViolation';
@@ -0,0 +1,11 @@
1
+ import { initDb, closeDb, query, spExecute } from './connection/pool.js';
2
+ import type { MsSqlRow } from './connection/pool.js';
3
+ import type { MsSqlConfig } from './types/db-config.js';
4
+ import type { DbErrorKind } from './errors/error-kind.js';
5
+ import type { DbErrorCode } from '../errors/db-error.js';
6
+ import { getDbErrorKind, isUniqueViolation } from './errors/error-kind.js';
7
+ import { DB_ERROR_CODES, DbError } from '../errors/db-error.js';
8
+ export { initDb, closeDb, query, spExecute };
9
+ export type { MsSqlConfig, MsSqlRow, DbErrorKind, DbErrorCode };
10
+ export { getDbErrorKind, isUniqueViolation };
11
+ export { DB_ERROR_CODES, DbError };
@@ -0,0 +1,9 @@
1
+ // Entry point '@mielk/db/mssql': queries and stored procedure calls on Microsoft SQL Server over ODBC, one
2
+ // connection per call, and recognition of server errors. Environment: Node.js only; requires the optional peer
3
+ // dependency msnodesqlv8.
4
+ import { initDb, closeDb, query, spExecute } from './connection/pool.js';
5
+ import { getDbErrorKind, isUniqueViolation } from './errors/error-kind.js';
6
+ import { DB_ERROR_CODES, DbError } from '../errors/db-error.js';
7
+ export { initDb, closeDb, query, spExecute };
8
+ export { getDbErrorKind, isUniqueViolation };
9
+ export { DB_ERROR_CODES, DbError };
@@ -0,0 +1,17 @@
1
+ import type { DbError } from '../../errors/db-error.js';
2
+ /** Settings of the MS SQL connection. Every query opens its own connection and closes it afterwards. */
3
+ export type MsSqlConfig = {
4
+ /** Server name, e.g. `localhost\SQLEXPRESS` or `db.example.com,1433`. */
5
+ host: string;
6
+ database: string;
7
+ user: string;
8
+ password: string;
9
+ /** Name of the ODBC driver installed on the computer, without braces, e.g. `ODBC Driver 18 for SQL Server`. */
10
+ driver: string;
11
+ /**
12
+ * Receives an error that the library cannot pass to a caller, as a `DbError` with the driver error as `cause`:
13
+ * today only a failure to close the connection of `spExecute` (`MSSQL_CLOSE_FAILED`). Without it such errors
14
+ * are ignored; the library never writes to the console.
15
+ */
16
+ onError?: (error: DbError) => void;
17
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import { Pool } from 'pg';
2
+ import type { PgConfig } from '../types/db-config.js';
3
+ /**
4
+ * Creates the connection pool. The pool opens connections only when a query needs them.
5
+ *
6
+ * The application calls it once, at start-up. A second call, with any settings, is most likely a mistake (two
7
+ * modules each configuring the database), so it throws instead of silently keeping one of the configurations.
8
+ *
9
+ * @throws {DbError} `PG_ALREADY_INITIALIZED` when the pool exists; call {@link closeDb} first to connect again.
10
+ */
11
+ export declare const initDb: (dbConfig: PgConfig) => void;
12
+ /**
13
+ * Closes all connections of the pool; {@link initDb} can be called again afterwards.
14
+ * Does nothing when there is no pool. Call it when the application shuts down, so that the process does not wait
15
+ * for idle connections to time out.
16
+ *
17
+ * @throws The error of `pool.end()`.
18
+ */
19
+ export declare const closeDb: () => Promise<void>;
20
+ /**
21
+ * Returns the pool created by {@link initDb}.
22
+ *
23
+ * @throws {DbError} `PG_NOT_INITIALIZED` when {@link initDb} has not been called.
24
+ */
25
+ export declare const getPool: () => Pool;
@@ -0,0 +1,49 @@
1
+ import { Pool } from 'pg';
2
+ import { DB_ERROR_CODES, DbError } from '../../errors/db-error.js';
3
+ const POOL_DEFAULTS = {
4
+ max: 10,
5
+ min: 0,
6
+ idleTimeoutMillis: 30_000,
7
+ connectionTimeoutMillis: 10_000,
8
+ };
9
+ let pool = null;
10
+ /**
11
+ * Creates the connection pool. The pool opens connections only when a query needs them.
12
+ *
13
+ * The application calls it once, at start-up. A second call, with any settings, is most likely a mistake (two
14
+ * modules each configuring the database), so it throws instead of silently keeping one of the configurations.
15
+ *
16
+ * @throws {DbError} `PG_ALREADY_INITIALIZED` when the pool exists; call {@link closeDb} first to connect again.
17
+ */
18
+ export const initDb = (dbConfig) => {
19
+ if (pool)
20
+ throw new DbError(DB_ERROR_CODES.PG_ALREADY_INITIALIZED);
21
+ const { onError, ...poolConfig } = dbConfig;
22
+ const newPool = new Pool({ ...POOL_DEFAULTS, ...poolConfig });
23
+ // Without a listener, the 'error' event of an idle connection would crash the process. The pool removes the
24
+ // broken connection itself, so the error is only reported, and only to an application that asked for it.
25
+ newPool.on('error', (err) => onError?.(new DbError(DB_ERROR_CODES.PG_UNEXPECTED_ERROR, { cause: err })));
26
+ pool = newPool;
27
+ };
28
+ /**
29
+ * Closes all connections of the pool; {@link initDb} can be called again afterwards.
30
+ * Does nothing when there is no pool. Call it when the application shuts down, so that the process does not wait
31
+ * for idle connections to time out.
32
+ *
33
+ * @throws The error of `pool.end()`.
34
+ */
35
+ export const closeDb = async () => {
36
+ const closing = pool;
37
+ pool = null;
38
+ await closing?.end();
39
+ };
40
+ /**
41
+ * Returns the pool created by {@link initDb}.
42
+ *
43
+ * @throws {DbError} `PG_NOT_INITIALIZED` when {@link initDb} has not been called.
44
+ */
45
+ export const getPool = () => {
46
+ if (pool === null)
47
+ throw new DbError(DB_ERROR_CODES.PG_NOT_INITIALIZED);
48
+ return pool;
49
+ };
@@ -0,0 +1,37 @@
1
+ import type { QueryResult, QueryResultRow } from 'pg';
2
+ import type { QueryExecutor } from '../types/query-executor.js';
3
+ /**
4
+ * Returns the object to run queries with: the client of the transaction of the current call chain inside
5
+ * {@link withTransaction}, otherwise the pool. Call it for each unit of work rather than keeping the result: an
6
+ * executor taken outside a transaction stays the pool also when used inside one.
7
+ *
8
+ * @throws {DbError} `PG_NOT_INITIALIZED` when {@link initDb} has not been called.
9
+ * @throws {DbError} `PG_TRANSACTION_ENDED` when called in the call chain of a transaction that has already ended,
10
+ * e.g. from an operation that `fn` started without awaiting it.
11
+ */
12
+ export declare const getQueryExecutor: () => QueryExecutor;
13
+ /**
14
+ * Runs a query in the transaction of the current call chain inside {@link withTransaction}, otherwise on the pool;
15
+ * shorthand for `getQueryExecutor().query(text, params)`.
16
+ *
17
+ * @param text SQL text with placeholders `$1`, `$2`, ...
18
+ * @param params Values of the placeholders, passed to the server separately from the text.
19
+ * @throws {DbError} `PG_NOT_INITIALIZED` (as a rejection) when {@link initDb} has not been called.
20
+ * @throws {DbError} `PG_TRANSACTION_ENDED` (as a rejection) in the call chain of a transaction that has ended.
21
+ * @throws The error of the `pg` driver when the query fails.
22
+ */
23
+ export declare function query<T extends QueryResultRow = QueryResultRow>(text: string, params?: unknown[]): Promise<QueryResult<T>>;
24
+ /**
25
+ * Runs `fn` in a transaction and commits it when `fn` resolves, or rolls it back when `fn` or the commit rejects.
26
+ * Queries of `fn` take the transaction client from {@link getQueryExecutor}. A `withTransaction` called inside
27
+ * `fn` joins the outer transaction: it opens no transaction of its own, and its error rolls back the whole one, also
28
+ * when `fn` catches it.
29
+ *
30
+ * @throws The error of `fn`, of `BEGIN` or of `COMMIT`, unchanged; a failed `ROLLBACK` does not replace it.
31
+ * @throws {DbError} `PG_NESTED_TRANSACTION_FAILED` when `fn` resolves although a nested `withTransaction` failed;
32
+ * the transaction is rolled back and the first error of a nested call is the `cause`.
33
+ * @throws {DbError} `PG_TRANSACTION_ABORTED` when PostgreSQL rolls back in response to `COMMIT`.
34
+ * @throws {DbError} `PG_TRANSACTION_ENDED` when called in the call chain of a transaction that has already ended.
35
+ * @throws The error of the pool when no connection can be opened.
36
+ */
37
+ export declare function withTransaction<T>(fn: () => Promise<T>): Promise<T>;
@@ -0,0 +1,114 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { DB_ERROR_CODES, DbError } from '../../errors/db-error.js';
3
+ import { getPool } from './pool.js';
4
+ // The transaction of the running call chain, separate for every asynchronous call chain: parallel requests of a
5
+ // server each get their own transaction, and a query outside withTransaction never runs inside another
6
+ // request's transaction.
7
+ const transactionContext = new AsyncLocalStorage();
8
+ /**
9
+ * Returns the transaction of the current call chain, or `undefined` outside {@link withTransaction}.
10
+ *
11
+ * An asynchronous operation started inside `fn` keeps the context after `fn` settles. Such a deferred operation
12
+ * must not use the client, which runs `COMMIT` or `ROLLBACK` and then goes back to the pool and to another
13
+ * transaction; it must not silently fall back to the pool either, because its author expected the transaction.
14
+ *
15
+ * @throws {DbError} `PG_TRANSACTION_ENDED` when the transaction of the call chain has already ended.
16
+ */
17
+ const getActiveTransaction = () => {
18
+ const context = transactionContext.getStore();
19
+ if (context && !context.active)
20
+ throw new DbError(DB_ERROR_CODES.PG_TRANSACTION_ENDED);
21
+ return context;
22
+ };
23
+ /**
24
+ * Returns the object to run queries with: the client of the transaction of the current call chain inside
25
+ * {@link withTransaction}, otherwise the pool. Call it for each unit of work rather than keeping the result: an
26
+ * executor taken outside a transaction stays the pool also when used inside one.
27
+ *
28
+ * @throws {DbError} `PG_NOT_INITIALIZED` when {@link initDb} has not been called.
29
+ * @throws {DbError} `PG_TRANSACTION_ENDED` when called in the call chain of a transaction that has already ended,
30
+ * e.g. from an operation that `fn` started without awaiting it.
31
+ */
32
+ export const getQueryExecutor = () => getActiveTransaction()?.client ?? getPool();
33
+ /**
34
+ * Runs a query in the transaction of the current call chain inside {@link withTransaction}, otherwise on the pool;
35
+ * shorthand for `getQueryExecutor().query(text, params)`.
36
+ *
37
+ * @param text SQL text with placeholders `$1`, `$2`, ...
38
+ * @param params Values of the placeholders, passed to the server separately from the text.
39
+ * @throws {DbError} `PG_NOT_INITIALIZED` (as a rejection) when {@link initDb} has not been called.
40
+ * @throws {DbError} `PG_TRANSACTION_ENDED` (as a rejection) in the call chain of a transaction that has ended.
41
+ * @throws The error of the `pg` driver when the query fails.
42
+ */
43
+ export async function query(text, params) {
44
+ return await getQueryExecutor().query(text, params);
45
+ }
46
+ /**
47
+ * Runs `fn` as a part of the transaction of `context`: its error marks the whole transaction as failed, also when
48
+ * the caller catches it, because the outer transaction cannot know whether the work of `fn` was undone.
49
+ */
50
+ async function runNested(context, fn) {
51
+ try {
52
+ return await fn();
53
+ }
54
+ catch (err) {
55
+ context.nestedFailure ??= { error: err };
56
+ throw err;
57
+ }
58
+ }
59
+ /**
60
+ * Runs `fn` in a transaction and commits it when `fn` resolves, or rolls it back when `fn` or the commit rejects.
61
+ * Queries of `fn` take the transaction client from {@link getQueryExecutor}. A `withTransaction` called inside
62
+ * `fn` joins the outer transaction: it opens no transaction of its own, and its error rolls back the whole one, also
63
+ * when `fn` catches it.
64
+ *
65
+ * @throws The error of `fn`, of `BEGIN` or of `COMMIT`, unchanged; a failed `ROLLBACK` does not replace it.
66
+ * @throws {DbError} `PG_NESTED_TRANSACTION_FAILED` when `fn` resolves although a nested `withTransaction` failed;
67
+ * the transaction is rolled back and the first error of a nested call is the `cause`.
68
+ * @throws {DbError} `PG_TRANSACTION_ABORTED` when PostgreSQL rolls back in response to `COMMIT`.
69
+ * @throws {DbError} `PG_TRANSACTION_ENDED` when called in the call chain of a transaction that has already ended.
70
+ * @throws The error of the pool when no connection can be opened.
71
+ */
72
+ export async function withTransaction(fn) {
73
+ const outer = getActiveTransaction();
74
+ if (outer)
75
+ return runNested(outer, fn);
76
+ const client = await getPool().connect();
77
+ const context = { client, active: true };
78
+ let brokenConnection;
79
+ let result;
80
+ let commit;
81
+ try {
82
+ await client.query('BEGIN');
83
+ try {
84
+ result = await transactionContext.run(context, fn);
85
+ }
86
+ finally {
87
+ // Ends the transaction for deferred operations of fn before COMMIT or ROLLBACK uses the client.
88
+ context.active = false;
89
+ }
90
+ if (context.nestedFailure) {
91
+ throw new DbError(DB_ERROR_CODES.PG_NESTED_TRANSACTION_FAILED, { cause: context.nestedFailure.error });
92
+ }
93
+ commit = await client.query('COMMIT');
94
+ }
95
+ catch (err) {
96
+ try {
97
+ await client.query('ROLLBACK');
98
+ }
99
+ catch (rollbackError) {
100
+ // The connection is in an unknown state: release(error) destroys it instead of returning it to the pool.
101
+ // The caller gets the original error, which says why the transaction failed.
102
+ brokenConnection =
103
+ rollbackError instanceof Error ? rollbackError : new Error('ROLLBACK failed', { cause: rollbackError });
104
+ }
105
+ throw err;
106
+ }
107
+ finally {
108
+ client.release(brokenConnection);
109
+ }
110
+ // PostgreSQL has already rolled back, so no further command is needed on the connection.
111
+ if (commit.command === 'ROLLBACK')
112
+ throw new DbError(DB_ERROR_CODES.PG_TRANSACTION_ABORTED);
113
+ return result;
114
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Kind of a PostgreSQL error that an application usually handles differently from a generic server error:
3
+ * with a message for the user (constraint violations) or by retrying the transaction
4
+ * (`serializationFailure`, `deadlock`).
5
+ */
6
+ export type DbErrorKind = 'uniqueViolation' | 'foreignKeyViolation' | 'notNullViolation' | 'checkViolation' | 'serializationFailure' | 'deadlock';
7
+ /**
8
+ * Recognises an error of the `pg` driver by its SQLSTATE code (the `code` property).
9
+ *
10
+ * @param err Any value caught in a `catch` block.
11
+ * @returns The kind of the error, or `undefined` for any other error, for a value without a SQLSTATE code
12
+ * and for `null` or `undefined`.
13
+ */
14
+ export declare const getDbErrorKind: (err: unknown) => DbErrorKind | undefined;
15
+ /**
16
+ * Checks whether an error of the `pg` driver is a unique constraint violation (SQLSTATE `23505`); shorthand
17
+ * for `getDbErrorKind(err) === 'uniqueViolation'`.
18
+ *
19
+ * @param err Any value caught in a `catch` block.
20
+ */
21
+ export declare const isUniqueViolation: (err: unknown) => boolean;
@@ -0,0 +1,29 @@
1
+ // SQLSTATE codes: https://www.postgresql.org/docs/current/errcodes-appendix.html
2
+ // A Map, not an object literal, so that a code such as "constructor" never matches an inherited property.
3
+ const KINDS_BY_SQLSTATE = new Map([
4
+ ['23505', 'uniqueViolation'],
5
+ ['23503', 'foreignKeyViolation'],
6
+ ['23502', 'notNullViolation'],
7
+ ['23514', 'checkViolation'],
8
+ ['40001', 'serializationFailure'],
9
+ ['40P01', 'deadlock'],
10
+ ]);
11
+ /**
12
+ * Recognises an error of the `pg` driver by its SQLSTATE code (the `code` property).
13
+ *
14
+ * @param err Any value caught in a `catch` block.
15
+ * @returns The kind of the error, or `undefined` for any other error, for a value without a SQLSTATE code
16
+ * and for `null` or `undefined`.
17
+ */
18
+ export const getDbErrorKind = (err) => {
19
+ if (typeof err !== 'object' || err === null || !('code' in err))
20
+ return undefined;
21
+ return typeof err.code === 'string' ? KINDS_BY_SQLSTATE.get(err.code) : undefined;
22
+ };
23
+ /**
24
+ * Checks whether an error of the `pg` driver is a unique constraint violation (SQLSTATE `23505`); shorthand
25
+ * for `getDbErrorKind(err) === 'uniqueViolation'`.
26
+ *
27
+ * @param err Any value caught in a `catch` block.
28
+ */
29
+ export const isUniqueViolation = (err) => getDbErrorKind(err) === 'uniqueViolation';
@@ -0,0 +1,13 @@
1
+ import type { PgConfig } from './types/db-config.js';
2
+ import type { QueryExecutor } from './types/query-executor.js';
3
+ import type { DbErrorKind } from './errors/error-kind.js';
4
+ import type { DbErrorCode } from '../errors/db-error.js';
5
+ import { initDb, closeDb } from './connection/pool.js';
6
+ import { getQueryExecutor, query, withTransaction } from './connection/transaction.js';
7
+ import { getDbErrorKind, isUniqueViolation } from './errors/error-kind.js';
8
+ import { DB_ERROR_CODES, DbError } from '../errors/db-error.js';
9
+ export type { PgConfig, QueryExecutor, DbErrorKind, DbErrorCode };
10
+ export { initDb, closeDb, getQueryExecutor, query };
11
+ export { withTransaction };
12
+ export { getDbErrorKind, isUniqueViolation };
13
+ export { DB_ERROR_CODES, DbError };
@@ -0,0 +1,8 @@
1
+ import { initDb, closeDb } from './connection/pool.js';
2
+ import { getQueryExecutor, query, withTransaction } from './connection/transaction.js';
3
+ import { getDbErrorKind, isUniqueViolation } from './errors/error-kind.js';
4
+ import { DB_ERROR_CODES, DbError } from '../errors/db-error.js';
5
+ export { initDb, closeDb, getQueryExecutor, query };
6
+ export { withTransaction };
7
+ export { getDbErrorKind, isUniqueViolation };
8
+ export { DB_ERROR_CODES, DbError };
@@ -0,0 +1,22 @@
1
+ import type { PoolConfig } from 'pg';
2
+ import type { DbError } from '../../errors/db-error.js';
3
+ /**
4
+ * Settings of the PostgreSQL connection.
5
+ *
6
+ * Only the connection data is required. Every other setting of `PoolConfig` from `pg` (e.g. `ssl`,
7
+ * `application_name`, `statement_timeout`) is optional and passed to the pool unchanged; the pool settings
8
+ * default to `max` 10, `min` 0, `idleTimeoutMillis` 30 000 and `connectionTimeoutMillis` 10 000.
9
+ */
10
+ export type PgConfig = Omit<PoolConfig, 'host' | 'port' | 'user' | 'password' | 'database'> & {
11
+ host: string;
12
+ port: number;
13
+ user: string;
14
+ password: string;
15
+ database: string;
16
+ /**
17
+ * Receives an error of an idle connection of the pool (e.g. the server closed it), as a `DbError` with code
18
+ * `PG_UNEXPECTED_ERROR` and the driver error as `cause`. Without it such errors are ignored: the pool discards
19
+ * the broken connection itself, and the library never writes to the console.
20
+ */
21
+ onError?: (error: DbError) => void;
22
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { QueryResult, QueryResultRow } from 'pg';
2
+ /** Runs a query: the pool, or the client of the current transaction (see `getQueryExecutor`). */
3
+ export type QueryExecutor = {
4
+ query<T extends QueryResultRow = QueryResultRow>(text: string, params?: unknown[]): Promise<QueryResult<T>>;
5
+ };
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,85 @@
1
1
  {
2
- "name": "@mielk/db",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@mielk/db",
3
+ "version": "3.1.0",
4
+ "description": "PostgreSQL connection pool with call-chain transactions and MS SQL queries over ODBC, with coded errors, for mielk Node.js applications.",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=24"
8
+ },
9
+ "scripts": {
10
+ "test": "vitest run --coverage",
11
+ "test:pg": "vitest run --config vitest.pg.config.ts",
12
+ "build": "npm run clean && tsc -p tsconfig.build.json",
13
+ "prepublishOnly": "npm run typecheck && npm run lint && npm test && npm run build && npm run check:package",
14
+ "dev": "tsc -p tsconfig.build.json --watch",
15
+ "test:watch": "vitest",
16
+ "typecheck": "tsc --noEmit",
17
+ "lint": "eslint . --max-warnings 0",
18
+ "format": "prettier --write .",
19
+ "format:check": "prettier --check .",
20
+ "check:package": "mielk-check-package",
21
+ "version": "mielk-release-changelog && git add CHANGELOG.md",
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 })\""
23
+ },
24
+ "exports": {
25
+ "./mssql": {
26
+ "types": "./dist/mssql/index.d.ts",
27
+ "import": "./dist/mssql/index.js",
28
+ "default": "./dist/mssql/index.js"
29
+ },
30
+ "./pg": {
31
+ "types": "./dist/pg/index.d.ts",
32
+ "import": "./dist/pg/index.js",
33
+ "default": "./dist/pg/index.js"
34
+ },
35
+ "./locales/*": "./dist/locales/*.json"
36
+ },
37
+ "prettier": "@mielk/lib-config/prettier",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/mielk/mielk-db.git"
41
+ },
42
+ "author": "Tomasz Mielniczek",
43
+ "license": "MIT",
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "bugs": {
48
+ "url": "https://github.com/mielk/mielk-db/issues"
49
+ },
50
+ "homepage": "https://github.com/mielk/mielk-db#readme",
51
+ "files": [
52
+ "dist",
53
+ "CHANGELOG.md"
54
+ ],
55
+ "devDependencies": {
56
+ "@arethetypeswrong/cli": "0.18.5",
57
+ "@mielk/lib-config": "1.0.0",
58
+ "@types/node": "24.19.2",
59
+ "@types/pg": "8.20.0",
60
+ "@vitest/coverage-v8": "5.1.0",
61
+ "eslint": "10.14.0",
62
+ "msnodesqlv8": "5.1.9",
63
+ "pg": "8.20.0",
64
+ "prettier": "3.10.1",
65
+ "publint": "0.3.25",
66
+ "typescript": "5.9.2",
67
+ "vitest": "5.1.0"
68
+ },
69
+ "peerDependencies": {
70
+ "@types/pg": "^8",
71
+ "msnodesqlv8": "^5",
72
+ "pg": "^8"
73
+ },
74
+ "peerDependenciesMeta": {
75
+ "@types/pg": {
76
+ "optional": true
77
+ },
78
+ "msnodesqlv8": {
79
+ "optional": true
80
+ },
81
+ "pg": {
82
+ "optional": true
83
+ }
84
+ }
85
+ }