UNPKG

ts-db-helper

Version:
2 lines 48.2 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("rxjs/Subject"),require("rxjs/add/operator/share"),require("rxjs/Observable"),require("rxjs/add/observable/combineLatest"),require("rxjs/add/operator/map"),require("rxjs/add/operator/switchMap"),require("rxjs/add/Observable/from"),require("rxjs/add/Observable/empty"),require("rxjs/add/operator/catch")):"function"==typeof define&&define.amd?define(["exports","rxjs/Subject","rxjs/add/operator/share","rxjs/Observable","rxjs/add/observable/combineLatest","rxjs/add/operator/map","rxjs/add/operator/switchMap","rxjs/add/Observable/from","rxjs/add/Observable/empty","rxjs/add/operator/catch"],t):t(e.TsDbHelper={},e.Rx,e.Rx.Observable.prototype,e.Rx)}(this,function(e,t,n,r){"use strict";function i(e,t){function n(){this.constructor=e}v(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function o(e){return new j(e)}function s(e){return new x(e)}function a(e){return new _(e)}function u(e){return new z(e)}function l(e){return new U(e)}function h(e,t,n){return function(r,i){var o=new A;o.field=i,t&&o.configure(t);var s=r.constructor.prototype.$$dbTable;s||(s=new S,r.constructor.prototype.$$dbTable=s);var a=s.getRelation(e,n);a||(a=new he(r.constructor,e),s.addRelation(e,a,n)),a.add(o);var u=e.prototype.$$dbTable;u||(u=new S,e.prototype.$$dbTable=u);var l=s.getRelation(r.constructor,n);l||(l=new he(r.constructor,e,!0),u.addRelation(r.constructor,l,n)),l.add(o),s.columnList.push(o),s.columns[o.name]=o,s.fields[o.field]=o;var h=Object.getOwnPropertyDescriptor(r,i);h&&void 0!==h.value&&(o.defaultValue=h.value),Object.defineProperty(r.constructor.prototype,i,{get:function(){return this.$$shadow[o.name].foreign},set:function(e){var t=this.$$shadow[o.name].val;e?(this.$$shadow[o.name].val=e.getFieldValue(o.foreignField),this.$$shadow[o.name].foreign=e):(this.$$shadow[o.name].val=null,this.$$shadow[o.name].foreign=null),this.$$shadow[o.name].val!==t&&(this.$$isModified=!0,this.$$shadow[o.name].prevVal=t)},enumerable:!0,configurable:!1})}}function c(e){return function(t,n){var r=new A(n);e&&r.configure(e),t.constructor.prototype.$$dbTable||(t.constructor.prototype.$$dbTable=new S),t.constructor.prototype.$$dbTable.columnList.push(r),t.constructor.prototype.$$dbTable.columns[r.name]=r,t.constructor.prototype.$$dbTable.fields[r.field]=r;var i=Object.getOwnPropertyDescriptor(t,n);i&&void 0!==i.value&&(r.defaultValue=i.value),Object.defineProperty(t.constructor.prototype,n,{get:function(){return this.$$shadow[r.name].val},set:function(e){var t=this.$$shadow[r.name].val;this.$$shadow[r.name].val=e,this.$$shadow[r.name].val!==t&&(this.$$isModified=!0,this.$$shadow[r.name].prevVal=t)},enumerable:!0,configurable:!1})}}function p(e){return e?e.primaryKey=!0:e={primaryKey:!0},c(e)}function d(e,t,n,r){var i=["PRAGMA","ALTER","DROP","CREATE","SELECT","UPDATE","INSERT","DELETE"],o=new R;o.query=e,o.params=t,o.size=n||1e3,o.page=r||0;var s=e.trim(),a=s.substr(0,s.indexOf(" "));if(!(a=a?a.toUpperCase():"")||!i.indexOf(a[0]))throw new b("Unsupported raw query",e,t.join(", "));return o.type=a,{exec:function(){return M.getInstance().query(o)}}}function f(e){return new pe(e)}function y(e){return new ye(e)}function m(e){return function(t){t.prototype.TABLE_NAME=e?e.name:t.name,t.prototype.$$dbTable||(t.prototype.$$dbTable=new S),t.prototype.$$dbTable.name=t.prototype.TABLE_NAME,t.prototype.$$dbTable.modelName=t.name,t.prototype.$$dbTable.configure(e),H.getInstance().addModel(t.prototype.$$dbTable)}}var g=function(){function e(){this.version="",this.autoIncrementVersion=!0}return e}(),v=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},b=function(){function e(e,t,n){var r=this.constructor;this.message=e,this.query=t,this.params=n,Object.setPrototypeOf(this,r.prototype),Error.captureStackTrace(this,this.constructor),this.message=e,this.name="query error"}return e.prototype.toString=function(){return this.name+"\n"+this.message+(this.query?"\nquery: "+this.query:"")+(this.params?"\nparams: "+this.params:"")},e}(),w=function(){function e(){this.levelValue=e.levels[3]}return Object.defineProperty(e.prototype,"level",{set:function(t){if(e.levels.indexOf(t)<0)throw new Error("level '"+t+"' is not a valid log level")},enumerable:!0,configurable:!0}),e.prototype.isLogLevelActivated=function(t){return e.levels.indexOf(this.levelValue)<=e.levels.indexOf(t)},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.isLogLevelActivated("verbose")&&console.log.apply(console,e)},e.prototype.trace=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.isLogLevelActivated("trace")&&console.trace.apply(console,e)},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.isLogLevelActivated("debug")&&console.log.apply(console,e)},e.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.isLogLevelActivated("info")&&console.info.apply(console,e)},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.isLogLevelActivated("warn")&&console.warn.apply(console,e)},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.isLogLevelActivated("error")&&console.error.apply(console,e)},e.prototype.fatal=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.isLogLevelActivated("fatal")&&console.error.apply(console,e)},e.levels=["verbose","debug","trace","info","warn","error","fatal"],e}(),$=function(){function e(e){var t=this.constructor;this.message=e,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace(this,this.constructor),this.message=e,this.name="unsatisfied requirement error"}return e.prototype.toString=function(){return this.name+"\n"+this.message},e}(),O=function(){function e(e,t){this.dbQuery=e,this.observer=t}return e}(),M=function(){function e(){this.pendingDbQueries=[],this.pendingBatchDbQueries=[],this.isReady=!1,this.isInitializationFailed=!1,this.supportRowidValue=!1}return Object.defineProperty(e.prototype,"logger",{get:function(){return this.loggerValue||(this.loggerValue=new w),this.loggerValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"supportRowid",{get:function(){return this.supportRowidValue},enumerable:!0,configurable:!0}),e.init=function(t){var n=e.getInstance();return n.queryConnector=t.queryConnector,n.modelMigration=t.modelMigration,n.supportRowidValue=t.queryConnector.supportRowid,t.logger&&(n.loggerValue=t.logger),H.version=t.version,t.autoIncrementVersion&&H.version&&(H.version+="."+H.getInstance().getModelCount()),n.queryConnector.onReady().subscribe(function(e){e?n.onQueryConnectorReady():n.onInitializationFailure(null)},n.onInitializationFailure),n},e.getInstance=function(){return e.instance},e.prototype.onQueryConnectorReady=function(){var e=this;if(!this.queryConnector||!this.modelMigration)throw new $("ModelMigration or QueryConnector object is missing, check and fix NgDbHelperModule configuration !");var t=this.modelMigration;this.queryConnector.getDbVersion().subscribe(function(n){e.logger.info("old version: "+n);var r=H.getInstance().getDataModel();r.version=H.version,e.logger.info("new version: "+r.version);var i=!1;n?n!==H.version?(e.logger.info("call upgrade data model migration"),t.upgradeModel(r,n).subscribe(function(){e.logger.info("upgrade data model migration successed")},function(t){i=t,e.logger.warn("upgrade data model migration failed")},function(){i?e.onInitializationFailure(i):e.dequeuePendingRequest()})):e.dequeuePendingRequest():(e.logger.info("call init data model migration"),t.initModel(r).subscribe(function(){e.logger.info("init data model migration successed")},function(t){i=t,e.logger.warn("init data model migration failed")},function(){i?e.onInitializationFailure(i):e.dequeuePendingRequest()}))},function(t){return e.onInitializationFailure(t)})},e.prototype.onInitializationFailure=function(e){this.logger.error(e),this.isInitializationFailed=!0,this.dequeuePendingRequest()},e.prototype.dequeuePendingRequest=function(){for(;this.pendingDbQueries.length;){var e=this.pendingDbQueries.shift();e&&this.executeQuery(e.dbQuery,e.observer)}this.isReady=!0},e.prototype.startBatch=function(e){this.batchLock||(this.batchLock=e)},e.prototype.query=function(e){var n=new t.Subject;return this.batchLock?this.pendingBatchDbQueries.push({dbQuery:e,observer:n}):this.isReady?this.executeQuery(e,n):this.pendingDbQueries.push(new O(e,n)),n},e.prototype.execBatch=function(e){var n=[],r=[];if(this.batchSubject||(this.batchSubject=new t.Subject),this.batchLock!==e)return this.batchSubject;for(this.batchLock=null;this.pendingBatchDbQueries.length;){var i=this.pendingBatchDbQueries.shift();n.push(i.dbQuery),r.push(i.observer)}var o=this.queryConnector.queryBatch(n);return o.map(function(e){for(var t=0,n=r;t<n.length;t++){var i=n[t];i.next({insertId:void 0,rowsAffected:0,rows:{length:0,item:function(e){return null},toArray:function(){return[]}}}),i.complete()}return e}),o.share().subscribe(this.batchSubject),this.batchSubject=void 0,o},e.prototype.executeQuery=function(e,t){if(this.isInitializationFailed){var n=new b("query manager initialization did failed",e.query,e.params?e.params.join(", "):"");t.error(n)}else{if(!this.queryConnector)throw new $("QueryConnector object is missing, check and fix NgDbHelperModule configuration !");this.queryConnector.query(e).subscribe(t)}},e.instance=new e,e}(),j=function(){function e(e){this.querySelect=e}return e.prototype.build=function(){return this.querySelect.copy().projection(["count(*)"]).build()},e.prototype.exec=function(){var e=this.build();return M.getInstance().query(e).map(function(t){if(t.rows.length){return t.rows.item(0)["count(*)"]}throw new b("no result error...",e.query,e.params.join(", "))})},e}(),C=function(){function e(){}return e}(),T=function(){function e(){}return e.isKeyOf=function(t){return e.hasOwnProperty(t.toUpperCase())},e.valueOf=function(t){return e[t.toUpperCase()]},e.DIFF="!=",e.LT="<",e.LTE="<=",e.GT=">",e.GTE=">=",e.LIKE="LIKE",e.IN="IN",e.EQ="=",e}(),I=function(){function e(e){var t=this.constructor;this.message=e,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace(this,this.constructor),this.message=e,this.name="not implemented error"}return e.prototype.toString=function(){return this.name+"\n"+this.message},e}(),E=function(){function e(){}return e.ONE_TO_MANY="OneToMany",e.ONE_TO_ONE="OneToOne",e.MANY_TO_MANY="ManyToMany",e.MANY_TO_ONE="ManyToOne",e}(),A=function(){function e(e){this.primaryKey=!1,this.autoIncrement=!1,this.unique=!1,this.indexed=!1,this.type="string",this.foreignTable=null,this.foreignKey=null,this.foreignField=null,this.defaultValue=void 0,e&&(this.name=e,this.field=this.name)}return e.prototype.configure=function(e){e.name&&(this.name=e.name),e.type&&(this.type=e.type),void 0!==e.primaryKey&&(this.primaryKey=e.primaryKey),void 0!==e.unique&&(this.unique=e.unique),void 0!==e.indexed&&(this.indexed=e.indexed),void 0!==e.autoIncrement&&(this.autoIncrement=e.autoIncrement)},e.prototype.fromAlias=function(t){var n=new e(t+"."+this.name);return n.field=t+"."+this.field,n.type=this.type,n.primaryKey=this.primaryKey,n.unique=this.unique,n.indexed=this.indexed,n.autoIncrement=this.autoIncrement,n},e}(),L=function(){function e(e,t,n){this.result=e,this.model=t,this.projection=n,this.cache=new Array(e.rows.length).fill(null)}return Object.defineProperty(e.prototype,"rowsAffected",{get:function(){return this.result.rowsAffected},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"insertId",{get:function(){return this.result.insertId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rows",{get:function(){var e=this;return{length:this.result.rows.length,item:function(t){if(!e.cache[t]){var n=new e.model,r=e.result.rows.item(t);for(var i in n.$$shadow)if(n.$$shadow.hasOwnProperty(i)){var o=n.$$shadow[i];if(e.projection&&e.projection.indexOf(i)<0)continue;r.hasOwnProperty(i)&&(o.val=r[i])}n.$$partialWithProjection=e.projection,n.$$rowid=r.hasOwnProperty("rowid")?r.rowid:null,n.$$inserted=!0,n.$$isModified=!1,e.cache[t]=n}return e.cache[t]},toArray:function(){for(var t=0;t<e.cache.length;t++)e.cache[t]||e.rows.item(t);return e.cache}}},enumerable:!0,configurable:!0}),e}(),P=function(){function e(e){var t=this.constructor;this.message=e,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace(this,this.constructor),this.message=e,this.name="bad column declaration error"}return e.prototype.toString=function(){return this.name+"\n"+this.message},e}(),S=function(){function e(){this.version=0,this.columnList=[],this.columns={},this.fields={},this.relations={}}return e.prototype.configure=function(e){e.version&&(this.version=e.version)},e.prototype.hasAutoIncrementedPrimaryKey=function(){for(var e=0,t=this.columnList;e<t.length;e++){var n=t[e];if(n.primaryKey&&n.autoIncrement)return!0}return!1},e.prototype.hasNoPrimaryKey=function(){for(var e=0,t=this.columnList;e<t.length;e++){if(t[e].primaryKey)return!1}return!0},e.prototype.getPrimaryColumns=function(){for(var e=[],t=0,n=this.columnList;t<n.length;t++){var r=n[t];r.primaryKey&&e.push(r)}return e},e.prototype.addRelation=function(t,n,r){if(this.relations.hasOwnProperty(t.name)&&this.relations[t.name].hasOwnProperty(r||e.RELATIONS_DEFAULT_KEY))throw new P('relation with key "'+(r||e.RELATIONS_DEFAULT_KEY)+'" is inserted twice');this.relations[t.name]||(this.relations[t.name]={}),this.relations[t.name][r||e.RELATIONS_DEFAULT_KEY]=n},e.prototype.getRelation=function(t,n){return this.relations.hasOwnProperty(t.name)&&this.relations[t.name].hasOwnProperty(n||e.RELATIONS_DEFAULT_KEY)?this.relations[t.name][n||e.RELATIONS_DEFAULT_KEY]:null},e.RELATIONS_DEFAULT_KEY="default",e}(),R=function(){function e(){this.page=0,this.params=[],this.query="",this.size=1e3}return e.prototype.append=function(e){return this.query=this.query.trim()+" "+e.content.trim(),this.params=this.params.concat(e.params),this},e}(),k=function(){function e(e,t){this.name=e,this.aliasing=t}return Object.defineProperty(e.prototype,"alias",{get:function(){if(this.aliasing instanceof String)return this.aliasing},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"querySrc",{get:function(){if(!(this.aliasing instanceof String))return this.aliasing},enumerable:!0,configurable:!0}),e.prototype.fqn=function(){return this.aliasing instanceof String?this.aliasing+"."+this.name:this.aliasing&&this.aliasing.alias?this.aliasing.alias+"."+this.name:this.name},e}(),N=function(){function e(){}return e.isKeyOf=function(t){return e.hasOwnProperty(t.toUpperCase())},e.valueOf=function(t){return e[t.toUpperCase()]},e.OR="OR",e.AND="AND",e}(),V=function(){function e(){this.content="",this.params=[]}return e.prototype.append=function(e){return this.appendContent(e.content),this.params=this.params.concat(e.params),this},e.prototype.appendSub=function(t){return t instanceof e?(this.content+=" (",this.append(t),this.content+=")"):(this.content+=" (",this.content+=t.query.trim(),this.content+=")",this.params=this.params.concat(t.params)),this},e.prototype.appendContent=function(e){return this.content=this.content+" "+e.trim(),this},e}(),q=function(){function e(e,t){this.operator=N.AND,this.keysValue=[],this.valuesValue=[],this.not=!1,this.comparator=T.EQ,e&&(this.keysValue=e),t&&(this.valuesValue=t)}return Object.defineProperty(e.prototype,"keys",{get:function(){return this.keysValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"values",{get:function(){return this.valuesValue},enumerable:!0,configurable:!0}),e.prototype.addKey=function(e){this.keysValue.push(e)},e.prototype.addValue=function(e){this.valuesValue.push(e)},e.prototype.build=function(){if(!this.keys&&!this.values)throw new b("one clause has no key for column name.","","");var e=new V;this.not&&e.appendContent("NOT"),e.appendContent("(`"+this.keysValue.join("`, `")+"`)"),e.appendContent(this.comparator),e.appendContent("(");for(var t=!0,n=0,r=this.valuesValue;n<r.length;n++){var i=r[n],o=new V;t?t=!1:o.appendContent(","),Array.isArray(i)?(o.appendContent("("+Array(i.length).fill("(?)").join(", ")+")"),o.params=i):i instanceof k?o.appendContent(i.fqn()):(o.appendContent("(?)"),o.params.push(void 0===i?null:i)),e.append(o)}return e.appendContent(")"),e},e}(),F=function(){function e(e,t){this.operator=N.AND,this.keyValue="",this.not=!1,this.comparator=T.EQ,e&&(this.key=e),t&&(this.value=t)}return Object.defineProperty(e.prototype,"key",{get:function(){return this.keyValue},set:function(e){var t=e.split(/__| /),n=new b("key clause is invalid","","");if(!t.length||t.length>4)throw n;if(1===t.length)this.keyValue=t[0];else{var r=0;if(N.isKeyOf(t[0])&&(this.operator=N.valueOf(t[0]),r++),"NOT"===t[r].toUpperCase()&&(this.not=!0,r++),r>=t.length)return;if(this.keyValue=T.isKeyOf(t[r])?T.valueOf(t[r]):t[r],++r===t.length)return;if(r!==t.length-1||!T.isKeyOf(t[r]))throw new b('Clause key "'+e+'" is malformed',"","");this.comparator=T.valueOf(t[r])}},enumerable:!0,configurable:!0}),e.prototype.build=function(){if(!this.key&&!(this.value instanceof K)&&("object"!=typeof this.value||this.value instanceof Date))throw new b("one clause has no key for column name.","","");var e=new V;if(this.not&&e.appendContent("NOT"),e.appendContent("`"+this.key+"`"),null!==this.value&&void 0!==this.value||this.comparator!==T.EQ?this.value instanceof K||"object"==typeof this.value&&!(this.value instanceof Date)&&!Array.isArray(this.value)||e.appendContent(this.comparator):e.appendContent("IS"),Array.isArray(this.value))e.appendContent("("+Array(this.value.length).fill("(?)").join(", ")+")"),e.params=this.value;else if(this.value instanceof x)e.appendSub(this.value.build());else if(this.value instanceof K)e.appendSub(this.value.build());else if("object"!=typeof this.value||null===this.value||this.value instanceof Date)this.value instanceof k?e.appendContent(this.value.fqn()):(e.appendContent("(?)"),e.params.push(void 0===this.value?null:this.value));else{var t=new K(this.value);e.appendSub(t.build())}return e},e}(),K=function(){function e(e){this.clauses=[],e&&this.add(e)}return e.prototype.isEmpty=function(){return!this.clauses},e.prototype.add=function(t){if(t instanceof e)this.add(t.clauses);else if(t instanceof F||t instanceof q)this.clauses.push(t);else if(Array.isArray(t))this.clauses=this.clauses.concat(t);else for(var n in t)if(t.hasOwnProperty(n)){var r=new F;r.key=n,r.value=t[n],this.clauses.push(r)}},e.prototype.build=function(){for(var e=new V,t=0,n=this.clauses;t<n.length;t++){var r=n[t];e.content&&e.appendContent(r.operator===N.AND?N.AND:N.OR),e.append(r.build())}return e},e}(),x=function(){function e(e){this.model=e,this.type="SELECT",this.joins=[],this.size=1e3,this.page=0,this.alias=""}return e.prototype.copy=function(){var t=new e(this.model).where(this.whereClauses).join(this.joins).groupBy(this.grpBy).orderBy(this.ordrBy);return this.proj&&t.projection(this.proj),t},e.prototype.projection=function(e){return this.proj=e,this},e.prototype.join=function(e){var t;t=Array.isArray(e)?e:[e];for(var n=0,r=t;n<r.length;n++){var i=r[n];i&&(i.alias||(i.alias="join_"+this.joins.length),this.joins.push(i))}return this},e.prototype.where=function(e){return this.whereClauses||(this.whereClauses=new K),this.whereClauses.add(e),this},e.prototype.groupBy=function(e){return this.grpBy=e,this},e.prototype.orderBy=function(e){return this.ordrBy=e,this},e.prototype.setPage=function(e){return this.page=e,this},e.prototype.setSize=function(e){return this.size=e,this},e.prototype.getSize=function(){return this.size},e.prototype.getPage=function(){return this.page},e.prototype.getProjectedTable=function(){var e=H.getInstance().getModel(this.model),t=new S;if(t.name=e.name,t.modelName=e.modelName,this.proj){for(var n=this.proj.slice(),r=0,i=e.columnList;r<i.length;r++){var o=i[r],s=n.indexOf(o.name);s>=0&&(t.columns[o.name]=o,t.fields[o.field]=o,t.columnList.push(o),n.slice(s,1))}for(var a=0,u=n;a<u.length;a++){var l=u[a],h=new A(l);h.field=l,t.columns[h.name]=h,t.columnList.push(h),t.fields[h.field]=h}}else{for(var c=0,p=e.columnList;c<p.length;c++){var o=p[c];t.columnList.push(o),t.columns[o.name]=o,t.fields[o.field]=o}if(t.columns.hasOwnProperty("rowid")){var d=new A("rowid");d.indexed=!0,d.autoIncrement=!0,d.field="$$rowid",d.type="integer",t.columns[d.name]=d,t.columnList.push(d),t.fields[d.field]=d}}if(this.joins)for(var f=0,y=this.joins;f<y.length;f++)for(var m=y[f],g=m.getProjectedTable(),v=0,b=g.columnList;v<b.length;v++){var o=b[v],w=o.fromAlias(m.alias);t.columnList.push(w),t.columns[w.name]=w,t.fields[w.field]=w}return t},e.prototype.getJoinProjection=function(){var e="";if(this.joins){for(var t=[],n=0,r=this.joins;n<r.length;n++)for(var i=r[n],o=i.getProjectedTable(),s=0,a=o.columnList;s<a.length;s++){var u=a[s];t.push(i.alias+"."+u.name)}e=t.join(", ")}return e},e.prototype.build=function(){var e=new R;if(e.page=this.page,e.size=this.size,e.table=H.getInstance().getModel(this.model).name,e.type=this.type,e.query+=this.type,this.proj){e.query+=" ";for(var t=0;t<this.proj.length;t++){var n=this.proj[t];n.trim().indexOf("(")>=0?e.query+=n:e.query+=" `"+n+"`",t<this.proj.length-1&&(e.query+=", ")}}else M.getInstance().supportRowid?e.query+=" rowid, *":e.query+=" *";this.joins&&this.joins.length&&!this.proj&&(e.query+=", "+this.getJoinProjection()),e.query+=" FROM "+e.table;for(var r=0,i=this.joins;r<i.length;r++){var o=i[r];e.append(o.build())}if(this.whereClauses){var s=this.whereClauses.build();s&&s.content&&(e.query+=" WHERE",e.append(s))}return this.grpBy&&(e.query+=" GROUP BY "+this.grpBy),this.ordrBy&&(e.query+=" ORDER BY "+this.ordrBy),e},e.prototype.exec=function(){var e=this;return M.getInstance().query(this.build()).map(function(t){return new L(t,e.model,e.proj)})},e.prototype.execRaw=function(){return M.getInstance().query(this.build())},e}(),D=function(){function e(e){var t=this.constructor;this.message=e,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace(this,this.constructor),this.message=e,this.name="Restore data error"}return e.prototype.toString=function(){return this.name+"\n"+this.message},e}(),_=function(){function e(e){this.model=e,this.type="INSERT"}return e.prototype.build=function(){var e,t=new R;if(Array.isArray(this.model)){if(!this.model.length)return t;e=H.getInstance().getModel(this.model[0])}else e=H.getInstance().getModel(this.model);t.table=e.name,t.type=this.type;for(var n=[],r=0,i=e.columnList;r<i.length;r++){var o=i[r];n.push(o.name)}t.query+=this.type+" INTO "+e.name+" (`"+n.join("`, `")+"`) VALUES ";for(var s=Array.isArray(this.model)?this.model:[this.model],a=[],u=[],l=0,h=s;l<h.length;l++){for(var c=h[l],p=[],d=0,f=e.columnList;d<f.length;d++){var o=f[d],y=c.getColumnValue(o.name);void 0===y?(u.push(null),c.setFieldValue(o.field,null)):u.push(y),p.push("?")}a.push("("+p.join(", ")+")")}return t.query+=a.join(", "),t.params=t.params.concat(u),t},e.prototype.exec=function(){var t=this,n=null;if(Array.isArray(this.model)){var i=void 0;if(!this.model.length)throw new b("Try to insert empty array","","");i=H.getInstance().getModel(this.model[0]);var o=Math.floor(e.SQLITE_PRAMS_LIMIT/i.columnList.length),s=Math.floor(this.model.length/o)+1;if(s>1){for(var a=[],u=0;u<s;u+=1){var l=u*o,h=l+o,c=h<this.model.length?h:this.model.length;if(l>=c)break;var p=new e(this.model.slice(l,c));a.push(p.exec())}n=r.Observable.combineLatest(a).map(function(e){for(var t,n=0,r=0,i=e;r<i.length;r++){var o=i[r];n+=o.rowsAffected,(o&&o.insertId||0===o.insertId)&&(t=Math.max(t||0,o.insertId))}return{rowsAffected:n,insertId:t,rows:{length:0,item:function(e){return null},toArray:function(){return[]}}}})}}return n||(n=M.getInstance().query(this.build()),n.map(function(e){if(Array.isArray(t.model))for(var n=0,r=t.model;n<r.length;n++){var i=r[n];i.$$inserted=!0,i.$$isModified=!1}else t.model.$$inserted=!0,t.model.$$isModified=!1;return e})),n},e.SQLITE_PRAMS_LIMIT=999,e}(),z=function(){function e(e){this.model=e,this.type="DELETE"}return e.prototype.where=function(e){return this.whereClauses||(this.whereClauses=new K),this.whereClauses.add(e),this},e.prototype.build=function(){var e=H.getInstance().getModel(this.model),t=new R;if(t.table=e.name,t.type=this.type,t.query+=this.type,t.query+=" FROM "+e.name,this.model.$$isDbHelperModel)for(var n=0,r=e.columnList;n<r.length;n++){var i=r[n];if(i.primaryKey){var o=new F;o.key=i.name,o.value=this.model[i.field],this.where(o)}}return this.whereClauses&&(t.query+=" WHERE",t.append(this.whereClauses.build())),t},e.prototype.exec=function(){return M.getInstance().query(this.build())},e}(),U=function(){function e(e){this.model=e,this.type="UPDATE"}return e.prototype.where=function(e){return this.whereClauses||(this.whereClauses=new K),this.whereClauses.add(e),this},e.prototype.set=function(e){if(this.model.$$isDbHelperModel)throw new b("Try to set values on Update query already containing a model. This is not supported","","");if(this.valueSet)for(var t in e)e.hasOwnProperty(t)&&(this.valueSet[t]=e[t]);else this.valueSet=e;return this},e.prototype.getValuesFromModel=function(){for(var e=H.getInstance().getModel(this.model),t=new V,n=[],r=0,i=e.columnList;r<i.length;r++){var o=i[r],s=this.model.getColumnValue(o.name);s=void 0===s?null:s,this.model.$$partialWithProjection?(this.model.$$partialWithProjection.indexOf(o.name)>=0||this.model[o.field])&&(n.push(o.name),s&&s.$$isDbHelperModel?t.params.push(s[o.field]):t.params.push(void 0===s?null:s)):(n.push(o.name),s&&s.$$isDbHelperModel?t.params.push(s[o.field]):t.params.push(void 0===s?null:s))}return t.content="SET `"+n.join("` = (?), `")+"` = (?)",t},e.prototype.getValuesFromSet=function(){var e=new V;for(var t in this.valueSet)this.valueSet.hasOwnProperty(t)&&(e.content+=e.content?", (?)":"(?)",e.params.push(this.valueSet[t]));return e},e.prototype.build=function(){var e=H.getInstance().getModel(this.model),t=new R;t.table=e.name,t.type=this.type;var n=this.model.$$rowid;if(this.model.$$isDbHelperModel&&(n||0===n)){var r=new F;r.key="rowid",r.value=n,this.where(r)}else for(var i=0,o=e.columnList;i<o.length;i++){var s=o[i];if(s.primaryKey){var r=new F;r.key=s.name,r.value=this.model[s.field],this.where(r)}}t.query+=this.type+" "+t.table;var a;if(this.model.$$isDbHelperModel)a=this.getValuesFromModel();else{if(!this.valueSet||!Object.getOwnPropertyNames(this.valueSet).length)throw new b("No values to update on Update query build, please use set method or call Update with a single model.","","");a=this.getValuesFromSet()}return t.append(a),this.whereClauses&&(t.query+=" WHERE",t.append(this.whereClauses.build())),t},e.prototype.exec=function(){return M.getInstance().query(this.build())},e}(),Q=function(){function e(){this.$$rowid=null,this.$$inserted=!1,this.$$shadow={},this.$$isModified=!0,this.$$isDbHelperModel=!0;for(var e=H.getInstance().getModel(this.constructor),t=0,n=e.columnList;t<n.length;t++){var r=n[t],i=new C;i.column=r,void 0!==r.defaultValue&&this.setFieldValue(r.field,r.defaultValue),this.$$shadow[r.name]=i}}return e.prototype.update=function(){var e=this;return l(this).exec().map(function(){return e.$$isModified=!1,null})},e.prototype.insert=function(){var e=this;return a(this).exec().switchMap(function(t){return e.$$inserted=!0,e.$$rowid||e.hasValidPrimaryKey()?(e.$$isModified=!1,r.Observable.from([null])):e.restoreFromStorage()})},e.prototype.save=function(){var e=this;if(this.$$partialWithProjection&&!this.hasValidRowid()&&!this.hasValidPrimaryKey())throw new D("Cannot save or restore data from projection without primary key or rowid,add rowid or primary kies to the projection or customize Update to do what you expect.");return this.$$inserted?this.update():this.checkIfShouldUpdateFromDatabase().switchMap(function(t){return t?e.update():e.insert()})},e.prototype.restoreFromStorage=function(){var e=this,t=H.getInstance().getModel(this.constructor),n=new K;if(this.hasValidRowid())n.add({rowid:this.$$rowid});else if(this.hasValidPrimaryKey())n.add(this.getPrimaryClause);else{if(this.$$partialWithProjection||!t.hasAutoIncrementedPrimaryKey()&&!t.hasNoPrimaryKey())throw this.$$inserted=!1,new D('Entity "'+this.constructor.name+'" cannot be restored from database. Detailled properties:\n'+JSON.stringify(this));n.add(this.toClauseGroup())}return s(this.constructor).where(n).setSize(1).exec().map(function(n){if(!n.rows.length)throw e.$$inserted=!1,new D('Entity "'+e.constructor.name+'" cannot be restored from database. Detailled properties:\n'+JSON.stringify(e));for(var r=n.rows.item(0),i=0,o=t.columnList;i<o.length;i++){var s=o[i];e.setFieldValue(s.field,r.getFieldValue(s.field))}return r.hasValidRowid()&&(e.$$rowid=r.$$rowid),e.$$isModified=!1,null})},e.prototype.hasValidRowid=function(){return!!this.$$rowid||0===this.$$rowid},e.prototype.toClauseGroup=function(){var e=new K;for(var t in this.$$shadow)if(this.$$shadow.hasOwnProperty(t)){var n=this.$$shadow[t];if(n.column.autoIncrement&&!n.val&&0!==n.val)continue;var r=new F;r.key=t,r.value=void 0===n.val?null:n.val,!n.val&&n.foreign&&(n.val=n.foreign.getColumnValue(n.column.foreignKey)),e.add(r)}return this.hasValidRowid()&&e.add({rowid:this.$$rowid}),e},e.prototype.getPrimaryClause=function(){var e=new q;e.comparator=T.IN;var t=[];for(var n in this.$$shadow)if(this.$$shadow.hasOwnProperty(n)){var r=this.$$shadow[n];r.foreign&&(r.val=r.foreign.getColumnValue(r.column.foreignKey)),r.column.primaryKey&&(!r.column.autoIncrement||void 0!==r.val&&null!==r.val)&&(e.addKey(r.column.name),t.push(void 0===r.val?null:r.val))}return e.addValue(t),e},e.prototype.hasValidPrimaryKey=function(){for(var e in this.$$shadow)if(this.$$shadow.hasOwnProperty(e)){var t=this.$$shadow[e];if(t.column.foreignKey&&t.foreign&&(t.val=t.foreign.getColumnValue(t.column.foreignKey)),void 0===t.val||t.column.autoIncrement&&null===t.val)return!1}return!0},e.prototype.getColumnValue=function(e){if(!this.$$shadow.hasOwnProperty(e))throw new P('Value for column "'+e+'" can\'t be retrieve because this column is missing on model "'+this.$$dbTable.name+'"');var t=this.$$shadow[e];t.column.foreignKey&&t.foreign&&(t.val=t.foreign.getColumnValue(t.column.foreignKey));return t.val},e.prototype.setColumnValue=function(e,t){if(!this.$$shadow.hasOwnProperty(e))throw new P('Value for column "'+e+'" can\'t be retrieve because this column is missing on model "'+this.$$dbTable.name+'"');var n=this.$$shadow[e],r=n.val;n.val=t,r!==t&&void 0!==r&&(this.$$isModified=!0)},e.prototype.getFieldValue=function(e){return this[e]},e.prototype.setFieldValue=function(e,t){this[e]=t},e.prototype.getCommonFieldType=function(e){var t=H.getInstance().getModel(this).fields[e].type;return t.toLocaleLowerCase().indexOf("varchar")>=0&&(t="varchar"),t},e.prototype.delete=function(){return u(this).exec()},e.prototype.getLinkedModelClauses=function(e,t){var n=H.getInstance().getModel(this),r=n.getRelation(e,t);if(!r)throw new b(this.constructor.name+" has no link with "+e.name,"","");switch(r.type){case E.ONE_TO_MANY:return this.getOneToManyClause(e,r);case E.ONE_TO_ONE:return this.getOneToOneClause(e,r);case E.MANY_TO_ONE:return this.getManyToOneClause(e,r);case E.MANY_TO_MANY:return this.getManyToManyClause(e);default:throw new b("Invalide relation type","","")}},e.prototype.getLinked=function(e,t){return s(e).where(this.getLinkedModelClauses(e,t)).exec()},e.prototype.getOneToManyClause=function(e,t){var n=new q;n.comparator=T.IN;for(var r=[],i=0,o=t.columns;i<o.length;i++){var s=o[i];n.addKey(s.name),r.push(this.getColumnValue(s.foreignKey))}return n.addValue(r),n},e.prototype.getManyToOneClause=function(e,t){var n=new q;n.comparator=T.IN;for(var r=[],i=0,o=t.columns;i<o.length;i++){var s=o[i];n.addKey(s.foreignKey),r.push(this.getColumnValue(s.name))}return n.addValue(r),n}, e.prototype.getOneToOneClause=function(e,t){var n=new q;n.comparator=T.IN;var r=[];if(t.isReverse)for(var i=0,o=t.columns;i<o.length;i++){var s=o[i];n.addKey(s.name),r.push(this.getColumnValue(s.foreignKey))}else for(var a=0,u=t.columns;a<u.length;a++){var s=u[a];n.addKey(s.foreignKey),r.push(this.getColumnValue(s.name))}return n.addValue(r),n},e.prototype.getManyToManyClause=function(e){throw new I("Many to many linked not implemented yet")},e.prototype.checkIfShouldUpdateFromDatabase=function(){var e=this;return this.hasValidRowid()?(this.$$inserted=!0,r.Observable.from([!0])):this.hasValidPrimaryKey()?o(s(this.constructor).where(this.getPrimaryClause())).exec().map(function(t){return e.$$inserted=1===t,e.$$inserted}):(this.$$inserted=!1,r.Observable.from([!1]))},e.prototype.linkModels=function(e,t){if(!e.length)throw new b("can't link empty array on \""+this.constructor.name+'"',"","");var n=e[0].constructor,r=H.getInstance().getModel(this),i=r.getRelation(n,t);if(!i)throw new b('"'+this.constructor.name+'" has no relation with "'+n.name+'"'+(t?' and key "'+t+'"':""),"","");if(e.length>1&&i.type===E.ONE_TO_ONE)throw new b('"'+this.constructor.name+'" could be linked to many models for type one to one',"","");return i.type===E.MANY_TO_MANY?this.linkModelsManyToMany(e,t):i.isReverse?this.linkModelsReverse(e,t):this.linkModelsStraight(e,t)},e.prototype.linkModelsManyToMany=function(e,t,n){throw new I("Many to many linked not implemented yet")},e.prototype.linkModelsStraight=function(e,n,r){var i=this;if(e.length>1)throw new b('"'+this.constructor.name+'" could be linked to many models for type one to one or many to one',"","");for(var o=this.constructor,s=e[0],a=s.getLinkedModelClauses(o,n),u=a.keys,h=a.values[0],c={},p=0;p<u.length;p++)c[u[p]]=r?null:h[p];var d=new t.Subject;return l(o).set(c).where(this.getPrimaryClause()).exec().subscribe(function(){i.getLinked(o,n).subscribe(d)},function(e){return d.error(e)}),d},e.prototype.linkModelsReverse=function(e,n,r){for(var i,o=this,s=null,a=[],u=0,h=e;u<h.length;u++){var c=h[u],p=c.getPrimaryClause();s||(s=p.keys,i=c.constructor),a.push(p.values[0])}for(var d=new q(s,a),f=this.getLinkedModelClauses(i,n),y=f.keys,m=f.values[0],g={},v=0;v<y.length;v++)g[y[v]]=r?null:m[v];var b=new t.Subject;return l(i).set(g).where(d).exec().subscribe(function(){o.getLinked(i,n).subscribe(b)},function(e){return b.error(e)}),b},e.prototype.unlinkModels=function(e,t){if(!e.length)throw new b("can't link empty array on \""+this.constructor.name+'"',"","");var n=e[0].constructor,r=H.getInstance().getModel(this),i=r.getRelation(n,t);if(!i)throw new b('"'+this.constructor.name+'" has no relation with "'+n.name+'"'+(t?' and key "'+t+'"':""),"","");if(e.length>1&&i.type===E.ONE_TO_ONE)throw new b('"'+this.constructor.name+'" could be linked to many models for type one to one',"","");return i.type===E.MANY_TO_MANY?this.linkModelsManyToMany(e,t,!0):i.isReverse?this.linkModelsReverse(e,t,!0):this.linkModelsStraight(e,t,!0)},e}(),B=function(){function e(e){this.tables=[],this.version="";for(var t in e)e.hasOwnProperty(t)&&this.tables.push(e[t])}return e}(),Y=function(){function e(e){var t=this.constructor;this.message=e,Object.setPrototypeOf(this,t.prototype),Error.captureStackTrace(this,this.constructor),this.message=e,this.name="bad table declaration error"}return e.prototype.toString=function(){return this.name+"\n"+this.message},e}(),H=function(){function e(){this.tables={},this.models={}}return e.getInstance=function(){return e.instance},e.prototype.addModel=function(e){this.tables[e.name]=e,this.models[e.modelName]=e.name},e.prototype.getColumnNameForField=function(e,t){if(!this.models.hasOwnProperty(e.name)){var n=new P("Did you forget to declare model: "+e.name+"\n Check @Table déclaration on this model");throw n}var r=this.models[e.name],i=this.tables[r];if(!i.fields.hasOwnProperty(t)){var n=new Y('Did you forget to declare column for field "'+t+'" of model "'+e.name+" - tableName : "+r+" table : "+i+'"\n Check @Column déclaration on this model');throw n}return i.fields[t].name},e.prototype.getDataModel=function(){return new B(this.tables)},e.prototype.getModelCount=function(){return Object.getOwnPropertyNames(this.models).length},e.prototype.getModel=function(e){return e instanceof String?this.tables[e]:e instanceof Q?this.tables[this.getTable(e.constructor)]:this.tables[this.getTable(e)]},e.prototype.getTable=function(e){return this.models[e.name]},e.version="",e.instance=new e,e}(),G=function(){function e(e,t){this.message=e,this.fieldErrors=t,this.name="Data is invalid"}return e}(),W=function(){function e(){this.isOptional=!1,this.defaultValue=null,this.isReadonly=!1,this.isWriteonly=!1,this.type="String"}return e}(),J=function(){function e(e,t,n){this.jsonKey=e,this.reason=t,this.fieldRules=n}return e}(),X=function(){function e(e,t,n){if(this.fieldName=e,this.jsonKey=t,this.rules=new W,this.partial=!1,n)for(var r in n)n.hasOwnProperty(r)&&(this.rules[r]=n[r])}return e.prototype.isValid=function(e){return e.hasOwnProperty(e)?this.rules.isReadonly?new J(this.jsonKey,"Field is readonly",this.rules):this.checkFieldRules(e):this.rules.isOptional?null:new J(this.jsonKey,"Field could be missing or null",this.rules)},e.prototype.serialize=function(e,t){var n=this,i=e.getFieldValue(this.fieldName);return this.rules.isWriteonly||this.rules.formatter?this.rules.formatter?(t[this.jsonKey]=this.rules.formatter(e),r.Observable.empty()):this.rules.serializer?e.getLinked(this.rules.serializer.model).switchMap(function(e){return n.rules.serializer.many?n.rules.serializer.setInstances(e.rows.toArray()):e.rows.length&&n.rules.serializer.setInstance(e.rows.item(0)),n.rules.serializer.getData().map(function(e){return t[n.jsonKey]=e,null})}):r.Observable.empty():(t[this.jsonKey]=i,r.Observable.empty())},e.prototype.deserialize=function(e,t){var n=this,i=this.isValid(t);if(!i){var o=e[this.jsonKey];if(void 0!==o&&this.partial){var s=H.getInstance().getModel(t).fields[this.fieldName];t.$$partialWithProjection||(t.$$partialWithProjection=[]),t.$$partialWithProjection.push(s.name)}return void 0===o?(this.partial||(null!==this.rules.defaultValue&&void 0!==this.rules.defaultValue?t.setFieldValue(this.fieldName,this.rules.defaultValue):t.setFieldValue(this.fieldName,null)),r.Observable.from([null])):this.rules.serializer?(this.rules.serializer.setData(o),this.rules.serializer.getInstance().map(function(e){return t.setFieldValue(n.fieldName,e),null}).catch(function(e){var t=new J(n.jsonKey,"Can't serialize model \""+n.rules.serializer.model.name+'"',n.rules);return t.error=e instanceof G?e.fieldErrors:e,r.Observable.from([t])})):(t.setFieldValue(this.fieldName,e[this.jsonKey]),r.Observable.from([null]))}return r.Observable.from([i])},e}(),Z=function(e){function t(t,n,r){var i=e.call(this,t,n,r)||this;return i.rules.type="String",i}return i(t,e),t.prototype.checkFieldRules=function(e){return null},t}(X),ee=function(e){function t(t,n,r){var i=e.call(this,t,n,r)||this;return i.rules.type="Real",i}return i(t,e),t.prototype.checkFieldRules=function(e){return null},t}(X),te=function(e){function t(t,n,r,i){var o=e.call(this,t,n,i)||this;return o.rules.type=r.name,o}return i(t,e),t.prototype.checkFieldRules=function(e){return null},t}(X),ne=function(){function e(){}return e}(),re=function(e){function t(t,n,r){var i=e.call(this,t,n,r)||this;return i.rules.isReadonly=!0,i}return i(t,e),t.prototype.checkFieldRules=function(e){return null},t}(X),ie=function(e){function t(t,n,r){var i=e.call(this,t,n,r)||this;return i.rules.type="Boolean",i}return i(t,e),t.prototype.checkFieldRules=function(e){var t=e[this.jsonKey];return!0!==t&&!1!==t?new J(this.jsonKey,"Field is not boolean",this.rules):null},t}(X),oe=function(){function e(){}return e.isString=function(e){return"string"==typeof e||e instanceof String},e}(),se=function(e){function t(t,n,r){var i=e.call(this,t,n,r)||this;return i.rules.type="Blob",i}return i(t,e),t.prototype.checkFieldRules=function(e){var t=e[this.jsonKey];return oe.isString(t)?null:new J(this.jsonKey,"Field should be a byte array encoded in base64 string",this.rules)},t}(X),ae=function(e){function t(t,n,r){var i=e.call(this,t,n,r)||this;return i.rules.type="Interger",i}return i(t,e),t.prototype.checkFieldRules=function(e){return null},t}(X),ue=function(){function e(e,t){this.many=t,this.partial=!1,this.model&&e instanceof this.model?this.instance=e:this.model&&Array.isArray(e)&&e[0]instanceof this.model?(this.many=!0,this.instances=e):e?this.data=e:void 0===e||!0!==e&&!1!==e||(this.many=e)}return e.prototype.setData=function(e){this.data=e},e.prototype.setInstance=function(e){this.instance=e},e.prototype.setInstances=function(e){this.instances=e},e.prototype.setPartialParse=function(e){this.partial=e},e.prototype.getData=function(){var e=this;if(this.data)return r.Observable.create(function(t){t.next(e.data),t.complete()});var t=[];if(this.many){this.data=[];for(var n=this.constructor,i=0,o=this.instances;i<o.length;i++){var s=o[i],a=new n(s);t.push(a.getData())}return r.Observable.combineLatest().map(function(t){return e.data=t,e.data})}this.data={};for(var u=0,l=this.fields;u<l.length;u++){var h=l[u],c=void 0;if(h instanceof X)c=h;else switch(this.instance.getCommonFieldType(h).toLocaleLowerCase()){case"integer":c=new ae(h,h,this.getFieldConfig(h));break;case"number":case"real":case"double":case"float":case"decimal":c=new ee(h,h,this.getFieldConfig(h));break;case"string":case"text":case"varchar":c=new Z(h,h,this.getFieldConfig(h));break;case"boolean":c=new ie(h,h,this.getFieldConfig(h));break;default:c=new Z(h,h,this.getFieldConfig(h))}t.push(c.serialize(this.instance,this.data))}return r.Observable.combineLatest().map(function(){return e.data})},e.prototype.getInstance=function(){var e=this;if(this.instance||this.instances)return r.Observable.create(function(t){t.next(e.instance||e.instances),t.complete()});if(this.data){if(this.many&&Array.isArray(this.data)){var t=[];this.instances=[];for(var n=this.constructor,i=0,o=this.data;i<o.length;i++){var s=o[i],a=new n(s);t.push(a.getInstance())}return r.Observable.combineLatest().map(function(t){return e.instances=t,e.instances})}if(this.many||Array.isArray(this.data))return r.Observable.create(function(e){e.next(null),e.complete()});var t=[];this.instance=new this.model;for(var u=0,l=this.fields;u<l.length;u++){var h=l[u],c=void 0;if(h instanceof X)c=h;else switch(this.instance.getCommonFieldType(h).toLocaleLowerCase()){case"integer":c=new ae(h,h);break;case"number":case"real":case"double":case"float":case"decimal":c=new ee(h,h);break;case"string":case"text":case"varchar":c=new Z(h,h);break;case"boolean":c=new ie(h,h);break;default:c=new Z(h,h)}t.push(c.deserialize(this.data,this.instance))}return r.Observable.combineLatest().map(function(t){for(var n=[],r=0,i=t;r<i.length;r++){var o=i[r];o&&n.push(o)}if(n.length)throw new G("Deserialization failed",n);return e.instance})}return r.Observable.create(function(e){e.next(null),e.complete()})},e.prototype.getFieldConfig=function(e){var t=H.getInstance().getModel(this.model).fields[e];if(!t)throw new Error('Model "'+this.model.name+'" has no field "'+e+'" but is declared in Serializer "'+this.constructor.name+'"');var n=new ne;return t.primaryKey&&(n.isOptional=!1),t.defaultValue&&(n.defaultValue=t.defaultValue),n},e.prototype.isValid=function(){return null},e}(),le=function(e){function t(t,n,r){var i=e.call(this,n,r)||this;i.fields=[],i.model=t;for(var o=H.getInstance().getModel(t).columnList,s=0,a=o;s<a.length;s++){var u=a[s];i.fields.push(u.field)}return i}return i(t,e),t}(ue),he=function(){function e(e,t,n){void 0===n&&(n=!1),this.srcModel=e,this.foreignModel=t,this.reverse=n,this.dbColumns=[],this.key=null,this.relationType=null}return Object.defineProperty(e.prototype,"sourceModel",{get:function(){return this.reverse?this.targetModel:this.srcModel},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"targetModel",{get:function(){return this.reverse?this.srcModel:this.foreignModel},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"columns",{get:function(){return this.dbColumns},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isReverse",{get:function(){return this.reverse},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"type",{get:function(){return this.reverse&&this.relationType===E.MANY_TO_ONE?E.ONE_TO_MANY:this.relationType},enumerable:!0,configurable:!0}),e.prototype.add=function(e){var t=H.getInstance().getModel(this.foreignModel),n=null;if(e.foreignKey){if(!(n=t.columns[e.foreignKey]))throw new P("Can't resolve foreignKey \""+this.srcModel.name+"."+e.field+'", no primary found in target model "'+this.foreignModel.name+'" with column name "'+e.foreignKey+'".')}else{var r=t.getPrimaryColumns();if(1!==r.length)throw new P(r.length>1?"Can't resolve foreignKey \""+this.srcModel.name+"."+e.field+'", multiple primary found in target model "'+this.foreignModel.name+'", add foreign column name in "foreignKey" of the column configurator.':"Can't resolve foreignKey \""+this.srcModel.name+"."+e.field+'", no primary found in target model "'+this.foreignModel.name+'".');n=r[0],e.foreignKey=n.name}e.name||(e.name=e.field+n.name.slice(0,1).toLocaleUpperCase()+n.name.slice(1,n.name.length)),e.foreignTable=t.name,e.foreignField=n.field,e.type=n.type,this.dbColumns.push(e);var i=e.unique?E.ONE_TO_ONE:E.MANY_TO_ONE;i!==E.MANY_TO_MANY&&null!==this.relationType&&i!==E.MANY_TO_ONE||(this.relationType=i)},e}(),ce=function(){function e(){}return e.isValid=function(t){return e.hasOwnProperty(t.toUpperCase())||""===t},e.INNER="INNER",e.RIGHT="RIGHT",e.LEFT="LEFT",e.FULL="FULL",e.CROSS="CROSS",e.DEFAULT="",e}(),pe=function(){function e(e){this.model=e,this.joinType=ce.DEFAULT}return e.prototype.type=function(e){if(!ce.isValid(e))throw new b('Join type "'+e+'" is invalid.',"","");return"DEFAULT"===e.toUpperCase()?this.joinType=ce.DEFAULT:this.joinType=e,this},e.prototype.on=function(e){return this.onGroup||(this.onGroup=new K),this.onGroup.add(e),this},e.prototype.getProjectedTable=function(){return this.model instanceof x?this.model.getProjectedTable():H.getInstance().getModel(this.model)},e.prototype.build=function(){var e=new V;e.content+=this.joinType+" JOIN";if(this.model instanceof x?(this.model.getProjectedTable(),e.appendSub(this.model.build())):(H.getInstance().getModel(this.model),e.appendContent(this.model.name)),e.appendContent("AS"),e.appendContent(this.alias),e.appendContent("ON"),!this.onGroup)throw new b("you can't join \""+this.alias+'" without "on clauses".',"","");return e.append(this.onGroup.build()),e},e}(),de=function(){function e(){this.version=0}return e}(),fe=function(){function e(){this.primaryKey=!1,this.autoIncrement=!1,this.unique=!1,this.indexed=!1,this.type="string"}return e}(),ye=function(){function e(e){this.table=e}return e.prototype.build=function(){for(var e=[],t=0,n=this.table.columnList;t<n.length;t++){var r=n[t],i="`"+r.name+"` "+(r.autoIncrement?"INTEGER":r.type);i+=r.primaryKey?" PRIMARY KEY":"",i+=r.autoIncrement?" AUTOINCREMENT":"",e.push(i)}return"CREATE TABLE IF NOT EXISTS "+this.table.name+" ("+e.join(",")+")"},e}();e.DbHelperModuleConfig=g,e.StringFieldSerializer=Z,e.RealFieldSerializer=ee,e.ForeignModelFieldSerializer=te,e.FieldSerializerError=J,e.FieldSerializerConfigurator=ne,e.FieldSerializerRules=W,e.ComputedFieldSerializer=re,e.BooleanFieldSerializer=ie,e.BlobFieldSerializer=se,e.FieldSerializer=X,e.AutoSerializer=le,e.SerializerError=G,e.Serializer=ue,e.QueryManager=M,e.ModelManager=H,e.ForeignModel=h,e.PrimaryKey=p,e.DbRelationModel=he,e.ClauseOperators=N,e.ClauseComparators=T,e.RelationType=E,e.RawQuery=d,e.ColumnClauseValue=k,e.Join=f,e.QueryJoin=pe,e.TableConfig=de,e.DbHelperModel=Q,e.DbTable=S,e.DbColumn=A,e.DataModel=B,e.ColumnConfig=fe,e.DbQuery=R,e.QueryUpdate=U,e.QuerySelect=x,e.QueryInsert=_,e.QueryDelete=z,e.QueryCreate=ye,e.Update=l,e.Select=s,e.Insert=a,e.Delete=u,e.Create=y,e.Count=o,e.Clause=F,e.ClauseGroup=K,e.UnsatisfiedRequirementError=$,e.QueryError=b,e.BadTableDeclarationError=Y,e.BadColumnDeclarationError=P,e.Table=m,e.Column=c,Object.defineProperty(e,"__esModule",{value:!0})});