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 | const connected = opts.connect()
|
32 | .then(query => query(createTable).then(() => query))
|
33 | .catch(err => this.emit('error', err));
|
34 |
|
35 | this.query = sqlString => connected
|
36 | .then(query => query(sqlString));
|
37 | }
|
38 |
|
39 | get(key) {
|
40 | const select = this.entry.select().where({ key }).toString();
|
41 | return this.query(select)
|
42 | .then(rows => {
|
43 | const row = rows[0];
|
44 | if (row === undefined) {
|
45 | return undefined;
|
46 | }
|
47 | return row.value;
|
48 | });
|
49 | }
|
50 |
|
51 | set(key, value) {
|
52 | let upsert;
|
53 | if (this.sql.dialectName === 'postgres') {
|
54 | upsert = this.entry.insert({ key, value }).onConflict({ columns: ['key'], update: ['value'] }).toString();
|
55 | } else {
|
56 | upsert = this.entry.replace({ key, value }).toString();
|
57 | }
|
58 | return this.query(upsert);
|
59 | }
|
60 |
|
61 | delete(key) {
|
62 | const select = this.entry.select().where({ key }).toString();
|
63 | const del = this.entry.delete().where({ key }).toString();
|
64 | return this.query(select)
|
65 | .then(rows => {
|
66 | const row = rows[0];
|
67 | if (row === undefined) {
|
68 | return false;
|
69 | }
|
70 | return this.query(del)
|
71 | .then(() => true);
|
72 | });
|
73 | }
|
74 |
|
75 | clear() {
|
76 | const del = this.entry.delete(this.entry.key.like(`${this.namespace}:%`)).toString();
|
77 | return this.query(del)
|
78 | .then(() => undefined);
|
79 | }
|
80 | }
|
81 |
|
82 | module.exports = KeyvSql;
|