1 | 'use strict';
|
2 |
|
3 | const EventEmitter = require('events');
|
4 | const Sql = require('sql').Sql;
|
5 |
|
6 | class KeyvSql extends EventEmitter {
|
7 | constructor(opts) {
|
8 | super();
|
9 | this.ttlSupport = false;
|
10 |
|
11 | opts = Object.assign({ table: 'keyv' }, opts);
|
12 |
|
13 | this.sql = new Sql(opts.dialect);
|
14 |
|
15 | this.entry = this.sql.define({
|
16 | name: opts.table,
|
17 | columns: [
|
18 | {
|
19 | name: 'key',
|
20 | primaryKey: true,
|
21 | dataType: 'VARCHAR(255)'
|
22 | },
|
23 | {
|
24 | name: 'value',
|
25 | dataType: 'TEXT'
|
26 | }
|
27 | ]
|
28 | });
|
29 | const createTable = this.entry.create().ifNotExists().toString();
|
30 |
|
31 | this.connected = opts.connect()
|
32 | .then(query => query(createTable).then(() => query))
|
33 | .catch(err => this.emit('error', err));
|
34 | }
|
35 |
|
36 | get(key) {
|
37 | const select = this.entry.select().where({ key }).toString();
|
38 | return this.connected
|
39 | .then(query => query(select))
|
40 | .then(rows => {
|
41 | const row = rows[0];
|
42 | if (row === undefined) {
|
43 | return undefined;
|
44 | }
|
45 | return row.value;
|
46 | });
|
47 | }
|
48 |
|
49 | set(key, value) {
|
50 | let upsert = this.entry.replace({ key, value }).toString();
|
51 | if (this.sql.dialectName === 'postgres') {
|
52 | upsert = this.entry.insert({ key, value }).onConflict({ columns: ['key'], update: ['value'] }).toString();
|
53 | }
|
54 | return this.connected
|
55 | .then(query => query(upsert));
|
56 | }
|
57 |
|
58 | delete(key) {
|
59 | const select = this.entry.select().where({ key }).toString();
|
60 | const del = this.entry.delete().where({ key }).toString();
|
61 | return this.connected
|
62 | .then(query => {
|
63 | return query(select)
|
64 | .then(rows => {
|
65 | const row = rows[0];
|
66 | if (row === undefined) {
|
67 | return false;
|
68 | }
|
69 | return query(del)
|
70 | .then(() => true);
|
71 | });
|
72 | });
|
73 | }
|
74 |
|
75 | clear() {
|
76 | const del = this.entry.delete(this.entry.key.like(`${this.namespace}:%`)).toString();
|
77 | return this.connected
|
78 | .then(query => query(del))
|
79 | .then(() => undefined);
|
80 | }
|
81 | }
|
82 |
|
83 | module.exports = KeyvSql;
|