-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
1441 lines (1248 loc) · 66.7 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
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
var asynk = require('asynk');
var _ = require('underscore');
var oracle = require('oracle');
var sql = require('./lib/sql.js');
var Query = require('./lib/query');
var utils = require('./utils');
_.str = require('underscore.string');
var Sequel = require('waterline-sequel');
var Processor = require('./lib/processor');
var Cursor = require('waterline-cursor');
var hop = utils.object.hasOwnProperty;
var SqlString = require('./lib/SqlString');
var Errors = require('waterline-errors').adapter;
var Pool = require('generic-pool');
var LOG_QUERIES = false;
var LOG_ERRORS = false;
module.exports = (function() {
//var dbs = {};
var connections = {};
var sqlOptions = {
parameterized: false,
caseSensitive: false,
escapeCharacter: '"',
casting: false,
canReturnValues: false,
escapeInserts: true,
declareDeleteAlias: false,
explicitTableAs: false,
prefixAlias: 'alias__',
stringDelimiter: "'",
rownum: true
};
var adapter = {
autoIncrements: [],
autoIncNextval: function(tableName, columnName) {
this.autoIncrements[tableName] = this.autoIncrements[tableName] || [];
this.autoIncrements[tableName][columnName] = this.autoIncrements[tableName][columnName] || 1;
var nextval = this.autoIncrements[tableName][columnName] + 1;
this.autoIncrements[tableName][columnName] = nextval;
return nextval;
},
// Set to true if this adapter supports (or requires) things like data types, validations, keys, etc.
// If true, the schema for models using this adapter will be automatically synced when the server starts.
// Not terribly relevant if not using a non-SQL / non-schema-ed data store
syncable: true,
// Including a commitLog config enables transactions in this adapter
// Please note that these are not ACID-compliant transactions:
// They guarantee *ISOLATION*, and use a configurable persistent store, so they are *DURABLE* in the face of server crashes.
// However there is no scheduled task that rebuild state from a mid-step commit log at server start, so they're not CONSISTENT yet.
// and there is still lots of work to do as far as making them ATOMIC (they're not undoable right now)
//
// However, for the immediate future, they do a great job of preventing race conditions, and are
// better than a naive solution. They add the most value in findOrCreate() and createEach().
//
// commitLog: {
// identity: '__default_mongo_transaction',
// adapter: 'sails-mongo'
// },
// Default configuration for collections
// (same effect as if these properties were included at the top level of the model definitions)
defaults: {
// For example:
// port: 3306,
// host: 'localhost'
tns: '',
user: '',
password: '',
// If setting syncable, you should consider the migrate option,
// which allows you to set how the sync will be performed.
// It can be overridden globally in an app (config/adapters.js) and on a per-model basis.
//
// drop => Drop schema and data, then recreate it
// alter => Drop/add columns as necessary, but try
// safe => Don't change anything (good for production DBs)
migrate: 'safe'
},
config: {
},
//added to match waterline orm
registerConnection: function(connection, collections, cb) {
if (!connection.identity)
return cb("Errors.IdentityMissing");
if (connections[connection.identity])
return cb("Errors.IdentityDuplicate");
var pool = Pool.Pool({
name: connection.identity,
create: function(callback) {
oracle.connect(marshalConfig(connection), function(err, cnx) {
if (err) {
return callback(err, null);
}
var queries = [];
queries[0] = "ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'yyyy-mm-dd hh24:mi:ss'";
queries[1] = "ALTER SESSION SET NLS_DATE_FORMAT = 'yyyy-mm-dd hh24:mi:ss'";
queries[2] = "ALTER SESSION SET NLS_COMP=LINGUISTIC";
queries[3] = "ALTER SESSION SET NLS_SORT=BINARY_CI";
asynk.each(queries,(cnx.execute).bind(cnx)).args(asynk.item,[],asynk.callback).serie(callback,[null,cnx]);
});
},
destroy: function(cnx){
cnx.close();
},
min: 5,
max: 20,
idleTimeoutMillis : 30000,
log: false
});
// Store the connection
connections[connection.identity] = {
config: connection,
collections: collections,
connection: pool
};
return cb();
},
//endd add
// The following methods are optional
////////////////////////////////////////////////////////////
// Optional hook fired when a model is unregistered, typically at server halt
// useful for tearing down remaining open connections, etc.
teardown: function(connectionName, cb) {
var pool = connections[connectionName].connection;
pool.drain(function() {
pool.destroyAllNow();
});
return cb();
},
// REQUIRED method if integrating with a schemaful database
define: function(connectionName, collectionName, definition, cb, connection) {
// Define a new "table" or "collection" schema in the data store
var self = this;
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
if (!collection) {
return cb(util.format('Unknown collection `%s` in connection `%s`', collectionName, connectionName));
}
var tableName = collectionName;
var schema = sql.schema(tableName, definition);
// Build query
var query = 'CREATE TABLE "' + tableName + '" (' + schema + ')';
if (connectionObject.config.charset) {
query += ' DEFAULT CHARSET ' + connectionObject.config.charset;
}
if (connectionObject.config.collation) {
if (!connectionObject.config.charset)
query += ' DEFAULT ';
query += ' COLLATE ' + connectionObject.config.collation;
}
// Run query
if (LOG_QUERIES) {
console.log('Executing DEFINE query: ', query);
}
execQuery(connections[connectionName],query, [], function __DEFINE__(err, result) {
if (err) {
if (LOG_ERRORS) {
console.log(err);
}
return cb(err);
}
// creation des sequence pour les champs autoIncrement
Object.keys(definition).forEach(function(columnName) {
var column = definition[columnName];
if (fieldIsAutoIncrement(column)) {
//init autoIncrement values
self.autoIncrements[tableName] = self.autoIncrements[tableName] || [];
self.autoIncrements[tableName][columnName] = 1;
var autoIncrementQuery = 'SELECT MAX("' + columnName + '") AS MAX FROM "' + tableName + '"';
execQuery(connections[connectionName],autoIncrementQuery, [], function(err, autoInc) {
if (err) {
if (LOG_ERRORS) {
console.log("could not get last autoIncrement value: ",err);
}
return cb(err);
}
self.autoIncrements[tableName][columnName] = autoInc[0]['MAX'] || 1;
});
}
});
//
// TODO:
// Determine if this can safely be changed to the `adapter` closure var
// (i.e. this is the last remaining usage of the "this" context in the MySQLAdapter)
//
self.describe(connectionName, collectionName, function(err) {
cb(err, result);
});
});
},
// REQUIRED method if integrating with a schemaful database
/* describe: function(collectionName, cb) {
// Respond with the schema (attributes) for a collection or table in the data store
var attributes = {};
cb(null, attributes);
},*/
describe: function(connectionName, collectionName, cb, connection) {
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
if (!collection) {
return cb(util.format('Unknown collection `%s` in connection `%s`', collectionName, connectionName));
}
var tableName = collectionName;
var queries = [];
queries[0] = "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '" + tableName + "'";
queries[1] = "SELECT index_name,COLUMN_NAME FROM user_ind_columns WHERE table_name = '" + tableName + "'";
queries[2] = "SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner "
+ "FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = '" + tableName
+ "' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner "
+ "ORDER BY cols.table_name, cols.position";
asynk.each(queries,execQuery).args(connectionObject,asynk.item,[],asynk.callback).parallel(function(err, results) {
if (err) {
if (LOG_ERRORS) {
console.log(err);
}
return cb(err);
}
var schema = results[0];
var indexes = results[1];
var tablePrimaryKeys = results[2];
if (schema.length === 0) {
return cb();
}
// Loop through Schema and attach extra attributes
schema.forEach(function(attribute) {
tablePrimaryKeys.forEach(function(pk) {
// Set Primary Key Attribute
if (attribute.COLUMN_NAME === pk.COLUMN_NAME) {
attribute.primaryKey = true;
// If also a number set auto increment attribute
if (attribute.DATA_TYPE === 'NUMBER') {
attribute.autoIncrement = true;
}
}
});
// Set Unique Attribute
if (attribute.NULLABLE === 'N') {
attribute.required = true;
}
});
// Loop Through Indexes and Add Properties
indexes.forEach(function(index) {
schema.forEach(function(attribute) {
if (attribute.COLUMN_NAME === index.COLUMN_NAME)
{
attribute.indexed = true;
}
});
});
// Convert mysql format to standard javascript object
var normalizedSchema = sql.normalizeSchema(schema, collection.attributes);
// Set Internal Schema Mapping
collection.schema = normalizedSchema;
// TODO: check that what was returned actually matches the cache
cb(null, normalizedSchema);
},[null,asynk.data('all')]);
},
// Direct access to query
query: function(connectionName, collectionName, query, data, cb, connection) {
if (_.isFunction(data)) {
cb = data;
data = null;
}
if (LOG_QUERIES) {
console.log('Executing QUERY query: ' + query);
}
data = data || [];
// Run query
execQuery(connections[connectionName],query, data, function(err, result) {
if (err) {
if (LOG_ERRORS) {
console.log("#Error executing QUERY " + err.toString() + ".");
}
return cb(handleQueryError(err));
}
return cb(null, result);
});
},
// REQUIRED method if integrating with a schemaful database
drop: function(connectionName, collectionName, relations, cb, connection) {
// Drop a "table" or "collection" schema from the data store
var self = this;
if (typeof relations === 'function') {
cb = relations;
relations = [];
}
var connectionObject = connections[connectionName];
// Drop any relations
function dropTable(item, next) {
var tableName = collectionName;
// Build query
var query = 'DROP TABLE "' + tableName + '"';
// Run query
if (LOG_QUERIES){
console.log('Executing DROP query: ' + query);
}
execQuery(connections[connectionName],query, [], function __DROP__(err, result) {
if (err) {
if (LOG_ERRORS) {
console.log("#Error executing DROP " + err.toString() + ".");
}
if (err.code !== 'ER_BAD_TABLE_ERROR' && err.code !== 'ER_NO_SUCH_TABLE')
return next(err);
result = null;
}
if (result) {
self.autoIncrements[tableName] = [];
}
next(null, result);
});
}
asynk.each(relations,dropTable).args(asynk.item,asynk.callback).parallel(function(err) {
if (err)
return cb(err);
dropTable(collectionName, cb);
},[null]);
},
createCallbackQueue: [],
// Optional override of built-in alter logic
// Can be simulated with describe(), define(), and drop(),
// but will probably be made much more efficient by an override here
// alter: function (collectionName, attributes, cb) {
// Modify the schema of a table or collection in the data store
// cb();
// },
// REQUIRED method if users expect to call Model.create() or any methods
create: function(connectionName, collectionName, data, cb, connection) {
var self = this;
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
var tableName = collectionName;
//var _insertData = lodash.cloneDeep(data);
var _insertData = _.clone(data);
// Prepare values
Object.keys(data).forEach(function(value) {
data[value] = utils.prepareValue(data[value]);
});
//recherche des champs incrémentals et de type date et affectation des valeurs lues des séquences
var pk = null;
var autoIncPK = null;
var autoIncPKval = null;
var definition = collection.definition;
Object.keys(definition).forEach(function(columnName) {
var column = definition[columnName];
if (fieldIsAutoIncrement(column)) {
data[columnName] = self.autoIncNextval(tableName, columnName);
if (column.hasOwnProperty('primaryKey')) {
autoIncPK = columnName;
autoIncPKval = self.autoIncrements[tableName][columnName];
}
}
if (column.hasOwnProperty('primaryKey')) {
pk = columnName;
}
//si le champs est de type date time
if (fieldIsDatetime(column)) {
data[columnName] = _.isUndefined(data[columnName]) ? 'null' : SqlString.dateField(data[columnName]);
}
else if (fieldIsBoolean(column)) {
data[columnName] = (data[columnName]) ? 1 : 0;
}
});
var curentCB = [];
self.createCallbackQueue.push(curentCB);
//fin recherche
var schema = collection.waterline.schema;
var _query;
var sequel = new Sequel(schema, sqlOptions);
// Build a query for the specific query strategy
try {
_query = sequel.create(collectionName, data);
} catch (e) {
return cb(e);
}
// Run query
if (LOG_QUERIES) {
console.log('Executing CREATE query: ' + _query.query);
}
execQuery(connections[connectionName],_query.query, [], function(err, result) {
if (err) {
if (LOG_ERRORS) {
console.log("#Error executing CREATE " + err.toString() + ".");
}
return cb(handleQueryError(err));
}
// Build model to return
var autoIncData = {};
if (autoIncPK) {
autoIncData[autoIncPK] = autoIncPKval;
var values = _.extend({}, _insertData, autoIncData);
curentCB[0] = cb;
curentCB[1] = values;
if (self.createCallbackQueue[0] === curentCB) {
while( self.createCallbackQueue.length && !_.isUndefined(self.createCallbackQueue[0][0]) ) {
var callback = self.createCallbackQueue.shift();
callback[0](null, callback[1]);
}
}
}
else {
autoIncData[pk] = data[pk];
var values = _.extend({}, _insertData, autoIncData);
curentCB[0] = cb;
curentCB[1] = values;
if (self.createCallbackQueue[0] === curentCB) {
while( self.createCallbackQueue.length && !_.isUndefined(self.createCallbackQueue[0][0]) ) {
var callback = self.createCallbackQueue.shift();
callback[0](null, callback[1]);
}
}
}
});
},
// Override of createEach to share a single connection
// instead of using a separate connection for each request
createEach: function(connectionName, collectionName, valuesList, cb, connection) {
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
var tableName = collectionName;
var records = [];
asynk.each(valuesList,function(data, cb) {
// Prepare values
Object.keys(data).forEach(function(value) {
data[value] = utils.prepareValue(data[value]);
});
var attributes = collection.attributes;
var definition = collection.definition;
Object.keys(attributes).forEach(function(attributeName) {
var attribute = attributes[attributeName];
/* searching for column name, if it doesn't exist, we'll use attribute name */
var columnName = attribute.columnName || attributeName;
/* affecting values to add to the columns */
data[columnName] = data[attributeName];
/* deleting attributesto be added and their names are differnet from columns names */
if (attributeName !== columnName)
delete data[attributeName];
/* deleting not mapped attributes */
if ((_.isUndefined(definition[columnName])) || (_.isUndefined(data[columnName])))
delete data[columnName];
if (fieldIsDatetime(attribute)) {
data[columnName] = (!data[columnName]) ? 'null' : SqlString.dateField(data[columnName]);
}
});
var schema = collection.waterline.schema;
var _query;
var sequel = new Sequel(schema, sqlOptions);
// Build a query for the specific query strategy
try {
_query = sequel.create(collectionName, data);
} catch (e) {
return cb(e);
}
// Run query
if (LOG_QUERIES) {
console.log('Executing CREATE_EACH : ' + _query.query);
}
execQuery(connections[connectionName],_query.query, [], function(err, results) {
if (err) {
if (LOG_ERRORS) {
console.log("#Error executing Create (CreateEach) " + err.toString() + ".");
}
return cb(handleQueryError(err));
}
records.push(results.insertId);
cb();
});
}).args(asynk.item,asynk.callback).parallel(function(err) {
if (err)
return cb(err);
var pk = 'id';
Object.keys(collection.definition).forEach(function(key) {
if (!collection.definition[key].hasOwnProperty('primaryKey'))
return;
pk = key;
});
// If there are no records (`!records.length`)
// then skip the query altogether- we don't need to look anything up
if (!records.length) {
return cb(null, []);
}
// Build a Query to get newly inserted records
/* var query = 'SELECT * FROM ' + tableName.toUpperCase() + ' WHERE ' + pk + ' IN (' + records + ');';
// Run Query returing results
connection.execute(query, [], function(err, results) {
if (err)
return cb(err);
cb(null, results);
});*/
cb(null, null);
},[null]);
},
// REQUIRED method if users expect to call Model.find(), Model.findAll() or related methods
// You're actually supporting find(), findAll(), and other methods here
// but the core will take care of supporting all the different usages.
// (e.g. if this is a find(), not a findAll(), it will only close back a single model)
find: function(connectionName, collectionName, options, cb, connection) {
// Check if this is an aggregate query and that there is something to return
if (options.groupBy || options.sum || options.average || options.min || options.max) {
if (!options.sum && !options.average && !options.min && !options.max) {
return cb(Errors.InvalidGroupBy);
}
}
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
// Build find query
var schema = collection.waterline.schema;
var processor = new Processor();
var _query;
var sequel = new Sequel(schema, sqlOptions);
//set default order by Primary key autoIncrement
if (!options.groupBy) {
var PK = _getPK(connectionName, collectionName);
if (!options.sort) {
options.sort = {};
}
options.sort[PK] = 1;
}
var limit = options.limit || null;
var skip = options.skip || null;
delete options.skip;
delete options.limit;
// Build a query for the specific query strategy
try {
_query = sequel.find(collectionName, options);
} catch (e) {
return cb(e);
}
var findQuery = _query.query[0];
if (limit && skip) {
findQuery = 'SELECT * FROM (' + findQuery + ') WHERE LINE_NUMBER > ' + skip + ' and LINE_NUMBER <= ' + (skip + limit);
}
else if (limit) {
findQuery = 'SELECT * FROM (' + findQuery + ') WHERE LINE_NUMBER <= ' + limit;
}
else if (skip) {
findQuery = 'SELECT * FROM (' + findQuery + ') WHERE LINE_NUMBER > ' + skip;
}
// Run query
if (LOG_QUERIES) {
console.log('Executing FIND query: ' + _query.query[0]);
}
execQuery(connections[connectionName],findQuery, [], function(err, result) {
if (err) {
if (LOG_ERRORS) {
console.log('#Error executing Find ' + err.toString() + '.');
}
return cb(err);
}
result = processor.synchronizeResultWithModel(result, collection.attributes);
cb(null, result);
});
},
// REQUIRED method if users expect to call Model.update()
update: function(connectionName, collectionName, options, values, cb, connection) {
var processor = new Processor();
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
// Build find query
var schema = collection.waterline.schema;
var _query;
var sequel = new Sequel(schema, sqlOptions);
// Build a query for the specific query strategy
try {
//_query = sequel.find(collectionName, lodash.cloneDeep(options));
_query = sequel.find(collectionName, _.clone(options));
} catch (e) {
return cb(e);
}
execQuery(connections[connectionName],_query.query[0], [], function(err, results) {
if (err) {
if (LOG_ERRORS) {
console.log("#Error executing Find_1 (Update) " + err.toString() + ".");
}
return cb(err);
}
var ids = [];
var pk = 'id';
Object.keys(collection.definition).forEach(function(key) {
if (!collection.definition[key].hasOwnProperty('primaryKey'))
return;
pk = key;
});
// update statement will affect 0 rows
if (results.length === 0) {
return cb(null, []);
}
results.forEach(function(result) {
//ids.push(result[pk.toUpperCase()]);
ids.push(result[pk]);
});
// Prepare values
Object.keys(values).forEach(function(value) {
values[value] = utils.prepareValue(values[value]);
});
var definition = collection.definition;
var attrs = collection.attributes;
Object.keys(definition).forEach(function(columnName) {
var column = definition[columnName];
if (fieldIsDatetime(column)) {
if (!values[columnName])
return;
values[columnName] = SqlString.dateField(values[columnName]);
}
else if (fieldIsBoolean(column)) {
values[columnName] = (values[columnName]) ? 1 : 0;
}
});
// Build query
try {
_query = sequel.update(collectionName, options, values);
} catch (e) {
return cb(e);
}
if (LOG_QUERIES) {
console.log('Executing UPDATE query: ' + _query.query);
}
// Run query
execQuery(connections[connectionName],_query.query, [], function(err, result) {
if (err) {
if (LOG_ERRORS) {
console.log('#Error executing Update ' + err.toString() + '.');
}
return cb(handleQueryError(err));
}
var criteria = {where: {}};
if (ids.length === 1) {
criteria.where[pk] = ids[0];
} else {
criteria.where[pk] = ids;
}
// Build a query for the specific query strategy
try {
_query = sequel.find(collectionName, criteria);
} catch (e) {
return cb(e);
}
var findQuery = _query.query[0];
if(ids.length === 1){
findQuery = 'SELECT * FROM (' + findQuery + ') WHERE LINE_NUMBER = 1';
}
// Run query
if (LOG_QUERIES) {
console.log("Executing UPDATE find query" + findQuery);
}
execQuery(connections[connectionName],findQuery, [], function(err, result) {
if (err) {
if (LOG_ERRORS) {
console.log("#Error executing Find_2 (Update) " + err.toString() + ".");
}
return cb(err);
}
result = processor.synchronizeResultWithModel(result, attrs);
cb(null, result);
});
});
});
},
// REQUIRED method if users expect to call Model.destroy()
destroy: function(connectionName, collectionName, options, cb, connection) {
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
var tableName = collectionName;
// Build query
var schema = collection.waterline.schema;
var _query;
var sequel = new Sequel(schema, sqlOptions);
// Build a query for the specific query strategy
try {
_query = sequel.destroy(collectionName, options);
} catch (e) {
return cb(e);
}
if (LOG_QUERIES) {
console.log("Executing DESTROY query: " + _query.query);
}
asynk.add((adapter.find).bind(adapter)).args(connectionName, collectionName, options, asynk.callback, connection).alias('findRecords')
.add(execQuery).args(connections[connectionName],_query.query, [], asynk.callback)
.serie(cb,[null,asynk.data('findRecords')]);
},
// REQUIRED method if users expect to call Model.stream()
stream: function(connectionName, collectionName, options, stream, connection) {
if (_.isUndefined(connection)) {
return spawnConnection(__STREAM__, connections[connectionName]);
} else {
__STREAM__(connection);
}
function __STREAM__(connection, cb) {
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
var tableName = collectionName;
// Build find query
var query = sql.selectQuery(tableName, options);
// Run query
var dbStream = connection.execute(query);
// Handle error, an 'end' event will be emitted after this as well
dbStream.on('error', function(err) {
stream.end(err); // End stream
cb(err); // Close connection
});
// the field packets for the rows to follow
dbStream.on('fields', function(fields) {
});
// Pausing the connnection is useful if your processing involves I/O
dbStream.on('result', function(row) {
connection.pause();
stream.write(row, function() {
connection.resume();
});
});
// all rows have been received
dbStream.on('end', function() {
stream.end(); // End stream
cb(); // Close connection
});
}
},
addAttribute: function(connectionName, collectionName, attrName, attrDef, cb, connection) {
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
var tableName = collectionName;
var query = sql.addColumn(tableName, attrName, attrDef);
// Run query
if (LOG_QUERIES) {
console.log('Executing ADD_ATTRIBUTE query: ', query);
}
// Run query
execQuery(connections[connectionName],query, function(err, result) {
if (err)
if (LOG_ERRORS) {
console.log('ADD_ATTRIBUTE error: ', err);
}
return cb(err);
// TODO: marshal response to waterline interface
cb(err);
});
},
removeAttribute: function(connectionName, collectionName, attrName, cb, connection) {
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
var tableName = collectionName;
var query = sql.removeColumn(tableName, attrName);
// Run query
if (LOG_QUERIES) {
console.log('Executing REMOVE_ATTRIBUTE query: ', query);
}
execQuery(connections[connectionName],query, function(err, result) {
if (err)
if (LOG_ERRORS) {
console.log('REMOVE_ATTRIBUTE error: ', err);
}
return cb(err);
// TODO: marshal response to waterline interface
cb(err);
});
},
count: function(connectionName, collectionName, options, cb, connection) {
// Check if this is an aggregate query and that there is something to return
if (options.groupBy || options.sum || options.average || options.min || options.max) {
if (!options.sum && !options.average && !options.min && !options.max) {
return cb('InvalidGroupBy');
}
}
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
var tableName = collectionName;
// Build a copy of the schema to send w/ the query
var localSchema = _.reduce(connectionObject.collections, function(localSchema, collection, cid) {
localSchema[cid] = collection.schema;
return localSchema;
}, {});
// Build find query
var query = sql.countQuery(tableName, options, localSchema);
// Run query
if (LOG_QUERIES) {
console.log('Executing COUNT query:',query);
}
execQuery(connections[connectionName],query, [], function(err, result) {
if (err) {
if (LOG_ERRORS) {
console.log('#Error counting table \'' + collectionName + '\' rows (Count) ' + err.toString() + '.');
}
return cb(err);
}
// Return the count from the simplified query
cb(null, result[0].COUNT);
});
},
join: function(connectionName, collectionName, options, cb, connection) {
// Populate associated records for each parent result
// (or do them all at once as an optimization, if possible)
Cursor({
instructions: options,
nativeJoins: true,
/**
* Find some records directly (using only this adapter)
* from the specified collection.
*
* @param {String} collectionName
* @param {Object} criteria
* @param {Function} _cb
*/
$find: function(collectionName, criteria, _cb) {
return adapter.find(connectionName, collectionName, criteria, _cb);
},
/**
* Look up the name of the primary key field
* for the collection with the specified identity.
*
* @param {String} collectionName
* @return {String}
*/
$getPK: function(collectionName) {
if (!collectionName)
return;
return _getPK(connectionName, collectionName);
},
/**
* Given a strategy type, build up and execute a SQL query for it.
*
* @param {}
*/
$populateBuffers: function populateBuffers(options, next) {
var buffers = options.buffers;
var instructions = options.instructions;
var mapping = [];
var criterias = [];
var i = 0;
_.keys(instructions.instructions).forEach(function(attr) {
var strategy = instructions.instructions[attr].strategy.strategy;
var population = instructions.instructions[attr].instructions[0];
mapping["p" + i] = population.parentKey;
population.parentKeyAlias = "p" + i;
i++;
var childInstructions = instructions.instructions[attr].instructions;
// reglage des limit et skip pour les childs
var x = 0;
childInstructions.forEach(function(childIns) {
var criteria = childIns.criteria;
if (criteria) {
criterias[childIns.child] = {skip: (criteria.skip ? criteria.skip : null), limit: (criteria.limit ? criteria.limit : null)};
delete criteria.skip;
delete criteria.limit;
}
x++;
});
});
// Grab the collection by looking into the connection
var connectionObject = connections[connectionName];
var collection = connectionObject.collections[collectionName];
var parentRecords = [];
var cachedChildren = {};
// Grab Connection Schema
var schema = {};
Object.keys(connectionObject.collections).forEach(function(coll) {
schema[coll] = connectionObject.collections[coll].schema;
});
var processor = new Processor();
// Build Query
var _schema = collection.waterline.schema;
var sequel = new Sequel(_schema, sqlOptions);
var _query;
// Build a query for the specific query strategy
try {
_query = sequel.find(collectionName, instructions);
} catch (e) {
return next(e);
}