Skip to content

Commit effffba

Browse files
committed
simplify output function
1 parent b90e06d commit effffba

File tree

5 files changed

+116
-70
lines changed

5 files changed

+116
-70
lines changed

lib/expressions/boolean.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
const booleanExpressions = new Object();
22

3-
const funcData = [
3+
const fnData = [
44
{ name: 'eq', sign: '='},
55
{ name: 'lt', sign: '<' },
66
{ name: 'gt', sign: '>' },
77
{ name: 'leq', sign: '<=' },
88
{ name: 'geq', sign: '>=' }
99
];
1010

11-
funcData.forEach(expr => {
11+
fnData.forEach(expr => {
1212
booleanExpressions[expr.name] = (lhs, rhs) => new Object({ lhs, operator: expr.sign, rhs });
1313
});
1414

lib/expressions/numeric.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
const numericExpressions = new Object();
22

3-
[ 'max', 'min', 'count', 'avg', 'sum' ].forEach(func => {
4-
numericExpressions[func] = options => `${func.toUpperCase()}(${options.all ? '*' : options})`;
3+
[ 'max', 'min', 'count', 'avg', 'sum' ].forEach(fn => {
4+
numericExpressions[fn] = options => `${fn.toUpperCase()}(${options.all ? '*' : options})`;
55
});
66

77
module.exports = numericExpressions;

lib/queries.js

Lines changed: 86 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,33 @@
11
const { PromiseDB } = require('./promisedb');
22
const { accessError, asyncError } = require('../util/psql-error');
3+
const { simplifyArray, simplifyObject } = require('../util/helpers');
34
const str = require('../util/string');
45
const sp = require('synchronized-promise');
56

67
// Current database (undefined if not open)
78
var db = undefined;
9+
var simplify = false;
810

911
/**
1012
* Opens a database file.
1113
* @param {string} file Relative path to the database file
14+
* @returns {void|never}
1215
*/
1316
function open(file) {
17+
if (db instanceof PromiseDB) {
18+
close();
19+
accessError(true);
20+
}
21+
1422
db = new PromiseDB(file);
1523
}
1624

1725
/**
1826
* Closes an open database.
27+
* @returns {void|never}
1928
*/
2029
function close() {
21-
db.close();
30+
db instanceof PromiseDB ? db.close() : accessError();
2231
db = undefined;
2332
}
2433

@@ -55,72 +64,72 @@ function dynamicAccess(file) {
5564

5665
/* ================ QUERIES ================ */
5766

58-
/**
59-
* Asynchronous database query.
60-
* @param {RunOptions} options SQL statement
61-
* @returns {QueryPromise}
62-
*/
63-
async function run(options) {
64-
dynamicAccess(options.file);
65-
return await db.query(options.statement, options.args);
66-
}
67+
class Query {
68+
/**
69+
* Query constructor - handles dynamic database access
70+
* @param {BaseOptions} options
71+
*/
72+
constructor(options) {
73+
this.options = options;
74+
dynamicAccess(options.file);
75+
}
6776

68-
/**
69-
* Asynchronous instert query.
70-
* @param {InsertOptions} options
71-
* @returns {Promise<void>}
72-
*/
73-
async function insert(options) {
74-
dynamicAccess(options.file);
75-
const sql = str.insertStr(options);
76-
await db.query(sql, options.values);
77-
}
77+
/**
78+
* Asynchronous database query.
79+
* @returns {QueryPromise}
80+
*/
81+
async run() {
82+
return await db.query(this.options.statement, this.options.args);
83+
}
7884

79-
/**
80-
* Asynchronous selection query.
81-
* @param {SelectionOptions} options
82-
* @returns {SelectionPromise}
83-
*/
84-
async function select(options) {
85-
dynamicAccess(options.file);
86-
const { sql, args } = str.selectStr(options);
87-
const data = await db.query(sql, args);
88-
return (data.length > 0 && options.first) ? data[0] : data;
89-
}
85+
/**
86+
* Asynchronous instert query.
87+
* @returns {Promise<void>}
88+
*/
89+
async insert() {
90+
const sql = str.insertStr(this.options);
91+
await db.query(sql, this.options.values);
92+
}
9093

91-
/**
92-
* Asynchronous update query.
93-
* @param {UpdateOptions} options
94-
* @returns {Promise<void>}
95-
*/
96-
async function update(options) {
97-
dynamicAccess(options.file);
98-
const { sql, args } = str.updateStr(options);
99-
await db.query(sql, args);
100-
}
94+
/**
95+
* Asynchronous selection query.
96+
* @returns {SelectionPromise}
97+
*/
98+
async select() {
99+
const { sql, args } = str.selectStr(this.options);
100+
const data = await db.query(sql, args);
101+
return (data.length > 0 && this.options.first) ? data[0] : data;
102+
}
101103

102-
/**
103-
* Asynchronous delete query.
104-
* @param {DeleteOptions} options
105-
* @returns {Promise<void>}
106-
*/
107-
async function remove(options) {
108-
dynamicAccess(options.file);
109-
const { sql, args } = str.deleteStr(options);
110-
await db.query(sql, args);
111-
}
104+
/**
105+
* Asynchronous update query.
106+
* @returns {Promise<void>}
107+
*/
108+
async update() {
109+
const { sql, args } = str.updateStr(this.options);
110+
await db.query(sql, args);
111+
}
112112

113-
/**
114-
* Asynchronous upsert query.
115-
* @param {UpsertOptions} options
116-
* @returns {Promise<void>}
117-
*/
118-
async function upsert(options) {
119-
await insert(options).catch(async error => {
120-
if (error.code !== 'SQLITE_CONSTRAINT') throw new error;
121-
if (!options.table) options.table = options.into;
122-
await update(options);
123-
});
113+
/**
114+
* Asynchronous delete query.
115+
* @returns {Promise<void>}
116+
*/
117+
async remove() {
118+
const { sql, args } = str.deleteStr(this.options);
119+
await db.query(sql, args);
120+
}
121+
122+
/**
123+
* Asynchronous upsert query.
124+
* @returns {Promise<void>}
125+
*/
126+
async upsert() {
127+
await this.insert(this.options).catch(async error => {
128+
if (error.code !== 'SQLITE_CONSTRAINT') throw new error;
129+
if (!this.options.table) this.options.table = this.options.into;
130+
await this.update(this.options);
131+
});
132+
}
124133
}
125134

126135
/**
@@ -134,17 +143,30 @@ function sync(query, options = []) {
134143
return sp(query)(options);
135144
}
136145

146+
const queryNames = Object.getOwnPropertyNames(Query.prototype).filter(name => name !== 'constructor'), queries = new Object();
147+
148+
queryNames.forEach(name => {
149+
queries[name] = async options => {
150+
const query = new Query(options);
151+
const run = query[name]();
152+
if (simplify) run.then(data => Array.isArray(data) ? simplifyArray(data) : simplifyObject(data));
153+
return await run;
154+
}
155+
});
156+
137157
module.exports = {
158+
simplifyOutput: (bit = undefined) => typeof bit === 'boolean' ? simplify = bit : simplify = !simplify,
159+
138160
// Export database open/close functions (synchronous!)
139161
open, close, get,
140162

141163
// Queries
142-
run, insert, select, update, remove, upsert, sync,
164+
...queries, sync,
143165

144166
/**
145167
* Asynchronous delete query. Optional overload, since 'delete' is reserved keyword.
146168
* @param {DeleteOptions} options
147169
* @returns {Promise<void>}
148170
*/
149-
delete: async options => await remove(options)
171+
delete: async options => await queries.remove(options)
150172
}

util/helpers.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,28 @@
1+
/**
2+
*
3+
* @param {Object} data
4+
*/
5+
function simplifyObject(datum) {
6+
for (const key of Object.keys(datum)) {
7+
if (!key.includes('(') || !key.includes(')')) continue;
8+
const newKey = key.substring(0, key.indexOf('(')).toLowerCase();
9+
Object.assign(datum, { [newKey]: datum[key] });
10+
delete datum[key];
11+
}
12+
}
13+
14+
/**
15+
*
16+
* @param {Object[]} data
17+
*/
18+
function simplifyArray(data) {
19+
if (!data) return;
20+
data.forEach(datum => simplifyObject(datum));
21+
}
22+
123
module.exports = {
24+
simplifyArray, simplifyObject,
25+
226
/**
327
* Parses the columns of an SQL statement.
428
* @param {string[]} columns

util/psql-error.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ module.exports = {
1111
/**
1212
* Access error - database is not open!
1313
*/
14-
accessError: function() {
15-
throw new PSQLError('PSQLAccessError', 'Database is not open.');
14+
accessError: function(open = false) {
15+
throw new PSQLError('PSQLAccessError', open ? 'Database is already open.' : 'Database is not open.');
1616
},
1717

1818
/**

0 commit comments

Comments
 (0)