@egi/smart-db 2.6.6 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +355 -0
  2. package/assets/mysql/smart-db-core-update.001.sql +10 -0
  3. package/assets/oracle/smart-db-core-update.001.sql +13 -0
  4. package/assets/sqlite3/smart-db-core-update.001.sql +10 -0
  5. package/drivers/smart-db-better-sqlite3.d.ts +103 -16
  6. package/drivers/smart-db-better-sqlite3.js +1 -1
  7. package/drivers/smart-db-mysql.d.ts +53 -10
  8. package/drivers/smart-db-mysql.js +1 -1
  9. package/drivers/smart-db-oracle.d.ts +93 -20
  10. package/drivers/smart-db-oracle.js +1 -1
  11. package/helpers/extract-db-api.js +1 -1
  12. package/models/abstract-model.d.ts +39 -4
  13. package/models/abstract-model.js +1 -1
  14. package/models/mysql-tables-model.d.ts +109 -0
  15. package/models/mysql-tables-model.js +1 -0
  16. package/models/oracle-all-cons-columns-model.d.ts +55 -0
  17. package/models/oracle-all-cons-columns-model.js +1 -0
  18. package/models/oracle-all-constraints-model.d.ts +177 -0
  19. package/models/oracle-all-constraints-model.js +1 -0
  20. package/models/oracle-all-dependencies-model.d.ts +77 -0
  21. package/models/oracle-all-dependencies-model.js +1 -0
  22. package/models/oracle-all-objects-model.d.ts +201 -0
  23. package/models/oracle-all-objects-model.js +1 -0
  24. package/models/oracle-all-tab-columns-model.d.ts +305 -0
  25. package/models/oracle-all-tab-columns-model.js +1 -0
  26. package/models/oracle-all-triggers-model.d.ts +187 -0
  27. package/models/oracle-all-triggers-model.js +1 -0
  28. package/{models.generated/smart-db-user-tab-columns-view-model.d.ts → models/smart-db-all-tab-columns-view-model.d.ts} +14 -6
  29. package/models/smart-db-all-tab-columns-view-model.js +1 -0
  30. package/models/smart-db-core-table-model.d.ts +24 -22
  31. package/models/smart-db-core-table-model.js +1 -1
  32. package/models/smart-db-dictionary.d.ts +2 -10
  33. package/models/smart-db-dictionary.js +1 -1
  34. package/models/smart-db-log-model.d.ts +25 -8
  35. package/models/smart-db-log-model.js +1 -1
  36. package/models/smart-db-test-table-model.d.ts +79 -0
  37. package/models/smart-db-test-table-model.js +1 -0
  38. package/models/smart-db-user-tab-columns-view-model.d.ts +2 -0
  39. package/models/smart-db-user-tab-columns-view-model.js +1 -1
  40. package/models/smart-db-version-model.d.ts +25 -8
  41. package/models/smart-db-version-model.js +1 -1
  42. package/models/smart-db-version-view-model.d.ts +27 -8
  43. package/models/smart-db-version-view-model.js +1 -1
  44. package/models/sqlite-master-model.d.ts +14 -12
  45. package/models/sqlite-master-model.js +1 -1
  46. package/models/sqlite-sequence-model.d.ts +9 -7
  47. package/models/sqlite-sequence-model.js +1 -1
  48. package/package.json +40 -56
  49. package/smart-db-api.d.ts +2 -1
  50. package/smart-db-api.js +1 -1
  51. package/smart-db-browser.d.ts +5 -0
  52. package/smart-db-browser.js +1 -0
  53. package/smart-db-globals.d.ts +37 -5
  54. package/smart-db-globals.js +1 -1
  55. package/smart-db-interfaces.d.ts +330 -40
  56. package/smart-db-interfaces.js +1 -1
  57. package/smart-db-sql-build-data.d.ts +10 -1
  58. package/smart-db-sql-build-data.js +1 -1
  59. package/smart-db-upgrade-manager.d.ts +6 -4
  60. package/smart-db-upgrade-manager.js +1 -1
  61. package/smart-db.d.ts +451 -55
  62. package/smart-db.js +1 -1
  63. package/smart-error.d.ts +9 -28
  64. package/smart-error.js +1 -1
  65. package/smart-tools.d.ts +178 -0
  66. package/smart-tools.js +1 -0
  67. package/drivers/smart-db-mysql2.d.ts +0 -20
  68. package/drivers/smart-db-mysql2.js +0 -1
  69. package/drivers/smart-db-sqlite3.d.ts +0 -23
  70. package/drivers/smart-db-sqlite3.js +0 -1
  71. package/models/oracle-cat-model.d.ts +0 -23
  72. package/models/oracle-cat-model.js +0 -1
  73. package/models/oracle-user-tab-columns-model.d.ts +0 -39
  74. package/models/oracle-user-tab-columns-model.js +0 -1
  75. package/models/oracle-user-tab-columns-view-model.d.ts +0 -43
  76. package/models/oracle-user-tab-columns-view-model.js +0 -1
  77. package/models.generated/abstract-model.d.ts +0 -23
  78. package/models.generated/abstract-model.js +0 -1
  79. package/models.generated/smart-db-core-table-model.d.ts +0 -41
  80. package/models.generated/smart-db-core-table-model.js +0 -1
  81. package/models.generated/smart-db-dictionary.d.ts +0 -14
  82. package/models.generated/smart-db-dictionary.js +0 -1
  83. package/models.generated/smart-db-log-model.d.ts +0 -82
  84. package/models.generated/smart-db-log-model.js +0 -1
  85. package/models.generated/smart-db-user-tab-columns-view-model.js +0 -1
  86. package/models.generated/smart-db-version-model.d.ts +0 -82
  87. package/models.generated/smart-db-version-model.js +0 -1
  88. package/models.generated/smart-db-version-view-model.d.ts +0 -90
  89. package/models.generated/smart-db-version-view-model.js +0 -1
  90. package/smart-db-log.d.ts +0 -40
  91. package/smart-db-log.js +0 -1
package/smart-db.js CHANGED
@@ -1 +1 @@
1
- import fs from"fs";import _ from"lodash";import{BehaviorSubject}from"rxjs";import{AbstractModel}from"./models/abstract-model";import{SmartDbDictionary}from"./models/smart-db-dictionary";import{SmartDbLogModel}from"./models/smart-db-log-model";import{IN,smartDbToDate,toSmartDbDate,toSmartDbTimestamp}from"./smart-db-globals";import{FieldNamingStyle,SqlFieldOperationType,SqlOperationType}from"./smart-db-interfaces";import{SmartDbLog}from"./smart-db-log";import{SmartDbSqlBuildData}from"./smart-db-sql-build-data";import{SmartDbUpgradeManager}from"./smart-db-upgrade-manager";import{SmartError,SmartErrorLocation}from"./smart-error";export class SmartDb{constructor(t,e){this.dictionaries=[],this.dbConnector=t,this.smartDbLog=new SmartDbLog(e?null:this),this.dbLogging=!e,this.db=null,this._isReady=null,this._onReady=new BehaviorSubject(this._isReady)}buildSelectStatement(t,e){e||(e={});const r=this.buildSelectSectionStatement(t,e);if(_.forEach(["union","minus","intersect"],(t=>{let s=_.get(e,t);s&&(_.isArray(s)||(s=[s]),_.forEach(s,(e=>{const s=this.buildSelectSectionStatement(e.model,e);r.sql+=" "+t.toUpperCase()+" ",r.append(s)})))})),e.orderBy){r.sql+=" ORDER BY ";const s=_.isString(e.orderBy)?e.orderBy.split(/ *, */):e.orderBy;r.sql+=s.map((e=>{let r="";const s=e.match(/^(\w*) (asc|desc)$/i);return s&&(e=s[1],r=s[2].toUpperCase()),e=this.translateFieldName(t,e),r&&(e+=" "+r),e})).join(", ")}return e.limit&&(e.limit.limit&&(r.sql+=" LIMIT "+e.limit.limit.toString()),e.limit.offset&&(r.sql+=" OFFSET "+e.limit.offset.toString())),this.lastBuildData=r,r}close(){return new Promise(((t,e)=>{try{this.isReady=!1,t(this.closeSync())}catch(t){e(t)}}))}closeSync(){throw new Error("Method not implemented (close)")}commit(){return new Promise(((t,e)=>{try{this.commitSync(),t()}catch(t){e(t)}}))}commitSync(){throw new Error("Method not implemented (commit)")}delete(t,e){return new Promise(((r,s)=>{const a=this.buildDeleteStatement(t,e);this.statementRun(a).then((t=>{t?r(t.changes):s(this.getLastError())})).catch((t=>{this.lastError=t,s(t)}))}))}deleteSync(t,e){if(this.supportSyncCalls)return this.saveExecute((()=>{const r=this.buildDeleteStatement(t,e);return this.statementRunSync(r).changes}));throw"This database driver doesn't support sync calls (deleteSync)"}exec(t){return new Promise(((e,r)=>{try{this.execSync(t)?e():r(this.getLastError())}catch(t){r(t)}}))}execScript(t,e){return new Promise((async(r,s)=>{const a=this.scriptParser(t);let i=!1;for(const t of a)try{await this.exec(t)}catch(r){if(!e||"drop "!=t.trim().substring(0,5).toLowerCase()){i=!0,this.lastBuildData=new SmartDbSqlBuildData(t),this.lastError=r;break}}i?(await this.rollback(),s(this.lastError)):(await this.commit(),r())}))}execScriptSync(t){if(!this.supportSyncCalls)throw"This database driver doesn't support sync calls (execScriptSync)";{const e=this.scriptParser(t);for(const t of e)try{this.execSync(t)}catch(e){if("drop "!=t.substring(0,5).toLowerCase())throw this.lastBuildData=new SmartDbSqlBuildData(t),this.lastError=e,e}this.commitSync()}}execSync(t){throw new Error("Method not implemented (exec)")}exists(t,e,r){return new Promise(((s,a)=>{try{s(this.existsSync(t,e,r))}catch(t){a(t)}}))}existsSync(t,e,r){throw new Error("Method not implemented (exists)")}get(t,e){return new Promise(((r,s)=>{e||(e={});const a=this.buildSelectStatement(t,e);e.firstOnly||e.count?this.statementGet(a).then((s=>{r(this.prepareResultRow(t,s,e))})).catch((t=>{s(t)})):this.statementGetAll(a).then((s=>{r(this.prepareResultRows(t,s,e))})).catch((t=>{s(t)}))}))}getAll(t,e,r,s,a){return this.get(t,{where:e,fields:r,orderBy:s,limit:a})}getAllSync(t,e,r,s,a){return this.getSync(t,{where:e,fields:r,orderBy:s,limit:a})}getDb(){return this.db}getDbConnector(){return this.dbConnector}getDbQuote(){return'"'}getFirst(t,e,r,s){return this.get(t,{firstOnly:!0,where:e,fields:r,orderBy:s})}getFirstSync(t,e,r,s){return this.getSync(t,{firstOnly:!0,where:e,fields:r,orderBy:s})}getLastBuildData(){return this.lastBuildData}getLastError(){return this.lastError}getLogger(){return this.smartDbLog}getSync(t,e){if(this.supportSyncCalls)return this.saveExecute((()=>{e||(e={});const r=this.buildSelectStatement(t,e);let s;if(e.firstOnly||e.count){const a=this.statementGetSync(r);s=this.prepareResultRow(t,a,e)}else{const a=this.statementGetAllSync(r);s=this.prepareResultRows(t,a,e)}return s}));throw"This database driver doesn't support sync calls (getSync)"}hasConcurrentTransactions(){return!1}hasTransaction(){throw new Error("Method not implemented (hasTransaction)")}initDb(t){return new Promise(((e,r)=>{this.dictionaries.push(SmartDbDictionary);const s=new SmartDbUpgradeManager(this);let a;a=import.meta&&import.meta.url?import.meta.url.replace(/file:\/\//,"").replace(/\/[^/]*$/,""):__dirname;const i={module:"smart-db-core",sqlFilesDirectory:a+"/assets/"+this.getDatabaseType()};s.prepareDatabase(i).then((a=>{this.exists(SmartDbLogModel).then((i=>{this.smartDbLog.setDbLogging(this.dbLogging&&i),s.prepareDatabase(t).then((t=>{e([a,t])}),(t=>{r(t)}))}))})).catch((t=>{r(t)}))}))}insert(t,e){return new Promise(((r,s)=>{const a=this.buildInsertStatement(t,e);this.statementRun(a).then((t=>{t?r(t.lastId):s(this.getLastError())})).catch((t=>{s(t)}))}))}insertSync(t,e){if(this.supportSyncCalls)return this.saveExecute((()=>{const r=this.buildInsertStatement(t,e);return this.statementRunSync(r).lastId}));throw"This database driver doesn't support sync calls (insertSync)"}rollback(){return new Promise(((t,e)=>{try{this.rollbackSync(),t()}catch(t){e(t)}}))}rollbackSync(){throw new Error("Method not implemented (rollback)")}toDate(t){return smartDbToDate(t)}toDbDate(t){return toSmartDbDate(t)}toDbTimestamp(t){return toSmartDbTimestamp(t)}update(t,e,r){return new Promise(((s,a)=>{const i=this.buildUpdateStatement(t,e,r);this.statementRun(i).then((t=>{t?s(t.changes):a(this.getLastError())})).catch((t=>{a(t)}))}))}updateSync(t,e,r){if(this.supportSyncCalls)return this.saveExecute((()=>{const s=this.buildUpdateStatement(t,e,r);return this.statementRunSync(s).changes}));throw"This database driver doesn't support sync calls (updateSync)"}statementRun(t){return new Promise(((e,r)=>{try{e(this.statementRun(t))}catch(t){r(t)}}))}statementRunSync(t){throw new Error("Method not implemented (statementRun)")}statementGet(t){return new Promise(((e,r)=>{try{e(this.statementGetSync(t))}catch(t){r(t)}}))}statementGetSync(t){throw new Error("Method not implemented (statementGet)")}statementGetAll(t){return new Promise(((e,r)=>{try{e(this.statementGetAllSync(t))}catch(t){r(t)}}))}statementGetAllSync(t){throw new Error("Method not implemented (statementGetAll)")}buildWhere(t,e,r){const s=new SmartDbSqlBuildData;return e&&_.keys(e).length>0&&(r||(r="AND",s.sql+=" WHERE "),s.sql+=_.map(e,((e,a)=>{const i=a.toUpperCase();if("AND"==i||"OR"==i){let r="";return(_.isArray(e)?e:[e]).forEach(((e,a)=>{const n=this.buildWhere(t,e,i);a>0&&(r+=" "+i+" "),r+=n.sql,s.values=_.concat(s.values,n.values)})),r="("+r+")",r}if("EXPRESSION"==i){let a=[];return _.forEach(e,(e=>{const r=this.prepareField(t,e.compare,s.values),i=this.prepareField(t,e.with,s.values);let n;n=_.isString(e.operation)&&SqlOperationType[e.operation]?SqlOperationType[e.operation]:e.operation||SqlOperationType.EQ,a.push(`${r} ${n} ${i}`)})),a.join(" "+r+" ")}{let r,i,n=!0;if(_.isArray(e)&&(e=IN(e)),_.isObject(e)){const t=e;switch(_.isString(t.operation)&&SqlOperationType[t.operation]&&(t.operation=SqlOperationType[t.operation]),t.operation){case SqlOperationType.IN:case SqlOperationType.NOT_IN:const e=new Array(t.value.length);e.fill("?"),r=t.operation+" ("+e.join(", ")+")",s.values=_.concat(s.values,t.value);break;case SqlOperationType.IS_NULL:case SqlOperationType.IS_NOT_NULL:r=t.operation;break;case SqlOperationType.LITERAL:a=t.key;const i=t.literalOperation||SqlOperationType.EQ;if(i==SqlOperationType.IN||i==SqlOperationType.NOT_IN){const e=new Array(t.value.length);e.fill("?"),r=i+" ("+e.join(", ")+")",s.values=_.concat(s.values,t.value)}else _.isUndefined(t.value)?r=i:(r=i+" ?",s.values.push(this.makeDbValue(t.value)));n=!1;break;default:r=t.operation+" ?",s.values.push(this.makeDbValue(t.value))}}else null===e?r=SqlOperationType.IS_NULL:void 0===e?(a="1",r="= 1",n=!1):(r=_.isString(e)&&e.match(/[%_]/)?SqlOperationType.LIKE+" ?":SqlOperationType.EQ+" ?",s.values.push(this.makeDbValue(e)));return i=n?this.translateFieldName(t,a)+" "+r:a+" "+r,i}})).join(" "+r+" ")),s}buildDeleteStatement(t,e){const r=this.getTableName(t),s=new SmartDbSqlBuildData("DELETE FROM");return s.sql+=" "+r,e&&s.append(this.buildWhere(t,e)),this.lastBuildData=s,s}buildUpdateStatement(t,e,r){const s=this.getTableName(t),a=new SmartDbSqlBuildData("UPDATE");a.sql+=" "+s+" SET ";const i=[],n=e instanceof AbstractModel?e.getPlainObject(FieldNamingStyle.Database):e;return _.forOwn(n,((e,r)=>{i.push(this.translateFieldName(t,r)+" = ?"),a.values.push(this.makeDbValue(e))})),a.sql+=i.join(", "),r&&a.append(this.buildWhere(t,r)),this.lastBuildData=a,a}buildInsertStatement(t,e){const r=this.getTableName(t),s=new SmartDbSqlBuildData("INSERT");s.sql+=" INTO "+r;const a=[];e instanceof AbstractModel&&(e=e.getPlainObject(FieldNamingStyle.Database)),_.forOwn(e,((e,r)=>{r=this.translateFieldName(t,r),a.push(r),s.values.push(this.makeDbValue(e))}));const i=new Array(a.length);return i.fill("?"),s.sql+=" ("+a.join(", ")+") VALUES ("+i.join(", ")+")",this.lastBuildData=s,s}prepareFieldValue(t,e){let r="<undefined>";switch(e.operation){case SqlFieldOperationType.FIELD:r=this.translateFieldName(t,e.value);break;case SqlFieldOperationType.VALUE:null===e.value?r="NULL":e.literal?r=e.value:_.isString(e.value)?!isNaN(parseFloat(e.value))&&isFinite(e.value)||(r="'"+e.value+"'"):_.isNumber(e.value)?r=e.value.toString():_.isBoolean(e.value)?r=e.value?"1":"0":_.isDate(e.value)?r="'"+e.value.toISOString().substring(0,23).replace("T"," ")+"'":console.error("unhandled field data type",typeof e.value,e.value);break;case SqlFieldOperationType.COUNT:r=_.isArray(e.value)?"COUNT("+e.value.join(",")+")":"COUNT("+(e.value||"")+")";break;case SqlFieldOperationType.COALESCE:const s=_.isArray(e.value)?e.value:[e.value];r="COALESCE("+this.buildFieldList(t,s).join(",")+")"}if(e.alias){const t=this.getDbQuote();r+=` as ${t}${e.alias}${t}`}return r}prepareField(t,e,r){let s;if(null===e)s="NULL";else if(_.isString(e)){const a=e.match(/^'(.*)'$/);a?r?(s="?",r.push(a[1])):s=e:s=this.translateFieldName(t,e)}else e.operation?s=this.prepareFieldValue(t,e):r?(s="?",r.push(e)):s=this.makeArgumentDbValue(e).toString();return s}buildFieldList(t,e){const r=[];return _.forEach(e,(e=>{r.push(this.prepareField(t,e))})),r}buildSelectSectionStatement(t,e){const r=this.getTableName(t);let s,a;if(_.isArray(e.fields))s=e.fields;else if(_.isString(e.fields)){const t=e.fields.trim();s=""===t||"*"==t?[]:t.split(/,/)}else s=e.fields&&e.fields.operation?[e.fields]:[];if(s.length>0){a=this.buildFieldList(t,s).join(", ")}else a="*";e.distinct&&(a="DISTINCT "+a),e.count&&(a=`COUNT(${a})`);const i=new SmartDbSqlBuildData(`SELECT ${a} FROM ${r}`);if(e.where&&i.append(this.buildWhere(t,e.where)),e.groupBy){i.sql+=" GROUP BY ";const r=_.isArray(e.groupBy)?e.groupBy:[e.groupBy];i.sql+=r.map((e=>this.translateFieldName(t,e))).join(", ")}return i}translateFieldName(t,e){if(_.isString(t)){const e=t;let r=!1;_.forEach(this.dictionaries,(s=>(s.models&&s.models[e]&&(t=s.models[e].cls,r=!0),!r)))}if(!_.isString(t)){const r=t.attributeMap[e];if(r)r.alias&&(e=r.alias);else{const r=t.getTableName();this.lastError=new Error(`unknown field '${e}' in table '${r}'`),this.smartDbLog.logError(SmartErrorLocation.Database,"translateFieldName",this.lastError)}}return e}makeDbValue(t){return _.isBoolean(t)?t=t?1:0:_.isDate(t)&&(t=toSmartDbDate(t)),t}makeArgumentDbValue(t){return _.isBoolean(t)?t=t?1:0:_.isDate(t)?t=`'${toSmartDbDate(t)}'`:_.isString(t)&&(t=`'${t.replace(/'/,"''").replace(/\\/,"\\\\")}'`),t}saveExecute(t){let e;try{e=t()}catch(t){this.lastError=t instanceof Error?t:new Error(t||"Unknown error"),this.smartDbLog.logFatal(SmartErrorLocation.Database,"saveExecute-catch",this.lastError),e=!1}return e}scriptParser(t){const e=fs.readFileSync(t,"utf8"),r=[];let s=0,a=0,i=!1,n=0,l=!1,o="";for(;a<e.length;){if(l){if("\n"==e[a])for(l=!1,s=a+1;" "==e[s]||"\n"==e[s]||"\n"==e[s];)s+=1}else"'"==e[a]?i=!i:!i&&e.substring(a,a+6).match(/^begin(\s|\n)/)?(n+=1,a+=6):n>0&&!i&&e.substring(a,a+4).match(/^end;/)?(n-=1,a+=4):0!==n||i||"/"!=e[a]?i||"-"!=e[a]||"-"!=e[a+1]?0!==n||i||";"!=e[a]||(r.push((o+e.substring(s,a)).trim()),o="",s=a+2):(o+=e.substring(s,a),l=!0):(r.push((o+e.substring(s,a)).trim()),o="",s=a+2);a+=1}if(s<e.length){const t=e.substring(s,e.length).trim().replace(/;$/,"");console.log(t),""!==t&&r.push(t)}return r}prepareResultRow(t,e,r){let s;if(r.indexedBy&&this.smartDbLog.logWarning(SmartErrorLocation.Database,"AbstractModel.get","option 'indexedBy' not supported without 'all'"),e)if(r.count)s=parseInt(_.values(e)[0],10);else if(r.collapseRow)s=_.values(e).join(",");else{const a=t.from(e);s=r.style==FieldNamingStyle.TypeScript?a.getPlainObject():a}return s}prepareResultRows(t,e,r){let s;if(!e||!r.indexedBy&&!r.collapseRow&&_.isString(t))s=e;else{const a=t;s=r.indexedBy?{}:new Array(e.length),_.forEach(e,((t,e)=>{let i=a.from?a.from(t):null,n=null;if(r.indexedBy&&(n=i?i.getValue(r.indexedBy):t[r.indexedBy]),r.collapseRow){const r=_.values(t).join(",");n?s[n]=r:s[e]=r}else i&&r.style==FieldNamingStyle.TypeScript&&(i=i.getPlainObject()),n?s[n]=i||t:s[e]=i||t}))}return s}getTableName(t){let e;if(_.isString(t)){let r=t;_.forEach(this.dictionaries,(t=>(t.models&&t.models[r]&&(e=t.models[r].cls.getTableName()),!e))),e||(e=r)}else{if(!t||!t.getTableName)throw new Error(`unknown model: ${t}`);e=t.getTableName()}return e}get isReady(){return this._isReady}set isReady(t){this._isReady=t,this._onReady.next(t)}get lastError(){return this._lastError}set lastError(t){this._lastError=new SmartError(t),this._lastError.location=SmartErrorLocation.Database}get onReady(){return this._onReady}get supportSyncCalls(){return!1}}
1
+ "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 t.prototype.getOptions=function(){return this.options},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}),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.getModuleVersions=function(){return this.moduleVersions},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.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.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.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.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.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.execSync=function(t,e){throw new Error("Method not implemented (exec)")},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.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.existsSync=function(t,e,r){throw new Error("Method not implemented (exists)")},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.getFirstWithOptionsSync=function(t,e){return this.getSync(t,Object.assign({},e,{firstOnly:!0}))},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.getAllWithOptionsSync=function(t,e){return this.getSync(t,e)},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.getAllSync=function(t,e,r,a,n){return this.getSync(t,{where:e,fields:r,orderBy:a,limit:n})},t.prototype.getDbConnector=function(){return this.dbConnector},t.prototype.getDbQuote=function(){return'"'},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.getFirstSync=function(t,e,r,a){return this.getSync(t,{firstOnly:!0,where:e,fields:r,orderBy:a})},t.prototype.getLastBuildData=function(){return this.lastBuildData},t.prototype.getLastError=function(){return this.lastError},t.prototype.getLogger=function(){return this.log},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.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.hasConcurrentTransactions=function(){return!1},t.prototype.hasTransaction=function(){throw new Error("Method not implemented (hasTransaction)")},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.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.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.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.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.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.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)"},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.makeDbValue=function(t,e){return abstract_model_1.AbstractModel.makeDbValue(t,e)},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.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}();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}();
package/smart-error.d.ts CHANGED
@@ -1,39 +1,20 @@
1
- export declare const SmartErrorLocation: {
2
- App: SmartErrorLocationValue;
3
- Frontend: SmartErrorLocationValue;
4
- Backend: SmartErrorLocationValue;
5
- Database: SmartErrorLocationValue;
6
- UpgradeManager: SmartErrorLocationValue;
7
- };
8
- export declare type SmartErrorLocationType = typeof SmartErrorLocation;
9
- export declare type SmartErrorLocationKey = keyof SmartErrorLocationType;
10
- export declare type SmartErrorLocationValue = "APP" | "FRONTEND" | "BACKEND" | "DATABASE" | "UPGRADE-MANAGER";
11
- export declare const SmartErrorSeverity: {
12
- readonly Fatal: SmartErrorSeverityValue;
13
- readonly Error: SmartErrorSeverityValue;
14
- readonly Warning: SmartErrorSeverityValue;
15
- readonly Info: SmartErrorSeverityValue;
16
- readonly Debug: SmartErrorSeverityValue;
17
- readonly Local: SmartErrorSeverityValue;
18
- };
19
- export declare type SmartErrorSeverityType = typeof SmartErrorSeverity;
20
- export declare type SmartErrorSeverityKey = keyof SmartErrorSeverityType;
21
- export declare type SmartErrorSeverityValue = "F" | "E" | "W" | "I" | "D" | "L";
1
+ import { SmartLocation, SmartSeverityLevel } from "@egi/smart-log";
2
+ export type SmartErrorLocation = SmartLocation;
22
3
  export interface SmartErrorData {
4
+ code?: number | string;
5
+ info?: Record<string, any>;
6
+ location?: SmartLocation;
23
7
  message: string;
24
8
  name: string;
25
- code?: number | string;
26
- type?: SmartErrorSeverityValue;
27
- location?: SmartErrorLocationValue;
28
9
  timestamp?: Date | string | number;
29
- info?: Record<string, any>;
10
+ type?: SmartSeverityLevel;
30
11
  }
31
12
  export declare class SmartError extends Error implements SmartErrorData {
32
13
  code: number | string;
33
- type: SmartErrorSeverityValue;
34
- location: SmartErrorLocationValue;
35
- timestamp: Date | string | number;
36
14
  info: Record<string, any>;
15
+ location: SmartLocation;
16
+ timestamp: Date | string | number;
17
+ type: SmartSeverityLevel;
37
18
  private smartErrorKeys;
38
19
  constructor(message: any);
39
20
  toObject(): SmartErrorData;
package/smart-error.js CHANGED
@@ -1 +1 @@
1
- export const SmartErrorLocation={App:"APP",Frontend:"FRONTEND",Backend:"BACKEND",Database:"DATABASE",UpgradeManager:"UPGRADE-MANAGER"};export const SmartErrorSeverity={Fatal:"F",Error:"E",Warning:"W",Info:"I",Debug:"D",Local:"L"};export class SmartError extends Error{constructor(t){let e,r,s,o,i,n,a;if(void 0===t||"string"==typeof t)e=t;else if("object"==typeof t){if(e="string"==typeof t.message?t.message:"string"==typeof t.text?t.text:"string"==typeof t.error?t.error:"Error",i=t.name,r=t.code,s=t.type,o=t.location,n=t.timestamp,!t.constructor){const e=Object.keys(t).filter((t=>!this.smartErrorKeys.includes(t)));e.length>0&&(a={},e.forEach((e=>{a[e]=t[e]})))}}else e="function"==typeof t.toString?t.toString():t;super(e),this.name=i??"",this.code=r??-1,this.type&&(this.type=s??"E"),o&&(this.location=o),n&&(this.timestamp=n),a&&(this.info=a),this.smartErrorKeys=["message","name","code","type","location","timestamp","info"]}toObject(){const t={name:this.name,message:this.message};return this.smartErrorKeys.forEach((e=>{"name"!=e&&"message"!=e&&this[e]&&(t[e]=this[e])})),t}toString(){let t=super.toString(),e="";return this.type&&(e+=this.type),this.location&&(""!==e&&(e+="-"),e+=this.location),this.code&&(""!==e&&(e+=" #"),e+=this.code),t+" ("+e+")"}}
1
+ "use strict";var __extends=this&&this.__extends||function(){var t=function(r,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var e in r)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]=r[e])},t(r,e)};return function(r,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function o(){this.constructor=r}t(r,e),r.prototype=null===e?Object.create(e):(o.prototype=e.prototype,new o)}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.SmartError=void 0;var smart_log_1=require("@egi/smart-log"),SmartError=function(t){function r(r){var e,o,n,i,s,a,c,p=this,u=["message","name","code","type","location","timestamp","info"];if(void 0===r||"string"==typeof r)e=r;else if("object"==typeof r){if(e="string"==typeof r.message?r.message:"string"==typeof r.text?r.text:"string"==typeof r.error?r.error:"Error",s=r.name,o=r.code,n=r.type,i=r.location,a=r.timestamp,!r.constructor){var l=Object.keys(r).filter(function(t){return!u.includes(t)});l.length>0&&(c={},l.forEach(function(t){c[t]=r[t]}))}}else e="function"==typeof r.toString?r.toString():r;return(p=t.call(this,e)||this).name=null!=s?s:"",p.code=null!=o?o:-1,p.type=null!=n?n:smart_log_1.SmartSeverityLevel.Error,i&&(p.location=i),a&&(p.timestamp=a),c&&(p.info=c),p.smartErrorKeys=u,p}return __extends(r,t),r.prototype.toObject=function(){var t=this,r={name:this.name,message:this.message};return this.smartErrorKeys.forEach(function(e){"name"!=e&&"message"!=e&&t[e]&&(r[e]=t[e])}),r},r.prototype.toString=function(){var r=t.prototype.toString.call(this),e="";return this.type&&(e+=this.type),this.location&&(""!==e&&(e+="-"),e+=this.location),this.code&&(""!==e&&(e+=" #"),e+=this.code),r+" ("+e+")"},r}(Error);exports.SmartError=SmartError;
@@ -0,0 +1,178 @@
1
+ import { DateTime } from "luxon";
2
+ export interface FormatDateOptions {
3
+ millis?: boolean;
4
+ noBlanks?: boolean;
5
+ separator?: string;
6
+ tz?: string;
7
+ }
8
+ export interface GetCallerOptions {
9
+ ignoreFiles?: string[];
10
+ projectRoot?: string;
11
+ }
12
+ export interface FrameData {
13
+ columnNumber: number;
14
+ fileName: string;
15
+ functionName: string;
16
+ lineNumber: number;
17
+ methodName: string;
18
+ native: boolean;
19
+ typeName: string;
20
+ }
21
+ /**
22
+ * Controls how `Date` values are converted when writing to and reading from the database.
23
+ * - `"rule"` *(default)* — TIMESTAMP columns store UTC; DATE / DATETIME columns store local time.
24
+ * - `"utc"` — all date/time columns store UTC.
25
+ * - `"local"` — all date/time columns store local time (no UTC conversion).
26
+ * - `"none"` — no conversion; values are passed through to the driver as-is.
27
+ */
28
+ export type SmartDbDateTimeMode = "rule" | "utc" | "local" | "none";
29
+ export interface SmartToolOptions {
30
+ /** Controls how `Date` values are converted on read and write. Defaults to `"rule"`. */
31
+ dateTimeMode?: SmartDbDateTimeMode;
32
+ }
33
+ export declare class SmartTools {
34
+ private formatters;
35
+ /**
36
+ * Captures the stack trace starting from the point just below the provided function.
37
+ *
38
+ * @param belowFn - A reference function to exclude from the stack trace.
39
+ * @returns An array of FrameData objects representing the captured stack trace.
40
+ */
41
+ getStackTrace(belowFn?: () => any): FrameData[];
42
+ /**
43
+ * Parses an error's stack trace into an array of FrameData objects.
44
+ *
45
+ * @param err - An error object containing the stack trace.
46
+ * @returns An array of FrameData objects parsed from the error's stack trace.
47
+ */
48
+ parseStackTrace(err: Error): FrameData[];
49
+ /**
50
+ * Retrieves caller information from the stack trace, excluding specified files or patterns.
51
+ *
52
+ * @param {Error | (() => Error)} [errorOrStackProvider] - An error object or function returning an error,
53
+ * used to extract the stack trace. Defaults to capturing the current stack trace if omitted.
54
+ * @param options - Optional settings for filtering and formatting the caller information.
55
+ * @returns {string} A string with the format "fileName:lineNumber (functionName)",
56
+ * or "unknown location" if caller information cannot be determined.
57
+ */
58
+ getCallerFromStack(errorOrStackProvider?: Error | (() => Error), options?: GetCallerOptions): string;
59
+ /** Converts a string to `kebab-case`. Accepts camelCase, PascalCase, snake_case, or kebab-case input. */
60
+ kebabCase(s: string): string;
61
+ /** Converts a string to `snake_case`. Accepts camelCase, PascalCase, kebab-case, or snake_case input. */
62
+ snakeCase(s: string): string;
63
+ /** Converts a string to `camelCase`. Returns `""` for empty or null input. */
64
+ camelCase(s: string): string;
65
+ /** Converts a string to `PascalCase`. Returns `""` for empty or null input. */
66
+ pascalCase(s: string): string;
67
+ /** Converts a string to `Title Case` with spaces between words. Returns `""` for empty or null input. */
68
+ titleCase(s: string): string;
69
+ /** Converts a string to `CONSTANT_CASE` (SCREAMING_SNAKE). */
70
+ constantCase(s: string): string;
71
+ /** Returns a shallow copy of `obj` (top-level properties are copied; nested objects are shared). */
72
+ clone<T extends object>(obj: T): T;
73
+ /** Returns a deep clone of `obj`. Handles nested objects, arrays, and primitive values. */
74
+ cloneDeep<T>(obj: T): T;
75
+ /** Returns `true` if `obj` is a plain object created with `{}` or `new Object()`. */
76
+ isSimpleObject(obj: any): boolean;
77
+ /** Returns `true` if `obj` is any object (includes arrays, Dates, class instances). Returns `false` for `null` and primitives. */
78
+ isObject(obj: any): boolean;
79
+ /** Returns `true` if `obj` is an array. */
80
+ isArray(obj: any): boolean;
81
+ /** Returns `true` for string primitives and `String` wrapper objects. */
82
+ isString(obj: any): boolean;
83
+ /** Returns `true` for finite numbers. Returns `false` for `NaN`, `Infinity`, and non-number types. */
84
+ isNumber(obj: any): boolean;
85
+ /** Returns `true` only for `true` or `false` boolean primitives. */
86
+ isBoolean(obj: any): boolean;
87
+ /** Returns `true` only for `null` (strict equality). */
88
+ isNull(obj: any): boolean;
89
+ /** Returns `true` only for `undefined`. */
90
+ isUndefined(obj: any): boolean;
91
+ /** Returns `true` for functions and class constructors. */
92
+ isFunction(obj: any): boolean;
93
+ /** Returns `true` for `Date` instances. Returns `false` for date strings or timestamps. */
94
+ isDate(obj: any): boolean;
95
+ /** Returns `true` for `RegExp` instances (both literals and `new RegExp()`). */
96
+ isRegExp(obj: any): boolean;
97
+ /** Returns `true` for `Error` instances and subclasses (e.g. `TypeError`, `RangeError`). */
98
+ isError(obj: any): boolean;
99
+ /** Returns `true` for Symbol values. */
100
+ isSymbol(obj: any): boolean;
101
+ /**
102
+ * Returns `true` when `obj` is considered empty:
103
+ * - `null` or `undefined`
104
+ * - empty string `""`
105
+ * - empty array `[]`
106
+ * - empty plain object `{}`
107
+ *
108
+ * Note: `0`, `false`, and non-plain objects are **not** considered empty.
109
+ */
110
+ isEmpty(obj: any): boolean;
111
+ /** Returns `true` for strings, numbers, booleans, `null`, `undefined`, and symbols. Returns `false` for objects, arrays, and functions. */
112
+ isPrimitive(obj: any): boolean;
113
+ /**
114
+ * Converts a millisecond timestamp, ISO string, Luxon `DateTime`, or `Date` to a JavaScript `Date`.
115
+ * If `date` is already a `Date` it is returned as-is.
116
+ */
117
+ toDate(date: number | Date | DateTime | string): Date;
118
+ /**
119
+ * Converts a millisecond timestamp, ISO string, JavaScript `Date`, or Luxon `DateTime` to a Luxon `DateTime`.
120
+ * Passing `null` or `undefined` returns `DateTime.now()`.
121
+ * Throws if the value cannot be parsed.
122
+ */
123
+ toDateTime(date: number | Date | DateTime | string): DateTime<boolean>;
124
+ /**
125
+ * Returns the Unix timestamp in milliseconds for the given date value.
126
+ * Accepts a millisecond number (returned as-is), `Date`, Luxon `DateTime`, or a parseable string.
127
+ */
128
+ toTimestamp(date: number | Date | DateTime | string): number;
129
+ /**
130
+ * Formats a date as a locale-independent ISO-like string (`YYYY-MM-DD HH:mm:ss`).
131
+ * Defaults to the system timezone and current time when arguments are omitted.
132
+ *
133
+ * @param date - The date to format. Accepts a `Date`, ISO string, or millisecond timestamp. Defaults to now.
134
+ * @param options - Optional formatting options:
135
+ * - `tz` — IANA timezone (defaults to the system timezone).
136
+ * - `noBlanks` — replaces the date/time separator space with `T`.
137
+ * - `separator` — replaces all separators (dashes, colons, space) with a single character.
138
+ * - `millis` — appends milliseconds to the output.
139
+ */
140
+ formatDate(date?: Date | string | number, options?: FormatDateOptions): string;
141
+ /**
142
+ * Converts a millisecond duration to a human-readable time string.
143
+ *
144
+ * @param millies - Duration in milliseconds. Must represent less than one month.
145
+ * @param includeMillis - When `true`, appends milliseconds to the output. Defaults to `false`.
146
+ * @param useHms - When `true`, uses `h`/`m`/`s` suffixes (e.g. `"1h30m05s"`) instead of `HH:MM:SS` notation.
147
+ * @throws {Error} If the duration is too large (exceeds one month).
148
+ *
149
+ * @example
150
+ * millisToTimeString(5_400_000) // "01:30:00"
151
+ * millisToTimeString(5_400_000, false, true) // "1h30m00s"
152
+ */
153
+ millisToTimeString(millies: number, includeMillis?: boolean, useHms?: boolean): string;
154
+ /**
155
+ * Returns a promise that resolves after `millis` milliseconds.
156
+ * Useful for introducing deliberate pauses in async code.
157
+ */
158
+ sleep(millis: number): Promise<void>;
159
+ /**
160
+ * Extracts a human-readable message string from any error value.
161
+ * Inspects common properties in order: `error`, `message`, `text`, `status`, `stderr`, `stdout`, `code`.
162
+ * Falls back to `String(error)` for unrecognized shapes.
163
+ */
164
+ getErrorText(error: any): string;
165
+ /**
166
+ * Casts `value` to the requested primitive type.
167
+ * - `"number"` — applies `Number(value)`.
168
+ * - `"boolean"` — returns `true` for `1`, `true`, `"1"`, `"T"`, or `"TRUE"` (case-insensitive); `false` otherwise.
169
+ * - `"string"` — returns `value` unchanged.
170
+ */
171
+ castToType(value: any, type: "string"): string;
172
+ castToType(value: any, type: "number"): number;
173
+ castToType(value: any, type: "boolean"): boolean;
174
+ castToType(value: any, type: "string" | "number" | "boolean"): any;
175
+ /** Splits a string into lowercase words by detecting camelCase boundaries and normalising separators. */
176
+ private splitWords;
177
+ }
178
+ export declare const tools: SmartTools;
package/smart-tools.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var __assign=this&&this.__assign||function(){return __assign=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},__assign.apply(this,arguments)},__awaiter=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))(function(o,i){function a(t){try{u(n.next(t))}catch(t){i(t)}}function s(t){try{u(n.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r(function(t){t(e)})).then(a,s)}u((n=n.apply(t,e||[])).next())})},__generator=this&&this.__generator||function(t,e){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(u){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,n=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,u])}}},__read=this&&this.__read||function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,o,i=r.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},__spreadArray=this&&this.__spreadArray||function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))},__values=this&&this.__values||function(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(exports,"__esModule",{value:!0}),exports.tools=exports.SmartTools=void 0;var fs=require("node:fs"),luxon_1=require("luxon"),SmartTools=function(){function t(){this.formatters={}}return t.prototype.getStackTrace=function(t){var e,r={},n=Error.stackTraceLimit;Error.stackTraceLimit=1/0;var o=Error.prepareStackTrace;Error.prepareStackTrace=function(t,e){return e},Error.captureStackTrace(r,t||this.getStackTrace);var i=null!==(e=r.stack)&&void 0!==e?e:[];return Error.prepareStackTrace=o,Error.stackTraceLimit=n,i.map(function(t){return{columnNumber:t.getColumnNumber(),fileName:t.getFileName(),functionName:t.getFunctionName(),lineNumber:t.getLineNumber(),methodName:t.getMethodName(),native:t.isNative(),typeName:t.getTypeName()}})},t.prototype.parseStackTrace=function(t){var e=[];t.stack&&(e=t.stack.split("\n").slice(1).map(function(t){var e=null;if(t.match(/^\s*-{4,}$/))e={fileName:t,lineNumber:null,functionName:null,typeName:null,methodName:null,columnNumber:null,native:null};else{var r=t.match(/at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);if(r){var n=null,o=null,i=null,a=null,s=null,u="native"===r[5];if(r[1]){var l=(i=r[1]).lastIndexOf(".");if("."==i[l-1]&&l--,l>0){n=i.substring(0,l),o=i.substring(l+1);var c=n.indexOf(".Module");c>0&&(i=i.substring(c+1),n=n.substring(0,c))}}o&&(a=n,s=o),"<anonymous>"===o&&(s=null,i=null),e={fileName:r[2],lineNumber:parseInt(r[3],10),functionName:i,typeName:a,methodName:s,columnNumber:parseInt(r[4],10),native:u}}}return e},this).filter(function(t){return!!t}));return e},t.prototype.getCallerFromStack=function(t,e){var r;void 0===e&&(e={}),r=t instanceof Error?this.parseStackTrace(t):"function"==typeof t?this.parseStackTrace(t()):this.getStackTrace();var n=[fs.realpathSync(__filename)];e.ignoreFiles&&n.push.apply(n,__spreadArray([],__read(e.ignoreFiles),!1));var o,i=r.find(function(t){var e=t.functionName;return!n.includes(t.fileName)&&!(null==e?void 0:e.match(/stackprovider/i))});if(i){var a=i.functionName,s=i.fileName.replace("file://","");e.projectRoot&&(s=s.replace(e.projectRoot,".")),o=a?"".concat(s,":").concat(i.lineNumber," (").concat(a,")"):"".concat(s,":").concat(i.lineNumber)}else o="unknown location";return o},t.prototype.kebabCase=function(t){return this.splitWords(t).join("-")},t.prototype.snakeCase=function(t){return this.splitWords(t).join("_")},t.prototype.camelCase=function(t){var e;if(t){var r=this.splitWords(t);e=r.shift(),r.length>0&&(e+=r.map(function(t){return t[0].toUpperCase()+t.substring(1)}).join(""))}else e="";return e},t.prototype.pascalCase=function(t){var e;t?e=this.splitWords(t).map(function(t){return t.length>0?t[0].toUpperCase()+t.substring(1):""}).join(""):e="";return e},t.prototype.titleCase=function(t){return t?this.splitWords(t).map(function(t){return t[0].toUpperCase()+t.substring(1)}).join(" "):""},t.prototype.constantCase=function(t){return this.snakeCase(t).toUpperCase()},t.prototype.clone=function(t){return __assign({},t)},t.prototype.cloneDeep=function(t){var e,r,n=this;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(function(t){return n.cloneDeep(t)});var o={};try{for(var i=__values(Object.keys(t)),a=i.next();!a.done;a=i.next()){var s=a.value;o[s]=this.cloneDeep(t[s])}}catch(t){e={error:t}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return o},t.prototype.isSimpleObject=function(t){return!!t&&t.constructor===Object},t.prototype.isObject=function(t){return!!t&&t===Object(t)},t.prototype.isArray=function(t){return Array.isArray(t)},t.prototype.isString=function(t){return"string"==typeof t||t instanceof String},t.prototype.isNumber=function(t){return"number"==typeof t&&isFinite(t)},t.prototype.isBoolean=function(t){return"boolean"==typeof t},t.prototype.isNull=function(t){return null===t},t.prototype.isUndefined=function(t){return void 0===t},t.prototype.isFunction=function(t){return"function"==typeof t},t.prototype.isDate=function(t){return t instanceof Date},t.prototype.isRegExp=function(t){return t instanceof RegExp},t.prototype.isError=function(t){return t instanceof Error},t.prototype.isSymbol=function(t){return"symbol"==typeof t},t.prototype.isEmpty=function(t){return null==t||(this.isString(t)||this.isArray(t)?0===t.length:!!this.isSimpleObject(t)&&0===Object.keys(t).length)},t.prototype.isPrimitive=function(t){return this.isString(t)||this.isNumber(t)||this.isBoolean(t)||this.isNull(t)||this.isUndefined(t)||this.isSymbol(t)},t.prototype.toDate=function(t){return t instanceof Date?t:this.toDateTime(t).toJSDate()},t.prototype.toDateTime=function(t){var e;if("number"==typeof t)e=luxon_1.DateTime.fromMillis(t);else if("string"==typeof t)(e=luxon_1.DateTime.fromISO(t)).isValid||(e=luxon_1.DateTime.fromJSDate(new Date(t)));else if(t instanceof luxon_1.DateTime)e=t;else if(t instanceof Date)e=luxon_1.DateTime.fromJSDate(t);else{if(null!=t)throw"unknown date '".concat(t,"'");e=luxon_1.DateTime.now()}return e},t.prototype.toTimestamp=function(t){return"number"==typeof t?t:t instanceof Date?t.getTime():t instanceof luxon_1.DateTime?t.toMillis():this.toDateTime(t).toMillis()},t.prototype.formatDate=function(t,e){var r,n;t&&"number"!=typeof t&&"string"!=typeof t||(t=new Date(null!=t?t:Date.now())),e||(e={});var o=null!==(r=e.tz)&&void 0!==r?r:Intl.DateTimeFormat().resolvedOptions().timeZone,i=this.formatters[o];i||(i=new Intl.DateTimeFormat("se",{timeZone:o,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}),this.formatters[o]=i);var a=i.format(t);if(e.noBlanks)a=a.replace(/ /,"T");else if(e.separator){var s=a.split(/[T \-:.]/);a=s.join(e.separator)}return e.millis&&(a+=(null!==(n=e.separator)&&void 0!==n?n:".")+t.getMilliseconds().toString().padStart(3,"0")),a},t.prototype.millisToTimeString=function(t,e,r){void 0===e&&(e=!1),void 0===r&&(r=!1);var n,o=new Date(t);if(o.getMonth()>0||o.getFullYear()>1970)throw new Error("date difference too large");var i=24*(o.getUTCDate()-1)+o.getUTCHours();return n=r?i>0?i+(r?"h":":")+String(o.getUTCMinutes()).padStart(2,"0")+(r?"m":":"):o.getUTCMinutes().toString()+"m":i.toString().padStart(2,"0")+":"+String(o.getUTCMinutes()).padStart(2,"0")+":",n+=o.getUTCSeconds().toString().padStart(2,"0"),e&&(n+="."+Math.round(o.getMilliseconds()).toString().padStart(3,"0")),r&&(n+="s"),n},t.prototype.sleep=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){setTimeout(function(){e()},t)})]})})},t.prototype.getErrorText=function(t){return"string"==typeof t?t:t?t.error?""+t.error:t.message?""+t.message:t.text?""+t.text:t.status?""+t.status:t.stderr?""+t.stderr:t.stdout?""+t.stdout:t.code?"number"==typeof t.code?"Error #".concat(t.code):""+t.code:"function"==t.toString?t.toString():"object"==t?JSON.stringify(t):"".concat(t):"Unknown Error (".concat(t,")")},t.prototype.castToType=function(t,e){return"number"==e?Number(t):"boolean"==e?!!t&&(1===t||!0===t||["1","T","TRUE"].includes(t.toUpperCase())):t},t.prototype.splitWords=function(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase().split("-")},t}();exports.SmartTools=SmartTools,exports.tools=new SmartTools;
@@ -1,20 +0,0 @@
1
- import Mysql, { Connection, ConnectionConfig } from "mysql";
2
- import { AbstractModel } from "../models/abstract-model";
3
- import { SmartDb } from "../smart-db";
4
- import { GenericModelData, SmartDbRunResult, SmartDbTableInfo } from "../smart-db-interfaces";
5
- import { SmartDbSqlBuildData } from "../smart-db-sql-build-data";
6
- export declare class SmartDbMysql2 extends SmartDb {
7
- protected db: Mysql.Connection;
8
- constructor(connectorOrDb: string | ConnectionConfig | Connection);
9
- close(): Promise<boolean>;
10
- commit(): Promise<void>;
11
- exec(script: string): Promise<void>;
12
- exists<T extends AbstractModel<T, D>, D extends GenericModelData>(modelClass: string | (new () => T), type?: "view" | "table" | "index", indexTableName?: string): Promise<boolean>;
13
- getDatabaseType(): string;
14
- getDbQuote(): string;
15
- getTableInfo(table: string): Promise<SmartDbTableInfo>;
16
- rollback(): Promise<void>;
17
- protected statementRun(buildData: SmartDbSqlBuildData): Promise<SmartDbRunResult>;
18
- protected statementGet<T extends object>(buildData: SmartDbSqlBuildData): Promise<T>;
19
- protected statementGetAll<T>(buildData: SmartDbSqlBuildData): Promise<T[]>;
20
- }
@@ -1 +0,0 @@
1
- import _ from"lodash";import Mysql from"mysql";import{SmartDb}from"../smart-db";export class SmartDbMysql2 extends SmartDb{constructor(t){t.config&&t.connect?(super(t.config),this.db=t):(super(t),this.db=Mysql.createConnection(t))}close(){return new Promise(((t,e)=>{this.db.end((e=>{this.isReady=!1,e?(this.lastError=e,t(!1)):t(!0)}))}))}commit(){return new Promise(((t,e)=>{this.db.commit((r=>{r?(this.lastError=r,e(r)):t()}))}))}exec(t){return new Promise(((e,r)=>{try{this.db.query(t,((t,s,o)=>{t?(this.lastError=t,r(t)):e()}))}catch(t){r(t)}}))}exists(t,e,r){return new Promise(((e,r)=>{const s=_.isString(t)?t:t.getTableName();this.db.query(`show tables like '${s}'`,((t,s,o)=>{t?(this.lastError=t,r(t)):e(s&&s.length>0)}))}))}getDatabaseType(){return"mysql"}getDbQuote(){return"`"}getTableInfo(t){throw new Error("Method not implemented (getTableInfo)")}rollback(){return new Promise(((t,e)=>{this.db.rollback((r=>{r?(this.lastError=r,e(r)):t()}))}))}statementRun(t){return new Promise(((e,r)=>{this.db.query(t.sql,t.values,((t,s,o)=>{if(t)this.lastError=t,r(t);else{const t={changes:s.changedRows,affected:s.affectedRows,lastId:s.insertId};e(t)}}))}))}statementGet(t){return new Promise(((e,r)=>{try{this.db.query(t.sql,t.values,((t,s,o)=>{t?(this.lastError=t,r(t)):e(s&&s[0])}))}catch(t){this.lastError=t,r(t)}}))}statementGetAll(t){return new Promise(((e,r)=>{this.db.query(t.sql,t.values,((t,s,o)=>{t?(this.lastError=t,r(t)):(console.log(o),e(s&&s))}))}))}}
@@ -1,23 +0,0 @@
1
- import Sqlite3 from "sqlite3";
2
- import { AbstractModel } from "../models/abstract-model";
3
- import { SmartDb } from "../smart-db";
4
- import { GenericModelData, SmartDbRunResult, SmartDbTableInfo } from "../smart-db-interfaces";
5
- import { SmartDbSqlBuildData } from "../smart-db-sql-build-data";
6
- export interface SmartDbSqlite3Options {
7
- mode?: number;
8
- callback?: (this: Sqlite3.Database, err: Error | null) => void;
9
- }
10
- export declare class SmartDbSqlite3 extends SmartDb {
11
- protected db: Sqlite3.Database;
12
- constructor(connectorOrDb: string | Sqlite3.Database, options?: SmartDbSqlite3Options);
13
- close(): Promise<boolean>;
14
- commit(): Promise<void>;
15
- exec(script: string): Promise<void>;
16
- exists<T extends AbstractModel<T, D>, D extends GenericModelData>(modelClass: string | (new () => T), type?: "view" | "table" | "index", indexTableName?: string): Promise<boolean>;
17
- getDatabaseType(): string;
18
- getTableInfo(table: string): Promise<SmartDbTableInfo>;
19
- rollback(): Promise<void>;
20
- protected statementRun(buildData: SmartDbSqlBuildData): Promise<SmartDbRunResult>;
21
- protected statementGet<T extends object>(buildData: SmartDbSqlBuildData): Promise<T>;
22
- protected statementGetAll<T>(buildData: SmartDbSqlBuildData): Promise<T[]>;
23
- }
@@ -1 +0,0 @@
1
- import _ from"lodash";import Sqlite3 from"sqlite3";import{SqliteMasterModel}from"../models/sqlite-master-model";import{SmartDb}from"../smart-db";export class SmartDbSqlite3 extends SmartDb{constructor(t,r){_.isString(t)?(super(t),this.db=new Sqlite3.Database(t,r&&r.mode,r&&r.callback)):(super(null),this.db=t)}close(){return new Promise(((t,r)=>{try{this.smartDbLog.setDb(null),this.db.close((r=>{this.isReady=!1,r?(this.lastError=r,t(!1)):t(!0)}))}catch(t){this.lastError=t,r(t)}}))}commit(){return this.exec("commit")}exec(t){return new Promise(((r,e)=>{try{this.db.exec(t,(t=>{t?(this.lastError=t,e(t)):r()}))}catch(t){this.lastError=t,e(t)}}))}exists(t,r,e){return new Promise(((s,a)=>{try{const i=_.isString(t)?t:t.getTableName();this.getFirst(SqliteMasterModel,{name:i,type:r,tblName:e}).then((t=>{s(!!t)})).catch((t=>{a(t)}))}catch(t){this.lastError=t,a(t)}}))}getDatabaseType(){return"sqlite3"}getTableInfo(t){throw new Error("Method not implemented (getTableInfo)")}rollback(){return this.exec("rollback")}statementRun(t){return new Promise(((r,e)=>{try{const s=this;this.db.run(t.sql,t.values,(function(t){t?(s.lastError=t,e(t)):r({changes:this.changes,affected:this.changes,lastId:this.lastID})}))}catch(t){this.lastError=t,e(t)}}))}statementGet(t){return new Promise(((r,e)=>{try{const s=this;this.db.prepare(t.sql,(function(a){a?e(a):this.get(t.values,(function(t,a){t?(s.lastError=t,e(t)):r(a)}))}))}catch(t){this.lastError=t,e(t)}}))}statementGetAll(t){return new Promise(((r,e)=>{try{const s=this;this.db.prepare(t.sql,(function(a){a?(s.lastError=a,e(a)):this.all(t.values,(function(t,a){t?(s.lastError=t,e(t)):r(a)}))}))}catch(t){this.lastError=t,e(t)}}))}}
@@ -1,23 +0,0 @@
1
- import { ModelAttributeMap } from "../smart-db-interfaces";
2
- import { AbstractModel } from "./abstract-model";
3
- export interface OracleCatModelData extends Record<string, any> {
4
- name?: string;
5
- type?: string;
6
- }
7
- export declare class OracleCatModel extends AbstractModel<OracleCatModel, OracleCatModelData> {
8
- private _name?;
9
- private _type;
10
- static readonly attributeMap: ModelAttributeMap;
11
- static getClassName(): string;
12
- static getTableName(): string;
13
- static from(other: OracleCatModel): OracleCatModel;
14
- clone(): OracleCatModel;
15
- getClassName(): string;
16
- getTableName(): string;
17
- getAttributeMap(): ModelAttributeMap;
18
- getPrimaryKey(): string;
19
- get name(): string;
20
- set name(name: string);
21
- get type(): string;
22
- set type(type: string);
23
- }
@@ -1 +0,0 @@
1
- import{AbstractModel}from"./abstract-model";export class OracleCatModel extends AbstractModel{static getClassName(){return"OracleCatModel"}static getTableName(){return"cat"}static from(t){let e=null;return t&&(e=new OracleCatModel,t instanceof OracleCatModel?Object.assign(e,t):e.assign(t)),e}clone(){return OracleCatModel.from(this)}getClassName(){return"OracleCatModel"}getTableName(){return"cat"}getAttributeMap(){return OracleCatModel.attributeMap}getPrimaryKey(){return"name"}get name(){return this._name}set name(t){this._name=t}get type(){return this._type}set type(t){this._type=t}}OracleCatModel.attributeMap={TABLE_TYPE:{physical:!0,type:"string",attribute:"_type"},type:{alias:"TABLE_TYPE",typeScriptStyle:!0,type:"string",attribute:"_type"},TABLE_NAME:{physical:!0,type:"string",attribute:"_name"},name:{alias:"TABLE_NAME",typeScriptStyle:!0,type:"string",attribute:"_name"}};
@@ -1,39 +0,0 @@
1
- import { ModelAttributeMap } from "../smart-db-interfaces";
2
- import { AbstractModel } from "./abstract-model";
3
- export interface OracleUserTabColumnsModelData extends Record<string, any> {
4
- tableName?: string;
5
- columnName?: string;
6
- dataType?: string;
7
- nullable?: string;
8
- columnId?: string;
9
- defaultValue?: string;
10
- }
11
- export declare class OracleUserTabColumnsModel extends AbstractModel<OracleUserTabColumnsModel, OracleUserTabColumnsModelData> {
12
- private _tableName?;
13
- private _columnName?;
14
- private _dataType;
15
- private _nullable;
16
- private _columnId;
17
- private _defaultValue;
18
- static readonly attributeMap: ModelAttributeMap;
19
- static getClassName(): string;
20
- static getTableName(): string;
21
- static from(other: OracleUserTabColumnsModel): OracleUserTabColumnsModel;
22
- clone(): OracleUserTabColumnsModel;
23
- getClassName(): string;
24
- getTableName(): string;
25
- getAttributeMap(): ModelAttributeMap;
26
- getPrimaryKey(): string;
27
- get columnId(): number;
28
- set columnId(value: number);
29
- get columnName(): string;
30
- set columnName(type: string);
31
- get dataType(): string;
32
- set dataType(type: string);
33
- get defaultValue(): string;
34
- set defaultValue(value: string);
35
- get nullable(): string;
36
- set nullable(value: string);
37
- get tableName(): string;
38
- set tableName(name: string);
39
- }
@@ -1 +0,0 @@
1
- import{AbstractModel}from"./abstract-model";export class OracleUserTabColumnsModel extends AbstractModel{static getClassName(){return"OracleUserTabColumnsModel"}static getTableName(){return"user_tab_columns"}static from(t){let e=null;return t&&(e=new OracleUserTabColumnsModel,t instanceof OracleUserTabColumnsModel?Object.assign(e,t):e.assign(t)),e}clone(){return OracleUserTabColumnsModel.from(this)}getClassName(){return"OracleUserTabColumnsModel"}getTableName(){return"user_tab_columns"}getAttributeMap(){return OracleUserTabColumnsModel.attributeMap}getPrimaryKey(){return"name"}get columnId(){return this._columnId}set columnId(t){this._columnId=t}get columnName(){return this._columnName}set columnName(t){this._columnName=t}get dataType(){return this._dataType}set dataType(t){this._dataType=t}get defaultValue(){return this._defaultValue}set defaultValue(t){this._defaultValue=t}get nullable(){return this._nullable}set nullable(t){this._nullable=t}get tableName(){return this._tableName}set tableName(t){this._tableName=t}}OracleUserTabColumnsModel.attributeMap={DATA_TYPE:{physical:!0,type:"string",attribute:"_dataType"},dataType:{alias:"DATA_TYPE",typeScriptStyle:!0,type:"string",attribute:"_dataType"},TABLE_NAME:{physical:!0,type:"string",attribute:"_tableName"},tableName:{alias:"TABLE_NAME",typeScriptStyle:!0,type:"string",attribute:"_tableName"},COLUMN_NAME:{physical:!0,type:"string",attribute:"_columnName"},columnName:{alias:"COLUMN_NAME",typeScriptStyle:!0,type:"string",attribute:"_columnName"},DEFAULT_VALUE:{physical:!0,type:"string",attribute:"_defaultValue"},defaultValue:{alias:"DEFAULT_VALUE",typeScriptStyle:!0,type:"string",attribute:"_defaultValue"},COLUMN_ID:{physical:!0,type:"number",attribute:"_columnId"},columnId:{alias:"COLUMN_ID",typeScriptStyle:!0,type:"number",attribute:"_columnId"},NULLABLE:{physical:!0,type:"string",attribute:"_nullable"},nullable:{alias:"NULLABLE",typeScriptStyle:!0,type:"string",attribute:"_nullable"}};
@@ -1,43 +0,0 @@
1
- import { ModelAttributeMap } from "../smart-db-interfaces";
2
- import { AbstractModel } from "./abstract-model";
3
- export interface OracleUserTabColumnsViewModelData extends Record<string, any> {
4
- tableName?: string;
5
- columnName?: string;
6
- dataType?: string;
7
- nullable?: string;
8
- columnId?: string;
9
- defaultValue?: string;
10
- constraintType?: string;
11
- }
12
- export declare class OracleUserTabColumnsViewModel extends AbstractModel<OracleUserTabColumnsViewModel, OracleUserTabColumnsViewModelData> {
13
- private _tableName?;
14
- private _columnName?;
15
- private _dataType;
16
- private _nullable;
17
- private _columnId;
18
- private _defaultValue;
19
- private _constraintType;
20
- static readonly attributeMap: ModelAttributeMap;
21
- static getClassName(): string;
22
- static getTableName(): string;
23
- static from(other: OracleUserTabColumnsViewModel): OracleUserTabColumnsViewModel;
24
- clone(): OracleUserTabColumnsViewModel;
25
- getClassName(): string;
26
- getTableName(): string;
27
- getAttributeMap(): ModelAttributeMap;
28
- getPrimaryKey(): string;
29
- get columnId(): number;
30
- set columnId(value: number);
31
- get columnName(): string;
32
- set columnName(type: string);
33
- get constraintType(): string;
34
- set constraintType(value: string);
35
- get dataType(): string;
36
- set dataType(type: string);
37
- get defaultValue(): string;
38
- set defaultValue(value: string);
39
- get nullable(): string;
40
- set nullable(value: string);
41
- get tableName(): string;
42
- set tableName(name: string);
43
- }
@@ -1 +0,0 @@
1
- import{AbstractModel}from"./abstract-model";export class OracleUserTabColumnsViewModel extends AbstractModel{static getClassName(){return"OracleUserTabColumnsViewModel"}static getTableName(){return"smart_db_user_tab_columns_view"}static from(t){let e=null;return t&&(e=new OracleUserTabColumnsViewModel,t instanceof OracleUserTabColumnsViewModel?Object.assign(e,t):e.assign(t)),e}clone(){return OracleUserTabColumnsViewModel.from(this)}getClassName(){return"OracleUserTabColumnsViewModel"}getTableName(){return"smart_db_user_tab_columns_view"}getAttributeMap(){return OracleUserTabColumnsViewModel.attributeMap}getPrimaryKey(){return"columnId"}get columnId(){return this._columnId}set columnId(t){this._columnId=t}get columnName(){return this._columnName}set columnName(t){this._columnName=t}get constraintType(){return this._constraintType}set constraintType(t){this._constraintType=t}get dataType(){return this._dataType}set dataType(t){this._dataType=t}get defaultValue(){return this._defaultValue}set defaultValue(t){this._defaultValue=t}get nullable(){return this._nullable}set nullable(t){this._nullable=t}get tableName(){return this._tableName}set tableName(t){this._tableName=t}}OracleUserTabColumnsViewModel.attributeMap={DATA_TYPE:{physical:!0,type:"string",attribute:"_dataType"},dataType:{alias:"DATA_TYPE",typeScriptStyle:!0,type:"string",attribute:"_dataType"},TABLE_NAME:{physical:!0,type:"string",attribute:"_tableName"},tableName:{alias:"TABLE_NAME",typeScriptStyle:!0,type:"string",attribute:"_tableName"},COLUMN_NAME:{physical:!0,type:"string",attribute:"_columnName"},columnName:{alias:"COLUMN_NAME",typeScriptStyle:!0,type:"string",attribute:"_columnName"},DEFAULT_VALUE:{physical:!0,type:"string",attribute:"_defaultValue"},defaultValue:{alias:"DEFAULT_VALUE",typeScriptStyle:!0,type:"string",attribute:"_defaultValue"},COLUMN_ID:{physical:!0,type:"number",attribute:"_columnId"},columnId:{alias:"COLUMN_ID",typeScriptStyle:!0,type:"number",attribute:"_columnId"},NULLABLE:{physical:!0,type:"string",attribute:"_nullable"},nullable:{alias:"NULLABLE",typeScriptStyle:!0,type:"string",attribute:"_nullable"},CONSTRAINT_TYPE:{physical:!0,type:"string",attribute:"_constraintType"},constraintType:{alias:"CONSTRAINT_TYPE",typeScriptStyle:!0,type:"string",attribute:"_constraintType"}};
@@ -1,23 +0,0 @@
1
- import { FieldNamingStyle, GenericModelData, ModelAttributeMap } from "../smart-db-interfaces";
2
- export declare abstract class AbstractModel<T extends AbstractModel<T, D>, D extends GenericModelData> {
3
- abstract clone(): T;
4
- abstract getClassName(): string;
5
- abstract getTableName(): string;
6
- abstract getPrimaryKey(): string;
7
- abstract getAttributeMap(): ModelAttributeMap;
8
- static readonly attributeMap: ModelAttributeMap;
9
- static getTableName(): string;
10
- static from(other: any): any;
11
- assign(other: T | D, options?: {
12
- only?: string[];
13
- exclude?: string[];
14
- skipUndefined?: boolean;
15
- }): void;
16
- setValue(attribute: string, value: string | number | boolean | Date): void;
17
- getValue(attribute: string): string | number | boolean;
18
- hasAttribute(attribute: string): boolean;
19
- clear(attributes: string | string[]): void;
20
- getPlainObject(includeVirtuals?: boolean, fields?: string[]): D;
21
- getPlainObject(style?: FieldNamingStyle, includeVirtuals?: boolean, fields?: string[]): GenericModelData;
22
- private toDbTimestamp;
23
- }
@@ -1 +0,0 @@
1
- import _ from"lodash";import{FieldNamingStyle}from"../smart-db-interfaces";export class AbstractModel{static getTableName(){return"overload this in child class"}static from(t){}assign(t,e){if("object"==typeof t){const i=this.getAttributeMap();let s=!e||!!e.skipUndefined;Object.keys(i).forEach((i=>{let a=!0;if(e&&(e.only&&!_.includes(e.only,i)&&(a=!1),e.exclude&&_.includes(e.exclude,i)&&(a=!1)),a)if(t instanceof AbstractModel&&t.hasAttribute(i)){const e=t.getValue(i);s&&void 0===e||this.setValue(i,e)}else if(t.hasOwnProperty(i)){const e=t[i];s&&void 0===e||this.setValue(i,e)}}))}}setValue(t,e){const i=this.getAttributeMap()[t];if(!i)throw`unknown attribute ${t} for ${this.getClassName()}`;if(null===e)this[i.attribute]=null;else if(void 0===e)delete this[i.attribute];else{switch(i.type){case"SqlValueType":break;case"string":_.isNumber(e)?e=e.toString():_.isBoolean(e)?e=e?"true":"false":_.isDate(e)&&(e=this.toDbTimestamp(e));break;case"number":_.isString(e)?e=parseFloat(e):_.isBoolean(e)?e=e?1:0:_.isDate(e)&&(e=e.getTime());break;case"boolean":_.isString(e)?e=!e.match(/(F|N|false|no|0)/i):_.isNumber(e)?e=!!e:_.isDate(e)&&(e=!0);break;case"Date":_.isString(e)&&e.match(/^\d{4}-[01][0-9]-[0-3][0-9][ T][0-2][0-9]:[0-5][0-9]:[0-5][0-9]\s*$/)&&(e+=" GMT"),e=_.isNumber(e)||_.isString(e)||_.isDate(e)?new Date(e):new Date;break;default:throw`AbstractModel.setValue: unknown data type '${i.type}'`}this[i.attribute]=e}}getValue(t){return this[this.getAttributeMap()[t].attribute]}hasAttribute(t){return!!this.getAttributeMap()[t]}clear(t){_.isArray(t)||(t=[t]);const e=this.getAttributeMap();t.forEach((t=>{const i=e[t];i&&delete this[i.attribute]}))}getPlainObject(t,e,i){let s,a=FieldNamingStyle.TypeScript,r=!1;void 0!==t&&("boolean"==typeof t?(r=t,s=e):(a=t,r=e,s=i));const l=this.getAttributeMap(),n=[];void 0===r&&(r=!0),_.forOwn(l,((t,e)=>{let i=a==FieldNamingStyle.All||r&&t.virtual;if(!i)if(a==FieldNamingStyle.Database)i=t.physical;else{if(a!=FieldNamingStyle.TypeScript)throw`unknown style ${a}`;i=t.typeScriptStyle}i&&(s&&!_.includes(s,e)||n.push(e))}));const o={};return n.forEach((t=>{const e=l[t];if(e){const i=this[e.attribute];void 0!==i&&(o[t]=i)}})),o}toDbTimestamp(t){let e;return t&&(_.isNumber(t)&&(t=new Date(t)),e=t.toISOString().substr(0,23).replace("T"," ")),e}}AbstractModel.attributeMap={};