@mielk/db 0.0.0-stage → 3.0.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 +67 -0
- package/LICENSE +21 -0
- package/README.md +238 -2
- package/dist/errors/db-error.d.ts +28 -0
- package/dist/errors/db-error.js +41 -0
- package/dist/locales/en.json +17 -0
- package/dist/locales/pl.json +17 -0
- package/dist/mssql/connection/pool.d.ts +48 -0
- package/dist/mssql/connection/pool.js +122 -0
- package/dist/mssql/errors/error-kind.d.ts +23 -0
- package/dist/mssql/errors/error-kind.js +27 -0
- package/dist/mssql/index.d.ts +11 -0
- package/dist/mssql/index.js +9 -0
- package/dist/mssql/types/db-config.d.ts +17 -0
- package/dist/mssql/types/db-config.js +1 -0
- package/dist/pg/connection/pool.d.ts +25 -0
- package/dist/pg/connection/pool.js +49 -0
- package/dist/pg/connection/transaction.d.ts +36 -0
- package/dist/pg/connection/transaction.js +109 -0
- package/dist/pg/errors/error-kind.d.ts +21 -0
- package/dist/pg/errors/error-kind.js +29 -0
- package/dist/pg/index.d.ts +13 -0
- package/dist/pg/index.js +8 -0
- package/dist/pg/types/db-config.d.ts +22 -0
- package/dist/pg/types/db-config.js +1 -0
- package/dist/pg/types/query-executor.d.ts +5 -0
- package/dist/pg/types/query-executor.js +1 -0
- package/package.json +83 -5
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
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.0.0] - 2026-11-15
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- `query(text, params?)` in `@mielk/db/pg`: runs a query in the transaction of the current call chain, otherwise on the pool (TASK-189).
|
|
15
|
+
- `closeDb()` in `@mielk/db/pg` and `@mielk/db/mssql`; `initDb` can be called again after it (TASK-189).
|
|
16
|
+
- `DbError` with `code`, English `message` and `cause`, the constant `DB_ERROR_CODES` and the type `DbErrorCode`, exported from both entry points (TASK-189).
|
|
17
|
+
- Texts of the error codes in English and Polish, in the entry point `@mielk/db/locales/<language>` (TASK-189).
|
|
18
|
+
- `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).
|
|
19
|
+
- `onError` in `PgConfig` and `MsSqlConfig`: receives errors that the library cannot pass to a caller (TASK-189).
|
|
20
|
+
- `PgConfig` accepts every setting of `PoolConfig` from `pg` (e.g. `ssl`, `statement_timeout`) (TASK-189).
|
|
21
|
+
- `query` of `@mielk/db/mssql` takes query parameters: `query(text, params?)` with `?` placeholders (TASK-189).
|
|
22
|
+
- Type `MsSqlRow` for the rows returned by `query` of `@mielk/db/mssql` (TASK-189).
|
|
23
|
+
- README, MIT license file and TSDoc comments for every export (TASK-189).
|
|
24
|
+
- The package contains `CHANGELOG.md`, so the migration notes are available after installation (TASK-189).
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
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).
|
|
29
|
+
- **Breaking:** Node.js 24 or later is required (`engines.node: >=24`). Migration: run the application on Node.js 24 (TASK-189).
|
|
30
|
+
- **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
|
+
- **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).
|
|
32
|
+
- **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).
|
|
33
|
+
- **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).
|
|
34
|
+
- **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).
|
|
35
|
+
- **Breaking:** `UniqueKeyViolationError` is removed; the library never threw it. Migration: recognise the error with `isUniqueViolation(err)` or `getDbErrorKind(err)` (TASK-189).
|
|
36
|
+
- **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).
|
|
37
|
+
- **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).
|
|
38
|
+
- **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).
|
|
39
|
+
- **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).
|
|
40
|
+
- **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).
|
|
41
|
+
- `withTransaction` rejects with the original error when `ROLLBACK` also fails, and destroys the connection instead of returning it to the pool (TASK-189).
|
|
42
|
+
- An error of an idle PostgreSQL connection goes to `onError` instead of the console (TASK-189).
|
|
43
|
+
|
|
44
|
+
### Removed
|
|
45
|
+
|
|
46
|
+
- **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).
|
|
47
|
+
|
|
48
|
+
### Fixed
|
|
49
|
+
|
|
50
|
+
- `initDb` of `@mielk/db/mssql` no longer writes the connection string, with the password, to the console (TASK-189).
|
|
51
|
+
- `spExecute` closes its connection after the statement, also when it fails; before, every call left a connection open (TASK-189).
|
|
52
|
+
- `query` of `@mielk/db/mssql` rejects once with the error of the driver; before, a failed query could reject without an error (TASK-189).
|
|
53
|
+
- 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).
|
|
54
|
+
|
|
55
|
+
## [2.1.0](https://github.com/mielk/mielk-db/compare/v2.0.1...v2.1.0) (2026-04-19)
|
|
56
|
+
|
|
57
|
+
### [2.0.1](https://github.com/mielk/mielk-db/compare/v2.0.0...v2.0.1) (2026-04-19)
|
|
58
|
+
|
|
59
|
+
## 2.0.0 (2026-04-19)
|
|
60
|
+
|
|
61
|
+
### ⚠ BREAKING CHANGES
|
|
62
|
+
|
|
63
|
+
- Change library purpose.
|
|
64
|
+
|
|
65
|
+
### Features
|
|
66
|
+
|
|
67
|
+
- 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,239 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mielk/db
|
|
2
2
|
|
|
3
|
-
|
|
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`. 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
|
|
11
|
+
[CHANGELOG.md](CHANGELOG.md).
|
|
12
|
+
|
|
13
|
+
## Requirements
|
|
14
|
+
|
|
15
|
+
- Node.js 24 or later (`engines.node: >=24`); development uses the version in `.nvmrc` (24.13.0).
|
|
16
|
+
- Optional peer dependencies, each needed only by the entry point that uses it:
|
|
17
|
+
|
|
18
|
+
| Peer dependency | Range | Needed by |
|
|
19
|
+
| --------------- | ----- | ------------------------------------------------------------------------------------------------ |
|
|
20
|
+
| `pg` | `^8` | `@mielk/db/pg` |
|
|
21
|
+
| `@types/pg` | `^8` | `@mielk/db/pg` in a TypeScript application (its types, e.g. `QueryResult`, are part of the API) |
|
|
22
|
+
| `msnodesqlv8` | `^5` | `@mielk/db/mssql` (native module; needs an ODBC driver for SQL Server installed on the computer) |
|
|
23
|
+
|
|
24
|
+
- ES modules: the package has no CommonJS build (`require` works only through dynamic `import()`).
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# PostgreSQL (TypeScript application):
|
|
30
|
+
npm install @mielk/db pg @types/pg
|
|
31
|
+
# PostgreSQL (JavaScript application):
|
|
32
|
+
npm install @mielk/db pg
|
|
33
|
+
# MS SQL:
|
|
34
|
+
npm install @mielk/db msnodesqlv8
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Entry points
|
|
38
|
+
|
|
39
|
+
| Entry point | Purpose | Environments |
|
|
40
|
+
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- |
|
|
41
|
+
| `@mielk/db/pg` | `initDb`, `closeDb`, `query`, `withTransaction`, `getQueryExecutor`, `getDbErrorKind`, `isUniqueViolation`, `DbError`, `DB_ERROR_CODES`; types `PgConfig`, `QueryExecutor`, `DbErrorKind`, `DbErrorCode` | Node.js only |
|
|
42
|
+
| `@mielk/db/mssql` | `initDb`, `closeDb`, `query`, `spExecute`, `getDbErrorKind`, `isUniqueViolation`, `DbError`, `DB_ERROR_CODES`; types `MsSqlConfig`, `MsSqlRow`, `DbErrorKind`, `DbErrorCode` | Node.js only |
|
|
43
|
+
| `@mielk/db/locales/<language>` | Texts of the error codes as JSON (`en`, `pl`), without any driver | all (data only) |
|
|
44
|
+
|
|
45
|
+
The package has no main entry point: import from `@mielk/db/pg` or `@mielk/db/mssql`. Each export is documented
|
|
46
|
+
with TSDoc in the source; editors show the description, parameters and errors.
|
|
47
|
+
|
|
48
|
+
## Usage: PostgreSQL
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { closeDb, initDb, query, withTransaction } from '@mielk/db/pg';
|
|
52
|
+
|
|
53
|
+
// Once, at application start-up.
|
|
54
|
+
initDb({
|
|
55
|
+
host: 'localhost',
|
|
56
|
+
port: 5432,
|
|
57
|
+
user: 'app',
|
|
58
|
+
password: secret,
|
|
59
|
+
database: 'shop',
|
|
60
|
+
onError: (error) => logger.error(error),
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const { rows } = await query<{ id: number; name: string }>('SELECT id, name FROM product WHERE id = $1', [42]);
|
|
64
|
+
|
|
65
|
+
await withTransaction(async () => {
|
|
66
|
+
await query('UPDATE stock SET quantity = quantity - $1 WHERE product_id = $2', [1, 42]);
|
|
67
|
+
await query('INSERT INTO order_line (product_id, quantity) VALUES ($1, $2)', [42, 1]);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// When the application shuts down.
|
|
71
|
+
await closeDb();
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Transactions
|
|
75
|
+
|
|
76
|
+
- `withTransaction(fn)` takes a connection from the pool, runs `BEGIN`, then `fn`, and commits when `fn` resolves.
|
|
77
|
+
When `fn` or the commit rejects, it rolls back and rejects with the original error. A connection whose
|
|
78
|
+
`ROLLBACK` fails is destroyed instead of returned to the pool.
|
|
79
|
+
- The transaction belongs to the asynchronous call chain of `fn` (`AsyncLocalStorage`): `query` and
|
|
80
|
+
`getQueryExecutor` called anywhere inside `fn`, also in other modules, use the transaction connection. Parallel
|
|
81
|
+
requests of a server each get their own transaction, and code outside `withTransaction` always uses the pool.
|
|
82
|
+
- The transaction ends when `fn` settles. An operation that `fn` started without awaiting it and that calls `query`,
|
|
83
|
+
`getQueryExecutor` or `withTransaction` later fails with `PG_TRANSACTION_ENDED`: it never runs on the connection,
|
|
84
|
+
which then goes back to the pool, and never silently outside the transaction. Await all work of `fn`.
|
|
85
|
+
- A `withTransaction` called inside another joins the outer transaction: it opens no transaction of its own, and
|
|
86
|
+
an error anywhere rolls back the whole one. This holds also when `fn` catches the error of a nested call: the
|
|
87
|
+
outer `withTransaction` then rolls back and rejects with `PG_NESTED_TRANSACTION_FAILED`, whose `cause` is the
|
|
88
|
+
first error of a nested call.
|
|
89
|
+
- 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.
|
|
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_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 |
|
|
165
|
+
|
|
166
|
+
Asynchronous functions report these errors as rejections. Errors of the server and the driver (failed connection,
|
|
167
|
+
failed query, `BEGIN`, `COMMIT`) are passed to the caller unchanged, not wrapped in `DbError`. `query` of
|
|
168
|
+
`@mielk/db/mssql` rejects with a `TypeError` when the driver returns a result row that is not an object. When the
|
|
169
|
+
driver reports a failed statement of `spExecute` with an object that is not an `Error`, `spExecute` rejects with an
|
|
170
|
+
`Error` that has the same fields (`code`, `sqlstate`, ...) and the original object as `cause`, so `getDbErrorKind`
|
|
171
|
+
recognises it.
|
|
172
|
+
|
|
173
|
+
### Texts of the error codes
|
|
174
|
+
|
|
175
|
+
A code has the form `<namespace>:<key>`, which is also the i18next key of its text in `@mielk/db/locales/<language>`
|
|
176
|
+
(English and Polish), so an application can show a translated message:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
import i18next from 'i18next';
|
|
180
|
+
import pl from '@mielk/db/locales/pl' with { type: 'json' };
|
|
181
|
+
|
|
182
|
+
for (const [namespace, texts] of Object.entries(pl)) i18next.addResourceBundle('pl', namespace, texts);
|
|
183
|
+
|
|
184
|
+
i18next.t(error.code); // 'Połączenie z PostgreSQL nie jest zainicjowane: najpierw wywołaj initDb.'
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Recognising server errors
|
|
188
|
+
|
|
189
|
+
`getDbErrorKind(err)` maps a server error to a kind that an application usually handles differently from a generic
|
|
190
|
+
error: with a message for the user (constraint violations) or by retrying the transaction. It returns `undefined`
|
|
191
|
+
for any other value. `isUniqueViolation(err)` is a shorthand for `getDbErrorKind(err) === 'uniqueViolation'`.
|
|
192
|
+
|
|
193
|
+
| Kind | PostgreSQL (SQLSTATE) | MS SQL (error number) |
|
|
194
|
+
| ---------------------- | --------------------- | --------------------- |
|
|
195
|
+
| `uniqueViolation` | `23505` | 2627, 2601 |
|
|
196
|
+
| `foreignKeyViolation` | `23503` | — |
|
|
197
|
+
| `checkViolation` | `23514` | — |
|
|
198
|
+
| `constraintViolation` | — | 547 |
|
|
199
|
+
| `notNullViolation` | `23502` | 515 |
|
|
200
|
+
| `serializationFailure` | `40001` | — |
|
|
201
|
+
| `deadlock` | `40P01` | 1205 |
|
|
202
|
+
|
|
203
|
+
SQL Server reports foreign key and CHECK violations with the same number 547 and tells them apart only in the
|
|
204
|
+
message text, which depends on the server language, so `@mielk/db/mssql` reports both as `constraintViolation`.
|
|
205
|
+
|
|
206
|
+
## Development
|
|
207
|
+
|
|
208
|
+
| Command | Purpose |
|
|
209
|
+
| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
210
|
+
| `npm ci` | install dependencies from `package-lock.json` |
|
|
211
|
+
| `npm test` | all unit tests (Vitest) with coverage; threshold 80% of lines and branches; the report is written to the system temp folder |
|
|
212
|
+
| `npm run test:watch` | tests in watch mode |
|
|
213
|
+
| `npm run typecheck` | TypeScript check without output |
|
|
214
|
+
| `npm run lint` | ESLint with type information, no warnings allowed |
|
|
215
|
+
| `npm run format` / `npm run format:check` | Prettier |
|
|
216
|
+
| `npm run build` | compiles `src` to `dist` (clears the content of `dist`, keeps the folder) |
|
|
217
|
+
| `npm run dev` | build in watch mode |
|
|
218
|
+
| `npm run check:package` | `publint --strict` and `attw` on the built package |
|
|
219
|
+
|
|
220
|
+
`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.
|
|
222
|
+
|
|
223
|
+
## Releases and changes
|
|
224
|
+
|
|
225
|
+
Changes are listed by hand in [CHANGELOG.md](CHANGELOG.md) under `Unreleased`; it also holds the migration notes
|
|
226
|
+
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.
|
|
228
|
+
|
|
229
|
+
## Documentation scope
|
|
230
|
+
|
|
231
|
+
Deviation from the documentation standard (`doc:SCP-1`, `doc:SCP-4`), as approved by the user for the mielk
|
|
232
|
+
libraries on 2026-11-13 (TASK-188) and applied to this library in TASK-189: the library has no generated user and
|
|
233
|
+
technical documentation sites, API reference or agent documentation (`doc/agent/CORE.md`), because the
|
|
234
|
+
documentation generator for TypeScript (TASK-197) is not finished yet. Until it is, this README, the TSDoc
|
|
235
|
+
comments of every export and [CHANGELOG.md](CHANGELOG.md) are the complete documentation.
|
|
236
|
+
|
|
237
|
+
## License
|
|
238
|
+
|
|
239
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,28 @@
|
|
|
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
|
+
readonly PG_TRANSACTION_ENDED: "db/pg/transaction:ended";
|
|
16
|
+
readonly PG_UNEXPECTED_ERROR: "db/pg/connection:unexpectedError";
|
|
17
|
+
};
|
|
18
|
+
/** Code of an error thrown by the library: one of the values of {@link DB_ERROR_CODES}. */
|
|
19
|
+
export type DbErrorCode = (typeof DB_ERROR_CODES)[keyof typeof DB_ERROR_CODES];
|
|
20
|
+
/**
|
|
21
|
+
* Error thrown by the library. `code` identifies the error (compare it with {@link DB_ERROR_CODES}, never the
|
|
22
|
+
* message); `message` is the English text for logs; `cause` holds the original error, if there was one.
|
|
23
|
+
*/
|
|
24
|
+
export declare class DbError extends Error {
|
|
25
|
+
readonly name = "DbError";
|
|
26
|
+
readonly code: DbErrorCode;
|
|
27
|
+
constructor(code: DbErrorCode, options?: ErrorOptions);
|
|
28
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
PG_TRANSACTION_ENDED: 'db/pg/transaction:ended',
|
|
17
|
+
PG_UNEXPECTED_ERROR: 'db/pg/connection:unexpectedError',
|
|
18
|
+
};
|
|
19
|
+
const ENGLISH_TEXTS = en;
|
|
20
|
+
/**
|
|
21
|
+
* Returns the English text of an error code from `locales/en.json`, or the code itself when the text is missing
|
|
22
|
+
* (a unit test keeps every code covered, so the fallback only guards against a broken build).
|
|
23
|
+
*/
|
|
24
|
+
const getEnglishText = (code) => {
|
|
25
|
+
const separator = code.indexOf(':');
|
|
26
|
+
const namespace = code.slice(0, separator);
|
|
27
|
+
const key = code.slice(separator + 1);
|
|
28
|
+
return ENGLISH_TEXTS[namespace]?.[key] ?? code;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Error thrown by the library. `code` identifies the error (compare it with {@link DB_ERROR_CODES}, never the
|
|
32
|
+
* message); `message` is the English text for logs; `cause` holds the original error, if there was one.
|
|
33
|
+
*/
|
|
34
|
+
export class DbError extends Error {
|
|
35
|
+
name = 'DbError';
|
|
36
|
+
code;
|
|
37
|
+
constructor(code, options) {
|
|
38
|
+
super(getEnglishText(code), options);
|
|
39
|
+
this.code = code;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
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
|
+
"ended": "The transaction of this call chain has already ended: a query started inside withTransaction cannot run after it.",
|
|
15
|
+
"nestedFailed": "A nested withTransaction failed and its error was caught: the whole transaction is rolled back."
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
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
|
+
"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.",
|
|
15
|
+
"nestedFailed": "Zagnieżdżone withTransaction nie powiodło się, a jego błąd został przechwycony: cała transakcja zostaje wycofana."
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -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,36 @@
|
|
|
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_ENDED` when called in the call chain of a transaction that has already ended.
|
|
34
|
+
* @throws The error of the pool when no connection can be opened.
|
|
35
|
+
*/
|
|
36
|
+
export declare function withTransaction<T>(fn: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,109 @@
|
|
|
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_ENDED` when called in the call chain of a transaction that has already ended.
|
|
69
|
+
* @throws The error of the pool when no connection can be opened.
|
|
70
|
+
*/
|
|
71
|
+
export async function withTransaction(fn) {
|
|
72
|
+
const outer = getActiveTransaction();
|
|
73
|
+
if (outer)
|
|
74
|
+
return runNested(outer, fn);
|
|
75
|
+
const client = await getPool().connect();
|
|
76
|
+
const context = { client, active: true };
|
|
77
|
+
let brokenConnection;
|
|
78
|
+
try {
|
|
79
|
+
await client.query('BEGIN');
|
|
80
|
+
let result;
|
|
81
|
+
try {
|
|
82
|
+
result = await transactionContext.run(context, fn);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
// Ends the transaction for deferred operations of fn before COMMIT or ROLLBACK uses the client.
|
|
86
|
+
context.active = false;
|
|
87
|
+
}
|
|
88
|
+
if (context.nestedFailure) {
|
|
89
|
+
throw new DbError(DB_ERROR_CODES.PG_NESTED_TRANSACTION_FAILED, { cause: context.nestedFailure.error });
|
|
90
|
+
}
|
|
91
|
+
await client.query('COMMIT');
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
try {
|
|
96
|
+
await client.query('ROLLBACK');
|
|
97
|
+
}
|
|
98
|
+
catch (rollbackError) {
|
|
99
|
+
// The connection is in an unknown state: release(error) destroys it instead of returning it to the pool.
|
|
100
|
+
// The caller gets the original error, which says why the transaction failed.
|
|
101
|
+
brokenConnection =
|
|
102
|
+
rollbackError instanceof Error ? rollbackError : new Error('ROLLBACK failed', { cause: rollbackError });
|
|
103
|
+
}
|
|
104
|
+
throw err;
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
client.release(brokenConnection);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -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 };
|
package/dist/pg/index.js
ADDED
|
@@ -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,84 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@mielk/db",
|
|
3
|
+
"version": "3.0.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
|
+
"build": "npm run clean && tsc -p tsconfig.build.json",
|
|
12
|
+
"prepublishOnly": "npm run typecheck && npm run lint && npm test && npm run build && npm run check:package",
|
|
13
|
+
"dev": "tsc -p tsconfig.build.json --watch",
|
|
14
|
+
"test:watch": "vitest",
|
|
15
|
+
"typecheck": "tsc --noEmit",
|
|
16
|
+
"lint": "eslint . --max-warnings 0",
|
|
17
|
+
"format": "prettier --write .",
|
|
18
|
+
"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",
|
|
21
|
+
"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
|
+
"exports": {
|
|
24
|
+
"./mssql": {
|
|
25
|
+
"types": "./dist/mssql/index.d.ts",
|
|
26
|
+
"import": "./dist/mssql/index.js",
|
|
27
|
+
"default": "./dist/mssql/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./pg": {
|
|
30
|
+
"types": "./dist/pg/index.d.ts",
|
|
31
|
+
"import": "./dist/pg/index.js",
|
|
32
|
+
"default": "./dist/pg/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./locales/*": "./dist/locales/*.json"
|
|
35
|
+
},
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/mielk/mielk-db.git"
|
|
39
|
+
},
|
|
40
|
+
"author": "Tomasz Mielniczek",
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"bugs": {
|
|
46
|
+
"url": "https://github.com/mielk/mielk-db/issues"
|
|
47
|
+
},
|
|
48
|
+
"homepage": "https://github.com/mielk/mielk-db#readme",
|
|
49
|
+
"files": [
|
|
50
|
+
"dist",
|
|
51
|
+
"CHANGELOG.md"
|
|
52
|
+
],
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
55
|
+
"@eslint/js": "10.0.1",
|
|
56
|
+
"@types/node": "24.19.2",
|
|
57
|
+
"@types/pg": "8.20.0",
|
|
58
|
+
"@vitest/coverage-v8": "5.1.0",
|
|
59
|
+
"eslint": "10.14.0",
|
|
60
|
+
"msnodesqlv8": "5.1.9",
|
|
61
|
+
"pg": "8.20.0",
|
|
62
|
+
"prettier": "3.10.1",
|
|
63
|
+
"publint": "0.3.25",
|
|
64
|
+
"typescript": "5.9.2",
|
|
65
|
+
"typescript-eslint": "8.72.2",
|
|
66
|
+
"vitest": "5.1.0"
|
|
67
|
+
},
|
|
68
|
+
"peerDependencies": {
|
|
69
|
+
"@types/pg": "^8",
|
|
70
|
+
"msnodesqlv8": "^5",
|
|
71
|
+
"pg": "^8"
|
|
72
|
+
},
|
|
73
|
+
"peerDependenciesMeta": {
|
|
74
|
+
"@types/pg": {
|
|
75
|
+
"optional": true
|
|
76
|
+
},
|
|
77
|
+
"msnodesqlv8": {
|
|
78
|
+
"optional": true
|
|
79
|
+
},
|
|
80
|
+
"pg": {
|
|
81
|
+
"optional": true
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|