@yhwh-script/sqlite 1.2.7
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/README.md +14 -0
- package/UNLICENSE +24 -0
- package/assets/javascript.svg +1 -0
- package/assets/style/default.css +6 -0
- package/gen.cjs +32 -0
- package/index.html +19 -0
- package/package.json +45 -0
- package/public/elements/index.js +1 -0
- package/public/elements/sqlite/sqlite-control.html +86 -0
- package/src/elements/index.js +1 -0
- package/src/main.js +94 -0
- package/src/modules/logger/index.js +11 -0
- package/src/modules/sqlite/READ.md +1 -0
- package/src/modules/sqlite/index.js +127 -0
- package/src/modules/sqlite/sqliteWorker.js +98 -0
- package/src/publicApis/SQLite.js +3 -0
- package/src/publicApis/index.js +5 -0
- package/vite.config.js +21 -0
package/README.md
ADDED
@@ -0,0 +1,14 @@
|
|
1
|
+
# Description
|
2
|
+
A [yhwh-script](https://github.com/yhwh-script) project with [SQLite WASM](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm) built on <a title="Vite" href="https://vitejs.dev"><img height="20" alt="Vitejs-logo" src="https://vitejs.dev/logo.svg"></a> without examples.
|
3
|
+
|
4
|
+
# Quick Start
|
5
|
+
Just call `npm install` and `npm run dev`.
|
6
|
+
|
7
|
+
# FYI
|
8
|
+
You can create Single File Web-Components in dedicated `.html` files inside the `public/elements` folder. `npm run dev` and `npm run build` will generate maps in `src/elements/index.js` which are being fetched in the `/src/main.js` script for defining your CustomElements.
|
9
|
+
|
10
|
+
Please understand that the project structure is leaned on [valid-custom-element-names](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name), i.e. using a dash ("-") is mandatory.
|
11
|
+
|
12
|
+
In `/src/publicApis/index.js` you can define APIs for your custom-elements (for example to the SQLite module) via the window object.
|
13
|
+
|
14
|
+
Just stick to the examples and you are good to go. Have fun!
|
package/UNLICENSE
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>
|
@@ -0,0 +1 @@
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="32" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path fill="#F7DF1E" d="M0 0h256v256H0V0Z"></path><path d="m67.312 213.932l19.59-11.856c3.78 6.701 7.218 12.371 15.465 12.371c7.905 0 12.89-3.092 12.89-15.12v-81.798h24.057v82.138c0 24.917-14.606 36.259-35.916 36.259c-19.245 0-30.416-9.967-36.087-21.996m85.07-2.576l19.588-11.341c5.157 8.421 11.859 14.607 23.715 14.607c9.969 0 16.325-4.984 16.325-11.858c0-8.248-6.53-11.17-17.528-15.98l-6.013-2.58c-17.357-7.387-28.87-16.667-28.87-36.257c0-18.044 13.747-31.792 35.228-31.792c15.294 0 26.292 5.328 34.196 19.247l-18.732 12.03c-4.125-7.389-8.591-10.31-15.465-10.31c-7.046 0-11.514 4.468-11.514 10.31c0 7.217 4.468 10.14 14.778 14.608l6.014 2.577c20.45 8.765 31.963 17.7 31.963 37.804c0 21.654-17.012 33.51-39.867 33.51c-22.339 0-36.774-10.654-43.819-24.574"></path></svg>
|
package/gen.cjs
ADDED
@@ -0,0 +1,32 @@
|
|
1
|
+
const fs = require('fs')
|
2
|
+
const { join } = require('path');
|
3
|
+
|
4
|
+
const constants = {
|
5
|
+
ELEMENTS_DIR: join('.', 'elements'),
|
6
|
+
PUBLIC_ELEMENTS_DIR: join('.', 'public', 'elements'),
|
7
|
+
SRC_ELEMENTS_DIR: join('.', 'src', 'elements'),
|
8
|
+
}
|
9
|
+
|
10
|
+
const elements = [];
|
11
|
+
|
12
|
+
fs.readdirSync(constants.PUBLIC_ELEMENTS_DIR, { withFileTypes: true })
|
13
|
+
.filter((dir) => dir.isDirectory())
|
14
|
+
.forEach((folder) => {
|
15
|
+
console.log(folder);
|
16
|
+
const fileNames = fs.readdirSync(
|
17
|
+
join(constants.PUBLIC_ELEMENTS_DIR, folder.name)
|
18
|
+
);
|
19
|
+
fileNames.forEach((fileName) => {
|
20
|
+
const dashSplit = fileName.split('-');
|
21
|
+
const prefix = dashSplit[0];
|
22
|
+
const dotSplit = dashSplit[1].split('.');
|
23
|
+
const suffix = dotSplit[0];
|
24
|
+
|
25
|
+
elements.push(join(constants.ELEMENTS_DIR, folder.name, prefix + '-' + suffix + '.html'))
|
26
|
+
});
|
27
|
+
});
|
28
|
+
|
29
|
+
fs.writeFileSync(
|
30
|
+
join(constants.SRC_ELEMENTS_DIR, 'index.js'),
|
31
|
+
`export const htmlFiles=${JSON.stringify(elements)};`
|
32
|
+
)
|
package/index.html
ADDED
@@ -0,0 +1,19 @@
|
|
1
|
+
<!doctype html>
|
2
|
+
<html lang="en">
|
3
|
+
|
4
|
+
<head>
|
5
|
+
<link rel="icon" type="image/svg+xml" href="./assets/javascript.svg" />
|
6
|
+
<link rel="stylesheet" href="./assets/style/default.css">
|
7
|
+
<meta charset="UTF-8">
|
8
|
+
<meta name="description" content="yhwh-script is a vite build on top of vanilla JavaScript WebComponents with an optional SQLite WASM database.">
|
9
|
+
<meta name="keywords" content="HTML, CSS, JavaScript, WebComponents, CustomElements, SFC, Vite, SQLite">
|
10
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
11
|
+
<title>@yhwh-script/sqlite</title>
|
12
|
+
</head>
|
13
|
+
|
14
|
+
<body>
|
15
|
+
<sqlite-control></sqlite-control>
|
16
|
+
<script type="module" src="/src/main.js" defer></script>
|
17
|
+
</body>
|
18
|
+
|
19
|
+
</html>
|
package/package.json
ADDED
@@ -0,0 +1,45 @@
|
|
1
|
+
{
|
2
|
+
"author": "Jahrome <yhwhscript@gmail.com>",
|
3
|
+
"bugs": {
|
4
|
+
"url": "https://github.com/yhwh-script/sqlite/issues"
|
5
|
+
},
|
6
|
+
"devDependencies": {
|
7
|
+
"@vitejs/plugin-basic-ssl": "^2.0.0",
|
8
|
+
"vite": "^6.2.0"
|
9
|
+
},
|
10
|
+
"dependencies": {
|
11
|
+
"@sqlite.org/sqlite-wasm": "^3.49.1-build2"
|
12
|
+
},
|
13
|
+
"description": "This is a @yhwh-script app with SQLite support.",
|
14
|
+
"homepage": "https://github.com/yhwh-script/sqlite#readme",
|
15
|
+
"keywords": [
|
16
|
+
"CSS",
|
17
|
+
"CustomElements",
|
18
|
+
"HTML",
|
19
|
+
"JavaScript",
|
20
|
+
"OPFS",
|
21
|
+
"SFC",
|
22
|
+
"Single File Components",
|
23
|
+
"SQLite",
|
24
|
+
"Vanilla",
|
25
|
+
"Vite",
|
26
|
+
"WebComponents"
|
27
|
+
],
|
28
|
+
"license": "Unlicense",
|
29
|
+
"name": "@yhwh-script/sqlite",
|
30
|
+
"publishConfig": {
|
31
|
+
"access": "public"
|
32
|
+
},
|
33
|
+
"repository": {
|
34
|
+
"type": "git",
|
35
|
+
"url": "git+https://github.com/yhwh-script/sqlite.git"
|
36
|
+
},
|
37
|
+
"scripts": {
|
38
|
+
"dev": "npm run gen && vite",
|
39
|
+
"gen": "node gen.cjs",
|
40
|
+
"build": "npm run gen && vite build",
|
41
|
+
"preview": "vite preview"
|
42
|
+
},
|
43
|
+
"type": "module",
|
44
|
+
"version": "1.2.7"
|
45
|
+
}
|
@@ -0,0 +1 @@
|
|
1
|
+
export const htmlFiles=["elements/animals/animals-li.html","elements/animals/animals-view.html","elements/home/home-app.html","elements/home/home-header.html","elements/home/home-navigation.html","elements/home/home-switch.html","elements/quick/quick-delete.html"];
|
@@ -0,0 +1,86 @@
|
|
1
|
+
<script>
|
2
|
+
const { log, error } = window.Logger;
|
3
|
+
const { uploadDB, downloadDB, deleteDB } = window.SQLite;
|
4
|
+
|
5
|
+
const uploadButton = shadowDocument.querySelector('#uploadButton');
|
6
|
+
uploadButton.querySelector('click', (e) => {
|
7
|
+
let confirmation = prompt("Pressing OK will overwrite current database! Please write OK.", "");
|
8
|
+
if (confirmation && confirmation.toLowerCase() == "ok") {
|
9
|
+
log("OK to overwrite current database...");
|
10
|
+
} else {
|
11
|
+
alert("Canceled.");
|
12
|
+
e.preventDefault();
|
13
|
+
}
|
14
|
+
});
|
15
|
+
uploadButton.addEventListener('change', () => {
|
16
|
+
// TODO accept sqlite3 files only
|
17
|
+
try {
|
18
|
+
const file = uploadButton.files[0];
|
19
|
+
if (!file) return;
|
20
|
+
const reader = new FileReader();
|
21
|
+
reader.addEventListener('load', (e) => {
|
22
|
+
uploadDB(file.name, e.target.result); // e.target.result is an ArrayBuffer with the file's contents
|
23
|
+
});
|
24
|
+
reader.readAsArrayBuffer(file);
|
25
|
+
} catch (e) {
|
26
|
+
error(e);
|
27
|
+
}
|
28
|
+
});
|
29
|
+
|
30
|
+
const downloadButton = shadowDocument.querySelector('#downloadButton');
|
31
|
+
downloadButton.addEventListener('click', (e) => {
|
32
|
+
let databaseName = prompt("Please enter the name of the database to download.", "");
|
33
|
+
const downloadChannel = new BroadcastChannel("download_channel");
|
34
|
+
downloadChannel.onmessage = (message) => {
|
35
|
+
if (message.data.error) {
|
36
|
+
switch (message.data.error) {
|
37
|
+
case "SQLITE_NOMEM":
|
38
|
+
alert("Nothing to download. DB empty.");
|
39
|
+
break;
|
40
|
+
default:
|
41
|
+
alert("Unknown Error.");
|
42
|
+
}
|
43
|
+
} else {
|
44
|
+
const a = shadowDocument.querySelector('#downloadLink');
|
45
|
+
a.href = window.URL.createObjectURL(message.data);
|
46
|
+
a.download = (`${databaseName}.sqlite3`);
|
47
|
+
a.addEventListener('click', function () {
|
48
|
+
setTimeout(function () {
|
49
|
+
window.URL.revokeObjectURL(a.href);
|
50
|
+
a.remove();
|
51
|
+
}, 500);
|
52
|
+
});
|
53
|
+
a.click();
|
54
|
+
}
|
55
|
+
};
|
56
|
+
downloadDB(databaseName);
|
57
|
+
});
|
58
|
+
|
59
|
+
const resetButton = shadowDocument.querySelector('#resetButton');
|
60
|
+
resetButton.addEventListener('click', async (e) => {
|
61
|
+
let databaseName = null;
|
62
|
+
try {
|
63
|
+
databaseName = prompt("Pressing OK will reset specified database! Please enter the name of the database.", "");
|
64
|
+
if (databaseName && databaseName.toLowerCase()) {
|
65
|
+
deleteDB(databaseName);
|
66
|
+
} else {
|
67
|
+
alert("Canceled.");
|
68
|
+
e.preventDefault();
|
69
|
+
}
|
70
|
+
} catch (err) {
|
71
|
+
if (err.name === 'NotFoundError') {
|
72
|
+
error(`${err.name} (${databaseName}.sqlite3): ${err.message}`)
|
73
|
+
}
|
74
|
+
}
|
75
|
+
});
|
76
|
+
</script>
|
77
|
+
|
78
|
+
<template>
|
79
|
+
<span>
|
80
|
+
<label for="uploadButton">Upload DB</label>
|
81
|
+
<input type="file" id="uploadButton" />
|
82
|
+
</span>
|
83
|
+
<button type="button" id="downloadButton">Download DB</button>
|
84
|
+
<button type="button" id="resetButton">Reset DB</button>
|
85
|
+
<a id="downloadLink" hidden></a>
|
86
|
+
</template>
|
@@ -0,0 +1 @@
|
|
1
|
+
export const htmlFiles=["elements/sqlite/sqlite-control.html"];
|
package/src/main.js
ADDED
@@ -0,0 +1,94 @@
|
|
1
|
+
import './publicApis'
|
2
|
+
import { htmlFiles } from './elements';
|
3
|
+
|
4
|
+
for (const filePath of htmlFiles) {
|
5
|
+
const fileName = filePath.split("/").pop();
|
6
|
+
const dashSplit = fileName.split('-');
|
7
|
+
const prefix = dashSplit[0];
|
8
|
+
const dotSplit = dashSplit[1].split('.');
|
9
|
+
const suffix = dotSplit[0];
|
10
|
+
|
11
|
+
fetch(filePath).then(file => file.text()).then(html => {
|
12
|
+
const fragment = document.createRange().createContextualFragment(html);
|
13
|
+
const scriptFragment = fragment.querySelector("script");
|
14
|
+
const styleFragment = fragment.querySelector("style");
|
15
|
+
const templateFragment = fragment.querySelector("template");
|
16
|
+
|
17
|
+
customElements.define(`${prefix}-${suffix}`, class extends HTMLElement {
|
18
|
+
static observedAttributes = ["data-state"];
|
19
|
+
constructor() {
|
20
|
+
super();
|
21
|
+
this.attachShadow({ mode: "open" });
|
22
|
+
}
|
23
|
+
connectedCallback() {
|
24
|
+
this.hostDataIDs = []; // the hostDataIDs are used to getDOM from the script
|
25
|
+
this.dataset.id = Math.random().toString(16).substring(2, 8);
|
26
|
+
let hostElement = this;
|
27
|
+
while (hostElement && hostElement.dataset.id) {
|
28
|
+
this.hostDataIDs.push(hostElement.dataset.id);
|
29
|
+
hostElement = hostElement.getRootNode().host;
|
30
|
+
}
|
31
|
+
this.shadowRoot.replaceChildren();
|
32
|
+
if (scriptFragment?.getAttributeNames().includes('prefer')) {
|
33
|
+
this.#appendScript();
|
34
|
+
this.#appendTemplate();
|
35
|
+
this.#appendStyle();
|
36
|
+
} else {
|
37
|
+
this.#appendTemplate();
|
38
|
+
this.#appendStyle();
|
39
|
+
this.#appendScript();
|
40
|
+
}
|
41
|
+
}
|
42
|
+
attributeChangedCallback(name, oldValue, newValue) {
|
43
|
+
if (this.isConnected) {
|
44
|
+
if (oldValue != newValue) {
|
45
|
+
this.replaceWith(this.cloneNode(false)); // remove all listeners and reconstruct
|
46
|
+
}
|
47
|
+
}
|
48
|
+
}
|
49
|
+
#createScript() {
|
50
|
+
const scriptElement = document.createElement("script");
|
51
|
+
scriptElement.setAttribute("type", "module");
|
52
|
+
scriptElement.textContent = `
|
53
|
+
const shadowDocument = (function getDOM(hostDataIDs = '${this.hostDataIDs.toReversed().toString()}') {
|
54
|
+
let shadowDocument = document;
|
55
|
+
for (let hostDataID of hostDataIDs.split(',')) {
|
56
|
+
const host = shadowDocument.querySelector('[data-id="' + hostDataID + '"]');
|
57
|
+
if (host) {
|
58
|
+
shadowDocument = host.shadowRoot;
|
59
|
+
} else {
|
60
|
+
return null;
|
61
|
+
}
|
62
|
+
}
|
63
|
+
return shadowDocument;
|
64
|
+
})();
|
65
|
+
|
66
|
+
const $ = (query) => shadowDocument.querySelector(query);
|
67
|
+
const $$ = (query) => shadowDocument.querySelectorAll(query);
|
68
|
+
const state = shadowDocument.host.dataset.state ? JSON.parse(shadowDocument.host.dataset.state) : undefined;
|
69
|
+
|
70
|
+
${scriptFragment ? scriptFragment.textContent : ''}
|
71
|
+
`;
|
72
|
+
return scriptElement;
|
73
|
+
}
|
74
|
+
#appendScript() {
|
75
|
+
if (scriptFragment) {
|
76
|
+
let scriptElement = this.#createScript(); // TODO: compile template to use state
|
77
|
+
this.shadowRoot.appendChild(scriptElement);
|
78
|
+
}
|
79
|
+
}
|
80
|
+
#appendStyle() {
|
81
|
+
if (styleFragment) {
|
82
|
+
let clonedStyle = styleFragment.cloneNode(true);
|
83
|
+
this.shadowRoot.appendChild(clonedStyle);
|
84
|
+
}
|
85
|
+
}
|
86
|
+
#appendTemplate() {
|
87
|
+
if (templateFragment) {
|
88
|
+
let documentFragment = document.createRange().createContextualFragment(templateFragment.innerHTML)
|
89
|
+
this.shadowRoot.appendChild(documentFragment);
|
90
|
+
}
|
91
|
+
}
|
92
|
+
});
|
93
|
+
});
|
94
|
+
}
|
@@ -0,0 +1,11 @@
|
|
1
|
+
const LOG_LEVEL = 5; // 2 ERROR, 3 WARN, 4 INFO, 5 DEBUG
|
2
|
+
|
3
|
+
export function error(...args) { if (LOG_LEVEL >= 2) console.error(...args); }
|
4
|
+
|
5
|
+
export function warn(...args) { if (LOG_LEVEL >= 3) console.warn(...args); }
|
6
|
+
|
7
|
+
export function log(...args) { if (LOG_LEVEL >= 4) console.log(...args); }
|
8
|
+
|
9
|
+
export function info(...args) { if (LOG_LEVEL >= 4) console.info(...args); }
|
10
|
+
// For DEBUG log level: verbose must be turned on in Dev Tools
|
11
|
+
export function debug(...args) { if (LOG_LEVEL >= 5) console.debug(...args); }
|
@@ -0,0 +1 @@
|
|
1
|
+
Please, do not import sqlite module directly. Use an API!
|
@@ -0,0 +1,127 @@
|
|
1
|
+
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
|
2
|
+
import { log, error } from '../logger'
|
3
|
+
|
4
|
+
// https://www.npmjs.com/package/@sqlite.org/sqlite-wasm
|
5
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
|
6
|
+
|
7
|
+
const workers = {};
|
8
|
+
let publicAPI = {};
|
9
|
+
|
10
|
+
export function getWorker(name = 'default') {
|
11
|
+
let worker = workers[name];
|
12
|
+
return worker ? worker : undefined;
|
13
|
+
}
|
14
|
+
|
15
|
+
export function createDB(name = 'default') {
|
16
|
+
return new Promise((resolve, reject) => {
|
17
|
+
initalizeWorker(name);
|
18
|
+
let worker = getWorker(name);
|
19
|
+
worker.onmessage = function ({ data }) {
|
20
|
+
const { type, message } = data;
|
21
|
+
if (type === 'created') {
|
22
|
+
resolve({ message });
|
23
|
+
}
|
24
|
+
}
|
25
|
+
worker.onerror = (error) => {
|
26
|
+
reject(new Error(error));
|
27
|
+
};
|
28
|
+
worker.postMessage({ action: 'createDB', name });
|
29
|
+
});
|
30
|
+
}
|
31
|
+
|
32
|
+
export function executeQuery({ sql, values }, name = 'default') {
|
33
|
+
return new Promise((resolve, reject) => {
|
34
|
+
let worker = getWorker(name);
|
35
|
+
if (worker) {
|
36
|
+
worker.onmessage = function ({ data }) {
|
37
|
+
const { type } = data;
|
38
|
+
if (type === 'application/json') {
|
39
|
+
const { result } = data;
|
40
|
+
resolve(result);
|
41
|
+
}
|
42
|
+
}
|
43
|
+
worker.onerror = (error) => {
|
44
|
+
reject(error);
|
45
|
+
};
|
46
|
+
if (values && sql.indexOf("$") != -1) {
|
47
|
+
values.forEach(
|
48
|
+
function replacePlaceholder(item, index) {
|
49
|
+
sql = sql.replace("$" + (index + 1), `'${item}'`);
|
50
|
+
}
|
51
|
+
);
|
52
|
+
}
|
53
|
+
worker.postMessage({ action: "executeQuery", sql });
|
54
|
+
} else {
|
55
|
+
reject(new Error("No worker"));
|
56
|
+
}
|
57
|
+
})
|
58
|
+
}
|
59
|
+
|
60
|
+
export function downloadDB(name = 'default') {
|
61
|
+
let worker = workers[name];
|
62
|
+
if (worker) {
|
63
|
+
worker.onmessage = function ({ data }) {
|
64
|
+
const { type } = data;
|
65
|
+
if (type === 'application/vnd.sqlite3') {
|
66
|
+
let downloadChannel = new BroadcastChannel("download_channel");
|
67
|
+
downloadChannel.postMessage(data);
|
68
|
+
downloadChannel.close();
|
69
|
+
}
|
70
|
+
}
|
71
|
+
worker.postMessage({ action: 'downloadDB' });
|
72
|
+
}
|
73
|
+
}
|
74
|
+
|
75
|
+
export function uploadDB(fileName, arrayBuffer) {
|
76
|
+
let [name, extension] = fileName.split(".");
|
77
|
+
if (extension === 'sqlite3') {
|
78
|
+
let worker = workers[name];
|
79
|
+
if (!worker) {
|
80
|
+
initalizeWorker(name);
|
81
|
+
worker = getWorker(name);
|
82
|
+
} // TODO: allow overwrite
|
83
|
+
worker.postMessage({ action: 'uploadDB', name, arrayBuffer });
|
84
|
+
} else {
|
85
|
+
throw new Error({ name: "UnsupportedError", message: "Unsupported extension" });
|
86
|
+
}
|
87
|
+
}
|
88
|
+
|
89
|
+
export async function deleteDB(name) {
|
90
|
+
var root = await navigator.storage.getDirectory();
|
91
|
+
let fileSystemFileHandle = await root.getFileHandle(`${name}.sqlite3`);
|
92
|
+
if (fileSystemFileHandle) {
|
93
|
+
let worker = workers[name];
|
94
|
+
worker.onmessage = async function ({ data }) {
|
95
|
+
const { type } = data;
|
96
|
+
if (type === 'closed') {
|
97
|
+
log("Removing...", fileSystemFileHandle);
|
98
|
+
await fileSystemFileHandle.remove();
|
99
|
+
await worker.terminate();
|
100
|
+
}
|
101
|
+
delete workers[name];
|
102
|
+
}
|
103
|
+
worker.postMessage({ action: 'closeDB' });
|
104
|
+
}
|
105
|
+
}
|
106
|
+
|
107
|
+
function initalizeWorker(name) {
|
108
|
+
let worker = new Worker(new URL('./sqliteWorker.js', import.meta.url), { type: 'module' });
|
109
|
+
if (workers[name]) {
|
110
|
+
error("InstantiationError: already taken");
|
111
|
+
worker.terminate();
|
112
|
+
} else {
|
113
|
+
workers[name] = worker;
|
114
|
+
}
|
115
|
+
}
|
116
|
+
|
117
|
+
if (window.Worker) {
|
118
|
+
try {
|
119
|
+
// instantiation test
|
120
|
+
const sqlite3 = await sqlite3InitModule({ print: log, printErr: error });
|
121
|
+
log('Running SQLite3 version', sqlite3.version.libVersion);
|
122
|
+
} catch (err) {
|
123
|
+
error('Initialization error:', err.name, err.message);
|
124
|
+
}
|
125
|
+
} else {
|
126
|
+
console.error('Your browser doesn\'t support web workers.');
|
127
|
+
}
|
@@ -0,0 +1,98 @@
|
|
1
|
+
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
|
2
|
+
import { log, info, error } from '../logger';
|
3
|
+
|
4
|
+
var db = null;
|
5
|
+
var sqlite3 = null;
|
6
|
+
|
7
|
+
onmessage = async function ({ data }) {
|
8
|
+
const { action } = data;
|
9
|
+
switch (action) {
|
10
|
+
case 'createDB': {
|
11
|
+
const { name } = data;
|
12
|
+
const { newDB, message } = await createDatabase(name)
|
13
|
+
db = newDB;
|
14
|
+
postMessage({ type: 'created', message });
|
15
|
+
break;
|
16
|
+
}
|
17
|
+
case 'executeQuery': {
|
18
|
+
const { sql } = data;
|
19
|
+
log(sql);
|
20
|
+
try {
|
21
|
+
const result = db.exec({ sql, returnValue: "resultRows" });
|
22
|
+
postMessage({ result, type: "application/json" });
|
23
|
+
} catch (e) {
|
24
|
+
if (e.message.indexOf("SQLITE_CANTOPEN") != -1) {
|
25
|
+
info("Info: Currently no SQLite database available for this worker. Upload a new database or reload the page.")
|
26
|
+
}
|
27
|
+
}
|
28
|
+
break;
|
29
|
+
}
|
30
|
+
case 'uploadDB':
|
31
|
+
const { name, arrayBuffer } = data;
|
32
|
+
const { message } = await uploadDatabase(name, arrayBuffer)
|
33
|
+
log(message, db);
|
34
|
+
break;
|
35
|
+
case 'downloadDB':
|
36
|
+
try {
|
37
|
+
const byteArray = sqlite3.capi.sqlite3_js_db_export(db);
|
38
|
+
const blob = new Blob([byteArray.buffer], { type: "application/vnd.sqlite3" });
|
39
|
+
postMessage(blob); // send the database Blob to the API
|
40
|
+
} catch (e) {
|
41
|
+
if (e.message.indexOf("SQLITE_NOMEM") != -1)
|
42
|
+
postMessage({ type: "application/vnd.sqlite3", error: "SQLITE_NOMEM" });
|
43
|
+
else
|
44
|
+
error(e);
|
45
|
+
}
|
46
|
+
break;
|
47
|
+
case 'closeDB':
|
48
|
+
closeDB();
|
49
|
+
postMessage({ type: "closed" });
|
50
|
+
break;
|
51
|
+
default:
|
52
|
+
log(data)
|
53
|
+
}
|
54
|
+
}
|
55
|
+
|
56
|
+
async function createDatabase(name) {
|
57
|
+
const sqlite3 = await getInstance();
|
58
|
+
return 'opfs' in sqlite3
|
59
|
+
? { newDB: new sqlite3.oo1.OpfsDb(`/${name}.sqlite3`), message: `OPFS is available, created persisted database at /${name}.sqlite3` }
|
60
|
+
: { newDB: new sqlite3.oo1.DB(`/${name}.sqlite3`, 'ct'), message: `OPFS is not available, created transient database /${name}.sqlite3` };
|
61
|
+
}
|
62
|
+
|
63
|
+
async function uploadDatabase(name, arrayBuffer) {
|
64
|
+
try {
|
65
|
+
const sqlite3 = await getInstance();
|
66
|
+
if ('opfs' in sqlite3) {
|
67
|
+
const size = await sqlite3.oo1.OpfsDb.importDb(`${name}.sqlite3`, arrayBuffer);
|
68
|
+
if (size) {
|
69
|
+
db = new sqlite3.oo1.OpfsDb(`/${name}.sqlite3`);
|
70
|
+
return { message: `New DB imported as ${name}.sqlite3. (${arrayBuffer.byteLength} Bytes)` }
|
71
|
+
} else {
|
72
|
+
throw new Error({ name: "ImportError", message: "Empty size" })
|
73
|
+
}
|
74
|
+
} else { // TODO allow alternative
|
75
|
+
throw new Error({ name: "OPFSMissingError", message: "Unsupported operation due to missing OPFS support." });
|
76
|
+
}
|
77
|
+
} catch (err) {
|
78
|
+
error(err.name, err.message);
|
79
|
+
}
|
80
|
+
}
|
81
|
+
|
82
|
+
function closeDB() {
|
83
|
+
if (db) {
|
84
|
+
log("Closing...", db);
|
85
|
+
db.close();
|
86
|
+
}
|
87
|
+
}
|
88
|
+
|
89
|
+
async function getInstance() {
|
90
|
+
try {
|
91
|
+
if (!sqlite3) {
|
92
|
+
sqlite3 = await sqlite3InitModule({ print: log, printErr: error });
|
93
|
+
}
|
94
|
+
return sqlite3;
|
95
|
+
} catch (err) {
|
96
|
+
error(err.name, err.message);
|
97
|
+
}
|
98
|
+
}
|
package/vite.config.js
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
import { defineConfig } from 'vite';
|
2
|
+
import basicSsl from '@vitejs/plugin-basic-ssl';
|
3
|
+
|
4
|
+
export default defineConfig({
|
5
|
+
build: {
|
6
|
+
target: 'esnext'
|
7
|
+
},
|
8
|
+
server: {
|
9
|
+
port: 3443,
|
10
|
+
headers: {
|
11
|
+
'Cross-Origin-Opener-Policy': 'same-origin',
|
12
|
+
'Cross-Origin-Embedder-Policy': 'require-corp',
|
13
|
+
},
|
14
|
+
},
|
15
|
+
optimizeDeps: {
|
16
|
+
exclude: ['@sqlite.org/sqlite-wasm'],
|
17
|
+
},
|
18
|
+
plugins: [
|
19
|
+
basicSsl()
|
20
|
+
]
|
21
|
+
});
|