-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.test.js
73 lines (62 loc) · 1.97 KB
/
index.test.js
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
const Database = require('./index')
const os = require('os')
const fs = require('fs')
const path = require('path')
const assert = require('assert').strict
const it = function() {
return process['isBun'] ? test : require('node:test').it
}()
it('should open in-memory database', () => {
//when
const db = new Database(":memory:")
const query = db.prepare("select 'Hello world' as message;")
//then
assert.deepEqual(query.get(), {message: 'Hello world'})
//when & then
const results = query.all()
assert.deepEqual(Array.isArray(results), true);
assert.deepEqual(results, [{message: 'Hello world'}])
//when & then
db.close()
})
it('should create file-based database', () => {
//given
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "better-sqlite3-wrapper-"))
const file = path.join(tmpDir, "test.db")
let db = new Database(file)
const changesQuery = db.prepare("SELECT changes() AS changes;")
const lastInsertRowIdQuery = db.prepare("SELECT last_insert_rowid() AS id;")
//when
const [changes, lastInsertRowId] = db.transaction(() => {
db.prepare(`
create table test(
id integer primary key,
name text not null
);
`).run()
const insert = db.prepare("insert into test (name) values (?);")
insert.run("test1")
insert.run("test2")
return [changesQuery.get().changes, lastInsertRowIdQuery.get().id]
})()
//then
assert.deepEqual(changes, 1)
assert.deepEqual(lastInsertRowId, 2)
db.close()
assert.deepEqual(fs.existsSync(file), true)
//when
db = new Database(file, { readonly: true })
const results = db.prepare("select * from test order by id;").all()
//then
assert.deepEqual(results, [{
id: 1,
name: "test1"
}, {
id: 2,
name: "test2"
}])
//cleanup
db.close()
fs.unlinkSync(file)
fs.rmdirSync(tmpDir)
})