@egi/smart-db 2.6.5 → 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
@@ -1,32 +1,105 @@
1
- import { Connection } from "oracledb";
1
+ import * as OracleDb from "oracledb";
2
+ import { Connection, ConnectionAttributes } from "oracledb";
2
3
  import { AbstractModel } from "../models/abstract-model";
3
4
  import { SmartDb } from "../smart-db";
4
- import { GenericModelData, SmartDbRunResult, SmartDbTableInfo } from "../smart-db-interfaces";
5
+ import { GenericModelData, ModelClass, SmartDbOptions, SmartDbRunResult, SmartDbTableInfo, SqlValueType } from "../smart-db-interfaces";
5
6
  import { SmartDbSqlBuildData } from "../smart-db-sql-build-data";
6
- export interface SmartDbOracleOptions {
7
- user: string;
8
- password: string;
9
- silent?: boolean;
10
- onReady?: (db: Connection, error?: any) => void;
11
- noDbLogging?: boolean;
7
+ /** Options for {@link SmartDbOracle}, extending the common {@link SmartDbOptions}. */
8
+ export interface SmartDbOracleOptions extends SmartDbOptions<SmartDbOracle> {
9
+ /**
10
+ * When `true`, every DML statement (INSERT / UPDATE / DELETE) is committed immediately
11
+ * without requiring an explicit `commit()` call. Defaults to `false`.
12
+ */
13
+ autoCommit?: boolean;
14
+ /**
15
+ * When `true`, initialises the Oracle client in thick mode using the native Oracle libraries
16
+ * found at `ORACLE_HOME` (macOS/Linux). Thick mode is required for features such as Advanced
17
+ * Queuing, Sharding, and some connection pool options. Only the first instance to set this
18
+ * flag actually calls `initOracleClient`; subsequent instances skip the call.
19
+ */
20
+ thickMode?: boolean;
12
21
  }
13
- export declare class SmartDbOracle extends SmartDb {
14
- protected db: Connection;
15
- private connectorOrDb;
16
- private options;
17
- static libInit: boolean;
18
- constructor(connectorOrDb: string | Connection, options?: SmartDbOracleOptions);
19
- close(): Promise<boolean>;
20
- commit(): Promise<void>;
21
- exec(script: string): Promise<void>;
22
- exists<T extends AbstractModel<T, D>, D extends GenericModelData>(modelClass: string | (new () => T), type?: "view" | "table" | "index", indexTableName?: string): Promise<boolean>;
22
+ /**
23
+ * SmartDB driver for Oracle Database via the `oracledb` library.
24
+ *
25
+ * All operations are **async-only** — there are no sync variants.
26
+ * The connection is established asynchronously in the constructor via `connectDb()`.
27
+ * On connect, the session is prepared with `NLS_DATE_FORMAT` and `NLS_TIMESTAMP_FORMAT`
28
+ * so that date/time values are exchanged as ISO-style strings. `needsExplicitEscape` is
29
+ * forced to `true` to handle Oracle's LIKE escape requirements.
30
+ *
31
+ * For views, `getTableInfo()` resolves the underlying base table to discover the primary
32
+ * key and sequence name used for INSERT operations.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const db = new SmartDbOracle(
37
+ * { user: "hr", password: "secret", connectString: "localhost/XEPDB1" },
38
+ * { module: "my-app", sqlFilesDirectory: "./sql", onReady: (db, err) => { ... } }
39
+ * );
40
+ * await db.databaseReady();
41
+ * ```
42
+ */
43
+ export declare class SmartDbOracle extends SmartDb<SmartDbOracle> {
44
+ static thickModeInit: boolean;
45
+ /**
46
+ * Initialises the Oracle client (once, if `thickMode` is requested) and calls `connectDb()`
47
+ * asynchronously. The ready-state will be `PREPARING` until the connection succeeds
48
+ * (`CONNECTED` → `READY`) or fails (`ERROR`).
49
+ *
50
+ * If neither `connectString` nor `connectionString` is provided in `config`, the driver
51
+ * falls back to the `ORACLE_SID` / `TWO_TASK` environment variables.
52
+ *
53
+ * @param config - oracledb `ConnectionAttributes` (user, password, connectString, etc.).
54
+ * @param options - SmartDB options plus Oracle-specific `autoCommit` and `thickMode`.
55
+ */
56
+ constructor(config: ConnectionAttributes, options?: SmartDbOracleOptions);
23
57
  getDatabaseType(): string;
24
58
  getTableInfo(tableName: string): Promise<SmartDbTableInfo>;
59
+ getDb(): OracleDb.Connection;
60
+ protected db: Connection;
61
+ protected options: SmartDbOracleOptions;
62
+ commit(): Promise<void>;
63
+ exec(script: string, params?: SqlValueType[]): Promise<void>;
64
+ query(script: string, params?: SqlValueType[]): Promise<GenericModelData[]>;
65
+ exists<T extends AbstractModel<T, D>, D extends GenericModelData>(modelClass: string | ModelClass<T>, type?: "view" | "table" | "index", indexTableName?: string): Promise<boolean>;
25
66
  hasConcurrentTransactions(): boolean;
26
- reconnect(connectorOrDb?: string | Connection, options?: SmartDbOracleOptions): void;
27
67
  rollback(): Promise<void>;
28
- protected statementRun(buildData: SmartDbSqlBuildData): Promise<SmartDbRunResult>;
29
68
  protected statementGet<T extends object>(buildData: SmartDbSqlBuildData): Promise<T>;
30
69
  protected statementGetAll<T>(buildData: SmartDbSqlBuildData): Promise<T[]>;
70
+ protected statementRun(buildData: SmartDbSqlBuildData): Promise<SmartDbRunResult>;
71
+ close(): Promise<boolean>;
72
+ /** Sends a round-trip ping to the Oracle server to verify the connection is alive. */
73
+ ping(): Promise<void>;
74
+ /**
75
+ * Reads the current value of an Oracle sequence (`CURRVAL`) without incrementing it.
76
+ * Used internally after an INSERT to return the generated primary key.
77
+ *
78
+ * @param sequenceName - Name of the Oracle sequence (e.g. `"MY_SEQ"`).
79
+ * @returns The current sequence value, or `null` if the query returned no rows.
80
+ */
81
+ getCurrentSequenceValue(sequenceName: string): Promise<number>;
82
+ /**
83
+ * (Re)connects to Oracle. Closes any existing connection first, then obtains a new one
84
+ * via `oracledb.getConnection()` and sets the session's NLS date/timestamp formats.
85
+ * Called automatically by the constructor; call it again to reconnect after a failure.
86
+ *
87
+ * @param config - oracledb `ConnectionAttributes` to use for the new connection.
88
+ */
89
+ connectDb(config: ConnectionAttributes): Promise<void>;
90
+ /**
91
+ * The Oracle library converts DATE and TIMESTAMP values to local time when it parses the string returned by
92
+ * the database. This method removes that local timezone offset, restoring the intended UTC value.
93
+ * Which column types are corrected depends on `dateTimeMode`:
94
+ * - `"rule"` — only TIMESTAMP columns (DATE columns are in local time intentionally).
95
+ * - `"utc"` — both TIMESTAMP and DATE columns (all were written as UTC).
96
+ * - `"local"` / `"none"` — no correction (local time is the intended representation).
97
+ *
98
+ * @param result
99
+ * @private
100
+ */
101
+ private adjustResultTimestamps;
102
+ private lookupSynonym;
31
103
  private replacePlaceholders;
104
+ private getTablePk;
32
105
  }
@@ -1 +1 @@
1
- import fs from"fs";import process from"node:process";import oracleDb from"oracledb";import{take}from"rxjs";import{OracleCatModel}from"../models/oracle-cat-model";import{OracleUserTabColumnsViewModel}from"../models/oracle-user-tab-columns-view-model";import{SmartDb}from"../smart-db";import{SmartErrorLocation}from"../smart-error";export class SmartDbOracle extends SmartDb{constructor(e,t){if(!SmartDbOracle.libInit){let e;"darwin"===process.platform&&(e=process.env.ORACLE_HOME),e&&fs.existsSync(e)&&oracleDb.initOracleClient({libDir:e}),SmartDbOracle.libInit=!0}"string"==typeof e?super(e,t?.noDbLogging):super(null),this.reconnect(e,t)}close(){return new Promise(((e,t)=>{try{this.smartDbLog.setDb(null),this.db.close((t=>{this.isReady=!1,t?(this.lastError=t,e(!1)):(this._onReady.next(!1),e(!0))}))}catch(e){this.lastError=e,t(e)}}))}commit(){return this.db.commit()}exec(e){return new Promise(((t,r)=>{try{this.db.execute(e,(e=>{e?(this.lastError=e,r(e)):t()}))}catch(e){this.lastError=e,r(e)}}))}exists(e,t,r){return new Promise(((r,s)=>{try{const o="string"==typeof e?e:e.getTableName();this.getFirst(OracleCatModel,{name:o.toUpperCase(),type:t?t.toUpperCase():void 0}).then((e=>{r(!!e)})).catch((e=>{s(e)}))}catch(e){this.lastError=e,s(e)}}))}getDatabaseType(){return"oracle"}getTableInfo(e){return new Promise((async(t,r)=>{await this.getAll(OracleUserTabColumnsViewModel,{tableName:e.toUpperCase()}).then((s=>{if(!1!==s){let r=[];r=s.map((e=>({cid:e.columnId,name:e.columnName,type:e.dataType,notNull:"Y"!=e.nullable,defaultValue:e.defaultValue,isPk:"P"==e.constraintType}))),t({name:e,fields:r})}else r(this.getLastError())})).catch((e=>{this.lastError=e,r(e)}))}))}hasConcurrentTransactions(){return!0}reconnect(e,t){e?this.connectorOrDb=e:e=this.connectorOrDb,t?this.options=t:t=this.options,"string"==typeof e?oracleDb.getConnection(Object.assign({connectString:e},t??this.options)).then((e=>{this.db=e,t&&t.onReady&&this.onReady.pipe(take(1)).subscribe((r=>{r&&t.onReady(e)})),this.exec("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'").then((e=>{this.exec("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY:MM:DD HH24:MI:SS.FF'").then((e=>{this.isReady=!0})).catch((e=>{throw e}))})).catch((e=>{throw e}))})).catch((e=>{t&&t.onReady&&t.onReady(null,e),this.smartDbLog.logError(SmartErrorLocation.Database,"reconnect","unable prepare session database connection",e),this.isReady=null})):this.db=e}rollback(){return this.db.rollback()}statementRun(e){return new Promise(((t,r)=>{try{this.db.execute(this.replacePlaceholders(e.sql),e.values,((e,s)=>{e?(this.lastError=e,r(e)):this.commit().then((()=>{t({changes:s.rowsAffected,affected:s.rowsAffected,lastId:null})})).catch((e=>{r(e)}))}))}catch(e){this.lastError=e,r(e)}}))}statementGet(e){return new Promise(((t,r)=>{try{this.db.execute(this.replacePlaceholders(this.replacePlaceholders(e.sql)),e.values,{maxRows:1,outFormat:oracleDb.OUT_FORMAT_OBJECT},((e,s)=>{if(e)this.lastError=e,r(e);else{const e=s.rows[0];let r=null;if(e){r={};Object.keys(e).forEach((t=>{r[t.toLowerCase()]=e[t]}))}t(r)}}))}catch(e){this.lastError=e,r(e)}}))}statementGetAll(e){return new Promise(((t,r)=>{try{this.db.execute(this.replacePlaceholders(e.sql),e.values,{maxRows:0,outFormat:oracleDb.OUT_FORMAT_OBJECT}).then((e=>{t(e.rows)})).catch((e=>{this.lastError=e,r(e)}))}catch(e){this.lastError=e,r(e)}}))}replacePlaceholders(e){let t=1,r=!1;for(let s=0;s<e.length;s++)"'"==e[s]?r=!r:r||"?"!=e[s]||(e=e.substring(0,s)+":"+t+++e.substring(s+1));return e}}SmartDbOracle.libInit=!1;
1
+ "use strict";var __extends=this&&this.__extends||function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),__awaiter=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(a,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function c(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,c)}l((n=n.apply(e,t||[])).next())})},__generator=this&&this.__generator||function(e,t){var r,n,a,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=c(0),s.throw=c(1),s.return=c(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function c(c){return function(l){return function(c){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(o=0)),o;)try{if(r=1,n&&(a=2&c[0]?n.return:c[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,c[1])).done)return a;switch(n=0,a&&(c=[2&c[0],a.value]),c[0]){case 0:case 1:a=c;break;case 4:return o.label++,{value:c[1],done:!1};case 5:o.label++,n=c[1],c=[0];continue;case 7:c=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==c[0]&&2!==c[0])){o=0;continue}if(3===c[0]&&(!a||c[1]>a[0]&&c[1]<a[3])){o.label=c[1];break}if(6===c[0]&&o.label<a[1]){o.label=a[1],a=c;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(c);break}a[2]&&o.ops.pop(),o.trys.pop();continue}c=t.call(e,o)}catch(e){c=[6,e],n=0}finally{r=a=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,l])}}},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,a,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){a={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(a)throw a.error}}return s},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,a=0,o=t.length;a<o;a++)!n&&a in t||(n||(n=Array.prototype.slice.call(t,0,a)),n[a]=t[a]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SmartDbOracle=void 0;var fs=require("fs"),process=require("node:process"),OracleDb=require("oracledb"),smart_db_1=require("../smart-db"),smart_db_interfaces_1=require("../smart-db-interfaces"),smart_db_sql_build_data_1=require("../smart-db-sql-build-data"),smart_db_globals_1=require("../smart-db-globals"),oracle_all_objects_model_1=require("../models/oracle-all-objects-model"),oracle_all_dependencies_model_1=require("../models/oracle-all-dependencies-model"),oracle_all_triggers_model_1=require("../models/oracle-all-triggers-model"),oracle_all_constraints_model_1=require("../models/oracle-all-constraints-model"),oracle_all_cons_columns_model_1=require("../models/oracle-all-cons-columns-model"),oracle_all_tab_columns_model_1=require("../models/oracle-all-tab-columns-model"),smart_log_1=require("@egi/smart-log"),SmartDbOracle=function(e){function t(r,n){var a,o,s,c=this;if(n&&n.thickMode&&!t.thickModeInit){var l=void 0;"darwin"===process.platform&&(l=process.env.ORACLE_HOME),l&&fs.existsSync(l)&&OracleDb.initOracleClient({libDir:l}),t.thickModeInit=!0}var i=null!==(o=null!==(a=r.connectString)&&void 0!==a?a:r.connectionString)&&void 0!==o?o:"";if(""===i){var u=null!==(s=process.env.ORACLE_SID)&&void 0!==s?s:process.env.TWO_TASK;i=r.user?r.user+"@"+i:u,r.connectionString=i}return(c=e.call(this,i,Object.assign({needsExplicitEscape:!0},n))||this).log.debug("begin setup",{type:smart_log_1.SmartLocation.Database}),c.log.debug("initial db connect",{type:smart_log_1.SmartLocation.Database}),c.connectDb(r).catch(function(e){c.log.error("unable to prepare database connection",{type:smart_log_1.SmartLocation.Database,data:e})}),c}return __extends(t,e),t.prototype.getDatabaseType=function(){return"oracle"},t.prototype.getTableInfo=function(e){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(r){return[2,new Promise(function(r,n){return __awaiter(t,void 0,void 0,function(){var t,a,o,s,c,l,i,u,d,_,f,p,h,b,m,y,v,g,w,S,E,T,O,A,N,D,M,R,P,x,C,q,I,j;return __generator(this,function(k){switch(k.label){case 0:return k.trys.push([0,36,,37]),e=e.toUpperCase(),[4,this.getFirst(oracle_all_objects_model_1.OracleAllObjectsModel,{objectName:e,objectType:["TABLE","VIEW"]})];case 1:return(t=k.sent())?[4,this.getAll(oracle_all_tab_columns_model_1.OracleAllTabColumnsModel,{owner:t.owner,tableName:e},[],"columnId")]:[3,34];case 2:return a=k.sent(),o=void 0,"VIEW"!=t.objectType?[3,12]:[4,this.getAll(oracle_all_dependencies_model_1.OracleAllDependenciesModel,{owner:t.owner,name:t.objectName,type:"VIEW",referencedType:"TABLE"})];case 3:return 1!=(s=k.sent()).length?[3,4]:(o=s[0].referencedName,[3,11]);case 4:k.trys.push([4,9,10,11]),c=__values(s),l=c.next(),k.label=5;case 5:return l.done?[3,8]:(i=l.value,[4,this.getTablePk(i.referencedName,i.referencedOwner)]);case 6:for(u=k.sent(),d=u.length>0,_=0;_<u.length;_++)if(u[_]!=a[_].columnName){d=!1;break}if(d)return o=i.referencedName,[3,8];k.label=7;case 7:return l=c.next(),[3,5];case 8:return[3,11];case 9:return f=k.sent(),P={error:f},[3,11];case 10:try{l&&!l.done&&(x=c.return)&&x.call(c)}finally{if(P)throw P.error}return[7];case 11:return[3,13];case 12:o=t.objectName,k.label=13;case 13:return p=void 0,o?[4,this.getAll(oracle_all_triggers_model_1.OracleAllTriggersModel,{owner:t.owner,tableName:o,triggerType:"BEFORE EACH ROW",triggeringEvent:"INSERT"})]:[3,30];case 14:h=k.sent(),b=[],m=[],k.label=15;case 15:k.trys.push([15,20,21,22]),y=__values(h),v=y.next(),k.label=16;case 16:return v.done?[3,19]:(g=v.value,[4,this.getAll(oracle_all_dependencies_model_1.OracleAllDependenciesModel,{owner:t.owner,name:g.triggerName,referencedType:["SEQUENCE","SYNONYM"]},[],["referencedType"])]);case 17:w=k.sent(),m.push.apply(m,__spreadArray([],__read(w.filter(function(e){return"SYNONYM"==e.referencedType})),!1)),b.push.apply(b,__spreadArray([],__read(w.filter(function(e){return"SEQUENCE"==e.referencedType})),!1)),k.label=18;case 18:return v=y.next(),[3,16];case 19:return[3,22];case 20:return S=k.sent(),C={error:S},[3,22];case 21:try{v&&!v.done&&(q=y.return)&&q.call(y)}finally{if(C)throw C.error}return[7];case 22:k.trys.push([22,27,28,29]),E=__values(m),T=E.next(),k.label=23;case 23:return T.done?[3,26]:(O=T.value,[4,this.lookupSynonym(O)]);case 24:"SEQUENCE"==k.sent().referencedType&&b.push(O),k.label=25;case 25:return T=E.next(),[3,23];case 26:return[3,29];case 27:return A=k.sent(),I={error:A},[3,29];case 28:try{T&&!T.done&&(j=E.return)&&j.call(E)}finally{if(I)throw I.error}return[7];case 29:1==b.length&&(p=b[0].referencedName),k.label=30;case 30:return o?[4,this.getTablePk(o,t.owner)]:[3,32];case 31:return D=k.sent(),[3,33];case 32:D=[],k.label=33;case 33:return N=D,M=a.map(function(e){var t,r=e.dataType.replace(/\([^)]*\)$/,"");switch(r){case"TIMESTAMP":t="TIMESTAMP(".concat(e.dataScale,")");break;case"NUMBER":t=e.dataScale?"NUMBER(".concat(e.dataPrecision,",").concat(e.dataScale,")"):e.dataPrecision?"NUMBER(".concat(e.dataPrecision,")"):0===e.dataScale?"NUMBER(38)":"NUMBER";break;case"CHAR":case"CLOB":case"VARCHAR2":t=e.dataLength?"".concat(r,"(").concat(e.dataLength,")"):r;break;case"NVARCHAR2":t=e.dataLength?"".concat(r,"(").concat(e.dataLength/2,")"):"NVARCHAR2";break;default:t=r}return{cid:e.columnId,name:e.columnName,dbType:r,dbFullType:t,notNull:"Y"!=e.nullable,defaultValue:e.dataDefault,isPk:!!N.includes(e.columnName)}}).sort(function(e,t){return e.cid<t.cid?-1:e.cid>t.cid?1:0}),r({name:e,fields:M,pkSequenceName:p}),[3,35];case 34:n("no such table '".concat(e,"'")),k.label=35;case 35:return[3,37];case 36:return R=k.sent(),this.lastError=R,n(R),[3,37];case 37:return[2]}})})})]})})},t.prototype.getDb=function(){return this.db},t.prototype.commit=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,this.db.commit()]})})},t.prototype.exec=function(e,t){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(n){return[2,new Promise(function(n,a){try{var o=t&&t.length>0?r.replacePlaceholders(e):e;r.db.execute(o,null!=t?t:[],function(e){e?(r.lastError=e,a(e)):n()})}catch(e){r.lastError=e,a(e)}})]})})},t.prototype.query=function(e,t){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(n){return[2,new Promise(function(n,a){try{var o=t&&t.length>0?r.replacePlaceholders(e):e;r.db.execute(o,null!=t?t:[],{outFormat:OracleDb.OUT_FORMAT_OBJECT},function(e,t){var o;e?(r.lastError=e,a(e)):n(null!==(o=t.rows)&&void 0!==o?o:[])})}catch(e){r.lastError=e,a(e)}})]})})},t.prototype.exists=function(e,t,r){return __awaiter(this,void 0,void 0,function(){var r,n;return __generator(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),r="string"==typeof e?e:e.getTableName(),[4,this.getFirst(oracle_all_objects_model_1.OracleAllObjectsModel,{owner:(0,smart_db_globals_1.LITERAL)("USER"),objectName:r.toUpperCase(),objectType:t?t.toUpperCase():void 0})];case 1:return[2,!!a.sent()];case 2:throw n=a.sent(),this.lastError=n,n;case 3:return[2]}})})},t.prototype.hasConcurrentTransactions=function(){return!0},t.prototype.rollback=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,this.db.rollback()]})})},t.prototype.statementGet=function(e){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(r){return[2,new Promise(function(r,n){try{t.db.execute(t.replacePlaceholders(t.replacePlaceholders(e.sql)),e.values,{maxRows:1,outFormat:OracleDb.OUT_FORMAT_OBJECT},function(e,a){e?(t.lastError=e,n(e)):(t.adjustResultTimestamps(a),r(a.rows?a.rows[0]:null))})}catch(e){t.lastError=e,n(e)}})]})})},t.prototype.statementGetAll=function(e){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(r){return[2,new Promise(function(r,n){try{t.db.execute(t.replacePlaceholders(e.sql),e.values,{outFormat:OracleDb.OUT_FORMAT_OBJECT}).then(function(e){t.adjustResultTimestamps(e),r(e.rows)}).catch(function(e){t.lastError=e,n(e)})}catch(e){t.lastError=e,n(e)}})]})})},t.prototype.statementRun=function(e){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(r){return[2,new Promise(function(r,n){try{t.db.execute(t.replacePlaceholders(e.sql),e.values,{autoCommit:t.options.autoCommit},function(a,o){return __awaiter(t,void 0,void 0,function(){var t,s;return __generator(this,function(c){switch(c.label){case 0:return a?(this.lastError=a,n(a),[3,4]):[3,1];case 1:return t=null,e.type!=smart_db_sql_build_data_1.SmartDbSqlBuildDataType.Insert?[3,3]:(s=this.getPkSequenceName(e.modelName))?[4,this.getCurrentSequenceValue(s)]:[3,3];case 2:t=c.sent(),c.label=3;case 3:r({changes:o.rowsAffected,affected:o.rowsAffected,lastId:t}),c.label=4;case 4:return[2]}})})})}catch(e){t.lastError=e,n(e)}})]})})},t.prototype.close=function(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(r){switch(r.label){case 0:return r.trys.push([0,4,,5]),this.db?(this.log.setDbWriter(null),[4,this.db.break()]):[3,3];case 1:return r.sent(),[4,this.db.close()];case 2:r.sent(),this.readyState=smart_db_interfaces_1.SmartDbReadyState.CLOSED,r.label=3;case 3:return e=!0,[3,5];case 4:return t=r.sent(),this.lastError=t,this.readyState=smart_db_interfaces_1.SmartDbReadyState.ERROR,e=!1,[3,5];case 5:return[2,e]}})})},t.prototype.ping=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,this.db.ping()]})})},t.prototype.getCurrentSequenceValue=function(e){return __awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(n){switch(n.label){case 0:return t=new smart_db_sql_build_data_1.SmartDbSqlBuildData("select "+"".concat(e,'.currval as "value" from dual')),[4,this.statementGet(t)];case 1:return[2,(r=n.sent())&&r.value]}})})},t.prototype.connectDb=function(e){return __awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(n){switch(n.label){case 0:return[4,this.close()];case 1:n.sent(),this.readyState=smart_db_interfaces_1.SmartDbReadyState.PREPARING,n.label=2;case 2:return n.trys.push([2,6,,7]),t=this,[4,OracleDb.getConnection(e)];case 3:return t.db=n.sent(),this.log.debug("connection initialized",{type:smart_log_1.SmartLocation.Database}),[4,this.exec("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'")];case 4:return n.sent(),[4,this.exec("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF3'")];case 5:return n.sent(),this.log.debug("session prepared",{type:smart_log_1.SmartLocation.Database}),this.readyState=smart_db_interfaces_1.SmartDbReadyState.CONNECTED,[3,7];case 6:return r=n.sent(),this.lastError=r,this.readyState=smart_db_interfaces_1.SmartDbReadyState.ERROR,[3,7];case 7:return[2]}})})},t.prototype.adjustResultTimestamps=function(e){var t;if(!e)throw"cannot handle empty result";var r=null!==(t=this.options.dateTimeMode)&&void 0!==t?t:"rule";if("rule"==r||"utc"==r){var n=e.metaData.filter(function(e){return"utc"==r?"TIMESTAMP"==e.dbTypeName||"DATE"==e.dbTypeName:"TIMESTAMP"==e.dbTypeName});e.rows.forEach(function(e){n.forEach(function(t){e[t.name]&&(e[t.name]=new Date(e[t.name].getTime()-6e4*e[t.name].getTimezoneOffset()))})})}},t.prototype.lookupSynonym=function(e){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(r){switch(r.label){case 0:return"SYNONYM"!=e.referencedType?[3,2]:[4,this.getFirst(oracle_all_dependencies_model_1.OracleAllDependenciesModel,{owner:e.referencedOwner,name:e.referencedName,type:e.referencedType})];case 1:t=r.sent(),r.label=2;case 2:return[2,t]}})})},t.prototype.replacePlaceholders=function(e){for(var t=1,r=!1,n=0;n<e.length;n++)"'"==e[n]?r=!r:r||"?"!=e[n]||(e=e.substring(0,n)+":".concat(t++)+e.substring(n+1));return e},t.prototype.getTablePk=function(e,t){return __awaiter(this,void 0,void 0,function(){var r,n,a;return __generator(this,function(o){switch(o.label){case 0:return[4,this.getFirst(oracle_all_constraints_model_1.OracleAllConstraintsModel,{owner:t,tableName:e,constraintType:"P"})];case 1:return(n=o.sent())?[4,this.getAll(oracle_all_cons_columns_model_1.OracleAllConsColumnsModel,{owner:n.owner,constraintName:n.constraintName})]:[3,3];case 2:return a=o.sent(),r=a.map(function(e){return e.columnName}),[3,4];case 3:r=[],o.label=4;case 4:return[2,r]}})})},t.thickModeInit=!1,t}(smart_db_1.SmartDb);exports.SmartDbOracle=SmartDbOracle;
@@ -1 +1 @@
1
- import fs from"fs";import _ from"lodash";import process from"process";import{SmartDbBetterSqlite3}from"../drivers/smart-db-better-sqlite3";import{SmartDbOracle}from"../drivers/smart-db-oracle";import{OracleCatModel}from"../models/oracle-cat-model";import{SmartDbCoreTableModel}from"../models/smart-db-core-table-model";import{SqliteMasterModel}from"../models/sqlite-master-model";import{IN,NE,NOT_LIKE}from"../smart-db-globals";function getType(e){let t;return t=e?e.match(/varchar/i)||e.match(/text/i)?"string":e.match(/integer\(1\)/i)?"boolean":e.match(/date/i)?"Date":e.match(/integer/i)||e.match(/number/i)?"number":e.match(/long/i)||e.match(/raw/i)?"any":"SqlValueType":"SqlValueType",t}function getRelations(e){return new Promise((async(t,r)=>{e instanceof SmartDbOracle?e.getAll(OracleCatModel,{type:IN(["TABLE","VIEW"]),name:NOT_LIKE("BIN$%")}).then((a=>{a?t(a.map((e=>e.name.toLowerCase()))):r(e.getLastError())})).catch((e=>{r(e)})):e instanceof SmartDbBetterSqlite3?e.getAll(SqliteMasterModel,{type:IN(["table","view"]),name:NE("sqlite_sequence")}).then((a=>{a?t(a.map((e=>e.name))):r(e.getLastError())})).catch((e=>{r(e)})):r("unimplemented database type")}))}async function extractDbApi(e){console.log(`extract interface from '${e.db.getDbConnector()}' to '${e.modelDirectory}'`);const t=["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","If","import","in","instanceOf","interface","new","null","return","super","switch","this","throw","true","try","typeOf","var","void","while","with"];fs.existsSync(e.modelDirectory)||fs.mkdirSync(e.modelDirectory,{recursive:!0}),getRelations(e.db).then((async r=>{let a=[];if((e.skipCoreTables||e.justCoreTables)&&await e.db.exists(SmartDbCoreTableModel)){const t=await e.db.getAll(SmartDbCoreTableModel);if(!1===t)throw e.db.getLastError();t.forEach((e=>{a.push(e.name)}))}const n=[];for(const s of r){let r=!0;if(e.justCoreTables?r=a.includes(s):e.skipCoreTables&&(r=!a.includes(s)),r){const r=s[0].toUpperCase()+_.camelCase(s.substring(1))+"Model",a=[];console.log("working on",s),await e.db.getTableInfo(s).then((o=>{const i=o.fields;let l=!1,c="",m="",p="",d="",b="";const u=s.toLowerCase().replace(/[^[a-z0-9]/g,"-")+"-model";if(n.push({className:r,fileName:u}),c+="/* eslint-disable @typescript-eslint/member-ordering */\n",c+="// noinspection JSUnusedGlobalSymbols\n",i){e.abstractModelModule==e.smartDbInterfaces?e.separateApi?(p+=`import {GenericModelData} from "${e.abstractModelModule}";\n`,b+=`import {AbstractModel, ModelAttributeMap} from "${e.abstractModelModule}";\n`,b+=`import {${r}Data} from "./${u}-api";\n`):b+=`import {AbstractModel, GenericModelData, ModelAttributeMap} from "${e.abstractModelModule}";\n`:e.separateApi?(p+=`import {GenericModelData} from "${e.smartDbInterfaces}";\n`,b+=`import {ModelAttributeMap} from "${e.smartDbInterfaces}";\n`,b+=`import {AbstractModel} from "${e.abstractModelModule}";\n`,b+=`import {${r}Data} from "./${u}-api";\n`):(b+=`import {GenericModelData, ModelAttributeMap} from "${e.smartDbInterfaces}";\n`,b+=`import {AbstractModel} from "${e.abstractModelModule}";\n`),m+=`export interface ${r}Data extends GenericModelData {\n`;let n,o="",f="",h=!1;const g=[];i.forEach((e=>{const t=e.name.match(/([a-z0-9]{1,4})_/i);e.isPk&&(o=e.name,t&&(f=t[1])),t?g.includes(t[1])||g.push(t[1]):h=!0})),f||h||1!=g.length||(f=g[0]),f&&(n=new RegExp(`^${f}_(.*)$`));const y={};i.forEach((t=>{const r=getType(t.type);let o;l||"SqlValueType"!=r||(p+=`import {SqlValueType} from "${e.smartDbInterfaces}";\n`,b+=`import {SqlValueType} from "${e.smartDbInterfaces}";\n`,l=!0);const i=n&&t.name.match(n);o=i?_.camelCase(i[1]):_.camelCase(t.name);let c=!0;if(o!=t.name&&(a.push({name:o,attribute:o,type:r,typeScriptStyle:c,alias:t.name}),c=!1),o!=t.name.toLowerCase()&&(a.push({name:t.name.toLowerCase(),attribute:o,type:r,physical:void 0!==t.cid&&t.name==t.name.toLowerCase(),typeScriptStyle:c}),c=!1),o!=t.name.toUpperCase()&&a.push({name:t.name.toUpperCase(),attribute:o,type:r,physical:void 0!==t.cid&&t.name==t.name.toUpperCase(),typeScriptStyle:c}),t.cid){const e=a.find((e=>e.physical&&e.name.toLowerCase()==t.name.toLowerCase()));e||a.push({name:t.name,attribute:o,type:r,physical:!0,typeScriptStyle:c})}y[o]=r,"user"==s&&"name"==o&&(m+=" // @ts-ignore"),m+=` ${o}?: ${r};\n`})),m+="}\n",d+=`export class ${r} extends AbstractModel<${r}, ${r}Data> {\n`,_.forEach(y,((e,t)=>{d+=` private _${t}?: ${e};\n`})),"user"==s&&(d+=" private _hash?: string;\n",d+=" private _privileges?: string[];\n"),d+="\n",d+=" static readonly attributeMap: ModelAttributeMap = {\n",a.forEach(((e,t)=>{t>0&&(d+=",\n"),d+=` ${e.name}: {\n`,e.physical&&(d+=" physical: true,\n"),e.alias&&(d+=` alias: "${e.alias}",\n`),e.virtual&&(d+=" virtual: true,\n"),e.typeScriptStyle&&(d+=" typeScriptStyle: true,\n"),d+=` type: "${e.type}",\n`,d+=` attribute: "_${e.attribute}"\n`,d+=" }"})),d+="\n",d+=" };\n",d+="\n",d+=" static getClassName(): string {\n",d+=` return "${r}";\n`,d+=" }\n",d+="\n",d+=" static getTableName(): string {\n",d+=` return "${s}";\n`,d+=" }\n",d+="\n",d+=" static getPrimaryKey(): string {\n",d+=` return "${o}";\n`,d+=" }\n",d+="\n",d+=` static from(other: ${r} | ${r}Data): ${r} {\n`,d+=` let value: ${r} = null;\n`,d+=" if (other) {\n",d+=` value = new ${r}();\n`,d+=` if (other instanceof ${r}) {\n`,d+=" Object.assign(value, other);\n",d+=" } else {\n",d+=" value.assign(other);\n",d+=" }\n",d+=" }\n",d+=" return value;\n",d+=" }\n",d+="\n",d+=` constructor(data?: ${r} | ${r}Data) {\n`,d+=" super();\n",d+=" if (data) {\n",d+=" this.assign(data);\n",d+=" }\n",d+=" }\n",d+="\n",d+=` public clone(): ${r} {\n`,d+=` return ${r}.from(this);\n`,d+=" }\n",d+="\n",d+=" public getClassName(): string {\n",d+=` return "${r}";\n`,d+=" }\n",d+="\n",d+=" public getTableName(): string {\n",d+=` return "${s}";\n`,d+=" }\n",d+="\n",d+=" public getPrimaryKey(): string {\n",d+=` return "${o}";\n`,d+=" }\n",d+="\n",d+=" public getAttributeMap(): ModelAttributeMap {\n",d+=` return ${r}.attributeMap;\n`,d+=" }\n",a.forEach((e=>{let r;d+="\n",r=e.name.length<3||e.name.match(/_/)?"FunctionNamingConventionJS":"",""!==r&&(d+=` // noinspection ${r}\n`),d+=` get ${e.name}(): ${e.type} {\n`,d+=` return this._${e.attribute};\n`,d+=" }\n\n",""!==r&&(d+=` // noinspection ${r}\n`);let a=e.attribute;t.includes(a)&&(a="value"),d+=` set ${e.name}(${a}: ${e.type}) {\n`,d+=` this._${e.attribute} = ${a};\n`,d+=" }\n"})),"user"==s&&(d+="\n",d+=" get hash(): string {\n",d+=" return this._hash;\n",d+=" }\n\n",d+=" set hash(hash: string) {\n",d+=" this._hash = hash;\n",d+=" }\n",d+="\n",d+=" get privileges(): string[] {\n",d+=" return this._privileges;\n",d+=" }\n\n",d+=" set privileges(p: string[]) {\n",d+=" this._privileges = p;\n",d+=" }\n"),d+="}\n",e.separateApi?(m=c+"\n"+p+"\n"+m,fs.writeFileSync(`${e.modelDirectory}/${u+"-api.ts"}`,m),d=c+"\n"+b+"\n"+d):d=c+"\n"+b+"\n"+m+"\n"+d,fs.writeFileSync(`${e.modelDirectory}/${u+".ts"}`,d)}else console.log("error: table has no fields")})).catch((e=>{console.error(e),process.abort()}))}}let s=`import {AbstractModel} from "${e.abstractModelModule}";\n`;_.forEach(n,(e=>{s+=`import {${e.className}} from "./${e.fileName}";\n`})),s+="\n",s+="interface SmartDbDictionaryEntry {\n",s+=" cls: "+n.map((e=>"typeof "+e.className)).join(" |\n "),s+=";\n",s+="}\n\n",s+="export class SmartDbDictionary {\n",s+=" static models: { [relation: string]: SmartDbDictionaryEntry; } = {\n",_.forEach(n,(e=>{s+=` ${e.className}: {\n`,s+=` cls: ${e.className}\n`,s+=" },\n"})),s=s.substring(0,s.length-2)+"\n",s+=" };\n",s+="}\n",fs.writeFileSync(`${e.modelDirectory}/smart-db-dictionary.ts`,s)})).catch((e=>{console.error("extraction error",e)}))}(async()=>{let e=!1;const t=Array.from(process.argv);let r,a,n,s=!1;for(t.shift(),t.shift();t[0]&&"--"==t[0].substring(0,2);)"--separate-api"==t[0]?(e=!0,t.shift()):"--database"==t[0]?(r=t[1],t.shift(),t.shift()):"--username"==t[0]?(a=t[1],t.shift(),t.shift()):"--password"==t[0]?(n=t[1],t.shift(),t.shift()):"--create"==t[0]?(s=!0,t.shift()):(console.error(`unknown option '${t[0]}'`),process.exit(-1));if(r||(r=process.env.ORACLE_SID),fs.existsSync(r)||(a||(a=process.env.ORA_USER),n||(n=process.env.ORA_PASS)),r&&t.length<=1){let o;a&&n?o=new SmartDbOracle(r,{user:a,password:n,noDbLogging:!0}):s||fs.existsSync(r)?o=new SmartDbBetterSqlite3(r,{}):(console.error(`ERROR: missing sqlite3 database file ${r}`),process.exit(-1)),1==t.length?o.onReady.subscribe((async r=>{if(r){o.getLogger().setDbLogging(!1);const r={skipCoreTables:!0,modelDirectory:t[0],smartDbInterfaces:"@egi/smart-db",abstractModelModule:"@egi/smart-db",separateApi:e,db:o};await extractDbApi(r)}})):fs.existsSync("src/helpers/extract-db-api.ts")?o.onReady.subscribe((t=>{if(t){const t={justCoreTables:!0,modelDirectory:"src/models/generated",smartDbInterfaces:"../smart-db-interfaces",abstractModelModule:"./abstract-model",separateApi:e,db:o};t.db.initDb({module:"smart-db-core",sqlFilesDirectory:"assets/sqlite3"}).then((async()=>{await extractDbApi(t)}))}else null!==t&&console.error("unable to connect to database")})):console.log("command must be run at the root directory of the smart-db project")}else console.log("USAGE: extract-db-api --database {db-connector|path-to-db} [{options}] {target-models-directory}\n"),console.log("Options are: [--username {username}]"),console.log(" [--password {password}]"),console.log(" [--create"),console.log(" [--separate-api]")})();
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,r,a){return new(r||(r=Promise))(function(n,o){function s(e){try{i(a.next(e))}catch(e){o(e)}}function l(e){try{i(a.throw(e))}catch(e){o(e)}}function i(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,l)}i((a=a.apply(e,t||[])).next())})},__generator=this&&this.__generator||function(e,t){var r,a,n,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=l(0),s.throw=l(1),s.return=l(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function l(l){return function(i){return function(l){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,l[0]&&(o=0)),o;)try{if(r=1,a&&(n=2&l[0]?a.return:l[0]?a.throw||((n=a.return)&&n.call(a),0):a.next)&&!(n=n.call(a,l[1])).done)return n;switch(a=0,n&&(l=[2&l[0],n.value]),l[0]){case 0:case 1:n=l;break;case 4:return o.label++,{value:l[1],done:!1};case 5:o.label++,a=l[1],l=[0];continue;case 7:l=o.ops.pop(),o.trys.pop();continue;default:if(!(n=o.trys,(n=n.length>0&&n[n.length-1])||6!==l[0]&&2!==l[0])){o=0;continue}if(3===l[0]&&(!n||l[1]>n[0]&&l[1]<n[3])){o.label=l[1];break}if(6===l[0]&&o.label<n[1]){o.label=n[1],n=l;break}if(n&&o.label<n[2]){o.label=n[2],o.ops.push(l);break}n[2]&&o.ops.pop(),o.trys.pop();continue}l=t.call(e,o)}catch(e){l=[6,e],a=0}finally{r=n=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}([l,i])}}},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],a=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var a,n,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(a=o.next()).done;)s.push(a.value)}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return s};Object.defineProperty(exports,"__esModule",{value:!0});var fs=require("fs"),process=require("process"),sqlite_master_model_1=require("../models/sqlite-master-model"),smart_db_globals_1=require("../smart-db-globals"),smart_db_oracle_1=require("../drivers/smart-db-oracle"),smart_db_better_sqlite3_1=require("../drivers/smart-db-better-sqlite3"),smart_log_1=require("@egi/smart-log"),oracle_all_objects_model_1=require("../models/oracle-all-objects-model"),smart_db_mysql_1=require("../drivers/smart-db-mysql"),mysql_tables_model_1=require("../models/mysql-tables-model"),os=require("node:os"),dns=require("node:dns"),abstract_model_1=require("../models/abstract-model"),smart_tools_1=require("../smart-tools");function getRelations(e,t){return __awaiter(this,void 0,void 0,function(){var r,a;return __generator(this,function(n){switch(n.label){case 0:return smart_db_oracle_1.SmartDbOracle&&e instanceof smart_db_oracle_1.SmartDbOracle?[4,e.getAll(oracle_all_objects_model_1.OracleAllObjectsModel,{owner:(0,smart_db_globals_1.LITERAL)("USER"),objectType:(0,smart_db_globals_1.IN)(["TABLE","VIEW"])},[],"objectName")]:[3,2];case 1:return a=n.sent(),t&&console.warn("option --ignore-virtual-tables has not been implemented for Oracle yet"),r=a.map(function(e){return{name:e.objectName.toLowerCase(),type:e.objectType.toLowerCase()}}),[3,7];case 2:return smart_db_better_sqlite3_1.SmartDbBetterSqlite3&&e instanceof smart_db_better_sqlite3_1.SmartDbBetterSqlite3?[4,e.getAll(sqlite_master_model_1.SqliteMasterModel,{type:(0,smart_db_globals_1.IN)(["table","view"]),name:(0,smart_db_globals_1.NE)("sqlite_sequence")})]:[3,4];case 3:return a=n.sent(),r=a.filter(function(e){return!t||0!==e.rootpage||"view"==e.type}).map(function(e){return{name:e.name.toLowerCase(),type:e.type.toLowerCase()}}),[3,7];case 4:return smart_db_mysql_1.SmartDbMysql&&e instanceof smart_db_mysql_1.SmartDbMysql?[4,e.getAll(mysql_tables_model_1.MysqlTablesModel,{tableSchema:(0,smart_db_globals_1.LITERAL)("database()"),tableType:(0,smart_db_globals_1.IN)(["BASE TABLE","VIEW"])})]:[3,6];case 5:return a=n.sent(),t&&console.warn("option --ignore-virtual-tables has not been implemented for MySQL yet"),r=a.map(function(e){return{name:e.tableName.toLowerCase(),type:e.tableType.toLowerCase()}}),[3,7];case 6:throw"unimplemented or uninstalled database type";case 7:return[2,r]}})})}function extractDbApi(e){return __awaiter(this,void 0,void 0,function(){var t,r,a,n,o,s,l,i,c,u,f,d,p,m,b,_,y,h,g,v,w,x,S,M,D,T,C,q,A,L,k,I;return __generator(this,function(P){switch(P.label){case 0:if(console.log("extract interface from '".concat(e.db.getDbConnector(),"' to '").concat(e.modelDirectory,"'")),t=["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","If","import","in","instanceOf","interface","new","null","return","super","switch","this","throw","true","try","typeOf","var","void","while","with"],fs.existsSync(e.modelDirectory)||fs.mkdirSync(e.modelDirectory,{recursive:!0}),r=e.dictionaryPrefix?smart_tools_1.tools.kebabCase(e.dictionaryPrefix)+"-smart-db-dictionary":"smart-db-dictionary",a={},n=null!==(A=e.tablePrefix)&&void 0!==A?A:"",e.swapPrefix){o=e.swapPrefix.split(",").map(function(e){return e.trim()});try{for(s=__values(o),l=s.next();!l.done;l=s.next())i=l.value,2==(c=i.split("=").map(function(e){return e.trim()})).length?a[c[0]]=c[1]:console.error("bad syntax in swap prefix")}catch(e){S={error:e}}finally{try{l&&!l.done&&(M=s.return)&&M.call(s)}finally{if(S)throw S.error}}}return f=null!==(L=e.additionalTables)&&void 0!==L?L:[],d=null!==(k=e.additionalPrefix)&&void 0!==k?k:"",e.tables?(u=e.tables.map(function(e){return{name:e.toLowerCase(),type:"table"}}),[3,3]):[3,1];case 1:return[4,getRelations(e.db,e.ignoreVirtualTables)];case 2:if(u=P.sent(),f)try{for(p=__values(f),m=p.next();!m.done;m=p.next())b=m.value,u.push({name:b.toLowerCase(),type:"table"})}catch(e){D={error:e}}finally{try{m&&!m.done&&(T=p.return)&&T.call(p)}finally{if(D)throw D.error}}P.label=3;case 3:_=[],y=function(o){var s,l,i,c,u,p,m,b,y,h,g,v,w,x,S,M,D,T,C,q,A,L,k,I,P,E,N,O,F,j,R,U,G,V,B,$,Q,W,Y,z,J,K,H,X,Z,ee,te,re,ae,ne,oe,se,le,ie,ce,ue,fe,de,pe,me,be,_e,ye;return __generator(this,function(he){switch(he.label){case 0:if(s=o.name,l=void 0,i=void 0,"view"==o.type?(l=e.viewIndicatorPrefix?e.viewIndicatorPrefix+"_":"",i=e.viewIndicatorSuffix?"_"+e.viewIndicatorSuffix:"",(e.viewIndicatorSuffix||e.viewIndicatorPrefix)&&(s=s.replace(/view_/,"").replace(/_view$/,"").replace(/vw_/,"").replace(/_vw$/,"").replace(/^v_/,"").replace(/_v$/,"").trim())):(l="",i=""),c=o.name.match(/^smart_db_/),!(c?!e.skipCoreTables:!e.justCoreTables||f.includes(o.name)))return[3,4];he.label=1;case 1:if(he.trys.push([1,3,,4]),u=void 0,e.omitTablePrefix)p=new RegExp("^".concat(e.omitTablePrefix,"_")),u=l+s.replace(p,"")+i;else if(f.includes(s))""!==d&&(u=d.toLowerCase()+"_"+l+s+i);else if(n)u=n.toLowerCase()+"_"+l+s+i;else{u=s;try{for(se=void 0,m=__values(Object.entries(a)),b=m.next();!b.done;b=m.next())if(y=__read(b.value,2),h=y[0],g=y[1],u.startsWith(h)){u=g+l+u.substring(h.length)+i;break}}catch(e){se={error:e}}finally{try{b&&!b.done&&(le=m.return)&&le.call(m)}finally{if(se)throw se.error}}}return v=smart_tools_1.tools.pascalCase(u)+e.classSuffix,w=[],console.log("working on '".concat(o.name,"'")),[4,e.db.getTableInfo(o.name)];case 2:switch(x=he.sent(),S=x.fields,M=!1,D="",T="",C="",q="",A="",L=u.toLowerCase().replace(/[^[a-z0-9]/g,"-"),e.classSuffix&&e.classSuffix.length>0&&(L+="-"+e.classSuffix.toLowerCase()),k=L+"-api",e.filenameStyle){case"kebab":break;case"camel":L=smart_tools_1.tools.camelCase(L),k=smart_tools_1.tools.camelCase(k),r=smart_tools_1.tools.camelCase(r);break;case"pascal":L=smart_tools_1.tools.pascalCase(L),k=smart_tools_1.tools.pascalCase(k),r=smart_tools_1.tools.pascalCase(r);break;case"snake":L=smart_tools_1.tools.snakeCase(L),k=smart_tools_1.tools.snakeCase(k),r=smart_tools_1.tools.snakeCase(r);break;default:console.error("unknown filename style '".concat(e.filenameStyle,"'")),process.exit(1)}if(_.push({className:v,fileName:L}),D+="/* eslint-disable @typescript-eslint/member-ordering */\n",D+="// noinspection JSUnusedGlobalSymbols\n",S){e.abstractModelModule==e.smartDbInterfaces?e.separateApi?(C+='import {GenericModelData} from "'.concat(e.abstractModelModule,'";\n'),A+='import {AbstractModel, ModelAttributeMap} from "'.concat(e.abstractModelModule,'";\n'),A+="import {".concat(v,'Data} from "./').concat(k,'";\n')):A+='import {AbstractModel, GenericModelData, ModelAttributeMap} from "'.concat(e.abstractModelModule,'";\n'):e.separateApi?(C+='import {GenericModelData} from "'.concat(e.smartDbInterfaces,'";\n'),A+='import {ModelAttributeMap} from "'.concat(e.smartDbInterfaces,'";\n'),A+='import {AbstractModel} from "'.concat(e.abstractModelModule,'";\n'),A+="import {".concat(v,'Data} from "./').concat(k,'";\n')):(A+='import {GenericModelData, ModelAttributeMap} from "'.concat(e.smartDbInterfaces,'";\n'),A+='import {AbstractModel} from "'.concat(e.abstractModelModule,'";\n')),T+="export interface ".concat(v,"Data extends GenericModelData {\n"),I="",P=null,E=!1,N=[];try{for(ie=void 0,O=__values(S),F=O.next();!F.done;F=O.next())z=F.value,B=z.name.match(/([a-z0-9]{1,4})_/i),z.isPk&&(""!==I?I="":(I=z.name,B&&(P=new RegExp("^".concat(B[1],"_(.*)$"))))),B?(j=B[1].toUpperCase(),N.includes(j)||e.ignoreFieldPrefix&&e.ignoreFieldPrefix.includes(j)||N.push(j)):E=!0}catch(e){ie={error:e}}finally{try{F&&!F.done&&(ce=O.return)&&ce.call(O)}finally{if(ie)throw ie.error}}if(P||E||1!=N.length||(P=new RegExp("^".concat(N[0],"_(.*)$"),"i")),P){R=[],U=!1;try{for(ue=void 0,G=__values(S),V=G.next();!V.done;V=G.next()){if(z=V.value,B=z.name.match(P),X=B?smart_tools_1.tools.camelCase(B[1]):smart_tools_1.tools.camelCase(z.name),R.includes(X)){U=!0;break}R.push(X)}}catch(e){ue={error:e}}finally{try{V&&!V.done&&(fe=G.return)&&fe.call(G)}finally{if(ue)throw ue.error}}U&&(P=null)}$={},Q=function(t){var r=abstract_model_1.AbstractModel.getValueType(null,t.dbFullType);M||"SqlValueType"!=r||(C+='import {SqlValueType} from "'.concat(e.smartDbInterfaces,'";\n'),A+='import {SqlValueType} from "'.concat(e.smartDbInterfaces,'";\n'),M=!0);var a=P&&t.name.match(P),n=a?smart_tools_1.tools.camelCase(a[1]):smart_tools_1.tools.camelCase(t.name),o=!0;if(n!=t.name&&(w.push({name:n,attribute:n,type:r,dbType:t.dbType,dbFullType:t.dbFullType,typeScriptStyle:o,alias:t.name}),o=!1),n!=smart_tools_1.tools.camelCase(t.name)&&(w.push({name:smart_tools_1.tools.camelCase(t.name),attribute:n,type:r,dbType:t.dbType,dbFullType:t.dbFullType,typeScriptStyle:o,alias:t.name}),o=!1),n!=t.name.toLowerCase()&&(w.push({name:t.name.toLowerCase(),attribute:n,type:r,dbType:t.dbType,dbFullType:t.dbFullType,physical:void 0!==t.cid&&t.name==t.name.toLowerCase(),typeScriptStyle:o}),o=!1),n!=t.name.toUpperCase()&&w.push({name:t.name.toUpperCase(),attribute:n,type:r,dbType:t.dbType,dbFullType:t.dbFullType,physical:void 0!==t.cid&&t.name==t.name.toUpperCase(),typeScriptStyle:o}),t.cid){var s=w.find(function(e){return e.physical&&e.name.toLowerCase()==t.name.toLowerCase()});s||w.push({name:t.name,attribute:n,type:r,dbType:t.dbType,dbFullType:t.dbFullType,physical:!0,typeScriptStyle:o})}$[n]=r,"user"==u&&"name"==n&&(T+=" // @ts-ignore"),T+=" ".concat(n,"?: ").concat(r,";\n")};try{for(de=void 0,W=__values(S),Y=W.next();!Y.done;Y=W.next())z=Y.value,Q(z)}catch(e){de={error:e}}finally{try{Y&&!Y.done&&(pe=W.return)&&pe.call(W)}finally{if(de)throw de.error}}T+="}\n",q+="export class ".concat(v," extends AbstractModel<").concat(v,", ").concat(v,"Data> {\n");try{for(me=void 0,J=__values(Object.entries($)),K=J.next();!K.done;K=J.next())H=__read(K.value,2),X=H[0],Z=H[1],q+=" private _".concat(X,"?: ").concat(Z,";\n")}catch(e){me={error:e}}finally{try{K&&!K.done&&(be=J.return)&&be.call(J)}finally{if(me)throw me.error}}"user"==u&&(q+=" private _hash?: string;\n",q+=" private _privileges?: string[];\n"),q+="\n",q+=" static readonly attributeMap: ModelAttributeMap = {\n",w.forEach(function(e,t){t>0&&(q+=",\n"),q+=" ".concat(e.name,": {\n"),e.physical&&(q+=" physical: true,\n"),e.alias&&(q+=' alias: "'.concat(e.alias,'",\n')),e.virtual&&(q+=" virtual: true,\n"),e.typeScriptStyle&&(q+=" typeScriptStyle: true,\n"),q+=' type: "'.concat(e.type,'",\n'),q+=' dbType: "'.concat(e.dbType,'",\n'),q+=' dbFullType: "'.concat(e.dbFullType,'",\n'),q+=' attribute: "_'.concat(e.attribute,'"\n'),q+=" }"}),q+="\n",q+=" };\n",q+="\n",q+=" static getClassName(): string {\n",q+=' return "'.concat(v,'";\n'),q+=" }\n",q+="\n",q+=" static getTableName(): string {\n",q+=' return "'.concat(o.name,'";\n'),q+=" }\n",q+="\n",q+=" static getPkSequenceName(): string {\n",x.pkSequenceName?q+=' return "'.concat(x.pkSequenceName,'";\n'):q+=" return null;\n",q+=" }\n",q+="\n",q+=" static getPrimaryKey(): string {\n",q+=' return "'.concat(I,'";\n'),q+=" }\n",q+="\n",q+=" static from(other: ".concat(v," | ").concat(v,"Data): ").concat(v," {\n"),q+=" let value: ".concat(v," = null;\n"),q+=" if (other) {\n",q+=" value = new ".concat(v,"(other);\n"),q+=" }\n",q+=" return value;\n",q+=" }\n",q+="\n",q+=" public clone(): ".concat(v," {\n"),q+=" return ".concat(v,".from(this);\n"),q+=" }\n",q+="\n",q+=" public getClassName(): string {\n",q+=' return "'.concat(v,'";\n'),q+=" }\n",q+="\n",q+=" public getTableName(): string {\n",q+=' return "'.concat(o.name,'";\n'),q+=" }\n",q+="\n",q+=" public getPkSequenceName(): string {\n",x.pkSequenceName?q+=' return "'.concat(x.pkSequenceName,'";\n'):q+=" return null;\n",q+=" }\n",q+="\n",q+=" public getPrimaryKey(): string {\n",q+=' return "'.concat(I,'";\n'),q+=" }\n",q+="\n",q+=" public getAttributeMap(): ModelAttributeMap {\n",q+=" return ".concat(v,".attributeMap;\n"),q+=" }\n";try{for(_e=void 0,ee=__values(w),te=ee.next();!te.done;te=ee.next())re=te.value,q+="\n",ae=void 0,""!==(ae=re.name.length<3||re.name.match(/_/)?"FunctionNamingConventionJS":"")&&(q+=" // noinspection ".concat(ae,"\n")),q+=" get ".concat(re.name,"(): ").concat(re.type," {\n"),q+=" return this._".concat(re.attribute,";\n"),q+=" }\n\n",""!==ae&&(q+=" // noinspection ".concat(ae,"\n")),ne=re.attribute,t.includes(ne)&&(ne="value"),q+=" set ".concat(re.name,"(").concat(ne,": ").concat(re.type,") {\n"),q+=" this._".concat(re.attribute," = ").concat(ne,";\n"),q+=" }\n"}catch(e){_e={error:e}}finally{try{te&&!te.done&&(ye=ee.return)&&ye.call(ee)}finally{if(_e)throw _e.error}}"user"==u&&(q+="\n",q+=" get hash(): string {\n",q+=" return this._hash;\n",q+=" }\n\n",q+=" set hash(hash: string) {\n",q+=" this._hash = hash;\n",q+=" }\n",q+="\n",q+=" get privileges(): string[] {\n",q+=" return this._privileges;\n",q+=" }\n\n",q+=" set privileges(p: string[]) {\n",q+=" this._privileges = p;\n",q+=" }\n"),q+="}\n",e.separateApi?(T=D+"\n"+C+"\n"+T,fs.writeFileSync("".concat(e.modelDirectory,"/").concat(L+"-api.ts"),T),q=D+"\n"+A+"\n"+q):q=D+"\n"+A+"\n"+T+"\n"+q,fs.writeFileSync("".concat(e.modelDirectory,"/").concat(L+".ts"),q)}else console.log("error: table has no fields");return[3,4];case 3:return oe=he.sent(),console.error(oe),[3,4];case 4:return[2]}})},P.label=4;case 4:P.trys.push([4,9,10,11]),h=__values(u),g=h.next(),P.label=5;case 5:return g.done?[3,8]:(v=g.value,[5,y(v)]);case 6:P.sent(),P.label=7;case 7:return g=h.next(),[3,5];case 8:return[3,11];case 9:return w=P.sent(),C={error:w},[3,11];case 10:try{g&&!g.done&&(q=h.return)&&q.call(h)}finally{if(C)throw C.error}return[7];case 11:return x='import {DbDictionaryEntry} from "'.concat(e.smartDbInterfaces,'";\n'),_.forEach(function(e){x+="import {".concat(e.className,'} from "./').concat(e.fileName,'";\n')}),x+="\n",x+="export class ".concat(null!==(I=e.dictionaryPrefix)&&void 0!==I?I:"","SmartDbDictionary {\n"),x+=" static models: { [relation: string]: DbDictionaryEntry; } = {\n",_.forEach(function(e){x+=" ".concat(e.className,": {\n"),x+=" cls: ".concat(e.className,"\n"),x+=" },\n"}),x=x.substring(0,x.length-2)+"\n",x+=" };\n",x+="}\n",fs.writeFileSync("".concat(e.modelDirectory,"/").concat(r,".ts"),x),[2]}})})}function main(){return __awaiter(this,void 0,void 0,function(){var e,t,r,a,n,o,s,l,i,c,u,f,d,p,m,b,_,y,h,g,v,w,x,S,M,D,T,C,q,A,L,k,I,P,E,N=this;return __generator(this,function(O){switch(O.label){case 0:for(e=!1,t=Array.from(process.argv),s=!1,u="Model",f="",p=!1,b="",_="kebab",t.shift(),t.shift();t[0]&&"--"==t[0].substring(0,2);)"--separate-api"==t[0]?(e=!0,t.shift()):"--omit-table-prefix"==t[0]?(a=t[1],t.shift(),t.shift()):"--database"==t[0]?(r=t[1],t.shift(),t.shift()):"--username"==t[0]?(n=t[1],t.shift(),t.shift()):"--password"==t[0]?(o=t[1],t.shift(),t.shift()):"--dictionary-prefix"==t[0]?(b=(b=smart_tools_1.tools.camelCase(t[1]))[0].toUpperCase()+b.substring(1),t.shift(),t.shift()):"--tables"==t[0]?(l=t[1].split(/ *, */).map(function(e){return e.toUpperCase().trim()}),t.shift(),t.shift()):"--table-prefix"==t[0]?(i=t[1],t.shift(),t.shift()):"--swap-prefix"==t[0]?(c=t[1],t.shift(),t.shift()):"--class-suffix"==t[0]?(u=t[1],t.shift(),t.shift()):"--filename-style"==t[0]?(_=t[1],t.shift(),t.shift()):"--additional-tables"==t[0]?(m=t[1].split(/ *, */).map(function(e){return e.toUpperCase().trim()}),t.shift(),t.shift()):"--additional-prefix"==t[0]?(f=t[1],t.shift(),t.shift()):"--ignore-virtual-tables"==t[0]?(p=!0,t.shift()):"--view-indicator-prefix"==t[0]?(y=t[1],t.shift(),t.shift()):"--view-indicator-suffix"==t[0]?(h=t[1],t.shift(),t.shift()):"--ignore-field-prefix"==t[0]?(d=t[1].split(/ *, */).map(function(e){return e.toUpperCase().trim()}),t.shift(),t.shift()):"--create"==t[0]?(s=!0,t.shift()):(console.error("unknown option '".concat(t[0],"'")),process.exit(-1));return g=r.match(/([\w:]+@)?([\w.]+):?(\d+)?\/?(\w+)?$/),r||(r=null!==(q=null!==(C=g[3])&&void 0!==C?C:process.env.ORACLE_SID)&&void 0!==q?q:process.env.MYSQL_DB),fs.existsSync(r)||g[1]&&(v=null===(A=g[1])||void 0===A?void 0:A.replace(/@$/,"").split(":"),n||(n=null!==(k=null!==(L=v[0])&&void 0!==L?L:process.env.ORA_USER)&&void 0!==k?k:process.env.MYSQL_USER),o||(o=null!==(P=null!==(I=v[1])&&void 0!==I?I:process.env.ORA_PASS)&&void 0!==P?P:process.env.MYSQL_PASS),console.log("Connecting to database",r,"as user",n,"with password")),r&&t.length<=1?(w=void 0,x=fs.existsSync("src/helpers/extract-db-api.ts"),n||g[1]?g&&g[2]?[4,(F=g[2],__awaiter(N,void 0,void 0,function(){return __generator(this,function(e){return[2,new Promise(function(e){dns.resolve(F,function(t,r){e(t?null:r[0])})})]})}))]:[3,2]:[3,3]):[3,22];case 1:(S=O.sent())&&(w=new smart_db_mysql_1.SmartDbMysql({host:S,port:g[3]?parseInt(g[3]):3306,database:null!==(E=g[4])&&void 0!==E?E:n,user:null!=n?n:os.userInfo().username,password:o},{silent:!0,logOptions:{logLevel:smart_log_1.SmartSeverityLevel.Debug}})),O.label=2;case 2:return w||(w=new smart_db_oracle_1.SmartDbOracle({connectString:r,user:n,password:o},{silent:!0,logOptions:{logLevel:smart_log_1.SmartSeverityLevel.Debug}})),[3,4];case 3:s||fs.existsSync(r)?w=new smart_db_better_sqlite3_1.SmartDbBetterSqlite3({filename:r},{}):(console.error("ERROR: missing sqlite3 database file ".concat(r)),process.exit(-1)),O.label=4;case 4:return[4,w.databaseReady()];case 5:if(O.sent(),M={modelDirectory:null,smartDbInterfaces:null,abstractModelModule:null,tables:l,tablePrefix:i,swapPrefix:c,classSuffix:u,additionalTables:m,additionalPrefix:f,dictionaryPrefix:b,separateApi:e,filenameStyle:_,ignoreFieldPrefix:d,ignoreVirtualTables:p,viewIndicatorPrefix:y,viewIndicatorSuffix:h,db:w},1!=t.length)return[3,12];Object.assign(M,{modelDirectory:t[0],smartDbInterfaces:"@egi/smart-db",abstractModelModule:"@egi/smart-db",skipCoreTables:!0,omitTablePrefix:a}),w.getLogger().setDbWriter(null),O.label=6;case 6:return O.trys.push([6,8,9,11]),[4,extractDbApi(M)];case 7:return O.sent(),[3,11];case 8:return D=O.sent(),w.getLogger().fatal("extractDbApi",D),[3,11];case 9:return[4,w.close()];case 10:return O.sent(),[7];case 11:return[3,21];case 12:if(!x)return[3,19];Object.assign(M,{modelDirectory:"src/models",smartDbInterfaces:"../smart-db-interfaces",abstractModelModule:"./abstract-model",justCoreTables:!0}),O.label=13;case 13:return O.trys.push([13,15,16,18]),[4,extractDbApi(M)];case 14:return O.sent(),[3,18];case 15:return T=O.sent(),w.getLogger().fatal("extractDbApi",T),[3,18];case 16:return[4,w.close()];case 17:return O.sent(),[7];case 18:return[3,21];case 19:return console.log("command must be run at the root directory of the smart-db project"),[4,w.close()];case 20:O.sent(),O.label=21;case 21:return[3,23];case 22:console.log("USAGE: extract-db-api --database {db-connector|path-to-db} [{options}] {target-models-directory}\n"),console.log("Options are: [--omit-table-prefix {prefix}]"),console.log(" [--username {username}]"),console.log(" [--password {password}]"),console.log(" [--create]"),console.log(" [--tables {table [, table...]}"),console.log(" [--table-prefix prefix]"),console.log(" [--class-suffix suffix]"),console.log(" [--additional-tables {table [, table...]}]"),console.log(" [--additional-prefix prefix]"),console.log(" [--remove-field-prefix]"),console.log(" [--filename-style {kebab|camel|pascal|snake}]"),console.log(" [--ignore-field-prefix prefix]"),console.log(" [--separate-api]"),O.label=23;case 23:return[2]}var F})})}main().then(function(){console.log("done"),process.exit(0)}).catch(function(e){console.error(e),process.exit(1)});
@@ -1,23 +1,58 @@
1
- import { FieldNamingStyle, GenericModelData, ModelAttributeMap } from "../smart-db-interfaces";
1
+ import { FieldNamingStyle, GenericModelData, MakeDbValueOptions, ModelAttributeMap, SmartDbInterface, SqlValueType, SqlValueTypes } from "../smart-db-interfaces";
2
2
  export declare abstract class AbstractModel<T extends AbstractModel<T, D>, D extends GenericModelData> {
3
3
  abstract clone(): T;
4
4
  abstract getClassName(): string;
5
5
  abstract getTableName(): string;
6
+ abstract getPkSequenceName(): string;
6
7
  abstract getPrimaryKey(): string;
7
8
  abstract getAttributeMap(): ModelAttributeMap;
8
9
  static readonly attributeMap: ModelAttributeMap;
10
+ /**
11
+ * The database instance this model record was read from.
12
+ * Set automatically by SmartDB when a row is fetched. `undefined` on manually
13
+ * constructed instances (e.g. `new MyModel()`).
14
+ * Used by {@link selfWrite} and {@link selfDelete} to persist changes back to the originating DB.
15
+ */
16
+ _instanceDb: SmartDbInterface;
17
+ constructor(data?: T | D);
18
+ static getClassName(): string;
9
19
  static getTableName(): string;
20
+ static getPkSequenceName(): string;
21
+ static getPrimaryKey(): string;
22
+ static getPrimaryKeyName(): string;
10
23
  static from(other: any): any;
24
+ static makeDbValue(value: SqlValueType, options?: MakeDbValueOptions): SqlValueType;
25
+ static getValueType(referenceValue: SqlValueType, fullDbType?: string): SqlValueTypes;
26
+ static toDbTimestamp(d: Date | number): string;
27
+ static toDbDate(date: Date | number, zone?: string, addZone?: boolean): string | null;
11
28
  assign(other: T | D, options?: {
12
29
  only?: string[];
13
30
  exclude?: string[];
14
31
  skipUndefined?: boolean;
15
32
  }): void;
16
- setValue(attribute: string, value: string | number | boolean | Date): void;
17
- getValue(attribute: string): string | number | boolean;
33
+ setValue(attribute: string, value: SqlValueType): void;
34
+ getValue(attribute: string): SqlValueType;
18
35
  hasAttribute(attribute: string): boolean;
19
36
  clear(attributes: string | string[]): void;
37
+ /**
38
+ * Persists this model instance to its originating database.
39
+ *
40
+ * - If the primary key is set: issues an `UPDATE` for the row matching that key.
41
+ * - If the primary key is absent: issues an `INSERT` and stores the generated key back
42
+ * onto the instance so subsequent `write()` calls become updates.
43
+ *
44
+ * Requires {@link _instanceDb} to be set (i.e. the instance was returned by a SmartDB query,
45
+ * or `instanceDb` was assigned manually). Throws if no database association exists.
46
+ */
47
+ selfWrite(): Promise<void>;
48
+ /**
49
+ * Deletes this model instance from its originating database using the primary key.
50
+ *
51
+ * Requires both {@link instanceDb} and a non-empty primary key value to be present.
52
+ * Throws if either is missing.
53
+ */
54
+ selfDelete(): Promise<void>;
20
55
  getPlainObject(includeVirtuals?: boolean, fields?: string[]): D;
21
56
  getPlainObject(style?: FieldNamingStyle, includeVirtuals?: boolean, fields?: string[]): GenericModelData;
22
- private toDbTimestamp;
57
+ private makeDbValue;
23
58
  }
@@ -1 +1 @@
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={};
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,a,n){return new(a||(a=Promise))(function(r,i){function o(e){try{l(n.next(e))}catch(e){i(e)}}function s(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof a?t:new a(function(e){e(t)})).then(o,s)}l((n=n.apply(e,t||[])).next())})},__generator=this&&this.__generator||function(e,t){var a,n,r,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[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(a)throw new TypeError("Generator is already executing.");for(;o&&(o=0,s[0]&&(i=0)),i;)try{if(a=1,n&&(r=2&s[0]?n.return:s[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,s[1])).done)return r;switch(n=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=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(!(r=i.trys,(r=r.length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){i.label=s[1];break}if(6===s[0]&&i.label<r[1]){i.label=r[1],r=s;break}if(r&&i.label<r[2]){i.label=r[2],i.ops.push(s);break}r[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],n=0}finally{a=r=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(e){var t="function"==typeof Symbol&&Symbol.iterator,a=t&&e[t],n=0;if(a)return a.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,t){var a="function"==typeof Symbol&&e[Symbol.iterator];if(!a)return e;var n,r,i=a.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)o.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(a=i.return)&&a.call(i)}finally{if(r)throw r.error}}return o};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AbstractModel=void 0;var smart_db_interfaces_1=require("../smart-db-interfaces"),AbstractModel=function(){function e(e){e&&this.assign(e)}return e.getClassName=function(){return"overload this in child class"},e.getTableName=function(){return"overload this in child class"},e.getPkSequenceName=function(){return"overload this in child class"},e.getPrimaryKey=function(){return"overload this in child class"},e.getPrimaryKeyName=function(){var e,t,a=this.getPrimaryKey(),n=a;try{for(var r=__values(Object.entries(this.attributeMap)),i=r.next();!i.done;i=r.next()){var o=__read(i.value,2),s=o[0],l=o[1];if(l.alias==a&&l.typeScriptStyle){n=s;break}}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}return n},e.from=function(e){},e.makeDbValue=function(t,a){var n,r,i;if(null!=t){var o=null!==(n=null==a?void 0:a.dateTimeMode)&&void 0!==n?n:"rule",s=e.getValueType(t,null==a?void 0:a.dbFullType);if(t instanceof Date)switch(s){case"string":t=e.toDbTimestamp(t);break;case"number":t=t.getTime();break;case"boolean":t=!0;break;case"any":case"clob":case"Date":"none"==o||(t="utc"==o||"rule"==o&&(null===(r=null==a?void 0:a.dbFullType)||void 0===r?void 0:r.toUpperCase().startsWith("TIMESTAMP"))?e.toDbDate(t,"UTC",!0):e.toDbDate(t))}else if(typeof t!=s)switch(s){case"string":t="boolean"==typeof t?t?"true":"false":t.toString();break;case"number":t="boolean"==typeof t?t?1:0:Number(t);break;case"boolean":t="string"==typeof t?!t.trim().match(/^(F|N|false|no|off|0)$/i):!!Boolean(t);break;case"Date":if("boolean"==typeof t)t=t?new Date:new Date(0);else if("number"==typeof t)t=e.toDbTimestamp(t);else{var l=new Date(t);isNaN(l.valueOf())||(t="none"==o?l:"utc"==o||"rule"==o&&(null===(i=null==a?void 0:a.dbFullType)||void 0===i?void 0:i.toUpperCase().startsWith("TIMESTAMP"))?e.toDbDate(l,"UTC",!0):e.toDbDate(l))}}}return null!=t?t:null},e.getValueType=function(e,t){return t?t.match(/(varchar|text)/i)?"string":t.match(/boolean/i)||t.match(/(number|int|integer)\(1\)/i)?"boolean":t.match(/(date|timestamp|datetime)/i)?"Date":t.match(/(int|decimal|number|double|single|float)/i)?"number":t.match(/clob/i)||t.match(/long/i)||t.match(/raw/i)?"any":"SqlValueType":e instanceof Date?"Date":"string"==typeof e?"string":"number"==typeof e?"number":"boolean"==typeof e?"boolean":"SqlValueType"},e.toDbTimestamp=function(e){var t;return e&&("number"==typeof e&&(e=new Date(e)),t=e.toISOString().substring(0,23).replace("T"," ")),t},e.toDbDate=function(e,t,a){e||(e=new Date);var n,r,i,o,s,l,c,u="number"==typeof e?new Date(e):e,f=function(e){return String(e).padStart(2,"0")};if(t){var b=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}),p=Object.fromEntries(b.formatToParts(u).map(function(e){return[e.type,e.value]}));n=parseInt(p.year),r=parseInt(p.month),i=parseInt(p.day),o=parseInt(p.hour)%24,s=parseInt(p.minute),l=parseInt(p.second);var y=new Date(Date.UTC(n,r-1,i,o,s,l));c=Math.round((y.getTime()-u.getTime())/6e4)}else n=u.getFullYear(),r=u.getMonth()+1,i=u.getDate(),o=u.getHours(),s=u.getMinutes(),l=u.getSeconds(),c=-u.getTimezoneOffset();var h="".concat(n,"-").concat(f(r),"-").concat(f(i)),d=t?"".concat(f(l),".").concat(String(u.getMilliseconds()).padStart(3,"0")):f(l),m="".concat(f(o),":").concat(f(s),":").concat(d),v="";if(t&&a){var g=t.toUpperCase();if("UTC"===g||"GMT"===g)v="Z";else{var _=c>=0?"+":"-",D=Math.abs(c),w=Math.floor(D/60),T=D%60;v="".concat(_).concat(f(w)).concat(f(T))}}return"".concat(h," ").concat(m).concat(v)},e.prototype.assign=function(t,a){var n=this;if("object"==typeof t){var r=this.getAttributeMap(),i=!a||void 0===a.skipUndefined||!!a.skipUndefined;Object.keys(r).forEach(function(r){var o=!0;if(a&&(a.only&&!a.only.includes(r)&&(o=!1),a.exclude&&a.exclude.includes(r)&&(o=!1)),o)if(t instanceof e&&t.hasAttribute(r)){var s=t.getValue(r);i&&void 0===s||n.setValue(r,s)}else if(t.hasOwnProperty(r)){s=t[r];i&&void 0===s||n.setValue(r,s)}})}},e.prototype.setValue=function(t,a){var n=this.getAttributeMap()[t];if(!n)throw"unknown attribute ".concat(t," for ").concat(this.getClassName());if(null===a)this[n.attribute]=null;else if(void 0===a)delete this[n.attribute];else{switch(n.type){case"SqlValueType":case"any":break;case"string":"number"==typeof a?a=a.toString():"boolean"==typeof a?a=a?"true":"false":a instanceof Date&&(a=e.toDbTimestamp(a));break;case"number":"string"==typeof a?a=parseFloat(a):"boolean"==typeof a?a=a?1:0:a instanceof Date&&(a=a.getTime());break;case"boolean":a="string"==typeof a?!a.match(/(F|N|false|no|off|0)/i):!!a;break;case"Date":a="number"==typeof a||"string"==typeof a||a instanceof Date?new Date(a):new Date;break;case"clob":a instanceof Date?a=e.toDbTimestamp(a):"object"==typeof a?a=JSON.stringify(a):"number"==typeof a?a=a.toString():"boolean"==typeof a&&(a=a?"true":"false");break;default:throw"AbstractModel.setValue: unknown data type '".concat(n.type,"'")}this[n.attribute]=a}},e.prototype.getValue=function(e){return this[this.getAttributeMap()[e].attribute]},e.prototype.hasAttribute=function(e){return!!this.getAttributeMap()[e]},e.prototype.clear=function(e){var t=this;Array.isArray(e)||(e=[e]);var a=this.getAttributeMap();e.forEach(function(e){var n=a[e];n&&delete t[n.attribute]})},e.prototype.selfWrite=function(){return __awaiter(this,void 0,void 0,function(){var e,t,a,n;return __generator(this,function(r){switch(r.label){case 0:return this._instanceDb?this[e=this.getPrimaryKey()]?[4,this._instanceDb.update(this.getClassName(),(n={},n[e]=this[e],n))]:[3,2]:[3,5];case 1:return r.sent(),[3,4];case 2:return t=this,a=e,[4,this._instanceDb.insert(this.getClassName(),this.getPlainObject())];case 3:t[a]=r.sent(),r.label=4;case 4:return[3,6];case 5:throw"unable to write model instance - no database association";case 6:return[2]}})})},e.prototype.selfDelete=function(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(a){switch(a.label){case 0:return this._instanceDb?this[e=this.getPrimaryKey()]?[4,this._instanceDb.delete(this.getClassName(),(t={},t[e]=this[e],t))]:[3,2]:[3,4];case 1:return a.sent(),[3,3];case 2:throw"unable to delete model instance - no primary key";case 3:return[3,5];case 4:throw"unable to delete model instance - no database association";case 5:return[2]}})})},e.prototype.getPlainObject=function(e,t,a){var n,r,i,o=this,s=smart_db_interfaces_1.FieldNamingStyle.TypeScript,l=!1;void 0!==e&&("boolean"==typeof e?(l=e,i=t):(s=e,l=t,i=a));var c=this.getAttributeMap(),u=[];void 0===l&&(l=!0);try{for(var f=__values(Object.entries(c)),b=f.next();!b.done;b=f.next()){var p=__read(b.value,2),y=p[0],h=p[1],d=s==smart_db_interfaces_1.FieldNamingStyle.All||l&&h.virtual;if(!d)if(s==smart_db_interfaces_1.FieldNamingStyle.Database)d=h.physical;else{if(s!=smart_db_interfaces_1.FieldNamingStyle.TypeScript)throw"unknown style ".concat(s);d=h.typeScriptStyle}d&&(i&&!i.includes(y)||u.push(y))}}catch(e){n={error:e}}finally{try{b&&!b.done&&(r=f.return)&&r.call(f)}finally{if(n)throw n.error}}var m={};return u.forEach(function(e){var t=c[e];if(t){var a=o[t.attribute];void 0!==a&&(m[e]=a)}}),m},e.prototype.makeDbValue=function(t,a){return e.makeDbValue(t,Object.assign({dbFullType:a},this._instanceDb.getOptions()))},e.attributeMap={},e}();exports.AbstractModel=AbstractModel;
@@ -0,0 +1,109 @@
1
+ import { ModelAttributeMap } from "../smart-db-interfaces";
2
+ import { AbstractModel } from "./abstract-model";
3
+ export interface SqliteMasterModelData extends Record<string, any> {
4
+ autoIncrement?: number;
5
+ avgRowLength?: number;
6
+ checkTime?: Date;
7
+ checksum?: number;
8
+ createOptions?: string;
9
+ createTime?: Date;
10
+ dataFree?: number;
11
+ dataLength?: number;
12
+ engine?: string;
13
+ indexLength?: number;
14
+ maxDataLength?: number;
15
+ maxIndexLength?: number;
16
+ rowFormat?: string;
17
+ tableCatalog?: string;
18
+ tableCollation?: string;
19
+ tableComment?: string;
20
+ tableName?: string;
21
+ tableRows?: number;
22
+ tableSchema?: string;
23
+ tableType?: string;
24
+ temporary?: string;
25
+ updateTime?: Date;
26
+ version?: number;
27
+ }
28
+ export declare class MysqlTablesModel extends AbstractModel<MysqlTablesModel, SqliteMasterModelData> {
29
+ private _autoIncrement?;
30
+ private _avgRowLength?;
31
+ private _checkTime?;
32
+ private _checksum?;
33
+ private _createOptions?;
34
+ private _createTime?;
35
+ private _dataFree?;
36
+ private _dataLength?;
37
+ private _engine?;
38
+ private _indexLength?;
39
+ private _maxDataLength?;
40
+ private _maxIndexLength?;
41
+ private _rowFormat?;
42
+ private _tableCatalog?;
43
+ private _tableCollation?;
44
+ private _tableComment?;
45
+ private _tableName?;
46
+ private _tableRows?;
47
+ private _tableSchema?;
48
+ private _tableType?;
49
+ private _temporary?;
50
+ private _updateTime?;
51
+ private _version?;
52
+ get autoIncrement(): number;
53
+ set autoIncrement(autoIncrement: number);
54
+ get avgRowLength(): number;
55
+ set avgRowLength(avgRowLength: number);
56
+ get checkTime(): Date;
57
+ set checkTime(checkTime: Date);
58
+ get checksum(): number;
59
+ set checksum(checksum: number);
60
+ get createOptions(): string;
61
+ set createOptions(createOptions: string);
62
+ get createTime(): Date;
63
+ set createTime(createTime: Date);
64
+ get dataFree(): number;
65
+ set dataFree(dataFree: number);
66
+ get dataLength(): number;
67
+ set dataLength(dataLength: number);
68
+ get engine(): string;
69
+ set engine(engine: string);
70
+ get indexLength(): number;
71
+ set indexLength(indexLength: number);
72
+ get maxDataLength(): number;
73
+ set maxDataLength(maxDataLength: number);
74
+ get maxIndexLength(): number;
75
+ set maxIndexLength(maxIndexLength: number);
76
+ get rowFormat(): string;
77
+ set rowFormat(rowFormat: string);
78
+ get tableCatalog(): string;
79
+ set tableCatalog(tableCatalog: string);
80
+ get tableCollation(): string;
81
+ set tableCollation(tableCollation: string);
82
+ get tableComment(): string;
83
+ set tableComment(tableComment: string);
84
+ get tableName(): string;
85
+ set tableName(tableName: string);
86
+ get tableRows(): number;
87
+ set tableRows(tableRows: number);
88
+ get tableSchema(): string;
89
+ set tableSchema(tableSchema: string);
90
+ get tableType(): string;
91
+ set tableType(tableType: string);
92
+ get temporary(): string;
93
+ set temporary(temporary: string);
94
+ get updateTime(): Date;
95
+ set updateTime(updateTime: Date);
96
+ get version(): number;
97
+ set version(version: number);
98
+ static getClassName(): string;
99
+ clone(): MysqlTablesModel;
100
+ getClassName(): string;
101
+ getTableName(): string;
102
+ getPkSequenceName(): string;
103
+ getPrimaryKey(): string;
104
+ getAttributeMap(): ModelAttributeMap;
105
+ static readonly attributeMap: ModelAttributeMap;
106
+ static getTableName(): string;
107
+ static getPkSequenceName(): string;
108
+ static from(other: MysqlTablesModel): MysqlTablesModel;
109
+ }
@@ -0,0 +1 @@
1
+ "use strict";var __extends=this&&this.__extends||function(){var t=function(e,a){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a])},t(e,a)};return function(e,a){if("function"!=typeof a&&null!==a)throw new TypeError("Class extends value "+String(a)+" is not a constructor or null");function r(){this.constructor=e}t(e,a),e.prototype=null===a?Object.create(a):(r.prototype=a.prototype,new r)}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.MysqlTablesModel=void 0;var abstract_model_1=require("./abstract-model"),MysqlTablesModel=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),Object.defineProperty(e.prototype,"autoIncrement",{get:function(){return this._autoIncrement},set:function(t){this._autoIncrement=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"avgRowLength",{get:function(){return this._avgRowLength},set:function(t){this._avgRowLength=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"checkTime",{get:function(){return this._checkTime},set:function(t){this._checkTime=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"checksum",{get:function(){return this._checksum},set:function(t){this._checksum=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"createOptions",{get:function(){return this._createOptions},set:function(t){this._createOptions=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"createTime",{get:function(){return this._createTime},set:function(t){this._createTime=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataFree",{get:function(){return this._dataFree},set:function(t){this._dataFree=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataLength",{get:function(){return this._dataLength},set:function(t){this._dataLength=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"engine",{get:function(){return this._engine},set:function(t){this._engine=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"indexLength",{get:function(){return this._indexLength},set:function(t){this._indexLength=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxDataLength",{get:function(){return this._maxDataLength},set:function(t){this._maxDataLength=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxIndexLength",{get:function(){return this._maxIndexLength},set:function(t){this._maxIndexLength=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rowFormat",{get:function(){return this._rowFormat},set:function(t){this._rowFormat=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tableCatalog",{get:function(){return this._tableCatalog},set:function(t){this._tableCatalog=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tableCollation",{get:function(){return this._tableCollation},set:function(t){this._tableCollation=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tableComment",{get:function(){return this._tableComment},set:function(t){this._tableComment=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tableName",{get:function(){return this._tableName},set:function(t){this._tableName=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tableRows",{get:function(){return this._tableRows},set:function(t){this._tableRows=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tableSchema",{get:function(){return this._tableSchema},set:function(t){this._tableSchema=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tableType",{get:function(){return this._tableType},set:function(t){this._tableType=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"temporary",{get:function(){return this._temporary},set:function(t){this._temporary=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"updateTime",{get:function(){return this._updateTime},set:function(t){this._updateTime=t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"version",{get:function(){return this._version},set:function(t){this._version=t},enumerable:!1,configurable:!0}),e.getClassName=function(){return"MysqlTablesModel"},e.prototype.clone=function(){return e.from(this)},e.prototype.getClassName=function(){return"MysqlTablesModel"},e.prototype.getTableName=function(){return"information_schema.tables"},e.prototype.getPkSequenceName=function(){return null},e.prototype.getPrimaryKey=function(){return null},e.prototype.getAttributeMap=function(){return e.attributeMap},e.getTableName=function(){return"information_schema.tables"},e.getPkSequenceName=function(){return null},e.from=function(t){var a=null;return t&&(a=new e(t)),a},e.attributeMap={TABLE_CATALOG:{physical:!0,type:"string",attribute:"_tableCatalog"},table_catalog:{physical:!0,type:"string",attribute:"_tableCatalog"},tableCatalog:{alias:"TABLE_CATALOG",typeScriptStyle:!0,type:"string",attribute:"_tableCatalog"},TABLE_SCHEMA:{physical:!0,type:"string",attribute:"_tableSchema"},table_schema:{physical:!0,type:"string",attribute:"_tableSchema"},tableSchema:{alias:"TABLE_SCHEMA",typeScriptStyle:!0,type:"string",attribute:"_tableSchema"},TABLE_NAME:{physical:!0,type:"string",attribute:"_tableName"},table_name:{physical:!0,type:"string",attribute:"_tableName"},tableName:{alias:"TABLE_NAME",typeScriptStyle:!0,type:"string",attribute:"_tableName"},TABLE_TYPE:{physical:!0,type:"string",attribute:"_tableType"},table_type:{physical:!0,type:"string",attribute:"_tableType"},tableType:{alias:"TABLE_TYPE",typeScriptStyle:!0,type:"string",attribute:"_tableType"},ENGINE:{physical:!0,type:"string",attribute:"_engine"},engine:{physical:!0,type:"string",attribute:"_engine"},VERSION:{physical:!0,type:"number",attribute:"_version"},version:{physical:!0,type:"number",attribute:"_version"},ROW_FORMAT:{physical:!0,type:"string",attribute:"_rowFormat"},row_format:{physical:!0,type:"string",attribute:"_rowFormat"},rowFormat:{alias:"ROW_FORMAT",typeScriptStyle:!0,type:"string",attribute:"_rowFormat"},TABLE_ROWS:{physical:!0,type:"number",attribute:"_tableRows"},table_rows:{physical:!0,type:"number",attribute:"_tableRows"},tableRows:{alias:"TABLE_ROWS",typeScriptStyle:!0,type:"number",attribute:"_tableRows"},AVG_ROW_LENGTH:{physical:!0,type:"number",attribute:"_avgRowLength"},avg_row_length:{physical:!0,type:"number",attribute:"_avgRowLength"},avgRowLength:{alias:"AVG_ROW_LENGTH",typeScriptStyle:!0,type:"number",attribute:"_avgRowLength"},DATA_LENGTH:{physical:!0,type:"number",attribute:"_dataLength"},data_length:{physical:!0,type:"number",attribute:"_dataLength"},dataLength:{alias:"DATA_LENGTH",typeScriptStyle:!0,type:"number",attribute:"_dataLength"},MAX_DATA_LENGTH:{physical:!0,type:"number",attribute:"_maxDataLength"},max_data_length:{physical:!0,type:"number",attribute:"_maxDataLength"},maxDataLength:{alias:"MAX_DATA_LENGTH",typeScriptStyle:!0,type:"number",attribute:"_maxDataLength"},INDEX_LENGTH:{physical:!0,type:"number",attribute:"_indexLength"},index_length:{physical:!0,type:"number",attribute:"_indexLength"},indexLength:{alias:"INDEX_LENGTH",typeScriptStyle:!0,type:"number",attribute:"_indexLength"},DATA_FREE:{physical:!0,type:"number",attribute:"_dataFree"},data_free:{physical:!0,type:"number",attribute:"_dataFree"},dataFree:{alias:"DATA_FREE",typeScriptStyle:!0,type:"number",attribute:"_dataFree"},AUTO_INCREMENT:{physical:!0,type:"number",attribute:"_autoIncrement"},auto_increment:{physical:!0,type:"number",attribute:"_autoIncrement"},autoIncrement:{alias:"AUTO_INCREMENT",typeScriptStyle:!0,type:"number",attribute:"_autoIncrement"},CREATE_TIME:{physical:!0,type:"Date",attribute:"_createTime"},create_time:{physical:!0,type:"Date",attribute:"_createTime"},createTime:{alias:"CREATE_TIME",typeScriptStyle:!0,type:"Date",attribute:"_createTime"},UPDATE_TIME:{physical:!0,type:"Date",attribute:"_updateTime"},update_time:{physical:!0,type:"Date",attribute:"_updateTime"},updateTime:{alias:"UPDATE_TIME",typeScriptStyle:!0,type:"Date",attribute:"_updateTime"},CHECK_TIME:{physical:!0,type:"Date",attribute:"_checkTime"},check_time:{physical:!0,type:"Date",attribute:"_checkTime"},checkTime:{alias:"CHECK_TIME",typeScriptStyle:!0,type:"Date",attribute:"_checkTime"},TABLE_COLLATION:{physical:!0,type:"string",attribute:"_tableCollation"},table_collation:{physical:!0,type:"string",attribute:"_tableCollation"},tableCollation:{alias:"TABLE_COLLATION",typeScriptStyle:!0,type:"string",attribute:"_tableCollation"},CHECKSUM:{physical:!0,type:"number",attribute:"_checksum"},checksum:{physical:!0,type:"number",attribute:"_checksum"},CREATE_OPTIONS:{physical:!0,type:"string",attribute:"_createOptions"},create_options:{physical:!0,type:"string",attribute:"_createOptions"},createOptions:{alias:"CREATE_OPTIONS",typeScriptStyle:!0,type:"string",attribute:"_createOptions"},TABLE_COMMENT:{physical:!0,type:"string",attribute:"_tableComment"},table_comment:{physical:!0,type:"string",attribute:"_tableComment"},tableComment:{alias:"TABLE_COMMENT",typeScriptStyle:!0,type:"string",attribute:"_tableComment"},MAX_INDEX_LENGTH:{physical:!0,type:"number",attribute:"_maxIndexLength"},max_index_length:{physical:!0,type:"number",attribute:"_maxIndexLength"},maxIndexLength:{alias:"MAX_INDEX_LENGTH",typeScriptStyle:!0,type:"number",attribute:"_maxIndexLength"},TEMPORARY:{physical:!0,type:"string",attribute:"_temporary"},temporary:{alias:"TEMPORARY",typeScriptStyle:!0,type:"string",attribute:"_temporary"}},e}(abstract_model_1.AbstractModel);exports.MysqlTablesModel=MysqlTablesModel;
@@ -0,0 +1,55 @@
1
+ import { GenericModelData, ModelAttributeMap } from "../smart-db-interfaces";
2
+ import { AbstractModel } from "./abstract-model";
3
+ export interface OracleAllConsColumnsModelData extends GenericModelData {
4
+ owner?: string;
5
+ constraintName?: string;
6
+ tableName?: string;
7
+ columnName?: string;
8
+ position?: number;
9
+ }
10
+ export declare class OracleAllConsColumnsModel extends AbstractModel<OracleAllConsColumnsModel, OracleAllConsColumnsModelData> {
11
+ private _owner?;
12
+ private _constraintName?;
13
+ private _tableName?;
14
+ private _columnName?;
15
+ private _position?;
16
+ static readonly attributeMap: ModelAttributeMap;
17
+ static getClassName(): string;
18
+ static getTableName(): string;
19
+ static getPkSequenceName(): string;
20
+ static getPrimaryKey(): string;
21
+ static from(other: OracleAllConsColumnsModel | OracleAllConsColumnsModelData): OracleAllConsColumnsModel;
22
+ constructor(data?: OracleAllConsColumnsModel | OracleAllConsColumnsModelData);
23
+ clone(): OracleAllConsColumnsModel;
24
+ getClassName(): string;
25
+ getTableName(): string;
26
+ getPkSequenceName(): string;
27
+ getPrimaryKey(): string;
28
+ getAttributeMap(): ModelAttributeMap;
29
+ get owner(): string;
30
+ set owner(owner: string);
31
+ get OWNER(): string;
32
+ set OWNER(owner: string);
33
+ get constraintName(): string;
34
+ set constraintName(constraintName: string);
35
+ get constraint_name(): string;
36
+ set constraint_name(constraintName: string);
37
+ get CONSTRAINT_NAME(): string;
38
+ set CONSTRAINT_NAME(constraintName: string);
39
+ get tableName(): string;
40
+ set tableName(tableName: string);
41
+ get table_name(): string;
42
+ set table_name(tableName: string);
43
+ get TABLE_NAME(): string;
44
+ set TABLE_NAME(tableName: string);
45
+ get columnName(): string;
46
+ set columnName(columnName: string);
47
+ get column_name(): string;
48
+ set column_name(columnName: string);
49
+ get COLUMN_NAME(): string;
50
+ set COLUMN_NAME(columnName: string);
51
+ get position(): number;
52
+ set position(position: number);
53
+ get POSITION(): number;
54
+ set POSITION(position: number);
55
+ }
@@ -0,0 +1 @@
1
+ "use strict";var __extends=this&&this.__extends||function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.OracleAllConsColumnsModel=void 0;var abstract_model_1=require("./abstract-model"),OracleAllConsColumnsModel=function(e){function t(t){var n=e.call(this)||this;return t&&n.assign(t),n}return __extends(t,e),t.getClassName=function(){return"OracleAllConsColumnsModel"},t.getTableName=function(){return"all_cons_columns"},t.getPkSequenceName=function(){return null},t.getPrimaryKey=function(){return""},t.from=function(e){var n=null;return e&&(n=new t(e)),n},t.prototype.clone=function(){return t.from(this)},t.prototype.getClassName=function(){return"OracleAllConsColumnsModel"},t.prototype.getTableName=function(){return"all_cons_columns"},t.prototype.getPkSequenceName=function(){return null},t.prototype.getPrimaryKey=function(){return""},t.prototype.getAttributeMap=function(){return t.attributeMap},Object.defineProperty(t.prototype,"owner",{get:function(){return this._owner},set:function(e){this._owner=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"OWNER",{get:function(){return this._owner},set:function(e){this._owner=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"constraintName",{get:function(){return this._constraintName},set:function(e){this._constraintName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"constraint_name",{get:function(){return this._constraintName},set:function(e){this._constraintName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"CONSTRAINT_NAME",{get:function(){return this._constraintName},set:function(e){this._constraintName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tableName",{get:function(){return this._tableName},set:function(e){this._tableName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"table_name",{get:function(){return this._tableName},set:function(e){this._tableName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"TABLE_NAME",{get:function(){return this._tableName},set:function(e){this._tableName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"columnName",{get:function(){return this._columnName},set:function(e){this._columnName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"column_name",{get:function(){return this._columnName},set:function(e){this._columnName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"COLUMN_NAME",{get:function(){return this._columnName},set:function(e){this._columnName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"POSITION",{get:function(){return this._position},set:function(e){this._position=e},enumerable:!1,configurable:!0}),t.attributeMap={owner:{alias:"OWNER",typeScriptStyle:!0,type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(128)",attribute:"_owner"},OWNER:{physical:!0,type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(128)",attribute:"_owner"},constraintName:{alias:"CONSTRAINT_NAME",typeScriptStyle:!0,type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(128)",attribute:"_constraintName"},constraint_name:{type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(128)",attribute:"_constraintName"},CONSTRAINT_NAME:{physical:!0,type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(128)",attribute:"_constraintName"},tableName:{alias:"TABLE_NAME",typeScriptStyle:!0,type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(128)",attribute:"_tableName"},table_name:{type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(128)",attribute:"_tableName"},TABLE_NAME:{physical:!0,type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(128)",attribute:"_tableName"},columnName:{alias:"COLUMN_NAME",typeScriptStyle:!0,type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(4000)",attribute:"_columnName"},column_name:{type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(4000)",attribute:"_columnName"},COLUMN_NAME:{physical:!0,type:"string",dbType:"VARCHAR2",dbFullType:"VARCHAR2(4000)",attribute:"_columnName"},position:{alias:"POSITION",typeScriptStyle:!0,type:"number",dbType:"NUMBER",dbFullType:"NUMBER",attribute:"_position"},POSITION:{physical:!0,type:"number",dbType:"NUMBER",dbFullType:"NUMBER",attribute:"_position"}},t}(abstract_model_1.AbstractModel);exports.OracleAllConsColumnsModel=OracleAllConsColumnsModel;