ueberdb2 4.1.1 → 4.1.3

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 (44) hide show
  1. package/package.json +5 -3
  2. package/.eslintignore +0 -2
  3. package/.eslintrc.cjs +0 -66
  4. package/.github/dependabot.yml +0 -11
  5. package/.github/workflows/npmpublish.yml +0 -134
  6. package/.travis.yml +0 -46
  7. package/CHANGELOG.md +0 -304
  8. package/CONTRIBUTING.md +0 -103
  9. package/SECURITY.md +0 -5
  10. package/databases/cassandra_db.ts +0 -265
  11. package/databases/couch_db.ts +0 -189
  12. package/databases/dirty_db.ts +0 -85
  13. package/databases/dirty_git_db.ts +0 -82
  14. package/databases/elasticsearch_db.ts +0 -257
  15. package/databases/memory_db.ts +0 -41
  16. package/databases/mock_db.ts +0 -43
  17. package/databases/mongodb_db.ts +0 -142
  18. package/databases/mssql_db.ts +0 -226
  19. package/databases/mysql_db.ts +0 -183
  20. package/databases/postgres_db.ts +0 -213
  21. package/databases/postgrespool_db.ts +0 -11
  22. package/databases/redis_db.ts +0 -129
  23. package/databases/rethink_db.ts +0 -114
  24. package/databases/sqlite_db.ts +0 -159
  25. package/docker-compose.yml +0 -44
  26. package/index.ts +0 -224
  27. package/lib/AbstractDatabase.ts +0 -79
  28. package/lib/CacheAndBufferLayer.ts +0 -665
  29. package/lib/logging.ts +0 -33
  30. package/test/lib/databases.ts +0 -73
  31. package/test/lib/mysql.sql +0 -84
  32. package/test/test.ts +0 -328
  33. package/test/test_bulk.ts +0 -69
  34. package/test/test_elasticsearch.ts +0 -128
  35. package/test/test_findKeys.ts +0 -41
  36. package/test/test_flush.ts +0 -55
  37. package/test/test_getSub.ts +0 -28
  38. package/test/test_lru.ts +0 -151
  39. package/test/test_memory.ts +0 -32
  40. package/test/test_metrics.ts +0 -734
  41. package/test/test_mysql.ts +0 -62
  42. package/test/test_postgres.ts +0 -16
  43. package/test/test_setSub.ts +0 -19
  44. package/test/test_tojson.ts +0 -34
@@ -1,257 +0,0 @@
1
- /**
2
- * 2015 Visionist, Inc.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS-IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- import AbstractDatabase, {Settings} from '../lib/AbstractDatabase';
18
- import {equal, strict} from 'assert';
19
-
20
- import {Buffer} from 'buffer';
21
- import {createHash} from 'crypto';
22
- import {Client} from 'elasticsearch7';
23
- import {BulkObject} from './cassandra_db';
24
-
25
- const schema = '2';
26
-
27
- const keyToId = (key:string) => {
28
- const keyBuf = Buffer.from(key);
29
- return keyBuf.length > 512 ? createHash('sha512').update(keyBuf).digest('hex') : key;
30
- };
31
-
32
- const mappings = {
33
- // _id is expected to equal key, unless the UTF-8 encoded key is > 512 bytes, in which case it is
34
- // the hex-encoded sha512 hash of the UTF-8 encoded key.
35
- properties: {
36
- key: {type: 'wildcard'}, // For findKeys, and because _id is limited to 512 bytes.
37
- value: {type: 'object', enabled: false}, // Values should be opaque to Elasticsearch.
38
- },
39
- };
40
-
41
- const migrateToSchema2 = async (client: any, v1BaseIndex: string | undefined, v2Index: string, logger: any) => {
42
- let recordsMigratedLastLogged = 0;
43
- let recordsMigrated = 0;
44
- const totals = new Map();
45
- logger.info('Attempting elasticsearch record migration from schema v1 at base index ' +
46
- `${v1BaseIndex} to schema v2 at index ${v2Index}...`);
47
- const {body: indices} = await client.indices.get({index: [v1BaseIndex, `${v1BaseIndex}-*-*`]});
48
- const scrollIds = new Map();
49
- const q = [];
50
- try {
51
- for (const index of Object.keys(indices)) {
52
- const {body: res} = await client.search({index, scroll: '10m'});
53
- scrollIds.set(index, res._scroll_id);
54
- q.push({index, res});
55
- }
56
- while (q.length) {
57
- const {index, res: {hits: {hits, total: {value: total}}}}:any = q.shift();
58
- if (hits.length === 0) continue;
59
- totals.set(index, total);
60
- const body = [];
61
- for (const {_id, _type, _source: {val}} of hits) {
62
- let key = `${_type}:${_id}`;
63
- if (v1BaseIndex && index !== v1BaseIndex) {
64
- const parts = index.slice(v1BaseIndex.length + 1).split('-');
65
- if (parts.length !== 2) {
66
- throw new Error(`unable to migrate records from index ${index} due to data ambiguity`);
67
- }
68
- key = `${parts[0]}:${decodeURIComponent(_type)}:${parts[1]}:${_id}`;
69
- }
70
- body.push({index: {_id: keyToId(key)}}, {key, value: JSON.parse(val)});
71
- }
72
- await client.bulk({index: v2Index, body});
73
- recordsMigrated += hits.length;
74
- if (Math.floor(recordsMigrated / 100) > Math.floor(recordsMigratedLastLogged / 100)) {
75
- // @ts-ignore
76
- const total = [...totals.values()].reduce((a, b) => a + b, 0);
77
- logger.info(`Migrated ${recordsMigrated} records out of ${total}`);
78
- recordsMigratedLastLogged = recordsMigrated;
79
- }
80
- q.push(
81
- {index, res: (await client.scroll({scroll: '5m', scrollId: scrollIds.get(index)})).body});
82
- }
83
- logger.info(`Finished migrating ${recordsMigrated} records`);
84
- } finally {
85
- // @ts-ignore
86
- await Promise.all([...scrollIds.values()].map((scrollId) => client.clearScroll({scrollId})));
87
- }
88
- };
89
-
90
- export const Database = class extends AbstractDatabase {
91
- private _client: any;
92
- private readonly _index: any;
93
- private _indexClean: boolean;
94
- private readonly _q: {index: any};
95
- constructor(settings:Settings) {
96
- super();
97
- this._client = null;
98
- this.settings = {
99
- host: '127.0.0.1',
100
- port: '9200',
101
- base_index: 'ueberes',
102
- migrate_to_newer_schema: false,
103
- // for a list of valid API values see:
104
- // https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/configuration.html#config-options
105
- api: '7.6',
106
- ...settings || {},
107
- json: false, // Elasticsearch will do the JSON conversion as necessary.
108
- };
109
- this._index = `${this.settings.base_index}_s${schema}`;
110
- this._q = {index: this._index};
111
- this._indexClean = true;
112
- }
113
-
114
- get isAsync() { return true; }
115
-
116
- async _refreshIndex() {
117
- if (this._indexClean) return;
118
- this._indexClean = true;
119
- await this._client.indices.refresh(this._q);
120
- }
121
-
122
- /**
123
- * Initialize the elasticsearch client, then ping the server to ensure that a
124
- * connection was made.
125
- */
126
- async init() {
127
- // create elasticsearch client
128
- const client = new Client({
129
- node: `http://${this.settings.host}:${this.settings.port}`,
130
- });
131
- await client.ping();
132
- if (!(await client.indices.exists({index: this._index})).body) {
133
- let tmpIndex;
134
- // @ts-ignore
135
- const {body: migrate} = await client.indices.exists({index: this.settings.base_index});
136
- if (migrate && !this.settings.migrate_to_newer_schema) {
137
- throw new Error(
138
- `Data exists under the legacy index (schema) named ${this.settings.base_index}. ` +
139
- 'Set migrate_to_newer_schema to true to copy the existing data to a new index ' +
140
- `named ${this._index}.`);
141
- }
142
- let attempt = 0;
143
- while (true) {
144
- tmpIndex = `${this._index}_${migrate ? 'migrate_attempt_' : 'i'}${attempt++}`;
145
- if (!(await client.indices.exists({index: tmpIndex})).body) break;
146
- }
147
- await client.indices.create({index: tmpIndex, body: {mappings}});
148
- if (migrate) await migrateToSchema2(client, this.settings.base_index, tmpIndex, this.logger);
149
- await client.indices.putAlias({index: tmpIndex, name: this._index});
150
- }
151
- const indices = Object.values((await client.indices.get({index: this._index})).body);
152
- equal(indices.length, 1);
153
- try {
154
- // @ts-ignore
155
- assert.deepEqual(indices[0].mappings, mappings);
156
- } catch (err) {
157
- this.logger.warn(`Index ${this._index} mappings does not match expected; ` +
158
- `attempting to use index anyway. Details: ${err}`);
159
- }
160
- this._client = client;
161
- }
162
-
163
- /**
164
- * This function provides read functionality to the database.
165
- *
166
- * @param {String} key Key
167
- */
168
- async get(key:string) {
169
- const {body} = await this._client.get({...this._q, id: keyToId(key)}, {ignore: [404]});
170
- if (!body.found) return null;
171
- return body._source.value;
172
- }
173
-
174
- /**
175
- * @param key Search key, which uses an asterisk (*) as the wild card.
176
- * @param notKey Used to filter the result set
177
- */
178
- async findKeys(key:string, notKey:string) {
179
- await this._refreshIndex();
180
- const q = {
181
- ...this._q,
182
- body: {
183
- query: {
184
- bool: {
185
- filter: {wildcard: {key: {value: key}}},
186
- ...notKey == null ? {} : {
187
- must_not: {wildcard: {key: {value: notKey}}},
188
- },
189
- },
190
- },
191
- },
192
- };
193
- const {body: {hits: {hits}}} = await this._client.search(q);
194
- return hits.map((h:{_source:{key:string}}) => h._source.key);
195
- }
196
-
197
- /**
198
- * This function provides write functionality to the database.
199
- *
200
- * @param {String} key Record identifier.
201
- * @param {JSON|String} value The value to store in the database.
202
- */
203
- async set(key: string, value:string) {
204
- this._indexClean = false;
205
- await this._client.index({...this._q, id: keyToId(key), body: {key, value}});
206
- }
207
-
208
- /**
209
- * This function provides delete functionality to the database.
210
- *
211
- * The index, type, and ID will be parsed from the key, and this document will
212
- * be deleted from the database.
213
- *
214
- * @param {String} key Record identifier.
215
- */
216
- async remove(key:string) {
217
- this._indexClean = false;
218
- await this._client.delete({...this._q, id: keyToId(key)}, {ignore: [404]});
219
- }
220
-
221
- /**
222
- * This uses the bulk upload functionality of elasticsearch (url:port/_bulk).
223
- *
224
- * The CacheAndBufferLayer will periodically (every this.settings.writeInterval)
225
- * flush writes that have already been done in the local cache out to the database.
226
- *
227
- * @param {Array} bulk An array of JSON data in the format:
228
- * {"type":type, "key":key, "value":value}
229
- */
230
- async doBulk(bulk: BulkObject[]) {
231
- // bulk is an array of JSON:
232
- // example: [{"type":"set", "key":"sessionstorage:{id}", "value":{"cookie":{...}}]
233
-
234
- const operations = [];
235
-
236
- for (const {type, key, value} of bulk) {
237
- this._indexClean = false;
238
- switch (type) {
239
- case 'set':
240
- operations.push({index: {_id: keyToId(key)}});
241
- operations.push({key, value});
242
- break;
243
- case 'remove':
244
- operations.push({delete: {_id: keyToId(key)}});
245
- break;
246
- default:
247
- continue;
248
- }
249
- }
250
- await this._client.bulk({...this._q, body: operations});
251
- }
252
-
253
- async close() {
254
- if (this._client != null) this._client.close();
255
- this._client = null;
256
- }
257
- };
@@ -1,41 +0,0 @@
1
- import AbstractDatabase, {Settings} from '../lib/AbstractDatabase';
2
-
3
-
4
- export const Database = class MemoryDB extends AbstractDatabase {
5
- private _data: any;
6
- constructor(settings:Settings) {
7
- super();
8
- this.settings = settings;
9
- settings.json = false;
10
- settings.cache = 0;
11
- settings.writeInterval = 0;
12
- this._data = null;
13
- }
14
-
15
- get isAsync() { return true; }
16
-
17
- close() {
18
- this._data = null;
19
- }
20
-
21
- findKeys(key:string, notKey:string) {
22
- const regex = this.createFindRegex(key, notKey);
23
- return [...this._data.keys()].filter((k) => regex.test(k));
24
- }
25
-
26
- get(key:string) {
27
- return this._data.get(key);
28
- }
29
-
30
- init() {
31
- this._data = this.settings.data || new Map();
32
- }
33
-
34
- remove(key:string) {
35
- this._data.delete(key);
36
- }
37
-
38
- set(key:string, value:string) {
39
- this._data.set(key, value);
40
- }
41
- };
@@ -1,43 +0,0 @@
1
- import {Settings} from '../lib/AbstractDatabase';
2
-
3
- import events from 'events';
4
-
5
- export const Database = class extends events.EventEmitter {
6
- private settings: Settings;
7
- constructor(settings:Settings) {
8
- super();
9
- this.settings = {
10
- writeInterval: 1,
11
- ...settings,
12
- };
13
- settings.mock = this;
14
- }
15
-
16
- close(cb: ()=>{}) {
17
- this.emit('close', cb);
18
- }
19
-
20
- doBulk(ops:string, cb: ()=>{}) {
21
- this.emit('doBulk', ops, cb);
22
- }
23
-
24
- findKeys(key:string, notKey:string, cb:()=>{}) {
25
- this.emit('findKeys', key, notKey, cb);
26
- }
27
-
28
- get(key:string, cb:()=>{}) {
29
- this.emit('get', key, cb);
30
- }
31
-
32
- init(cb:()=>{}) {
33
- this.emit('init', cb);
34
- }
35
-
36
- remove(key:string, cb:()=>{}) {
37
- this.emit('remove', key, cb);
38
- }
39
-
40
- set(key:string, value:string, cb:()=>{}) {
41
- this.emit('set', key, value, cb);
42
- }
43
- };
@@ -1,142 +0,0 @@
1
- /**
2
- * 2020 Sylchauf
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS-IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- import AbstractDatabase, {Settings} from '../lib/AbstractDatabase';
18
- import {Func} from 'mocha';
19
- import {BulkObject} from './cassandra_db';
20
-
21
- exports.Database = class extends AbstractDatabase {
22
- private interval: any;
23
- private database: any;
24
- private client: any;
25
- private collection: any;
26
- constructor(settings:Settings) {
27
- super();
28
- this.settings = settings;
29
-
30
- if (!this.settings.url) throw new Error('You must specify a mongodb url');
31
- // For backwards compatibility:
32
- if (this.settings.database == null) this.settings.database = this.settings.dbName;
33
-
34
- if (!this.settings.collection) this.settings.collection = 'ueberdb';
35
- }
36
-
37
- clearPing() {
38
- if (this.interval) {
39
- clearInterval(this.interval);
40
- }
41
- }
42
-
43
- schedulePing() {
44
- this.clearPing();
45
- this.interval = setInterval(() => {
46
- this.database.command({
47
- ping: 1,
48
- });
49
- }, 10000);
50
- }
51
-
52
- init(callback:Function) {
53
- const MongoClient = require('mongodb').MongoClient;
54
-
55
- MongoClient.connect(this.settings.url, (err:any, client:any) => {
56
- if (!err) {
57
- this.client = client;
58
- this.database = client.db(this.settings.database);
59
- this.collection = this.database.collection(this.settings.collection);
60
- }
61
-
62
- callback(err);
63
- });
64
-
65
- this.schedulePing();
66
- }
67
-
68
- get(key:string, callback:Function) {
69
- this.collection.findOne({_id: key}, (err:any, document:any) => {
70
- if (err) callback(err);
71
- else callback(null, document ? document.value : null);
72
- });
73
-
74
- this.schedulePing();
75
- }
76
-
77
- findKeys(key:string, notKey:string, callback:Function) {
78
- const selector = {
79
- $and: [
80
- {_id: {$regex: `${key.replace(/\*/g, '')}`}},
81
- ],
82
- };
83
-
84
- if (notKey) {
85
- // @ts-ignore
86
- selector.$and.push({_id: {$not: {$regex: `${notKey.replace(/\*/g, '')}`}}});
87
- }
88
-
89
- this.collection.find(selector, async (err:any, res:any) => {
90
- if (err) {
91
- callback(err);
92
- } else {
93
- const data = await res.toArray();
94
-
95
- callback(null, data.map((i:any) => i._id));
96
- }
97
- });
98
-
99
- this.schedulePing();
100
- }
101
-
102
- set(key:string, value:string, callback:Function) {
103
- if (key.length > 100) {
104
- callback('Your Key can only be 100 chars');
105
- } else {
106
- this.collection.update({_id: key}, {$set: {value}}, {upsert: true}, callback);
107
- }
108
-
109
- this.schedulePing();
110
- }
111
-
112
- remove(key:string, callback:Function) {
113
- this.collection.remove({_id: key}, callback);
114
-
115
- this.schedulePing();
116
- }
117
-
118
- doBulk(bulk:BulkObject[], callback:Function) {
119
- const bulkMongo = this.collection.initializeOrderedBulkOp();
120
-
121
- for (const i in bulk) {
122
- if (bulk[i].type === 'set') {
123
- bulkMongo.find({_id: bulk[i].key}).upsert().updateOne({$set: {value: bulk[i].value}});
124
- } else if (bulk[i].type === 'remove') {
125
- bulkMongo.find({_id: bulk[i].key}).deleteOne();
126
- }
127
- }
128
-
129
- bulkMongo.execute().then((res:any) => {
130
- callback(null, res);
131
- }).catch((error:any) => {
132
- callback(error);
133
- });
134
-
135
- this.schedulePing();
136
- }
137
-
138
- close(callback:any) {
139
- this.clearPing();
140
- this.client.close(callback);
141
- }
142
- };
@@ -1,226 +0,0 @@
1
- /* eslint new-cap: ["error", {"capIsNewExceptions": ["mssql.NVarChar"]}] */
2
-
3
- /**
4
- * 2019 - exspecto@gmail.com
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS-IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- *
18
- *
19
- * Note: This requires MS SQL Server >= 2008 due to the usage of the MERGE statement
20
- *
21
- */
22
-
23
- import AbstractDatabase, {Settings} from '../lib/AbstractDatabase';
24
- import async from 'async';
25
- import mssql, {ConnectionPool} from 'mssql';
26
- import {BulkObject} from './cassandra_db';
27
-
28
- type RowResult = {
29
- key: string;
30
- };
31
-
32
-
33
- export const Database = class MSSQL extends AbstractDatabase {
34
- private db: ConnectionPool | undefined;
35
- constructor(settings:Settings) {
36
- super();
37
- settings = settings || {};
38
-
39
- if (settings.json != null) {
40
- settings.parseJSON = settings.json;
41
- }
42
-
43
- // set the request timeout to 5 minutes
44
- settings.requestTimeout = 300000;
45
-
46
- settings.server = settings.host;
47
- this.settings = settings;
48
-
49
- /*
50
- Turning off the cache and write buffer here. You
51
- can reenable it, but also take a look at maxInserts in
52
- the doBulk function to decide how you want to split it up.
53
- */
54
- this.settings.cache = 0;
55
- this.settings.writeInterval = 0;
56
- }
57
-
58
- init(callback:(err: any)=>{}) {
59
- const sqlCreate =
60
- "IF OBJECT_ID(N'dbo.store', N'U') IS NULL" +
61
- ' BEGIN' +
62
- ' CREATE TABLE [store] (' +
63
- ' [key] NVARCHAR(100) PRIMARY KEY,' +
64
- ' [value] NTEXT NOT NULL' +
65
- ' );' +
66
- ' END';
67
-
68
- // @ts-ignore
69
- new mssql.ConnectionPool(this.settings).connect().then((pool) => {
70
- this.db = pool;
71
-
72
- const request = new mssql.Request(this.db);
73
-
74
- request.query(sqlCreate, (err) => {
75
- callback(err);
76
- });
77
-
78
- this.db.on('error', (err) => {
79
- console.log(err);
80
- });
81
- });
82
- }
83
-
84
- get(key:string, callback:(err?:Error, value?:string)=>{}) {
85
- const request = new mssql.Request(this.db);
86
-
87
- request.input('key', mssql.NVarChar(100), key);
88
-
89
- request.query('SELECT [value] FROM [store] WHERE [key] = @key', (err, results) => {
90
- let value = null;
91
-
92
- if (!err && results && results.rowsAffected[0] === 1) {
93
- // @ts-ignore
94
- value = results.recordset[0].value;
95
- }
96
-
97
- callback(err, value);
98
- });
99
- }
100
-
101
- findKeys(key:string, notKey:string, callback:(err: Error | undefined, value:string[])=>{}) {
102
- const request = new mssql.Request(this.db);
103
- let query = 'SELECT [key] FROM [store] WHERE [key] LIKE @key';
104
-
105
- // desired keys are key, e.g. pad:%
106
- key = key.replace(/\*/g, '%');
107
-
108
- request.input('key', mssql.NVarChar(100), key);
109
-
110
- if (notKey != null) {
111
- // not desired keys are notKey, e.g. %:%:%
112
- notKey = notKey.replace(/\*/g, '%');
113
- request.input('notkey', mssql.NVarChar(100), notKey);
114
- query += ' AND [key] NOT LIKE @notkey';
115
- }
116
-
117
- request.query(query, (err, results) => {
118
- const value:string[] = [];
119
-
120
- if (!err && results && results.rowsAffected[0] > 0) {
121
- for (let i = 0; i < results.recordset.length; i++) {
122
- value.push((results.recordset[i] as RowResult).key);
123
- }
124
- }
125
-
126
- callback(err, value);
127
- });
128
- }
129
-
130
- set(key:string, value:string, callback: (val:string)=>{}) {
131
- const request = new mssql.Request(this.db);
132
-
133
- if (key.length > 100) {
134
- callback('Your Key can only be 100 chars');
135
- } else {
136
- const query =
137
- 'MERGE [store] t USING (SELECT @key [key], @value [value]) s' +
138
- ' ON t.[key] = s.[key]' +
139
- ' WHEN MATCHED AND s.[value] IS NOT NULL THEN UPDATE SET t.[value] = s.[value]' +
140
- ' WHEN NOT MATCHED THEN INSERT ([key], [value]) VALUES (s.[key], s.[value]);';
141
-
142
- request.input('key', mssql.NVarChar(100), key);
143
- request.input('value', mssql.NText, value);
144
-
145
- request.query(query, (err, info) => {
146
- callback(err ? err.toString() : '');
147
- });
148
- }
149
- }
150
-
151
- remove(key:string, callback:()=>{}) {
152
- const request = new mssql.Request(this.db);
153
- request.input('key', mssql.NVarChar(100), key);
154
- request.query('DELETE FROM [store] WHERE [key] = @key', callback);
155
- }
156
-
157
- doBulk(bulk: BulkObject[], callback:(err:any, results?: any)=>{}) {
158
- const maxInserts = 100;
159
- const request = new mssql.Request(this.db);
160
- let firstReplace = true;
161
- let firstRemove = true;
162
- const replacements: string[] = [];
163
- let removeSQL = 'DELETE FROM [store] WHERE [key] IN (';
164
-
165
- for (const i in bulk) {
166
- if (bulk[i].type === 'set') {
167
- if (firstReplace) {
168
- replacements.push('BEGIN TRANSACTION;');
169
- firstReplace = false;
170
- } else if (Number(i) % maxInserts === 0) {
171
- replacements.push('\nCOMMIT TRANSACTION;\nBEGIN TRANSACTION;\n');
172
- }
173
-
174
- replacements.push(
175
- `MERGE [store] t USING (SELECT '${bulk[i].key}' [key], '${bulk[i].value}' [value]) s`,
176
- 'ON t.[key] = s.[key]',
177
- 'WHEN MATCHED AND s.[value] IS NOT NULL THEN UPDATE SET t.[value] = s.[value]',
178
- 'WHEN NOT MATCHED THEN INSERT ([key], [value]) VALUES (s.[key], s.[value]);');
179
- } else if (bulk[i].type === 'remove') {
180
- if (!firstRemove) {
181
- removeSQL += ',';
182
- }
183
-
184
- firstRemove = false;
185
- removeSQL += `'${bulk[i].key}'`;
186
- }
187
- }
188
-
189
- removeSQL += ');';
190
- replacements.push('COMMIT TRANSACTION;');
191
-
192
- async.parallel(
193
- [
194
- (callback) => {
195
- if (!firstReplace) {
196
- request.batch(replacements.join('\n'), (err, results) => {
197
- if (err) {
198
- callback(err);
199
- }
200
- callback(err, results);
201
- });
202
- } else {
203
- callback();
204
- }
205
- },
206
- (callback) => {
207
- if (!firstRemove) {
208
- request.query(removeSQL, callback);
209
- } else {
210
- callback();
211
- }
212
- },
213
- ],
214
- (err, results) => {
215
- if (err) {
216
- callback(err);
217
- }
218
- callback(err, results);
219
- },
220
- );
221
- }
222
-
223
- close(callback: (err?:Error)=>{}) {
224
- this.db && this.db.close(callback);
225
- }
226
- };