@vanillaspa/sqlite-database 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ ## Getting started
2
+
3
+ To install the sqlite-database into your project, simply run
4
+
5
+ ```bash
6
+ npm install @vanillaspa/sqlite-database
7
+ ```
8
+
9
+ ## How-To
10
+
11
+ Now integrate the sqlite datebase into your app:
12
+
13
+ ```javascript
14
+ <script type="module">
15
+ import * as sqlite from '@vanillaspa/sqlite-database';
16
+ window.sqlite = sqlite;
17
+ </script>
18
+ ```
19
+
20
+ This is only a recommendation. You can use it however you like. With the `sqlite` object attached to the `window` object, you have access to the sqlite-database in your WebComponents.
package/index.js ADDED
@@ -0,0 +1,153 @@
1
+ import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
2
+
3
+ // https://www.npmjs.com/package/@sqlite.org/sqlite-wasm
4
+ // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
5
+
6
+ export const name = "sqlite";
7
+
8
+ const workers = {};
9
+
10
+ function initalizeWorker(name) {
11
+ let worker = new Worker(new URL('./sqliteWorker.js', import.meta.url), { type: 'module' });
12
+ if (workers[name]) {
13
+ console.error("InstantiationError: already taken");
14
+ worker.terminate();
15
+ } else {
16
+ workers[name] = worker;
17
+ }
18
+ }
19
+
20
+ export function createDB(name = 'default') {
21
+ return new Promise((resolve, reject) => {
22
+ initalizeWorker(name);
23
+ let worker = getWorker(name);
24
+ worker.onmessage = function ({ data }) {
25
+ const { type, message } = data;
26
+ if (type === 'created') {
27
+ resolve({ message });
28
+ }
29
+ }
30
+ worker.onerror = (error) => {
31
+ reject(new Error(error));
32
+ };
33
+ worker.postMessage({ action: 'createDB', name });
34
+ });
35
+ }
36
+
37
+ export async function deleteAndTerminateDB(name) {
38
+ var root = await navigator.storage.getDirectory();
39
+ let fileSystemFileHandle = await root.getFileHandle(`${name}.sqlite3`);
40
+ if (fileSystemFileHandle) {
41
+ let worker = workers[name];
42
+ worker.onmessage = async function ({ data }) {
43
+ const { type } = data;
44
+ if (type === 'closed') {
45
+ console.log("Removing...", fileSystemFileHandle);
46
+ await fileSystemFileHandle.remove();
47
+ await worker.terminate();
48
+ }
49
+ delete workers[name];
50
+ }
51
+ worker.postMessage({ action: 'closeDB' });
52
+ }
53
+ }
54
+
55
+ export function downloadDB(name = 'default') {
56
+ let worker = workers[name];
57
+ if (worker) {
58
+ worker.onmessage = function ({ data }) {
59
+ const { type } = data;
60
+ if (type === 'application/vnd.sqlite3') {
61
+ let downloadChannel = new BroadcastChannel("download_channel");
62
+ downloadChannel.postMessage(data);
63
+ downloadChannel.close();
64
+ }
65
+ }
66
+ worker.postMessage({ action: 'downloadDB' });
67
+ }
68
+ }
69
+
70
+ export function executeQuery(sql, name = 'default') {
71
+ return new Promise((resolve, reject) => {
72
+ let worker = getWorker(name);
73
+ if (worker) {
74
+ worker.onmessage = function ({ data }) {
75
+ const { type } = data;
76
+ if (type === 'application/json') {
77
+ const { result } = data;
78
+ resolve(result);
79
+ }
80
+ }
81
+ worker.onerror = (error) => {
82
+ reject(error);
83
+ };
84
+ worker.postMessage({ action: "executeQuery", sql });
85
+ } else {
86
+ reject(new Error("No worker"));
87
+ }
88
+ });
89
+ }
90
+
91
+ export function executeStatement({ sql, values, name = "default" }) {
92
+ return new Promise((resolve, reject) => {
93
+ let worker = getWorker(name);
94
+ if (worker) {
95
+ worker.onmessage = function ({ data }) {
96
+ const { type } = data;
97
+ if (type === 'application/json') {
98
+ const { result } = data;
99
+ resolve(result);
100
+ }
101
+ }
102
+ worker.onerror = (error) => {
103
+ reject(error);
104
+ };
105
+ worker.postMessage({ action: "prepareStatement", sql, values });
106
+ } else {
107
+ reject(new Error("No worker"));
108
+ }
109
+ });
110
+ }
111
+
112
+ export function getWorker(name = 'default') {
113
+ let worker = workers[name];
114
+ return worker ? worker : undefined;
115
+ }
116
+
117
+ export function getWorkers() {
118
+ return workers;
119
+ }
120
+
121
+ export function uploadDB(fileName, arrayBuffer) {
122
+ let [name, extension] = fileName.split(".");
123
+ if (['sqlite', 'sqlite3'].includes(extension)) {
124
+ let worker = workers[name];
125
+ if (!worker) {
126
+ initalizeWorker(name);
127
+ worker = getWorker(name);
128
+ console.log({worker})
129
+ } // TODO: allow overwrite
130
+ worker.postMessage({ action: 'uploadDB', name, arrayBuffer });
131
+ } else {
132
+ throw new Error({ name: "UnsupportedError", message: "Unsupported extension" });
133
+ }
134
+ }
135
+
136
+ export function terminate(name = 'default') {
137
+ let worker = workers[name];
138
+ if (worker) {
139
+ worker.postMessage({ command: 'terminate' });
140
+ }
141
+ }
142
+
143
+ if (window.Worker) {
144
+ try {
145
+ // instantiation test
146
+ const sqlite3 = await sqlite3InitModule({ print: console.log, printErr: console.error });
147
+ console.log('Running SQLite3 version', sqlite3.version.libVersion);
148
+ } catch (err) {
149
+ console.error('Initialization error:', err.name, err.message);
150
+ }
151
+ } else {
152
+ console.error('Your browser doesn\'t support web workers.');
153
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "author": "Robert Meissner <rome@live.com>",
3
+ "bugs": {
4
+ "url": "https://github.com/vanillaspa/sqlite-database/issues"
5
+ },
6
+ "description": "A serverless SQLite database inside your browser.",
7
+ "dependencies": {
8
+ "@sqlite.org/sqlite-wasm":"^3.51.2-build6"
9
+ },
10
+ "homepage": "https://github.com/vanillaspa/sqlite-database#readme",
11
+ "keywords": [
12
+ "Database",
13
+ "JavaScript",
14
+ "OPFS",
15
+ "SPA",
16
+ "SQLite",
17
+ "Vanilla",
18
+ "WebAssembly"
19
+ ],
20
+ "license": "Unlicense",
21
+ "main": "index.js",
22
+ "name": "@vanillaspa/sqlite-database",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/vanillaspa/sqlite-database.git"
29
+ },
30
+ "type": "module",
31
+ "version": "1.0.0"
32
+ }
@@ -0,0 +1,134 @@
1
+ import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
2
+
3
+ var db = null;
4
+ var sqlite3 = null;
5
+
6
+ onmessage = async function ({ data }) {
7
+ const { action } = data;
8
+ switch (action) {
9
+ case 'createDB': {
10
+ const { name } = data;
11
+ const { newDB, message } = await createDatabase(name)
12
+ db = newDB;
13
+ postMessage({ type: 'created', message });
14
+ break;
15
+ }
16
+ case 'executeQuery': {
17
+ const { sql } = data;
18
+ try {
19
+ const result = await db.exec({ sql, returnValue: "resultRows" });
20
+ // console.log(sql, result);
21
+ postMessage({ result, type: "application/json" });
22
+ } catch (e) {
23
+ if (e.message.indexOf("SQLITE_CANTOPEN") != -1) {
24
+ console.info("Info: Currently no SQLite database available for this worker. Upload a new database or reload the page.");
25
+ }
26
+ if (e.message.indexOf("SQLITE_CONSTRAINT_UNIQUE") != -1) {
27
+ console.error("Error executing SQL statement", sql, e.message);
28
+ }
29
+ }
30
+ break;
31
+ }
32
+ case 'prepareStatement': {
33
+ const { sql, values } = data;
34
+ let stmt;
35
+ try {
36
+ // console.debug(sql, values);
37
+ stmt = await db.prepare(sql, values);
38
+ const columns = stmt.getColumnNames();
39
+ // console.debug("columns", columns);
40
+ stmt.bind(values);
41
+ // console.debug("stmt", stmt)
42
+ const result = [];
43
+ while (stmt.step()) {
44
+ let row = stmt.get([]);
45
+ let zipped = columns.map(function (columnName, index) {
46
+ return [columnName, row[index]];
47
+ });
48
+ let obj = Object.fromEntries(zipped);
49
+ result.push(obj);
50
+ }
51
+ // console.debug("RESULT", result)
52
+ postMessage({ result, type: "application/json" });
53
+ } catch (e) {
54
+ if (e.message.indexOf("SQLITE_CANTOPEN") != -1) {
55
+ console.info("Info: Currently no SQLite database available for this worker. Upload a new database or reload the page.");
56
+ } else if (e.message.indexOf("SQLITE_CONSTRAINT_UNIQUE") != -1) {
57
+ console.error("Error executing SQL statement", sql, e.message);
58
+ } else {
59
+ console.error("Error executing SQL statement", sql, e.message);
60
+ }
61
+ } finally {
62
+ stmt.finalize();
63
+ }
64
+ break;
65
+ }
66
+ case 'uploadDB':
67
+ const { name, arrayBuffer } = data;
68
+ const { message } = await uploadDatabase(name, arrayBuffer)
69
+ console.log(message, db);
70
+ break;
71
+ case 'downloadDB':
72
+ try {
73
+ const byteArray = sqlite3.capi.sqlite3_js_db_export(db);
74
+ const blob = new Blob([byteArray.buffer], { type: "application/vnd.sqlite3" });
75
+ postMessage(blob); // send the database Blob to the API
76
+ } catch (e) {
77
+ if (e.message.indexOf("SQLITE_NOMEM") != -1)
78
+ postMessage({ type: "application/vnd.sqlite3", error: "SQLITE_NOMEM" });
79
+ else
80
+ console.error(e);
81
+ }
82
+ break;
83
+ case 'closeDB':
84
+ closeDB();
85
+ postMessage({ type: "closed" });
86
+ break;
87
+ default:
88
+ console.log(data)
89
+ }
90
+ }
91
+
92
+ async function createDatabase(name) {
93
+ const sqlite3 = await getInstance();
94
+ return 'opfs' in sqlite3
95
+ ? { newDB: new sqlite3.oo1.OpfsDb(`/${name}.sqlite3`), message: `OPFS is available, created persisted database at /${name}.sqlite3` }
96
+ : { newDB: new sqlite3.oo1.DB(`/${name}.sqlite3`, 'ct'), message: `OPFS is not available, created transient database /${name}.sqlite3` };
97
+ }
98
+
99
+ async function uploadDatabase(name, arrayBuffer) {
100
+ try {
101
+ const sqlite3 = await getInstance();
102
+ if ('opfs' in sqlite3) {
103
+ const size = await sqlite3.oo1.OpfsDb.importDb(`${name}.sqlite3`, arrayBuffer);
104
+ if (size) {
105
+ db = new sqlite3.oo1.OpfsDb(`/${name}.sqlite3`);
106
+ return { message: `New DB imported as ${name}.sqlite3. (${arrayBuffer.byteLength} Bytes)` }
107
+ } else {
108
+ throw new Error({ name: "ImportError", message: "Empty size" })
109
+ }
110
+ } else { // TODO allow alternative
111
+ throw new Error({ name: "OPFSMissingError", message: "Unsupported operation due to missing OPFS support." });
112
+ }
113
+ } catch (err) {
114
+ console.error(err.name, err.message);
115
+ }
116
+ }
117
+
118
+ function closeDB() {
119
+ if (db) {
120
+ console.log("Closing...", db);
121
+ db.close();
122
+ }
123
+ }
124
+
125
+ async function getInstance() {
126
+ try {
127
+ if (!sqlite3) {
128
+ sqlite3 = await sqlite3InitModule({ print: console.log, printErr: console.error });
129
+ }
130
+ return sqlite3;
131
+ } catch (err) {
132
+ console.error(err.name, err.message);
133
+ }
134
+ }