forked from MarrLiss/backbone-websql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackbone-websql.js
363 lines (302 loc) · 11.4 KB
/
backbone-websql.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
(function(root) {
var factory = (function(Backbone, _) {
// ====== [UTILS] ======
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
// ====== [ WebSQLStore ] ======
var WebSQLStore = function(db, tableName, columns, initSuccessCallback, initErrorCallback) {
// make columns optional for backwards compatibility w/ original API
if ( typeof columns == 'function') {
initErrorCallback = initSuccessCallback;
initSuccessCallback = columns;
columns = null;
}
this.tableName = tableName;
this.db = db;
this.columns = columns || [];
if (! _.find(this.columns, function(item){return item.name === "id"})){
this.columns.push({
name: 'id',
type: 'string',
unique: true
});
}
var success = function(tx, res) {
if (initSuccessCallback)
initSuccessCallback();
};
var error = function(tx, error) {
console.error("Error while create table", error);
if (initErrorCallback)
initErrorCallback();
};
var colDefns = [];
colDefns = colDefns.concat(this.columns.map(createColDefn));
this._executeSql("CREATE TABLE IF NOT EXISTS `" + tableName + "` (" + colDefns.join(", ") + ");", null, success, error, {});
};
WebSQLStore.debug = false;
WebSQLStore.insertOrReplace = false;
_.extend(WebSQLStore.prototype, {
create : function(model, success, error, options) {
//when you want use your id as identifier, use apiid attribute
if (!model.attributes[model.idAttribute]) {
// Reference model.attributes.apiid for backward compatibility.
var obj = {};
if (model.attributes.apiid) {
obj[model.idAttribute] = model.attributes.apiid;
delete model.attributes.apiid;
} else {
obj[model.idAttribute] = guid();
}
model.set(obj);
}
var colNames = [];
var placeholders = [];
var params = [];
_.each(this.columns, function(col){
colNames.push("`" + col.name + "`");
placeholders.push(['?']);
params.push(model.attributes[col.name]);
});
var orReplace = WebSQLStore.insertOrReplace ? ' OR REPLACE' : '';
this._executeSql("INSERT" + orReplace + " INTO `" + this.tableName + "`(" + colNames.join(",") + ") VALUES(" + placeholders.join(",") + ");", params, success, error, options);
},
update : function(model, success, error, options) {
if (WebSQLStore.insertOrReplace)
return this.create(model, success, error, options);
var modelKeys = _.map(model.attributes, function(value, key){return key;});
var columnsKeys = this._listOfColumns();
var news =_.difference(modelKeys, columnsKeys);
var SQLs = [];
if (news.length != 0){
for (var i=0; i < news.length; i++) {
this.columns.push({
name: news[i],
type: 'string'
});
SQLs.push({
SQL : "ALTER TABLE `" + this.tableName + "` ADD COLUMN `" + news[i] + "` TEXT;" //TEXT by default
});
};
}
var setStmts = [];
var params = [];
_.each(this.columns, function(col) {
if (col.name === model.idAttribute){ //we do not update the `id` attribute
return;
}
var data = model.attributes[col.name];
if (typeof data !== "undefined") { //we do not update if the value of a field is undefined
setStmts.push("`" + col.name + "`=?");
params.push(data);
}
});
params.push(model.attributes[model.idAttribute]);//We compare with the `id` in the WHERE clausule
SQLs.push({
SQL: "UPDATE `" + this.tableName + "` SET " + setStmts.join(" , ") + " WHERE(`"+ model.idAttribute +"`=?);",
params: params,
successCallback: function(tx, result) {
if (result.rowsAffected == 1)
success(tx, result);
else
error(tx, new Error('UPDATE affected ' + result.rowsAffected + ' rows'));
},
error: error
});
this._executeSqlBulk(SQLs, null, options);
},
destroy : function(model, success, error, options) {
var id = (model.attributes[model.idAttribute] || model.attributes.id);
this._executeSql("DELETE FROM `" + this.tableName + "` WHERE(`" + model.idAttribute + "`=?);", [id], success, error, options);
},
find : function(model, success, error, options) {
var id = (model.attributes[model.idAttribute] || model.attributes.id);
this._executeSql("SELECT " + this._listOfColumns().join(", ") + " FROM `" + this.tableName + "` WHERE(`" + model.idAttribute + "`=?);", [id], success, error, options);
},
findAll : function(model, success, error, options) {
var params = [];
var sql = "SELECT " + this._listOfColumns().join(", ") + " FROM `" + this.tableName + "`";
if (options.filters) {
if ( typeof options.filters == 'string') {
sql += ' WHERE ' + options.filters;
} else if ( typeof options.filters == 'object') {
sql += ' WHERE ' + Object.keys(options.filters).map(function(col) {
params.push(options.filters[col]);
return '`' + col + '` = ?';
}).join(' AND ');
} else {
throw new Error('Unsupported filters type: ' + typeof options.filters);
}
}
this._executeSql(sql, params, success, error, options);
},
_listOfColumns: function(){
return _.map(this.columns, function(value){return value.name;});
},
_executeSql : function(SQL, params, successCallback, errorCallback, options) {
var success = function(tx, result) {
if (WebSQLStore.debug) {
console.log(SQL, params, " - finished");
}
if (successCallback)
successCallback(tx, result);
};
var error = function(tx, error) {
if (WebSQLStore.debug) {
console.error(SQL, params, " - error: " + error)
};
if (errorCallback)
return errorCallback(tx, error);
};
if (options.transaction) {
options.transaction.executeSql(SQL, params, success, error);
} else {
this.db.transaction(function(tx) {
tx.executeSql(SQL, params, success, error);
});
}
},
/**
* Execute a list of SQL statment in the same transaction in order.
*
* @param {Object} SQLs array of {SQL, params, successCallback, errorCallback} objects
* @param {function} endCallback callback when the last statment finishes
* @param {Object} options might contain an existing transaction
*/
_executeSqlBulk : function(SQLs, endCallback, options) {
var iterateSQL = function(transaction) {
for (var i = 0; i < SQLs.length; i++) {
var SQL = SQLs[i].SQL;
var params = SQLs[i].params;
var successCallback = SQLs[i].successCallback;
var errorCallback = SQLs[i].errorCallback;
var success;
if (endCallback && (i == SQLs.length - 1)){
success = function(cbk, endCbk) {
return function(tx, result) {
if (cbk)
cbk(tx, result);
endCbk();
}
}(successCallback, endCallback);
}else{
success = function(cbk) {
return function(tx, result) {
if (cbk)
cbk(tx, result);
}
}(successCallback);
}
var error = function(cbk) {
return function(tx, error) {
if (cbk)
cbk(tx, error);
}
}(errorCallback);
transaction.executeSql(SQL, params, success, error);
};
};
if (options && options.transaction) {
iterateSQL(options.transaction);
} else {
this.db.transaction(function(tx) {
iterateSQL(tx);
});
}
}
});
// ====== [ Backbone.sync WebSQL implementation ] ======
Backbone.sync = function(method, model, options) {
var success, error, store = model.getStore() || model.collection.getStore();
if (store == null) {
console.warn("[BACKBONE-WEBSQL] model without store object -> ", model);
return;
}
var isSingleResult = false;
success = function(tx, res) {
var len = res.rows.length, result;
if (len > 0) {
var parseResult = function(item){
var obj = {};
_.each(item, function(val, key) {
obj[key] = val;
});
return obj;
};
if (isSingleResult) {
result = parseResult(res.rows.item(0));
} else {
result = [];
var i;
for ( i = 0; i < len; i++) {
result.push(parseResult(res.rows.item(i)));
}
}
}
options.success(result);
};
error = function(tx, error) {
console.error("sql error");
console.error(error.message);
};
switch(method) {
case "read":
if (model.attributes && model.attributes[model.idAttribute]) {
isSingleResult = true;
store.find(model, success, error, options)
} else {
store.findAll(model, success, error, options)
}
break;
case "create":
store.create(model, success, error, options);
break;
case "update":
store.update(model, success, error, options);
break;
case "delete":
store.destroy(model, success, error, options);
break;
default:
console.error(method);
}
};
var typeMap = {
"number": "INTEGER",
"string": "TEXT",
"boolean": "BOOLEAN",
"array": "LIST",
"datetime": "TEXT",
"date": "TEXT",
"object": "TEXT"
};
function createColDefn(col) {
if (col.type && !(col.type in typeMap))
throw new Error("Unsupported type: " + col.type);
var defn = "`" + col.name + "`";
if (col.type) {
if (col.scale)
defn += " REAL";
else
defn += " " + typeMap[col.type];
}
if (col.unique){
defn += ' UNIQUE';
}
return defn;
}
return WebSQLStore
})
if ( typeof exports !== 'undefined') {
factory(require('Backbone'), require('underscore'));
} else if ( typeof define === 'function' && define.amd) {
define(['Backbone', 'underscore'], factory);
} else {
root.WebSQLStore = factory(root.Backbone, root._)
}
})(this)