@otwdesign/db-core 1.1.0 → 1.3.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.d.ts +55 -0
- package/dist/backup/api.js +441 -0
- package/dist/backup/api.js.map +1 -0
- package/dist/backup/catalog.d.ts +47 -0
- package/dist/backup/catalog.js +348 -0
- package/dist/backup/catalog.js.map +1 -0
- package/dist/backup/dump.d.ts +48 -0
- package/dist/backup/dump.js +860 -0
- package/dist/backup/dump.js.map +1 -0
- package/dist/backup/format.d.ts +38 -0
- package/dist/backup/format.js +70 -0
- package/dist/backup/format.js.map +1 -0
- package/dist/backup/pg-tools.d.ts +29 -0
- package/dist/backup/pg-tools.js +154 -0
- package/dist/backup/pg-tools.js.map +1 -0
- package/dist/backup/restore.d.ts +41 -0
- package/dist/backup/restore.js +196 -0
- package/dist/backup/restore.js.map +1 -0
- package/dist/backup/split.d.ts +18 -0
- package/dist/backup/split.js +316 -0
- package/dist/backup/split.js.map +1 -0
- package/dist/backup/staging.d.ts +29 -0
- package/dist/backup/staging.js +96 -0
- package/dist/backup/staging.js.map +1 -0
- package/dist/browser.d.ts +5 -0
- package/dist/connections.d.ts +4 -3
- package/dist/connections.js +14 -3
- package/dist/connections.js.map +1 -1
- package/dist/drivers/pglite.js +57 -0
- package/dist/drivers/pglite.js.map +1 -1
- package/dist/drivers/postgres-catalog.d.ts +5 -0
- package/dist/drivers/postgres-catalog.js +10 -0
- package/dist/drivers/postgres-catalog.js.map +1 -1
- package/dist/drivers/postgres.d.ts +6 -0
- package/dist/drivers/postgres.js +81 -1
- package/dist/drivers/postgres.js.map +1 -1
- package/dist/handler.d.ts +5 -0
- package/dist/handler.js +152 -23
- package/dist/handler.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/types.d.ts +60 -1
- package/package.json +2 -2
- package/src/backup/api.ts +543 -0
- package/src/backup/catalog.ts +381 -0
- package/src/backup/dump.ts +1102 -0
- package/src/backup/format.ts +114 -0
- package/src/backup/pg-tools.ts +185 -0
- package/src/backup/restore.ts +270 -0
- package/src/backup/split.ts +300 -0
- package/src/backup/staging.ts +143 -0
- package/src/browser.ts +5 -0
- package/src/connections.ts +13 -3
- package/src/drivers/pglite.ts +55 -0
- package/src/drivers/postgres-catalog.ts +11 -0
- package/src/drivers/postgres.ts +94 -0
- package/src/handler.ts +171 -23
- package/src/index.ts +6 -0
- package/src/types.ts +60 -1
package/src/drivers/postgres.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { connect } from 'node:net'
|
|
|
3
3
|
import type { FieldDef, Pool, PoolClient, PoolConfig } from 'pg'
|
|
4
4
|
import { ConnectionError, DbAdminError, QueryError } from '../errors.ts'
|
|
5
5
|
import {
|
|
6
|
+
DATABASES_SQL,
|
|
6
7
|
detail,
|
|
7
8
|
dialect,
|
|
8
9
|
INFO_SQL,
|
|
@@ -21,12 +22,14 @@ import type {
|
|
|
21
22
|
ApplyResult,
|
|
22
23
|
Capabilities,
|
|
23
24
|
Change,
|
|
25
|
+
DatabaseList,
|
|
24
26
|
Driver,
|
|
25
27
|
QueryOptions,
|
|
26
28
|
QueryResult,
|
|
27
29
|
ResultSet,
|
|
28
30
|
RowsRequest,
|
|
29
31
|
ServerInfo,
|
|
32
|
+
Session,
|
|
30
33
|
TableDetail,
|
|
31
34
|
TableSummary,
|
|
32
35
|
} from '../types.ts'
|
|
@@ -107,6 +110,38 @@ async function load(modules: PostgresModules, failure: string): Promise<Modules>
|
|
|
107
110
|
return { Pool: PoolClass, Cursor: Cursor as typeof CursorClass }
|
|
108
111
|
}
|
|
109
112
|
|
|
113
|
+
/** A placeholder host for a URL with none, as pg's own parser uses: `user@/db?host=/socket`. */
|
|
114
|
+
const NO_HOST = '___otw_db_no_host___'
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* `url` at another of its server's databases: its path swapped for `database`, its login, host and
|
|
118
|
+
* settings kept. pg reads the path back with decodeURI, which leaves `?` and `#` escaped, so a
|
|
119
|
+
* name with either can't be carried.
|
|
120
|
+
*/
|
|
121
|
+
export function postgresUrlAt(url: string, database: string): string {
|
|
122
|
+
if (/[?#]/.test(database)) {
|
|
123
|
+
throw new DbAdminError(
|
|
124
|
+
`The database "${database}" can't be opened: a connection URL can't name a database with ? or #.`,
|
|
125
|
+
400,
|
|
126
|
+
'bad-database',
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
const hostless = url.includes('@/')
|
|
130
|
+
let parsed: URL
|
|
131
|
+
try {
|
|
132
|
+
parsed = new URL(hostless ? url.replace('@/', `@${NO_HOST}/`) : url)
|
|
133
|
+
} catch {
|
|
134
|
+
// Not the URL itself, which may hold a password.
|
|
135
|
+
throw new DbAdminError(
|
|
136
|
+
"The connection's URL can't be moved to another database.",
|
|
137
|
+
500,
|
|
138
|
+
'bad-url',
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
parsed.pathname = `/${encodeURI(database)}`
|
|
142
|
+
return hostless ? parsed.href.replace(`@${NO_HOST}/`, '@/') : parsed.href
|
|
143
|
+
}
|
|
144
|
+
|
|
110
145
|
/**
|
|
111
146
|
* A PostgreSQL driver for `url`. It connects on first use, with a pool of up to three
|
|
112
147
|
* connections, each closed after 10 s unused; an admin tool needs few.
|
|
@@ -119,6 +154,8 @@ class PostgresDriver implements Driver {
|
|
|
119
154
|
readonly kind = 'postgres'
|
|
120
155
|
readonly capabilities: Capabilities = { schemas: true, transactionalDdl: true, cancel: true }
|
|
121
156
|
readonly sql = { identifier: quote, literal }
|
|
157
|
+
readonly pgUrl: string
|
|
158
|
+
readonly #url: string
|
|
122
159
|
readonly #config: PoolConfig
|
|
123
160
|
readonly #modules: PostgresModules | undefined
|
|
124
161
|
#pool: Promise<{ pool: Pool; modules: Modules }> | undefined
|
|
@@ -126,6 +163,8 @@ class PostgresDriver implements Driver {
|
|
|
126
163
|
readonly #typeNames = new Map<number, string>()
|
|
127
164
|
|
|
128
165
|
constructor(url: string, modules: PostgresModules | undefined) {
|
|
166
|
+
this.#url = url
|
|
167
|
+
this.pgUrl = url
|
|
129
168
|
this.#modules = modules
|
|
130
169
|
this.#config = {
|
|
131
170
|
connectionString: url,
|
|
@@ -222,6 +261,18 @@ class PostgresDriver implements Driver {
|
|
|
222
261
|
return this.#run(sql, undefined, options)
|
|
223
262
|
}
|
|
224
263
|
|
|
264
|
+
async databases(): Promise<DatabaseList> {
|
|
265
|
+
const rows = await this.#catalog<{ name: string; current: string }>(DATABASES_SQL)
|
|
266
|
+
return {
|
|
267
|
+
current: rows.find((row) => row.current === 't')?.name ?? '',
|
|
268
|
+
databases: rows.map((row) => row.name),
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
withDatabase(name: string): Driver {
|
|
273
|
+
return new PostgresDriver(postgresUrlAt(this.#url, name), this.#modules)
|
|
274
|
+
}
|
|
275
|
+
|
|
225
276
|
async apply(
|
|
226
277
|
{ schema, table }: { schema: string; table: string },
|
|
227
278
|
changes: readonly Change[],
|
|
@@ -372,6 +423,49 @@ class PostgresDriver implements Driver {
|
|
|
372
423
|
}))
|
|
373
424
|
}
|
|
374
425
|
|
|
426
|
+
/** A transaction on a connection of its own, closed after: a restore's SETs leave with it. */
|
|
427
|
+
async session(mode: 'snapshot' | 'write'): Promise<Session> {
|
|
428
|
+
const { client } = await this.#connect()
|
|
429
|
+
try {
|
|
430
|
+
await client.query(
|
|
431
|
+
mode === 'snapshot' ? 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY' : 'BEGIN',
|
|
432
|
+
)
|
|
433
|
+
} catch (error) {
|
|
434
|
+
client.release(true)
|
|
435
|
+
throw toError(error)
|
|
436
|
+
}
|
|
437
|
+
let ended = false
|
|
438
|
+
return {
|
|
439
|
+
exclusive: false,
|
|
440
|
+
async query(text, values) {
|
|
441
|
+
try {
|
|
442
|
+
const result = await client.query({
|
|
443
|
+
text,
|
|
444
|
+
values: values?.map((v) =>
|
|
445
|
+
v instanceof Uint8Array ? Buffer.from(v.buffer, v.byteOffset, v.byteLength) : v,
|
|
446
|
+
),
|
|
447
|
+
rowMode: 'array',
|
|
448
|
+
types: AS_TEXT,
|
|
449
|
+
})
|
|
450
|
+
return { rows: result.rows as (string | null)[][] }
|
|
451
|
+
} catch (error) {
|
|
452
|
+
throw toError(error)
|
|
453
|
+
}
|
|
454
|
+
},
|
|
455
|
+
async end(commit) {
|
|
456
|
+
if (ended) return
|
|
457
|
+
ended = true
|
|
458
|
+
try {
|
|
459
|
+
await client.query(commit ? 'COMMIT' : 'ROLLBACK')
|
|
460
|
+
} catch (error) {
|
|
461
|
+
throw toError(error)
|
|
462
|
+
} finally {
|
|
463
|
+
client.release(true)
|
|
464
|
+
}
|
|
465
|
+
},
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
375
469
|
async close(): Promise<void> {
|
|
376
470
|
const opened = this.#pool
|
|
377
471
|
this.#pool = undefined
|
package/src/handler.ts
CHANGED
|
@@ -16,6 +16,7 @@ import type {
|
|
|
16
16
|
Viewer,
|
|
17
17
|
} from './types.ts'
|
|
18
18
|
import { ROUTES } from './routes.ts'
|
|
19
|
+
import type * as BackupApi from './backup/api.ts'
|
|
19
20
|
import { renderAsset, renderIndex, type UiAssets } from './ui.ts'
|
|
20
21
|
|
|
21
22
|
/** What `createDbAdmin` needs: who may use the tool, the databases it may open, its limits. */
|
|
@@ -47,6 +48,11 @@ export interface DbAdminOptions {
|
|
|
47
48
|
ui?: (() => Promise<UiAssets>) | false
|
|
48
49
|
/** Where the app sends a browser the API turns away (401): the host's sign-in page. */
|
|
49
50
|
signInUrl?: string
|
|
51
|
+
/** Backups and restores (PostgreSQL). A restore's upload waits in the database it restores. */
|
|
52
|
+
backups?: {
|
|
53
|
+
/** The biggest backup a restore takes, in bytes. Defaults to 1 GiB. */
|
|
54
|
+
maxRestoreBytes?: number
|
|
55
|
+
}
|
|
50
56
|
}
|
|
51
57
|
|
|
52
58
|
/**
|
|
@@ -82,6 +88,10 @@ const QUERY_ID = /^[A-Za-z0-9_-]{1,64}$/
|
|
|
82
88
|
const MAX_FILTERS = 20
|
|
83
89
|
const MAX_CHANGES = 1_000
|
|
84
90
|
const MAX_LIST = 1_000
|
|
91
|
+
/** A connection's other databases kept open at once; the one used longest ago closes first. */
|
|
92
|
+
const MAX_DATABASES = 8
|
|
93
|
+
/** PostgreSQL's NAMEDATALEN, less its terminator: the longest database name, in bytes. */
|
|
94
|
+
const MAX_DATABASE_NAME = 63
|
|
85
95
|
const OPERATORS: ReadonlySet<string> = new Set<FilterOperator>([
|
|
86
96
|
'=',
|
|
87
97
|
'<>',
|
|
@@ -127,10 +137,23 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
127
137
|
const limits = { ...DEFAULT_LIMITS, ...options.limits }
|
|
128
138
|
const audit = options.audit === false ? undefined : (options.audit ?? logAudit)
|
|
129
139
|
const drivers = new Map<string, Driver>()
|
|
140
|
+
/** Each connection's other databases' drivers, the one used last at the end. */
|
|
141
|
+
const others = new Map<string, Map<string, Driver>>()
|
|
130
142
|
const running = new Map<string, { viewer: string; controller: AbortController }>()
|
|
131
143
|
const open = options.driver ?? openDriver
|
|
132
144
|
const loadUi = options.ui === false ? undefined : (options.ui ?? defaultUi)
|
|
133
145
|
let ui: Promise<UiAssets> | undefined
|
|
146
|
+
// Loaded on the first backup or restore: a host that never makes one never loads it.
|
|
147
|
+
let backupApi: Promise<typeof BackupApi> | undefined
|
|
148
|
+
const backups = () => (backupApi ??= import('./backup/api.ts'))
|
|
149
|
+
const maxRestoreBytes = options.backups?.maxRestoreBytes ?? 1_073_741_824
|
|
150
|
+
/** What a backup endpoint needs to know, from the connection it reached. */
|
|
151
|
+
const backupContext = (target: ReturnType<typeof reach>, viewer: Viewer) => ({
|
|
152
|
+
...target,
|
|
153
|
+
viewer,
|
|
154
|
+
record,
|
|
155
|
+
maxRestoreBytes,
|
|
156
|
+
})
|
|
134
157
|
|
|
135
158
|
function driver(connection: ConnectionConfig): Driver {
|
|
136
159
|
let found = drivers.get(connection.name)
|
|
@@ -141,14 +164,55 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
141
164
|
return found
|
|
142
165
|
}
|
|
143
166
|
|
|
144
|
-
/**
|
|
145
|
-
|
|
167
|
+
/**
|
|
168
|
+
* The driver for one of the connection's other databases. The 8 used last stay open; opening a
|
|
169
|
+
* ninth closes the one used longest ago, so a viewer can't keep pools open without end.
|
|
170
|
+
*/
|
|
171
|
+
function driverAt(connection: ConnectionConfig, database: string): Driver {
|
|
172
|
+
let open = others.get(connection.name)
|
|
173
|
+
if (!open) others.set(connection.name, (open = new Map()))
|
|
174
|
+
let found = open.get(database)
|
|
175
|
+
if (found) open.delete(database)
|
|
176
|
+
else found = driver(connection).withDatabase!(database)
|
|
177
|
+
open.set(database, found)
|
|
178
|
+
if (open.size > MAX_DATABASES) {
|
|
179
|
+
const [oldest, evicted] = open.entries().next().value!
|
|
180
|
+
open.delete(oldest)
|
|
181
|
+
evicted.close().catch((error: unknown) => {
|
|
182
|
+
console.error(`otw-db: could not close database "${oldest}" of "${connection.name}"`, error)
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
return found
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The connection by name, with this viewer's access to it and the driver for `database`: one of
|
|
190
|
+
* the server's other databases, or the connection's own when none is named. Unknown and hidden
|
|
191
|
+
* connections look the same.
|
|
192
|
+
*/
|
|
193
|
+
function reach(
|
|
194
|
+
viewer: Viewer,
|
|
195
|
+
name: unknown,
|
|
196
|
+
database?: unknown,
|
|
197
|
+
): { connection: ConnectionConfig; access: Access; db: Driver; database?: string } {
|
|
146
198
|
const connection = typeof name === 'string' ? connections.get(name) : undefined
|
|
147
199
|
const access = connection ? accessOf(viewer, connection) : null
|
|
148
200
|
if (!connection || !access) {
|
|
149
201
|
throw new DbAdminError(`There's no connection "${String(name)}".`, 404, 'unknown-connection')
|
|
150
202
|
}
|
|
151
|
-
|
|
203
|
+
if (database === undefined || database === null || database === '') {
|
|
204
|
+
return { connection, access, db: driver(connection) }
|
|
205
|
+
}
|
|
206
|
+
const named = databaseName(database)
|
|
207
|
+
if (!opensOthers(connection)) throw oneDatabase(connection)
|
|
208
|
+
return { connection, access, db: driverAt(connection, named), database: named }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Whether the connection may open its server's other databases, and its driver can. */
|
|
212
|
+
function opensOthers(connection: ConnectionConfig): boolean {
|
|
213
|
+
if (connection.databases === 'one') return false
|
|
214
|
+
const opened = driver(connection)
|
|
215
|
+
return typeof opened.databases === 'function' && typeof opened.withDatabase === 'function'
|
|
152
216
|
}
|
|
153
217
|
|
|
154
218
|
async function record(event: Omit<AuditEvent, 'at'>): Promise<void> {
|
|
@@ -176,7 +240,12 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
176
240
|
// A kind without a driver yet is listed, but can't be opened.
|
|
177
241
|
let capabilities: Driver['capabilities'] | null = null
|
|
178
242
|
try {
|
|
179
|
-
|
|
243
|
+
const opened = driver(connection)
|
|
244
|
+
capabilities = {
|
|
245
|
+
...opened.capabilities,
|
|
246
|
+
databases: opensOthers(connection),
|
|
247
|
+
backup: typeof opened.session === 'function',
|
|
248
|
+
}
|
|
180
249
|
} catch (error) {
|
|
181
250
|
if (!(error instanceof DbAdminError)) throw error
|
|
182
251
|
}
|
|
@@ -188,12 +257,25 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
188
257
|
return { connections: visible }
|
|
189
258
|
},
|
|
190
259
|
},
|
|
260
|
+
{
|
|
261
|
+
method: 'GET',
|
|
262
|
+
path: '/api/databases',
|
|
263
|
+
async run(request, viewer) {
|
|
264
|
+
const { connection, db } = reach(
|
|
265
|
+
viewer,
|
|
266
|
+
new URL(request.url).searchParams.get('connection'),
|
|
267
|
+
)
|
|
268
|
+
if (!opensOthers(connection)) throw oneDatabase(connection)
|
|
269
|
+
return await db.databases!()
|
|
270
|
+
},
|
|
271
|
+
},
|
|
191
272
|
{
|
|
192
273
|
method: 'GET',
|
|
193
274
|
path: '/api/tables',
|
|
194
275
|
async run(request, viewer) {
|
|
195
|
-
const
|
|
196
|
-
|
|
276
|
+
const params = new URL(request.url).searchParams
|
|
277
|
+
const { db } = reach(viewer, params.get('connection'), params.get('database'))
|
|
278
|
+
return { tables: await db.tables() }
|
|
197
279
|
},
|
|
198
280
|
},
|
|
199
281
|
{
|
|
@@ -201,8 +283,8 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
201
283
|
path: '/api/table',
|
|
202
284
|
async run(request, viewer) {
|
|
203
285
|
const params = new URL(request.url).searchParams
|
|
204
|
-
const {
|
|
205
|
-
const table = await
|
|
286
|
+
const { db } = reach(viewer, params.get('connection'), params.get('database'))
|
|
287
|
+
const table = await db.table(
|
|
206
288
|
text(params.get('schema'), 'schema'),
|
|
207
289
|
text(params.get('name'), 'name'),
|
|
208
290
|
)
|
|
@@ -214,8 +296,9 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
214
296
|
method: 'GET',
|
|
215
297
|
path: '/api/info',
|
|
216
298
|
async run(request, viewer) {
|
|
217
|
-
const
|
|
218
|
-
|
|
299
|
+
const params = new URL(request.url).searchParams
|
|
300
|
+
const { db } = reach(viewer, params.get('connection'), params.get('database'))
|
|
301
|
+
return { info: await db.info() }
|
|
219
302
|
},
|
|
220
303
|
},
|
|
221
304
|
{
|
|
@@ -223,7 +306,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
223
306
|
path: '/api/count',
|
|
224
307
|
async run(request, viewer) {
|
|
225
308
|
const body = await json(request)
|
|
226
|
-
const { connection } = reach(viewer, body.connection)
|
|
309
|
+
const { connection, db, database } = reach(viewer, body.connection, body.database)
|
|
227
310
|
const target = {
|
|
228
311
|
schema: text(body.schema, 'schema'),
|
|
229
312
|
table: text(body.table, 'table'),
|
|
@@ -232,13 +315,14 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
232
315
|
const started = performance.now()
|
|
233
316
|
const statement = `count ${target.schema}.${target.table}`
|
|
234
317
|
try {
|
|
235
|
-
const rows = await
|
|
318
|
+
const rows = await db.count(target, {
|
|
236
319
|
timeoutMs: limits.timeoutMs,
|
|
237
320
|
signal: request.signal,
|
|
238
321
|
})
|
|
239
322
|
await record({
|
|
240
323
|
viewer: viewer.id,
|
|
241
324
|
connection: connection.name,
|
|
325
|
+
...(database ? { database } : {}),
|
|
242
326
|
action: 'count',
|
|
243
327
|
statement,
|
|
244
328
|
durationMs: Math.round(performance.now() - started),
|
|
@@ -249,6 +333,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
249
333
|
await record({
|
|
250
334
|
viewer: viewer.id,
|
|
251
335
|
connection: connection.name,
|
|
336
|
+
...(database ? { database } : {}),
|
|
252
337
|
action: 'count',
|
|
253
338
|
statement,
|
|
254
339
|
durationMs: Math.round(performance.now() - started),
|
|
@@ -263,18 +348,19 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
263
348
|
path: '/api/rows',
|
|
264
349
|
async run(request, viewer) {
|
|
265
350
|
const body = await json(request)
|
|
266
|
-
const { connection } = reach(viewer, body.connection)
|
|
351
|
+
const { connection, db, database } = reach(viewer, body.connection, body.database)
|
|
267
352
|
const page = rowsRequest(body)
|
|
268
353
|
const started = performance.now()
|
|
269
354
|
const statement = `${page.schema}.${page.table}`
|
|
270
355
|
try {
|
|
271
|
-
const result = await
|
|
356
|
+
const result = await db.rows(page, {
|
|
272
357
|
timeoutMs: limits.timeoutMs,
|
|
273
358
|
signal: request.signal,
|
|
274
359
|
})
|
|
275
360
|
await record({
|
|
276
361
|
viewer: viewer.id,
|
|
277
362
|
connection: connection.name,
|
|
363
|
+
...(database ? { database } : {}),
|
|
278
364
|
action: 'rows',
|
|
279
365
|
statement,
|
|
280
366
|
durationMs: result.durationMs,
|
|
@@ -285,6 +371,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
285
371
|
await record({
|
|
286
372
|
viewer: viewer.id,
|
|
287
373
|
connection: connection.name,
|
|
374
|
+
...(database ? { database } : {}),
|
|
288
375
|
action: 'rows',
|
|
289
376
|
statement,
|
|
290
377
|
durationMs: Math.round(performance.now() - started),
|
|
@@ -299,7 +386,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
299
386
|
path: '/api/query',
|
|
300
387
|
async run(request, viewer) {
|
|
301
388
|
const body = await json(request)
|
|
302
|
-
const { connection, access } = reach(viewer, body.connection)
|
|
389
|
+
const { connection, access, db, database } = reach(viewer, body.connection, body.database)
|
|
303
390
|
const sql = text(body.sql, 'sql')
|
|
304
391
|
const maxRows =
|
|
305
392
|
body.maxRows === undefined
|
|
@@ -318,7 +405,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
318
405
|
}
|
|
319
406
|
const started = performance.now()
|
|
320
407
|
try {
|
|
321
|
-
const result = await
|
|
408
|
+
const result = await db.query(sql, {
|
|
322
409
|
access,
|
|
323
410
|
maxRows,
|
|
324
411
|
timeoutMs: limits.timeoutMs,
|
|
@@ -327,6 +414,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
327
414
|
await record({
|
|
328
415
|
viewer: viewer.id,
|
|
329
416
|
connection: connection.name,
|
|
417
|
+
...(database ? { database } : {}),
|
|
330
418
|
action: 'query',
|
|
331
419
|
statement: sql,
|
|
332
420
|
durationMs: result.durationMs,
|
|
@@ -337,6 +425,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
337
425
|
await record({
|
|
338
426
|
viewer: viewer.id,
|
|
339
427
|
connection: connection.name,
|
|
428
|
+
...(database ? { database } : {}),
|
|
340
429
|
action: 'query',
|
|
341
430
|
statement: sql,
|
|
342
431
|
durationMs: Math.round(performance.now() - started),
|
|
@@ -354,7 +443,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
354
443
|
path: '/api/apply',
|
|
355
444
|
async run(request, viewer) {
|
|
356
445
|
const body = await json(request)
|
|
357
|
-
const { connection, access } = reach(viewer, body.connection)
|
|
446
|
+
const { connection, access, db, database } = reach(viewer, body.connection, body.database)
|
|
358
447
|
const target = { schema: text(body.schema, 'schema'), table: text(body.table, 'table') }
|
|
359
448
|
const changes = changesOf(body.changes)
|
|
360
449
|
const dryRun = body.dryRun === true
|
|
@@ -363,7 +452,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
363
452
|
}
|
|
364
453
|
const started = performance.now()
|
|
365
454
|
try {
|
|
366
|
-
const result = await
|
|
455
|
+
const result = await db.apply(target, changes, {
|
|
367
456
|
timeoutMs: limits.timeoutMs,
|
|
368
457
|
dryRun,
|
|
369
458
|
})
|
|
@@ -371,6 +460,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
371
460
|
await record({
|
|
372
461
|
viewer: viewer.id,
|
|
373
462
|
connection: connection.name,
|
|
463
|
+
...(database ? { database } : {}),
|
|
374
464
|
action: 'apply',
|
|
375
465
|
statement: result.statements.join(';\n'),
|
|
376
466
|
durationMs: Math.round(performance.now() - started),
|
|
@@ -383,6 +473,7 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
383
473
|
await record({
|
|
384
474
|
viewer: viewer.id,
|
|
385
475
|
connection: connection.name,
|
|
476
|
+
...(database ? { database } : {}),
|
|
386
477
|
action: 'apply',
|
|
387
478
|
statement: `${changes.length} changes to ${target.schema}.${target.table}`,
|
|
388
479
|
durationMs: Math.round(performance.now() - started),
|
|
@@ -398,12 +489,11 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
398
489
|
path: '/api/export',
|
|
399
490
|
async run(request, viewer) {
|
|
400
491
|
const body = await json(request)
|
|
401
|
-
const { connection } = reach(viewer, body.connection)
|
|
492
|
+
const { connection, db, database } = reach(viewer, body.connection, body.database)
|
|
402
493
|
const format = formatOf(body.format)
|
|
403
494
|
const page = rowsRequest({ ...body, limit: undefined, offset: undefined })
|
|
404
|
-
const opened = driver(connection)
|
|
405
495
|
const started = performance.now()
|
|
406
|
-
const batches =
|
|
496
|
+
const batches = db.export(page, { timeoutMs: limits.timeoutMs })
|
|
407
497
|
// Read the first batch before answering, so a bad table or filter is a proper error.
|
|
408
498
|
const first = await batches.next()
|
|
409
499
|
let replayed = false
|
|
@@ -419,11 +509,12 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
419
509
|
format,
|
|
420
510
|
replay,
|
|
421
511
|
page,
|
|
422
|
-
|
|
512
|
+
db.sql,
|
|
423
513
|
(rows, error) =>
|
|
424
514
|
void record({
|
|
425
515
|
viewer: viewer.id,
|
|
426
516
|
connection: connection.name,
|
|
517
|
+
...(database ? { database } : {}),
|
|
427
518
|
action: 'export',
|
|
428
519
|
statement: `${page.schema}.${page.table} as ${format}`,
|
|
429
520
|
durationMs: Math.round(performance.now() - started),
|
|
@@ -443,6 +534,42 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
443
534
|
})
|
|
444
535
|
},
|
|
445
536
|
},
|
|
537
|
+
{
|
|
538
|
+
method: 'GET',
|
|
539
|
+
path: '/api/backup-options',
|
|
540
|
+
async run(request, viewer) {
|
|
541
|
+
const params = new URL(request.url).searchParams
|
|
542
|
+
const target = reach(viewer, params.get('connection'), params.get('database'))
|
|
543
|
+
return (await backups()).options(backupContext(target, viewer))
|
|
544
|
+
},
|
|
545
|
+
},
|
|
546
|
+
...(
|
|
547
|
+
[
|
|
548
|
+
['/api/backup', 'download'],
|
|
549
|
+
['/api/restore-plan', 'plan'],
|
|
550
|
+
['/api/restore-start', 'start'],
|
|
551
|
+
['/api/restore-run', 'run'],
|
|
552
|
+
['/api/restore-discard', 'discard'],
|
|
553
|
+
] as const
|
|
554
|
+
).map(([path, action]) => ({
|
|
555
|
+
method: 'POST' as const,
|
|
556
|
+
path,
|
|
557
|
+
async run(request: Request, viewer: Viewer) {
|
|
558
|
+
const body = await json(request)
|
|
559
|
+
const target = reach(viewer, body.connection, body.database)
|
|
560
|
+
return (await backups())[action](backupContext(target, viewer), body)
|
|
561
|
+
},
|
|
562
|
+
})),
|
|
563
|
+
{
|
|
564
|
+
method: 'POST',
|
|
565
|
+
path: '/api/restore-chunk',
|
|
566
|
+
async run(request, viewer) {
|
|
567
|
+
// The body is the piece itself; the rest comes in the address.
|
|
568
|
+
const params = new URL(request.url).searchParams
|
|
569
|
+
const target = reach(viewer, params.get('connection'), params.get('database'))
|
|
570
|
+
return (await backups()).chunk(backupContext(target, viewer), request)
|
|
571
|
+
},
|
|
572
|
+
},
|
|
446
573
|
{
|
|
447
574
|
method: 'POST',
|
|
448
575
|
path: '/api/cancel',
|
|
@@ -541,8 +668,9 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
|
|
|
541
668
|
return reply(404, { error: { code: 'not-found', message: 'Not found.' } })
|
|
542
669
|
},
|
|
543
670
|
async close() {
|
|
544
|
-
const open = [...drivers.values()]
|
|
671
|
+
const open = [...drivers.values(), ...[...others.values()].flatMap((o) => [...o.values()])]
|
|
545
672
|
drivers.clear()
|
|
673
|
+
others.clear()
|
|
546
674
|
await Promise.all(open.map((d) => d.close()))
|
|
547
675
|
},
|
|
548
676
|
}
|
|
@@ -576,6 +704,26 @@ async function defaultUi(): Promise<UiAssets> {
|
|
|
576
704
|
return assets
|
|
577
705
|
}
|
|
578
706
|
|
|
707
|
+
function oneDatabase(connection: ConnectionConfig): DbAdminError {
|
|
708
|
+
return new DbAdminError(
|
|
709
|
+
`Connection "${connection.name}" opens its own database only.`,
|
|
710
|
+
400,
|
|
711
|
+
'one-database',
|
|
712
|
+
)
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/** A database's name as PostgreSQL takes it: up to 63 bytes, with no NUL. */
|
|
716
|
+
function databaseName(value: unknown): string {
|
|
717
|
+
if (
|
|
718
|
+
typeof value !== 'string' ||
|
|
719
|
+
value.includes('\0') ||
|
|
720
|
+
new TextEncoder().encode(value).length > MAX_DATABASE_NAME
|
|
721
|
+
) {
|
|
722
|
+
throw bad('"database" is a database’s name.')
|
|
723
|
+
}
|
|
724
|
+
return value
|
|
725
|
+
}
|
|
726
|
+
|
|
579
727
|
function accessOf(viewer: Viewer, connection: ConnectionConfig): Access | null {
|
|
580
728
|
const granted = viewer.access ? viewer.access(connection) : connection.access
|
|
581
729
|
if (!granted) return null
|
package/src/index.ts
CHANGED
|
@@ -18,3 +18,9 @@ export {
|
|
|
18
18
|
export { ROUTES } from './routes.ts'
|
|
19
19
|
export { renderAsset, renderIndex, type UiAssets, type UiConfig } from './ui.ts'
|
|
20
20
|
export type * from './types.ts'
|
|
21
|
+
// Types only: the backup code itself loads on the first backup or restore.
|
|
22
|
+
export type { BackupOptions } from './backup/api.ts'
|
|
23
|
+
export type { SchemaChoice } from './backup/dump.ts'
|
|
24
|
+
export type { BackupHeader, BackupSummary } from './backup/format.ts'
|
|
25
|
+
export type { PgTool } from './backup/pg-tools.ts'
|
|
26
|
+
export type { RestorePlan, RestoreResult } from './backup/restore.ts'
|
package/src/types.ts
CHANGED
|
@@ -20,6 +20,12 @@ export interface ConnectionConfig {
|
|
|
20
20
|
tag?: ConnectionTag
|
|
21
21
|
/** Shown wherever people run SQL on it, such as what a heavy statement does to the host. */
|
|
22
22
|
warning?: string
|
|
23
|
+
/**
|
|
24
|
+
* Which of its server's databases it opens, where a connection opens one database at a time
|
|
25
|
+
* (PostgreSQL): `all`, the default, every one its login may connect to, the URL's first; `one`,
|
|
26
|
+
* the URL's only, for a login with more privileges than the tool should show.
|
|
27
|
+
*/
|
|
28
|
+
databases?: 'all' | 'one'
|
|
23
29
|
}
|
|
24
30
|
|
|
25
31
|
/** A connection's environment, as a color: production red, staging orange, and so on. */
|
|
@@ -36,6 +42,16 @@ export interface Capabilities {
|
|
|
36
42
|
* runs on the host's own thread.
|
|
37
43
|
*/
|
|
38
44
|
cancel: boolean
|
|
45
|
+
/**
|
|
46
|
+
* The server's other databases open from the connection, by name. The API sets it: a driver
|
|
47
|
+
* offers them with `databases()` and `withDatabase()`, and a connection may be pinned to its own.
|
|
48
|
+
*/
|
|
49
|
+
databases?: boolean
|
|
50
|
+
/**
|
|
51
|
+
* Whole-database backups and restores: PostgreSQL and PGlite. The API sets it: a driver offers
|
|
52
|
+
* them with `session()`.
|
|
53
|
+
*/
|
|
54
|
+
backup?: boolean
|
|
39
55
|
}
|
|
40
56
|
|
|
41
57
|
/** What a schema-tree entry is: SQLite and MySQL have tables and views, PostgreSQL the rest too. */
|
|
@@ -195,6 +211,14 @@ export interface ServerInfo {
|
|
|
195
211
|
user: string
|
|
196
212
|
}
|
|
197
213
|
|
|
214
|
+
/** The databases a connection's login may open on its server, for the database picker. */
|
|
215
|
+
export interface DatabaseList {
|
|
216
|
+
/** The one the driver opened. */
|
|
217
|
+
current: string
|
|
218
|
+
/** By name, the current one among them. */
|
|
219
|
+
databases: string[]
|
|
220
|
+
}
|
|
221
|
+
|
|
198
222
|
/** How many rows one statement may send back, and how long it may run. */
|
|
199
223
|
export interface Limits {
|
|
200
224
|
/** Rows sent back at most; the rest are cut, and the result says so. */
|
|
@@ -242,9 +266,42 @@ export interface Driver {
|
|
|
242
266
|
readonly sql: SqlDialect
|
|
243
267
|
/** One statement. */
|
|
244
268
|
query(sql: string, options: QueryOptions): Promise<QueryResult>
|
|
269
|
+
/**
|
|
270
|
+
* The server's databases its login may open, where a connection opens one at a time
|
|
271
|
+
* (PostgreSQL). Absent where it has one (SQLite) or shows the rest as schemas (MySQL).
|
|
272
|
+
*/
|
|
273
|
+
databases?(): Promise<DatabaseList>
|
|
274
|
+
/**
|
|
275
|
+
* A driver for another of the server's databases, with the same login and settings. It connects
|
|
276
|
+
* on first use; whoever asked for it closes it.
|
|
277
|
+
*/
|
|
278
|
+
withDatabase?(name: string): Driver
|
|
279
|
+
/**
|
|
280
|
+
* One transaction on a connection of its own, for a backup (`snapshot`: read-only, all of it as
|
|
281
|
+
* of one moment) or a restore (`write`: all of it or none). PostgreSQL and PGlite.
|
|
282
|
+
*/
|
|
283
|
+
session?(mode: 'snapshot' | 'write'): Promise<Session>
|
|
284
|
+
/**
|
|
285
|
+
* The URL pg_dump and pg_restore may connect with: a server's driver has one, PGlite's (a
|
|
286
|
+
* database in the host's own process) doesn't.
|
|
287
|
+
*/
|
|
288
|
+
readonly pgUrl?: string
|
|
245
289
|
close(): Promise<void>
|
|
246
290
|
}
|
|
247
291
|
|
|
292
|
+
/** A backup's or a restore's transaction. Values come back as the server's text. */
|
|
293
|
+
export interface Session {
|
|
294
|
+
/** One statement, its values as $1, $2… (a Uint8Array as bytea). */
|
|
295
|
+
query(sql: string, values?: unknown[]): Promise<{ rows: (string | null)[][] }>
|
|
296
|
+
/** Commits (a restore) or rolls back (a backup), then lets the connection go. */
|
|
297
|
+
end(commit: boolean): Promise<void>
|
|
298
|
+
/**
|
|
299
|
+
* It holds the host while open: PGlite runs in the host's process, one transaction at a time.
|
|
300
|
+
* Finish quickly, without waiting on a slow download.
|
|
301
|
+
*/
|
|
302
|
+
readonly exclusive: boolean
|
|
303
|
+
}
|
|
304
|
+
|
|
248
305
|
/** Who is asking, as the host's `authorize()` says. */
|
|
249
306
|
export interface Viewer {
|
|
250
307
|
/** Recorded in the audit log, such as a user id or an email. */
|
|
@@ -261,7 +318,9 @@ export interface AuditEvent {
|
|
|
261
318
|
at: string
|
|
262
319
|
viewer: string
|
|
263
320
|
connection: string
|
|
264
|
-
|
|
321
|
+
/** The database it ran on, when it wasn't the connection's own. */
|
|
322
|
+
database?: string
|
|
323
|
+
action: 'query' | 'rows' | 'count' | 'apply' | 'export' | 'cancel' | 'backup' | 'restore'
|
|
265
324
|
/** The SQL run, or for `rows`, the table read. */
|
|
266
325
|
statement: string
|
|
267
326
|
durationMs: number
|