Convert Figma logo to code with AI

WiseLibs logobetter-sqlite3

The fastest and simplest library for SQLite3 in Node.js.

5,385
394
5,385
85

Top Related Projects

SQLite3 bindings for Node.js

Hosting read-only SQLite databases on static file hosters like Github Pages

Quick Overview

Better-sqlite3 is a high-performance SQLite3 driver for Node.js, offering both a synchronous and asynchronous API. It's designed to be faster and more efficient than other SQLite libraries for Node.js, with a focus on developer-friendly features and robust error handling.

Pros

  • Excellent performance, often outperforming other SQLite libraries for Node.js
  • Supports both synchronous and asynchronous operations
  • Provides advanced features like prepared statements and user-defined functions
  • Thorough documentation and active community support

Cons

  • Synchronous API can potentially block the event loop if not used carefully
  • Requires native build tools, which can complicate installation on some systems
  • Limited to SQLite, not suitable for projects requiring other database systems
  • May have a steeper learning curve for developers new to SQLite

Code Examples

  1. Creating a database connection and executing a simple query:
const Database = require('better-sqlite3');
const db = new Database('foobar.db', { verbose: console.log });

const row = db.prepare('SELECT * FROM users WHERE id = ?').get(1);
console.log(row.firstName, row.lastName, row.email);
  1. Using prepared statements for better performance:
const stmt = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');

const insertUser = db.transaction((users) => {
  for (const user of users) stmt.run(user.name, user.email);
});

insertUser([
  { name: 'Joey', email: 'joey@example.com' },
  { name: 'Sally', email: 'sally@example.com' }
]);
  1. Creating and using a user-defined function:
db.function('add2', (a, b) => a + b);

const result = db.prepare('SELECT add2(?, ?)').get(12, 3);
console.log(result['add2(?, ?)']; // Outputs: 15

Getting Started

To get started with better-sqlite3, first install it via npm:

npm install better-sqlite3

Then, in your Node.js application:

const Database = require('better-sqlite3');
const db = new Database('mydb.sqlite', { verbose: console.log });

// Create a table
db.exec(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    email TEXT UNIQUE
  )
`);

// Insert a user
const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
const info = insert.run('John Doe', 'john@example.com');

console.log(`A row has been inserted with rowid ${info.lastInsertRowid}`);

// Close the database connection when done
db.close();

This example creates a new SQLite database, creates a table, inserts a row, and then closes the connection.

Competitor Comparisons

SQLite3 bindings for Node.js

Pros of node-sqlite3

  • More established and widely used in the Node.js ecosystem
  • Supports asynchronous operations, which can be beneficial for I/O-bound applications
  • Offers a familiar API for developers coming from other SQLite bindings

Cons of node-sqlite3

  • Generally slower performance compared to better-sqlite3
  • Lacks some advanced features and optimizations present in better-sqlite3
  • Asynchronous nature can lead to more complex code in certain scenarios

Code Comparison

node-sqlite3:

db.serialize(() => {
  db.run("CREATE TABLE users (id INT, name TEXT)");
  db.run("INSERT INTO users VALUES (?, ?)", [1, "John"]);
  db.each("SELECT * FROM users", (err, row) => {
    console.log(row);
  });
});

better-sqlite3:

const db = new Database('foobar.db');
db.prepare("CREATE TABLE users (id INT, name TEXT)").run();
db.prepare("INSERT INTO users VALUES (?, ?)").run(1, "John");
const rows = db.prepare("SELECT * FROM users").all();
console.log(rows);

The code comparison shows that better-sqlite3 offers a more straightforward and synchronous API, potentially leading to simpler and more readable code. node-sqlite3, on the other hand, uses callbacks and a serialized approach for query execution.

Hosting read-only SQLite databases on static file hosters like Github Pages

Pros of sql.js-httpvfs

  • Runs entirely in the browser, enabling client-side SQLite operations
  • Supports virtual file system for efficient loading of large databases
  • Works well with static hosting and serverless architectures

Cons of sql.js-httpvfs

  • Generally slower performance compared to native SQLite implementations
  • Limited to JavaScript ecosystem and browser environments
  • May have compatibility issues with certain SQLite features or extensions

Code Comparison

sql.js-httpvfs:

const worker = await createDbWorker(
  [{ from: "inline", config: { serverMode: "full" } }],
  "/sqlite-wasm-worker.js",
  "/sqlite-wasm.wasm"
);
const result = await worker.db.query("SELECT * FROM users");

better-sqlite3:

const Database = require('better-sqlite3');
const db = new Database('foobar.db', { readonly: true });
const row = db.prepare('SELECT * FROM users WHERE id = ?').get(userId);

Both libraries provide SQLite functionality, but sql.js-httpvfs is designed for browser use with virtual file system support, while better-sqlite3 offers native performance for Node.js applications. The code examples illustrate the different approaches to querying a database, with sql.js-httpvfs using a worker-based asynchronous model and better-sqlite3 providing a synchronous API.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

better-sqlite3 Build Status

The fastest and simplest library for SQLite3 in Node.js.

  • Full transaction support
  • High performance, efficiency, and safety
  • Easy-to-use synchronous API (better concurrency than an asynchronous API... yes, you read that correctly)
  • Support for user-defined functions, aggregates, virtual tables, and extensions
  • 64-bit integers (invisible until you need them)
  • Worker thread support (for large/slow queries)

Help this project stay strong! 💪

better-sqlite3 is used by thousands of developers and engineers on a daily basis. Long nights and weekends were spent keeping this project strong and dependable, with no ask for compensation or funding, until now. If your company uses better-sqlite3, ask your manager to consider supporting the project:

How other libraries compare

select 1 row  get() select 100 rows   all()  select 100 rows iterate() 1-by-1insert 1 row run()insert 100 rows in a transaction
better-sqlite31x1x1x1x1x
sqlite and sqlite311.7x slower2.9x slower24.4x slower2.8x slower15.6x slower

You can verify these results by running the benchmark yourself.

Installation

npm install better-sqlite3

You must be using Node.js v14.21.1 or above. Prebuilt binaries are available for LTS versions. If you have trouble installing, check the troubleshooting guide.

Usage

const db = require('better-sqlite3')('foobar.db', options);

const row = db.prepare('SELECT * FROM users WHERE id = ?').get(userId);
console.log(row.firstName, row.lastName, row.email);

Though not required, it is generally important to set the WAL pragma for performance reasons.

db.pragma('journal_mode = WAL');
In ES6 module notation:
import Database from 'better-sqlite3';
const db = new Database('foobar.db', options);
db.pragma('journal_mode = WAL');

Why should I use this instead of node-sqlite3?

  • node-sqlite3 uses asynchronous APIs for tasks that are either CPU-bound or serialized. That's not only bad design, but it wastes tons of resources. It also causes mutex thrashing which has devastating effects on performance.
  • node-sqlite3 exposes low-level (C language) memory management functions. better-sqlite3 does it the JavaScript way, allowing the garbage collector to worry about memory management.
  • better-sqlite3 is simpler to use, and it provides nice utilities for some operations that are very difficult or impossible in node-sqlite3.
  • better-sqlite3 is much faster than node-sqlite3 in most cases, and just as fast in all other cases.

When is this library not appropriate?

In most cases, if you're attempting something that cannot be reasonably accomplished with better-sqlite3, it probably cannot be reasonably accomplished with SQLite3 in general. For example, if you're executing queries that take one second to complete, and you expect to have many concurrent users executing those queries, no amount of asynchronicity will save you from SQLite3's serialized nature. Fortunately, SQLite3 is very very fast. With proper indexing, we've been able to achieve upward of 2000 queries per second with 5-way-joins in a 60 GB database, where each query was handling 5–50 kilobytes of real data.

If you have a performance problem, the most likely causes are inefficient queries, improper indexing, or a lack of WAL mode—not better-sqlite3 itself. However, there are some cases where better-sqlite3 could be inappropriate:

  • If you expect a high volume of concurrent reads each returning many megabytes of data (i.e., videos)
  • If you expect a high volume of concurrent writes (i.e., a social media site)
  • If your database's size is near the terabyte range

For these situations, you should probably use a full-fledged RDBMS such as PostgreSQL.

Documentation

License

MIT

NPM DownloadsLast 30 Days