-
Notifications
You must be signed in to change notification settings - Fork 1
/
knex.jsy
68 lines (51 loc) · 1.6 KB
/
knex.jsy
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
import {bkc_hexkey_api, as_hex_key, as_u8_key} from '../_utils.jsy'
export {as_hex_key, as_u8_key}
export default bkc_with_knex
export async function bkc_with_knex(knex, opt={}) ::
let immutable = !! opt.immutable
let table = opt.table || 'phorbas_kv'
if ! await knex.schema.hasTable(table) ::
await knex.schema.createTable @ table, @\ t ::
let {key_type, blob_type} = opt
let col_key = key_type
? t.specificType('hk', key_type)
: t.string('hk')
col_key.unique().notNullable().primary()
let col_bc = blob_type
? t.specificType('bc', blob_type)
: t.binary('bc')
col_bc.notNullable()
return bkc_hexkey_api @:
bkc_opt: @{} immutable
async hk_has(hex_key) ::
let ans = await knex(table)
.select('hk')
.where('hk', hex_key)
.first()
return null != ans ? 1 : 0
async hk_get(hex_key) ::
let ans = await knex(table)
.select('bc')
.where('hk', hex_key)
.first()
if null != ans ::
return Uint8Array.from(ans.bc)
async hk_set(hex_key, u8_content) ::
let bc =
#IF PLAT_NODEJS
Buffer.from(u8_content)
#ELSE
u8_content
try ::
await knex(table).insert({hk: hex_key, bc})
catch err ::
if immutable ::
// Note: better to ensure `err` is a constraint error, but
// inconsistent error returns between backends
return false
try ::
await knex(table)
.where({hk: hex_key})
.update({bc})
catch err2 ::
return err