49e6fdc7851d43fc0dd34c797c9bd3f545e5aa0a2d5d12be62b3b20d424fd104d27286b89b7c1e07b234868d59b0f6c8f883fe64cd49635598b0a7e0f00444 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. /**
  2. * The `node:sqlite` module facilitates working with SQLite databases.
  3. * To access it:
  4. *
  5. * ```js
  6. * import sqlite from 'node:sqlite';
  7. * ```
  8. *
  9. * This module is only available under the `node:` scheme. The following will not
  10. * work:
  11. *
  12. * ```js
  13. * import sqlite from 'sqlite';
  14. * ```
  15. *
  16. * The following example shows the basic usage of the `node:sqlite` module to open
  17. * an in-memory database, write data to the database, and then read the data back.
  18. *
  19. * ```js
  20. * import { DatabaseSync } from 'node:sqlite';
  21. * const database = new DatabaseSync(':memory:');
  22. *
  23. * // Execute SQL statements from strings.
  24. * database.exec(`
  25. * CREATE TABLE data(
  26. * key INTEGER PRIMARY KEY,
  27. * value TEXT
  28. * ) STRICT
  29. * `);
  30. * // Create a prepared statement to insert data into the database.
  31. * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
  32. * // Execute the prepared statement with bound values.
  33. * insert.run(1, 'hello');
  34. * insert.run(2, 'world');
  35. * // Create a prepared statement to read data from the database.
  36. * const query = database.prepare('SELECT * FROM data ORDER BY key');
  37. * // Execute the prepared statement and log the result set.
  38. * console.log(query.all());
  39. * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]
  40. * ```
  41. * @since v22.5.0
  42. * @experimental
  43. * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/sqlite.js)
  44. */
  45. declare module "node:sqlite" {
  46. type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView;
  47. type SQLOutputValue = null | number | bigint | string | Uint8Array;
  48. /** @deprecated Use `SQLInputValue` or `SQLOutputValue` instead. */
  49. type SupportedValueType = SQLOutputValue;
  50. interface DatabaseSyncOptions {
  51. /**
  52. * If `true`, the database is opened by the constructor. When
  53. * this value is `false`, the database must be opened via the `open()` method.
  54. * @since v22.5.0
  55. * @default true
  56. */
  57. open?: boolean | undefined;
  58. /**
  59. * If `true`, foreign key constraints
  60. * are enabled. This is recommended but can be disabled for compatibility with
  61. * legacy database schemas. The enforcement of foreign key constraints can be
  62. * enabled and disabled after opening the database using
  63. * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys).
  64. * @since v22.10.0
  65. * @default true
  66. */
  67. enableForeignKeyConstraints?: boolean | undefined;
  68. /**
  69. * If `true`, SQLite will accept
  70. * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote).
  71. * This is not recommended but can be
  72. * enabled for compatibility with legacy database schemas.
  73. * @since v22.10.0
  74. * @default false
  75. */
  76. enableDoubleQuotedStringLiterals?: boolean | undefined;
  77. /**
  78. * If `true`, the database is opened in read-only mode.
  79. * If the database does not exist, opening it will fail.
  80. * @since v22.12.0
  81. * @default false
  82. */
  83. readOnly?: boolean | undefined;
  84. /**
  85. * If `true`, the `loadExtension` SQL function
  86. * and the `loadExtension()` method are enabled.
  87. * You can call `enableLoadExtension(false)` later to disable this feature.
  88. * @since v22.13.0
  89. * @default false
  90. */
  91. allowExtension?: boolean | undefined;
  92. /**
  93. * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of
  94. * time that SQLite will wait for a database lock to be released before
  95. * returning an error.
  96. * @since v24.0.0
  97. * @default 0
  98. */
  99. timeout?: number | undefined;
  100. /**
  101. * If `true`, integer fields are read as JavaScript `BigInt` values. If `false`,
  102. * integer fields are read as JavaScript numbers.
  103. * @since v24.4.0
  104. * @default false
  105. */
  106. readBigInts?: boolean | undefined;
  107. /**
  108. * If `true`, query results are returned as arrays instead of objects.
  109. * @since v24.4.0
  110. * @default false
  111. */
  112. returnArrays?: boolean | undefined;
  113. /**
  114. * If `true`, allows binding named parameters without the prefix
  115. * character (e.g., `foo` instead of `:foo`).
  116. * @since v24.4.40
  117. * @default true
  118. */
  119. allowBareNamedParameters?: boolean | undefined;
  120. /**
  121. * If `true`, unknown named parameters are ignored when binding.
  122. * If `false`, an exception is thrown for unknown named parameters.
  123. * @since v24.4.40
  124. * @default false
  125. */
  126. allowUnknownNamedParameters?: boolean | undefined;
  127. }
  128. interface CreateSessionOptions {
  129. /**
  130. * A specific table to track changes for. By default, changes to all tables are tracked.
  131. * @since v22.12.0
  132. */
  133. table?: string | undefined;
  134. /**
  135. * Name of the database to track. This is useful when multiple databases have been added using
  136. * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html).
  137. * @since v22.12.0
  138. * @default 'main'
  139. */
  140. db?: string | undefined;
  141. }
  142. interface ApplyChangesetOptions {
  143. /**
  144. * Skip changes that, when targeted table name is supplied to this function, return a truthy value.
  145. * By default, all changes are attempted.
  146. * @since v22.12.0
  147. */
  148. filter?: ((tableName: string) => boolean) | undefined;
  149. /**
  150. * A function that determines how to handle conflicts. The function receives one argument,
  151. * which can be one of the following values:
  152. *
  153. * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values.
  154. * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist.
  155. * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key.
  156. * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation.
  157. * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint
  158. * violation.
  159. *
  160. * The function should return one of the following values:
  161. *
  162. * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes.
  163. * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with
  164. `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts).
  165. * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database.
  166. *
  167. * When an error is thrown in the conflict handler or when any other value is returned from the handler,
  168. * applying the changeset is aborted and the database is rolled back.
  169. *
  170. * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`.
  171. * @since v22.12.0
  172. */
  173. onConflict?: ((conflictType: number) => number) | undefined;
  174. }
  175. interface FunctionOptions {
  176. /**
  177. * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is
  178. * set on the created function.
  179. * @default false
  180. */
  181. deterministic?: boolean | undefined;
  182. /**
  183. * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on
  184. * the created function.
  185. * @default false
  186. */
  187. directOnly?: boolean | undefined;
  188. /**
  189. * If `true`, integer arguments to `function`
  190. * are converted to `BigInt`s. If `false`, integer arguments are passed as
  191. * JavaScript numbers.
  192. * @default false
  193. */
  194. useBigIntArguments?: boolean | undefined;
  195. /**
  196. * If `true`, `function` may be invoked with any number of
  197. * arguments (between zero and
  198. * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`,
  199. * `function` must be invoked with exactly `function.length` arguments.
  200. * @default false
  201. */
  202. varargs?: boolean | undefined;
  203. }
  204. interface AggregateOptions<T extends SQLInputValue = SQLInputValue> extends FunctionOptions {
  205. /**
  206. * The identity value for the aggregation function. This value is used when the aggregation
  207. * function is initialized. When a `Function` is passed the identity will be its return value.
  208. */
  209. start: T | (() => T);
  210. /**
  211. * The function to call for each row in the aggregation. The
  212. * function receives the current state and the row value. The return value of
  213. * this function should be the new state.
  214. */
  215. step: (accumulator: T, ...args: SQLOutputValue[]) => T;
  216. /**
  217. * The function to call to get the result of the
  218. * aggregation. The function receives the final state and should return the
  219. * result of the aggregation.
  220. */
  221. result?: ((accumulator: T) => SQLInputValue) | undefined;
  222. /**
  223. * When this function is provided, the `aggregate` method will work as a window function.
  224. * The function receives the current state and the dropped row value. The return value of this function should be the
  225. * new state.
  226. */
  227. inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined;
  228. }
  229. /**
  230. * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs
  231. * exposed by this class execute synchronously.
  232. * @since v22.5.0
  233. */
  234. class DatabaseSync implements Disposable {
  235. /**
  236. * Constructs a new `DatabaseSync` instance.
  237. * @param path The path of the database.
  238. * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html).
  239. * To use a file-backed database, the path should be a file path.
  240. * To use an in-memory database, the path should be the special name `':memory:'`.
  241. * @param options Configuration options for the database connection.
  242. */
  243. constructor(path: string | Buffer | URL, options?: DatabaseSyncOptions);
  244. /**
  245. * Registers a new aggregate function with the SQLite database. This method is a wrapper around
  246. * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html).
  247. *
  248. * When used as a window function, the `result` function will be called multiple times.
  249. *
  250. * ```js
  251. * import { DatabaseSync } from 'node:sqlite';
  252. *
  253. * const db = new DatabaseSync(':memory:');
  254. * db.exec(`
  255. * CREATE TABLE t3(x, y);
  256. * INSERT INTO t3 VALUES ('a', 4),
  257. * ('b', 5),
  258. * ('c', 3),
  259. * ('d', 8),
  260. * ('e', 1);
  261. * `);
  262. *
  263. * db.aggregate('sumint', {
  264. * start: 0,
  265. * step: (acc, value) => acc + value,
  266. * });
  267. *
  268. * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }
  269. * ```
  270. * @since v24.0.0
  271. * @param name The name of the SQLite function to create.
  272. * @param options Function configuration settings.
  273. */
  274. aggregate(name: string, options: AggregateOptions): void;
  275. aggregate<T extends SQLInputValue>(name: string, options: AggregateOptions<T>): void;
  276. /**
  277. * Closes the database connection. An exception is thrown if the database is not
  278. * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html).
  279. * @since v22.5.0
  280. */
  281. close(): void;
  282. /**
  283. * Loads a shared library into the database connection. This method is a wrapper
  284. * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the
  285. * `allowExtension` option when constructing the `DatabaseSync` instance.
  286. * @since v22.13.0
  287. * @param path The path to the shared library to load.
  288. */
  289. loadExtension(path: string): void;
  290. /**
  291. * Enables or disables the `loadExtension` SQL function, and the `loadExtension()`
  292. * method. When `allowExtension` is `false` when constructing, you cannot enable
  293. * loading extensions for security reasons.
  294. * @since v22.13.0
  295. * @param allow Whether to allow loading extensions.
  296. */
  297. enableLoadExtension(allow: boolean): void;
  298. /**
  299. * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html)
  300. * @since v24.0.0
  301. * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other
  302. * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`.
  303. * @returns The location of the database file. When using an in-memory database,
  304. * this method returns null.
  305. */
  306. location(dbName?: string): string | null;
  307. /**
  308. * This method allows one or more SQL statements to be executed without returning
  309. * any results. This method is useful when executing SQL statements read from a
  310. * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html).
  311. * @since v22.5.0
  312. * @param sql A SQL string to execute.
  313. */
  314. exec(sql: string): void;
  315. /**
  316. * This method is used to create SQLite user-defined functions. This method is a
  317. * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html).
  318. * @since v22.13.0
  319. * @param name The name of the SQLite function to create.
  320. * @param options Optional configuration settings for the function.
  321. * @param func The JavaScript function to call when the SQLite
  322. * function is invoked. The return value of this function should be a valid
  323. * SQLite data type: see
  324. * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite).
  325. * The result defaults to `NULL` if the return value is `undefined`.
  326. */
  327. function(
  328. name: string,
  329. options: FunctionOptions,
  330. func: (...args: SQLOutputValue[]) => SQLInputValue,
  331. ): void;
  332. function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void;
  333. /**
  334. * Whether the database is currently open or not.
  335. * @since v22.15.0
  336. */
  337. readonly isOpen: boolean;
  338. /**
  339. * Whether the database is currently within a transaction. This method
  340. * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html).
  341. * @since v24.0.0
  342. */
  343. readonly isTransaction: boolean;
  344. /**
  345. * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via
  346. * the constructor. An exception is thrown if the database is already open.
  347. * @since v22.5.0
  348. */
  349. open(): void;
  350. /**
  351. * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper
  352. * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html).
  353. * @since v22.5.0
  354. * @param sql A SQL string to compile to a prepared statement.
  355. * @return The prepared statement.
  356. */
  357. prepare(sql: string): StatementSync;
  358. /**
  359. * Creates and attaches a session to the database. This method is a wrapper around
  360. * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and
  361. * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html).
  362. * @param options The configuration options for the session.
  363. * @returns A session handle.
  364. * @since v22.12.0
  365. */
  366. createSession(options?: CreateSessionOptions): Session;
  367. /**
  368. * An exception is thrown if the database is not
  369. * open. This method is a wrapper around
  370. * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html).
  371. *
  372. * ```js
  373. * const sourceDb = new DatabaseSync(':memory:');
  374. * const targetDb = new DatabaseSync(':memory:');
  375. *
  376. * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
  377. * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
  378. *
  379. * const session = sourceDb.createSession();
  380. *
  381. * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
  382. * insert.run(1, 'hello');
  383. * insert.run(2, 'world');
  384. *
  385. * const changeset = session.changeset();
  386. * targetDb.applyChangeset(changeset);
  387. * // Now that the changeset has been applied, targetDb contains the same data as sourceDb.
  388. * ```
  389. * @param changeset A binary changeset or patchset.
  390. * @param options The configuration options for how the changes will be applied.
  391. * @returns Whether the changeset was applied successfully without being aborted.
  392. * @since v22.12.0
  393. */
  394. applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean;
  395. /**
  396. * Closes the database connection. If the database connection is already closed
  397. * then this is a no-op.
  398. * @since v22.15.0
  399. */
  400. [Symbol.dispose](): void;
  401. }
  402. /**
  403. * @since v22.12.0
  404. */
  405. interface Session {
  406. /**
  407. * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times.
  408. * An exception is thrown if the database or the session is not open. This method is a wrapper around
  409. * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html).
  410. * @returns Binary changeset that can be applied to other databases.
  411. * @since v22.12.0
  412. */
  413. changeset(): Uint8Array;
  414. /**
  415. * Similar to the method above, but generates a more compact patchset. See
  416. * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets)
  417. * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a
  418. * wrapper around
  419. * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html).
  420. * @returns Binary patchset that can be applied to other databases.
  421. * @since v22.12.0
  422. */
  423. patchset(): Uint8Array;
  424. /**
  425. * Closes the session. An exception is thrown if the database or the session is not open. This method is a
  426. * wrapper around
  427. * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html).
  428. */
  429. close(): void;
  430. }
  431. interface StatementColumnMetadata {
  432. /**
  433. * The unaliased name of the column in the origin
  434. * table, or `null` if the column is the result of an expression or subquery.
  435. * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html).
  436. */
  437. column: string | null;
  438. /**
  439. * The unaliased name of the origin database, or
  440. * `null` if the column is the result of an expression or subquery. This
  441. * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html).
  442. */
  443. database: string | null;
  444. /**
  445. * The name assigned to the column in the result set of a
  446. * `SELECT` statement. This property is the result of
  447. * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html).
  448. */
  449. name: string;
  450. /**
  451. * The unaliased name of the origin table, or `null` if
  452. * the column is the result of an expression or subquery. This property is the
  453. * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html).
  454. */
  455. table: string | null;
  456. /**
  457. * The declared data type of the column, or `null` if the
  458. * column is the result of an expression or subquery. This property is the
  459. * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html).
  460. */
  461. type: string | null;
  462. }
  463. interface StatementResultingChanges {
  464. /**
  465. * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement.
  466. * This field is either a number or a `BigInt` depending on the prepared statement's configuration.
  467. * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html).
  468. */
  469. changes: number | bigint;
  470. /**
  471. * The most recently inserted rowid.
  472. * This field is either a number or a `BigInt` depending on the prepared statement's configuration.
  473. * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html).
  474. */
  475. lastInsertRowid: number | bigint;
  476. }
  477. /**
  478. * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be
  479. * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute
  480. * synchronously.
  481. *
  482. * A prepared statement is an efficient binary representation of the SQL used to
  483. * create it. Prepared statements are parameterizable, and can be invoked multiple
  484. * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are
  485. * preferred
  486. * over hand-crafted SQL strings when handling user input.
  487. * @since v22.5.0
  488. */
  489. class StatementSync {
  490. private constructor();
  491. /**
  492. * This method executes a prepared statement and returns all results as an array of
  493. * objects. If the prepared statement does not return any results, this method
  494. * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using
  495. * the values in `namedParameters` and `anonymousParameters`.
  496. * @since v22.5.0
  497. * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping.
  498. * @param anonymousParameters Zero or more values to bind to anonymous parameters.
  499. * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of
  500. * the row.
  501. */
  502. all(...anonymousParameters: SQLInputValue[]): Record<string, SQLOutputValue>[];
  503. all(
  504. namedParameters: Record<string, SQLInputValue>,
  505. ...anonymousParameters: SQLInputValue[]
  506. ): Record<string, SQLOutputValue>[];
  507. /**
  508. * This method is used to retrieve information about the columns returned by the
  509. * prepared statement.
  510. * @since v23.11.0
  511. * @returns An array of objects. Each object corresponds to a column
  512. * in the prepared statement, and contains the following properties:
  513. */
  514. columns(): StatementColumnMetadata[];
  515. /**
  516. * The source SQL text of the prepared statement with parameter
  517. * placeholders replaced by the values that were used during the most recent
  518. * execution of this prepared statement. This property is a wrapper around
  519. * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html).
  520. * @since v22.5.0
  521. */
  522. readonly expandedSQL: string;
  523. /**
  524. * This method executes a prepared statement and returns the first result as an
  525. * object. If the prepared statement does not return any results, this method
  526. * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the
  527. * values in `namedParameters` and `anonymousParameters`.
  528. * @since v22.5.0
  529. * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping.
  530. * @param anonymousParameters Zero or more values to bind to anonymous parameters.
  531. * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no
  532. * rows were returned from the database then this method returns `undefined`.
  533. */
  534. get(...anonymousParameters: SQLInputValue[]): Record<string, SQLOutputValue> | undefined;
  535. get(
  536. namedParameters: Record<string, SQLInputValue>,
  537. ...anonymousParameters: SQLInputValue[]
  538. ): Record<string, SQLOutputValue> | undefined;
  539. /**
  540. * This method executes a prepared statement and returns an iterator of
  541. * objects. If the prepared statement does not return any results, this method
  542. * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using
  543. * the values in `namedParameters` and `anonymousParameters`.
  544. * @since v22.13.0
  545. * @param namedParameters An optional object used to bind named parameters.
  546. * The keys of this object are used to configure the mapping.
  547. * @param anonymousParameters Zero or more values to bind to anonymous parameters.
  548. * @returns An iterable iterator of objects. Each object corresponds to a row
  549. * returned by executing the prepared statement. The keys and values of each
  550. * object correspond to the column names and values of the row.
  551. */
  552. iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator<Record<string, SQLOutputValue>>;
  553. iterate(
  554. namedParameters: Record<string, SQLInputValue>,
  555. ...anonymousParameters: SQLInputValue[]
  556. ): NodeJS.Iterator<Record<string, SQLOutputValue>>;
  557. /**
  558. * This method executes a prepared statement and returns an object summarizing the
  559. * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the
  560. * values in `namedParameters` and `anonymousParameters`.
  561. * @since v22.5.0
  562. * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping.
  563. * @param anonymousParameters Zero or more values to bind to anonymous parameters.
  564. */
  565. run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges;
  566. run(
  567. namedParameters: Record<string, SQLInputValue>,
  568. ...anonymousParameters: SQLInputValue[]
  569. ): StatementResultingChanges;
  570. /**
  571. * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding
  572. * parameters. However, with the exception of dollar sign character, these
  573. * prefix characters also require extra quoting when used in object keys.
  574. *
  575. * To improve ergonomics, this method can be used to also allow bare named
  576. * parameters, which do not require the prefix character in JavaScript code. There
  577. * are several caveats to be aware of when enabling bare named parameters:
  578. *
  579. * * The prefix character is still required in SQL.
  580. * * The prefix character is still allowed in JavaScript. In fact, prefixed names
  581. * will have slightly better binding performance.
  582. * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared
  583. * statement will result in an exception as it cannot be determined how to bind
  584. * a bare name.
  585. * @since v22.5.0
  586. * @param enabled Enables or disables support for binding named parameters without the prefix character.
  587. */
  588. setAllowBareNamedParameters(enabled: boolean): void;
  589. /**
  590. * By default, if an unknown name is encountered while binding parameters, an
  591. * exception is thrown. This method allows unknown named parameters to be ignored.
  592. * @since v22.15.0
  593. * @param enabled Enables or disables support for unknown named parameters.
  594. */
  595. setAllowUnknownNamedParameters(enabled: boolean): void;
  596. /**
  597. * When enabled, query results returned by the `all()`, `get()`, and `iterate()` methods will be returned as arrays instead
  598. * of objects.
  599. * @since v24.0.0
  600. * @param enabled Enables or disables the return of query results as arrays.
  601. */
  602. setReturnArrays(enabled: boolean): void;
  603. /**
  604. * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript
  605. * numbers by default. However, SQLite `INTEGER`s can store values larger than
  606. * JavaScript numbers are capable of representing. In such cases, this method can
  607. * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no
  608. * impact on database write operations where numbers and `BigInt`s are both
  609. * supported at all times.
  610. * @since v22.5.0
  611. * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database.
  612. */
  613. setReadBigInts(enabled: boolean): void;
  614. /**
  615. * The source SQL text of the prepared statement. This property is a
  616. * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html).
  617. * @since v22.5.0
  618. */
  619. readonly sourceSQL: string;
  620. }
  621. interface BackupOptions {
  622. /**
  623. * Name of the source database. This can be `'main'` (the default primary database) or any other
  624. * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html)
  625. * @default 'main'
  626. */
  627. source?: string | undefined;
  628. /**
  629. * Name of the target database. This can be `'main'` (the default primary database) or any other
  630. * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html)
  631. * @default 'main'
  632. */
  633. target?: string | undefined;
  634. /**
  635. * Number of pages to be transmitted in each batch of the backup.
  636. * @default 100
  637. */
  638. rate?: number | undefined;
  639. /**
  640. * Callback function that will be called with the number of pages copied and the total number of
  641. * pages.
  642. */
  643. progress?: ((progressInfo: BackupProgressInfo) => void) | undefined;
  644. }
  645. interface BackupProgressInfo {
  646. totalPages: number;
  647. remainingPages: number;
  648. }
  649. /**
  650. * This method makes a database backup. This method abstracts the
  651. * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit),
  652. * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep)
  653. * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions.
  654. *
  655. * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same
  656. * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause
  657. * the backup process to restart.
  658. *
  659. * ```js
  660. * import { backup, DatabaseSync } from 'node:sqlite';
  661. *
  662. * const sourceDb = new DatabaseSync('source.db');
  663. * const totalPagesTransferred = await backup(sourceDb, 'backup.db', {
  664. * rate: 1, // Copy one page at a time.
  665. * progress: ({ totalPages, remainingPages }) => {
  666. * console.log('Backup in progress', { totalPages, remainingPages });
  667. * },
  668. * });
  669. *
  670. * console.log('Backup completed', totalPagesTransferred);
  671. * ```
  672. * @since v23.8.0
  673. * @param sourceDb The database to backup. The source database must be open.
  674. * @param path The path where the backup will be created. If the file already exists,
  675. * the contents will be overwritten.
  676. * @param options Optional configuration for the backup. The
  677. * following properties are supported:
  678. * @returns A promise that resolves when the backup is completed and rejects if an error occurs.
  679. */
  680. function backup(sourceDb: DatabaseSync, path: string | Buffer | URL, options?: BackupOptions): Promise<void>;
  681. /**
  682. * @since v22.13.0
  683. */
  684. namespace constants {
  685. /**
  686. * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values.
  687. * @since v22.14.0
  688. */
  689. const SQLITE_CHANGESET_DATA: number;
  690. /**
  691. * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database.
  692. * @since v22.14.0
  693. */
  694. const SQLITE_CHANGESET_NOTFOUND: number;
  695. /**
  696. * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values.
  697. * @since v22.14.0
  698. */
  699. const SQLITE_CHANGESET_CONFLICT: number;
  700. /**
  701. * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back.
  702. * @since v22.14.0
  703. */
  704. const SQLITE_CHANGESET_FOREIGN_KEY: number;
  705. /**
  706. * Conflicting changes are omitted.
  707. * @since v22.12.0
  708. */
  709. const SQLITE_CHANGESET_OMIT: number;
  710. /**
  711. * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`.
  712. * @since v22.12.0
  713. */
  714. const SQLITE_CHANGESET_REPLACE: number;
  715. /**
  716. * Abort when a change encounters a conflict and roll back database.
  717. * @since v22.12.0
  718. */
  719. const SQLITE_CHANGESET_ABORT: number;
  720. }
  721. }