-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapsql.js
359 lines (263 loc) · 10 KB
/
wrapsql.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
const mysql = require('mysql')
class Wrapsql {
/**
* Constructor accepts either pre-built mySql connection or config object.
* @param {object} sql Pre-built mySql connection or config object.
* @param {bool} debug Toggle debug mode which prints all queries to console.
*/
constructor(sql,debug=false){
this.debug = debug
if ( sql.hasOwnProperty('config') ){
this.sql = sql
} else {
this.sql = mysql.createConnection({
host: sql.host,
port: sql.port,
user: sql.user,
password: sql.password,
database: sql.database
})
}
}
/**
* Returns details about db connection. Useful for determining if the conneciton was successful before running queries.
*/
connect(){
return new Promise( ( resolve, reject ) => {
this.sql.connect( ( err, suc ) => {
if ( err )
return reject( err )
resolve( suc )
} )
} )
}
/**
* Select all results from table.
* @param {string} table Name of table
*/
async selectAll(table){
return this.runQuery(`SELECT * FROM ${table}`)
}
/**
* Select data from a table.
* @param {string} table Table to select from.
* @param {array or string(*)} columns Accepts either an array of columns to return or '*' to return all columns.
* @param {object} where Object of where conditions.
* @param {string} orderBy Column you would like to order by.
* @param {string} order Order of results ('ASC','DESC').
* @param {int} limit Number of results to return.
* @param {int} offset Number of rows to offset before return results.
*/
async select(table,columns,where,orderBy=false,order='ASC',limit=false,offset=false,groupBy=false){
let query = `SELECT `
if ( Array.isArray(columns) ){
columns.forEach(column => {
query += `${column},`
})
query = query.substring(0, query.length - 1)
} else {
query += ` * FROM ${table} `
}
query += this.addOptions(where,orderBy,order,limit,offset,groupBy)
return this.runQuery(query)
}
/**
* Insert data into a table.
* @param {string} table Table name.
* @param {object/array} insert Insert values. Insert multiple rows be submitting an array of insert values.
*/
async insert(table,insert){
let query = `INSERT INTO ${table} (`
if( Array.isArray(insert) ){
for (let property in insert[0]) {
query += `${property}, `
}
query = query.substring(0, query.length - 2)
query += `) VALUES `
insert.forEach(insertValues => {
query += `(`
for (let property in insertValues) {
query += `${this.formatString(insertValues[property])}, `
}
query = query.substring(0, query.length - 2)
query += `),`
})
query = query.substring(0, query.length - 1)
} else {
for (let property in insert) {
query += `${property}, `
}
query = query.substring(0, query.length - 2)
query += `) VALUES (`
for (let property in insert) {
query += `${this.formatString(insert[property])}, `
}
query = query.substring(0, query.length - 2)
query += `) `
}
return this.runQuery(query)
}
/**
* Update values in table.
* @param {string} table Table Name.
* @param {object} set Update values.
* @param {object} where Object of where conditions.
*/
async update(table,set,where=false){
let query = `UPDATE ${table} SET `
for (let property in set) {
query += `${property} = ${this.formatString(set[property])}, `
}
query = query.substring(0, query.length - 2)
query += this.addOptions(where)
return this.runQuery(query)
}
/**
* Delete records from table.
* @param {string} table Table name.
* @param {object} where Values conditions to determine which rows to delete.
*/
async delete(table,where){
let query = `DELETE FROM ${table} ` + this.addOptions(where)
return this.runQuery(query)
}
/**
* Count rows in table.
* @param {string} table Table name.
* @param {object} where Values conditions to determine which rows to delete.
* @param {string} as Label for the result
*/
async count(table,where=false,as='count'){
let query = `SELECT COUNT(*) AS ${as} FROM ${table} ${this.addOptions(where)}`
return this.runQuery(query)
}
/**
* Truncate table.
* @param {string} table Table name.
* @param {object} where Values conditions to determine which rows to delete.
* @param {string} as Label for the result
*/
async truncate(table){
let query = `TRUNCATE TABLE ${table}`
return this.runQuery(query)
}
/**
* Run a SQL query.
* @param {string} query SQL Query
*/
async query(query){
return this.runQuery(query)
}
/**
* Pass through to run SQL queries directly.
* @param {string} query MySQL query string.
*/
async runQuery(query){
if (this.debug) console.log(query)
return new Promise( ( resolve, reject ) => {
this.sql.query(query, [], ( err, rows ) => {
if ( err ) return reject( err )
resolve( rows )
} )
} )
}
/**
* Execute an array of SQL queries where if there is an error or exception all are rolled back.
* @param {array} queryArray Array of sql query strings.
*/
async transaction(queryArray){
return new Promise(async (resolve,reject) => {
try {
let queryResults = []
this.sql.beginTransaction((transactionError) => {
if (transactionError !== null) {
reject(transactionError);
}
for (const query of queryArray) {
if (this.debug) console.log(query)
this.sql.query(query, [], ( queryErr, rows ) => {
if (queryErr !== null) {
try {
this.sql.rollback((err) => {
reject(err);
});
} catch (rollbackError) {
reject(rollbackError);
}
}
queryResults.push(rows)
})
}
this.sql.commit((commitError) => {
if (commitError !== null) {
reject(commitError);
}
resolve(queryResults);
})
})
} catch (error) {
reject(error);
}
})
}
/**
* Adds options to end of SQL string.
* @param {bool,obj,array} where Can either be an object which defaults to "AND" comparison type of an array of formant ["comparisonType",{{row:value},{row:value}}]
* @param {string} orderBy Column you would like to order by.
* @param {string} order Order of results ('ASC','DESC').
* @param {int} limit Number of results to return.
* @param {int} offset Number of rows to offset before return results.
* @param {string} groupBy Value to group results by.
*/
addOptions(where=false,orderBy=false,order='DESC',limit=false,offset=false,groupBy=false){
let query = ""
let comparisonType = "AND"
if ( where ) {
if ( typeof where === "string" ){
query += ` WHERE ${where}`
} else {
query += ` WHERE `
if ( Array.isArray(where) ){
comparisonType = where[0].toUpperCase()
where = where[1]
}
if ( comparisonType === "AND" || comparisonType === "OR" ) {
for (let property in where) {
let operator = "="
let value = where[property]
if ( Array.isArray(value) ){
operator = value[0]
value = value[1]
}
query += `${property} ${operator} ${this.formatString(value)} ${comparisonType} `
}
query = query.substring(0, query.length - (comparisonType.length+1))
}
if ( comparisonType === "IN" ) {
for (let property in where) {
let formattedArray = []
where[property].forEach(entry => {
formattedArray.push(this.formatString(entry))
});
formattedArray = formattedArray.join(",")
query += `${property} IN (${formattedArray}) `
}
}
}
}
query += (groupBy) ? ` GROUP BY ${groupBy}` : ''
query += (orderBy) ? ` ORDER BY ${orderBy} ${order}` : ''
query += (limit) ? ` LIMIT ${limit}` : ''
query += (offset) ? ` OFFSET ${offset}` : ''
return query
}
/**
* Escapes "'" character form string if value is not an integer.
* @param {string} value
* @returns
*/
formatString(value){
return (Number.isInteger(value))?value:(`'`+value.replace(/'/g,`''`)+`'`)
}
}
module.exports = Wrapsql