diff --git a/CHANGELOG.md b/CHANGELOG.md index e7829874..8c6f129b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ Read: ~100 records/ms - Write SQLite plugin. - Finish integration tests. -## [1.0.0] 12-7-2017 -MANY BREAKING CHANGES, PLEASE READ THE MIGRATION GUIDE +## [1.0.0] 12-10-2017 +MANY BREAKING CHANGES, PLEASE READ THE [MIGRATION GUIDE](https://docs.nanosql.io/fine-print/migration) This build is intended to stabilize the library, increase performance and make it easy to extend in the future. The API for v1.X.X releases will be very stable moving forward. ***** - Complete rewrite of the database engine, ORM system, and history system. @@ -22,13 +22,17 @@ This build is intended to stabilize the library, increase performance and make i - All database adapters now use a sorted B-Tree index to gaurantee consistency. - You can use instance tables with nSQL queries. ex: nSQL([{name: "Bill"}, {name: "Bob"}]).query("select").... - History is no longer enabled by default. -- Added WebSQL support. Safari in iOS and macOS will use WebSQL by default. +- Added WebSQL support. Safari in iOS/macOS will use WebSQL by default. - Added support for running IndexedDB in a webworker. - Added new INTERSECT and NOT INTERSECT .where() comparators. To check if any array values intersect with any values in an array of the database column. - .where() statements now accept a function, much like filter: `nSQL("table").query("select").where(row => row.age > 20).exec()` - Tables without a primary key are no longer supported, unless it's an instance table. - Added `loadCSV` method to automate importing CSVs into the database. - +- You can now get the version of NanoSQL being used with `nSQL().version`. +- Database versions will now be tracked to make automatic migration changes in the future. +- `updateORM` query has been removed entirely. +- ORM updates now happen along side `upsert`, `delete` and `drop` queries. +- ORM updates are more consistent and way more performant. ## [0.9.3] 10-15-2017 - Added changed rows property to database events. diff --git a/README.md b/README.md index 806eb523..040f9957 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,8 @@ It's written to take advantage of trendy buzzwords like "isomorphic", "immutable Persistence supports `Local Storage`, `Indexed DB`, `Indexed DB in a Web Worker`, and `WebSQL` in the browser, and `Level DB` in NodeJS *with the same API*. The storage engine is automatically selected based on the browser/environment, or can be manually selected. -* [Todo Example](https://some-sql.com/react-todo/) -* [Draw Example](https://some-sql.com/react-draw/) +* [Todo Example](https://nanosql.io/react-todo/) +* [Draw Example](https://nanosql.io/react-draw/) [Documentation](https://docs.nanosql.io/) diff --git a/dist/nano-sql.min.js b/dist/nano-sql.min.js index 9e2f3696..bee6d99e 100644 --- a/dist/nano-sql.min.js +++ b/dist/nano-sql.min.js @@ -1 +1 @@ -!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=4)}([function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var r=n(1);t._assign=function(e){return e?JSON.parse(JSON.stringify(e)):null};var i=function(){function e(e){this.callbacks=e}return e.prototype.then=function(e){var t=this,n=[],i=0;this.callbacks&&this.callbacks.length||e([]);var o=function(){i0||s.indexOf("Trident/")>0||s.indexOf("Edge/")>0),t.isAndroid=/Android/.test(s),t.random16Bits=function(){if("undefined"==typeof crypto)return Math.round(Math.random()*Math.pow(2,16));if(crypto.getRandomValues){var e=new Uint16Array(1);return crypto.getRandomValues(e),e[0]}return"undefined"!==global&&global._crypto.randomBytes?global._crypto.randomBytes(2).reduce(function(e,t){return t*e}):Math.round(Math.random()*Math.pow(2,16))},t.timeid=function(e){for(var n=Math.round((new Date).getTime()/(e?1:1e3)).toString();n.length<(e?13:10);)n="0"+n;return n+"-"+(t.random16Bits()+t.random16Bits()).toString(16)},t.uuid=function(){var e,n,r="";return[r,r,r,r,r,r,r,r,r].reduce(function(i,o,s){for(e=t.random16Bits(),n=4===s?s:5===s?(e%16&3|8).toString(16):r,e=e.toString(16);e.length<4;)e="0"+e;return i+([3,4,5,6].indexOf(s)>-1?"-":r)+(n+e).slice(0,4)},r)},t.hash=function(e){return Math.abs(e.split("").reduce(function(t,n,r){return(t<<5)+t+e.charCodeAt(r)},0)).toString(16)},t.generateID=function(e,n){switch(e){case"int":return n||1;case"uuid":return t.uuid();case"timeId":return t.timeid();case"timeIdms":return t.timeid(!0)}return""},t.cleanArgs=function(e,n){for(var r={},i=e.length||-1;i--;){var o=e[i].split(":");o.length>1?r[o[0]]=t.cast(o[1],n[o[0]]||void 0):r[o[0]]=n[o[0]]||void 0}return r},t.isObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)},t.cast=function(e,n){var r={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="},i=typeof n;if("undefined"===i||null===n)return n;var o=function(e,n){switch(e){case"safestr":return o("string",n).replace(/[&<>"'`=\/]/gim,function(e){return r[e]});case"int":return"number"!==i||n%1!=0?parseInt(n||0):n;case"number":case"float":return"number"!==i?parseFloat(n||0):n;case"any[]":case"array":return Array.isArray(n)?n:[];case"uuid":case"timeId":case"timeIdms":case"string":return"string"!==i?String(n):n;case"object":case"obj":case"map":return t.isObject(n)?n:{};case"boolean":case"bool":return!0===n}return n},s=o(String(e||"").toLowerCase(),n);if(-1!==e.indexOf("[]")){var a=e.slice(0,e.lastIndexOf("[]"));return(n||[]).map(function(e){return t.cast(a,e)})}return void 0!==s?["int","float","number"].indexOf(e)>-1&&isNaN(s)?0:s:void 0},t.sortedInsert=function(e,n,r,i){return e.length?(e.splice(t.binarySearch(e,n),0,n),e):(e.push(n),e)},t.binarySearch=function(e,n,r,i){var o=e.length,s=r||0,a=void 0!==i?i:o-1;if(0===o)return 0;if(n>e[a])return a+1;if(n=a)return 0;var u=s+Math.floor((a-s)/2);return ne[u]?t.binarySearch(e,n,u+1,a):0},t.removeDuplicates=function(e){if(!e.length)return[];for(var t=[e[0]],n=1;n-1?[].concat.apply([],e.split(".").map(function(e){return e.match(/([^\[]+)|\[([^\]]+)\]\[/gim)||e})).map(function(e){return e.replace(/\[|\]/gim,"")}):e.split("."),n){var s=o.shift()+"."+o.shift();o.unshift(s)}return a[i]=o,r(o,0,t)}},function(e,t,n){"use strict";function r(e,n,r){t.setFast(function(){var t;try{t=n.apply(null,r)}catch(t){return m._reject(e,t)}return t===e?m._reject(e,new TypeError):m._resolve(e,t),null})}function i(e){var t=e&&e.then;return!e||"object"!=typeof e&&"function"!=typeof e||"function"!=typeof t?null:function(){t.apply(e,arguments)}}function o(e,t){function n(){for(var t=[],n=0;n=this.ai&&this.ai++,this._indexOf[String(e)]=this._sorted.length,this._sorted.push(e);else{var t=r.binarySearch(this._sorted,e);this._sorted.splice(t,0,e),this._indexOf[String(e)]=t;for(var n=t+1;n")&&(i=e.replace("ref=>",""))}),e.relationColumns[t].push(r.key),e.relations[t].push({column:r.key,toTable:r.type.replace("[]",""),toColumn:i,type:-1===r.type.indexOf("[]")?"single":"array",toType:i?Object.keys(e._models).reduce(function(t,n){return n===r.type.replace("[]","")?e._models[n].reduce(function(e,t){return t.key===i?-1!==t.type.indexOf("[]")?"array":"single":e},""):t},""):""})}}()}),new u.ALL(e._plugins.map(function(e){return function(t){e.didConnect?e.didConnect(i,function(){t()}):t()}})).then(n)})})},e.prototype.use=function(e){return this._plugins.push(e),this},e.prototype.on=function(e,t){var n=this,r=n.sTable,i=n._events.length,o=e.split(" ");if(Array.isArray(r))return this;for(n._callbacks[r]||(n._callbacks[r]=new a.ReallySmallEvents),i=o.length;i--;)-1!==n._events.indexOf(o[i])&&n._callbacks[r].on(o[i],t);return n._refreshEventChecker()},e.prototype.off=function(e,t){var n=this,r=e.split(" "),i=r.length,o=n.sTable;if(Array.isArray(o))return this;for(;i--;)-1!==n._events.indexOf(r[i])&&n._callbacks[o].off(r[i],t);return n._refreshEventChecker()},e.prototype._refreshEventChecker=function(){var e=this;return this._hasEvents={},Object.keys(this._models).concat(["*"]).forEach(function(t){e._hasEvents[t]=e._events.reduce(function(n,r){return n+(e._callbacks[t]&&e._callbacks[t].eventListeners[r]?e._callbacks[t].eventListeners[r].length:0)},0)>0}),this},e.prototype.model=function(e){var t=this,n=t.sTable;return Array.isArray(n)?this:(t._callbacks[n]||(t._callbacks[n]=new a.ReallySmallEvents),t._models[n]=e,t._views[n]=[],t._actions[n]=[],t)},e.prototype.views=function(e){return Array.isArray(this.sTable)?this:(this._views[this.sTable]=e,this)},e.prototype.getView=function(e,t){return void 0===t&&(t={}),Array.isArray(this.sTable)?new i.Promise(function(e,t){return t()}):this._doAV("View",this._views[this.sTable],e,t)},e.prototype.actions=function(e){return Array.isArray(this.sTable)?this:(this._actions[this.sTable]=e,this)},e.prototype.doAction=function(e,t){return Array.isArray(this.sTable)?new i.Promise(function(e,t){return t()}):this._doAV("Action",this._actions[this.sTable],e,t)},e.prototype._doAV=function(e,t,n,r){var o=this,s=t.reduce(function(e,t){return t.name===n?t:e},null);return s?(o._activeAV=n,s.call(s.args?u.cleanArgs(s.args,r):{},o)):new i.Promise(function(e,t){return t("Action/View Not Found!")})},e.prototype.query=function(e,t,n){var r=this,i=new o._NanoSQLQuery(r.sTable,r,e.toLowerCase(),t,r._activeAV,n);return r._activeAV=void 0,i},e.prototype.triggerEvent=function(e){var t=this;return i.setFast(function(){e.types.forEach(function(n){t._callbacks["*"].trigger(n,e,t),t._callbacks["*"].trigger("*",e,t),e.table&&t._callbacks[e.table]&&t._callbacks[e.table].trigger(n,e,t)})}),t},e.prototype.default=function(e){var t={},n=this;return Array.isArray(n.sTable)?{}:(n._models[n.sTable].forEach(function(n){t[n.key]=e&&e[n.key]?e[n.key]:n.default,void 0===t[n.key]&&(t[n.key]=u.cast(n.type,null))}),t)},e.prototype.doTransaction=function(e){var t=this,n=this,o=[],a=u.random16Bits().toString(16);return new i.Promise(function(i,c){if(!n._plugins.length)return void c("Nothing to do, no plugins!");new u.CHAIN(n._plugins.map(function(e){return function(t){e.transactionBegin?e.transactionBegin(a,t):t()}})).then(function(){Array.isArray(n.sTable)||e(function(e){var t=e||n.sTable;return{query:function(e,n){return new s._NanoSQLTransactionQuery(e,n,t,o,a)}}},function(){var e=[];new u.CHAIN(o.map(function(t){return function(i){e.push(t.table),n.table(t.table).query(t.action,t.actionArgs,!0).manualExec(r({},t,{transaction:!0,queryID:a,actionArgs:void 0})).then(i)}})).then(function(r){new u.CHAIN(t._plugins.map(function(e){return function(t){e.transactionEnd?e.transactionEnd(a,t):t()}})).then(function(){e.filter(function(e,t,n){return n.indexOf(e)===t}).forEach(function(e){0!==e.indexOf("_")&&n.triggerEvent({query:o[0],table:e,time:(new Date).getTime(),result:r,types:["transaction"],actionOrView:"",notes:[],transactionID:a,affectedRowPKS:[],affectedRows:[]})}),i(r)})})})})})},e.prototype.config=function(e){return this._config=e,this},e.prototype.extend=function(){for(var e=[],t=0;tr&&(r=u.objQuery(n,e))}),t(r)}else t(0)}},MIN:{type:"A",call:function(e,t,n){if(e.length){var r=u.objQuery(n,e[0])||0;e.forEach(function(e){var t=u.objQuery(n,e);t-1))throw Error("No valid database action!");var u=r||("select"===a||"delete"===a?[]:{});if("upsert"===a){var c={};this._db._models[this._db.sTable].forEach(function(e){void 0!==u[e.key]&&(c[e.key]=i.cast(e.type,u[e.key]))}),u=c}this._query.action=a,this._query.actionArgs=r?u:void 0}}return e.prototype.where=function(e){return this._query.where=e,this},e.prototype.range=function(e,t){return this._query.range=[e,t],this},e.prototype.orm=function(e){return this._query.orm=e,this},e.prototype.orderBy=function(e){return this._query.orderBy=e,this},e.prototype.groupBy=function(e){return this._query.groupBy=e,this},e.prototype.having=function(e){return e.length&&Array.isArray(e)||(this._error="Having condition requires an array!"),this._query.having=e,this},e.prototype.join=function(e){if(Array.isArray(this._query.table))throw Error("Can't JOIN with instance table!");return e.table&&e.type||(this._error="Join command requires table and type arguments!"),this._query.join=e,this},e.prototype.limit=function(e){return this._query.limit=e,this},e.prototype.trieSearch=function(e,t){return this._query.trie={column:e,search:t},this},e.prototype.ormSync=function(e){return this._query.ormSync=e||[],this},e.prototype.comment=function(e){return this._query.comments.push(e),this},e.prototype.extend=function(){for(var e=[],t=0;t-1?this._store._adapter.getIndex(r,"idx"!==t[0],function(n){e(t,n)}):e(t,[]);break;case"rebuild_idx":this._store.rebuildIndexes(t[1],function(n){e(t,[n])});break;default:e(t,n)}},e}();t.NanoSQLDefaultBackend=s},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n=!0),i.props&&(i.props.indexOf("idx")>-1||i.props.indexOf("trie")>-1)&&(r=!0,e["_"+t+"_idx_"+i.key]=[{key:"id",type:"string",props:["pk"]},{key:"rows",type:"any[]"}])}),r&&!n)throw new Error("Tables with secondary indexes must have a primary key!")}),e},e.prototype._newTable=function(e,t){this.tableInfo[e]={_pk:"",_pkType:"",_keys:[],_defaults:[],_secondaryIndexes:[],_trieColumns:[],_name:e},this._cache[e]={},this._trieIndexes[e]={},this._adapter.makeTable(e,t);for(var n=this.models[e].length;n--;){var r=this.models[e][n];this.tableInfo[e]._keys.unshift(r.key),this.tableInfo[e]._defaults[n]=r.default,r.props&&r.props.indexOf("pk")>-1&&(this.tableInfo[e]._pk=r.key,this.tableInfo[e]._pkType=r.type),r.props&&(r.props.indexOf("idx")>-1||r.props.indexOf("trie")>-1)&&this.tableInfo[e]._secondaryIndexes.push(r.key),r.props&&r.props.indexOf("trie")>=0&&(this.tableInfo[e]._trieColumns.push(r.key),this._trieIndexes[e][r.key]=new i.Trie([]))}return e},e}();t._NanoSQLStorage=c},function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n={END_WORD:"$",PERMS_MIN_LEN:2},r=function(){function e(t){this._trie=e._create(t)}return e.prototype.addWord=function(t){var n=function(t,n,r,i){return e._append(t,n,r,i)};return t.toLowerCase().split("").reduce(n,this._trie),this},e.prototype.removeWord=function(t){var r=e._checkPrefix(this._trie,t),i=r.prefixFound,o=r.prefixNode;return i&&delete o[n.END_WORD],this},e.prototype.getWords=function(){return e._recursePrefix(this._trie,"")},e.prototype.getPrefix=function(t){if(t=t.toLowerCase(),!this._isPrefix(t))return[];var n=e._checkPrefix(this._trie,t).prefixNode;return e._recursePrefix(n,t)},e.prototype._isPrefix=function(t){return e._checkPrefix(this._trie,t).prefixFound},e._append=function(e,t,r,i){return e[t]=e[t]||{},e=e[t],r===i.length-1&&(e[n.END_WORD]=1),e},e._checkPrefix=function(e,t){return{prefixFound:t.toLowerCase().split("").every(function(t,n){return!!e[t]&&(e=e[t])}),prefixNode:e}},e._create=function(t){return t.reduce(function(t,n){return n.toLowerCase().split("").reduce(e._append,t),t},{})},e._recursePrefix=function(t,r,i){void 0===i&&(i=[]);var o=r;for(var s in t)s===n.END_WORD&&(i.push(o),o=""),e._recursePrefix(t[s],r+s,i);return i.sort()},e}();t.Trie=r},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n._pkType[e]=t.type,n._pkKey[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n._dbIndex[e].doAI=!0),n._ls){var r=localStorage.getItem(n._id+"*"+e+"_idx");r&&n._dbIndex[e].set(JSON.parse(r))}})},e.prototype.write=function(e,t,n,i,s){if(!(t=t||o.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");if(-1===this._dbIndex[e].indexOf(t)&&(this._dbIndex[e].add(t),this._ls&&localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify(this._dbIndex[e].keys()))),this._ls){var a=r({},s?{}:JSON.parse(localStorage.getItem(this._id+"*"+e+"__"+t)||"{}"),n,(u={},u[this._pkKey[e]]=t,u));localStorage.setItem(this._id+"*"+e+"__"+t,JSON.stringify(a)),i(a)}else{var a=r({},s?{}:this._rows[e][t],n,(c={},c[this._pkKey[e]]=t,c));this._rows[e][t]=o.deepFreeze(a),i(a)}var u,c},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&(this._dbIndex[e].remove(t),this._ls&&localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify(this._dbIndex[e].keys()))),this._ls?localStorage.removeItem(this._id+"*"+e+"__"+t):delete this._rows[e][t],n()},e.prototype.read=function(e,t,n){if(this._ls){var r=localStorage.getItem(this._id+"*"+e+"__"+t);n(r?JSON.parse(r):void 0)}else n(this._rows[e][t])},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this._dbIndex[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[0,u.length-1];if(!u.length)return void n();s&&c&&(f=f.map(function(t){return a._dbIndex[e].getLocation(t)}));var h=f[0],d=0,_=function(){h++,d++,d>200?i.setFast(l):l()},l=function(){if(h<=f[1])if(a._ls){var r=localStorage.getItem(a._id+"*"+e+"__"+u[h]);t(r?JSON.parse(r):void 0,h,_)}else t(a._rows[e][u[h]],h,_);else n()};l()},e.prototype.drop=function(e,t){var n=this;this._ls?(localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify([])),this._dbIndex[e].keys().forEach(function(t){localStorage.removeItem(n._id+"*"+e+"__"+t)})):this._rows[e]={};var r=new s.DatabaseIndex;r.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=r,t()},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;new o.ALL(Object.keys(this._dbIndex).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();t._SyncStore=a},function(module,exports,__webpack_require__){var __assign=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n._pkType[e]=t.type,n._pkKey[e]=t.key,t.props&&t.props.indexOf("ai")>-1&&("int"===t.type||"number"===t.type)&&(n._dbIndex[e].doAI=!0))})},e.prototype.write=function(e,t,n,r,i){var o=this;if(!(t=t||utilities_1.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");-1===this._dbIndex[e].indexOf(t)&&this._dbIndex[e].add(t);var s=utilities_1.uuid(),a=__assign({},n,(c={},c[this._pkKey[e]]=t,c));this._waitingCBs["write_"+s]=function(e){r(a)};var u=function(t){a=__assign({},t,a),o._w.postMessage({do:"write",args:{table:e,id:s,row:a}})};i?u({}):this.read(e,t,function(e){u(e)});var c},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&this._dbIndex[e].remove(t);var r=utilities_1.uuid();this._waitingCBs["delete_"+r]=function(e){n()},this._w.postMessage({do:"delete",args:{table:e,id:r,pk:t}})},e.prototype.read=function(e,t,n){var r=utilities_1.uuid();if(-1===this._dbIndex[e].indexOf(t))return void n(null);this._waitingCBs["read_"+r]=function(e){n(e)},this._w.postMessage({do:"read",args:{table:e,id:r,pk:t}})},e.prototype.rangeRead=function(e,t,n,r,i,o){var s=this,a=this._dbIndex[e].keys(),u=-1===[typeof r,typeof i].indexOf("undefined"),c=u?[r,i]:[0,a.length-1];if(!a.length)return void n();var f=utilities_1.uuid(),h=[],d=c[0],_=0;this._waitingCBs["readRange_"+f+"_done"]=function(e){delete s._waitingCBs["readRange_"+f],h=e;var r=function(){d<=c[1]?t(h[_],d,function(){d++,_++,_>200?lie_ts_1.setFast(r):r()}):n()};r()},this._w.postMessage({do:"readRange",args:{table:e,id:f,range:o&&u?c:c.map(function(e){return a[e]})}})},e.prototype.drop=function(e,t){var n=new db_idx_1.DatabaseIndex;n.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=n;var r=utilities_1.uuid();this._waitingCBs["delete_"+r]=function(e){t()},this._w.postMessage({do:"delete",args:{table:e,id:r,pk:"_clear_"}})},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;new utilities_1.ALL(Object.keys(this._dbIndex).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();exports._IndexedDBStore=_IndexedDBStore},function(e,t){e.exports='function e(e){this.go=function(n){var t=0;e&&e.length||n([]),e.forEach(function(o,r){o(function(){++t===e.length&&n([])})})}}var n={db:null,store:function(e,t,o){var r=n.db.transaction(e,t);o(r,r.objectStore(e),function(e,n){return function(){postMessage({do:e,args:n})}})},init:function(){addEventListener("message",function(e){var t=e.data;n[t.do]&&n[t.do](t.args)},!1)},setup:function(t){var o=indexedDB.open(t.id,1),r=!1,a={};o.onupgradeneeded=function(e){r=!0,n.db=e.target.result,Object.keys(t.pkKeys).forEach(function(e){n.db.createObjectStore(e,{keyPath:t.pkKeys[e]}),a[e]=[]})},o.onsuccess=function(o){if(n.db=o.target.result,r)postMessage({do:"rdy",args:a});else{var s=function(e,t){var o=[];n.store(e,"readonly",function(e,n,r){n.openCursor().onsuccess=function(e){var n=e.target.result;n&&(o.push(n.key),n.continue())},e.oncomplete=function(){t(o)}})};new e(Object.keys(t.pkKeys).map(function(e){return function(n){s(e,function(t){a[e]=t,n()})}})).go(function(){postMessage({do:"rdy",args:a})})}}},write:function(e){n.store(e.table,"readwrite",function(n,t,o){t.put(e.row),n.oncomplete=o("write_"+e.id,null)})},read:function(e){n.store(e.table,"readonly",function(n,t,o){var r=t.get(e.pk);r.onsuccess=function(){postMessage({do:"read_"+e.id,args:r.result})}})},readRange:function(e){n.store(e.table,"readonly",function(n,t,o){var r=[],a=-1===e.range.indexOf(void 0)?t.openCursor(IDBKeyRange.bound(e.range[0],e.range[1])):t.openCursor();n.oncomplete=o("readRange_"+e.id+"_done",r),a.onsuccess=function(e){var n=e.target.result;n&&(r.push(n.value),n.continue())}})},delete:function(e){n.store(e.table,"readwrite",function(n,t,o){n.oncomplete=o("delete_"+e.id,!0),n.onerror=o("delete_"+e.id,!1),"_clear_"===e.pk?t.clear():t.delete(e.pk)})}};n.init();'},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n._pkType[e]=t.type,n._pkKey[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n._dbIndex[e].doAI=!0)})},e.prototype._sql=function(e,t,n,r){var i=function(e){e.executeSql(t,n,function(e,t){r(t)},function(e,r){return console.error(t,n,r),!1})};e?this._db.transaction(i):this._db.readTransaction(i)},e.prototype.write=function(e,t,n,i,s){var a=this;if(!(t=t||o.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");var u=!1;if(-1===this._dbIndex[e].indexOf(t)&&(u=!0,this._dbIndex[e].add(t)),u){var c=r({},n,(h={},h[this._pkKey[e]]=t,h));this._sql(!0,"INSERT into "+this._chkTable(e)+" (id, data) VALUES (?, ?)",[t,JSON.stringify(c)],function(e){i(c)})}else{var f=function(o){var s=r({},o,n,(u={},u[a._pkKey[e]]=t,u));a._sql(!0,"UPDATE "+a._chkTable(e)+" SET data = ? WHERE id = ?",[JSON.stringify(s),t],function(){i(s)});var u};s?f({}):this.read(e,t,function(e){f(e)})}var h},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&this._dbIndex[e].remove(t),this._sql(!0,"DELETE FROM "+this._chkTable(e)+" WHERE id = ?",[t],function(){n()})},e.prototype.read=function(e,t,n){this._sql(!1,"SELECT data FROM "+this._chkTable(e)+" WHERE id = ?",[t],function(e){n(e.rows.length?JSON.parse(e.rows.item(0).data):void 0)})},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this._dbIndex[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[];if(!u.length)return void n();s&&c&&(f=f.map(function(t){return a._dbIndex[e].getLocation(t)}));var h=f[0]||0,d=[],_=f[0],l="SELECT data from "+this._chkTable(e);if(f.length){for(var p="number"==typeof u[_];_<=f[1];)d.push(p?u[_]:'"'+u[_]+'"'),_++;l+=" WHERE id IN ("+d.join(", ")+")"}l+=" ORDER BY id",this._sql(!1,l,[],function(e){var r=0,o=function(){e.rows.length>r?t(JSON.parse(e.rows.item(r).data),h,function(){h++,r++,r>200?i.setFast(o):o()}):n()};o()})},e.prototype.drop=function(e,t){var n=new s.DatabaseIndex;n.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=n,this._sql(!0,"DELETE FROM "+this._chkTable(e),[],function(e){t()})},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;new o.ALL(Object.keys(this._dbIndex).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();t._WebSQLStore=a},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n=t&&n.q.range[1]<=t}):e)})}},e.prototype._groupByKey=function(e,t){return e.reduce(function(e,n){return-1!==n.indexOf(".length")?e+"."+String((t[n.replace(".length","")]||[]).length):e+"."+String(t[n])},"").slice(1)},e.prototype._groupBy=function(e){var t=this,n=this.q.groupBy||{},r=e.sort(function(e,r){return t._sortObj(e,r,n,!0)});return r.forEach(function(e,r){var i=Object.keys(n).map(function(t){return String(e[t])||""}).join(".");t._sortGroups||(t._sortGroups={}),t._sortGroups[i]||(t._sortGroups[i]=[]),t._sortGroups[i].push(r)}),r},e.prototype._having=function(e){var t=this;return e.filter(function(e,n){return Array.isArray(t.q.having)?f(e,t.q.having||[],n,!0):t.q.having(e,n)})},e.prototype._orderBy=function(e){var t=this;return e.sort(function(e,n){return t._sortObj(e,n,t.q.orderBy||{},!1)})},e.prototype._offset=function(e){var t=this;return e.filter(function(e,n){return!t.q.offset||n>=t.q.offset})},e.prototype._limit=function(e){var t=this;return e.filter(function(e,n){return!t.q.limit||n-1,n.type.replace("[]","")):e},""),n._ormTableCache[o]=[s,i]),s){var a=n.s.tableInfo[s]._pk,u=[a,i?"IN":"=",e[t.key]],c=n.s._nsql.table(s).query("select",t.select);t.where?Array.isArray(t.where)?c.where("string"==typeof t.where[0]?[u,"AND",t.where]:t.where.concat(["AND",u])):c.where(function(n,r){return(i?-1!==e[t.key].indexOf(n[a]):e[t.key]===n[a])&&t.where(n,r)}):c.where(u),void 0!==t.limit&&c.limit(t.limit),void 0!==t.offset&&c.offset(t.offset),t.orderBy&&c.orderBy(t.orderBy),c.exec().then(function(n){n.filter(function(e){return e}).length?e[t.key]=i?n.filter(function(e){return e}):n[0]:e[t.key]=i?[]:void 0,r()})}else r()}})).then(function(){t(e)})}})).then(t)},e.prototype._doJoin=function(e,t,n,r,i){var o="right",s="outer",a=this,u=a.s.tableInfo[e===o?n:t],c=a.s.tableInfo[e===o?t:n],h=function(e,t){return[u,c].reduce(function(n,r,i){return r._keys.forEach(function(o){n[r._name+"."+o]=((0===i?e:t)||{})[o]}),n},{})},d=[],_=r&&r._right?r._right.split(".").pop()||"":"",l=[];a.s._read(u._name,function(t,n,i){var p=!1;a.s._read(c._name,function(n,i,a){if(r&&"cross"!==e){f((y={},y[u._name]=t,y[c._name]=n,y),[r._left,r._check,e===o?t[_]:n[_]],0)&&(e===s&&l.push(i),d.push(h(t,n)),p=!0)}else d.push(h(t,n)),p=!0;a(!1);var y},function(){!p&&["left",o,s].indexOf(e)>-1&&d.push(h(t,null)),i(!1)})},function(){e===s?a.s._read(c._name,function(e,t,n){-1===l.indexOf(t)&&d.push(h(null,e)),n(!1)},function(){i(d)}):i(d)})},e.prototype._sortObj=function(e,t,n,r){return Object.keys(n).reduce(function(i,s){var a=r?o.objQuery(s,e):e[s],u=r?o.objQuery(s,t):t[s];return i||(a===u?0:(a>u?1:-1)*("desc"===n[s]?-1:1))},0)},e.prototype._mutateRows=function(e,t){var n=this,r=this.q.actionArgs,s={},a={};if(r&&r.length){var u=!1,c={};r.forEach(function(e){if(-1!==e.indexOf("(")){var t=(e.match(/^.*\(/g)||[""])[0].replace(/\(|\)/g,"").toUpperCase(),n=i.NanoSQLInstance.functions[t],r=1===e.split(" AS ").length?t:(e.split(" AS ").pop()||"").trim();if(!n)throw new Error("'"+t+"' is not a valid function!");"A"===n.type&&(u=!0),c[e]={fn:n,key:r}}}),new o.ALL(r.map(function(t){return function(r){if(t.indexOf("(")>-1){var i=(t.match(/\(.*\)/g)||[""])[0].replace(/\(|\)/g,"").split(",").map(function(e){return e.trim()});n._sortGroups&&u?new o.ALL(Object.keys(n._sortGroups).map(function(r){return a[r]||(a[r]={}),function(o){(s=c[t].fn).call.apply(s,[e.filter(function(e,t){return n._sortGroups[r].indexOf(t)>-1}),function(e){a[r][c[t].key]=e,o()}].concat(i));var s}})).then(r):(f=c[t].fn).call.apply(f,[e,function(e){s[c[t].key]=e,r()}].concat(i))}else r();var f}})).then(function(){var i=function(e,t,i){var s={};return r.forEach(function(r){var a=r.indexOf("(")>-1,u=a?c[r].fn.type:"";if(r.indexOf(" AS ")>-1){var f=r.split(" AS "),h=a?c[r].key:f[0].trim();s[f[1]]=a?"A"===u?i[h]:i[h][t]:o.objQuery(h,e,void 0!==n.q.join)}else{var h=a?c[r].key:r;s[r]=a?"A"===u?i[h]:i[h][t]:o.objQuery(h,e,void 0!==n.q.join)}}),s};if(n._sortGroups&&u){var f=[];Object.keys(n._sortGroups).forEach(function(t){var r=e.filter(function(e,r){return n._sortGroups[t].indexOf(r)>-1}).filter(function(e,t){return t<1});r&&r.length&&f.push(i(r[0],0,a[t]))}),t(f)}else t(u?e.filter(function(e,t){return t<1}).map(function(e,t){return i(e,t,s)}):e.map(function(e,t){return i(e,t,s)}))})}else t(e)},e.prototype._executeQueryArguments=function(e,t){var n=this,r=function(){n.q.having&&(e=n._having(e)),n.q.orderBy&&(e=n._orderBy(e)),n.q.offset&&(e=n._offset(e)),n.q.limit&&(e=n._limit(e)),t(e)},i=function(){n.q.actionArgs&&n.q.actionArgs.length?n._mutateRows(e,function(t){e=t,r()}):r()},o=function(){n.q.groupBy&&(e=n._groupBy(e)),n.q.orm?n._orm(e,function(t){e=t,i()}):i()};this.q.join?this._join(e,function(t){e=t,o()}):o()},e}();t._MutateSelection=a;var u=function(){function e(e,t){this.q=e,this.s=t}return e.prototype.getRows=function(e){var t=this;if(this.q.join)return void e([]);if(this.q.join&&this.q.orm)throw new Error("Cannot do a JOIN and ORM command at the same time!");if([this.q.where,this.q.range,this.q.trie].filter(function(e){return e}).length>1)throw new Error("Can only have ONE of Trie, Range or Where!");if(this.q.trie&&this.q.trie.column&&this.q.trie.search)return void this._selectByTrie(e);if(this.q.range&&this.q.range.length)return void this._selectByRange(e);if(!this.q.where||!this.q.where.length)return void this._fullTableScan(e);if(!Array.isArray(this.q.where))return void this._fullTableScan(function(n){e(n.filter(t.q.where))});if("string"==typeof this.q.where[0]?0===this._isOptimizedWhere(this.q.where):0===(this.q.where||[]).reduce(function(e,n,r){return r%2==1?e:e+t._isOptimizedWhere(n)},0))return void this._selectByKeys(e);this._fullTableScan(e)},e.prototype._selectByKeys=function(e){var t=this;if(this.q.where&&"string"==typeof this.q.where[0])this._selectRowsByIndex(this.q.where,e);else if(this.q.where){var n=[],r="";new o.CHAIN(this.q.where.map(function(e){return function(i){if("OR"===e||"AND"===e)return r=e,void i();t._selectRowsByIndex(e,function(e){if("AND"===r){var o=e.map(function(e){return e[t.s.tableInfo[t.q.table]._pk]});n=n.filter(function(e){return-1!==o.indexOf(e[t.s.tableInfo[t.q.table]._pk])})}else n.concat(e);i()})}})).then(function(){e(n)})}},e.prototype._selectRowsByIndex=function(e,t){var n=this;if("BETWEEN"!==e[1]){var r=[];switch(e[1]){case"IN":r=e[2];break;case"=":r=[e[2]]}e[0]===this.s.tableInfo[this.q.table]._pk?this.s._read(this.q.table,r,t):new o.ALL(r.map(function(t){return function(r){n.s._secondaryIndexRead(n.q.table,e[0],t,r)}})).then(function(e){t([].concat.apply([],e))})}else{var i=e[0]===this.s.tableInfo[this.q.table]._pk?"":e[0];if(i){var s="_"+this.q.table+"_idx_"+i;this.s._rangeReadPKs(s,e[2][0],e[2][1],function(e){var r=[].concat.apply([],e);n.s._read(n.q.table,r,t)})}else this.s._rangeReadPKs(this.q.table,e[2][0],e[2][1],function(e){t(e)})}},e.prototype._selectByRange=function(e){var t=this;if(this.q.range){var n=this.q.range;this.s._adapter.getIndex(this.q.table,!0,function(r){for(var i=n[0]>0?n[1]:r+n[0]-n[1],o=i,s=Math.abs(n[0])-1;s--;)o++;t.s._rangeReadIDX(t.q.table,i,o,e)})}else e([])},e.prototype._selectByTrie=function(e){this.q.trie?this.s._trieRead(this.q.table,this.q.trie.column,this.q.trie.search,e):e([])},e.prototype._fullTableScan=function(e){var t=this;this.s._read(this.q.table,function(e,n,r){r(!t.q.where||(Array.isArray(t.q.where)?f(e,t.q.where||[],n||0):t.q.where(e,n)))},e)},e.prototype._isOptimizedWhere=function(e){var t=this.s.tableInfo[this.q.table];return["=","IN","BETWEEN"].indexOf(e[1])>-1&&(e[0]===t._pk||t._secondaryIndexes.indexOf(e[0])>-1)?0:1},e}();t._RowSelection=u;var c=function(){function e(e){this.q=e}return e.prototype.getRows=function(e){var t=this;if(this.q.join||this.q.orm||this.q.trie)throw new Error("Cannot do a JOIN, ORM or TRIE command with instance table!");if(this.q.range&&this.q.range.length){var n,r,i=this.q.range;n=i[0]<0?this.q.table.length+i[0]-i[1]:i[1];var o=Math.abs(i[0])-1;for(r=n;o--;)r++;return void e(this.q.table.filter(function(e,t){return t>=n&&t<=r}))}e(this.q.table.filter(function(e,n){return!t.q.where||(Array.isArray(t.q.where)?f(e,t.q.where||[],n):t.q.where(e,n))}))},e}();t.InstanceSelection=c;var f=function(e,t,n,r){var i=["AND","OR"];if("string"!=typeof t[0]){var s=!1,a=t.map(function(t,a){return-1!==i.indexOf(t)?("AND"===t&&(s=!0),t):0===h(t[2],t[1],"_IDX_"===t[0]?n:o.objQuery(t[0],e,r))});if(a.forEach(function(e,t){"OR"===e&&(a[t]=a[t-1]||a[t+1],a[t-1]=void 0,a[t+1]=void 0)}),a=a.filter(function(e){return void 0!==e}),s){var u,c=!1;return-1===a.reduce(function(e,t,n){return 0===n?(e.push(t),u=e.length-1,e):"AND"===t?(c=!0,e.push(t),e):c?(e.push(t),u=e.length-1,c=!1,e):(void 0!==u&&(e[u]=t||e[u]),e)},[]).filter(function(e){return void 0!==e}).indexOf(!1)}return-1!==a.indexOf(!0)}return 0===h(t[2],t[1],"_IDX_"===t[0]?n:o.objQuery(t[0],e,r))},h=function(e,t,n){var r=function(e){return["LIKE","NOT LIKE"].indexOf(t)>0?String(e||"").toLowerCase():e},i=r(n),o=r(e);if("NULL"===e||"NOT NULL"===e){var s="="===t||"LIKE"===t;return("NULL"===e?null===n||void 0===n:null!==n&&void 0!==n)?s?0:1:s?1:0}switch(t){case"=":return i===o?0:1;case"!=":return i!==o?0:1;case">":return i>o?0:1;case"<":return i=":return i>=o?0:1;case"IN":return(o||[]).indexOf(i)<0?1:0;case"NOT IN":return(o||[]).indexOf(i)<0?0:1;case"REGEX":return i.search(o)<0?1:0;case"LIKE":return i.indexOf(o)<0?1:0;case"NOT LIKE":return i.indexOf(o)>0?1:0;case"BETWEEN":return o[0]<=i&&o[1]>=i?0:1;case"HAVE":return(i||[]).indexOf(o)<0?1:0;case"NOT HAVE":return(i||[]).indexOf(o)<0?0:1;case"INTERSECT":return(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length>0?0:1;case"NOT INTERSECT":return 0===(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length?0:1;default:return 1}}},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n0){var a=r.parent.table(e).query("select");n||a.range(-1*s.ptr,0),a.exec().then(function(o){if(!o.length)return void t();var a={};o.forEach(function(e){a[e.table]||(a[e.table]=[]),a[e.table]=a[e.table].concat(e.keys)}),new i.ALL(Object.keys(a).map(function(e){return function(t){r._purgeRowHistory(e,a[e],t,n)}})).then(function(){r.parent.table(e).query("delete").comment("History Purge").where(["id","IN",o.map(function(e){return e.id})]).exec().then(function(){s.ptr=0,r.parent.table(e+"_ptr").query("upsert",s).comment("History Purge").where(["id","=",s.id]).exec().then(t)})})})}else t()})},e.prototype._purgeParentHistory=function(e,t,n){if(!this.historyModes)return void this._purgeTableHistory("_hist",n);var r=this._histTable(e);r?this._purgeTableHistory(r,n):this._purgeRowHistory(e,t,n)},e.prototype._purgeAllHistory=function(e,t,n){if(!this.historyModes)return void this._purgeTableHistory("_hist",n,!0);var r=this._histTable(e);r?this._purgeTableHistory(r,n,!0):this._purgeRowHistory(e,[t],n,!0)},e.prototype.didExec=function(e,t){var n=this;e.table&&0!==e.table.indexOf("_")&&e.types.indexOf("change")>-1&&-1===e.query.comments.indexOf("History Write")?this._purgeParentHistory(e.table,e.affectedRowPKS,function(){new i.ALL(e.affectedRows.map(function(t){return function(r){var i=t[n._tablePkKeys[e.table]];n._tableKeys[e.table][i]?n._unshiftSingleRow(e.table,e.types,i,t,!1,function(e){r(i)}):(n._tableKeys[e.table][i]=!0,n._unshiftSingleRow(e.table,e.types,i,t,!0,function(t){n.parent.table("_"+e.table+"__hist_idx").query("upsert",{id:i,histRows:[t,-1],histPtr:0}).exec().then(function(){r(i)})}))}})).then(function(r){n._unshiftParent(e,r,t)})}):t(e)},e.prototype._unshiftParent=function(e,t,n){var r=this._histTable(e.table);r?this.parent.table(r).query("upsert",{id:i.timeid(!0),table:e.table,keys:t}).exec().then(function(){n(e)}):n(e)},e.prototype._unshiftSingleRow=function(e,t,n,o,s,a){var u=this,c="_"+e+"__hist_idx",f=i.timeid(!0),h=function(e){u.parent.table(c).query("select").where(["id","=",n]).exec().then(function(t){var r=Object.isFrozen(t[0])?i._assign(t[0]):t[0];r.histRows.unshift(e),u.parent.table(c).query("upsert",r).where(["id","=",n]).exec().then(function(){a(e)})})};t.indexOf("delete")>-1||t.indexOf("drop")>-1?h(-1):this.parent.table("_"+e+"__hist_rows").query("upsert",r({_id:f},o)).exec().then(function(){if(s)return void a(f);h(f)})},e.prototype.extend=function(e,t,n){if("hist"===t[0]){var r=t[1],i=t[2],o=t[3];switch(r){case"<":case">":this._shiftHistory(r,i,o,function(n){e(t,[n])});break;case"?":this._queryHistory(i,o,function(n){e(t,n)});break;case"rev":this._getRevisionHistory(i,o,function(n){e(t,n)});break;case"clear":this._purgeAllHistory(i,o,function(){e(t,n)})}}else e(t,n)},e.prototype._getRevisionHistory=function(e,t,n){var r=this,o="_"+e+"__hist_idx";this.parent.table(o).query("select").where(["id","=",t]).exec().then(function(t){var o=t[0].histRows.filter(function(e){return-1!==e});r.parent.table("_"+e+"__hist_rows").query("select").where(["_id","IN",o]).exec().then(function(e){var r={};e.forEach(function(e){r[e._id]=Object.isFrozen(e)?i._assign(e):e,delete r[e._id]._id}),n([{pointer:t[0].histRows.length-t[0].histPtr-1,revisions:t[0].histRows.reverse().map(function(e){return-1===e?null:r[e]})}])})})},e.prototype._getTableHistory=function(e,t){var n=this;this.parent.extend("idx.length",e).then(function(r){n.parent.table(e+"_ptr").query("select").exec().then(function(e){if(!e.length)return void t([0,0]);t([r,r-e[0].ptr])})})},e.prototype._queryHistory=function(e,t,n){if(!this.historyModes)return void this._getTableHistory("_hist",function(e){n(e)});var r=this._histTable(e);if(r){if(!e)throw Error("Need a table to query this history!");this._getTableHistory(r,n)}else{if(!t)throw Error("Need a row primary key to query this history!");var i="_"+e+"__hist_idx";this.parent.table(i).query("select").where(["id","=",t]).exec().then(function(e){var t=e[0];n([t.histRows.length,t.histRows.length-t.histPtr-1])})}},e.prototype._shiftTableHistory=function(e,t,n){var r=this;this.parent.table(t+"_ptr").query("select").exec().then(function(o){var s=i._assign(o[0]);s.ptr+="<"===e?1:-1,s.ptr<0&&(s.ptr=0),r.parent.extend("idx.length",t).then(function(a){if(s.ptr>a&&(s.ptr=a),o[0].ptr===s.ptr)return void n(!1);r.parent.table(t).query("select").range(-1,"<"===e?o[0].ptr:s.ptr).exec().then(function(o){r.parent.table(t+"_ptr").query("upsert",s).exec().then(function(){new i.ALL(o[0].keys.map(function(t){return function(n){r._shiftRowHistory(e,o[0].table,t,n)}})).then(function(e){n(e.indexOf(!0)>-1)})})})})})},e.prototype._shiftRowHistory=function(e,t,n,r){var o=this,s=function(e){o.parent.table("_"+t+"__hist_idx").query("upsert",e).where([o._tablePkKeys[t],"=",n]).exec().then(function(){r(!0)})};this.parent.table("_"+t+"__hist_idx").query("select").where([this._tablePkKeys[t],"=",n]).exec().then(function(a){var u=i._assign(a[0]);if(u.histPtr+="<"===e?1:-1,u.histPtr<0&&(u.histPtr=0),u.histPtr>u.histRows.length-1&&(u.histPtr=u.histRows.length-1),u.histPtr===a[0].histPtr)return void r(!1);var c=u.histRows[u.histPtr];-1===c?o.parent.table(t).query("delete").comment("History Write").where([o._tablePkKeys[t],"=",n]).exec().then(function(){s(u)}):o.parent.table("_"+t+"__hist_rows").query("select").where(["_id","=",c]).exec().then(function(e){o.parent.table(t).query("upsert",e[0]).comment("History Write").exec().then(function(){s(u)})})})},e.prototype._shiftHistory=function(e,t,n,r){if(!this.historyModes)return void this._shiftTableHistory(e,"_hist",r);var i=this._histTable(t);if(i){if(!t)throw Error("Need a table to change this history!");this._shiftTableHistory(e,i,r)}else{if(!n)throw Error("Need a row primary key to change this history!");this._shiftRowHistory(e,t,n,r)}},e}();t._NanoSQLHistoryPlugin=s}])}); \ No newline at end of file +!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.e?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=4)}([function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var r=n(1);t.t=function(e){return e?JSON.parse(JSON.stringify(e)):null};var i=function(){function e(e){this.callbacks=e}return e.prototype.then=function(e){var t=this,n=[],i=0;this.callbacks&&this.callbacks.length||e([]);var o=function(){i0||s.indexOf("Trident/")>0||s.indexOf("Edge/")>0),t.isAndroid=/Android/.test(s),t.random16Bits=function(){if("undefined"==typeof crypto)return Math.round(Math.random()*Math.pow(2,16));if(crypto.getRandomValues){var e=new Uint16Array(1);return crypto.getRandomValues(e),e[0]}return"undefined"!==global&&global.r.randomBytes?global.r.randomBytes(2).reduce(function(e,t){return t*e}):Math.round(Math.random()*Math.pow(2,16))},t.timeid=function(e){for(var n=Math.round((new Date).getTime()/(e?1:1e3)).toString();n.length<(e?13:10);)n="0"+n;return n+"-"+(t.random16Bits()+t.random16Bits()).toString(16)},t.uuid=function(){var e,n,r="";return[r,r,r,r,r,r,r,r,r].reduce(function(i,o,s){for(e=t.random16Bits(),n=4===s?s:5===s?(e%16&3|8).toString(16):r,e=e.toString(16);e.length<4;)e="0"+e;return i+([3,4,5,6].indexOf(s)>-1?"-":r)+(n+e).slice(0,4)},r)},t.hash=function(e){return Math.abs(e.split("").reduce(function(t,n,r){return(t<<5)+t+e.charCodeAt(r)},0)).toString(16)},t.generateID=function(e,n){switch(e){case"int":return n||1;case"uuid":return t.uuid();case"timeId":return t.timeid();case"timeIdms":return t.timeid(!0)}return""},t.cleanArgs=function(e,n){for(var r={},i=e.length||-1;i--;){var o=e[i].split(":");o.length>1?r[o[0]]=t.cast(o[1],n[o[0]]||void 0):r[o[0]]=n[o[0]]||void 0}return r},t.isObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)},t.cast=function(e,n){var r={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="},i=typeof n;if("undefined"===i||null===n)return n;var o=function(e,n){switch(e){case"safestr":return o("string",n).replace(/[&<>"'`=\/]/gim,function(e){return r[e]});case"int":return"number"!==i||n%1!=0?parseInt(n||0):n;case"number":case"float":return"number"!==i?parseFloat(n||0):n;case"any[]":case"array":return Array.isArray(n)?n:[];case"uuid":case"timeId":case"timeIdms":case"string":return"string"!==i?String(n):n;case"object":case"obj":case"map":return t.isObject(n)?n:{};case"boolean":case"bool":return!0===n}return n},s=o(String(e||"").toLowerCase(),n);if(-1!==e.indexOf("[]")){var a=e.slice(0,e.lastIndexOf("[]"));return(n||[]).map(function(e){return t.cast(a,e)})}return void 0!==s?["int","float","number"].indexOf(e)>-1&&isNaN(s)?0:s:void 0},t.sortedInsert=function(e,n,r,i){return e.length?(e.splice(t.binarySearch(e,n),0,n),e):(e.push(n),e)},t.binarySearch=function(e,n,r,i){var o=e.length,s=r||0,a=void 0!==i?i:o-1;if(0===o)return 0;if(n>e[a])return a+1;if(n=a)return 0;var u=s+Math.floor((a-s)/2);return ne[u]?t.binarySearch(e,n,u+1,a):0},t.removeDuplicates=function(e){if(!e.length)return[];for(var t=[e[0]],n=1;n-1?[].concat.apply([],e.split(".").map(function(e){return e.match(/([^\[]+)|\[([^\]]+)\]\[/gim)||e})).map(function(e){return e.replace(/\[|\]/gim,"")}):e.split("."),n){var s=o.shift()+"."+o.shift();o.unshift(s)}return a[i]=o,r(o,0,t)}},function(e,t,n){"use strict";function r(e,n,r){t.setFast(function(){var t;try{t=n.apply(null,r)}catch(t){return m.a(e,t)}return t===e?m.a(e,new TypeError):m.u(e,t),null})}function i(e){var t=e&&e.then;return!e||"object"!=typeof e&&"function"!=typeof e||"function"!=typeof t?null:function(){t.apply(e,arguments)}}function o(e,t){function n(){for(var t=[],n=0;n=this.ai&&this.ai++,this.T[String(e)]=this.j.length,this.j.push(e);else{var t=r.binarySearch(this.j,e);this.j.splice(t,0,e),this.T[String(e)]=t;for(var n=t+1;n0}),this},e.prototype.model=function(e){var t=this,n=t.sTable;return Array.isArray(n)?this:(t.Q[n]||(t.Q[n]=new a.ReallySmallEvents),t.N[n]=e,t.P[n]=[],t.L[n]=[],t)},e.prototype.views=function(e){return Array.isArray(this.sTable)?this:(this.P[this.sTable]=e,this)},e.prototype.getView=function(e,t){return void 0===t&&(t={}),Array.isArray(this.sTable)?new i.v(function(e,t){return t()}):this.V("View",this.P[this.sTable],e,t)},e.prototype.actions=function(e){return Array.isArray(this.sTable)?this:(this.L[this.sTable]=e,this)},e.prototype.doAction=function(e,t){return Array.isArray(this.sTable)?new i.v(function(e,t){return t()}):this.V("Action",this.L[this.sTable],e,t)},e.prototype.V=function(e,t,n,r){var o=this,s=t.reduce(function(e,t){return t.name===n?t:e},null);return s?(o.U=n,s.call(s.args?u.cleanArgs(s.args,r):{},o)):new i.v(function(e,t){return t("Action/View Not Found!")})},e.prototype.query=function(e,t,n){var r=this,i=new o.z(r.sTable,r,e.toLowerCase(),t,r.U,n);return r.U=void 0,i},e.prototype.triggerEvent=function(e){var t=this;return i.setFast(function(){e.types.forEach(function(n){t.Q["*"].trigger(n,e,t),t.Q["*"].trigger("*",e,t),e.table&&t.Q[e.table]&&t.Q[e.table].trigger(n,e,t)})}),t},e.prototype.default=function(e){var t={},n=this;return Array.isArray(n.sTable)?{}:(n.N[n.sTable].forEach(function(n){t[n.key]=e&&e[n.key]?e[n.key]:n.default,void 0===t[n.key]&&(t[n.key]=u.cast(n.type,null))}),t)},e.prototype.doTransaction=function(e){var t=this,n=this,o=[],a=u.random16Bits().toString(16);return new i.v(function(i,c){if(!n.D.length)return void c("Nothing to do, no plugins!");new u.CHAIN(n.D.map(function(e){return function(t){e.transactionBegin?e.transactionBegin(a,t):t()}})).then(function(){Array.isArray(n.sTable)||e(function(e){var t=e||n.sTable;return{query:function(e,n){return new s.G(e,n,t,o,a)}}},function(){var e=[];new u.CHAIN(o.map(function(t){return function(i){e.push(t.table),n.table(t.table).query(t.action,t.actionArgs,!0).manualExec(r({},t,{transaction:!0,queryID:a,actionArgs:void 0})).then(i)}})).then(function(r){new u.CHAIN(t.D.map(function(e){return function(t){e.transactionEnd?e.transactionEnd(a,t):t()}})).then(function(){e.filter(function(e,t,n){return n.indexOf(e)===t}).forEach(function(e){0!==e.indexOf("_")&&n.triggerEvent({query:o[0],table:e,time:(new Date).getTime(),result:r,types:["transaction"],actionOrView:"",notes:[],transactionID:a,affectedRowPKS:[],affectedRows:[]})}),i(r)})})})})})},e.prototype.config=function(e){return this.K=e,this},e.prototype.extend=function(){for(var e=[],t=0;tr&&(r=u.objQuery(n,e))}),t(r)}else t(0)}},MIN:{type:"A",call:function(e,t,n){if(e.length){var r=u.objQuery(n,e[0])||0;e.forEach(function(e){var t=u.objQuery(n,e);t-1))throw Error("No valid database action!");var u=r||("select"===a||"delete"===a?[]:{});if("upsert"===a){var c={};this.X.N[this.X.sTable].forEach(function(e){void 0!==u[e.key]&&(c[e.key]=i.cast(e.type,u[e.key]))}),u=c}this.$.action=a,this.$.actionArgs=r?u:void 0}}return e.prototype.where=function(e){return this.$.where=e,this},e.prototype.range=function(e,t){return this.$.range=[e,t],this},e.prototype.orm=function(e){return this.$.orm=e,this},e.prototype.orderBy=function(e){return this.$.orderBy=e,this},e.prototype.groupBy=function(e){return this.$.groupBy=e,this},e.prototype.having=function(e){return e.length&&Array.isArray(e)||(this.Z="Having condition requires an array!"),this.$.having=e,this},e.prototype.join=function(e){if(Array.isArray(this.$.table))throw Error("Can't JOIN with instance table!");return e.table&&e.type||(this.Z="Join command requires table and type arguments!"),this.$.join=e,this},e.prototype.limit=function(e){return this.$.limit=e,this},e.prototype.trieSearch=function(e,t){return this.$.trie={column:e,search:t},this},e.prototype.comment=function(e){return this.$.comments.push(e),this},e.prototype.extend=function(){for(var e=[],t=0;t-1?this.te.ie.getIndex(i,"idx"!==t[0],function(n){e(t,n)}):e(t,[]);break;case"rebuild_idx":t[1]?this.te.rebuildIndexes(t[1],function(n){e(t,[n])}):new s.ALL(Object.keys(this.te.tableInfo).map(function(e){return function(t){r.te.rebuildIndexes(e,t)}})).then(function(n){e(t,n)});break;case"clear_cache":t[1]?this.te.oe[t[1]]={}:Object.keys(this.te.tableInfo).forEach(function(e){r.te.oe[e]={}}),e(t,t[1]||Object.keys(this.te.tableInfo));break;default:e(t,n)}},e}();t.NanoSQLDefaultBackend=a},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n")&&(i=e.replace("ref=>",""))}),i&&(n.we[e].push(r.key),n.ve[e][r.key]={me:r.type.replace("[]",""),xe:i.replace("[]",""),qe:-1===i.indexOf("[]")?"single":"array",ke:-1===r.type.indexOf("[]")?"single":"array"})}}()}),Object.keys(this.ve).forEach(function(e){Object.keys(n.ve[e]).forEach(function(t){var r=n.ve[e][t];n.ge[r.me].push({Oe:r.xe,ke:r.qe,Ie:e,Se:t,Ae:r.ke})})}),this.ie.connect(function(){new o.ALL(Object.keys(n.fe).map(function(e){return function(t){var r=n.fe[e];Object.keys(r).length?n.je(e,function(t,i,o){if(!t)return void o(!1);Object.keys(r).forEach(function(r){void 0!==t[r]&&n.fe[e][r].addWord(String(t[r]))}),o(!1)},t):t()}})).then(function(){t(n.models)})})},e.prototype.rebuildIndexes=function(e,t){var n=this,r=(new Date).getTime();new o.ALL(Object.keys(this.tableInfo).map(function(t){return function(r){if("_ALL_"!==e&&e!==t||0===t.indexOf("_"))return void r();var i=n.tableInfo[t].Te;new o.ALL(i.map(function(e){return function(r){var i="_"+t+"_idx_"+e,o=n.tableInfo[t].Ee;n.Re(i,function(){n.je(t,function(e,r,i){n.Le(t,e[o],e,[],function(){i(!1)})},r)})}})).then(r)}})).then(function(){t((new Date).getTime()-r)})},e.prototype.Pe=function(e){return o.isObject(e)||Array.isArray(e)?JSON.stringify(e).substr(0,12):"number"==typeof e?e:String(e).substr(0,32)},e.prototype._e=function(){if("undefined"==typeof window)return"LVL";if(o.isSafari)return"WSQL";if(o.isMSBrowser)return"undefined"!=typeof indexedDB?"IDB":"LS";if(-1===[typeof Worker,typeof Blob,typeof indexedDB].indexOf("undefined")&&window.URL&&window.URL.createObjectURL)try{var e=new Worker(window.URL.createObjectURL(new Blob(["var t = 't';"])));return e.postMessage(""),e.terminate(),indexedDB.open("1234",1),indexedDB.deleteDatabase("1234"),"IDB_WW"}catch(e){if("undefined"!=typeof indexedDB)return"IDB"}return"LS"},e.prototype.Ne=function(e,t,n,r){var i=this;this.ie.read("_"+e+"_idx_"+t,this.Pe(n),function(t){void 0!==t?i.je(e,t.rows||[],r):r([])})},e.prototype.Ce=function(e,t,n,r){var i=[];this.ie.rangeRead(e,function(e,t,n){i.push(e),n()},function(){r(i)},t,n)},e.prototype.Me=function(e,t,n,r){var i=[];this.ie.rangeRead(e,function(e,t,n){i.push(e),n()},function(){r(i)},t,n,!0)},e.prototype.je=function(e,t,n){var r=this;if(Array.isArray(t))return void new o.ALL(t.map(function(t){return function(n){r.ie.read(e,t,n)}})).then(function(e){n(e.filter(function(e){return e}))});var i=[];return"function"==typeof t?void this.ie.rangeRead(e,function(e,n,r){t(e,n,function(t){t&&i.push(e),r()})},function(){n(i)}):void 0},e.prototype.Be=function(e,t,n,r){var i=this,s=this.fe[e][t].getPrefix(n);new o.ALL(s.map(function(n){return function(r){i.Ne(e,t,n,r)}})).then(function(e){r([].concat.apply([],e))})},e.prototype.De=function(e,t,n,r,i){var s=this;new o.ALL(this.tableInfo[e].Te.filter(function(e){return-1===r.indexOf(e)}).map(function(r){return function(i){var a=s.Pe(n[r]),u="_"+e+"_idx_"+r;s.ie.read(u,a,function(e){if(!e)return void i();var n=e.rows.indexOf(t);if(-1===n)return void i();var r=e?Object.isFrozen(e)?o.t(e):e:{id:null,rows:[]};r.rows.splice(n,1),r.rows.sort(),r.rows=o.removeDuplicates(r.rows),s.ie.write(u,r.id,r,i,!0)})}})).then(i)},e.prototype.Le=function(e,t,n,r,i){var s=this;new o.ALL(this.tableInfo[e].Te.filter(function(e){return-1===r.indexOf(e)}).map(function(r){return function(i){var a=s.Pe(n[r]);s.fe[e][r]&&s.fe[e][r].addWord(String(n[r]));var u="_"+e+"_idx_"+r;s.ie.read(u,a,function(e){var n=e?Object.isFrozen(e)?o.t(e):e:{id:a,rows:[]};n.rows.push(t),n.rows.sort(),n.rows=o.removeDuplicates(n.rows),s.ie.write(u,a,n,i,!0)})}})).then(i)},e.prototype.Qe=function(e,t,n,i,o){var s=this;if(n){var a=r({},n,i,(c={},c[this.tableInfo[e].Ee]=t,c)),u=Object.keys(a).filter(function(e){return a[e]===n[e]});this.De(e,t,n,u,function(){s.Le(e,t,a,u,function(){s.ie.write(e,t,a,o,!0)})})}else this.ie.write(e,t,i,function(t){s.Le(e,t[s.tableInfo[e].Ee],i,[],function(){o(t)})},!0);var c},e.prototype.He=function(e,t,n){var r=this;if(!t)throw new Error("Can't delete without a primary key!");this.ie.read(e,t,function(i){r.De(e,t,i,[],function(){r.ie.delete(e,t,function(){n(i)})})})},e.prototype.Re=function(e,t){var n=this;new o.ALL(this.tableInfo[e].Te.map(function(t){return function(r){n.ie.drop("_"+e+"_idx_"+t,r)}})).then(function(){n.fe[e]={},n.tableInfo[e].Ke.forEach(function(t){n.fe[e][t]=new i.Trie([])}),n.ie.drop(e,t)})},e.prototype.ye=function(e){return Object.keys(e).forEach(function(t){var n=!1,r=!1;if(e[t].forEach(function(i){i.props&&i.props.indexOf("pk")>-1&&(n=!0),i.props&&(i.props.indexOf("idx")>-1||i.props.indexOf("trie")>-1)&&(r=!0,e["_"+t+"_idx_"+i.key]=[{key:"id",type:"string",props:["pk"]},{key:"rows",type:"any[]"}])}),r&&!n)throw new Error("Tables with secondary indexes must have a primary key!")}),e},e.prototype.be=function(e,t){this.tableInfo[e]={Ee:"",Fe:"",We:[],Je:[],Te:[],Ke:[],Ve:e},this.oe[e]={},this.fe[e]={},this.ie.makeTable(e,t);for(var n=this.models[e].length;n--;){var r=this.models[e][n];this.tableInfo[e].We.unshift(r.key),this.tableInfo[e].Je[n]=r.default,r.props&&r.props.indexOf("pk")>-1&&(this.tableInfo[e].Ee=r.key,this.tableInfo[e].Fe=r.type),r.props&&(r.props.indexOf("idx")>-1||r.props.indexOf("trie")>-1)&&this.tableInfo[e].Te.push(r.key),r.props&&r.props.indexOf("trie")>=0&&(this.tableInfo[e].Ke.push(r.key),this.fe[e][r.key]=new i.Trie([]))}return e},e}();t.ne=c},function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n={END_WORD:"$",PERMS_MIN_LEN:2},r=function(){function e(t){this.Ue=e.ze(t)}return e.prototype.addWord=function(t){var n=function(t,n,r,i){return e.Ge(t,n,r,i)};return t.toLowerCase().split("").reduce(n,this.Ue),this},e.prototype.removeWord=function(t){var r=e.Xe(this.Ue,t),i=r.prefixFound,o=r.prefixNode;return i&&delete o[n.END_WORD],this},e.prototype.getWords=function(){return e.Ye(this.Ue,"")},e.prototype.getPrefix=function(t){if(t=t.toLowerCase(),!this.$e(t))return[];var n=e.Xe(this.Ue,t).prefixNode;return e.Ye(n,t)},e.prototype.$e=function(t){return e.Xe(this.Ue,t).prefixFound},e.Ge=function(e,t,r,i){return e[t]=e[t]||{},e=e[t],r===i.length-1&&(e[n.END_WORD]=1),e},e.Xe=function(e,t){return{prefixFound:t.toLowerCase().split("").every(function(t,n){return!!e[t]&&(e=e[t])}),prefixNode:e}},e.ze=function(t){return t.reduce(function(t,n){return n.toLowerCase().split("").reduce(e.Ge,t),t},{})},e.Ye=function(t,r,i){void 0===i&&(i=[]);var o=r;for(var s in t)s===n.END_WORD&&(i.push(o),o=""),e.Ye(t[s],r+s,i);return i.sort()},e}();t.Trie=r},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n.Fe[e]=t.type,n.Ze[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n.tt[e].doAI=!0),n.nt){var r=localStorage.getItem(n.ue+"*"+e+"_idx");r&&n.tt[e].set(JSON.parse(r))}})},e.prototype.write=function(e,t,n,i,s){if(!(t=t||o.generateID(this.Fe[e],this.tt[e].ai)))throw new Error("Can't add a row without a primary key!");if(-1===this.tt[e].indexOf(t)&&(this.tt[e].add(t),this.nt&&localStorage.setItem(this.ue+"*"+e+"_idx",JSON.stringify(this.tt[e].keys()))),this.nt){var a=r({},s?{}:JSON.parse(localStorage.getItem(this.ue+"*"+e+"__"+t)||"{}"),n,(u={},u[this.Ze[e]]=t,u));localStorage.setItem(this.ue+"*"+e+"__"+t,JSON.stringify(a)),i(a)}else{var a=r({},s?{}:this.et[e][t],n,(c={},c[this.Ze[e]]=t,c));this.et[e][t]=o.deepFreeze(a),i(a)}var u,c},e.prototype.delete=function(e,t,n){-1!==this.tt[e].indexOf(t)&&(this.tt[e].remove(t),this.nt&&localStorage.setItem(this.ue+"*"+e+"_idx",JSON.stringify(this.tt[e].keys()))),this.nt?localStorage.removeItem(this.ue+"*"+e+"__"+t):delete this.et[e][t],n()},e.prototype.read=function(e,t,n){if(this.nt){var r=localStorage.getItem(this.ue+"*"+e+"__"+t);n(r?JSON.parse(r):void 0)}else n(this.et[e][t])},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this.tt[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[0,u.length-1];if(!u.length)return void n();s&&c&&(f=f.map(function(t){return a.tt[e].getLocation(t)}));var h=f[0],_=0,l=function(){h++,_++,_>200?i.setFast(d):d()},d=function(){if(h<=f[1])if(a.nt){var r=localStorage.getItem(a.ue+"*"+e+"__"+u[h]);t(r?JSON.parse(r):void 0,h,l)}else t(a.et[e][u[h]],h,l);else n()};d()},e.prototype.drop=function(e,t){var n=this;this.nt?(localStorage.setItem(this.ue+"*"+e+"_idx",JSON.stringify([])),this.tt[e].keys().forEach(function(t){localStorage.removeItem(n.ue+"*"+e+"__"+t)})):this.et[e]={};var r=new s.DatabaseIndex;r.doAI=this.tt[e].doAI,this.tt[e]=r,t()},e.prototype.getIndex=function(e,t,n){n(t?this.tt[e].keys().length:this.tt[e].keys())},e.prototype.destroy=function(e){var t=this;new o.ALL(Object.keys(this.tt).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();t.pe=a},function(module,exports,__webpack_require__){var __assign=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n.Fe[e]=t.type,n.Ze[e]=t.key,t.props&&t.props.indexOf("ai")>-1&&("int"===t.type||"number"===t.type)&&(n.tt[e].doAI=!0))})},e.prototype.write=function(e,t,n,r,i){var o=this;if(!(t=t||utilities_1.generateID(this.Fe[e],this.tt[e].ai)))throw new Error("Can't add a row without a primary key!");-1===this.tt[e].indexOf(t)&&this.tt[e].add(t);var s=utilities_1.uuid(),a=__assign({},n,(c={},c[this.Ze[e]]=t,c));this.it["write_"+s]=function(e){r(a)};var u=function(t){a=__assign({},t,a),o.st.postMessage({do:"write",args:{table:e,id:s,row:a}})};i?u({}):this.read(e,t,function(e){u(e)});var c},e.prototype.delete=function(e,t,n){-1!==this.tt[e].indexOf(t)&&this.tt[e].remove(t);var r=utilities_1.uuid();this.it["delete_"+r]=function(e){n()},this.st.postMessage({do:"delete",args:{table:e,id:r,pk:t}})},e.prototype.read=function(e,t,n){var r=utilities_1.uuid();if(-1===this.tt[e].indexOf(t))return void n(null);this.it["read_"+r]=function(e){n(e)},this.st.postMessage({do:"read",args:{table:e,id:r,pk:t}})},e.prototype.rangeRead=function(e,t,n,r,i,o){var s=this,a=this.tt[e].keys(),u=-1===[typeof r,typeof i].indexOf("undefined"),c=u?[r,i]:[0,a.length-1];if(!a.length)return void n();var f=utilities_1.uuid(),h=[],_=c[0],l=0;this.it["readRange_"+f+"_done"]=function(e){delete s.it["readRange_"+f],h=e;var r=function(){_<=c[1]?t(h[l],_,function(){_++,l++,l>200?lie_ts_1.setFast(r):r()}):n()};r()},this.st.postMessage({do:"readRange",args:{table:e,id:f,range:o&&u?c:c.map(function(e){return a[e]})}})},e.prototype.drop=function(e,t){var n=new db_idx_1.DatabaseIndex;n.doAI=this.tt[e].doAI,this.tt[e]=n;var r=utilities_1.uuid();this.it["delete_"+r]=function(e){t()},this.st.postMessage({do:"delete",args:{table:e,id:r,pk:"_clear_"}})},e.prototype.getIndex=function(e,t,n){n(t?this.tt[e].keys().length:this.tt[e].keys())},e.prototype.destroy=function(e){var t=this;new utilities_1.ALL(Object.keys(this.tt).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();exports.le=_IndexedDBStore},function(e,t){e.exports='function e(e){this.go=function(n){var t=0;e&&e.length||n([]),e.forEach(function(o,r){o(function(){++t===e.length&&n([])})})}}var n={db:null,store:function(e,t,o){var r=n.db.transaction(e,t);o(r,r.objectStore(e),function(e,n){return function(){postMessage({do:e,args:n})}})},init:function(){addEventListener("message",function(e){var t=e.data;n[t.do]&&n[t.do](t.args)},!1)},setup:function(t){var o=indexedDB.open(t.id,1),r=!1,a={};o.onupgradeneeded=function(e){r=!0,n.db=e.target.result,Object.keys(t.pkKeys).forEach(function(e){n.db.createObjectStore(e,{keyPath:t.pkKeys[e]}),a[e]=[]})},o.onsuccess=function(o){if(n.db=o.target.result,r)postMessage({do:"rdy",args:a});else{var s=function(e,t){var o=[];n.store(e,"readonly",function(e,n,r){n.openCursor().onsuccess=function(e){var n=e.target.result;n&&(o.push(n.key),n.continue())},e.oncomplete=function(){t(o)}})};new e(Object.keys(t.pkKeys).map(function(e){return function(n){s(e,function(t){a[e]=t,n()})}})).go(function(){postMessage({do:"rdy",args:a})})}}},write:function(e){n.store(e.table,"readwrite",function(n,t,o){t.put(e.row),n.oncomplete=o("write_"+e.id,null)})},read:function(e){n.store(e.table,"readonly",function(n,t,o){var r=t.get(e.pk);r.onsuccess=function(){postMessage({do:"read_"+e.id,args:r.result})}})},readRange:function(e){n.store(e.table,"readonly",function(n,t,o){var r=[],a=-1===e.range.indexOf(void 0)?t.openCursor(IDBKeyRange.bound(e.range[0],e.range[1])):t.openCursor();n.oncomplete=o("readRange_"+e.id+"_done",r),a.onsuccess=function(e){var n=e.target.result;n&&(r.push(n.value),n.continue())}})},delete:function(e){n.store(e.table,"readwrite",function(n,t,o){n.oncomplete=o("delete_"+e.id,!0),n.onerror=o("delete_"+e.id,!1),"_clear_"===e.pk?t.clear():t.delete(e.pk)})}};n.init();'},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n.Fe[e]=t.type,n.Ze[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n.tt[e].doAI=!0)})},e.prototype.ut=function(e,t,n,r){var i=function(e){e.executeSql(t,n,function(e,t){r(t)},function(e,r){return console.error(t,n,r),!1})};e?this.X.transaction(i):this.X.readTransaction(i)},e.prototype.write=function(e,t,n,i,s){var a=this;if(!(t=t||o.generateID(this.Fe[e],this.tt[e].ai)))throw new Error("Can't add a row without a primary key!");var u=!1;if(-1===this.tt[e].indexOf(t)&&(u=!0,this.tt[e].add(t)),u){var c=r({},n,(h={},h[this.Ze[e]]=t,h));this.ut(!0,"INSERT into "+this.ct(e)+" (id, data) VALUES (?, ?)",[t,JSON.stringify(c)],function(e){i(c)})}else{var f=function(o){var s=r({},o,n,(u={},u[a.Ze[e]]=t,u));a.ut(!0,"UPDATE "+a.ct(e)+" SET data = ? WHERE id = ?",[JSON.stringify(s),t],function(){i(s)});var u};s?f({}):this.read(e,t,function(e){f(e)})}var h},e.prototype.delete=function(e,t,n){-1!==this.tt[e].indexOf(t)&&this.tt[e].remove(t),this.ut(!0,"DELETE FROM "+this.ct(e)+" WHERE id = ?",[t],function(){n()})},e.prototype.read=function(e,t,n){this.ut(!1,"SELECT data FROM "+this.ct(e)+" WHERE id = ?",[t],function(e){n(e.rows.length?JSON.parse(e.rows.item(0).data):void 0)})},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this.tt[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[];if(!u.length)return void n();s&&c&&(f=f.map(function(t){return a.tt[e].getLocation(t)}));var h=f[0]||0,_=[],l=f[0],d="SELECT data from "+this.ct(e);if(f.length){for(var p="number"==typeof u[l];l<=f[1];)_.push(p?u[l]:'"'+u[l]+'"'),l++;d+=" WHERE id IN ("+_.join(", ")+")"}d+=" ORDER BY id",this.ut(!1,d,[],function(e){var r=0,o=function(){e.rows.length>r?t(JSON.parse(e.rows.item(r).data),h,function(){h++,r++,r>200?i.setFast(o):o()}):n()};o()})},e.prototype.drop=function(e,t){var n=new s.DatabaseIndex;n.doAI=this.tt[e].doAI,this.tt[e]=n,this.ut(!0,"DELETE FROM "+this.ct(e),[],function(e){t()})},e.prototype.getIndex=function(e,t,n){n(t?this.tt[e].keys().length:this.tt[e].keys())},e.prototype.destroy=function(e){var t=this;new o.ALL(Object.keys(this.tt).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();t.de=a},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n0:e===t}(t[a][r.Oe],n[a][r.Oe]))s();else if("array"===r.ke){var h=(n[a][r.Oe]||[]).filter(function(e){return-1===(t[a][r.Oe]||[]).indexOf(e)}),_=(t[a][r.Oe]||[]).filter(function(e){return-1===(n[a][r.Oe]||[]).indexOf(e)});new o.ALL([h,_].map(function(e,t){return function(n){i.pt(r,e,0===t,f,n)}})).then(s)}else{var l=function(){void 0!==n[a][r.Oe]?i.pt(r,[n[a][r.Oe]],!0,f,s):s()};void 0!==t[a][r.Oe]?i.pt(r,[t[a][r.Oe]],!1,f,l):l()}else{var d="array"===r.ke?n[a][r.Oe]||[]:[n[a][r.Oe]].filter(function(e){return e});d&&d.length?i.pt(r,d,!0,f,s):s()}}}})).then(r)}})).then(r)},e.prototype._t=function(e){var t=this,n=this.te.tableInfo[this.$.table].Ee;if(this.ft)return void this.lt(function(n){t.$.result=t.$.table.map(function(e){return-1===n.indexOf(e)?e:r({},t.$.actionArgs,e)}),e(t.$)});if(this.$.where)this.lt(function(r){r.length?new o.CHAIN(r.map(function(e){return function(r){t.te.Qe(t.$.table,e[n],e,t.$.actionArgs||{},r)}})).then(function(i){t.te.oe[t.$.table]={},t.$.result=[{msg:i.length+" row(s) modfied.",affectedRowPKS:i.map(function(e){return e[n]}),affectedRows:i}],t.yt("add",r,i,function(){e(t.$)})}):(t.$.result=[{msg:"0 row(s) modfied.",affectedRowPKS:[],affectedRows:[]}],e(t.$))});else{var i=this.$.actionArgs||{};this.te.oe[this.$.table]={};var s=function(r){t.te.Qe(t.$.table,i[n],r,i,function(i){t.$.result=[{msg:"1 row inserted.",affectedRowPKS:[i[n]],affectedRows:[i]}],t.yt("add",[r].filter(function(e){return e}),[i],function(){e(t.$)})})};void 0!==i[n]?this.te.je(this.$.table,[i[n]],function(e){s(e.length?e[0]:null)}):s(null)}},e.prototype.He=function(e){var t=this;if(this.ft)return void(this.$.where?this.lt(function(n){t.$.result=t.$.table.filter(function(e){return-1===n.indexOf(e)}),e(t.$)}):(this.$.result=[],e(this.$)));this.$.where?this.lt(function(n){n=n.filter(function(e){return e}),n.length?new o.ALL(n.map(function(e){return function(n){t.te.He(t.$.table,e[t.te.tableInfo[t.$.table].Ee],n)}})).then(function(r){t.te.oe[t.$.table]={},t.$.result=[{msg:n.length+" row(s) deleted.",affectedRowPKS:n.map(function(e){return e[t.te.tableInfo[t.$.table].Ee]}),affectedRows:n}],t.yt("del",n,[],function(){e(t.$)})}):(t.$.result=[{msg:"0 row(s) deleted.",affectedRowPKS:[],affectedRows:[]}],e(t.$))}):this.Re(e)},e.prototype.Re=function(e){var t=this;if(this.ft)return this.$.result=[],void e(this.$);this.te.Ce(this.$.table,void 0,void 0,function(n){t.te.oe[t.$.table]={},t.te.Re(t.$.table,function(){t.$.result=[{msg:"'"+t.$.table+"' table dropped.",affectedRowPKS:n.map(function(e){return e[t.te.tableInfo[t.$.table].Ee]}),affectedRows:n}],t.yt("del",n,[],function(){e(t.$)})})})},e}();t.re=s;var a=function(){function e(e,t){this.q=e,this.s=t,this.bt=[]}return e.prototype.vt=function(e,t){var n=this;if(this.q.join){var r={};"cross"!==this.q.join.type&&this.q.join.where&&(r={gt:this.q.join.where[0],wt:this.q.join.where[1],mt:this.q.join.where[2]});var i=this.q.table,o=this.q.join.table;this.xt(this.q.join.type,i,o,r,function(e){t(n.q.where?e.filter(function(e,t){return Array.isArray(n.q.where)?f(e,n.q.where||[],t,!0):n.q.where(e,t)}):n.q.range?e.filter(function(e,t){return n.q.range&&n.q.range[0]>=t&&n.q.range[1]<=t}):e)})}},e.prototype.qt=function(e,t){return e.reduce(function(e,n){return-1!==n.indexOf(".length")?e+"."+String((t[n.replace(".length","")]||[]).length):e+"."+String(t[n])},"").slice(1)},e.prototype.kt=function(e){var t=this,n=this.q.groupBy||{},r=e.sort(function(e,r){return t.Ot(e,r,n,!0)});return r.forEach(function(e,r){var i=Object.keys(n).map(function(t){return String(e[t])||""}).join(".");t.It||(t.It={}),t.It[i]||(t.It[i]=[]),t.It[i].push(r)}),r},e.prototype.St=function(e){var t=this;return e.filter(function(e,n){return Array.isArray(t.q.having)?f(e,t.q.having||[],n,!0):t.q.having(e,n)})},e.prototype.At=function(e){var t=this;return e.sort(function(e,n){return t.Ot(e,n,t.q.orderBy||{},!1)})},e.prototype.jt=function(e){var t=this;return e.filter(function(e,n){return!t.q.offset||n>=t.q.offset})},e.prototype.Tt=function(e){var t=this;return e.filter(function(e,n){return!t.q.limit||n-1&&_.push(h(t,null)),i(!1)})},function(){e===s?a.s.je(c.Ve,function(e,t,n){-1===d.indexOf(t)&&_.push(h(null,e)),n(!1)},function(){i(_)}):i(_)})},e.prototype.Ot=function(e,t,n,r){return Object.keys(n).reduce(function(i,s){var a=r?o.objQuery(s,e):e[s],u=r?o.objQuery(s,t):t[s];return i||(a===u?0:(a>u?1:-1)*("desc"===n[s]?-1:1))},0)},e.prototype.Rt=function(e,t){var n=this,r=this.q.actionArgs,s={},a={};if(r&&r.length){var u=!1,c={};r.forEach(function(e){if(-1!==e.indexOf("(")){var t=(e.match(/^.*\(/g)||[""])[0].replace(/\(|\)/g,"").toUpperCase(),n=i.NanoSQLInstance.functions[t],r=1===e.split(" AS ").length?t:(e.split(" AS ").pop()||"").trim();if(!n)throw new Error("'"+t+"' is not a valid function!");"A"===n.type&&(u=!0),c[e]={fn:n,key:r}}}),new o.ALL(r.map(function(t){return function(r){if(t.indexOf("(")>-1){var i=(t.match(/\(.*\)/g)||[""])[0].replace(/\(|\)/g,"").split(",").map(function(e){return e.trim()});n.It&&u?new o.ALL(Object.keys(n.It).map(function(r){return a[r]||(a[r]={}),function(o){(s=c[t].fn).call.apply(s,[e.filter(function(e,t){return n.It[r].indexOf(t)>-1}),function(e){a[r][c[t].key]=e,o()}].concat(i));var s}})).then(r):(f=c[t].fn).call.apply(f,[e,function(e){s[c[t].key]=e,r()}].concat(i))}else r();var f}})).then(function(){var i=function(e,t,i){var s={};return r.forEach(function(r){var a=r.indexOf("(")>-1,u=a?c[r].fn.type:"";if(r.indexOf(" AS ")>-1){var f=r.split(" AS "),h=a?c[r].key:f[0].trim();s[f[1]]=a?"A"===u?i[h]:i[h][t]:o.objQuery(h,e,void 0!==n.q.join)}else{var h=a?c[r].key:r;s[r]=a?"A"===u?i[h]:i[h][t]:o.objQuery(h,e,void 0!==n.q.join)}}),s};if(n.It&&u){var f=[];Object.keys(n.It).forEach(function(t){var r=e.filter(function(e,r){return n.It[t].indexOf(r)>-1}).filter(function(e,t){return t<1});r&&r.length&&f.push(i(r[0],0,a[t]))}),t(f)}else t(u?e.filter(function(e,t){return t<1}).map(function(e,t){return i(e,t,s)}):e.map(function(e,t){return i(e,t,s)}))})}else t(e)},e.prototype.dt=function(e,t){var n=this,r=function(){n.q.having&&(e=n.St(e)),n.q.orderBy&&(e=n.At(e)),n.q.offset&&(e=n.jt(e)),n.q.limit&&(e=n.Tt(e)),t(e)},i=function(){n.q.actionArgs&&n.q.actionArgs.length?n.Rt(e,function(t){e=t,r()}):r()},o=function(){n.q.groupBy&&(e=n.kt(e)),n.q.orm?n.Et(e,function(t){e=t,i()}):i()};this.q.join?this.vt(e,function(t){e=t,o()}):o()},e}();t.Lt=a;var u=function(){function e(e,t){this.q=e,this.s=t}return e.prototype.getRows=function(e){var t=this;if(this.q.join)return void e([]);if(this.q.join&&this.q.orm)throw new Error("Cannot do a JOIN and ORM command at the same time!");if([this.q.where,this.q.range,this.q.trie].filter(function(e){return e}).length>1)throw new Error("Can only have ONE of Trie, Range or Where!");return this.q.trie&&this.q.trie.column&&this.q.trie.search?void this.Pt(e):this.q.range&&this.q.range.length?void this.Nt(e):this.q.where&&this.q.where.length?Array.isArray(this.q.where)?("string"==typeof this.q.where[0]?0===this.Ct(this.q.where):0===(this.q.where||[]).reduce(function(e,n,r){return r%2==1?e:e+t.Ct(n)},0))?void this.Mt(e):void this.Bt(e):void this.Bt(function(n){e(n.filter(t.q.where))}):void this.Bt(e)},e.prototype.Mt=function(e){var t=this;if(this.q.where&&"string"==typeof this.q.where[0])this.Dt(this.q.where,e);else if(this.q.where){var n=[],r="";new o.CHAIN(this.q.where.map(function(e){return function(i){if("OR"===e||"AND"===e)return r=e,void i();t.Dt(e,function(e){if("AND"===r){var o=e.map(function(e){return e[t.s.tableInfo[t.q.table].Ee]});n=n.filter(function(e){return-1!==o.indexOf(e[t.s.tableInfo[t.q.table].Ee])})}else n.concat(e);i()})}})).then(function(){e(n)})}},e.prototype.Dt=function(e,t){var n=this;if("BETWEEN"!==e[1]){var r=[];switch(e[1]){case"IN":r=e[2];break;case"=":r=[e[2]]}e[0]===this.s.tableInfo[this.q.table].Ee?this.s.je(this.q.table,r,t):new o.ALL(r.map(function(t){return function(r){n.s.Ne(n.q.table,e[0],t,r)}})).then(function(e){t([].concat.apply([],e))})}else{var i=e[0]===this.s.tableInfo[this.q.table].Ee?"":e[0];if(i){var s="_"+this.q.table+"_idx_"+i;this.s.Me(s,e[2][0],e[2][1],function(e){var r=[].concat.apply([],e);n.s.je(n.q.table,r,t)})}else this.s.Me(this.q.table,e[2][0],e[2][1],function(e){t(e)})}},e.prototype.Nt=function(e){var t=this;if(this.q.range){var n=this.q.range;this.s.ie.getIndex(this.q.table,!0,function(r){for(var i=n[0]>0?n[1]:r+n[0]-n[1],o=i,s=Math.abs(n[0])-1;s--;)o++;t.s.Ce(t.q.table,i,o,e)})}else e([])},e.prototype.Pt=function(e){this.q.trie?this.s.Be(this.q.table,this.q.trie.column,this.q.trie.search,e):e([])},e.prototype.Bt=function(e){var t=this;this.s.je(this.q.table,function(e,n,r){r(!t.q.where||(Array.isArray(t.q.where)?f(e,t.q.where||[],n||0):t.q.where(e,n)))},e)},e.prototype.Ct=function(e){var t=this.s.tableInfo[this.q.table];return["=","IN","BETWEEN"].indexOf(e[1])>-1&&(e[0]===t.Ee||t.Te.indexOf(e[0])>-1)?0:1},e}();t.Qt=u;var c=function(){function e(e){this.q=e}return e.prototype.getRows=function(e){var t=this;if(this.q.join||this.q.orm||this.q.trie)throw new Error("Cannot do a JOIN, ORM or TRIE command with instance table!");if(this.q.range&&this.q.range.length){var n,r,i=this.q.range;n=i[0]<0?this.q.table.length+i[0]-i[1]:i[1];var o=Math.abs(i[0])-1;for(r=n;o--;)r++;return void e(this.q.table.filter(function(e,t){return t>=n&&t<=r}))}e(this.q.table.filter(function(e,n){return!t.q.where||(Array.isArray(t.q.where)?f(e,t.q.where||[],n):t.q.where(e,n))}))},e}();t.InstanceSelection=c;var f=function(e,t,n,r){var i=["AND","OR"];if("string"!=typeof t[0]){var s=!1,a=t.map(function(t,a){return-1!==i.indexOf(t)?("AND"===t&&(s=!0),t):0===h(t[2],t[1],"_IDX_"===t[0]?n:o.objQuery(t[0],e,r))});if(a.forEach(function(e,t){"OR"===e&&(a[t]=a[t-1]||a[t+1],a[t-1]=void 0,a[t+1]=void 0)}),a=a.filter(function(e){return void 0!==e}),s){var u,c=!1;return-1===a.reduce(function(e,t,n){return 0===n?(e.push(t),u=e.length-1,e):"AND"===t?(c=!0,e.push(t),e):c?(e.push(t),u=e.length-1,c=!1,e):(void 0!==u&&(e[u]=t||e[u]),e)},[]).filter(function(e){return void 0!==e}).indexOf(!1)}return-1!==a.indexOf(!0)}return 0===h(t[2],t[1],"_IDX_"===t[0]?n:o.objQuery(t[0],e,r))},h=function(e,t,n){var r=function(e){return["LIKE","NOT LIKE"].indexOf(t)>-1?String(e||"").toLowerCase():e},i=r(n),o=r(e);if("NULL"===e||"NOT NULL"===e){var s="="===t||"LIKE"===t;return("NULL"===e?null===n||void 0===n:null!==n&&void 0!==n)?s?0:1:s?1:0}switch(t){case"=":return i===o?0:1;case"!=":return i!==o?0:1;case">":return i>o?0:1;case"<":return i=":return i>=o?0:1;case"IN":return(o||[]).indexOf(i)<0?1:0;case"NOT IN":return(o||[]).indexOf(i)<0?0:1;case"REGEX":return i.match(o)?0:1;case"LIKE":return i.indexOf(o)<0?1:0;case"NOT LIKE":return i.indexOf(o)>0?1:0;case"BETWEEN":return o[0]<=i&&o[1]>=i?0:1;case"HAVE":return(i||[]).indexOf(o)<0?1:0;case"NOT HAVE":return(i||[]).indexOf(o)<0?0:1;case"INTERSECT":return(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length>0?0:1;case"NOT INTERSECT":return 0===(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length?0:1;default:return 1}}},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n0){var a=r.parent.table(e).query("select");n||a.range(-1*s.ptr,0),a.exec().then(function(o){if(!o.length)return void t();var a={};o.forEach(function(e){a[e.table]||(a[e.table]=[]),a[e.table]=a[e.table].concat(e.keys)}),new i.ALL(Object.keys(a).map(function(e){return function(t){r.Vt(e,a[e],t,n)}})).then(function(){r.parent.table(e).query("delete").comment("History Purge").where(["id","IN",o.map(function(e){return e.id})]).exec().then(function(){s.ptr=0,r.parent.table(e+"_ptr").query("upsert",s).comment("History Purge").where(["id","=",s.id]).exec().then(t)})})})}else t()})},e.prototype.Gt=function(e,t,n){if(!this.historyModes)return void this.zt("_hist",n);var r=this.Wt(e);r?this.zt(r,n):this.Vt(e,t,n)},e.prototype.Xt=function(e,t,n){if(!this.historyModes)return void this.zt("_hist",n,!0);var r=this.Wt(e);r?this.zt(r,n,!0):this.Vt(e,[t],n,!0)},e.prototype.didExec=function(e,t){var n=this;e.table&&0!==e.table.indexOf("_")&&e.types.indexOf("change")>-1&&-1===e.query.comments.indexOf("History Write")?this.Gt(e.table,e.affectedRowPKS,function(){new i.ALL(e.affectedRows.map(function(t){return function(r){var i=t[n.Ht[e.table]];n.Ft[e.table][i]?n.Ut(e.table,e.types,i,t,!1,function(e){r(i)}):(n.Ft[e.table][i]=!0,n.Ut(e.table,e.types,i,t,!0,function(t){n.parent.table("_"+e.table+"__hist_idx").query("upsert",{id:i,histRows:[t,-1],histPtr:0}).exec().then(function(){r(i)})}))}})).then(function(r){n.Yt(e,r,t)})}):t(e)},e.prototype.Yt=function(e,t,n){var r=this.Wt(e.table);r?this.parent.table(r).query("upsert",{id:i.timeid(!0),table:e.table,keys:t}).exec().then(function(){n(e)}):n(e)},e.prototype.Ut=function(e,t,n,o,s,a){var u=this,c="_"+e+"__hist_idx",f=i.timeid(!0),h=function(e){u.parent.table(c).query("select").where(["id","=",n]).exec().then(function(t){var r=Object.isFrozen(t[0])?i.t(t[0]):t[0];r.histRows.unshift(e),u.parent.table(c).query("upsert",r).where(["id","=",n]).exec().then(function(){a(e)})})};t.indexOf("delete")>-1||t.indexOf("drop")>-1?h(-1):this.parent.table("_"+e+"__hist_rows").query("upsert",r({ue:f},o)).exec().then(function(){if(s)return void a(f);h(f)})},e.prototype.extend=function(e,t,n){if("hist"===t[0]){var r=t[1],i=t[2],o=t[3];switch(r){case"<":case">":this.$t(r,i,o,function(n){e(t,[n])});break;case"?":this.Zt(i,o,function(n){e(t,n)});break;case"rev":this.en(i,o,function(n){e(t,n)});break;case"clear":this.Xt(i,o,function(){e(t,n)})}}else e(t,n)},e.prototype.en=function(e,t,n){var r=this,s="_"+e+"__hist_idx";this.parent.table(s).query("select").where(["id","=",t]).exec().then(function(t){var s=t[0].histRows.filter(function(e){return-1!==e});r.parent.table("_"+e+"__hist_rows").query("select").where(["_id","IN",s]).exec().then(function(e){var r={};e.forEach(function(e){r[e[o[2]]]=Object.isFrozen(e)?i.t(e):e,delete r[e[o[2]]][o[2]]}),n([{pointer:t[0].histRows.length-t[0].histPtr-1,revisions:t[0].histRows.reverse().map(function(e){return-1===e?null:r[e]})}])})})},e.prototype.tn=function(e,t){var n=this;this.parent.extend("idx.length",e).then(function(r){n.parent.table(e+"_ptr").query("select").exec().then(function(e){if(!e.length)return void t([0,0]);t([r,r-e[0].ptr])})})},e.prototype.Zt=function(e,t,n){if(!this.historyModes)return void this.tn("_hist",function(e){n(e)});var r=this.Wt(e);if(r){if(!e)throw Error("Need a table to query this history!");this.tn(r,n)}else{if(!t)throw Error("Need a row primary key to query this history!");var i="_"+e+"__hist_idx";this.parent.table(i).query("select").where(["id","=",t]).exec().then(function(e){var t=e[0];n([t.histRows.length,t.histRows.length-t.histPtr-1])})}},e.prototype.nn=function(e,t,n){var r=this;this.parent.table(t+"_ptr").query("select").exec().then(function(o){var s=i.t(o[0]);s.ptr+="<"===e?1:-1,s.ptr<0&&(s.ptr=0),r.parent.extend("idx.length",t).then(function(a){if(s.ptr>a&&(s.ptr=a),o[0].ptr===s.ptr)return void n(!1);r.parent.table(t).query("select").range(-1,"<"===e?o[0].ptr:s.ptr).exec().then(function(o){r.parent.table(t+"_ptr").query("upsert",s).exec().then(function(){new i.ALL(o[0].keys.map(function(t){return function(n){r.rn(e,o[0].table,t,n)}})).then(function(e){n(e.indexOf(!0)>-1)})})})})})},e.prototype.rn=function(e,t,n,r){var o=this,s=function(e){o.parent.table("_"+t+"__hist_idx").query("upsert",e).where([o.Ht[t],"=",n]).exec().then(function(){r(!0)})};this.parent.table("_"+t+"__hist_idx").query("select").where([this.Ht[t],"=",n]).exec().then(function(a){var u=i.t(a[0]);if(u.histPtr+="<"===e?1:-1,u.histPtr<0&&(u.histPtr=0),u.histPtr>u.histRows.length-1&&(u.histPtr=u.histRows.length-1),u.histPtr===a[0].histPtr)return void r(!1);var c=u.histRows[u.histPtr];-1===c?o.parent.table(t).query("delete").comment("History Write").where([o.Ht[t],"=",n]).exec().then(function(){s(u)}):o.parent.table("_"+t+"__hist_rows").query("select").where(["_id","=",c]).exec().then(function(e){o.parent.table(t).query("upsert",e[0]).comment("History Write").exec().then(function(){s(u)})})})},e.prototype.$t=function(e,t,n,r){if(!this.historyModes)return void this.nn(e,"_hist",r);var i=this.Wt(t);if(i){if(!t)throw Error("Need a table to change this history!");this.nn(e,i,r)}else{if(!n)throw Error("Need a row primary key to change this history!");this.rn(e,t,n,r)}},e}();t.W=s}])}); \ No newline at end of file diff --git a/examples/nano-sql.min.js b/examples/nano-sql.min.js index 9e2f3696..bee6d99e 100644 --- a/examples/nano-sql.min.js +++ b/examples/nano-sql.min.js @@ -1 +1 @@ -!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=4)}([function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var r=n(1);t._assign=function(e){return e?JSON.parse(JSON.stringify(e)):null};var i=function(){function e(e){this.callbacks=e}return e.prototype.then=function(e){var t=this,n=[],i=0;this.callbacks&&this.callbacks.length||e([]);var o=function(){i0||s.indexOf("Trident/")>0||s.indexOf("Edge/")>0),t.isAndroid=/Android/.test(s),t.random16Bits=function(){if("undefined"==typeof crypto)return Math.round(Math.random()*Math.pow(2,16));if(crypto.getRandomValues){var e=new Uint16Array(1);return crypto.getRandomValues(e),e[0]}return"undefined"!==global&&global._crypto.randomBytes?global._crypto.randomBytes(2).reduce(function(e,t){return t*e}):Math.round(Math.random()*Math.pow(2,16))},t.timeid=function(e){for(var n=Math.round((new Date).getTime()/(e?1:1e3)).toString();n.length<(e?13:10);)n="0"+n;return n+"-"+(t.random16Bits()+t.random16Bits()).toString(16)},t.uuid=function(){var e,n,r="";return[r,r,r,r,r,r,r,r,r].reduce(function(i,o,s){for(e=t.random16Bits(),n=4===s?s:5===s?(e%16&3|8).toString(16):r,e=e.toString(16);e.length<4;)e="0"+e;return i+([3,4,5,6].indexOf(s)>-1?"-":r)+(n+e).slice(0,4)},r)},t.hash=function(e){return Math.abs(e.split("").reduce(function(t,n,r){return(t<<5)+t+e.charCodeAt(r)},0)).toString(16)},t.generateID=function(e,n){switch(e){case"int":return n||1;case"uuid":return t.uuid();case"timeId":return t.timeid();case"timeIdms":return t.timeid(!0)}return""},t.cleanArgs=function(e,n){for(var r={},i=e.length||-1;i--;){var o=e[i].split(":");o.length>1?r[o[0]]=t.cast(o[1],n[o[0]]||void 0):r[o[0]]=n[o[0]]||void 0}return r},t.isObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)},t.cast=function(e,n){var r={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="},i=typeof n;if("undefined"===i||null===n)return n;var o=function(e,n){switch(e){case"safestr":return o("string",n).replace(/[&<>"'`=\/]/gim,function(e){return r[e]});case"int":return"number"!==i||n%1!=0?parseInt(n||0):n;case"number":case"float":return"number"!==i?parseFloat(n||0):n;case"any[]":case"array":return Array.isArray(n)?n:[];case"uuid":case"timeId":case"timeIdms":case"string":return"string"!==i?String(n):n;case"object":case"obj":case"map":return t.isObject(n)?n:{};case"boolean":case"bool":return!0===n}return n},s=o(String(e||"").toLowerCase(),n);if(-1!==e.indexOf("[]")){var a=e.slice(0,e.lastIndexOf("[]"));return(n||[]).map(function(e){return t.cast(a,e)})}return void 0!==s?["int","float","number"].indexOf(e)>-1&&isNaN(s)?0:s:void 0},t.sortedInsert=function(e,n,r,i){return e.length?(e.splice(t.binarySearch(e,n),0,n),e):(e.push(n),e)},t.binarySearch=function(e,n,r,i){var o=e.length,s=r||0,a=void 0!==i?i:o-1;if(0===o)return 0;if(n>e[a])return a+1;if(n=a)return 0;var u=s+Math.floor((a-s)/2);return ne[u]?t.binarySearch(e,n,u+1,a):0},t.removeDuplicates=function(e){if(!e.length)return[];for(var t=[e[0]],n=1;n-1?[].concat.apply([],e.split(".").map(function(e){return e.match(/([^\[]+)|\[([^\]]+)\]\[/gim)||e})).map(function(e){return e.replace(/\[|\]/gim,"")}):e.split("."),n){var s=o.shift()+"."+o.shift();o.unshift(s)}return a[i]=o,r(o,0,t)}},function(e,t,n){"use strict";function r(e,n,r){t.setFast(function(){var t;try{t=n.apply(null,r)}catch(t){return m._reject(e,t)}return t===e?m._reject(e,new TypeError):m._resolve(e,t),null})}function i(e){var t=e&&e.then;return!e||"object"!=typeof e&&"function"!=typeof e||"function"!=typeof t?null:function(){t.apply(e,arguments)}}function o(e,t){function n(){for(var t=[],n=0;n=this.ai&&this.ai++,this._indexOf[String(e)]=this._sorted.length,this._sorted.push(e);else{var t=r.binarySearch(this._sorted,e);this._sorted.splice(t,0,e),this._indexOf[String(e)]=t;for(var n=t+1;n")&&(i=e.replace("ref=>",""))}),e.relationColumns[t].push(r.key),e.relations[t].push({column:r.key,toTable:r.type.replace("[]",""),toColumn:i,type:-1===r.type.indexOf("[]")?"single":"array",toType:i?Object.keys(e._models).reduce(function(t,n){return n===r.type.replace("[]","")?e._models[n].reduce(function(e,t){return t.key===i?-1!==t.type.indexOf("[]")?"array":"single":e},""):t},""):""})}}()}),new u.ALL(e._plugins.map(function(e){return function(t){e.didConnect?e.didConnect(i,function(){t()}):t()}})).then(n)})})},e.prototype.use=function(e){return this._plugins.push(e),this},e.prototype.on=function(e,t){var n=this,r=n.sTable,i=n._events.length,o=e.split(" ");if(Array.isArray(r))return this;for(n._callbacks[r]||(n._callbacks[r]=new a.ReallySmallEvents),i=o.length;i--;)-1!==n._events.indexOf(o[i])&&n._callbacks[r].on(o[i],t);return n._refreshEventChecker()},e.prototype.off=function(e,t){var n=this,r=e.split(" "),i=r.length,o=n.sTable;if(Array.isArray(o))return this;for(;i--;)-1!==n._events.indexOf(r[i])&&n._callbacks[o].off(r[i],t);return n._refreshEventChecker()},e.prototype._refreshEventChecker=function(){var e=this;return this._hasEvents={},Object.keys(this._models).concat(["*"]).forEach(function(t){e._hasEvents[t]=e._events.reduce(function(n,r){return n+(e._callbacks[t]&&e._callbacks[t].eventListeners[r]?e._callbacks[t].eventListeners[r].length:0)},0)>0}),this},e.prototype.model=function(e){var t=this,n=t.sTable;return Array.isArray(n)?this:(t._callbacks[n]||(t._callbacks[n]=new a.ReallySmallEvents),t._models[n]=e,t._views[n]=[],t._actions[n]=[],t)},e.prototype.views=function(e){return Array.isArray(this.sTable)?this:(this._views[this.sTable]=e,this)},e.prototype.getView=function(e,t){return void 0===t&&(t={}),Array.isArray(this.sTable)?new i.Promise(function(e,t){return t()}):this._doAV("View",this._views[this.sTable],e,t)},e.prototype.actions=function(e){return Array.isArray(this.sTable)?this:(this._actions[this.sTable]=e,this)},e.prototype.doAction=function(e,t){return Array.isArray(this.sTable)?new i.Promise(function(e,t){return t()}):this._doAV("Action",this._actions[this.sTable],e,t)},e.prototype._doAV=function(e,t,n,r){var o=this,s=t.reduce(function(e,t){return t.name===n?t:e},null);return s?(o._activeAV=n,s.call(s.args?u.cleanArgs(s.args,r):{},o)):new i.Promise(function(e,t){return t("Action/View Not Found!")})},e.prototype.query=function(e,t,n){var r=this,i=new o._NanoSQLQuery(r.sTable,r,e.toLowerCase(),t,r._activeAV,n);return r._activeAV=void 0,i},e.prototype.triggerEvent=function(e){var t=this;return i.setFast(function(){e.types.forEach(function(n){t._callbacks["*"].trigger(n,e,t),t._callbacks["*"].trigger("*",e,t),e.table&&t._callbacks[e.table]&&t._callbacks[e.table].trigger(n,e,t)})}),t},e.prototype.default=function(e){var t={},n=this;return Array.isArray(n.sTable)?{}:(n._models[n.sTable].forEach(function(n){t[n.key]=e&&e[n.key]?e[n.key]:n.default,void 0===t[n.key]&&(t[n.key]=u.cast(n.type,null))}),t)},e.prototype.doTransaction=function(e){var t=this,n=this,o=[],a=u.random16Bits().toString(16);return new i.Promise(function(i,c){if(!n._plugins.length)return void c("Nothing to do, no plugins!");new u.CHAIN(n._plugins.map(function(e){return function(t){e.transactionBegin?e.transactionBegin(a,t):t()}})).then(function(){Array.isArray(n.sTable)||e(function(e){var t=e||n.sTable;return{query:function(e,n){return new s._NanoSQLTransactionQuery(e,n,t,o,a)}}},function(){var e=[];new u.CHAIN(o.map(function(t){return function(i){e.push(t.table),n.table(t.table).query(t.action,t.actionArgs,!0).manualExec(r({},t,{transaction:!0,queryID:a,actionArgs:void 0})).then(i)}})).then(function(r){new u.CHAIN(t._plugins.map(function(e){return function(t){e.transactionEnd?e.transactionEnd(a,t):t()}})).then(function(){e.filter(function(e,t,n){return n.indexOf(e)===t}).forEach(function(e){0!==e.indexOf("_")&&n.triggerEvent({query:o[0],table:e,time:(new Date).getTime(),result:r,types:["transaction"],actionOrView:"",notes:[],transactionID:a,affectedRowPKS:[],affectedRows:[]})}),i(r)})})})})})},e.prototype.config=function(e){return this._config=e,this},e.prototype.extend=function(){for(var e=[],t=0;tr&&(r=u.objQuery(n,e))}),t(r)}else t(0)}},MIN:{type:"A",call:function(e,t,n){if(e.length){var r=u.objQuery(n,e[0])||0;e.forEach(function(e){var t=u.objQuery(n,e);t-1))throw Error("No valid database action!");var u=r||("select"===a||"delete"===a?[]:{});if("upsert"===a){var c={};this._db._models[this._db.sTable].forEach(function(e){void 0!==u[e.key]&&(c[e.key]=i.cast(e.type,u[e.key]))}),u=c}this._query.action=a,this._query.actionArgs=r?u:void 0}}return e.prototype.where=function(e){return this._query.where=e,this},e.prototype.range=function(e,t){return this._query.range=[e,t],this},e.prototype.orm=function(e){return this._query.orm=e,this},e.prototype.orderBy=function(e){return this._query.orderBy=e,this},e.prototype.groupBy=function(e){return this._query.groupBy=e,this},e.prototype.having=function(e){return e.length&&Array.isArray(e)||(this._error="Having condition requires an array!"),this._query.having=e,this},e.prototype.join=function(e){if(Array.isArray(this._query.table))throw Error("Can't JOIN with instance table!");return e.table&&e.type||(this._error="Join command requires table and type arguments!"),this._query.join=e,this},e.prototype.limit=function(e){return this._query.limit=e,this},e.prototype.trieSearch=function(e,t){return this._query.trie={column:e,search:t},this},e.prototype.ormSync=function(e){return this._query.ormSync=e||[],this},e.prototype.comment=function(e){return this._query.comments.push(e),this},e.prototype.extend=function(){for(var e=[],t=0;t-1?this._store._adapter.getIndex(r,"idx"!==t[0],function(n){e(t,n)}):e(t,[]);break;case"rebuild_idx":this._store.rebuildIndexes(t[1],function(n){e(t,[n])});break;default:e(t,n)}},e}();t.NanoSQLDefaultBackend=s},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n=!0),i.props&&(i.props.indexOf("idx")>-1||i.props.indexOf("trie")>-1)&&(r=!0,e["_"+t+"_idx_"+i.key]=[{key:"id",type:"string",props:["pk"]},{key:"rows",type:"any[]"}])}),r&&!n)throw new Error("Tables with secondary indexes must have a primary key!")}),e},e.prototype._newTable=function(e,t){this.tableInfo[e]={_pk:"",_pkType:"",_keys:[],_defaults:[],_secondaryIndexes:[],_trieColumns:[],_name:e},this._cache[e]={},this._trieIndexes[e]={},this._adapter.makeTable(e,t);for(var n=this.models[e].length;n--;){var r=this.models[e][n];this.tableInfo[e]._keys.unshift(r.key),this.tableInfo[e]._defaults[n]=r.default,r.props&&r.props.indexOf("pk")>-1&&(this.tableInfo[e]._pk=r.key,this.tableInfo[e]._pkType=r.type),r.props&&(r.props.indexOf("idx")>-1||r.props.indexOf("trie")>-1)&&this.tableInfo[e]._secondaryIndexes.push(r.key),r.props&&r.props.indexOf("trie")>=0&&(this.tableInfo[e]._trieColumns.push(r.key),this._trieIndexes[e][r.key]=new i.Trie([]))}return e},e}();t._NanoSQLStorage=c},function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n={END_WORD:"$",PERMS_MIN_LEN:2},r=function(){function e(t){this._trie=e._create(t)}return e.prototype.addWord=function(t){var n=function(t,n,r,i){return e._append(t,n,r,i)};return t.toLowerCase().split("").reduce(n,this._trie),this},e.prototype.removeWord=function(t){var r=e._checkPrefix(this._trie,t),i=r.prefixFound,o=r.prefixNode;return i&&delete o[n.END_WORD],this},e.prototype.getWords=function(){return e._recursePrefix(this._trie,"")},e.prototype.getPrefix=function(t){if(t=t.toLowerCase(),!this._isPrefix(t))return[];var n=e._checkPrefix(this._trie,t).prefixNode;return e._recursePrefix(n,t)},e.prototype._isPrefix=function(t){return e._checkPrefix(this._trie,t).prefixFound},e._append=function(e,t,r,i){return e[t]=e[t]||{},e=e[t],r===i.length-1&&(e[n.END_WORD]=1),e},e._checkPrefix=function(e,t){return{prefixFound:t.toLowerCase().split("").every(function(t,n){return!!e[t]&&(e=e[t])}),prefixNode:e}},e._create=function(t){return t.reduce(function(t,n){return n.toLowerCase().split("").reduce(e._append,t),t},{})},e._recursePrefix=function(t,r,i){void 0===i&&(i=[]);var o=r;for(var s in t)s===n.END_WORD&&(i.push(o),o=""),e._recursePrefix(t[s],r+s,i);return i.sort()},e}();t.Trie=r},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n._pkType[e]=t.type,n._pkKey[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n._dbIndex[e].doAI=!0),n._ls){var r=localStorage.getItem(n._id+"*"+e+"_idx");r&&n._dbIndex[e].set(JSON.parse(r))}})},e.prototype.write=function(e,t,n,i,s){if(!(t=t||o.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");if(-1===this._dbIndex[e].indexOf(t)&&(this._dbIndex[e].add(t),this._ls&&localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify(this._dbIndex[e].keys()))),this._ls){var a=r({},s?{}:JSON.parse(localStorage.getItem(this._id+"*"+e+"__"+t)||"{}"),n,(u={},u[this._pkKey[e]]=t,u));localStorage.setItem(this._id+"*"+e+"__"+t,JSON.stringify(a)),i(a)}else{var a=r({},s?{}:this._rows[e][t],n,(c={},c[this._pkKey[e]]=t,c));this._rows[e][t]=o.deepFreeze(a),i(a)}var u,c},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&(this._dbIndex[e].remove(t),this._ls&&localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify(this._dbIndex[e].keys()))),this._ls?localStorage.removeItem(this._id+"*"+e+"__"+t):delete this._rows[e][t],n()},e.prototype.read=function(e,t,n){if(this._ls){var r=localStorage.getItem(this._id+"*"+e+"__"+t);n(r?JSON.parse(r):void 0)}else n(this._rows[e][t])},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this._dbIndex[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[0,u.length-1];if(!u.length)return void n();s&&c&&(f=f.map(function(t){return a._dbIndex[e].getLocation(t)}));var h=f[0],d=0,_=function(){h++,d++,d>200?i.setFast(l):l()},l=function(){if(h<=f[1])if(a._ls){var r=localStorage.getItem(a._id+"*"+e+"__"+u[h]);t(r?JSON.parse(r):void 0,h,_)}else t(a._rows[e][u[h]],h,_);else n()};l()},e.prototype.drop=function(e,t){var n=this;this._ls?(localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify([])),this._dbIndex[e].keys().forEach(function(t){localStorage.removeItem(n._id+"*"+e+"__"+t)})):this._rows[e]={};var r=new s.DatabaseIndex;r.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=r,t()},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;new o.ALL(Object.keys(this._dbIndex).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();t._SyncStore=a},function(module,exports,__webpack_require__){var __assign=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n._pkType[e]=t.type,n._pkKey[e]=t.key,t.props&&t.props.indexOf("ai")>-1&&("int"===t.type||"number"===t.type)&&(n._dbIndex[e].doAI=!0))})},e.prototype.write=function(e,t,n,r,i){var o=this;if(!(t=t||utilities_1.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");-1===this._dbIndex[e].indexOf(t)&&this._dbIndex[e].add(t);var s=utilities_1.uuid(),a=__assign({},n,(c={},c[this._pkKey[e]]=t,c));this._waitingCBs["write_"+s]=function(e){r(a)};var u=function(t){a=__assign({},t,a),o._w.postMessage({do:"write",args:{table:e,id:s,row:a}})};i?u({}):this.read(e,t,function(e){u(e)});var c},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&this._dbIndex[e].remove(t);var r=utilities_1.uuid();this._waitingCBs["delete_"+r]=function(e){n()},this._w.postMessage({do:"delete",args:{table:e,id:r,pk:t}})},e.prototype.read=function(e,t,n){var r=utilities_1.uuid();if(-1===this._dbIndex[e].indexOf(t))return void n(null);this._waitingCBs["read_"+r]=function(e){n(e)},this._w.postMessage({do:"read",args:{table:e,id:r,pk:t}})},e.prototype.rangeRead=function(e,t,n,r,i,o){var s=this,a=this._dbIndex[e].keys(),u=-1===[typeof r,typeof i].indexOf("undefined"),c=u?[r,i]:[0,a.length-1];if(!a.length)return void n();var f=utilities_1.uuid(),h=[],d=c[0],_=0;this._waitingCBs["readRange_"+f+"_done"]=function(e){delete s._waitingCBs["readRange_"+f],h=e;var r=function(){d<=c[1]?t(h[_],d,function(){d++,_++,_>200?lie_ts_1.setFast(r):r()}):n()};r()},this._w.postMessage({do:"readRange",args:{table:e,id:f,range:o&&u?c:c.map(function(e){return a[e]})}})},e.prototype.drop=function(e,t){var n=new db_idx_1.DatabaseIndex;n.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=n;var r=utilities_1.uuid();this._waitingCBs["delete_"+r]=function(e){t()},this._w.postMessage({do:"delete",args:{table:e,id:r,pk:"_clear_"}})},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;new utilities_1.ALL(Object.keys(this._dbIndex).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();exports._IndexedDBStore=_IndexedDBStore},function(e,t){e.exports='function e(e){this.go=function(n){var t=0;e&&e.length||n([]),e.forEach(function(o,r){o(function(){++t===e.length&&n([])})})}}var n={db:null,store:function(e,t,o){var r=n.db.transaction(e,t);o(r,r.objectStore(e),function(e,n){return function(){postMessage({do:e,args:n})}})},init:function(){addEventListener("message",function(e){var t=e.data;n[t.do]&&n[t.do](t.args)},!1)},setup:function(t){var o=indexedDB.open(t.id,1),r=!1,a={};o.onupgradeneeded=function(e){r=!0,n.db=e.target.result,Object.keys(t.pkKeys).forEach(function(e){n.db.createObjectStore(e,{keyPath:t.pkKeys[e]}),a[e]=[]})},o.onsuccess=function(o){if(n.db=o.target.result,r)postMessage({do:"rdy",args:a});else{var s=function(e,t){var o=[];n.store(e,"readonly",function(e,n,r){n.openCursor().onsuccess=function(e){var n=e.target.result;n&&(o.push(n.key),n.continue())},e.oncomplete=function(){t(o)}})};new e(Object.keys(t.pkKeys).map(function(e){return function(n){s(e,function(t){a[e]=t,n()})}})).go(function(){postMessage({do:"rdy",args:a})})}}},write:function(e){n.store(e.table,"readwrite",function(n,t,o){t.put(e.row),n.oncomplete=o("write_"+e.id,null)})},read:function(e){n.store(e.table,"readonly",function(n,t,o){var r=t.get(e.pk);r.onsuccess=function(){postMessage({do:"read_"+e.id,args:r.result})}})},readRange:function(e){n.store(e.table,"readonly",function(n,t,o){var r=[],a=-1===e.range.indexOf(void 0)?t.openCursor(IDBKeyRange.bound(e.range[0],e.range[1])):t.openCursor();n.oncomplete=o("readRange_"+e.id+"_done",r),a.onsuccess=function(e){var n=e.target.result;n&&(r.push(n.value),n.continue())}})},delete:function(e){n.store(e.table,"readwrite",function(n,t,o){n.oncomplete=o("delete_"+e.id,!0),n.onerror=o("delete_"+e.id,!1),"_clear_"===e.pk?t.clear():t.delete(e.pk)})}};n.init();'},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n._pkType[e]=t.type,n._pkKey[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n._dbIndex[e].doAI=!0)})},e.prototype._sql=function(e,t,n,r){var i=function(e){e.executeSql(t,n,function(e,t){r(t)},function(e,r){return console.error(t,n,r),!1})};e?this._db.transaction(i):this._db.readTransaction(i)},e.prototype.write=function(e,t,n,i,s){var a=this;if(!(t=t||o.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");var u=!1;if(-1===this._dbIndex[e].indexOf(t)&&(u=!0,this._dbIndex[e].add(t)),u){var c=r({},n,(h={},h[this._pkKey[e]]=t,h));this._sql(!0,"INSERT into "+this._chkTable(e)+" (id, data) VALUES (?, ?)",[t,JSON.stringify(c)],function(e){i(c)})}else{var f=function(o){var s=r({},o,n,(u={},u[a._pkKey[e]]=t,u));a._sql(!0,"UPDATE "+a._chkTable(e)+" SET data = ? WHERE id = ?",[JSON.stringify(s),t],function(){i(s)});var u};s?f({}):this.read(e,t,function(e){f(e)})}var h},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&this._dbIndex[e].remove(t),this._sql(!0,"DELETE FROM "+this._chkTable(e)+" WHERE id = ?",[t],function(){n()})},e.prototype.read=function(e,t,n){this._sql(!1,"SELECT data FROM "+this._chkTable(e)+" WHERE id = ?",[t],function(e){n(e.rows.length?JSON.parse(e.rows.item(0).data):void 0)})},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this._dbIndex[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[];if(!u.length)return void n();s&&c&&(f=f.map(function(t){return a._dbIndex[e].getLocation(t)}));var h=f[0]||0,d=[],_=f[0],l="SELECT data from "+this._chkTable(e);if(f.length){for(var p="number"==typeof u[_];_<=f[1];)d.push(p?u[_]:'"'+u[_]+'"'),_++;l+=" WHERE id IN ("+d.join(", ")+")"}l+=" ORDER BY id",this._sql(!1,l,[],function(e){var r=0,o=function(){e.rows.length>r?t(JSON.parse(e.rows.item(r).data),h,function(){h++,r++,r>200?i.setFast(o):o()}):n()};o()})},e.prototype.drop=function(e,t){var n=new s.DatabaseIndex;n.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=n,this._sql(!0,"DELETE FROM "+this._chkTable(e),[],function(e){t()})},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;new o.ALL(Object.keys(this._dbIndex).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();t._WebSQLStore=a},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n=t&&n.q.range[1]<=t}):e)})}},e.prototype._groupByKey=function(e,t){return e.reduce(function(e,n){return-1!==n.indexOf(".length")?e+"."+String((t[n.replace(".length","")]||[]).length):e+"."+String(t[n])},"").slice(1)},e.prototype._groupBy=function(e){var t=this,n=this.q.groupBy||{},r=e.sort(function(e,r){return t._sortObj(e,r,n,!0)});return r.forEach(function(e,r){var i=Object.keys(n).map(function(t){return String(e[t])||""}).join(".");t._sortGroups||(t._sortGroups={}),t._sortGroups[i]||(t._sortGroups[i]=[]),t._sortGroups[i].push(r)}),r},e.prototype._having=function(e){var t=this;return e.filter(function(e,n){return Array.isArray(t.q.having)?f(e,t.q.having||[],n,!0):t.q.having(e,n)})},e.prototype._orderBy=function(e){var t=this;return e.sort(function(e,n){return t._sortObj(e,n,t.q.orderBy||{},!1)})},e.prototype._offset=function(e){var t=this;return e.filter(function(e,n){return!t.q.offset||n>=t.q.offset})},e.prototype._limit=function(e){var t=this;return e.filter(function(e,n){return!t.q.limit||n-1,n.type.replace("[]","")):e},""),n._ormTableCache[o]=[s,i]),s){var a=n.s.tableInfo[s]._pk,u=[a,i?"IN":"=",e[t.key]],c=n.s._nsql.table(s).query("select",t.select);t.where?Array.isArray(t.where)?c.where("string"==typeof t.where[0]?[u,"AND",t.where]:t.where.concat(["AND",u])):c.where(function(n,r){return(i?-1!==e[t.key].indexOf(n[a]):e[t.key]===n[a])&&t.where(n,r)}):c.where(u),void 0!==t.limit&&c.limit(t.limit),void 0!==t.offset&&c.offset(t.offset),t.orderBy&&c.orderBy(t.orderBy),c.exec().then(function(n){n.filter(function(e){return e}).length?e[t.key]=i?n.filter(function(e){return e}):n[0]:e[t.key]=i?[]:void 0,r()})}else r()}})).then(function(){t(e)})}})).then(t)},e.prototype._doJoin=function(e,t,n,r,i){var o="right",s="outer",a=this,u=a.s.tableInfo[e===o?n:t],c=a.s.tableInfo[e===o?t:n],h=function(e,t){return[u,c].reduce(function(n,r,i){return r._keys.forEach(function(o){n[r._name+"."+o]=((0===i?e:t)||{})[o]}),n},{})},d=[],_=r&&r._right?r._right.split(".").pop()||"":"",l=[];a.s._read(u._name,function(t,n,i){var p=!1;a.s._read(c._name,function(n,i,a){if(r&&"cross"!==e){f((y={},y[u._name]=t,y[c._name]=n,y),[r._left,r._check,e===o?t[_]:n[_]],0)&&(e===s&&l.push(i),d.push(h(t,n)),p=!0)}else d.push(h(t,n)),p=!0;a(!1);var y},function(){!p&&["left",o,s].indexOf(e)>-1&&d.push(h(t,null)),i(!1)})},function(){e===s?a.s._read(c._name,function(e,t,n){-1===l.indexOf(t)&&d.push(h(null,e)),n(!1)},function(){i(d)}):i(d)})},e.prototype._sortObj=function(e,t,n,r){return Object.keys(n).reduce(function(i,s){var a=r?o.objQuery(s,e):e[s],u=r?o.objQuery(s,t):t[s];return i||(a===u?0:(a>u?1:-1)*("desc"===n[s]?-1:1))},0)},e.prototype._mutateRows=function(e,t){var n=this,r=this.q.actionArgs,s={},a={};if(r&&r.length){var u=!1,c={};r.forEach(function(e){if(-1!==e.indexOf("(")){var t=(e.match(/^.*\(/g)||[""])[0].replace(/\(|\)/g,"").toUpperCase(),n=i.NanoSQLInstance.functions[t],r=1===e.split(" AS ").length?t:(e.split(" AS ").pop()||"").trim();if(!n)throw new Error("'"+t+"' is not a valid function!");"A"===n.type&&(u=!0),c[e]={fn:n,key:r}}}),new o.ALL(r.map(function(t){return function(r){if(t.indexOf("(")>-1){var i=(t.match(/\(.*\)/g)||[""])[0].replace(/\(|\)/g,"").split(",").map(function(e){return e.trim()});n._sortGroups&&u?new o.ALL(Object.keys(n._sortGroups).map(function(r){return a[r]||(a[r]={}),function(o){(s=c[t].fn).call.apply(s,[e.filter(function(e,t){return n._sortGroups[r].indexOf(t)>-1}),function(e){a[r][c[t].key]=e,o()}].concat(i));var s}})).then(r):(f=c[t].fn).call.apply(f,[e,function(e){s[c[t].key]=e,r()}].concat(i))}else r();var f}})).then(function(){var i=function(e,t,i){var s={};return r.forEach(function(r){var a=r.indexOf("(")>-1,u=a?c[r].fn.type:"";if(r.indexOf(" AS ")>-1){var f=r.split(" AS "),h=a?c[r].key:f[0].trim();s[f[1]]=a?"A"===u?i[h]:i[h][t]:o.objQuery(h,e,void 0!==n.q.join)}else{var h=a?c[r].key:r;s[r]=a?"A"===u?i[h]:i[h][t]:o.objQuery(h,e,void 0!==n.q.join)}}),s};if(n._sortGroups&&u){var f=[];Object.keys(n._sortGroups).forEach(function(t){var r=e.filter(function(e,r){return n._sortGroups[t].indexOf(r)>-1}).filter(function(e,t){return t<1});r&&r.length&&f.push(i(r[0],0,a[t]))}),t(f)}else t(u?e.filter(function(e,t){return t<1}).map(function(e,t){return i(e,t,s)}):e.map(function(e,t){return i(e,t,s)}))})}else t(e)},e.prototype._executeQueryArguments=function(e,t){var n=this,r=function(){n.q.having&&(e=n._having(e)),n.q.orderBy&&(e=n._orderBy(e)),n.q.offset&&(e=n._offset(e)),n.q.limit&&(e=n._limit(e)),t(e)},i=function(){n.q.actionArgs&&n.q.actionArgs.length?n._mutateRows(e,function(t){e=t,r()}):r()},o=function(){n.q.groupBy&&(e=n._groupBy(e)),n.q.orm?n._orm(e,function(t){e=t,i()}):i()};this.q.join?this._join(e,function(t){e=t,o()}):o()},e}();t._MutateSelection=a;var u=function(){function e(e,t){this.q=e,this.s=t}return e.prototype.getRows=function(e){var t=this;if(this.q.join)return void e([]);if(this.q.join&&this.q.orm)throw new Error("Cannot do a JOIN and ORM command at the same time!");if([this.q.where,this.q.range,this.q.trie].filter(function(e){return e}).length>1)throw new Error("Can only have ONE of Trie, Range or Where!");if(this.q.trie&&this.q.trie.column&&this.q.trie.search)return void this._selectByTrie(e);if(this.q.range&&this.q.range.length)return void this._selectByRange(e);if(!this.q.where||!this.q.where.length)return void this._fullTableScan(e);if(!Array.isArray(this.q.where))return void this._fullTableScan(function(n){e(n.filter(t.q.where))});if("string"==typeof this.q.where[0]?0===this._isOptimizedWhere(this.q.where):0===(this.q.where||[]).reduce(function(e,n,r){return r%2==1?e:e+t._isOptimizedWhere(n)},0))return void this._selectByKeys(e);this._fullTableScan(e)},e.prototype._selectByKeys=function(e){var t=this;if(this.q.where&&"string"==typeof this.q.where[0])this._selectRowsByIndex(this.q.where,e);else if(this.q.where){var n=[],r="";new o.CHAIN(this.q.where.map(function(e){return function(i){if("OR"===e||"AND"===e)return r=e,void i();t._selectRowsByIndex(e,function(e){if("AND"===r){var o=e.map(function(e){return e[t.s.tableInfo[t.q.table]._pk]});n=n.filter(function(e){return-1!==o.indexOf(e[t.s.tableInfo[t.q.table]._pk])})}else n.concat(e);i()})}})).then(function(){e(n)})}},e.prototype._selectRowsByIndex=function(e,t){var n=this;if("BETWEEN"!==e[1]){var r=[];switch(e[1]){case"IN":r=e[2];break;case"=":r=[e[2]]}e[0]===this.s.tableInfo[this.q.table]._pk?this.s._read(this.q.table,r,t):new o.ALL(r.map(function(t){return function(r){n.s._secondaryIndexRead(n.q.table,e[0],t,r)}})).then(function(e){t([].concat.apply([],e))})}else{var i=e[0]===this.s.tableInfo[this.q.table]._pk?"":e[0];if(i){var s="_"+this.q.table+"_idx_"+i;this.s._rangeReadPKs(s,e[2][0],e[2][1],function(e){var r=[].concat.apply([],e);n.s._read(n.q.table,r,t)})}else this.s._rangeReadPKs(this.q.table,e[2][0],e[2][1],function(e){t(e)})}},e.prototype._selectByRange=function(e){var t=this;if(this.q.range){var n=this.q.range;this.s._adapter.getIndex(this.q.table,!0,function(r){for(var i=n[0]>0?n[1]:r+n[0]-n[1],o=i,s=Math.abs(n[0])-1;s--;)o++;t.s._rangeReadIDX(t.q.table,i,o,e)})}else e([])},e.prototype._selectByTrie=function(e){this.q.trie?this.s._trieRead(this.q.table,this.q.trie.column,this.q.trie.search,e):e([])},e.prototype._fullTableScan=function(e){var t=this;this.s._read(this.q.table,function(e,n,r){r(!t.q.where||(Array.isArray(t.q.where)?f(e,t.q.where||[],n||0):t.q.where(e,n)))},e)},e.prototype._isOptimizedWhere=function(e){var t=this.s.tableInfo[this.q.table];return["=","IN","BETWEEN"].indexOf(e[1])>-1&&(e[0]===t._pk||t._secondaryIndexes.indexOf(e[0])>-1)?0:1},e}();t._RowSelection=u;var c=function(){function e(e){this.q=e}return e.prototype.getRows=function(e){var t=this;if(this.q.join||this.q.orm||this.q.trie)throw new Error("Cannot do a JOIN, ORM or TRIE command with instance table!");if(this.q.range&&this.q.range.length){var n,r,i=this.q.range;n=i[0]<0?this.q.table.length+i[0]-i[1]:i[1];var o=Math.abs(i[0])-1;for(r=n;o--;)r++;return void e(this.q.table.filter(function(e,t){return t>=n&&t<=r}))}e(this.q.table.filter(function(e,n){return!t.q.where||(Array.isArray(t.q.where)?f(e,t.q.where||[],n):t.q.where(e,n))}))},e}();t.InstanceSelection=c;var f=function(e,t,n,r){var i=["AND","OR"];if("string"!=typeof t[0]){var s=!1,a=t.map(function(t,a){return-1!==i.indexOf(t)?("AND"===t&&(s=!0),t):0===h(t[2],t[1],"_IDX_"===t[0]?n:o.objQuery(t[0],e,r))});if(a.forEach(function(e,t){"OR"===e&&(a[t]=a[t-1]||a[t+1],a[t-1]=void 0,a[t+1]=void 0)}),a=a.filter(function(e){return void 0!==e}),s){var u,c=!1;return-1===a.reduce(function(e,t,n){return 0===n?(e.push(t),u=e.length-1,e):"AND"===t?(c=!0,e.push(t),e):c?(e.push(t),u=e.length-1,c=!1,e):(void 0!==u&&(e[u]=t||e[u]),e)},[]).filter(function(e){return void 0!==e}).indexOf(!1)}return-1!==a.indexOf(!0)}return 0===h(t[2],t[1],"_IDX_"===t[0]?n:o.objQuery(t[0],e,r))},h=function(e,t,n){var r=function(e){return["LIKE","NOT LIKE"].indexOf(t)>0?String(e||"").toLowerCase():e},i=r(n),o=r(e);if("NULL"===e||"NOT NULL"===e){var s="="===t||"LIKE"===t;return("NULL"===e?null===n||void 0===n:null!==n&&void 0!==n)?s?0:1:s?1:0}switch(t){case"=":return i===o?0:1;case"!=":return i!==o?0:1;case">":return i>o?0:1;case"<":return i=":return i>=o?0:1;case"IN":return(o||[]).indexOf(i)<0?1:0;case"NOT IN":return(o||[]).indexOf(i)<0?0:1;case"REGEX":return i.search(o)<0?1:0;case"LIKE":return i.indexOf(o)<0?1:0;case"NOT LIKE":return i.indexOf(o)>0?1:0;case"BETWEEN":return o[0]<=i&&o[1]>=i?0:1;case"HAVE":return(i||[]).indexOf(o)<0?1:0;case"NOT HAVE":return(i||[]).indexOf(o)<0?0:1;case"INTERSECT":return(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length>0?0:1;case"NOT INTERSECT":return 0===(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length?0:1;default:return 1}}},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n0){var a=r.parent.table(e).query("select");n||a.range(-1*s.ptr,0),a.exec().then(function(o){if(!o.length)return void t();var a={};o.forEach(function(e){a[e.table]||(a[e.table]=[]),a[e.table]=a[e.table].concat(e.keys)}),new i.ALL(Object.keys(a).map(function(e){return function(t){r._purgeRowHistory(e,a[e],t,n)}})).then(function(){r.parent.table(e).query("delete").comment("History Purge").where(["id","IN",o.map(function(e){return e.id})]).exec().then(function(){s.ptr=0,r.parent.table(e+"_ptr").query("upsert",s).comment("History Purge").where(["id","=",s.id]).exec().then(t)})})})}else t()})},e.prototype._purgeParentHistory=function(e,t,n){if(!this.historyModes)return void this._purgeTableHistory("_hist",n);var r=this._histTable(e);r?this._purgeTableHistory(r,n):this._purgeRowHistory(e,t,n)},e.prototype._purgeAllHistory=function(e,t,n){if(!this.historyModes)return void this._purgeTableHistory("_hist",n,!0);var r=this._histTable(e);r?this._purgeTableHistory(r,n,!0):this._purgeRowHistory(e,[t],n,!0)},e.prototype.didExec=function(e,t){var n=this;e.table&&0!==e.table.indexOf("_")&&e.types.indexOf("change")>-1&&-1===e.query.comments.indexOf("History Write")?this._purgeParentHistory(e.table,e.affectedRowPKS,function(){new i.ALL(e.affectedRows.map(function(t){return function(r){var i=t[n._tablePkKeys[e.table]];n._tableKeys[e.table][i]?n._unshiftSingleRow(e.table,e.types,i,t,!1,function(e){r(i)}):(n._tableKeys[e.table][i]=!0,n._unshiftSingleRow(e.table,e.types,i,t,!0,function(t){n.parent.table("_"+e.table+"__hist_idx").query("upsert",{id:i,histRows:[t,-1],histPtr:0}).exec().then(function(){r(i)})}))}})).then(function(r){n._unshiftParent(e,r,t)})}):t(e)},e.prototype._unshiftParent=function(e,t,n){var r=this._histTable(e.table);r?this.parent.table(r).query("upsert",{id:i.timeid(!0),table:e.table,keys:t}).exec().then(function(){n(e)}):n(e)},e.prototype._unshiftSingleRow=function(e,t,n,o,s,a){var u=this,c="_"+e+"__hist_idx",f=i.timeid(!0),h=function(e){u.parent.table(c).query("select").where(["id","=",n]).exec().then(function(t){var r=Object.isFrozen(t[0])?i._assign(t[0]):t[0];r.histRows.unshift(e),u.parent.table(c).query("upsert",r).where(["id","=",n]).exec().then(function(){a(e)})})};t.indexOf("delete")>-1||t.indexOf("drop")>-1?h(-1):this.parent.table("_"+e+"__hist_rows").query("upsert",r({_id:f},o)).exec().then(function(){if(s)return void a(f);h(f)})},e.prototype.extend=function(e,t,n){if("hist"===t[0]){var r=t[1],i=t[2],o=t[3];switch(r){case"<":case">":this._shiftHistory(r,i,o,function(n){e(t,[n])});break;case"?":this._queryHistory(i,o,function(n){e(t,n)});break;case"rev":this._getRevisionHistory(i,o,function(n){e(t,n)});break;case"clear":this._purgeAllHistory(i,o,function(){e(t,n)})}}else e(t,n)},e.prototype._getRevisionHistory=function(e,t,n){var r=this,o="_"+e+"__hist_idx";this.parent.table(o).query("select").where(["id","=",t]).exec().then(function(t){var o=t[0].histRows.filter(function(e){return-1!==e});r.parent.table("_"+e+"__hist_rows").query("select").where(["_id","IN",o]).exec().then(function(e){var r={};e.forEach(function(e){r[e._id]=Object.isFrozen(e)?i._assign(e):e,delete r[e._id]._id}),n([{pointer:t[0].histRows.length-t[0].histPtr-1,revisions:t[0].histRows.reverse().map(function(e){return-1===e?null:r[e]})}])})})},e.prototype._getTableHistory=function(e,t){var n=this;this.parent.extend("idx.length",e).then(function(r){n.parent.table(e+"_ptr").query("select").exec().then(function(e){if(!e.length)return void t([0,0]);t([r,r-e[0].ptr])})})},e.prototype._queryHistory=function(e,t,n){if(!this.historyModes)return void this._getTableHistory("_hist",function(e){n(e)});var r=this._histTable(e);if(r){if(!e)throw Error("Need a table to query this history!");this._getTableHistory(r,n)}else{if(!t)throw Error("Need a row primary key to query this history!");var i="_"+e+"__hist_idx";this.parent.table(i).query("select").where(["id","=",t]).exec().then(function(e){var t=e[0];n([t.histRows.length,t.histRows.length-t.histPtr-1])})}},e.prototype._shiftTableHistory=function(e,t,n){var r=this;this.parent.table(t+"_ptr").query("select").exec().then(function(o){var s=i._assign(o[0]);s.ptr+="<"===e?1:-1,s.ptr<0&&(s.ptr=0),r.parent.extend("idx.length",t).then(function(a){if(s.ptr>a&&(s.ptr=a),o[0].ptr===s.ptr)return void n(!1);r.parent.table(t).query("select").range(-1,"<"===e?o[0].ptr:s.ptr).exec().then(function(o){r.parent.table(t+"_ptr").query("upsert",s).exec().then(function(){new i.ALL(o[0].keys.map(function(t){return function(n){r._shiftRowHistory(e,o[0].table,t,n)}})).then(function(e){n(e.indexOf(!0)>-1)})})})})})},e.prototype._shiftRowHistory=function(e,t,n,r){var o=this,s=function(e){o.parent.table("_"+t+"__hist_idx").query("upsert",e).where([o._tablePkKeys[t],"=",n]).exec().then(function(){r(!0)})};this.parent.table("_"+t+"__hist_idx").query("select").where([this._tablePkKeys[t],"=",n]).exec().then(function(a){var u=i._assign(a[0]);if(u.histPtr+="<"===e?1:-1,u.histPtr<0&&(u.histPtr=0),u.histPtr>u.histRows.length-1&&(u.histPtr=u.histRows.length-1),u.histPtr===a[0].histPtr)return void r(!1);var c=u.histRows[u.histPtr];-1===c?o.parent.table(t).query("delete").comment("History Write").where([o._tablePkKeys[t],"=",n]).exec().then(function(){s(u)}):o.parent.table("_"+t+"__hist_rows").query("select").where(["_id","=",c]).exec().then(function(e){o.parent.table(t).query("upsert",e[0]).comment("History Write").exec().then(function(){s(u)})})})},e.prototype._shiftHistory=function(e,t,n,r){if(!this.historyModes)return void this._shiftTableHistory(e,"_hist",r);var i=this._histTable(t);if(i){if(!t)throw Error("Need a table to change this history!");this._shiftTableHistory(e,i,r)}else{if(!n)throw Error("Need a row primary key to change this history!");this._shiftRowHistory(e,t,n,r)}},e}();t._NanoSQLHistoryPlugin=s}])}); \ No newline at end of file +!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.e?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=4)}([function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var r=n(1);t.t=function(e){return e?JSON.parse(JSON.stringify(e)):null};var i=function(){function e(e){this.callbacks=e}return e.prototype.then=function(e){var t=this,n=[],i=0;this.callbacks&&this.callbacks.length||e([]);var o=function(){i0||s.indexOf("Trident/")>0||s.indexOf("Edge/")>0),t.isAndroid=/Android/.test(s),t.random16Bits=function(){if("undefined"==typeof crypto)return Math.round(Math.random()*Math.pow(2,16));if(crypto.getRandomValues){var e=new Uint16Array(1);return crypto.getRandomValues(e),e[0]}return"undefined"!==global&&global.r.randomBytes?global.r.randomBytes(2).reduce(function(e,t){return t*e}):Math.round(Math.random()*Math.pow(2,16))},t.timeid=function(e){for(var n=Math.round((new Date).getTime()/(e?1:1e3)).toString();n.length<(e?13:10);)n="0"+n;return n+"-"+(t.random16Bits()+t.random16Bits()).toString(16)},t.uuid=function(){var e,n,r="";return[r,r,r,r,r,r,r,r,r].reduce(function(i,o,s){for(e=t.random16Bits(),n=4===s?s:5===s?(e%16&3|8).toString(16):r,e=e.toString(16);e.length<4;)e="0"+e;return i+([3,4,5,6].indexOf(s)>-1?"-":r)+(n+e).slice(0,4)},r)},t.hash=function(e){return Math.abs(e.split("").reduce(function(t,n,r){return(t<<5)+t+e.charCodeAt(r)},0)).toString(16)},t.generateID=function(e,n){switch(e){case"int":return n||1;case"uuid":return t.uuid();case"timeId":return t.timeid();case"timeIdms":return t.timeid(!0)}return""},t.cleanArgs=function(e,n){for(var r={},i=e.length||-1;i--;){var o=e[i].split(":");o.length>1?r[o[0]]=t.cast(o[1],n[o[0]]||void 0):r[o[0]]=n[o[0]]||void 0}return r},t.isObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)},t.cast=function(e,n){var r={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="},i=typeof n;if("undefined"===i||null===n)return n;var o=function(e,n){switch(e){case"safestr":return o("string",n).replace(/[&<>"'`=\/]/gim,function(e){return r[e]});case"int":return"number"!==i||n%1!=0?parseInt(n||0):n;case"number":case"float":return"number"!==i?parseFloat(n||0):n;case"any[]":case"array":return Array.isArray(n)?n:[];case"uuid":case"timeId":case"timeIdms":case"string":return"string"!==i?String(n):n;case"object":case"obj":case"map":return t.isObject(n)?n:{};case"boolean":case"bool":return!0===n}return n},s=o(String(e||"").toLowerCase(),n);if(-1!==e.indexOf("[]")){var a=e.slice(0,e.lastIndexOf("[]"));return(n||[]).map(function(e){return t.cast(a,e)})}return void 0!==s?["int","float","number"].indexOf(e)>-1&&isNaN(s)?0:s:void 0},t.sortedInsert=function(e,n,r,i){return e.length?(e.splice(t.binarySearch(e,n),0,n),e):(e.push(n),e)},t.binarySearch=function(e,n,r,i){var o=e.length,s=r||0,a=void 0!==i?i:o-1;if(0===o)return 0;if(n>e[a])return a+1;if(n=a)return 0;var u=s+Math.floor((a-s)/2);return ne[u]?t.binarySearch(e,n,u+1,a):0},t.removeDuplicates=function(e){if(!e.length)return[];for(var t=[e[0]],n=1;n-1?[].concat.apply([],e.split(".").map(function(e){return e.match(/([^\[]+)|\[([^\]]+)\]\[/gim)||e})).map(function(e){return e.replace(/\[|\]/gim,"")}):e.split("."),n){var s=o.shift()+"."+o.shift();o.unshift(s)}return a[i]=o,r(o,0,t)}},function(e,t,n){"use strict";function r(e,n,r){t.setFast(function(){var t;try{t=n.apply(null,r)}catch(t){return m.a(e,t)}return t===e?m.a(e,new TypeError):m.u(e,t),null})}function i(e){var t=e&&e.then;return!e||"object"!=typeof e&&"function"!=typeof e||"function"!=typeof t?null:function(){t.apply(e,arguments)}}function o(e,t){function n(){for(var t=[],n=0;n=this.ai&&this.ai++,this.T[String(e)]=this.j.length,this.j.push(e);else{var t=r.binarySearch(this.j,e);this.j.splice(t,0,e),this.T[String(e)]=t;for(var n=t+1;n0}),this},e.prototype.model=function(e){var t=this,n=t.sTable;return Array.isArray(n)?this:(t.Q[n]||(t.Q[n]=new a.ReallySmallEvents),t.N[n]=e,t.P[n]=[],t.L[n]=[],t)},e.prototype.views=function(e){return Array.isArray(this.sTable)?this:(this.P[this.sTable]=e,this)},e.prototype.getView=function(e,t){return void 0===t&&(t={}),Array.isArray(this.sTable)?new i.v(function(e,t){return t()}):this.V("View",this.P[this.sTable],e,t)},e.prototype.actions=function(e){return Array.isArray(this.sTable)?this:(this.L[this.sTable]=e,this)},e.prototype.doAction=function(e,t){return Array.isArray(this.sTable)?new i.v(function(e,t){return t()}):this.V("Action",this.L[this.sTable],e,t)},e.prototype.V=function(e,t,n,r){var o=this,s=t.reduce(function(e,t){return t.name===n?t:e},null);return s?(o.U=n,s.call(s.args?u.cleanArgs(s.args,r):{},o)):new i.v(function(e,t){return t("Action/View Not Found!")})},e.prototype.query=function(e,t,n){var r=this,i=new o.z(r.sTable,r,e.toLowerCase(),t,r.U,n);return r.U=void 0,i},e.prototype.triggerEvent=function(e){var t=this;return i.setFast(function(){e.types.forEach(function(n){t.Q["*"].trigger(n,e,t),t.Q["*"].trigger("*",e,t),e.table&&t.Q[e.table]&&t.Q[e.table].trigger(n,e,t)})}),t},e.prototype.default=function(e){var t={},n=this;return Array.isArray(n.sTable)?{}:(n.N[n.sTable].forEach(function(n){t[n.key]=e&&e[n.key]?e[n.key]:n.default,void 0===t[n.key]&&(t[n.key]=u.cast(n.type,null))}),t)},e.prototype.doTransaction=function(e){var t=this,n=this,o=[],a=u.random16Bits().toString(16);return new i.v(function(i,c){if(!n.D.length)return void c("Nothing to do, no plugins!");new u.CHAIN(n.D.map(function(e){return function(t){e.transactionBegin?e.transactionBegin(a,t):t()}})).then(function(){Array.isArray(n.sTable)||e(function(e){var t=e||n.sTable;return{query:function(e,n){return new s.G(e,n,t,o,a)}}},function(){var e=[];new u.CHAIN(o.map(function(t){return function(i){e.push(t.table),n.table(t.table).query(t.action,t.actionArgs,!0).manualExec(r({},t,{transaction:!0,queryID:a,actionArgs:void 0})).then(i)}})).then(function(r){new u.CHAIN(t.D.map(function(e){return function(t){e.transactionEnd?e.transactionEnd(a,t):t()}})).then(function(){e.filter(function(e,t,n){return n.indexOf(e)===t}).forEach(function(e){0!==e.indexOf("_")&&n.triggerEvent({query:o[0],table:e,time:(new Date).getTime(),result:r,types:["transaction"],actionOrView:"",notes:[],transactionID:a,affectedRowPKS:[],affectedRows:[]})}),i(r)})})})})})},e.prototype.config=function(e){return this.K=e,this},e.prototype.extend=function(){for(var e=[],t=0;tr&&(r=u.objQuery(n,e))}),t(r)}else t(0)}},MIN:{type:"A",call:function(e,t,n){if(e.length){var r=u.objQuery(n,e[0])||0;e.forEach(function(e){var t=u.objQuery(n,e);t-1))throw Error("No valid database action!");var u=r||("select"===a||"delete"===a?[]:{});if("upsert"===a){var c={};this.X.N[this.X.sTable].forEach(function(e){void 0!==u[e.key]&&(c[e.key]=i.cast(e.type,u[e.key]))}),u=c}this.$.action=a,this.$.actionArgs=r?u:void 0}}return e.prototype.where=function(e){return this.$.where=e,this},e.prototype.range=function(e,t){return this.$.range=[e,t],this},e.prototype.orm=function(e){return this.$.orm=e,this},e.prototype.orderBy=function(e){return this.$.orderBy=e,this},e.prototype.groupBy=function(e){return this.$.groupBy=e,this},e.prototype.having=function(e){return e.length&&Array.isArray(e)||(this.Z="Having condition requires an array!"),this.$.having=e,this},e.prototype.join=function(e){if(Array.isArray(this.$.table))throw Error("Can't JOIN with instance table!");return e.table&&e.type||(this.Z="Join command requires table and type arguments!"),this.$.join=e,this},e.prototype.limit=function(e){return this.$.limit=e,this},e.prototype.trieSearch=function(e,t){return this.$.trie={column:e,search:t},this},e.prototype.comment=function(e){return this.$.comments.push(e),this},e.prototype.extend=function(){for(var e=[],t=0;t-1?this.te.ie.getIndex(i,"idx"!==t[0],function(n){e(t,n)}):e(t,[]);break;case"rebuild_idx":t[1]?this.te.rebuildIndexes(t[1],function(n){e(t,[n])}):new s.ALL(Object.keys(this.te.tableInfo).map(function(e){return function(t){r.te.rebuildIndexes(e,t)}})).then(function(n){e(t,n)});break;case"clear_cache":t[1]?this.te.oe[t[1]]={}:Object.keys(this.te.tableInfo).forEach(function(e){r.te.oe[e]={}}),e(t,t[1]||Object.keys(this.te.tableInfo));break;default:e(t,n)}},e}();t.NanoSQLDefaultBackend=a},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n")&&(i=e.replace("ref=>",""))}),i&&(n.we[e].push(r.key),n.ve[e][r.key]={me:r.type.replace("[]",""),xe:i.replace("[]",""),qe:-1===i.indexOf("[]")?"single":"array",ke:-1===r.type.indexOf("[]")?"single":"array"})}}()}),Object.keys(this.ve).forEach(function(e){Object.keys(n.ve[e]).forEach(function(t){var r=n.ve[e][t];n.ge[r.me].push({Oe:r.xe,ke:r.qe,Ie:e,Se:t,Ae:r.ke})})}),this.ie.connect(function(){new o.ALL(Object.keys(n.fe).map(function(e){return function(t){var r=n.fe[e];Object.keys(r).length?n.je(e,function(t,i,o){if(!t)return void o(!1);Object.keys(r).forEach(function(r){void 0!==t[r]&&n.fe[e][r].addWord(String(t[r]))}),o(!1)},t):t()}})).then(function(){t(n.models)})})},e.prototype.rebuildIndexes=function(e,t){var n=this,r=(new Date).getTime();new o.ALL(Object.keys(this.tableInfo).map(function(t){return function(r){if("_ALL_"!==e&&e!==t||0===t.indexOf("_"))return void r();var i=n.tableInfo[t].Te;new o.ALL(i.map(function(e){return function(r){var i="_"+t+"_idx_"+e,o=n.tableInfo[t].Ee;n.Re(i,function(){n.je(t,function(e,r,i){n.Le(t,e[o],e,[],function(){i(!1)})},r)})}})).then(r)}})).then(function(){t((new Date).getTime()-r)})},e.prototype.Pe=function(e){return o.isObject(e)||Array.isArray(e)?JSON.stringify(e).substr(0,12):"number"==typeof e?e:String(e).substr(0,32)},e.prototype._e=function(){if("undefined"==typeof window)return"LVL";if(o.isSafari)return"WSQL";if(o.isMSBrowser)return"undefined"!=typeof indexedDB?"IDB":"LS";if(-1===[typeof Worker,typeof Blob,typeof indexedDB].indexOf("undefined")&&window.URL&&window.URL.createObjectURL)try{var e=new Worker(window.URL.createObjectURL(new Blob(["var t = 't';"])));return e.postMessage(""),e.terminate(),indexedDB.open("1234",1),indexedDB.deleteDatabase("1234"),"IDB_WW"}catch(e){if("undefined"!=typeof indexedDB)return"IDB"}return"LS"},e.prototype.Ne=function(e,t,n,r){var i=this;this.ie.read("_"+e+"_idx_"+t,this.Pe(n),function(t){void 0!==t?i.je(e,t.rows||[],r):r([])})},e.prototype.Ce=function(e,t,n,r){var i=[];this.ie.rangeRead(e,function(e,t,n){i.push(e),n()},function(){r(i)},t,n)},e.prototype.Me=function(e,t,n,r){var i=[];this.ie.rangeRead(e,function(e,t,n){i.push(e),n()},function(){r(i)},t,n,!0)},e.prototype.je=function(e,t,n){var r=this;if(Array.isArray(t))return void new o.ALL(t.map(function(t){return function(n){r.ie.read(e,t,n)}})).then(function(e){n(e.filter(function(e){return e}))});var i=[];return"function"==typeof t?void this.ie.rangeRead(e,function(e,n,r){t(e,n,function(t){t&&i.push(e),r()})},function(){n(i)}):void 0},e.prototype.Be=function(e,t,n,r){var i=this,s=this.fe[e][t].getPrefix(n);new o.ALL(s.map(function(n){return function(r){i.Ne(e,t,n,r)}})).then(function(e){r([].concat.apply([],e))})},e.prototype.De=function(e,t,n,r,i){var s=this;new o.ALL(this.tableInfo[e].Te.filter(function(e){return-1===r.indexOf(e)}).map(function(r){return function(i){var a=s.Pe(n[r]),u="_"+e+"_idx_"+r;s.ie.read(u,a,function(e){if(!e)return void i();var n=e.rows.indexOf(t);if(-1===n)return void i();var r=e?Object.isFrozen(e)?o.t(e):e:{id:null,rows:[]};r.rows.splice(n,1),r.rows.sort(),r.rows=o.removeDuplicates(r.rows),s.ie.write(u,r.id,r,i,!0)})}})).then(i)},e.prototype.Le=function(e,t,n,r,i){var s=this;new o.ALL(this.tableInfo[e].Te.filter(function(e){return-1===r.indexOf(e)}).map(function(r){return function(i){var a=s.Pe(n[r]);s.fe[e][r]&&s.fe[e][r].addWord(String(n[r]));var u="_"+e+"_idx_"+r;s.ie.read(u,a,function(e){var n=e?Object.isFrozen(e)?o.t(e):e:{id:a,rows:[]};n.rows.push(t),n.rows.sort(),n.rows=o.removeDuplicates(n.rows),s.ie.write(u,a,n,i,!0)})}})).then(i)},e.prototype.Qe=function(e,t,n,i,o){var s=this;if(n){var a=r({},n,i,(c={},c[this.tableInfo[e].Ee]=t,c)),u=Object.keys(a).filter(function(e){return a[e]===n[e]});this.De(e,t,n,u,function(){s.Le(e,t,a,u,function(){s.ie.write(e,t,a,o,!0)})})}else this.ie.write(e,t,i,function(t){s.Le(e,t[s.tableInfo[e].Ee],i,[],function(){o(t)})},!0);var c},e.prototype.He=function(e,t,n){var r=this;if(!t)throw new Error("Can't delete without a primary key!");this.ie.read(e,t,function(i){r.De(e,t,i,[],function(){r.ie.delete(e,t,function(){n(i)})})})},e.prototype.Re=function(e,t){var n=this;new o.ALL(this.tableInfo[e].Te.map(function(t){return function(r){n.ie.drop("_"+e+"_idx_"+t,r)}})).then(function(){n.fe[e]={},n.tableInfo[e].Ke.forEach(function(t){n.fe[e][t]=new i.Trie([])}),n.ie.drop(e,t)})},e.prototype.ye=function(e){return Object.keys(e).forEach(function(t){var n=!1,r=!1;if(e[t].forEach(function(i){i.props&&i.props.indexOf("pk")>-1&&(n=!0),i.props&&(i.props.indexOf("idx")>-1||i.props.indexOf("trie")>-1)&&(r=!0,e["_"+t+"_idx_"+i.key]=[{key:"id",type:"string",props:["pk"]},{key:"rows",type:"any[]"}])}),r&&!n)throw new Error("Tables with secondary indexes must have a primary key!")}),e},e.prototype.be=function(e,t){this.tableInfo[e]={Ee:"",Fe:"",We:[],Je:[],Te:[],Ke:[],Ve:e},this.oe[e]={},this.fe[e]={},this.ie.makeTable(e,t);for(var n=this.models[e].length;n--;){var r=this.models[e][n];this.tableInfo[e].We.unshift(r.key),this.tableInfo[e].Je[n]=r.default,r.props&&r.props.indexOf("pk")>-1&&(this.tableInfo[e].Ee=r.key,this.tableInfo[e].Fe=r.type),r.props&&(r.props.indexOf("idx")>-1||r.props.indexOf("trie")>-1)&&this.tableInfo[e].Te.push(r.key),r.props&&r.props.indexOf("trie")>=0&&(this.tableInfo[e].Ke.push(r.key),this.fe[e][r.key]=new i.Trie([]))}return e},e}();t.ne=c},function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n={END_WORD:"$",PERMS_MIN_LEN:2},r=function(){function e(t){this.Ue=e.ze(t)}return e.prototype.addWord=function(t){var n=function(t,n,r,i){return e.Ge(t,n,r,i)};return t.toLowerCase().split("").reduce(n,this.Ue),this},e.prototype.removeWord=function(t){var r=e.Xe(this.Ue,t),i=r.prefixFound,o=r.prefixNode;return i&&delete o[n.END_WORD],this},e.prototype.getWords=function(){return e.Ye(this.Ue,"")},e.prototype.getPrefix=function(t){if(t=t.toLowerCase(),!this.$e(t))return[];var n=e.Xe(this.Ue,t).prefixNode;return e.Ye(n,t)},e.prototype.$e=function(t){return e.Xe(this.Ue,t).prefixFound},e.Ge=function(e,t,r,i){return e[t]=e[t]||{},e=e[t],r===i.length-1&&(e[n.END_WORD]=1),e},e.Xe=function(e,t){return{prefixFound:t.toLowerCase().split("").every(function(t,n){return!!e[t]&&(e=e[t])}),prefixNode:e}},e.ze=function(t){return t.reduce(function(t,n){return n.toLowerCase().split("").reduce(e.Ge,t),t},{})},e.Ye=function(t,r,i){void 0===i&&(i=[]);var o=r;for(var s in t)s===n.END_WORD&&(i.push(o),o=""),e.Ye(t[s],r+s,i);return i.sort()},e}();t.Trie=r},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n.Fe[e]=t.type,n.Ze[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n.tt[e].doAI=!0),n.nt){var r=localStorage.getItem(n.ue+"*"+e+"_idx");r&&n.tt[e].set(JSON.parse(r))}})},e.prototype.write=function(e,t,n,i,s){if(!(t=t||o.generateID(this.Fe[e],this.tt[e].ai)))throw new Error("Can't add a row without a primary key!");if(-1===this.tt[e].indexOf(t)&&(this.tt[e].add(t),this.nt&&localStorage.setItem(this.ue+"*"+e+"_idx",JSON.stringify(this.tt[e].keys()))),this.nt){var a=r({},s?{}:JSON.parse(localStorage.getItem(this.ue+"*"+e+"__"+t)||"{}"),n,(u={},u[this.Ze[e]]=t,u));localStorage.setItem(this.ue+"*"+e+"__"+t,JSON.stringify(a)),i(a)}else{var a=r({},s?{}:this.et[e][t],n,(c={},c[this.Ze[e]]=t,c));this.et[e][t]=o.deepFreeze(a),i(a)}var u,c},e.prototype.delete=function(e,t,n){-1!==this.tt[e].indexOf(t)&&(this.tt[e].remove(t),this.nt&&localStorage.setItem(this.ue+"*"+e+"_idx",JSON.stringify(this.tt[e].keys()))),this.nt?localStorage.removeItem(this.ue+"*"+e+"__"+t):delete this.et[e][t],n()},e.prototype.read=function(e,t,n){if(this.nt){var r=localStorage.getItem(this.ue+"*"+e+"__"+t);n(r?JSON.parse(r):void 0)}else n(this.et[e][t])},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this.tt[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[0,u.length-1];if(!u.length)return void n();s&&c&&(f=f.map(function(t){return a.tt[e].getLocation(t)}));var h=f[0],_=0,l=function(){h++,_++,_>200?i.setFast(d):d()},d=function(){if(h<=f[1])if(a.nt){var r=localStorage.getItem(a.ue+"*"+e+"__"+u[h]);t(r?JSON.parse(r):void 0,h,l)}else t(a.et[e][u[h]],h,l);else n()};d()},e.prototype.drop=function(e,t){var n=this;this.nt?(localStorage.setItem(this.ue+"*"+e+"_idx",JSON.stringify([])),this.tt[e].keys().forEach(function(t){localStorage.removeItem(n.ue+"*"+e+"__"+t)})):this.et[e]={};var r=new s.DatabaseIndex;r.doAI=this.tt[e].doAI,this.tt[e]=r,t()},e.prototype.getIndex=function(e,t,n){n(t?this.tt[e].keys().length:this.tt[e].keys())},e.prototype.destroy=function(e){var t=this;new o.ALL(Object.keys(this.tt).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();t.pe=a},function(module,exports,__webpack_require__){var __assign=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n.Fe[e]=t.type,n.Ze[e]=t.key,t.props&&t.props.indexOf("ai")>-1&&("int"===t.type||"number"===t.type)&&(n.tt[e].doAI=!0))})},e.prototype.write=function(e,t,n,r,i){var o=this;if(!(t=t||utilities_1.generateID(this.Fe[e],this.tt[e].ai)))throw new Error("Can't add a row without a primary key!");-1===this.tt[e].indexOf(t)&&this.tt[e].add(t);var s=utilities_1.uuid(),a=__assign({},n,(c={},c[this.Ze[e]]=t,c));this.it["write_"+s]=function(e){r(a)};var u=function(t){a=__assign({},t,a),o.st.postMessage({do:"write",args:{table:e,id:s,row:a}})};i?u({}):this.read(e,t,function(e){u(e)});var c},e.prototype.delete=function(e,t,n){-1!==this.tt[e].indexOf(t)&&this.tt[e].remove(t);var r=utilities_1.uuid();this.it["delete_"+r]=function(e){n()},this.st.postMessage({do:"delete",args:{table:e,id:r,pk:t}})},e.prototype.read=function(e,t,n){var r=utilities_1.uuid();if(-1===this.tt[e].indexOf(t))return void n(null);this.it["read_"+r]=function(e){n(e)},this.st.postMessage({do:"read",args:{table:e,id:r,pk:t}})},e.prototype.rangeRead=function(e,t,n,r,i,o){var s=this,a=this.tt[e].keys(),u=-1===[typeof r,typeof i].indexOf("undefined"),c=u?[r,i]:[0,a.length-1];if(!a.length)return void n();var f=utilities_1.uuid(),h=[],_=c[0],l=0;this.it["readRange_"+f+"_done"]=function(e){delete s.it["readRange_"+f],h=e;var r=function(){_<=c[1]?t(h[l],_,function(){_++,l++,l>200?lie_ts_1.setFast(r):r()}):n()};r()},this.st.postMessage({do:"readRange",args:{table:e,id:f,range:o&&u?c:c.map(function(e){return a[e]})}})},e.prototype.drop=function(e,t){var n=new db_idx_1.DatabaseIndex;n.doAI=this.tt[e].doAI,this.tt[e]=n;var r=utilities_1.uuid();this.it["delete_"+r]=function(e){t()},this.st.postMessage({do:"delete",args:{table:e,id:r,pk:"_clear_"}})},e.prototype.getIndex=function(e,t,n){n(t?this.tt[e].keys().length:this.tt[e].keys())},e.prototype.destroy=function(e){var t=this;new utilities_1.ALL(Object.keys(this.tt).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();exports.le=_IndexedDBStore},function(e,t){e.exports='function e(e){this.go=function(n){var t=0;e&&e.length||n([]),e.forEach(function(o,r){o(function(){++t===e.length&&n([])})})}}var n={db:null,store:function(e,t,o){var r=n.db.transaction(e,t);o(r,r.objectStore(e),function(e,n){return function(){postMessage({do:e,args:n})}})},init:function(){addEventListener("message",function(e){var t=e.data;n[t.do]&&n[t.do](t.args)},!1)},setup:function(t){var o=indexedDB.open(t.id,1),r=!1,a={};o.onupgradeneeded=function(e){r=!0,n.db=e.target.result,Object.keys(t.pkKeys).forEach(function(e){n.db.createObjectStore(e,{keyPath:t.pkKeys[e]}),a[e]=[]})},o.onsuccess=function(o){if(n.db=o.target.result,r)postMessage({do:"rdy",args:a});else{var s=function(e,t){var o=[];n.store(e,"readonly",function(e,n,r){n.openCursor().onsuccess=function(e){var n=e.target.result;n&&(o.push(n.key),n.continue())},e.oncomplete=function(){t(o)}})};new e(Object.keys(t.pkKeys).map(function(e){return function(n){s(e,function(t){a[e]=t,n()})}})).go(function(){postMessage({do:"rdy",args:a})})}}},write:function(e){n.store(e.table,"readwrite",function(n,t,o){t.put(e.row),n.oncomplete=o("write_"+e.id,null)})},read:function(e){n.store(e.table,"readonly",function(n,t,o){var r=t.get(e.pk);r.onsuccess=function(){postMessage({do:"read_"+e.id,args:r.result})}})},readRange:function(e){n.store(e.table,"readonly",function(n,t,o){var r=[],a=-1===e.range.indexOf(void 0)?t.openCursor(IDBKeyRange.bound(e.range[0],e.range[1])):t.openCursor();n.oncomplete=o("readRange_"+e.id+"_done",r),a.onsuccess=function(e){var n=e.target.result;n&&(r.push(n.value),n.continue())}})},delete:function(e){n.store(e.table,"readwrite",function(n,t,o){n.oncomplete=o("delete_"+e.id,!0),n.onerror=o("delete_"+e.id,!1),"_clear_"===e.pk?t.clear():t.delete(e.pk)})}};n.init();'},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1&&(n.Fe[e]=t.type,n.Ze[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n.tt[e].doAI=!0)})},e.prototype.ut=function(e,t,n,r){var i=function(e){e.executeSql(t,n,function(e,t){r(t)},function(e,r){return console.error(t,n,r),!1})};e?this.X.transaction(i):this.X.readTransaction(i)},e.prototype.write=function(e,t,n,i,s){var a=this;if(!(t=t||o.generateID(this.Fe[e],this.tt[e].ai)))throw new Error("Can't add a row without a primary key!");var u=!1;if(-1===this.tt[e].indexOf(t)&&(u=!0,this.tt[e].add(t)),u){var c=r({},n,(h={},h[this.Ze[e]]=t,h));this.ut(!0,"INSERT into "+this.ct(e)+" (id, data) VALUES (?, ?)",[t,JSON.stringify(c)],function(e){i(c)})}else{var f=function(o){var s=r({},o,n,(u={},u[a.Ze[e]]=t,u));a.ut(!0,"UPDATE "+a.ct(e)+" SET data = ? WHERE id = ?",[JSON.stringify(s),t],function(){i(s)});var u};s?f({}):this.read(e,t,function(e){f(e)})}var h},e.prototype.delete=function(e,t,n){-1!==this.tt[e].indexOf(t)&&this.tt[e].remove(t),this.ut(!0,"DELETE FROM "+this.ct(e)+" WHERE id = ?",[t],function(){n()})},e.prototype.read=function(e,t,n){this.ut(!1,"SELECT data FROM "+this.ct(e)+" WHERE id = ?",[t],function(e){n(e.rows.length?JSON.parse(e.rows.item(0).data):void 0)})},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this.tt[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[];if(!u.length)return void n();s&&c&&(f=f.map(function(t){return a.tt[e].getLocation(t)}));var h=f[0]||0,_=[],l=f[0],d="SELECT data from "+this.ct(e);if(f.length){for(var p="number"==typeof u[l];l<=f[1];)_.push(p?u[l]:'"'+u[l]+'"'),l++;d+=" WHERE id IN ("+_.join(", ")+")"}d+=" ORDER BY id",this.ut(!1,d,[],function(e){var r=0,o=function(){e.rows.length>r?t(JSON.parse(e.rows.item(r).data),h,function(){h++,r++,r>200?i.setFast(o):o()}):n()};o()})},e.prototype.drop=function(e,t){var n=new s.DatabaseIndex;n.doAI=this.tt[e].doAI,this.tt[e]=n,this.ut(!0,"DELETE FROM "+this.ct(e),[],function(e){t()})},e.prototype.getIndex=function(e,t,n){n(t?this.tt[e].keys().length:this.tt[e].keys())},e.prototype.destroy=function(e){var t=this;new o.ALL(Object.keys(this.tt).map(function(e){return function(n){t.drop(e,n)}})).then(e)},e}();t.de=a},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n0:e===t}(t[a][r.Oe],n[a][r.Oe]))s();else if("array"===r.ke){var h=(n[a][r.Oe]||[]).filter(function(e){return-1===(t[a][r.Oe]||[]).indexOf(e)}),_=(t[a][r.Oe]||[]).filter(function(e){return-1===(n[a][r.Oe]||[]).indexOf(e)});new o.ALL([h,_].map(function(e,t){return function(n){i.pt(r,e,0===t,f,n)}})).then(s)}else{var l=function(){void 0!==n[a][r.Oe]?i.pt(r,[n[a][r.Oe]],!0,f,s):s()};void 0!==t[a][r.Oe]?i.pt(r,[t[a][r.Oe]],!1,f,l):l()}else{var d="array"===r.ke?n[a][r.Oe]||[]:[n[a][r.Oe]].filter(function(e){return e});d&&d.length?i.pt(r,d,!0,f,s):s()}}}})).then(r)}})).then(r)},e.prototype._t=function(e){var t=this,n=this.te.tableInfo[this.$.table].Ee;if(this.ft)return void this.lt(function(n){t.$.result=t.$.table.map(function(e){return-1===n.indexOf(e)?e:r({},t.$.actionArgs,e)}),e(t.$)});if(this.$.where)this.lt(function(r){r.length?new o.CHAIN(r.map(function(e){return function(r){t.te.Qe(t.$.table,e[n],e,t.$.actionArgs||{},r)}})).then(function(i){t.te.oe[t.$.table]={},t.$.result=[{msg:i.length+" row(s) modfied.",affectedRowPKS:i.map(function(e){return e[n]}),affectedRows:i}],t.yt("add",r,i,function(){e(t.$)})}):(t.$.result=[{msg:"0 row(s) modfied.",affectedRowPKS:[],affectedRows:[]}],e(t.$))});else{var i=this.$.actionArgs||{};this.te.oe[this.$.table]={};var s=function(r){t.te.Qe(t.$.table,i[n],r,i,function(i){t.$.result=[{msg:"1 row inserted.",affectedRowPKS:[i[n]],affectedRows:[i]}],t.yt("add",[r].filter(function(e){return e}),[i],function(){e(t.$)})})};void 0!==i[n]?this.te.je(this.$.table,[i[n]],function(e){s(e.length?e[0]:null)}):s(null)}},e.prototype.He=function(e){var t=this;if(this.ft)return void(this.$.where?this.lt(function(n){t.$.result=t.$.table.filter(function(e){return-1===n.indexOf(e)}),e(t.$)}):(this.$.result=[],e(this.$)));this.$.where?this.lt(function(n){n=n.filter(function(e){return e}),n.length?new o.ALL(n.map(function(e){return function(n){t.te.He(t.$.table,e[t.te.tableInfo[t.$.table].Ee],n)}})).then(function(r){t.te.oe[t.$.table]={},t.$.result=[{msg:n.length+" row(s) deleted.",affectedRowPKS:n.map(function(e){return e[t.te.tableInfo[t.$.table].Ee]}),affectedRows:n}],t.yt("del",n,[],function(){e(t.$)})}):(t.$.result=[{msg:"0 row(s) deleted.",affectedRowPKS:[],affectedRows:[]}],e(t.$))}):this.Re(e)},e.prototype.Re=function(e){var t=this;if(this.ft)return this.$.result=[],void e(this.$);this.te.Ce(this.$.table,void 0,void 0,function(n){t.te.oe[t.$.table]={},t.te.Re(t.$.table,function(){t.$.result=[{msg:"'"+t.$.table+"' table dropped.",affectedRowPKS:n.map(function(e){return e[t.te.tableInfo[t.$.table].Ee]}),affectedRows:n}],t.yt("del",n,[],function(){e(t.$)})})})},e}();t.re=s;var a=function(){function e(e,t){this.q=e,this.s=t,this.bt=[]}return e.prototype.vt=function(e,t){var n=this;if(this.q.join){var r={};"cross"!==this.q.join.type&&this.q.join.where&&(r={gt:this.q.join.where[0],wt:this.q.join.where[1],mt:this.q.join.where[2]});var i=this.q.table,o=this.q.join.table;this.xt(this.q.join.type,i,o,r,function(e){t(n.q.where?e.filter(function(e,t){return Array.isArray(n.q.where)?f(e,n.q.where||[],t,!0):n.q.where(e,t)}):n.q.range?e.filter(function(e,t){return n.q.range&&n.q.range[0]>=t&&n.q.range[1]<=t}):e)})}},e.prototype.qt=function(e,t){return e.reduce(function(e,n){return-1!==n.indexOf(".length")?e+"."+String((t[n.replace(".length","")]||[]).length):e+"."+String(t[n])},"").slice(1)},e.prototype.kt=function(e){var t=this,n=this.q.groupBy||{},r=e.sort(function(e,r){return t.Ot(e,r,n,!0)});return r.forEach(function(e,r){var i=Object.keys(n).map(function(t){return String(e[t])||""}).join(".");t.It||(t.It={}),t.It[i]||(t.It[i]=[]),t.It[i].push(r)}),r},e.prototype.St=function(e){var t=this;return e.filter(function(e,n){return Array.isArray(t.q.having)?f(e,t.q.having||[],n,!0):t.q.having(e,n)})},e.prototype.At=function(e){var t=this;return e.sort(function(e,n){return t.Ot(e,n,t.q.orderBy||{},!1)})},e.prototype.jt=function(e){var t=this;return e.filter(function(e,n){return!t.q.offset||n>=t.q.offset})},e.prototype.Tt=function(e){var t=this;return e.filter(function(e,n){return!t.q.limit||n-1&&_.push(h(t,null)),i(!1)})},function(){e===s?a.s.je(c.Ve,function(e,t,n){-1===d.indexOf(t)&&_.push(h(null,e)),n(!1)},function(){i(_)}):i(_)})},e.prototype.Ot=function(e,t,n,r){return Object.keys(n).reduce(function(i,s){var a=r?o.objQuery(s,e):e[s],u=r?o.objQuery(s,t):t[s];return i||(a===u?0:(a>u?1:-1)*("desc"===n[s]?-1:1))},0)},e.prototype.Rt=function(e,t){var n=this,r=this.q.actionArgs,s={},a={};if(r&&r.length){var u=!1,c={};r.forEach(function(e){if(-1!==e.indexOf("(")){var t=(e.match(/^.*\(/g)||[""])[0].replace(/\(|\)/g,"").toUpperCase(),n=i.NanoSQLInstance.functions[t],r=1===e.split(" AS ").length?t:(e.split(" AS ").pop()||"").trim();if(!n)throw new Error("'"+t+"' is not a valid function!");"A"===n.type&&(u=!0),c[e]={fn:n,key:r}}}),new o.ALL(r.map(function(t){return function(r){if(t.indexOf("(")>-1){var i=(t.match(/\(.*\)/g)||[""])[0].replace(/\(|\)/g,"").split(",").map(function(e){return e.trim()});n.It&&u?new o.ALL(Object.keys(n.It).map(function(r){return a[r]||(a[r]={}),function(o){(s=c[t].fn).call.apply(s,[e.filter(function(e,t){return n.It[r].indexOf(t)>-1}),function(e){a[r][c[t].key]=e,o()}].concat(i));var s}})).then(r):(f=c[t].fn).call.apply(f,[e,function(e){s[c[t].key]=e,r()}].concat(i))}else r();var f}})).then(function(){var i=function(e,t,i){var s={};return r.forEach(function(r){var a=r.indexOf("(")>-1,u=a?c[r].fn.type:"";if(r.indexOf(" AS ")>-1){var f=r.split(" AS "),h=a?c[r].key:f[0].trim();s[f[1]]=a?"A"===u?i[h]:i[h][t]:o.objQuery(h,e,void 0!==n.q.join)}else{var h=a?c[r].key:r;s[r]=a?"A"===u?i[h]:i[h][t]:o.objQuery(h,e,void 0!==n.q.join)}}),s};if(n.It&&u){var f=[];Object.keys(n.It).forEach(function(t){var r=e.filter(function(e,r){return n.It[t].indexOf(r)>-1}).filter(function(e,t){return t<1});r&&r.length&&f.push(i(r[0],0,a[t]))}),t(f)}else t(u?e.filter(function(e,t){return t<1}).map(function(e,t){return i(e,t,s)}):e.map(function(e,t){return i(e,t,s)}))})}else t(e)},e.prototype.dt=function(e,t){var n=this,r=function(){n.q.having&&(e=n.St(e)),n.q.orderBy&&(e=n.At(e)),n.q.offset&&(e=n.jt(e)),n.q.limit&&(e=n.Tt(e)),t(e)},i=function(){n.q.actionArgs&&n.q.actionArgs.length?n.Rt(e,function(t){e=t,r()}):r()},o=function(){n.q.groupBy&&(e=n.kt(e)),n.q.orm?n.Et(e,function(t){e=t,i()}):i()};this.q.join?this.vt(e,function(t){e=t,o()}):o()},e}();t.Lt=a;var u=function(){function e(e,t){this.q=e,this.s=t}return e.prototype.getRows=function(e){var t=this;if(this.q.join)return void e([]);if(this.q.join&&this.q.orm)throw new Error("Cannot do a JOIN and ORM command at the same time!");if([this.q.where,this.q.range,this.q.trie].filter(function(e){return e}).length>1)throw new Error("Can only have ONE of Trie, Range or Where!");return this.q.trie&&this.q.trie.column&&this.q.trie.search?void this.Pt(e):this.q.range&&this.q.range.length?void this.Nt(e):this.q.where&&this.q.where.length?Array.isArray(this.q.where)?("string"==typeof this.q.where[0]?0===this.Ct(this.q.where):0===(this.q.where||[]).reduce(function(e,n,r){return r%2==1?e:e+t.Ct(n)},0))?void this.Mt(e):void this.Bt(e):void this.Bt(function(n){e(n.filter(t.q.where))}):void this.Bt(e)},e.prototype.Mt=function(e){var t=this;if(this.q.where&&"string"==typeof this.q.where[0])this.Dt(this.q.where,e);else if(this.q.where){var n=[],r="";new o.CHAIN(this.q.where.map(function(e){return function(i){if("OR"===e||"AND"===e)return r=e,void i();t.Dt(e,function(e){if("AND"===r){var o=e.map(function(e){return e[t.s.tableInfo[t.q.table].Ee]});n=n.filter(function(e){return-1!==o.indexOf(e[t.s.tableInfo[t.q.table].Ee])})}else n.concat(e);i()})}})).then(function(){e(n)})}},e.prototype.Dt=function(e,t){var n=this;if("BETWEEN"!==e[1]){var r=[];switch(e[1]){case"IN":r=e[2];break;case"=":r=[e[2]]}e[0]===this.s.tableInfo[this.q.table].Ee?this.s.je(this.q.table,r,t):new o.ALL(r.map(function(t){return function(r){n.s.Ne(n.q.table,e[0],t,r)}})).then(function(e){t([].concat.apply([],e))})}else{var i=e[0]===this.s.tableInfo[this.q.table].Ee?"":e[0];if(i){var s="_"+this.q.table+"_idx_"+i;this.s.Me(s,e[2][0],e[2][1],function(e){var r=[].concat.apply([],e);n.s.je(n.q.table,r,t)})}else this.s.Me(this.q.table,e[2][0],e[2][1],function(e){t(e)})}},e.prototype.Nt=function(e){var t=this;if(this.q.range){var n=this.q.range;this.s.ie.getIndex(this.q.table,!0,function(r){for(var i=n[0]>0?n[1]:r+n[0]-n[1],o=i,s=Math.abs(n[0])-1;s--;)o++;t.s.Ce(t.q.table,i,o,e)})}else e([])},e.prototype.Pt=function(e){this.q.trie?this.s.Be(this.q.table,this.q.trie.column,this.q.trie.search,e):e([])},e.prototype.Bt=function(e){var t=this;this.s.je(this.q.table,function(e,n,r){r(!t.q.where||(Array.isArray(t.q.where)?f(e,t.q.where||[],n||0):t.q.where(e,n)))},e)},e.prototype.Ct=function(e){var t=this.s.tableInfo[this.q.table];return["=","IN","BETWEEN"].indexOf(e[1])>-1&&(e[0]===t.Ee||t.Te.indexOf(e[0])>-1)?0:1},e}();t.Qt=u;var c=function(){function e(e){this.q=e}return e.prototype.getRows=function(e){var t=this;if(this.q.join||this.q.orm||this.q.trie)throw new Error("Cannot do a JOIN, ORM or TRIE command with instance table!");if(this.q.range&&this.q.range.length){var n,r,i=this.q.range;n=i[0]<0?this.q.table.length+i[0]-i[1]:i[1];var o=Math.abs(i[0])-1;for(r=n;o--;)r++;return void e(this.q.table.filter(function(e,t){return t>=n&&t<=r}))}e(this.q.table.filter(function(e,n){return!t.q.where||(Array.isArray(t.q.where)?f(e,t.q.where||[],n):t.q.where(e,n))}))},e}();t.InstanceSelection=c;var f=function(e,t,n,r){var i=["AND","OR"];if("string"!=typeof t[0]){var s=!1,a=t.map(function(t,a){return-1!==i.indexOf(t)?("AND"===t&&(s=!0),t):0===h(t[2],t[1],"_IDX_"===t[0]?n:o.objQuery(t[0],e,r))});if(a.forEach(function(e,t){"OR"===e&&(a[t]=a[t-1]||a[t+1],a[t-1]=void 0,a[t+1]=void 0)}),a=a.filter(function(e){return void 0!==e}),s){var u,c=!1;return-1===a.reduce(function(e,t,n){return 0===n?(e.push(t),u=e.length-1,e):"AND"===t?(c=!0,e.push(t),e):c?(e.push(t),u=e.length-1,c=!1,e):(void 0!==u&&(e[u]=t||e[u]),e)},[]).filter(function(e){return void 0!==e}).indexOf(!1)}return-1!==a.indexOf(!0)}return 0===h(t[2],t[1],"_IDX_"===t[0]?n:o.objQuery(t[0],e,r))},h=function(e,t,n){var r=function(e){return["LIKE","NOT LIKE"].indexOf(t)>-1?String(e||"").toLowerCase():e},i=r(n),o=r(e);if("NULL"===e||"NOT NULL"===e){var s="="===t||"LIKE"===t;return("NULL"===e?null===n||void 0===n:null!==n&&void 0!==n)?s?0:1:s?1:0}switch(t){case"=":return i===o?0:1;case"!=":return i!==o?0:1;case">":return i>o?0:1;case"<":return i=":return i>=o?0:1;case"IN":return(o||[]).indexOf(i)<0?1:0;case"NOT IN":return(o||[]).indexOf(i)<0?0:1;case"REGEX":return i.match(o)?0:1;case"LIKE":return i.indexOf(o)<0?1:0;case"NOT LIKE":return i.indexOf(o)>0?1:0;case"BETWEEN":return o[0]<=i&&o[1]>=i?0:1;case"HAVE":return(i||[]).indexOf(o)<0?1:0;case"NOT HAVE":return(i||[]).indexOf(o)<0?0:1;case"INTERSECT":return(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length>0?0:1;case"NOT INTERSECT":return 0===(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length?0:1;default:return 1}}},function(e,t,n){var r=this&&this.R||Object.assign||function(e){for(var t,n=1,r=arguments.length;n0){var a=r.parent.table(e).query("select");n||a.range(-1*s.ptr,0),a.exec().then(function(o){if(!o.length)return void t();var a={};o.forEach(function(e){a[e.table]||(a[e.table]=[]),a[e.table]=a[e.table].concat(e.keys)}),new i.ALL(Object.keys(a).map(function(e){return function(t){r.Vt(e,a[e],t,n)}})).then(function(){r.parent.table(e).query("delete").comment("History Purge").where(["id","IN",o.map(function(e){return e.id})]).exec().then(function(){s.ptr=0,r.parent.table(e+"_ptr").query("upsert",s).comment("History Purge").where(["id","=",s.id]).exec().then(t)})})})}else t()})},e.prototype.Gt=function(e,t,n){if(!this.historyModes)return void this.zt("_hist",n);var r=this.Wt(e);r?this.zt(r,n):this.Vt(e,t,n)},e.prototype.Xt=function(e,t,n){if(!this.historyModes)return void this.zt("_hist",n,!0);var r=this.Wt(e);r?this.zt(r,n,!0):this.Vt(e,[t],n,!0)},e.prototype.didExec=function(e,t){var n=this;e.table&&0!==e.table.indexOf("_")&&e.types.indexOf("change")>-1&&-1===e.query.comments.indexOf("History Write")?this.Gt(e.table,e.affectedRowPKS,function(){new i.ALL(e.affectedRows.map(function(t){return function(r){var i=t[n.Ht[e.table]];n.Ft[e.table][i]?n.Ut(e.table,e.types,i,t,!1,function(e){r(i)}):(n.Ft[e.table][i]=!0,n.Ut(e.table,e.types,i,t,!0,function(t){n.parent.table("_"+e.table+"__hist_idx").query("upsert",{id:i,histRows:[t,-1],histPtr:0}).exec().then(function(){r(i)})}))}})).then(function(r){n.Yt(e,r,t)})}):t(e)},e.prototype.Yt=function(e,t,n){var r=this.Wt(e.table);r?this.parent.table(r).query("upsert",{id:i.timeid(!0),table:e.table,keys:t}).exec().then(function(){n(e)}):n(e)},e.prototype.Ut=function(e,t,n,o,s,a){var u=this,c="_"+e+"__hist_idx",f=i.timeid(!0),h=function(e){u.parent.table(c).query("select").where(["id","=",n]).exec().then(function(t){var r=Object.isFrozen(t[0])?i.t(t[0]):t[0];r.histRows.unshift(e),u.parent.table(c).query("upsert",r).where(["id","=",n]).exec().then(function(){a(e)})})};t.indexOf("delete")>-1||t.indexOf("drop")>-1?h(-1):this.parent.table("_"+e+"__hist_rows").query("upsert",r({ue:f},o)).exec().then(function(){if(s)return void a(f);h(f)})},e.prototype.extend=function(e,t,n){if("hist"===t[0]){var r=t[1],i=t[2],o=t[3];switch(r){case"<":case">":this.$t(r,i,o,function(n){e(t,[n])});break;case"?":this.Zt(i,o,function(n){e(t,n)});break;case"rev":this.en(i,o,function(n){e(t,n)});break;case"clear":this.Xt(i,o,function(){e(t,n)})}}else e(t,n)},e.prototype.en=function(e,t,n){var r=this,s="_"+e+"__hist_idx";this.parent.table(s).query("select").where(["id","=",t]).exec().then(function(t){var s=t[0].histRows.filter(function(e){return-1!==e});r.parent.table("_"+e+"__hist_rows").query("select").where(["_id","IN",s]).exec().then(function(e){var r={};e.forEach(function(e){r[e[o[2]]]=Object.isFrozen(e)?i.t(e):e,delete r[e[o[2]]][o[2]]}),n([{pointer:t[0].histRows.length-t[0].histPtr-1,revisions:t[0].histRows.reverse().map(function(e){return-1===e?null:r[e]})}])})})},e.prototype.tn=function(e,t){var n=this;this.parent.extend("idx.length",e).then(function(r){n.parent.table(e+"_ptr").query("select").exec().then(function(e){if(!e.length)return void t([0,0]);t([r,r-e[0].ptr])})})},e.prototype.Zt=function(e,t,n){if(!this.historyModes)return void this.tn("_hist",function(e){n(e)});var r=this.Wt(e);if(r){if(!e)throw Error("Need a table to query this history!");this.tn(r,n)}else{if(!t)throw Error("Need a row primary key to query this history!");var i="_"+e+"__hist_idx";this.parent.table(i).query("select").where(["id","=",t]).exec().then(function(e){var t=e[0];n([t.histRows.length,t.histRows.length-t.histPtr-1])})}},e.prototype.nn=function(e,t,n){var r=this;this.parent.table(t+"_ptr").query("select").exec().then(function(o){var s=i.t(o[0]);s.ptr+="<"===e?1:-1,s.ptr<0&&(s.ptr=0),r.parent.extend("idx.length",t).then(function(a){if(s.ptr>a&&(s.ptr=a),o[0].ptr===s.ptr)return void n(!1);r.parent.table(t).query("select").range(-1,"<"===e?o[0].ptr:s.ptr).exec().then(function(o){r.parent.table(t+"_ptr").query("upsert",s).exec().then(function(){new i.ALL(o[0].keys.map(function(t){return function(n){r.rn(e,o[0].table,t,n)}})).then(function(e){n(e.indexOf(!0)>-1)})})})})})},e.prototype.rn=function(e,t,n,r){var o=this,s=function(e){o.parent.table("_"+t+"__hist_idx").query("upsert",e).where([o.Ht[t],"=",n]).exec().then(function(){r(!0)})};this.parent.table("_"+t+"__hist_idx").query("select").where([this.Ht[t],"=",n]).exec().then(function(a){var u=i.t(a[0]);if(u.histPtr+="<"===e?1:-1,u.histPtr<0&&(u.histPtr=0),u.histPtr>u.histRows.length-1&&(u.histPtr=u.histRows.length-1),u.histPtr===a[0].histPtr)return void r(!1);var c=u.histRows[u.histPtr];-1===c?o.parent.table(t).query("delete").comment("History Write").where([o.Ht[t],"=",n]).exec().then(function(){s(u)}):o.parent.table("_"+t+"__hist_rows").query("select").where(["_id","=",c]).exec().then(function(e){o.parent.table(t).query("upsert",e[0]).comment("History Write").exec().then(function(){s(u)})})})},e.prototype.$t=function(e,t,n,r){if(!this.historyModes)return void this.nn(e,"_hist",r);var i=this.Wt(t);if(i){if(!t)throw Error("Need a table to change this history!");this.nn(e,i,r)}else{if(!n)throw Error("Need a row primary key to change this history!");this.rn(e,t,n,r)}},e}();t.W=s}])}); \ No newline at end of file diff --git a/examples/testing.html b/examples/testing.html index 7b2ad978..dff2055c 100644 --- a/examples/testing.html +++ b/examples/testing.html @@ -1,449 +1,13 @@ - + - - - - Everything is in the console, not much to see here just a scratchpad to test queries with. \ No newline at end of file diff --git a/lib/database/index.js b/lib/database/index.js index 6da7194b..b87a5131 100644 --- a/lib/database/index.js +++ b/lib/database/index.js @@ -9,6 +9,7 @@ var __assign = (this && this.__assign) || Object.assign || function(t) { Object.defineProperty(exports, "__esModule", { value: true }); var storage_1 = require("./storage"); var query_1 = require("./query"); +var utilities_1 = require("../utilities"); var NanoSQLDefaultBackend = (function () { function NanoSQLDefaultBackend() { } @@ -25,6 +26,7 @@ var NanoSQLDefaultBackend = (function () { new query_1._NanoSQLStorageQuery(this._store).doQuery(execArgs, next); }; NanoSQLDefaultBackend.prototype.extend = function (next, args, result) { + var _this = this; switch (args[0]) { case "idx.length": case "idx": @@ -39,9 +41,31 @@ var NanoSQLDefaultBackend = (function () { } break; case "rebuild_idx": - this._store.rebuildIndexes(args[1], function (time) { - next(args, [time]); - }); + if (args[1]) { + this._store.rebuildIndexes(args[1], function (time) { + next(args, [time]); + }); + } + else { + new utilities_1.ALL(Object.keys(this._store.tableInfo).map(function (table) { + return function (done) { + _this._store.rebuildIndexes(table, done); + }; + })).then(function (times) { + next(args, times); + }); + } + break; + case "clear_cache": + if (args[1]) { + this._store._cache[args[1]] = {}; + } + else { + Object.keys(this._store.tableInfo).forEach(function (table) { + _this._store._cache[table] = {}; + }); + } + next(args, args[1] || Object.keys(this._store.tableInfo)); break; default: next(args, result); diff --git a/lib/database/query.d.ts b/lib/database/query.d.ts index 887091bd..763f1d21 100644 --- a/lib/database/query.d.ts +++ b/lib/database/query.d.ts @@ -4,6 +4,8 @@ export declare class _NanoSQLStorageQuery { private _store; constructor(_store: _NanoSQLStorage); doQuery(query: IdbQuery, next: (q: IdbQuery) => void): void; + private _updateORMRows(relation, fromPKs, add, primaryKey, complete); + private _syncORM(type, oldRows, newRows, complete); } export declare class _MutateSelection { q: IdbQuery; diff --git a/lib/database/query.js b/lib/database/query.js index 67e4b420..e6d8f6c0 100644 --- a/lib/database/query.js +++ b/lib/database/query.js @@ -79,6 +79,117 @@ var _NanoSQLStorageQuery = (function () { } }); }; + _NanoSQLStorageQuery.prototype._updateORMRows = function (relation, fromPKs, add, primaryKey, complete) { + var _this = this; + this._store._nsql.table(relation._fromTable).query("select").where([this._store.tableInfo[relation._fromTable]._pk, "IN", fromPKs]).exec().then(function (rows) { + new utilities_1.ALL(rows.map(function (row) { + return function (rowDone) { + row = Object.isFrozen(row) ? utilities_1._assign(row) : row; + if (relation._fromType === "array") { + row[relation._fromColumn] = row[relation._fromColumn] || []; + if (add) { + row[relation._fromColumn].push(primaryKey); + } + else { + var idxOf = row[relation._fromColumn].indexOf(primaryKey); + if (idxOf !== -1) { + row[relation._fromColumn].splice(idxOf, 1); + } + } + row[relation._fromColumn].sort(); + } + else { + if (add) { + row[relation._fromColumn] = primaryKey; + } + else { + row[relation._fromColumn] = undefined; + } + } + _this._store._nsql.table(relation._fromTable).query("upsert", row).exec().then(rowDone); + }; + })).then(complete); + }); + }; + _NanoSQLStorageQuery.prototype._syncORM = function (type, oldRows, newRows, complete) { + var _this = this; + var useRelations = this._store._relToTable[this._query.table]; + if (!useRelations || !useRelations.length) { + complete(); + return; + } + var cnt = Math.max(oldRows.length, newRows.length); + var arra = []; + while (cnt--) + arra.push(" "); + new utilities_1.CHAIN(arra.map(function (v, idx) { + return function (rowDone) { + new utilities_1.ALL(useRelations.map(function (relation) { + return function (relationDone) { + var equals = function (val1, val2) { + if (Array.isArray(val1) && Array.isArray(val2)) { + return val1.filter(function (v, i) { return v !== val2[i]; }).length > 0; + } + else { + return val1 === val2; + } + }; + switch (type) { + case "del": + var delPrimarykey = oldRows[idx][_this._store.tableInfo[_this._query.table]._pk]; + var updateIDs = relation._thisType === "array" ? (oldRows[idx][relation._thisColumn] || []) : ([oldRows[idx][relation._thisColumn]].filter(function (v) { return v; })); + _this._updateORMRows(relation, updateIDs, false, delPrimarykey, relationDone); + break; + case "add": + var primaryKey_1 = newRows[idx][_this._store.tableInfo[_this._query.table]._pk]; + if (oldRows[idx]) { + if (equals(oldRows[idx][relation._thisColumn], newRows[idx][relation._thisColumn])) { + relationDone(); + } + else { + if (relation._thisType === "array") { + var addIds = (newRows[idx][relation._thisColumn] || []).filter(function (v) { return (oldRows[idx][relation._thisColumn] || []).indexOf(v) === -1; }); + var removeIds = (oldRows[idx][relation._thisColumn] || []).filter(function (v) { return (newRows[idx][relation._thisColumn] || []).indexOf(v) === -1; }); + new utilities_1.ALL([addIds, removeIds].map(function (list, i) { + return function (done) { + _this._updateORMRows(relation, list, i === 0, primaryKey_1, done); + }; + })).then(relationDone); + } + else { + var addRelation = function () { + if (newRows[idx][relation._thisColumn] !== undefined) { + _this._updateORMRows(relation, [newRows[idx][relation._thisColumn]], true, primaryKey_1, relationDone); + } + else { + relationDone(); + } + }; + if (oldRows[idx][relation._thisColumn] !== undefined) { + _this._updateORMRows(relation, [oldRows[idx][relation._thisColumn]], false, primaryKey_1, addRelation); + } + else { + addRelation(); + } + } + } + } + else { + var valuesToAdd = relation._thisType === "array" ? (newRows[idx][relation._thisColumn] || []) : ([newRows[idx][relation._thisColumn]].filter(function (v) { return v; })); + if (valuesToAdd && valuesToAdd.length) { + _this._updateORMRows(relation, valuesToAdd, true, primaryKey_1, relationDone); + } + else { + relationDone(); + } + } + break; + } + }; + })).then(rowDone); + }; + })).then(complete); + }; _NanoSQLStorageQuery.prototype._upsert = function (next) { var _this = this; var pk = this._store.tableInfo[this._query.table]._pk; @@ -101,11 +212,12 @@ var _NanoSQLStorageQuery = (function () { return function (rowDone) { _this._store._write(_this._query.table, r[pk], r, _this._query.actionArgs || {}, rowDone); }; - })).then(function (rows) { - var result = [].concat.apply([], rows); + })).then(function (newRows) { _this._store._cache[_this._query.table] = {}; - _this._query.result = [{ msg: rows.length + " row(s) modfied.", affectedRowPKS: result.map(function (r) { return r[pk]; }), affectedRows: result }]; - next(_this._query); + _this._query.result = [{ msg: newRows.length + " row(s) modfied.", affectedRowPKS: newRows.map(function (r) { return r[pk]; }), affectedRows: newRows }]; + _this._syncORM("add", rows, newRows, function () { + next(_this._query); + }); }); } else { @@ -120,7 +232,9 @@ var _NanoSQLStorageQuery = (function () { var write_1 = function (oldRow) { _this._store._write(_this._query.table, row_1[pk], oldRow, row_1, function (result) { _this._query.result = [{ msg: "1 row inserted.", affectedRowPKS: [result[pk]], affectedRows: [result] }]; - next(_this._query); + _this._syncORM("add", [oldRow].filter(function (r) { return r; }), [result], function () { + next(_this._query); + }); }); }; if (row_1[pk] !== undefined) { @@ -166,7 +280,9 @@ var _NanoSQLStorageQuery = (function () { })).then(function (affectedRows) { _this._store._cache[_this._query.table] = {}; _this._query.result = [{ msg: rows.length + " row(s) deleted.", affectedRowPKS: rows.map(function (r) { return r[_this._store.tableInfo[_this._query.table]._pk]; }), affectedRows: rows }]; - next(_this._query); + _this._syncORM("del", rows, [], function () { + next(_this._query); + }); }); } else { @@ -186,20 +302,15 @@ var _NanoSQLStorageQuery = (function () { next(this._query); return; } - var rows = []; - var doDrop = function (rows) { + this._store._rangeReadIDX(this._query.table, undefined, undefined, function (rows) { _this._store._cache[_this._query.table] = {}; _this._store._drop(_this._query.table, function () { _this._query.result = [{ msg: "'" + _this._query.table + "' table dropped.", affectedRowPKS: rows.map(function (r) { return r[_this._store.tableInfo[_this._query.table]._pk]; }), affectedRows: rows }]; - next(_this._query); + _this._syncORM("del", rows, [], function () { + next(_this._query); + }); }); - }; - if (this._query.transaction) { - doDrop([]); - } - else { - this._store._rangeReadIDX(this._query.table, undefined, undefined, doDrop); - } + }); }; return _NanoSQLStorageQuery; }()); @@ -208,7 +319,6 @@ var _MutateSelection = (function () { function _MutateSelection(q, s) { this.q = q; this.s = s; - this._ormTableCache = {}; this._groupByColumns = []; } _MutateSelection.prototype._join = function (rows, complete) { @@ -310,64 +420,35 @@ var _MutateSelection = (function () { return function (rowResult) { new utilities_1.ALL(ormQueries.map(function (orm) { return function (ormResult) { - if (row[orm.key] === undefined || row[orm.key] === null) { + if (!row[orm.key] || !row[orm.key].length) { ormResult(); return; } - var isArray = false; - var cacheKey = _this.q.table + "-" + orm.key; - var otherTable = ""; - if (_this._ormTableCache[cacheKey]) { - otherTable = _this._ormTableCache[cacheKey][0]; - isArray = _this._ormTableCache[cacheKey][1]; - } - else { - otherTable = _this.s.models[_this.q.table].reduce(function (prev, cur) { - if (cur.props && cur.props.length) { - if (cur.key === orm.key) { - isArray = cur.type.indexOf("[]") > -1; - return cur.type.replace("[]", ""); - } + var relateData = _this.s._relFromTable[_this.q.table][orm.key]; + if (relateData) { + _this.s._nsql.table(relateData._toTable).query("select").where([_this.s.tableInfo[relateData._toTable]._pk, relateData._thisType === "array" ? "IN" : "=", row[orm.key]]).exec().then(function (rows) { + var q = _this.s._nsql.table(rows).query("select", orm.select); + if (orm.where) { + q.where(orm.where); } - return prev; - }, ""); - _this._ormTableCache[cacheKey] = [otherTable, isArray]; - } - if (otherTable) { - var otherPK_1 = _this.s.tableInfo[otherTable]._pk; - var ormWhere = [otherPK_1, (isArray ? "IN" : "="), row[orm.key]]; - var q = _this.s._nsql.table(otherTable) - .query("select", orm.select); - if (orm.where) { - if (Array.isArray(orm.where)) { - q.where(typeof orm.where[0] === "string" ? [ormWhere, "AND", orm.where] : orm.where.concat(["AND", ormWhere])); + if (orm.limit !== undefined) { + q.limit(orm.limit); } - else { - q.where(function (r, idx) { - return (isArray ? row[orm.key].indexOf(r[otherPK_1]) !== -1 : row[orm.key] === r[otherPK_1]) && orm.where(r, idx); - }); + if (orm.offset !== undefined) { + q.offset(orm.offset); } - } - else { - q.where(ormWhere); - } - if (orm.limit !== undefined) { - q.limit(orm.limit); - } - if (orm.offset !== undefined) { - q.offset(orm.offset); - } - if (orm.orderBy) { - q.orderBy(orm.orderBy); - } - q.exec().then(function (rows) { - if (!rows.filter(function (r) { return r; }).length) { - row[orm.key] = isArray ? [] : undefined; + if (orm.orderBy) { + q.orderBy(orm.orderBy); } - else { - row[orm.key] = isArray ? rows.filter(function (r) { return r; }) : rows[0]; - } - ormResult(); + q.exec().then(function (result) { + if (!rows.filter(function (r) { return r; }).length) { + row[orm.key] = relateData._thisType === "array" ? [] : undefined; + } + else { + row[orm.key] = relateData._thisType === "array" ? rows.filter(function (r) { return r; }) : rows[0]; + } + ormResult(); + }); }); } else { @@ -877,7 +958,7 @@ var _where = function (singleRow, where, rowIDX, ignoreFirstPath) { }; var _compare = function (val1, compare, val2) { var setValue = function (val) { - return ["LIKE", "NOT LIKE"].indexOf(compare) > 0 ? String(val || "").toLowerCase() : val; + return ["LIKE", "NOT LIKE"].indexOf(compare) > -1 ? String(val || "").toLowerCase() : val; }; var columnValue = setValue(val2); var givenValue = setValue(val1); @@ -897,7 +978,7 @@ var _compare = function (val1, compare, val2) { case ">=": return columnValue >= givenValue ? 0 : 1; case "IN": return (givenValue || []).indexOf(columnValue) < 0 ? 1 : 0; case "NOT IN": return (givenValue || []).indexOf(columnValue) < 0 ? 0 : 1; - case "REGEX": return columnValue.search(givenValue) < 0 ? 1 : 0; + case "REGEX": return columnValue.match(givenValue) ? 0 : 1; case "LIKE": return columnValue.indexOf(givenValue) < 0 ? 1 : 0; case "NOT LIKE": return columnValue.indexOf(givenValue) > 0 ? 1 : 0; case "BETWEEN": return givenValue[0] <= columnValue && givenValue[1] >= columnValue ? 0 : 1; diff --git a/lib/database/storage.d.ts b/lib/database/storage.d.ts index 7c60fa70..98288dba 100644 --- a/lib/database/storage.d.ts +++ b/lib/database/storage.d.ts @@ -45,6 +45,28 @@ export declare class _NanoSQLStorage { }; _nsql: NanoSQLInstance; private _size; + _relFromTable: { + [tableName: string]: { + [thisColmn: string]: { + _toTable: string; + _toColumn: string; + _toType: "array" | "single"; + _thisType: "array" | "single"; + }; + }; + }; + _relToTable: { + [tableName: string]: { + _thisColumn: string; + _thisType: "array" | "single"; + _fromTable: string; + _fromColumn: string; + _fromType: "array" | "single"; + }[]; + }; + _relationColumns: { + [tableName: string]: string[]; + }; constructor(parent: NanoSQLInstance, args: { mode: string | NanoSQLStorageAdapter; id: string; diff --git a/lib/database/storage.js b/lib/database/storage.js index beddf3f0..2fc25f15 100644 --- a/lib/database/storage.js +++ b/lib/database/storage.js @@ -72,6 +72,49 @@ var _NanoSQLStorage = (function () { this._tableNames.forEach(function (table) { _this._newTable(table, dataModels[table]); }); + this._relFromTable = {}; + this._relToTable = {}; + this._relationColumns = {}; + this._tableNames.forEach(function (table) { + var i = _this.models[table].length; + _this._relFromTable[table] = {}; + _this._relationColumns[table] = []; + _this._relToTable[table] = []; + var _loop_1 = function () { + var p = _this.models[table][i]; + if (p.props && _this._tableNames.indexOf(p.type.replace("[]", "")) !== -1) { + var mapTo_1 = ""; + p.props.forEach(function (p) { + if (p.indexOf("ref=>") !== -1) + mapTo_1 = p.replace("ref=>", ""); + }); + if (mapTo_1) { + _this._relationColumns[table].push(p.key); + _this._relFromTable[table][p.key] = { + _toTable: p.type.replace("[]", ""), + _toColumn: mapTo_1.replace("[]", ""), + _toType: mapTo_1.indexOf("[]") === -1 ? "single" : "array", + _thisType: p.type.indexOf("[]") === -1 ? "single" : "array" + }; + } + } + }; + while (i--) { + _loop_1(); + } + }); + Object.keys(this._relFromTable).forEach(function (table) { + Object.keys(_this._relFromTable[table]).forEach(function (column) { + var rel = _this._relFromTable[table][column]; + _this._relToTable[rel._toTable].push({ + _thisColumn: rel._toColumn, + _thisType: rel._toType, + _fromTable: table, + _fromColumn: column, + _fromType: rel._thisType + }); + }); + }); this._adapter.connect(function () { new utilities_1.ALL(Object.keys(_this._trieIndexes).map(function (table) { return function (tableDone) { diff --git a/lib/history-plugin.js b/lib/history-plugin.js index b3f82281..89bde805 100644 --- a/lib/history-plugin.js +++ b/lib/history-plugin.js @@ -8,7 +8,7 @@ var __assign = (this && this.__assign) || Object.assign || function(t) { }; Object.defineProperty(exports, "__esModule", { value: true }); var utilities_1 = require("./utilities"); -var strs = ["_hist", "_hist_ptr"]; +var strs = ["_hist", "_hist_ptr", "_id"]; var _NanoSQLHistoryPlugin = (function () { function _NanoSQLHistoryPlugin(historyModeArgs) { this.historyModeArgs = historyModeArgs; @@ -361,8 +361,8 @@ var _NanoSQLHistoryPlugin = (function () { _this.parent.table("_" + table + "__hist_rows").query("select").where(["_id", "IN", getRows]).exec().then(function (resultRows) { var rObj = {}; resultRows.forEach(function (row) { - rObj[row._id] = Object.isFrozen(row) ? utilities_1._assign(row) : row; - delete rObj[row._id]._id; + rObj[row[strs[2]]] = Object.isFrozen(row) ? utilities_1._assign(row) : row; + delete rObj[row[strs[2]]][strs[2]]; }); complete([{ pointer: rows[0].histRows.length - rows[0].histPtr - 1, diff --git a/lib/index.d.ts b/lib/index.d.ts index 80679628..92e5e73a 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -55,24 +55,14 @@ export declare class NanoSQLInstance { sTable: string | any[]; private _config; _plugins: NanoSQLPlugin[]; + version: number; + _instanceBackend: NanoSQLPlugin; static functions: { [fnName: string]: NanoSQLFunction; }; data: any; _hasEvents: StdObject; _tableNames: string[]; - relations: { - [tableName: string]: { - toTable: string; - column: string; - toColumn: string; - type: "array" | "single"; - toType: "array" | "single" | ""; - }[]; - }; - relationColumns: { - [tableName: string]: string[]; - }; private _callbacks; constructor(); table(table?: string): NanoSQLInstance; diff --git a/lib/index.js b/lib/index.js index e72446e3..4a3dd056 100644 --- a/lib/index.js +++ b/lib/index.js @@ -16,6 +16,7 @@ var index_1 = require("./database/index"); var history_plugin_1 = require("./history-plugin"); var NanoSQLInstance = (function () { function NanoSQLInstance() { + this.version = 1; var t = this; t._actions = {}; t._views = {}; @@ -26,6 +27,22 @@ var NanoSQLInstance = (function () { t._plugins = []; t._callbacks = {}; t._callbacks["*"] = new really_small_events_1.ReallySmallEvents(); + t._instanceBackend = new index_1.NanoSQLDefaultBackend(); + var instanceConnectArgs = { + models: {}, + actions: {}, + views: {}, + config: {}, + parent: this + }; + if (t._instanceBackend.willConnect) { + t._instanceBackend.willConnect(instanceConnectArgs, function () { + if (t._instanceBackend.didConnect) { + t._instanceBackend.didConnect(instanceConnectArgs, function () { + }); + } + }); + } } NanoSQLInstance.prototype.table = function (table) { if (table) @@ -43,6 +60,10 @@ var NanoSQLInstance = (function () { config: t._config, parent: _this, }; + connectArgs.models["_util"] = [ + { key: "key", type: "string", props: ["pk", "ai"] }, + { key: "value", type: "any" } + ]; if (t._config && t._config.history) { _this.use(new history_plugin_1._NanoSQLHistoryPlugin(t._config.historyMode)); } @@ -66,57 +87,37 @@ var NanoSQLInstance = (function () { _this._actions = connectArgs.actions; _this._views = connectArgs.views; _this._config = connectArgs.config; - _this.relations = {}; - _this.relationColumns = {}; t._tableNames = Object.keys(_this._models); - t._tableNames.forEach(function (table) { - var i = _this._models[table].length; - _this.relations[table] = []; - _this.relationColumns[table] = []; - var _loop_1 = function () { - var p = _this._models[table][i]; - if (p.props && _this._tableNames.indexOf(p.type.replace("[]", "")) !== -1) { - var mapTo_1 = ""; - p.props.forEach(function (p) { - if (p.indexOf("ref=>") !== -1) - mapTo_1 = p.replace("ref=>", ""); - }); - _this.relationColumns[table].push(p.key); - _this.relations[table].push({ - column: p.key, - toTable: p.type.replace("[]", ""), - toColumn: mapTo_1, - type: p.type.indexOf("[]") === -1 ? "single" : "array", - toType: mapTo_1 ? Object.keys(_this._models).reduce(function (prev, cur) { - if (cur === p.type.replace("[]", "")) { - return _this._models[cur].reduce(function (p, c) { - if (c.key === mapTo_1) { - return c.type.indexOf("[]") !== -1 ? "array" : "single"; - } - return p; - }, ""); - } - return prev; - }, "") : "" + var oldTable = _this.sTable; + var completeConnect = function () { + _this.table(oldTable); + new utilities_1.ALL(_this._plugins.map(function (p) { + return function (nextP) { + if (p.didConnect) { + p.didConnect(connectArgs, function () { + nextP(); + }); + } + else { + nextP(); + } + }; + })).then(function () { + res(_this.table); + }); + }; + _this.table("_util").query("select").where(["key", "=", "version"]).exec().then(function (rows) { + if (!rows.length) { + _this.table("_util").query("upsert", { key: "version", value: _this.version }).exec().then(function () { + _this.extend("rebuild_idx").then(function () { + completeConnect(); }); - } - }; - while (i--) { - _loop_1(); + }); + } + else { + completeConnect(); } }); - new utilities_1.ALL(_this._plugins.map(function (p) { - return function (nextP) { - if (p.didConnect) { - p.didConnect(connectArgs, function () { - nextP(); - }); - } - else { - nextP(); - } - }; - })).then(res); }); }); }; diff --git a/lib/query/std-query.d.ts b/lib/query/std-query.d.ts index fb29dbbc..b3e70882 100644 --- a/lib/query/std-query.d.ts +++ b/lib/query/std-query.d.ts @@ -34,7 +34,7 @@ export declare class _NanoSQLQuery { _error: string; _AV: string; private _query; - constructor(table: string | any[], db: NanoSQLInstance, queryAction: string, queryArgs?: any, actionOrView?: string, bypassORMPurge?: boolean); + constructor(table: string | any[], db: NanoSQLInstance, queryAction: string, queryArgs?: any, actionOrView?: string, bypassORM?: boolean); where(args: any[] | any): _NanoSQLQuery; range(limit: number, offset: number): _NanoSQLQuery; orm(ormArgs?: (string | ORMArgs)[]): _NanoSQLQuery; @@ -48,7 +48,6 @@ export declare class _NanoSQLQuery { join(args: JoinArgs): _NanoSQLQuery; limit(args: number): _NanoSQLQuery; trieSearch(column: string, stringToSearch: string): _NanoSQLQuery; - ormSync(columns?: string[]): this; comment(comment: string): _NanoSQLQuery; extend(...args: any[]): _NanoSQLQuery; offset(args: number): _NanoSQLQuery; diff --git a/lib/query/std-query.js b/lib/query/std-query.js index 8fed096b..a371ec5b 100644 --- a/lib/query/std-query.js +++ b/lib/query/std-query.js @@ -10,7 +10,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); var utilities_1 = require("../utilities"); var lie_ts_1 = require("lie-ts"); var _NanoSQLQuery = (function () { - function _NanoSQLQuery(table, db, queryAction, queryArgs, actionOrView, bypassORMPurge) { + function _NanoSQLQuery(table, db, queryAction, queryArgs, actionOrView, bypassORM) { this._db = db; this._AV = actionOrView || ""; this._query = { @@ -89,10 +89,6 @@ var _NanoSQLQuery = (function () { this._query.trie = { column: column, search: stringToSearch }; return this; }; - _NanoSQLQuery.prototype.ormSync = function (columns) { - this._query.ormSync = columns || []; - return this; - }; _NanoSQLQuery.prototype.comment = function (comment) { this._query.comments.push(comment); return this; @@ -140,6 +136,14 @@ var _NanoSQLQuery = (function () { var _this = this; var t = this; return new lie_ts_1.Promise(function (res, rej) { + if (Array.isArray(_this._query.table)) { + if (_this._db._instanceBackend.doExec) { + _this._db._instanceBackend.doExec(_this._query, function (q) { + res(q.result); + }); + } + return; + } if (!t._db._plugins.length) { t._error = "No plugins, nothing to do!"; } diff --git a/src/database/index.ts b/src/database/index.ts index b6904dc3..2ae367f9 100644 --- a/src/database/index.ts +++ b/src/database/index.ts @@ -3,6 +3,7 @@ import { IdbQuery } from "../query/std-query"; import { NanoSQLPlugin, DBConnect, NanoSQLInstance } from "../index"; import { _NanoSQLStorage } from "./storage"; import { _NanoSQLStorageQuery } from "./query"; +import { ALL } from "../utilities"; declare var global: any; @@ -46,6 +47,7 @@ export class NanoSQLDefaultBackend implements NanoSQLPlugin { next(); } */ + public extend(next: (args: any[], result: any[]) => void, args: any[], result: any[]): void { switch (args[0]) { case "idx.length": @@ -60,9 +62,30 @@ export class NanoSQLDefaultBackend implements NanoSQLPlugin { } break; case "rebuild_idx": - this._store.rebuildIndexes(args[1], (time) => { - next(args, [time]); - }); + if (args[1]) { + this._store.rebuildIndexes(args[1], (time) => { + next(args, [time]); + }); + } else { + new ALL(Object.keys(this._store.tableInfo).map((table) => { + return (done) => { + this._store.rebuildIndexes(table, done); + }; + })).then((times) => { + next(args, times); + }); + } + + break; + case "clear_cache": + if (args[1]) { + this._store._cache[args[1]] = {}; + } else { + Object.keys(this._store.tableInfo).forEach((table) => { + this._store._cache[table] = {}; + }); + } + next(args, args[1] || Object.keys(this._store.tableInfo)); break; default: next(args, result); diff --git a/src/database/query.ts b/src/database/query.ts index e7f9592c..7284feca 100644 --- a/src/database/query.ts +++ b/src/database/query.ts @@ -136,6 +136,136 @@ export class _NanoSQLStorageQuery { }); } + private _updateORMRows(relation: { + _thisColumn: string; + _thisType: "array" | "single"; + _fromTable: string; + _fromColumn: string; + _fromType: "array" | "single"; + }, fromPKs: any[], add: boolean, primaryKey: any, complete: () => void) { + this._store._nsql.table(relation._fromTable).query("select").where([this._store.tableInfo[relation._fromTable]._pk, "IN", fromPKs]).exec().then((rows) => { + new ALL(rows.map((row) => { + return (rowDone) => { + row = Object.isFrozen(row) ? _assign(row) : row; + + if (relation._fromType === "array") { + row[relation._fromColumn] = row[relation._fromColumn] || []; + if (add) { // add + row[relation._fromColumn].push(primaryKey); + } else { // remove + const idxOf = row[relation._fromColumn].indexOf(primaryKey); + if (idxOf !== -1) { + row[relation._fromColumn].splice(idxOf, 1); + } + } + row[relation._fromColumn].sort(); + } else { + if (add) { // add + row[relation._fromColumn] = primaryKey; + } else { // remove + row[relation._fromColumn] = undefined; + } + } + this._store._nsql.table(relation._fromTable).query("upsert", row).exec().then(rowDone); + }; + })).then(complete); + }); + } + + private _syncORM(type: "del"|"add", oldRows: DBRow[], newRows: DBRow[], complete: () => void) { + + const useRelations = this._store._relToTable[this._query.table as string]; + + if (!useRelations || !useRelations.length) { + complete(); + return; + } + + // go over every relation and every changed row to make the needed updates. + let cnt = Math.max(oldRows.length, newRows.length); + let arra: any[] = []; + while (cnt--) arra.push(" "); + new CHAIN(arra.map((v, idx) => { + return (rowDone) => { + + new ALL(useRelations.map((relation) => { + return (relationDone) => { + + const equals = (val1, val2) => { + if (Array.isArray(val1) && Array.isArray(val2)) { + return val1.filter((v, i) => v !== val2[i]).length > 0; + } else { + return val1 === val2; + } + }; + + switch (type) { + case "del": + const delPrimarykey = oldRows[idx][this._store.tableInfo[this._query.table as any]._pk]; + const updateIDs = relation._thisType === "array" ? (oldRows[idx][relation._thisColumn] || []) : ([oldRows[idx][relation._thisColumn]].filter(v => v)); + this._updateORMRows(relation, updateIDs, false, delPrimarykey, relationDone); + break; + case "add": + const primaryKey = newRows[idx][this._store.tableInfo[this._query.table as any]._pk]; + // possibly update existing relation + // if adding oldRows[idx] is possibly undefined (if theres no previouse row record) + if (oldRows[idx]) { + // previouse record exists + if (equals(oldRows[idx][relation._thisColumn], newRows[idx][relation._thisColumn])) { + // no update needed + relationDone(); + } else { + if (relation._thisType === "array") { + + const addIds = (newRows[idx][relation._thisColumn] || []).filter(v => (oldRows[idx][relation._thisColumn] || []).indexOf(v) === -1); + const removeIds = (oldRows[idx][relation._thisColumn] || []).filter(v => (newRows[idx][relation._thisColumn] || []).indexOf(v) === -1); + + new ALL([addIds, removeIds].map((list, i) => { + return (done) => { + this._updateORMRows(relation, list, i === 0, primaryKey, done); + }; + })).then(relationDone); + + } else { + + const addRelation = () => { + // add new relation + if (newRows[idx][relation._thisColumn] !== undefined) { + this._updateORMRows(relation, [newRows[idx][relation._thisColumn]], true, primaryKey, relationDone); + } else { + // no new relation + relationDone(); + } + }; + + // remove old connection + if (oldRows[idx][relation._thisColumn] !== undefined) { + this._updateORMRows(relation, [oldRows[idx][relation._thisColumn]], false, primaryKey, addRelation); + } else { + // no old connection, just add the new one + addRelation(); + } + + } + } + } else { // new relation + const valuesToAdd = relation._thisType === "array" ? (newRows[idx][relation._thisColumn] || []) : ([newRows[idx][relation._thisColumn]].filter(v => v)); + if (valuesToAdd && valuesToAdd.length) { + this._updateORMRows(relation, valuesToAdd, true, primaryKey, relationDone); + } else { + relationDone(); + } + } + break; + } + }; + })).then(rowDone); + }; + })).then(complete); + + + } + /** * Initilize an UPSERT query. * @@ -167,18 +297,20 @@ export class _NanoSQLStorageQuery { if (this._query.where) { // has where statement, select rows then modify them this._getRows((rows) => { - // rows = rows.filter(r => r); if (rows.length) { new CHAIN(rows.map((r) => { return (rowDone) => { this._store._write(this._query.table as any, r[pk], r, this._query.actionArgs || {}, rowDone); }; - })).then((rows) => { - let result = [].concat.apply([], rows); + })).then((newRows: DBRow[]) => { + // any changes to this table invalidates the cache this._store._cache[this._query.table as any] = {}; - this._query.result = [{ msg: rows.length + " row(s) modfied.", affectedRowPKS: result.map(r => r[pk]), affectedRows: result }]; - next(this._query); + + this._query.result = [{ msg: newRows.length + " row(s) modfied.", affectedRowPKS: newRows.map(r => r[pk]), affectedRows: newRows }]; + this._syncORM("add", rows, newRows, () => { + next(this._query); + }); }); } else { this._query.result = [{ msg: "0 row(s) modfied.", affectedRowPKS: [], affectedRows: [] }]; @@ -192,7 +324,9 @@ export class _NanoSQLStorageQuery { const write = (oldRow: any) => { this._store._write(this._query.table as any, row[pk], oldRow, row, (result) => { this._query.result = [{ msg: "1 row inserted.", affectedRowPKS: [result[pk]], affectedRows: [result] }]; - next(this._query); + this._syncORM("add", [oldRow].filter(r => r), [result], () => { + next(this._query); + }); }); }; @@ -248,9 +382,14 @@ export class _NanoSQLStorageQuery { this._store._delete(this._query.table as any, r[this._store.tableInfo[this._query.table as any]._pk], done); }; })).then((affectedRows) => { + // any changes to this table invalidate the cache this._store._cache[this._query.table as any] = {}; + + this._query.result = [{ msg: rows.length + " row(s) deleted.", affectedRowPKS: rows.map(r => r[this._store.tableInfo[this._query.table as any]._pk]), affectedRows: rows }]; - next(this._query); + this._syncORM("del", rows, [], () => { + next(this._query); + }); }); } else { this._query.result = [{ msg: "0 row(s) deleted.", affectedRowPKS: [], affectedRows: [] }]; @@ -278,21 +417,15 @@ export class _NanoSQLStorageQuery { return; } - let rows = []; - - const doDrop = (rows) => { + this._store._rangeReadIDX(this._query.table as string, undefined as any, undefined as any, (rows) => { this._store._cache[this._query.table as any] = {}; this._store._drop(this._query.table as any, () => { this._query.result = [{ msg: "'" + this._query.table as any + "' table dropped.", affectedRowPKS: rows.map(r => r[this._store.tableInfo[this._query.table as any]._pk]), affectedRows: rows }]; - next(this._query); + this._syncORM("del", rows, [], () => { + next(this._query); + }); }); - }; - - if (this._query.transaction) { - doDrop([]); - } else { - this._store._rangeReadIDX(this._query.table as string, undefined as any, undefined as any, doDrop); - } + }); } } @@ -484,19 +617,6 @@ export class _MutateSelection { }); } - /** - * Cache relationships between tables to reduce ORM query cost. - * - * @internal - * @type {{ - * [key: string]: any[]; - * }} - * @memberof _MutateSelection - */ - private _ormTableCache: { - [key: string]: any[]; - } = {}; - /** * Add ORM values to rows based on query. * @@ -521,62 +641,35 @@ export class _MutateSelection { return (rowResult) => { new ALL(ormQueries.map((orm) => { return (ormResult) => { - if (row[orm.key] === undefined || row[orm.key] === null) { + if (!row[orm.key] || !row[orm.key].length) { ormResult(); return; } - let isArray = false; - const cacheKey = this.q.table + "-" + orm.key; - let otherTable: string = ""; - if (this._ormTableCache[cacheKey]) { - otherTable = this._ormTableCache[cacheKey][0]; - isArray = this._ormTableCache[cacheKey][1]; - } else { - otherTable = this.s.models[this.q.table as any].reduce((prev, cur) => { - if (cur.props && cur.props.length) { - if (cur.key === orm.key) { - isArray = cur.type.indexOf("[]") > -1; - return cur.type.replace("[]", ""); - } - } - return prev; - }, ""); - this._ormTableCache[cacheKey] = [otherTable, isArray]; - } + const relateData = this.s._relFromTable[this.q.table as string][orm.key]; - if (otherTable) { - const otherPK = this.s.tableInfo[otherTable]._pk; - const ormWhere = [otherPK, (isArray ? "IN" : "="), row[orm.key]]; - - const q = this.s._nsql.table(otherTable) - .query("select", orm.select); - if (orm.where) { - if (Array.isArray(orm.where)) { // array where statement [something, =, whatever] - q.where(typeof orm.where[0] === "string" ? [ormWhere, "AND", orm.where] : orm.where.concat(["AND", ormWhere])); - } else { // function where statement - q.where((r, idx) => { - return (isArray ? row[orm.key].indexOf(r[otherPK]) !== -1 : row[orm.key] === r[otherPK]) && (orm.where as any)(r, idx); - }); + if (relateData) { + this.s._nsql.table(relateData._toTable).query("select").where([this.s.tableInfo[relateData._toTable]._pk, relateData._thisType === "array" ? "IN" : "=", row[orm.key]]).exec().then((rows) => { + const q = this.s._nsql.table(rows).query("select", orm.select); + if (orm.where) { + q.where(orm.where); } - } else { - q.where(ormWhere); - } - if (orm.limit !== undefined) { - q.limit(orm.limit); - } - if (orm.offset !== undefined) { - q.offset(orm.offset); - } - if (orm.orderBy) { - q.orderBy(orm.orderBy); - } - q.exec().then((rows) => { - if (!rows.filter(r => r).length) { - row[orm.key] = isArray ? [] : undefined; - } else { - row[orm.key] = isArray ? rows.filter(r => r) : rows[0]; + if (orm.limit !== undefined) { + q.limit(orm.limit); + } + if (orm.offset !== undefined) { + q.offset(orm.offset); } - ormResult(); + if (orm.orderBy) { + q.orderBy(orm.orderBy); + } + q.exec().then((result) => { + if (!rows.filter(r => r).length) { + row[orm.key] = relateData._thisType === "array" ? [] : undefined; + } else { + row[orm.key] = relateData._thisType === "array" ? rows.filter(r => r) : rows[0]; + } + ormResult(); + }); }); } else { ormResult(); @@ -1272,7 +1365,7 @@ const _where = (singleRow: any, where: any[], rowIDX: number, ignoreFirstPath?: const _compare = (val1: any, compare: string, val2: any): number => { const setValue = (val: any) => { - return ["LIKE", "NOT LIKE"].indexOf(compare) > 0 ? String(val || "").toLowerCase() : val; + return ["LIKE", "NOT LIKE"].indexOf(compare) > -1 ? String(val || "").toLowerCase() : val; }; const columnValue = setValue(val2); @@ -1304,7 +1397,7 @@ const _compare = (val1: any, compare: string, val2: any): number => { // if column does not exist in given array case "NOT IN": return (givenValue || []).indexOf(columnValue) < 0 ? 0 : 1; // regexp search the column - case "REGEX": return columnValue.search(givenValue) < 0 ? 1 : 0; + case "REGEX": return columnValue.match(givenValue) ? 0 : 1; // if given value exists in column value case "LIKE": return columnValue.indexOf(givenValue) < 0 ? 1 : 0; // if given value does not exist in column value diff --git a/src/database/storage.ts b/src/database/storage.ts index 8f6497aa..3a73686d 100644 --- a/src/database/storage.ts +++ b/src/database/storage.ts @@ -121,7 +121,7 @@ export interface NanoSQLStorageAdapter { * @param {(count: number) => void} complete * @memberof NanoSQLStorageAdapter */ - getIndex(table: string, getLength: boolean, complete: (index: any[]|number) => void): void; + getIndex(table: string, getLength: boolean, complete: (index: any[] | number) => void): void; /** * Completely delete/destroy the entire database. @@ -233,6 +233,66 @@ export class _NanoSQLStorage { private _size: number; + /** + * Given a table, keep track of all ORM references pointing FROM that table. + * + * @type {({ + * [tableName: string]: { // Relations with this table + * _table: string // other table + * _key: string // this column + * _mapTo: string // other column + * _type: "array" | "single" // type of relation + * }[]; + * })} + * @memberof NanoSQLInstance + */ + public _relFromTable: { + [tableName: string]: { + [thisColmn: string]: { // Relations with this table + _toTable: string // other table + _toColumn: string // other column + _toType: "array" | "single" // other column type + _thisType: "array" | "single" // type of relation, + }; + } + }; + + + /** + * Given a table, keep track of all ORM references pointing TO that table. + * + * @type {({ + * [tableName: string]: { + * thisColumn: string; + * fromTable: string; + * fromColumn: string; + * fromType: "array" | "single" + * }[] + * })} + * @memberof NanoSQLInstance + */ + public _relToTable: { + [tableName: string]: { + _thisColumn: string; + _thisType: "array" | "single"; + _fromTable: string; + _fromColumn: string; + _fromType: "array" | "single"; + }[] + }; + + /** + * Stores which columns are used for ORM stuff. + * + * @type {{ + * [tableName: string]: string[]; + * }} + * @memberof NanoSQLInstance + */ + public _relationColumns: { + [tableName: string]: string[]; + }; + constructor(parent: NanoSQLInstance, args: { mode: string | NanoSQLStorageAdapter; // pass in string or adapter class. id: string; // id of database @@ -316,6 +376,55 @@ export class _NanoSQLStorage { this._newTable(table, dataModels[table]); }); + this._relFromTable = {}; + this._relToTable = {}; + this._relationColumns = {}; + + this._tableNames.forEach((table) => { + + let i = this.models[table].length; + this._relFromTable[table] = {}; + this._relationColumns[table] = []; + this._relToTable[table] = []; + + while (i--) { + const p = this.models[table][i]; + + // Check for relations + if (p.props && this._tableNames.indexOf(p.type.replace("[]", "")) !== -1) { + let mapTo = ""; + p.props.forEach(p => { + if (p.indexOf("ref=>") !== -1) mapTo = p.replace("ref=>", ""); + }); + + if (mapTo) { + this._relationColumns[table].push(p.key); + + this._relFromTable[table][p.key] = { + _toTable: p.type.replace("[]", ""), + _toColumn: mapTo.replace("[]", ""), + _toType: mapTo.indexOf("[]") === -1 ? "single" : "array", + _thisType: p.type.indexOf("[]") === -1 ? "single" : "array" + }; + } + } + } + + }); + + Object.keys(this._relFromTable).forEach((table) => { + Object.keys(this._relFromTable[table]).forEach((column) => { + const rel = this._relFromTable[table][column]; + this._relToTable[rel._toTable].push({ + _thisColumn: rel._toColumn, + _thisType: rel._toType, + _fromTable: table, + _fromColumn: column, + _fromType: rel._thisType + }); + }); + }); + this._adapter.connect(() => { // populate trie data @@ -511,7 +620,7 @@ export class _NanoSQLStorage { * @returns * @memberof _NanoSQLStorage */ - public _read(table: string, query: (row: DBRow, idx: number, toKeep: (result: boolean) => void) => void|any[], callback: (rows: DBRow[]) => void) { + public _read(table: string, query: (row: DBRow, idx: number, toKeep: (result: boolean) => void) => void | any[], callback: (rows: DBRow[]) => void) { if (Array.isArray(query)) { // select by array of primary keys new ALL(query.map((q) => { diff --git a/src/history-plugin.ts b/src/history-plugin.ts index 92c6ba54..32eaed50 100644 --- a/src/history-plugin.ts +++ b/src/history-plugin.ts @@ -20,10 +20,8 @@ interface HistoryRowMeta { histPtr: number; } -// const hist = "_hist"; -// const histPtr = "_hist_ptr"; - -const strs = ["_hist", "_hist_ptr"]; +// uglifyJS workaround +const strs = ["_hist", "_hist_ptr", "_id"]; /** * New History Plugin @@ -501,8 +499,8 @@ export class _NanoSQLHistoryPlugin implements NanoSQLPlugin { this.parent.table("_" + table + "__hist_rows").query("select").where(["_id", "IN", getRows]).exec().then((resultRows: any[]) => { const rObj = {}; resultRows.forEach((row) => { - rObj[row._id] = Object.isFrozen(row) ? _assign(row) : row; - delete rObj[row._id]._id; + rObj[row[strs[2]]] = Object.isFrozen(row) ? _assign(row) : row; + delete rObj[row[strs[2]]][strs[2]]; }); complete([{ pointer: rows[0].histRows.length - rows[0].histPtr - 1, diff --git a/src/index.ts b/src/index.ts index 8f717584..904ce65e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,5 @@ import { Promise, setFast } from "lie-ts"; import { _NanoSQLQuery, IdbQuery } from "./query/std-query"; -// import { _NanoSQLORMQuery } from "./query/orm-query"; import { _NanoSQLTransactionQuery } from "./query/transaction"; import { ReallySmallEvents } from "really-small-events"; import { StdObject, _assign, CHAIN, ALL, random16Bits, cast, cleanArgs, objQuery } from "./utilities"; @@ -136,6 +135,10 @@ export class NanoSQLInstance { public _plugins: NanoSQLPlugin[]; + public version: number = 1; + + public _instanceBackend: NanoSQLPlugin; + public static functions: { [fnName: string]: NanoSQLFunction; }; @@ -214,42 +217,6 @@ export class NanoSQLInstance { */ public _tableNames: string[]; - - /** - * Stores the relations between tables. - * - * @type {({ - * [tableName: string]: { // Relations with this table - * _table: string // other table - * _key: string // this column - * _mapTo: string // other column - * _type: "array" | "single" // type of relation - * }[]; - * })} - * @memberof NanoSQLInstance - */ - public relations: { - [tableName: string]: { // Relations with this table - toTable: string // other table - column: string // this column - toColumn: string // other column - type: "array" | "single" // type of relation, - toType: "array" | "single" | "" // type of relation this points to - }[]; - }; - - /** - * Stores which columns are used for ORM stuff. - * - * @type {{ - * [tableName: string]: string[]; - * }} - * @memberof NanoSQLInstance - */ - public relationColumns: { - [tableName: string]: string[]; - }; - private _callbacks: { [table: string]: ReallySmallEvents; }; @@ -268,6 +235,23 @@ export class NanoSQLInstance { t._callbacks = {}; t._callbacks["*"] = new ReallySmallEvents(); + t._instanceBackend = new NanoSQLDefaultBackend(); + const instanceConnectArgs: DBConnect = { + models: {}, + actions: {}, + views: {}, + config: {}, + parent: this + }; + if (t._instanceBackend.willConnect) { + t._instanceBackend.willConnect(instanceConnectArgs, () => { + if (t._instanceBackend.didConnect) { + t._instanceBackend.didConnect(instanceConnectArgs, () => { + + }); + } + }); + } } @@ -307,6 +291,11 @@ export class NanoSQLInstance { parent: this, }; + connectArgs.models["_util"] = [ + {key: "key", type: "string", props: ["pk", "ai"]}, + {key: "value", type: "any"} + ]; + // if history is enabled, turn on the built in history plugin if (t._config && t._config.history) { this.use(new _NanoSQLHistoryPlugin(t._config.historyMode)); @@ -333,62 +322,42 @@ export class NanoSQLInstance { this._actions = connectArgs.actions; this._views = connectArgs.views; this._config = connectArgs.config; - this.relations = {}; - this.relationColumns = {}; t._tableNames = Object.keys(this._models); - t._tableNames.forEach((table) => { - - let i = this._models[table].length; - this.relations[table] = []; - this.relationColumns[table] = []; - - while (i--) { - const p = this._models[table][i]; + const oldTable: any = this.sTable; - // Check for relations - if (p.props && this._tableNames.indexOf(p.type.replace("[]", "")) !== -1) { - let mapTo = ""; - p.props.forEach(p => { - if (p.indexOf("ref=>") !== -1) mapTo = p.replace("ref=>", ""); - }); + const completeConnect = () => { + this.table(oldTable as any); + new ALL(this._plugins.map((p) => { + return (nextP) => { + if (p.didConnect) { + p.didConnect(connectArgs, () => { + nextP(); + }); + } else { + nextP(); + } + }; + })).then(() => { + res(this.table); + }); + }; - this.relationColumns[table].push(p.key); - - this.relations[table].push({ - column: p.key, - toTable: p.type.replace("[]", ""), - toColumn: mapTo, - type: p.type.indexOf("[]") === -1 ? "single" : "array", - toType: mapTo ? Object.keys(this._models).reduce((prev, cur) => { - if (cur === p.type.replace("[]", "")) { - return this._models[cur].reduce((p, c) => { - if (c.key === mapTo) { - return c.type.indexOf("[]") !== -1 ? "array" : "single" as any; - } - return p; - }, ""); - } - return prev; - }, "") : "" + this.table("_util").query("select").where(["key", "=", "version"]).exec().then((rows) => { + if (!rows.length) { + // new database or an old one that needs indexes rebuilt + this.table("_util").query("upsert", {key: "version", value: this.version}).exec().then(() => { + this.extend("rebuild_idx").then(() => { + completeConnect(); }); - } + }); + } else { + // future migration messes go here + completeConnect(); } - }); - new ALL(this._plugins.map((p) => { - return (nextP) => { - if (p.didConnect) { - p.didConnect(connectArgs, () => { - nextP(); - }); - } else { - nextP(); - } - }; - })).then(res); }); }); } @@ -744,21 +713,6 @@ export class NanoSQLInstance { return query; } - /** - * Update relational ORM data. - * - * @param {("add"|"delete"|"drop"|"rebuild"|"set")} action - * @param {string} column - * @param {any[]} [relationIDs] - * @returns - * - * @memberof NanoSQLInstance - */ - /*public updateORM(action: "add" | "delete" | "drop" | "rebuild" | "set", column?: string, relationIDs?: any[]): _NanoSQLORMQuery { - if (Array.isArray(this.sTable)) return null as any; - return new _NanoSQLORMQuery(this, this.sTable, action, column, relationIDs); - }*/ - /** * Trigger a database event * diff --git a/src/query/orm-query.ts b/src/query/orm-query.ts deleted file mode 100644 index 3428b2ff..00000000 --- a/src/query/orm-query.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { NanoSQLInstance, ORMArgs, JoinArgs, DatabaseEvent, DataModel } from "../index"; -import { CHAIN, _assign, StdObject, uuid, cast, ALL } from "../utilities"; -import { Promise, setFast } from "lie-ts"; -import { DBRow } from "../database/storage"; - -// tslint:disable-next-line -export class _NanoSQLORMQuery { - - private _db: NanoSQLInstance; - private _tableName: string; - private _action: "add" | "delete" | "drop" | "rebuild" | "set"; - private _column: string; - private _relationIDs: any[]; - private _whereArgs: any[]; - public _transactionID: number; - - constructor(db: NanoSQLInstance, table: string, action: "add" | "delete" | "drop" | "rebuild" | "set", column?: string, relationIDs?: any[]) { - this._db = db; - this._tableName = table; - this._action = action; - this._column = column || ""; - this._relationIDs = relationIDs || []; - } - - public where(args: any[]): this { - this._whereArgs = args; - return this; - } - - public rebuild(callBack: (updatedRows: number) => void): void { - let jobQue: DataModel[] = []; - - this._db._models[this._tableName].forEach((m) => { - if (this._db._tableNames.indexOf(m.key.replace("[]", "")) !== -1) { - jobQue.push(m); - } - }); - - new CHAIN(jobQue.map((j) => { - return (nextJ) => { - this._rebuildSingleRelation(this._tableName, j.key, nextJ); - }; - })).then(() => { - callBack(0); - }); - } - - private _rebuildSingleRelation(table: string, column: string, complete: () => void) { - const pk = this._tablePK(table); - const relatedColumn = this._getRelatedColumn(table, column); - const relatedTable = this._getRelatedTable(table, column); - - if (!relatedColumn || !relatedTable) { - complete(); // no ref=> set, can't automatically rebuid - return; - } - - const childRelateTable = this._getRelatedTable(relatedTable.table, relatedColumn); - let ptr = 0; - const loopRows = () => { - this._db.table(table).query("select").range(1, ptr).exec().then((rows) => { - if (rows.length && childRelateTable) { - const pk = rows[this._tablePK(table)]; - this._db.table(childRelateTable.table).query("select").where( - [relatedColumn, childRelateTable.isArray ? "HAVE" : "=", pk] as any - ).exec().then((childRows) => { - this._db.table(table).query("upsert", { - ...rows[0], - [column]: childRows.length ? relatedTable.isArray ? childRows.map(r => r[this._tablePK(childRelateTable.table)]) : childRows[0][this._tablePK(childRelateTable.table)] : null - }, true).exec().then(() => { - ptr++; - loopRows(); - }); - }); - } else { - complete(); - } - }); - }; - - loopRows(); - } - - private _tablePK(table: string) { - return this._db._models[table].reduce((prev, cur) => { - return cur.props && cur.props.indexOf("pk") !== -1 ? cur.key : prev; - }, ""); - } - - private _getRelatedColumn(table: string, column: string): string | null { - return this._db._models[table].reduce((prev, cur) => { - if (cur.key === column) { - return cur.props && cur.props.reduce((p, c) => { - return c.indexOf("ref=>") !== -1 ? c.replace("ref=>", "") : p; - }, null); - } - return prev; - }, null); - } - - private _getRelatedTable(table: string, column: string): { table: string, isArray: boolean } | null { - return this._db._models[table].reduce((prev, cur) => { - if (cur.key === column) { - return { - table: cur.type.replace("[]", ""), - isArray: cur.type.indexOf("[]") !== -1 - } as any; - } - return prev; - }, null); - } - - private _setRelationships(type: "rm" | "set" | "add", rows: DBRow[], column: string, setIds: string[], complete: () => void) { - - const pk = this._tablePK(this._tableName); - - const changedParentRecords: any[] = rows.map(r => r[pk]); - - const relatedColumn = this._getRelatedColumn(this._tableName, column); - const relatedTable = this._getRelatedTable(this._tableName, column); - - const cleanUp = () => { - this._updateRelatedRecords(type, changedParentRecords, relatedColumn, relatedTable, complete); - }; - - if (setIds.length) { - new ALL(rows.map((row) => { - return (doneRow) => { - - const setColumn = () => { - switch (type) { - case "rm": - return relatedTable && relatedTable.isArray ? - (row[column] || []).filter(id => setIds.indexOf(id) === -1) : // filter out remove ids from array relation - setIds.indexOf(row[column]) !== -1 ? null : row[column]; // set to NULL if it's a non array relation and a removeID exists - case "set": - return relatedTable && relatedTable.isArray ? setIds : setIds[0]; - case "add": - return relatedTable && relatedTable.isArray ? (row[column] || []).concat(setIds) : setIds[0]; - } - }; - - this._db.table(this._tableName).query("upsert", { - ...row, - [column]: setColumn() - }, true).exec().then(doneRow); - }; - })).then(cleanUp); - } else { - this._db.table(this._tableName).query("upsert", { - [column]: relatedTable && relatedTable.isArray ? [] : null - }, true).where([pk, "IN", rows.map(r => changedParentRecords)]).exec().then(cleanUp); - } - } - - private _updateRelatedRecords(type: "rm" | "set" | "add", changedParentRecords: any[], relatedColumn: string | null, relatedTable: { table: string, isArray: boolean } | null, complete: () => void) { - - let childRelateTable: { table: string, isArray: boolean } | null = null; - let childRleatePK: string; - if (relatedColumn && relatedTable) { - childRelateTable = this._getRelatedTable(relatedTable.table, relatedColumn); - } - - // if there's no ref=> then skip the related update - if (!relatedColumn || !relatedTable || !childRelateTable) { - complete(); - return; - } - - const compare = childRelateTable.isArray ? "HAVE" : "IN"; - - this._db.table(childRelateTable.table).query("select").where([relatedColumn, compare, changedParentRecords]).exec().then((rows) => { - new ALL(rows.map((r) => { - return (done) => { - if (!childRelateTable) return; - - const newColumn = () => { - if (!childRelateTable) return null; - switch (type) { - case "rm": - return childRelateTable.isArray ? r[relatedColumn].filter(i => changedParentRecords.indexOf(i) === -1) : null; - case "set": - case "add": - return childRelateTable.isArray ? r[relatedColumn].concat(changedParentRecords).filter((val, idx, self) => { - return self.indexOf(val) === idx; - }) : changedParentRecords[0]; - } - }; - - this._db.table(childRelateTable.table).query("upsert", { - ...r, - [relatedColumn]: newColumn() - }).exec().then(done); - }; - })).then(complete); - }); - - } - - public exec(): Promise { - - let t = this; - return new Promise((res, rej) => { - - if (t._action === "rebuild") { - return t.rebuild(res); - } - const q = t._db.table(t._tableName).query("select"); - if (t._whereArgs) { - q.where(t._whereArgs); - } - q.exec().then((rows: DBRow[]) => { - if (!rows.length) { - res([]); - return; - } - switch (this._action) { - case "set": - this._setRelationships("rm", rows, this._column, [], () => { // clear all existing relations - this._setRelationships("set", rows, this._column, this._relationIDs, () => { // set relations - res(); - }); - }); - break; - case "add": - this._setRelationships("add", rows, this._column, this._relationIDs, () => { // set relations - res(); - }); - break; - case "delete": - this._setRelationships("rm", rows, this._column, this._relationIDs, () => { - res(); - }); - break; - case "drop": - this._setRelationships("rm", rows, this._column, [], () => { - res(); - }); - break; - } - }); - }); - } -} \ No newline at end of file diff --git a/src/query/std-query.ts b/src/query/std-query.ts index 7ea814f2..8f94ab43 100644 --- a/src/query/std-query.ts +++ b/src/query/std-query.ts @@ -37,7 +37,7 @@ export class _NanoSQLQuery { private _query: IdbQuery; - constructor(table: string|any[], db: NanoSQLInstance, queryAction: string, queryArgs?: any, actionOrView?: string, bypassORMPurge?: boolean) { + constructor(table: string|any[], db: NanoSQLInstance, queryAction: string, queryArgs?: any, actionOrView?: string, bypassORM?: boolean) { this._db = db; this._AV = actionOrView || ""; this._query = { @@ -59,13 +59,12 @@ export class _NanoSQLQuery { let newArgs = queryArgs || (a === "select" || a === "delete" ? [] : {}); - // Purge ORM columns from the delete arguments - /*if (["delete", "upsert"].indexOf(a) > -1 && !bypassORMPurge && this._db.relationColumns[this._db.sTable as string].length) { - let inputArgs = {}; + /* + // Purge ORM columns from the delete and upsert arguments + if (["delete", "upsert"].indexOf(a) > -1 && !bypassORM && this._db.relationColumns[this._db.sTable as string].length) { this._db.relationColumns[this._db.sTable as string].forEach((column) => { newArgs[column] = undefined; }); - newArgs = inputArgs; }*/ if (a === "upsert") { @@ -267,17 +266,6 @@ export class _NanoSQLQuery { return this; } - /** - * Track changes to the ORM system in this query. - * - * @returns - * @memberof _NanoSQLQuery - */ - public ormSync(columns?: string[]) { - this._query.ormSync = columns || []; - return this; - } - /** * If this query results in revision(s) being generated, this will add a comment to those revisions. * @@ -399,6 +387,15 @@ export class _NanoSQLQuery { return new Promise((res, rej) => { + if (Array.isArray(this._query.table)) { + if (this._db._instanceBackend.doExec) { + this._db._instanceBackend.doExec(this._query, (q) => { + res(q.result); + }); + } + return; + } + if (!t._db._plugins.length) { t._error = "No plugins, nothing to do!"; } diff --git a/tests/03-integrity.ts b/tests/03-integrity.ts index d382bc4f..4648a82e 100644 --- a/tests/03-integrity.ts +++ b/tests/03-integrity.ts @@ -26,7 +26,7 @@ describe("Data Integrity", () => { posts: [1, 2, 3] }], "Runtime type casting failed!"); done(); - } catch(e) { + } catch (e) { done(e); } }); diff --git a/tests/11-history.ts b/tests/11-orm.ts similarity index 100% rename from tests/11-history.ts rename to tests/11-orm.ts diff --git a/tests/12-history.ts b/tests/12-history.ts new file mode 100644 index 00000000..e69de29b diff --git a/webpack.config.js b/webpack.config.js index 3e464eb8..cf04cb7e 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -71,11 +71,13 @@ const options = { switch (process.env.NODE_ENV) { case "production": options['plugins'].push(new webpack.optimize.UglifyJsPlugin({ - mangle: true - /*mangle: { - props: { regex: new RegExp(/^_|Promise/) }, - except: ['wood'] - }*/ + compress: { + warnings: false, + passes: 2 + }, + mangle: { + props: { regex: new RegExp(/^_|Promise/) } + } })); break; }