Spec-Zone.ru › Deno 2

sqlite

Deno compatibility

This module has been added in Deno v2.2.

The node:sqlite module facilitates working with SQLite databases. To access it:

import sqlite from 'node:sqlite';

This module is only available under the node: scheme. The following will not work:

import sqlite from 'sqlite';

The following example shows the basic usage of the node:sqlite module to open an in-memory database, write data to the database, and then read the data back.

import { DatabaseSync } from 'node:sqlite';
const database = new DatabaseSync(':memory:');

// Execute SQL statements from strings.
database.exec(`
  CREATE TABLE data(
    key INTEGER PRIMARY KEY,
    value TEXT
  ) STRICT
`);
// Create a prepared statement to insert data into the database.
const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
// Execute the prepared statement with bound values.
insert.run(1, 'hello');
insert.run(2, 'world');
// Create a prepared statement to read data from the database.
const query = database.prepare('SELECT * FROM data ORDER BY key');
// Execute the prepared statement and log the result set.
console.log(query.all());
// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]

Usage in Deno

import * as mod from "node:sqlite";

class DatabaseSync

Usage in Deno

import { DatabaseSync } from "node:sqlite";

This class represents a single connection to a SQLite database. All APIs exposed by this class execute synchronously.

Constructors

DatabaseSync(
location: string,
options?: DatabaseSyncOptions,
)
new

Constructs a new DatabaseSync instance.

Methods

applyChangeset(
changeset: Uint8Array,
options?: ApplyChangesetOptions,
): boolean

An exception is thrown if the database is not open. This method is a wrapper around sqlite3changeset_apply().

const sourceDb = new DatabaseSync(':memory:');
const targetDb = new DatabaseSync(':memory:');

sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');
targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');

const session = sourceDb.createSession();

const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
insert.run(1, 'hello');
insert.run(2, 'world');

const changeset = session.changeset();
targetDb.applyChangeset(changeset);
// Now that the changeset has been applied, targetDb contains the same data as sourceDb.
close(): void

Closes the database connection. An exception is thrown if the database is not open. This method is a wrapper around sqlite3_close_v2().

createSession(options?: CreateSessionOptions): Session

Creates and attaches a session to the database. This method is a wrapper around sqlite3session_create() and sqlite3session_attach().

enableLoadExtension(allow: boolean): void

Enables or disables the loadExtension SQL function, and the loadExtension() method. When allowExtension is false when constructing, you cannot enable loading extensions for security reasons.

exec(sql: string): void

This method allows one or more SQL statements to be executed without returning any results. This method is useful when executing SQL statements read from a file. This method is a wrapper around sqlite3_exec().

function(
name: string,
options: FunctionOptions,
func: (...args: SupportedValueType[]) => SupportedValueType,
): void

This method is used to create SQLite user-defined functions. This method is a wrapper around sqlite3_create_function_v2().

function(
name: string,
func: (...args: SupportedValueType[]) => SupportedValueType,
): void
loadExtension(path: string): void

Loads a shared library into the database connection. This method is a wrapper around sqlite3_load_extension(). It is required to enable the allowExtension option when constructing the DatabaseSync instance.

open(): void

Opens the database specified in the location argument of the DatabaseSyncconstructor. This method should only be used when the database is not opened via the constructor. An exception is thrown if the database is already open.

prepare(sql: string): StatementSync

Compiles a SQL statement into a prepared statement. This method is a wrapper around sqlite3_prepare_v2().


class StatementSync

Usage in Deno

import { StatementSync } from "node:sqlite";

This class represents a single prepared statement. This class cannot be instantiated via its constructor. Instead, instances are created via thedatabase.prepare() method. All APIs exposed by this class execute synchronously.

A prepared statement is an efficient binary representation of the SQL used to create it. Prepared statements are parameterizable, and can be invoked multiple times with different bound values. Parameters also offer protection against SQL injection attacks. For these reasons, prepared statements are preferred over hand-crafted SQL strings when handling user input.

Constructors

StatementSync()
new

Properties

expandedSQL: string
readonly

The source SQL text of the prepared statement with parameter placeholders replaced by the values that were used during the most recent execution of this prepared statement. This property is a wrapper around sqlite3_expanded_sql().

sourceSQL: string
readonly

The source SQL text of the prepared statement. This property is a wrapper around sqlite3_sql().

Methods

all(...anonymousParameters: SQLInputValue[]): Record<string, SQLOutputValue>[]

This method executes a prepared statement and returns all results as an array of objects. If the prepared statement does not return any results, this method returns an empty array. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

all(
namedParameters: Record<string, SQLInputValue>,
...anonymousParameters: SQLInputValue[],
): Record<string, SQLOutputValue>[]
get(...anonymousParameters: SQLInputValue[]): Record<string, SQLOutputValue> | undefined

This method executes a prepared statement and returns the first result as an object. If the prepared statement does not return any results, this method returns undefined. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

get(
namedParameters: Record<string, SQLInputValue>,
...anonymousParameters: SQLInputValue[],
): Record<string, SQLOutputValue> | undefined
iterate(...anonymousParameters: SQLInputValue[]): Iterator<Record<string, SQLOutputValue>>

This method executes a prepared statement and returns an iterator of objects. If the prepared statement does not return any results, this method returns an empty iterator. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

iterate(
namedParameters: Record<string, SQLInputValue>,
...anonymousParameters: SQLInputValue[],
): Iterator<Record<string, SQLOutputValue>>
run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges

This method executes a prepared statement and returns an object summarizing the resulting changes. The prepared statement parameters are bound using the values in namedParameters and anonymousParameters.

run(
namedParameters: Record<string, SQLInputValue>,
...anonymousParameters: SQLInputValue[],
): StatementResultingChanges
setAllowBareNamedParameters(enabled: boolean): void

The names of SQLite parameters begin with a prefix character. By default,node:sqlite requires that this prefix character is present when binding parameters. However, with the exception of dollar sign character, these prefix characters also require extra quoting when used in object keys.

To improve ergonomics, this method can be used to also allow bare named parameters, which do not require the prefix character in JavaScript code. There are several caveats to be aware of when enabling bare named parameters:

  • The prefix character is still required in SQL.
  • The prefix character is still allowed in JavaScript. In fact, prefixed names will have slightly better binding performance.
  • Using ambiguous named parameters, such as $k and @k, in the same prepared statement will result in an exception as it cannot be determined how to bind a bare name.
setReadBigInts(enabled: boolean): void

When reading from the database, SQLite INTEGERs are mapped to JavaScript numbers by default. However, SQLite INTEGERs can store values larger than JavaScript numbers are capable of representing. In such cases, this method can be used to read INTEGER data using JavaScript BigInts. This method has no impact on database write operations where numbers and BigInts are both supported at all times.


interface ApplyChangesetOptions

Usage in Deno

import { type ApplyChangesetOptions } from "node:sqlite";

Properties

filter: ((tableName: string) => boolean) | undefined
optional

Skip changes that, when targeted table name is supplied to this function, return a truthy value. By default, all changes are attempted.

onConflict: ((conflictType: number) => number) | undefined
optional

A function that determines how to handle conflicts. The function receives one argument, which can be one of the following values:

  • SQLITE_CHANGESET_DATA: A DELETE or UPDATE change does not contain the expected "before" values.
  • SQLITE_CHANGESET_NOTFOUND: A row matching the primary key of the DELETE or UPDATE change does not exist.
  • SQLITE_CHANGESET_CONFLICT: An INSERT change results in a duplicate primary key.
  • SQLITE_CHANGESET_FOREIGN_KEY: Applying a change would result in a foreign key violation.
  • SQLITE_CHANGESET_CONSTRAINT: Applying a change results in a UNIQUE, CHECK, or NOT NULL constraint violation.

The function should return one of the following values:

  • SQLITE_CHANGESET_OMIT: Omit conflicting changes.
  • SQLITE_CHANGESET_REPLACE: Replace existing values with conflicting changes (only valid with SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT conflicts).
  • SQLITE_CHANGESET_ABORT: Abort on conflict and roll back the database.

When an error is thrown in the conflict handler or when any other value is returned from the handler, applying the changeset is aborted and the database is rolled back.

Default: A function that returns SQLITE_CHANGESET_ABORT.


interface CreateSessionOptions

Usage in Deno

import { type CreateSessionOptions } from "node:sqlite";

Properties

table: string | undefined
optional

A specific table to track changes for. By default, changes to all tables are tracked.

db: string | undefined
optional

Name of the database to track. This is useful when multiple databases have been added using ATTACH DATABASE.


interface DatabaseSyncOptions

Usage in Deno

import { type DatabaseSyncOptions } from "node:sqlite";

Properties

open: boolean | undefined
optional

If true, the database is opened by the constructor. When this value is false, the database must be opened via the open() method.

enableForeignKeyConstraints: boolean | undefined
optional

If true, foreign key constraints are enabled. This is recommended but can be disabled for compatibility with legacy database schemas. The enforcement of foreign key constraints can be enabled and disabled after opening the database using PRAGMA foreign_keys.

enableDoubleQuotedStringLiterals: boolean | undefined
optional

If true, SQLite will accept double-quoted string literals. This is not recommended but can be enabled for compatibility with legacy database schemas.

readOnly: boolean | undefined
optional

If true, the database is opened in read-only mode. If the database does not exist, opening it will fail.

allowExtension: boolean | undefined
optional

If true, the loadExtension SQL function and the loadExtension() method are enabled. You can call enableLoadExtension(false) later to disable this feature.


interface FunctionOptions

Usage in Deno

import { type FunctionOptions } from "node:sqlite";

Properties

deterministic: boolean | undefined
optional

If true, the SQLITE_DETERMINISTIC flag is set on the created function.

directOnly: boolean | undefined
optional

If true, the SQLITE_DIRECTONLY flag is set on the created function.

useBigIntArguments: boolean | undefined
optional

If true, integer arguments to function are converted to BigInts. If false, integer arguments are passed as JavaScript numbers.

varargs: boolean | undefined
optional

If true, function can accept a variable number of arguments. If false, function must be invoked with exactly function.length arguments.


interface Session

Usage in Deno

import { type Session } from "node:sqlite";

Methods

changeset(): Uint8Array

Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. An exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_changeset().

patchset(): Uint8Array

Similar to the method above, but generates a more compact patchset. See Changesets and Patchsets in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_patchset().

close(): void

Closes the session. An exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_delete().


interface StatementResultingChanges

Usage in Deno

import { type StatementResultingChanges } from "node:sqlite";

Properties

changes: number | bigint

The number of rows modified, inserted, or deleted by the most recently completed INSERT, UPDATE, or DELETE statement. This field is either a number or a BigInt depending on the prepared statement's configuration. This property is the result of sqlite3_changes64().

lastInsertRowid: number | bigint

The most recently inserted rowid. This field is either a number or a BigInt depending on the prepared statement's configuration. This property is the result of sqlite3_last_insert_rowid().


namespace constants

Usage in Deno

import { constants } from "node:sqlite";

Variables

constants.SQLITE_CHANGESET_ABORT

Abort when a change encounters a conflict and roll back database.

constants.SQLITE_CHANGESET_CONFLICT

This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values.

constants.SQLITE_CHANGESET_DATA

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.

constants.SQLITE_CHANGESET_FOREIGN_KEY

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.

constants.SQLITE_CHANGESET_NOTFOUND

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.

constants.SQLITE_CHANGESET_OMIT

Conflicting changes are omitted.

constants.SQLITE_CHANGESET_REPLACE

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.


type alias SQLInputValue

unstable

Usage in Deno

import { type SQLInputValue } from "node:sqlite";
Deno compatibility

This module has been added in Deno v2.2.

The node:sqlite module facilitates working with SQLite databases. To access it:

import sqlite from 'node:sqlite';

This module is only available under the node: scheme. The following will not work:

import sqlite from 'sqlite';

The following example shows the basic usage of the node:sqlite module to open an in-memory database, write data to the database, and then read the data back.

import { DatabaseSync } from 'node:sqlite';
const database = new DatabaseSync(':memory:');

// Execute SQL statements from strings.
database.exec(`
  CREATE TABLE data(
    key INTEGER PRIMARY KEY,
    value TEXT
  ) STRICT
`);
// Create a prepared statement to insert data into the database.
const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');
// Execute the prepared statement with bound values.
insert.run(1, 'hello');
insert.run(2, 'world');
// Create a prepared statement to read data from the database.
const query = database.prepare('SELECT * FROM data ORDER BY key');
// Execute the prepared statement and log the result set.
console.log(query.all());
// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]

Definition

null
| number
| bigint
| string
| ArrayBufferView

See

  • source


type alias SQLOutputValue

Usage in Deno

import { type SQLOutputValue } from "node:sqlite";

Definition

null
| number
| bigint
| string
| Uint8Array

type alias SupportedValueType

Usage in Deno

import { type SupportedValueType } from "node:sqlite";
Deprecated

Use SQLInputValue or SQLOutputValue instead.

Definition

SQLOutputValue

variable constants.SQLITE_CHANGESET_ABORT

Usage in Deno

import { constants } from "node:sqlite";

Abort when a change encounters a conflict and roll back database.

Type

number

variable constants.SQLITE_CHANGESET_CONFLICT

Usage in Deno

import { constants } from "node:sqlite";

This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values.

Type

number

variable constants.SQLITE_CHANGESET_DATA

Usage in Deno

import { constants } from "node:sqlite";

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.

Type

number

variable constants.SQLITE_CHANGESET_FOREIGN_KEY

Usage in Deno

import { constants } from "node:sqlite";

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.

Type

number

variable constants.SQLITE_CHANGESET_NOTFOUND

Usage in Deno

import { constants } from "node:sqlite";

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.

Type

number

variable constants.SQLITE_CHANGESET_OMIT

Usage in Deno

import { constants } from "node:sqlite";

Conflicting changes are omitted.

Type

number

variable constants.SQLITE_CHANGESET_REPLACE

Usage in Deno

import { constants } from "node:sqlite";

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.

Type

number

© 2018–2025 the Deno authors
Licensed under the MIT License.
https://docs.deno.com/api/node/sqlite

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API