UNPKG

@egi/smart-db

Version:

Unified Smart DB Access

1 lines 30.1 kB
"use strict";var __awaiter=this&&this.__awaiter||function(t,e,r,a){return new(r||(r=Promise))(function(n,i){function o(t){try{l(a.next(t))}catch(t){i(t)}}function s(t){try{l(a.throw(t))}catch(t){i(t)}}function l(t){var e;t.done?n(t.value):(e=t.value,e instanceof r?e:new r(function(t){t(e)})).then(o,s)}l((a=a.apply(t,e||[])).next())})},__generator=this&&this.__generator||function(t,e){var r,a,n,i={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(l){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,s[0]&&(i=0)),i;)try{if(r=1,a&&(n=2&s[0]?a.return:s[0]?a.throw||((n=a.return)&&n.call(a),0):a.next)&&!(n=n.call(a,s[1])).done)return n;switch(a=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,a=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(n=i.trys,(n=n.length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){i.label=s[1];break}if(6===s[0]&&i.label<n[1]){i.label=n[1],n=s;break}if(n&&i.label<n[2]){i.label=n[2],i.ops.push(s);break}n[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],a=0}finally{r=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}},__values=this&&this.__values||function(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],a=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&a>=t.length&&(t=void 0),{value:t&&t[a++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var a,n,i=r.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(a=i.next()).done;)o.push(a.value)}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return o},__spreadArray=this&&this.__spreadArray||function(t,e,r){if(r||2===arguments.length)for(var a,n=0,i=e.length;n<i;n++)!a&&n in e||(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SmartDb=void 0;var fs=require("fs"),rxjs_1=require("rxjs"),abstract_model_1=require("./models/abstract-model"),smart_db_dictionary_1=require("./models/smart-db-dictionary"),smart_db_log_model_1=require("./models/smart-db-log-model"),smart_log_1=require("@egi/smart-log"),smart_db_globals_1=require("./smart-db-globals"),smart_db_interfaces_1=require("./smart-db-interfaces"),smart_db_sql_build_data_1=require("./smart-db-sql-build-data"),smart_db_upgrade_manager_1=require("./smart-db-upgrade-manager"),smart_error_1=require("./smart-error"),smart_tools_1=require("./smart-tools"),SmartDb=function(){function t(t,e){void 0===e&&(e={});var r=this;this.dbWriter=null,this.dbConnector=t,"string"!=typeof t&&(this.db=t),this.options=e,this.waitReadySubscriptions=new rxjs_1.Subscription,this.log=new smart_log_1.SmartLog(this.options.logOptions),this.options.silent&&this.log.setLogLevel(smart_log_1.SmartSeverityLevel.Fatal),this.options.smartDbDictionary?this.dictionaries=Array.isArray(this.options.smartDbDictionary)?this.options.smartDbDictionary:[this.options.smartDbDictionary]:this.dictionaries=[],this._onReady=new rxjs_1.BehaviorSubject(smart_db_interfaces_1.SmartDbReadyState.INIT),e.delayInit||this.initDb().catch(function(t){r.lastError=t,r.readyState=smart_db_interfaces_1.SmartDbReadyState.ERROR}),e.onReady&&this.databaseReady().then(function(t){e.onReady(r,t==smart_db_interfaces_1.SmartDbReadyState.READY?null:r.lastError)}).catch(function(t){e.onReady(r,t)})}return Object.defineProperty(t.prototype,"dbLogging",{get:function(){return this.log.hasDbWriter()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isConnected",{get:function(){return this._onReady.value==smart_db_interfaces_1.SmartDbReadyState.CONNECTED||this.isReady},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isReady",{get:function(){return this._onReady.value==smart_db_interfaces_1.SmartDbReadyState.READY},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lastError",{get:function(){return this._lastError},set:function(t){this._lastError=new smart_error_1.SmartError(t),this._lastError.message=this._lastError.message.replace(/Help:.*$/,"").trim(),this._lastError.location=smart_log_1.SmartLocation.Database},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onReady",{get:function(){return this._onReady.asObservable()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"readyState",{get:function(){return this._onReady.value},set:function(t){this.log.debug("ready change: ".concat(t),{type:smart_log_1.SmartLocation.Database}),this._onReady.next(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"supportSyncCalls",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dateTimeMode",{get:function(){var t,e;return null!==(e=null===(t=this.options)||void 0===t?void 0:t.dateTimeMode)&&void 0!==e?e:"rule"},enumerable:!1,configurable:!0}),t.prototype.getOptions=function(){return this.options},t.prototype.databaseReady=function(t){var e=this;return void 0===t&&(t=smart_db_interfaces_1.SmartDbReadyState.READY),new Promise(function(r,a){if(e.readyState==smart_db_interfaces_1.SmartDbReadyState.READY||e.readyState==smart_db_interfaces_1.SmartDbReadyState.ERROR)r(e.readyState);else{var n=e.onReady.pipe((0,rxjs_1.filter)(function(e){return e==t||e==smart_db_interfaces_1.SmartDbReadyState.ERROR})).subscribe(function(i){i==smart_db_interfaces_1.SmartDbReadyState.ERROR?a(e.lastError):i==t&&(e.waitReadySubscriptions.remove(n),r(i))});e.waitReadySubscriptions.add(n)}})},t.prototype.initDb=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,a,n,i,o,s,l,u,c,d,p,_;return __generator(this,function(y){switch(y.label){case 0:return this.moduleVersions=[],this.readyState!=smart_db_interfaces_1.SmartDbReadyState.CONNECTED?[3,19]:(this.dictionaries.push(smart_db_dictionary_1.SmartDbDictionary),[4,this.enableDbLogging()]);case 1:y.sent(),t=__dirname.replace(/\/src$/,""),e=new smart_db_upgrade_manager_1.SmartDbUpgradeManager(this,t+"/assets/"+this.getDatabaseType()),this.log.debug("begin prepare modules",{type:smart_log_1.SmartLocation.Database}),y.label=2;case 2:return y.trys.push([2,4,,5]),[4,e.prepareDatabaseModule("smart-db-core")];case 3:return r=y.sent(),this.moduleVersions.push(r),[3,5];case 4:return a=y.sent(),this.log.error("upgrade of core module failed",{type:smart_log_1.SmartLocation.Database}),this.lastError=a,this.readyState=smart_db_interfaces_1.SmartDbReadyState.ERROR,[3,5];case 5:if(!this.options.module)return[3,17];e.setSqlScriptDirectory(null!==(_=this.options.sqlFilesDirectory)&&void 0!==_?_:t+"/assets/"+this.getDatabaseType()),n="string"==typeof this.options.module?[this.options.module]:this.options.module,y.label=6;case 6:y.trys.push([6,15,,16]),y.label=7;case 7:y.trys.push([7,12,13,14]),i=__values(n),o=i.next(),y.label=8;case 8:return o.done?[3,11]:(s=o.value,[4,e.prepareDatabaseModule(s)]);case 9:l=y.sent(),this.moduleVersions.push(l),y.label=10;case 10:return o=i.next(),[3,8];case 11:return[3,14];case 12:return u=y.sent(),d={error:u},[3,14];case 13:try{o&&!o.done&&(p=i.return)&&p.call(i)}finally{if(d)throw d.error}return[7];case 14:return this.log.debug("DB is ready",{type:smart_log_1.SmartLocation.Database}),this.readyState=smart_db_interfaces_1.SmartDbReadyState.READY,[3,16];case 15:return c=y.sent(),this.lastError=c,this.log.error("upgrade of module '".concat(module,"' failed"),{type:smart_log_1.SmartLocation.Database,data:c}),this.readyState=smart_db_interfaces_1.SmartDbReadyState.ERROR,[3,16];case 16:return[3,18];case 17:this.readyState=smart_db_interfaces_1.SmartDbReadyState.READY,y.label=18;case 18:return[3,25];case 19:return[4,this.databaseReady(smart_db_interfaces_1.SmartDbReadyState.CONNECTED)];case 20:return y.sent()!=smart_db_interfaces_1.SmartDbReadyState.CONNECTED?[3,24]:this.options.connectOnly?(this.readyState=smart_db_interfaces_1.SmartDbReadyState.READY,[3,23]):[3,21];case 21:return[4,this.initDb()];case 22:y.sent(),y.label=23;case 23:return[3,25];case 24:this.log.debug("DB connection error",{type:smart_log_1.SmartLocation.Database,data:this.lastError}),y.label=25;case 25:return[2,this.moduleVersions]}})})},t.prototype.close=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return this.waitReadySubscriptions&&(this.waitReadySubscriptions.unsubscribe(),this.waitReadySubscriptions=null),this.readyState=smart_db_interfaces_1.SmartDbReadyState.CLOSED,[2,this.closeSync()]})})},t.prototype.closeSync=function(){throw new Error("Method not implemented (close)")},t.prototype.commit=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return this.commitSync(),[2]})})},t.prototype.commitSync=function(){throw new Error("Method not implemented (commit)")},t.prototype.rollback=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return this.rollbackSync(),[2]})})},t.prototype.rollbackSync=function(){throw new Error("Method not implemented (rollback)")},t.prototype.hasTransaction=function(){throw new Error("Method not implemented (hasTransaction)")},t.prototype.hasConcurrentTransactions=function(){return!1},t.prototype.get=function(t,e){return __awaiter(this,void 0,void 0,function(){var r,a,n,i;return __generator(this,function(o){switch(o.label){case 0:return e||(e={}),r=this.buildSelectStatement(t,e),e.firstOnly||e.count?[4,this.statementGet(r)]:[3,2];case 1:return n=o.sent(),a=this.prepareResultRow(t,n,e),[3,4];case 2:return[4,this.statementGetAll(r)];case 3:i=o.sent(),a=this.prepareResultRows(t,i,e),o.label=4;case 4:return[2,a]}})})},t.prototype.async=function(t,e){return this.get(t,Object.assign({},e,{firstOnly:!0}))},t.prototype.getFirst=function(t,e,r,a){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(n){switch(n.label){case 0:return[4,this.get(t,{firstOnly:!0,where:e,fields:r,orderBy:a})];case 1:return[2,n.sent()]}})})},t.prototype.getAll=function(t,e,r,a,n){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(i){switch(i.label){case 0:return[4,this.get(t,{where:e,fields:r,orderBy:a,limit:n})];case 1:return[2,i.sent()]}})})},t.prototype.getAllWithOptions=function(t,e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(r){switch(r.label){case 0:return[4,this.get(t,e)];case 1:return[2,r.sent()]}})})},t.prototype.insert=function(t,e){return __awaiter(this,void 0,void 0,function(){var r,a;return __generator(this,function(n){switch(n.label){case 0:return r=this.buildInsertStatement(t,e),[4,this.statementRun(r)];case 1:if(!(a=n.sent()))throw this.getLastError();return[2,a.lastId]}})})},t.prototype.update=function(t,e,r){return __awaiter(this,void 0,void 0,function(){var a,n;return __generator(this,function(i){switch(i.label){case 0:return a=this.buildUpdateStatement(t,e,r),[4,this.statementRun(a)];case 1:if(!(n=i.sent()))throw this.getLastError();return[2,n.changes]}})})},t.prototype.delete=function(t,e){return __awaiter(this,void 0,void 0,function(){var r,a;return __generator(this,function(n){switch(n.label){case 0:return r=this.buildDeleteStatement(t,e),[4,this.statementRun(r)];case 1:if(!(a=n.sent()))throw this.getLastError();return[2,a.changes]}})})},t.prototype.exists=function(t,e,r){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(a){return[2,this.existsSync(t,e,r)]})})},t.prototype.getSync=function(t,e){var r=this;if(this.supportSyncCalls)return this.saveExecute(function(){e||(e={});var a,n=r.buildSelectStatement(t,e);if(e.firstOnly||e.count){var i=r.statementGetSync(n);a=r.prepareResultRow(t,i,e)}else{var o=r.statementGetAllSync(n);a=r.prepareResultRows(t,o,e)}return a});throw"This database driver doesn't support sync calls (getSync)"},t.prototype.getFirstSync=function(t,e,r,a){return this.getSync(t,{firstOnly:!0,where:e,fields:r,orderBy:a})},t.prototype.getFirstWithOptionsSync=function(t,e){return this.getSync(t,Object.assign({},e,{firstOnly:!0}))},t.prototype.getAllSync=function(t,e,r,a,n){return this.getSync(t,{where:e,fields:r,orderBy:a,limit:n})},t.prototype.getAllWithOptionsSync=function(t,e){return this.getSync(t,e)},t.prototype.insertSync=function(t,e){var r=this;if(this.supportSyncCalls)return this.saveExecute(function(){var a=r.buildInsertStatement(t,e);return r.statementRunSync(a).lastId});throw"This database driver doesn't support sync calls (insertSync)"},t.prototype.updateSync=function(t,e,r){var a=this;if(this.supportSyncCalls)return this.saveExecute(function(){var n=a.buildUpdateStatement(t,e,r);return a.statementRunSync(n).changes});throw"This database driver doesn't support sync calls (updateSync)"},t.prototype.deleteSync=function(t,e){var r=this;if(this.supportSyncCalls)return this.saveExecute(function(){var a=r.buildDeleteStatement(t,e);return r.statementRunSync(a).changes});throw"This database driver doesn't support sync calls (deleteSync)"},t.prototype.existsSync=function(t,e,r){throw new Error("Method not implemented (exists)")},t.prototype.exec=function(t,e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(r){return this.execSync(t,e),[2]})})},t.prototype.execSync=function(t,e){throw new Error("Method not implemented (exec)")},t.prototype.execScript=function(t,e){return __awaiter(this,void 0,void 0,function(){var r,a,n,i,o,s,l,u,c;return __generator(this,function(d){switch(d.label){case 0:r=this.scriptParser(t),a=!1,d.label=1;case 1:d.trys.push([1,8,9,10]),n=__values(r),i=n.next(),d.label=2;case 2:if(i.done)return[3,7];o=i.value,d.label=3;case 3:return d.trys.push([3,5,,6]),[4,this.exec(o)];case 4:return d.sent(),[3,6];case 5:return s=d.sent(),e&&"drop "==o.trim().substring(0,5).toLowerCase()?[3,6]:(a=!0,this.lastBuildData=new smart_db_sql_build_data_1.SmartDbSqlBuildData(o),this.lastError=s,[3,7]);case 6:return i=n.next(),[3,2];case 7:return[3,10];case 8:return l=d.sent(),u={error:l},[3,10];case 9:try{i&&!i.done&&(c=n.return)&&c.call(n)}finally{if(u)throw u.error}return[7];case 10:return a?[4,this.rollback()]:[3,12];case 11:throw d.sent(),this.lastError;case 12:return[4,this.commit()];case 13:d.sent(),d.label=14;case 14:return[2]}})})},t.prototype.execScriptSync=function(t){var e,r;if(!this.supportSyncCalls)throw"This database driver doesn't support sync calls (execScriptSync)";var a=this.scriptParser(t);try{for(var n=__values(a),i=n.next();!i.done;i=n.next()){var o=i.value;try{this.execSync(o)}catch(t){if("drop "!=o.substring(0,5).toLowerCase())throw this.lastBuildData=new smart_db_sql_build_data_1.SmartDbSqlBuildData(o),this.lastError=t,t}}}catch(t){e={error:t}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}this.commitSync()},t.prototype.query=function(t,e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(r){return[2,this.querySync(t,e)]})})},t.prototype.querySync=function(t,e){throw new Error("Method not implemented (query)")},t.prototype.buildSelectStatement=function(t,e){var r=this;e||(e={});var a=this.buildSelectSectionStatement(t,e);if(["union","minus","intersect"].forEach(function(t){var n=e[t];n&&(Array.isArray(n)||(n=[n]),n.forEach(function(e){var n=r.buildSelectSectionStatement(e.model,e);a.sql+=" "+t.toUpperCase()+" ",a.append(n)}))}),e.orderBy){a.sql+=" ORDER BY ";var n="string"==typeof e.orderBy?e.orderBy.split(/ *, */):e.orderBy;a.sql+=n.map(function(e){var a="",n=e.match(/^(\w*) (asc|desc)$/i);return n&&(e=n[1],a=n[2].toUpperCase()),e=r.translateFieldName(t,e),a&&(e+=" "+a),e}).join(", ")}return e.limit&&(e.limit.limit&&(a.sql+=" LIMIT "+e.limit.limit.toString()),e.limit.offset&&(a.sql+=" OFFSET "+e.limit.offset.toString())),this.lastBuildData=a,a},t.prototype.getDbConnector=function(){return this.dbConnector},t.prototype.getDbQuote=function(){return'"'},t.prototype.getLastBuildData=function(){return this.lastBuildData},t.prototype.getLastError=function(){return this.lastError},t.prototype.getLogger=function(){return this.log},t.prototype.getModuleVersions=function(){return this.moduleVersions},t.prototype.makeDbValue=function(t,e){return abstract_model_1.AbstractModel.makeDbValue(t,e)},t.prototype.toDate=function(t){return(0,smart_db_globals_1.smartDbToDate)(t)},t.prototype.toDbDate=function(t){return(0,smart_db_globals_1.toSmartDbDate)(t)},t.prototype.toDbTimestamp=function(t){return(0,smart_db_globals_1.toSmartDbTimestamp)(t)},t.prototype.getDbWriter=function(){return this.dbWriter},t.prototype.enableDbLogging=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return this.options.dbLogging?[4,this.exists(smart_db_log_model_1.SmartDbLogModel)]:[3,2];case 1:if(t.sent())return this.dbWriter||(this.dbWriter=new SmartDbLogWriter(this)),this.log.setDbWriter(this.dbWriter),[2];t.label=2;case 2:return this.log.setDbWriter(null),[2]}})})},t.prototype.buildDeleteStatement=function(t,e){var r=this.getTableName(t),a=new smart_db_sql_build_data_1.SmartDbSqlBuildData("DELETE FROM",r);return a.sql+=" "+r,e&&a.append(this.buildWhere(t,e)),this.lastBuildData=a,a},t.prototype.buildFieldList=function(t,e){var r=this,a=[];return e.forEach(function(e){a.push(r.prepareField(t,e))}),a},t.prototype.buildInsertStatement=function(t,e){var r,a,n=this.getTableName(t),i=new smart_db_sql_build_data_1.SmartDbSqlBuildData("INSERT INTO ".concat(n),n),o=[];if(e instanceof abstract_model_1.AbstractModel)e=e.getPlainObject(smart_db_interfaces_1.FieldNamingStyle.Database);else if(!smart_tools_1.tools.isSimpleObject(e))throw"insert values must be provided as object or model instance (insert ".concat(n,")");try{for(var s=__values(Object.entries(e)),l=s.next();!l.done;l=s.next()){var u=__read(l.value,2),c=u[0],d=u[1],p=this.translateFieldName(t,c),_=this.getFieldFullType(t,c);o.push(p),i.values.push(this.makeDbValue(d,{dbFullType:_}))}}catch(t){r={error:t}}finally{try{l&&!l.done&&(a=s.return)&&a.call(s)}finally{if(r)throw r.error}}var y=new Array(o.length);return y.fill("?"),i.sql+=" ("+o.join(", ")+") VALUES ("+y.join(", ")+")",this.lastBuildData=i,i},t.prototype.buildSelectSectionStatement=function(t,e){var r,a,n=this,i=this.getTableName(t);if(Array.isArray(e.fields))r=e.fields;else if("string"==typeof e.fields){var o=e.fields.trim();r=""===o||"*"==o?[]:o.split(/,/)}else r=e.fields&&e.fields.operation?[e.fields]:[];r.length>0?a=this.buildFieldList(t,r).join(", "):a="*";e.distinct&&(a="DISTINCT "+a),e.count&&(a="COUNT(".concat(a,")"));var s=new smart_db_sql_build_data_1.SmartDbSqlBuildData("SELECT "+"".concat(a," FROM ").concat(i),i);if(e.where&&s.append(this.buildWhere(t,e.where)),e.groupBy){s.sql+=" GROUP BY ";var l=Array.isArray(e.groupBy)?e.groupBy:[e.groupBy];s.sql+=l.map(function(e){return n.translateFieldName(t,e)}).join(", "),e.having&&s.append(this.buildWhere(t,e.having,"HAVING"))}return s},t.prototype.buildUpdateStatement=function(t,e,r){var a,n,i=this.getTableName(t),o=new smart_db_sql_build_data_1.SmartDbSqlBuildData("UPDATE",i);o.sql+=" "+i+" SET ";var s,l=[];if(e instanceof abstract_model_1.AbstractModel)s=e.getPlainObject(smart_db_interfaces_1.FieldNamingStyle.Database);else{if(!smart_tools_1.tools.isSimpleObject(e))throw"update values must be provided as object or model instance (update ".concat(i,")");s=e}try{for(var u=__values(Object.entries(s)),c=u.next();!c.done;c=u.next()){var d=__read(c.value,2),p=d[0],_=d[1];l.push(this.translateFieldName(t,p)+" = ?");var y=this.getFieldFullType(t,p);o.values.push(this.makeDbValue(_,{dbFullType:y}))}}catch(t){a={error:t}}finally{try{c&&!c.done&&(n=u.return)&&n.call(u)}finally{if(a)throw a.error}}return o.sql+=l.join(", "),r&&o.append(this.buildWhere(t,r)),this.lastBuildData=o,o},t.prototype.buildWhere=function(t,e,r){var a,n,i,o=this,s=new smart_db_sql_build_data_1.SmartDbSqlBuildData;if(e&&Object.keys(e).length>0){"HAVING"==r?(r="AND",s.sql+=" HAVING "):r||(r="AND",s.sql+=" WHERE ");var l=[],u=function(e,a){var n=e.toUpperCase();if("AND"==n||"OR"==n){var u="";(Array.isArray(a)?a:[a]).forEach(function(e,r){var a=o.buildWhere(t,e,n);r>0&&(u+=" "+n+" "),u+=a.sql,s.values=__spreadArray(__spreadArray([],__read(s.values),!1),__read(a.values),!1)}),u="("+u+")",l.push(u)}else if("EXPRESSION"==n){var d=[];a.forEach(function(e){var r,a=o.prepareField(t,e.compare,s.values),n=o.prepareField(t,e.with,s.values);r="string"==typeof e.operation&&smart_db_interfaces_1.SqlOperationType[e.operation]?smart_db_interfaces_1.SqlOperationType[e.operation]:e.operation||smart_db_interfaces_1.SqlOperationType.EQ,d.push("".concat(a," ").concat(r," ").concat(n))}),l.push(d.join(" "+r+" "))}else{var p=!0,_=void 0;if(null===a?a=(0,smart_db_globals_1.IS_NULL)():Array.isArray(a)&&(a=(0,smart_db_globals_1.IN)(a)),a instanceof Date||"object"!=typeof a)if(null===a)_=smart_db_interfaces_1.SqlOperationType.IS_NULL;else if(void 0===a)e="1",_="= 1",p=!1;else{"string"==typeof a&&a.match(/[%_]/)?(_=smart_db_interfaces_1.SqlOperationType.LIKE+" ?",c.options.needsExplicitEscape&&a.match(/(\\%|\\_)/)&&(_+=" ESCAPE '\\'")):_=smart_db_interfaces_1.SqlOperationType.EQ+" ?";var y=c.getFieldFullType(t,e);s.values.push(c.makeDbValue(a,{dbFullType:y}))}else{var f=a;switch("string"==typeof f.operation&&smart_db_interfaces_1.SqlOperationType[f.operation]&&(f.operation=smart_db_interfaces_1.SqlOperationType[f.operation]),f.operation){case smart_db_interfaces_1.SqlOperationType.BETWEEN:_=f.operation+" ? AND ?",s.values=__spreadArray(__spreadArray([],__read(s.values),!1),__read(f.value),!1);break;case smart_db_interfaces_1.SqlOperationType.IN:case smart_db_interfaces_1.SqlOperationType.NOT_IN:var h=new Array(f.value.length);h.fill("?"),_=f.operation+" ("+h.join(", ")+")",s.values=__spreadArray(__spreadArray([],__read(s.values),!1),__read(f.value),!1);break;case smart_db_interfaces_1.SqlOperationType.IS_NULL:case smart_db_interfaces_1.SqlOperationType.IS_NOT_NULL:_=f.operation;break;case smart_db_interfaces_1.SqlOperationType.LITERAL:_=(null!==(i=f.literalOperation)&&void 0!==i?i:smart_db_interfaces_1.SqlOperationType.EQ)+" "+f.value;break;default:_=f.operation+" ?",f.value instanceof Date?s.values.push(f.value):s.values.push(c.makeDbValue(f.value))}}var b=void 0;b=p?c.translateFieldName(t,e)+" "+_:e+" "+_,l.push(b)}},c=this;try{for(var d=__values(Object.entries(e)),p=d.next();!p.done;p=d.next()){var _=__read(p.value,2);u(_[0],_[1])}}catch(t){a={error:t}}finally{try{p&&!p.done&&(n=d.return)&&n.call(d)}finally{if(a)throw a.error}}s.sql+=l.join(" "+r+" ")}return s},t.prototype.makeArgumentDbValue=function(t,e){return t instanceof Date?t="'".concat((0,smart_db_globals_1.toSmartDbDate)(t,e),"'"):"boolean"==typeof t?t=t?1:0:"string"==typeof t&&(t="'".concat(t.replace(/'/,"''").replace(/\\/,"\\\\"),"'")),t},t.prototype.getJsType=function(t){},t.prototype.prepareField=function(t,e,r){var a;if(null===e)a="NULL";else if("string"==typeof e){var n=e.match(/^'(.*)'$/);n?r?(a="?",r.push(n[1])):a=e:a=this.translateFieldName(t,e)}else e.operation?a=this.prepareFieldValue(t,e):r?(a="?",r.push(e)):a=this.makeArgumentDbValue(e).toString();return a},t.prototype.prepareFieldValue=function(t,e){var r=this,a="<undefined>";switch(e.operation){case smart_db_interfaces_1.SqlFieldOperationType.FIELD:a=this.translateFieldName(t,e.value);break;case smart_db_interfaces_1.SqlFieldOperationType.VALUE:null===e.value?a="NULL":e.literal?a=e.value:"string"==typeof e.value?!isNaN(parseFloat(e.value))&&isFinite(e.value)||(a="'"+e.value+"'"):"number"==typeof e.value?a=e.value.toString():"boolean"==typeof e.value?a=e.value?"1":"0":e.value instanceof Date?a="'"+e.value.toISOString().substring(0,23).replace("T"," ")+"'":console.error("unhandled field data type",typeof e.value,e.value);break;case smart_db_interfaces_1.SqlFieldOperationType.COUNT:a=Array.isArray(e.value)?"COUNT("+e.value.join(",")+")":"COUNT("+(e.value||"")+")";break;case smart_db_interfaces_1.SqlFieldOperationType.COUNT_FIELD:a=Array.isArray(e.value)?"COUNT("+e.value.map(function(e){return r.translateFieldName(t,e)}).join(",")+")":"COUNT("+(this.translateFieldName(t,e.value)||"")+")";break;case smart_db_interfaces_1.SqlFieldOperationType.SUM:a="SUM("+(e.value||"")+")";break;case smart_db_interfaces_1.SqlFieldOperationType.MIN:a="MIN("+(e.value||"")+")";break;case smart_db_interfaces_1.SqlFieldOperationType.MAX:a="MAX("+(e.value||"")+")";break;case smart_db_interfaces_1.SqlFieldOperationType.AVG:a="AVG("+(e.value||"")+")";break;case smart_db_interfaces_1.SqlFieldOperationType.COALESCE:var n=Array.isArray(e.value)?e.value:[e.value];a="COALESCE("+this.buildFieldList(t,n).join(",")+")"}if(e.alias){var i=this.getDbQuote();a+=" as ".concat(i).concat(e.alias).concat(i)}return a},t.prototype.saveExecute=function(t){var e;try{e=t()}catch(t){this.lastError=t instanceof Error?t:new Error(t||"Unknown error"),this.log.fatal(this.lastError,{type:smart_log_1.SmartLocation.Database,data:t}),e=!1}return e},t.prototype.statementGet=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,this.statementGetSync(t)]})})},t.prototype.statementGetAll=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,this.statementGetAllSync(t)]})})},t.prototype.statementGetAllSync=function(t){throw new Error("Method not implemented (statementGetAll)")},t.prototype.statementGetSync=function(t){throw new Error("Method not implemented (statementGet)")},t.prototype.statementRun=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,this.statementRunSync(t)]})})},t.prototype.statementRunSync=function(t){throw new Error("Method not implemented (statementRun)")},t.prototype.getFieldInfo=function(t,e){var r,a;if((r="string"==typeof t?this.getTableClass(t):t)&&!(a=r.attributeMap[e])){var n=r.getTableName();this.lastError=new Error("unknown field '".concat(e,"' in table '").concat(n,"'")),this.log.error(this.lastError,{type:smart_log_1.SmartLocation.Database})}return a},t.prototype.translateFieldName=function(t,e){var r=this.getFieldInfo(t,e);return r&&r.alias&&(e=r.alias),e},t.prototype.getFieldType=function(t,e){var r=this.getFieldInfo(t,e);return r?r.type:"unknown"},t.prototype.getFieldFullType=function(t,e){var r=this.getFieldInfo(t,e);return r?r.dbType:"unknown"},t.prototype.getTableClass=function(t){var e,r,a;if("string"==typeof t){t=t.toLowerCase();try{for(var n=__values(this.dictionaries),i=n.next();!i.done;i=n.next()){var o=i.value;if(o.models[t]||o.models[t+"Model"]){a=o.models[t].cls;break}var s=Object.values(o.models).find(function(e){return e.cls.getTableName()==t});if(s){a=s.cls;break}}}catch(t){e={error:t}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}}else a=t;return a},t.prototype.getPkSequenceName=function(t){var e,r=this.getTableClass(t);if(r){if(!r.getPkSequenceName)throw new Error("model class '".concat(t,"' is missing method getPkSequenceName()"));e=r.getPkSequenceName()}return e},t.prototype.getTableName=function(t){var e,r=this.getTableClass(t);if(r){if(!r.getTableName)throw new Error("bad model: ".concat(t));e=r.getTableName()}else{if("string"!=typeof t)throw new Error("unknown model: ".concat(t));e=t}return e},t.prototype.scriptParser=function(t){for(var e=fs.readFileSync(t,"utf8"),r=[],a=0,n=0,i=!1,o=0,s=!1,l="";n<e.length;){if(s){if("\n"==e[n])for(s=!1,a=n+1;" "==e[a]||"\n"==e[a]||"\n"==e[a];)a+=1}else"'"==e[n]?i=!i:!i&&e.substring(n,n+6).match(/^begin(\s|\n)/)?(o+=1,n+=6):o>0&&!i&&e.substring(n,n+4).match(/^end;/)?(o-=1,n+=4):0!==o||i||"/"!=e[n]?i||"-"!=e[n]||"-"!=e[n+1]?0!==o||i||";"!=e[n]||(r.push((l+e.substring(a,n)).trim()),l="",a=n+2):(l+=e.substring(a,n),s=!0):(r.push((l+e.substring(a,n)).trim()),l="",a=n+2);n+=1}if(a<e.length){var u=e.substring(a,e.length).trim().replace(/;$/,"");""!==u&&r.push(u)}return r},t.prototype.prepareResultRow=function(t,e,r){var a;if(r.indexedBy&&this.log.warning("option 'indexedBy' not supported without 'all'",{type:smart_log_1.SmartLocation.Database}),e)if(r.count)a=parseInt(Object.values(e)[0],10);else if(r.collapseRow)a=Object.values(e).join(",");else{var n=t.from(e);n._instanceDb=this,a=r.style==smart_db_interfaces_1.FieldNamingStyle.TypeScript?n.getPlainObject():n}return a},t.prototype.prepareResultRows=function(t,e,r){var a,n=this;if(e&&(r.indexedBy||r.collapseRow||"string"!=typeof t)){var i=t;a=r.indexedBy?{}:new Array(e.length),e.forEach(function(t,e){var o=i.from?i.from(t):null;o instanceof abstract_model_1.AbstractModel&&(o._instanceDb=n);var s=null;if(r.indexedBy&&(s=o?o.getValue(r.indexedBy):t[r.indexedBy]),r.collapseRow){var l=Object.values(t).join(",");s?a[s]=l:a[e]=l}else o&&r.style==smart_db_interfaces_1.FieldNamingStyle.TypeScript&&(o=o.getPlainObject()),s?a[s]=o||t:a[e]=o||t})}else a=e;return a},t}();exports.SmartDb=SmartDb;var SmartDbLogWriter=function(){function t(t){this.db=t}return t.prototype.write=function(t){var e,r=this,a=null;t.data&&(a=t.data instanceof Error?t.data.stack:"object"==typeof t.data?JSON.stringify(t.data):String(t.data));var n=new smart_db_log_model_1.SmartDbLogModel({severity:this.db.getLogger().severityCodeFromLevel(t.severityLevel),type:t.type,location:t.location,info:null!==(e=t.location)&&void 0!==e?e:"<empty>",data:a,user:null!=t.user?String(t.user):"",timestamp:(0,smart_db_globals_1.smartDbToDate)(t.timestamp)});if(!this.db.supportSyncCalls)return this.db.insert(smart_db_log_model_1.SmartDbLogModel,n).then(function(){return r.db.commit()});this.db.insertSync(smart_db_log_model_1.SmartDbLogModel,n),this.db.commitSync()},t}();