From 00745f53193ab3d21a0c40dbba147de9dcb977ae Mon Sep 17 00:00:00 2001 From: Robert Parham Date: Wed, 14 Dec 2016 21:59:49 -0500 Subject: [PATCH] Prefer vanilla indexeddb over the webkit flavor and other Safari-related tweaks. --- jSQL.js | 19 ++++++++----------- jSQL.min.js | 7 +++---- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/jSQL.js b/jSQL.js index 9842d61..4c79c30 100644 --- a/jSQL.js +++ b/jSQL.js @@ -1,5 +1,5 @@ /** - * jSQL.js v1.2 + * jSQL.js v1.3 * A Javascript Query Language Database Engine * @author Robert Parham * @website https://github.com/Pamblam/jSQL#jsql @@ -1589,8 +1589,8 @@ try { indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; - IDBTransaction = window.hasOwnProperty('webkitIndexedDB') ? window.webkitIDBTransaction : window.IDBTransaction; - IDBKeyRange = window.hasOwnProperty('webkitIndexedDB') ? window.webkitIDBKeyRange : window.IDBKeyRange; + IDBTransaction = window.hasOwnProperty('IDBTransaction') ? window.IDBTransaction : window.webkitIDBTransaction ; + IDBKeyRange = window.hasOwnProperty('IDBKeyRange') ? window.IDBKeyRange : window.webkitIndexedDB; } catch (e) { throw "indexedDB is not supported in this browser"; } @@ -1665,8 +1665,7 @@ // Insert a group of rows self.insert = function(model, data, successCallback) { if(typeof successCallback !== "function") successCallback = function(){}; - var transParam = undefined === IDBTransaction ? 'readwrite' : IDBTransaction.READ_WRITE; - var transaction = self.db.transaction([model], transParam); + var transaction = self.db.transaction([model], undefined === IDBTransaction.READ_WRITE ? 'readwrite' : IDBTransaction.READ_WRITE); var store, i, request; var total = data.length; @@ -1688,9 +1687,8 @@ // Delete all items from the database self.delete = function(model, successCallback) { - var transParam = undefined === IDBTransaction ? 'readwrite' : IDBTransaction.READ_WRITE; - if(typeof successCallback !== "function") successCallback = function(){}; - var transaction = self.db.transaction([model], transParam), store, request; + if(typeof successCallback != "function") successCallback = function(){}; + var transaction = self.db.transaction([model], undefined === IDBTransaction.READ_WRITE ? 'readwrite' : IDBTransaction.READ_WRITE), store, request; transaction.onerror = function(){ throw "Could not initiate a transaction"; };; store = transaction.objectStore(model); request = store.clear(); @@ -1701,8 +1699,7 @@ // Get all data from the datastore self.select = function(model, successCallback) { if("function" !== typeof successCallback) successCallback = function(){}; - var transParam = undefined === IDBTransaction ? 'readonly' : IDBTransaction.READ_ONLY ; - var transaction = self.db.transaction([model], transParam), store, request, results = []; + var transaction = self.db.transaction([model], undefined === IDBTransaction.READ_ONLY ? 'readonly' : IDBTransaction.READ_ONLY), store, request, results = []; transaction.onerror = function(){ throw "Could not initiate a transaction"; };; store = transaction.objectStore(model); request = store.openCursor(); @@ -1899,7 +1896,7 @@ //////////////////////////////////////////////////////////////////////////// return { - version: 1.2, + version: 1.3, tables: {}, query: jSQLParseQuery, createTable: createTable, diff --git a/jSQL.min.js b/jSQL.min.js index 42847fb..4aa226f 100644 --- a/jSQL.min.js +++ b/jSQL.min.js @@ -1,10 +1,9 @@ /** - * jSQL.js + * jSQL.min.js v1.3 * A Javascript Query Language Database Engine * @author Robert Parham * @website https://github.com/Pamblam/jSQL#jsql * @license http://www.apache.org/licenses/LICENSE-2.0 */ - -window.jSQL=function(){"use strict";function jSQLDataTypeList(){this.list=[{type:"NUMERIC",aliases:["NUMBER","DECIMAL","FLOAT"],serialize:function(e,t){return!isNaN(parseFloat(e))&&isFinite(e)?parseFloat(e):0},unserialize:function(e,t){return!isNaN(parseFloat(e))&&isFinite(e)?parseFloat(e):0}},{type:"FUNCTION",serialize:function(e,t){return"function"!=typeof e&&(e=function(){}),"jSQLFunct-"+e.toString()},unserialize:function(value,args){var p=value.split("-");if("jSQLFunct"!==p.shift())throw"Corrupted function stored in data";p=value.split("-"),p.shift();var f=null;try{eval("f = "+p.join("-"))}catch(e){}if("function"==typeof f)return f;throw"Corrupted function stored in data"}},{type:"BOOLEAN",aliases:["BOOL"],serialize:function(e,t){return!!e},unserialize:function(e,t){return!!e}},{type:"INT",serialize:function(e,t){return!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):0},unserialize:function(e,t){return!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):0}},{type:"CHAR",aliases:["VARCHAR","LONGTEXT","MEDIUMTEXT"],serialize:function(e,t){return""+e},unserialize:function(e,t){return""+e}},{type:"DATE",serialize:function(e,t){return e instanceof Date?e.getTime():new Date(0).now()},unserialize:function(e,t){return new Date(e)}},{type:"AMBI",serialize:function(e,t){return e instanceof Date?e.getTime():"function"==typeof e?"jSQLFunct-"+e.toString():!isNaN(parseFloat(e))&&isFinite(e)?e:""+e},unserialize:function(value,args){if("string"==typeof value&&"jSQLFunct"===value.split("-")[0]){var p=value.split("-");p.shift();var f=null;try{eval("f = "+p.join("-"))}catch(e){}if("function"==typeof f)return f}return value}}],this.add=function(e){if("object"!=typeof e)throw"Invalid datatype definition";if(void 0===e.type)throw"DataType must have a `type` property.";if("function"!=typeof e.serialize)throw"DataType must have a `serialize` function.";if("function"!=typeof e.unserialize)throw"DataType must have an `unserialize` function.";this.list.push({type:e.type.toUpperCase(),aliases:Array.isArray(e.aliases)?e.aliases:[],serialize:e.serialize,unserialize:e.unserialize})},this.exists=function(e){e=e.toUpperCase();for(var t=this.list.length;t--;)if(this.list[t].type===e||void 0!==this.list[t].aliases&&this.list[t].aliases.indexOf(e)>-1)return!0;return!1},this.getByType=function(e){e=e.toUpperCase();for(var t=this.list.length;t--;)if(this.list[t].type===e||void 0!==this.list[t].aliases&&this.list[t].aliases.indexOf(e)>-1)return this.list[t];throw e+" is not a supported datatype"}}function jSQLTable(e,t,n,r){var a=this;a.name="",a.columns=[],a.data=[],a.colmap={},a.types=[],a.init=function(e,t,n,r){if(a.name=e,void 0===r&&(r=[]),!Array.isArray(r))throw"Invalid table types array";if(Array.isArray(t)&&void 0===n&&(n=t,t=[]),Array.isArray(t)&&!Array.isArray(t[0])&&"object"==typeof t[0]){var i=[];for(var e in t[0])t[0].hasOwnProperty(e)&&i.push(e);n=t,t=i}if(!Array.isArray(t))throw"Columns must be an array.";a.columns=t;for(var s=0;sa.columns.length;)a.addColumn();for(;e.length-1){a.renameColumn("u0",r);for(var i=1;a.columns.indexOf("u"+i)>-1;)a.renameColumn("u"+i,"u"+(i-1))}else a.addColumn(r);for(var n=0;n0&&e.length==this.whereClause.LIMIT);t++)if(this.whereClause.finalConditions.length<1)e.push(t);else{for(var n=!1,r=this.whereClause.finalConditions.length;r--;){for(var a=this.whereClause.finalConditions[r],i=!0,s=a.length;s--;){var o=a[s];switch(o.type){case">":(isNaN(parseFloat(this.table.data[t][this.table.colmap[o.col]]))||this.table.data[t][this.table.colmap[o.col]]o.value)&&(i=!1);break;case"=":this.table.data[t][this.table.colmap[o.col]]!=o.value&&(i=!1);break;case"!=":break;case"%%":this.table.data[t][this.table.colmap[o.col]].indexOf(o.value)<0&&(i=!1);break;case"%-":this.table.data[t][this.table.colmap[o.col]].indexOf(o.value)!=this.table.data[t][this.table.colmap[o.col]].length-o.value.length&&(i=!1);break;case"-%":0!=this.table.data[t][this.table.colmap[o.col]].indexOf(o.value)&&(i=!1)}if(!i)break}if(i){n=!0;break}}n&&e.push(t)}for(var l=[],u=[],h=e.length;h--;)for(var c=e[h],t=this.table.data.length;t--;)t===c?u.push(this.table.data[t]):l.push(this.table.data[t]);return this.table.data=l,this.resultSet=e,this},this.where=function(e){return this.whereClause.where(e)},this.fetch=function(){return null},this.fetchAll=function(){return[]},this.values=function(){throw"values() is not a valid method for a delete query"},this.ifNotExists=function(){throw"ifNotExists() is not a valid method for a delete query"},this.set=function(){throw"set() is not a valid method for a delete query"},this.from=function(){throw"from() is not a valid method for a delete query"}}function jSQLDropQuery(){this.init=function(e){return this.tablename=e,this},this.execute=function(){if(void 0===jSQL.tables[this.tablename])throw"Table "+this.tablename+" does not exist.";return delete jSQL.tables[this.tablename],this},this.fetch=function(){return null},this.fetchAll=function(){return[]},this.values=function(){throw"values() is not a valid method for a drop query"},this.ifNotExists=function(){throw"ifNotExists() is not a valid method for a drop query"},this.set=function(){throw"set() is not a valid method for a drop query"},this.where=function(){throw"where() is not a valid method for a drop query"},this.from=function(){throw"from() is not a valid method for a drop query"}}function jSQLInsertQuery(){this.init=function(e){return this.table=e,this},this.values=function(e){if(void 0===jSQL.tables[this.table])throw"Table: "+this.table+" doesn't exist.";return this.data=e,this},this.execute=function(e){if(void 0!==e&&Array.isArray(e)&&e.length>0)if(Array.isArray(this.data))for(var t=this.data.length;t--&&e.length;)"?"==this.data[t]&&(this.data[t]=e.shift());else for(var t in this.data)this.data.hasOwnProperty(t)&&e.length&&"?"==this.data[t]&&(this.data[t]=e.shift());jSQL.tables[this.table].insertRow(this.data)},this.fetch=function(){return null},this.fetchAll=function(){return[]},this.ifNotExists=function(){throw"ifNotExists() is not a valid method for an insert query"},this.set=function(){throw"set() is not a valid method for an insert query"},this.where=function(){throw"where() is not a valid method for an insert query"},this.from=function(){throw"from() is not a valid method for an insert query"}}function jSQLSelectQuery(){this.init=function(e){return this.columns=Array.isArray(e)?e:[e],this},this.from=function(e){if(void 0===jSQL.tables[e])throw"Table: "+e+" doesn't exist.";return this.table=jSQL.tables[e],"*"==this.columns[0]&&(this.columns=this.table.columns),this},this.where=function(e){return this.whereClause.where(e)},this.execute=function(){for(var e=[],t=0;t0&&e.length==this.whereClause.LIMIT);t++)if(this.whereClause.finalConditions.length<1){for(var n={},r=0;r":(isNaN(parseFloat(this.table.data[t][this.table.colmap[u.col]]))||this.table.data[t][this.table.colmap[u.col]]u.value)&&(o=!1);break;case"=":this.table.data[t][this.table.colmap[u.col]]!=u.value&&(o=!1);break;case"!=":break;case"%%":this.table.data[t][this.table.colmap[u.col]].indexOf(u.value)<0&&(o=!1);break;case"%-":this.table.data[t][this.table.colmap[u.col]].indexOf(u.value)!=this.table.data[t][this.table.colmap[u.col]].length-u.value.length&&(o=!1);break;case"-%":0!=this.table.data[t][this.table.colmap[u.col]].indexOf(u.value)&&(o=!1)}if(!o)break}if(o){a=!0;break}}if(a){for(var n={},r=0;r0&&(e.sort(function(e,t){return function n(r){return void 0===this.whereClause.sortColumn[r]?0:e[this.whereClause.sortColumn[r]]t[this.whereClause.sortColumn[r]]?1:n(r+1)}(0)}),"DESC"==this.whereClause.sortDirection&&e.reverse()),this.resultSet=e,this},this.fetch=function(e){if(void 0===e&&(e="ASSOC"),e=e.toUpperCase(),"ASSOC"!==e&&"ARRAY"!==e)throw"Fetch expects paramter one to be 'ASSOC', 'ARRAY', or blank";if(!this.resultSet.length)return!1;var t=this.resultSet.shift();for(var n in t)if(t.hasOwnProperty(n)){var r=this.table.normalizeColumnFetchValue(n,t[n]);t[n]=r}if("ARRAY"==e){var r=[];for(var a in t)t.hasOwnProperty(a)&&r.push(t[a]);t=r}return t},this.fetchAll=function(e){if(void 0===e&&(e="ASSOC"),e=e.toUpperCase(),"ASSOC"!==e&&"ARRAY"!==e)throw"Fetch expects paramter one to be 'ASSOC', 'ARRAY', or blank";if(!this.resultSet.length)return!1;for(var t=[];this.resultSet.length>0;)t.push(this.fetch(e));return t},this.values=function(){throw"values() is not a valid method for a select query"},this.ifNotExists=function(){throw"ifNotExists() is not a valid method for a select query"},this.set=function(){throw"set() is not a valid method for a select query"}}function jSQLUpdateQuery(){this.init=function(e){if(void 0===jSQL.tables[e])throw"Table: "+e+" doesn't exist.";return this.table=this.table=jSQL.tables[e],this},this.set=function(e){this.newvals=e;for(var t in e)e.hasOwnProperty(t)&&this.columns.push(t);return this},this.where=function(e){return this.whereClause.where(e)},this.execute=function(e){if(void 0!==e&&Array.isArray(e))for(var t in this.newvals)this.newvals.hasOwnProperty(t)&&"?"==this.newvals[t]&&e.length&&(this.newvals[t]=e.shift());for(var n=[],t=0;t0&&n.length==this.whereClause.LIMIT);t++)if(this.whereClause.finalConditions.length<1){for(var r={},a=0;a":(isNaN(parseFloat(this.table.data[t][this.table.colmap[h.col]]))||this.table.data[t][this.table.colmap[h.col]]h.value)&&(l=!1);break;case"=":this.table.data[t][this.table.colmap[h.col]]!=h.value&&(l=!1);break;case"!=":break;case"%%":this.table.data[t][this.table.colmap[h.col]].indexOf(h.value)<0&&(l=!1);break;case"%-":this.table.data[t][this.table.colmap[h.col]].indexOf(h.value)!=this.table.data[t][this.table.colmap[h.col]].length-h.value.length&&(l=!1);break;case"-%":0!=this.table.data[t][this.table.colmap[h.col]].indexOf(h.value)&&(l=!1)}if(!l)break}if(l){i=!0;break}}if(i){for(var r={},a=0;a0&&"\\"===e[i-1])if(i>1&&"\\"===e[i-2]){r=!1,n.push(a.join(""));var a=[]}else a[a.length-1]=e[i];else{r=!1,n.push(a.join(""));var a=[]}else t=e[i],r=!0;else if(r){if("\\"===e[i]&&i>0&&"\\"===e[i-1])continue;a.push(e[i])}else if("?"===e[i])n.push("?");else if(" "!==e[i]&&","!==e[i])return n;return n},a=function(e){for(var n=e.split(","),r={},a="",i=0,s=0;s":e=e.greaterThan(t(r.shift()));break;case"<":e=e.lessThan(t(r.shift()));break;case"!=":case"<>":e=e.doesNotEqual(t(r.shift()));break;case"LIKE":var o=t(r.shift());e="%"==o.substr(0,1)&&"%"==o.substr(o.length-1,1)?e.contains(o.substr(1,o.length-2)):"%"==o.substr(0,1)?e.endsWith(o.substr(1,o.length-1)):"%"==o.substr(o.length-1,1)?e.beginsWith(o.substr(0,o.length-1)):"?"===o?e.preparedLike():e.equals(o);break;case"OR":var i;try{i=n(r.shift())}catch(s){throw s.message}e=e.or(i);break;case"LIMIT":e=e.limit(r.shift());break;case"ORDER":if("BY"!=r.shift().toUpperCase())throw"Expected 'ORDER BY', got something else.";for(;r.length>0;){var l=r.shift();try{for(;l.indexOf(",")==l.length-1;)l=l.substr(0,l.length-1);l=n(l),T.push(l)}catch(u){r.unshift(l);break}}e=e.orderBy(T);break;case"ASC":if(!T.length)throw"Must call ORDER BY before using ASC.";e=e.asc();break;case"DESC":if(!T.length)throw"Must call ORDER BY before using DESC.";e=e.desc()}}return e};e=e.replace(/(\r\n|\n|\r)/gm," ").replace(/ +(?= )/g,"").trim();var s=e.split(" ");switch(s.shift().toUpperCase()){case"DELETE":if("FROM"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'TABLE'";var o=t(s.shift());if(void 0===jSQL.tables[o])throw"Table "+o+" does not exist.";var e=jSQL.deleteFrom(o);return e=i(e,s);case"DROP":if("TABLE"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'TABLE'";var o=t(s.shift());if(void 0===jSQL.tables[o])throw"Table "+o+" does not exist.";return jSQL.dropTable(o);case"INSERT":var o,l=[],u=[];if("INTO"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'INTO'";if(o=t(s.shift()),void 0===jSQL.tables[o])throw"Table "+o+" does not exist.";s=m.split("(").join(" ").split(")").join(" ").split(",").join(" ").split(" ").join(" ").trim().split(" ");for(var h=s.shift();s.length&&"VALUES"!==h.toUpperCase();)l.push(t(h)),h=s.shift();if("VALUES"!==h.toUpperCase())throw"Unintelligible query. Expected 'VALUES' near '"+h+"'";var c=s.join(" ");if(u=r(c),!l.length)for(var f=0;f0&&(w=m.substring(m.indexOf("(")+1,m.lastIndexOf(")"))),s=s.join(" ").split("(").join(" ").split(")").join(" ").split(",").join(" ").split(" ").join(" ").trim().split(" "),o=t(s.shift()),"IF"===o.toUpperCase()){if("NOT"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'NOT'";if("EXISTS"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'EXISTS'";o=t(s.shift()),y=!0}d[o]={};for(var v=w.split(","),f=0;f-1){var g=(Q.match(/\(/g)||[]).length,b=(Q.match(/\)/g)||[]).length;if(g!==b)throw"Invalid Arg definition: "+Q;g>0&&(E=Q.substring(Q.indexOf("(")+1,Q.lastIndexOf(")")))}if(""!==E.trim())for(var L=E.split(","),j=0;jI)throw"Unintelligible query. Expected 'FROM'";x=s.splice(0,I);for(var f=x.length;f--;)for(;x[f].indexOf(",")==x[f].length-1;)x[f]=x[f].substr(0,x[f].length-1);s.shift(),o=s.shift();for(var O in jSQL.tables)if(jSQL.tables.hasOwnProperty(O)&&O.toUpperCase()==t(o.toUpperCase())){o=O;break}if(void 0===jSQL.tables[o])return new function(e){this.execute=function(){throw e},this.fetch=function(){throw e},this.fetchAll=function(){throw e}}("Table: "+o+" does not exist.");if(1==x.length&&"*"==x[0])x="*";else for(var f=0;f",value:e}),t.pendingColumn="",t},t.contains=function(e){if(""==t.pendingColumn)throw"Must add a 'where' clause before the 'contains' call.";return t.conditions.push({col:t.pendingColumn,type:"%%",value:e}),t.pendingColumn="",t},t.endsWith=function(e){if(""==t.pendingColumn)throw"Must add a 'where' clause before the 'endsWith' call.";return t.conditions.push({col:t.pendingColumn,type:"%-",value:e}),t.pendingColumn="",t},t.beginsWith=function(e){if(""==t.pendingColumn)throw"Must add a 'where' clause before the 'beginsWith' call.";return t.conditions.push({col:t.pendingColumn,type:"-%",value:e}),t.pendingColumn="",t},t.and=function(e){return t.where(e)},t.or=function(e){return t.finalConditions.push(t.conditions),t.conditions=[],t.where(e)},t.limit=function(e){return t.LIMIT=parseInt(e),t},t.orderBy=function(e){return Array.isArray(e)||(e=[e]),t.sortColumn=e,t},t.asc=function(){if(""==t.sortColumn)throw"Must use orderBy clause before using ASC";return t.sortDirection="ASC",t},t.desc=function(){if(""==t.sortColumn)throw"Must use orderBy clause before using DESC";return t.sortDirection="DESC",t},t.execute=function(e){if(void 0===e&&(e=[]),t.conditions.length>0&&t.finalConditions.push(t.conditions),e.length>0)for(var n=t.finalConditions.length;n--;)for(var r=t.finalConditions[n].length;r--;)if("?"===t.finalConditions[n][r].value&&"pl"===t.finalConditions[n][r].type){var a=e.pop();"%"==a.substr(0,1)&&"%"==a.substr(a.length-1,1)?(t.finalConditions[n][r].value=a.substr(1,a.length-2),t.finalConditions[n][r].type="%%"):"%"==a.substr(0,1)?(t.finalConditions[n][r].value=a.substr(1,a.length-1),t.finalConditions[n][r].type="%-"):"%"==a.substr(a.length-1,1)?(t.finalConditions[n][r].value=a.substr(0,a.length-1),t.finalConditions[n][r].type="-%"):(t.finalConditions[n][r].value=a,t.finalConditions[n][r].type="=")}else"?"===t.finalConditions[n][r].value&&e.length>0&&(t.finalConditions[n][r].value=e.pop());return t.context.execute(e)},t.fetch=function(e){return t.context.fetch(e)},t.fetchAll=function(e){return t.context.fetchAll(e)}}function WebSQLAPI(){var e=this;e.db=null;var t=function(t,n,r,a){"function"!=typeof r&&(r=function(){}),"function"!=typeof a&&(a=function(){throw"Could not execute query: "+t});var i,s,o;Array.isArray(n[0])||(n=[n]),o=n.length;var l=function(e,t){var n,a,i=[];if(o-=1,!o){for(n=0,a=t.rows.length;a>n;n+=1){var s=t.rows.item(n).json;i.push(s)}r(i)}};e.db.transaction(function(e){for(i=0,s=n.length;s>i;i+=1)e.executeSql(t,n[i],l,a)})};e.init=function(n,r){"function"!=typeof r&&(r=function(){});var a=function(){try{for(var r=n.length;r--;)(function(n,r){t("DROP TABLE IF EXISTS "+n,[],function(){t("CREATE TABLE IF NOT EXISTS "+n+"(json TEXT)",[],function(){e.insert(n,r)})})})(n[r].name,n[r].rows)}catch(a){throw"Error creating table"}};try{var i=window.location.href.replace(/\W+/g,"");e.db=openDatabase("jSQL_"+i,"1.0","jSQL "+i,5242880)}catch(s){throw"Error opening database"}t("SELECT COUNT(*) FROM "+n[0].name,[],null,function(){a()}),r()},e.insert=function(e,n,r){"function"!=typeof r&&(r=function(){});var a,i,s=n.length,o=[];for(0===s&&r(),a=0,i=n.length;i>a;a+=1)o[a]=[JSON.stringify(n[a])];t("INSERT INTO "+e+" (json) VALUES (?);",o,r)},e["delete"]=function(e,n){"function"!=typeof n&&(n=function(){}),t("DELETE FROM "+e,[],n)},e.select=function(e,n){t("SELECT json FROM "+e,[],function(e){for(var t=[],r=e.length;r--;)t.push(JSON.parse(e[r]));n(t)})}}function indexedDBAPI(){var e=this;e.db=null;var t,n,r;e.init=function(a,i){"function"!=typeof i&&(i=function(){});try{t=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.msIndexedDB,n=window.hasOwnProperty("webkitIndexedDB")?window.webkitIDBTransaction:window.IDBTransaction,r=window.hasOwnProperty("webkitIndexedDB")?window.webkitIDBKeyRange:window.IDBKeyRange}catch(s){throw"indexedDB is not supported in this browser"}if(!t)throw"indexedDB is not supported in this browser";var o=1,l=window.location.href.replace(/\W+/g,""),u=t.open("jSQL_"+l,o),h=function(){for(var t=a.length;t--;)e.db.objectStoreNames.contains(a[t].name)&&e.db.deleteObjectStore(a[t].name),e.db.createObjectStore(a[t].name,{keyPath:"_id",autoIncrement:!0});var n=0,r=!1,i=setInterval(function(){if(!r){r=!0;try{for(var t=a.length;t--;){var s=a[t].name,o=void 0==a[t].rows?[]:a[t].rows;e.insert(s,o)}clearInterval(i)}catch(l){if(n>1e3)throw clearInterval(i),"Could not add data after 10 seconds.";r=!1}}},10)};u.onsuccess=function(t){var n;e.db=t.target.result,o=String(o),e.db.setVersion&&o!==e.db.version?(n=e.db.setVersion(o),n.onfailure=function(){throw"Error updating datastore version"},n.onsuccess=function(e){h(),n.result.oncomplete=function(){i()}}):i()},u.onupgradeneeded=function(t){e.db=t.target.result,h()},u.onerror=function(e){throw"Could not connect to the indexedDB datastore."; -}},e.insert=function(t,r,a){"function"!=typeof a&&(a=function(){});var i,s,o,l=e.db.transaction([t],n.READ_WRITE||"readwrite"),u=r.length,h=function(){u-=1,0===u&&a(u)};l.onerror=function(){throw"Could not initiate a transaction"},i=l.objectStore(t);for(s in r)r.hasOwnProperty(s)&&(o=i.add(r[s]),o.onsuccess=h,o.onerror=function(){throw"Could not initiate a request"})},e["delete"]=function(t,r){"function"!=typeof r&&(r=function(){});var a,i,s=e.db.transaction([t],n.READ_WRITE||"readwrite");s.onerror=function(){throw"Could not initiate a transaction"},a=s.objectStore(t),i=a.clear(),i.onerror=function(){throw"Could not initiate a request"},i.onsuccess=r},e.select=function(t,r){"function"!=typeof r&&(r=function(){});var a,i,s=e.db.transaction([t],n.READ_ONLY||"readonly"),o=[];s.onerror=function(){throw"Could not initiate a transaction"},a=s.objectStore(t),i=a.openCursor(),i.onerror=function(){throw"Could not initiate a request"};var l=!1;i.onsuccess=function(e){if(!l){var t=e.target.result;return t?(o.push(t.value),void t["continue"]()):(l=!0,void r(o))}}}}function createTable(e,t,n){if(void 0===t&&void 0===n&&"object"==typeof e){t=[],n=[];for(var r in e)if(e.hasOwnProperty(r)){var a=e[r];e=r;for(var i in a)a.hasOwnProperty(i)&&(t.push(i),n.push({type:a[i].type,args:void 0===a[i].args?[]:a[i].args}));break}}return Array.isArray(t)||(t=[t]),new jSQLQuery("CREATE").init(e,t,n)}function select(e){return Array.isArray(e)||(e=[e]),new jSQLQuery("SELECT").init(e)}function update(e){return new jSQLQuery("UPDATE").init(e)}function insertInto(e){return new jSQLQuery("INSERT").init(e)}function dropTable(e){return new jSQLQuery("DROP").init(e)}function deleteFrom(e){return new jSQLQuery("DELETE").init(e)}var persistenceManager=new function(){var e=this;e.api=null,e.error=!1,e.persist=function(t){if("function"==typeof t&&(t=function(){}),e.error!==!1)throw e.error;var n=[];for(var r in jSQL.tables)if(jSQL.tables.hasOwnProperty(r))for(var a=jSQL.select("*").from(r).execute().fetchAll(),i=a.length;i--;){var s=a[i];for(var o in s)s.hasOwnProperty(o)&&(s[o]=jSQL.tables[r].normalizeColumnStoreValue(o,s[o]));n.push({table:r,data:JSON.stringify(s),colTypes:JSON.stringify(jSQL.tables[r].types)})}e.api["delete"]("jSQL_data_schema",function(){e.api.insert("jSQL_data_schema",n,t)})},e.load=function(t){"function"!=typeof t&&(t=function(){}),function n(r){try{e.api.select("jSQL_data_schema",function(e){if(jSQL.tables={},0===e.length)return t();for(var n=e.length;n--;){var r=e[n].table,a=JSON.parse(e[n].data),i=JSON.parse(e[n].colTypes);if(void 0===jSQL.tables[r]){var s=[];for(var o in a)a.hasOwnProperty(o)&&s.push(o);jSQL.createTable(r,s,i).execute()}for(var o in a)a.hasOwnProperty(o)&&(a[o]=jSQL.tables[r].normalizeColumnFetchValue(o,a[o]));jSQL.tables[r].insertRow(a)}return t()})}catch(a){if(r>500)return t();setTimeout(function(){n(r+1)},10)}}(0)},function(){try{e.api=new indexedDBAPI,e.api.init([{name:"jSQL_data_schema",rows:[]}])}catch(t){try{e.api=new WebSQLAPI,e.api.init([{name:"jSQL_data_schema",rows:[]}])}catch(n){e.error="Browser doesn't support Web SQL or IndexedDB"}}}()};return{tables:{},query:jSQLParseQuery,createTable:createTable,dropTable:dropTable,select:select,update:update,deleteFrom:deleteFrom,insertInto:insertInto,types:new jSQLDataTypeList,persist:persistenceManager.persist,load:persistenceManager.load}}(); \ No newline at end of file +window.jSQL=function(){"use strict";function jSQLDataTypeList(){this.list=[{type:"NUMERIC",aliases:["NUMBER","DECIMAL","FLOAT"],serialize:function(e,t){return!isNaN(parseFloat(e))&&isFinite(e)?parseFloat(e):0},unserialize:function(e,t){return!isNaN(parseFloat(e))&&isFinite(e)?parseFloat(e):0}},{type:"JSON",aliases:["ARRAY","OBJECT"],serialize:function(e,t){return JSON.stringify(e)},unserialize:function(e,t){return JSON.parse(e)}},{type:"FUNCTION",serialize:function(e,t){return"function"!=typeof e&&(e=function(){}),"jSQLFunct-"+e.toString()},unserialize:function(value,args){var p=value.split("-");if("jSQLFunct"!==p.shift())throw"Corrupted function stored in data";p=value.split("-"),p.shift();var f=null;try{eval("f = "+p.join("-"))}catch(e){}if("function"==typeof f)return f;throw"Corrupted function stored in data"}},{type:"BOOLEAN",aliases:["BOOL"],serialize:function(e,t){return!!e},unserialize:function(e,t){return!!e}},{type:"INT",serialize:function(e,t){return!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):0},unserialize:function(e,t){return!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):0}},{type:"CHAR",aliases:["VARCHAR","LONGTEXT","MEDIUMTEXT"],serialize:function(e,t){return""+e},unserialize:function(e,t){return""+e}},{type:"DATE",serialize:function(e,t){return e instanceof Date?e.getTime():new Date(0).getTime()},unserialize:function(e,t){return new Date(e)}},{type:"AMBI",serialize:function(e,t){return e instanceof Date?e.getTime():"function"==typeof e?"jSQLFunct-"+e.toString():!isNaN(parseFloat(e))&&isFinite(e)?e:""+e},unserialize:function(value,args){if("string"==typeof value&&"jSQLFunct"===value.split("-")[0]){var p=value.split("-");p.shift();var f=null;try{eval("f = "+p.join("-"))}catch(e){}if("function"==typeof f)return f}return value}}],this.add=function(e){if("object"!=typeof e)throw"Invalid datatype definition";if(void 0===e.type)throw"DataType must have a `type` property.";if("function"!=typeof e.serialize)throw"DataType must have a `serialize` function.";if("function"!=typeof e.unserialize)throw"DataType must have an `unserialize` function.";this.list.push({type:e.type.toUpperCase(),aliases:Array.isArray(e.aliases)?e.aliases:[],serialize:e.serialize,unserialize:e.unserialize})},this.exists=function(e){e=e.toUpperCase();for(var t=this.list.length;t--;)if(this.list[t].type===e||void 0!==this.list[t].aliases&&this.list[t].aliases.indexOf(e)>-1)return!0;return!1},this.getByType=function(e){e=e.toUpperCase();for(var t=this.list.length;t--;)if(this.list[t].type===e||void 0!==this.list[t].aliases&&this.list[t].aliases.indexOf(e)>-1)return this.list[t];throw e+" is not a supported datatype"}}function jSQLTable(e,t,n,r){var a=this;a.name="",a.columns=[],a.data=[],a.colmap={},a.types=[],a.init=function(e,t,n,r){if(a.name=e,void 0===r&&(r=[]),!Array.isArray(r))throw"Invalid table types array";if(Array.isArray(t)&&void 0===n&&(n=t,t=[]),Array.isArray(t)&&!Array.isArray(t[0])&&"object"==typeof t[0]){var i=[];for(var e in t[0])t[0].hasOwnProperty(e)&&i.push(e);n=t,t=i}if(!Array.isArray(t))throw"Columns must be an array.";a.columns=t;for(var s=0;sa.columns.length;)a.addColumn();for(;e.length-1){a.renameColumn("u0",r);for(var i=1;a.columns.indexOf("u"+i)>-1;)a.renameColumn("u"+i,"u"+(i-1))}else a.addColumn(r);for(var n=0;n0&&e.length==this.whereClause.LIMIT);t++)if(this.whereClause.finalConditions.length<1)e.push(t);else{for(var n=!1,r=this.whereClause.finalConditions.length;r--;){for(var a=this.whereClause.finalConditions[r],i=!0,s=a.length;s--;){var o=a[s];switch(o.type){case">":(isNaN(parseFloat(this.table.data[t][this.table.colmap[o.col]]))||this.table.data[t][this.table.colmap[o.col]]o.value)&&(i=!1);break;case"=":this.table.data[t][this.table.colmap[o.col]]!=o.value&&(i=!1);break;case"!=":break;case"%%":this.table.data[t][this.table.colmap[o.col]].indexOf(o.value)<0&&(i=!1);break;case"%-":this.table.data[t][this.table.colmap[o.col]].indexOf(o.value)!=this.table.data[t][this.table.colmap[o.col]].length-o.value.length&&(i=!1);break;case"-%":0!=this.table.data[t][this.table.colmap[o.col]].indexOf(o.value)&&(i=!1)}if(!i)break}if(i){n=!0;break}}n&&e.push(t)}for(var l=[],u=[],h=e.length;h--;)for(var c=e[h],t=this.table.data.length;t--;)t===c?u.push(this.table.data[t]):l.push(this.table.data[t]);return this.table.data=l,this.resultSet=e,this},this.where=function(e){return this.whereClause.where(e)},this.fetch=function(){return null},this.fetchAll=function(){return[]},this.values=function(){throw"values() is not a valid method for a delete query"},this.ifNotExists=function(){throw"ifNotExists() is not a valid method for a delete query"},this.set=function(){throw"set() is not a valid method for a delete query"},this.from=function(){throw"from() is not a valid method for a delete query"}}function jSQLDropQuery(){this.init=function(e){return this.tablename=e,this},this.execute=function(){if(void 0===jSQL.tables[this.tablename])throw"Table "+this.tablename+" does not exist.";return delete jSQL.tables[this.tablename],this},this.fetch=function(){return null},this.fetchAll=function(){return[]},this.values=function(){throw"values() is not a valid method for a drop query"},this.ifNotExists=function(){throw"ifNotExists() is not a valid method for a drop query"},this.set=function(){throw"set() is not a valid method for a drop query"},this.where=function(){throw"where() is not a valid method for a drop query"},this.from=function(){throw"from() is not a valid method for a drop query"}}function jSQLInsertQuery(){this.init=function(e){return this.table=e,this},this.values=function(e){if(void 0===jSQL.tables[this.table])throw"Table: "+this.table+" doesn't exist.";return this.data=e,this},this.execute=function(e){if(void 0!==e&&Array.isArray(e)&&e.length>0)if(Array.isArray(this.data))for(var t=this.data.length;t--&&e.length;)"?"==this.data[t]&&(this.data[t]=e.shift());else for(var t in this.data)this.data.hasOwnProperty(t)&&e.length&&"?"==this.data[t]&&(this.data[t]=e.shift());jSQL.tables[this.table].insertRow(this.data)},this.fetch=function(){return null},this.fetchAll=function(){return[]},this.ifNotExists=function(){throw"ifNotExists() is not a valid method for an insert query"},this.set=function(){throw"set() is not a valid method for an insert query"},this.where=function(){throw"where() is not a valid method for an insert query"},this.from=function(){throw"from() is not a valid method for an insert query"}}function jSQLSelectQuery(){this.init=function(e){return this.columns=Array.isArray(e)?e:[e],this},this.from=function(e){if(void 0===jSQL.tables[e])throw"Table: "+e+" doesn't exist.";return this.table=jSQL.tables[e],"*"==this.columns[0]&&(this.columns=this.table.columns),this},this.where=function(e){return this.whereClause.where(e)},this.execute=function(){for(var e=[],t=0;t0&&e.length==this.whereClause.LIMIT);t++)if(this.whereClause.finalConditions.length<1){for(var n={},r=0;r":(isNaN(parseFloat(this.table.data[t][this.table.colmap[u.col]]))||this.table.data[t][this.table.colmap[u.col]]u.value)&&(o=!1);break;case"=":this.table.data[t][this.table.colmap[u.col]]!=u.value&&(o=!1);break;case"!=":break;case"%%":this.table.data[t][this.table.colmap[u.col]].indexOf(u.value)<0&&(o=!1);break;case"%-":this.table.data[t][this.table.colmap[u.col]].indexOf(u.value)!=this.table.data[t][this.table.colmap[u.col]].length-u.value.length&&(o=!1);break;case"-%":0!=this.table.data[t][this.table.colmap[u.col]].indexOf(u.value)&&(o=!1)}if(!o)break}if(o){a=!0;break}}if(a){for(var n={},r=0;r0&&(e.sort(function(e,t){return function n(r){return void 0===this.whereClause.sortColumn[r]?0:e[this.whereClause.sortColumn[r]]t[this.whereClause.sortColumn[r]]?1:n(r+1)}(0)}),"DESC"==this.whereClause.sortDirection&&e.reverse()),this.resultSet=e,this},this.fetch=function(e){if(void 0===e&&(e="ASSOC"),e=e.toUpperCase(),"ASSOC"!==e&&"ARRAY"!==e)throw"Fetch expects paramter one to be 'ASSOC', 'ARRAY', or blank";if(!this.resultSet.length)return!1;var t=this.resultSet.shift();for(var n in t)if(t.hasOwnProperty(n)){var r=this.table.normalizeColumnFetchValue(n,t[n]);t[n]=r}if("ARRAY"==e){var r=[];for(var a in t)t.hasOwnProperty(a)&&r.push(t[a]);t=r}return t},this.fetchAll=function(e){if(void 0===e&&(e="ASSOC"),e=e.toUpperCase(),"ASSOC"!==e&&"ARRAY"!==e)throw"Fetch expects paramter one to be 'ASSOC', 'ARRAY', or blank";if(!this.resultSet.length)return!1;for(var t=[];this.resultSet.length>0;)t.push(this.fetch(e));return t},this.values=function(){throw"values() is not a valid method for a select query"},this.ifNotExists=function(){throw"ifNotExists() is not a valid method for a select query"},this.set=function(){throw"set() is not a valid method for a select query"}}function jSQLUpdateQuery(){this.init=function(e){if(void 0===jSQL.tables[e])throw"Table: "+e+" doesn't exist.";return this.table=this.table=jSQL.tables[e],this},this.set=function(e){this.newvals=e;for(var t in e)e.hasOwnProperty(t)&&this.columns.push(t);return this},this.where=function(e){return this.whereClause.where(e)},this.execute=function(e){if(void 0!==e&&Array.isArray(e))for(var t in this.newvals)this.newvals.hasOwnProperty(t)&&"?"==this.newvals[t]&&e.length&&(this.newvals[t]=e.shift());for(var n=[],t=0;t0&&n.length==this.whereClause.LIMIT);t++)if(this.whereClause.finalConditions.length<1){for(var r={},a=0;a":(isNaN(parseFloat(this.table.data[t][this.table.colmap[h.col]]))||this.table.data[t][this.table.colmap[h.col]]h.value)&&(l=!1);break;case"=":this.table.data[t][this.table.colmap[h.col]]!=h.value&&(l=!1);break;case"!=":break;case"%%":this.table.data[t][this.table.colmap[h.col]].indexOf(h.value)<0&&(l=!1);break;case"%-":this.table.data[t][this.table.colmap[h.col]].indexOf(h.value)!=this.table.data[t][this.table.colmap[h.col]].length-h.value.length&&(l=!1);break;case"-%":0!=this.table.data[t][this.table.colmap[h.col]].indexOf(h.value)&&(l=!1)}if(!l)break}if(l){i=!0;break}}if(i){for(var r={},a=0;a0&&"\\"===e[i-1])if(i>1&&"\\"===e[i-2]){r=!1,n.push(a.join(""));var a=[]}else a[a.length-1]=e[i];else{r=!1,n.push(a.join(""));var a=[]}else t=e[i],r=!0;else if(r){if("\\"===e[i]&&i>0&&"\\"===e[i-1])continue;a.push(e[i])}else if("?"===e[i])n.push("?");else if(" "!==e[i]&&","!==e[i])return n;return n},a=function(e){for(var n=e.split(","),r={},a="",i=0,s=0;s":e=e.greaterThan(t(r.shift()));break;case"<":e=e.lessThan(t(r.shift()));break;case"!=":case"<>":e=e.doesNotEqual(t(r.shift()));break;case"LIKE":var o=t(r.shift());e="%"==o.substr(0,1)&&"%"==o.substr(o.length-1,1)?e.contains(o.substr(1,o.length-2)):"%"==o.substr(0,1)?e.endsWith(o.substr(1,o.length-1)):"%"==o.substr(o.length-1,1)?e.beginsWith(o.substr(0,o.length-1)):"?"===o?e.preparedLike():e.equals(o);break;case"OR":var i;try{i=n(r.shift())}catch(s){throw s.message}e=e.or(i);break;case"LIMIT":e=e.limit(r.shift());break;case"ORDER":if("BY"!=r.shift().toUpperCase())throw"Expected 'ORDER BY', got something else.";for(;r.length>0;){var l=r.shift();try{for(;l.indexOf(",")==l.length-1;)l=l.substr(0,l.length-1);l=n(l),T.push(l)}catch(u){r.unshift(l);break}}e=e.orderBy(T);break;case"ASC":if(!T.length)throw"Must call ORDER BY before using ASC.";e=e.asc();break;case"DESC":if(!T.length)throw"Must call ORDER BY before using DESC.";e=e.desc()}}return e};e=e.replace(/(\r\n|\n|\r)/gm," ").replace(/ +(?= )/g,"").trim();var s=e.split(" ");switch(s.shift().toUpperCase()){case"DELETE":if("FROM"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'TABLE'";var o=t(s.shift());if(void 0===jSQL.tables[o])throw"Table "+o+" does not exist.";var e=jSQL.deleteFrom(o);return e=i(e,s);case"DROP":if("TABLE"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'TABLE'";var o=t(s.shift());if(void 0===jSQL.tables[o])throw"Table "+o+" does not exist.";return jSQL.dropTable(o);case"INSERT":var o,l=[],u=[];if("INTO"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'INTO'";if(o=t(s.shift()),void 0===jSQL.tables[o])throw"Table "+o+" does not exist.";s=s.join(" ").split("(").join(" ").split(")").join(" ").split(",").join(" ").split(" ").join(" ").trim().split(" ");for(var h=s.shift();s.length&&"VALUES"!==h.toUpperCase();)l.push(t(h)),h=s.shift();if("VALUES"!==h.toUpperCase())throw"Unintelligible query. Expected 'VALUES' near '"+h+"'";var c=s.join(" ");if(u=r(c),!l.length)for(var f=0;f0&&(w=m.substring(m.indexOf("(")+1,m.lastIndexOf(")"))),s=m.split("(").join(" ").split(")").join(" ").split(",").join(" ").split(" ").join(" ").trim().split(" "),o=t(s.shift()),"IF"===o.toUpperCase()){if("NOT"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'NOT'";if("EXISTS"!==s.shift().toUpperCase())throw"Unintelligible query. Expected 'EXISTS'";o=t(s.shift()),y=!0}d[o]={};for(var v=w.split(","),f=0;f-1){var g=(Q.match(/\(/g)||[]).length,b=(Q.match(/\)/g)||[]).length;if(g!==b)throw"Invalid Arg definition: "+Q;g>0&&(E=Q.substring(Q.indexOf("(")+1,Q.lastIndexOf(")")))}if(""!==E.trim())for(var L=E.split(","),j=0;jI)throw"Unintelligible query. Expected 'FROM'";x=s.splice(0,I);for(var f=x.length;f--;)for(;x[f].indexOf(",")==x[f].length-1;)x[f]=x[f].substr(0,x[f].length-1);s.shift(),o=s.shift();for(var O in jSQL.tables)if(jSQL.tables.hasOwnProperty(O)&&O.toUpperCase()==t(o.toUpperCase())){o=O;break}if(void 0===jSQL.tables[o])return new function(e){this.execute=function(){throw e},this.fetch=function(){throw e},this.fetchAll=function(){throw e}}("Table: "+o+" does not exist.");if(1==x.length&&"*"==x[0])x="*";else for(var f=0;f",value:e}),t.pendingColumn="",t},t.contains=function(e){if(""==t.pendingColumn)throw"Must add a 'where' clause before the 'contains' call.";return t.conditions.push({col:t.pendingColumn,type:"%%",value:e}),t.pendingColumn="",t},t.endsWith=function(e){if(""==t.pendingColumn)throw"Must add a 'where' clause before the 'endsWith' call.";return t.conditions.push({col:t.pendingColumn,type:"%-",value:e}),t.pendingColumn="",t},t.beginsWith=function(e){if(""==t.pendingColumn)throw"Must add a 'where' clause before the 'beginsWith' call.";return t.conditions.push({col:t.pendingColumn,type:"-%",value:e}),t.pendingColumn="",t},t.and=function(e){return t.where(e)},t.or=function(e){return t.finalConditions.push(t.conditions),t.conditions=[],t.where(e)},t.limit=function(e){return t.LIMIT=parseInt(e),t},t.orderBy=function(e){return Array.isArray(e)||(e=[e]),t.sortColumn=e,t},t.asc=function(){if(""==t.sortColumn)throw"Must use orderBy clause before using ASC";return t.sortDirection="ASC",t},t.desc=function(){if(""==t.sortColumn)throw"Must use orderBy clause before using DESC";return t.sortDirection="DESC",t},t.execute=function(e){if(void 0===e&&(e=[]),t.conditions.length>0&&t.finalConditions.push(t.conditions),e.length>0)for(var n=t.finalConditions.length;n--;)for(var r=t.finalConditions[n].length;r--;)if("?"===t.finalConditions[n][r].value&&"pl"===t.finalConditions[n][r].type){var a=e.pop();"%"==a.substr(0,1)&&"%"==a.substr(a.length-1,1)?(t.finalConditions[n][r].value=a.substr(1,a.length-2),t.finalConditions[n][r].type="%%"):"%"==a.substr(0,1)?(t.finalConditions[n][r].value=a.substr(1,a.length-1),t.finalConditions[n][r].type="%-"):"%"==a.substr(a.length-1,1)?(t.finalConditions[n][r].value=a.substr(0,a.length-1),t.finalConditions[n][r].type="-%"):(t.finalConditions[n][r].value=a,t.finalConditions[n][r].type="=")}else"?"===t.finalConditions[n][r].value&&e.length>0&&(t.finalConditions[n][r].value=e.pop());return t.context.execute(e)},t.fetch=function(e){return t.context.fetch(e)},t.fetchAll=function(e){return t.context.fetchAll(e)}}function WebSQLAPI(){var e=this;e.db=null;var t=function(t,n,r,a){"function"!=typeof r&&(r=function(){}),"function"!=typeof a&&(a=function(){throw"Could not execute query: "+t});var i,s,o;Array.isArray(n[0])||(n=[n]),o=n.length;var l=function(e,t){var n,a,i=[];if(o-=1,!o){for(n=0,a=t.rows.length;a>n;n+=1){var s=t.rows.item(n).json;i.push(s)}r(i)}};e.db.transaction(function(e){for(i=0,s=n.length;s>i;i+=1)e.executeSql(t,n[i],l,a)})};e.init=function(n,r){"function"!=typeof r&&(r=function(){});var a=function(){try{for(var r=n.length;r--;)(function(n,r){t("DROP TABLE IF EXISTS "+n,[],function(){t("CREATE TABLE IF NOT EXISTS "+n+"(json TEXT)",[],function(){e.insert(n,r)})})})(n[r].name,n[r].rows)}catch(a){throw"Error creating table"}};try{var i=window.location.href.replace(/\W+/g,"");e.db=openDatabase("jSQL_"+i,"1.0","jSQL "+i,5242880)}catch(s){throw"Error opening database"}t("SELECT COUNT(*) FROM "+n[0].name,[],null,function(){a()}),r()},e.insert=function(e,n,r){"function"!=typeof r&&(r=function(){});var a,i,s=n.length,o=[];for(0===s&&r(),a=0,i=n.length;i>a;a+=1)o[a]=[JSON.stringify(n[a])];t("INSERT INTO "+e+" (json) VALUES (?);",o,r)},e["delete"]=function(e,n){"function"!=typeof n&&(n=function(){}),t("DELETE FROM "+e,[],n)},e.select=function(e,n){t("SELECT json FROM "+e,[],function(e){for(var t=[],r=e.length;r--;)t.push(JSON.parse(e[r]));n(t)})}}function indexedDBAPI(){var e=this;e.db=null;var t,n,r;e.init=function(a,i){"function"!=typeof i&&(i=function(){});try{t=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.msIndexedDB,n=window.hasOwnProperty("IDBTransaction")?window.IDBTransaction:window.webkitIDBTransaction,r=window.hasOwnProperty("IDBKeyRange")?window.IDBKeyRange:window.webkitIndexedDB}catch(s){throw"indexedDB is not supported in this browser"}if(!t)throw"indexedDB is not supported in this browser";var o=1,l=window.location.href.replace(/\W+/g,""),u=t.open("jSQL_"+l,o),h=function(){for(var t=a.length;t--;)e.db.objectStoreNames.contains(a[t].name)&&e.db.deleteObjectStore(a[t].name),e.db.createObjectStore(a[t].name,{keyPath:"_id",autoIncrement:!0});var n=0,r=!1,i=setInterval(function(){if(!r){r=!0;try{for(var t=a.length;t--;){var s=a[t].name,o=void 0==a[t].rows?[]:a[t].rows;e.insert(s,o)}clearInterval(i)}catch(l){if(n>1e3)throw clearInterval(i),"Could not add data after 10 seconds.";r=!1}}},10)};u.onsuccess=function(t){var n;e.db=t.target.result,o=String(o),e.db.setVersion&&o!==e.db.version?(n=e.db.setVersion(o),n.onfailure=function(){throw"Error updating datastore version"},n.onsuccess=function(e){h(),n.result.oncomplete=function(){ +i()}}):i()},u.onupgradeneeded=function(t){e.db=t.target.result,h()},u.onerror=function(e){throw"Could not connect to the indexedDB datastore."}},e.insert=function(t,r,a){"function"!=typeof a&&(a=function(){});var i,s,o,l=e.db.transaction([t],void 0===n.READ_WRITE?"readwrite":n.READ_WRITE),u=r.length,h=function(){u-=1,0===u&&a(u)};l.onerror=function(){throw"Could not initiate a transaction"},i=l.objectStore(t);for(s in r)r.hasOwnProperty(s)&&(o=i.add(r[s]),o.onsuccess=h,o.onerror=function(){throw"Could not initiate a request"})},e["delete"]=function(t,r){"function"!=typeof r&&(r=function(){});var a,i,s=e.db.transaction([t],void 0===n.READ_WRITE?"readwrite":n.READ_WRITE);s.onerror=function(){throw"Could not initiate a transaction"},a=s.objectStore(t),i=a.clear(),i.onerror=function(){throw"Could not initiate a request"},i.onsuccess=r},e.select=function(t,r){"function"!=typeof r&&(r=function(){});var a,i,s=e.db.transaction([t],void 0===n.READ_ONLY?"readonly":n.READ_ONLY),o=[];s.onerror=function(){throw"Could not initiate a transaction"},a=s.objectStore(t),i=a.openCursor(),i.onerror=function(){throw"Could not initiate a request"};var l=!1;i.onsuccess=function(e){if(!l){var t=e.target.result;return t?(o.push(t.value),void t["continue"]()):(l=!0,void r(o))}}}}function createTable(e,t,n){if(void 0===t&&void 0===n&&"object"==typeof e){t=[],n=[];for(var r in e)if(e.hasOwnProperty(r)){var a=e[r];e=r;for(var i in a)a.hasOwnProperty(i)&&(t.push(i),n.push({type:a[i].type,args:void 0===a[i].args?[]:a[i].args}));break}}return Array.isArray(t)||(t=[t]),new jSQLQuery("CREATE").init(e,t,n)}function select(e){return Array.isArray(e)||(e=[e]),new jSQLQuery("SELECT").init(e)}function update(e){return new jSQLQuery("UPDATE").init(e)}function insertInto(e){return new jSQLQuery("INSERT").init(e)}function dropTable(e){return new jSQLQuery("DROP").init(e)}function deleteFrom(e){return new jSQLQuery("DELETE").init(e)}var persistenceManager=new function(){var e=this;e.api=null,e.error=!1,e.loaded=!1,e.isLoading=!1,e.loadingCallbacks=[],e.persist=function(t){if("function"==typeof t&&(t=function(){}),e.error!==!1)throw e.error;var n=[];for(var r in jSQL.tables)if(jSQL.tables.hasOwnProperty(r))for(var a=jSQL.select("*").from(r).execute().fetchAll(),i=a.length;i--;){var s=a[i];for(var o in s)s.hasOwnProperty(o)&&(s[o]=jSQL.tables[r].normalizeColumnStoreValue(o,s[o]));n.push({table:r,data:JSON.stringify(s),colTypes:JSON.stringify(jSQL.tables[r].types)})}e.api["delete"]("jSQL_data_schema",function(){e.api.insert("jSQL_data_schema",n,t)})},e.load=function(t){if("function"!=typeof t&&(t=function(){}),e.loadingCallbacks.push(t),e.loaded)for(;e.loadingCallbacks.length;)e.loadingCallbacks.shift()();e.isLoading||(e.isLoading=!0,function n(t){try{e.api.select("jSQL_data_schema",function(t){if(jSQL.tables={},0!==t.length){for(var n=t.length;n--;){var r=t[n].table,a=JSON.parse(t[n].data),i=JSON.parse(t[n].colTypes);if(void 0===jSQL.tables[r]){var s=[];for(var o in a)a.hasOwnProperty(o)&&s.push(o);jSQL.createTable(r,s,i).execute()}for(var o in a)a.hasOwnProperty(o)&&(a[o]=jSQL.tables[r].normalizeColumnFetchValue(o,a[o]));jSQL.tables[r].insertRow(a)}for(e.isLoading=!1,e.loaded=!0;e.loadingCallbacks.length;)e.loadingCallbacks.shift()()}else for(e.isLoading=!1,e.loaded=!0;e.loadingCallbacks.length;)e.loadingCallbacks.shift()()})}catch(r){if(t>500){for(e.isLoading=!1,e.loaded=!0;e.loadingCallbacks.length;)e.loadingCallbacks.shift()();return}setTimeout(function(){n(t+1)},10)}}(0))},function(){try{e.api=new indexedDBAPI,e.api.init([{name:"jSQL_data_schema",rows:[]}])}catch(t){try{e.api=new WebSQLAPI,e.api.init([{name:"jSQL_data_schema",rows:[]}])}catch(n){e.error="Browser doesn't support Web SQL or IndexedDB"}}}()};return{version:1.2,tables:{},query:jSQLParseQuery,createTable:createTable,dropTable:dropTable,select:select,update:update,deleteFrom:deleteFrom,insertInto:insertInto,types:new jSQLDataTypeList,persist:persistenceManager.persist,load:persistenceManager.load}}(); \ No newline at end of file