-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
971 lines (844 loc) · 24.6 KB
/
index.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
var util = require('util');
var events = require('events');
var log;
var type;
var Class = require('./class.js');
var Promise = require('bluebird');
var internals = {};
var Base = Class.extend({
init: function(intern) {
this._escapeDDL = this._escapeDDL || '"';
this._escapeString = this._escapeString || "'";
internals = intern;
this.internals = intern;
log = this.internals.mod.log;
type = this.internals.mod.type;
this.eventEmmiter = new events.EventEmitter();
for (var n in events.EventEmitter.prototype) {
this[n] = events.EventEmitter.prototype[n];
}
},
close: function() {
throw new Error('not implemented');
},
_translateSpecialDefaultValues: function(
spec,
options,
tableName,
columnName
) {
spec.defaultValue.prep = null;
log.warn(
'special default value ' +
spec.defaultvalue.special +
' is not supported by your driver. Setting to no defaultvalue instead.'
);
},
_prepareSpec: function(columnName, spec, options, tableName) {
if (spec.defaultValue) {
if (spec.defaultValue.raw) {
spec.defaultValue.prep = spec.defaultValue.raw;
} else if (spec.defaultValue.special) {
this._translateSpecialDefaultValues(
spec,
options,
tableName,
columnName
);
}
}
},
mapDataType: function(str) {
switch (str) {
case type.STRING:
return 'VARCHAR';
case type.TEXT:
return 'TEXT';
case type.INTEGER:
return 'INTEGER';
case type.BIG_INTEGER:
return 'BIGINT';
case type.DATE_TIME:
return 'INTEGER';
case type.REAL:
return 'REAL';
case type.BLOB:
return 'BLOB';
case type.TIMESTAMP:
return 'TIMESTAMP';
case type.BINARY:
return 'BINARY';
case type.BOOLEAN:
return 'BOOLEAN';
case type.DECIMAL:
return 'DECIMAL';
case type.CHAR:
return 'CHAR';
case type.DATE:
return 'DATE';
case type.SMALLINT:
return 'SMALLINT';
default:
var unknownType = str.toUpperCase();
log.warn('Using unknown data type', unknownType);
return unknownType;
}
},
truncate: function(tableName, callback) {
return this.runSql(
'TRUNCATE ' + this._escapeDDL + tableName + this._escapeDDL
).nodeify(callback);
},
checkDBMS: function(dbms, callback) {
if (this.dbms === dbms) return Promise.resolve(dbms).nodeify(callback);
else return Promise.reject('dbms does not match');
},
createDatabase: function() {
throw new Error('not implemented');
},
showDatabase: function() {
throw new Error('not implemented');
},
switchDatabase: function() {
throw new Error('not implemented');
},
dropDatabase: function() {
throw new Error('not implemented');
},
recurseCallbackArray: function(foreignKeys, callback) {
var fkFunc;
var promises = [];
while ((fkFunc = foreignKeys.pop())) {
promises.push(Promise.resolve(fkFunc()));
}
return Promise.all(promises).nodeify(callback);
},
bindForeignKey: function(tableName, columnName, fkOptions) {
var self = this;
var mapping = {};
if (typeof fkOptions.mapping === 'string') {
mapping[columnName] = fkOptions.mapping;
} else mapping = fkOptions.mapping;
return function(callback) {
if (typeof callback === 'function') {
self.addForeignKey(
tableName,
fkOptions.table,
fkOptions.name,
mapping,
fkOptions.rules,
callback
);
} else {
return self.addForeignKey(
tableName,
fkOptions.table,
fkOptions.name,
mapping,
fkOptions.rules
);
}
};
},
createColumnDef: function(name, spec, options) {
name = this._escapeDDL + name + this._escapeDDL;
var type = this.mapDataType(spec.type);
var len = spec.length ? util.format('(%s)', spec.length) : '';
var constraint = this.createColumnConstraint(spec, options);
return {
foreignKey: null,
constraints: [name, type, len, constraint].join(' ')
};
},
_createList: function(table, opt = {}) {
var options = {
columns: {
id: {
type: type.INTEGER,
notNull: true,
primaryKey: true,
autoIncrement: true
},
name: { type: type.STRING, length: 255, notNull: true },
run_on: { type: type.DATE_TIME, notNull: true }
},
ifNotExists: true
};
return this.createTable(table, options);
},
_createKV: function(table, opt = { valueJson: false }) {
var options = {
columns: {
key: {
type: type.STRING,
notNull: true,
primaryKey: true,
unique: true
},
value: { type: type.TEXT, notNull: true },
run_on: { type: type.DATE_TIME, notNull: true }
},
ifNotExists: true
};
return this.createTable(table, options);
},
createMigrationsTable: function(callback) {
var options = {
columns: {
id: {
type: type.INTEGER,
notNull: true,
primaryKey: true,
autoIncrement: true
},
name: { type: type.STRING, length: 255, notNull: true },
run_on: { type: type.DATE_TIME, notNull: true }
},
ifNotExists: true
};
this.createTable(this.internals.migrationTable, options, callback);
},
createSeedsTable: function(callback) {
var options = {
columns: {
id: {
type: type.INTEGER,
notNull: true,
primaryKey: true,
autoIncrement: true
},
name: { type: type.STRING, length: 255, notNull: true },
run_on: { type: type.DATE_TIME, notNull: true }
},
ifNotExists: true
};
this.createTable(this.internals.seedTable, options, callback);
},
_handleMultiPrimaryKeys: function(primaryKeyColumns) {
return util.format(
', PRIMARY KEY (%s)',
this.quoteDDLArr(
primaryKeyColumns.map(function(value) {
return value.name;
})
).join(', ')
);
},
createTable: function(tableName, options, callback) {
log.verbose('creating table:', tableName);
var columnSpecs = options;
var opts = {};
if (options.columns !== undefined) {
columnSpecs = options.columns;
opts = options;
}
var ifNotExistsSql = '';
if (opts.ifNotExists) {
ifNotExistsSql = 'IF NOT EXISTS';
}
var primaryKeyColumns = [];
var columnDefOptions = {
emitPrimaryKey: false
};
for (var columnName in columnSpecs) {
var columnSpec = this.normalizeColumnSpec(columnSpecs[columnName]);
columnSpecs[columnName] = columnSpec;
if (columnSpec.primaryKey) {
primaryKeyColumns.push({ spec: columnSpec, name: columnName });
}
}
var pkSql = '';
if (primaryKeyColumns.length > 1) {
pkSql = this._handleMultiPrimaryKeys(primaryKeyColumns);
} else if (primaryKeyColumns.length === 1) {
primaryKeyColumns[0] = primaryKeyColumns[0].name;
columnDefOptions.emitPrimaryKey = true;
}
var columnDefs = [];
var callbacks = [];
var extensions = '';
var tableOptions = '';
for (var columnName in columnSpecs) {
var columnSpec = columnSpecs[columnName];
this._prepareSpec(columnName, columnSpec, columnDefOptions, tableName);
var constraint = this.createColumnDef(
columnName,
columnSpec,
columnDefOptions,
tableName
);
columnDefs.push(constraint.constraints);
// check foreignKey for backward compatiable
if (constraint.foreignKey) callbacks.push(constraint.foreignKey);
if (constraint.callbacks) {
// support multiple callbacks
callbacks = callbacks.concat(constraint.callbacks);
}
}
if (typeof this._applyExtensions === 'function') {
extensions = this._applyExtensions(options, tableName);
}
if (typeof this._applyTableOptions === 'function') {
tableOptions = this._applyTableOptions(options, tableName);
}
var sql = util.format(
'CREATE TABLE %s %s (%s%s%s) %s',
ifNotExistsSql,
this.escapeDDL(tableName),
columnDefs.join(', '),
extensions,
pkSql,
tableOptions
);
return this.runSql(sql)
.then(
function() {
if (this._dbmControl === true) this._counter.signal();
return this.recurseCallbackArray(callbacks);
}.bind(this)
)
.nodeify(callback);
},
dropTable: function(tableName, options, callback) {
if (arguments.length < 3 && typeof options === 'function') {
callback = options;
options = {};
} else {
options = options || {};
}
var ifExistsSql = '';
if (options.ifExists) {
ifExistsSql = 'IF EXISTS';
}
var sql = util.format(
'DROP TABLE %s %s',
ifExistsSql,
this.escapeDDL(tableName)
);
return this.runSql(sql).nodeify(callback);
},
renameTable: function(tableName, newTableName, callback) {
throw new Error('not implemented');
},
addColumn: function(tableName, columnName, columnSpec, callback) {
var columnSpec = this.normalizeColumnSpec(columnSpec);
this._prepareSpec(columnName, columnSpec, {}, tableName);
var def = this.createColumnDef(columnName, columnSpec, {}, tableName);
var extensions = '';
var self = this;
if (typeof this._applyAddColumnExtension === 'function') {
extensions = this._applyAddColumnExtension(def, tableName, columnName);
}
var sql = util.format(
'ALTER TABLE %s ADD COLUMN %s %s',
this.escapeDDL(tableName),
def.constraints,
extensions
);
return this.runSql(sql)
.then(function() {
if (this._dbmControl === true) this._counter.signal();
var callbacks = def.callbacks || [];
if (def.foreignKey) callbacks.push(def.foreignKey);
return self.recurseCallbackArray(callbacks);
})
.nodeify(callback);
},
removeColumn: function(tableName, columnName, callback) {
throw new Error('not implemented');
},
renameColumn: function(tableName, oldColumnName, newColumnName, callback) {
throw new Error('not implemented');
},
changeColumn: function(tableName, columnName, columnSpec, callback) {
throw new Error('not implemented');
},
quoteDDLArr: function(arr) {
for (var i = 0; i < arr.length; ++i) {
arr[i] = this._escapeDDL + arr[i] + this._escapeDDL;
}
return arr;
},
quoteArr: function(arr) {
for (var i = 0; i < arr.length; ++i) {
arr[i] = this._escapeString + arr[i] + this._escapeString;
}
return arr;
},
addIndex: function(tableName, indexName, columns, unique, callback) {
if (typeof unique === 'function') {
callback = unique;
unique = false;
}
if (!Array.isArray(columns)) {
columns = [columns];
}
var sql = util.format(
'CREATE %s INDEX "%s" ON "%s" (%s)',
unique ? 'UNIQUE' : '',
indexName,
tableName,
this.quoteDDLArr(columns).join(', ')
);
return this.runSql(sql).nodeify(callback);
},
insert: function(tableName, valueArray, callback) {
var columnNameArray = {};
if (arguments.length > 3 || Array.isArray(callback)) {
columnNameArray = valueArray;
valueArray = callback;
} else {
var names;
if (Array.isArray(valueArray)) {
names = Object.keys(valueArray[0]);
} else {
names = Object.keys(valueArray);
}
for (var i = 0; i < names.length; ++i) {
columnNameArray[names[i]] = names[i];
}
}
if (columnNameArray.length !== valueArray.length) {
return Promise.reject(
new Error('The number of columns does not match the number of values.')
).nodeify(callback);
}
var sql = util.format('INSERT INTO %s ', this.escapeDDL(tableName));
var columnNames = '(';
var values = 'VALUES ';
var values_part = [];
for (var index in columnNameArray) {
columnNames += this.escapeDDL(columnNameArray[index]);
if (Array.isArray(valueArray) && typeof valueArray[0] === 'object') {
for (var i = 0; i < valueArray.length; ++i) {
values_part[i] = values_part[i] || '';
if (typeof valueArray[i][index] === 'string') {
values_part[i] += this.escapeString(valueArray[i][index]);
} else {
values_part[i] += valueArray[i][index];
}
}
} else {
if (typeof valueArray[index] === 'string') {
values_part += this.escapeString(valueArray[index]);
} else {
values_part += valueArray[index];
}
values_part += ',';
}
columnNames += ',';
}
if (Array.isArray(valueArray) && typeof valueArray[0] === 'object') {
for (var i = 0; i < values_part.length; ++i) {
values += '(' + values_part[i].slice(0, -1) + '),';
}
values = values.slice(0, -1);
} else {
values += '(' + values_part.slice(0, -1) + ')';
}
sql += columnNames.slice(0, -1) + ') ' + values + ';';
return this.runSql(sql).nodeify(callback);
},
update: function(tableName, valueArray, ids, callback) {
var columnNameArray = {};
if (arguments.length > 4 && arguments[1].length !== arguments[2].length) {
return callback(
new Error('The number of columns does not match the number of values.')
);
} else if (arguments.length > 4) {
columnNameArray = valueArray;
valueArray = ids;
ids = callback;
callback = arguments[4];
} else {
var names;
if (Array.isArray(valueArray)) {
names = Object.keys(valueArray[0]);
} else {
names = Object.keys(valueArray);
}
for (var i = 0; i < names.length; ++i) {
columnNameArray[names[i]] = names[i];
}
}
var sql = util.format(
'UPDATE ' + this._escapeDDL + '%s' + this._escapeDDL + ' SET ',
tableName
);
for (var index in columnNameArray) {
sql += columnNameArray[index] + '=';
if (typeof valueArray[index] === 'string') {
sql +=
this._escapeString +
this.escape(valueArray[index]) +
this._escapeString;
} else {
sql += valueArray[index];
}
if (index != columnNameArray.length - 1) {
sql += ', ';
}
}
sql = sql.substring(0, sql.length - 2) + ' ' + this.buildWhereClause(ids);
return this.runSql(sql).nodeify(callback);
},
lookup: function(tableName, column, id, callback) {
var sql =
'SELECT ' +
this.escapeDDL(column) +
' FROM ' +
this.escapeDDL(tableName) +
' ' +
this.buildWhereClause(id);
return this.runSql(sql).then(function(row) {
return row[0];
});
},
removeIndex: function(tableName, indexName, callback) {
if (arguments.length === 2 && typeof indexName === 'function') {
callback = indexName;
indexName = tableName;
} else if (arguments.length === 1 && typeof tableName === 'string') {
indexName = tableName;
}
var sql = util.format('DROP INDEX "%s"', indexName);
return this.runSql(sql).nodeify(callback);
},
addForeignKey: function() {
throw new Error('not implemented');
},
removeForeignKey: function() {
throw new Error('not implemented');
},
normalizeColumnSpec: function(obj) {
if (typeof obj === 'string') {
return { type: obj };
} else {
return obj;
}
},
_insertEntry: function(table, name) {
return this.runSql(
'INSERT INTO ' +
this.escapeDDL(table) +
' (' +
this.escapeDDL('name') +
', ' +
this.escapeDDL('run_on') +
') VALUES (?, ?)',
[name, new Date()]
);
},
_insertKV: function(table, key, value) {
return this.runSql(
`INSERT INTO ${this.escapeDDL(table)}
(${this.escapeDDL('key')}, ${this.escapeDDL('value')}, ${this.escapeDDL(
'run_on'
)}) VALUES (?, ?, ?)`,
[key, value, new Date()]
);
},
_updateKV: function(table, key, value) {
return this.runSql(
`UPDATE ${this.escapeDDL(table)} SET ${this.escapeDDL('value')} = ?,
${this.escapeDDL('run_on')} = ?
WHERE ${this.escapeDDL('key')} = ?`,
[value, new Date(), key]
);
},
_updateKVC: function(table, key, value, c, v) {
return this.runSql(
`UPDATE ${this.escapeDDL(table)} SET ${this.escapeDDL('value')} = ?,
${this.escapeDDL('run_on')} = ?
WHERE ${this.escapeDDL('key')} = ? AND ${this.escapeDDL(c)} = ?`,
[value, new Date(), key, v]
);
},
addMigrationRecord: function(name, callback) {
this.runSql(
'INSERT INTO ' +
this.escapeDDL(this.internals.migrationTable) +
' (' +
this.escapeDDL('name') +
', ' +
this.escapeDDL('run_on') +
') VALUES (?, ?)',
[name, new Date()],
callback
);
},
addSeedRecord: function(name, callback) {
this.runSql(
'INSERT INTO ' +
this.escapeDDL(this.internals.seedTable) +
' (' +
this.escapeDDL('name') +
', ' +
this.escapeDDL('run_on') +
') VALUES (?, ?)',
[name, new Date()],
callback
);
},
startMigration: function(cb) {
return Promise.resolve().nodeify(cb);
},
endMigration: function(cb) {
return Promise.resolve().nodeify(cb);
},
// sql, params, callback
// sql, callback
runSql: function() {
throw new Error('not implemented');
},
_getList: function(table) {
var sql =
'SELECT * FROM ' +
this._escapeDDL +
table +
this._escapeDDL +
` ORDER BY ${this.escapeDDL('run_on')} DESC,
${this.escapeDDL('name')} DESC`;
return this.allAsync(sql);
},
_getKV: function(table, key) {
var sql =
'SELECT * FROM ' +
this._escapeDDL +
table +
this._escapeDDL +
` WHERE ${this.escapeDDL('key')} = ?`;
return this.allAsync(sql, [key]).then(([row]) => row);
},
/**
* Queries the migrations table
*
* @param callback
*/
allLoadedMigrations: function(callback) {
var sql =
'SELECT * FROM ' +
this._escapeDDL +
this.internals.migrationTable +
this._escapeDDL +
' ORDER BY run_on DESC, name DESC';
return this.all(sql, callback);
},
/**
* Queries the seeds table
*
* @param callback
*/
allLoadedSeeds: function(callback) {
var sql =
'SELECT * FROM ' +
this._escapeDDL +
this.internals.seedTable +
this._escapeDDL +
' ORDER BY run_on DESC, name DESC';
return this.all(sql, callback);
},
_deleteEntry: function(table, entry) {
var sql =
'DELETE FROM ' +
this._escapeDDL +
table +
this._escapeDDL +
' WHERE name = ?';
return this.runSql(sql, [entry]);
},
_deleteExpired: function(table, expiry) {
var sql =
'DELETE FROM ' +
this._escapeDDL +
table +
this._escapeDDL +
' WHERE run_on <= ?';
return this.runSql(sql, [expiry]);
},
_deleteKV: function(table, key) {
var sql =
'DELETE FROM ' +
this._escapeDDL +
table +
this._escapeDDL +
` WHERE ${this.escapeDDL('key')} = ?`;
return this.runSql(sql, [key]);
},
/**
* Deletes a migration
*
* @param migrationName - The name of the migration to be deleted
*/
deleteMigration: function(migrationName, callback) {
var sql =
'DELETE FROM ' +
this._escapeDDL +
this.internals.migrationTable +
this._escapeDDL +
' WHERE name = ?';
this.runSql(sql, [migrationName], callback);
},
/**
* Removes the specified keys from the database
*
* @param table - The table in which the to be deleted values are located
* @param ids - array or object
* id array - arrayof the to be deleted ids
* id object - { table: "name of the table to resolve the ids from",
* column: [
* {
* name: "name of column", //defaults to id if unset
* operator: ">", //defaults to = if unset
* searchValue: "12",
* searchValue: { table: "source", column: [...] },
* //recursion with objects possible
* link: "AND" //defaults to AND if unset
* }
* ]
* }
*
* @return Promise(runSql)
*/
remove: function(table, ids, callback) {
var sql = 'DELETE FROM ' + this._escapeDDL + table + +this._escapeDDL;
// var searchClause = '';
return this.runSql(sql + this.buildWhereClause(ids)).nodeify(callback);
},
/**
* Builds a where clause out of column objects.
*
* @param ids - array or object
* id array - arrayof the to be deleted ids
* id object - { table: "name of the table to resolve the ids from",
* column: [
* {
* name: "name of column", //defaults to id if unset
* operator: ">", //defaults to = if unset
* searchValue: "12",
* searchValue: { table: "source", column: [...] },
* //recursion with objects possible
* link: "AND" //defaults to AND if unset
* }
* ]
* }
*
* @return string
*/
buildWhereClause: function(ids) {
var searchClause = '';
if (Array.isArray(ids) && typeof ids[0] !== 'object' && ids.length > 1) {
searchClause +=
'WHERE id IN (' +
ids.join(this._escapeString + ',' + this._escapeString) +
')';
} else if (
typeof ids === 'string' ||
ids.length === 1 ||
typeof ids === 'number'
) {
var id = Array.isArray(ids) ? ids[0] : ids;
searchClause +=
'WHERE id = ' + this._escapeString + id + this._escapeString;
} else if (Array.isArray(ids) && typeof ids[0] === 'object') {
var preLink = '';
searchClause = ' WHERE ';
for (var column in ids) {
var columnKeys = Object.keys(ids[column]);
if (columnKeys.length === 1) {
var _column = {
name: columnKeys[0],
value: ids[column][columnKeys[0]]
};
column = _column;
} else {
column = ids[column];
}
(column.name = column.name || 'id'),
(column.operator = column.operator || '='),
(column.link = column.link || 'AND');
if (!column.value) {
return Promise.reject(
'column ' + column.name + ' was entered without a search value.'
);
}
searchClause +=
' ' +
preLink +
' ' +
this._escapeDDL +
column.name +
this._escapeDDL +
' ' +
column.operator;
if (
typeof searchValue === 'object' &&
typeof searchValue.table === 'string' &&
typeof searchValue.columns === 'object'
) {
searchClause +=
' (SELECT ' +
this._escapeDDL +
column.selector +
this._escapeDDL +
' FROM ' +
this._escapeDDL +
column.searchValue.table +
this._escapeDDL +
this.buildWhereClause(column.searchValue.column) +
')';
} else {
searchClause +=
' (' + this._escapeString + column.value + this._escapeString + ')';
}
preLink = column.link;
}
} else if (typeof ids === 'object') {
var key = Object.keys(ids);
var preLink = '';
searchClause += 'WHERE ';
for (var i = 0; i < key.length; ++i) {
searchClause +=
preLink +
this._escapeDDL +
key[i] +
this._escapeDDL +
' = ' +
this._escapeString +
ids[key[i]] +
this._escapeString;
preLink = ' AND ';
}
}
return searchClause;
},
/**
* Deletes a seed
*
* @param seedName - The name of the seed to be deleted
*/
deleteSeed: function(seedName, callback) {
var sql =
'DELETE FROM ' +
this._escapeDDL +
this.internals.seedTable +
this._escapeDDL +
' WHERE name = ?';
this.runSql(sql, [seedName], callback);
},
all: function(sql, params, callback) {
throw new Error('not implemented');
},
escape: function(str) {
if (this._escapeString === "'") return str.replace(/'/g, "''");
else return str.replace(/"/g, '"""');
},
escapeString: function(str) {
return this._escapeString + this.escape(str) + this._escapeString;
},
escapeDDL: function(str) {
return this._escapeDDL + str + this._escapeDDL;
}
});
Promise.promisifyAll(Base);
module.exports = Base;