@otwdesign/db-core 1.3.1 → 1.4.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/dist/backup/api.js +67 -9
- package/dist/backup/api.js.map +1 -1
- package/dist/backup/catalog.d.ts +9 -2
- package/dist/backup/catalog.js +42 -18
- package/dist/backup/catalog.js.map +1 -1
- package/dist/backup/dump.d.ts +6 -2
- package/dist/backup/dump.js +188 -20
- package/dist/backup/dump.js.map +1 -1
- package/dist/backup/restore.d.ts +9 -1
- package/dist/backup/restore.js +131 -11
- package/dist/backup/restore.js.map +1 -1
- package/dist/backup/split.d.ts +7 -2
- package/dist/backup/split.js +38 -6
- package/dist/backup/split.js.map +1 -1
- package/dist/backup/staging.d.ts +6 -1
- package/dist/backup/staging.js +38 -10
- package/dist/backup/staging.js.map +1 -1
- package/dist/drivers/mysql.d.ts +6 -0
- package/dist/drivers/mysql.js +142 -18
- package/dist/drivers/mysql.js.map +1 -1
- package/dist/drivers/pglite.d.ts +18 -3
- package/dist/drivers/pglite.js +357 -55
- package/dist/drivers/pglite.js.map +1 -1
- package/dist/drivers/postgres-catalog.d.ts +16 -1
- package/dist/drivers/postgres-catalog.js +34 -0
- package/dist/drivers/postgres-catalog.js.map +1 -1
- package/dist/drivers/postgres.d.ts +10 -0
- package/dist/drivers/postgres.js +203 -29
- package/dist/drivers/postgres.js.map +1 -1
- package/dist/drivers/read-only.d.ts +4 -0
- package/dist/drivers/read-only.js +156 -0
- package/dist/drivers/read-only.js.map +1 -0
- package/dist/drivers/sql.d.ts +51 -4
- package/dist/drivers/sql.js +112 -35
- package/dist/drivers/sql.js.map +1 -1
- package/dist/drivers/sqlite.d.ts +33 -1
- package/dist/drivers/sqlite.js +645 -69
- package/dist/drivers/sqlite.js.map +1 -1
- package/dist/export.d.ts +4 -5
- package/dist/export.js +21 -3
- package/dist/export.js.map +1 -1
- package/dist/format.js +7 -1
- package/dist/format.js.map +1 -1
- package/dist/handler.js +37 -15
- package/dist/handler.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +37 -3
- package/dist/words.d.ts +19 -0
- package/dist/words.js +76 -0
- package/dist/words.js.map +1 -0
- package/package.json +8 -7
- package/src/backup/api.ts +82 -14
- package/src/backup/catalog.ts +43 -18
- package/src/backup/dump.ts +208 -21
- package/src/backup/restore.ts +152 -12
- package/src/backup/split.ts +38 -6
- package/src/backup/staging.ts +51 -10
- package/src/drivers/mysql.ts +171 -21
- package/src/drivers/pglite.ts +419 -56
- package/src/drivers/postgres-catalog.ts +51 -1
- package/src/drivers/postgres.ts +241 -33
- package/src/drivers/read-only.ts +174 -0
- package/src/drivers/sql.ts +170 -37
- package/src/drivers/sqlite.ts +739 -98
- package/src/export.ts +26 -6
- package/src/format.ts +9 -1
- package/src/handler.ts +55 -19
- package/src/index.ts +7 -2
- package/src/types.ts +38 -1
- package/src/words.ts +67 -0
package/src/backup/split.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* PostgreSQL's SQL cut into statements as it streams in, the way psql reads a file: a semicolon
|
|
3
3
|
* ends a statement unless it's inside a string ('…', E'…', $tag$…$tag$), a quoted name ("…") or a
|
|
4
|
-
* comment (-- …
|
|
4
|
+
* comment (-- … to the line's end, a line feed or a carriage return, and nested /* … *\/), inside
|
|
5
|
+
* parentheses, or inside a function's BEGIN ATOMIC …
|
|
5
6
|
* END body. Text may arrive cut anywhere, even inside a string or a dollar quote's tag. A
|
|
6
7
|
* statement keeps the comments inside and before it; comments with nothing after them are
|
|
7
8
|
* dropped.
|
|
@@ -28,21 +29,47 @@ export class StatementSplitter {
|
|
|
28
29
|
/** Words read in the statement, and the first letters of the first four that matter. */
|
|
29
30
|
#words = 0
|
|
30
31
|
#head = ''
|
|
32
|
+
/** What has come since the last read, and how much text must have come before the next. */
|
|
33
|
+
#waiting: string[] = []
|
|
34
|
+
#waitingLength = 0
|
|
35
|
+
#hold = 0
|
|
31
36
|
|
|
32
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* Reads `text` and returns the statements it completes, without their semicolons. While one
|
|
39
|
+
* statement is longer than `LONG`, its text is read again only once as much again has come, so
|
|
40
|
+
* the statements after it may come out a push or two later, or from `end()`.
|
|
41
|
+
*/
|
|
33
42
|
push(text: string): string[] {
|
|
34
|
-
|
|
43
|
+
this.#waiting.push(text)
|
|
44
|
+
this.#waitingLength += text.length
|
|
45
|
+
if (this.#waitingLength < this.#hold) return []
|
|
46
|
+
this.#take()
|
|
47
|
+
const done = this.#read(false)
|
|
48
|
+
// Each read makes one string of all the statement has so far. Once per piece, a statement
|
|
49
|
+
// of megabytes that comes in kilobytes is copied thousands of times over; reading it again
|
|
50
|
+
// only when it has doubled copies it twice in all, whatever its length.
|
|
51
|
+
const unfinished = this.#text.length - this.#start
|
|
52
|
+
this.#hold = done.length === 0 && unfinished >= LONG ? unfinished : 0
|
|
53
|
+
return done
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Adds what has come since the last read to the text. */
|
|
57
|
+
#take(): void {
|
|
58
|
+
// Drop what earlier statements took, once per read rather than once per statement.
|
|
35
59
|
if (this.#start > 0) {
|
|
36
60
|
this.#text = this.#text.slice(this.#start)
|
|
37
61
|
this.#at -= this.#start
|
|
38
62
|
this.#start = 0
|
|
39
63
|
}
|
|
40
|
-
this.#text +=
|
|
41
|
-
|
|
64
|
+
this.#text += this.#waiting.length === 1 ? this.#waiting[0]! : this.#waiting.join('')
|
|
65
|
+
this.#waiting = []
|
|
66
|
+
this.#waitingLength = 0
|
|
42
67
|
}
|
|
43
68
|
|
|
44
69
|
/** The statement left at the end, if any: the last one may have no semicolon. */
|
|
45
70
|
end(): string[] {
|
|
71
|
+
this.#take()
|
|
72
|
+
this.#hold = 0
|
|
46
73
|
const done = this.#read(true)
|
|
47
74
|
if (this.#state !== 'code' && this.#state !== 'line-comment') {
|
|
48
75
|
throw new Error(`The SQL ends inside ${UNFINISHED[this.#state]}.`)
|
|
@@ -188,7 +215,9 @@ export class StatementSplitter {
|
|
|
188
215
|
break
|
|
189
216
|
}
|
|
190
217
|
case 'line-comment': {
|
|
191
|
-
|
|
218
|
+
// At a line feed or a carriage return, whichever comes first, as the server ends it.
|
|
219
|
+
LINE_END.lastIndex = at
|
|
220
|
+
const end = LINE_END.exec(s)?.index ?? -1
|
|
192
221
|
if (end === -1) {
|
|
193
222
|
at = n
|
|
194
223
|
break read
|
|
@@ -231,6 +260,9 @@ export class StatementSplitter {
|
|
|
231
260
|
type State =
|
|
232
261
|
'code' | 'string' | 'escape-string' | 'name' | 'line-comment' | 'block-comment' | 'dollar'
|
|
233
262
|
|
|
263
|
+
const LINE_END = /[\n\r]/g
|
|
264
|
+
/** From this many characters on, an unfinished statement waits to double before it's read again. */
|
|
265
|
+
const LONG = 65_536
|
|
234
266
|
const SEMICOLON = 59
|
|
235
267
|
const QUOTE = 39
|
|
236
268
|
const DOUBLE_QUOTE = 34
|
package/src/backup/staging.ts
CHANGED
|
@@ -23,16 +23,51 @@ export interface Upload {
|
|
|
23
23
|
/** The pieces received, and their bytes. */
|
|
24
24
|
chunks: number
|
|
25
25
|
received: number
|
|
26
|
+
/** The last piece's number, -1 with none: one less than `chunks` when none is missing. */
|
|
27
|
+
last: number
|
|
26
28
|
}
|
|
27
29
|
|
|
28
30
|
const SCHEMA = quote(STAGING_SCHEMA)
|
|
29
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Whether the staging schema is there, refusing one this login didn't make. The schema is found
|
|
34
|
+
* by its name, and it's dropped after each restore, so any role that may create schemas could
|
|
35
|
+
* make it first: with tables of its own it would read the uploaded backup, change the pieces
|
|
36
|
+
* before they run as this login, or have a trigger on them run as this login. So the schema and
|
|
37
|
+
* everything in it must belong to the login that uses them.
|
|
38
|
+
*/
|
|
39
|
+
async function ours(session: Session): Promise<boolean> {
|
|
40
|
+
const { rows } = await session.query(
|
|
41
|
+
`SELECT pg_catalog.pg_get_userbyid(n.nspowner), current_user,
|
|
42
|
+
(SELECT pg_catalog.pg_get_userbyid(c.relowner) FROM pg_catalog.pg_class c
|
|
43
|
+
WHERE c.relnamespace = n.oid AND c.relowner <> n.nspowner LIMIT 1)
|
|
44
|
+
FROM pg_catalog.pg_namespace n WHERE n.nspname = $1`,
|
|
45
|
+
[STAGING_SCHEMA],
|
|
46
|
+
)
|
|
47
|
+
const found = rows[0]
|
|
48
|
+
if (!found) return false
|
|
49
|
+
const [owner, login, stranger] = found
|
|
50
|
+
const other = owner !== login ? owner : stranger
|
|
51
|
+
if (other !== null && other !== undefined) {
|
|
52
|
+
throw new DbAdminError(
|
|
53
|
+
owner !== login
|
|
54
|
+
? `The schema ${STAGING_SCHEMA}, where a restore’s upload waits, belongs to "${owner}", not to this connection’s login "${login}": someone else made it. Drop it (DROP SCHEMA ${STAGING_SCHEMA} CASCADE), then restore.`
|
|
55
|
+
: `The schema ${STAGING_SCHEMA}, where a restore’s upload waits, holds a table of "${stranger}", not of this connection’s login "${login}": someone else put it there. Drop the schema (DROP SCHEMA ${STAGING_SCHEMA} CASCADE), then restore.`,
|
|
56
|
+
409,
|
|
57
|
+
'staging-taken',
|
|
58
|
+
)
|
|
59
|
+
}
|
|
60
|
+
return true
|
|
61
|
+
}
|
|
62
|
+
|
|
30
63
|
/** Makes the tables if need be, drops uploads a day old, and starts one. */
|
|
31
64
|
export async function startUpload(
|
|
32
65
|
session: Session,
|
|
33
66
|
upload: { viewer: string; kind: UploadKind; size: number; name: string },
|
|
34
67
|
): Promise<string> {
|
|
35
68
|
await session.query(`CREATE SCHEMA IF NOT EXISTS ${SCHEMA}`)
|
|
69
|
+
// Before anything is put in it: one made by someone else is refused, not filled.
|
|
70
|
+
await ours(session)
|
|
36
71
|
await session.query(`CREATE TABLE IF NOT EXISTS ${SCHEMA}.uploads (
|
|
37
72
|
id uuid PRIMARY KEY, viewer text NOT NULL, kind text NOT NULL, size bigint NOT NULL,
|
|
38
73
|
name text NOT NULL, created timestamptz NOT NULL DEFAULT now())`)
|
|
@@ -53,12 +88,10 @@ export async function findUpload(session: Session, id: string, viewer: string):
|
|
|
53
88
|
const missing = () =>
|
|
54
89
|
new DbAdminError('That upload is gone: start the restore again.', 404, 'unknown-upload')
|
|
55
90
|
if (!UUID.test(id)) throw missing()
|
|
56
|
-
|
|
57
|
-
STAGING_SCHEMA,
|
|
58
|
-
])
|
|
59
|
-
if (!exists.rows.length) throw missing()
|
|
91
|
+
if (!(await ours(session))) throw missing()
|
|
60
92
|
const { rows } = await session.query(
|
|
61
|
-
`SELECT u.kind, u.size, count(c.seq), coalesce(sum(length(c.data)), 0)
|
|
93
|
+
`SELECT u.kind, u.size, count(c.seq), coalesce(sum(length(c.data)), 0),
|
|
94
|
+
coalesce(max(c.seq), -1)
|
|
62
95
|
FROM ${SCHEMA}.uploads u LEFT JOIN ${SCHEMA}.chunks c ON c.upload = u.id
|
|
63
96
|
WHERE u.id = $1 AND u.viewer = $2 GROUP BY u.id`,
|
|
64
97
|
[id, viewer],
|
|
@@ -71,6 +104,7 @@ export async function findUpload(session: Session, id: string, viewer: string):
|
|
|
71
104
|
size: Number(row[1]),
|
|
72
105
|
chunks: Number(row[2]),
|
|
73
106
|
received: Number(row[3]),
|
|
107
|
+
last: Number(row[4]),
|
|
74
108
|
}
|
|
75
109
|
}
|
|
76
110
|
|
|
@@ -99,7 +133,10 @@ export async function putChunk(
|
|
|
99
133
|
}
|
|
100
134
|
}
|
|
101
135
|
|
|
102
|
-
/**
|
|
136
|
+
/**
|
|
137
|
+
* Refuses an upload with pieces missing: bytes short, or a number skipped. The bytes alone can
|
|
138
|
+
* add up with a piece missing in the middle, when another was sent too long.
|
|
139
|
+
*/
|
|
103
140
|
export function complete(upload: Upload): void {
|
|
104
141
|
if (upload.received !== upload.size) {
|
|
105
142
|
throw new DbAdminError(
|
|
@@ -108,6 +145,13 @@ export function complete(upload: Upload): void {
|
|
|
108
145
|
'incomplete-upload',
|
|
109
146
|
)
|
|
110
147
|
}
|
|
148
|
+
if (upload.last + 1 !== upload.chunks) {
|
|
149
|
+
throw new DbAdminError(
|
|
150
|
+
`The upload has pieces missing: ${upload.chunks.toLocaleString('en')} arrived, the last of them number ${(upload.last + 1).toLocaleString('en')}. Start the restore again.`,
|
|
151
|
+
400,
|
|
152
|
+
'incomplete-upload',
|
|
153
|
+
)
|
|
154
|
+
}
|
|
111
155
|
}
|
|
112
156
|
|
|
113
157
|
/** The pieces in order, one at a time, so a big backup never sits in memory whole. */
|
|
@@ -128,10 +172,7 @@ export async function* chunks(session: Session, upload: Upload): AsyncGenerator<
|
|
|
128
172
|
|
|
129
173
|
/** Drops the upload, and the schema once nothing else waits in it. */
|
|
130
174
|
export async function discard(session: Session, id: string): Promise<void> {
|
|
131
|
-
|
|
132
|
-
STAGING_SCHEMA,
|
|
133
|
-
])
|
|
134
|
-
if (!exists.rows.length) return
|
|
175
|
+
if (!(await ours(session))) return
|
|
135
176
|
await session.query(
|
|
136
177
|
`DELETE FROM ${SCHEMA}.uploads WHERE id = $1 OR created < now() - interval '1 day'`,
|
|
137
178
|
[id],
|
package/src/drivers/mysql.ts
CHANGED
|
@@ -1,23 +1,40 @@
|
|
|
1
1
|
import type { Connection as CallbackConnection } from 'mysql2'
|
|
2
2
|
import type * as MySqlModule from 'mysql2/promise'
|
|
3
|
-
import type {
|
|
3
|
+
import type {
|
|
4
|
+
ConnectionOptions,
|
|
5
|
+
FieldPacket,
|
|
6
|
+
Pool,
|
|
7
|
+
PoolConnection,
|
|
8
|
+
PoolOptions,
|
|
9
|
+
} from 'mysql2/promise'
|
|
4
10
|
import { ConnectionError, DbAdminError, QueryError } from '../errors.ts'
|
|
11
|
+
import { refuseBeyondReadingMysql } from './read-only.ts'
|
|
5
12
|
import type {
|
|
6
13
|
ApplyResult,
|
|
7
14
|
Capabilities,
|
|
8
15
|
Change,
|
|
9
16
|
Column,
|
|
10
17
|
Driver,
|
|
18
|
+
ExportColumn,
|
|
11
19
|
QueryOptions,
|
|
12
20
|
QueryResult,
|
|
13
21
|
ResultSet,
|
|
14
22
|
RowsRequest,
|
|
15
23
|
ServerInfo,
|
|
24
|
+
SqlDialect,
|
|
16
25
|
TableDetail,
|
|
17
26
|
TableKind,
|
|
18
27
|
TableSummary,
|
|
19
28
|
} from '../types.ts'
|
|
20
|
-
import {
|
|
29
|
+
import {
|
|
30
|
+
changeStatement,
|
|
31
|
+
orderBy,
|
|
32
|
+
Parameters,
|
|
33
|
+
refuseChanged,
|
|
34
|
+
where,
|
|
35
|
+
whole,
|
|
36
|
+
type Dialect,
|
|
37
|
+
} from './sql.ts'
|
|
21
38
|
|
|
22
39
|
type MySql = typeof MySqlModule
|
|
23
40
|
|
|
@@ -65,11 +82,58 @@ function hexLiteral(value: string | null): string {
|
|
|
65
82
|
return value === '' ? "''" : `_utf8mb4 X'${Buffer.from(value, 'utf8').toString('hex')}'`
|
|
66
83
|
}
|
|
67
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Bytes as the grid shows them, `0x1F`, as the literal that is those bytes; null for anything
|
|
87
|
+
* else. A binary column compared with the letters "0x1F" matches nothing, and set to them holds
|
|
88
|
+
* those letters.
|
|
89
|
+
*/
|
|
90
|
+
export function mysqlBytes(shown: string): string | null {
|
|
91
|
+
const hex = /^0x((?:[0-9A-Fa-f]{2})*)$/.exec(shown)?.[1]
|
|
92
|
+
return hex === undefined ? null : `X'${hex.toUpperCase()}'`
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* How MySQL's SQL is written for people and for exports. An export's strings escape a backslash
|
|
97
|
+
* with another, which a session in NO_BACKSLASH_ESCAPES mode would read as two: the file takes
|
|
98
|
+
* that mode off for itself, and puts the session's back at its end.
|
|
99
|
+
*/
|
|
100
|
+
const sqlDialect: SqlDialect = {
|
|
101
|
+
identifier: backtick,
|
|
102
|
+
literal: mysqlLiteral,
|
|
103
|
+
bytes: mysqlBytes,
|
|
104
|
+
insertDefaults: '() VALUES ()',
|
|
105
|
+
exportHeader:
|
|
106
|
+
"SET @otw_db_sql_mode = @@sql_mode, sql_mode = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', @@sql_mode, ','), ',NO_BACKSLASH_ESCAPES,', ','));\n",
|
|
107
|
+
exportFooter: 'SET sql_mode = @otw_db_sql_mode;\n',
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The types whose values are bytes, as information_schema names them. */
|
|
111
|
+
const BYTE_TYPES = new Set([
|
|
112
|
+
'binary',
|
|
113
|
+
'varbinary',
|
|
114
|
+
'tinyblob',
|
|
115
|
+
'blob',
|
|
116
|
+
'mediumblob',
|
|
117
|
+
'longblob',
|
|
118
|
+
'bit',
|
|
119
|
+
'geometry',
|
|
120
|
+
'point',
|
|
121
|
+
'linestring',
|
|
122
|
+
'polygon',
|
|
123
|
+
'multipoint',
|
|
124
|
+
'multilinestring',
|
|
125
|
+
'multipolygon',
|
|
126
|
+
'geometrycollection',
|
|
127
|
+
'geomcollection',
|
|
128
|
+
])
|
|
129
|
+
|
|
68
130
|
const dialect: Dialect = {
|
|
69
131
|
identifier: backtick,
|
|
70
132
|
literal: mysqlLiteral,
|
|
71
133
|
placeholder: () => '?',
|
|
72
134
|
inline: hexLiteral,
|
|
135
|
+
bytes: mysqlBytes,
|
|
136
|
+
forUpdate: ' FOR UPDATE',
|
|
73
137
|
text: (expression) => `CAST(${expression} AS CHAR)`,
|
|
74
138
|
// LIKE follows the column's collation; the default ones ignore case.
|
|
75
139
|
ilike: 'LIKE',
|
|
@@ -85,6 +149,8 @@ const SYSTEM_SCHEMAS = "('mysql', 'information_schema', 'performance_schema', 's
|
|
|
85
149
|
const EXPORT_BATCH = 1_000
|
|
86
150
|
/** "Query execution was interrupted": KILL QUERY's answer. */
|
|
87
151
|
const INTERRUPTED = 1317
|
|
152
|
+
/** How long KILL QUERY gets to end a statement before its connection is closed under it. */
|
|
153
|
+
const KILL_GRACE_MS = 2_000
|
|
88
154
|
|
|
89
155
|
/** MySQL's column types by number, as the protocol sends them. */
|
|
90
156
|
const TYPES: Record<number, string> = {
|
|
@@ -133,24 +199,24 @@ export function mysqlDriver(url: string): Driver {
|
|
|
133
199
|
class MySqlDriver implements Driver {
|
|
134
200
|
readonly kind = 'mysql'
|
|
135
201
|
readonly capabilities: Capabilities = { schemas: true, transactionalDdl: false, cancel: true }
|
|
136
|
-
readonly sql =
|
|
202
|
+
readonly sql = sqlDialect
|
|
203
|
+
/** One connection's settings: the pool's, and the one that carries KILL QUERY. */
|
|
204
|
+
readonly #single: ConnectionOptions
|
|
137
205
|
readonly #config: PoolOptions
|
|
138
206
|
#pool: Promise<{ pool: Pool; mysql: MySql }> | undefined
|
|
139
207
|
|
|
140
208
|
constructor(url: string) {
|
|
141
209
|
// mysql2 reads mysql:// addresses; mariadb:// is the same thing.
|
|
142
210
|
const address = url.replace(/^mariadb:/i, 'mysql:')
|
|
143
|
-
this.#
|
|
211
|
+
this.#single = {
|
|
144
212
|
uri: address,
|
|
145
|
-
connectionLimit: 3,
|
|
146
|
-
maxIdle: 3,
|
|
147
|
-
idleTimeout: 10_000,
|
|
148
213
|
// One statement a query: `COMMIT; DROP …` is a syntax error.
|
|
149
214
|
multipleStatements: false,
|
|
150
215
|
// Rows matched, not rows changed: an update to the same value still counts its row.
|
|
151
216
|
flags: ['FOUND_ROWS', '-LOCAL_FILES'],
|
|
152
217
|
connectAttributes: { program_name: 'otw-db' },
|
|
153
218
|
}
|
|
219
|
+
this.#config = { ...this.#single, connectionLimit: 3, maxIdle: 3, idleTimeout: 10_000 }
|
|
154
220
|
}
|
|
155
221
|
|
|
156
222
|
#open(): Promise<{ pool: Pool; mysql: MySql }> {
|
|
@@ -184,17 +250,30 @@ class MySqlDriver implements Driver {
|
|
|
184
250
|
{ timeoutMs, signal }: { timeoutMs: number; signal?: AbortSignal },
|
|
185
251
|
): Promise<{ rows: (string | null)[][]; fields: FieldPacket[]; affected: number | null }> {
|
|
186
252
|
let stopped: 'timeout' | 'cancel' | null = null
|
|
253
|
+
let giveUp: NodeJS.Timeout | undefined
|
|
254
|
+
let abandon!: (error: Error) => void
|
|
255
|
+
const abandoned = new Promise<never>((_, reject) => (abandon = reject))
|
|
187
256
|
const stop = (why: 'timeout' | 'cancel') => {
|
|
188
257
|
if (stopped) return
|
|
189
258
|
stopped = why
|
|
190
259
|
void this.#kill(mysql, connection.threadId)
|
|
260
|
+
// KILL QUERY needs a connection of its own, which a server at its limit refuses, and some
|
|
261
|
+
// proxies never pass it on: the statement would run on, and the request wait with it.
|
|
262
|
+
// Closing its connection ends the wait whatever the server does.
|
|
263
|
+
giveUp = setTimeout(() => {
|
|
264
|
+
connection.destroy()
|
|
265
|
+
abandon(interrupted(why, timeoutMs))
|
|
266
|
+
}, KILL_GRACE_MS)
|
|
191
267
|
}
|
|
192
268
|
const timer = setTimeout(() => stop('timeout'), timeoutMs)
|
|
193
269
|
const abort = () => stop('cancel')
|
|
194
270
|
signal?.addEventListener('abort', abort, { once: true })
|
|
195
271
|
try {
|
|
196
272
|
if (signal?.aborted) throw new DbAdminError('The query was canceled.', 409, 'canceled')
|
|
197
|
-
const
|
|
273
|
+
const running = connection.query({ sql, rowsAsArray: true, typeCast: asBytes })
|
|
274
|
+
// Abandoned, it fails later with its connection gone: nobody is left to hear that.
|
|
275
|
+
running.catch(() => {})
|
|
276
|
+
const [result, fields] = await Promise.race([running, abandoned])
|
|
198
277
|
if (stopped) throw interrupted(stopped, timeoutMs)
|
|
199
278
|
if (!Array.isArray(result)) {
|
|
200
279
|
return { rows: [], fields: [], affected: (result as { affectedRows: number }).affectedRows }
|
|
@@ -210,6 +289,7 @@ class MySqlDriver implements Driver {
|
|
|
210
289
|
throw error
|
|
211
290
|
} finally {
|
|
212
291
|
clearTimeout(timer)
|
|
292
|
+
clearTimeout(giveUp)
|
|
213
293
|
signal?.removeEventListener('abort', abort)
|
|
214
294
|
}
|
|
215
295
|
}
|
|
@@ -217,7 +297,7 @@ class MySqlDriver implements Driver {
|
|
|
217
297
|
/** KILL QUERY on a connection of its own: the busy one can't take it. You may kill your own. */
|
|
218
298
|
async #kill(mysql: MySql, threadId: number): Promise<void> {
|
|
219
299
|
try {
|
|
220
|
-
const killer = await mysql.createConnection(this.#
|
|
300
|
+
const killer = await mysql.createConnection(this.#single)
|
|
221
301
|
try {
|
|
222
302
|
await killer.query(`KILL QUERY ${whole(threadId)}`)
|
|
223
303
|
} finally {
|
|
@@ -321,11 +401,39 @@ class MySqlDriver implements Driver {
|
|
|
321
401
|
}
|
|
322
402
|
}
|
|
323
403
|
|
|
404
|
+
/**
|
|
405
|
+
* What a statement must know of the table's columns that their values don't say: which hold
|
|
406
|
+
* bytes (shown as hex, and written back as bytes), and which the server computes itself.
|
|
407
|
+
*/
|
|
408
|
+
async #columns(schema: string, table: string): Promise<Map<string, ExportColumn>> {
|
|
409
|
+
const rows = await this.#catalog(
|
|
410
|
+
`SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_SET_NAME, EXTRA FROM information_schema.COLUMNS
|
|
411
|
+
WHERE TABLE_SCHEMA = ${hexLiteral(schema)} AND TABLE_NAME = ${hexLiteral(table)}`,
|
|
412
|
+
)
|
|
413
|
+
return new Map(
|
|
414
|
+
rows.map(([name, type, charset, extra]) => [
|
|
415
|
+
name!,
|
|
416
|
+
{
|
|
417
|
+
name: name!,
|
|
418
|
+
...(BYTE_TYPES.has(type!.toLowerCase()) || charset === 'binary' ? { bytes: true } : {}),
|
|
419
|
+
...(/\bGENERATED\b/i.test(extra ?? '') ? { generated: true } : {}),
|
|
420
|
+
},
|
|
421
|
+
]),
|
|
422
|
+
)
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** The table's columns that hold bytes; not looked up where nothing is compared with a column. */
|
|
426
|
+
async #bytes(schema: string, table: string, needed = true): Promise<ReadonlySet<string>> {
|
|
427
|
+
if (!needed) return new Set()
|
|
428
|
+
const columns = await this.#columns(schema, table)
|
|
429
|
+
return new Set([...columns.values()].filter((c) => c.bytes).map((c) => c.name))
|
|
430
|
+
}
|
|
431
|
+
|
|
324
432
|
async rows(
|
|
325
433
|
{ schema, table, limit, offset, order = [], filters = [] }: RowsRequest,
|
|
326
434
|
options: Omit<QueryOptions, 'access' | 'maxRows'>,
|
|
327
435
|
): Promise<ResultSet> {
|
|
328
|
-
const parameters = new Parameters(dialect)
|
|
436
|
+
const parameters = new Parameters(dialect, await this.#bytes(schema, table, filters.length > 0))
|
|
329
437
|
const sql = `SELECT * FROM ${backtick(schema)}.${backtick(table)}${where(dialect, filters, parameters)}${orderBy(dialect, order)} LIMIT ${whole(limit) + 1} OFFSET ${whole(offset)}`
|
|
330
438
|
const started = performance.now()
|
|
331
439
|
const { rows, fields } = await this.#pooled(sql, options)
|
|
@@ -342,7 +450,7 @@ class MySqlDriver implements Driver {
|
|
|
342
450
|
{ schema, table, filters = [] }: Pick<RowsRequest, 'schema' | 'table' | 'filters'>,
|
|
343
451
|
options: Omit<QueryOptions, 'access' | 'maxRows'>,
|
|
344
452
|
): Promise<number> {
|
|
345
|
-
const parameters = new Parameters(dialect)
|
|
453
|
+
const parameters = new Parameters(dialect, await this.#bytes(schema, table, filters.length > 0))
|
|
346
454
|
const sql = `SELECT COUNT(*) FROM ${backtick(schema)}.${backtick(table)}${where(dialect, filters, parameters)}`
|
|
347
455
|
return Number((await this.#pooled(sql, options)).rows[0]![0])
|
|
348
456
|
}
|
|
@@ -354,7 +462,14 @@ class MySqlDriver implements Driver {
|
|
|
354
462
|
try {
|
|
355
463
|
return await this.#run(connection, mysql, sql, options)
|
|
356
464
|
} catch (error) {
|
|
357
|
-
|
|
465
|
+
// A statement stopped at its limit or by its viewer: its KILL QUERY may still be on the
|
|
466
|
+
// way, and would stop whatever ran next on this connection. So the connection goes.
|
|
467
|
+
const stoppedHere =
|
|
468
|
+
error instanceof DbAdminError &&
|
|
469
|
+
(error.code === 'canceled' || (error as QueryError).sqlState === '70100')
|
|
470
|
+
broken =
|
|
471
|
+
stoppedHere ||
|
|
472
|
+
(!(error instanceof DbAdminError) && !(error as { sqlMessage?: string }).sqlMessage)
|
|
358
473
|
throw toError(error)
|
|
359
474
|
} finally {
|
|
360
475
|
if (broken) connection.destroy()
|
|
@@ -381,6 +496,7 @@ class MySqlDriver implements Driver {
|
|
|
381
496
|
* refused too; and caps what a SELECT returns at the row limit, plus one to tell it was cut.
|
|
382
497
|
*/
|
|
383
498
|
async query(sql: string, options: QueryOptions): Promise<QueryResult> {
|
|
499
|
+
if (options.access === 'read') refuseBeyondReadingMysql(sql)
|
|
384
500
|
const { connection, mysql } = await this.#connect()
|
|
385
501
|
const started = performance.now()
|
|
386
502
|
try {
|
|
@@ -409,13 +525,19 @@ class MySqlDriver implements Driver {
|
|
|
409
525
|
{ timeoutMs, dryRun = false }: { timeoutMs: number; dryRun?: boolean },
|
|
410
526
|
): Promise<ApplyResult> {
|
|
411
527
|
const target = `${backtick(schema)}.${backtick(table)}`
|
|
412
|
-
const
|
|
528
|
+
const bytes = await this.#bytes(schema, table)
|
|
529
|
+
const statements = changes.map((change) => changeStatement(dialect, target, change, bytes))
|
|
413
530
|
const shown = statements.map((s) => s.shown)
|
|
414
531
|
if (dryRun) return { statements: shown, applied: false }
|
|
415
532
|
const { connection, mysql } = await this.#connect()
|
|
416
533
|
try {
|
|
417
534
|
await connection.query('START TRANSACTION')
|
|
418
535
|
for (const statement of statements) {
|
|
536
|
+
if (statement.check) {
|
|
537
|
+
// Through #run, so each value reads as the grid read it.
|
|
538
|
+
const { rows } = await this.#run(connection, mysql, statement.check.text, { timeoutMs })
|
|
539
|
+
refuseChanged(dialect, statement, rows[0])
|
|
540
|
+
}
|
|
419
541
|
const { affected } = await this.#run(connection, mysql, statement.text, { timeoutMs })
|
|
420
542
|
if (statement.oneRow && affected !== 1) {
|
|
421
543
|
const why =
|
|
@@ -443,14 +565,36 @@ class MySqlDriver implements Driver {
|
|
|
443
565
|
order = [],
|
|
444
566
|
}: Pick<RowsRequest, 'schema' | 'table' | 'filters' | 'order'>,
|
|
445
567
|
{ timeoutMs }: { timeoutMs: number },
|
|
446
|
-
): AsyncGenerator<{ columns:
|
|
447
|
-
const
|
|
568
|
+
): AsyncGenerator<{ columns: ExportColumn[]; rows: (string | null)[][] }> {
|
|
569
|
+
const known = await this.#columns(schema, table)
|
|
570
|
+
const bytes = new Set([...known.values()].filter((c) => c.bytes).map((c) => c.name))
|
|
571
|
+
const parameters = new Parameters(dialect, bytes)
|
|
448
572
|
const sql = `SELECT * FROM ${backtick(schema)}.${backtick(table)}${where(dialect, filters, parameters)}${orderBy(dialect, order)}`
|
|
449
|
-
const
|
|
573
|
+
const columns = (fields: FieldPacket[]) =>
|
|
574
|
+
fields.map((f) => known.get(f.name) ?? { name: f.name })
|
|
575
|
+
const { connection, mysql } = await this.#connect()
|
|
450
576
|
// Rows come as the server sends them; a stop on the way leaves the connection mid-result.
|
|
451
577
|
let finished = false
|
|
578
|
+
// The time limit is on the server saying nothing: a statement that sends no row for that long
|
|
579
|
+
// is stopped, while a big table that keeps coming may take as long as it takes. It's kept
|
|
580
|
+
// here, not set on the session (max_execution_time would stay on a connection the pool hands
|
|
581
|
+
// to the next statement, and MariaDB has no such setting), and it rests while the reader has
|
|
582
|
+
// a batch in hand: that wait is the reader's.
|
|
583
|
+
let heard = performance.now()
|
|
584
|
+
let listening = true
|
|
585
|
+
let silent = false
|
|
586
|
+
const watch = setInterval(
|
|
587
|
+
() => {
|
|
588
|
+
if (!listening || silent || performance.now() - heard <= timeoutMs) return
|
|
589
|
+
silent = true
|
|
590
|
+
void this.#kill(mysql, connection.threadId)
|
|
591
|
+
// Where KILL QUERY can't reach it, its connection goes instead.
|
|
592
|
+
setTimeout(() => connection.destroy(), KILL_GRACE_MS).unref()
|
|
593
|
+
},
|
|
594
|
+
Math.max(20, Math.min(1_000, timeoutMs / 4)),
|
|
595
|
+
)
|
|
596
|
+
watch.unref()
|
|
452
597
|
try {
|
|
453
|
-
await connection.query(`SET SESSION max_execution_time = ${whole(timeoutMs)}`).catch(() => {})
|
|
454
598
|
// The callback connection underneath streams; the promise one doesn't.
|
|
455
599
|
const stream = (connection.connection as unknown as CallbackConnection)
|
|
456
600
|
.query({ sql, rowsAsArray: true, typeCast: asBytes })
|
|
@@ -460,19 +604,25 @@ class MySqlDriver implements Driver {
|
|
|
460
604
|
let batch: (string | null)[][] = []
|
|
461
605
|
let first = true
|
|
462
606
|
for await (const row of stream as AsyncIterable<unknown[]>) {
|
|
607
|
+
heard = performance.now()
|
|
463
608
|
batch.push(toText(row, fields))
|
|
464
609
|
if (batch.length === EXPORT_BATCH) {
|
|
465
|
-
|
|
610
|
+
listening = false
|
|
611
|
+
yield { columns: columns(fields), rows: batch }
|
|
612
|
+
heard = performance.now()
|
|
613
|
+
listening = true
|
|
466
614
|
batch = []
|
|
467
615
|
first = false
|
|
468
616
|
}
|
|
469
617
|
}
|
|
470
|
-
|
|
471
|
-
|
|
618
|
+
listening = false
|
|
619
|
+
if (silent) throw interrupted('timeout', timeoutMs)
|
|
620
|
+
if (batch.length || first) yield { columns: columns(fields), rows: batch }
|
|
472
621
|
finished = true
|
|
473
622
|
} catch (error) {
|
|
474
|
-
throw toError(error)
|
|
623
|
+
throw silent ? interrupted('timeout', timeoutMs) : toError(error)
|
|
475
624
|
} finally {
|
|
625
|
+
clearInterval(watch)
|
|
476
626
|
if (finished) connection.release()
|
|
477
627
|
else connection.destroy()
|
|
478
628
|
}
|