kysely-postgrejs 1.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 +23 -0
- package/LICENSE +30 -0
- package/README.md +231 -0
- package/constants.d.ts +14 -0
- package/constants.js +14 -0
- package/index.d.ts +5 -0
- package/index.js +5 -0
- package/package.json +48 -0
- package/postgrejs-connection.d.ts +101 -0
- package/postgrejs-connection.js +246 -0
- package/postgrejs-dialect-config.d.ts +90 -0
- package/postgrejs-dialect-config.js +1 -0
- package/postgrejs-dialect.d.ts +29 -0
- package/postgrejs-dialect.js +39 -0
- package/postgrejs-driver.d.ts +53 -0
- package/postgrejs-driver.js +129 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
## Changelog
|
|
2
|
+
|
|
3
|
+
### 1.0.0
|
|
4
|
+
|
|
5
|
+
#### 🚀 New Features
|
|
6
|
+
|
|
7
|
+
- feat: the Kysely dialect itself - dialect, driver, connection @Eray Hanoğlu
|
|
8
|
+
- feat: run Kysely's own dialect suite, and fix what it found @Eray Hanoğlu
|
|
9
|
+
- feat: cancelQuery and killSession, the in-flight abort strategies @Eray Hanoğlu
|
|
10
|
+
- feat: pass fetchAsString through, and take the suite down to three @Eray Hanoğlu
|
|
11
|
+
|
|
12
|
+
#### 📖 Documentation Changes
|
|
13
|
+
|
|
14
|
+
- docs: bring CLAUDE.md in line with the dialect that got built @Eray Hanoğlu
|
|
15
|
+
- docs: record where the suite's last failure goes @Eray Hanoğlu
|
|
16
|
+
|
|
17
|
+
#### 🧪 Changes to Test Assests
|
|
18
|
+
|
|
19
|
+
- test: point the suite's two pg-specific tests at this dialect @Eray Hanoğlu
|
|
20
|
+
|
|
21
|
+
#### 💬 General Changes
|
|
22
|
+
|
|
23
|
+
- Initial commit @Eray Hanoglu
|
package/LICENSE
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020 Panates
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted provided that the following conditions are met:
|
|
8
|
+
|
|
9
|
+
1. Redistributions of source code must retain the above copyright notice,
|
|
10
|
+
this list of conditions and the following disclaimer.
|
|
11
|
+
|
|
12
|
+
2. Redistributions in binary form must reproduce the above copyright
|
|
13
|
+
notice, this list of conditions and the following disclaimer in the
|
|
14
|
+
documentation and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
17
|
+
contributors may be used to endorse or promote products derived from
|
|
18
|
+
this software without specific prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
21
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
22
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
23
|
+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
24
|
+
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
25
|
+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
26
|
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
27
|
+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
28
|
+
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
29
|
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
30
|
+
POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# kysely-postgrejs
|
|
2
|
+
|
|
3
|
+
A [Kysely](https://kysely.dev) dialect for [PostgreJS](https://github.com/panates/postgrejs) - run a
|
|
4
|
+
Kysely query builder on PostgreJS's wire-protocol client instead of `pg`.
|
|
5
|
+
|
|
6
|
+
Only the driver is PostgreJS-specific. The SQL is the same either way, so the adapter, introspector
|
|
7
|
+
and query compiler are Kysely's own `Postgres*` implementations.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install kysely-postgrejs kysely postgrejs
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`kysely` (>=0.29 <0.31) and `postgrejs` (>=3.6) are peer dependencies.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { Kysely } from 'kysely';
|
|
21
|
+
import { Pool } from 'postgrejs';
|
|
22
|
+
import { PostgrejsDialect } from 'kysely-postgrejs';
|
|
23
|
+
|
|
24
|
+
const db = new Kysely<Database>({
|
|
25
|
+
dialect: new PostgrejsDialect({
|
|
26
|
+
pool: new Pool('postgres://localhost:5432/mydb'),
|
|
27
|
+
}),
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`pool` takes a `Pool` instance, or an async function returning one - it is called once, when the
|
|
32
|
+
driver initialises. `db.destroy()` closes the pool.
|
|
33
|
+
|
|
34
|
+
Streaming goes through a server-side cursor, with Kysely's chunk size as the cursor's batch size:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
for await (const person of db.selectFrom('person').selectAll().stream(100)) {
|
|
38
|
+
// one round trip per 100 rows; the cursor closes when the loop ends,
|
|
39
|
+
// whether it runs out, breaks, or throws
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Everything Kysely's interface does not reach - COPY, LISTEN/NOTIFY, large objects, logical
|
|
44
|
+
replication - is still there on the PostgreJS connection underneath, which the two hooks hand you:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
new PostgrejsDialect({
|
|
48
|
+
pool,
|
|
49
|
+
onCreateConnection: async (connection) => {
|
|
50
|
+
const postgrejs = (connection as PostgrejsConnection).connection;
|
|
51
|
+
await postgrejs.query(`set application_name = 'reports'`);
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The pool you passed in is of course still yours to `acquire()` from directly as well.
|
|
57
|
+
|
|
58
|
+
## Config
|
|
59
|
+
|
|
60
|
+
| Option | Default | What it does |
|
|
61
|
+
| --------------------- | ----------------- | ----------------------------------------------------------------------------------------- |
|
|
62
|
+
| `pool` | (required) | A PostgreJS `Pool`, or a function returning one. |
|
|
63
|
+
| `fetchAsString` | - | OIDs to hand back as the server's own text. `[DataTypeOIDs.int8]` is how to get `pg`'s bigints. |
|
|
64
|
+
| `fetchCount` | `4294967295` | How many rows a statement may return before the portal suspends. See below. |
|
|
65
|
+
| `inferParameterTypes` | `true` | Whether PostgreSQL resolves each parameter's type from context, as it does for `pg`. |
|
|
66
|
+
| `prepare` | connection's own | Whether statements are cached as server-side prepared statements. `false` for PgBouncer. |
|
|
67
|
+
| `rollbackOnError` | `false` | Whether a failed statement leaves the rest of the transaction usable. See below. |
|
|
68
|
+
| `typeMap` | `GlobalTypeMap` | A custom `DataTypeMap`, to override how individual PostgreSQL types are decoded. |
|
|
69
|
+
| `onCreateConnection` | - | Called once per physical connection, before it is first handed to Kysely. |
|
|
70
|
+
| `onReserveConnection` | - | Called every time a connection is acquired from the pool. |
|
|
71
|
+
|
|
72
|
+
### Why `fetchCount` defaults to "everything"
|
|
73
|
+
|
|
74
|
+
The dialect asks for the protocol maximum rather than leaving the limit unsaid. Kysely's
|
|
75
|
+
`QueryResult` has nowhere to report that rows were left behind, so a truncated result would reach
|
|
76
|
+
the caller as a short answer with nothing wrong about it - PostgreJS flags one with `suspended`, and
|
|
77
|
+
that flag has no way through. Lower it only if you know what a short result would mean for your
|
|
78
|
+
queries; `streamQuery` ignores it and uses Kysely's `chunkSize` as the cursor's batch size.
|
|
79
|
+
|
|
80
|
+
### Why parameter types are left to the server
|
|
81
|
+
|
|
82
|
+
PostgreJS gives every parameter a type OID taken from its JavaScript value, so a string arrives
|
|
83
|
+
declared as `varchar`. That is a declaration, not a hint, and PostgreSQL stops inferring:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
await db.insertInto('log').values({ payload: '{"a":1}' }).execute()
|
|
87
|
+
// column "payload" is of type json but expression is of type character varying
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`coalesce($1, 1)`, `$1 || name` and any call to an overloaded function fail the same way. `pg` sends
|
|
91
|
+
type 0 - unspecified - and lets PostgreSQL resolve each parameter from where it appears, so none of
|
|
92
|
+
this surfaces there. The dialect does the same by default. Only strings, numbers, booleans, bigints
|
|
93
|
+
and nulls are affected; dates, buffers, arrays and objects keep PostgreJS's typed, binary encoding,
|
|
94
|
+
which is both correct and faster. Set `inferParameterTypes: false` to declare types again.
|
|
95
|
+
|
|
96
|
+
### Getting `pg`'s bigints
|
|
97
|
+
|
|
98
|
+
PostgreJS decodes `int8` as a number inside the safe integer range and a `BigInt` beyond it, where
|
|
99
|
+
`pg` hands back a string - which is what Kysely's generated types and most code ported from `pg`
|
|
100
|
+
expect, `count(*)` and `sum(...)` above all. One line asks for the same thing:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { DataTypeOIDs } from 'postgrejs';
|
|
104
|
+
|
|
105
|
+
new PostgrejsDialect({ pool, fetchAsString: [DataTypeOIDs.int8] });
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The server renders those columns as text and the dialect hands them over untouched, so a value past
|
|
109
|
+
2^53 keeps every digit. Any OID works - `numeric`, `date`, `json` - and nothing else is affected.
|
|
110
|
+
|
|
111
|
+
### Why `rollbackOnError` defaults to `false`
|
|
112
|
+
|
|
113
|
+
PostgreJS wraps every statement inside a transaction in a savepoint of its own, so a failed
|
|
114
|
+
statement leaves the transaction usable. That is not what PostgreSQL does, nor what `pg` - and
|
|
115
|
+
therefore every existing Kysely user - expects. The dialect turns it off: a failed statement aborts
|
|
116
|
+
the transaction. Set it back to `true` to opt into PostgreJS's behaviour.
|
|
117
|
+
|
|
118
|
+
## Aborting a query
|
|
119
|
+
|
|
120
|
+
Pass a signal, and pick what should happen to the statement already running on the server:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
const controller = new AbortController();
|
|
124
|
+
|
|
125
|
+
await db.selectFrom('person').selectAll().execute({
|
|
126
|
+
signal: controller.signal,
|
|
127
|
+
inflightQueryAbortStrategy: 'cancel query', // or 'kill session'
|
|
128
|
+
});
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Both strategies are supported, and neither queues behind the pool:
|
|
132
|
+
|
|
133
|
+
- **`'cancel query'`** sends a CancelRequest, which the protocol carries on a connection of its own.
|
|
134
|
+
The statement rejects with PostgreSQL's `57014` and the connection stays usable. Kysely's `pg`
|
|
135
|
+
dialect has to run `pg_cancel_backend()` from a second connection instead - either a dedicated
|
|
136
|
+
client or, failing that, one it waits for the pool to free.
|
|
137
|
+
- **`'kill session'`** runs `pg_terminate_backend()` from a session opened for the occasion. The
|
|
138
|
+
query, its transaction and its locks go with the backend; the pool notices the closed connection
|
|
139
|
+
and replaces it.
|
|
140
|
+
|
|
141
|
+
The default, `'ignore query'`, stops waiting and leaves the statement running - no dialect support
|
|
142
|
+
is involved.
|
|
143
|
+
|
|
144
|
+
## Differences from Kysely's `pg` dialect
|
|
145
|
+
|
|
146
|
+
- **`int8` is a number, not a string, unless you ask.** The default is PostgreJS's own decoding;
|
|
147
|
+
`fetchAsString: [DataTypeOIDs.int8]` gives you `pg`'s strings. See above.
|
|
148
|
+
- **Errors are PostgreJS's `DatabaseError`,** not `pg`'s. The PostgreSQL `code` (`23505`, `42P01`)
|
|
149
|
+
is the same and is what to match on; `instanceof` against `pg`'s class is not.
|
|
150
|
+
|
|
151
|
+
## Kysely's own test suite
|
|
152
|
+
|
|
153
|
+
Kysely holds its dialects to a suite of several hundred tests. `scripts/run-kysely-suite.sh` checks Kysely
|
|
154
|
+
out at a known version, points its `postgres` variant at this dialect instead of the built-in `pg`
|
|
155
|
+
one, and runs all of it:
|
|
156
|
+
|
|
157
|
+
```sh
|
|
158
|
+
scripts/run-kysely-suite.sh
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Against Kysely v0.29.6: **683 passing, 1 failing**. Against v0.30.0-beta.2, the other end of the
|
|
162
|
+
peer range: **727 passing, the same 1 failing**. For comparison, the same checkout against Kysely's
|
|
163
|
+
own `pg` dialect passes 684 - the same tests, none of them skipped.
|
|
164
|
+
|
|
165
|
+
The one failure asserts that the pool's last error reads "Connection terminated unexpectedly", which
|
|
166
|
+
is `pg`'s wording after a killed session. PostgreJS 3.6 emits nothing at all there: it destroys the
|
|
167
|
+
connection and opens another. The kill itself works - the test's own check that the query is gone
|
|
168
|
+
passes first. PostgreJS has since grown a `ConnectionLostError` (SQLSTATE `08006`, carrying the
|
|
169
|
+
backend's `processID`) that its pool reports on `'error'` and `'destroy'`, and with that build the
|
|
170
|
+
suite passes all 684 - the same number as Kysely's own `pg` dialect. These numbers move to
|
|
171
|
+
**684 / 0** and **728 / 0** when that release lands and the peer floor moves with it.
|
|
172
|
+
|
|
173
|
+
Two other tests name the `pg` driver rather than describe behaviour: one asserts the error is an
|
|
174
|
+
instance of `pg`'s `DatabaseError`, and one stubs `PostgresDriver.prototype` and expects the stub to
|
|
175
|
+
be called. The patch points both at this dialect's equivalents, which is what makes them test
|
|
176
|
+
anything at all here - left alone they would pass over the behaviour without exercising it.
|
|
177
|
+
|
|
178
|
+
The suite also runs with `fetchAsString: [DataTypeOIDs.int8]`, since every expectation in it is
|
|
179
|
+
written against `pg`'s string bigints.
|
|
180
|
+
|
|
181
|
+
A weekly CI job re-runs both, and fails if that count moves in either direction - the failures are
|
|
182
|
+
known, so what matters is whether the set of them changed.
|
|
183
|
+
|
|
184
|
+
The suite is also what settled two design questions. Transaction and savepoint commands go through
|
|
185
|
+
`connection.executeQuery` rather than PostgreJS's primitives, because that is the seam Kysely wraps
|
|
186
|
+
its logging around - two dozen tests assert the exact statements a transaction runs. And parameter
|
|
187
|
+
types are left to the server, because a declared type breaks every context PostgreSQL would have
|
|
188
|
+
inferred.
|
|
189
|
+
|
|
190
|
+
## Use from a MikroORM driver
|
|
191
|
+
|
|
192
|
+
MikroORM's SQL layer runs on Kysely, so a custom driver only has to hand this dialect over:
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
import { PostgrejsDialect } from 'kysely-postgrejs';
|
|
196
|
+
|
|
197
|
+
class PostgrejsSqlConnection extends AbstractSqlConnection {
|
|
198
|
+
createKyselyDialect() {
|
|
199
|
+
// `pool` being whichever PostgreJS pool the driver manages
|
|
200
|
+
return new PostgrejsDialect({ pool });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Nothing the dialect needs is behind a deep import: `PostgrejsDialect`, `PostgrejsDriver`,
|
|
206
|
+
`PostgrejsConnection` and the config types are all exported from the package root.
|
|
207
|
+
|
|
208
|
+
## Development
|
|
209
|
+
|
|
210
|
+
The unit tests need nothing; the live ones need a PostgreSQL at `127.0.0.1:5432`
|
|
211
|
+
(`postgres`/`postgres`, database `postgres`), which `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD` and
|
|
212
|
+
`PGDATABASE` override.
|
|
213
|
+
|
|
214
|
+
```sh
|
|
215
|
+
npm test # unit + live tests
|
|
216
|
+
npm run citest # the same, with coverage
|
|
217
|
+
npm run qc # lint and circular dependency check
|
|
218
|
+
npm run compile # type check without emitting
|
|
219
|
+
|
|
220
|
+
scripts/run-kysely-suite.sh # Kysely's own suite, on its own database
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
## Status
|
|
224
|
+
|
|
225
|
+
Pre-1.0, and complete enough to use: the query builder, transactions, savepoints, streaming,
|
|
226
|
+
introspection and both in-flight abort strategies all work against a live server, and Kysely's own
|
|
227
|
+
dialect suite passes every test that is not asserting the identity of the `pg` driver.
|
|
228
|
+
|
|
229
|
+
## License
|
|
230
|
+
|
|
231
|
+
BSD-3-Clause
|
package/constants.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The largest row count an Execute message can ask for - PostgreSQL's
|
|
3
|
+
* `maxRows` field is an unsigned 32-bit integer, and PostgreJS refuses
|
|
4
|
+
* anything above this outright.
|
|
5
|
+
*
|
|
6
|
+
* This is what the dialect asks for, rather than leaving the limit unsaid.
|
|
7
|
+
* Kysely's contract is a complete result: `QueryResult` has nowhere to
|
|
8
|
+
* report that rows were left behind, so a truncated one would reach the
|
|
9
|
+
* caller as a short answer with nothing wrong about it. PostgreJS 3.6
|
|
10
|
+
* fetches everything by default and flags a truncated result with
|
|
11
|
+
* `suspended`, so this is belt and braces - but it is the one thing that
|
|
12
|
+
* cannot be got wrong quietly, and saying it costs nothing.
|
|
13
|
+
*/
|
|
14
|
+
export declare const MAX_FETCH_COUNT = 4294967295;
|
package/constants.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The largest row count an Execute message can ask for - PostgreSQL's
|
|
3
|
+
* `maxRows` field is an unsigned 32-bit integer, and PostgreJS refuses
|
|
4
|
+
* anything above this outright.
|
|
5
|
+
*
|
|
6
|
+
* This is what the dialect asks for, rather than leaving the limit unsaid.
|
|
7
|
+
* Kysely's contract is a complete result: `QueryResult` has nowhere to
|
|
8
|
+
* report that rows were left behind, so a truncated one would reach the
|
|
9
|
+
* caller as a short answer with nothing wrong about it. PostgreJS 3.6
|
|
10
|
+
* fetches everything by default and flags a truncated result with
|
|
11
|
+
* `suspended`, so this is belt and braces - but it is the one thing that
|
|
12
|
+
* cannot be got wrong quietly, and saying it costs nothing.
|
|
13
|
+
*/
|
|
14
|
+
export const MAX_FETCH_COUNT = 4294967295;
|
package/index.d.ts
ADDED
package/index.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "kysely-postgrejs",
|
|
3
|
+
"description": "Kysely dialect for PostgreJS - run a Kysely query builder on PostgreJS's wire-protocol client",
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"author": "Panates",
|
|
6
|
+
"license": "BSD-3-Clause",
|
|
7
|
+
"peerDependencies": {
|
|
8
|
+
"kysely": ">=0.29.0 <0.31.0",
|
|
9
|
+
"postgrejs": ">=3.6.1 <4"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"module": "./index.js",
|
|
13
|
+
"types": "./index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./index.d.ts",
|
|
17
|
+
"default": "./index.js"
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=22.0"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://www.postgrejs.com/",
|
|
25
|
+
"contributors": [
|
|
26
|
+
"Eray Hanoglu <e.hanoglu@panates.com>"
|
|
27
|
+
],
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "https://github.com/panates/postgrejs-kysely.git"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"kysely",
|
|
34
|
+
"kysely-dialect",
|
|
35
|
+
"postgrejs",
|
|
36
|
+
"postgresql",
|
|
37
|
+
"postgres",
|
|
38
|
+
"sql",
|
|
39
|
+
"query-builder",
|
|
40
|
+
"typescript",
|
|
41
|
+
"wire-protocol",
|
|
42
|
+
"no-native-bindings",
|
|
43
|
+
"mikro-orm"
|
|
44
|
+
],
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { CompiledQuery, DatabaseConnection, QueryId, QueryResult } from 'kysely';
|
|
2
|
+
import { Connection, type QueryOptions } from 'postgrejs';
|
|
3
|
+
import type { PostgrejsDialectConfig } from './postgrejs-dialect-config.js';
|
|
4
|
+
/**
|
|
5
|
+
* The part of the dialect config a single connection reads - everything
|
|
6
|
+
* about how a statement is executed, and nothing about where connections
|
|
7
|
+
* come from.
|
|
8
|
+
*/
|
|
9
|
+
export type PostgrejsConnectionOptions = Pick<PostgrejsDialectConfig, 'fetchAsString' | 'fetchCount' | 'inferParameterTypes' | 'prepare' | 'rollbackOnError' | 'typeMap'>;
|
|
10
|
+
/**
|
|
11
|
+
* One PostgreJS connection, as Kysely's `DatabaseConnection`.
|
|
12
|
+
*
|
|
13
|
+
* A new instance wraps each acquire: PostgreJS's pool builds a fresh
|
|
14
|
+
* `Connection` facade over the same physical connection every time, so
|
|
15
|
+
* there is nothing stable to cache these on.
|
|
16
|
+
*
|
|
17
|
+
* Neither `executeQuery` nor `streamQuery` takes Kysely's
|
|
18
|
+
* `AbortableOperationOptions`, and that is deliberate rather than an
|
|
19
|
+
* omission: Kysely races the query against the signal itself, and what
|
|
20
|
+
* happens to the statement still running on the server is the caller's
|
|
21
|
+
* choice, made through `inflightQueryAbortStrategy` and carried out by
|
|
22
|
+
* `cancelQuery`/`killSession` below. Handing the signal down to PostgreJS
|
|
23
|
+
* - which cancels the statement out of band - would silently make every
|
|
24
|
+
* abort behave like `'cancel query'`, whatever the caller asked for.
|
|
25
|
+
* Kysely's own `pg` dialect ignores the argument for the same reason.
|
|
26
|
+
*
|
|
27
|
+
* `collectSessionInfo` is not implemented, also deliberately: it exists
|
|
28
|
+
* so a dialect can go and find the session's own backend process id
|
|
29
|
+
* before a query starts, and PostgreJS already knows it - skipping the
|
|
30
|
+
* hook saves the round trip Kysely's `pg` dialect spends on
|
|
31
|
+
* `pg_backend_pid()`.
|
|
32
|
+
*/
|
|
33
|
+
export declare class PostgrejsConnection implements DatabaseConnection {
|
|
34
|
+
protected readonly _connection: Connection;
|
|
35
|
+
protected readonly _config: PostgrejsConnectionOptions;
|
|
36
|
+
/**
|
|
37
|
+
* The query `executeQuery` is waiting on, if any. Both abort handlers
|
|
38
|
+
* are no-ops without one: a cancel that arrives after its query
|
|
39
|
+
* finished is harmless, but `killSession` would otherwise take down a
|
|
40
|
+
* connection that has already gone back to doing someone else's work.
|
|
41
|
+
*/
|
|
42
|
+
protected _inflightQueryId?: QueryId;
|
|
43
|
+
constructor(connection: Connection, config: PostgrejsConnectionOptions);
|
|
44
|
+
/**
|
|
45
|
+
* The underlying PostgreJS connection - everything Kysely's interface
|
|
46
|
+
* does not cover (COPY, LISTEN/NOTIFY, large objects, logical
|
|
47
|
+
* replication) is reachable through it.
|
|
48
|
+
*/
|
|
49
|
+
get connection(): Connection;
|
|
50
|
+
executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>>;
|
|
51
|
+
streamQuery<R>(compiledQuery: CompiledQuery, chunkSize: number): AsyncIterableIterator<QueryResult<R>>;
|
|
52
|
+
/**
|
|
53
|
+
* Cancels the statement this connection is running, for Kysely's
|
|
54
|
+
* `'cancel query'` abort strategy.
|
|
55
|
+
*
|
|
56
|
+
* The CancelRequest travels on a connection of its own, which the
|
|
57
|
+
* protocol opens for exactly this - so unlike Kysely's `pg` dialect,
|
|
58
|
+
* nothing here waits for a second pooled connection to fall idle, and
|
|
59
|
+
* the `controlConnectionProvider` Kysely offers goes unused. The
|
|
60
|
+
* cancelled statement rejects with PostgreSQL's `57014`, and the
|
|
61
|
+
* connection stays usable.
|
|
62
|
+
*
|
|
63
|
+
* Cancelling is a request, not a guarantee: the statement may finish
|
|
64
|
+
* first, and writes are often past the point of being cancellable.
|
|
65
|
+
*/
|
|
66
|
+
cancelQuery(): Promise<void>;
|
|
67
|
+
/**
|
|
68
|
+
* Terminates the backend this connection is running on, for Kysely's
|
|
69
|
+
* `'kill session'` abort strategy - the query, its transaction and any
|
|
70
|
+
* locks it holds go with it.
|
|
71
|
+
*
|
|
72
|
+
* `pg_terminate_backend` has to be called from another session, and
|
|
73
|
+
* that session is opened for the occasion rather than borrowed from the
|
|
74
|
+
* pool: killing is the strategy for when the query must stop at all
|
|
75
|
+
* costs, and queueing behind a busy pool - possibly behind the very
|
|
76
|
+
* connection being killed - would defeat it.
|
|
77
|
+
*/
|
|
78
|
+
killSession(): Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* The session `killSession` runs `pg_terminate_backend` from. It is
|
|
81
|
+
* built from the pooled connection's own configuration, so it reaches
|
|
82
|
+
* the same server as the same user with no further wiring.
|
|
83
|
+
*/
|
|
84
|
+
protected _createControlConnection(): Connection;
|
|
85
|
+
/**
|
|
86
|
+
* PostgreJS gives every parameter a type OID derived from its
|
|
87
|
+
* JavaScript value, and a string becomes `varchar`. That is a
|
|
88
|
+
* declaration, not a hint: `insert into t (json_column) values ($1)`
|
|
89
|
+
* then fails with "column is of type json but expression is of type
|
|
90
|
+
* character varying", and so do `coalesce($1, 1)`, `$1 || x`, and any
|
|
91
|
+
* call to an overloaded function. `pg` sends type 0 - unspecified - and
|
|
92
|
+
* lets PostgreSQL resolve each parameter from where it appears, which
|
|
93
|
+
* is why none of that surfaces there.
|
|
94
|
+
*
|
|
95
|
+
* Wrapping a value in a `BindParam` of OID 0 asks PostgreJS for the
|
|
96
|
+
* same thing: type 0 in Parse, and the value as text in Bind. Set
|
|
97
|
+
* `inferParameterTypes: false` to go back to declaring types.
|
|
98
|
+
*/
|
|
99
|
+
protected _params(parameters: readonly unknown[]): unknown[];
|
|
100
|
+
protected _queryOptions(compiledQuery: CompiledQuery): QueryOptions;
|
|
101
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { BindParam, Connection } from 'postgrejs';
|
|
2
|
+
import { MAX_FETCH_COUNT } from './constants.js';
|
|
3
|
+
/**
|
|
4
|
+
* Commands whose row count answers "how many rows did this change?".
|
|
5
|
+
*
|
|
6
|
+
* MERGE is in the list because Kysely counts it, but PostgreJS only fills
|
|
7
|
+
* `rowsAffected` for INSERT/UPDATE/DELETE, so a MERGE reports `undefined`
|
|
8
|
+
* rather than a count. Nothing is invented here to cover that up - the
|
|
9
|
+
* number simply does not reach us.
|
|
10
|
+
*/
|
|
11
|
+
const AFFECTED_ROW_COMMANDS = new Set(['INSERT', 'UPDATE', 'DELETE', 'MERGE']);
|
|
12
|
+
/**
|
|
13
|
+
* Parameter type OID 0 - "I am not telling you, work it out from the
|
|
14
|
+
* query". PostgreSQL then resolves the parameter from where it appears.
|
|
15
|
+
*/
|
|
16
|
+
const UNSPECIFIED_OID = 0;
|
|
17
|
+
/**
|
|
18
|
+
* The JavaScript types whose PostgreSQL type is better left to the
|
|
19
|
+
* server. Everything else - Date, Buffer, arrays, objects - keeps
|
|
20
|
+
* PostgreJS's own type determination and its binary encoders, which are
|
|
21
|
+
* both correct and faster, and where a value's text form is not something
|
|
22
|
+
* PostgreSQL could parse anyway.
|
|
23
|
+
*/
|
|
24
|
+
const INFERRED_PARAM_TYPES = new Set(['string', 'number', 'boolean', 'bigint']);
|
|
25
|
+
/**
|
|
26
|
+
* One PostgreJS connection, as Kysely's `DatabaseConnection`.
|
|
27
|
+
*
|
|
28
|
+
* A new instance wraps each acquire: PostgreJS's pool builds a fresh
|
|
29
|
+
* `Connection` facade over the same physical connection every time, so
|
|
30
|
+
* there is nothing stable to cache these on.
|
|
31
|
+
*
|
|
32
|
+
* Neither `executeQuery` nor `streamQuery` takes Kysely's
|
|
33
|
+
* `AbortableOperationOptions`, and that is deliberate rather than an
|
|
34
|
+
* omission: Kysely races the query against the signal itself, and what
|
|
35
|
+
* happens to the statement still running on the server is the caller's
|
|
36
|
+
* choice, made through `inflightQueryAbortStrategy` and carried out by
|
|
37
|
+
* `cancelQuery`/`killSession` below. Handing the signal down to PostgreJS
|
|
38
|
+
* - which cancels the statement out of band - would silently make every
|
|
39
|
+
* abort behave like `'cancel query'`, whatever the caller asked for.
|
|
40
|
+
* Kysely's own `pg` dialect ignores the argument for the same reason.
|
|
41
|
+
*
|
|
42
|
+
* `collectSessionInfo` is not implemented, also deliberately: it exists
|
|
43
|
+
* so a dialect can go and find the session's own backend process id
|
|
44
|
+
* before a query starts, and PostgreJS already knows it - skipping the
|
|
45
|
+
* hook saves the round trip Kysely's `pg` dialect spends on
|
|
46
|
+
* `pg_backend_pid()`.
|
|
47
|
+
*/
|
|
48
|
+
export class PostgrejsConnection {
|
|
49
|
+
_connection;
|
|
50
|
+
_config;
|
|
51
|
+
/**
|
|
52
|
+
* The query `executeQuery` is waiting on, if any. Both abort handlers
|
|
53
|
+
* are no-ops without one: a cancel that arrives after its query
|
|
54
|
+
* finished is harmless, but `killSession` would otherwise take down a
|
|
55
|
+
* connection that has already gone back to doing someone else's work.
|
|
56
|
+
*/
|
|
57
|
+
_inflightQueryId;
|
|
58
|
+
constructor(connection, config) {
|
|
59
|
+
this._connection = connection;
|
|
60
|
+
this._config = config;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The underlying PostgreJS connection - everything Kysely's interface
|
|
64
|
+
* does not cover (COPY, LISTEN/NOTIFY, large objects, logical
|
|
65
|
+
* replication) is reachable through it.
|
|
66
|
+
*/
|
|
67
|
+
get connection() {
|
|
68
|
+
return this._connection;
|
|
69
|
+
}
|
|
70
|
+
async executeQuery(compiledQuery) {
|
|
71
|
+
this._inflightQueryId = compiledQuery.queryId;
|
|
72
|
+
try {
|
|
73
|
+
const result = await this._connection.query(compiledQuery.sql, this._queryOptions(compiledQuery));
|
|
74
|
+
const rowsAffected = result.command && AFFECTED_ROW_COMMANDS.has(result.command)
|
|
75
|
+
? result.rowsAffected
|
|
76
|
+
: undefined;
|
|
77
|
+
return {
|
|
78
|
+
rows: (result.rows || []),
|
|
79
|
+
numAffectedRows: rowsAffected == null ? undefined : BigInt(rowsAffected),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
// The stack of an error from a pooled connection stops at the
|
|
84
|
+
// driver; this puts the call that asked for the query back on it.
|
|
85
|
+
throw extendStackTrace(error, new Error());
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
this._inflightQueryId = undefined;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async *streamQuery(compiledQuery, chunkSize) {
|
|
92
|
+
if (!Number.isInteger(chunkSize) || chunkSize <= 0)
|
|
93
|
+
throw new Error('chunkSize must be a positive integer');
|
|
94
|
+
const result = await this._connection.query(compiledQuery.sql, {
|
|
95
|
+
...this._queryOptions(compiledQuery),
|
|
96
|
+
// One server round trip per chunk rather than per row: the cursor
|
|
97
|
+
// fetches `fetchCount` rows at a time, and `fetch()` hands out that
|
|
98
|
+
// same number.
|
|
99
|
+
cursor: true,
|
|
100
|
+
fetchCount: chunkSize,
|
|
101
|
+
});
|
|
102
|
+
/* c8 ignore next - `cursor: true` always produces one */
|
|
103
|
+
if (!result.cursor)
|
|
104
|
+
throw new Error('Server did not return a cursor');
|
|
105
|
+
const cursor = result.cursor;
|
|
106
|
+
try {
|
|
107
|
+
while (true) {
|
|
108
|
+
const rows = await cursor.fetch(chunkSize);
|
|
109
|
+
if (!rows.length)
|
|
110
|
+
break;
|
|
111
|
+
yield { rows: rows };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
// Closes whether the consumer ran out of rows, broke out of the
|
|
116
|
+
// loop, or threw. This is also how an aborted stream ends: Kysely
|
|
117
|
+
// calls the iterator's `return()` rather than either handler below.
|
|
118
|
+
await cursor.close();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Cancels the statement this connection is running, for Kysely's
|
|
123
|
+
* `'cancel query'` abort strategy.
|
|
124
|
+
*
|
|
125
|
+
* The CancelRequest travels on a connection of its own, which the
|
|
126
|
+
* protocol opens for exactly this - so unlike Kysely's `pg` dialect,
|
|
127
|
+
* nothing here waits for a second pooled connection to fall idle, and
|
|
128
|
+
* the `controlConnectionProvider` Kysely offers goes unused. The
|
|
129
|
+
* cancelled statement rejects with PostgreSQL's `57014`, and the
|
|
130
|
+
* connection stays usable.
|
|
131
|
+
*
|
|
132
|
+
* Cancelling is a request, not a guarantee: the statement may finish
|
|
133
|
+
* first, and writes are often past the point of being cancellable.
|
|
134
|
+
*/
|
|
135
|
+
async cancelQuery() {
|
|
136
|
+
if (!this._inflightQueryId)
|
|
137
|
+
return;
|
|
138
|
+
await this._connection.cancel();
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Terminates the backend this connection is running on, for Kysely's
|
|
142
|
+
* `'kill session'` abort strategy - the query, its transaction and any
|
|
143
|
+
* locks it holds go with it.
|
|
144
|
+
*
|
|
145
|
+
* `pg_terminate_backend` has to be called from another session, and
|
|
146
|
+
* that session is opened for the occasion rather than borrowed from the
|
|
147
|
+
* pool: killing is the strategy for when the query must stop at all
|
|
148
|
+
* costs, and queueing behind a busy pool - possibly behind the very
|
|
149
|
+
* connection being killed - would defeat it.
|
|
150
|
+
*/
|
|
151
|
+
async killSession() {
|
|
152
|
+
const queryId = this._inflightQueryId;
|
|
153
|
+
if (!queryId)
|
|
154
|
+
return;
|
|
155
|
+
const processId = this._connection.processID;
|
|
156
|
+
/* c8 ignore next - a connection the pool handed out is connected */
|
|
157
|
+
if (processId == null)
|
|
158
|
+
return;
|
|
159
|
+
const control = this._createControlConnection();
|
|
160
|
+
await control.connect();
|
|
161
|
+
try {
|
|
162
|
+
// Opening that connection took a moment, and the query may have
|
|
163
|
+
// finished in it. Killing the backend then would take down a
|
|
164
|
+
// connection that is no longer doing what we wanted stopped.
|
|
165
|
+
if (this._inflightQueryId !== queryId)
|
|
166
|
+
return;
|
|
167
|
+
await control.query('select pg_terminate_backend($1)', {
|
|
168
|
+
params: [processId],
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
await control.close();
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The session `killSession` runs `pg_terminate_backend` from. It is
|
|
177
|
+
* built from the pooled connection's own configuration, so it reaches
|
|
178
|
+
* the same server as the same user with no further wiring.
|
|
179
|
+
*/
|
|
180
|
+
_createControlConnection() {
|
|
181
|
+
return new Connection(this._connection.config);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* PostgreJS gives every parameter a type OID derived from its
|
|
185
|
+
* JavaScript value, and a string becomes `varchar`. That is a
|
|
186
|
+
* declaration, not a hint: `insert into t (json_column) values ($1)`
|
|
187
|
+
* then fails with "column is of type json but expression is of type
|
|
188
|
+
* character varying", and so do `coalesce($1, 1)`, `$1 || x`, and any
|
|
189
|
+
* call to an overloaded function. `pg` sends type 0 - unspecified - and
|
|
190
|
+
* lets PostgreSQL resolve each parameter from where it appears, which
|
|
191
|
+
* is why none of that surfaces there.
|
|
192
|
+
*
|
|
193
|
+
* Wrapping a value in a `BindParam` of OID 0 asks PostgreJS for the
|
|
194
|
+
* same thing: type 0 in Parse, and the value as text in Bind. Set
|
|
195
|
+
* `inferParameterTypes: false` to go back to declaring types.
|
|
196
|
+
*/
|
|
197
|
+
_params(parameters) {
|
|
198
|
+
if (this._config.inferParameterTypes === false)
|
|
199
|
+
return parameters;
|
|
200
|
+
const l = parameters.length;
|
|
201
|
+
const params = new Array(l);
|
|
202
|
+
let i;
|
|
203
|
+
let value;
|
|
204
|
+
for (i = 0; i < l; i++) {
|
|
205
|
+
value = parameters[i];
|
|
206
|
+
params[i] =
|
|
207
|
+
value == null || INFERRED_PARAM_TYPES.has(typeof value)
|
|
208
|
+
? new BindParam(UNSPECIFIED_OID, value)
|
|
209
|
+
: value;
|
|
210
|
+
}
|
|
211
|
+
return params;
|
|
212
|
+
}
|
|
213
|
+
_queryOptions(compiledQuery) {
|
|
214
|
+
const config = this._config;
|
|
215
|
+
return {
|
|
216
|
+
params: this._params(compiledQuery.parameters),
|
|
217
|
+
// Kysely reads rows as objects; PostgreJS hands out arrays of
|
|
218
|
+
// values unless told otherwise.
|
|
219
|
+
rowDecoder: 'object',
|
|
220
|
+
fetchCount: config.fetchCount ?? MAX_FETCH_COUNT,
|
|
221
|
+
// PostgreSQL's own behaviour: a failed statement aborts the
|
|
222
|
+
// transaction. PostgreJS defaults to the opposite.
|
|
223
|
+
rollbackOnError: config.rollbackOnError ?? false,
|
|
224
|
+
prepare: config.prepare,
|
|
225
|
+
typeMap: config.typeMap,
|
|
226
|
+
fetchAsString: config.fetchAsString,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Kysely's own `extendStackTrace`, which it does not export: an error
|
|
232
|
+
* thrown from inside a pooled connection carries the driver's stack, not
|
|
233
|
+
* the caller's, and this appends the one captured where the query was
|
|
234
|
+
* issued.
|
|
235
|
+
*/
|
|
236
|
+
function extendStackTrace(error, stackError) {
|
|
237
|
+
if (error !== null &&
|
|
238
|
+
typeof error === 'object' &&
|
|
239
|
+
typeof error.stack === 'string' &&
|
|
240
|
+
stackError.stack) {
|
|
241
|
+
const holder = error;
|
|
242
|
+
// The first line is just "Error", which would read as a second error.
|
|
243
|
+
holder.stack += '\n' + stackError.stack.split('\n').slice(1).join('\n');
|
|
244
|
+
}
|
|
245
|
+
return error;
|
|
246
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { AbortableOperationOptions, DatabaseConnection } from 'kysely';
|
|
2
|
+
import type { DataTypeMap, OID, Pool } from 'postgrejs';
|
|
3
|
+
/**
|
|
4
|
+
* Config for the PostgreJS dialect.
|
|
5
|
+
*/
|
|
6
|
+
export interface PostgrejsDialectConfig {
|
|
7
|
+
/**
|
|
8
|
+
* PostgreSQL types that should come back as the text the server renders,
|
|
9
|
+
* by OID, instead of being decoded into a JavaScript value.
|
|
10
|
+
*
|
|
11
|
+
* This is how to get `pg`'s bigints: `fetchAsString: [DataTypeOIDs.int8]`
|
|
12
|
+
* makes `count(*)`, `sum(...)` and every other `int8` a string, which is
|
|
13
|
+
* what Kysely's generated types and most code ported from `pg` expect.
|
|
14
|
+
* PostgreJS otherwise decodes `int8` as a number inside the safe integer
|
|
15
|
+
* range and a BigInt beyond it. The server renders the listed columns as
|
|
16
|
+
* text and they are handed over untouched, so a value past 2^53 keeps
|
|
17
|
+
* every digit.
|
|
18
|
+
*/
|
|
19
|
+
fetchAsString?: OID[];
|
|
20
|
+
/**
|
|
21
|
+
* How many rows each statement may return before PostgreSQL suspends the
|
|
22
|
+
* portal. Defaults to {@link MAX_FETCH_COUNT}, i.e. "however many there
|
|
23
|
+
* are" - see that constant for why the dialect says so rather than
|
|
24
|
+
* leaving it unsaid. Lower it and a result can come back short with no
|
|
25
|
+
* way for Kysely to know: `QueryResult` has nowhere to carry PostgreJS's
|
|
26
|
+
* `suspended`. `streamQuery` ignores this and uses Kysely's `chunkSize`.
|
|
27
|
+
*/
|
|
28
|
+
fetchCount?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Whether each parameter's PostgreSQL type is left to the server to
|
|
31
|
+
* resolve from where it appears in the query - what `pg` does, and what
|
|
32
|
+
* Kysely's users therefore expect.
|
|
33
|
+
*
|
|
34
|
+
* Defaults to `true`. PostgreJS otherwise declares a type derived from
|
|
35
|
+
* the JavaScript value, which makes a string a `varchar` and breaks
|
|
36
|
+
* every context where PostgreSQL would have inferred something else: a
|
|
37
|
+
* `json` column, a `coalesce` of mixed types, `||`, an overloaded
|
|
38
|
+
* function. Only strings, numbers, booleans, bigints and nulls are
|
|
39
|
+
* affected - dates, buffers, arrays and objects keep PostgreJS's typed,
|
|
40
|
+
* binary encoding either way.
|
|
41
|
+
*/
|
|
42
|
+
inferParameterTypes?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Called once for each physical connection the pool opens, before it is
|
|
45
|
+
* first handed to Kysely.
|
|
46
|
+
*
|
|
47
|
+
* PostgreJS's pool builds a fresh `Connection` facade on every acquire,
|
|
48
|
+
* so "the same connection" is recognised by its backend process id
|
|
49
|
+
* rather than by object identity. A pid is forgotten when the pool
|
|
50
|
+
* destroys that connection, so the hook runs again for its replacement.
|
|
51
|
+
*/
|
|
52
|
+
onCreateConnection?: (connection: DatabaseConnection, options?: AbortableOperationOptions) => Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Called every time a connection is acquired from the pool.
|
|
55
|
+
*/
|
|
56
|
+
onReserveConnection?: (connection: DatabaseConnection, options?: AbortableOperationOptions) => Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* A PostgreJS `Pool` instance, or a function returning one - the
|
|
59
|
+
* function is called once, when the driver initialises.
|
|
60
|
+
*
|
|
61
|
+
* The driver never uses `pool.query()`: that is free to pick a different
|
|
62
|
+
* connection per call, which would scatter a transaction across
|
|
63
|
+
* connections. It acquires and releases explicitly instead.
|
|
64
|
+
*/
|
|
65
|
+
pool: Pool | ((options?: AbortableOperationOptions) => Promise<Pool>);
|
|
66
|
+
/**
|
|
67
|
+
* Whether statements are cached as server-side prepared statements.
|
|
68
|
+
* Leave unset to follow the connection's own `prepare` setting;
|
|
69
|
+
* `false` is what PgBouncer in transaction pooling mode needs (before
|
|
70
|
+
* 1.21), where a named statement does not survive to the next call.
|
|
71
|
+
*/
|
|
72
|
+
prepare?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Whether a failed statement inside a transaction leaves the rest of the
|
|
75
|
+
* transaction usable.
|
|
76
|
+
*
|
|
77
|
+
* Defaults to `false`, which is PostgreSQL's own behaviour and the one
|
|
78
|
+
* `pg` - and therefore every existing Kysely user - expects: the
|
|
79
|
+
* transaction is aborted and nothing but a rollback is accepted after
|
|
80
|
+
* it. PostgreJS defaults this to `true` instead, wrapping every
|
|
81
|
+
* statement in a savepoint of its own; set it back to `true` here to opt
|
|
82
|
+
* into that.
|
|
83
|
+
*/
|
|
84
|
+
rollbackOnError?: boolean;
|
|
85
|
+
/**
|
|
86
|
+
* A custom `DataTypeMap`, to override how individual PostgreSQL types
|
|
87
|
+
* are decoded. Defaults to PostgreJS's `GlobalTypeMap`.
|
|
88
|
+
*/
|
|
89
|
+
typeMap?: DataTypeMap;
|
|
90
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type DatabaseIntrospector, type Dialect, type DialectAdapter, type Driver, type Kysely, type QueryCompiler } from 'kysely';
|
|
2
|
+
import type { PostgrejsDialectConfig } from './postgrejs-dialect-config.js';
|
|
3
|
+
/**
|
|
4
|
+
* A Kysely dialect that runs on PostgreJS.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { Kysely } from 'kysely';
|
|
8
|
+
* import { Pool } from 'postgrejs';
|
|
9
|
+
* import { PostgrejsDialect } from 'kysely-postgrejs';
|
|
10
|
+
*
|
|
11
|
+
* const db = new Kysely<Database>({
|
|
12
|
+
* dialect: new PostgrejsDialect({
|
|
13
|
+
* pool: new Pool('postgres://localhost:5432/mydb'),
|
|
14
|
+
* }),
|
|
15
|
+
* });
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* Only the driver is PostgreJS-specific: the SQL PostgreSQL speaks is the
|
|
19
|
+
* same either way, so the adapter, introspector and compiler are Kysely's
|
|
20
|
+
* own.
|
|
21
|
+
*/
|
|
22
|
+
export declare class PostgrejsDialect implements Dialect {
|
|
23
|
+
protected readonly _config: PostgrejsDialectConfig;
|
|
24
|
+
constructor(config: PostgrejsDialectConfig);
|
|
25
|
+
createAdapter(): DialectAdapter;
|
|
26
|
+
createDriver(): Driver;
|
|
27
|
+
createIntrospector(db: Kysely<any>): DatabaseIntrospector;
|
|
28
|
+
createQueryCompiler(): QueryCompiler;
|
|
29
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler, } from 'kysely';
|
|
2
|
+
import { PostgrejsDriver } from './postgrejs-driver.js';
|
|
3
|
+
/**
|
|
4
|
+
* A Kysely dialect that runs on PostgreJS.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { Kysely } from 'kysely';
|
|
8
|
+
* import { Pool } from 'postgrejs';
|
|
9
|
+
* import { PostgrejsDialect } from 'kysely-postgrejs';
|
|
10
|
+
*
|
|
11
|
+
* const db = new Kysely<Database>({
|
|
12
|
+
* dialect: new PostgrejsDialect({
|
|
13
|
+
* pool: new Pool('postgres://localhost:5432/mydb'),
|
|
14
|
+
* }),
|
|
15
|
+
* });
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* Only the driver is PostgreJS-specific: the SQL PostgreSQL speaks is the
|
|
19
|
+
* same either way, so the adapter, introspector and compiler are Kysely's
|
|
20
|
+
* own.
|
|
21
|
+
*/
|
|
22
|
+
export class PostgrejsDialect {
|
|
23
|
+
_config;
|
|
24
|
+
constructor(config) {
|
|
25
|
+
this._config = config;
|
|
26
|
+
}
|
|
27
|
+
createAdapter() {
|
|
28
|
+
return new PostgresAdapter();
|
|
29
|
+
}
|
|
30
|
+
createDriver() {
|
|
31
|
+
return new PostgrejsDriver(this._config);
|
|
32
|
+
}
|
|
33
|
+
createIntrospector(db) {
|
|
34
|
+
return new PostgresIntrospector(db);
|
|
35
|
+
}
|
|
36
|
+
createQueryCompiler() {
|
|
37
|
+
return new PostgresQueryCompiler();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type AbortableOperationOptions, type DatabaseConnection, type Driver, type QueryCompiler, type TransactionSettings } from 'kysely';
|
|
2
|
+
import type { Pool } from 'postgrejs';
|
|
3
|
+
import type { PostgrejsDialectConfig } from './postgrejs-dialect-config.js';
|
|
4
|
+
/** What the pool's `destroy` event hands us, narrowed to what we read. */
|
|
5
|
+
interface DestroyedConnection {
|
|
6
|
+
processID?: number;
|
|
7
|
+
}
|
|
8
|
+
export declare class PostgrejsDriver implements Driver {
|
|
9
|
+
protected readonly _config: PostgrejsDialectConfig;
|
|
10
|
+
/**
|
|
11
|
+
* Backend process ids `onCreateConnection` has already run for. A pid
|
|
12
|
+
* identifies a physical connection where object identity cannot: the
|
|
13
|
+
* pool builds a new `Connection` facade on every acquire. Entries are
|
|
14
|
+
* dropped when the pool destroys that connection, so its replacement is
|
|
15
|
+
* initialised again.
|
|
16
|
+
*/
|
|
17
|
+
protected readonly _initializedProcessIds: Set<number>;
|
|
18
|
+
protected _pool?: Pool;
|
|
19
|
+
protected _onPoolDestroy?: (connection: DestroyedConnection) => void;
|
|
20
|
+
constructor(config: PostgrejsDialectConfig);
|
|
21
|
+
init(options?: AbortableOperationOptions): Promise<void>;
|
|
22
|
+
acquireConnection(options?: AbortableOperationOptions): Promise<DatabaseConnection>;
|
|
23
|
+
/**
|
|
24
|
+
* Every transaction and savepoint command goes through the connection's
|
|
25
|
+
* own `executeQuery` rather than PostgreJS's same-named primitives -
|
|
26
|
+
* `startTransaction()`, `commit()`, `savepoint(name)` and the rest.
|
|
27
|
+
*
|
|
28
|
+
* That seam is where Kysely wraps logging: `RuntimeDriver` patches
|
|
29
|
+
* `executeQuery` on each connection it hands out, so a BEGIN sent any
|
|
30
|
+
* other way never reaches the `log` callback, `db.on('query')`, or
|
|
31
|
+
* anything else built on it - it simply does not exist as far as Kysely
|
|
32
|
+
* is concerned. Kysely's own dialect test suite asserts the full list
|
|
33
|
+
* of statements a transaction runs, and running the primitives instead
|
|
34
|
+
* fails around two dozen of those cases.
|
|
35
|
+
*
|
|
36
|
+
* Nothing is lost by going through SQL. PostgreJS reads `inTransaction`
|
|
37
|
+
* from the server's own transaction status rather than from the depth
|
|
38
|
+
* counter its primitives keep, and recognises BEGIN/COMMIT/SAVEPOINT in
|
|
39
|
+
* a statement, so its bookkeeping stays in step either way. Savepoint
|
|
40
|
+
* names also stop going through PostgreJS's own validation: Kysely
|
|
41
|
+
* compiles the name as a quoted identifier, as `pg` does.
|
|
42
|
+
*/
|
|
43
|
+
beginTransaction(connection: DatabaseConnection, settings: TransactionSettings): Promise<void>;
|
|
44
|
+
commitTransaction(connection: DatabaseConnection): Promise<void>;
|
|
45
|
+
rollbackTransaction(connection: DatabaseConnection): Promise<void>;
|
|
46
|
+
savepoint(connection: DatabaseConnection, savepointName: string, compileQuery: QueryCompiler['compileQuery']): Promise<void>;
|
|
47
|
+
rollbackToSavepoint(connection: DatabaseConnection, savepointName: string, compileQuery: QueryCompiler['compileQuery']): Promise<void>;
|
|
48
|
+
releaseSavepoint(connection: DatabaseConnection, savepointName: string, compileQuery: QueryCompiler['compileQuery']): Promise<void>;
|
|
49
|
+
releaseConnection(connection: DatabaseConnection): Promise<void>;
|
|
50
|
+
destroy(): Promise<void>;
|
|
51
|
+
protected _assertPool(): Pool;
|
|
52
|
+
}
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { CompiledQuery, createQueryId, IdentifierNode, RawNode, } from 'kysely';
|
|
2
|
+
import { PostgrejsConnection } from './postgrejs-connection.js';
|
|
3
|
+
export class PostgrejsDriver {
|
|
4
|
+
_config;
|
|
5
|
+
/**
|
|
6
|
+
* Backend process ids `onCreateConnection` has already run for. A pid
|
|
7
|
+
* identifies a physical connection where object identity cannot: the
|
|
8
|
+
* pool builds a new `Connection` facade on every acquire. Entries are
|
|
9
|
+
* dropped when the pool destroys that connection, so its replacement is
|
|
10
|
+
* initialised again.
|
|
11
|
+
*/
|
|
12
|
+
_initializedProcessIds = new Set();
|
|
13
|
+
_pool;
|
|
14
|
+
_onPoolDestroy;
|
|
15
|
+
constructor(config) {
|
|
16
|
+
this._config = Object.freeze({ ...config });
|
|
17
|
+
}
|
|
18
|
+
async init(options) {
|
|
19
|
+
const { pool } = this._config;
|
|
20
|
+
const resolved = typeof pool === 'function' ? await pool(options) : pool;
|
|
21
|
+
this._onPoolDestroy = (connection) => {
|
|
22
|
+
if (connection?.processID != null)
|
|
23
|
+
this._initializedProcessIds.delete(connection.processID);
|
|
24
|
+
};
|
|
25
|
+
resolved.on('destroy', this._onPoolDestroy);
|
|
26
|
+
this._pool = resolved;
|
|
27
|
+
}
|
|
28
|
+
async acquireConnection(options) {
|
|
29
|
+
const connection = new PostgrejsConnection(await this._assertPool().acquire(), this._config);
|
|
30
|
+
const { onCreateConnection, onReserveConnection } = this._config;
|
|
31
|
+
if (onCreateConnection) {
|
|
32
|
+
const pid = connection.connection.processID;
|
|
33
|
+
if (pid == null || !this._initializedProcessIds.has(pid)) {
|
|
34
|
+
if (pid != null)
|
|
35
|
+
this._initializedProcessIds.add(pid);
|
|
36
|
+
await onCreateConnection(connection, options);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (onReserveConnection)
|
|
40
|
+
await onReserveConnection(connection, options);
|
|
41
|
+
return connection;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Every transaction and savepoint command goes through the connection's
|
|
45
|
+
* own `executeQuery` rather than PostgreJS's same-named primitives -
|
|
46
|
+
* `startTransaction()`, `commit()`, `savepoint(name)` and the rest.
|
|
47
|
+
*
|
|
48
|
+
* That seam is where Kysely wraps logging: `RuntimeDriver` patches
|
|
49
|
+
* `executeQuery` on each connection it hands out, so a BEGIN sent any
|
|
50
|
+
* other way never reaches the `log` callback, `db.on('query')`, or
|
|
51
|
+
* anything else built on it - it simply does not exist as far as Kysely
|
|
52
|
+
* is concerned. Kysely's own dialect test suite asserts the full list
|
|
53
|
+
* of statements a transaction runs, and running the primitives instead
|
|
54
|
+
* fails around two dozen of those cases.
|
|
55
|
+
*
|
|
56
|
+
* Nothing is lost by going through SQL. PostgreJS reads `inTransaction`
|
|
57
|
+
* from the server's own transaction status rather than from the depth
|
|
58
|
+
* counter its primitives keep, and recognises BEGIN/COMMIT/SAVEPOINT in
|
|
59
|
+
* a statement, so its bookkeeping stays in step either way. Savepoint
|
|
60
|
+
* names also stop going through PostgreJS's own validation: Kysely
|
|
61
|
+
* compiles the name as a quoted identifier, as `pg` does.
|
|
62
|
+
*/
|
|
63
|
+
async beginTransaction(connection, settings) {
|
|
64
|
+
const { isolationLevel, accessMode } = settings;
|
|
65
|
+
let sql = 'begin';
|
|
66
|
+
if (isolationLevel || accessMode) {
|
|
67
|
+
sql = 'start transaction';
|
|
68
|
+
if (isolationLevel)
|
|
69
|
+
sql += ` isolation level ${isolationLevel}`;
|
|
70
|
+
if (accessMode)
|
|
71
|
+
sql += ` ${accessMode}`;
|
|
72
|
+
}
|
|
73
|
+
await connection.executeQuery(CompiledQuery.raw(sql));
|
|
74
|
+
}
|
|
75
|
+
async commitTransaction(connection) {
|
|
76
|
+
await connection.executeQuery(CompiledQuery.raw('commit'));
|
|
77
|
+
}
|
|
78
|
+
async rollbackTransaction(connection) {
|
|
79
|
+
await connection.executeQuery(CompiledQuery.raw('rollback'));
|
|
80
|
+
}
|
|
81
|
+
async savepoint(connection, savepointName, compileQuery) {
|
|
82
|
+
await connection.executeQuery(compileSavepointCommand('savepoint', savepointName, compileQuery));
|
|
83
|
+
}
|
|
84
|
+
async rollbackToSavepoint(connection, savepointName, compileQuery) {
|
|
85
|
+
await connection.executeQuery(compileSavepointCommand('rollback to', savepointName, compileQuery));
|
|
86
|
+
}
|
|
87
|
+
async releaseSavepoint(connection, savepointName, compileQuery) {
|
|
88
|
+
await connection.executeQuery(compileSavepointCommand('release', savepointName, compileQuery));
|
|
89
|
+
}
|
|
90
|
+
async releaseConnection(connection) {
|
|
91
|
+
await this._pool?.release(assertPostgrejsConnection(connection).connection);
|
|
92
|
+
}
|
|
93
|
+
async destroy() {
|
|
94
|
+
const pool = this._pool;
|
|
95
|
+
if (!pool)
|
|
96
|
+
return;
|
|
97
|
+
this._pool = undefined;
|
|
98
|
+
if (this._onPoolDestroy)
|
|
99
|
+
pool.removeListener('destroy', this._onPoolDestroy);
|
|
100
|
+
this._initializedProcessIds.clear();
|
|
101
|
+
await pool.close();
|
|
102
|
+
}
|
|
103
|
+
_assertPool() {
|
|
104
|
+
if (!this._pool)
|
|
105
|
+
throw new Error('Driver is not initialized. Did you call init()?');
|
|
106
|
+
return this._pool;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A savepoint command as Kysely's own dialects build it: the name goes
|
|
111
|
+
* through the dialect's compiler as an identifier, so it is quoted rather
|
|
112
|
+
* than pasted into the SQL. Kysely keeps its `parseSavepointCommand`
|
|
113
|
+
* internal, so the two nodes it makes are spelled out here.
|
|
114
|
+
*/
|
|
115
|
+
function compileSavepointCommand(command, savepointName, compileQuery) {
|
|
116
|
+
return compileQuery(RawNode.createWithChildren([
|
|
117
|
+
RawNode.createWithSql(`${command} `),
|
|
118
|
+
IdentifierNode.create(savepointName),
|
|
119
|
+
]), createQueryId());
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Kysely hands a driver back the connection its own `acquireConnection`
|
|
123
|
+
* returned, so this only ever fails for a connection from somewhere else.
|
|
124
|
+
*/
|
|
125
|
+
function assertPostgrejsConnection(connection) {
|
|
126
|
+
if (!(connection instanceof PostgrejsConnection))
|
|
127
|
+
throw new TypeError('Connection was not created by PostgrejsDriver');
|
|
128
|
+
return connection;
|
|
129
|
+
}
|