dbgate-sqlite-dumper 0.1.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.
@@ -0,0 +1,1893 @@
1
+ import { a as SqliteConnectionInput, A as AcquiredSqliteConnection, S as SqliteConnection, b as SqliteExecResult, c as SqliteRow, d as SqliteErrorInfo } from './types-CTyJTzB6.js';
2
+ export { e as SqliteColumnValue, f as SqliteConnectionSource, g as SqliteParameterValue, h as SqliteQuery, i as SqliteQueryResult, j as SqliteStreamOptions, k as isSqliteConnectionSource } from './types-CTyJTzB6.js';
3
+ import { Writable, Readable } from 'node:stream';
4
+
5
+ /**
6
+ * Normalizes a {@link SqliteConnectionInput} into an acquired connection with
7
+ * a release callback. A direct connection resolves immediately with a no-op
8
+ * release and `dedicated: false` (the caller may be sharing it); a source is
9
+ * asked for one handle through its own `acquire()`, which is what snapshot
10
+ * consistency requires.
11
+ */
12
+ declare function acquireSqliteConnection(input: SqliteConnectionInput, signal?: AbortSignal): Promise<AcquiredSqliteConnection>;
13
+ /** Runs one statement through `execute()` when the adapter has it, else through `query()`. */
14
+ declare function executeStatement(connection: SqliteConnection, sql: string, signal?: AbortSignal): Promise<SqliteExecResult>;
15
+ /**
16
+ * Coerces an integer-valued catalog cell to a JavaScript number.
17
+ *
18
+ * Adapters may return SQLite `INTEGER`s as `number` or `bigint`; catalog
19
+ * values (column positions, flags, `user_version`) always fit in a double,
20
+ * so either shape is accepted here.
21
+ */
22
+ declare function toNumber(value: unknown, fallback?: number): number;
23
+ /** Coerces a text-valued catalog cell to a string, or `null` for SQL `NULL`. */
24
+ declare function toText(value: unknown): string | null;
25
+
26
+ /**
27
+ * How a dump obtains a consistent view of the database.
28
+ *
29
+ * - `'snapshot'` (default) — opens a read transaction (as a `SAVEPOINT`, see
30
+ * below) and performs one read inside it before anything else, so every
31
+ * table is read from the same state of the file. In WAL mode that is a
32
+ * true snapshot and writers carry on unblocked; in rollback-journal mode
33
+ * the transaction holds a `SHARED` lock, which keeps writers out until the
34
+ * dump finishes. Either way the result is consistent — it is the same
35
+ * mechanism the native `.dump` uses (`SAVEPOINT dump`).
36
+ * - `'none'` — no transaction; each statement reads whatever is committed
37
+ * when it runs. Only safe when nothing else writes to the database.
38
+ */
39
+ type SqliteConsistencyMode = 'snapshot' | 'none';
40
+ interface SqliteDumpSessionOptions {
41
+ readonly consistency?: SqliteConsistencyMode;
42
+ }
43
+ interface SqliteDumpSession {
44
+ readonly consistency: SqliteConsistencyMode;
45
+ /**
46
+ * `true` when the handle was already inside a transaction the caller
47
+ * opened, so the dump reads within *their* transaction and sees their
48
+ * uncommitted changes. Reported so a caller can tell.
49
+ */
50
+ readonly joinedExistingTransaction: boolean;
51
+ /**
52
+ * Ends the read transaction. Idempotent. Never throws for a handle that is
53
+ * already closed — cleanup must not mask the error that caused it.
54
+ */
55
+ finish(): Promise<void>;
56
+ }
57
+ /**
58
+ * Opens the dump's read session.
59
+ *
60
+ * A `SAVEPOINT` rather than `BEGIN`: outside a transaction the two are the
61
+ * same (a savepoint then starts a deferred transaction), but inside one a
62
+ * `BEGIN` fails while a savepoint nests. A caller who is already in a
63
+ * transaction therefore gets a dump of what *they* see instead of an error.
64
+ *
65
+ * A deferred transaction does not take its read lock until the first read,
66
+ * so the session performs one immediately — otherwise the snapshot would be
67
+ * taken lazily by whichever catalog query happened to come first, which is
68
+ * the same thing but leaves the guarantee to an accident of ordering.
69
+ */
70
+ declare function beginSqliteDumpSession(connection: SqliteConnection, options?: SqliteDumpSessionOptions, signal?: AbortSignal): Promise<SqliteDumpSession>;
71
+
72
+ /** Normalized SQLite library version. */
73
+ interface SqliteVersion {
74
+ /** Raw `sqlite_version()` string, e.g. `"3.45.1"`. */
75
+ readonly versionString: string;
76
+ readonly majorVersion: number;
77
+ readonly minorVersion: number;
78
+ readonly patchVersion: number;
79
+ /**
80
+ * The numeric form SQLite itself uses for `SQLITE_VERSION_NUMBER`:
81
+ * `major * 1000000 + minor * 1000 + patch`. `3045001` for 3.45.1.
82
+ */
83
+ readonly versionNumber: number;
84
+ /** `sqlite_source_id()`, identifying the exact check-in, when available. */
85
+ readonly sourceId?: string;
86
+ }
87
+ /**
88
+ * Capabilities derived once from {@link SqliteVersion}. These describe what
89
+ * the SQLite library behind a handle understands; they are used both for the
90
+ * source (which catalog pragmas introspection may use) and, through
91
+ * `compatibility/`, for a restore target (what DDL it can accept).
92
+ */
93
+ interface SqliteCapabilities {
94
+ /** `WITHOUT ROWID` tables; 3.8.2+. */
95
+ readonly supportsWithoutRowid: boolean;
96
+ /** Multi-row `INSERT ... VALUES (...), (...)`; 3.7.11+. */
97
+ readonly supportsMultiRowValues: boolean;
98
+ /** Table-valued pragma functions (`pragma_table_info(...)`); 3.16.0+. */
99
+ readonly supportsPragmaFunctions: boolean;
100
+ /** `PRAGMA table_xinfo`, which reports hidden and generated columns; 3.26.0+. */
101
+ readonly supportsTableXinfo: boolean;
102
+ /** Generated (`GENERATED ALWAYS AS`) columns; 3.31.0+. */
103
+ readonly supportsGeneratedColumns: boolean;
104
+ /** The `sqlite_schema` alias for `sqlite_master`; 3.33.0+. */
105
+ readonly supportsSqliteSchemaAlias: boolean;
106
+ /** `PRAGMA writable_schema=RESET`; 3.35.0+. */
107
+ readonly supportsWritableSchemaReset: boolean;
108
+ /** `STRICT` tables; 3.37.0+. */
109
+ readonly supportsStrictTables: boolean;
110
+ /** `PRAGMA table_list`, which reports `WITHOUT ROWID`, `STRICT` and shadow tables; 3.37.0+. */
111
+ readonly supportsTableList: boolean;
112
+ }
113
+ /**
114
+ * Parses a `sqlite_version()` string. Only the leading `major.minor.patch`
115
+ * is interpreted; anything after it is kept verbatim for reporting.
116
+ */
117
+ declare function parseSqliteVersion(versionString: string): {
118
+ majorVersion: number;
119
+ minorVersion: number;
120
+ patchVersion: number;
121
+ versionNumber: number;
122
+ };
123
+
124
+ /**
125
+ * Detects the SQLite library version behind a handle.
126
+ *
127
+ * This is the version of the library the *driver* links, which is not
128
+ * necessarily the version of the `sqlite3` command-line shell installed on
129
+ * the same machine — `better-sqlite3`, for instance, bundles its own. The
130
+ * difference matters for one thing in a dump: `REAL` values are rendered by
131
+ * SQLite's own `printf`, whose digit generation changed between releases.
132
+ */
133
+ declare function detectSqliteVersion(connection: SqliteConnection, signal?: AbortSignal): Promise<SqliteVersion>;
134
+
135
+ /**
136
+ * Derives {@link SqliteCapabilities} from a detected {@link SqliteVersion}.
137
+ *
138
+ * Gating is by `versionNumber` (`major*1000000 + minor*1000 + patch`), so a
139
+ * capability is gated at the exact release that shipped it. Each gate is the
140
+ * release named in SQLite's own change log for that feature.
141
+ */
142
+ declare function detectSqliteCapabilities(version: SqliteVersion): SqliteCapabilities;
143
+
144
+ type SqliteObjectKind = 'database' | 'table' | 'virtualTable' | 'column' | 'index' | 'view' | 'trigger' | 'foreignKey';
145
+ /** Identifies the object a diagnostic is about. */
146
+ interface SqliteObjectReference {
147
+ readonly kind: SqliteObjectKind;
148
+ /** Schema the object lives in (`main`, or an attached database's name). */
149
+ readonly schemaName: string;
150
+ readonly name: string;
151
+ /** Owning table, for columns, indexes, triggers and foreign keys. */
152
+ readonly parentName?: string;
153
+ }
154
+ type SqliteDiagnosticSeverity = 'info' | 'warning' | 'error';
155
+ /**
156
+ * A structured diagnostic surfaced by introspection, archive planning,
157
+ * rendering, data export or restore. Diagnostics are never thrown as
158
+ * exceptions for recoverable conditions; callers inspect them explicitly
159
+ * instead of parsing log text.
160
+ */
161
+ interface SqliteDiagnostic {
162
+ readonly severity: SqliteDiagnosticSeverity;
163
+ /** Stable machine-readable identifier, e.g. `"user-version-not-dumped"`. */
164
+ readonly code: string;
165
+ readonly message: string;
166
+ readonly objectReference?: SqliteObjectReference;
167
+ }
168
+
169
+ /**
170
+ * The normalized SQLite schema model.
171
+ *
172
+ * SQLite stores every schema object's DDL verbatim in `sqlite_schema.sql`,
173
+ * and that text — not a reconstruction from the column model — is what a
174
+ * dump emits, exactly as the native `.dump` does. The structured fields
175
+ * exist for everything else: archive planning, selection, data export
176
+ * column lists, compatibility checks and diagnostics.
177
+ */
178
+ /** What kind of table a `type = 'table'` row of `sqlite_schema` is. */
179
+ type SqliteTableKind =
180
+ /** An ordinary table. */
181
+ 'table'
182
+ /** `CREATE VIRTUAL TABLE ... USING module(...)`. */
183
+ | 'virtual'
184
+ /** A table a virtual table module created to store its own data (`ft_data`, `rt_node`, ...). */
185
+ | 'shadow'
186
+ /** `sqlite_sequence`, `sqlite_stat1`, `sqlite_stat4`, and any other `sqlite_` table. */
187
+ | 'system';
188
+ /**
189
+ * `hidden` as `PRAGMA table_xinfo` reports it: `0` an ordinary column,
190
+ * `1` a hidden column of a virtual table, `2` a `VIRTUAL` generated column,
191
+ * `3` a `STORED` generated column.
192
+ */
193
+ type SqliteColumnHidden = 0 | 1 | 2 | 3;
194
+ interface SqliteColumn {
195
+ /** 0-based position, as `PRAGMA table_xinfo` numbers it (`cid`). */
196
+ readonly cid: number;
197
+ readonly name: string;
198
+ /** The declared type exactly as written (`VARCHAR(20)`, `INTEGER`, or `''` for none). */
199
+ readonly declaredType: string;
200
+ readonly notNull: boolean;
201
+ /** Default value expression text as written, or `null` for none. */
202
+ readonly defaultValue: string | null;
203
+ /** 1-based position within the primary key, `0` when not part of it. */
204
+ readonly primaryKeyPosition: number;
205
+ readonly hidden: SqliteColumnHidden;
206
+ readonly generated: 'none' | 'virtual' | 'stored';
207
+ }
208
+ interface SqliteTable {
209
+ readonly name: string;
210
+ readonly kind: SqliteTableKind;
211
+ /** `rowid` of this table's row in `sqlite_schema`; native dump order is by it. */
212
+ readonly schemaRowid: number;
213
+ /** Verbatim `sqlite_schema.sql`. */
214
+ readonly sql: string;
215
+ readonly withoutRowid: boolean;
216
+ readonly strict: boolean;
217
+ readonly hasAutoincrement: boolean;
218
+ /** For a virtual table, the module named in `USING` (`fts5`, `rtree`, ...). */
219
+ readonly virtualModule?: string;
220
+ /** For a shadow table, the virtual table that owns it. */
221
+ readonly ownerVirtualTable?: string;
222
+ /**
223
+ * The column that aliases the rowid (`INTEGER PRIMARY KEY`), or `null`
224
+ * when the table has a separate, hidden rowid — the case in which a plain
225
+ * dump renumbers rows, and `preserveRowids` exists to prevent that. Always
226
+ * `null` for a `WITHOUT ROWID` table.
227
+ */
228
+ readonly rowidAliasColumn: string | null;
229
+ /** Columns in `cid` order, including hidden and generated ones. */
230
+ readonly columns: readonly SqliteColumn[];
231
+ }
232
+ interface SqliteIndexColumn {
233
+ /** Column name, or `null` for an expression key part. */
234
+ readonly name: string | null;
235
+ readonly cid: number;
236
+ readonly descending: boolean;
237
+ readonly collation: string | null;
238
+ }
239
+ interface SqliteIndex {
240
+ readonly name: string;
241
+ readonly tableName: string;
242
+ readonly schemaRowid: number;
243
+ /**
244
+ * Verbatim `CREATE INDEX` text, or `null` for an automatic index SQLite
245
+ * built for a `UNIQUE`/`PRIMARY KEY` constraint. Those carry no DDL of
246
+ * their own: they are recreated by the table's `CREATE TABLE`.
247
+ */
248
+ readonly sql: string | null;
249
+ readonly isUnique: boolean;
250
+ /** `'c'` created by `CREATE INDEX`, `'u'` a `UNIQUE` constraint, `'pk'` a `PRIMARY KEY`. */
251
+ readonly origin: 'c' | 'u' | 'pk';
252
+ readonly isPartial: boolean;
253
+ /** Key columns only, in index order. */
254
+ readonly columns: readonly SqliteIndexColumn[];
255
+ }
256
+ interface SqliteView {
257
+ readonly name: string;
258
+ readonly schemaRowid: number;
259
+ readonly sql: string;
260
+ }
261
+ interface SqliteTrigger {
262
+ readonly name: string;
263
+ /** The table (or, for `INSTEAD OF`, view) the trigger is attached to. */
264
+ readonly tableName: string;
265
+ readonly schemaRowid: number;
266
+ readonly sql: string;
267
+ }
268
+ interface SqliteForeignKeyColumn {
269
+ readonly from: string;
270
+ /** Referenced column, or `null` when the constraint names only the table (its primary key). */
271
+ readonly to: string | null;
272
+ }
273
+ interface SqliteForeignKey {
274
+ readonly tableName: string;
275
+ /** `PRAGMA foreign_key_list` id; unique per table. */
276
+ readonly id: number;
277
+ readonly referencedTableName: string;
278
+ readonly columns: readonly SqliteForeignKeyColumn[];
279
+ readonly onUpdate: string;
280
+ readonly onDelete: string;
281
+ readonly match: string;
282
+ }
283
+ /** One row of `sqlite_sequence`: an `AUTOINCREMENT` table's high-water mark. */
284
+ interface SqliteSequence {
285
+ readonly tableName: string;
286
+ /** Read as text so a value past 2^53 is carried exactly. */
287
+ readonly value: string;
288
+ }
289
+ interface SqliteDatabase {
290
+ /** The schema that was introspected: `main`, or an attached database's name. */
291
+ readonly schemaName: string;
292
+ /** `PRAGMA encoding`: `UTF-8`, `UTF-16le` or `UTF-16be`. */
293
+ readonly encoding: string;
294
+ /** `PRAGMA user_version`, which applications use for their own migrations. */
295
+ readonly userVersion: number;
296
+ /** `PRAGMA application_id`. */
297
+ readonly applicationId: number;
298
+ readonly pageSize?: number;
299
+ readonly tables: readonly SqliteTable[];
300
+ readonly indexes: readonly SqliteIndex[];
301
+ readonly views: readonly SqliteView[];
302
+ readonly triggers: readonly SqliteTrigger[];
303
+ readonly foreignKeys: readonly SqliteForeignKey[];
304
+ readonly sequences: readonly SqliteSequence[];
305
+ }
306
+
307
+ /**
308
+ * Caller-facing object selection.
309
+ *
310
+ * Names are exact SQLite identifiers: they are matched against the names in
311
+ * `sqlite_schema` and are never treated as wildcard patterns (unlike the
312
+ * native `.dump ?PATTERN?`, which takes a `LIKE` pattern).
313
+ *
314
+ * **Case sensitivity** follows SQLite's own rule for identifiers: ASCII
315
+ * letters compare case-insensitively (`Orders` and `orders` are the same
316
+ * table), and nothing else is folded.
317
+ */
318
+ interface DumpSelection {
319
+ /** Exact table names to include. When omitted, all non-excluded tables are included. */
320
+ readonly tables?: readonly string[];
321
+ /** Exact table names to exclude, applied after {@link tables}. */
322
+ readonly excludeTables?: readonly string[];
323
+ /** Exact view names to include. When omitted, all non-excluded views are included. */
324
+ readonly views?: readonly string[];
325
+ readonly excludeViews?: readonly string[];
326
+ /**
327
+ * Exact trigger names to include. A trigger is dumped only when the table
328
+ * (or view) it is attached to is dumped too.
329
+ */
330
+ readonly triggers?: readonly string[];
331
+ readonly excludeTriggers?: readonly string[];
332
+ /**
333
+ * Exact index names to exclude. Indexes otherwise follow their table: a
334
+ * selected table brings every index defined on it.
335
+ */
336
+ readonly excludeIndexes?: readonly string[];
337
+ /**
338
+ * Tables whose *structure* is dumped but whose rows are not. Useful for
339
+ * large log or cache tables. A table excluded through
340
+ * {@link excludeTables} is omitted entirely instead.
341
+ */
342
+ readonly dataExcludedTables?: readonly string[];
343
+ }
344
+ /**
345
+ * Which object kinds participate in the dump at all, independent of the
346
+ * per-name filters in {@link DumpSelection}. All default to `true`, which is
347
+ * what the native `.dump` includes.
348
+ */
349
+ interface DumpObjectKinds {
350
+ readonly includeTables?: boolean;
351
+ readonly includeViews?: boolean;
352
+ readonly includeIndexes?: boolean;
353
+ readonly includeTriggers?: boolean;
354
+ /**
355
+ * Virtual tables (`CREATE VIRTUAL TABLE ... USING fts5(...)`) and the
356
+ * shadow tables that hold their data.
357
+ */
358
+ readonly includeVirtualTables?: boolean;
359
+ /**
360
+ * `sqlite_sequence` (the `AUTOINCREMENT` counters) and the `sqlite_stat*`
361
+ * tables `ANALYZE` maintains. The native `.dump --nosys` turns this off.
362
+ */
363
+ readonly includeSystemTables?: boolean;
364
+ }
365
+ interface NormalizedDumpSelection {
366
+ readonly tables?: ReadonlySet<string>;
367
+ readonly excludeTables: ReadonlySet<string>;
368
+ readonly views?: ReadonlySet<string>;
369
+ readonly excludeViews: ReadonlySet<string>;
370
+ readonly triggers?: ReadonlySet<string>;
371
+ readonly excludeTriggers: ReadonlySet<string>;
372
+ readonly excludeIndexes: ReadonlySet<string>;
373
+ readonly dataExcludedTables: ReadonlySet<string>;
374
+ /** `true` when any filter at all was given, i.e. the dump may be a subset of the database. */
375
+ readonly isPartial: boolean;
376
+ }
377
+
378
+ /** Folds a name the way SQLite compares identifiers: ASCII letters only. */
379
+ declare function foldSqliteName(name: string): string;
380
+ declare function normalizeDumpSelection(selection?: DumpSelection): NormalizedDumpSelection;
381
+ declare function isTableSelected(name: string, selection: NormalizedDumpSelection): boolean;
382
+ declare function isViewSelected(name: string, selection: NormalizedDumpSelection): boolean;
383
+ declare function isTriggerSelected(name: string, selection: NormalizedDumpSelection): boolean;
384
+ declare function isIndexSelected(name: string, selection: NormalizedDumpSelection): boolean;
385
+ /** True when the table's *rows* should be skipped while its structure is still dumped. */
386
+ declare function isTableDataExcluded(name: string, selection: NormalizedDumpSelection): boolean;
387
+
388
+ /** True when `name` is an SQLite keyword, compared case-insensitively as SQLite does. */
389
+ declare function isSqliteKeyword(name: string): boolean;
390
+ /** The number of keywords known to {@link isSqliteKeyword}; exported for tests. */
391
+ declare const SQLITE_KEYWORD_COUNT: number;
392
+ /**
393
+ * Upper-cases ASCII letters only, which is how SQLite compares identifiers
394
+ * and keywords: its case folding is ASCII-only (`sqlite3UpperToLower`), so
395
+ * `ß` and `Dž` are never folded and a locale-aware `toUpperCase()` would
396
+ * disagree with the engine.
397
+ */
398
+ declare function toAsciiUpperCase(value: string): string;
399
+ /** Lower-cases ASCII letters only; see {@link toAsciiUpperCase}. */
400
+ declare function toAsciiLowerCase(value: string): string;
401
+ /**
402
+ * Whether the native shell would quote `name`, and with what — a port of
403
+ * `quoteChar()` from SQLite's `shell.c`:
404
+ *
405
+ * ```c
406
+ * if( !IsAlpha(zName[0]) && zName[0]!='_' ) return '"';
407
+ * for(i=0; zName[i]; i++){
408
+ * if( !IsAlnum(zName[i]) && zName[i]!='_' ) return '"';
409
+ * }
410
+ * return sqlite3_keyword_check(zName, i) ? '"' : 0;
411
+ * ```
412
+ *
413
+ * `IsAlpha`/`IsAlnum` are the C-locale classifications, so any non-ASCII
414
+ * character forces quoting.
415
+ */
416
+ declare function needsIdentifierQuoting(name: string): boolean;
417
+ /**
418
+ * Double-quotes an identifier, doubling any embedded `"`. Always quotes.
419
+ *
420
+ * Used for every query this package *runs*. Quoting unconditionally there
421
+ * removes the whole question of which words are reserved in which SQLite
422
+ * release; the output-shaping decision, where the native layout matters, is
423
+ * {@link quoteIdentifierIfNeeded}.
424
+ */
425
+ declare function quoteIdentifier(name: string): string;
426
+ /**
427
+ * Quotes an identifier exactly when the native `.dump` would
428
+ * ({@link needsIdentifierQuoting}), so `INSERT INTO t` stays unquoted while
429
+ * `INSERT INTO "order"` and `INSERT INTO "a b"` are quoted.
430
+ */
431
+ declare function quoteIdentifierIfNeeded(name: string): string;
432
+ /** `"schema"."name"`, for queries against an attached database. */
433
+ declare function quoteQualifiedIdentifier(schemaName: string, name: string): string;
434
+
435
+ /**
436
+ * SQL literal rendering, ported from the functions SQLite's own shell uses
437
+ * for `.dump` (`shell.c`), so a value renders exactly as `sqlite3` renders
438
+ * it.
439
+ *
440
+ * SQLite string literals have exactly one escape: a `'` inside the literal
441
+ * is doubled. There are **no** backslash escapes — `'\n'` is a backslash
442
+ * followed by the letter `n` — which is why the shell cannot write a newline
443
+ * as `\n` and instead wraps the literal in a `replace()` call (see
444
+ * {@link renderEscapedStringLiteral}).
445
+ *
446
+ * Every function here works on a JavaScript string in which each code unit
447
+ * may be either a real character or — for text that is not valid UTF-8 — one
448
+ * byte (a `latin1` "byte string"). The characters the escaping reacts to
449
+ * (`'`, `\n`, `\r`) are ASCII, and no byte of a multi-byte UTF-8 sequence can
450
+ * be mistaken for one, so the same code is correct for both representations.
451
+ */
452
+ /**
453
+ * `output_quoted_string()`: `'...'` with every `'` doubled, newlines and
454
+ * carriage returns written raw. The shell uses this form under
455
+ * `.dump --newlines`.
456
+ */
457
+ declare function renderQuotedStringLiteral(text: string): string;
458
+ /**
459
+ * `output_quoted_escaped_string()`: the form the native `.dump` uses by
460
+ * default.
461
+ *
462
+ * A literal containing neither `\n` nor `\r` is written as a plain quoted
463
+ * string. Otherwise each newline is replaced by a placeholder that does not
464
+ * otherwise occur in the text (`\n`, else `\012`, else `(\n0)`, ...) and the
465
+ * literal is wrapped in `replace(..., '<placeholder>', char(10))` — and the
466
+ * same for carriage returns with `char(13)` — so that the dump keeps one
467
+ * statement per line and survives any tool that normalizes line endings.
468
+ *
469
+ * ```sql
470
+ * replace('line one\nline two','\n',char(10))
471
+ * replace(replace('a\r\nb','\r',char(13)),'\n',char(10))
472
+ * ```
473
+ */
474
+ declare function renderEscapedStringLiteral(text: string): string;
475
+ type TextLiteralStyle = 'escaped' | 'raw-newlines';
476
+ /**
477
+ * Renders a `TEXT` value as a SQL expression.
478
+ *
479
+ * SQLite text may contain `NUL` characters, which the native shell cannot
480
+ * represent at all: it handles values as C strings, so everything after the
481
+ * first `NUL` is silently dropped from the dump. This package keeps them,
482
+ * joining the pieces with `||char(0)||` — an expression that evaluates to
483
+ * the identical value in a database of any text encoding. Text with no
484
+ * `NUL`, which is all text in practice, renders exactly as the shell renders
485
+ * it.
486
+ */
487
+ declare function renderTextLiteral(text: string, style?: TextLiteralStyle): string;
488
+ /**
489
+ * `output_hex_blob()`: `X'...'` in lower-case hexadecimal, which is how the
490
+ * native `.dump` writes every `BLOB`. An empty blob is `X''`.
491
+ */
492
+ declare function renderBlobLiteral(value: Uint8Array): string;
493
+ /**
494
+ * Renders a string as a plain single-quoted SQL literal, for text this
495
+ * package composes itself (table names in `INSERT INTO sqlite_schema ...`,
496
+ * `sqlite_sequence` filters).
497
+ */
498
+ declare function quoteStringLiteral(text: string): string;
499
+
500
+ declare function redactSecrets(text: string): string;
501
+
502
+ /**
503
+ * Incremental output sink for rendered dump text.
504
+ *
505
+ * `write` accepts a `Buffer` as well as a `string` because a SQLite dump is
506
+ * not necessarily valid UTF-8. SQLite does not validate the encoding of the
507
+ * text it stores, and the native `.dump` command writes a `TEXT` value's
508
+ * bytes out exactly as stored — so a value holding bytes that are not valid
509
+ * UTF-8 produces a dump line that is not valid UTF-8 either. Routing those
510
+ * bytes through a JavaScript string would replace every invalid sequence
511
+ * with U+FFFD and silently corrupt the data, so that path hands the writer a
512
+ * `Buffer` instead.
513
+ *
514
+ * Implementations never close the underlying resource; callers own its
515
+ * lifecycle.
516
+ */
517
+ interface DumpWriter {
518
+ /** Writes one chunk, resolving once it is safe to write again (respects backpressure). */
519
+ write(chunk: string | Buffer, signal?: AbortSignal): Promise<void>;
520
+ /** Total bytes written so far. */
521
+ readonly bytesWritten: number;
522
+ }
523
+
524
+ /**
525
+ * Writes incrementally to a caller-owned `Writable`, honoring backpressure
526
+ * (awaiting the stream's own `drain` when `write()` returns `false`) and
527
+ * `AbortSignal` cancellation. Never calls `end()`/`close()` on the stream.
528
+ *
529
+ * `Buffer` chunks are written verbatim; `string` chunks are encoded as
530
+ * UTF-8. See {@link DumpWriter} for why both shapes exist.
531
+ */
532
+ declare class StreamDumpWriter implements DumpWriter {
533
+ private readonly stream;
534
+ private bytes;
535
+ private writeError;
536
+ constructor(stream: Writable);
537
+ get bytesWritten(): number;
538
+ write(chunk: string | Buffer, signal?: AbortSignal): Promise<void>;
539
+ }
540
+
541
+ /**
542
+ * In-memory {@link DumpWriter}, for tests and bounded previews. Not for
543
+ * production dump sizes.
544
+ *
545
+ * Accumulates `Buffer`s rather than strings so a dump containing text that
546
+ * is not valid UTF-8 round-trips byte-exactly; {@link toString} is a
547
+ * convenience for the common all-text case and will replace invalid UTF-8
548
+ * with U+FFFD, so use {@link toBuffer} when binary fidelity matters.
549
+ */
550
+ declare class BufferDumpWriter implements DumpWriter {
551
+ private readonly chunks;
552
+ private bytes;
553
+ get bytesWritten(): number;
554
+ write(chunk: string | Buffer, signal?: AbortSignal): Promise<void>;
555
+ toBuffer(): Buffer;
556
+ toString(): string;
557
+ }
558
+
559
+ /**
560
+ * Every kind of entry the archive planner can produce.
561
+ *
562
+ * These map one-to-one onto what the native `.dump` writes:
563
+ *
564
+ * - `table` — a table's structure: its verbatim `CREATE TABLE`, or for the
565
+ * two system tables the statement that prepares them
566
+ * (`DELETE FROM sqlite_sequence;`, `ANALYZE sqlite_schema;`).
567
+ * - `tableData` — the table's rows, as `INSERT` statements.
568
+ * - `virtualTable` — a `CREATE VIRTUAL TABLE`, recreated the way the native
569
+ * `.dump` recreates it: by inserting its row into `sqlite_schema` under
570
+ * `PRAGMA writable_schema=ON`, *without* running the module's
571
+ * constructor. Its data lives in its shadow tables, which are ordinary
572
+ * `table`/`tableData` entries of their own — that is what makes the
573
+ * restored index byte-identical to the source instead of rebuilt.
574
+ * - `index`, `trigger`, `view` — verbatim DDL, after all table data.
575
+ */
576
+ type ArchiveObjectType = 'table' | 'tableData' | 'virtualTable' | 'index' | 'trigger' | 'view';
577
+ /**
578
+ * Emission sections, in output order. They mirror the two passes the native
579
+ * `.dump` makes over `sqlite_schema`:
580
+ *
581
+ * 1. `tables` — every table, in `sqlite_schema` rowid order (creation
582
+ * order), each immediately followed by its rows, with `sqlite_sequence`
583
+ * moved last so the `AUTOINCREMENT` counters are set *after* the inserts
584
+ * that would otherwise advance them.
585
+ * 2. `schema` — indexes, triggers and views, in `sqlite_schema` rowid order.
586
+ * After the data on purpose: an index built once over loaded rows is
587
+ * faster than one maintained row by row, and a trigger created before
588
+ * the load would fire once per inserted row.
589
+ */
590
+ type DumpSection = 'tables' | 'schema';
591
+ /**
592
+ * `hard`: the restore fails, or produces a wrong result, if the order is
593
+ * violated. `preference`: the order is meaningful but a violation is
594
+ * harmless — a foreign key between two tables is the canonical case, since
595
+ * `PRAGMA foreign_keys=OFF` at the top of the dump makes any table order
596
+ * restorable, which is exactly what allows circular foreign keys.
597
+ */
598
+ type ArchiveDependencyStrength = 'hard' | 'preference';
599
+ /** One directed edge from an entry to another entry it depends on. */
600
+ interface ArchiveDependency {
601
+ readonly targetDumpId: string;
602
+ readonly strength: ArchiveDependencyStrength;
603
+ }
604
+ /**
605
+ * One immutable, restore-orderable unit of the archive. Entries carry no SQL
606
+ * text; rendering derives text from the model object identified by `name`
607
+ * at render time.
608
+ */
609
+ interface ArchiveEntry {
610
+ readonly dumpId: string;
611
+ readonly identity: string;
612
+ readonly objectType: ArchiveObjectType;
613
+ readonly section: DumpSection;
614
+ readonly schemaName: string;
615
+ readonly name: string;
616
+ /** Owning table, for `tableData`, `index` and `trigger` entries. */
617
+ readonly parentName?: string;
618
+ /** For `table` and `tableData` entries: which kind of table. */
619
+ readonly tableKind?: SqliteTableKind;
620
+ /**
621
+ * For the rows of `sqlite_sequence` and `sqlite_stat*` in a *partial* dump:
622
+ * the tables whose rows are kept. A dump of a subset of tables must not
623
+ * carry — or, on restore, reset — the counters and statistics of tables
624
+ * it does not contain. Absent when every row is dumped.
625
+ */
626
+ readonly systemRowFilter?: readonly string[];
627
+ readonly dependsOn: readonly ArchiveDependency[];
628
+ /**
629
+ * This entry's 0-based position in {@link DumpArchiveInspection.entries}.
630
+ * Omitted when `valid` is `false`, since no such order exists.
631
+ */
632
+ readonly sequenceNumber?: number;
633
+ }
634
+ /** A set of entries mutually blocking each other via *hard* dependencies only; no valid order exists. */
635
+ interface ArchiveCycle {
636
+ readonly memberDumpIds: readonly string[];
637
+ }
638
+ /**
639
+ * A hard dependency the planned order does not satisfy. Always empty for a
640
+ * plan built from a consistent model — it is reported rather than silently
641
+ * reordered, because the emission order is fixed by native compatibility, so
642
+ * a violation means a model or planning bug that reordering would only hide.
643
+ */
644
+ interface UnsatisfiedDependency {
645
+ readonly fromDumpId: string;
646
+ readonly toDumpId: string;
647
+ }
648
+ interface DumpArchiveInspection {
649
+ readonly valid: boolean;
650
+ /**
651
+ * In emission order, with `sequenceNumber` set, when `valid` is `true`.
652
+ * When `valid` is `false` the same entries are present in the same
653
+ * deterministic order, but without `sequenceNumber`.
654
+ */
655
+ readonly entries: readonly ArchiveEntry[];
656
+ readonly diagnostics: readonly SqliteDiagnostic[];
657
+ /** Unresolved hard-dependency cycles. Always present; empty when `valid` is `true`. */
658
+ readonly cycles: readonly ArchiveCycle[];
659
+ /** Hard dependencies the emission order violates. Always present; empty when `valid` is `true`. */
660
+ readonly unsatisfiedDependencies: readonly UnsatisfiedDependency[];
661
+ }
662
+ type DumpMode = 'full' | 'schema-only' | 'data-only';
663
+
664
+ declare function assignDumpSection(objectType: ArchiveObjectType): DumpSection;
665
+ declare function dumpSectionPriority(section: DumpSection): number;
666
+ declare function tableGroupPriority(objectType: ArchiveObjectType): number;
667
+
668
+ interface ArchiveIdentityInput {
669
+ readonly objectType: ArchiveObjectType;
670
+ readonly schemaName: string;
671
+ readonly name: string;
672
+ readonly parentName?: string;
673
+ }
674
+ declare function createArchiveIdentity(input: ArchiveIdentityInput): string;
675
+
676
+ interface InspectDumpArchiveOptions {
677
+ readonly mode?: DumpMode;
678
+ readonly selection?: NormalizedDumpSelection;
679
+ readonly objectKinds?: DumpObjectKinds;
680
+ }
681
+ /** `sqlite3_strglob("sqlite_stat?", name)` — the tables `ANALYZE` maintains. */
682
+ declare function isStatisticsTableName(name: string): boolean;
683
+ /** The native shell compares this name with `strcmp`, so case-sensitively. */
684
+ declare const SEQUENCE_TABLE_NAME = "sqlite_sequence";
685
+ /**
686
+ * Converts a normalized {@link SqliteDatabase} into an ordered,
687
+ * dependency-validated set of {@link ArchiveEntry} objects.
688
+ *
689
+ * Independent of SQL text, output streams and connections: it decides only
690
+ * *what* is dumped and in *what order*. The order is the native `.dump`'s —
691
+ * see {@link DumpSection} — which is creation order (`sqlite_schema` rowid)
692
+ * rather than a topological sort. Creation order is itself a valid
693
+ * dependency order for everything SQLite checks at `CREATE` time, and the
694
+ * dump's `PRAGMA foreign_keys=OFF` covers the rest. Dependencies are still
695
+ * recorded and then *verified* against that order, so a model or planning
696
+ * bug surfaces as `valid: false` rather than as an unrestorable dump.
697
+ */
698
+ declare function inspectDumpArchive(database: SqliteDatabase, options?: InspectDumpArchiveOptions): DumpArchiveInspection;
699
+
700
+ interface IntrospectSqliteOptions {
701
+ /**
702
+ * Schema to introspect: `main` (default), `temp`, or the name of an
703
+ * attached database.
704
+ */
705
+ readonly schemaName?: string;
706
+ }
707
+ interface SqliteIntrospectionResult {
708
+ readonly database: SqliteDatabase;
709
+ readonly version: SqliteVersion;
710
+ readonly capabilities: SqliteCapabilities;
711
+ readonly diagnostics: readonly SqliteDiagnostic[];
712
+ }
713
+ /**
714
+ * Reads the complete schema of one SQLite database into a normalized
715
+ * {@link SqliteDatabase}.
716
+ *
717
+ * Every object comes from `sqlite_schema` (read through its historical name
718
+ * `sqlite_master`, which every release accepts), in rowid order — the order
719
+ * the native `.dump` uses. Column, index and foreign-key detail comes from
720
+ * the table-valued pragma functions where the library has them, falling back
721
+ * to the plain `PRAGMA` statements otherwise.
722
+ *
723
+ * Runs entirely on the one handle it is given, in sequence, and never writes.
724
+ */
725
+ declare function introspectSqlite(connection: SqliteConnection, options?: IntrospectSqliteOptions, signal?: AbortSignal): Promise<SqliteIntrospectionResult>;
726
+
727
+ /**
728
+ * Small, deliberately conservative helpers for reading facts out of the
729
+ * verbatim DDL SQLite keeps in `sqlite_schema.sql`, for the few facts no
730
+ * catalog pragma reports on every supported version.
731
+ */
732
+ /**
733
+ * Blanks out string literals, quoted identifiers and comments (keeping
734
+ * their length), so a keyword search cannot match text *inside* them —
735
+ * `DEFAULT 'AUTOINCREMENT'` is not an autoincrement column.
736
+ */
737
+ declare function maskSqlLiterals(sql: string): string;
738
+ /** `true` when the `CREATE TABLE` text declares an `AUTOINCREMENT` column. */
739
+ declare function declaresAutoincrement(sql: string): boolean;
740
+ /**
741
+ * Table options after the closing parenthesis of a `CREATE TABLE`
742
+ * (`WITHOUT ROWID`, `STRICT`, in any combination). Used only when the
743
+ * library is too old for `PRAGMA table_list`, which reports both directly.
744
+ */
745
+ declare function parseTableOptions(sql: string): {
746
+ withoutRowid: boolean;
747
+ strict: boolean;
748
+ };
749
+ /** The module named in `CREATE VIRTUAL TABLE name USING module(...)`. */
750
+ declare function parseVirtualTableModule(sql: string): string | undefined;
751
+
752
+ type DumpProgressPhase = 'connecting' | 'detecting-version' | 'starting-snapshot' | 'introspecting' | 'planning-archive' | 'rendering-schema' | 'exporting-data' | 'finalizing';
753
+ /** The dump section a progress event belongs to, mirroring the native `.dump` output order. */
754
+ type DumpProgressSection = 'header' | 'table-structure' | 'table-data' | 'virtual-table' | 'index' | 'trigger' | 'view' | 'footer';
755
+ interface DumpProgressEvent {
756
+ readonly phase: DumpProgressPhase;
757
+ readonly message?: string;
758
+ readonly section?: DumpProgressSection;
759
+ /** Archive entries rendered so far, and the total planned. */
760
+ readonly objectsProcessed?: number;
761
+ readonly objectsTotal?: number;
762
+ /** Name of the object currently being rendered/exported. */
763
+ readonly objectName?: string;
764
+ /** Schema being dumped (`main`, or an attached database's name). */
765
+ readonly schemaName?: string;
766
+ readonly tableName?: string;
767
+ /** Rows exported from the current table. */
768
+ readonly rowsExported?: number;
769
+ /** Bytes written to the output so far. */
770
+ readonly bytesWritten?: number;
771
+ /** Lifecycle of a table data export. */
772
+ readonly exportState?: 'started' | 'progress' | 'finished' | 'failed' | 'cancelled';
773
+ }
774
+ type DumpProgressCallback = (event: DumpProgressEvent) => void;
775
+ type RestoreProgressPhase = 'connecting' | 'preflight' | 'parsing' | 'executing' | 'finalizing';
776
+ interface RestoreProgressEvent {
777
+ readonly phase: RestoreProgressPhase;
778
+ readonly message?: string;
779
+ /** Statements executed plus statements failed so far. */
780
+ readonly statementsProcessed?: number;
781
+ /** The statement currently being parsed/executed, 0-based in source order. */
782
+ readonly statementIndex?: number;
783
+ /**
784
+ * Running total of rows changed across every statement executed so far;
785
+ * see `SqlDumpRestoreResult.rowsRestored`.
786
+ */
787
+ readonly rowsRestored?: number;
788
+ /** Bytes of the source consumed by the parser so far. */
789
+ readonly bytesConsumed?: number;
790
+ /**
791
+ * The object the current statement creates or fills, read from the
792
+ * statement itself (`CREATE TABLE t`, `INSERT INTO t`), when recognizable.
793
+ * A native `.dump` carries no section banners, so this is the only way a
794
+ * long restore can say where it is.
795
+ */
796
+ readonly currentObject?: string;
797
+ /** Lifecycle of the current execution attempt. */
798
+ readonly executionState?: 'started' | 'finished' | 'failed';
799
+ /** Details of the statement failure, emitted immediately with `executionState: 'failed'`. */
800
+ readonly error?: {
801
+ readonly statementIndex: number;
802
+ readonly location: {
803
+ readonly startLine: number;
804
+ readonly endLine: number;
805
+ };
806
+ readonly sqlPreview: string;
807
+ readonly message: string;
808
+ };
809
+ }
810
+ type RestoreProgressCallback = (event: RestoreProgressEvent) => void;
811
+
812
+ interface PlainSqlRenderOptions {
813
+ /**
814
+ * Wrap the dump in `PRAGMA foreign_keys=OFF;` / `BEGIN TRANSACTION;` …
815
+ * `COMMIT;`, exactly as the native `.dump` does. Defaults to `true`, and
816
+ * turning it off produces a `session-guards-disabled` warning.
817
+ *
818
+ * These are not decoration. `foreign_keys=OFF` is what lets tables be
819
+ * created and filled in creation order whatever references what —
820
+ * circular foreign keys included — and the transaction is what makes the
821
+ * restore both atomic and fast: without it every `INSERT` is its own
822
+ * transaction, and its own disk sync. A data-only dump never carries them,
823
+ * matching `.dump --data-only`.
824
+ */
825
+ readonly includeSessionGuards?: boolean;
826
+ /**
827
+ * Emit the `/* WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be
828
+ * disabled *\/` line the native `.dump` writes first when the dump
829
+ * contains virtual tables. Defaults to `true`.
830
+ */
831
+ readonly includeHeaderComments?: boolean;
832
+ /**
833
+ * Emit `DROP ... IF EXISTS` before each object's `CREATE`, so the dump can
834
+ * be restored over an existing copy. Defaults to `false`: the native
835
+ * `.dump` has no such option, and a dump restored into a fresh database
836
+ * does not need it.
837
+ */
838
+ readonly addDropStatements?: boolean;
839
+ /**
840
+ * Emit `PRAGMA user_version=…;` and `PRAGMA application_id=…;` before the
841
+ * final `COMMIT`, when either is non-zero. Defaults to `false`, matching
842
+ * the native `.dump` — which does not carry them, so an application that
843
+ * versions its schema through `user_version` loses that version in a
844
+ * native round trip. When they are not dumped, a non-zero value is
845
+ * reported as a `user-version-not-dumped` / `application-id-not-dumped`
846
+ * warning.
847
+ */
848
+ readonly includeDatabaseSettings?: boolean;
849
+ /**
850
+ * Write `sqlite_master` instead of `sqlite_schema` in the two places the
851
+ * dump names the schema table (`ANALYZE sqlite_schema;` and the virtual
852
+ * table `INSERT INTO sqlite_schema ...`). Defaults to `false`. The
853
+ * `sqlite_schema` spelling needs SQLite 3.33.0 or later on the restoring
854
+ * side; set this for a dump that must restore on something older.
855
+ */
856
+ readonly legacySchemaTableName?: boolean;
857
+ /**
858
+ * How to react to an archive entry that cannot be rendered. `'error'`
859
+ * (default) fails the render; `'warn-omit'` skips the entry and records a
860
+ * warning diagnostic.
861
+ */
862
+ readonly unsupportedFeaturePolicy?: 'error' | 'warn-omit';
863
+ }
864
+ interface ResolvedPlainSqlRenderOptions {
865
+ readonly includeSessionGuards: boolean;
866
+ readonly includeHeaderComments: boolean;
867
+ readonly addDropStatements: boolean;
868
+ readonly includeDatabaseSettings: boolean;
869
+ readonly legacySchemaTableName: boolean;
870
+ readonly unsupportedFeaturePolicy: 'error' | 'warn-omit';
871
+ }
872
+ declare function resolvePlainSqlRenderOptions(options?: PlainSqlRenderOptions): ResolvedPlainSqlRenderOptions;
873
+ interface PlainSqlRenderRequest {
874
+ readonly database: SqliteDatabase;
875
+ readonly archive: DumpArchiveInspection;
876
+ readonly writer: DumpWriter;
877
+ readonly options?: PlainSqlRenderOptions;
878
+ readonly signal?: AbortSignal;
879
+ readonly onProgress?: DumpProgressCallback;
880
+ /** Source library version; informational. */
881
+ readonly sourceVersion?: SqliteVersion;
882
+ /** Which dump mode produced `archive`. Defaults to `'full'`. */
883
+ readonly mode?: DumpMode;
884
+ /**
885
+ * Called for each `tableData` entry, for callers that can actually stream
886
+ * the rows (see `dumpSqlite`, which supplies this backed by a live
887
+ * connection). Resolve `true` once the rows have been written to
888
+ * `writer`; resolve `false` to fall back to the default "not rendered"
889
+ * warning for that entry.
890
+ */
891
+ readonly onTableData?: (entry: ArchiveEntry) => Promise<boolean>;
892
+ }
893
+ interface PlainSqlRenderResult {
894
+ readonly bytesWritten: number;
895
+ readonly renderedDumpIds: readonly string[];
896
+ readonly skippedDumpIds: readonly string[];
897
+ readonly warnings: readonly SqliteDiagnostic[];
898
+ readonly cancelled: boolean;
899
+ }
900
+
901
+ /** The native `.dump` preamble: integrity checks off, then one transaction around everything. */
902
+ declare const SESSION_GUARD_HEADER = "PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n";
903
+ declare const SESSION_GUARD_FOOTER = "COMMIT;\n";
904
+ declare const WRITABLE_SCHEMA_ON = "PRAGMA writable_schema=ON;\n";
905
+ declare const WRITABLE_SCHEMA_OFF = "PRAGMA writable_schema=OFF;\n";
906
+ /**
907
+ * `printSchemaLine()` from `shell.c`: how the native `.dump` writes a
908
+ * table's stored `CREATE TABLE` text.
909
+ *
910
+ * Two details are reproduced exactly, because both change the bytes:
911
+ *
912
+ * - **A trailing comment.** SQLite stores DDL verbatim, so it can end in a
913
+ * `--` comment (which would swallow an appended `;`) or even an
914
+ * unterminated `/*` comment (which SQLite accepts at end of input). When
915
+ * the text contains either, the shell tries appending nothing, `*\/` and a
916
+ * newline, in that order, and keeps the first variant that
917
+ * `sqlite3_complete()` accepts once `;` is added.
918
+ * - **`IF NOT EXISTS` for quoted names.** A `CREATE TABLE` whose name is
919
+ * written in single or double quotes becomes
920
+ * `CREATE TABLE IF NOT EXISTS`. Virtual table modules create their shadow
921
+ * tables with exactly that spelling (`CREATE TABLE 'ft_data'(...)`), and
922
+ * by the time the dump reaches them on restore, a module may already have
923
+ * created them.
924
+ */
925
+ declare function renderSchemaLine(sql: string, tail?: string): string;
926
+ /**
927
+ * How `run_table_dump_query()` in `shell.c` writes an index, trigger or view:
928
+ * the stored text, then `;` — on a line of its own if the text contains
929
+ * `--` anywhere, so a trailing line comment cannot swallow it. (The test is
930
+ * a plain substring search, so a `--` inside a string literal triggers it
931
+ * too, and does here.)
932
+ */
933
+ declare function renderSchemaObject(sql: string): string;
934
+ /**
935
+ * A virtual table, recreated the way the native `.dump` does it: by writing
936
+ * its row into `sqlite_schema` directly (under `PRAGMA writable_schema=ON`)
937
+ * instead of running `CREATE VIRTUAL TABLE`.
938
+ *
939
+ * Running the `CREATE` would invoke the module's constructor, which for most
940
+ * modules creates and initializes the shadow tables — and the dump is about
941
+ * to recreate those itself, with the source's exact contents. Writing the
942
+ * schema row leaves the shadow tables to the dump, so an FTS index or R-tree
943
+ * comes back byte-identical rather than rebuilt.
944
+ */
945
+ declare function renderVirtualTable(name: string, sql: string, schemaTableName: string): string;
946
+ /**
947
+ * The statement that prepares a system table for its rows.
948
+ *
949
+ * - `sqlite_sequence` is emptied, so the `AUTOINCREMENT` counters that
950
+ * follow replace — rather than duplicate — the counters the preceding
951
+ * inserts advanced. A partial dump only resets the counters of the tables
952
+ * it contains.
953
+ * - `sqlite_stat1`/`sqlite_stat4` are created, if missing, by analyzing the
954
+ * (trivial) schema table, which is how the native `.dump` guarantees they
955
+ * exist before inserting into them.
956
+ */
957
+ declare function renderSystemTablePrelude(name: string, schemaTableName: string, systemRowFilter: readonly string[] | undefined): string;
958
+ type DroppableKind = 'TABLE' | 'INDEX' | 'TRIGGER' | 'VIEW';
959
+ /** `DROP <kind> IF EXISTS <name>;`, for `addDropStatements`. */
960
+ declare function renderDrop(kind: DroppableKind, name: string): string;
961
+ /** `PRAGMA user_version=…;` / `PRAGMA application_id=…;`, for `includeDatabaseSettings`. */
962
+ declare function renderDatabaseSettings(userVersion: number, applicationId: number): string;
963
+
964
+ /**
965
+ * Renders a validated {@link DumpArchiveInspection} as plain SQL in the
966
+ * native `.dump` layout — the same statements, in the same order, spelled
967
+ * the same way.
968
+ *
969
+ * Purely a function of the static model and the archive plan: it never
970
+ * queries the database, which is why row data has to arrive through the
971
+ * `onTableData` hook (see `exportTableDataAsInserts` for the streaming
972
+ * implementation `dumpSqlite` supplies).
973
+ */
974
+ declare function renderPlainSql(request: PlainSqlRenderRequest): Promise<PlainSqlRenderResult>;
975
+
976
+ interface TableDataExportOptions {
977
+ /** Row-fetch hint passed through to `connection.stream()`. */
978
+ readonly streamBatchSize?: number;
979
+ /**
980
+ * Emit multi-row `INSERT INTO t VALUES(...),(...)` statements rather than
981
+ * one statement per row. Defaults to `false`, matching the native `.dump`.
982
+ *
983
+ * One row per statement is not slow in SQLite: the whole dump runs inside
984
+ * one transaction, so each `INSERT` is an in-memory b-tree update rather
985
+ * than a disk sync. Multi-row statements make the file smaller and the
986
+ * restore somewhat faster, at the cost of native byte-identity.
987
+ */
988
+ readonly extendedInsert?: boolean;
989
+ /** With {@link extendedInsert}: maximum rows per statement. Defaults to 500. */
990
+ readonly maxRowsPerStatement?: number;
991
+ /**
992
+ * With {@link extendedInsert}: approximate maximum size, in bytes, of one
993
+ * statement. Defaults to 1 MiB — far below SQLite's own 1 GB
994
+ * `SQLITE_MAX_SQL_LENGTH`, so a statement never approaches the limit, and
995
+ * small enough to keep restore memory modest. A statement is closed once
996
+ * the next row would exceed it; a single larger row is still emitted
997
+ * alone, since one row cannot be split.
998
+ */
999
+ readonly maxStatementBytes?: number;
1000
+ /**
1001
+ * Keep each row's `rowid` by naming it in the `INSERT`
1002
+ * (`INSERT INTO t(rowid,a,b) VALUES(...)`), for tables whose rowid is not
1003
+ * already a declared column. The native `.dump --preserve-rowids`.
1004
+ *
1005
+ * Defaults to `false`, as natively. Without it such a table's rows get
1006
+ * fresh rowids on restore, numbered from 1 in dump order — which matters
1007
+ * when anything refers to them: an external-content FTS index, an
1008
+ * application storing rowids, or a `VACUUM`-sensitive process.
1009
+ */
1010
+ readonly preserveRowids?: boolean;
1011
+ /**
1012
+ * Write newlines and carriage returns inside string literals raw, instead
1013
+ * of the native default `replace('...\n...','\n',char(10))` form. The
1014
+ * native `.dump --newlines`. Defaults to `false`.
1015
+ */
1016
+ readonly rawNewlines?: boolean;
1017
+ }
1018
+ interface TableDataExportRequest {
1019
+ readonly connection: SqliteConnection;
1020
+ /** Schema the table lives in: `main`, `temp`, or an attached database's name. */
1021
+ readonly schemaName: string;
1022
+ readonly table: SqliteTable;
1023
+ readonly writer: DumpWriter;
1024
+ /**
1025
+ * `PRAGMA encoding` of the database. Text values are read as their stored
1026
+ * bytes in a UTF-8 database; see `columnValueSelect`. Defaults to `UTF-8`.
1027
+ */
1028
+ readonly encoding?: string;
1029
+ /**
1030
+ * For `sqlite_sequence` and the `sqlite_stat*` tables only: keep just the
1031
+ * rows that belong to these tables. Used by partial dumps; see
1032
+ * `ArchiveEntry.systemRowFilter`.
1033
+ */
1034
+ readonly systemRowFilter?: readonly string[];
1035
+ readonly options?: TableDataExportOptions;
1036
+ readonly signal?: AbortSignal;
1037
+ readonly onProgress?: DumpProgressCallback;
1038
+ }
1039
+ interface TableDataExportResult {
1040
+ readonly rowsExported: number;
1041
+ readonly bytesWritten: number;
1042
+ readonly statementsWritten: number;
1043
+ readonly cancelled: boolean;
1044
+ readonly warnings: readonly SqliteDiagnostic[];
1045
+ }
1046
+
1047
+ /**
1048
+ * Accumulates SQL fragments that may be text *or* raw bytes.
1049
+ *
1050
+ * A `TEXT` value holding bytes that are not valid UTF-8 is written out raw,
1051
+ * exactly as the native `.dump` writes it, so a statement cannot always be
1052
+ * assembled as a JavaScript string. Joining through a string would replace
1053
+ * every invalid sequence with U+FFFD and corrupt the data silently.
1054
+ *
1055
+ * The all-text case — which is every row of every ordinary database — stays
1056
+ * on the fast path: parts are joined with `String.prototype.join` and no
1057
+ * `Buffer` is allocated at all. Only a builder that has actually been handed
1058
+ * bytes falls back to `Buffer.concat`.
1059
+ */
1060
+ declare class SqlChunkBuilder {
1061
+ private readonly parts;
1062
+ private byteLength;
1063
+ private hasBytes;
1064
+ /** UTF-8 byte length of everything appended so far. */
1065
+ get length(): number;
1066
+ get isEmpty(): boolean;
1067
+ append(part: string | Buffer): this;
1068
+ /** Appends everything from `other`, leaving `other` untouched. */
1069
+ appendBuilder(other: SqlChunkBuilder): this;
1070
+ /** The accumulated content, as a `string` when it is all text and a `Buffer` otherwise. */
1071
+ build(): string | Buffer;
1072
+ }
1073
+
1074
+ /**
1075
+ * The select-list for one column: its storage class, and a value shaped so
1076
+ * that only exact representations cross the driver boundary.
1077
+ *
1078
+ * - `INTEGER` → decimal text, so a 64-bit value is exact whatever the
1079
+ * driver would have done with it;
1080
+ * - `REAL` → the literal text, see {@link realLiteralExpression};
1081
+ * - `TEXT` → the stored bytes (`CAST(... AS BLOB)`), so text that is not
1082
+ * valid UTF-8 is not "repaired" by the driver's decoder on the way out.
1083
+ * In a UTF-16 database those bytes would be UTF-16, so there the value is
1084
+ * read as text instead and the driver's (lossless, for valid UTF-16)
1085
+ * conversion is used;
1086
+ * - `BLOB` → the bytes; `NULL` → `NULL`.
1087
+ */
1088
+ declare function columnValueSelect(column: string, index: number, utf8Database: boolean): string;
1089
+ /**
1090
+ * Renders column `index` of a row produced by {@link columnValueSelect} as
1091
+ * the SQL literal the native `.dump` writes for it.
1092
+ *
1093
+ * Returns a `Buffer` only for text that is not valid UTF-8: the shell writes
1094
+ * such bytes out raw, and so does this package, so the dump reproduces the
1095
+ * stored value exactly (see `DumpWriter` for why that cannot go through a
1096
+ * string).
1097
+ */
1098
+ declare function renderColumnLiteral(row: SqliteRow, index: number, textStyle: TextLiteralStyle): string | Buffer;
1099
+
1100
+ /**
1101
+ * The columns the native `.dump` inserts: those `PRAGMA table_info` lists,
1102
+ * which excludes generated columns and the hidden columns of virtual tables.
1103
+ * Generated columns cannot be inserted into; SQLite recomputes them.
1104
+ */
1105
+ declare function insertableColumns(table: SqliteTable): SqliteColumn[];
1106
+ /**
1107
+ * The name under which `preserveRowids` can address a table's rowid, as
1108
+ * `tableColumnList()` in `shell.c` decides it: never for a `WITHOUT ROWID`
1109
+ * table or one whose rowid is already a declared `INTEGER PRIMARY KEY`, and
1110
+ * otherwise the first of `rowid`, `_rowid_`, `oid` that no column is named.
1111
+ */
1112
+ declare function preservableRowidName(table: SqliteTable): string | null;
1113
+ /**
1114
+ * Streams one table's rows as `INSERT` statements in the native `.dump`
1115
+ * layout.
1116
+ *
1117
+ * Requires a live connection; this is deliberately separate from
1118
+ * `renderPlainSql`, which renders schema objects from the static model and
1119
+ * never touches the database.
1120
+ *
1121
+ * Rows are read in the table's natural order — no `ORDER BY`, exactly like
1122
+ * the native `.dump`. For an ordinary table that is rowid order, and for a
1123
+ * `WITHOUT ROWID` table primary-key order, so two dumps of an unchanged
1124
+ * database are identical.
1125
+ *
1126
+ * Memory is bounded by one statement plus a small output buffer: rows are
1127
+ * consumed from a stream and written as they are rendered, so a table of any
1128
+ * size dumps in constant memory.
1129
+ */
1130
+ declare function exportTableDataAsInserts(request: TableDataExportRequest): Promise<TableDataExportResult>;
1131
+
1132
+ /**
1133
+ * A restore target's capabilities have the same shape as a source's, but the
1134
+ * two stay distinct concepts: a source's describe what introspection may
1135
+ * use, a target's what DDL it can accept.
1136
+ */
1137
+ type TargetCapabilities = SqliteCapabilities;
1138
+
1139
+ interface TargetCompatibilityOptions {
1140
+ /**
1141
+ * Virtual table modules the target has (`PRAGMA module_list`), when known.
1142
+ * Without it, module availability is not checked.
1143
+ */
1144
+ readonly modules?: ReadonlySet<string>;
1145
+ /** The dump names `sqlite_master` rather than `sqlite_schema`; see `PlainSqlRenderOptions`. */
1146
+ readonly legacySchemaTableName?: boolean;
1147
+ /** The dump uses multi-row `INSERT ... VALUES (...), (...)`. */
1148
+ readonly extendedInsert?: boolean;
1149
+ }
1150
+ /**
1151
+ * Reports what a dump of `database` needs that `target` cannot provide.
1152
+ *
1153
+ * Feature-level rather than statement-level: the dump carries SQLite's own
1154
+ * stored DDL, so what can be checked is which features the source model
1155
+ * actually uses — which turns "restore failed with a syntax error at line
1156
+ * 4713" into "the target is SQLite 3.31 and this dump contains STRICT
1157
+ * tables".
1158
+ *
1159
+ * Never throws: callers decide whether an unsupported feature blocks the
1160
+ * restore or is merely reported.
1161
+ */
1162
+ declare function checkTargetCompatibility(database: SqliteDatabase, target: TargetCapabilities, options?: TargetCompatibilityOptions): SqliteDiagnostic[];
1163
+
1164
+ /**
1165
+ * Database state this package deliberately does not dump.
1166
+ *
1167
+ * Every one of these is either a property of the database *file* rather
1168
+ * than of its contents, or lives outside SQL entirely. Rather than silently
1169
+ * omitting them — which would make a dump look complete when it is not —
1170
+ * each is described here so `unsupportedFeatureDiagnostics()` can report
1171
+ * them, and `docs/known-limitations.md` can list them with the same wording.
1172
+ */
1173
+ declare const UNSUPPORTED_FEATURES: readonly {
1174
+ readonly code: string;
1175
+ readonly summary: string;
1176
+ readonly detail: string;
1177
+ }[];
1178
+ /** The {@link UNSUPPORTED_FEATURES} as `info` diagnostics, for a UI that lists what a dump does not include. */
1179
+ declare function unsupportedFeatureDiagnostics(): SqliteDiagnostic[];
1180
+
1181
+ interface PreflightRestoreRequest {
1182
+ readonly connection: SqliteConnectionInput;
1183
+ /**
1184
+ * The model of the database the dump was taken from (from
1185
+ * `introspectSqlite`). With it, the report answers "what does this dump
1186
+ * need that this target cannot do"; without it, only "what can this target
1187
+ * do".
1188
+ */
1189
+ readonly database?: SqliteDatabase;
1190
+ readonly options?: TargetCompatibilityOptions & {
1191
+ /** The dump was rendered with `addDropStatements`, so existing objects are replaced rather than conflicting. */
1192
+ readonly addDropStatements?: boolean;
1193
+ };
1194
+ readonly signal?: AbortSignal;
1195
+ }
1196
+ interface PreflightRestoreReport {
1197
+ readonly version: SqliteVersion;
1198
+ readonly capabilities: SqliteCapabilities;
1199
+ /** `PRAGMA encoding` of the target. */
1200
+ readonly encoding: string;
1201
+ /** Whether the target enforces foreign keys (`PRAGMA foreign_keys`). */
1202
+ readonly foreignKeysEnabled: boolean;
1203
+ /** Whether the handle is already inside a transaction. `undefined` when the adapter cannot tell. */
1204
+ readonly inTransaction?: boolean;
1205
+ /** Whether the adapter can lift defensive mode for a dump that writes `sqlite_schema`. */
1206
+ readonly canDisableDefensiveMode: boolean;
1207
+ /** Virtual table modules the target has, when `PRAGMA module_list` is available. */
1208
+ readonly modules?: readonly string[];
1209
+ /** `PRAGMA compile_options` of the target, when readable. */
1210
+ readonly compileOptions?: readonly string[];
1211
+ /** Tables, views, indexes and triggers already present in the target's `main` schema. */
1212
+ readonly existingObjects: readonly {
1213
+ readonly type: string;
1214
+ readonly name: string;
1215
+ }[];
1216
+ readonly diagnostics: readonly SqliteDiagnostic[];
1217
+ }
1218
+ /**
1219
+ * Inspects a restore target before anything is written to it.
1220
+ *
1221
+ * Turns a failure part-way through a restore — `table t already exists`,
1222
+ * `no such module: fts5`, a syntax error on a `STRICT` table — into an
1223
+ * up-front, actionable report. Never writes to the target.
1224
+ */
1225
+ declare function preflightRestore(request: PreflightRestoreRequest): Promise<PreflightRestoreReport>;
1226
+
1227
+ /** 1-based line range a parsed statement's SQL text occupies in its source. */
1228
+ interface StatementSourceLocation {
1229
+ readonly startLine: number;
1230
+ readonly endLine: number;
1231
+ }
1232
+
1233
+ /**
1234
+ * Anything {@link restoreSqlDump}/{@link streamSqlStatements} can read a dump
1235
+ * from.
1236
+ *
1237
+ * `Buffer`/`Uint8Array` is accepted alongside `string` for a reason that
1238
+ * matters: the native `.dump` writes a `TEXT` value's stored bytes verbatim,
1239
+ * so a database holding text that is not valid UTF-8 produces a dump that is
1240
+ * not valid UTF-8 either. Forcing a caller to `.toString()` such a dump
1241
+ * before restoring it would replace every invalid sequence with U+FFFD and
1242
+ * silently corrupt the data, so the bytes are taken directly instead.
1243
+ *
1244
+ * `Readable` streams are consumed through their own async-iterable protocol
1245
+ * (`for await`), so `fs.createReadStream(path)` needs no adapter.
1246
+ */
1247
+ type SqlDumpSource = string | Buffer | Uint8Array | Readable | AsyncIterable<string | Buffer | Uint8Array>;
1248
+
1249
+ /** Base class for every error this package throws intentionally. */
1250
+ declare class SqliteDumperError extends Error {
1251
+ readonly code: string;
1252
+ constructor(code: string, message: string, options?: {
1253
+ cause?: unknown;
1254
+ });
1255
+ }
1256
+ /** Thrown when an operation stops because its `AbortSignal` was triggered. */
1257
+ declare class OperationCancelledError extends SqliteDumperError {
1258
+ constructor(message?: string);
1259
+ }
1260
+ declare function throwIfAborted(signal: AbortSignal | undefined): void;
1261
+ /**
1262
+ * True for both cancellation shapes this package can observe: its own
1263
+ * {@link OperationCancelledError} and the `DOMException` an `AbortSignal`
1264
+ * (or a Node stream aborted through one) raises.
1265
+ */
1266
+ declare function isAbortError(error: unknown): boolean;
1267
+
1268
+ /** Common base for every error {@link restoreSqlDump} (or its parser) throws intentionally. */
1269
+ declare class RestoreError extends SqliteDumperError {
1270
+ }
1271
+ /**
1272
+ * The input could not be split into statements correctly.
1273
+ *
1274
+ * Always fatal: unlike a statement that fails when executed, a parse failure
1275
+ * means the statement boundaries themselves are not trustworthy, so nothing
1276
+ * after the failure point can be safely executed either.
1277
+ */
1278
+ declare class SqlParseError extends RestoreError {
1279
+ readonly line: number;
1280
+ constructor(code: string, message: string, line: number, options?: {
1281
+ cause?: unknown;
1282
+ });
1283
+ }
1284
+ /**
1285
+ * The input ended while a quoted token — a string, a `"`/`` ` ``/`[...]`
1286
+ * identifier — was still open. The script is structurally incomplete (most
1287
+ * often a truncated file) and cannot be split into valid statements.
1288
+ *
1289
+ * An unterminated `/*` comment is *not* reported: SQLite itself accepts a
1290
+ * block comment that runs to the end of the input.
1291
+ */
1292
+ declare class MalformedSqlDumpError extends SqlParseError {
1293
+ readonly openConstruct: string;
1294
+ constructor(openConstruct: string, line: number);
1295
+ }
1296
+ /**
1297
+ * One statement's accumulated text exceeded
1298
+ * {@link SqlStatementParserOptions.maxStatementBytes} before it was
1299
+ * complete.
1300
+ *
1301
+ * A statement must be sent to SQLite whole, so this bounds how much of a
1302
+ * pathological input — a truncated dump, or an unterminated `CREATE TRIGGER`
1303
+ * that swallows the rest of the file — the parser will buffer before giving
1304
+ * up, instead of growing without limit.
1305
+ */
1306
+ declare class StatementTooLargeError extends SqlParseError {
1307
+ readonly maxStatementBytes: number;
1308
+ constructor(maxStatementBytes: number, line: number);
1309
+ }
1310
+ /**
1311
+ * A `sqlite3` shell dot-command was found that would change what the script
1312
+ * does to the database.
1313
+ *
1314
+ * The shell executes lines beginning with `.` itself (`.read`, `.import`,
1315
+ * `.open`, `.load`, `.shell`, ...) before anything reaches SQLite. Commands
1316
+ * that only affect the shell's own presentation (`.mode`, `.headers`,
1317
+ * `.print`, ...) are skipped with a warning; the rest are refused with a
1318
+ * precise diagnostic rather than being silently ignored, which would corrupt
1319
+ * the restore — a `.read` that never runs leaves the referenced file's
1320
+ * objects missing, and an `.import` that never runs leaves a table empty.
1321
+ */
1322
+ declare class UnsupportedClientCommandError extends SqlParseError {
1323
+ readonly command: string;
1324
+ constructor(command: string, line: number);
1325
+ }
1326
+ /**
1327
+ * A statement holds bytes that are not valid UTF-8 outside any string
1328
+ * literal, so it cannot be handed to SQLite as text without corrupting them.
1329
+ *
1330
+ * Invalid UTF-8 *inside* a string literal — which the native `.dump` writes
1331
+ * whenever a `TEXT` value holds such bytes — is handled transparently, by
1332
+ * rewriting the literal into the equivalent `CAST(X'...' AS TEXT)`. Reaching
1333
+ * this error means the bytes are in an identifier or keyword position.
1334
+ */
1335
+ declare class InvalidTextEncodingError extends SqlParseError {
1336
+ constructor(message: string, line: number);
1337
+ }
1338
+ /**
1339
+ * A statement parsed successfully but failed when executed.
1340
+ *
1341
+ * Unlike a parse error this is scoped to one statement: with
1342
+ * `stopOnError: false`, restoration continues with the next one, and this
1343
+ * error's data — never the raw driver error, which can echo back parts of
1344
+ * the failing statement — is what is recorded in
1345
+ * {@link SqlDumpRestoreResult.errors}.
1346
+ */
1347
+ declare class RestoreExecutionError extends RestoreError {
1348
+ readonly statementIndex: number;
1349
+ readonly location: StatementSourceLocation;
1350
+ readonly sqlPreview: string;
1351
+ readonly sqliteError?: SqliteErrorInfo;
1352
+ constructor(statementIndex: number, location: StatementSourceLocation, sqlPreview: string, message: string, sqliteError?: SqliteErrorInfo, options?: {
1353
+ cause?: unknown;
1354
+ });
1355
+ }
1356
+
1357
+ /**
1358
+ * Truncates SQL for inclusion in an error message or a progress event.
1359
+ *
1360
+ * Never a full statement — a single `INSERT` can carry a megabyte of blob —
1361
+ * and never a literal encryption key.
1362
+ */
1363
+ declare function safeSqlPreview(sql: string, maximumLength?: number): string;
1364
+ /** The warning line the native `.dump` writes first when the dump contains virtual tables. */
1365
+ declare const DEFENSIVE_WARNING_COMMENT = "/* WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */";
1366
+ /**
1367
+ * Heuristically detects whether `sample` looks like a SQLite dump — whether
1368
+ * produced by the native `.dump` command or by this package, which write the
1369
+ * same thing.
1370
+ *
1371
+ * A full dump opens with `PRAGMA foreign_keys=OFF;` and
1372
+ * `BEGIN TRANSACTION;`, optionally preceded by the defensive-mode warning
1373
+ * comment; that opening is what is recognized. A `--data-only` dump has no
1374
+ * such preamble and is indistinguishable from any other script of
1375
+ * `INSERT`s, so it is only recognized when it carries the warning comment.
1376
+ *
1377
+ * Only the first few kilobytes need to be supplied; the check never reads
1378
+ * beyond what it is given, so a caller can pass the head of a large file.
1379
+ */
1380
+ declare function isSqliteDump(sample: string | Uint8Array): boolean;
1381
+
1382
+ /**
1383
+ * A port of SQLite's `sqlite3_complete()` (`complete.c`) — the function the
1384
+ * `sqlite3` shell calls to decide whether the text it has accumulated so far
1385
+ * is one or more *complete* statements, and therefore ready to run.
1386
+ *
1387
+ * Splitting on `;` is not enough, and not in an edge-case way: a trigger
1388
+ * body is a list of statements, each ending in `;`, inside a single
1389
+ * `CREATE TRIGGER ... BEGIN ... END;`. `sqlite3_complete()` recognizes that
1390
+ * with a small state machine over eight token classes, and reproducing that
1391
+ * machine exactly is what makes this package split a script where the shell
1392
+ * does.
1393
+ */
1394
+ /** Token classes of the `sqlite3_complete()` state machine. */
1395
+ declare const CompleteToken: {
1396
+ readonly Semi: 0;
1397
+ readonly Whitespace: 1;
1398
+ readonly Other: 2;
1399
+ readonly Explain: 3;
1400
+ readonly Create: 4;
1401
+ readonly Temp: 5;
1402
+ readonly Trigger: 6;
1403
+ readonly End: 7;
1404
+ };
1405
+ type CompleteToken = (typeof CompleteToken)[keyof typeof CompleteToken];
1406
+ /**
1407
+ * States of the machine:
1408
+ *
1409
+ * - `0` INVALID — nothing but whitespace/comments seen yet.
1410
+ * - `1` START — at the start of a statement, or just after a complete one.
1411
+ * - `2` NORMAL — inside an ordinary statement.
1412
+ * - `3` EXPLAIN — the statement began with `EXPLAIN`.
1413
+ * - `4` CREATE — the statement began with `CREATE` (or `EXPLAIN CREATE`).
1414
+ * - `5` TRIGGER — inside `CREATE [TEMP] TRIGGER ...`, before or within its body.
1415
+ * - `6` SEMI — just saw a `;` inside a trigger body.
1416
+ * - `7` END — saw `END` right after such a `;`; the next `;` completes the trigger.
1417
+ */
1418
+ declare const COMPLETE_TRANSITIONS: readonly (readonly number[])[];
1419
+ /** Applies one token to a state. */
1420
+ declare function completeTransition(state: number, token: CompleteToken): number;
1421
+ /**
1422
+ * `IdChar()` from `complete.c`: letters, digits, `_`, `$`, and every byte (or
1423
+ * code unit) at or above `0x80`, which is how SQLite admits non-ASCII
1424
+ * identifiers without decoding them.
1425
+ */
1426
+ declare function isIdentifierCharCode(code: number): boolean;
1427
+ /** Classifies a complete identifier-like word the way `sqlite3_complete()` does. */
1428
+ declare function classifyWord(word: string): CompleteToken;
1429
+ /**
1430
+ * `sqlite3_complete()`: `true` when `sql` ends with a complete statement —
1431
+ * a `;` that is not inside a string, identifier, comment or trigger body,
1432
+ * followed by nothing but whitespace and comments.
1433
+ *
1434
+ * Faithful to the C, including its quirks: an unterminated `/*` comment or
1435
+ * quoted token makes the text incomplete, while a trailing `--` comment
1436
+ * with no newline does not.
1437
+ */
1438
+ declare function isCompleteStatement(sql: string): boolean;
1439
+
1440
+ /** What a statement is, as far as restore bookkeeping needs to know. */
1441
+ interface StatementInfo {
1442
+ /** The statement's first keyword, upper-cased: `CREATE`, `INSERT`, `PRAGMA`, `BEGIN`, ... */
1443
+ readonly verb: string;
1444
+ /** For `CREATE`: the object kind (`TABLE`, `INDEX`, `VIEW`, `TRIGGER`, `VIRTUAL TABLE`). */
1445
+ readonly objectKind?: string;
1446
+ /** The object the statement creates, fills or changes, when recognizable. */
1447
+ readonly objectName?: string;
1448
+ /** For `PRAGMA`: the pragma name, lower-cased, without a schema prefix. */
1449
+ readonly pragmaName?: string;
1450
+ /** For `PRAGMA x = value` / `PRAGMA x(value)`: the value as written, unquoted. */
1451
+ readonly pragmaValue?: string;
1452
+ /**
1453
+ * `begin`, `commit`, `rollback`, `savepoint`, `release` or
1454
+ * `rollback-to-savepoint` for transaction-control statements.
1455
+ */
1456
+ readonly transactionControl?: 'begin' | 'commit' | 'rollback' | 'rollback-to-savepoint' | 'savepoint' | 'release';
1457
+ }
1458
+ /**
1459
+ * Classifies a statement from its leading tokens.
1460
+ *
1461
+ * Used for restore progress (`currentObject`), for following the script's
1462
+ * own transaction control, and for noticing the session-level pragmas a dump
1463
+ * changes (`foreign_keys`, `writable_schema`) so they can be put back if the
1464
+ * restore stops early.
1465
+ */
1466
+ declare function describeStatement(sql: string): StatementInfo;
1467
+
1468
+ /**
1469
+ * Converts a statement's bytes into text SQLite can be handed, preserving
1470
+ * every byte.
1471
+ *
1472
+ * SQLite does not validate the encoding of the text it stores, and the
1473
+ * native `.dump` writes a `TEXT` value's bytes exactly as stored — so a value
1474
+ * holding bytes that are not valid UTF-8 appears in the dump as a string
1475
+ * literal that is not valid UTF-8 either. The `sqlite3` shell passes those
1476
+ * bytes straight to `sqlite3_prepare()`, which stores them unchanged. A
1477
+ * JavaScript driver cannot: its statement text is a JavaScript string, and
1478
+ * every invalid sequence would become U+FFFD on the way in.
1479
+ *
1480
+ * So a literal that is not valid UTF-8 is rewritten into an expression that
1481
+ * yields the identical bytes as text, written entirely in ASCII:
1482
+ *
1483
+ * ```sql
1484
+ * 'caf\xE9' → (CAST(X'636166e9' AS TEXT))
1485
+ * ```
1486
+ *
1487
+ * In a UTF-8 database (every database the native `.dump` can reproduce
1488
+ * exactly) that is byte-for-byte the value the shell would have stored.
1489
+ * Invalid bytes inside a comment are dropped along with the comment; invalid
1490
+ * bytes anywhere else — in an identifier or keyword position — cannot be
1491
+ * represented and raise {@link InvalidTextEncodingError}.
1492
+ *
1493
+ * `statement` is a byte string: one code unit per byte, as `latin1` decodes
1494
+ * it. Returns the statement as ordinary text, plus how many literals were
1495
+ * rewritten.
1496
+ */
1497
+ declare function decodeStatementBytes(statement: string, startLine: number): {
1498
+ sql: string;
1499
+ literalsRewritten: number;
1500
+ };
1501
+
1502
+ /**
1503
+ * What to do with a `sqlite3` shell dot-command (`.mode csv`, `.read x.sql`).
1504
+ *
1505
+ * - `'skip-presentational'` (default) skips commands that only affect the
1506
+ * shell's output (`.mode`, `.headers`, `.print`, ...), reporting each, and
1507
+ * refuses every command that would change what the script does to the
1508
+ * database (`.read`, `.import`, `.open`, `.load`, ...).
1509
+ * - `'error'` refuses every dot-command.
1510
+ *
1511
+ * `.quit` and `.exit` end the input in both modes, exactly as in the shell.
1512
+ */
1513
+ type DotCommandPolicy = 'skip-presentational' | 'error';
1514
+ interface SqlStatementParserOptions {
1515
+ /**
1516
+ * Upper bound, in bytes, on one statement's accumulated text.
1517
+ *
1518
+ * Guards against unbounded memory growth from a truncated dump or a
1519
+ * `CREATE TRIGGER` whose `END` is missing. Defaults to 256 MiB — far
1520
+ * larger than any statement a real dump contains, while still bounded.
1521
+ */
1522
+ readonly maxStatementBytes?: number;
1523
+ readonly dotCommands?: DotCommandPolicy;
1524
+ }
1525
+ interface ParsedStatement {
1526
+ readonly statementIndex: number;
1527
+ /**
1528
+ * Statement text, without its terminating `;` and without the whitespace
1529
+ * and comments that preceded it. Never empty.
1530
+ */
1531
+ readonly sql: string;
1532
+ readonly location: StatementSourceLocation;
1533
+ /** What the statement is, from its leading tokens. */
1534
+ readonly info: StatementInfo;
1535
+ /**
1536
+ * The object the restore is currently working on: this statement's own
1537
+ * object when it names one (`CREATE TABLE t`, `INSERT INTO t`), else the
1538
+ * last one seen. Reported through restore progress.
1539
+ */
1540
+ readonly currentObject?: string;
1541
+ /** Bytes of source the parser had consumed when this statement was emitted. */
1542
+ readonly bytesConsumed: number;
1543
+ /**
1544
+ * How many string literals holding bytes that are not valid UTF-8 were
1545
+ * rewritten to `CAST(X'...' AS TEXT)` so the statement could be sent as
1546
+ * text. See `textEncoding.ts`.
1547
+ */
1548
+ readonly textLiteralsRewritten: number;
1549
+ }
1550
+ /** A dot-command the parser skipped under `'skip-presentational'`. */
1551
+ interface SkippedDotCommand {
1552
+ readonly command: string;
1553
+ readonly line: number;
1554
+ }
1555
+ /**
1556
+ * An incremental splitter for `sqlite3` scripts that decides statement
1557
+ * boundaries exactly where the `sqlite3` shell does.
1558
+ *
1559
+ * Two layers, both ported from SQLite's own sources:
1560
+ *
1561
+ * - **Tokens and completeness** follow `sqlite3_complete()`
1562
+ * (see `complete.ts`): `'...'` strings, `"..."`, `` `...` `` and `[...]`
1563
+ * identifiers, `--` and (non-nesting) `/* *\/` comments, and the state
1564
+ * machine that keeps the `;`-terminated statements inside a
1565
+ * `CREATE TRIGGER ... BEGIN ... END;` body in one statement.
1566
+ * - **Lines** follow the shell's `process_input()`: a line starting with `.`
1567
+ * at column 0, when no SQL is pending, is a dot-command; a line starting
1568
+ * with `#` there is a comment; a line holding only `GO` or `/` ends the
1569
+ * pending statement; and a carriage return immediately before a newline is
1570
+ * dropped, exactly as the shell's line reader drops it.
1571
+ *
1572
+ * The parser runs on **bytes** — chunks are byte strings, one code unit per
1573
+ * byte, as `latin1` decodes them — because a dump is not necessarily valid
1574
+ * UTF-8, and decoding up front would replace invalid bytes with U+FFFD
1575
+ * before the parser ever saw them. Every character it reacts to is ASCII,
1576
+ * and no byte of a multi-byte UTF-8 sequence can be mistaken for one.
1577
+ *
1578
+ * Correctness across chunk boundaries is not assumed: anything whose
1579
+ * meaning depends on what follows — a `-` or `/` that may open a comment, a
1580
+ * `*` that may close one, a `\r` that may precede `\n`, the start of a line
1581
+ * that may be a `GO` line — is carried to the next chunk.
1582
+ *
1583
+ * Memory is bounded by one statement: only the current statement's text and
1584
+ * a few carried bytes are held, and `maxStatementBytes` fails fast on a
1585
+ * pathological input rather than growing without limit.
1586
+ */
1587
+ declare class SqlStatementParser {
1588
+ private readonly maxStatementBytes;
1589
+ private readonly dotCommandPolicy;
1590
+ private lex;
1591
+ private completeState;
1592
+ /** Length and (lower-cased, capped) prefix of the identifier being scanned. */
1593
+ private wordLength;
1594
+ private wordPrefix;
1595
+ /** In a block comment: whether the previous byte was `*`. */
1596
+ private blockStar;
1597
+ private openLine;
1598
+ private carry;
1599
+ private parts;
1600
+ private partsBytes;
1601
+ /** True once the pending statement has content other than whitespace and comments. */
1602
+ private hasContent;
1603
+ private statementStartLine;
1604
+ private line;
1605
+ private atLineStart;
1606
+ private firstChunk;
1607
+ private dotText;
1608
+ private dotLine;
1609
+ private nextStatementIndex;
1610
+ private finished;
1611
+ private bytesConsumedTotal;
1612
+ private lastObject;
1613
+ private readonly skipped;
1614
+ constructor(options?: SqlStatementParserOptions);
1615
+ /** Bytes of source consumed so far. */
1616
+ get bytesConsumed(): number;
1617
+ /** Dot-commands skipped so far under the `'skip-presentational'` policy. */
1618
+ get skippedDotCommands(): readonly SkippedDotCommand[];
1619
+ /** `true` once a `.quit`/`.exit` command ended the input. */
1620
+ get stopped(): boolean;
1621
+ /**
1622
+ * Feeds one chunk of the source, as a **byte string** — one code unit per
1623
+ * byte, as produced by `buffer.toString('latin1')`. Callers holding text
1624
+ * should use {@link parseSqlStatements} or {@link streamSqlStatements},
1625
+ * which convert for them.
1626
+ */
1627
+ push(chunk: string): ParsedStatement[];
1628
+ finish(): ParsedStatement[];
1629
+ private scan;
1630
+ /**
1631
+ * Cheap pre-check before the terminator-line lookahead: only a line whose
1632
+ * first non-blank character is `/` or `g` can be one. Keeps the lookahead —
1633
+ * which has to look at the whole line — off the ordinary `INSERT` lines
1634
+ * that make up almost all of a dump.
1635
+ */
1636
+ private mayStartTerminatorLine;
1637
+ private countNewlines;
1638
+ private extendWord;
1639
+ private endWord;
1640
+ /** A terminator line: behave as if the line were `;`. */
1641
+ private completeWithSemicolon;
1642
+ private emit;
1643
+ private handleDotCommand;
1644
+ }
1645
+ /** Parses a complete, already-in-memory script. A convenience wrapper over {@link SqlStatementParser}. */
1646
+ declare function parseSqlStatements(sql: string | Buffer, options?: SqlStatementParserOptions): ParsedStatement[];
1647
+ /**
1648
+ * Normalizes any {@link SqlDumpSource} into *byte strings*: one JavaScript
1649
+ * code unit per input byte, via `latin1`. See {@link SqlStatementParser} for
1650
+ * why the parser runs on bytes; a `latin1` decode can also never split a
1651
+ * character across chunks, so no `StringDecoder` is needed.
1652
+ */
1653
+ declare function toByteStringChunks(source: SqlDumpSource): AsyncGenerator<string>;
1654
+ /**
1655
+ * Streams `source` into {@link ParsedStatement}s without ever buffering the
1656
+ * whole input: at most the current statement's text, plus a few carried
1657
+ * bytes, is held at a time.
1658
+ */
1659
+ declare function streamSqlStatements(source: SqlDumpSource, options?: SqlStatementParserOptions, signal?: AbortSignal): AsyncGenerator<ParsedStatement>;
1660
+ /** Drives an existing parser over `source`, so a caller can inspect it afterwards. */
1661
+ declare function streamWithParser(parser: SqlStatementParser, source: SqlDumpSource, signal?: AbortSignal): AsyncGenerator<ParsedStatement>;
1662
+
1663
+ /** Parses a boolean pragma value the way SQLite does (`sqlite3GetBoolean`). */
1664
+ declare function isTruthyPragmaValue(value: string | undefined): boolean;
1665
+ /**
1666
+ * Follows the connection state a restore script changes, so it can be put
1667
+ * back when the script stops before undoing it itself — or, for the
1668
+ * settings a native dump never undoes, when it finishes.
1669
+ *
1670
+ * Only statements the parser has classified (see `describeStatement`) are
1671
+ * followed: top-level transaction control and the two session pragmas a
1672
+ * dump uses. Text inside row values or trigger bodies is never mistaken for
1673
+ * one, because a statement is classified from its leading tokens only.
1674
+ */
1675
+ declare class RestoreSessionState {
1676
+ private initialForeignKeys;
1677
+ private foreignKeysChanged;
1678
+ private writableSchemaOn;
1679
+ private schemaRowsWritten;
1680
+ /** Tracked when the adapter cannot report `isInTransaction()`. */
1681
+ private trackedTransaction;
1682
+ private callerTransaction;
1683
+ /** Records the state to restore to. Call once, before the first statement. */
1684
+ begin(connection: SqliteConnection, signal?: AbortSignal): Promise<void>;
1685
+ /** Whether the handle was already inside a transaction the caller opened. */
1686
+ get joinedCallerTransaction(): boolean;
1687
+ /** Whether any statement wrote virtual-table rows into the schema table. */
1688
+ get wroteSchemaRows(): boolean;
1689
+ /** Call after every statement that executed successfully. */
1690
+ observe(info: StatementInfo): void;
1691
+ /** Whether a transaction the script (not the caller) opened is still open. */
1692
+ scriptTransactionOpen(connection: SqliteConnection): boolean;
1693
+ /**
1694
+ * Puts back what the script changed. Runs without the caller's signal on
1695
+ * purpose: on the cancellation path that signal is already aborted, and
1696
+ * the cleanup must still happen. Returns a description of each change it
1697
+ * undid, for the `session-state-restored` warning.
1698
+ */
1699
+ restore(connection: SqliteConnection, options: {
1700
+ readonly rollbackOpenTransaction: boolean;
1701
+ }): Promise<{
1702
+ readonly rolledBack: boolean;
1703
+ readonly restored: readonly string[];
1704
+ }>;
1705
+ }
1706
+ /** `sqlite_schema`, `sqlite_master`, and their temp-schema forms. */
1707
+ declare function isSchemaTableName(name: string | undefined): boolean;
1708
+
1709
+ interface RestoreOptions extends SqlStatementParserOptions {
1710
+ /** Stop at the first statement that fails. Defaults to `true`. */
1711
+ readonly stopOnError?: boolean;
1712
+ /**
1713
+ * Put back the connection state a dump changes, whether or not the
1714
+ * restore runs to the end. Defaults to `true`. Specifically:
1715
+ *
1716
+ * - a transaction the *script* opened (`BEGIN TRANSACTION;`) and never
1717
+ * closed — because a statement failed, the restore was cancelled, or the
1718
+ * file was truncated before its `COMMIT` — is rolled back, exactly as the
1719
+ * `sqlite3` shell's exit would roll it back. Otherwise the caller would
1720
+ * get the handle back mid-transaction, holding a write lock on the file;
1721
+ * - `PRAGMA foreign_keys` is returned to its value before the restore. A
1722
+ * native dump turns enforcement off in its first line and never turns it
1723
+ * back on, which is harmless in a shell that then exits, and a silent
1724
+ * integrity hazard on a long-lived handle;
1725
+ * - `PRAGMA writable_schema` is turned back off if the script left it on;
1726
+ * - defensive mode is re-enabled if this restore disabled it.
1727
+ */
1728
+ readonly restoreSessionState?: boolean;
1729
+ /**
1730
+ * What to do when a dump recreates virtual tables by writing
1731
+ * `sqlite_schema` directly, as every native `.dump` of such a database
1732
+ * does (see `renderVirtualTable`).
1733
+ *
1734
+ * - `'allow'` (default): when the adapter supports it, lift
1735
+ * `SQLITE_DBCONFIG_DEFENSIVE` for the duration of the restore (the dump's
1736
+ * own header says it requires that), and afterwards reload the schema so
1737
+ * the restored virtual tables are usable on the same handle.
1738
+ * - `'refuse'`: fail every statement that writes the schema table.
1739
+ */
1740
+ readonly schemaWrites?: 'allow' | 'refuse';
1741
+ /**
1742
+ * Transaction handling.
1743
+ *
1744
+ * - `'script'` (default): statements run exactly as written, so the
1745
+ * dump's own `BEGIN TRANSACTION` / `COMMIT` decide atomicity — which
1746
+ * for any full dump means the whole restore is one transaction.
1747
+ * - `'wrap'`: this package opens its own transaction before the first
1748
+ * statement that is not a `PRAGMA`, skips the script's own
1749
+ * transaction-control statements, and commits at the end — or rolls
1750
+ * everything back on failure. Useful for a data-only dump, which has no
1751
+ * transaction of its own and would otherwise commit (and sync to disk)
1752
+ * once per row.
1753
+ */
1754
+ readonly transaction?: 'script' | 'wrap';
1755
+ /**
1756
+ * After a successful restore, run `PRAGMA foreign_key_check` and report
1757
+ * every violation as a `foreign-key-violation` warning. Defaults to
1758
+ * `false`. A dump is loaded with enforcement off, so a source database
1759
+ * that already violated its own foreign keys restores without complaint;
1760
+ * this makes that visible.
1761
+ */
1762
+ readonly verifyForeignKeys?: boolean;
1763
+ /**
1764
+ * Run `PRAGMA foreign_keys=OFF` before the first statement, and put the
1765
+ * previous value back afterwards. Defaults to `false`.
1766
+ *
1767
+ * A full dump turns enforcement off itself, in its first line. A
1768
+ * data-only dump does not (neither does the native `--data-only`), and
1769
+ * the `sqlite3` shell never needs it to, because the shell starts with
1770
+ * enforcement off — while `better-sqlite3`, like most drivers, turns it on.
1771
+ * Loading a data-only dump whose tables reference each other in both
1772
+ * directions therefore needs this.
1773
+ */
1774
+ readonly disableForeignKeys?: boolean;
1775
+ }
1776
+ interface SqlDumpRestoreRequest {
1777
+ readonly connection: SqliteConnectionInput;
1778
+ readonly source: SqlDumpSource;
1779
+ readonly options?: RestoreOptions;
1780
+ readonly signal?: AbortSignal;
1781
+ readonly progress?: RestoreProgressCallback;
1782
+ }
1783
+ /** One statement that parsed successfully but failed when executed. */
1784
+ interface RestoreStatementError {
1785
+ readonly statementIndex: number;
1786
+ readonly location: StatementSourceLocation;
1787
+ /** Truncated, secret-redacted preview of the failing statement. */
1788
+ readonly sqlPreview: string;
1789
+ readonly message: string;
1790
+ /** SQLite's own result code, when the adapter can report it. */
1791
+ readonly sqliteError?: SqliteErrorInfo;
1792
+ }
1793
+ interface SqlDumpRestoreResult {
1794
+ readonly statementsExecuted: number;
1795
+ readonly statementsFailed: number;
1796
+ /**
1797
+ * Sum of the rows changed by every successfully executed statement. In
1798
+ * practice this is rows inserted, since DDL changes none — but it is a
1799
+ * straightforward sum, so a script's own `UPDATE`/`DELETE` statements
1800
+ * contribute too.
1801
+ */
1802
+ readonly rowsRestored: number;
1803
+ /** Bytes of the source consumed. */
1804
+ readonly bytesConsumed: number;
1805
+ readonly errors: readonly RestoreStatementError[];
1806
+ readonly warnings: readonly RestoreWarning[];
1807
+ readonly cancelled: boolean;
1808
+ }
1809
+ interface RestoreWarning {
1810
+ readonly code: string;
1811
+ readonly message: string;
1812
+ readonly statementIndex?: number;
1813
+ }
1814
+
1815
+ /**
1816
+ * Restores a plain-SQL dump using only the {@link SqliteConnection}
1817
+ * abstraction — no `sqlite3` shell, no external process.
1818
+ *
1819
+ * The input is split into statements by a streaming parser that reproduces
1820
+ * the `sqlite3` shell's own rules (see `statementParser.ts`), so a script is
1821
+ * executed as the same statements, in the same order, that
1822
+ * `sqlite3 database.db < dump.sql` would execute. Statements run
1823
+ * sequentially on one handle.
1824
+ *
1825
+ * A structural problem with the input — an unterminated string, an
1826
+ * unsupported dot-command, bytes that cannot be represented — throws,
1827
+ * because the statement boundaries past that point cannot be trusted. A
1828
+ * statement that parses but fails in SQLite is recorded in `result.errors`
1829
+ * instead, and unless `stopOnError` (the default) is set, the restore
1830
+ * continues.
1831
+ */
1832
+ declare function restoreSqlDump(request: SqlDumpRestoreRequest): Promise<SqlDumpRestoreResult>;
1833
+
1834
+ /**
1835
+ * Builds a collision-resistant identity string from ordered parts.
1836
+ *
1837
+ * Parts are length-prefixed rather than joined with a separator, because
1838
+ * SQLite identifiers may contain any character at all — including
1839
+ * whatever separator would otherwise be chosen. Without the prefix,
1840
+ * `["a.b", "c"]` and `["a", "b.c"]` would produce the same identity.
1841
+ */
1842
+ declare function createCanonicalIdentity(parts: readonly string[]): string;
1843
+ /** Stable short hash of a canonical identity, used as an archive entry's `dumpId`. */
1844
+ declare function createDumpId(identity: string): string;
1845
+
1846
+ interface DumpSqliteOptions {
1847
+ /** `'full'` (default): schema and data. `'schema-only'`: definitions only. `'data-only'`: rows only. */
1848
+ readonly mode?: DumpMode;
1849
+ /**
1850
+ * Schema to dump: `main` (default), `temp`, or an attached database's name.
1851
+ * The dump itself is schema-less — `CREATE TABLE t`, never
1852
+ * `CREATE TABLE aux.t` — so it restores into whatever database it is run
1853
+ * against, exactly like a native `.dump`.
1854
+ */
1855
+ readonly schemaName?: string;
1856
+ readonly selection?: DumpSelection;
1857
+ /** Which object kinds to include. All default to `true`, which is what the native `.dump` includes. */
1858
+ readonly objectKinds?: DumpObjectKinds;
1859
+ readonly render?: PlainSqlRenderOptions;
1860
+ /** Row rendering and batching options; see `exportTableDataAsInserts`. */
1861
+ readonly dataExport?: TableDataExportOptions;
1862
+ /**
1863
+ * How the dump obtains a consistent view. Defaults to `'snapshot'`; see
1864
+ * {@link SqliteConsistencyMode}.
1865
+ */
1866
+ readonly consistency?: SqliteConsistencyMode;
1867
+ }
1868
+ interface DumpResult {
1869
+ readonly bytesWritten: number;
1870
+ readonly renderedDumpIds: readonly string[];
1871
+ readonly skippedDumpIds: readonly string[];
1872
+ readonly warnings: readonly SqliteDiagnostic[];
1873
+ readonly cancelled: boolean;
1874
+ /** Total rows written across every exported table. */
1875
+ readonly rowsExported: number;
1876
+ /** Total `INSERT` statements written. */
1877
+ readonly statementsWritten: number;
1878
+ }
1879
+
1880
+ /**
1881
+ * Runs a complete SQLite dump: acquire one handle, open a read snapshot,
1882
+ * introspect, plan, render, and stream row data — writing plain SQL in the
1883
+ * native `.dump` layout to `output`.
1884
+ *
1885
+ * Everything happens on **one** handle inside **one** read transaction, so
1886
+ * every table is read from the same state of the database even while other
1887
+ * connections write to it. When a source is passed, one handle is acquired
1888
+ * for the whole dump and released afterwards; a bare connection is borrowed
1889
+ * and never closed.
1890
+ */
1891
+ declare function dumpSqlite(connectionInput: SqliteConnectionInput, options: DumpSqliteOptions, output: Writable, onProgress?: DumpProgressCallback, signal?: AbortSignal): Promise<DumpResult>;
1892
+
1893
+ export { AcquiredSqliteConnection, type ArchiveCycle, type ArchiveDependency, type ArchiveDependencyStrength, type ArchiveEntry, type ArchiveIdentityInput, type ArchiveObjectType, BufferDumpWriter, COMPLETE_TRANSITIONS, CompleteToken, DEFENSIVE_WARNING_COMMENT, type DotCommandPolicy, type DroppableKind, type DumpArchiveInspection, type DumpMode, type DumpObjectKinds, type DumpProgressCallback, type DumpProgressEvent, type DumpProgressPhase, type DumpProgressSection, type DumpResult, type DumpSection, type DumpSelection, type DumpSqliteOptions, type DumpWriter, type InspectDumpArchiveOptions, type IntrospectSqliteOptions, InvalidTextEncodingError, MalformedSqlDumpError, type NormalizedDumpSelection, OperationCancelledError, type ParsedStatement, type PlainSqlRenderOptions, type PlainSqlRenderRequest, type PlainSqlRenderResult, type PreflightRestoreReport, type PreflightRestoreRequest, type ResolvedPlainSqlRenderOptions, RestoreError, RestoreExecutionError, type RestoreOptions, type RestoreProgressCallback, type RestoreProgressEvent, type RestoreProgressPhase, RestoreSessionState, type RestoreStatementError, type RestoreWarning, SEQUENCE_TABLE_NAME, SESSION_GUARD_FOOTER, SESSION_GUARD_HEADER, SQLITE_KEYWORD_COUNT, type SkippedDotCommand, SqlChunkBuilder, type SqlDumpRestoreRequest, type SqlDumpRestoreResult, type SqlDumpSource, SqlParseError, SqlStatementParser, type SqlStatementParserOptions, type SqliteCapabilities, type SqliteColumn, type SqliteColumnHidden, SqliteConnection, SqliteConnectionInput, type SqliteConsistencyMode, type SqliteDatabase, type SqliteDiagnostic, type SqliteDiagnosticSeverity, type SqliteDumpSession, type SqliteDumpSessionOptions, SqliteDumperError, SqliteErrorInfo, SqliteExecResult, type SqliteForeignKey, type SqliteForeignKeyColumn, type SqliteIndex, type SqliteIndexColumn, type SqliteIntrospectionResult, type SqliteObjectKind, type SqliteObjectReference, SqliteRow, type SqliteSequence, type SqliteTable, type SqliteTableKind, type SqliteTrigger, type SqliteVersion, type SqliteView, type StatementInfo, type StatementSourceLocation, StatementTooLargeError, StreamDumpWriter, type TableDataExportOptions, type TableDataExportRequest, type TableDataExportResult, type TargetCapabilities, type TargetCompatibilityOptions, type TextLiteralStyle, UNSUPPORTED_FEATURES, type UnsatisfiedDependency, UnsupportedClientCommandError, WRITABLE_SCHEMA_OFF, WRITABLE_SCHEMA_ON, acquireSqliteConnection, assignDumpSection, beginSqliteDumpSession, checkTargetCompatibility, classifyWord, columnValueSelect, completeTransition, createArchiveIdentity, createCanonicalIdentity, createDumpId, declaresAutoincrement, decodeStatementBytes, describeStatement, detectSqliteCapabilities, detectSqliteVersion, detectSqliteCapabilities as detectTargetCapabilities, dumpSectionPriority, dumpSqlite, executeStatement, exportTableDataAsInserts, foldSqliteName, insertableColumns, inspectDumpArchive, introspectSqlite, isAbortError, isCompleteStatement, isIdentifierCharCode, isIndexSelected, isSchemaTableName, isSqliteDump, isSqliteKeyword, isStatisticsTableName, isTableDataExcluded, isTableSelected, isTriggerSelected, isTruthyPragmaValue, isViewSelected, maskSqlLiterals, needsIdentifierQuoting, normalizeDumpSelection, parseSqlStatements, parseSqliteVersion, parseTableOptions, parseVirtualTableModule, preflightRestore, preservableRowidName, quoteIdentifier, quoteIdentifierIfNeeded, quoteQualifiedIdentifier, quoteStringLiteral, redactSecrets, renderBlobLiteral, renderColumnLiteral, renderDatabaseSettings, renderDrop, renderEscapedStringLiteral, renderPlainSql, renderQuotedStringLiteral, renderSchemaLine, renderSchemaObject, renderSystemTablePrelude, renderTextLiteral, renderVirtualTable, resolvePlainSqlRenderOptions, restoreSqlDump, safeSqlPreview, streamSqlStatements, streamWithParser, tableGroupPriority, throwIfAborted, toAsciiLowerCase, toAsciiUpperCase, toByteStringChunks, toNumber, toText, unsupportedFeatureDiagnostics };