diff --git a/web/database/queries/db-queries.js b/web/database/queries/db-queries.js index 045ad81a8..ddf6c9b80 100644 --- a/web/database/queries/db-queries.js +++ b/web/database/queries/db-queries.js @@ -1,28 +1,33 @@ // @flow import type { SqliteDatabase } from 'sql.js'; function getSQLiteDBVersion(db: SqliteDatabase): number { const versionData = db.exec('PRAGMA user_version;'); if (!versionData.length || !versionData[0].values.length) { throw new Error('Error while retrieving database version: empty result'); } const [dbVersion] = versionData[0].values[0]; if (typeof dbVersion !== 'number') { throw new Error( 'Error while retrieving database version: invalid type returned', ); } return dbVersion; } function setupSQLiteDB(db: SqliteDatabase) { db.exec(` CREATE TABLE IF NOT EXISTS drafts ( key TEXT UNIQUE PRIMARY KEY NOT NULL, text TEXT NOT NULL - ) + ); + + CREATE TABLE IF NOT EXISTS metadata ( + name TEXT UNIQUE PRIMARY KEY NOT NULL, + data TEXT NOT NULL + ); `); } export { getSQLiteDBVersion, setupSQLiteDB }; diff --git a/web/database/queries/metadata-queries.js b/web/database/queries/metadata-queries.js new file mode 100644 index 000000000..fb88c022d --- /dev/null +++ b/web/database/queries/metadata-queries.js @@ -0,0 +1,56 @@ +// @flow + +import { SqliteDatabase } from 'sql.js'; + +import { parseMultiStatementSQLiteResult } from '../utils/db-utils.js'; + +type Metadata = { + name: string, + data: string, +}; + +function setMetadata(db: SqliteDatabase, entryName: string, data: string) { + const query = ` + INSERT OR REPLACE INTO metadata (name, data) + VALUES ($entryName, $data) + `; + const params = { + $entryName: entryName, + $data: data, + }; + + db.exec(query, params); +} + +function getMetadata(db: SqliteDatabase, entryName: string): ?string { + const query = ` + SELECT * + FROM metadata + WHERE name = $entryName + `; + const params = { + $entryName: entryName, + }; + + const rawResult = db.exec(query, params); + const result = parseMultiStatementSQLiteResult(rawResult); + if (result.length === 0 || result[0].length === 0) { + return undefined; + } + const [entry] = result[0]; + return entry.data; +} + +function clearMetadata(db: SqliteDatabase, entryName: string) { + const query = ` + DELETE FROM metadata + WHERE name = $entryName + `; + const params = { + $entryName: entryName, + }; + + db.exec(query, params); +} + +export { setMetadata, getMetadata, clearMetadata };