@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
package/dist/types.d.ts
CHANGED
|
@@ -150,6 +150,12 @@ export type Change = {
|
|
|
150
150
|
type: 'update';
|
|
151
151
|
key: Readonly<Record<string, string>>;
|
|
152
152
|
values: Readonly<Record<string, string | null>>;
|
|
153
|
+
/**
|
|
154
|
+
* What the edited cells held when the person edited them, as the grid showed them. With
|
|
155
|
+
* it, nothing is saved if one holds something else by now: someone changed it meanwhile.
|
|
156
|
+
* Without it, the update goes by the key alone, and the last to save wins.
|
|
157
|
+
*/
|
|
158
|
+
original?: Readonly<Record<string, string | null>>;
|
|
153
159
|
} | {
|
|
154
160
|
type: 'delete';
|
|
155
161
|
key: Readonly<Record<string, string>>;
|
|
@@ -167,6 +173,30 @@ export type ExportFormat = 'csv' | 'json' | 'sql';
|
|
|
167
173
|
export interface SqlDialect {
|
|
168
174
|
identifier(name: string): string;
|
|
169
175
|
literal(value: string | null): string;
|
|
176
|
+
/**
|
|
177
|
+
* Bytes as the grid shows them (MySQL's `0x1F`, SQLite's `X'1F'`), as a literal that is those
|
|
178
|
+
* bytes; null when `shown` isn't in that form. Absent where the shown form is text the
|
|
179
|
+
* database reads as bytes itself (PostgreSQL's `\x1f`).
|
|
180
|
+
*/
|
|
181
|
+
bytes?(shown: string): string | null;
|
|
182
|
+
/** What an INSERT says before VALUES to bring its own values for a column numbered always. */
|
|
183
|
+
overriding?: string;
|
|
184
|
+
/** An INSERT of nothing but defaults, where it isn't `DEFAULT VALUES`. */
|
|
185
|
+
insertDefaults?: string;
|
|
186
|
+
/** What an SQL export starts with, so its literals are read as written whatever the session. */
|
|
187
|
+
exportHeader?: string;
|
|
188
|
+
/** What it ends with, putting back what the header changed. */
|
|
189
|
+
exportFooter?: string;
|
|
190
|
+
}
|
|
191
|
+
/** A column of an export, with what an SQL export must know to put its values back. */
|
|
192
|
+
export interface ExportColumn {
|
|
193
|
+
name: string;
|
|
194
|
+
/** Its values are bytes, in the database's own hex form. */
|
|
195
|
+
bytes?: boolean;
|
|
196
|
+
/** The database computes it from other columns: an INSERT leaves it out. */
|
|
197
|
+
generated?: boolean;
|
|
198
|
+
/** The database numbers it always: an INSERT says it brings its own values. */
|
|
199
|
+
identity?: boolean;
|
|
170
200
|
}
|
|
171
201
|
/** The server a connection reaches, for the toolbar. */
|
|
172
202
|
export interface ServerInfo {
|
|
@@ -224,9 +254,7 @@ export interface Driver {
|
|
|
224
254
|
export(request: Pick<RowsRequest, 'schema' | 'table' | 'filters' | 'order'>, options: {
|
|
225
255
|
timeoutMs: number;
|
|
226
256
|
}): AsyncGenerator<{
|
|
227
|
-
columns:
|
|
228
|
-
name: string;
|
|
229
|
-
}[];
|
|
257
|
+
columns: ExportColumn[];
|
|
230
258
|
rows: (string | null)[][];
|
|
231
259
|
}>;
|
|
232
260
|
readonly sql: SqlDialect;
|
|
@@ -267,6 +295,12 @@ export interface Session {
|
|
|
267
295
|
* Finish quickly, without waiting on a slow download.
|
|
268
296
|
*/
|
|
269
297
|
readonly exclusive: boolean;
|
|
298
|
+
/**
|
|
299
|
+
* Whether the transaction it opened is still open: false once a statement has ended it, by a
|
|
300
|
+
* COMMIT or a ROLLBACK of its own. A restore asks after each statement of its file, so one
|
|
301
|
+
* that ends the transaction is the last to run. A driver that can't tell leaves it out.
|
|
302
|
+
*/
|
|
303
|
+
inTransaction?(): boolean;
|
|
270
304
|
}
|
|
271
305
|
/** Who is asking, as the host's `authorize()` says. */
|
|
272
306
|
export interface Viewer {
|
package/dist/words.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the SQL goes on from `at`, past spaces and comments, as PostgreSQL reads them: a `--`
|
|
3
|
+
* comment ends at a line feed or a carriage return, whichever comes first, and block comments
|
|
4
|
+
* nest. Read otherwise, a word after a carriage return would be taken for part of the comment
|
|
5
|
+
* here and for SQL by the server.
|
|
6
|
+
*/
|
|
7
|
+
export declare function pastComments(statement: string, from: number): number;
|
|
8
|
+
/**
|
|
9
|
+
* The statement's first two words with one space between, past the comments and spaces before
|
|
10
|
+
* and between them: `PREPARE TRANSACTION`, however it's written.
|
|
11
|
+
*/
|
|
12
|
+
export declare function firstWords(statement: string): string;
|
|
13
|
+
/**
|
|
14
|
+
* The statement's first word in capitals, past spaces, comments, brackets and empty statements
|
|
15
|
+
* (`;COPY …` is COPY to the server). Read a character at a time: a pattern for "any number of
|
|
16
|
+
* comments" tries every way to split them when no word follows, and a statement of a hundred
|
|
17
|
+
* characters can hold the thread for hours.
|
|
18
|
+
*/
|
|
19
|
+
export declare function leadingWord(sql: string): string;
|
package/dist/words.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* A PostgreSQL statement's first words, read the way the server reads them. What refuses a
|
|
3
|
+
* statement by how it starts (a restore's COMMIT, a read-only connection's COPY) must see the
|
|
4
|
+
* word the server will, whatever comments and line ends are put before it.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Where the SQL goes on from `at`, past spaces and comments, as PostgreSQL reads them: a `--`
|
|
8
|
+
* comment ends at a line feed or a carriage return, whichever comes first, and block comments
|
|
9
|
+
* nest. Read otherwise, a word after a carriage return would be taken for part of the comment
|
|
10
|
+
* here and for SQL by the server.
|
|
11
|
+
*/
|
|
12
|
+
export function pastComments(statement, from) {
|
|
13
|
+
let at = from;
|
|
14
|
+
for (;;) {
|
|
15
|
+
while (/\s/.test(statement[at] ?? ''))
|
|
16
|
+
at += 1;
|
|
17
|
+
if (statement.startsWith('--', at)) {
|
|
18
|
+
const end = statement.slice(at).search(/[\n\r]/);
|
|
19
|
+
if (end === -1)
|
|
20
|
+
return statement.length;
|
|
21
|
+
at += end + 1;
|
|
22
|
+
}
|
|
23
|
+
else if (statement.startsWith('/*', at)) {
|
|
24
|
+
let depth = 0;
|
|
25
|
+
do {
|
|
26
|
+
if (statement.startsWith('/*', at)) {
|
|
27
|
+
depth += 1;
|
|
28
|
+
at += 2;
|
|
29
|
+
}
|
|
30
|
+
else if (statement.startsWith('*/', at)) {
|
|
31
|
+
depth -= 1;
|
|
32
|
+
at += 2;
|
|
33
|
+
}
|
|
34
|
+
else
|
|
35
|
+
at += 1;
|
|
36
|
+
} while (depth > 0 && at < statement.length);
|
|
37
|
+
}
|
|
38
|
+
else
|
|
39
|
+
return at;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The statement's first two words with one space between, past the comments and spaces before
|
|
44
|
+
* and between them: `PREPARE TRANSACTION`, however it's written.
|
|
45
|
+
*/
|
|
46
|
+
export function firstWords(statement) {
|
|
47
|
+
const words = [];
|
|
48
|
+
let at = 0;
|
|
49
|
+
while (words.length < 2) {
|
|
50
|
+
at = pastComments(statement, at);
|
|
51
|
+
const word = /^[A-Za-z_]+/.exec(statement.slice(at, at + 64))?.[0];
|
|
52
|
+
if (!word)
|
|
53
|
+
break;
|
|
54
|
+
words.push(word);
|
|
55
|
+
at += word.length;
|
|
56
|
+
}
|
|
57
|
+
return words.join(' ');
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The statement's first word in capitals, past spaces, comments, brackets and empty statements
|
|
61
|
+
* (`;COPY …` is COPY to the server). Read a character at a time: a pattern for "any number of
|
|
62
|
+
* comments" tries every way to split them when no word follows, and a statement of a hundred
|
|
63
|
+
* characters can hold the thread for hours.
|
|
64
|
+
*/
|
|
65
|
+
export function leadingWord(sql) {
|
|
66
|
+
let at = 0;
|
|
67
|
+
for (;;) {
|
|
68
|
+
at = pastComments(sql, at);
|
|
69
|
+
if (sql[at] === ';' || sql[at] === '(')
|
|
70
|
+
at += 1;
|
|
71
|
+
else
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
return (/^[A-Za-z_]+/.exec(sql.slice(at, at + 64))?.[0] ?? '').toUpperCase();
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=words.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"words.js","sourceRoot":"","sources":["../src/words.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,SAAiB,EAAE,IAAY;IAC1D,IAAI,EAAE,GAAG,IAAI,CAAA;IACb,SAAS,CAAC;QACR,OAAO,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC;YAAE,EAAE,IAAI,CAAC,CAAA;QAC9C,IAAI,SAAS,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;YACnC,MAAM,GAAG,GAAG,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;YAChD,IAAI,GAAG,KAAK,CAAC,CAAC;gBAAE,OAAO,SAAS,CAAC,MAAM,CAAA;YACvC,EAAE,IAAI,GAAG,GAAG,CAAC,CAAA;QACf,CAAC;aAAM,IAAI,SAAS,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;YAC1C,IAAI,KAAK,GAAG,CAAC,CAAA;YACb,GAAG,CAAC;gBACF,IAAI,SAAS,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;oBACnC,KAAK,IAAI,CAAC,CAAA;oBACV,EAAE,IAAI,CAAC,CAAA;gBACT,CAAC;qBAAM,IAAI,SAAS,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;oBAC1C,KAAK,IAAI,CAAC,CAAA;oBACV,EAAE,IAAI,CAAC,CAAA;gBACT,CAAC;;oBAAM,EAAE,IAAI,CAAC,CAAA;YAChB,CAAC,QAAQ,KAAK,GAAG,CAAC,IAAI,EAAE,GAAG,SAAS,CAAC,MAAM,EAAC;QAC9C,CAAC;;YAAM,OAAO,EAAE,CAAA;IAClB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,SAAiB;IAC1C,MAAM,KAAK,GAAa,EAAE,CAAA;IAC1B,IAAI,EAAE,GAAG,CAAC,CAAA;IACV,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACxB,EAAE,GAAG,YAAY,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;QAChC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;QAClE,IAAI,CAAC,IAAI;YAAE,MAAK;QAChB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAChB,EAAE,IAAI,IAAI,CAAC,MAAM,CAAA;IACnB,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AACxB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,IAAI,EAAE,GAAG,CAAC,CAAA;IACV,SAAS,CAAC;QACR,EAAE,GAAG,YAAY,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;QAC1B,IAAI,GAAG,CAAC,EAAE,CAAC,KAAK,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,KAAK,GAAG;YAAE,EAAE,IAAI,CAAC,CAAA;;YAC1C,MAAK;IACZ,CAAC;IACD,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAA;AAC9E,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@otwdesign/db-core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "A database manager's engine and HTTP API, as one Fetch handler: browse, query and inspect PostgreSQL, MySQL and SQLite from any app.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "OTW SRL",
|
|
@@ -52,12 +52,12 @@
|
|
|
52
52
|
"NOTICE"
|
|
53
53
|
],
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"@otwdesign/db-ui": "1.
|
|
55
|
+
"@otwdesign/db-ui": "1.4.0"
|
|
56
56
|
},
|
|
57
57
|
"peerDependencies": {
|
|
58
|
+
"mysql2": "^3.11.0",
|
|
58
59
|
"pg": "^8.11.0",
|
|
59
|
-
"pg-cursor": "^2.10.0"
|
|
60
|
-
"mysql2": "^3.11.0"
|
|
60
|
+
"pg-cursor": "^2.10.0"
|
|
61
61
|
},
|
|
62
62
|
"peerDependenciesMeta": {
|
|
63
63
|
"pg": {
|
|
@@ -71,12 +71,13 @@
|
|
|
71
71
|
}
|
|
72
72
|
},
|
|
73
73
|
"devDependencies": {
|
|
74
|
+
"@electric-sql/pglite": "^0.5.13",
|
|
74
75
|
"@types/pg": "^8.23.1",
|
|
75
76
|
"@types/pg-cursor": "^2.7.2",
|
|
76
|
-
"pg": "^8.23.1",
|
|
77
|
-
"pg-cursor": "^2.22.1",
|
|
78
77
|
"mysql2": "^3.24.6",
|
|
79
|
-
"
|
|
78
|
+
"pg": "^8.23.1",
|
|
79
|
+
"pg-8-11": "npm:pg@8.11.0",
|
|
80
|
+
"pg-cursor": "^2.22.1"
|
|
80
81
|
},
|
|
81
82
|
"scripts": {
|
|
82
83
|
"build": "tsc -p tsconfig.build.json",
|
package/src/backup/api.ts
CHANGED
|
@@ -23,7 +23,13 @@ import {
|
|
|
23
23
|
type BackupHeader,
|
|
24
24
|
} from './format.ts'
|
|
25
25
|
import { pgTool, runDump, runRestore, type PgTool } from './pg-tools.ts'
|
|
26
|
-
import {
|
|
26
|
+
import {
|
|
27
|
+
LOCK_NOT_AVAILABLE,
|
|
28
|
+
refuseBlocked,
|
|
29
|
+
restorePlan,
|
|
30
|
+
restoreSql,
|
|
31
|
+
type RestorePlan,
|
|
32
|
+
} from './restore.ts'
|
|
27
33
|
import * as staging from './staging.ts'
|
|
28
34
|
|
|
29
35
|
/*
|
|
@@ -264,27 +270,49 @@ export async function run(ctx: BackupContext, body: Record<string, unknown>): Pr
|
|
|
264
270
|
try {
|
|
265
271
|
upload = await staging.findUpload(session, id, ctx.viewer.id)
|
|
266
272
|
staging.complete(upload)
|
|
273
|
+
await confirmed(session, body.confirm)
|
|
267
274
|
} catch (error) {
|
|
268
275
|
await session.end(false)
|
|
269
276
|
throw error
|
|
270
277
|
}
|
|
271
278
|
let header: BackupHeader | null = null
|
|
272
|
-
|
|
279
|
+
// Which file ran, and how much of it: the schemas alone are only what its first line says.
|
|
280
|
+
const audit = (result: { statements?: number; rows?: number; sha256?: string }, error?: Error) =>
|
|
273
281
|
void ctx.record({
|
|
274
282
|
viewer: ctx.viewer.id,
|
|
275
283
|
connection: ctx.connection.name,
|
|
276
284
|
...(ctx.database ? { database: ctx.database } : {}),
|
|
277
285
|
action: 'restore',
|
|
278
|
-
statement: `restore of ${header ? header.schemas.join(', ') : 'a backup'} (${
|
|
286
|
+
statement: `restore of ${header ? header.schemas.join(', ') : 'a backup'} (${[
|
|
287
|
+
upload.kind,
|
|
288
|
+
`${upload.size} bytes`,
|
|
289
|
+
...(result.sha256 ? [`${result.statements} statements`, `sha256 ${result.sha256}`] : []),
|
|
290
|
+
].join(', ')})`,
|
|
279
291
|
durationMs: Math.round(performance.now() - started),
|
|
280
292
|
...(result.rows === undefined ? {} : { rows: result.rows }),
|
|
281
293
|
...(error ? { error: error.message } : {}),
|
|
282
294
|
})
|
|
283
295
|
const encoder = new TextEncoder()
|
|
296
|
+
/** The browser stopped reading: there's nobody to tell, and nobody watching what a restore does. */
|
|
297
|
+
let gone = false
|
|
284
298
|
const stream = new ReadableStream<Uint8Array>({
|
|
285
299
|
async start(controller) {
|
|
286
|
-
const send = (line: unknown) =>
|
|
287
|
-
|
|
300
|
+
const send = (line: unknown) => {
|
|
301
|
+
if (!gone) {
|
|
302
|
+
try {
|
|
303
|
+
controller.enqueue(encoder.encode(`${JSON.stringify(line)}\n`))
|
|
304
|
+
return
|
|
305
|
+
} catch {
|
|
306
|
+
gone = true
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// Thrown into the restore as it reports its progress, which rolls it back.
|
|
310
|
+
throw new DbAdminError(
|
|
311
|
+
'The browser stopped listening before the restore was done, so it was stopped: nothing was restored.',
|
|
312
|
+
499,
|
|
313
|
+
'client-gone',
|
|
314
|
+
)
|
|
315
|
+
}
|
|
288
316
|
try {
|
|
289
317
|
const result =
|
|
290
318
|
upload.kind === 'sql'
|
|
@@ -298,7 +326,19 @@ export async function run(ctx: BackupContext, body: Record<string, unknown>): Pr
|
|
|
298
326
|
send({ type: 'progress', statements: 0, bytes: upload.size }),
|
|
299
327
|
)
|
|
300
328
|
audit(result)
|
|
301
|
-
|
|
329
|
+
const { statements, tables, rows } = result
|
|
330
|
+
try {
|
|
331
|
+
send({
|
|
332
|
+
type: 'done',
|
|
333
|
+
statements,
|
|
334
|
+
tables,
|
|
335
|
+
rows,
|
|
336
|
+
durationMs: Math.round(performance.now() - started),
|
|
337
|
+
})
|
|
338
|
+
} catch {
|
|
339
|
+
// Gone at the very end. It's committed, and the audit log has said so: this must not
|
|
340
|
+
// reach the catch below, which would log that nothing was restored.
|
|
341
|
+
}
|
|
302
342
|
} catch (error) {
|
|
303
343
|
const failure =
|
|
304
344
|
error instanceof DbAdminError
|
|
@@ -309,15 +349,27 @@ export async function run(ctx: BackupContext, body: Record<string, unknown>): Pr
|
|
|
309
349
|
'restore-failed',
|
|
310
350
|
)
|
|
311
351
|
audit({}, failure)
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
352
|
+
if (!gone) {
|
|
353
|
+
try {
|
|
354
|
+
send({ type: 'error', error: { code: failure.code, message: failure.message } })
|
|
355
|
+
} catch {
|
|
356
|
+
// Gone meanwhile: the audit log has it.
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
// A failed restore's upload goes too: it would only fail again. Unless the database was
|
|
360
|
+
// busy, which passes: the upload waits for another try (a day at most).
|
|
361
|
+
if (failure.code !== 'busy') {
|
|
362
|
+
await write(ctx, (s) => staging.discard(s, id)).catch((e: unknown) =>
|
|
363
|
+
console.error('otw-db: could not remove a restore’s upload', e),
|
|
364
|
+
)
|
|
365
|
+
}
|
|
317
366
|
} finally {
|
|
318
|
-
controller.close()
|
|
367
|
+
if (!gone) controller.close()
|
|
319
368
|
}
|
|
320
369
|
},
|
|
370
|
+
cancel() {
|
|
371
|
+
gone = true
|
|
372
|
+
},
|
|
321
373
|
})
|
|
322
374
|
return new Response(stream, {
|
|
323
375
|
headers: {
|
|
@@ -347,7 +399,7 @@ async function restoreInSession(
|
|
|
347
399
|
upload: staging.Upload,
|
|
348
400
|
onHeader: (header: BackupHeader) => void,
|
|
349
401
|
onProgress: (progress: { statements: number; bytes: number }) => void,
|
|
350
|
-
): Promise<{ statements: number; tables: number; rows: number }> {
|
|
402
|
+
): Promise<{ statements: number; tables: number; rows: number; sha256: string }> {
|
|
351
403
|
try {
|
|
352
404
|
// A table the site is using makes DROP wait; better to fail soon and say why.
|
|
353
405
|
if (!session.exclusive) await session.query(`SET LOCAL lock_timeout = '10s'`)
|
|
@@ -363,7 +415,7 @@ async function restoreInSession(
|
|
|
363
415
|
return result
|
|
364
416
|
} catch (error) {
|
|
365
417
|
await session.end(false).catch(() => {})
|
|
366
|
-
if (error instanceof QueryError && error.sqlState ===
|
|
418
|
+
if (error instanceof QueryError && error.sqlState === LOCK_NOT_AVAILABLE) {
|
|
367
419
|
throw new DbAdminError(
|
|
368
420
|
'The database is busy: something is using a table the restore replaces. Nothing changed; try again in a moment.',
|
|
369
421
|
409,
|
|
@@ -412,6 +464,22 @@ async function restoreTool(ctx: BackupContext): Promise<void> {
|
|
|
412
464
|
if (!tool.available) throw bad(tool.reason!)
|
|
413
465
|
}
|
|
414
466
|
|
|
467
|
+
/**
|
|
468
|
+
* Refuses a restore that doesn't come with the database's name, as the person typed it. The
|
|
469
|
+
* dialog asks for it; checked here, a request that skips the dialog is asked too.
|
|
470
|
+
*/
|
|
471
|
+
async function confirmed(session: Session, confirm: unknown): Promise<void> {
|
|
472
|
+
const { rows } = await session.query('SELECT current_database()')
|
|
473
|
+
const database = rows[0]![0]!
|
|
474
|
+
if (confirm !== database) {
|
|
475
|
+
throw new DbAdminError(
|
|
476
|
+
`To restore, send the database’s name, "${database}", as "confirm".`,
|
|
477
|
+
400,
|
|
478
|
+
'unconfirmed',
|
|
479
|
+
)
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
415
483
|
function mayRestore(ctx: BackupContext): void {
|
|
416
484
|
if (ctx.access !== 'write') {
|
|
417
485
|
throw new DbAdminError(
|
package/src/backup/catalog.ts
CHANGED
|
@@ -53,6 +53,18 @@ const collation = (coll: string, type: string) => `CASE WHEN ${coll} <> 0
|
|
|
53
53
|
const inSchemas = (namespace: string) =>
|
|
54
54
|
`${namespace} IN (SELECT oid FROM pg_namespace WHERE nspname = ANY($1))`
|
|
55
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Whether the relation `c` is one a backup can't hold: a foreign table, a typed table, a table
|
|
58
|
+
* that inherits another, or a partition whose parent is outside the schemas. Nothing of such a
|
|
59
|
+
* table is in a backup either (its keys, indexes, triggers, rules, policies, statistics, the
|
|
60
|
+
* sequences its columns own): a backup that named one would name a table it doesn't make.
|
|
61
|
+
*/
|
|
62
|
+
export const unheld = (c: string) => `(${c}.relkind = 'f' OR ${c}.reloftype <> 0
|
|
63
|
+
OR (${c}.relkind IN ('r', 'p') AND NOT ${c}.relispartition
|
|
64
|
+
AND EXISTS (SELECT 1 FROM pg_inherits ui WHERE ui.inhrelid = ${c}.oid))
|
|
65
|
+
OR (${c}.relispartition AND NOT EXISTS (SELECT 1 FROM pg_inherits ui JOIN pg_class up ON up.oid = ui.inhparent
|
|
66
|
+
WHERE ui.inhrelid = ${c}.oid AND ${inSchemas('up.relnamespace')})))`
|
|
67
|
+
|
|
56
68
|
/** The session's settings: names printed qualified, values printed so they read back the same. */
|
|
57
69
|
export const SESSION_SQL = [
|
|
58
70
|
`SELECT set_config('search_path', '', true)`,
|
|
@@ -121,11 +133,18 @@ export const NOT_INCLUDED_SQL = `SELECT coalesce(json_agg(json_build_object('sch
|
|
|
121
133
|
WHERE ${inSchemas('o.connamespace')} AND ${notMember(2607, 'o.oid')}
|
|
122
134
|
UNION ALL SELECT ${schemaOf('c.relnamespace')}, pg_describe_object(${PG_CLASS}, c.oid, 0) FROM pg_class c
|
|
123
135
|
WHERE ${inSchemas('c.relnamespace')} AND ${notMember(PG_CLASS, 'c.oid')}
|
|
124
|
-
AND
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
136
|
+
AND c.relkind IN ('r', 'p', 'f') AND ${unheld('c')}
|
|
137
|
+
UNION ALL SELECT ${schemaOf('c.relnamespace')}, pg_describe_object(${PG_CONSTRAINT}, co.oid, 0)
|
|
138
|
+
|| ' (it refers to ' || co.confrelid::regclass || ', which a backup can’t hold)'
|
|
139
|
+
FROM pg_constraint co JOIN pg_class c ON c.oid = co.conrelid JOIN pg_class rc ON rc.oid = co.confrelid
|
|
140
|
+
WHERE co.contype = 'f' AND ${inSchemas('c.relnamespace')} AND NOT ${unheld('c')}
|
|
141
|
+
AND ${inSchemas('rc.relnamespace')} AND ${unheld('rc')} AND ${notMember(PG_CLASS, 'c.oid')}
|
|
142
|
+
UNION ALL SELECT ${schemaOf('c.relnamespace')}, 'where ' || pg_describe_object(${PG_CLASS}, c.oid, 0)
|
|
143
|
+
|| ' has got to (this login may not read it)'
|
|
144
|
+
FROM pg_class c
|
|
145
|
+
WHERE ${inSchemas('c.relnamespace')} AND ${notMember(PG_CLASS, 'c.oid')}
|
|
146
|
+
-- In a CASE, so the privilege is only ever asked of a sequence: asked of a table, it fails.
|
|
147
|
+
AND CASE WHEN c.relkind = 'S' THEN NOT has_sequence_privilege(c.oid, 'SELECT') ELSE false END
|
|
129
148
|
UNION ALL SELECT NULL, pg_describe_object('pg_cast'::regclass, k.oid, 0) FROM pg_cast k
|
|
130
149
|
WHERE k.oid >= 16384 AND ${notMember(2605, 'k.oid')} AND ${notInternal(2605, 'k.oid')}
|
|
131
150
|
UNION ALL SELECT NULL, pg_describe_object('pg_event_trigger'::regclass, v.oid, 0) FROM pg_event_trigger v
|
|
@@ -220,8 +239,7 @@ const sequenceSettings = (c: string, s: string) => `json_build_object(
|
|
|
220
239
|
'type', format_type(${s}.seqtypid, NULL), 'start', ${s}.seqstart::text,
|
|
221
240
|
'increment', ${s}.seqincrement::text, 'min', ${s}.seqmin::text, 'max', ${s}.seqmax::text,
|
|
222
241
|
'cache', ${s}.seqcache::text, 'cycle', ${s}.seqcycle,
|
|
223
|
-
'
|
|
224
|
-
AND ps.sequencename = ${c}.relname))`
|
|
242
|
+
'readable', has_sequence_privilege(${c}.oid, 'SELECT'))`
|
|
225
243
|
|
|
226
244
|
/** Sequences of their own; an identity column's comes with its table. */
|
|
227
245
|
export const SEQUENCES_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
@@ -234,7 +252,10 @@ export const SEQUENCES_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
|
234
252
|
ORDER BY sn.nspname, c.relname), '[]')
|
|
235
253
|
FROM pg_class c JOIN pg_sequence s ON s.seqrelid = c.oid JOIN pg_namespace sn ON sn.oid = c.relnamespace
|
|
236
254
|
WHERE c.relkind = 'S' AND sn.nspname = ANY($1) AND ${notMember(PG_CLASS, 'c.oid')}
|
|
237
|
-
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = ${PG_CLASS} AND d.objid = c.oid AND d.deptype = 'i')
|
|
255
|
+
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = ${PG_CLASS} AND d.objid = c.oid AND d.deptype = 'i')
|
|
256
|
+
AND NOT EXISTS (SELECT 1 FROM pg_depend d JOIN pg_class oc ON oc.oid = d.refobjid
|
|
257
|
+
WHERE d.classid = ${PG_CLASS} AND d.objid = c.oid AND d.refclassid = ${PG_CLASS}
|
|
258
|
+
AND d.deptype = 'a' AND ${unheld('oc')})`
|
|
238
259
|
|
|
239
260
|
/** A relation's columns: types, defaults, identity and generation, collations, comments, grants. */
|
|
240
261
|
const columns = (c: string) => `(SELECT coalesce(json_agg(json_build_object(
|
|
@@ -277,10 +298,7 @@ export const TABLES_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
|
277
298
|
ORDER BY n.nspname, c.relname), '[]')
|
|
278
299
|
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
279
300
|
WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1) AND ${notMember(PG_CLASS, 'c.oid')}
|
|
280
|
-
AND c
|
|
281
|
-
AND (c.relispartition OR NOT EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhrelid = c.oid))
|
|
282
|
-
AND (NOT c.relispartition OR EXISTS (SELECT 1 FROM pg_inherits i JOIN pg_class pc ON pc.oid = i.inhparent
|
|
283
|
-
WHERE i.inhrelid = c.oid AND ${inSchemas('pc.relnamespace')}))`
|
|
301
|
+
AND NOT ${unheld('c')}`
|
|
284
302
|
|
|
285
303
|
export const VIEWS_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
286
304
|
'oid', c.oid, 'schema', n.nspname, 'name', c.relname, 'kind', c.relkind,
|
|
@@ -299,7 +317,10 @@ export const CONSTRAINTS_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
|
299
317
|
ORDER BY n.nspname, c.relname, co.conname), '[]')
|
|
300
318
|
FROM pg_constraint co JOIN pg_class c ON c.oid = co.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
301
319
|
WHERE co.contype IN ('p', 'u', 'x', 'f') AND n.nspname = ANY($1) AND c.relkind IN ('r', 'p')
|
|
302
|
-
AND ${notMember(PG_CLASS, 'c.oid')}
|
|
320
|
+
AND ${notMember(PG_CLASS, 'c.oid')} AND NOT ${unheld('c')}
|
|
321
|
+
-- A foreign key to a table the backup can't hold would refer to a table it doesn't make.
|
|
322
|
+
AND NOT EXISTS (SELECT 1 FROM pg_class rc WHERE rc.oid = co.confrelid
|
|
323
|
+
AND ${inSchemas('rc.relnamespace')} AND ${unheld('rc')})`
|
|
303
324
|
|
|
304
325
|
export const INDEXES_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
305
326
|
'oid', x.indexrelid, 'schema', n.nspname, 'name', ic.relname, 'table', x.indrelid,
|
|
@@ -311,7 +332,8 @@ export const INDEXES_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
|
311
332
|
ORDER BY n.nspname, ic.relname), '[]')
|
|
312
333
|
FROM pg_index x JOIN pg_class ic ON ic.oid = x.indexrelid JOIN pg_class tc ON tc.oid = x.indrelid
|
|
313
334
|
JOIN pg_namespace n ON n.oid = tc.relnamespace
|
|
314
|
-
WHERE n.nspname = ANY($1) AND tc.relkind IN ('r', 'p', 'm') AND ${notMember(PG_CLASS, 'tc.oid')}
|
|
335
|
+
WHERE n.nspname = ANY($1) AND tc.relkind IN ('r', 'p', 'm') AND ${notMember(PG_CLASS, 'tc.oid')}
|
|
336
|
+
AND NOT ${unheld('tc')}`
|
|
315
337
|
|
|
316
338
|
export const TRIGGERS_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
317
339
|
'name', t.tgname, 'table', t.tgrelid, 'def', pg_get_triggerdef(t.oid), 'enabled', t.tgenabled,
|
|
@@ -319,14 +341,15 @@ export const TRIGGERS_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
|
319
341
|
ORDER BY n.nspname, c.relname, t.tgname), '[]')
|
|
320
342
|
FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
321
343
|
WHERE NOT t.tgisinternal AND t.tgparentid = 0 AND n.nspname = ANY($1)
|
|
322
|
-
AND ${notMember(PG_CLASS, 'c.oid')}`
|
|
344
|
+
AND ${notMember(PG_CLASS, 'c.oid')} AND NOT ${unheld('c')}`
|
|
323
345
|
|
|
324
346
|
/** Rules besides a view's own. */
|
|
325
347
|
export const RULES_SQL = `SELECT coalesce(json_agg(json_build_object('name', r.rulename, 'table', r.ev_class,
|
|
326
348
|
'def', pg_get_ruledef(r.oid), 'comment', obj_description(r.oid, 'pg_rewrite'))
|
|
327
349
|
ORDER BY n.nspname, c.relname, r.rulename), '[]')
|
|
328
350
|
FROM pg_rewrite r JOIN pg_class c ON c.oid = r.ev_class JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
329
|
-
WHERE r.rulename <> '_RETURN' AND n.nspname = ANY($1) AND ${notMember(PG_CLASS, 'c.oid')}
|
|
351
|
+
WHERE r.rulename <> '_RETURN' AND n.nspname = ANY($1) AND ${notMember(PG_CLASS, 'c.oid')}
|
|
352
|
+
AND NOT ${unheld('c')}`
|
|
330
353
|
|
|
331
354
|
export const POLICIES_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
332
355
|
'name', p.polname, 'table', p.polrelid, 'command', p.polcmd, 'permissive', p.polpermissive,
|
|
@@ -335,13 +358,15 @@ export const POLICIES_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
|
335
358
|
'comment', obj_description(p.oid, 'pg_policy'))
|
|
336
359
|
ORDER BY n.nspname, c.relname, p.polname), '[]')
|
|
337
360
|
FROM pg_policy p JOIN pg_class c ON c.oid = p.polrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
338
|
-
WHERE n.nspname = ANY($1)`
|
|
361
|
+
WHERE n.nspname = ANY($1) AND NOT ${unheld('c')}`
|
|
339
362
|
|
|
340
363
|
export const STATISTICS_SQL = `SELECT coalesce(json_agg(json_build_object(
|
|
341
364
|
'name', quote_ident(n.nspname) || '.' || quote_ident(s.stxname),
|
|
342
365
|
'def', pg_get_statisticsobjdef(s.oid), 'comment', obj_description(s.oid, 'pg_statistic_ext'))
|
|
343
366
|
ORDER BY n.nspname, s.stxname), '[]')
|
|
344
|
-
FROM pg_statistic_ext s JOIN pg_namespace n ON n.oid = s.stxnamespace
|
|
367
|
+
FROM pg_statistic_ext s JOIN pg_namespace n ON n.oid = s.stxnamespace
|
|
368
|
+
JOIN pg_class c ON c.oid = s.stxrelid
|
|
369
|
+
WHERE n.nspname = ANY($1) AND NOT ${unheld('c')}`
|
|
345
370
|
|
|
346
371
|
/**
|
|
347
372
|
* What depends on what, among the objects a backup creates before its data: [catalog, oid,
|