• Stars
    star
    159
  • Rank 235,843 (Top 5 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created almost 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple, and persistent, SQLite database for Web and Workers.

sqlite-worker

Social Media Photo by Alexander Sinn on Unsplash

A simple, and persistent, SQLite database for Web and Workers, based on sql.js and sqlite-tag.

How to use this module

The most important thing for this module to work, is being able to reach its pre-built, and pre-optimized files, via its own dist folder.

The resolution is done automatically, whenever this modules is imported via native ESM, but due to a long standing bug that involves both Web and Service Workers across browsers, such dist folder must be specified manually, whenever this module is used directly within either a Service Worker, or a generic Web Worker.

Importing on Web pages via ESM

In any generic page, it is possible to import this module via native ESM with, or without, the help of a CDN:

<script type="module">
// no ?module needed, it's the main export in unpkg
import {SQLiteWorker} from '//unpkg.com/sqlite-worker';

// `dist` option resolved automatically via import.meta.url
SQLiteWorker({name: 'my-db'})
  .then(async ({all, get, query, raw}) => {
    const table = raw`todos`;
    await query`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY, value TEXT)`;
    const {total} = await get`SELECT COUNT(id) as total FROM ${table}`;
    if (total < 1) {
      console.log('Inserting some value');
      await query`INSERT INTO ${table} (value) VALUES (${'a'})`;
      await query`INSERT INTO ${table} (value) VALUES (${'b'})`;
      await query`INSERT INTO ${table} (value) VALUES (${'c'})`;
    }
    console.log(await all`SELECT * FROM ${table}`);
  });
</script>

If the current dist folder is pre-installed though, import {SQLiteWorker} from './js/sqlite-worker/dist/index.js'; would work too.

While above example would run sqlite-worker through a Web Worker, which is recommended, it is also possible to bootstrap this module right away in the main thread.

<script type="module">
// no ?module needed, it's the main export in unpkg
import {init} from '//unpkg.com/sqlite-worker';

// `dist` option resolved automatically via import.meta.url
init({name: 'my-db'}).then(async ({all, get, query, raw}) => {
  // ... same code as before ...
});
</script>

Beside being slightly faster, avoiding the worker postMessage dance, the main difference between SQLiteWorker and init is that init accepts an extra update option, that could be used to synchronize remotely the local database, whenever it's needed.

import {init} from 'sqlite-worker';

init({name: 'my-db', update(uInt8Array) {
  // store the latest uInt8Array somewhere
}});

The very same stored buffer could be used in the future to start from last stored update, in case the client erased its data (changed phone, IndexedDB cleared data, etc.).

This functionality could also be used in a Service Worker, but the initialization in there would be slightly different.

Importing on Service Worker

Instead of import, we must use importScripts to have cross browser compatibility, but this is not an issue, as this module provides, through its dist folder, everything needed to do so, as long as such folder is reachable:

// will add a `sqliteWorker` "global" initiator
importScripts('./dist/sw.js');

/* âš  IMPORTANT âš  */
const dist = './dist/';

sqliteWorker({dist, name: 'my-db'})
  .then(async ({all, get, query, raw, transaction}) => {
    const table = raw`todos`;
    await query`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY, value TEXT)`;
    const {total} = await get`SELECT COUNT(id) as total FROM ${table}`;
    if (total < 1) {
      console.log('Inserting some value');
      const populate = transaction();
      transaction`INSERT INTO ${table} (value) VALUES (${'a'})`;
      transaction`INSERT INTO ${table} (value) VALUES (${'b'})`;
      transaction`INSERT INTO ${table} (value) VALUES (${'c'})`;
    }
    await transaction.commit();
    console.table(await all`SELECT * FROM ${table}`);
  });

The dist option could also be used from generic pages, but usually with import.meta.url such information can be easily, automatically, retrieved by the module itself.

ℹ About Bundlers

Because of its own folder dependencies, including the WASM file, and the module, needed to bootstripe SQLite 3, importing this module via bundlers might break its actual execution if:

  • all files are not also included in the bundle folder
  • the bundler transform import.meta.url in a "too smart" way, breaking its native functionality
  • something else some bundler might do

However, as previously mentioned, if the dist option is provided, everything should be fine, even if bundled.

Initialization Options

Both init([options]) and SQLiteWorker([options]) optionally accept a configuration/options object with the following fields:

  • name: the persistent database name. By default it's the string 'sqlite-worker'
  • dist: the folder, as string, containing all distribution files of this module. This is resolved automatically on pages that are not workers, but it must be provided within workers when importScripts is used instead.
  • database: an initial SQLite database, as Uint8Array instance. This is used only the very first time, and it fallbacks to new Uint8Array(0).
  • timeout: minimum interval, in milliseconds, between saves, to make storing, and exporting, the database, less greedy. By default it's the number 250.

Direct init Extra Options

These options work only with direct initialization, so either in the main thread or via Service Worker (once fixed in Chrome) after importing its init export.

  • update: a function that receives latest version of the database, as Uint8Array, whenever some query executed an INSERT, a DELETE, or an UPDATE.

SQLiteWorker Extra Options

These options work only with SQLiteWorker initialization.

  • worker: the string path where the JS worker to use is located. By default, this is the dist/worker.js file, which is a pre-optimized version of this source.
  • credentials: the optional credentials string between omit, same-origin, or include, defaulting to omit, or better, undefined credentials.

After Initialization Helpers

Both init(...) and SQLiteWorker(...) resolves with the sqlite-tag API.

The API in a nutshell is:

  • all: a template literal tag to retrieve all rows that match the query
  • get: a template literal tag to retrieve one row that matches the query
  • query: a template literal tag to simply query the database (no result returned)
  • raw: a template literal tag to represent static parts of the query (not values)
  • transaction: a function that returns a template literal tag to perform any statement until tag.commit() is awaited and executed.
  • close: a function to force save and close the db at any time.
  • create_function: a function to register custom SQLite functions. Please note when used as Worker it requires a pure function (no outer scope access) and Function evaluation. No limitations when used directly through init.

All tags, except the raw helper, are asynchronous, so that it's possible to await their result.

Extra Initialization Helpers

The sqlite-worker/tables export helps defining, or modifying, tables at runtime, without needing to write complex logic, or queries.

All it's needed, is a tables property that describe the table name and its fields, handled via sqlite-tables-handler, before returning all module helpers.

import {init, SQLiteWorker} from 'sqlite-worker/tables';

init({
  name: 'test-db',
  // the tables schema
  tables: {
    todos: {
      id: 'INTEGER PRIMARY KEY',
      value: 'TEXT'
    }
  }
}).then(async ({all, get, query, raw}) => {
  const {total} = await get`SELECT COUNT(id) as total FROM todos`;
  if (total < 1) {
    console.log('Inserting some value');
    await query`INSERT INTO todos (value) VALUES (${'a'})`;
    await query`INSERT INTO todos (value) VALUES (${'b'})`;
    await query`INSERT INTO todos (value) VALUES (${'c'})`;
  }
  console.table(await all`SELECT * FROM todos`);
});

For Service Worker one must use the dist/sw-tables.js file instead of dist/sw.js.

importScripts('./dist/sw-tables.js');

sqliteWorker({
  dist: './dist',
  name: 'my-db',
  tables: {
    todos: {
      id: 'INTEGER PRIMARY KEY',
      value: 'TEXT'
    }
  }
})
  .then(async ({all, get, query}) => {
    // ...
  });

Compatibility

This module requires a browser compatible with WASM and native ESM import.

This module won't work in old Edge or IE.

Live Demo - please note if you read two OK after the list of expected errors (due code coverage) it means everything is fine and your browser works as expected.

CodePen - will show the table result, as JSON, in the body.

More Repositories

1

hyperHTML

A Fast & Light Virtual DOM Alternative
HTML
3,028
star
2

linkedom

A triple-linked lists based DOM implementation.
HTML
1,156
star
3

document-register-element

A stand-alone working lightweight version of the W3C Custom Elements specification
JavaScript
1,131
star
4

dom4

Modern DOM functionalities for every browser
JavaScript
929
star
5

flatted

A fast and minimal circular JSON parser.
JavaScript
893
star
6

url-search-params

Simple polyfill for URLSearchParams standard
JavaScript
765
star
7

uhtml

A micro HTML/SVG render
JavaScript
707
star
8

lighterhtml

The hyperHTML strength & experience without its complexity 🎉
JavaScript
702
star
9

JSONH

Homogeneous Collection Compressor
JavaScript
618
star
10

circular-json

JSON does not handle circular references. Now it does
JavaScript
599
star
11

viperHTML

Isomorphic hyperHTML
JavaScript
318
star
12

heresy

React-like Custom Elements via V1 API builtin extends.
JavaScript
271
star
13

es6-collections

Map, WeakMap, and Set fast/simple shim for Harmony collections
JavaScript
253
star
14

neverland

React like Hooks for lighterhtml
JavaScript
241
star
15

wicked-elements

Components for the DOM as you've never seen before
JavaScript
235
star
16

eddy

Event Driven JS
JavaScript
211
star
17

dblite

sqlite for node.js without gyp problems
JavaScript
209
star
18

domdiff

Diffing the DOM without virtual DOM
JavaScript
197
star
19

hyperHTML-Element

An extensible class to define hyperHTML based Custom Elements.
JavaScript
195
star
20

benja

Bootable Electron Node JS Application
194
star
21

uce

µhtml based Custom Elements
JavaScript
183
star
22

usignal

A blend of @preact/signals-core and solid-js basic reactivity API
JavaScript
176
star
23

highlighted-code

A textarea builtin extend to automatically provide code highlights based on one of the languages available via highlight.js
HTML
172
star
24

restyle

JavaScript
167
star
25

testardo

a browser and OS agnostic web driver for mobile and desktop
JavaScript
166
star
26

augmentor

Extensible, general purpose, React like hooks for the masses.
JavaScript
135
star
27

uhooks

micro hooks: a minimalistic client/server hooks' implementation
JavaScript
127
star
28

polpetta

Polpetta, any folder is served spiced
JavaScript
125
star
29

basicHTML

A NodeJS based, standard oriented, HTML implementation.
JavaScript
123
star
30

udomdiff

An essential diffing algorithm for µhtml.
JavaScript
117
star
31

pocket.io

A minimalistic version of socket.io that weights about 1K instead of 60K.
JavaScript
112
star
32

caller-of

The tiniest yet most powerful JS utility ever :D
HTML
102
star
33

uland

A µhtml take at neverland
JavaScript
101
star
34

uce-template

A Vue 3 inspired Custom Elements toolless alternative.
JavaScript
100
star
35

json.hpack

JSON Homogeneous Collections Packer
C#
95
star
36

wru

essential unit test framework
JavaScript
95
star
37

html-escaper

A module to escape/unescape common problematic entities done the right way.
JavaScript
95
star
38

udomsay

A stricter, signals driven, ESX based library
JavaScript
95
star
39

db

JavaScript
94
star
40

import.js

A dynamic import() polyfill
JavaScript
93
star
41

regular-elements

Custom Elements made available for any node, and through CSS selectors
JavaScript
91
star
42

proxy-pants

Secured and reliable Proxy based utilities for more or less common tasks.
JavaScript
90
star
43

ucompress

A micro, all-in-one, compressor for common Web files.
JavaScript
90
star
44

archibold.io

archibold.io
Shell
85
star
45

jsgtk

A simplified approach to GJS for Node.JS and JavaScript developers.
JavaScript
85
star
46

heresy-ssr

🔥 heresy 🔥 Server Side Rendering
JavaScript
84
star
47

hypersimple

The easiest way to use hyperHTML
JavaScript
83
star
48

asbundle

A minimalistic JS bundler
JavaScript
77
star
49

introspected

Introspection for serializable arrays and JSON friendly objects.
HTML
77
star
50

node-gtk

GNOME Gtk+ bindings for NodeJS
C++
74
star
51

i18n-utils

The i18n tag function utilitities
JavaScript
73
star
52

viper-news

viperHTML version of the Hacker News app.
JavaScript
72
star
53

ucdn

A µcompress based CDN utility, compatible with both Express and native http module
JavaScript
67
star
54

electroff

A cross browser, electron-less helper, for IoT projects and standalone applications.
JavaScript
64
star
55

builtin-elements

A zero friction custom elements like primitive.
JavaScript
62
star
56

nonchalance

The easiest way to augment DOM builtin elements.
JavaScript
61
star
57

universal-mixin

A mixin usable for both generic objects and decorators.
JavaScript
59
star
58

attachshadow

An iframe based Shadow DOM poorlyfill
JavaScript
59
star
59

ucontent

An SSR HTML content generator.
JavaScript
58
star
60

dom-augmentor

Same as augmentor but with DOM oriented useEffect handling via dropEffect.
JavaScript
56
star
61

ascjs

ES2015 to CommonJS import/export transformer
JavaScript
55
star
62

geo2city

Basic offline reverse geocode
JavaScript
53
star
63

vanilla-elements

A Minimalistic Custom Elements Helper.
JavaScript
51
star
64

wrist

Minimalistic utility for generic one/two ways data bindings.
HTML
51
star
65

screenfit

A cross platform, cross WebView, solution to fit 100% any Web page.
HTML
50
star
66

html-parsed-element

A base custom element class with a reliable `parsedCallback` method.
HTML
50
star
67

sqlite-tag

Template literal tag based sqlite3 queries.
JavaScript
49
star
68

jsdon

A DOM serializer based on LinkeDOM idea
HTML
48
star
69

echomd

A terminal oriented MD like syntax
JavaScript
48
star
70

dom-class

A lightweight, cross browser, simplification of WebComponents.
JavaScript
46
star
71

cloner

Cloning ES5+ objects in a shallow or deep way
JavaScript
46
star
72

css-proxied-vars

The easiest way to set, read, or update, CSS variables per each element.
JavaScript
46
star
73

event-target

The EventTarget Class Polyfill.
HTML
46
star
74

hn

Isomorphic Hacker News
JavaScript
45
star
75

proxied-worker

A tiny utility to asynchronously drive a namespace exposed through a Worker.
JavaScript
45
star
76

Database

Web SQL Storage Made Easy
JavaScript
44
star
77

promise

Abortable and Resolvable Promises.
JavaScript
43
star
78

poorlyfills

Simplified, partial, and poor ES6 collections polyfills, targeting IE9+ and older mobile browsers.
HTML
43
star
79

babel-plugin-transform-builtin-classes

A fix for the infamous Babel #4480 bug.
JavaScript
43
star
80

redefine

lightweight utility for smart object properties definition
JavaScript
42
star
81

nativeHTML

coming soon
JavaScript
42
star
82

bidi-sse

Bidirectional Server-sent Events
JavaScript
42
star
83

domtagger

The hyperHTML's template literal parser
JavaScript
41
star
84

hooked-elements

wickedElements 🧙 with render hooks
JavaScript
41
star
85

classtrophobic

Breaking JS Class Constrains
HTML
41
star
86

a-route

Express like routing as Custom Element or standalone
JavaScript
40
star
87

header-snippets

A collection of snippets to put in your header.
HTML
40
star
88

life-diary

your albums, your journey, your data
JavaScript
40
star
89

static.email

The easiest way to send emails on the Web
JavaScript
39
star
90

lazytag

Lazy loading Custom Elements and their styles without even thinking about it.
JavaScript
38
star
91

es-class

ECMAScript 3 to 6 compatible Class definition
JavaScript
38
star
92

tiny-cdn

A tiny static files serving handler
JavaScript
37
star
93

broadcast

Notification channel for the past, the present, and the future.
JavaScript
37
star
94

p-cool

Pretty Cool Elements
JavaScript
36
star
95

monthly

A simplified way to show a calendar month in any console.
HTML
36
star
96

jsx2tag

Enable JSX for Template Literal Tags based projects.
JavaScript
36
star
97

consolemd

Bringing echomd to console.
JavaScript
36
star
98

common-js

CommonJS + module.import() for any Browser
JavaScript
35
star
99

qsa-observer

handle elements lifecycle through CSS selectors
JavaScript
35
star
100

create-viperhtml-app

A basic viperHTML + hyperHTML setup
JavaScript
35
star