Unverified Commit 786a9dff authored by An Nyeong's avatar An Nyeong
Browse files

- Change `initialize` into synchronous function since all SQLite Driver

  provide synchronous API.
- Add deno-lint-ignore to ignore `require-await` error
- Add type annotations for `sqlite.node.ts`
- Add type constructor for Number for SQLStatment of node:sqlite, since
  the type of `changes` is `number | bigint`
parent 629f4eec
Loading
Loading
Loading
Loading
+8 −15
Original line number Diff line number Diff line
@@ -3,31 +3,24 @@
  "version": "1.8.0",
  "license": "MIT",
  "exports": {
    ".": "./mod.ts"
    ".": "./mod.ts",
    "./kv": "./kv.ts"
  },
  "imports": {
    "@fedify/sqlite": "./mod.ts",
    "@fedify/sqlite/": "./",
    "#sqlite": "./dist/sqlite.node.js"
    "#sqlite": "./sqlite.node.ts"
  },
  "nodeModulesDir": "none",
  "unstable": [
    "temporal"
  ],
  "exclude": [
    "dist",
    "node_modules"
  ],
  "publish": {
    "exclude": [
      "!dist/"
    ]
  },
  "tasks": {
    "check": "deno fmt --check && deno lint && deno check *.ts",
    "test": "deno test --allow-net --allow-env --doc --no-check=leaks"
  },
  "test": {
    "include": [
      "deno.test.ts"
    ],
    "exclude": [
      "node.test.ts"
    ]
  }
}
+23 −6
Original line number Diff line number Diff line
@@ -77,7 +77,12 @@ test("SqliteKvStore.set()", async () => {
    const result = db.prepare(`
      SELECT * FROM ${tableName}
      WHERE key = ?
    `).all(JSON.stringify(["foo", "baz"]));
    `).all(JSON.stringify(["foo", "baz"])) as {
      key: string;
      value: string;
      created: number;
      expires: number | null;
    }[];

    assert.strictEqual(result.length, 1);
    assert.deepStrictEqual(JSON.parse(result[0].key), ["foo", "baz"]);
@@ -90,17 +95,29 @@ test("SqliteKvStore.set()", async () => {
    const result2 = db.prepare(`
      SELECT * FROM ${tableName}
      WHERE key = ?
    `).all(JSON.stringify(["foo", "qux"]));
    `).all(JSON.stringify(["foo", "qux"])) as {
      key: string;
      value: string;
      created: number;
      expires: number | null;
    }[];
    assert.strictEqual(result2.length, 1);
    assert.deepStrictEqual(JSON.parse(result2[0].key), ["foo", "qux"]);
    assert.strictEqual(JSON.parse(result2[0].value), "qux");
    assert(result2[0].expires >= result2[0].created + 86400000);
    assert(
      result2[0].expires && result2[0].expires >= result2[0].created + 86400000,
    );

    await store.set(["foo", "quux"], true);
    const result3 = db.prepare(`
      SELECT * FROM ${tableName}
      WHERE key = ?
    `).all(JSON.stringify(["foo", "quux"]));
    `).all(JSON.stringify(["foo", "quux"])) as {
      key: string;
      value: string;
      created: number;
      expires: number | null;
    }[];
    assert.strictEqual(result3.length, 1);
    assert.deepStrictEqual(JSON.parse(result3[0].key), ["foo", "quux"]);
    assert.strictEqual(JSON.parse(result3[0].value), true);
@@ -174,7 +191,7 @@ test("SqliteKvStore.drop()", async () => {
});

test("SqliteKvStore.cas()", async () => {
  const { db, tableName, store } = getStore();
  const { db, store } = getStore();
  try {
    await store.set(["foo", "bar"], "foobar");
    assert.strictEqual(await store.cas(["foo", "bar"], "bar", "baz"), false);
@@ -195,7 +212,7 @@ test("SqliteKvStore.cas()", async () => {
});

test("SqliteKvStore - complex values", async () => {
  const { db, tableName, store } = getStore();
  const { db, store } = getStore();
  try {
    await store.set(["complex"], {
      nested: {
+17 −11
Original line number Diff line number Diff line
import { PlatformDatabase, SqliteDatabase } from "#sqlite";
import { type PlatformDatabase, SqliteDatabase } from "#sqlite";
import type { KvKey, KvStore, KvStoreSetOptions } from "@fedify/fedify";
import { Temporal } from "@js-temporal/polyfill";
import { getLogger } from "@logtape/logtape";
@@ -67,8 +67,9 @@ export class SqliteKvStore implements KvStore {
  /**
   * {@inheritDoc KvStore.get}
   */
  // deno-lint-ignore require-await
  async get<T = unknown>(key: KvKey): Promise<T | undefined> {
    await this.initialize();
    this.initialize();

    const encodedKey = this.#encodeKey(key);
    const now = Temporal.Now.instant().epochMilliseconds;
@@ -90,12 +91,13 @@ export class SqliteKvStore implements KvStore {
  /**
   * {@inheritDoc KvStore.set}
   */
  // deno-lint-ignore require-await
  async set(
    key: KvKey,
    value: unknown,
    options?: KvStoreSetOptions,
  ): Promise<void> {
    await this.initialize();
    this.initialize();

    if (value === undefined) {
      return;
@@ -118,14 +120,16 @@ export class SqliteKvStore implements KvStore {
      )
      .run(encodedKey, encodedValue, now, expiresAt);

    await this.#expire();
    this.#expire();
    return;
  }

  /**
   * {@inheritDoc KvStore.delete}
   */
  // deno-lint-ignore require-await
  async delete(key: KvKey): Promise<void> {
    await this.initialize();
    this.initialize();

    const encodedKey = this.#encodeKey(key);

@@ -134,19 +138,21 @@ export class SqliteKvStore implements KvStore {
      DELETE FROM "${this.#tableName}" WHERE key = ?
    `)
      .run(encodedKey);
    await this.#expire();
    this.#expire();
    return Promise.resolve();
  }

  /**
   * {@inheritDoc KvStore.cas}
   */
  // deno-lint-ignore require-await
  async cas(
    key: KvKey,
    expectedValue: unknown,
    newValue: unknown,
    options?: KvStoreSetOptions,
  ): Promise<boolean> {
    await this.initialize();
    this.initialize();

    const encodedKey = this.#encodeKey(key);
    const now = Temporal.Now.instant().epochMilliseconds;
@@ -194,7 +200,7 @@ export class SqliteKvStore implements KvStore {
      }

      this.#db.exec("COMMIT");
      await this.#expire();
      this.#expire();
      return true;
    } catch (error) {
      this.#db.exec("ROLLBACK");
@@ -206,7 +212,7 @@ export class SqliteKvStore implements KvStore {
   * Creates the table used by the key-value store if it does not already exist.
   * Does nothing if the table already exists.
   */
  async initialize(): Promise<void> {
  initialize() {
    if (this.#initialized) {
      return;
    }
@@ -235,7 +241,7 @@ export class SqliteKvStore implements KvStore {
    });
  }

  async #expire(): Promise<void> {
  #expire() {
    const now = Temporal.Now.instant().epochMilliseconds;
    this.#db
      .prepare(`
@@ -249,7 +255,7 @@ export class SqliteKvStore implements KvStore {
   * Drops the table used by the key-value store.  Does nothing if the table
   * does not exist.
   */
  async drop(): Promise<void> {
  drop() {
    this.#db.exec(`DROP TABLE IF EXISTS "${this.#tableName}"`);
    this.#initialized = false;
  }
+1 −1
Original line number Diff line number Diff line
import { Database, Statement } from "bun:sqlite";
import { Database, type Statement } from "bun:sqlite";
import type {
  SqliteDatabaseAdapter,
  SqliteStatementAdapter,
+12 −4
Original line number Diff line number Diff line
import { DatabaseSync, StatementSync } from "node:sqlite";
import {
  DatabaseSync,
  type SQLInputValue,
  type StatementSync,
} from "node:sqlite";
import type {
  SqliteDatabaseAdapter,
  SqliteStatementAdapter,
@@ -27,14 +31,18 @@ export class SqliteStatement implements SqliteStatementAdapter {
  constructor(private readonly stmt: StatementSync) {}

  run(...params: unknown[]): { changes: number; lastInsertRowid: number } {
    return this.stmt.run(...params);
    const result = this.stmt.run(...params as SQLInputValue[]);
    return {
      changes: Number(result.changes),
      lastInsertRowid: Number(result.lastInsertRowid),
    };
  }

  get(...params: unknown[]): unknown | undefined {
    return this.stmt.get(...params);
    return this.stmt.get(...params as SQLInputValue[]);
  }

  all(...params: unknown[]): unknown[] {
    return this.stmt.all(...params);
    return this.stmt.all(...params as SQLInputValue[]);
  }
}
+1 −1

File changed.

Contains only whitespace changes.

Loading