core: clear database on logout

This commit is contained in:
Abdullah Atta
2023-12-12 10:02:26 +05:00
parent 5ca765e5b0
commit 65a6555065
4 changed files with 24 additions and 8 deletions

View File

@@ -66,7 +66,7 @@ import {
SQLiteOptions,
createDatabase
} from "../database";
import { Kysely, Transaction } from "kysely";
import { Kysely, Transaction, sql } from "kysely";
import { CachedCollection } from "../database/cached-collection";
type EventSourceConstructor = new (
@@ -223,6 +223,22 @@ class Database {
await this.session.set();
}
async reset() {
await this.storage().clear();
for (const statement of [
"PRAGMA writable_schema = 1",
"DELETE FROM sqlite_master",
"PRAGMA writable_schema = 0",
"VACUUM",
"PRAGMA integrity_check"
]) {
await sql.raw(statement).execute(this.sql());
}
await this.sql().destroy();
this._sql = await createDatabase("notesnook", this.options.sqliteOptions);
}
async init() {
if (!this.options)
throw new Error(
@@ -244,7 +260,7 @@ class Database {
this.disconnectSSE();
});
this._sql = await createDatabase(this.options.sqliteOptions);
this._sql = await createDatabase("notesnook", this.options.sqliteOptions);
await this._validate();

View File

@@ -151,10 +151,10 @@ class Sync {
this.logger.info("Starting sync", { full, force });
this.connection.onclose((error) => {
this.connection.onclose((error = new Error("Connection closed.")) => {
this.db.eventManager.publish(EVENTS.syncAborted);
console.error(error);
this.logger.error(error || new Error("Connection closed."));
this.logger.error(error);
throw new Error("Connection closed.");
});

View File

@@ -265,7 +265,7 @@ class UserManager {
} catch (e) {
console.error(e);
} finally {
await this.db.storage().clear();
await this.db.reset();
EV.publish(EVENTS.userLoggedOut, reason);
EV.publish(EVENTS.appRefreshRequested);
}

View File

@@ -197,7 +197,7 @@ const DataMappers: Partial<Record<ItemType, (row: any) => void>> = {
};
export type SQLiteOptions = {
dialect: Dialect;
dialect: (name: string) => Dialect;
journalMode?: "WAL" | "MEMORY" | "OFF" | "PERSIST" | "TRUNCATE" | "DELETE";
synchronous?: "normal" | "extra" | "full" | "off";
lockingMode?: "normal" | "exclusive";
@@ -205,9 +205,9 @@ export type SQLiteOptions = {
cacheSize?: number;
pageSize?: number;
};
export async function createDatabase(options: SQLiteOptions) {
export async function createDatabase(name: string, options: SQLiteOptions) {
const db = new Kysely<DatabaseSchema>({
dialect: options.dialect,
dialect: options.dialect(name),
plugins: [new SqliteBooleanPlugin()]
});