]>
Commit | Line | Data |
---|---|---|
6527f429 DM |
1 | /**\r |
2 | * SQL proxy lets you store data in a SQL database.\r | |
3 | * The Sencha Touch SQL proxy outputs model data into an HTML5\r | |
4 | * local database using WebSQL.\r | |
5 | *\r | |
6 | * You can create a Store for the proxy, for example:\r | |
7 | *\r | |
8 | * Ext.require(["Ext.data.proxy.SQL"]);\r | |
9 | *\r | |
10 | * Ext.define("User", {\r | |
11 | * extend: "Ext.data.Model",\r | |
12 | * config: {\r | |
13 | * fields: [ "firstName", "lastName" ]\r | |
14 | * }\r | |
15 | * });\r | |
16 | *\r | |
17 | * Ext.create("Ext.data.Store", {\r | |
18 | * model: "User",\r | |
19 | * storeId: "Users",\r | |
20 | * proxy: {\r | |
21 | * type: "sql"\r | |
22 | * }\r | |
23 | * });\r | |
24 | *\r | |
25 | * Ext.getStore("Users").add({\r | |
26 | * firstName: "Polly",\r | |
27 | * lastName: "Hedra"\r | |
28 | * });\r | |
29 | *\r | |
30 | * Ext.getStore("Users").sync();\r | |
31 | *\r | |
32 | * To destroy a table use:\r | |
33 | *\r | |
34 | * Ext.getStore("Users").getProxy().dropTable();\r | |
35 | *\r | |
36 | * To recreate a table use:\r | |
37 | *\r | |
38 | * Ext.data.Store.sync() or Ext.data.Model.save()\r | |
39 | */\r | |
40 | Ext.define('Ext.data.proxy.Sql', {\r | |
41 | alias: 'proxy.sql',\r | |
42 | extend: 'Ext.data.proxy.Client',\r | |
43 | alternateClassName: 'Ext.data.proxy.SQL',\r | |
44 | \r | |
45 | isSQLProxy: true,\r | |
46 | \r | |
47 | config: {\r | |
48 | /**\r | |
49 | * @cfg {Object} reader\r | |
50 | * @hide\r | |
51 | */\r | |
52 | reader: null,\r | |
53 | /**\r | |
54 | * @cfg {Object} writer\r | |
55 | * @hide\r | |
56 | */\r | |
57 | writer: null,\r | |
58 | /**\r | |
59 | * @cfg {String} table\r | |
60 | * Optional Table name to use if not provided ModelName will be used\r | |
61 | */\r | |
62 | table: null,\r | |
63 | /**\r | |
64 | * @cfg {String} database\r | |
65 | * Database name to access tables from\r | |
66 | */\r | |
67 | database: 'Sencha'\r | |
68 | },\r | |
69 | \r | |
70 | _createOptions: {\r | |
71 | silent: true,\r | |
72 | dirty: false\r | |
73 | },\r | |
74 | \r | |
75 | updateModel: function(model) {\r | |
76 | var me = this,\r | |
77 | modelName,\r | |
78 | len, i, columns, quoted;\r | |
79 | \r | |
80 | if (model) {\r | |
81 | me.uniqueIdStrategy = model.identifier.isUnique;\r | |
82 | if (!me.getTable()) {\r | |
83 | modelName = model.entityName;\r | |
84 | me.setTable(modelName.slice(modelName.lastIndexOf('.') + 1));\r | |
85 | }\r | |
86 | me.columns = columns = me.getPersistedModelColumns(model);\r | |
87 | me.quotedColumns = quoted = [];\r | |
88 | for (i = 0, len = columns.length; i < len; ++i) {\r | |
89 | quoted.push('"' + columns[i] + '"');\r | |
90 | }\r | |
91 | }\r | |
92 | \r | |
93 | me.callParent([model]);\r | |
94 | },\r | |
95 | \r | |
96 | setException: function(operation, error) {\r | |
97 | operation.setException(error);\r | |
98 | },\r | |
99 | \r | |
100 | create: function (operation) {\r | |
101 | var me = this,\r | |
102 | records = operation.getRecords(),\r | |
103 | result, error;\r | |
104 | \r | |
105 | operation.setStarted();\r | |
106 | \r | |
107 | me.executeTransaction(function(transaction) {\r | |
108 | me.insertRecords(records, transaction, function (resultSet, statementError) {\r | |
109 | result = resultSet;\r | |
110 | error = statementError;\r | |
111 | });\r | |
112 | }, function(transactionError) {\r | |
113 | operation.setException(transactionError);\r | |
114 | }, function() {\r | |
115 | if (error) {\r | |
116 | operation.setException(statementError);\r | |
117 | } else {\r | |
118 | operation.process(result);\r | |
119 | }\r | |
120 | });\r | |
121 | },\r | |
122 | \r | |
123 | read: function(operation) {\r | |
124 | var me = this,\r | |
125 | model = me.getModel(),\r | |
126 | records = operation.getRecords(),\r | |
127 | record = records ? records[0] : null,\r | |
128 | result, error, id, params;\r | |
129 | \r | |
130 | if (record && !record.phantom) {\r | |
131 | id = record.getId();\r | |
132 | } else {\r | |
133 | id = operation.getId();\r | |
134 | }\r | |
135 | \r | |
136 | if (id !== undefined) {\r | |
137 | params = {\r | |
138 | idOnly: true,\r | |
139 | id: id\r | |
140 | }\r | |
141 | } else {\r | |
142 | params = {\r | |
143 | page: operation.getPage(),\r | |
144 | start: operation.getStart(),\r | |
145 | limit: operation.getLimit(),\r | |
146 | sorters: operation.getSorters(),\r | |
147 | filters: operation.getFilters()\r | |
148 | };\r | |
149 | }\r | |
150 | \r | |
151 | operation.setStarted();\r | |
152 | \r | |
153 | me.executeTransaction(function(transaction) {\r | |
154 | me.selectRecords(transaction, params, function (resultSet, statementError) {\r | |
155 | result = resultSet;\r | |
156 | error = statementError;\r | |
157 | });\r | |
158 | }, function(transactionError) {\r | |
159 | operation.setException(transactionError);\r | |
160 | }, function() {\r | |
161 | if (error) {\r | |
162 | operation.setException(statementError);\r | |
163 | } else {\r | |
164 | operation.process(result);\r | |
165 | }\r | |
166 | });\r | |
167 | },\r | |
168 | \r | |
169 | update: function(operation) {\r | |
170 | var me = this,\r | |
171 | records = operation.getRecords(),\r | |
172 | result, error;\r | |
173 | \r | |
174 | operation.setStarted();\r | |
175 | \r | |
176 | me.executeTransaction(function(transaction) {\r | |
177 | me.updateRecords(transaction, records, function (resultSet, statementError) {\r | |
178 | result = resultSet;\r | |
179 | error = statementError;\r | |
180 | });\r | |
181 | }, function(transactionError) {\r | |
182 | operation.setException(transactionError);\r | |
183 | }, function() {\r | |
184 | if (error) {\r | |
185 | operation.setException(statementError);\r | |
186 | } else {\r | |
187 | operation.process(result);\r | |
188 | }\r | |
189 | });\r | |
190 | },\r | |
191 | \r | |
192 | erase: function(operation) {\r | |
193 | var me = this,\r | |
194 | records = operation.getRecords(),\r | |
195 | result, error;\r | |
196 | \r | |
197 | operation.setStarted();\r | |
198 | \r | |
199 | me.executeTransaction(function(transaction) {\r | |
200 | me.destroyRecords(transaction, records, function(resultSet, statementError) {\r | |
201 | result = resultSet;\r | |
202 | error = statementError;\r | |
203 | });\r | |
204 | }, function(transactionError) {\r | |
205 | operation.setException(transactionError);\r | |
206 | }, function() {\r | |
207 | if (error) {\r | |
208 | operation.setException(error);\r | |
209 | } else {\r | |
210 | operation.process(result);\r | |
211 | }\r | |
212 | });\r | |
213 | },\r | |
214 | \r | |
215 | createTable: function (transaction) {\r | |
216 | var me = this;\r | |
217 | if (!transaction) {\r | |
218 | me.executeTransaction(function(transaction) {\r | |
219 | me.createTable(transaction);\r | |
220 | });\r | |
221 | return;\r | |
222 | }\r | |
223 | me.executeStatement(transaction, 'CREATE TABLE IF NOT EXISTS "' + me.getTable() + '" (' + me.getSchemaString() + ')', function() {\r | |
224 | me.tableExists = true;\r | |
225 | });\r | |
226 | },\r | |
227 | \r | |
228 | insertRecords: function(records, transaction, callback) {\r | |
229 | var me = this,\r | |
230 | columns = me.columns,\r | |
231 | totalRecords = records.length,\r | |
232 | executed = 0,\r | |
233 | uniqueIdStrategy = me.uniqueIdStrategy,\r | |
234 | setOptions = me._createOptions,\r | |
235 | len = records.length,\r | |
236 | i, record, placeholders, sql, data, values, errors, completeIf;\r | |
237 | \r | |
238 | completeIf = function(transaction) {\r | |
239 | ++executed;\r | |
240 | if (executed === totalRecords) {\r | |
241 | callback.call(me, new Ext.data.ResultSet({\r | |
242 | success: !errors\r | |
243 | }), errors);\r | |
244 | }\r | |
245 | };\r | |
246 | placeholders = Ext.String.repeat('?', columns.length, ',');\r | |
247 | sql = 'INSERT INTO "' + me.getTable() + '" (' + me.quotedColumns.join(',') + ') VALUES (' + placeholders + ')';\r | |
248 | \r | |
249 | for (i = 0; i < len; ++i) {\r | |
250 | record = records[i];\r | |
251 | data = me.getRecordData(record);\r | |
252 | values = me.getColumnValues(columns, data);\r | |
253 | \r | |
254 | // Capture the record in closure scope so we can access it later\r | |
255 | (function(record) {\r | |
256 | me.executeStatement(transaction, sql, values, function(transaction, resultSet) {\r | |
257 | if (!uniqueIdStrategy) {\r | |
258 | record.setId(resultSet.insertId, setOptions);\r | |
259 | }\r | |
260 | completeIf();\r | |
261 | }, function(transaction, error) {\r | |
262 | if (!errors) {\r | |
263 | errors = [];\r | |
264 | }\r | |
265 | errors.push(error);\r | |
266 | completeIf();\r | |
267 | });\r | |
268 | })(record);\r | |
269 | }\r | |
270 | },\r | |
271 | \r | |
272 | selectRecords: function(transaction, params, callback, scope) {\r | |
273 | var me = this,\r | |
274 | Model = me.getModel(),\r | |
275 | idProperty = Model.idProperty,\r | |
276 | sql = 'SELECT * FROM "' + me.getTable() + '"',\r | |
277 | filterStatement = ' WHERE ',\r | |
278 | sortStatement = ' ORDER BY ',\r | |
279 | values = [],\r | |
280 | sorters, filters, placeholder,\r | |
281 | i, len, result, filter, sorter, property, operator, value;\r | |
282 | \r | |
283 | if (params.idOnly) {\r | |
284 | sql += filterStatement + '"' + idProperty + '" = ?';\r | |
285 | values.push(params);\r | |
286 | } else {\r | |
287 | filters = params.filters;\r | |
288 | len = filters && filters.length;\r | |
289 | if (len) {\r | |
290 | for (i = 0; i < len; i++) {\r | |
291 | filter = filters[i];\r | |
292 | property = filter.getProperty();\r | |
293 | value = me.toSqlValue(filter.getValue(), Model.getField(property));\r | |
294 | operator = filter.getOperator();\r | |
295 | if (property !== null) {\r | |
296 | operator = operator || '=';\r | |
297 | placeholder = '?';\r | |
298 | if (operator === 'like' || (operator === '=' && filter.getAnyMatch())) {\r | |
299 | operator = 'LIKE';\r | |
300 | value = '%' + value + '%';\r | |
301 | }\r | |
302 | \r | |
303 | if (operator === 'in' || operator === 'notin') {\r | |
304 | if (operator === 'notin') {\r | |
305 | operator = 'not in';\r | |
306 | }\r | |
307 | placeholder = '(' + Ext.String.repeat('?', value.length, ',') + ')';\r | |
308 | values = values.concat(value);\r | |
309 | } else {\r | |
310 | values.push(value);\r | |
311 | }\r | |
312 | sql += filterStatement + '"' + property + '" ' + operator + ' ' + placeholder;\r | |
313 | filterStatement = ' AND ';\r | |
314 | }\r | |
315 | }\r | |
316 | }\r | |
317 | \r | |
318 | sorters = params.sorters;\r | |
319 | len = sorters && sorters.length;\r | |
320 | if (len) {\r | |
321 | for (i = 0; i < len; i++) {\r | |
322 | sorter = sorters[i];\r | |
323 | property = sorter.getProperty();\r | |
324 | if (property !== null) {\r | |
325 | sql += sortStatement + '"' + property + '" ' + sorter.getDirection();\r | |
326 | sortStatement = ', ';\r | |
327 | }\r | |
328 | }\r | |
329 | }\r | |
330 | \r | |
331 | // handle start, limit, sort, filter and group params\r | |
332 | if (params.page !== undefined) {\r | |
333 | sql += ' LIMIT ' + parseInt(params.start, 10) + ', ' + parseInt(params.limit, 10);\r | |
334 | }\r | |
335 | }\r | |
336 | \r | |
337 | me.executeStatement(transaction, sql, values, function(transaction, resultSet) {\r | |
338 | var rows = resultSet.rows,\r | |
339 | count = rows.length,\r | |
340 | records = [],\r | |
341 | fields = Model.fields,\r | |
342 | fieldsLen = fields.length,\r | |
343 | raw, data, i, len, j, field, name;\r | |
344 | \r | |
345 | for (i = 0, len = count; i < len; ++i) {\r | |
346 | raw = rows.item(i);\r | |
347 | data = {};\r | |
348 | for (j = 0; j < fieldsLen; ++j) {\r | |
349 | field = fields[j];\r | |
350 | name = field.name;\r | |
351 | data[name] = me.fromSqlValue(raw[name], field);\r | |
352 | }\r | |
353 | records.push(new Model(data));\r | |
354 | }\r | |
355 | \r | |
356 | callback.call(me, new Ext.data.ResultSet({\r | |
357 | records: records,\r | |
358 | success: true,\r | |
359 | total: count,\r | |
360 | count: count\r | |
361 | }));\r | |
362 | }, function(transaction, error) {\r | |
363 | callback.call(me, new Ext.data.ResultSet({\r | |
364 | success: false,\r | |
365 | total: 0,\r | |
366 | count: 0\r | |
367 | }), error);\r | |
368 | });\r | |
369 | },\r | |
370 | \r | |
371 | updateRecords: function (transaction, records, callback) {\r | |
372 | var me = this,\r | |
373 | columns = me.columns,\r | |
374 | quotedColumns = me.quotedColumns,\r | |
375 | totalRecords = records.length,\r | |
376 | executed = 0,\r | |
377 | updates = [],\r | |
378 | setOptions = me._createOptions,\r | |
379 | len, i, record, placeholders, sql, data, values, errors, completeIf;\r | |
380 | \r | |
381 | completeIf = function(transaction) {\r | |
382 | ++executed;\r | |
383 | if (executed === totalRecords) {\r | |
384 | callback.call(me, new Ext.data.ResultSet({\r | |
385 | success: !errors\r | |
386 | }), errors);\r | |
387 | }\r | |
388 | };\r | |
389 | \r | |
390 | for (i = 0, len = quotedColumns.length; i < len; i++) {\r | |
391 | updates.push(quotedColumns[i] + ' = ?');\r | |
392 | }\r | |
393 | \r | |
394 | sql = 'UPDATE "' + me.getTable() + '" SET ' + updates.join(', ') + ' WHERE "' + me.getModel().idProperty + '" = ?';\r | |
395 | \r | |
396 | for (i = 0, len = records.length; i < len; ++i) {\r | |
397 | record = records[i];\r | |
398 | data = me.getRecordData(record);\r | |
399 | values = me.getColumnValues(columns, data);\r | |
400 | values.push(record.getId());\r | |
401 | \r | |
402 | // Capture the record in closure scope so we can access it later\r | |
403 | (function(record) {\r | |
404 | me.executeStatement(transaction, sql, values, function(transaction, resultSet) {\r | |
405 | completeIf();\r | |
406 | }, function(transaction, error) {\r | |
407 | if (!errors) {\r | |
408 | errors = [];\r | |
409 | }\r | |
410 | errors.push(error);\r | |
411 | completeIf();\r | |
412 | });\r | |
413 | })(record);\r | |
414 | }\r | |
415 | },\r | |
416 | \r | |
417 | destroyRecords: function (transaction, records, callback) {\r | |
418 | var me = this,\r | |
419 | table = me.getTable(),\r | |
420 | idProperty = me.getModel().idProperty,\r | |
421 | ids = [],\r | |
422 | values = [],\r | |
423 | destroyedRecords = [],\r | |
424 | len = records.length,\r | |
425 | idStr = '"' + idProperty + '" = ?',\r | |
426 | i, result, record, sql;\r | |
427 | \r | |
428 | for (i = 0; i < len; i++) {\r | |
429 | ids.push(idStr);\r | |
430 | values.push(records[i].getId());\r | |
431 | }\r | |
432 | \r | |
433 | sql = 'DELETE FROM "' + me.getTable() + '" WHERE ' + ids.join(' OR ');\r | |
434 | \r | |
435 | me.executeStatement(transaction, sql, values, function (transaction, resultSet) {\r | |
436 | callback.call(me, new Ext.data.ResultSet({\r | |
437 | success: true\r | |
438 | }));\r | |
439 | }, function (transaction, error) {\r | |
440 | callback.call(me, new Ext.data.ResultSet({\r | |
441 | success: false\r | |
442 | }), error);\r | |
443 | });\r | |
444 | },\r | |
445 | \r | |
446 | /**\r | |
447 | * Formats the data for each record before sending it to the server. This\r | |
448 | * method should be overridden to format the data in a way that differs from the default.\r | |
449 | * @param {Object} record The record that we are writing to the server.\r | |
450 | * @return {Object} An object literal of name/value keys to be written to the server.\r | |
451 | * By default this method returns the data property on the record.\r | |
452 | */\r | |
453 | getRecordData: function (record) {\r | |
454 | var me = this,\r | |
455 | fields = record.fields,\r | |
456 | idProperty = record.idProperty,\r | |
457 | uniqueIdStrategy = me.uniqueIdStrategy,\r | |
458 | data = {},\r | |
459 | len = fields.length,\r | |
460 | recordData = record.data,\r | |
461 | i, name, value, field;\r | |
462 | \r | |
463 | for (i = 0; i < len; ++i) {\r | |
464 | field = fields[i];\r | |
465 | if (field.persist !== false) {\r | |
466 | name = field.name;\r | |
467 | if (name === idProperty && !uniqueIdStrategy) {\r | |
468 | continue;\r | |
469 | }\r | |
470 | data[name] = me.toSqlValue(recordData[name], field);\r | |
471 | }\r | |
472 | }\r | |
473 | \r | |
474 | return data;\r | |
475 | },\r | |
476 | \r | |
477 | getColumnValues: function(columns, data) {\r | |
478 | var len = columns.length,\r | |
479 | values = [],\r | |
480 | i, column, value;\r | |
481 | \r | |
482 | for (i = 0; i < len; i++) {\r | |
483 | column = columns[i];\r | |
484 | value = data[column];\r | |
485 | if (value !== undefined) {\r | |
486 | values.push(value);\r | |
487 | }\r | |
488 | }\r | |
489 | \r | |
490 | return values;\r | |
491 | },\r | |
492 | \r | |
493 | getSchemaString: function() {\r | |
494 | var me = this,\r | |
495 | schema = [],\r | |
496 | model = me.getModel(),\r | |
497 | idProperty = model.idProperty,\r | |
498 | fields = model.fields,\r | |
499 | uniqueIdStrategy = me.uniqueIdStrategy,\r | |
500 | len = fields.length,\r | |
501 | i, field, type, name;\r | |
502 | \r | |
503 | for (i = 0; i < len; i++) {\r | |
504 | field = fields[i];\r | |
505 | type = field.getType();\r | |
506 | name = field.name;\r | |
507 | \r | |
508 | if (name === idProperty) {\r | |
509 | if (uniqueIdStrategy) {\r | |
510 | type = me.convertToSqlType(type);\r | |
511 | schema.unshift('"' + idProperty + '" ' + type);\r | |
512 | } else {\r | |
513 | schema.unshift('"' + idProperty + '" INTEGER PRIMARY KEY AUTOINCREMENT');\r | |
514 | }\r | |
515 | } else {\r | |
516 | type = me.convertToSqlType(type);\r | |
517 | schema.push('"' + name + '" ' + type);\r | |
518 | }\r | |
519 | }\r | |
520 | \r | |
521 | return schema.join(', ');\r | |
522 | },\r | |
523 | \r | |
524 | convertToSqlType: function(type) {\r | |
525 | switch (type.toLowerCase()) {\r | |
526 | case 'string':\r | |
527 | case 'auto':\r | |
528 | return 'TEXT';\r | |
529 | case 'int':\r | |
530 | case 'date':\r | |
531 | return 'INTEGER';\r | |
532 | case 'float':\r | |
533 | return 'REAL';\r | |
534 | case 'bool':\r | |
535 | return 'NUMERIC';\r | |
536 | }\r | |
537 | },\r | |
538 | \r | |
539 | dropTable: function() {\r | |
540 | var me = this;\r | |
541 | \r | |
542 | me.executeTransaction(function(transaction) {\r | |
543 | me.executeStatement(transaction, 'DROP TABLE "' + me.getTable() + '"', function() {\r | |
544 | me.tableExists = false;\r | |
545 | });\r | |
546 | }, null, null, false);\r | |
547 | },\r | |
548 | \r | |
549 | getDatabaseObject: function() {\r | |
550 | return window.openDatabase(this.getDatabase(), '1.0', 'Sencha Database', 5 * 1024 * 1024);\r | |
551 | },\r | |
552 | \r | |
553 | privates: {\r | |
554 | executeStatement: function(transaction, sql, values, success, failure) {\r | |
555 | var me = this;\r | |
556 | transaction.executeSql(sql, values, success ? function() {\r | |
557 | success.apply(me, arguments);\r | |
558 | } : null, failure ? function() {\r | |
559 | failure.apply(me, arguments);\r | |
560 | } : null);\r | |
561 | },\r | |
562 | \r | |
563 | executeTransaction: function(runner, failure, success, autoCreateTable) {\r | |
564 | var me = this;\r | |
565 | \r | |
566 | autoCreateTable = autoCreateTable !== false;\r | |
567 | \r | |
568 | me.getDatabaseObject().transaction(runner ? function(transaction) {\r | |
569 | if (autoCreateTable && !me.tableExists) {\r | |
570 | me.createTable(transaction);\r | |
571 | }\r | |
572 | runner.apply(me, arguments);\r | |
573 | } : null, failure ? function() {\r | |
574 | failure.apply(me, arguments);\r | |
575 | } : null, success ? function() {\r | |
576 | success.apply(me, arguments);\r | |
577 | } : null);\r | |
578 | },\r | |
579 | \r | |
580 | fromSqlValue: function(value, field) {\r | |
581 | if (field.isDateField) {\r | |
582 | value = value ? new Date(value) : null;\r | |
583 | } else if (field.isBooleanField) {\r | |
584 | value = value === 1;\r | |
585 | }\r | |
586 | return value;\r | |
587 | },\r | |
588 | \r | |
589 | getPersistedModelColumns: function(model) {\r | |
590 | var fields = model.fields,\r | |
591 | uniqueIdStrategy = this.uniqueIdStrategy,\r | |
592 | idProperty = model.idProperty,\r | |
593 | columns = [],\r | |
594 | len = fields.length,\r | |
595 | i, field, name;\r | |
596 | \r | |
597 | for (i = 0; i < len; ++i) {\r | |
598 | field = fields[i];\r | |
599 | name = field.name;\r | |
600 | \r | |
601 | if (name === idProperty && !uniqueIdStrategy) {\r | |
602 | continue;\r | |
603 | }\r | |
604 | \r | |
605 | if (field.persist !== false) {\r | |
606 | columns.push(field.name);\r | |
607 | }\r | |
608 | }\r | |
609 | return columns;\r | |
610 | },\r | |
611 | \r | |
612 | toSqlValue: function(value, field) {\r | |
613 | if (field.isDateField) {\r | |
614 | value = value ? value.getTime() : null;\r | |
615 | } else if (field.isBooleanField) {\r | |
616 | value = value ? 1 : 0;\r | |
617 | }\r | |
618 | return value;\r | |
619 | }\r | |
620 | }\r | |
621 | }); |