Giter Site home page Giter Site logo

akylas / node-sqlite Goto Github PK

View Code? Open in Web Editor NEW

This project forked from kriasoft/node-sqlite

0.0 2.0 0.0 95 KB

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

License: MIT License

JavaScript 99.10% SQLPL 0.90%

node-sqlite's Introduction

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).


๐Ÿ”ฅ Want to strengthen your core JavaScript skills and master ES6?
I would personally recommend this awesome ES6 course by Wes Bos.


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 db from 'sqlite';

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

app.get('/post/:id', async (req, res, next) => {
  try {
    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);
  }
});

Promise.resolve()
  // First, try connect to the database
  .then(() => db.open('./database.sqlite', { Promise }))
  .catch(err => console.error(err.stack))
  // Finally, launch Node.js app
  .finally(() => app.listen(port));

Cached DB Driver

If you want to enable the database object cache

db.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 db from 'sqlite';

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

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

Promise.resolve()
  // First, try connect to the database and update its schema to the latest version
  .then(() => db.open('./database.sqlite', { Promise }))
  .then(() => db.migrate({ force: 'last' }))
  .catch(err => console.error(err.stack))
  // Finally, launch Node.js app
  .finally(() => 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();

References

Related Projects

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

node-sqlite's People

Contributors

dtrebbien avatar farfromrefug avatar kevana avatar koistya avatar lguzzon avatar ltrlg avatar marvinroger avatar simonselg avatar taumechanica avatar theogravity avatar timer avatar tracker1 avatar wmertens avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.