forked from viezel/napp.alloy.adapter.restsql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlrest.js
1463 lines (1268 loc) · 39.7 KB
/
sqlrest.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
/**
* SQL Rest Adapter for Titanium Alloy
* @author Mads Møller
* @version 0.3.2
* Copyright Napp ApS
* www.napp.dk
*/
var _ = require('alloy/underscore')._,
Alloy = require("alloy"),
Backbone = Alloy.Backbone,
moment = require('alloy/moment');
// The database name used when none is specified in the
// model configuration.
var ALLOY_DB_DEFAULT = '_alloy_';
var ALLOY_ID_DEFAULT = 'alloy_id';
var cache = {
config : {},
Model : {},
URL : null
};
// The sql-specific migration object, which is the main parameter
// to the up() and down() migration functions.
//
// db The database handle for migration processing. Do not open
// or close this as it is a running transaction that ensures
// data integrity during the migration process.
// dbname The name of the SQLite database for this model.
// table The name of the SQLite table for this model.
// idAttribute The unique ID column for this model, which is
// mapped back to Backbone.js for its update and
// delete operations.
function Migrator(config, transactionDb) {
this.db = transactionDb;
this.dbname = config.adapter.db_name;
this.table = config.adapter.collection_name;
this.idAttribute = config.adapter.idAttribute;
this.column = function(name) {
var parts = name.split(/\s+/),
type = parts[0];
switch (type.toLowerCase()) {
case "string":
case "varchar":
case "date":
case "datetime":
Ti.API.warn("\"" + type + "\" is not a valid sqlite field, using TEXT instead");
case "text":
type = "TEXT";
break;
case "int":
case "tinyint":
case "smallint":
case "bigint":
case "boolean":
Ti.API.warn("\"" + type + "\" is not a valid sqlite field, using INTEGER instead");
case "integer":
type = "INTEGER";
break;
case "double":
case "float":
case "decimal":
case "number":
Ti.API.warn("\"" + name + "\" is not a valid sqlite field, using REAL instead");
case "real":
type = "REAL";
break;
case "blob":
type = "BLOB";
break;
case "null":
type = "NULL";
break;
default:
type = "TEXT";
}
parts[0] = type;
return parts.join(" ");
};
this.createTable = function(config) {
var columns = [],
found = !1;
for (var k in config.columns) {
k === this.idAttribute && ( found = !0);
columns.push(k + " " + this.column(config.columns[k]));
}
!found && this.idAttribute === ALLOY_ID_DEFAULT && columns.push(ALLOY_ID_DEFAULT + " TEXT");
var sql = "CREATE TABLE IF NOT EXISTS " + this.table + " ( " + columns.join(",") + ")";
this.db.execute(sql);
};
this.createIndex = function(config) {
for (var i in config) {
var columns = [];
columns.push(config[i]);
var sql = "CREATE INDEX IF NOT EXISTS " + i + " ON '" + this.table + "' (" + columns.join(",") + ")";
this.db.execute(sql);
}
};
this.dropTable = function(config) {
this.db.execute("DROP TABLE IF EXISTS " + this.table);
};
this.insertRow = function(columnValues) {
var columns = [],
values = [],
qs = [],
found = !1;
for (var key in columnValues) {
key === this.idAttribute && ( found = !0);
columns.push(key);
values.push(columnValues[key]);
qs.push("?");
}
if (!found && this.idAttribute === ALLOY_ID_DEFAULT) {
columns.push(this.idAttribute);
values.push(guid());
qs.push("?");
}
this.db.execute("INSERT INTO " + this.table + " (" + columns.join(",") + ") VALUES (" + qs.join(",") + ");", values);
};
this.deleteRow = function(columns) {
var sql = "DELETE FROM " + this.table,
keys = _.keys(columns),
len = keys.length,
conditions = [],
values = [];
len && (sql += " WHERE ");
for (var i = 0; i < len; i++) {
conditions.push(keys[i] + " = ?");
values.push(columns[keys[i]]);
}
sql += conditions.join(" AND ");
this.db.execute(sql, values);
};
}
function apiCall(_options, _callback) {
//adding localOnly
if (Ti.Network.online && !_options.localOnly) {
//we are online - talk with Rest API
var xhr = Ti.Network.createHTTPClient({
timeout : _options.timeout,
cache : _options.cache,
validatesSecureCertificate: _options.validatesSecureCertificate
});
xhr.onload = function() {
var responseJSON,
success = (this.status <= 304) ? "ok" : "error",
status = true,
error;
// save the eTag for future reference
if (_options.eTagEnabled && success) {
setETag(_options.url, xhr.getResponseHeader('ETag'));
}
// we dont want to parse the JSON on a empty response
if (this.status != 304 && this.status != 204) {
// parse JSON
try {
responseJSON = JSON.parse(this.responseText);
} catch (e) {
Ti.API.error('[SQL REST API] apiCall PARSE ERROR: ' + e.message);
Ti.API.error('[SQL REST API] apiCall PARSE ERROR: ' + this.responseText);
status = false;
error = e.message;
}
}
_callback({
success : status,
status : success,
code : this.status,
data : error,
responseText : this.responseText || null,
responseJSON : responseJSON || null
});
cleanup();
};
//Handle error
xhr.onerror = function(err) {
var responseJSON,
error;
try {
responseJSON = JSON.parse(this.responseText);
} catch (e) {
error = e.message;
}
_callback({
success : false,
status : "error",
code : this.status,
error : err.error,
data : error,
responseText : this.responseText,
responseJSON : responseJSON || null
});
Ti.API.error('[SQL REST API] apiCall ERROR: ' + this.responseText);
Ti.API.error('[SQL REST API] apiCall ERROR CODE: ' + this.status);
Ti.API.error('[SQL REST API] apiCall ERROR MSG: ' + err.error);
Ti.API.error('[SQL REST API] apiCall ERROR URL: ' + _options.url);
cleanup();
};
//Prepare the request
xhr.open(_options.type, _options.url);
// headers (should be between open and send methods)
for (var header in _options.headers) {
// use value or function to return value
xhr.setRequestHeader(header, _.isFunction(_options.headers[header]) ? _options.headers[header]() : _options.headers[header]);
}
if (_options.beforeSend) {
_options.beforeSend(xhr);
}
if (_options.eTagEnabled) {
var etag = getETag(_options.url);
etag && xhr.setRequestHeader('IF-NONE-MATCH', etag);
}
xhr.send(_options.data);
} else {
// we are offline
_callback({
success : false,
responseText : null,
offline : true,
localOnly : _options.localOnly
});
}
/**
* Clean up the request
*/
function cleanup() {
xhr = null;
_options = null;
_callback = null;
error = null;
responseJSON = null;
}
}
function Sync(method, model, opts) {
var table = model.config.adapter.collection_name,
columns = model.config.columns,
dbName = model.config.adapter.db_name || ALLOY_DB_DEFAULT,
resp = null,
db;
model.idAttribute = model.config.adapter.idAttribute || "id";
model.deletedAttribute = model.config.adapter.deletedAttribute || 'is_deleted';
// Debug mode
var DEBUG = opts.debug || model.config.debug;
// Are we dealing with a colleciton or a model?
var isCollection = ( model instanceof Backbone.Collection) ? true : false;
var singleModelRequest = null;
if (model.config.adapter.lastModifiedColumn) {
if (opts.sql && opts.sql.where) {
singleModelRequest = opts.sql.where[model.idAttribute];
}
if (!singleModelRequest && opts.data && opts.data[model.idAttribute]) {
singleModelRequest = opts.data[model.idAttribute];
}
}
var params = _.extend({}, opts);
// fill params with default values
_.defaults(params, {
// Last modified logic
lastModifiedColumn : model.config.adapter.lastModifiedColumn,
addModifedToUrl : model.config.adapter.addModifedToUrl,
lastModifiedDateFormat : model.config.adapter.lastModifiedDateFormat,
singleModelRequest : singleModelRequest,
// eTag
eTagEnabled : model.config.eTagEnabled,
// Used for custom parsing of the response data
parentNode : model.config.parentNode,
// Validate the response data and only allow those items with all columns defined in the object to be saved to the database.
useStrictValidation : model.config.useStrictValidation,
// before fethcing data from remote server - the adapter will return the stored data if enabled
initFetchWithLocalData : model.config.initFetchWithLocalData,
// If enabled - it will delete all the rows in the table on a successful fetch
deleteAllOnFetch : model.config.deleteAllOnFetch,
// If enabled - it will delete rows based a sql query on a successful fetch
deleteSQLOnFetch : model.config.deleteSQLOnFetch,
// Save data locally on server error?
disableSaveDataLocallyOnServerError : model.config.disableSaveDataLocallyOnServerError,
// Return the exact error reponse
returnErrorResponse : model.config.returnErrorResponse,
// Request params
requestparams : model.config.requestparams,
// xhr settings
timeout: 7000,
cache: false,
validatesSecureCertificate: ENV_PROD ? true : false
});
// REST API - set the type
var methodMap = {
'create' : 'POST',
'read' : 'GET',
'update' : 'PUT',
'delete' : 'DELETE'
};
var type = methodMap[method];
params.type = type;
// set default headers
params.headers = params.headers || {};
// process the runtime params
for (var header in params.headers) {
params.headers[header] = _.isFunction(params.headers[header]) ? params.headers[header]() : params.headers[header];
}
// Send our own custom headers
if (model.config.hasOwnProperty("headers")) {
for (var header in model.config.headers) {
// only process headers from model config if not provided through runtime params
if (!params.headers[header]) {
params.headers[header] = _.isFunction(model.config.headers[header]) ? model.config.headers[header]() : model.config.headers[header];
}
}
}
// We need to ensure that we have a base url.
if (!params.url) {
model.config.URL = _.isFunction(model.config.URL) ? model.config.URL() : model.config.URL;
params.url = (model.config.URL || model.url());
if (!params.url) {
Ti.API.error("[SQL REST API] ERROR: NO BASE URL");
return;
}
}
// Check if Last Modified is active
if (params.lastModifiedColumn && _.isUndefined(params.disableLastModified)) {
//send last modified model datestamp to the remote server
params.lastModifiedValue = null;
try {
params.lastModifiedValue = sqlLastModifiedItem();
} catch (e) {
logger(DEBUG, "LASTMOD SQL FAILED: ");
}
if (params.lastModifiedValue) {
params.headers['If-Modified-Since'] = params.lastModifiedValue;
}
}
// Extend the provided url params with those from the model config
if (_.isObject(params.urlparams) || model.config.URLPARAMS) {
if(_.isUndefined(params.urlparams)) {
params.urlparams = {};
}
_.extend(params.urlparams, _.isFunction(model.config.URLPARAMS) ? model.config.URLPARAMS() : model.config.URLPARAMS);
}
// parse url {requestparams}
_.each(params.requestparams, function(value,key) {
params.url = params.url.replace('{' + key + '}', value ? escape(value) : '', "gi");
});
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Alloy.Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.processData = true;
params.data = params.data ? {
model : params.data
} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Alloy.Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Alloy.Backbone.emulateJSON)
params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
params.headers['X-HTTP-Method-Override'] = type;
};
}
}
// json data transfers
params.headers['Content-Type'] = 'application/json';
logger(DEBUG, "REST METHOD: " + method);
switch (method) {
case 'create':
// convert to string for API call
params.data = JSON.stringify(model.toJSON());
logger(DEBUG, "create options", params);
apiCall(params, function(_response) {
if (_response.success) {
var data = parseJSON(_response, params.parentNode);
// Rest API should return a new model id.
resp = saveData(data);
_.isFunction(params.success) && params.success(resp);
} else {
// offline or error
// save data locally when server returned an error
if (!_response.localOnly && params.disableSaveDataLocallyOnServerError) {
logger(DEBUG, "NOTICE: The data is not being saved locally");
} else {
resp = saveData();
}
if (_.isUndefined(_response.offline)) {
// error
_.isFunction(params.error) && params.error( params.returnErrorResponse ? _response : resp);
} else {
//offline - still a data success
_.isFunction(params.success) && params.success(resp);
}
}
});
break;
case 'read':
if (!isCollection && model.id) {
// find model by id
params.url = params.url + '/' + model.id;
}
if (params.search) {
// search mode
params.returnExactServerResponse = true;
params.url = params.url + "/search/" + Ti.Network.encodeURIComponent(params.search);
}
if (params.urlparams) {
// build url with parameters
params.url = encodeData(params.urlparams, params.url);
}
// check is all the necessary info is in place for last modified
if (params.lastModifiedColumn && params.addModifedToUrl && params.lastModifiedValue) {
// add last modified date to url
var obj = {};
obj[params.lastModifiedColumn] = params.lastModifiedValue;
params.url = encodeData(obj, params.url);
}
if(!params.expireIn) {
params.expireIn = (model.config.expireIn || false);
}
if(params.expireIn) {
params.expireIn = parseInt(params.expireIn);
var date = new Date();
if(typeof model.expireTimes !== 'undefined' && (model.expireTimes != null && model.expireTimes!="")) {
var urlKey = Ti.Utils.base64encode(params.url);
var expire = model.expireTimes[urlKey];
logger(DEBUG, "expiration", expire);
if( expire > date.getTime() ) {
params.localOnly = true;
} else {
model.expireTimes[urlKey] = date.getTime()+params.expireIn;
}
} else {
model.expireTimes = {};
model.expireTimes[urlKey] = date.getTime()+params.expireIn;
}
}
logger(DEBUG, "read options", params);
if (!params.localOnly && params.initFetchWithLocalData) {
// read local data before receiving server data
resp = readSQL();
_.isFunction(params.success) && params.success(resp);
model.trigger("fetch", {
serverData : false
});
}
apiCall(params, function(_response) {
if (_response.success) {
if (_response.code != 304) {
// delete all rows
if (params.deleteAllOnFetch) {
deleteAllSQL();
}
// delete on sql query
if (params.deleteSQLOnFetch) {
deleteBasedOnSQL(params.deleteSQLOnFetch);
}
// parse data
var data = parseJSON(_response, params.parentNode);
if (!params.localOnly) {
//we dont want to manipulate the data on localOnly requests
saveData(data);
}
}
resp = readSQL(data);
_.isFunction(params.success) && params.success(resp);
model.trigger("fetch");
} else {
//error or offline - read local data
if (!params.localOnly && params.initFetchWithLocalData) {
} else {
resp = readSQL();
}
if (_.isUndefined(_response.offline)) {
//error
_.isFunction(params.error) && params.error( params.returnErrorResponse ? _response : resp);
} else {
//offline - still a data success
_.isFunction(params.success) && params.success(resp);
model.trigger("fetch");
}
}
});
break;
case 'update':
if (!model.id) {
params.error(null, "MISSING MODEL ID");
Ti.API.error("[SQL REST API] ERROR: MISSING MODEL ID");
return;
}
// setup the url & data
if (_.indexOf(params.url, "?") == -1) {
params.url = params.url + '/' + model.id;
} else {
var str = params.url.split("?");
params.url = str[0] + '/' + model.id + "?" + str[1];
}
if (params.urlparams) {
params.url = encodeData(params.urlparams, params.url);
}
params.data = JSON.stringify(model.toJSON());
logger(DEBUG, "update options", params);
apiCall(params, function(_response) {
if (_response.success) {
var data = parseJSON(_response, params.parentNode);
resp = saveData(data);
_.isFunction(params.success) && params.success(resp);
} else {
// error or offline - save & use local data
// save data locally when server returned an error
if (!_response.localOnly && params.disableSaveDataLocallyOnServerError) {
logger(DEBUG, "NOTICE: The data is not being saved locally");
} else {
resp = saveData();
}
if (_.isUndefined(_response.offline)) {
//error
_.isFunction(params.error) && params.error( params.returnErrorResponse ? _response : resp);
} else {
//offline - still a data success
_.isFunction(params.success) && params.success(resp);
}
}
});
break;
case 'delete':
if (!model.id) {
params.error(null, "MISSING MODEL ID");
Ti.API.error("[SQL REST API] ERROR: MISSING MODEL ID");
return;
}
params.url = params.url + '/' + model.id;
logger(DEBUG, "delete options", params);
apiCall(params, function(_response) {
if (_response.success) {
var data = parseJSON(_response, params.parentNode);
resp = deleteSQL();
_.isFunction(params.success) && params.success(resp);
} else {
// error or offline
// save data locally when server returned an error
if (!_response.localOnly && params.disableSaveDataLocallyOnServerError) {
logger(DEBUG, "NOTICE: The data is not being deleted locally");
} else {
resp = deleteSQL();
}
if (_.isUndefined(_response.offline)) {
//error
_.isFunction(params.error) && params.error( params.returnErrorResponse ? _response : resp);
} else {
//offline - still a data success
_.isFunction(params.success) && params.success(resp);
}
}
});
break;
}
/////////////////////////////////////////////
//SQL INTERFACE
/////////////////////////////////////////////
function saveData(data) {
if (!data && !isCollection) {
data = model.toJSON();
}
if (!data) {
// its empty
return;
}
if (!_.isArray(data)) {// its a model
if (!_.isUndefined(data[model.deletedAttribute]) && data[model.deletedAttribute] == true) {
//delete item
deleteSQL(data[model.idAttribute]);
} else if (sqlFindItem(data[model.idAttribute]).length == 1) {
//item exists - update it
return updateSQL(data);
} else {
//write data to local sql
return createSQL(data);
}
} else {//its an array of models
var currentModels = sqlCurrentModels();
for (var i in data) {
if (!_.isUndefined(data[i][model.deletedAttribute]) && data[i][model.deletedAttribute] == true) {
//delete item
deleteSQL(data[i][model.idAttribute]);
} else if (_.indexOf(currentModels, data[i][model.idAttribute]) != -1) {
//item exists - update it
updateSQL(data[i]);
} else {
//write data to local sql
createSQL(data[i]);
}
}
}
}
function createSQL(data) {
var attrObj = {};
logger(DEBUG, "createSQL data:", data);
if (data) {
attrObj = data;
} else {
if (!isCollection) {
attrObj = model.toJSON();
} else {
Ti.API.error("[SQL REST API] Its a collection - error !");
}
}
if (!attrObj[model.idAttribute]) {
if (model.idAttribute === ALLOY_ID_DEFAULT) {
// alloy-created GUID field
attrObj.id = guid();
attrObj[model.idAttribute] = attrObj.id;
} else {
// idAttribute not assigned by alloy. Leave it empty and
// allow sqlite to process as null, which is the
// expected value for an AUTOINCREMENT field.
attrObj[model.idAttribute] = null;
}
}
//validate the item
if (params.useStrictValidation) {
for (var c in columns) {
if (c == model.idAttribute) {
continue;
}
if (!_.contains(_.keys(attrObj), c)) {
Ti.API.error("[SQL REST API] ITEM NOT VALID - REASON: " + c + " is not present");
return;
}
}
}
// Create arrays for insert query
var names = [],
values = [],
q = [];
for (var k in columns) {
names.push(k);
if (_.isObject(attrObj[k])) {
values.push(JSON.stringify(attrObj[k]));
} else {
values.push(attrObj[k]);
}
q.push('?');
}
// Last Modified logic
if (params.lastModifiedColumn && _.isUndefined(params.disableLastModified)) {
values[_.indexOf(names, params.lastModifiedColumn)] = params.lastModifiedDateFormat ? moment().format(params.lastModifiedDateFormat) : moment().lang('en').zone('GMT').format('ddd, D MMM YYYY HH:mm:ss ZZ');
}
// Assemble create query
var sqlInsert = "INSERT INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");";
// execute the query and return the response
db = Ti.Database.open(dbName);
db.execute('BEGIN;');
db.execute(sqlInsert, values);
// get the last inserted id
if (model.id === null) {
var sqlId = "SELECT last_insert_rowid();";
var rs = db.execute(sqlId);
if (rs.isValidRow()) {
model.id = rs.field(0);
attrObj[model.idAttribute] = model.id;
} else {
Ti.API.warn('Unable to get ID from database for model: ' + model.toJSON());
}
}
db.execute('COMMIT;');
db.close();
return attrObj;
}
function readSQL(data) {
if (DEBUG) {
Ti.API.debug("[SQL REST API] readSQL");
logger(DEBUG, "\n******************************\nCollection total BEFORE read from db: " + model.length + " models\n******************************");
}
var sql = opts.query || 'SELECT * FROM ' + table;
// we want the exact server response returned by the adapter
if (params.returnExactServerResponse && data) {
opts.sql = opts.sql || {};
opts.sql.where = opts.sql.where || {};
if (_.isEmpty(data)) {
// No result
opts.sql.where[model.idAttribute] = "1=2";
} else {
// Find all idAttribute in the server response
var ids = [];
_.each(data, function(element) {
ids.push(element[model.idAttribute]);
});
// this will select IDs in the sql query
opts.sql.where[model.idAttribute] = ids;
}
}
// execute the select query
db = Ti.Database.open(dbName);
// run a specific sql query if defined
if (opts.query) {
if (opts.query.params) {
var rs = db.execute(opts.query.sql, opts.query.params);
} else {
var rs = db.execute(opts.query.sql);
}
} else {
//extend sql where with data
if (opts.data) {
opts.sql = opts.sql || {};
opts.sql.where = opts.sql.where || {};
_.extend(opts.sql.where, opts.data);
}
// build the sql query
var sql = _buildQuery(table, opts.sql || opts);
logger(DEBUG, "SQL QUERY: " + sql);
var rs = db.execute(sql);
}
var len = 0,
values = [];
// iterate through all queried rows
while (rs.isValidRow()) {
var o = {};
var fc = 0;
fc = _.isFunction(rs.fieldCount) ? rs.fieldCount() : rs.fieldCount;
// create list of rows returned from query
_.times(fc, function(c) {
var fn = rs.fieldName(c);
o[fn] = rs.fieldByName(fn);
});
values.push(o);
// Only push models if its a collection
// and not if we are using fetch({add:true})
if (isCollection && !params.add) {
//push the models
var m = new model.config.Model(o);
model.models.push(m);
}
len++;
rs.next();
}
// close off db after read query
rs.close();
db.close();
// shape response based on whether it's a model or collection
model.length = len;
logger(DEBUG, "\n******************************\n readSQL db read complete: " + len + " models \n******************************");
resp = len === 1 ? values[0] : values;
return resp;
}
function updateSQL(data) {
var attrObj = {};
logger(DEBUG, "updateSQL data: ", data);
if (data) {
attrObj = data;
} else {
if (!isCollection) {
attrObj = model.toJSON();
} else {
Ti.API.error("Its a collection - error!");
}
}
// Create arrays for insert query
var names = [],
values = [],
q = [];
for (var k in columns) {
if (!_.isUndefined(attrObj[k])) {//only update those who are in the data
names.push(k + '=?');
if (_.isObject(attrObj[k])) {
values.push(JSON.stringify(attrObj[k]));
} else {
values.push(attrObj[k]);
}
q.push('?');
}
}
if (params.lastModifiedColumn && _.isUndefined(params.disableLastModified)) {
values[_.indexOf(names, params.lastModifiedColumn + "=?")] = params.lastModifiedDateFormat ? moment().format(params.lastModifiedDateFormat) : moment().lang('en').zone('GMT').format('YYYY-MM-DD HH:mm:ss ZZ');
}
// compose the update query
var sql = 'UPDATE ' + table + ' SET ' + names.join(',') + ' WHERE ' + model.idAttribute + '=?';
values.push(attrObj[model.idAttribute]);
logger(DEBUG, "updateSQL sql query: " + sql);
logger(DEBUG, "updateSQL values: ", values);
// execute the update
db = Ti.Database.open(dbName);
db.execute(sql, values);
db.close();
return attrObj;
}
function deleteSQL(id) {
var sql = 'DELETE FROM ' + table + ' WHERE ' + model.idAttribute + '=?';
// execute the delete
db = Ti.Database.open(dbName);
db.execute(sql, id || model.id);
db.close();
model.id = null;
return model.toJSON();
}
function deleteAllSQL() {
var sql = 'DELETE FROM ' + table;
db = Ti.Database.open(dbName);
db.execute(sql);
db.close();
}
function deleteBasedOnSQL(obj) {
if (!_.isObject(obj)) {
Ti.API.error("[SQL REST API] deleteBasedOnSQL :: Error no object provided");
return;
}
var sql = _buildQuery(table, obj, "DELETE");
db = Ti.Database.open(dbName);
db.execute(sql);
db.close();
}
function sqlCurrentModels() {
var sql = 'SELECT ' + model.idAttribute + ' FROM ' + table;
db = Ti.Database.open(dbName);
var rs = db.execute(sql);
var output = [];
while (rs.isValidRow()) {
output.push(rs.fieldByName(model.idAttribute));
rs.next();
}
rs.close();
db.close();
return output;
}
function sqlFindItem(_id) {
if (_.isUndefined(_id)) {
return [];
}
var sql = 'SELECT ' + model.idAttribute + ' FROM ' + table + ' WHERE ' + model.idAttribute + '=?';
db = Ti.Database.open(dbName);
var rs = db.execute(sql, _id);
var output = [];
while (rs.isValidRow()) {
output.push(rs.fieldByName(model.idAttribute));
rs.next();
}
rs.close();
db.close();
return output;
}
function sqlLastModifiedItem() {
if (params.singleModelRequest || !isCollection) {
//model
var sql = 'SELECT ' + params.lastModifiedColumn + ' FROM ' + table + ' WHERE ' + params.lastModifiedColumn + ' IS NOT NULL AND ' + model.idAttribute + '=' + params.singleModelRequest + ' ORDER BY ' + params.lastModifiedColumn + ' DESC LIMIT 0,1';
} else {
//collection
var sql = 'SELECT ' + params.lastModifiedColumn + ' FROM ' + table + ' WHERE ' + params.lastModifiedColumn + ' IS NOT NULL ORDER BY ' + params.lastModifiedColumn + ' DESC LIMIT 0,1';
}
db = Ti.Database.open(dbName);
rs = db.execute(sql);
var output = null;
if (rs.isValidRow()) {
output = rs.field(0);
}
rs.close();
db.close();
return output;
}
function parseJSON(_response, parentNode) {
var data = _response.responseJSON;
if (!_.isUndefined(parentNode)) {
data = _.isFunction(parentNode) ? parentNode(data) : traverseProperties(data, parentNode);
}
logger(DEBUG, "server response: ", data);
return data;
}
}
/////////////////////////////////////////////
// SQL HELPERS
/////////////////////////////////////////////