Example #1
0
exports.removeClass = function(controller, proxy, classes, opts) {
	classes = classes || [];
	var pClasses = proxy[CONST.CLASS_PROPERTY] || [];
	var beforeLen = pClasses.length;

	// make sure there's classes to remove before processing
	if (!beforeLen || !classes.length) {
		if (opts) {
			if (MW320_CHECK) { delete opts.apiName; }
			proxy.applyProperties(opts);
		}
		return;
	} else {
		// remove the given class(es)
		classes = _.isString(classes) ? classes.split(/\s+/) : classes;
		var newClasses = _.difference(pClasses, classes);

		// make sure there was actually a difference before processing
		if (beforeLen === newClasses.length) {
			if (opts) {
				if (MW320_CHECK) { delete opts.apiName; }
				proxy.applyProperties(opts);
			}
			return;
		} else {
			processStyle(controller, proxy, newClasses, opts, RESET);
		}
	}
};
Example #2
0
exports.addClass = function(controller, proxy, classes, opts) {

	// make sure we actually have classes to add
	if (!classes) {
		if (opts) {
			if (MW320_CHECK) { delete opts.apiName; }
			proxy.applyProperties(opts);
		}
		return;
	} else {
		// create a union of the existing classes with the new one(s)
		var pClasses = proxy[CONST.CLASS_PROPERTY] || [];
		var beforeLen = pClasses.length;
		classes = _.isString(classes) ? classes.split(/\s+/) : classes;
		var newClasses = _.union(pClasses, classes || []);

		// make sure we actually added classes before processing styles
		if (beforeLen === newClasses.length) {
			if (opts) {
				if (MW320_CHECK) { delete opts.apiName; }
				proxy.applyProperties(opts);
			}
			return;
		} else {
			processStyle(controller, proxy, newClasses, opts);
		}
	}
};
Example #3
0
exports.createStyle = function(controller, opts, defaults) {
    var classes, apiName;
    if (!opts) return {};
    classes = _.isArray(opts.classes) ? opts.classes.slice(0) : _.isString(opts.classes) ? opts.classes.split(/\s+/) : [];
    apiName = opts.apiName;
    apiName && -1 === apiName.indexOf(".") && (apiName = addNamespace(apiName));
    var styleArray;
    styleArray = controller && _.isObject(controller) ? require("alloy/widgets/" + controller.widgetId + "/styles/" + controller.name) : require("alloy/styles/" + controller);
    var styleFinal = {};
    var i, len;
    for (i = 0, len = styleArray.length; len > i; i++) {
        var style = styleArray[i];
        var styleApi = style.key;
        style.isApi && -1 === styleApi.indexOf(".") && (styleApi = (CONST.IMPLICIT_NAMESPACES[styleApi] || CONST.NAMESPACE_DEFAULT) + "." + styleApi);
        if (style.isId && opts.id && style.key === opts.id || style.isClass && _.contains(classes, style.key)) ; else {
            if (!style.isApi) continue;
            -1 === style.key.indexOf(".") && (style.key = addNamespace(style.key));
            if (style.key !== apiName) continue;
        }
        if (style.queries && style.queries.formFactor && !Alloy[style.queries.formFactor]) continue;
        _.extend(styleFinal, style.style);
    }
    var extraStyle = _.omit(opts, [ CONST.CLASS_PROPERTY, CONST.APINAME_PROPERTY ]);
    _.extend(styleFinal, extraStyle);
    styleFinal[CONST.CLASS_PROPERTY] = classes;
    styleFinal[CONST.APINAME_PROPERTY] = apiName;
    return defaults ? _.defaults(styleFinal, defaults) : styleFinal;
};
Example #4
0
exports.createWidget = function(id, name, args) {
    if ("undefined" != typeof name && null !== name && _.isObject(name) && !_.isString(name)) {
        args = name;
        name = DEFAULT_WIDGET;
    }
    return new (require("alloy/widgets/" + id + "/controllers/" + (name || DEFAULT_WIDGET)))(args);
};
Example #5
0
exports.createWidget = function(id, name, args) {
	if (typeof name !== 'undefined' && name !== null &&
		_.isObject(name) && !_.isString(name)) {
		args = name;
		name = DEFAULT_WIDGET;
	}
	return new (require('alloy/widgets/' + id + '/controllers/' + (name || DEFAULT_WIDGET)))(args);
};
Example #6
0
 function openView(params) {            
     var args, name;
     if(_.isArray(params) && params.length) {
         name = params[0];
         args = params.length > 1 && params[1];    
     } else if(_.isString(params)) {
         name = params;
     }        
     Alloy.createController(name, args).getView().open(); 
 }        
Example #7
0
exports.addClass = function(controller, proxy, classes, opts) {
    if (!classes) {
        opts && proxy.applyProperties(opts);
        return;
    }
    var pClasses = proxy[CONST.CLASS_PROPERTY] || [];
    var beforeLen = pClasses.length;
    classes = _.isString(classes) ? classes.split(/\s+/) : classes;
    var newClasses = _.union(pClasses, classes || []);
    if (beforeLen === newClasses.length) {
        opts && proxy.applyProperties(opts);
        return;
    }
    processStyle(controller, proxy, newClasses, opts);
};
Example #8
0
exports.removeClass = function(controller, proxy, classes, opts) {
    classes = classes || [];
    var pClasses = proxy[CONST.CLASS_PROPERTY] || [];
    var beforeLen = pClasses.length;
    if (!beforeLen || !classes.length) {
        opts && proxy.applyProperties(opts);
        return;
    }
    classes = _.isString(classes) ? classes.split(/\s+/) : classes;
    var newClasses = _.difference(pClasses, classes);
    if (beforeLen === newClasses.length) {
        opts && proxy.applyProperties(opts);
        return;
    }
    processStyle(controller, proxy, newClasses, opts, RESET);
};
Example #9
0
 _.times(fc, function(c) {
   var fn = rs.fieldName(c);
   var text = rs.fieldByName(fn);
   o[fn] = text;
   if (text && _.isString(text)) {
     if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
       replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
       replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
       //the json is ok
       try {
         o[fn] = JSON.parse(text);
       } catch(e) {
         //
       }
     }
   }
 });
Example #10
0
/*
 * @method loginRequired
 * Проверяет залогинен ли пользователь и вызывает действие логина если требуется
 * @param {Mixed} nextAction Действие выполняемое после удачного логина. По умолчанию открывает вид `index`.
 * Функция или массив вида ['viewName', argsObject] или 'имя вида'. 
 * @param {Mixed} loginAction Действие выполняемое если пользователь не аутентифицирован. По умолчанию открывает вид  `logon`, если он существует.
 * Функция или массив вида ['viewName', argsObject] или 'имя вида'.
 * @param {Object} context Контекст в котором будут вызваны функции.
 * @return {Boolean} Истина если потребовался вход.
 */
function loginRequired(nextAction, loginAction, context) {
    if(currentUser.isAuthenticated()) return false; 
         
    nextAction = nextAction || config.nextAction;  
    loginAction = loginAction || config.loginAction;
    
    function openView(params) {            
        var args, name;
        if(_.isArray(params) && params.length) {
            name = params[0];
            args = params.length > 1 && params[1];    
        } else if(_.isString(params)) {
            name = params;
        }        
        Alloy.createController(name, args).getView().open(); 
    }        
    
    // build next action callback
    if(_.isFunction(nextAction)) {
        context && (nextAction = _.bind(nextAction, context));            
    } else {
        nextAction = _.partial(openView, nextAction);            
    }        
    
    // build login action callback
    if(_.isFunction(loginAction)) {
        loginAction = _.bind(loginAction, context || null, nextAction);
    } else {
        if(_.isString(loginAction)) {
            loginAction = [loginAction, {next: nextAction}];
        } else if(_.isArray(loginAction)) {
            loginAction[1] = _.extend({next: nextAction}, loginAction[1]);
        } 
        loginAction = _.partial(openView, loginAction);
    }    
    
    Ti.API.info(MODULE_NAME,'Redirect to login action');
    loginAction();
    
    return true;   
}; 
Example #11
0
exports.createStyle = function(controller, opts, defaults) {
	var classes, apiName;

	// If there's no opts, there's no reason to load the style module. Just
	// return an empty object.
	if (!opts) { return {}; }

	// make opts.classes an array if it isn't already
	if (_.isArray(opts.classes)) {
		classes = opts.classes.slice(0);
	} else if (_.isString(opts.classes)) {
		classes = opts.classes.split(/\s+/);
	} else {
		classes = [];
	}

	// give opts.apiName a namespace if it doesn't have one already
	apiName = opts.apiName;
	if (apiName && apiName.indexOf('.') === -1) {
		apiName = addNamespace(apiName);
	}

	// TODO: check cached styles based on opts and controller

	// Load the runtime style for the given controller
	var styleArray;
	if (controller && _.isObject(controller)) {
		styleArray = require('alloy/widgets/' + controller.widgetId +
			'/styles/' + controller.name);
	} else {
		styleArray = require('alloy/styles/' + controller);
	}
	var styleFinal = {};

	// iterate through all styles
	var i, len;
	for (i = 0, len = styleArray.length; i < len; i++) {
		var style = styleArray[i];

		// give the apiName a namespace if necessary
		var styleApi = style.key;
		if (style.isApi && styleApi.indexOf('.') === -1) {
			styleApi = (CONST.IMPLICIT_NAMESPACES[styleApi] ||
				CONST.NAMESPACE_DEFAULT) + '.' + styleApi;
		}

		// does this style match the given opts?
		if ((style.isId && opts.id && style.key === opts.id) ||
			(style.isClass && _.contains(classes, style.key))) {
			// do nothing here, keep on processing
		} else if (style.isApi) {
			if (style.key.indexOf('.') === -1) {
				style.key = addNamespace(style.key);
			}
			if (style.key !== apiName) { continue; }
		} else {
			// no matches, skip this style
			continue;
		}

		// can we clear out any form factor queries?
		if (style.queries && style.queries.formFactor &&
			!Alloy[style.queries.formFactor]) {
			continue;
		}

		// Merge this style into the existing style object
		deepExtend(true, styleFinal, style.style);
	}

	// TODO: cache the style based on the opts and controller

	// Merge remaining extra style properties from opts, if any
	var extraStyle = _.omit(opts, [
		CONST.CLASS_PROPERTY,
		CONST.APINAME_PROPERTY
	]);
	deepExtend(true, styleFinal, extraStyle);
	styleFinal[CONST.CLASS_PROPERTY] = classes;
	styleFinal[CONST.APINAME_PROPERTY] = apiName;

	if (MW320_CHECK) { delete styleFinal[CONST.APINAME_PROPERTY]; }

	return defaults ? _.defaults(styleFinal,defaults) : styleFinal;
};
function Sync(method, model, opts) {
    var db, sql, table = model.config.adapter.collection_name, columns = model.config.columns, dbName = model.config.adapter.db_name || ALLOY_DB_DEFAULT, resp = null;
    switch (method) {
      case "create":
      case "update":
        resp = function() {
            var attrObj = {};
            if (!model.id) {
                model.id = model.idAttribute === ALLOY_ID_DEFAULT ? guid() : null;
                attrObj[model.idAttribute] = model.id;
                "0.9.2" === backbone.VERSION ? model.set(attrObj, {
                    silent: true
                }) : model.set(attrObj);
            }
            var names = [], values = [], q = [];
            for (var k in columns) {
                names.push(k);
                values.push(model.get(k));
                q.push("?");
            }
            sql = "REPLACE INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");";
            db = Ti.Database.open(dbName);
            db.execute(sql, values);
            if (null === model.id) {
                model.id = db.lastInsertRowId;
                attrObj[model.idAttribute] = model.id;
                "0.9.2" === backbone.VERSION ? model.set(attrObj, {
                    silent: true
                }) : model.set(attrObj);
            }
            db.close();
            return model.toJSON();
        }();
        break;

      case "read":
        opts.query && opts.id && Ti.API.warn('Both "query" and "id" options were specified for model.fetch(). "id" will be ignored.');
        sql = "SELECT * FROM " + table;
        opts.query ? sql = opts.query : opts.id && (sql += " WHERE " + (model.idAttribute ? model.idAttribute : ALLOY_ID_DEFAULT) + " = " + (_.isString(opts.id) ? '"' + opts.id + '"' : opts.id));
        db = Ti.Database.open(dbName);
        var rs;
        rs = _.isString(sql) ? db.execute(sql) : db.execute(sql.statement, sql.params);
        var values = [];
        var fieldNames = [];
        var fieldCount = _.isFunction(rs.fieldCount) ? rs.fieldCount() : rs.fieldCount;
        var getField = rs.field;
        var i = 0;
        for (;fieldCount > i; i++) fieldNames.push(rs.fieldName(i));
        while (rs.isValidRow()) {
            var o = {};
            for (i = 0; fieldCount > i; i++) o[fieldNames[i]] = getField(i);
            values.push(o);
            rs.next();
        }
        rs.close();
        db.close();
        var len = values.length;
        "0.9.2" === backbone.VERSION && (model.length = len);
        resp = 1 === len ? values[0] : values;
        break;

      case "delete":
        sql = "DELETE FROM " + table + " WHERE " + model.idAttribute + "=?";
        db = Ti.Database.open(dbName);
        db.execute(sql, model.id);
        db.close();
        resp = model.toJSON();
    }
    if (resp) {
        _.isFunction(opts.success) && opts.success(resp);
        "read" !== method || opts.silent || model.trigger("fetch", {
            fromAdapter: true
        });
    } else _.isFunction(opts.error) && opts.error(resp);
}
Example #13
0
			toBeFile: function() {
				var file = _.isString(this.actual) ? Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, this.actual) : this.actual;
				return file.exists() && file.isFile();
			}
Example #14
0
function ucfirst(e){return e?e[0].toUpperCase()+e.substr(1):e}function addNamespace(e){return(CONST.IMPLICIT_NAMESPACES[e]||CONST.NAMESPACE_DEFAULT)+"."+e}function processStyle(e,t,o,r,n){r=r||{},r.classes=o,t.apiName&&(r.apiName=t.apiName),t.id&&(r.id=t.id),t.applyProperties(exports.createStyle(e,r,n))}function isTabletFallback(){return Math.min(Ti.Platform.displayCaps.platformHeight,Ti.Platform.displayCaps.platformWidth)>=700}var _=require("alloy/underscore")._,Backbone=require("alloy/backbone"),CONST=require("alloy/constants");exports.version="1.3.0",exports._=_,exports.Backbone=Backbone;var DEFAULT_WIDGET="widget",TI_VERSION=Ti.version,MW320_CHECK=!0&&TI_VERSION>="3.2.0",IDENTITY_TRANSFORM=void 0,RESET={bottom:null,left:null,right:null,top:null,height:null,width:null,shadowColor:null,shadowOffset:null,backgroundImage:null,backgroundRepeat:null,center:null,layout:null,backgroundSelectedColor:null,backgroundSelectedImage:null,opacity:1,touchEnabled:!0,enabled:!0,horizontalWrap:!0,zIndex:0,backgroundColor:null,font:null,visible:!0,color:null,transform:null,backgroundGradient:{},borderColor:"transparent",borderRadius:null,borderWidth:null};exports.M=function(e,t,o){var r,n=(t||{}).config||{},s=n.adapter||{},l={},a={};s.type?(r=require("alloy/sync/"+s.type),l.sync=function(e,t,o){r.sync(e,t,o)}):l.sync=function(e,t){Ti.API.warn("Execution of "+e+"#sync() function on a model that does not support persistence"),Ti.API.warn("model: "+JSON.stringify(t.toJSON()))},l.defaults=n.defaults,o&&(a.migrations=o),r&&_.isFunction(r.beforeModelCreate)&&(n=r.beforeModelCreate(n,e)||n);var i=Backbone.Model.extend(l,a);return i.prototype.config=n,_.isFunction(t.extendModel)&&(i=t.extendModel(i)||i),r&&_.isFunction(r.afterModelCreate)&&r.afterModelCreate(i,e),i},exports.C=function(e,t,o){var r,n={model:o},s=(o?o.prototype.config:{})||{};s.adapter&&s.adapter.type?(r=require("alloy/sync/"+s.adapter.type),n.sync=function(e,t,o){r.sync(e,t,o)}):n.sync=function(e,t){Ti.API.warn("Execution of "+e+"#sync() function on a collection that does not support persistence"),Ti.API.warn("model: "+JSON.stringify(t.toJSON()))};var l=Backbone.Collection.extend(n);return l.prototype.config=s,_.isFunction(t.extendCollection)&&(l=t.extendCollection(l)||l),r&&_.isFunction(r.afterCollectionCreate)&&r.afterCollectionCreate(l),l},exports.UI={},exports.UI.create=function(controller,apiName,opts){opts=opts||{};var baseName,ns,parts=apiName.split(".");if(1===parts.length)baseName=apiName,ns=opts.ns||CONST.IMPLICIT_NAMESPACES[baseName]||CONST.NAMESPACE_DEFAULT;else{if(!(parts.length>1))throw"Alloy.UI.create() failed: No API name was given in the second parameter";baseName=parts[parts.length-1],ns=parts.slice(0,parts.length-1).join(".")}opts.apiName=ns+"."+baseName,baseName=baseName[0].toUpperCase()+baseName.substr(1);var style=exports.createStyle(controller,opts);return eval(ns)["create"+baseName](style)},exports.createStyle=function(e,t,o){var r,n;if(!t)return{};r=_.isArray(t.classes)?t.classes.slice(0):_.isString(t.classes)?t.classes.split(/\s+/):[],n=t.apiName,n&&-1===n.indexOf(".")&&(n=addNamespace(n));var s;s=require(e&&_.isObject(e)?"alloy/widgets/"+e.widgetId+"/styles/"+e.name:"alloy/styles/"+e);var l,a,i={};for(l=0,a=s.length;a>l;l++){var p=s[l],c=p.key;if(p.isApi&&-1===c.indexOf(".")&&(c=(CONST.IMPLICIT_NAMESPACES[c]||CONST.NAMESPACE_DEFAULT)+"."+c),p.isId&&t.id&&p.key===t.id||p.isClass&&_.contains(r,p.key));else{if(!p.isApi)continue;if(-1===p.key.indexOf(".")&&(p.key=addNamespace(p.key)),p.key!==n)continue}p.queries&&p.queries.formFactor&&!Alloy[p.queries.formFactor]||_.extend(i,p.style)}var u=_.omit(t,[CONST.CLASS_PROPERTY,CONST.APINAME_PROPERTY]);return _.extend(i,u),i[CONST.CLASS_PROPERTY]=r,i[CONST.APINAME_PROPERTY]=n,MW320_CHECK&&delete i[CONST.APINAME_PROPERTY],o?_.defaults(i,o):i},exports.addClass=function(e,t,o,r){if(!o)return void(r&&(MW320_CHECK&&delete r.apiName,t.applyProperties(r)));var n=t[CONST.CLASS_PROPERTY]||[],s=n.length;o=_.isString(o)?o.split(/\s+/):o;var l=_.union(n,o||[]);return s===l.length?void(r&&(MW320_CHECK&&delete r.apiName,t.applyProperties(r))):void processStyle(e,t,l,r)},exports.removeClass=function(e,t,o,r){o=o||[];var n=t[CONST.CLASS_PROPERTY]||[],s=n.length;if(!s||!o.length)return void(r&&(MW320_CHECK&&delete r.apiName,t.applyProperties(r)));o=_.isString(o)?o.split(/\s+/):o;var l=_.difference(n,o);return s===l.length?void(r&&(MW320_CHECK&&delete r.apiName,t.applyProperties(r))):void processStyle(e,t,l,r,RESET)},exports.resetClass=function(e,t,o,r){o=o||[],o=_.isString(o)?o.split(/\s+/):o,processStyle(e,t,o,r,RESET)},exports.createWidget=function(e,t,o){return"undefined"!=typeof t&&null!==t&&_.isObject(t)&&!_.isString(t)&&(o=t,t=DEFAULT_WIDGET),new(require("alloy/widgets/"+e+"/controllers/"+(t||DEFAULT_WIDGET)))(o)},exports.createController=function(e,t){return new(require("alloy/controllers/"+e))(t)},exports.createModel=function(e,t){return new(require("alloy/models/"+ucfirst(e)).Model)(t)},exports.createCollection=function(e,t){return new(require("alloy/models/"+ucfirst(e)).Collection)(t)},exports.isTablet=function(){return Math.min(Ti.Platform.displayCaps.platformHeight,Ti.Platform.displayCaps.platformWidth)>=400}(),exports.isHandheld=!exports.isTablet,exports.Globals={},exports.Models={},exports.Models.instance=function(e){return exports.Models[e]||(exports.Models[e]=exports.createModel(e))},exports.Collections={},exports.Collections.instance=function(e){return exports.Collections[e]||(exports.Collections[e]=exports.createCollection(e))},exports.CFG=require("alloy/CFG");
Example #15
0
function ucfirst(e){return e?e[0].toUpperCase()+e.substr(1):e}function addNamespace(e){return(CONST.IMPLICIT_NAMESPACES[e]||CONST.NAMESPACE_DEFAULT)+"."+e}function processStyle(e,t,i,n,r){n=n||{},n.classes=i,t.apiName&&(n.apiName=t.apiName),t.id&&(n.id=t.id),t.applyProperties(exports.createStyle(e,n,r)),t.classes=i}function isTabletFallback(){return Math.min(Ti.Platform.displayCaps.platformHeight,Ti.Platform.displayCaps.platformWidth)>=700}function deepExtend(){var e,t,i,n,r,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1;for("boolean"==typeof a&&(u=a,a=arguments[1]||{},s=2),"object"==typeof a||_.isFunction(a)||(a={});l>s;s++)if(e=arguments[s],null!=e){"string"==typeof e&&(e=e.split(""));for(t in e)i=a[t],n=e[t],a!==n&&(u&&n&&(_.isObject(n)&&!_.has(n,"apiName")||(r=_.isArray(n)))&&!n.colors?(r?(r=!1,o=i&&_.isArray(i)?i:[]):o=_.isDate(n)?new Date(n.valueOf()):i&&_.isObject(i)?i:{},a[t]=deepExtend(u,o,n)):"undefined"!=typeof n?a[t]=n:n.colors&&(a[t]=n))}return a}var _=require("alloy/underscore")._,Backbone=require("alloy/backbone"),CONST=require("alloy/constants");exports.version="1.5.1",exports._=_,exports.Backbone=Backbone;var DEFAULT_WIDGET="widget",TI_VERSION=Ti.version,MW320_CHECK=!1,IDENTITY_TRANSFORM=Ti.UI.create2DMatrix(),RESET={bottom:null,left:null,right:null,top:null,height:null,width:null,shadowColor:null,shadowOffset:null,backgroundImage:null,backgroundRepeat:null,center:null,layout:null,backgroundSelectedColor:null,backgroundSelectedImage:null,opacity:1,touchEnabled:!0,enabled:!0,horizontalWrap:!0,zIndex:0,backgroundColor:"transparent",font:null,visible:!0,color:"#000",transform:IDENTITY_TRANSFORM,backgroundGradient:null,borderColor:null,borderRadius:null,borderWidth:null};RESET=_.extend(RESET,{backgroundDisabledColor:null,backgroundDisabledImage:null,backgroundFocusedColor:null,backgroundFocusedImage:null,focusable:!1,keepScreenOn:!1}),exports.M=function(e,t,i){var n,r=(t||{}).config||{},o=r.adapter||{},a={},s={};o.type?(n=require("alloy/sync/"+o.type),a.sync=function(e,t,i){n.sync(e,t,i)}):a.sync=function(e,t){Ti.API.warn("Execution of "+e+"#sync() function on a model that does not support persistence"),Ti.API.warn("model: "+JSON.stringify(t.toJSON()))},a.defaults=r.defaults,i&&(s.migrations=i),n&&_.isFunction(n.beforeModelCreate)&&(r=n.beforeModelCreate(r,e)||r);var l=Backbone.Model.extend(a,s);return l.prototype.config=r,_.isFunction(t.extendModel)&&(l=t.extendModel(l)||l),n&&_.isFunction(n.afterModelCreate)&&n.afterModelCreate(l,e),l},exports.C=function(e,t,i){var n,r={model:i},o=(i?i.prototype.config:{})||{};o.adapter&&o.adapter.type?(n=require("alloy/sync/"+o.adapter.type),r.sync=function(e,t,i){n.sync(e,t,i)}):r.sync=function(e,t){Ti.API.warn("Execution of "+e+"#sync() function on a collection that does not support persistence"),Ti.API.warn("model: "+JSON.stringify(t.toJSON()))};var a=Backbone.Collection.extend(r);return a.prototype.config=o,_.isFunction(t.extendCollection)&&(a=t.extendCollection(a)||a),n&&_.isFunction(n.afterCollectionCreate)&&n.afterCollectionCreate(a),a},exports.UI={},exports.UI.create=function(controller,apiName,opts){opts=opts||{};var baseName,ns,parts=apiName.split(".");if(1===parts.length)baseName=apiName,ns=opts.ns||CONST.IMPLICIT_NAMESPACES[baseName]||CONST.NAMESPACE_DEFAULT;else{if(!(parts.length>1))throw"Alloy.UI.create() failed: No API name was given in the second parameter";baseName=parts[parts.length-1],ns=parts.slice(0,parts.length-1).join(".")}opts.apiName=ns+"."+baseName,baseName=baseName[0].toUpperCase()+baseName.substr(1);var style=exports.createStyle(controller,opts);return eval(ns)["create"+baseName](style)},exports.createStyle=function(e,t,i){var n,r;if(!t)return{};n=_.isArray(t.classes)?t.classes.slice(0):_.isString(t.classes)?t.classes.split(/\s+/):[],r=t.apiName,r&&-1===r.indexOf(".")&&(r=addNamespace(r));var o;o=require(e&&_.isObject(e)?"alloy/widgets/"+e.widgetId+"/styles/"+e.name:"alloy/styles/"+e);var a,s,l={};for(a=0,s=o.length;s>a;a++){var u=o[a],c=u.key;if(u.isApi&&-1===c.indexOf(".")&&(c=(CONST.IMPLICIT_NAMESPACES[c]||CONST.NAMESPACE_DEFAULT)+"."+c),u.isId&&t.id&&u.key===t.id||u.isClass&&_.contains(n,u.key));else{if(!u.isApi)continue;if(-1===u.key.indexOf(".")&&(u.key=addNamespace(u.key)),u.key!==r)continue}u.queries&&u.queries.formFactor&&!Alloy[u.queries.formFactor]||deepExtend(!0,l,u.style)}var d=_.omit(t,[CONST.CLASS_PROPERTY,CONST.APINAME_PROPERTY]);return deepExtend(!0,l,d),l[CONST.CLASS_PROPERTY]=n,l[CONST.APINAME_PROPERTY]=r,MW320_CHECK&&delete l[CONST.APINAME_PROPERTY],i?_.defaults(l,i):l},exports.addClass=function(e,t,i,n){if(!i)return void(n&&(MW320_CHECK&&delete n.apiName,t.applyProperties(n)));var r=t[CONST.CLASS_PROPERTY]||[],o=r.length;i=_.isString(i)?i.split(/\s+/):i;var a=_.union(r,i||[]);return o===a.length?void(n&&(MW320_CHECK&&delete n.apiName,t.applyProperties(n))):void processStyle(e,t,a,n)},exports.removeClass=function(e,t,i,n){i=i||[];var r=t[CONST.CLASS_PROPERTY]||[],o=r.length;if(!o||!i.length)return void(n&&(MW320_CHECK&&delete n.apiName,t.applyProperties(n)));i=_.isString(i)?i.split(/\s+/):i;var a=_.difference(r,i);return o===a.length?void(n&&(MW320_CHECK&&delete n.apiName,t.applyProperties(n))):void processStyle(e,t,a,n,RESET)},exports.resetClass=function(e,t,i,n){i=i||[],i=_.isString(i)?i.split(/\s+/):i,processStyle(e,t,i,n,RESET)},exports.createWidget=function(e,t,i){return"undefined"!=typeof t&&null!==t&&_.isObject(t)&&!_.isString(t)&&(i=t,t=DEFAULT_WIDGET),new(require("alloy/widgets/"+e+"/controllers/"+(t||DEFAULT_WIDGET)))(i)},exports.createController=function(e,t){return new(require("alloy/controllers/"+e))(t)},exports.createModel=function(e,t){return new(require("alloy/models/"+ucfirst(e)).Model)(t)},exports.createCollection=function(e,t){return new(require("alloy/models/"+ucfirst(e)).Collection)(t)},exports.isTablet=function(){var e=Ti.Platform.Android.physicalSizeCategory;return e===Ti.Platform.Android.PHYSICAL_SIZE_CATEGORY_LARGE||e===Ti.Platform.Android.PHYSICAL_SIZE_CATEGORY_XLARGE}(),exports.isHandheld=!exports.isTablet,exports.Globals={},exports.Models={},exports.Models.instance=function(e){return exports.Models[e]||(exports.Models[e]=exports.createModel(e))},exports.Collections={},exports.Collections.instance=function(e){return exports.Collections[e]||(exports.Collections[e]=exports.createCollection(e))},exports.CFG=require("alloy/CFG"),exports.Android={},exports.Android.menuItemCreateArgs=["itemId","groupId","title","order","actionView","checkable","checked","enabled","icon","showAsAction","titleCondensed","visible"];
Example #16
0
File: sql.js Project: 16N4C10/alloy
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, sql;

	switch (method) {
		case 'create':
		case 'update':
			resp = (function() {
				var attrObj = {};

				if (!model.id) {
					model.id = model.idAttribute === ALLOY_ID_DEFAULT ? guid() : null;
					attrObj[model.idAttribute] = model.id;
					model.set(attrObj, { silent: true });
				}

				// assemble columns and values
				var names = [], values = [], q = [];
				for (var k in columns) {
					names.push(k);
					values.push(model.get(k));
					q.push("?");
				}

				// execute the query
				sql = "REPLACE INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");";
				db = Ti.Database.open(dbName);
				db.execute('BEGIN;');
				db.execute(sql, values);

				// if model.id is still null, grab the last inserted id
				if (model.id === null) {
					var sqlId = "SELECT last_insert_rowid();";
					var rs = db.execute(sqlId);
					if (rs && rs.isValidRow()) {
						model.id = rs.field(0);
						attrObj[model.idAttribute] = model.id;
						model.set(attrObj, { silent: true });
					} else {
						Ti.API.warn('Unable to get ID from database for model: ' + model.toJSON());
					}
					if (rs) { rs.close(); }
				}

				// cleanup
				db.execute('COMMIT;');
				db.close();

				return model.toJSON();
			})();
			break;

		case 'read':
			// print warning about using both id and query
			if (opts.query && opts.id) {
				Ti.API.warn('Both "query" and "id" options were specified for model.fetch(). "id" will be ignored.');
			}

			// determine the query to execute
			sql = 'SELECT * FROM ' + table;
			if (opts.query) {
				sql = opts.query;
			} else if (opts.id) {
				sql += ' WHERE ' + model.idAttribute + ' = ' + opts.id;
			}

			// execute the select query
			db = Ti.Database.open(dbName);
			var rs;

			// is it a string or a prepared statement?
			if (_.isString(sql)) {
				rs = db.execute(sql);
			} else {
				rs = db.execute(sql.statement, sql.params);
			}

			var len = 0;
			var values = [];

			// iterate through all queried rows
			while(rs.isValidRow())
			{
				var o = {};
        var fc = 0;

                // TODO: https://jira.appcelerator.org/browse/ALOY-459
				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);

				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;
			if (len === 1) {
				resp = values[0];
			} else {
				resp = values;
			}
			break;

		case 'delete':
			sql = 'DELETE FROM '+table+' WHERE ' + model.idAttribute + '=?';

			// execute the delete
			db = Ti.Database.open(dbName);
			db.execute(sql, model.id);
			db.close();

			model.id = null;
			resp = model.toJSON();
			break;
	}

  // process success/error handlers, if present
	if (resp) {
		if (_.isFunction(opts.success)) { opts.success(resp); }
		if (method === "read" && !opts.silent) { model.trigger("fetch", { fromAdapter: true }); }
  } else {
		if (_.isFunction(opts.error)) { opts.error(resp); }
  }

}
Example #17
0
exports.resetClass = function(controller, proxy, classes, opts) {
	classes = classes || [];
	classes = _.isString(classes) ? classes.split(/\s+/) : classes;
	processStyle(controller, proxy, classes, opts, RESET);
};
Example #18
0
File: sql.js Project: jpcm/alloy
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;

	switch (method) {
		case 'create':
			resp = (function(){
				var attrObj = {};

				// Use idAttribute to account for something other than "id"
				// being used for the model's id.
				if (!model.id) {
					if (model.idAttribute === ALLOY_ID_DEFAULT) {
						// alloy-created GUID field
						model.id = util.guid();
						attrObj[model.idAttribute] = model.id;

						// make it silent so it doesn't fire an unnecessary
						// Backbone change events
						model.set(attrObj, {silent:true});
					} else {
						// idAttribute not assigned by alloy. Use the idAttribute
						// field, or leave it empty and allow sqlite to process 
						// as null, which is the expected value for an 
						// AUTOINCREMENT field.
						var tmpM = model.get(model.idAttribute);
						model.id = tmpM !== null && typeof tmpM !== 'undefined' ? tmpM : null;
					}
	            }

	            // Create arrays for insert query
				var names = [], values = [], q = [];
				for (var k in columns) {
					names.push(k);
					values.push(model.get(k));
					q.push('?');
				}

				// Assemble create query
				var sqlInsert = "INSERT INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");";
				var sqlId = "SELECT last_insert_rowid();";

	            // 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 rs = db.execute(sqlId);
	            	if (rs.isValidRow()) {
	            		model.id = rs.field(0);
	            		attrObj[model.idAttribute] = model.id;

						// make it silent so it doesn't fire an unnecessary
						// Backbone change event
						model.set(attrObj, {silent:true});
	            	} else {
	            		Ti.API.warn('Unable to get ID from database for model: ' + model.toJSON());
	            	}
	        	}

	            db.execute('COMMIT;');
	            db.close();

	            return model.toJSON();
			})();
			break;
		case 'read':
			var sql = opts.query || 'SELECT * FROM ' + table;

			// execute the select query
			db = Ti.Database.open(dbName);
			var rs;

			// is it a string or a prepared statement?
			if (_.isString(sql)) { 
				rs = db.execute(sql);
			} else {
				rs = db.execute(sql.statement, sql.params);
			}

			var len = 0;
			var values = [];

			// iterate through all queried rows
			while(rs.isValidRow())
			{
				var o = {};
                var fc = 0;

                // TODO: https://jira.appcelerator.org/browse/ALOY-459
				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);

				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;
			len === 1 ? resp = values[0] : resp = values;
			break;

		case 'update':
			var names = [];
			var values = [];
			var q = [];

			// create the list of columns
			for (var k in columns)
			{
				names.push(k+'=?');
				values.push(model.get(k));
				q.push('?');
			}

			// compose the update query
			var sql = 'UPDATE '+table+' SET '+names.join(',')+' WHERE ' + model.idAttribute + '=?';
		    values.push(model.id);

		    // execute the update
		    db = Ti.Database.open(dbName);
			db.execute(sql,values);
			db.close();

			resp = model.toJSON();
			break;

		case 'delete':
			var sql = 'DELETE FROM '+table+' WHERE ' + model.idAttribute + '=?';

			// execute the delete
			db = Ti.Database.open(dbName);
			db.execute(sql, model.id);
			db.close();

			model.id = null;
			resp = model.toJSON();
			break;
	}

    // process success/error handlers, if present
	if (resp) {
        _.isFunction(opts.success) && opts.success(resp);
        method === "read" && model.trigger("fetch");
    } else {
    	_.isFunction(opts.error) && opts.error(resp);
    }

}
Example #19
0
function S4(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function guid(){return S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()}function Migrator(e,t){this.db=t,this.dbname=e.adapter.db_name,this.table=e.adapter.collection_name,this.idAttribute=e.adapter.idAttribute,this.column=function(e){var t=e.split(/\s+/),i=t[0];switch(i.toLowerCase()){case"string":case"varchar":case"date":case"datetime":Ti.API.warn('"'+i+'" is not a valid sqlite field, using TEXT instead');case"text":i="TEXT";break;case"int":case"tinyint":case"smallint":case"bigint":case"boolean":Ti.API.warn('"'+i+'" is not a valid sqlite field, using INTEGER instead');case"integer":i="INTEGER";break;case"double":case"float":case"decimal":case"number":Ti.API.warn('"'+e+'" is not a valid sqlite field, using REAL instead');case"real":i="REAL";break;case"blob":i="BLOB";break;case"null":i="NULL";break;default:i="TEXT"}return t[0]=i,t.join(" ")},this.createTable=function(e){var t=[],i=!1;for(var r in e.columns)r===this.idAttribute&&(i=!0),t.push(r+" "+this.column(e.columns[r]));i||this.idAttribute!==ALLOY_ID_DEFAULT||t.push(ALLOY_ID_DEFAULT+" TEXT UNIQUE");var o="CREATE TABLE IF NOT EXISTS "+this.table+" ( "+t.join(",")+")";this.db.execute(o)},this.dropTable=function(){this.db.execute("DROP TABLE IF EXISTS "+this.table)},this.insertRow=function(e){var t=[],i=[],r=[],o=!1;for(var n in e)n===this.idAttribute&&(o=!0),t.push(n),i.push(e[n]),r.push("?");o||this.idAttribute!==ALLOY_ID_DEFAULT||(t.push(this.idAttribute),i.push(guid()),r.push("?")),this.db.execute("INSERT INTO "+this.table+" ("+t.join(",")+") VALUES ("+r.join(",")+");",i)},this.deleteRow=function(e){var t="DELETE FROM "+this.table,i=_.keys(e),r=i.length,o=[],n=[];r&&(t+=" WHERE ");for(var s=0;r>s;s++)o.push(i[s]+" = ?"),n.push(e[i[s]]);t+=o.join(" AND "),this.db.execute(t,n)}}function Sync(e,t,i){var r,o,n=t.config.adapter.collection_name,s=t.config.columns,a=t.config.adapter.db_name||ALLOY_DB_DEFAULT,l=null;switch(e){case"create":case"update":l=function(){var e={};t.id||(t.id=t.idAttribute===ALLOY_ID_DEFAULT?guid():null,e[t.idAttribute]=t.id,t.set(e,{silent:!0}));var i=[],l=[],d=[];for(var c in s)i.push(c),l.push(t.get(c)),d.push("?");if(o="REPLACE INTO "+n+" ("+i.join(",")+") VALUES ("+d.join(",")+");",r=Ti.Database.open(a),r.execute("BEGIN;"),r.execute(o,l),null===t.id){var u="SELECT last_insert_rowid();",_=r.execute(u);_&&_.isValidRow()?(t.id=_.field(0),e[t.idAttribute]=t.id,t.set(e,{silent:!0})):Ti.API.warn("Unable to get ID from database for model: "+t.toJSON()),_&&_.close()}return r.execute("COMMIT;"),r.close(),t.toJSON()}();break;case"read":i.query&&i.id&&Ti.API.warn('Both "query" and "id" options were specified for model.fetch(). "id" will be ignored.'),o="SELECT * FROM "+n,i.query?o=i.query:i.id&&(o+=" WHERE "+(t.idAttribute?t.idAttribute:ALLOY_ID_DEFAULT)+" = "+(_.isString(i.id)?'"'+i.id+'"':i.id)),r=Ti.Database.open(a);var d;d=_.isString(o)?r.execute(o):r.execute(o.statement,o.params);for(var c=0,u=[];d.isValidRow();){var p={},h=0;h=_.isFunction(d.fieldCount)?d.fieldCount():d.fieldCount,_.times(h,function(e){var t=d.fieldName(e);p[t]=d.fieldByName(t)}),u.push(p),c++,d.next()}d.close(),r.close(),t.length=c,l=1===c?u[0]:u;break;case"delete":o="DELETE FROM "+n+" WHERE "+t.idAttribute+"=?",r=Ti.Database.open(a),r.execute(o,t.id),r.close(),t.id=null,l=t.toJSON()}l?(_.isFunction(i.success)&&i.success(l),"read"!==e||i.silent||t.trigger("fetch",{fromAdapter:!0})):_.isFunction(i.error)&&i.error(l)}function GetMigrationFor(e,t){var i=null,r=Ti.Database.open(e);r.execute("CREATE TABLE IF NOT EXISTS migrations (latest TEXT, model TEXT);");var o=r.execute("SELECT latest FROM migrations where model = ?;",t);return o.isValidRow()&&(i=o.field(0)+""),o.close(),r.close(),i}function Migrate(e){var t=e.migrations||[],i={};t.length&&t[t.length-1](i);var r=e.prototype.config;r.adapter.db_name=r.adapter.db_name||ALLOY_DB_DEFAULT;var o=new Migrator(r),n="undefined"==typeof r.adapter.migration||null===r.adapter.migration?i.id:r.adapter.migration;if("undefined"==typeof n||null===n){var s=Ti.Database.open(r.adapter.db_name);return o.db=s,o.createTable(r),void s.close()}n+="";var a,l=GetMigrationFor(r.adapter.db_name,r.adapter.collection_name);if(l!==n){if(l&&l>n?(a=0,t.reverse()):a=1,db=Ti.Database.open(r.adapter.db_name),o.db=db,db.execute("BEGIN;"),t.length)for(var d=0;d<t.length;d++){var c=t[d],u={};if(c(u),a){if(u.id>n)break;if(u.id<=l)continue}else{if(u.id<=n)break;if(u.id>l)continue}var p=a?"up":"down";_.isFunction(u[p])&&u[p](o)}else o.createTable(r);db.execute("DELETE FROM migrations where model = ?",r.adapter.collection_name),db.execute("INSERT INTO migrations VALUES (?,?)",n,r.adapter.collection_name),db.execute("COMMIT;"),db.close(),o.db=null}}function installDatabase(e){var t=e.adapter.db_file,i=e.adapter.collection_name,r=/(^|.*\/)([^\/]+)\.[^\/]+$/,o=t.match(r);if(null===o)throw'Invalid sql database filename "'+t+'"';e.adapter.db_name=e.adapter.db_name||o[2];var n=e.adapter.db_name;Ti.API.debug('Installing sql database "'+t+'" with name "'+n+'"');var s,a,l=Ti.Database.install(t,n),d=l.execute('pragma table_info("'+i+'");'),c={};if(d){for(;d.isValidRow();)s=d.fieldByName("name"),a=d.fieldByName("type"),c[s]=a,s!==ALLOY_ID_DEFAULT||e.adapter.idAttribute||(e.adapter.idAttribute=ALLOY_ID_DEFAULT),d.next();d.close()}else{e.adapter.idAttribute?e.adapter.idAttribute:ALLOY_ID_DEFAULT;for(var u in e.columns)s=u,a=e.columns[u],s!==ALLOY_ID_DEFAULT||e.adapter.idAttribute?u===e.adapter.idAttribute&&(a+=" UNIQUE"):e.adapter.idAttribute=ALLOY_ID_DEFAULT,c[s]=a}if(e.columns=c,e.adapter.idAttribute){if(!_.contains(_.keys(e.columns),e.adapter.idAttribute))throw'config.adapter.idAttribute "'+e.adapter.idAttribute+'" not found in list of columns for table "'+i+'"\ncolumns: ['+_.keys(e.columns).join(",")+"]"}else{Ti.API.info('No config.adapter.idAttribute specified for table "'+i+'"'),Ti.API.info('Adding "'+ALLOY_ID_DEFAULT+'" to uniquely identify rows');var p=[],h=[];_.each(e.columns,function(e,t){h.push(t),p.push(t+" "+e)});var g=h.join(",");l.execute("ALTER TABLE "+i+" RENAME TO "+i+"_temp;"),l.execute("CREATE TABLE "+i+"("+p.join(",")+","+ALLOY_ID_DEFAULT+" TEXT UNIQUE);"),l.execute("INSERT INTO "+i+"("+g+","+ALLOY_ID_DEFAULT+") SELECT "+g+",CAST(_ROWID_ AS TEXT) FROM "+i+"_temp;"),l.execute("DROP TABLE "+i+"_temp;"),e.columns[ALLOY_ID_DEFAULT]="TEXT UNIQUE",e.adapter.idAttribute=ALLOY_ID_DEFAULT}l.close()}var _=require("alloy/underscore")._,ALLOY_DB_DEFAULT="_alloy_",ALLOY_ID_DEFAULT="alloy_id",cache={config:{},Model:{}};module.exports.beforeModelCreate=function(e,t){if(cache.config[t])return cache.config[t];if("undefined"==typeof Ti.Database)throw"No support for Titanium.Database in MobileWeb environment.";return e.adapter.db_file&&installDatabase(e),e.adapter.idAttribute||(Ti.API.info('No config.adapter.idAttribute specified for table "'+e.adapter.collection_name+'"'),Ti.API.info('Adding "'+ALLOY_ID_DEFAULT+'" to uniquely identify rows'),e.columns[ALLOY_ID_DEFAULT]="TEXT UNIQUE",e.adapter.idAttribute=ALLOY_ID_DEFAULT),cache.config[t]=e,e},module.exports.afterModelCreate=function(e,t){return cache.Model[t]?cache.Model[t]:(e=e||{},e.prototype.idAttribute=e.prototype.config.adapter.idAttribute,Migrate(e),cache.Model[t]=e,e)},module.exports.sync=Sync;
Example #20
0
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, sql;

	switch (method) {
		case 'create':
		case 'update':
			resp = (function() {
				var attrObj = {};

				if (!model.id) {
					model.id = model.idAttribute === ALLOY_ID_DEFAULT ? guid() : null;
					attrObj[model.idAttribute] = model.id;
					model.set(attrObj, { silent: true });
				}

				// assemble columns and values
				var names = [], values = [], q = [];
				for (var k in columns) {
					names.push(k);
					values.push(model.get(k));
					q.push("?");
				}

				// execute the query
				sql = "REPLACE INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");";
				db = Ti.Database.open(dbName);
				db.execute(sql, values);

				// if model.id is still null, grab the last inserted id
				if (model.id === null) {
					model.id = db.lastInsertRowId;
					attrObj[model.idAttribute] = model.id;
					model.set(attrObj, { silent: true });
				}

				// cleanup
				db.close();

				return model.toJSON();
			})();
			break;

		case 'read':
			// print warning about using both id and query
			if (opts.query && opts.id) {
				Ti.API.warn('Both "query" and "id" options were specified for model.fetch(). "id" will be ignored.');
			}

			// determine the query to execute
			sql = 'SELECT * FROM ' + table;
			if (opts.query) {
				sql = opts.query;
			} else if (opts.id) {
				sql += ' WHERE ' + (model.idAttribute ? model.idAttribute : ALLOY_ID_DEFAULT) + ' = ' + (_.isString(opts.id) ? '"' + opts.id + '"' : opts.id);
			}

			// execute the select query
			db = Ti.Database.open(dbName);
			var rs;

			// is it a string or a prepared statement?
			if (_.isString(sql)) {
				rs = db.execute(sql);
			} else {
				rs = db.execute(sql.statement, sql.params);
			}

			var values = [];
			var fieldNames = [];
			var fieldCount = _.isFunction(rs.fieldCount) ? rs.fieldCount() : rs.fieldCount;
			var getField = OS_ANDROID ? rs.field.bind(rs) : rs.field;
			var i = 0;

			for (; i < fieldCount; i++) {
				fieldNames.push(rs.fieldName(i));
			}

			// iterate through all queried rows
			while(rs.isValidRow())
			{
				var o = {};
				for(i=0;i<fieldCount;i++) {
					o[fieldNames[i]] = getField(i);
				}
				values.push(o);
				rs.next();
			}

			// close off db after read query
			rs.close();
			db.close();

			// shape response based on whether it's a model or collection
			var len = values.length;
			model.length = len;
			resp = (len===1) ? values[0] : values;
			break;

		case 'delete':
			sql = 'DELETE FROM '+table+' WHERE ' + model.idAttribute + '=?';

			// execute the delete
			db = Ti.Database.open(dbName);
			db.execute(sql, model.id);
			db.close();

			resp = model.toJSON();
			break;
	}

  // process success/error handlers, if present
	if (resp) {
		if (_.isFunction(opts.success)) { opts.success(resp); }
		if (method === "read" && !opts.silent) { model.trigger("fetch", { fromAdapter: true }); }
  } else {
		if (_.isFunction(opts.error)) { opts.error(resp); }
  }

}
Example #21
0
function Sync(method, model, opts) {
    var db, table = model.config.adapter.collection_name, columns = model.config.columns, dbName = model.config.adapter.db_name || ALLOY_DB_DEFAULT, resp = null;
    switch (method) {
      case "create":
      case "update":
        resp = function() {
            var attrObj = {};
            if (!model.id) {
                model.id = model.idAttribute === ALLOY_ID_DEFAULT ? util.guid() : null;
                attrObj[model.idAttribute] = model.id;
                model.set(attrObj, {
                    silent: true
                });
            }
            var names = [], values = [], q = [];
            for (var k in columns) {
                names.push(k);
                values.push(model.get(k));
                q.push("?");
            }
            var sql = "REPLACE INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");";
            db = Ti.Database.open(dbName);
            db.execute("BEGIN;");
            db.execute(sql, values);
            if (null === model.id) {
                var sqlId = "SELECT last_insert_rowid();";
                var rs = db.execute(sqlId);
                if (rs && rs.isValidRow()) {
                    model.id = rs.field(0);
                    attrObj[model.idAttribute] = model.id;
                    model.set(attrObj, {
                        silent: true
                    });
                } else Ti.API.warn("Unable to get ID from database for model: " + model.toJSON());
                rs && rs.close();
            }
            db.execute("COMMIT;");
            db.close();
            return model.toJSON();
        }();
        break;

      case "read":
        var sql = opts.query || "SELECT * FROM " + table;
        db = Ti.Database.open(dbName);
        var rs;
        rs = _.isString(sql) ? db.execute(sql) : db.execute(sql.statement, sql.params);
        var len = 0;
        var values = [];
        while (rs.isValidRow()) {
            var o = {};
            var fc = 0;
            fc = _.isFunction(rs.fieldCount) ? rs.fieldCount() : rs.fieldCount;
            _.times(fc, function(c) {
                var fn = rs.fieldName(c);
                o[fn] = rs.fieldByName(fn);
            });
            values.push(o);
            len++;
            rs.next();
        }
        rs.close();
        db.close();
        model.length = len;
        resp = 1 === len ? values[0] : values;
        break;

      case "delete":
        var sql = "DELETE FROM " + table + " WHERE " + model.idAttribute + "=?";
        db = Ti.Database.open(dbName);
        db.execute(sql, model.id);
        db.close();
        model.id = null;
        resp = model.toJSON();
    }
    if (resp) {
        _.isFunction(opts.success) && opts.success(resp);
        "read" === method && model.trigger("fetch");
    } else _.isFunction(opts.error) && opts.error(resp);
}
Example #22
0
function Sync(method, model, opts) {
    var db, sql, table = model.config.adapter.collection_name, columns = model.config.columns, dbName = model.config.adapter.db_name || ALLOY_DB_DEFAULT, resp = null;
    switch (method) {
      case "create":
      case "update":
        resp = function() {
            var attrObj = {};
            if (!model.id) {
                model.id = model.idAttribute === ALLOY_ID_DEFAULT ? guid() : null;
                attrObj[model.idAttribute] = model.id;
                model.set(attrObj, {
                    silent: true
                });
            }
            var names = [], values = [], q = [];
            for (var k in columns) {
                var description = columns[k] || '';
                var parts = description.split(/\s+/);
                var type = parts[0];
                var value;

                switch(type.toLowerCase()){
                    case 'date':
                    case 'datetime':
                        var fieldValue = new moment( model.get(k) );
                        if(fieldValue.isValid()){
                            value = fieldValue.unix();
                        } else {
                            value = 0;
                        }
                        break;
                    case 'boolean':
                    case 'bool':
                        value = +model.get(k);
                        break;
                    default:
                        value = model.get(k);

                }


                names.push(k);
                values.push(value);
                q.push("?");
            }
            sql = "REPLACE INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");";
            db = Ti.Database.open(dbName);
            db.execute("BEGIN;");
            db.execute(sql, values);
            if (null === model.id) {
                var sqlId = "SELECT last_insert_rowid();";
                var rs = db.execute(sqlId);
                if (rs && rs.isValidRow()) {
                    model.id = rs.field(0);
                    attrObj[model.idAttribute] = model.id;
                    model.set(attrObj, {
                        silent: true
                    });
                } else Ti.API.warn("Unable to get ID from database for model: " + model.toJSON());
                rs && rs.close();
            }
            db.execute("COMMIT;");
            db.close();
            return model.toJSON();
        }();
        break;

      case "read":
        opts.query && opts.id && Ti.API.warn('Both "query" and "id" options were specified for model.fetch(). "id" will be ignored.');
        sql = "SELECT * FROM " + table;
        opts.query ? sql = opts.query : opts.id && (sql += " WHERE " + (model.idAttribute ? model.idAttribute : ALLOY_ID_DEFAULT) + " = " + (_.isString(opts.id) ? '"' + opts.id + '"' : opts.id));
        db = Ti.Database.open(dbName);
        var rs;
        rs = _.isString(sql) ? db.execute(sql) : db.execute(sql.statement, sql.params);
        var len = 0;
        var values = [];
        while (rs.isValidRow()) {
            var o = {};
            var fc = 0;
            fc = _.isFunction(rs.fieldCount) ? rs.fieldCount() : rs.fieldCount;
            _.times(fc, function(c) {
                var fn = rs.fieldName(c);
                o[fn] = rs.fieldByName(fn);
            });
            values.push(o);
            len++;
            rs.next();
        }
        rs.close();
        db.close();
        model.length = len;
        resp = 1 === len ? values[0] : values;
        break;

      case "delete":
        sql = "DELETE FROM " + table + " WHERE " + model.idAttribute + "=?";
        db = Ti.Database.open(dbName);
        db.execute(sql, model.id);
        db.close();
        model.id = null;
        resp = model.toJSON();
    }
    if (resp) {
        _.isFunction(opts.success) && opts.success(resp);
        "read" !== method || opts.silent || model.trigger("fetch", {
            fromAdapter: true
        });
    } else _.isFunction(opts.error) && opts.error(resp);
}