123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556 |
- /**
- * SQL proxy lets you store data in a SQL database.
- * The Sencha Touch SQL proxy outputs model data into an HTML5
- * local database using WebSQL.
- *
- * You can create a Store for the proxy, for example:
- *
- * Ext.require(["Ext.data.proxy.SQL"]);
- *
- * Ext.define("User", {
- * extend: "Ext.data.Model",
- * config: {
- * fields: [ "firstName", "lastName" ]
- * }
- * });
- *
- * Ext.create("Ext.data.Store", {
- * model: "User",
- * storeId: "Users",
- * proxy: {
- * type: "sql"
- * }
- * });
- *
- * Ext.getStore("Users").add({
- * firstName: "Polly",
- * lastName: "Hedra"
- * });
- *
- * Ext.getStore("Users").sync();
- *
- * To destroy a table use:
- *
- * Ext.getStore("Users").getProxy().dropTable();
- *
- * To recreate a table use:
- *
- * Ext.data.Store.sync() or Ext.data.Model.save()
- */
- Ext.define('Ext.data.proxy.Sql', {
- alias: 'proxy.sql',
- extend: 'Ext.data.proxy.Client',
- alternateClassName: 'Ext.data.proxy.SQL',
- isSQLProxy: true,
- config: {
- /**
- * @cfg {Object} reader
- * @hide
- */
- reader: null,
- /**
- * @cfg {Object} writer
- * @hide
- */
- writer: null,
- /**
- * @cfg {String} table
- * Optional Table name to use if not provided ModelName will be used
- */
- table: null,
- /**
- * @cfg {String} database
- * Database name to access tables from
- */
- database: 'Sencha'
- },
- _createOptions: {
- silent: true,
- dirty: false
- },
- updateModel: function(model) {
- var me = this,
- modelName, len, i, columns, quoted;
- if (model) {
- me.uniqueIdStrategy = model.identifier.isUnique;
- if (!me.getTable()) {
- modelName = model.entityName;
- me.setTable(modelName.slice(modelName.lastIndexOf('.') + 1));
- }
- me.columns = columns = me.getPersistedModelColumns(model);
- me.quotedColumns = quoted = [];
- for (i = 0 , len = columns.length; i < len; ++i) {
- quoted.push('"' + columns[i] + '"');
- }
- }
- me.callParent([
- model
- ]);
- },
- setException: function(operation, error) {
- operation.setException(error);
- },
- create: function(operation) {
- var me = this,
- records = operation.getRecords(),
- result, error;
- operation.setStarted();
- me.executeTransaction(function(transaction) {
- me.insertRecords(records, transaction, function(resultSet, statementError) {
- result = resultSet;
- error = statementError;
- });
- }, function(transactionError) {
- operation.setException(transactionError);
- }, function() {
- if (error) {
- operation.setException(statementError);
- } else {
- operation.process(result);
- }
- });
- },
- read: function(operation) {
- var me = this,
- model = me.getModel(),
- records = operation.getRecords(),
- record = records ? records[0] : null,
- result, error, id, params;
- if (record && !record.phantom) {
- id = record.getId();
- } else {
- id = operation.getId();
- }
- if (id !== undefined) {
- params = {
- idOnly: true,
- id: id
- };
- } else {
- params = {
- page: operation.getPage(),
- start: operation.getStart(),
- limit: operation.getLimit(),
- sorters: operation.getSorters(),
- filters: operation.getFilters()
- };
- }
- operation.setStarted();
- me.executeTransaction(function(transaction) {
- me.selectRecords(transaction, params, function(resultSet, statementError) {
- result = resultSet;
- error = statementError;
- });
- }, function(transactionError) {
- operation.setException(transactionError);
- }, function() {
- if (error) {
- operation.setException(statementError);
- } else {
- operation.process(result);
- }
- });
- },
- update: function(operation) {
- var me = this,
- records = operation.getRecords(),
- result, error;
- operation.setStarted();
- me.executeTransaction(function(transaction) {
- me.updateRecords(transaction, records, function(resultSet, statementError) {
- result = resultSet;
- error = statementError;
- });
- }, function(transactionError) {
- operation.setException(transactionError);
- }, function() {
- if (error) {
- operation.setException(statementError);
- } else {
- operation.process(result);
- }
- });
- },
- erase: function(operation) {
- var me = this,
- records = operation.getRecords(),
- result, error;
- operation.setStarted();
- me.executeTransaction(function(transaction) {
- me.destroyRecords(transaction, records, function(resultSet, statementError) {
- result = resultSet;
- error = statementError;
- });
- }, function(transactionError) {
- operation.setException(transactionError);
- }, function() {
- if (error) {
- operation.setException(error);
- } else {
- operation.process(result);
- }
- });
- },
- createTable: function(transaction) {
- var me = this;
- if (!transaction) {
- me.executeTransaction(function(transaction) {
- me.createTable(transaction);
- });
- return;
- }
- me.executeStatement(transaction, 'CREATE TABLE IF NOT EXISTS "' + me.getTable() + '" (' + me.getSchemaString() + ')', function() {
- me.tableExists = true;
- });
- },
- insertRecords: function(records, transaction, callback) {
- var me = this,
- columns = me.columns,
- totalRecords = records.length,
- executed = 0,
- uniqueIdStrategy = me.uniqueIdStrategy,
- setOptions = me._createOptions,
- len = records.length,
- i, record, placeholders, sql, data, values, errors, completeIf;
- completeIf = function(transaction) {
- ++executed;
- if (executed === totalRecords) {
- callback.call(me, new Ext.data.ResultSet({
- success: !errors
- }), errors);
- }
- };
- placeholders = Ext.String.repeat('?', columns.length, ',');
- sql = 'INSERT INTO "' + me.getTable() + '" (' + me.quotedColumns.join(',') + ') VALUES (' + placeholders + ')';
- for (i = 0; i < len; ++i) {
- record = records[i];
- data = me.getRecordData(record);
- values = me.getColumnValues(columns, data);
- // Capture the record in closure scope so we can access it later
- (function(record) {
- me.executeStatement(transaction, sql, values, function(transaction, resultSet) {
- if (!uniqueIdStrategy) {
- record.setId(resultSet.insertId, setOptions);
- }
- completeIf();
- }, function(transaction, error) {
- if (!errors) {
- errors = [];
- }
- errors.push(error);
- completeIf();
- });
- })(record);
- }
- },
- selectRecords: function(transaction, params, callback, scope) {
- var me = this,
- Model = me.getModel(),
- idProperty = Model.idProperty,
- sql = 'SELECT * FROM "' + me.getTable() + '"',
- filterStatement = ' WHERE ',
- sortStatement = ' ORDER BY ',
- values = [],
- sorters, filters, placeholder, i, len, result, filter, sorter, property, operator, value;
- if (params.idOnly) {
- sql += filterStatement + '"' + idProperty + '" = ?';
- values.push(params);
- } else {
- filters = params.filters;
- len = filters && filters.length;
- if (len) {
- for (i = 0; i < len; i++) {
- filter = filters[i];
- property = filter.getProperty();
- value = me.toSqlValue(filter.getValue(), Model.getField(property));
- operator = filter.getOperator();
- if (property !== null) {
- operator = operator || '=';
- placeholder = '?';
- if (operator === 'like' || (operator === '=' && filter.getAnyMatch())) {
- operator = 'LIKE';
- value = '%' + value + '%';
- }
- if (operator === 'in' || operator === 'notin') {
- if (operator === 'notin') {
- operator = 'not in';
- }
- placeholder = '(' + Ext.String.repeat('?', value.length, ',') + ')';
- values = values.concat(value);
- } else {
- values.push(value);
- }
- sql += filterStatement + '"' + property + '" ' + operator + ' ' + placeholder;
- filterStatement = ' AND ';
- }
- }
- }
- sorters = params.sorters;
- len = sorters && sorters.length;
- if (len) {
- for (i = 0; i < len; i++) {
- sorter = sorters[i];
- property = sorter.getProperty();
- if (property !== null) {
- sql += sortStatement + '"' + property + '" ' + sorter.getDirection();
- sortStatement = ', ';
- }
- }
- }
- // handle start, limit, sort, filter and group params
- if (params.page !== undefined) {
- sql += ' LIMIT ' + parseInt(params.start, 10) + ', ' + parseInt(params.limit, 10);
- }
- }
- me.executeStatement(transaction, sql, values, function(transaction, resultSet) {
- var rows = resultSet.rows,
- count = rows.length,
- records = [],
- fields = Model.fields,
- fieldsLen = fields.length,
- raw, data, i, len, j, field, name;
- for (i = 0 , len = count; i < len; ++i) {
- raw = rows.item(i);
- data = {};
- for (j = 0; j < fieldsLen; ++j) {
- field = fields[j];
- name = field.name;
- data[name] = me.fromSqlValue(raw[name], field);
- }
- records.push(new Model(data));
- }
- callback.call(me, new Ext.data.ResultSet({
- records: records,
- success: true,
- total: count,
- count: count
- }));
- }, function(transaction, error) {
- callback.call(me, new Ext.data.ResultSet({
- success: false,
- total: 0,
- count: 0
- }), error);
- });
- },
- updateRecords: function(transaction, records, callback) {
- var me = this,
- columns = me.columns,
- quotedColumns = me.quotedColumns,
- totalRecords = records.length,
- executed = 0,
- updates = [],
- setOptions = me._createOptions,
- len, i, record, placeholders, sql, data, values, errors, completeIf;
- completeIf = function(transaction) {
- ++executed;
- if (executed === totalRecords) {
- callback.call(me, new Ext.data.ResultSet({
- success: !errors
- }), errors);
- }
- };
- for (i = 0 , len = quotedColumns.length; i < len; i++) {
- updates.push(quotedColumns[i] + ' = ?');
- }
- sql = 'UPDATE "' + me.getTable() + '" SET ' + updates.join(', ') + ' WHERE "' + me.getModel().idProperty + '" = ?';
- for (i = 0 , len = records.length; i < len; ++i) {
- record = records[i];
- data = me.getRecordData(record);
- values = me.getColumnValues(columns, data);
- values.push(record.getId());
- // Capture the record in closure scope so we can access it later
- (function(record) {
- me.executeStatement(transaction, sql, values, function(transaction, resultSet) {
- completeIf();
- }, function(transaction, error) {
- if (!errors) {
- errors = [];
- }
- errors.push(error);
- completeIf();
- });
- })(record);
- }
- },
- destroyRecords: function(transaction, records, callback) {
- var me = this,
- table = me.getTable(),
- idProperty = me.getModel().idProperty,
- ids = [],
- values = [],
- destroyedRecords = [],
- len = records.length,
- idStr = '"' + idProperty + '" = ?',
- i, result, record, sql;
- for (i = 0; i < len; i++) {
- ids.push(idStr);
- values.push(records[i].getId());
- }
- sql = 'DELETE FROM "' + me.getTable() + '" WHERE ' + ids.join(' OR ');
- me.executeStatement(transaction, sql, values, function(transaction, resultSet) {
- callback.call(me, new Ext.data.ResultSet({
- success: true
- }));
- }, function(transaction, error) {
- callback.call(me, new Ext.data.ResultSet({
- success: false
- }), error);
- });
- },
- /**
- * Formats the data for each record before sending it to the server. This
- * method should be overridden to format the data in a way that differs from the default.
- * @param {Object} record The record that we are writing to the server.
- * @return {Object} An object literal of name/value keys to be written to the server.
- * By default this method returns the data property on the record.
- */
- getRecordData: function(record) {
- var me = this,
- fields = record.fields,
- idProperty = record.idProperty,
- uniqueIdStrategy = me.uniqueIdStrategy,
- data = {},
- len = fields.length,
- recordData = record.data,
- i, name, value, field;
- for (i = 0; i < len; ++i) {
- field = fields[i];
- if (field.persist !== false) {
- name = field.name;
- if (name === idProperty && !uniqueIdStrategy) {
-
- continue;
- }
- data[name] = me.toSqlValue(recordData[name], field);
- }
- }
- return data;
- },
- getColumnValues: function(columns, data) {
- var len = columns.length,
- values = [],
- i, column, value;
- for (i = 0; i < len; i++) {
- column = columns[i];
- value = data[column];
- if (value !== undefined) {
- values.push(value);
- }
- }
- return values;
- },
- getSchemaString: function() {
- var me = this,
- schema = [],
- model = me.getModel(),
- idProperty = model.idProperty,
- fields = model.fields,
- uniqueIdStrategy = me.uniqueIdStrategy,
- len = fields.length,
- i, field, type, name;
- for (i = 0; i < len; i++) {
- field = fields[i];
- type = field.getType();
- name = field.name;
- if (name === idProperty) {
- if (uniqueIdStrategy) {
- type = me.convertToSqlType(type);
- schema.unshift('"' + idProperty + '" ' + type);
- } else {
- schema.unshift('"' + idProperty + '" INTEGER PRIMARY KEY AUTOINCREMENT');
- }
- } else {
- type = me.convertToSqlType(type);
- schema.push('"' + name + '" ' + type);
- }
- }
- return schema.join(', ');
- },
- convertToSqlType: function(type) {
- switch (type.toLowerCase()) {
- case 'string':
- case 'auto':
- return 'TEXT';
- case 'int':
- case 'date':
- return 'INTEGER';
- case 'float':
- return 'REAL';
- case 'bool':
- return 'NUMERIC';
- }
- },
- dropTable: function() {
- var me = this;
- me.executeTransaction(function(transaction) {
- me.executeStatement(transaction, 'DROP TABLE "' + me.getTable() + '"', function() {
- me.tableExists = false;
- });
- }, null, null, false);
- },
- getDatabaseObject: function() {
- return window.openDatabase(this.getDatabase(), '1.0', 'Sencha Database', 5 * 1024 * 1024);
- },
- privates: {
- executeStatement: function(transaction, sql, values, success, failure) {
- var me = this;
- transaction.executeSql(sql, values, success ? function() {
- success.apply(me, arguments);
- } : null, failure ? function() {
- failure.apply(me, arguments);
- } : null);
- },
- executeTransaction: function(runner, failure, success, autoCreateTable) {
- var me = this;
- autoCreateTable = autoCreateTable !== false;
- me.getDatabaseObject().transaction(runner ? function(transaction) {
- if (autoCreateTable && !me.tableExists) {
- me.createTable(transaction);
- }
- runner.apply(me, arguments);
- } : null, failure ? function() {
- failure.apply(me, arguments);
- } : null, success ? function() {
- success.apply(me, arguments);
- } : null);
- },
- fromSqlValue: function(value, field) {
- if (field.isDateField) {
- value = value ? new Date(value) : null;
- } else if (field.isBooleanField) {
- value = value === 1;
- }
- return value;
- },
- getPersistedModelColumns: function(model) {
- var fields = model.fields,
- uniqueIdStrategy = this.uniqueIdStrategy,
- idProperty = model.idProperty,
- columns = [],
- len = fields.length,
- i, field, name;
- for (i = 0; i < len; ++i) {
- field = fields[i];
- name = field.name;
- if (name === idProperty && !uniqueIdStrategy) {
-
- continue;
- }
- if (field.persist !== false) {
- columns.push(field.name);
- }
- }
- return columns;
- },
- toSqlValue: function(value, field) {
- if (field.isDateField) {
- value = value ? value.getTime() : null;
- } else if (field.isBooleanField) {
- value = value ? 1 : 0;
- }
- return value;
- }
- }
- });
|