ueberdb2 4.0.11 → 4.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/.eslintignore +2 -0
  2. package/.eslintrc.cjs +44 -5
  3. package/.github/workflows/npmpublish.yml +3 -3
  4. package/databases/{cassandra_db.js → cassandra_db.ts} +45 -30
  5. package/databases/{couch_db.js → couch_db.ts} +78 -31
  6. package/databases/{dirty_db.js → dirty_db.ts} +19 -14
  7. package/databases/{dirty_git_db.js → dirty_git_db.ts} +19 -15
  8. package/databases/{elasticsearch_db.js → elasticsearch_db.ts} +30 -21
  9. package/databases/{memory_db.js → memory_db.ts} +8 -8
  10. package/databases/mock_db.ts +43 -0
  11. package/databases/{mongodb_db.js → mongodb_db.ts} +22 -16
  12. package/databases/{mssql_db.js → mssql_db.ts} +29 -21
  13. package/databases/{mysql_db.js → mysql_db.ts} +20 -15
  14. package/databases/{postgres_db.js → postgres_db.ts} +37 -22
  15. package/databases/{postgrespool_db.js → postgrespool_db.ts} +3 -3
  16. package/databases/redis_db.ts +129 -0
  17. package/databases/{rethink_db.js → rethink_db.ts} +35 -19
  18. package/databases/{sqlite_db.js → sqlite_db.ts} +37 -36
  19. package/dist/databases/cassandra_db.js +237 -0
  20. package/dist/databases/couch_db.js +181 -0
  21. package/dist/databases/dirty_db.js +78 -0
  22. package/dist/databases/dirty_git_db.js +77 -0
  23. package/dist/databases/elasticsearch_db.js +251 -0
  24. package/dist/databases/memory_db.js +39 -0
  25. package/dist/databases/mock_db.js +40 -0
  26. package/dist/databases/mongodb_db.js +127 -0
  27. package/dist/databases/mssql_db.js +187 -0
  28. package/dist/databases/mysql_db.js +170 -0
  29. package/dist/databases/postgres_db.js +192 -0
  30. package/dist/databases/postgrespool_db.js +12 -0
  31. package/dist/databases/redis_db.js +105 -0
  32. package/dist/databases/rethink_db.js +123 -0
  33. package/dist/databases/sqlite_db.js +140 -0
  34. package/dist/index.js +215 -0
  35. package/dist/lib/AbstractDatabase.js +38 -0
  36. package/dist/lib/CacheAndBufferLayer.js +657 -0
  37. package/dist/lib/logging.js +34 -0
  38. package/dist/test/lib/databases.js +72 -0
  39. package/dist/test/test.js +373 -0
  40. package/dist/test/test_bulk.js +74 -0
  41. package/dist/test/test_elasticsearch.js +157 -0
  42. package/dist/test/test_findKeys.js +69 -0
  43. package/dist/test/test_flush.js +83 -0
  44. package/dist/test/test_getSub.js +57 -0
  45. package/dist/test/test_lru.js +155 -0
  46. package/dist/test/test_memory.js +59 -0
  47. package/dist/test/test_metrics.js +772 -0
  48. package/dist/test/test_mysql.js +91 -0
  49. package/dist/test/test_postgres.js +40 -0
  50. package/dist/test/test_setSub.js +48 -0
  51. package/dist/test/test_tojson.js +62 -0
  52. package/docker-compose.yml +44 -0
  53. package/{index.js → index.ts} +76 -25
  54. package/lib/AbstractDatabase.ts +79 -0
  55. package/lib/{CacheAndBufferLayer.js → CacheAndBufferLayer.ts} +17 -16
  56. package/lib/{logging.js → logging.ts} +10 -6
  57. package/package.json +18 -3
  58. package/test/lib/{databases.js → databases.ts} +8 -5
  59. package/test/test.ts +328 -0
  60. package/test/test_bulk.ts +69 -0
  61. package/test/{test_elasticsearch.js → test_elasticsearch.ts} +48 -53
  62. package/test/{test_findKeys.js → test_findKeys.ts} +15 -17
  63. package/test/{test_flush.js → test_flush.ts} +16 -22
  64. package/test/test_getSub.ts +28 -0
  65. package/test/test_lru.ts +151 -0
  66. package/test/test_memory.ts +32 -0
  67. package/test/{test_metrics.js → test_metrics.ts} +73 -68
  68. package/test/{test_mysql.js → test_mysql.ts} +16 -22
  69. package/test/test_postgres.ts +16 -0
  70. package/test/{test_setSub.js → test_setSub.ts} +8 -12
  71. package/test/test_tojson.ts +34 -0
  72. package/databases/mock_db.js +0 -42
  73. package/databases/redis_db.js +0 -96
  74. package/lib/AbstractDatabase.js +0 -37
  75. package/test/test.js +0 -328
  76. package/test/test_bulk.js +0 -69
  77. package/test/test_getSub.js +0 -31
  78. package/test/test_lru.js +0 -145
  79. package/test/test_memory.js +0 -31
  80. package/test/test_postgres.js +0 -16
  81. package/test/test_tojson.js +0 -37
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ /**
3
+ * 2011 Peter 'Pita' Martischka
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS-IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.Database = void 0;
22
+ const AbstractDatabase_1 = __importDefault(require("../lib/AbstractDatabase"));
23
+ const mysql_1 = __importDefault(require("mysql"));
24
+ const util_1 = __importDefault(require("util"));
25
+ const Database = class extends AbstractDatabase_1.default {
26
+ _mysqlSettings;
27
+ _pool;
28
+ constructor(settings) {
29
+ super();
30
+ this.logger = console;
31
+ this._mysqlSettings = {
32
+ charset: 'utf8mb4',
33
+ ...settings,
34
+ };
35
+ this.settings = {
36
+ engine: 'InnoDB',
37
+ // Limit the query size to avoid timeouts or other failures.
38
+ bulkLimit: 100,
39
+ json: true,
40
+ queryTimeout: 60000,
41
+ };
42
+ this._pool = null; // Initialized in init();
43
+ }
44
+ get isAsync() { return true; }
45
+ async _query(options) {
46
+ try {
47
+ return await new Promise((resolve, reject) => {
48
+ options = { timeout: this.settings.queryTimeout, ...options };
49
+ // @ts-ignore
50
+ this._pool && this._pool.query(options, (err, ...args) => err != null ? reject(err) : resolve(args));
51
+ });
52
+ }
53
+ catch (err) {
54
+ this.logger.error(`${err.fatal ? 'Fatal ' : ''}MySQL error: ${err.stack || err}`);
55
+ throw err;
56
+ }
57
+ }
58
+ async init() {
59
+ // @ts-ignore
60
+ this._pool = mysql_1.default.createPool(this._mysqlSettings);
61
+ const { database, charset } = this._mysqlSettings;
62
+ const sqlCreate = `${'CREATE TABLE IF NOT EXISTS `store` ( ' +
63
+ '`key` VARCHAR( 100 ) NOT NULL COLLATE utf8mb4_bin, ' +
64
+ '`value` LONGTEXT COLLATE utf8mb4_bin NOT NULL , ' +
65
+ 'PRIMARY KEY ( `key` ) ' +
66
+ ') ENGINE='}${this.settings.engine} CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`;
67
+ const sqlAlter = 'ALTER TABLE store MODIFY `key` VARCHAR(100) COLLATE utf8mb4_bin;';
68
+ await this._query({ sql: sqlCreate });
69
+ // Checks for Database charset et al
70
+ const dbCharSet = 'SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME ' +
71
+ `FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${database}'`;
72
+ // @ts-ignore
73
+ let [result] = await this._query({ sql: dbCharSet });
74
+ result = JSON.parse(JSON.stringify(result));
75
+ if (result[0].DEFAULT_CHARACTER_SET_NAME !== charset) {
76
+ this.logger.error(`Database is not configured with charset ${charset} -- ` +
77
+ 'This may lead to crashes when certain characters are pasted in pads');
78
+ this.logger.log(result[0], charset);
79
+ }
80
+ if (result[0].DEFAULT_COLLATION_NAME.indexOf(charset) === -1) {
81
+ this.logger.error(`Database is not configured with collation name that includes ${charset} -- ` +
82
+ 'This may lead to crashes when certain characters are pasted in pads');
83
+ this.logger.log(result[0], charset, result[0].DEFAULT_COLLATION_NAME);
84
+ }
85
+ const tableCharSet = 'SELECT CCSA.character_set_name AS character_set_name ' +
86
+ 'FROM information_schema.`TABLES` ' +
87
+ 'T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA ' +
88
+ 'WHERE CCSA.collation_name = T.table_collation ' +
89
+ `AND T.table_schema = '${database}' ` +
90
+ "AND T.table_name = 'store'";
91
+ [result] = await this._query({ sql: tableCharSet });
92
+ if (!result[0]) {
93
+ this.logger.warn('Data has no character_set_name value -- ' +
94
+ 'This may lead to crashes when certain characters are pasted in pads');
95
+ }
96
+ if (result[0] && (result[0].character_set_name !== charset)) {
97
+ this.logger.error(`table is not configured with charset ${charset} -- ` +
98
+ 'This may lead to crashes when certain characters are pasted in pads');
99
+ this.logger.log(result[0], charset);
100
+ }
101
+ // check migration level, alter if not migrated
102
+ const level = await this.get('MYSQL_MIGRATION_LEVEL');
103
+ if (level !== '1') {
104
+ await this._query({ sql: sqlAlter });
105
+ await this.set('MYSQL_MIGRATION_LEVEL', '1');
106
+ }
107
+ }
108
+ async get(key) {
109
+ const [results] = await this._query({
110
+ sql: 'SELECT `value` FROM `store` WHERE `key` = ? AND BINARY `key` = ?',
111
+ values: [key, key],
112
+ });
113
+ return results.length === 1 ? results[0].value : null;
114
+ }
115
+ async findKeys(key, notKey) {
116
+ let query = 'SELECT `key` FROM `store` WHERE `key` LIKE ?';
117
+ const params = [];
118
+ // desired keys are key, e.g. pad:%
119
+ key = key.replace(/\*/g, '%');
120
+ params.push(key);
121
+ if (notKey != null) {
122
+ // not desired keys are notKey, e.g. %:%:%
123
+ notKey = notKey.replace(/\*/g, '%');
124
+ query += ' AND `key` NOT LIKE ?';
125
+ params.push(notKey);
126
+ }
127
+ const [results] = await this._query({ sql: query, values: params });
128
+ return results.map((val) => val.key);
129
+ }
130
+ async set(key, value) {
131
+ if (key.length > 100)
132
+ throw new Error('Your Key can only be 100 chars');
133
+ await this._query({ sql: 'REPLACE INTO `store` VALUES (?,?)', values: [key, value] });
134
+ }
135
+ async remove(key) {
136
+ await this._query({
137
+ sql: 'DELETE FROM `store` WHERE `key` = ? AND BINARY `key` = ?',
138
+ values: [key, key],
139
+ });
140
+ }
141
+ async doBulk(bulk) {
142
+ const replaces = [];
143
+ const deletes = [];
144
+ for (const op of bulk) {
145
+ switch (op.type) {
146
+ case 'set':
147
+ replaces.push([op.key, op.value]);
148
+ break;
149
+ case 'remove':
150
+ deletes.push(op.key);
151
+ break;
152
+ default: throw new Error(`unknown op type: ${op.type}`);
153
+ }
154
+ }
155
+ await Promise.all([
156
+ replaces.length ? this._query({
157
+ sql: 'REPLACE INTO `store` VALUES ?;',
158
+ values: [replaces],
159
+ }) : null,
160
+ deletes.length ? this._query({
161
+ sql: 'DELETE FROM `store` WHERE `key` IN (?) AND BINARY `key` IN (?);',
162
+ values: [deletes, deletes],
163
+ }) : null,
164
+ ]);
165
+ }
166
+ async close() {
167
+ await util_1.default.promisify(this._pool.end.bind(this._pool))();
168
+ }
169
+ };
170
+ exports.Database = Database;
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ /**
3
+ * 2011 Peter 'Pita' Martischka
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS-IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.Database = void 0;
22
+ const AbstractDatabase_1 = __importDefault(require("../lib/AbstractDatabase"));
23
+ const async_1 = __importDefault(require("async"));
24
+ const pg_1 = __importDefault(require("pg"));
25
+ const Database = class extends AbstractDatabase_1.default {
26
+ db;
27
+ upsertStatement;
28
+ constructor(settings) {
29
+ super();
30
+ if (typeof settings === 'string')
31
+ settings = { connectionString: settings };
32
+ this.settings = settings;
33
+ this.settings.cache = settings.cache || 1000;
34
+ this.settings.writeInterval = 100;
35
+ this.settings.json = true;
36
+ // Pool specific defaults
37
+ this.settings.max = this.settings.max || 20;
38
+ this.settings.min = this.settings.min || 4;
39
+ this.settings.idleTimeoutMillis = this.settings.idleTimeoutMillis || 1000;
40
+ // @ts-ignore
41
+ this.db = new pg_1.default.Pool(this.settings);
42
+ }
43
+ init(callback) {
44
+ const testTableExists = "SELECT 1 as exists FROM pg_tables WHERE tablename = 'store'";
45
+ const createTable = 'CREATE TABLE IF NOT EXISTS store (' +
46
+ '"key" character varying(100) NOT NULL, ' +
47
+ '"value" text NOT NULL, ' +
48
+ 'CONSTRAINT store_pkey PRIMARY KEY (key))';
49
+ // this variable will be given a value depending on the result of the
50
+ // feature detection
51
+ this.upsertStatement = null;
52
+ /*
53
+ * - Detects if this Postgres version supports INSERT .. ON CONFLICT
54
+ * UPDATE (PostgreSQL >= 9.5 and CockroachDB)
55
+ * - If upsert is not supported natively, creates in the DB a pl/pgsql
56
+ * function that emulates it
57
+ * - Performs a side effect, setting this.upsertStatement to the sql
58
+ * statement that needs to be used, based on the detection result
59
+ * - calls the callback
60
+ */
61
+ const detectUpsertMethod = (callback) => {
62
+ const upsertViaFunction = 'SELECT ueberdb_insert_or_update($1,$2)';
63
+ const upsertNatively = 'INSERT INTO store(key, value) VALUES ($1, $2) ' +
64
+ 'ON CONFLICT (key) DO UPDATE SET value = excluded.value';
65
+ const createFunc = 'CREATE OR REPLACE FUNCTION ueberdb_insert_or_update(character varying, text) ' +
66
+ 'RETURNS void AS $$ ' +
67
+ 'BEGIN ' +
68
+ ' IF EXISTS( SELECT * FROM store WHERE key = $1 ) THEN ' +
69
+ ' UPDATE store SET value = $2 WHERE key = $1; ' +
70
+ ' ELSE ' +
71
+ ' INSERT INTO store(key,value) VALUES( $1, $2 ); ' +
72
+ ' END IF; ' +
73
+ ' RETURN; ' +
74
+ 'END; ' +
75
+ '$$ LANGUAGE plpgsql;';
76
+ const testNativeUpsert = `EXPLAIN ${upsertNatively}`;
77
+ this.db.query(testNativeUpsert, ['test-key', 'test-value'], (err) => {
78
+ if (err) {
79
+ // the UPSERT statement failed: we will have to emulate it via
80
+ // an sql function
81
+ this.upsertStatement = upsertViaFunction;
82
+ // actually create the emulation function
83
+ this.db.query(createFunc, [], callback);
84
+ return;
85
+ }
86
+ // if we get here, the EXPLAIN UPSERT succeeded, and we can use a
87
+ // native UPSERT
88
+ this.upsertStatement = upsertNatively;
89
+ callback();
90
+ });
91
+ };
92
+ this.db.query(testTableExists, (err, result) => {
93
+ if (err != null)
94
+ return callback(err);
95
+ if (result.rows.length === 0) {
96
+ this.db.query(createTable, (err) => {
97
+ if (err != null)
98
+ return callback(err);
99
+ // @ts-ignore
100
+ detectUpsertMethod(callback);
101
+ });
102
+ }
103
+ else {
104
+ // @ts-ignore
105
+ detectUpsertMethod(callback);
106
+ }
107
+ });
108
+ }
109
+ get(key, callback) {
110
+ this.db.query('SELECT value FROM store WHERE key=$1', [key], (err, results) => {
111
+ let value = null;
112
+ if (!err && results.rows.length === 1) {
113
+ value = results.rows[0].value;
114
+ }
115
+ callback(err, value);
116
+ });
117
+ }
118
+ findKeys(key, notKey, callback) {
119
+ let query = 'SELECT key FROM store WHERE key LIKE $1';
120
+ const params = [];
121
+ // desired keys are %key:%, e.g. pad:%
122
+ key = key.replace(/\*/g, '%');
123
+ params.push(key);
124
+ if (notKey != null) {
125
+ // not desired keys are notKey:%, e.g. %:%:%
126
+ notKey = notKey.replace(/\*/g, '%');
127
+ query += ' AND key NOT LIKE $2';
128
+ params.push(notKey);
129
+ }
130
+ this.db.query(query, params, (err, results) => {
131
+ const value = [];
132
+ if (!err && results.rows.length > 0) {
133
+ results.rows.forEach((val) => {
134
+ value.push(val.key);
135
+ });
136
+ }
137
+ callback(err, value);
138
+ });
139
+ }
140
+ set(key, value, callback) {
141
+ if (key.length > 100) {
142
+ const val = '';
143
+ callback(Error('Your Key can only be 100 chars'), val);
144
+ }
145
+ else if (this.upsertStatement != null) {
146
+ this.db.query(this.upsertStatement, [key, value], callback);
147
+ }
148
+ }
149
+ remove(key, callback) {
150
+ this.db.query('DELETE FROM store WHERE key=$1', [key], callback);
151
+ }
152
+ doBulk(bulk, callback) {
153
+ const replaceVALs = [];
154
+ let removeSQL = 'DELETE FROM store WHERE key IN (';
155
+ const removeVALs = [];
156
+ let removeCount = 0;
157
+ for (const i in bulk) {
158
+ if (bulk[i].type === 'set') {
159
+ replaceVALs.push([bulk[i].key, bulk[i].value]);
160
+ }
161
+ else if (bulk[i].type === 'remove') {
162
+ if (removeCount !== 0)
163
+ removeSQL += ',';
164
+ removeCount += 1;
165
+ removeSQL += `$${removeCount}`;
166
+ removeVALs.push(bulk[i].key);
167
+ }
168
+ }
169
+ removeSQL += ');';
170
+ if (!this.upsertStatement) {
171
+ return;
172
+ }
173
+ // @ts-ignore
174
+ const functions = replaceVALs.map((v) => (cb) => this.db.query(this.upsertStatement, v, cb));
175
+ const removeFunction = (callback) => {
176
+ // @ts-ignore
177
+ if (!(removeVALs.length) > 1) {
178
+ this.db.query(removeSQL, removeVALs, callback);
179
+ }
180
+ else {
181
+ callback();
182
+ }
183
+ };
184
+ functions.push(removeFunction);
185
+ // @ts-ignore
186
+ async_1.default.parallel(functions, callback);
187
+ }
188
+ close(callback) {
189
+ this.db.end(callback);
190
+ }
191
+ };
192
+ exports.Database = Database;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Database = void 0;
4
+ const postgres = require('./postgres_db');
5
+ const Database = class PostgresDB extends postgres.Database {
6
+ constructor(settings) {
7
+ console.warn('ueberdb: The postgrespool database driver is deprecated ' +
8
+ 'and will be removed in a future version. Use postgres instead.');
9
+ super(settings);
10
+ }
11
+ };
12
+ exports.Database = Database;
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ /**
3
+ * 2011 Peter 'Pita' Martischka
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS-IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.Database = void 0;
22
+ const AbstractDatabase_1 = __importDefault(require("../lib/AbstractDatabase"));
23
+ const redis_1 = require("redis");
24
+ const Database = class RedisDB extends AbstractDatabase_1.default {
25
+ _client;
26
+ constructor(settings) {
27
+ super();
28
+ this._client = null;
29
+ this.settings = settings || {};
30
+ }
31
+ get isAsync() { return true; }
32
+ async init() {
33
+ this._client = (0, redis_1.createClient)({ url: this.settings.url });
34
+ if (this._client) {
35
+ await this._client.connect();
36
+ await this._client.ping();
37
+ }
38
+ }
39
+ async get(key) {
40
+ if (this._client == null)
41
+ return null;
42
+ return await this._client.get(key);
43
+ }
44
+ async findKeys(key, notKey) {
45
+ if (this._client == null)
46
+ return null;
47
+ const [type] = /^([^:*]+):\*$/.exec(key) || [];
48
+ if (type != null && ['*:*:*', `${key}:*`].includes(notKey)) {
49
+ // Performance optimization for a common Etherpad case.
50
+ return await this._client.sMembers(`ueberDB:keys:${type}`);
51
+ }
52
+ let keys = await this._client.keys(key.replace(/[?[\]\\]/g, '\\$&'));
53
+ if (notKey != null) {
54
+ const regex = this.createFindRegex(key, notKey);
55
+ keys = keys.filter((k) => regex.test(k));
56
+ }
57
+ return keys;
58
+ }
59
+ async set(key, value) {
60
+ if (this._client == null)
61
+ return null;
62
+ const matches = /^([^:]+):([^:]+)$/.exec(key);
63
+ await Promise.all([
64
+ matches && this._client.sAdd(`ueberDB:keys:${matches[1]}`, matches[0]),
65
+ this._client.set(key, value),
66
+ ]);
67
+ }
68
+ async remove(key) {
69
+ if (this._client == null)
70
+ return null;
71
+ const matches = /^([^:]+):([^:]+)$/.exec(key);
72
+ await Promise.all([
73
+ matches && this._client.sRem(`ueberDB:keys:${matches[1]}`, matches[0]),
74
+ this._client.del(key),
75
+ ]);
76
+ }
77
+ async doBulk(bulk) {
78
+ if (this._client == null)
79
+ return null;
80
+ const multi = this._client.multi();
81
+ for (const { key, type, value } of bulk) {
82
+ const matches = /^([^:]+):([^:]+)$/.exec(key);
83
+ if (type === 'set') {
84
+ if (matches) {
85
+ multi.sAdd(`ueberDB:keys:${matches[1]}`, matches[0]);
86
+ }
87
+ multi.set(key, value);
88
+ }
89
+ else if (type === 'remove') {
90
+ if (matches) {
91
+ multi.sRem(`ueberDB:keys:${matches[1]}`, matches[0]);
92
+ }
93
+ multi.del(key);
94
+ }
95
+ }
96
+ await multi.exec();
97
+ }
98
+ async close() {
99
+ if (this._client == null)
100
+ return null;
101
+ await this._client.quit();
102
+ this._client = null;
103
+ }
104
+ };
105
+ exports.Database = Database;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ /**
3
+ * 2016 Remi Arnaud
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS-IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.Database = void 0;
22
+ const AbstractDatabase_1 = __importDefault(require("../lib/AbstractDatabase"));
23
+ const rethinkdb_1 = __importDefault(require("rethinkdb"));
24
+ const async_1 = __importDefault(require("async"));
25
+ const Database = class extends AbstractDatabase_1.default {
26
+ host;
27
+ db;
28
+ port;
29
+ table;
30
+ connection;
31
+ constructor(settings) {
32
+ super();
33
+ if (!settings)
34
+ settings = {};
35
+ if (!settings.host) {
36
+ settings.host = 'localhost';
37
+ }
38
+ if (!settings.port) {
39
+ settings.port = 28015;
40
+ }
41
+ if (!settings.db) {
42
+ settings.db = 'test';
43
+ }
44
+ if (!settings.table) {
45
+ settings.table = 'test';
46
+ }
47
+ this.host = settings.host;
48
+ this.db = settings.db;
49
+ this.port = settings.port;
50
+ this.table = settings.table;
51
+ this.connection = null;
52
+ }
53
+ init(callback) {
54
+ // @ts-ignore
55
+ rethinkdb_1.default.connect(this, (err, conn) => {
56
+ if (err)
57
+ throw err;
58
+ this.connection = conn;
59
+ rethinkdb_1.default.table(this.table).run(this.connection, (err, cursor) => {
60
+ if (err) {
61
+ // assuming table does not exists
62
+ // @ts-ignore
63
+ rethinkdb_1.default.tableCreate(this.table).run(this.connection, callback);
64
+ }
65
+ else if (callback) {
66
+ callback(null, cursor);
67
+ }
68
+ });
69
+ });
70
+ }
71
+ get(key, callback) {
72
+ // @ts-ignore
73
+ rethinkdb_1.default.table(this.table).get(key).run(this.connection, (err, item) => {
74
+ // @ts-ignore
75
+ callback(err, (item ? item.content : item));
76
+ });
77
+ }
78
+ findKeys(key, notKey, callback) {
79
+ const keys = [];
80
+ const regex = this.createFindRegex(key, notKey);
81
+ // @ts-ignore
82
+ rethinkdb_1.default.filter((item) => {
83
+ if (item.id.search(regex) !== -1) {
84
+ keys.push(item.id);
85
+ }
86
+ }).run(this.connection, callback);
87
+ }
88
+ set(key, value, callback) {
89
+ rethinkdb_1.default.table(this.table)
90
+ .insert({ id: key, content: value }, { conflict: 'replace' })
91
+ .run(this.connection, callback);
92
+ }
93
+ doBulk(bulk, callback) {
94
+ const _in = [];
95
+ const _out = [];
96
+ for (const i in bulk) {
97
+ if (bulk[i].type === 'set') {
98
+ _in.push({ id: bulk[i].key, content: bulk[i].value });
99
+ }
100
+ else if (bulk[i].type === 'remove') {
101
+ _out.push(bulk[i].key);
102
+ }
103
+ }
104
+ async_1.default.parallel([
105
+ (cb) => {
106
+ rethinkdb_1.default.table(this.table).insert(_in, { conflict: 'replace' }).run(this.connection, cb);
107
+ },
108
+ (cb) => {
109
+ rethinkdb_1.default.table(this.table).getAll(_out).delete().run(this.connection, cb);
110
+ },
111
+ ], callback);
112
+ }
113
+ remove(key, callback) {
114
+ // @ts-ignore
115
+ rethinkdb_1.default.table(this.table).get(key).delete().run(this.connection, callback);
116
+ }
117
+ close(callback) {
118
+ if (this.connection) {
119
+ this.connection.close(callback);
120
+ }
121
+ }
122
+ };
123
+ exports.Database = Database;