Skip to content

Commit df1af07

Browse files
authored
Merge pull request #43 from Pchelolo/dep_updates
Update dependencies and adapt to version 3 connection pool
2 parents cfd62af + 016cf4e commit df1af07

File tree

6 files changed

+73
-78
lines changed

6 files changed

+73
-78
lines changed

index.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ class RBSQLite {
7979
}
8080
const domain = req.params.domain;
8181
return this.store.get(domain, req.body)
82-
.then((res) => ({
82+
.then(res => ({
8383
status: res.items.length ? 200 : 404,
8484
body: res
8585
}))
@@ -146,7 +146,7 @@ class RBSQLite {
146146
getTableSchema(rb, req) {
147147
const domain = req.params.domain;
148148
return this.store.getTableSchema(domain, req.params.table)
149-
.then((res) => ({
149+
.then(res => ({
150150
status: 200,
151151
body: res.schema
152152
}))
@@ -173,7 +173,7 @@ class RBSQLite {
173173
// deleted
174174
status: 204
175175
})
176-
.catch((e) => ({
176+
.catch(e => ({
177177
status: 500,
178178
body: {
179179
type: 'delete_error',
@@ -208,7 +208,7 @@ class RBSQLite {
208208

209209
/**
210210
* Factory
211-
* @param options
211+
* @param {Object} options
212212
* @return {Promise<registration>} with registration being the registration
213213
* object
214214
*/

lib/SchemaMigrator.js

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ class Attributes {
5050
const currSet = new Set(Object.keys(this.current));
5151
const propSet = new Set(Object.keys(this.proposed));
5252

53-
this.addColumns = Array.from(propSet).filter((x) => !currSet.has(x));
53+
this.addColumns = Array.from(propSet).filter(x => !currSet.has(x));
5454
// TODO: null-out deleted columns
5555
// We can't delete the column in SQLite, but we would remove it from * projection
56-
this.delColumns = Array.from(currSet).filter((x) => !propSet.has(x));
56+
this.delColumns = Array.from(currSet).filter(x => !propSet.has(x));
5757
}
5858

5959
_colType(col) {
@@ -62,7 +62,7 @@ class Attributes {
6262

6363
_alterTableAdd(col) {
6464
const colIndex = this.newSchema.index
65-
&& this.newSchema.index.find((index) => index.attribute === col);
65+
&& this.newSchema.index.find(index => index.attribute === col);
6666
if (colIndex && colIndex.type === 'static') {
6767
if (!dbu.staticTableExist(this.oldSchema)) {
6868
return dbu.buildStaticsTableSql(this.newSchema, this.table);
@@ -99,7 +99,7 @@ class Attributes {
9999

100100
Attributes.prototype.validate = () => {};
101101

102-
Attributes.prototype._alterTable = (fullTableName) => `ALTER TABLE [${fullTableName}]`;
102+
Attributes.prototype._alterTable = fullTableName => `ALTER TABLE [${fullTableName}]`;
103103

104104
/**
105105
* Index definition migrations
@@ -111,8 +111,8 @@ class Index {
111111
this.currentSchema = parentMigrator.current;
112112
this.proposedSchema = parentMigrator.proposed;
113113

114-
this.addIndex = proposed.filter((x) => !this._hasSameIndex(this.current, x));
115-
this.delIndex = current.filter((x) => !this._hasSameIndex(this.proposed, x));
114+
this.addIndex = proposed.filter(x => !this._hasSameIndex(this.current, x));
115+
this.delIndex = current.filter(x => !this._hasSameIndex(this.proposed, x));
116116

117117
this.alteredColumns = [];
118118

@@ -136,8 +136,8 @@ class Index {
136136
}
137137

138138
validate() {
139-
if (this.addIndex.some((index) => index.type !== 'static')
140-
|| this.delIndex.some((index) => index.type !== 'static')) {
139+
if (this.addIndex.some(index => index.type !== 'static')
140+
|| this.delIndex.some(index => index.type !== 'static')) {
141141
throw new Error('Only static index additions and removals supported');
142142
}
143143
if (this.alteredColumns.length > 0) {
@@ -147,7 +147,7 @@ class Index {
147147
}
148148

149149
Index.prototype._hasSameIndex = (indexes, proposedIndex) =>
150-
indexes.some((idx) => idx.attribute === proposedIndex.attribute
150+
indexes.some(idx => idx.attribute === proposedIndex.attribute
151151
&& idx.type === proposedIndex.type
152152
&& idx.order === proposedIndex.order);
153153

@@ -212,7 +212,7 @@ class SchemaMigrator {
212212
this.proposed = proposed;
213213

214214
this.migrators = Object.keys(migrationHandlers)
215-
.map((key) => new migrationHandlers[key](this, current[key], proposed[key]));
215+
.map(key => new migrationHandlers[key](this, current[key], proposed[key]));
216216

217217
this._validate();
218218
}
@@ -225,11 +225,10 @@ class SchemaMigrator {
225225

226226
/**
227227
* Perform any required migration tasks.
228-
*
229-
* @return a promise that resolves when the migration tasks are complete
228+
* @return {Promise} a promise that resolves when the migration tasks are complete
230229
*/
231230
migrate() {
232-
return P.each(this.migrators, (migrator) => migrator.migrate());
231+
return P.each(this.migrators, migrator => migrator.migrate());
233232
}
234233
}
235234

lib/clientWrapper.js

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
const P = require('bluebird');
44
const sqlite3 = require('sqlite3').verbose();
5-
const poolModule = require('generic-pool');
5+
const genericPool = require('generic-pool');
66

77
P.promisifyAll(sqlite3, { suffix: '_p' });
88

@@ -20,29 +20,28 @@ class Wrapper {
2020
this.retryLimit = options.conf.retry_limit || 5;
2121
this.randomDelay = () => Math.ceil(Math.random() * delay);
2222

23-
this.connectionPool = new poolModule.Pool({
24-
name: 'sqlite',
25-
create(callback) {
26-
const client = new sqlite3.Database(expandDBName(options));
27-
callback(null, client);
23+
this.connectionPool = genericPool.createPool({
24+
create() {
25+
return P.resolve(new sqlite3.Database(expandDBName(options)));
2826
},
2927
destroy(client) {
30-
client.close();
31-
},
28+
return P.try(() => client.close());
29+
}
30+
},
31+
{
3232
max: 1,
3333
idleTimeoutMillis: options.conf.pool_idle_timeout || 10000,
34-
log: options.log
34+
log: options.log,
35+
Promise: P
3536
});
36-
P.promisifyAll(this.connectionPool, { suffix: '_p' });
3737
this.readerConnection = new sqlite3.Database(expandDBName(options));
3838
}
3939

4040
/**
4141
* Run a set of queries within a transaction.
42-
*
43-
* @param queries an array of query objects, containing sql field with SQL
42+
* @param {Array} queries an array of query objects, containing sql field with SQL
4443
* and params array with query parameters.
45-
* @returns {*} operation promise
44+
* @return {Promise} operation promise
4645
*/
4746
run(queries) {
4847
let retryCount = 0;
@@ -53,7 +52,7 @@ class Wrapper {
5352
}
5453

5554
return client.run_p('begin immediate')
56-
.then(() => client)
55+
.thenReturn(client)
5756
.catch((err) => {
5857
if (err && err.cause
5958
&& err.cause.code === 'SQLITE_BUSY'
@@ -67,10 +66,10 @@ class Wrapper {
6766
});
6867
};
6968

70-
return this.connectionPool.acquire_p()
69+
return this.connectionPool.acquire()
7170
.then(beginTransaction)
7271
.then((client) => {
73-
queries = queries.filter((query) => query && query.sql);
72+
queries = queries.filter(query => query && query.sql);
7473
return P.each(queries, (query) => {
7574
if (this.conf.show_sql) {
7675
this.log(query.sql);
@@ -83,27 +82,22 @@ class Wrapper {
8382
this.log('rollback');
8483
}
8584
return client.run_p('rollback')
86-
.finally(() => {
87-
this.connectionPool.release(client);
88-
throw err;
89-
});
85+
.finally(() => this.connectionPool.release(client))
86+
.thenThrow(err);
9087
});
9188
})
9289
.then((client) => {
9390
this.log('commit');
9491
return client.run_p('commit')
95-
.finally(() => {
96-
this.connectionPool.release(client);
97-
});
92+
.finally(() => this.connectionPool.release(client));
9893
});
9994
}
10095

10196
/**
10297
* Run read query and return a result promise
103-
*
104-
* @param query SQL query to execute
105-
* @param params query parameters
106-
* @returns {*} query result promise
98+
* @param {Object} query SQL query to execute
99+
* @param {Object} params query parameters
100+
* @return {Promise} query result promise
107101
*/
108102
all(query, params) {
109103
let retryCount = 0;

lib/db.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ class DB {
100100
}
101101
createOperation = migrator.migrate()
102102
.then(() => {
103-
this.queryCache.keys().filter((key) => key.indexOf(tableName) === 0)
103+
this.queryCache.keys().filter(key => key.indexOf(tableName) === 0)
104104
.forEach((key) => {
105105
this.queryCache.del(key);
106106
});
@@ -152,7 +152,7 @@ class DB {
152152

153153
if (!this.schemaCache[tableName]) {
154154
return this._getSchema(tableName)
155-
.then((schema) => deleteRequest(schema));
155+
.then(schema => deleteRequest(schema));
156156
} else {
157157
const schema = this.schemaCache[tableName];
158158
delete this.schemaCache[tableName];
@@ -204,7 +204,7 @@ class DB {
204204
options = options || {};
205205
validator.validateGetRequest(req, schema);
206206
const buildResult = this._createGetQuery(tableName, req,
207-
schema, options.includePreparedForDelete);
207+
schema, options.includePreparedForDelete);
208208
return this.client.all(buildResult.sql, buildResult.params)
209209
.then((result) => {
210210
if (!result) {

lib/dbutils.js

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -156,10 +156,10 @@ function generateConverters(schema) {
156156
const objType = setType ? setType[1] : schema.attributes[key];
157157
const objConverter = dbu.conversions[objType] || {};
158158
if (!objConverter.write) {
159-
objConverter.write = (val) => val;
159+
objConverter.write = val => val;
160160
}
161161
if (!objConverter.read) {
162-
objConverter.read = (val) => val;
162+
objConverter.read = val => val;
163163
}
164164
if (!objConverter.type) {
165165
objConverter.type = objType;
@@ -189,7 +189,7 @@ dbu.HTTPError = HTTPError;
189189

190190
function getAllKeysOfTypes(schema, types) {
191191
return Object.keys(schema.iKeyMap)
192-
.filter((key) => schema.iKeyMap[key]
192+
.filter(key => schema.iKeyMap[key]
193193
&& types.indexOf(schema.iKeyMap[key].type) >= 0);
194194
}
195195

@@ -198,9 +198,9 @@ dbu.hashKey = function hashKey(key) {
198198
.update(key)
199199
.digest()
200200
.toString('base64')
201-
// Replace [+/] from base64 with _ (illegal in Cassandra)
201+
// Replace [+/] from base64 with _ (illegal in Cassandra)
202202
.replace(/[+/]/g, '_')
203-
// Remove base64 padding, has no entropy
203+
// Remove base64 padding, has no entropy
204204
.replace(/=+$/, '');
205205
};
206206

@@ -276,7 +276,7 @@ function constructProj(query, schema) {
276276
function isStaticJoinNeeded(query, schema) {
277277
if (query && query.proj) {
278278
if (Array.isArray(query.proj)) {
279-
return query.proj.some((key) => schema.iKeyMap[key]
279+
return query.proj.some(key => schema.iKeyMap[key]
280280
&& schema.iKeyMap[key].type === 'static');
281281
} else if (query.proj.constructor === String) {
282282
return schema.iKeyMap[query.proj] && schema.iKeyMap[query.proj].type === 'static';
@@ -285,11 +285,11 @@ function isStaticJoinNeeded(query, schema) {
285285
+ `${query.proj} of type ${query.proj.constructor}`);
286286
}
287287
} else {
288-
return Object.keys(schema.iKeyMap).some((key) => schema.iKeyMap[key].type === 'static');
288+
return Object.keys(schema.iKeyMap).some(key => schema.iKeyMap[key].type === 'static');
289289
}
290290
}
291291

292-
dbu.staticTableExist = (schema) => isStaticJoinNeeded(null, schema);
292+
dbu.staticTableExist = schema => isStaticJoinNeeded(null, schema);
293293

294294
function constructLimit(query) {
295295
let sql = '';
@@ -451,11 +451,11 @@ function buildUpdateQuery(req, tableName, schema, dataKVMap, primaryKeyKVMap, ig
451451
let dataParams = [];
452452
const condition = buildCondition(Object.assign(primaryKeyKVMap, req.if), schema, true, true);
453453
let sql = `${ignore ? 'update or ignore ' : 'update '}[${tableName}_data] set `;
454-
sql += Object.keys(dataKVMap).filter((column) =>
455-
schema.iKeys.indexOf(column) < 0).map((column) => {
456-
dataParams.push(dataKVMap[column]);
457-
return `${dbu.fieldName(column)}= ?`;
458-
}).join(',');
454+
sql += Object.keys(dataKVMap).filter(column => schema.iKeys.indexOf(column) < 0)
455+
.map((column) => {
456+
dataParams.push(dataKVMap[column]);
457+
return `${dbu.fieldName(column)}= ?`;
458+
}).join(',');
459459
sql += ` where ${condition.query}`;
460460
dataParams = dataParams.concat(condition.params);
461461
return {
@@ -547,7 +547,7 @@ dbu.buildPutQuery = (req, tableName, schema, ignoreStatic) => {
547547
const staticSql = `insert or replace into [${tableName}_static] `
548548
+ `(${Object.keys(staticKVMap).map(dbu.fieldName).join(', ')}) `
549549
+ `values (${Object.keys(staticKVMap).map(() => '?').join(', ')})`;
550-
const staticData = Object.keys(staticKVMap).map((key) => staticKVMap[key]);
550+
const staticData = Object.keys(staticKVMap).map(key => staticKVMap[key]);
551551
queries.push({
552552
sql: staticSql,
553553
params: staticData
@@ -583,7 +583,7 @@ dbu.buildStaticsTableSql = (schema, tableName) => {
583583
}
584584
let sql = 'create table if not exists ';
585585
sql += `[${tableName}_static] (`;
586-
sql += hashKeys.concat(staticFields).map((key) =>
586+
sql += hashKeys.concat(staticFields).map(key =>
587587
`${dbu.fieldName(key)} ${schema.converters[schema.attributes[key]].type}`
588588
).join(', ');
589589
sql += `, primary key (${hashKeys.map(dbu.fieldName).join(', ')}), `;
@@ -596,8 +596,8 @@ dbu.buildTableSql = (schema, tableName) => {
596596
const indexKeys = getAllKeysOfTypes(schema, ['hash', 'range']);
597597
let sql = `create table if not exists [${tableName}_data] (`;
598598
sql += Object.keys(schema.attributes)
599-
.filter((attr) => !schema.iKeyMap[attr] || schema.iKeyMap[attr].type !== 'static')
600-
.map((attr) => `${dbu.fieldName(attr)} ${schema.converters[schema.attributes[attr]].type}`)
599+
.filter(attr => !schema.iKeyMap[attr] || schema.iKeyMap[attr].type !== 'static')
600+
.map(attr => `${dbu.fieldName(attr)} ${schema.converters[schema.attributes[attr]].type}`)
601601
.join(', ');
602602
sql += `, primary key (${indexKeys.map(dbu.fieldName).join(', ')}) )`;
603603
return sql;

0 commit comments

Comments
 (0)