-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathjSQL.min.js
2 lines (2 loc) · 53.3 KB
/
jSQL.min.js
1
2
/*! jsql-official - v3.3.19 */
!function(){var isNode=!("undefined"==typeof module||!module.exports),jSQL=function(){"use strict";function jSQL_Error(e){this.error=e,this.stack=void 0;var t=new Error;t.stack&&(this.stack=t.stack),this.message=jSQL_Error.message_codes[e],this.toString=function(){return"jSQL Error #"+this.error+" - "+this.message}}function jSQL_Lexer_Error(e,t){var r=t.length>e+25?25:t.length-e,n=t.substr(e,r);this.error="0070",this.message="Unknown token near char "+e+" of "+t.length+' "'+n+'".',this.stack=void 0;var i=new Error;i.stack&&(this.stack=i.stack),this.toString=function(){return"jSQL Lexer Error #"+this.error+" - "+this.message}}function jSQL_Parse_Error(e,t){this.error="0071",this.message="Unexpected "+e.type+" ("+e.name+") at character "+e.input_pos+".",t&&(this.message+=" Expected "+t+"."),this.stack=void 0;var r=new Error;r.stack&&(this.stack=r.stack),this.toString=function(){return"jSQL Parse Error #"+this.error+" - "+this.message}}jSQL_Error.message_codes={"0001":"Corrupted function stored in data.","0003":"Invalid datatype definition.","0004":"DataType must have a `type` property.","0005":"DataType must have a `serialize` function.","0006":"DataType must have an `unserialize` function.","0007":"Unsupported data type.","0010":"Invalid constraint.","0011":"This table already has a primary key.","0012":"renameColumn expects and old column name and a new one, both must be strings.","0013":"Column does not exist.","0014":"Data must be an array.","0015":"Data not structured properly.","0016":"Cannot insert a null value in a primary column.","0017":"Primary Key violated.","0018":"Cannot insert a null value in a unique column.","0019":"Unique key violated.","0020":"Data type's serialize() method did not return a string.","0021":"Table does not exist.","0022":"Method does not apply to query type.","0023":"Fetch expects paramter one to be 'ASSOC', 'ARRAY', or undefined.","0024":"Expected number or quoted string.","0025":"Expected 'ORDER BY'.","0026":"Must call ORDER BY before using ASC.","0027":"Must call ORDER BY before using DESC.","0028":"Unintelligible query. Expected 'FROM'.","0029":"Unintelligible query. Expected 'TABLE'.","0030":"Unintelligible query. Expected 'INTO'.","0031":"Unintelligible query. Expected 'VALUES'.","0032":"Unintelligible query. Too many values.","0033":"Unintelligible query. Columns mismatch.","0034":"Invalid Column definition.","0035":"Unintelligible query. Expected 'NOT'.","0036":"Unintelligible query. Expected 'EXISTS'.","0037":"Unintelligible query. expected ')'.","0038":"Invalid Arg definition.","0039":"Unintelligible query. Expected 'SET'.","0040":"Unintelligible query. Expected 'FROM'.","0041":"Unintelligible query. WTF?","0042":"Must add a conditional before adding another 'Where' condition.","0043":"Column name must be a string.","0044":"Must add a 'where' clause before the 'equals' call.","0045":"Must add a 'where' clause before the 'preparedLike' call.","0046":"Must add a 'where' clause before the 'doesNotEqual' call.","0047":"Must add a 'where' clause before the 'lessThan' call.","0048":"Must add a 'where' clause before the 'greaterThan' call.","0049":"Must add a 'where' clause before the 'contains' call.","0050":"Must add a 'where' clause before the 'endsWith' call.","0051":"Must add a 'where' clause before the 'beginsWith' call.","0052":"Must use orderBy clause before using ASC.","0053":"Must use orderBy clause before using DESC.","0054":"Could not execute query.","0055":"Error creating table.","0056":"Error opening database.","0057":"indexedDB is not supported in this browser.","0058":"Could not add data after 10 seconds.","0059":"Error updating datastore version.","0060":"Could not connect to the indexedDB datastore.","0061":"Could not initiate a transaction.","0062":"Could not initiate a request.","0063":"Browser doesn't support Web SQL or IndexedDB.","0064":"Unable towrite to datastore file.","0065":"AUTO_INCREMENT column must be a key.","0066":"AUTO_INCREMENT column must be an INT type.","0067":"API is out of memory, cannot store more data.","0068":"Invalid ENUM value.","0069":"NUMERIC or INT type invalid or out of range.","0070":"Unknown Lexer Error.","0071":"Unknown Parser Error.","0072":"Inserting null into a non-null column."};var error_handler_function=function(){},mute_jsql_errors=!1;function _throw(e,t){throw!0!==t&&!0!==mute_jsql_errors&&error_handler_function(e),e}function onError(e){"function"==typeof e&&(error_handler_function=e)}function jSQLDataTypeList(){this.list=[{type:"NUMERIC",aliases:["NUMBER","DECIMAL","FLOAT"],serialize:function(e,t){return null===e&&(e=0),!isNaN(parseFloat(e))&&isFinite(e)?parseFloat(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseFloat(e))&&isFinite(e)?parseFloat(e):_throw(new jSQL_Error("0069"))}},{type:"ENUM",serialize:function(e,t){if(null===e)return"jsqlNull";for(var r=t.length;r--;)if(e===removeQuotes(t[r]))return e;return _throw(new jSQL_Error("0068"))},unserialize:function(e,t){if("jsqlNull"===e)return null;for(var r=t.length;r--;)if(e===removeQuotes(t[r]))return e;return _throw(new jSQL_Error("0068"))}},{type:"TINYINT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-128<=e&&e<=127?parseInt(e):0},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):0}},{type:"SMALLINT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-32768<=e&&e<=32767?parseInt(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):_throw(new jSQL_Error("0069"))}},{type:"MEDIUMINT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-8388608<=e&&e<=8388607?parseInt(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):_throw(new jSQL_Error("0069"))}},{type:"INT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-2147483648<=e&&e<=2147483647?parseInt(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):_throw(new jSQL_Error("0069"))}},{type:"BIGINT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-9007199254740991<=e&&e<=9007199254740991?parseInt(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):_throw(new jSQL_Error("0069"))}},{type:"JSON",aliases:["ARRAY","OBJECT"],serialize:function(e){return null===e?"jsqlNull":"string"==typeof e?e:JSON.stringify(e)},unserialize:function(e){return"jsqlNull"===e?null:JSON.parse(e)}},{type:"FUNCTION",serialize:function(value){if(null===value)return"jsqlNull";if("function"!=typeof value){var f=null;try{eval("f = "+value)}catch(e){}"function"==typeof f?value=f:_throw(new jSQL_Error("0001"))}return"jSQLFunct-"+value.toString()},unserialize:function(value){if("jsqlNull"===value)return null;var p=value.split("-");if("jSQLFunct"!==p.shift())return _throw(new jSQL_Error("0001"));p=value.split("-"),p.shift();var f=null;try{eval("f = "+p.join("-"))}catch(e){}return"function"==typeof f?f:_throw(new jSQL_Error("0001"))}},{type:"BOOLEAN",aliases:["BOOL"],serialize:function(e){return null===e?"jsqlNull":!0===e||"TRUE"==e.toUpperCase()||1==e?"1":"0"},unserialize:function(e){return"jsqlNull"===e?null:!0===e||"TRUE"==e.toUpperCase()||1==e}},{type:"CHAR",serialize:function(e,t){return null===e?"jsqlNull":""+e},unserialize:function(e,t){if("jsqlNull"===e)return null;var r=t[0]>>0,n=" ";return e.length>r?e.substr(0,t[0]):((r-=e.length)>n.length&&(n+=n.repeat(r/n.length)),String(e)+n.slice(0,r))}},{type:"VARCHAR",aliases:["LONGTEXT","MEDIUMTEXT"],serialize:function(e,t){return null===e?"jsqlNull":""+e},unserialize:function(e,t){return"jsqlNull"===e?null:""+e}},{type:"DATE",serialize:function(e){return null===e?"jsqlNull":e instanceof Date?e.getTime():new Date(e).getTime()},unserialize:function(e){return"jsqlNull"===e?null:new Date(e)}},{type:"AMBI",serialize:function(e){return null===e?"jsqlNull":e instanceof Date?e.getTime():"function"==typeof e?"jSQLFunct-"+e.toString():!isNaN(parseFloat(e))&&isFinite(e)?e:""+e},unserialize:function(value){if("jsqlNull"===value)return null;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){return"object"!=typeof e?_throw(new jSQL_Error("0003")):void 0===e.type?_throw(new jSQL_Error("0004")):"function"!=typeof e.serialize?_throw(new jSQL_Error("0005")):"function"!=typeof e.unserialize?_throw(new jSQL_Error("0006")):void 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&&-1<this.list[t].aliases.indexOf(e))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&&-1<this.list[t].aliases.indexOf(e))return this.list[t];return _throw(new jSQL_Error("0007"))}}function jSQLTable(e,t,r,n,i,s){var a=this;if(a.isTemp=!1,a.name="",a.columns=[],a.data=[],a.colmap={},a.types=[],a.auto_inc_col=!1,a.auto_inc_seq=0,a.keys={primary:{column:!1,map:{}},unique:[]},a.name=e,void 0===n&&(n=[]),Array.isArray(t)&&void 0===r&&(r=t,t=[]),Array.isArray(t)&&!Array.isArray(t[0])&&"object"==typeof t[0]){var o,u=[];for(o in t[0])t[0].hasOwnProperty(o)&&u.push(o);r=t,t=u}a.initColumns(t,n),a.initKeys(i,s),a.initAI(s),void 0!==r&&a.loadData(r)}function jSQLQuery(e){var r=this;r.type=e.toUpperCase(),r.tablename=null,r.columns=[],r.data=[],r.INEFlag=!1,r.coltypes=[],r.table=null,r.newvals={},r.whereClause=new jSQLWhereClause(r),r.resultSet=[],r.isTemp=!1;for(var n=["init","ifNotExists","execute","fetch","ignore","fetchAll","values","set","where","from","orderBy","asc","desc","limit","distinct","temporary"],i={CREATE:jSQLCreateQuery,UPDATE:jSQLUpdateQuery,SELECT:jSQLSelectQuery,INSERT:jSQLInsertQuery,DROP:jSQLDropQuery,DELETE:jSQLDeleteQuery},t=0;t<n.length;t++)!function(t){r[n[t]]=function(){var e=new i[r.type];return"function"==typeof e[n[t]]?e[n[t]].apply(r,arguments):_throw(new jSQL_Error("0022"))}}(t)}function jSQLDeleteQuery(){this.init=function(e){return void 0===jSQL.tables[e]?_throw(new jSQL_Error("0021")):(this.table=jSQL.tables[e],this)},this.execute=function(){for(var e=this.whereClause.getResultRowIndexes(),t=[],r=[],n=0;n<this.table.data.length;n++){var i,s=this.table.data[n],a=this.table.keys.primary.column,o=!1;if(!1!==a){var u;Array.isArray(a)||(a=[a]),o=[];for(var l=0;u=a[l];l++){var h=this.table.colmap[u];if(null===s[h])return _throw(new jSQL_Error("0016"));o.push(s[h])}o=JSON.stringify(o),this.table.keys.primary.map.hasOwnProperty(o)&&this.table.keys.primary.map[o]==n&&(-1<e.indexOf(n)?delete this.table.keys.primary.map[o]:this.table.keys.primary.map[o]=r.length)}for(var c=0;i=this.table.keys.unique[c];c++){for(var f,p=Array.isArray(i.column)?i.column:[i.column],y=[],m=0;f=p[m];m++){var S=this.table.colmap[f];if(null===s[S])return _throw(new jSQL_Error("0018"));y.push(s[S])}if(y=JSON.stringify(y),i.map.hasOwnProperty(y)&&i.map[y]==n){if(!0===this.ignoreFlag)return this;-1<e.indexOf(n)?delete this.table.keys.unique[c].map[y]:this.table.keys.unique[c].map[y]=r.length}}-1<e.indexOf(n)?t.push(s):r.push(this.table.data[n])}return this.table.data=r,this.resultSet=t,this},this.where=function(e){return this.whereClause.where(e)},this.fetch=function(){return null},this.fetchAll=function(){return[]},this.orderBy=function(e){return this.whereClause.orderBy(e)},this.asc=function(){return this.whereClause.asc()},this.desc=function(){return this.whereClause.desc()},this.limit=function(){return this.whereClause.limit()},this.distinct=function(){return this.whereClause.isDistinct=!0,this}}function jSQLDropQuery(){this.init=function(e){return this.tablename=e,this},this.execute=function(){return void 0===jSQL.tables[this.tablename]?_throw(new jSQL_Error("0021")):(delete jSQL.tables[this.tablename],this)},this.fetch=function(){return null},this.fetchAll=function(){return[]}}function jSQLInsertQuery(){this.init=function(e){return this.table=e,this.ignoreFlag=!1,this},this.values=function(e){return void 0===jSQL.tables[this.table]?_throw(new jSQL_Error("0021")):(this.data=e,this)},this.execute=function(e){if(void 0!==e&&Array.isArray(e)&&0<e.length)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());return jSQL.tables[this.table].insertRow(this.data,this.ignoreFlag),this},this.ignore=function(){return this.ignoreFlag=!0,this},this.fetch=function(){return null},this.fetchAll=function(){return[]}}function jSQLSelectQuery(){this.init=function(e){return this.columns=Array.isArray(e)?e:[e],this},this.from=function(e){return void 0===jSQL.tables[e]?_throw(new jSQL_Error("0021")):(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=this.whereClause.getResultRowIndexes(),t=[],r=0;r<e.length;r++)t.push(this.table.data[e[r]]);var n=[];for(r=0;r<t.length;r++){for(var i={},s=0;s<this.columns.length;s++)i[this.columns[s]]=t[r][this.table.colmap[this.columns[s]]];n.push(i)}return this.resultSet=n,this},this.fetch=function(e){if(void 0===e&&(e="ASSOC"),"ASSOC"!==(e=e.toUpperCase())&&"ARRAY"!==e)return _throw(new jSQL_Error("0023"));if(!this.resultSet.length)return!1;var t=this.resultSet.shift();for(var r in t)if(t.hasOwnProperty(r)){var n=this.table.normalizeColumnFetchValue(r,t[r]);t[r]=n}if("ARRAY"==e){n=[];for(var i in t)t.hasOwnProperty(i)&&n.push(t[i]);t=n}return t},this.fetchAll=function(e){if(void 0===e&&(e="ASSOC"),"ASSOC"!==(e=e.toUpperCase())&&"ARRAY"!==e)return _throw(new jSQL_Error("0023"));if(!this.resultSet.length)return!1;for(var t=[];0<this.resultSet.length;)t.push(this.fetch(e));return t},this.orderBy=function(e){return this.whereClause.orderBy(e)},this.asc=function(){return this.whereClause.asc()},this.desc=function(){return this.whereClause.desc()},this.limit=function(){return this.whereClause.limit()},this.distinct=function(){return this.whereClause.isDistinct=!0,this}}function jSQLUpdateQuery(){this.init=function(e){return void 0===jSQL.tables[e]?_throw(new jSQL_Error("0021")):(this.table=this.table=jSQL.tables[e],this.ignoreFlag=!1,this)},this.set=function(e){for(var t in this.newvals=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());var r=this.whereClause.getResultRowIndexes(),n=[],i=[];for(t=0;t<r.length;t++){for(var s=r[t],a=this.table.data[s].slice(0),o=0;o<this.columns.length;o++)this.columns[o]===this.table.auto_inc_col&&(this.newvals[this.columns[o]]||(this.newvals[this.columns[o]]=this.table.auto_inc_seq,this.table.auto_inc_seq++),this.newvals[this.columns[o]]>=this.table.auto_inc_seq&&(this.table.auto_inc_seq=this.newvals[this.columns[o]]+1)),a[this.table.colmap[this.columns[o]]]=this.table.normalizeColumnStoreValue(this.columns[o],this.newvals[this.columns[o]]);var u=this.table.keys.primary.column,l=!1;if(!1!==u){var h;Array.isArray(u)||(u=[u]),l=[];for(var c=0;h=u[c];c++){var f=this.table.colmap[h];if(null===a[f])return!0===this.ignoreFlag?this:_throw(new jSQL_Error("0016"));l.push(a[f])}if(l=JSON.stringify(l),this.table.keys.primary.map.hasOwnProperty(l)&&this.table.keys.primary.map[l]!==s)return!0===this.ignoreFlag?this:_throw(new jSQL_Error("0017"))}for(var p,y=[],m=0;p=this.table.keys.unique[m];m++){for(var S=Array.isArray(p.column)?p.column:[p.column],d=[],E=0;g=S[E];E++){var L=this.table.colmap[g];if(null===a[L])return!0===this.ignoreFlag?this:_throw(new jSQL_Error("0018"));d.push(a[L])}if(d=JSON.stringify(d),p.map.hasOwnProperty(d)&&p.map[d]!==s)return!0===this.ignoreFlag?this:_throw(new jSQL_Error("0019"));y.push(d)}i.push({rowIndex:s,row:a,pk_vals:l,uni_vals:y})}for(t=0;t<i.length;t++){for(var g in n.push(i[t].row),this.table.data[i[t].rowIndex]=i[t].row,this.table.keys.primary.map)if(this.table.keys.primary.map.hasOwnProperty(g)&&this.table.keys.primary.map[g]==i[t].rowIndex){delete this.table.keys.primary.map[g],this.table.keys.primary.map[i[t].pk_vals]=i[t].rowIndex;break}for(m=0;p=this.table.keys.unique[m];m++)for(var g in this.table.keys.unique[m].map)if(this.table.keys.unique[m].map.hasOwnProperty(g)&&this.table.keys.unique[m].map[g]==i[t].rowIndex){delete this.table.keys.unique[m].map[g],this.table.keys.unique[m].map[i[t].uni_vals[m]]=i[t].rowIndex;break}}return this.resultSet=n,this},this.fetch=function(){return null},this.fetchAll=function(){return[]},this.ignore=function(){return this.ignoreFlag=!0,this},this.orderBy=function(e){return this.whereClause.orderBy(e)},this.asc=function(){return this.whereClause.asc()},this.desc=function(){return this.whereClause.desc()},this.limit=function(){return this.whereClause.limit()},this.distinct=function(){return this.whereClause.isDistinct=!0,this}}function jSQLCreateQuery(){this.init=function(e,t,r,n,i){return this.tablename=e,this.columns=t,this.coltypes=r,this.keys=n,this.ai_col=i,this},this.ifNotExists=function(){return this.INEFlag=!0,this},this.execute=function(e){return void 0!==e&&(this.data=e),this.INEFlag&&jSQL.tables.hasOwnProperty(this.tablename)||(jSQL.tables[this.tablename]=new jSQLTable(this.tablename,this.columns,this.data,this.coltypes,this.keys,this.ai_col),this.isTemp&&(jSQL.tables[this.tablename].isTemp=!0)),this},this.temporary=function(){return this.isTemp=!0,this},this.fetch=function(){return null},this.fetchAll=function(){return[]}}function jSQLLexer(e){this.input=e,this.pos=0,this.real_pos=0,this.tokens=[],this.token_matches=[]}function jSQLToken(e,t,r){this.type_id=r,this.input_pos=e,this.literal=t,this.value=t,this.length=t.length,this.type=jSQLLexer.token_types[r].type,this.name=jSQLLexer.token_types[r].name,"IDENTIFIER"===this.type&&"UNQTD IDENTIFIER"===this.name&&jSQL.types.exists(this.literal)&&(this.name="DATA TYPE"),"IDENTIFIER"===this.type&&"QTD IDENTIFIER"===this.name&&(this.value=t.replace(/`/g,"")),"STRING"===this.type&&"DQ STRING"===this.name&&(this.value=t.substr(1,t.length-2).replace(/\"/g,'"')),"STRING"===this.type&&"SQ STRING"===this.name&&(this.value=t.substr(1,t.length-2).replace(/\'/g,"'")),"NUMBER"===this.type&&(this.value=parseFloat(this.literal)),"KEYWORD"===this.type&&"NULL"===this.name&&(this.value=null)}function jSQLParseQuery(e){var t=jSQL.tokenize(e);if(!t||!Array.isArray(t)||!t.length)return _throw(new jSQL_Error("0041"));if("DIRECTIVE"!==t[0].type)return _throw(new jSQL_Parse_Error(t[0],"DIRECTIVE"));switch(t.shift().name){case"CREATE":return jSQLParseCreateTokens(t);case"INSERT":return jSQLParseInsertTokens(t);case"SELECT":return jSQLParseSelectTokens(t);case"UPDATE":return jSQLParseUpdateTokens(t);case"DELETE FROM":return jSQLParseDeleteTokens(t);case"DROP TABLE":return jSQLParseDropTokens(t)}return _throw(new jSQL_Error("0041"))}function jSQLParseCreateTokens(e){var t,r=!1,n=!1,i=[],s={},a=!1;if("KEYWORD"===(t=e.shift()).type&&"TEMPORARY"===t.name&&(a=!0,t=e.shift()),"TABLE"!==t.name)return _throw(new jSQL_Parse_Error(t,"TABLE"));if("QUALIFIER"===(t=e.shift()).type&&"IF NOT EXISTS"===t.name&&(n=!0,t=e.shift()),"IDENTIFIER"===t.type&&(r=t.value),!r)return _throw(new jSQL_Parse_Error(t,"TABLE NAME"));if(s[r]=[],"SYMBOL"!==(t=e.shift()).type||"LEFT PEREN"!==t.name)return _throw(new jSQL_Parse_Error(t,"LEFT PEREN"));for(;e.length;)if("SYMBOL"!==(t=e.shift()).type||"COMMA"!==t.name){if("SYMBOL"===t.type&&"RIGHT PEREN"===t.name)break;if("KEYWORD"!==t.type||"UNIQUE KEY"!==t.name&&"PRIMARY KEY"!==t.name){if("IDENTIFIER"!==t.type)return _throw(new jSQL_Parse_Error(t,"COLUMN NAME"));var o=t.value,u={name:o,type:"AMBI",args:[],null:!0,default:void 0};if("DATA TYPE"===(t=e.shift()).name&&(u.type=t.literal.toUpperCase(),"SYMBOL"===(t=e.shift()).type&&"LEFT PEREN"===t.name)){for(;e.length;)if("SYMBOL"!==(t=e.shift()).type||"COMMA"!==t.name){if("SYMBOL"===t.type&&"RIGHT PEREN"===t.name)break;if("STRING"!==t.type&&"NUMBER"!==t.type)return _throw(new jSQL_Parse_Error(t,"DATA TYPE PARAM OR CLOSING PEREN"));u.args.push(t.value)}t=e.shift()}"KEYWORD"!==t.type||"NULL"!==t.name&&"NOT NULL"!==t.name||(u.null="NULL"===t.name,t=e.shift()),"KEYWORD"===t.type&&"DEFAULT"===t.name&&(u.default=e.shift().value,t=e.shift()),"KEYWORD"===t.type&&"AUTO_INCREMENT"===t.name&&(u.auto_increment=!0,t=e.shift()),"KEYWORD"!==t.type||"UNIQUE KEY"!==t.name&&"PRIMARY KEY"!==t.name||(i.push({column:o,type:t.name.split(" ")[0].toLowerCase()}),t=e.shift()),s[r].push(u)}else{var l=t.name.split(" ")[0].toLowerCase();if("SYMBOL"!==(t=e.shift()).type||"LEFT PEREN"!==t.name)return _throw(new jSQL_Parse_Error(t,"LEFT PEREN"));for(var h=[];e.length;)if("SYMBOL"!==(t=e.shift()).type||"COMMA"!==t.name){if("SYMBOL"===t.type&&"RIGHT PEREN"===t.name)break;if("IDENTIFIER"!==t.type)return _throw(new jSQL_Parse_Error(t,"COLUMN NAME"));var c=t.value;h.push(c)}if(!h.length)return _throw(new jSQL_Parse_Error(t,"COLUMN NAME"));i.push({column:h,type:l})}}if(e.length&&("SYMBOL"!==(t=e.shift()).type||"SEMICOLON"!==t.name))return _throw(new jSQL_Parse_Error(t,"END OF STATEMENT"));var f=jSQL.createTable(s,i);return a&&f.temporary(),n&&f.ifNotExists(),f}function jSQLParseInsertTokens(e){var t,r=[],n=[],i=!1,s=e.shift();if("KEYWORD"===s.type&&"IGNORE"===s.name&&(i=!0,s=e.shift()),"KEYWORD"!==s.type&&"INTO"===s.name)return _throw(new jSQL_Parse_Error(s,"INTO"));if(s=e.shift(),t=jSQLParseQuery.validateTableNameToken(s),"KEYWORD"!==(s=e.shift()).type&&"VALUES"!==s.name){if("SYMBOL"!==s.type||"LEFT PEREN"!==s.name)return _throw(new jSQL_Parse_Error(s,"COLUMN LIST OR VALUES"));for(;e.length;)if("SYMBOL"!==(s=e.shift()).type||"COMMA"!==s.name){if("SYMBOL"===s.type&&"RIGHT PEREN"===s.name){s=e.shift();break}if("IDENTIFIER"!==s.type)return _throw(new jSQL_Parse_Error(s,"COLUMN NAME"));var a=jSQLParseQuery.validateColumnName(s.value,t);r.push(a)}}if("KEYWORD"!==s.type&&"VALUES"!==s.name)return _throw(new jSQL_Parse_Error(s,"VALUES"));if("SYMBOL"!==(s=e.shift()).type||"LEFT PEREN"!==s.name)return _throw(new jSQL_Parse_Error(s,"VALUES LIST"));for(;e.length;)if("SYMBOL"!==(s=e.shift()).type||"COMMA"!==s.name){if("SYMBOL"===s.type&&"RIGHT PEREN"===s.name)break;n.push(s.value)}if(e.length&&("SYMBOL"!==(s=e.shift()).type||"SEMICOLON"!==s.name))return _throw(new jSQL_Parse_Error(s,"END OF STATEMENT"));if(!r.length)for(var o=0;o<n.length;o++){if(void 0===jSQL.tables[t].columns[o])return _throw(new jSQL_Error("0032"));r.push(jSQL.tables[t].columns[o])}if(n.length!==r.length)return _throw(new jSQL_Error("0033"));var u={};for(o=0;o<r.length;o++)u[r[o]]=n[o];var l=jSQL.insertInto(t).values(u);return i?l.ignore():l}function jSQLParseSelectTokens(e){var t,r,n=[],i=!1,s=e.shift();for("KEYWORD"===s.type&&"ALL"===s.name&&(s=e.shift()),"KEYWORD"!==s.type||"DISTINCT"!==s.name&&"DISTINCTROW"!==s.name||(i=!0,s=e.shift());e.length;)if(n.push(s.value),"SYMBOL"!==(s=e.shift()).type||"COMMA"!==s.name){if("KEYWORD"===s.type&&"FROM"===s.name)break}else s=e.shift();if("KEYWORD"!==s.type&&"FROM"!==s.name)return _throw(new jSQL_Parse_Error(s,"FROM"));if(s=e.shift(),t=jSQLParseQuery.validateTableNameToken(s),1==n.length&&"*"==n[0])n="*";else for(var a=0;a<n.length;a++)n[a]=jSQLParseQuery.validateColumnName(n[a],t);return r=jSQL.select(n).from(t),i&&(r=r.distinct()),r=jSQLParseWhereClause(r,e,t)}function jSQLParseUpdateTokens(e){var t,r={},n=e.shift();if(t=jSQLParseQuery.validateTableNameToken(n),"KEYWORD"!==(n=e.shift()).type&&"SET"!==n.name)return _throw(new jSQL_Parse_Error(n,"SET"));for(;e.length;){var i=jSQLParseQuery.validateColumnName(e.shift().value,t);if("SYMBOL"!==(n=e.shift()).type&&"EQUALS"!==n.name)return _throw(new jSQL_Parse_Error(n,"EQUALS"));var s=e.shift().value;if(r[i]=s,!e.length)break;if(("SYMBOL"!==(n=e.shift()).type||"COMMA"!==n.name)&&"KEYWORD"===n.type&&"WHERE"===n.name){e.unshift(n);break}}return jSQLParseWhereClause(jSQL.update(t).set(r),e,t)}function jSQLParseDeleteTokens(e){var t=e.shift(),r=jSQLParseQuery.validateTableNameToken(t),n=jSQL.deleteFrom(r);return n=jSQLParseWhereClause(n,e,r)}function jSQLParseDropTokens(e){var t=e.shift(),r=jSQLParseQuery.validateTableNameToken(t);return jSQL.dropTable(r)}function jSQLParseWhereClause(e,t,r){for(var n=[];t.length;){switch((u=t.shift()).type){case"KEYWORD":switch(u.name){case"WHERE":case"AND":e=e.where(jSQLParseQuery.validateColumnName(t.shift().value,r));break;case"LIKE":var i=t.shift().value;e="%"==i.substr(0,1)&&"%"==i.substr(i.length-1,1)?e.contains(i.substr(1,i.length-2)):"%"==i.substr(0,1)?e.endsWith(i.substr(1,i.length-1)):"%"==i.substr(i.length-1,1)?e.beginsWith(i.substr(0,i.length-1)):"?"===i?e.preparedLike():e.equals(i);break;case"OR":e=e.or(jSQLParseQuery.validateColumnName(t.shift().value,r));break;case"LIMIT":var s,a=t.shift().value,o=!1;if("SYMBOL"===(u=t.shift()).type&&"COMMA"===u.name?o=!0:t.unshift(u),o&&(s=a,a=t.shift().value),t.length&&!o)"KEYWORD"===(u=t.shift()).type&&"OFFSET"===u.name?s=t.shift().value:t.unshift(u);e=e.limit(a,s);break;case"ORDER BY":for(;t.length;){var u;if("SYMBOL"!==(u=t.shift()).type||"COMMA"!==u.name)try{var l=jSQLParseQuery.validateColumnName(u.value,r);n.push(l)}catch(e){t.unshift(u);break}}e=e.orderBy(n);break;case"ASC":if(!n.length)return _throw(new jSQL_Error("0026"));e=e.asc();break;case"DESC":if(!n.length)return _throw(new jSQL_Error("0027"));e=e.desc();break;default:return _throw(new jSQL_Parse_Error(u))}break;case"SYMBOL":switch(u.name){case"EQUALS":e=e.equals(t.shift().value);break;case"GREATER THAN":e=e.greaterThan(t.shift().value);break;case"LESS THAN":e=e.lessThan(t.shift().value);break;case"NOT EQUAL":e=e.doesNotEqual(t.shift().value);break;default:return _throw(new jSQL_Parse_Error(u))}break;default:return _throw(new jSQL_Parse_Error(u,"SYMBOL OR KEYWORD"))}}return e}function jSQLWhereClause(e){var S=this;S.context=e,S.pendingColumn="",S.conditions=[],S.LIMIT=0,S.OFFSET=0,S.finalConditions=[],S.sortColumn=[],S.sortDirection="ASC",S.isDistinct=!1,S.where=function(e){return""!==S.pendingColumn?_throw(new jSQL_Error("0042")):"string"!=typeof e?_throw(new jSQL_Error("0043")):(S.pendingColumn=e,S)},S.equals=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0044")):(S.conditions.push({col:S.pendingColumn,type:"=",value:e}),S.pendingColumn="",S)},S.preparedLike=function(){return""==S.pendingColumn?_throw(new jSQL_Error("0045")):(S.conditions.push({col:S.pendingColumn,type:"pl",value:"?"}),S.pendingColumn="",S)},S.doesNotEqual=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0046")):(S.conditions.push({col:S.pendingColumn,type:"!=",value:e}),S.pendingColumn="",S)},S.lessThan=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0047")):(S.conditions.push({col:S.pendingColumn,type:"<",value:e}),S.pendingColumn="",S)},S.greaterThan=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0048")):(S.conditions.push({col:S.pendingColumn,type:">",value:e}),S.pendingColumn="",S)},S.contains=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0049")):(S.conditions.push({col:S.pendingColumn,type:"%%",value:e}),S.pendingColumn="",S)},S.endsWith=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0050")):(S.conditions.push({col:S.pendingColumn,type:"%-",value:e}),S.pendingColumn="",S)},S.beginsWith=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0051")):(S.conditions.push({col:S.pendingColumn,type:"-%",value:e}),S.pendingColumn="",S)},S.and=function(e){return S.where(e)},S.or=function(e){return S.finalConditions.push(S.conditions),S.conditions=[],S.where(e)},S.limit=function(e,t){return S.LIMIT=parseInt(e),void 0!==t&&(S.OFFSET=parseInt(t)),S},S.orderBy=function(e){return Array.isArray(e)||(e=[e]),S.sortColumn=e,S},S.asc=function(){return""==S.sortColumn?_throw(new jSQL_Error("0052")):(S.sortDirection="ASC",S)},S.desc=function(){return""==S.sortColumn?_throw(new jSQL_Error("0053")):(S.sortDirection="DESC",S)},S.execute=function(e){if(void 0===e&&(e=[]),0<S.conditions.length&&S.finalConditions.push(S.conditions),0<e.length)for(var t=S.finalConditions.length;t--;)for(var r=S.finalConditions[t].length;r--;)if("?"===S.finalConditions[t][r].value&&"pl"===S.finalConditions[t][r].type){var n=e.pop();"%"==n.substr(0,1)&&"%"==n.substr(n.length-1,1)?(S.finalConditions[t][r].value=n.substr(1,n.length-2),S.finalConditions[t][r].type="%%"):"%"==n.substr(0,1)?(S.finalConditions[t][r].value=n.substr(1,n.length-1),S.finalConditions[t][r].type="%-"):"%"==n.substr(n.length-1,1)?(S.finalConditions[t][r].value=n.substr(0,n.length-1),S.finalConditions[t][r].type="-%"):(S.finalConditions[t][r].value=n,S.finalConditions[t][r].type="=")}else"?"===S.finalConditions[t][r].value&&0<e.length&&(S.finalConditions[t][r].value=e.pop());return S.context.execute(e)},S.fetch=function(e){return S.context.fetch(e)},S.fetchAll=function(e){return S.context.fetchAll(e)},S.getResultRowIndexes=function(){for(var e=[],t=0;t<S.context.table.data.length;t++)if(S.finalConditions.length<1)e.push(t);else{for(var r=!1,n=S.finalConditions.length;n--;){for(var i=S.finalConditions[n],s=!0,a=i.length;a--;){var o=i[a],u=S.context.table.colmap[o.col],l=S.context.table.data[t][u];switch(o.type){case">":(isNaN(parseFloat(l))||l<=o.value)&&(s=!1);break;case"<":(isNaN(parseFloat(l))||l>=o.value)&&(s=!1);break;case"=":l!=o.value&&(s=!1);break;case"!=":break;case"%%":l.indexOf(o.value)<0&&(s=!1);break;case"%-":l.indexOf(o.value)!=l.length-o.value.length&&(s=!1);break;case"-%":0!=l.indexOf(o.value)&&(s=!1)}if(!s)break}if(s){r=!0;break}}r&&e.push(t)}if(0<S.sortColumn.length&&(e.sort(function(i,s){return i=S.context.table.data[i],s=S.context.table.data[s],function e(t){if(void 0===S.sortColumn[t])return 0;var r=S.sortColumn[t],n=S.context.table.colmap[r];return i[n]<s[n]?-1:i[n]>s[n]?1:e(t+1)}(0)}),"DESC"==S.sortDirection&&e.reverse()),S.isDistinct){var h=[];for(t=0;t<e.length;t++)h.push(S.context.table.data[e[t]]);var c=[],f=[];for(t=0;t<h.length;t++){for(var p={},y=0;y<S.context.columns.length;y++)p[S.context.columns[y]]=h[t][S.context.table.colmap[S.context.columns[y]]];var m=JSON.stringify(p);-1<c.indexOf(m)||(f.push(e[t]),c.push(m))}e=f}return 0<S.LIMIT&&e.length>S.LIMIT&&(S.OFFSET>e.length&&(e=[]),S.LIMIT>e.length&&(S.LIMIT=e.length),e.length&&(e=e.slice(S.OFFSET,S.OFFSET+S.LIMIT))),e}}jSQLTable.prototype.initColumns=function(e,t){var r;for(this.columns=e,r=0;r<e.length;r++)this.types[r]=void 0===t[r]||void 0===t[r].type?{type:"ambi",args:[],default:void 0,null:!0}:t[r];for(r=this.types.length;r--;){var n=this.types[r].type.toUpperCase();if(!jSQL.types.exists(n))return _throw(new jSQL_Error("0007"));this.types[r].type=n}for(r=0;r<e.length;r++)this.colmap[e[r]]=r},jSQLTable.prototype.initKeys=function(e){for(var t,r=["primary","unique"],n=0;n<e.length;n++){if(!(t=e[n]).hasOwnProperty("column")||!Array.isArray(t.column)&&-1===this.columns.indexOf(t.column))return _throw(new jSQL_Error("0010"));if(Array.isArray(t.column))for(var i=0;i<t.column.length;i++)if(-1===this.columns.indexOf(t.column[i]))return _throw(new jSQL_Error("0010"));var s=t.hasOwnProperty("type")&&-1!==r.indexOf(t.type.toLowerCase())?t.type.toLowerCase():"unique";if("primary"===s&&!1!==this.keys.primary.column)return _throw(new jSQL_Error("0011"));"primary"===s&&(this.keys.primary.column=t.column),"unique"===s&&this.keys.unique.push({column:t.column,map:{}})}},jSQLTable.prototype.initAI=function(e){if(e){for(var t=Array.isArray(this.keys.primary.column)&&-1<this.keys.primary.column.indexOf(e),r=this.keys.primary.column===e,n=!1,i=this.keys.unique.length;i--;){var s=Array.isArray(this.keys.unique[i].column)&&-1<this.keys.unique[i].column.indexOf(e),a=this.keys.unique[i].column===e;(s||a)&&(n=!0)}if(!(t||r||n))return _throw(new jSQL_Error("0065"));if("INT"!==this.types[this.colmap[e]].type)return _throw(new jSQL_Error("0066"));this.auto_inc_col=e}},jSQLTable.prototype.renameColumn=function(e,t){if(void 0===e||"string"!=typeof t)return _throw(new jSQL_Error("0012"));if(this.columns.indexOf(e)<0)return _throw(new jSQL_Error("0013"));if(this.columns.splice(this.columns.indexOf(e),1,t),this.keys.primary.column===e&&(this.keys.primary.column=t),Array.isArray(this.keys.primary.column))for(var r=this.keys.primary.column.length;r--;)this.keys.primary.column[r]===e&&(this.keys.primary.column[r]=t);for(var n=this.keys.unique.length;n--;)if(this.keys.unique[n].column===e&&(this.keys.unique[n].column=t),Array.isArray(this.keys.unique[n].column))for(r=this.keys.unique[n].column.length;r--;)this.keys.unique[n].column[r]===e&&(this.keys.unique[n].column[r]=t);var i={};for(var s in this.colmap)this.colmap.hasOwnProperty(s)&&(s===e?i[t]=this.colmap[s]:i[s]=this.colmap[s]);this.colmap=i,this.auto_inc_col===e&&(this.auto_inc_col=t)},jSQLTable.prototype.addColumn=function(e,t,r){if(void 0!==r&&void 0!==r.type||(r={type:"AMBI",args:[],null:!0,default:void 0}),r.type=r.type.toUpperCase(),void 0===t&&(t=null),"string"!=typeof e){var n=this;e=function e(t){for(var r=0;r<n.columns.length;r++)if(n.columns[r]==="u"+t)return e(t+1);return"u"+t}(0)}this.columns.push(e);for(var i=this.data.length;i--;)this.data[i].push(t);if(this.colmap[e]=this.columns.length-1,!jSQL.types.exists(r.type))return _throw(new jSQL_Error("0007"));this.types.push(r)},jSQLTable.prototype.loadData=function(e){if(!Array.isArray(e))return _throw(new jSQL_Error("0014"));for(var t=e.length;t--;)this.insertRow(e[t])},jSQLTable.prototype.normalizeInsertRowData=function(e){var t,r=[];if(Array.isArray(e)){for(;e.length>this.columns.length;)this.addColumn();for(;e.length<this.columns.length;)e.push(null);for(t=0;t<e.length;t++)r.push(e[t]);for(;r.length<this.columns.length;)r.push(null)}else{if("object"!=typeof e)return _throw(new jSQL_Error("0015"));for(t=0;t<this.columns.length;t++)void 0===e[this.columns[t]]&&(e[this.columns[t]]=null);var n=this;for(var i in e)if(!e.hasOwnProperty(i))continue;if(function(e){for(;e--;)if(n.columns[e]===i)return 0;return 1}(this.columns.length))if(-1<this.columns.indexOf("u0")){this.renameColumn("u0",i);for(;-1<this.columns.indexOf("u1");)this.renameColumn("u1","u0")}else this.addColumn(i);for(t=0;t<this.columns.length;t++)r.push(e[this.columns[t]])}return r},jSQLTable.prototype.insertRow=function(e,t){for(var r=this.normalizeInsertRowData(e),n=r.length;n--;)this.columns[n]===this.auto_inc_col&&(r[n]||(r[n]=this.auto_inc_seq,this.auto_inc_seq++),r[n]>=this.auto_inc_seq&&(this.auto_inc_seq=parseInt(r[n],10)+1)),r[n]=this.normalizeColumnStoreValue(this.columns[n],r[n]);if(!1===this.updateKeysOnInsert(r,t))return!1;this.data.push(r)},jSQLTable.prototype.updateKeysOnInsert=function(e,t){if(this.keys.primary.column){for(var r,n=Array.isArray(this.keys.primary.column)?this.keys.primary.column:[this.keys.primary.column],i=[],s=0;s<n.length;s++){r=n[s];var a=this.colmap[r];if(null===e[a])return!0!==t&&_throw(new jSQL_Error("0016"));i.push(e[a])}if(i=JSON.stringify(i),this.keys.primary.map.hasOwnProperty(i))return!0!==t&&_throw(new jSQL_Error("0017"));this.keys.primary.map[i]=this.data.length}for(var o,u=0;u<this.keys.unique.length;u++){o=this.keys.unique[u];for(var l,h=Array.isArray(o.column)?o.column:[o.column],c=[],f=0;f<h.length;f++){l=h[f];var p=this.colmap[l];if(null===e[p])return!0!==t&&_throw(new jSQL_Error("0018"));c.push(e[p])}if(c=JSON.stringify(c),o.map.hasOwnProperty(c))return!0!==t&&_throw(new jSQL_Error("0019"));this.keys.unique[u].map[c]=this.data.length}},jSQLTable.prototype.normalizeColumnStoreValue=function(e,t){var r=this.types[this.colmap[e]];if(-1<[!1,void 0].indexOf(r.null)&&null===t)return _throw(new jSQL_Error("0072"));null===t&&void 0!==r.default&&(t=r.default);var n=jSQL.types.getByType(r.type.toUpperCase()).serialize(t,r.args);return!isNaN(parseFloat(n))&&isFinite(n)||"string"==typeof n?n:_throw(new jSQL_Error("0020"))},jSQLTable.prototype.normalizeColumnFetchValue=function(e,t){var r=this.types[this.colmap[e]];return jSQL.types.getByType(r.type.toUpperCase()).unserialize(t,r.args)},jSQLLexer.prototype.getNextToken=function(){for(var e,t=0;t<jSQLLexer.token_types.length;t++)for(;null!=(e=jSQLLexer.token_types[t].pattern.exec(this.input));)if(e.index===this.pos){var r=new jSQLToken(this.pos,e[0],t);return this.pos+=r.length,r}return!1},jSQLLexer.prototype.getTokens=function(){if(this.tokens.length)return this.tokens;this.pos=0,this.tokens=[];for(var e,t=["COMMENT","WHITESPACE"];0!=(e=this.getNextToken());)-1===t.indexOf(e.type)&&this.tokens.push(e);if(this.pos!==this.input.length){var r;if(this.tokens.length){var n=this.tokens[this.tokens.length-1];r=n.input_pos+n.length}else r=0;return console.log(this.tokens.map(function(e){return e.literal}).join(" ")),_throw(new jSQL_Lexer_Error(r,this.input))}return this.tokens},jSQLLexer.token_types=[{pattern:/"(?:[^"\\]|\\.)*"/g,type:"STRING",name:"DQ STRING"},{pattern:/'(?:[^'\\]|\\.)*'/g,type:"STRING",name:"SQ STRING"},{pattern:/--.*[\n\r$]/g,type:"COMMENT",name:"SINGLE LINE COMMENT"},{pattern:/\/\*([\s\S]*?)\*\//g,type:"COMMENT",name:"MULTI LINE COMMENT"},{pattern:/\r?\n|\r/g,type:"WHITESPACE",name:"LINEBREAK"},{pattern:/[ \t]/g,type:"WHITESPACE",name:"WHITESPACE"},{pattern:/[?-]?\d+.\.\d+/g,type:"NUMBER",name:"FLOAT"},{pattern:/[?-]?\d+/g,type:"NUMBER",name:"INTEGER"},{pattern:/if not exists/gi,type:"QUALIFIER",name:"IF NOT EXISTS"},{pattern:/!=/gi,type:"SYMBOL",name:"NOT EQUAL"},{pattern:/<>/gi,type:"SYMBOL",name:"NOT EQUAL"},{pattern:/\(/gi,type:"SYMBOL",name:"LEFT PEREN"},{pattern:/\)/gi,type:"SYMBOL",name:"RIGHT PEREN"},{pattern:/,/gi,type:"SYMBOL",name:"COMMA"},{pattern:/\?/gi,type:"SYMBOL",name:"QUESTION MARK"},{pattern:/,/gi,type:"SYMBOL",name:"COMMA"},{pattern:/\*/gi,type:"SYMBOL",name:"ASTERISK"},{pattern:/;/gi,type:"SYMBOL",name:"SEMICOLON"},{pattern:/=/gi,type:"SYMBOL",name:"EQUALS"},{pattern:/>/gi,type:"SYMBOL",name:"GREATER THAN"},{pattern:/</gi,type:"SYMBOL",name:"LESS THAN"},{pattern:/primary key/gi,type:"KEYWORD",name:"PRIMARY KEY"},{pattern:/unique key/gi,type:"KEYWORD",name:"UNIQUE KEY"},{pattern:/values(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"VALUES"},{pattern:/temporary(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"TEMPORARY"},{pattern:/from(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"FROM"},{pattern:/auto_increment(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"AUTO_INCREMENT"},{pattern:/ignore(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"IGNORE"},{pattern:/into(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"INTO"},{pattern:/all(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"ALL"},{pattern:/distinct(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"DISTINCT"},{pattern:/distinctrow(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"DISTINCTROW"},{pattern:/where(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"WHERE"},{pattern:/and(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"AND"},{pattern:/like(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"LIKE"},{pattern:/order by/gi,type:"KEYWORD",name:"ORDER BY"},{pattern:/or(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"OR"},{pattern:/limit(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"LIMIT"},{pattern:/offset(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"OFFSET"},{pattern:/asc(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"ASC"},{pattern:/desc(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"DESC"},{pattern:/set(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"SET"},{pattern:/not null/gi,type:"KEYWORD",name:"NOT NULL"},{pattern:/null(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"NULL"},{pattern:/default(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"DEFAULT"},{pattern:/table(?=[\s(`,]|$)/gi,type:"KEYWORD",name:"TABLE"},{pattern:/create(?=[\s(`,]|$)/gi,type:"DIRECTIVE",name:"CREATE"},{pattern:/insert(?=[\s(`,]|$)/gi,type:"DIRECTIVE",name:"INSERT"},{pattern:/delete from/gi,type:"DIRECTIVE",name:"DELETE FROM"},{pattern:/drop table/gi,type:"DIRECTIVE",name:"DROP TABLE"},{pattern:/update(?=[\s(`,]|$)/gi,type:"DIRECTIVE",name:"UPDATE"},{pattern:/select(?=[\s(`,]|$)/gi,type:"DIRECTIVE",name:"SELECT"},{pattern:/`[0-9a-zA-Z$_]*[0-9a-zA-Z$_]`/gi,type:"IDENTIFIER",name:"QTD IDENTIFIER"},{pattern:/[0-9a-zA-Z$_]*[0-9a-zA-Z$_]/gi,type:"IDENTIFIER",name:"UNQTD IDENTIFIER"}],jSQLParseQuery.validateTableNameToken=function(e){for(var t in jSQL.tables)if(jSQL.tables.hasOwnProperty(t)&&e.value.toUpperCase()==t.toUpperCase())return t;return _throw(new jSQL_Error("0021"))},jSQLParseQuery.validateColumnName=function(e,t){for(var r=jSQL.tables[t].columns.length;r--;)if(e.toUpperCase()===jSQL.tables[t].columns[r].toUpperCase())return jSQL.tables[t].columns[r];return _throw(new jSQL_Error("0013"))};var API={cookieAPI:function(){var i=this,o=function(e,t){var r=new Date;r.setTime(r.getTime()+864e9);var n="expires="+r.toUTCString();document.cookie=e+"="+t+";"+n+";path=/"},u=function(e){for(var t=e+"=",r=document.cookie.split(";"),n=0;n<r.length;n++){for(var i=r[n];" "==i.charAt(0);)i=i.substring(1);if(0==i.indexOf(t))return i.substring(t.length,i.length)}return""};i.init=function(e,t){"function"!=typeof t&&(t=function(){});for(var r,n=0;r=e[n];n++)i.insert(r.name,r.rows);t()},i.insert=function(e,t,r){var n;"function"!=typeof r&&(r=function(){});try{n=JSON.parse(u(e))}catch(e){n=[]}Array.isArray(n)||(n=[]);for(var i=0;i<t.length;i++)n.push(t[i]);var s=JSON.stringify(n);if(o(e,s),u(e)!==s){for(var a=100;a--&&u(e)!==s;)n.pop(),s=JSON.stringify(n),o(e,s);return _throw(new jSQL_Error("0067"))}r()},i.delete=function(e,t){"function"!=typeof t&&(t=function(){}),o(e,JSON.stringify([])),t()},i.select=function(e,t){"function"!=typeof t&&(t=function(){}),t(JSON.parse(u(e)))}},localStorageAPI:function(){var i=this;i.init=function(e,t){"function"!=typeof t&&(t=function(){});for(var r,n=0;r=e[n];n++)i.insert(r.name,r.rows);t()},i.insert=function(e,t,r){var n;"function"!=typeof r&&(r=function(){});try{n=JSON.parse(localStorage.getItem(e))}catch(e){n=[]}Array.isArray(n)||(n=[]);for(var i=0;i<t.length;i++)n.push(t[i]);var s=JSON.stringify(n);if(localStorage.setItem(e,s),localStorage.getItem(e)!==s){for(var a=100;a--&&localStorage.getItem(e)!==s;)n.pop(),s=JSON.stringify(n),localStorage.setItem(e,s);return _throw(new jSQL_Error("0067"))}r()},i.delete=function(e,t){"function"!=typeof t&&(t=function(){}),localStorage.setItem(e,JSON.stringify([])),t()},i.select=function(e,t){"function"!=typeof t&&(t=function(){}),t(JSON.parse(localStorage.getItem(e)))}},nodeAPI:function(){var e=this;e.db=null;var a=require("fs");e.init=function(e,t){if("function"!=typeof t&&(t=function(){}),!a.existsSync(".jsqldatastore"))try{a.writeFileSync(".jsqldatastore",JSON.stringify(e))}catch(e){return _throw(new jSQL_Error("0064"))}t()},e.insert=function(e,t,r){"function"!=typeof r&&(r=function(){});var n,i=JSON.parse(a.readFileSync(".jsqldatastore",{encoding:"utf8"}));for(n=i.length;n--&&!i[n].name===e;);for(var s=0;s<t.length;s++)i[n].rows.push(t[s]);a.writeFileSync(".jsqldatastore",JSON.stringify(i)),r()},e.delete=function(e,t){"function"!=typeof t&&(t=function(){});for(var r=JSON.parse(a.readFileSync(".jsqldatastore",{encoding:"utf8"})),n=r.length;n--;)if(!r[n].name!==e){r[n].rows=[];break}a.writeFileSync(".jsqldatastore",JSON.stringify(r)),t()},e.select=function(e,t){"function"!=typeof t&&(t=function(){});for(var r=JSON.parse(a.readFileSync(".jsqldatastore",{encoding:"utf8"})),n=r.length;n--;)if(!r[n].name!==e)return void t(r[n].rows)}},indexedDBAPI:function(){var a,l,h=this;h.db=null,h.init=function(s,r){"function"!=typeof r&&(r=function(){});try{a=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.msIndexedDB,l=window.hasOwnProperty("IDBTransaction")?window.IDBTransaction:window.webkitIDBTransaction,window.hasOwnProperty("IDBKeyRange")?window.IDBKeyRange:window.webkitIndexedDB}catch(e){return _throw(new jSQL_Error("0057"))}if(!a)return _throw(new jSQL_Error("0057"));var n=1,e=window.location.href.replace(/\W+/g,""),t=a.open("jSQL_"+e,n),i=function(){for(var e=s.length;e--;)h.db.objectStoreNames.contains(s[e].name)&&h.db.deleteObjectStore(s[e].name),h.db.createObjectStore(s[e].name,{keyPath:"_id",autoIncrement:!0});var n=!1,i=setInterval(function(){if(!n){n=!0;try{for(var e=s.length;e--;){var t=s[e].name,r=null==s[e].rows?[]:s[e].rows;h.insert(t,r)}clearInterval(i)}catch(e){0,n=!1}}},10)};t.onsuccess=function(e){var t;h.db=e.target.result,n=String(n),h.db.setVersion&&n!==h.db.version?((t=h.db.setVersion(n)).onfailure=function(){return _throw(new jSQL_Error("0059"))},t.onsuccess=function(e){i(),t.result.oncomplete=function(){r()}}):r()},t.onupgradeneeded=function(e){h.db=e.target.result,i()},t.onerror=function(e){return _throw(new jSQL_Error("0060"))}},h.insert=function(e,t,r){"function"!=typeof r&&(r=function(){});var n,i,s,a=h.db.transaction([e],void 0===l.READ_WRITE?"readwrite":l.READ_WRITE),o=t.length,u=function(){0===(o-=1)&&r(o)};for(i in a.onerror=function(){return _throw(new jSQL_Error("0061"))},n=a.objectStore(e),t)t.hasOwnProperty(i)&&((s=n.add(t[i])).onsuccess=u,s.onerror=function(){return _throw(new jSQL_Error("0062"))})},h.delete=function(e,t){"function"!=typeof t&&(t=function(){});var r,n=h.db.transaction([e],void 0===l.READ_WRITE?"readwrite":l.READ_WRITE);n.onerror=function(){return _throw(new jSQL_Error("0061"))},(r=n.objectStore(e).clear()).onerror=function(){return _throw(new jSQL_Error("0062"))},r.onsuccess=t},h.select=function(e,r){"function"!=typeof r&&(r=function(){});var t,n=h.db.transaction([e],void 0===l.READ_ONLY?"readonly":l.READ_ONLY),i=[];n.onerror=function(){return _throw(new jSQL_Error("0061"))};var s=!((t=n.objectStore(e).openCursor()).onerror=function(){return _throw(new jSQL_Error("0062"))});t.onsuccess=function(e){if(!s){var t=e.target.result;if(!t)return s=!0,void r(i);i.push(t.value),t.continue()}}}},WebSQLAPI:function(){var l=this;l.db=null;var a=function(t,r,a,n){var i,s,o;"function"!=typeof a&&(a=function(){}),"function"!=typeof n&&(n=function(){return _throw(new jSQL_Error("0054"))}),Array.isArray(r[0])||(r=[r]),o=r.length;var u=function(e,t){var r,n,i=[];if(!(o-=1)){for(r=0,n=t.rows.length;r<n;r+=1){var s=t.rows.item(r).json;i.push(s)}a(i)}};l.db.transaction(function(e){for(i=0,s=r.length;i<s;i+=1)e.executeSql(t,r[i],u,n)})};l.init=function(t,e){"function"!=typeof e&&(e=function(){});try{var r=window.location.href.replace(/\W+/g,"");l.db=openDatabase("jSQL_"+r,"1.0","jSQL "+r,5242880)}catch(e){return _throw(new jSQL_Error("0056"))}a("SELECT COUNT(*) FROM "+t[0].name,[],null,function(){!function(){try{for(var e=t.length;e--;)!function(e,t){a("DROP TABLE IF EXISTS "+e,[],function(){a("CREATE TABLE IF NOT EXISTS "+e+"(json TEXT)",[],function(){l.insert(e,t)})})}(t[e].name,t[e].rows)}catch(e){return _throw(new jSQL_Error("0055"))}}()}),e()},l.insert=function(e,t,r){"function"!=typeof r&&(r=function(){});var n,i,s=[];for(0===t.length&&r(),n=0,i=t.length;n<i;n+=1)s[n]=[JSON.stringify(t[n])];a("INSERT INTO "+e+" (json) VALUES (?);",s,r)},l.delete=function(e,t){"function"!=typeof t&&(t=function(){}),a("DELETE FROM "+e,[],t)},l.select=function(e,n){a("SELECT json FROM "+e,[],function(e){for(var t=[],r=e.length;r--;)t.push(JSON.parse(e[r]));n(t)})}}},persistenceManager=new function(){var u=this;u.api=null,u.error=!1,u.loaded=!1,u.isLoading=!1,u.initiated=!1,u.loadingCallbacks=[],u.api_default_priority=["indexedDBAPI","WebSQLAPI","localStorageAPI","cookieAPI"],u.api_user_priority=[],u.setApiPriority=function(){u.api_user_priority=1===arguments.length?[arguments[0]]:Array.apply(null,arguments)},u.getApi=function(){var t=!1;try{t=u.api.constructor.name}catch(e){t=!1}return t},u.commit=function(e){if("function"==typeof e&&(e=function(){}),!1!==u.error)return _throw(u.error);var t=[];for(var r in jSQL.tables)if(jSQL.tables.hasOwnProperty(r)&&!jSQL.tables[r].isTemp){for(var n=[],i=0;i<jSQL.tables[r].keys.unique.length;i++)n.push({column:jSQL.tables[r].keys.unique[i].column,type:"unique"});jSQL.tables[r].keys.primary.column&&n.push({column:jSQL.tables[r].keys.primary.column,type:"primary"});var s=jSQL.select("*").from(r).execute().fetchAll();s.length||t.push({table:r,data:JSON.stringify(jSQL.tables[r].columns),colTypes:JSON.stringify(jSQL.tables[r].types),keys:JSON.stringify(n),ai_col:jSQL.tables[r].auto_inc_col});for(i=s.length;i--;){var a=s[i];for(var o in a)a.hasOwnProperty(o)&&(a[o]=jSQL.tables[r].normalizeColumnStoreValue(o,a[o]));t.push({table:r,data:JSON.stringify(a),colTypes:JSON.stringify(jSQL.tables[r].types),keys:JSON.stringify(n),ai_col:jSQL.tables[r].auto_inc_col})}}u.api.delete("jSQL_data_schema",function(){u.api.insert("jSQL_data_schema",t,e)})},u.load=function(e){if("function"!=typeof e&&(e=function(){}),u.loadingCallbacks.push(e),u.loaded)for(;u.loadingCallbacks.length;)u.loadingCallbacks.shift()();u.isLoading||(u.isLoading=!0,u.initiated?u.rollback(function(){for(u.isLoading=!1,u.loaded=!0;u.loadingCallbacks.length;)u.loadingCallbacks.shift()()}):u.init(function(){u.rollback(function(){for(u.isLoading=!1,u.loaded=!0;u.loadingCallbacks.length;)u.loadingCallbacks.shift()()})}))},u.rollback=function(l){"function"!=typeof l&&(l=function(){}),mute_jsql_errors=!0,function t(r){try{u.api.select("jSQL_data_schema",function(e){if(jSQL.tables={},0===e.length)return mute_jsql_errors=!1,void l();for(var t=e.length;t--;){var r=e[t].table,n=JSON.parse(e[t].data),i=JSON.parse(e[t].colTypes),s=JSON.parse(e[t].keys),a=e[t].ai_col;if(void 0===jSQL.tables[r])if(Array.isArray(n))o=n,jSQL.createTable(r,o,i,s,a).execute();else{var o=[];for(var u in n)n.hasOwnProperty(u)&&o.push(u);jSQL.createTable(r,o,i,s,a).execute()}if(!Array.isArray(n)){for(var u in n)n.hasOwnProperty(u)&&(n[u]=jSQL.tables[r].normalizeColumnFetchValue(u,n[u]));jSQL.tables[r].insertRow(n,!0)}}mute_jsql_errors=!1,l()})}catch(e){if(500<r){for(mute_jsql_errors=!1,u.isLoading=!1,u.loaded=!0;u.loadingCallbacks.length;)u.loadingCallbacks.shift()();return}setTimeout(function(){t(r+1)},10)}}(0)},u.init=function(r){if("function"!=typeof r&&(r=function(){}),u.initiated=!0,isNode)u.api=new API.nodeAPI,u.api.init([{name:"jSQL_data_schema",rows:[]}],r);else{var n=u.api_user_priority.concat(u.api_default_priority),i=[],s=!1;!function e(t){if(t>=n.length&&!s)return _throw(new jSQL_Error("0063"));if(-1===u.api_default_priority.indexOf(n[t]))return e(1+t);if(-1<i.indexOf(n[t]))return e(1+t);try{u.api=new API[n[t]],u.api.init([{name:"jSQL_data_schema",rows:[]}],r),s=!0}catch(e){s=!1}s||e(1+t)}(0)}}};function createTable(e,t,r,n,i){var s=void 0===t&&void 0===r&&"object"==typeof e&&void 0===n,a=Array.isArray(t)&&void 0===r&&"object"==typeof e&&void 0===n;if(s||a)for(var o in a&&(n=void 0===t?[]:t),void 0===n&&(n=[]),t=[],r=[],e)if(e.hasOwnProperty(o)){var u=e[o];e=o;for(var l=0;l<u.length;l++){var h=u[l].name;t.push(h),r.push({type:u[l].type,args:void 0===u[l].args?[]:u[l].args,default:void 0===u[l].default?void 0:u[l].default,null:void 0===u[l].null||u[l].null}),u[l].hasOwnProperty("key")&&Array.isArray(n)&&n.push({column:u[l].name,type:u[l].key}),u[l].hasOwnProperty("auto_increment")&&!0===u[l].auto_increment&&(i=u[l].name)}break}return Array.isArray(t)||(t=[t]),void 0===n&&(n=[]),Array.isArray(n)||(n=[n]),new jSQLQuery("CREATE").init(e,t,r,n,i)}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)}function tokenize(e){return new jSQLLexer(e).getTokens()}function jSQLReset(){jSQL.tables={},jSQL.commit()}function jSQLMinifier(e){for(var t=new jSQLLexer(e).getTokens(),r=[],n=0;n<t.length;n++)r.push(t[n].literal);return r.join(" ")}function removeQuotes(e){for(var t=['"',"'","`"],r=t.length;r--;)if(e.substr(0,1)==t[r]&&e.substr(e.length-1,1)==t[r])return e.substr(1,e.length-2);return e}function jsql_export(e,t){e=void 0===e||!!e,t=t||[];var r=[];for(var n in jSQL.tables)if(jSQL.tables.hasOwnProperty(n)&&(!t.length||~t.indexOf(n))){if(e){for(var i=[],s=0;s<jSQL.tables[n].columns.length;s++){var a=[];a.push("`"+jSQL.tables[n].columns[s]+"` ");var o="";jSQL.tables[n].types[s].args.length&&(o=JSON.stringify(jSQL.tables[n].types[s].args).trim().slice(1,-1)),a.push(jSQL.tables[n].types[s].type+"("+o+") "),a.push(jSQL.tables[n].types[s].null?"NULL ":"NOT NULL "),jSQL.tables[n].types[s].default&&a.push("DEFAULT "+JSON.stringify(jSQL.tables[n].types[s].default)+" "),jSQL.tables[n].columns[s]===jSQL.tables[n].auto_inc_col&&a.push("AUTO_INCREMENT"),i.push("\n\t"+a.join("").trim())}if(jSQL.tables[n].keys.primary.column){if(a=[],Array.isArray(jSQL.tables[n].keys.primary.column))for(s=0;s<jSQL.tables[n].keys.primary.column.length;s++)a.push("`"+jSQL.tables[n].keys.primary.column[s]+"`");else a.push("`"+jSQL.tables[n].keys.primary.column+"`");i.push("\n\tPRIMARY KEY ("+a.join(",")+")")}if(jSQL.tables[n].keys.unique.length)for(var u=0;u<jSQL.tables[n].keys.unique.length;u++){if(a=[],Array.isArray(jSQL.tables[n].keys.unique[u].column))for(s=0;s<jSQL.tables[n].keys.unique[u].column.length;s++)a.push("`"+jSQL.tables[n].keys.unique[u].column[s]+"`");else a.push("`"+jSQL.tables[n].keys.unique[u].column+"`");i.push("\n\tUNIQUE KEY ("+a.join(",")+")")}r.push("CREATE TABLE `"+n+"` ("+i.join(",")+"\n)")}for(s=0;s<jSQL.tables[n].data.length;s++){var l=JSON.stringify(jSQL.tables[n].data[s]).trim().slice(1,-1).replace(/"jsqlNull"/g,"null");r.push("INSERT INTO `"+n+"` (`"+jSQL.tables[n].columns.join("`,`")+"`) VALUES ("+l+")")}}var h=["-- Exported by jSQL v"+jSQL.version+" "+(new Date).toUTCString()],c="-".repeat(h[0].length);return h.unshift(c),h.push(c),h.join("\n")+"\n"+r.join(";\n")}function jsql_import(e){e=e.split(";\n");for(var t=0;t<e.length;t++)jSQL.query(e[t]).execute()}return{version:"3.3.19",tables:{},query:jSQLParseQuery,createTable:createTable,dropTable:dropTable,select:select,update:update,deleteFrom:deleteFrom,insertInto:insertInto,types:new jSQLDataTypeList,load:persistenceManager.load,onError:onError,reset:jSQLReset,minify:jSQLMinifier,commit:persistenceManager.commit,rollback:persistenceManager.rollback,setApiPriority:persistenceManager.setApiPriority,getApi:persistenceManager.getApi,tokenize:tokenize,export:jsql_export,import:jsql_import}}();isNode?module.exports=jSQL:window.jSQL=jSQL}();