All files / kernel-store/src/sqlite nodejs.ts

98.92% Statements 92/93
92.85% Branches 26/28
100% Functions 24/24
98.92% Lines 92/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341                                                        94x 94x 94x         94x 94x                   94x 94x   94x 94x                   15233x 15233x 1x   15232x     94x 94x                     165x       165x     94x                 11482x     94x               1573x     94x 13874x   1359x                                         94x   94x   94x 94x   94x 94x 94x 94x 94x 94x 94x 94x 94x               246x 5x   241x 241x             231x 229x               3x 2x 2x               57x 57x                   2x 2x                                 125x         125x 297x 297x   125x                   478x 478x 2167x   478x 3x         128x                       12x                       246x 246x 246x 246x 246x                 7x 7x 7x 1x   6x 6x 6x 6x 3x                   235x 235x 235x 1x   234x 234x 234x 234x 231x       94x                 1x                     96x 89x   7x 7x 7x    
import { Logger } from '@metamask/logger';
import type { Database as SqliteDatabase } from 'better-sqlite3';
import Sqlite from 'better-sqlite3';
import { mkdir } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
 
import {
  SQL_QUERIES,
  DEFAULT_DB_FILENAME,
  assertSafeIdentifier,
} from './common.ts';
import { getDBFolder } from './env.ts';
import type { KVStore, VatStore, KernelDatabase } from '../types.ts';
 
export type Database = SqliteDatabase & {
  // stack of active savepoint names
  _spStack: string[];
};
 
/**
 * Ensure that SQLite is initialized.
 *
 * @param dbFilename - The filename of the database to use.
 * @param logger - The logger to use, if any.
 * @returns The SQLite database object.
 */
async function initDB(dbFilename: string, logger?: Logger): Promise<Database> {
  const dbPath = await getDBFilename(dbFilename);
  logger?.debug('dbPath:', dbPath);
  const db = new Sqlite(dbPath, {
    verbose: (logger ? logger.info.bind(logger) : undefined) as
      | ((...args: unknown[]) => void)
      | undefined,
  }) as Database;
  db._spStack = [];
  return db;
}
 
/**
 * Makes a persistent {@link KVStore} on top of a SQLite database.
 *
 * @param db - The (open) database to use.
 * @returns A key/value store using the given database.
 */
function makeKVStore(db: Database): KVStore {
  const sqlKVInit = db.prepare(SQL_QUERIES.CREATE_TABLE);
  sqlKVInit.run();
 
  const sqlKVGet = db.prepare<[string], string>(SQL_QUERIES.GET);
  sqlKVGet.pluck(true);
 
  /**
   * Read a key's value from the database.
   *
   * @param key - A key to fetch.
   * @param required - True if it is an error for the entry not to be there.
   * @returns The value at that key.
   */
  function kvGet(key: string, required: boolean): string | undefined {
    const result = sqlKVGet.get(key);
    if (required && !result) {
      throw Error(`no record matching key '${key}'`);
    }
    return result;
  }
 
  const sqlKVGetNextKey = db.prepare(SQL_QUERIES.GET_NEXT);
  sqlKVGetNextKey.pluck(true);
 
  /**
   * Get the lexicographically next key in the KV store after a given key.
   *
   * @param previousKey - The key you want to know the key after.
   *
   * @returns The key after `previousKey`, or undefined if `previousKey` is the
   *   last key in the store.
   */
  function kvGetNextKey(previousKey: string): string | undefined {
    Iif (typeof previousKey !== 'string') {
      // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
      throw new Error(`previousKey ${previousKey} must be a string`);
    }
    return sqlKVGetNextKey.get(previousKey) as string | undefined;
  }
 
  const sqlKVSet = db.prepare(SQL_QUERIES.SET);
 
  /**
   * Set the value associated with a key in the database.
   *
   * @param key - A key to assign.
   * @param value - The value to assign to it.
   */
  function kvSet(key: string, value: string): void {
    sqlKVSet.run(key, value);
  }
 
  const sqlKVDelete = db.prepare(SQL_QUERIES.DELETE);
 
  /**
   * Delete a key from the database.
   *
   * @param key - The key to remove.
   */
  function kvDelete(key: string): void {
    sqlKVDelete.run(key);
  }
 
  return {
    get: (key) => kvGet(key, false),
    getNextKey: kvGetNextKey,
    getRequired: (key) => kvGet(key, true) as string,
    set: kvSet,
    delete: kvDelete,
  };
}
 
/**
 * Makes a {@link KernelDatabase} for low-level persistent storage.
 *
 * @param options - The options for the database.
 * @param options.dbFilename - The filename of the database to use. Defaults to {@link DEFAULT_DB_FILENAME}.
 * @param options.logger - A logger to use.
 * @returns The key/value store to base the kernel store on.
 */
export async function makeSQLKernelDatabase({
  dbFilename,
  logger,
}: {
  dbFilename?: string | undefined;
  logger?: Logger;
}): Promise<KernelDatabase> {
  const db = await initDB(dbFilename ?? DEFAULT_DB_FILENAME, logger);
 
  const kvStore = makeKVStore(db);
 
  const sqlKVInitVS = db.prepare(SQL_QUERIES.CREATE_TABLE_VS);
  sqlKVInitVS.run();
 
  const sqlKVClear = db.prepare(SQL_QUERIES.CLEAR);
  const sqlKVClearVS = db.prepare(SQL_QUERIES.CLEAR_VS);
  const sqlVatstoreGetAll = db.prepare(SQL_QUERIES.GET_ALL_VS);
  const sqlVatstoreSet = db.prepare(SQL_QUERIES.SET_VS);
  const sqlVatstoreDelete = db.prepare(SQL_QUERIES.DELETE_VS);
  const sqlVatstoreDeleteAll = db.prepare(SQL_QUERIES.DELETE_VS_ALL);
  const sqlBeginTransaction = db.prepare(SQL_QUERIES.BEGIN_TRANSACTION);
  const sqlCommitTransaction = db.prepare(SQL_QUERIES.COMMIT_TRANSACTION);
  const sqlAbortTransaction = db.prepare(SQL_QUERIES.ABORT_TRANSACTION);
 
  /**
   * Begin a transaction if not already in one
   *
   *  @returns True if a new transaction was started, false if already in one
   */
  function beginIfNeeded(): boolean {
    if (db.inTransaction) {
      return false;
    }
    sqlBeginTransaction.run();
    return true;
  }
 
  /**
   * Commit a transaction if one is active and no savepoints remain
   */
  function commitIfNeeded(): void {
    if (db.inTransaction && db._spStack.length === 0) {
      sqlCommitTransaction.run();
    }
  }
 
  /**
   * Rollback a transaction
   */
  function rollbackIfNeeded(): void {
    if (db.inTransaction) {
      sqlAbortTransaction.run();
      db._spStack.length = 0;
    }
  }
 
  /**
   * Delete everything from the database.
   */
  function kvClear(): void {
    sqlKVClear.run();
    sqlKVClearVS.run();
  }
 
  /**
   * Execute an arbitrary query and return the results.
   *
   * @param sql - The query to execute.
   * @returns The results
   */
  function kvExecuteQuery(sql: string): Record<string, string>[] {
    const query = db.prepare(sql);
    return query.all() as Record<string, string>[];
  }
 
  /**
   * Create a new VatStore for a vat.
   *
   * @param vatID - The vat for which this is being done.
   *
   * @returns a a VatStore object for the given vat.
   */
  function makeVatStore(vatID: string): VatStore {
    /**
     * Fetch all the data in the vatstore.
     *
     * @returns the vatstore contents as a key-value Map.
     */
    function getKVData(): [string, string][] {
      const result: [string, string][] = [];
      type KVPair = {
        key: string;
        value: string;
      };
      for (const kvPair of sqlVatstoreGetAll.iterate(vatID)) {
        const { key, value } = kvPair as KVPair;
        result.push([key, value]);
      }
      return result;
    }
 
    /**
     * Update the state of the vatstore
     *
     * @param sets - A map of key values that have been changed.
     * @param deletes - A set of keys that have been deleted.
     */
    function updateKVData(sets: [string, string][], deletes: string[]): void {
      db.transaction(() => {
        for (const [key, value] of sets) {
          sqlVatstoreSet.run(vatID, key, value);
        }
        for (const value of deletes) {
          sqlVatstoreDelete.run(vatID, value);
        }
      })();
    }
 
    return {
      getKVData,
      updateKVData,
    };
  }
 
  /**
   * Delete an entire VatStore.
   *
   * @param vatId - The vat whose store is to be deleted.
   */
  function deleteVatStore(vatId: string): void {
    sqlVatstoreDeleteAll.run(vatId);
  }
 
  /**
   * Create a savepoint in the database.
   *
   * @param name - The name of the savepoint.
   */
  function createSavepoint(name: string): void {
    // We must be in a transaction when creating the savepoint or releasing it
    // later will cause an autocommit.
    // See https://github.com/Agoric/agoric-sdk/issues/8423
    beginIfNeeded();
    assertSafeIdentifier(name);
    const query = SQL_QUERIES.CREATE_SAVEPOINT.replace('%NAME%', name);
    db.exec(query);
    db._spStack.push(name);
  }
 
  /**
   * Rollback to a savepoint in the database.
   *
   * @param name - The name of the savepoint.
   */
  function rollbackSavepoint(name: string): void {
    assertSafeIdentifier(name);
    const idx = db._spStack.lastIndexOf(name);
    if (idx < 0) {
      throw new Error(`No such savepoint: ${name}`);
    }
    const query = SQL_QUERIES.ROLLBACK_SAVEPOINT.replace('%NAME%', name);
    db.exec(query);
    db._spStack.splice(idx);
    if (db._spStack.length === 0) {
      rollbackIfNeeded();
    }
  }
 
  /**
   * Release a savepoint in the database.
   *
   * @param name - The name of the savepoint.
   */
  function releaseSavepoint(name: string): void {
    assertSafeIdentifier(name);
    const idx = db._spStack.lastIndexOf(name);
    if (idx < 0) {
      throw new Error(`No such savepoint: ${name}`);
    }
    const query = SQL_QUERIES.RELEASE_SAVEPOINT.replace('%NAME%', name);
    db.exec(query);
    db._spStack.splice(idx);
    if (db._spStack.length === 0) {
      commitIfNeeded();
    }
  }
 
  return {
    kernelKVStore: kvStore,
    executeQuery: kvExecuteQuery,
    clear: db.transaction(kvClear),
    makeVatStore,
    deleteVatStore,
    createSavepoint,
    rollbackSavepoint,
    releaseSavepoint,
    close: () => db.close(),
  };
}
 
/**
 * Get the filename for a database.
 *
 * @param label - A label for the database.
 * @returns The filename for the database.
 */
export async function getDBFilename(label: string): Promise<string> {
  if (label.startsWith(':')) {
    return label;
  }
  const dbRoot = join(tmpdir(), './ocap-sqlite', getDBFolder());
  await mkdir(dbRoot, { recursive: true });
  return join(dbRoot, label);
}