@otwdesign/db-core 1.3.2 → 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
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { DbAdminError } from '../errors.ts'
|
|
2
|
+
import { leadingWord } from '../words.ts'
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* What read access runs of someone's own SQL. A read-only transaction keeps a statement from
|
|
6
|
+
* changing rows; the server's files, its programs, its settings and its other connections aren't
|
|
7
|
+
* rows, and a login that may touch them (a superuser, root, and PGlite, which has no other kind)
|
|
8
|
+
* still can through a connection marked read-only: COPY … TO PROGRAM runs a command on the
|
|
9
|
+
* database's server.
|
|
10
|
+
*
|
|
11
|
+
* So read access takes the statements that read, by their first word, and no others: what isn't
|
|
12
|
+
* on the list isn't run, however it's written. Within a statement that reads, a function can
|
|
13
|
+
* still reach past the database, and no list has every function: the ones that are known are
|
|
14
|
+
* refused by name, wherever the name appears, in a string or a comment too, since a function
|
|
15
|
+
* that runs SQL it's given could be handed the name in pieces. That refuses a statement that
|
|
16
|
+
* only mentions one, which read access can live with. It's a guard, not a wall: a function the
|
|
17
|
+
* database's owner wrote can do anything. A read-only connection is safe with a login that may
|
|
18
|
+
* only read.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
function refuse(what: string): never {
|
|
22
|
+
throw new DbAdminError(`This connection is read-only: ${what}`, 403, 'not-allowed')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const READS = 'Read access runs SELECT, WITH, VALUES, TABLE, SHOW and EXPLAIN'
|
|
26
|
+
|
|
27
|
+
/** The statements that read, on PostgreSQL. */
|
|
28
|
+
const POSTGRES_READS = new Set(['SELECT', 'WITH', 'VALUES', 'TABLE', 'SHOW', 'EXPLAIN'])
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* PostgreSQL's functions that read or write the server's files, act on the server or on its
|
|
32
|
+
* other connections, open another connection, hold a lock for the session, or run SQL they're
|
|
33
|
+
* given as text (through which any of the others could be named in pieces).
|
|
34
|
+
*/
|
|
35
|
+
const POSTGRES_NAMES = new RegExp(
|
|
36
|
+
`\\b(${[
|
|
37
|
+
// The server's files, read or written.
|
|
38
|
+
'lo_export',
|
|
39
|
+
'lo_import',
|
|
40
|
+
'pg_read_\\w*file\\w*',
|
|
41
|
+
'pg_ls_[a-z_]*dir\\w*',
|
|
42
|
+
'pg_stat_file',
|
|
43
|
+
'pg_file_\\w+',
|
|
44
|
+
'pg_hba_file_rules',
|
|
45
|
+
'pg_ident_file_mappings',
|
|
46
|
+
'pg_show_all_file_settings',
|
|
47
|
+
'pg_current_logfile',
|
|
48
|
+
// The server itself, and its other connections.
|
|
49
|
+
'pg_terminate_backend',
|
|
50
|
+
'pg_cancel_backend',
|
|
51
|
+
'pg_log_backend_memory_contexts',
|
|
52
|
+
'pg_log_standby_snapshot',
|
|
53
|
+
'pg_reload_conf',
|
|
54
|
+
'pg_rotate_logfile\\w*',
|
|
55
|
+
'pg_switch_wal',
|
|
56
|
+
'pg_promote',
|
|
57
|
+
'pg_create_restore_point',
|
|
58
|
+
'pg_backup_\\w+',
|
|
59
|
+
'pg_start_backup',
|
|
60
|
+
'pg_stop_backup',
|
|
61
|
+
'pg_wal_replay_\\w+',
|
|
62
|
+
'pg_stat_\\w*reset\\w*',
|
|
63
|
+
'pg_create_\\w*replication_slot',
|
|
64
|
+
'pg_copy_\\w*replication_slot',
|
|
65
|
+
'pg_drop_replication_slot',
|
|
66
|
+
'pg_replication_slot_advance',
|
|
67
|
+
'pg_sync_replication_slots',
|
|
68
|
+
'pg_replication_origin_(?:create|drop|advance|session_setup|session_reset|xact_setup|xact_reset)',
|
|
69
|
+
'pg_logical_\\w+',
|
|
70
|
+
// The session, which the next query on this connection shares.
|
|
71
|
+
'pg_advisory_\\w+',
|
|
72
|
+
'pg_try_advisory_\\w+',
|
|
73
|
+
'set_config',
|
|
74
|
+
'setseed',
|
|
75
|
+
// Another connection, or SQL given as text, through which any of the above could be named
|
|
76
|
+
// in pieces: built in, and from the extensions most often installed.
|
|
77
|
+
'dblink\\w*',
|
|
78
|
+
'query_to_xml\\w*',
|
|
79
|
+
'cursor_to_xml\\w*',
|
|
80
|
+
'ts_stat',
|
|
81
|
+
'ts_rewrite',
|
|
82
|
+
'crosstab\\w*',
|
|
83
|
+
'connectby',
|
|
84
|
+
'xpath_table',
|
|
85
|
+
].join('|')})\\b`,
|
|
86
|
+
'i',
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
/** PostgreSQL, and PGlite, which is one. */
|
|
90
|
+
export function refuseBeyondReadingPostgres(sql: string): void {
|
|
91
|
+
const word = leadingWord(sql)
|
|
92
|
+
if (!POSTGRES_READS.has(word)) {
|
|
93
|
+
refuse(
|
|
94
|
+
word
|
|
95
|
+
? `${READS}, not ${word}. COPY, DO and LOAD among the others reach the server itself, which no transaction holds back.`
|
|
96
|
+
: `${READS}.`,
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
const name = POSTGRES_NAMES.exec(sql)?.[1]
|
|
100
|
+
if (name) {
|
|
101
|
+
refuse(
|
|
102
|
+
`${name.toLowerCase()} reaches past the database’s rows: to the server’s files, the server itself, its other connections, or SQL of its own. A statement that only mentions it is refused as well.`,
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
// A name spelled in escapes is a name this can't read.
|
|
106
|
+
if (/(?<![A-Za-z0-9_$])U&\s*["']/i.test(sql)) {
|
|
107
|
+
refuse('names and strings written with U& escapes aren’t taken here.')
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The statements that read, on MySQL and MariaDB. */
|
|
112
|
+
const MYSQL_READS = new Set([
|
|
113
|
+
'SELECT',
|
|
114
|
+
'WITH',
|
|
115
|
+
'VALUES',
|
|
116
|
+
'TABLE',
|
|
117
|
+
'SHOW',
|
|
118
|
+
'EXPLAIN',
|
|
119
|
+
'DESCRIBE',
|
|
120
|
+
'DESC',
|
|
121
|
+
])
|
|
122
|
+
|
|
123
|
+
const MYSQL_NAMES =
|
|
124
|
+
/\b(asynchronous_connection_failover_\w+|group_replication_\w+|innodb_set_open_files_limit|innodb_redo_log_\w+|sys_exec|sys_eval)\b/i
|
|
125
|
+
|
|
126
|
+
/** MySQL and MariaDB. */
|
|
127
|
+
export function refuseBeyondReadingMysql(sql: string): void {
|
|
128
|
+
// What's inside /*! … */ and /*M! … */ runs as SQL: a statement within a comment.
|
|
129
|
+
if (/\/\*M?!/.test(sql)) refuse('comments that run as SQL (/*! … */) aren’t taken here.')
|
|
130
|
+
const word = mysqlFirstWord(sql)
|
|
131
|
+
if (!MYSQL_READS.has(word)) {
|
|
132
|
+
refuse(
|
|
133
|
+
word
|
|
134
|
+
? `${READS} (DESCRIBE too), not ${word}. KILL, SET GLOBAL and FLUSH among the others act on the server itself, which no transaction holds back.`
|
|
135
|
+
: `${READS}.`,
|
|
136
|
+
)
|
|
137
|
+
}
|
|
138
|
+
// Keywords and a function no SELECT can spell any other way: refused wherever they appear.
|
|
139
|
+
const beyond = /\b(OUTFILE|DUMPFILE|LOAD_FILE)\b/i.exec(sql)?.[1]
|
|
140
|
+
if (beyond) {
|
|
141
|
+
refuse(
|
|
142
|
+
`${beyond.toUpperCase()} reads or writes a file on the database’s server. A statement that only mentions it is refused as well.`,
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
// Functions that change the server, which a SELECT may call and no transaction undoes.
|
|
146
|
+
const acts = MYSQL_NAMES.exec(sql)?.[1]
|
|
147
|
+
if (acts) {
|
|
148
|
+
refuse(
|
|
149
|
+
`${acts.toLowerCase()} changes the server itself. A statement that only mentions it is refused as well.`,
|
|
150
|
+
)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The first word past spaces, comments (-- , # and blocks) and brackets, in capitals. */
|
|
155
|
+
function mysqlFirstWord(text: string): string {
|
|
156
|
+
let at = 0
|
|
157
|
+
for (;;) {
|
|
158
|
+
while (/[\s(;]/.test(text[at] ?? '')) at += 1
|
|
159
|
+
// `--` starts a comment before a space, a control character, or the end: MySQL's own rule.
|
|
160
|
+
if (
|
|
161
|
+
text.startsWith('#', at) ||
|
|
162
|
+
(text.startsWith('--', at) && !(text.charCodeAt(at + 2) > 32))
|
|
163
|
+
) {
|
|
164
|
+
const end = text.indexOf('\n', at)
|
|
165
|
+
if (end === -1) return ''
|
|
166
|
+
at = end + 1
|
|
167
|
+
} else if (text.startsWith('/*', at)) {
|
|
168
|
+
const end = text.indexOf('*/', at + 2)
|
|
169
|
+
if (end === -1) return ''
|
|
170
|
+
at = end + 2
|
|
171
|
+
} else break
|
|
172
|
+
}
|
|
173
|
+
return (/^[A-Za-z_]+/.exec(text.slice(at, at + 64))?.[0] ?? '').toUpperCase()
|
|
174
|
+
}
|
package/src/drivers/sql.ts
CHANGED
|
@@ -33,13 +33,58 @@ export interface Dialect {
|
|
|
33
33
|
): string
|
|
34
34
|
/** An insert of nothing but defaults: `DEFAULT VALUES`, or MySQL's `() VALUES ()`. */
|
|
35
35
|
insertDefaults: string
|
|
36
|
+
/**
|
|
37
|
+
* Bytes as the grid shows them, as a literal that is those bytes; null when the text isn't in
|
|
38
|
+
* that form. Absent where the shown form is text the database reads as bytes itself.
|
|
39
|
+
*/
|
|
40
|
+
bytes?(shown: string): string | null
|
|
41
|
+
/**
|
|
42
|
+
* What ends a SELECT that holds its rows until the transaction ends: ` FOR UPDATE`, or nothing
|
|
43
|
+
* where a write transaction already holds the whole database (SQLite).
|
|
44
|
+
*/
|
|
45
|
+
forUpdate: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** How long an export may wait between two batches for its reader, unless a driver is told otherwise. */
|
|
49
|
+
export const EXPORT_IDLE_MS = 300_000
|
|
50
|
+
|
|
51
|
+
/** Milliseconds as people read them: `10 s`, `0.3 s`. */
|
|
52
|
+
export function seconds(ms: number): string {
|
|
53
|
+
return `${(ms / 1000).toLocaleString('en', { maximumFractionDigits: 1 })} s`
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* What an export says when it's ended because nobody read it. A browser that stays away mid-file
|
|
58
|
+
* would otherwise hold what the export holds (a connection, a cursor's rows, a lock on the file)
|
|
59
|
+
* for as long as it stays away.
|
|
60
|
+
*/
|
|
61
|
+
export function stalledExport(idleMs: number): DbAdminError {
|
|
62
|
+
return new DbAdminError(
|
|
63
|
+
`The export waited ${seconds(idleMs)} for its rows to be read, and was stopped so its connection is free for others.`,
|
|
64
|
+
408,
|
|
65
|
+
'export-stalled',
|
|
66
|
+
)
|
|
36
67
|
}
|
|
37
68
|
|
|
38
|
-
/**
|
|
69
|
+
/** No column holds bytes, or the database reads their shown form itself. */
|
|
70
|
+
const NO_BYTES: ReadonlySet<string> = new Set()
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Parameters as a builder adds them, with their placeholders. `bytes` names the columns that hold
|
|
74
|
+
* bytes: a value for one of them, in the form the grid shows bytes in, goes into the SQL as the
|
|
75
|
+
* bytes it stands for, not as those letters.
|
|
76
|
+
*/
|
|
39
77
|
export class Parameters {
|
|
40
78
|
readonly values: unknown[] = []
|
|
41
|
-
constructor(
|
|
42
|
-
|
|
79
|
+
constructor(
|
|
80
|
+
private readonly dialect: Dialect,
|
|
81
|
+
private readonly bytes: ReadonlySet<string> = NO_BYTES,
|
|
82
|
+
) {}
|
|
83
|
+
add = (value: unknown, column?: string): string => {
|
|
84
|
+
if (column !== undefined && typeof value === 'string' && this.bytes.has(column)) {
|
|
85
|
+
const literal = this.dialect.bytes?.(value)
|
|
86
|
+
if (literal != null) return literal
|
|
87
|
+
}
|
|
43
88
|
if (this.dialect.inline) return this.dialect.inline(value as string | null)
|
|
44
89
|
this.values.push(value)
|
|
45
90
|
return this.dialect.placeholder(this.values.length)
|
|
@@ -66,21 +111,23 @@ export function where(
|
|
|
66
111
|
): string {
|
|
67
112
|
const conditions = filters.map(({ column, operator, value }) => {
|
|
68
113
|
const name = dialect.identifier(column)
|
|
69
|
-
|
|
114
|
+
// Compared with the column itself, so as the column's kind: bytes where it holds bytes.
|
|
115
|
+
const add = (compared: unknown) => parameters.add(compared, column)
|
|
116
|
+
if (COMPARISONS.has(operator)) return `${name} ${operator} ${add(value)}`
|
|
70
117
|
switch (operator) {
|
|
71
118
|
case 'is null':
|
|
72
119
|
return `${name} IS NULL`
|
|
73
120
|
case 'is not null':
|
|
74
121
|
return `${name} IS NOT NULL`
|
|
75
122
|
case 'in':
|
|
76
|
-
return dialect.inList(name, value as readonly string[],
|
|
123
|
+
return dialect.inList(name, value as readonly string[], add)
|
|
77
124
|
case 'not in':
|
|
78
|
-
return `NOT (${dialect.inList(name, value as readonly string[],
|
|
125
|
+
return `NOT (${dialect.inList(name, value as readonly string[], add)})`
|
|
79
126
|
case 'between':
|
|
80
127
|
case 'not between': {
|
|
81
128
|
const [low, high] = value as readonly string[]
|
|
82
129
|
const not = operator === 'not between' ? 'NOT ' : ''
|
|
83
|
-
return `${name} ${not}BETWEEN ${
|
|
130
|
+
return `${name} ${not}BETWEEN ${add(low)} AND ${add(high)}`
|
|
84
131
|
}
|
|
85
132
|
case 'like':
|
|
86
133
|
return `${dialect.text(name)} LIKE ${parameters.add(value)}`
|
|
@@ -120,48 +167,134 @@ export interface ChangeStatement {
|
|
|
120
167
|
shown: string
|
|
121
168
|
/** Updates and deletes must change exactly one row. */
|
|
122
169
|
oneRow: boolean
|
|
170
|
+
/**
|
|
171
|
+
* For an update that says what its cells held when they were edited: the SELECT that reads
|
|
172
|
+
* them now and holds the row until the transaction ends, and what they held, in its order.
|
|
173
|
+
*/
|
|
174
|
+
check?: {
|
|
175
|
+
text: string
|
|
176
|
+
values: (string | null)[]
|
|
177
|
+
columns: string[]
|
|
178
|
+
original: (string | null)[]
|
|
179
|
+
}
|
|
123
180
|
}
|
|
124
181
|
|
|
125
|
-
|
|
182
|
+
/**
|
|
183
|
+
* SQL with its values: `build` writes the text, calling `value` where each one goes. They become
|
|
184
|
+
* parameters to run, or go into the text where the driver sends none, and literals to show.
|
|
185
|
+
*/
|
|
186
|
+
function written(
|
|
187
|
+
dialect: Dialect,
|
|
188
|
+
bytes: ReadonlySet<string>,
|
|
189
|
+
build: (value: (column: string, value: string | null) => string) => string,
|
|
190
|
+
): { text: string; values: (string | null)[]; shown: string } {
|
|
126
191
|
const values: (string | null)[] = []
|
|
127
|
-
const
|
|
128
|
-
const runValues: string[] = []
|
|
192
|
+
const slots: { run: string; shown: string }[] = []
|
|
129
193
|
// Placeholders are numbered here and swapped afterwards: `?` alone can't be told apart.
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
194
|
+
const text = build((column, value) => {
|
|
195
|
+
const literal = value !== null && bytes.has(column) ? (dialect.bytes?.(value) ?? null) : null
|
|
196
|
+
if (literal !== null) slots.push({ run: literal, shown: literal })
|
|
197
|
+
else if (dialect.inline) {
|
|
198
|
+
slots.push({ run: dialect.inline(value), shown: dialect.literal(value) })
|
|
199
|
+
} else {
|
|
200
|
+
values.push(value)
|
|
201
|
+
slots.push({ run: dialect.placeholder(values.length), shown: dialect.literal(value) })
|
|
202
|
+
}
|
|
203
|
+
return `\uE000${slots.length}\uE000`
|
|
204
|
+
})
|
|
205
|
+
// A private-use character: no SQL a driver builds contains one.
|
|
206
|
+
const mark = /\uE000(\d+)\uE000/g
|
|
207
|
+
return {
|
|
208
|
+
text: text.replace(mark, (_, n: string) => slots[Number(n) - 1]!.run),
|
|
209
|
+
values,
|
|
210
|
+
shown: text.replace(mark, (_, n: string) => slots[Number(n) - 1]!.shown),
|
|
135
211
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* A change as the statement that makes it. `bytes` names the table's columns that hold bytes,
|
|
216
|
+
* where the database doesn't read their shown form itself.
|
|
217
|
+
*/
|
|
218
|
+
export function changeStatement(
|
|
219
|
+
dialect: Dialect,
|
|
220
|
+
target: string,
|
|
221
|
+
change: Change,
|
|
222
|
+
bytes: ReadonlySet<string> = NO_BYTES,
|
|
223
|
+
): ChangeStatement {
|
|
141
224
|
if (change.type === 'insert') {
|
|
142
225
|
const columns = Object.keys(change.values)
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const key = assignments(change.key).join(' AND ')
|
|
150
|
-
text =
|
|
151
|
-
change.type === 'update'
|
|
152
|
-
? `UPDATE ${target} SET ${set} WHERE ${key}`
|
|
153
|
-
: `DELETE FROM ${target} WHERE ${key}`
|
|
226
|
+
const statement = written(dialect, bytes, (value) =>
|
|
227
|
+
columns.length
|
|
228
|
+
? `INSERT INTO ${target} (${columns.map(dialect.identifier).join(', ')}) VALUES (${columns.map((c) => value(c, change.values[c]!)).join(', ')})`
|
|
229
|
+
: `INSERT INTO ${target} ${dialect.insertDefaults}`,
|
|
230
|
+
)
|
|
231
|
+
return { ...statement, oneRow: false }
|
|
154
232
|
}
|
|
155
|
-
|
|
156
|
-
|
|
233
|
+
const assignments =
|
|
234
|
+
(value: (column: string, value: string | null) => string) =>
|
|
235
|
+
(record: Readonly<Record<string, string | null>>) =>
|
|
236
|
+
Object.entries(record).map(
|
|
237
|
+
([column, v]) => `${dialect.identifier(column)} = ${value(column, v)}`,
|
|
238
|
+
)
|
|
239
|
+
// SET before WHERE, in the order the SQL has them: `?` placeholders bind by position.
|
|
240
|
+
const statement = written(dialect, bytes, (value) => {
|
|
241
|
+
const set = change.type === 'update' ? assignments(value)(change.values).join(', ') : ''
|
|
242
|
+
const key = assignments(value)(change.key).join(' AND ')
|
|
243
|
+
return change.type === 'update'
|
|
244
|
+
? `UPDATE ${target} SET ${set} WHERE ${key}`
|
|
245
|
+
: `DELETE FROM ${target} WHERE ${key}`
|
|
246
|
+
})
|
|
247
|
+
const original = change.type === 'update' ? change.original : undefined
|
|
248
|
+
if (!original || !Object.keys(original).length) return { ...statement, oneRow: true }
|
|
249
|
+
const columns = Object.keys(original)
|
|
250
|
+
const { text, values } = written(
|
|
251
|
+
dialect,
|
|
252
|
+
bytes,
|
|
253
|
+
(value) =>
|
|
254
|
+
`SELECT ${columns.map(dialect.identifier).join(', ')} FROM ${target} WHERE ${assignments(value)(change.key).join(' AND ')}${dialect.forUpdate}`,
|
|
255
|
+
)
|
|
157
256
|
return {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
oneRow: change.type !== 'insert',
|
|
257
|
+
...statement,
|
|
258
|
+
oneRow: true,
|
|
259
|
+
check: { text, values, columns, original: columns.map((c) => original[c] ?? null) },
|
|
162
260
|
}
|
|
163
261
|
}
|
|
164
262
|
|
|
263
|
+
/**
|
|
264
|
+
* Refuses an update whose cells no longer hold what they did when the person edited them.
|
|
265
|
+
* `current` is the row the statement's check read, as the grid would show it, or nothing when the
|
|
266
|
+
* row is gone. The check reads inside the update's transaction and holds the row, so what it sees
|
|
267
|
+
* is what the update would overwrite.
|
|
268
|
+
*/
|
|
269
|
+
export function refuseChanged(
|
|
270
|
+
dialect: Dialect,
|
|
271
|
+
statement: ChangeStatement,
|
|
272
|
+
current: readonly (string | null)[] | undefined,
|
|
273
|
+
): void {
|
|
274
|
+
const check = statement.check
|
|
275
|
+
if (!check) return
|
|
276
|
+
if (!current) {
|
|
277
|
+
throw new DbAdminError(
|
|
278
|
+
`Nothing was saved: its row is gone or its key changed.\n${statement.shown}`,
|
|
279
|
+
409,
|
|
280
|
+
'conflict',
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
const show = (value: string | null) => {
|
|
284
|
+
const literal = dialect.literal(value)
|
|
285
|
+
return literal.length > 200 ? `${literal.slice(0, 200)}…` : literal
|
|
286
|
+
}
|
|
287
|
+
check.columns.forEach((column, i) => {
|
|
288
|
+
const now = current[i] ?? null
|
|
289
|
+
if (now === check.original[i]) return
|
|
290
|
+
throw new DbAdminError(
|
|
291
|
+
`Nothing was saved: ${column} was changed by someone else meanwhile, from ${show(check.original[i]!)} to ${show(now)}.\n${statement.shown}`,
|
|
292
|
+
409,
|
|
293
|
+
'conflict',
|
|
294
|
+
)
|
|
295
|
+
})
|
|
296
|
+
}
|
|
297
|
+
|
|
165
298
|
/** A whole number for SQL text, which only ever takes numbers checked here. */
|
|
166
299
|
export function whole(value: number): number {
|
|
167
300
|
if (!Number.isSafeInteger(value) || value < 0) {
|