node-sqlite

SQLite client library for Node.js applications (SQlite3, ES6 Promise, ES7 async/await, Babel) and SQL-based migrations API

Github星跟蹤圖

SQLite Client for Node.js Apps

NPM version
NPM downloads
Build Status
Dependency Status
Online Chat

A wrapper library that adds ES6 promises and SQL-based migrations API to
sqlite3 (docs).



How to Install

$ npm install sqlite --save

How to Use

NOTE: For Node.js v5 and below use var db = require('sqlite/legacy');.

This module has the same API as the original sqlite3 library (docs),
except that all its API methods return ES6 Promises and do not accept callback arguments.

Below is an example of how to use it with Node.js, Express and Babel:

import express from 'express';
import Promise from 'bluebird';
import sqlite from 'sqlite';

const app = express();
const port = process.env.PORT, 3000;
const dbPromise = sqlite.open('./database.sqlite', { Promise });

app.get('/post/:id', async (req, res, next) => {
  try {
    const db = await dbPromise;
    const [post, categories] = await Promise.all([
      db.get('SELECT * FROM Post WHERE id = ?', req.params.id),
      db.all('SELECT * FROM Category')
    ]);
    res.render('post', { post, categories });
  } catch (err) {
    next(err);
  }
});

app.listen(port);

ES6 tagged template strings

This module is compatible with sql-template-strings.

import SQL from 'sql-template-strings';
import sqlite from 'sqlite';

const db = await sqlite.open('./database.sqlite');

const book = 'harry potter';
const author = 'J. K. Rowling';

const data = await db.all(SQL`SELECT author FROM books WHERE name = ${book} AND author = ${author}`);

Cached DB Driver

If you want to enable the database object cache

sqlite.open('./database.sqlite', { cached: true })

Migrations

This module comes with a lightweight migrations API that works with SQL-based migration files
as the following example demonstrates:

migrations/001-initial-schema.sql
-- Up
CREATE TABLE Category (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE Post (id INTEGER PRIMARY KEY, categoryId INTEGER, title TEXT,
  CONSTRAINT Post_fk_categoryId FOREIGN KEY (categoryId)
    REFERENCES Category (id) ON UPDATE CASCADE ON DELETE CASCADE);
INSERT INTO Category (id, name) VALUES (1, 'Business');
INSERT INTO Category (id, name) VALUES (2, 'Technology');

-- Down
DROP TABLE Category
DROP TABLE Post;
migrations/002-missing-index.sql
-- Up
CREATE INDEX Post_ix_categoryId ON Post (categoryId);

-- Down
DROP INDEX Post_ix_categoryId;
app.js (Node.js/Express)
import express from 'express';
import Promise from 'bluebird';
import sqlite from 'sqlite';

const app = express();
const port = process.env.PORT, 3000;

const dbPromise = Promise.resolve()
  .then(() => sqlite.open('./database.sqlite', { Promise }))
  .then(db => db.migrate({ force: 'last' }));

app.use(/* app routes */);

app.listen(port);

NOTE: For the development environment, while working on the database schema, you may want to set
force: 'last' (default false) that will force the migration API to rollback and re-apply the
latest migration over again each time when Node.js app launches.

Multiple Connections

The open method resolves to the db instance which can be used in order to reference multiple open databases.

ES6

import sqlite from 'sqlite';

Promise.all([
  sqlite.open('./main.sqlite', { Promise }),
  sqlite.open('./users.sqlite', { Promise })
]).then(function([mainDb, usersDb]){
  ...
});

ES7+ Async/Await

import sqlite from 'sqlite';

async function main() {
  const [mainDb, usersDb] = await Promise.all([
    sqlite.open('./main.sqlite', { Promise }),
    sqlite.open('./users.sqlite', { Promise })
  ]);
  ...
}
main();

Getting the ID of the Row You Inserted

const sqlite = require('sqlite');
const SQL = require('sql-template-strings');

async function main() {
    const db = await sqlite.open("./my-db.sqlite");
    const firstName = 'Tamika';
    const lastName = 'Washington';
    // First value is auto-incrementing primary key
    const statement = await db.run(SQL`insert into People values (NULL, ${firstName}, ${lastName})`);
    // Get access to the primary key of the inserted row:
    console.log(statement.lastID);
    await sqlite.close(db);
}

main();

References

Support

  • Join #node-sqlite chat room on Gitter to stay up to date regarding the project
  • Join #sqlite IRC chat room on Freenode about general discussion about SQLite

License

The MIT License © 2015-present Kriasoft. All rights reserved.


Made with ♥ by Konstantin Tarkus (@koistya), Theo Gravity and contributors

主要指標

概覽
名稱與所有者kriasoft/node-sqlite
主編程語言TypeScript
編程語言JavaScript (語言數: 3)
平台
許可證MIT License
所有者活动
創建於2016-01-03 12:37:42
推送於2025-04-28 23:03:33
最后一次提交2023-11-01 23:59:09
發布數47
最新版本名稱v5.1.1 (發布於 )
第一版名稱v1.0.0 (發布於 )
用户参与
星數0.9k
關注者數15
派生數95
提交數235
已啟用問題?
問題數99
打開的問題數3
拉請求數59
打開的拉請求數4
關閉的拉請求數22
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?