87 lines
2.7 KiB
JavaScript
87 lines
2.7 KiB
JavaScript
import sqlite3InitModule from '/sqlite3.mjs';
|
|
|
|
const DB_FILE = '/lifeos.sqlite';
|
|
let db;
|
|
let pool;
|
|
|
|
function reply(id, result, error) {
|
|
self.postMessage({ id, result, error: error ? String(error.message || error) : null });
|
|
}
|
|
|
|
async function initialize() {
|
|
const sqlite3 = await sqlite3InitModule({
|
|
print: () => {},
|
|
printErr: (...args) => console.warn('[Life OS SQLite]', ...args)
|
|
});
|
|
pool = await sqlite3.installOpfsSAHPoolVfs({
|
|
name: 'lifeos-opfs',
|
|
directory: '/lifeos-sqlite',
|
|
initialCapacity: 6
|
|
});
|
|
db = new pool.OpfsSAHPoolDb(DB_FILE);
|
|
db.exec(`
|
|
PRAGMA journal_mode=DELETE;
|
|
PRAGMA synchronous=FULL;
|
|
CREATE TABLE IF NOT EXISTS app_state (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL,
|
|
updated_at TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS metadata (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL
|
|
);
|
|
INSERT INTO metadata(key, value) VALUES('schema_version', '1')
|
|
ON CONFLICT(key) DO UPDATE SET value=excluded.value;
|
|
`);
|
|
return status();
|
|
}
|
|
|
|
function snapshot() {
|
|
const rows = db.exec({
|
|
sql: 'SELECT key, value, updated_at FROM app_state ORDER BY key',
|
|
rowMode: 'object',
|
|
returnValue: 'resultRows'
|
|
});
|
|
return {
|
|
values: Object.fromEntries(rows.map(row => [row.key, row.value])),
|
|
updatedAt: rows.reduce((latest, row) => row.updated_at > latest ? row.updated_at : latest, '')
|
|
};
|
|
}
|
|
|
|
function write({ key, value, updatedAt }) {
|
|
db.exec({
|
|
sql: `INSERT INTO app_state(key, value, updated_at) VALUES(?, ?, ?)
|
|
ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at`,
|
|
bind: [key, value, updatedAt]
|
|
});
|
|
return true;
|
|
}
|
|
|
|
function remove({ key }) {
|
|
db.exec({ sql: 'DELETE FROM app_state WHERE key = ?', bind: [key] });
|
|
return true;
|
|
}
|
|
|
|
async function status() {
|
|
const rows = db.exec({ sql: 'SELECT COUNT(*) AS count FROM app_state', rowMode: 'object', returnValue: 'resultRows' });
|
|
let size = 0;
|
|
try { size = (await pool.exportFile(DB_FILE)).byteLength; } catch {}
|
|
return { ready: true, engine: 'SQLite', sqliteVersion: db.selectValue('SELECT sqlite_version()'), records: Number(rows[0]?.count || 0), size };
|
|
}
|
|
|
|
self.onmessage = async event => {
|
|
const { id, action, payload = {} } = event.data || {};
|
|
try {
|
|
if (action === 'init') return reply(id, await initialize());
|
|
if (!db) throw new Error('Local database is not initialized');
|
|
if (action === 'snapshot') return reply(id, snapshot());
|
|
if (action === 'write') return reply(id, write(payload));
|
|
if (action === 'remove') return reply(id, remove(payload));
|
|
if (action === 'status') return reply(id, await status());
|
|
throw new Error(`Unknown local database action: ${action}`);
|
|
} catch (error) {
|
|
reply(id, null, error);
|
|
}
|
|
};
|