A tiny cross-platform client for SQLite3, with precompiled binaries as the only third-party dependencies.

Overview

Tiny SQLite3

A tiny cross-platform client for SQLite3, with precompiled binaries as the only third-party dependencies.

A nice feature about this module is that queries are processed in another process by SQLite3, and Node's hyper-slow streams are bypassed, so actually the main thread stays idle and able to perform work almost for the entire time, while better-sqlite3 blocks.

Install

npm install --save tiny-sqlite3

Usage

import Database from 'tiny-sqlite3';

// Create a temporary in-memory database

const mem = new Database ( ':memory:' );

// Create a permament in-disk database

const db = new Database ( 'foo.db' );

// Read the various properties attached to the database instance

db.name // => full path to the main file containing the data for the database
db.memory // => whether it's in an in-memory database or not, in-memory databases are actually just stored in temporary files on disk
db.open // => whether there's a connection to the database or not
db.readonly // => whether the database is opened in read-only mode or not
db.batching // => Whether queries are currently being executed in a batch or not
db.transacting // => whether a transaction is currently being executed or not

// Backup the whole database to a specific location, safer than manually coping files

await db.backup ( 'foo.db.bak' );

// Serialize the database to a Uint8Array, and create a new in-memory database from that Uint8Array

const serialized = await db.serialize ();
const deserialized = new Database ( serialized );

// Perform an SQL query, interpolated values are escaped automatically

const limit = 1;
const rows = await db.sql`SELECT * FROM example LIMIT ${limit}`;

// Interpolate a raw, unescaped, string in a SQL query

const rows2 = await db.sql`SELECT * FROM ${db.raw ( 'example' )} LIMIT ${limit}`;

// Start a batch, which will cause all queries to be executed as one, their output won't be available

await db.sql`CREATE TABLE example ( id INTEGER PRIMARY KEY, title TEXT, description TEXT )`;

await db.batch ( () => {
  db.sql`INSERT INTO example VALUES( ${101}, ${'title101'}, ${'description101'} )`;
  db.sql`INSERT INTO example VALUES( ${102}, ${'title102'}, ${'description102'} )`;
  db.sql`INSERT INTO example VALUES( ${103}, ${'title103'}, ${'description103'} )`;
});

// Start a transaction, which is executed immediately and rolled back automatically if the function passed to the "transaction" method throws at any point

const success = await db.transaction ( () => {
  await db.sql`INSERT INTO example VALUES( ${1}, ${'title1'}, ${'description1'} )`;
  await db.sql`INSERT INTO example VALUES( ${2}, ${'title2'}, ${'description2'} )`;
  await db.sql`INSERT INTO example VALUES( ${1}, ${'title1'}, ${'description1'} )`; // This will cause the transaction to be rolled back
});

console.log ( success ); // => true|false

// Transactions and batches can be combined together for greater performance

await db.transaction ( async () => {
  await db.batch ( () => {
    db.sql`INSERT INTO example VALUES( ${201}, ${'title201'}, ${'description201'} )`;
    db.sql`INSERT INTO example VALUES( ${202}, ${'title202'}, ${'description202'} )`;
    db.sql`INSERT INTO example VALUES( ${203}, ${'title203'}, ${'description203'} )`;
  });
});

// Close the connection to the database, from this point onwards no further queries can be executed

db.close ();

Benchmark

Executing the benchmark provided in this repo generates the following flamecharts for different SQLite3 clients.

Basically better-sqlite3 returns results faster, but it blocks for longer. Depending on your use case you may prefer one or the other.

better-sqlite3

sqlite-tag-spawned

tiny-sqlite3

Thanks

  • sqlite-tag-spawned: for providing a sort of reference implementation, tiny-sqlite3 is very much derivative work of sqlite-tag-spawned.
  • @WebReflection: for also providing the idea of directly spawning the official prebuild binaries.

License

  • Parts: ISC © Andrea Giammarchi
  • Parts: MIT © Fabio Spampinato
You might also like...

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

Webview is a tiny cross-platform library to make web-based GUIs for desktop applications.

Webview is a tiny cross-platform library to make web-based GUIs for desktop applications.

webview_deno deno bindings for webview Webview is a tiny cross-platform library to make web-based GUIs for desktop applications. ⚠️ This project is st

Jan 2, 2023

GetOsLocalesCrossPlatform - A cross platform alternative to get locales used on the platform. Works on Node, Electron, NW.js and Browsers

getOsLocalesCrossPlatform A cross platform alternative to get locales used on the platform. Works on Node, Electron, NW.js and Browsers This script is

Jan 2, 2022

LucaMail - an Open Source,Cross Platform Email Client

LucaMail -  an Open Source,Cross Platform Email Client

LucaMail v0.0.1-beta An Awesome Cross Platform Email Client! Note : This Project Is Still in Beta Version Website . Report Bug . Request Feature . Dis

Dec 28, 2022

A Bilibili Cross-Platform Desktop Client Powered By Tauri

A Bilibili Cross-Platform Desktop Client Powered By Tauri

BBHouse 取自常见的『我在B站买了房』的评论 BBHouse 是一款 哔哩哔哩 的第三方应用,基于 Tauri 跨平台构建,支持 Windows macOS Linux. 核心功能 一个支持对视频动态分区展示的首页, 去除了B博和推荐流 一个支持无限添加的 (临时的) 稍后播放列表与配套的播放

Dec 26, 2022

Lightweight (zero dependencies) library for enabling cross document web messaging on top of the MessageChannel API.

Lightweight (zero dependencies) library for enabling cross document web messaging on top of the MessageChannel API.

Jul 15, 2022

A super tiny Javascript library to make DOM elements draggable and movable. ~500 bytes and no dependencies.

dragmove.js A super tiny Javascript library to make DOM elements draggable and movable. Has touch screen support. Zero dependencies and 500 bytes Gzip

Dec 29, 2022

🌈 GitHub following, followers, only-following, only-follower tracker 🌈

🌈 GitHub following, followers, only-following, only-follower tracker 🌈

github-following-tracker GitHub following, followers, only-following, only-follower tracker 👀 Just enter your GitHub name and track your followings!

Jun 15, 2022
Comments
  • Can't build for production with Vite and Solid-start

    Can't build for production with Vite and Solid-start

    Hi,

    I'm trying tiny-sqlite3 with solid-start, while in DEV mode npm run dev, it works fine.

    As soon as I try to build for production, I get the following error:

    ....
    dist/public/manifest.json                        2.43 KiB
    dist/public/ssr-manifest.json                    15.19 KiB
    dist/public/assets/_...id_.1edbca83.js           0.42 KiB / gzip: 0.29 KiB
    dist/public/assets/root.c3bee30b.js              8.61 KiB / gzip: 2.95 KiB
    dist/public/assets/Leled.705a3a96.js             0.89 KiB / gzip: 0.55 KiB
    dist/public/assets/_...id_.64d4cb54.js           1.10 KiB / gzip: 0.55 KiB
    dist/public/assets/index.0e6913af.js             18.75 KiB / gzip: 5.11 KiB
    dist/public/assets/_id_.36d37e57.js              1.18 KiB / gzip: 0.56 KiB
    dist/public/assets/entry-client.7089fcef.js      36.08 KiB / gzip: 13.39 KiB
    dist/public/assets/root.8ae906ba.css             40.09 KiB / gzip: 7.17 KiB
    dist/public/assets/index.1520d1ea.css            23.21 KiB / gzip: 3.91 KiB
    dist/public/assets/Leled.8f56de37.css            2.24 KiB / gzip: 0.79 KiB
    dist/public/assets/ProgramPreview.ce925eef.css   97.09 KiB / gzip: 13.27 KiB
    dist/public/assets/ProgramPreview.b0dea92d.js    103.07 KiB / gzip: 21.31 KiB
    vite v3.0.3 building SSR bundle for production...
    ✓ 146 modules transformed.
    .solid/server/manifest.json     0.18 KiB
    .solid/server/entry-server.js   224.55 KiB
    Circular dependency: node_modules/.pnpm/[email protected]/node_modules/tiny-sqlite3/dist/objects/database.js -> node_modules/.pnpm/[email protected]/node_modules/tiny-sqlite3/dist/objects/executor.js -> node_modules/.pnpm/[email protected]/node_modules/tiny-sqlite3/dist/objects/spawner.js -> node_modules/.pnpm/[email protected]/node_modules/tiny-sqlite3/dist/utils.js -> node_modules/.pnpm/[email protected]/node_modules/tiny-sqlite3/dist/objects/database.js
    
    > start
    > solid-start start
    
      > Page Routes:
         http://localhost:3000/*id
         http://localhost:3000/
         http://localhost:3000/achat-immobilier-neuf/*id
         http://localhost:3000/program/:id
    
      > API Routes:
    
    node:events:505
          throw er; // Unhandled 'error' event
          ^
    
    Error: spawn /Users/jchatard/Documents/Foo/Foo.de/front-solidjs/resources/binaries/sqlite3-darwin-arm64 ENOENT
        at ChildProcess._handle.onexit (node:internal/child_process:283:19)
        at onErrorNT (node:internal/child_process:476:16)
        at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
    Emitted 'error' event on ChildProcess instance at:
        at ChildProcess._handle.onexit (node:internal/child_process:289:12)
        at onErrorNT (node:internal/child_process:476:16)
        at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
      errno: -2,
      code: 'ENOENT',
      syscall: 'spawn /Users/jchatard/Documents/Foo/Foo.de/front-solidjs/resources/binaries/sqlite3-darwin-arm64',
      path: '/Users/jchatard/Documents/Foo/Foo.de/front-solidjs/resources/binaries/sqlite3-darwin-arm64',
      spawnargs: [
        '/Users/jchatard/Documents/Foo/Foo.de/front-solidjs/cache2.sqlite3'
      ]
    }
    
    Node.js v18.3.0
    

    Here's my package.json

    {
      "name": "front-solidjs",
      "scripts": {
        "dev": "solid-start dev",
        "build": "solid-start build",
        "start": "solid-start start",
        "postinstall": "node ./scripts/fix-jest-dom.mjs",
        "test": "vitest run"
      },
      "type": "module",
      "devDependencies": {
        "@testing-library/jest-dom": "^5.16.2",
        "@types/testing-library__jest-dom": "^5.14.3",
        "autoprefixer": "^10.4.7",
        "jsdom": "^19.0.0",
        "postcss": "^8.4.14",
        "postcss-mixins": "^9.0.3",
        "postcss-preset-env": "^7.7.2",
        "solid-app-router": "^0.4.1",
        "solid-js": "^1.4.7",
        "solid-meta": "^0.27.3",
        "solid-start": "0.1.0-alpha.95",
        "solid-start-node": "0.1.0-alpha.95",
        "solid-testing-library": "^0.3.0",
        "typescript": "^4.4.3",
        "undici": "^5.5.1",
        "vite": "^3.0.2",
        "vite-plugin-inspect": "^0.5.0",
        "vite-plugin-solid": "^2.3.0",
        "vite-plugin-solid-svg": "^0.2.0",
        "vitest": "^0.6.1"
      },
      "engines": {
        "node": ">=14"
      },
      "dependencies": {
        "tiny-sqlite3": "^1.2.0"
      }
    }
    

    Is there something I'm doing wrong?

    Thank you! Jérémy

    bug 
    opened by jchatard 1
Owner
Fabio Spampinato
Full-stack developer passionate about open source and empowering people.
Fabio Spampinato
Calculating Pi number without limitation until 10k digits or more in your browser powered by JS without any third party library!

PI Calculator Web JS (Online) Calculating Pi number without limitation until 10k digits or more in your browser powered by JS without any third party

Max Base 6 Jul 27, 2022
Userscript developed by Stay & Third Party userscript available on Stay.

Stay offical userscript Get the userscript manager Stay² Developed by Stay Name Description Link 知乎@AutoExpand 自动展开回答,支持知乎桌面版 Get Google@PreventAppJum

shen yin 72 Nov 15, 2022
Minimal versions of popular analytics libraries. Reduce the impact of third-party scripts on your application.

minimal-analytics This project aims to provide minimal implementations of popular analytics libraries. It's aimed at users who want to reduce the impa

James Hill 32 Dec 25, 2022
A wrapper for valorant-api, a third-party API for getting data within Valorant. Available on npm

valorant-wrapper A wrapper for the third-party valorant-api How to Use All endpoints can be accessed off the ValAPI class. import { ValAPI } from 'val

Aircraft Overviewer 5 Nov 7, 2022
A third-party messenger application for Path of Exile.

PoE Instant Messenger Download (Windows) The latest release can be downloaded here Tool showcase Theme Setup Notifier Messenger Settings Light Dark Co

Cedric 11 Jul 29, 2022
A third-party VALORANT API wrapper library.

wrapper-valorant-api A NodeJS wrapper for the VALORANT API. Installation npm: npm i wrapper-valorant-api yarn: yarn add wrapper-valorant-api VAL-CONTE

LordPrinz 3 Dec 8, 2022
Quickly check your websites for third party requests.

Third Party Checker Tool for crawling websites and checking for third party requests using Puppeteer. Installation git clone https://github.com/pxlrbt

Dennis Koch 7 Nov 1, 2022
Identitfy and categorize Node.js dependencies (builtins, third parties..)

Dependa Identify and categorize Node.js dependencies (builtins, alias, third parties..). The module and the code has been inspired by builtins and bui

null 4 Nov 10, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022