summaryrefslogtreecommitdiff
path: root/packages/idb-bridge/src/SqliteBackend.test.ts
blob: 612cb9d4b42c177156aea6f8b9e47fd9ef45fc11 (plain)
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
/*
 Copyright 2019 Florian Dold

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 or implied. See the License for the specific language governing
 permissions and limitations under the License.
 */

import test from "ava";
import { createSqliteBackend } from "./SqliteBackend.js";
import { ResultLevel, StoreLevel } from "./backend-interface.js";
import { BridgeIDBKeyRange } from "./bridge-idb.js";
import * as fs from "node:fs";
import { createNodeSqlite3Impl } from "./node-sqlite3-impl.js";

test("sqlite3 backend", async (t) => {
  const filename = "mytestdb.sqlite3";
  try {
    fs.unlinkSync(filename);
  } catch (e) {
    // Do nothing.
  }
  try {
    const sqlite3Impl = await createNodeSqlite3Impl();
    const backend = await createSqliteBackend(sqlite3Impl, {
      filename,
    });
    const dbConnRes = await backend.connectDatabase("mydb");
    const dbConn = dbConnRes.conn;
    const tx = await backend.enterVersionChange(dbConn, 1);
    backend.createObjectStore(tx, "books", "isbn", true);
    backend.createIndex(tx, "byName", "books", "name", false, false);
    await backend.storeRecord(tx, {
      objectStoreName: "books",
      storeLevel: StoreLevel.AllowOverwrite,
      value: { name: "foo" },
      key: undefined,
    });
    const res = await backend.getObjectStoreRecords(tx, {
      direction: "next",
      limit: 1,
      objectStoreName: "books",
      resultLevel: ResultLevel.Full,
      range: BridgeIDBKeyRange.only(1),
    });
    t.deepEqual(res.count, 1);
    t.deepEqual(res.primaryKeys![0], 1);
    t.deepEqual(res.values![0].name, "foo");

    const indexRes = await backend.getIndexRecords(tx, {
      direction: "next",
      limit: 1,
      objectStoreName: "books",
      indexName: "byName",
      resultLevel: ResultLevel.Full,
      range: BridgeIDBKeyRange.only("foo"),
    });

    t.deepEqual(indexRes.count, 1);
    t.deepEqual(indexRes.values![0].isbn, 1);
    t.deepEqual(indexRes.values![0].name, "foo");

    await backend.commit(tx);

    const tx2 = await backend.beginTransaction(dbConn, ["books"], "readwrite");
    await backend.commit(tx2);

    await backend.close(dbConn);

    t.pass();
  } catch (e: any) {
    console.log(e);
    throw e;
  }
});