-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.js
1806 lines (1671 loc) · 53.3 KB
/
sql.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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright IBM Corp. 2014,2016. All Rights Reserved.
// Node module: loopback-connector
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
var SG = require('strong-globalize');
var g = SG();
var util = require('util');
var async = require('async');
var assert = require('assert');
var Connector = require('./connector');
var debug = require('debug')('loopback:connector:sql');
var ParameterizedSQL = require('./parameterized-sql');
var Transaction = require('./transaction');
module.exports = SQLConnector;
function NOOP() {}
/**
* Base class for connectors that connect to relational databases using SQL
* @class
*/
function SQLConnector() {
// Call the super constructor
Connector.apply(this, [].slice.call(arguments));
}
// Inherit from the base Connector
util.inherits(SQLConnector, Connector);
// Export ParameterizedSQL
SQLConnector.ParameterizedSQL = ParameterizedSQL;
// The generic placeholder
var PLACEHOLDER = SQLConnector.PLACEHOLDER = ParameterizedSQL.PLACEHOLDER;
SQLConnector.Transaction = Transaction;
/**
* Set the relational property to indicate the backend is a relational DB
* @type {boolean}
*/
SQLConnector.prototype.relational = true;
/**
* Invoke a prototype method on the super class
* @param {String} methodName Method name
*/
SQLConnector.prototype.invokeSuper = function(methodName) {
var args = [].slice.call(arguments, 1);
var superMethod = this.constructor.super_.prototype[methodName];
return superMethod.apply(this, args);
};
/**
* Get types associated with the connector
* Returns {String[]} The types for the connector
*/
SQLConnector.prototype.getTypes = function() {
return ['db', 'rdbms', 'sql'];
};
/**
* Get the default data type for ID
* @param prop Property definition
* Returns {Function}
*/
SQLConnector.prototype.getDefaultIdType = function(prop) {
return Number;
};
/**
* Get the default database schema name
* @returns {string} The default schema name, such as 'public' or 'dbo'
*/
SQLConnector.prototype.getDefaultSchemaName = function() {
return '';
};
/**
* Get the database schema name for the given model. The schema name can be
* customized at model settings or connector configuration level as `schema` or
* `schemaName`. For example,
*
* ```json
* "Customer": {
* "name": "Customer",
* "mysql": {
* "schema": "MYDB",
* "table": "CUSTOMER"
* }
* }
* ```
*
* @param {String} model The model name
* @returns {String} The database schema name
*/
SQLConnector.prototype.schema = function(model) {
// Check if there is a 'schema' property for connector
var dbMeta = this.getConnectorSpecificSettings(model);
var schemaName = (dbMeta && (dbMeta.schema || dbMeta.schemaName)) ||
(this.settings.schema || this.settings.schemaName) ||
this.getDefaultSchemaName();
return schemaName;
};
/**
* Get the table name for the given model. The table name can be customized
* at model settings as `table` or `tableName`. For example,
*
* ```json
* "Customer": {
* "name": "Customer",
* "mysql": {
* "table": "CUSTOMER"
* }
* }
* ```
*
* Returns the table name (String).
* @param {String} model The model name
*/
SQLConnector.prototype.table = function(model) {
var dbMeta = this.getConnectorSpecificSettings(model);
var tableName;
if (dbMeta) {
tableName = dbMeta.table || dbMeta.tableName;
if (tableName) {
// Explicit table name, return as-is
return tableName;
}
}
tableName = model;
if (typeof this.dbName === 'function') {
tableName = this.dbName(tableName);
}
return tableName;
};
/**
* Get the column name for the given model property. The column name can be
* customized at the model property definition level as `column` or
* `columnName`. For example,
*
* ```json
* "name": {
* "type": "string",
* "mysql": {
* "column": "NAME"
* }
* }
* ```
*
* @param {String} model The model name
* @param {String} property The property name
* @returns {String} The column name
*/
SQLConnector.prototype.column = function(model, property) {
var prop = this.getPropertyDefinition(model, property);
var columnName;
if (prop && prop[this.name]) {
columnName = prop[this.name].column || prop[this.name].columnName;
if (columnName) {
// Explicit column name, return as-is
return columnName;
}
}
columnName = property;
if (typeof this.dbName === 'function') {
columnName = this.dbName(columnName);
}
return columnName;
};
/**
* Get the column metadata for the given model property
* @param {String} model The model name
* @param {String} property The property name
* @returns {Object} The column metadata
*/
SQLConnector.prototype.columnMetadata = function(model, property) {
return this.getDataSource(model).columnMetadata(model, property);
};
/**
* Get the corresponding property name for the given column name
* @param {String} model The model name
* @param {String} column The column name
* @returns {String} The property name for a given column
*/
SQLConnector.prototype.propertyName = function(model, column) {
var props = this.getModelDefinition(model).properties;
for (var p in props) {
if (this.column(model, p) === column) {
return p;
}
}
return null;
};
/**
* Get the id column name
* @param {String} model The model name
* @returns {String} The id column name
*/
SQLConnector.prototype.idColumn = function(model) {
var name = this.getDataSource(model).idColumnName(model);
var dbName = this.dbName;
if (typeof dbName === 'function') {
name = dbName(name);
}
return name;
};
/**
* Get the escaped id column name
* @param {String} model The model name
* @returns {String} the escaped id column name
*/
SQLConnector.prototype.idColumnEscaped = function(model) {
return this.escapeName(this.idColumn(model));
};
/**
* Get the escaped table name
* @param {String} model The model name
* @returns {String} the escaped table name
*/
SQLConnector.prototype.tableEscaped = function(model) {
return this.escapeName(this.table(model));
};
/**
* Get the escaped column name for a given model property
* @param {String} model The model name
* @param {String} property The property name
* @returns {String} The escaped column name
*/
SQLConnector.prototype.columnEscaped = function(model, property) {
return this.escapeName(this.column(model, property));
};
/*!
* Check if id value is set
* @param idValue
* @param cb
* @param returningNull
* @returns {boolean}
*/
function isIdValuePresent(idValue, cb, returningNull) {
try {
assert(idValue !== null && idValue !== undefined, 'id value is required');
return true;
} catch (err) {
process.nextTick(function() {
if (cb) cb(returningNull ? null : err);
});
return false;
}
}
/**
* Convert the id value to the form required by database column
* @param {String} model The model name
* @param {*} idValue The id property value
* @returns {*} The escaped id column value
*/
SQLConnector.prototype.idColumnValue = function(model, idValue) {
var idProp = this.getDataSource(model).idProperty(model);
if (typeof this.toColumnValue === 'function') {
return this.toColumnValue(idProp, idValue);
} else {
return idValue;
}
};
/**
* Replace `?` with connector specific placeholders. For example,
*
* ```
* {sql: 'SELECT * FROM CUSTOMER WHERE NAME=?', params: ['John']}
* ==>
* {sql: 'SELECT * FROM CUSTOMER WHERE NAME=:1', params: ['John']}
* ```
* *LIMITATION*: We don't handle the ? inside escaped values, for example,
* `SELECT * FROM CUSTOMER WHERE NAME='J?hn'` will not be parameterized
* correctly.
*
* @param {ParameterizedSQL|Object} ps Parameterized SQL
* @returns {ParameterizedSQL} Parameterized SQL with the connector specific
* placeholders
*/
SQLConnector.prototype.parameterize = function(ps) {
ps = new ParameterizedSQL(ps);
// The value is parameterized, for example
// {sql: 'to_point(?,?)', values: [1, 2]}
var parts = ps.sql.split(PLACEHOLDER);
var clause = [];
for (var j = 0, m = parts.length; j < m; j++) {
// Replace ? with the keyed placeholder, such as :5
clause.push(parts[j]);
if (j !== parts.length - 1) {
clause.push(this.getPlaceholderForValue(j + 1));
}
}
ps.sql = clause.join('');
return ps;
};
/**
* Build the the `INSERT INTO` statement
* @param {String} model The model name
* @param {Object} fields Fields to be inserted
* @param {Object} options Options object
* @returns {ParameterizedSQL}
*/
SQLConnector.prototype.buildInsertInto = function(model, fields, options) {
var stmt = new ParameterizedSQL('INSERT INTO ' + this.tableEscaped(model));
var columnNames = fields.names.join(',');
if (columnNames) {
stmt.merge('(' + columnNames + ')', '');
}
return stmt;
};
/**
* Build the clause to return id values after insert
* @param {String} model The model name
* @param {Object} data The model data object
* @param {Object} options Options object
* @returns {string}
*/
SQLConnector.prototype.buildInsertReturning = function(model, data, options) {
return '';
};
/**
* Build the clause for default values if the fields is empty
* @param {String} model The model name
* @param {Object} data The model data object
* @param {Object} options Options object
* @returns {string} 'DEFAULT VALUES'
*/
SQLConnector.prototype.buildInsertDefaultValues = function(model, data, options) {
return 'VALUES()';
};
/**
* Build INSERT SQL statement
* @param {String} model The model name
* @param {Object} data The model data object
* @param {Object} options The options object
* @returns {string} The INSERT SQL statement
*/
SQLConnector.prototype.buildInsert = function(model, data, options) {
var fields = this.buildFields(model, data);
var insertStmt = this.buildInsertInto(model, fields, options);
var columnValues = fields.columnValues;
var fieldNames = fields.names;
if (fieldNames.length) {
var values = ParameterizedSQL.join(columnValues, ',');
values.sql = 'VALUES(' + values.sql + ')';
insertStmt.merge(values);
} else {
insertStmt.merge(this.buildInsertDefaultValues(model, data, options));
}
var returning = this.buildInsertReturning(model, data, options);
if (returning) {
insertStmt.merge(returning);
}
return this.parameterize(insertStmt);
};
/**
* Execute a SQL statement with given parameters.
*
* @param {String} sql The SQL statement
* @param {*[]} [params] An array of parameter values
* @param {Object} [options] Options object
* @param {Function} [callback] The callback function
*/
SQLConnector.prototype.execute = function(sql, params, options, callback) {
assert(typeof sql === 'string', 'sql must be a string');
if (typeof params === 'function' && options === undefined &&
callback === undefined) {
// execute(sql, callback)
options = {};
callback = params;
params = [];
} else if (typeof options === 'function' && callback === undefined) {
// execute(sql, params, callback)
callback = options;
options = {};
}
params = params || [];
options = options || {};
assert(Array.isArray(params), 'params must be an array');
assert(typeof options === 'object', 'options must be an object');
assert(typeof callback === 'function', 'callback must be a function');
var self = this;
if (!this.dataSource.connected) {
return this.dataSource.once('connected', function() {
self.execute(sql, params, options, callback);
});
}
var context = {
req: {
sql: sql,
params: params,
},
options: options,
};
this.notifyObserversAround('execute', context, function(context, done) {
self.executeSQL(context.req.sql, context.req.params, context.options,
function(err, info) {
if (err) {
debug('Error: %j %j %j', err, context.req.sql, context.req.params);
}
if (!err && info != null) {
context.res = info;
}
// Don't pass more than one args as it will confuse async.waterfall
done(err, info);
});
}, callback);
};
/**
* Create the data model in MySQL
*
* @param {String} model The model name
* @param {Object} data The model instance data
* @param {Object} options Options object
* @param {Function} [callback] The callback function
*/
SQLConnector.prototype.create = function(model, data, options, callback) {
var self = this;
var stmt = this.buildInsert(model, data, options);
this.execute(stmt.sql, stmt.params, options, function(err, info) {
if (err) {
callback(err);
} else {
var insertedId = self.getInsertedId(model, info);
callback(err, insertedId);
}
});
};
/**
* Save the model instance into the database
* @param {String} model The model name
* @param {Object} data The model instance data
* @param {Object} options Options object
* @param {Function} cb The callback function
*/
SQLConnector.prototype.save = function(model, data, options, cb) {
var idName = this.idName(model);
var idValue = data[idName];
if (!isIdValuePresent(idValue, cb)) {
return;
}
var where = {};
where[idName] = idValue;
var updateStmt = new ParameterizedSQL('UPDATE ' + this.tableEscaped(model));
updateStmt.merge(this.buildFieldsForUpdate(model, data));
var whereStmt = this.buildWhere(model, where);
updateStmt.merge(whereStmt);
updateStmt = this.parameterize(updateStmt);
this.execute(updateStmt.sql, updateStmt.params, options,
function(err, result) {
if (cb) cb(err, result);
});
};
/**
* Check if a model instance exists for the given id value
* @param {String} model The model name
* @param {*} id The id value
* @param {Object} options Options object
* @param {Function} cb The callback function
*/
SQLConnector.prototype.exists = function(model, id, options, cb) {
if (!isIdValuePresent(id, cb, true)) {
return;
}
var idName = this.idName(model);
var where = {};
where[idName] = id;
var selectStmt = new ParameterizedSQL(
'SELECT 1 FROM ' + this.tableEscaped(model) +
' WHERE ' + this.idColumnEscaped(model)
);
selectStmt.merge(this.buildWhere(model, where));
selectStmt = this.applyPagination(model, selectStmt, {
limit: 1,
offset: 0,
order: [idName],
});
selectStmt = this.parameterize(selectStmt);
this.execute(selectStmt.sql, selectStmt.params, options, function(err, data) {
if (!cb) return;
if (err) {
cb(err);
} else {
cb(null, data.length >= 1);
}
});
};
/**
* ATM, this method is not used by loopback-datasource-juggler dao, which
* maps `destroy` to `destroyAll` with a `where` filter that includes the `id`
* instead.
*
* Delete a model instance by id value
* @param {String} model The model name
* @param {*} id The id value
* @param {Object} options Options object
* @param {Function} cb The callback function
* @private
*/
SQLConnector.prototype.destroy = function(model, id, options, cb) {
if (!isIdValuePresent(id, cb, true)) {
return;
}
var idName = this.idName(model);
var where = {};
where[idName] = id;
this.destroyAll(model, where, options, cb);
};
// Alias to `destroy`. Juggler checks `destroy` only.
Connector.defineAliases(SQLConnector.prototype, 'destroy',
['delete', 'deleteById', 'destroyById']);
/**
* Build the `DELETE FROM` SQL statement
* @param {String} model The model name
* @param {Object} where The where object
* @param {Object} options Options object
* @returns {ParameterizedSQL} The SQL DELETE FROM statement
*/
SQLConnector.prototype.buildDelete = function(model, where, options) {
var deleteStmt = new ParameterizedSQL('DELETE FROM ' +
this.tableEscaped(model));
deleteStmt.merge(this.buildWhere(model, where));
return this.parameterize(deleteStmt);
};
/**
* Delete all matching model instances
*
* @param {String} model The model name
* @param {Object} where The where object
* @param {Object} options The options object
* @param {Function} cb The callback function
*/
SQLConnector.prototype.destroyAll = function(model, where, options, cb) {
var stmt = this.buildDelete(model, where, options);
this._executeAlteringQuery(model, stmt.sql, stmt.params, options, cb || NOOP);
};
// Alias to `destroyAll`. Juggler checks `destroyAll` only.
Connector.defineAliases(SQLConnector.prototype, 'destroyAll', ['deleteAll']);
/**
* ATM, this method is not used by loopback-datasource-juggler dao, which
* maps `updateAttributes` to `update` with a `where` filter that includes the
* `id` instead.
*
* Update attributes for a given model instance
* @param {String} model The model name
* @param {*} id The id value
* @param {Object} data The model data instance containing all properties to
* be updated
* @param {Object} options Options object
* @param {Function} cb The callback function
* @private
*/
SQLConnector.prototype.updateAttributes = function(model, id, data, options, cb) {
if (!isIdValuePresent(id, cb)) return;
var where = this._buildWhereObjById(model, id, data);
this.updateAll(model, where, data, options, cb);
};
/**
* Replace attributes for a given model instance
* @param {String} model The model name
* @param {*} id The id value
* @param {Object} data The model data instance containing all properties to
* be replaced
* @param {Object} options Options object
* @param {Function} cb The callback function
* @private
*/
SQLConnector.prototype.replaceById = function(model, id, data, options, cb) {
if (!isIdValuePresent(id, cb)) return;
var where = this._buildWhereObjById(model, id, data);
this._replace(model, where, data, options, cb);
};
/*
* @param model The model name.
* @param id The instance ID.
* @param {Object} data The data Object.
* @returns {Object} where The where object for a spcific instance.
* @private
*/
SQLConnector.prototype._buildWhereObjById = function(model, id, data) {
var idName = this.idName(model);
delete data[idName];
var where = {};
where[idName] = id;
return where;
};
/**
* Build the UPDATE statement
* @param {String} model The model name
* @param {Object} where The where object
* @param {Object} data The data to be changed
* @param {Object} options The options object
* @param {Function} cb The callback function
* @returns {ParameterizedSQL} The UPDATE SQL statement
*/
SQLConnector.prototype.buildUpdate = function(model, where, data, options) {
var fields = this.buildFieldsForUpdate(model, data);
return this._constructUpdateQuery(model, where, fields);
};
/**
* Build the UPDATE statement for replacing
* @param {String} model The model name
* @param {Object} where The where object
* @param {Object} data The data to be changed
* @param {Object} options The options object
* @param {Function} cb The callback function
* @returns {ParameterizedSQL} The UPDATE SQL statement for replacing fields
*/
SQLConnector.prototype.buildReplace = function(model, where, data, options) {
var fields = this.buildFieldsForReplace(model, data);
return this._constructUpdateQuery(model, where, fields);
};
/*
* @param model The model name.
* @param {} where The where object.
* @param {Object} field The parameterizedSQL fileds.
* @returns {Object} update query Constructed update query.
* @private
*/
SQLConnector.prototype._constructUpdateQuery = function(model, where, fields) {
var updateClause = new ParameterizedSQL('UPDATE ' + this.tableEscaped(model));
var whereClause = this.buildWhere(model, where);
updateClause.merge([fields, whereClause]);
return this.parameterize(updateClause);
};
/**
* Update all instances that match the where clause with the given data
* @param {String} model The model name
* @param {Object} where The where object
* @param {Object} data The property/value object representing changes
* to be made
* @param {Object} options The options object
* @param {Function} cb The callback function
*/
SQLConnector.prototype.update = function(model, where, data, options, cb) {
var stmt = this.buildUpdate(model, where, data, options);
this._executeAlteringQuery(model, stmt.sql, stmt.params, options, cb || NOOP);
};
/**
* Replace all instances that match the where clause with the given data
* @param {String} model The model name
* @param {Object} where The where object
* @param {Object} data The property/value object representing changes
* to be made
* @param {Object} options The options object
* @param {Function} cb The callback function
*/
SQLConnector.prototype._replace = function(model, where, data, options, cb) {
var stmt = this.buildReplace(model, where, data, options);
this.execute(stmt.sql, stmt.params, options, function(err, info) {
if (err) return cb(err);
if (info.affectedRows === 0) {
return cb(errorIdNotFoundForReplace(where.id));
} else {
return cb(null, info);
}
});
};
function errorIdNotFoundForReplace(idValue) {
var msg = g.f('Could not replace. Object with id %s does not exist!', idValue);
var error = new Error(msg);
error.statusCode = error.status = 404;
return error;
}
SQLConnector.prototype._executeAlteringQuery = function(model, sql, params, options, cb) {
var self = this;
this.execute(sql, params, options, function(err, info) {
var affectedRows = self.getCountForAffectedRows(model, info);
cb(err, { count: affectedRows });
});
};
// Alias to `update` and `replace`. Juggler checks `update` and `replace` only.
Connector.defineAliases(SQLConnector.prototype, 'update', ['updateAll']);
Connector.defineAliases(SQLConnector.prototype, 'replace', ['replaceAll']);
/**
* Build the SQL WHERE clause for the where object
* @param {string} model Model name
* @param {object} where An object for the where conditions
* @returns {ParameterizedSQL} The SQL WHERE clause
*/
SQLConnector.prototype.buildWhere = function(model, where) {
var whereClause = this._buildWhere(model, where);
if (whereClause.sql) {
whereClause.sql = 'WHERE ' + whereClause.sql;
}
return whereClause;
};
/**
* Build SQL expression
* @param {String} columnName Escaped column name
* @param {String} operator SQL operator
* @param {*} columnValue Column value
* @param {*} propertyValue Property value
* @returns {ParameterizedSQL} The SQL expression
*/
SQLConnector.prototype.buildExpression =
function(columnName, operator, columnValue, propertyValue) {
function buildClause(columnValue, separator, grouping) {
var values = [];
for (var i = 0, n = columnValue.length; i < n; i++) {
if (columnValue[i] instanceof ParameterizedSQL) {
values.push(columnValue[i]);
} else {
values.push(new ParameterizedSQL(PLACEHOLDER, [columnValue[i]]));
}
}
separator = separator || ',';
var clause = ParameterizedSQL.join(values, separator);
if (grouping) {
clause.sql = '(' + clause.sql + ')';
}
return clause;
}
var sqlExp = columnName;
var clause;
if (columnValue instanceof ParameterizedSQL) {
clause = columnValue;
} else {
clause = new ParameterizedSQL(PLACEHOLDER, [columnValue]);
}
switch (operator) {
case 'gt':
sqlExp += '>';
break;
case 'gte':
sqlExp += '>=';
break;
case 'lt':
sqlExp += '<';
break;
case 'lte':
sqlExp += '<=';
break;
case 'between':
sqlExp += ' BETWEEN ';
clause = buildClause(columnValue, ' AND ', false);
break;
case 'inq':
sqlExp += ' IN ';
clause = buildClause(columnValue, ',', true);
break;
case 'nin':
sqlExp += ' NOT IN ';
clause = buildClause(columnValue, ',', true);
break;
case 'neq':
if (columnValue == null) {
return new ParameterizedSQL(sqlExp + ' IS NOT NULL');
}
sqlExp += '!=';
break;
case 'like':
sqlExp += ' LIKE ';
break;
case 'nlike':
sqlExp += ' NOT LIKE ';
break;
// this case not needed since each database has its own regex syntax, but
// we leave the MySQL syntax here as a placeholder
case 'regexp':
sqlExp += ' REGEXP ';
break;
}
var stmt = ParameterizedSQL.join([sqlExp, clause], '');
return stmt;
};
/*!
* @param model
* @param where
* @returns {ParameterizedSQL}
* @private
*/
SQLConnector.prototype._buildWhere = function(model, where) {
if (!where) {
return new ParameterizedSQL('');
}
if (typeof where !== 'object' || Array.isArray(where)) {
debug('Invalid value for where: %j', where);
return new ParameterizedSQL('');
}
var self = this;
var props = self.getModelDefinition(model).properties;
var whereStmts = [];
for (var key in where) {
var stmt = new ParameterizedSQL('', []);
// Handle and/or operators
if (key === 'and' || key === 'or') {
var branches = [];
var branchParams = [];
var clauses = where[key];
if (Array.isArray(clauses)) {
for (var i = 0, n = clauses.length; i < n; i++) {
var stmtForClause = self._buildWhere(model, clauses[i]);
if (stmtForClause.sql) {
stmtForClause.sql = '(' + stmtForClause.sql + ')';
branchParams = branchParams.concat(stmtForClause.params);
branches.push(stmtForClause.sql);
}
}
stmt.merge({
sql: branches.join(' ' + key.toUpperCase() + ' '),
params: branchParams,
});
whereStmts.push(stmt);
continue;
}
// The value is not an array, fall back to regular fields
}
var p = props[key];
if (p == null) {
// Unknown property, ignore it
debug('Unknown property %s is skipped for model %s', key, model);
continue;
}
/* eslint-disable one-var */
var columnName = self.columnEscaped(model, key);
var expression = where[key];
var columnValue;
var sqlExp;
/* eslint-enable one-var */
if (expression === null || expression === undefined) {
stmt.merge(columnName + ' IS NULL');
} else if (expression && expression.constructor === Object) {
var operator = Object.keys(expression)[0];
// Get the expression without the operator
expression = expression[operator];
if (operator === 'inq' || operator === 'nin' || operator === 'between') {
columnValue = [];
if (Array.isArray(expression)) {
// Column value is a list
for (var j = 0, m = expression.length; j < m; j++) {
columnValue.push(this.toColumnValue(p, expression[j]));
}
} else {
columnValue.push(this.toColumnValue(p, expression));
}
if (operator === 'between') {
// BETWEEN v1 AND v2
var v1 = columnValue[0] === undefined ? null : columnValue[0];
var v2 = columnValue[1] === undefined ? null : columnValue[1];
columnValue = [v1, v2];
} else {
// IN (v1,v2,v3) or NOT IN (v1,v2,v3)
if (columnValue.length === 0) {
if (operator === 'inq') {
columnValue = [null];
} else {
// nin () is true
continue;
}
}
}
} else if (operator === 'regexp' && expression instanceof RegExp) {
// do not coerce RegExp based on property definitions
columnValue = expression;
} else {
columnValue = this.toColumnValue(p, expression);
}
sqlExp = self.buildExpression(
columnName, operator, columnValue, p);
stmt.merge(sqlExp);
} else {
// The expression is the field value, not a condition
columnValue = self.toColumnValue(p, expression);
if (columnValue === null) {
stmt.merge(columnName + ' IS NULL');
} else {
if (columnValue instanceof ParameterizedSQL) {
stmt.merge(columnName + '=').merge(columnValue);
} else {
stmt.merge({
sql: columnName + '=?',
params: [columnValue],
});
}
}
}
whereStmts.push(stmt);
}
var params = [];
var sqls = [];
for (var k = 0, s = whereStmts.length; k < s; k++) {
sqls.push(whereStmts[k].sql);
params = params.concat(whereStmts[k].params);
}
var whereStmt = new ParameterizedSQL({
sql: sqls.join(' AND '),
params: params,
});
return whereStmt;
};
/**
* Build the ORDER BY clause
* @param {string} model Model name
* @param {string[]} order An array of sorting criteria
* @returns {string} The ORDER BY clause
*/
SQLConnector.prototype.buildOrderBy = function(model, order) {
if (!order) {
return '';
}
var self = this;
if (typeof order === 'string') {
order = [order];
}
var clauses = [];
for (var i = 0, n = order.length; i < n; i++) {
var t = order[i].split(/[\s,]+/);
if (t.length === 1) {
clauses.push(self.columnEscaped(model, order[i]));
} else {
clauses.push(self.columnEscaped(model, t[0]) + ' ' + t[1]);
}
}
return 'ORDER BY ' + clauses.join(',');
};
/**
* Build an array of fields for the database operation
* @param {String} model Model name
* @param {Object} data Model data object
* @param {Boolean} excludeIds Exclude id properties or not, default to false
* @returns {{names: Array, values: Array, properties: Array}}
*/
SQLConnector.prototype.buildFields = function(model, data, excludeIds) {
var keys = Object.keys(data);
return this._buildFieldsForKeys(model, data, keys, excludeIds);
};
/**
* Build an array of fields for the replace database operation
* @param {String} model Model name
* @param {Object} data Model data object
* @param {Boolean} excludeIds Exclude id properties or not, default to false
* @returns {{names: Array, values: Array, properties: Array}}
*/
SQLConnector.prototype.buildReplaceFields = function(model, data, excludeIds) {
var props = this.getModelDefinition(model).properties;
var keys = Object.keys(props);
return this._buildFieldsForKeys(model, data, keys, excludeIds);
};
/*
* @param {String} model The model name.
* @returns {Object} data The model data object.
* @returns {Array} keys The key fields for which need to be built.
* @param {Boolean} excludeIds Exclude id properties or not, default to false
* @private