@egi/smart-db 2.0.4 → 2.1.0

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 (76) hide show
  1. package/.eslintrc.json +212 -0
  2. package/README.md +2 -0
  3. package/assets/mysql/{database-init.sql → smart-db-core-init.sql} +0 -0
  4. package/assets/sqlite3/{database-init.sql → smart-db-core-init.sql} +0 -0
  5. package/bin/copy-assets +6 -0
  6. package/bin/extract-db-api +19 -0
  7. package/package.json +54 -26
  8. package/src/drivers/smart-db-better-sqlite3.ts +284 -0
  9. package/src/drivers/smart-db-mysql.ts +159 -0
  10. package/src/drivers/smart-db-mysql2.ts +159 -0
  11. package/src/drivers/smart-db-sqlite3.ts +198 -0
  12. package/src/helpers/extract-db-api.ts +465 -0
  13. package/src/helpers/terser-tree.ts +39 -0
  14. package/src/models/abstract-model.ts +209 -0
  15. package/src/models/smart-db-core-table-model.ts +161 -0
  16. package/src/models/smart-db-dictionary.ts +28 -0
  17. package/src/models/smart-db-log-model.ts +316 -0
  18. package/src/models/smart-db-version-model.ts +316 -0
  19. package/src/models/smart-db-version-view-model.ts +347 -0
  20. package/src/models/sqlite-master-model.ts +140 -0
  21. package/src/models/sqlite-sequence-model.ts +91 -0
  22. package/src/smart-db-api.ts +15 -0
  23. package/src/smart-db-globals.ts +136 -0
  24. package/src/smart-db-interfaces.ts +218 -0
  25. package/src/smart-db-log.ts +262 -0
  26. package/src/smart-db-sql-build-data.ts +28 -0
  27. package/src/smart-db-upgrade-manager.ts +171 -0
  28. package/src/smart-db.ts +854 -0
  29. package/test/data/sql-engine-tests.json +232 -0
  30. package/test/db/mysql/database-init.sql +11 -0
  31. package/test/db/sqlite3/database-init.sql +11 -0
  32. package/test/exer.js +28 -0
  33. package/test/model/smart-db-dictionary.ts +19 -0
  34. package/test/model/test-table-model.ts +214 -0
  35. package/test/test.js +273 -0
  36. package/test/test2.js +252 -0
  37. package/tsconfig.json +32 -0
  38. package/tsconfig.pro.json +32 -0
  39. package/tsconfig.test-model.json +23 -0
  40. package/bin/extract-db-interface +0 -18
  41. package/drivers/smart-db-better-sqlite3.d.ts +0 -34
  42. package/drivers/smart-db-better-sqlite3.js +0 -1
  43. package/drivers/smart-db-mysql.d.ts +0 -24
  44. package/drivers/smart-db-mysql.js +0 -1
  45. package/drivers/smart-db-mysql2.d.ts +0 -24
  46. package/drivers/smart-db-mysql2.js +0 -1
  47. package/drivers/smart-db-sqlite3.d.ts +0 -28
  48. package/drivers/smart-db-sqlite3.js +0 -1
  49. package/helpers/extract-db-interface.d.ts +0 -1
  50. package/helpers/extract-db-interface.js +0 -1
  51. package/index.d.ts +0 -10
  52. package/index.js +0 -1
  53. package/model/abstract-model.d.ts +0 -44
  54. package/model/abstract-model.js +0 -1
  55. package/model/smart-db-core-table-model.d.ts +0 -33
  56. package/model/smart-db-core-table-model.js +0 -1
  57. package/model/smart-db-dictionary.d.ts +0 -15
  58. package/model/smart-db-dictionary.js +0 -1
  59. package/model/smart-db-log-model.d.ts +0 -63
  60. package/model/smart-db-log-model.js +0 -1
  61. package/model/smart-db-version-model.d.ts +0 -63
  62. package/model/smart-db-version-model.js +0 -1
  63. package/model/smart-db-version-view-model.d.ts +0 -70
  64. package/model/smart-db-version-view-model.js +0 -1
  65. package/model/sqlite-master-model.d.ts +0 -29
  66. package/model/sqlite-master-model.js +0 -1
  67. package/model/sqlite-sequence-model.d.ts +0 -24
  68. package/model/sqlite-sequence-model.js +0 -1
  69. package/smart-db-interface.d.ts +0 -173
  70. package/smart-db-interface.js +0 -1
  71. package/smart-db-log.d.ts +0 -32
  72. package/smart-db-log.js +0 -1
  73. package/smart-db-upgrade-manager.d.ts +0 -13
  74. package/smart-db-upgrade-manager.js +0 -1
  75. package/smart-db.d.ts +0 -74
  76. package/smart-db.js +0 -1
@@ -1,173 +0,0 @@
1
- import { AbstractModel } from "./model/abstract-model";
2
- import { SmartDbDictionary } from "./model/smart-db-dictionary";
3
- export interface SmartDbOptions {
4
- module: string;
5
- sqlFilesDirectory: string;
6
- smartDbDictionary?: typeof SmartDbDictionary | any[];
7
- skipAutoUpgrade?: boolean;
8
- }
9
- export declare enum SeverityCode {
10
- Fatal = "F",
11
- Error = "E",
12
- Warning = "W",
13
- Info = "I",
14
- Debug = "D",
15
- Local = "L"
16
- }
17
- export declare enum SeverityLevel {
18
- None = 0,
19
- Fatal = 1,
20
- Error = 2,
21
- Warning = 3,
22
- Info = 4,
23
- Debug = 5,
24
- All = 9
25
- }
26
- export interface SmartDbRunResult {
27
- lastId: number;
28
- changes: number;
29
- affected: number;
30
- }
31
- export interface SmartDbTableInfo {
32
- fields: SmartDbFieldDescription[];
33
- }
34
- export interface SmartDbFieldDescription {
35
- name: string;
36
- type: string;
37
- cid?: string;
38
- virtual?: boolean;
39
- pk?: boolean;
40
- }
41
- export interface SmartDbSqlComparison {
42
- compare: string | SqlFieldDescriptor;
43
- with: string | SqlFieldDescriptor;
44
- operation?: SqlOperationType;
45
- }
46
- export interface SqlWhere {
47
- [key: string]: SqlValueType | SqlValueType[] | SqlOperation | SqlWhere | SqlWhere[] | SmartDbSqlComparison[];
48
- or?: SqlWhere | SqlWhere[];
49
- and?: SqlWhere | SqlWhere[];
50
- expression?: SmartDbSqlComparison[];
51
- }
52
- export declare type SqlUpdateValues = Record<string, SqlValueType>;
53
- export declare type SqlOrderBy = string | string[];
54
- declare type SqlGroupBy = string | string[];
55
- export interface SqlLimit {
56
- offset?: number;
57
- limit?: number;
58
- }
59
- export interface SectionDescription {
60
- model: (new () => AbstractModel) | string;
61
- where?: SqlWhere;
62
- fields?: string | SqlFieldDescriptor | (string | SqlFieldDescriptor)[] | null;
63
- groupBy?: SqlGroupBy;
64
- limit?: SqlLimit;
65
- }
66
- export interface SmartDbSqlOptions {
67
- firstOnly?: boolean;
68
- where?: SqlWhere;
69
- fields?: string | SqlFieldDescriptor | (string | SqlFieldDescriptor)[] | null;
70
- orderBy?: SqlOrderBy;
71
- groupBy?: SqlGroupBy;
72
- limit?: SqlLimit;
73
- count?: boolean;
74
- distinct?: boolean;
75
- collapseRow?: boolean;
76
- indexedBy?: string;
77
- union?: SectionDescription | SectionDescription[];
78
- minus?: SectionDescription | SectionDescription[];
79
- intersect?: SectionDescription | SectionDescription[];
80
- }
81
- export declare enum SqlOperationType {
82
- GT = ">",
83
- GE = ">=",
84
- LT = "<",
85
- LE = "<=",
86
- EQ = "=",
87
- NE = "!=",
88
- IN = "IN",
89
- LIKE = "LIKE",
90
- NOT_LIKE = "NOT LIKE",
91
- IS_NULL = "IS NULL",
92
- IS_NOT_NULL = "IS NOT NULL",
93
- LITERAL = "LITERAL",
94
- VALUE = "VALUE"
95
- }
96
- export declare enum SqlFieldOperationType {
97
- VALUE = "VALUE",
98
- FIELD = "FIELD",
99
- COUNT = "COUNT",
100
- COALESCE = "COALESCE"
101
- }
102
- export interface SqlFieldDescriptor {
103
- operation: SqlFieldOperationType;
104
- value: SqlFieldDescriptor | SqlValueType | (SqlFieldDescriptor | SqlValueType)[];
105
- alias?: string;
106
- literal?: boolean;
107
- }
108
- export interface SqlOperation {
109
- operation: SqlOperationType;
110
- value: SqlValueType | SqlValueType[];
111
- key?: string;
112
- literalOperation?: SqlOperationType;
113
- }
114
- export declare type SqlValueType = string | number | boolean | Date;
115
- export interface DatabaseRow {
116
- [field: string]: SqlValueType;
117
- }
118
- export interface KeyValueList {
119
- [key: string]: SqlValueType;
120
- }
121
- export interface IndexedDatabaseRows<T extends AbstractModel> {
122
- [key: string]: AbstractModel | T | DatabaseRow;
123
- }
124
- export declare const OP: (op: SqlOperationType, value?: string | number | boolean | Date | SqlValueType[], key?: string, literalOp?: SqlOperationType) => SqlOperation;
125
- export declare const VALUE: (value: SqlValueType, alias?: string, literal?: boolean) => SqlFieldDescriptor;
126
- export declare const FIELD: (value: string, alias?: string) => SqlFieldDescriptor;
127
- export declare const COUNT: (value?: string, alias?: string) => SqlFieldDescriptor;
128
- export declare const COALESCE: (values: (string | number | boolean | Date | SqlFieldDescriptor)[], alias?: string) => SqlFieldDescriptor;
129
- export declare const NVL: (values: (string | number | boolean | Date | SqlFieldDescriptor)[], alias?: string) => SqlFieldDescriptor;
130
- export declare const LITERAL: (key: string, value: SqlValueType, op?: SqlOperationType) => SqlOperation;
131
- export declare const GT: (value: SqlValueType) => SqlOperation;
132
- export declare const GE: (value: SqlValueType) => SqlOperation;
133
- export declare const LT: (value: SqlValueType) => SqlOperation;
134
- export declare const LE: (value: SqlValueType) => SqlOperation;
135
- export declare const EQ: (value: SqlValueType) => SqlOperation;
136
- export declare const NE: (value: any) => SqlOperation;
137
- export declare const IN: (value: SqlValueType[]) => SqlOperation;
138
- export declare const IS_NULL: () => SqlOperation;
139
- export declare const IS_NOT_NULL: () => SqlOperation;
140
- export interface SmartDbSqlBuildDataResults {
141
- sql: string;
142
- values: SqlValueType[];
143
- }
144
- export declare class SmartDbSqlBuildData {
145
- sql: string;
146
- values: SqlValueType[];
147
- constructor(sql?: string, values?: SqlValueType[]);
148
- append(data: SmartDbSqlBuildData): void;
149
- toString(): string;
150
- results(): SmartDbSqlBuildDataResults;
151
- }
152
- export interface SmartDbInterface {
153
- exists<T extends AbstractModel>(modelClass: string | (new () => T), type?: "view" | "table" | "index", indexTableName?: string): Promise<boolean>;
154
- existsSync<T extends AbstractModel>(modelClass: string | (new () => T), type?: "view" | "table" | "index", indexTableName?: string): boolean;
155
- get<T extends AbstractModel>(modelClass: string | (new () => T), options: SmartDbSqlOptions): Promise<T | T[] | string | string[] | DatabaseRow | SqlValueType | IndexedDatabaseRows<T>>;
156
- getSync<T extends AbstractModel>(modelClass: string | (new () => T), options: SmartDbSqlOptions): T | T[] | string | string[] | DatabaseRow | SqlValueType | IndexedDatabaseRows<T> | false;
157
- getFirst<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere, fields?: string | string[] | null, orderBy?: SqlOrderBy): Promise<T>;
158
- getFirstSync<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere, fields?: string | string[] | null, orderBy?: SqlOrderBy): T | false;
159
- getAll<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere, fields?: string | string[] | null, orderBy?: SqlOrderBy, limit?: SqlLimit): Promise<T[]>;
160
- getAllSync<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere, fields?: string | string[] | null, orderBy?: SqlOrderBy, limit?: SqlLimit): T[] | false;
161
- delete<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere): Promise<number>;
162
- deleteSync<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere): number | false;
163
- update<T extends AbstractModel>(modelClass: string | (new () => T), values: SqlUpdateValues, where?: SqlWhere): Promise<number>;
164
- updateSync<T extends AbstractModel>(modelClass: string | (new () => T), values: SqlUpdateValues, where?: SqlWhere): number | false;
165
- insert<T extends AbstractModel>(modelClass: string | (new () => T), values: SqlUpdateValues): Promise<number>;
166
- insertSync<T extends AbstractModel>(modelClass: string | (new () => T), values: SqlUpdateValues): number | false;
167
- getLastError(): any;
168
- getLastBuildData(): SmartDbSqlBuildData;
169
- toDate(d: Date | number | string): Date | null;
170
- toDbTimestamp(d: Date | number): string;
171
- toDbDate(d: Date | number): string;
172
- }
173
- export {};
@@ -1 +0,0 @@
1
- "use strict";var __importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(exports,"__esModule",{value:!0});var SeverityCode,SeverityLevel,SqlOperationType,SqlFieldOperationType,_=__importStar(require("lodash"));!function(e){e.Fatal="F",e.Error="E",e.Warning="W",e.Info="I",e.Debug="D",e.Local="L"}(SeverityCode=exports.SeverityCode||(exports.SeverityCode={})),function(e){e[e.None=0]="None",e[e.Fatal=1]="Fatal",e[e.Error=2]="Error",e[e.Warning=3]="Warning",e[e.Info=4]="Info",e[e.Debug=5]="Debug",e[e.All=9]="All"}(SeverityLevel=exports.SeverityLevel||(exports.SeverityLevel={})),function(e){e.GT=">",e.GE=">=",e.LT="<",e.LE="<=",e.EQ="=",e.NE="!=",e.IN="IN",e.LIKE="LIKE",e.NOT_LIKE="NOT LIKE",e.IS_NULL="IS NULL",e.IS_NOT_NULL="IS NOT NULL",e.LITERAL="LITERAL",e.VALUE="VALUE"}(SqlOperationType=exports.SqlOperationType||(exports.SqlOperationType={})),function(e){e.VALUE="VALUE",e.FIELD="FIELD",e.COUNT="COUNT",e.COALESCE="COALESCE"}(SqlFieldOperationType=exports.SqlFieldOperationType||(exports.SqlFieldOperationType={})),exports.OP=function(e,t,r,o){return r?{operation:e,value:t,key:r,literalOperation:o}:{operation:e,value:t}},exports.VALUE=function(e,t,r){return{operation:SqlFieldOperationType.VALUE,value:e,alias:t,literal:r}},exports.FIELD=function(e,t){return{operation:SqlFieldOperationType.FIELD,value:e,alias:t}},exports.COUNT=function(e,t){return{operation:SqlFieldOperationType.COUNT,value:e,alias:t}},exports.COALESCE=function(e,t){return{operation:SqlFieldOperationType.COALESCE,value:e,alias:t}},exports.NVL=function(e,t){return exports.COALESCE(e,t)},exports.LITERAL=function(e,t,r){return exports.OP(SqlOperationType.LITERAL,t,e,r||SqlOperationType.EQ)},exports.GT=function(e){return exports.OP(SqlOperationType.GT,e)},exports.GE=function(e){return exports.OP(SqlOperationType.GE,e)},exports.LT=function(e){return exports.OP(SqlOperationType.LT,e)},exports.LE=function(e){return exports.OP(SqlOperationType.LE,e)},exports.EQ=function(e){return exports.OP(SqlOperationType.EQ,e)},exports.NE=function(e){return exports.OP(SqlOperationType.NE,e)},exports.IN=function(e){return exports.OP(SqlOperationType.IN,e)},exports.IS_NULL=function(){return exports.OP(SqlOperationType.IS_NULL)},exports.IS_NOT_NULL=function(){return exports.OP(SqlOperationType.IS_NOT_NULL)};var SmartDbSqlBuildData=function(){function e(e,t){this.sql=e||"",this.values=t||[]}return e.prototype.append=function(e){this.sql=this.sql.trim()+" "+e.sql.trim(),this.values=_.concat(this.values,e.values)},e.prototype.toString=function(){return this.sql+" <= ("+this.values.join(", ")+")"},e.prototype.results=function(){return{sql:this.sql,values:this.values}},e}();exports.SmartDbSqlBuildData=SmartDbSqlBuildData;
package/smart-db-log.d.ts DELETED
@@ -1,32 +0,0 @@
1
- import { SmartDbInterface, SeverityLevel, SeverityCode } from "./smart-db-interface";
2
- export declare enum SmartDbLogType {
3
- Frontend = "frontend",
4
- Backend = "backend",
5
- Database = "database",
6
- UpgradeManager = "upgrade-mananger",
7
- Other = "other"
8
- }
9
- export declare class SmartDbLog {
10
- private db;
11
- private dbLogLevel;
12
- private consoleLogLevel;
13
- private userId;
14
- private dbLogging;
15
- private isLogging;
16
- constructor(db?: SmartDbInterface);
17
- getConsoleLogLevel(): SeverityLevel;
18
- setConsoleLogLevel(consoleLogLevel: SeverityLevel): void;
19
- getDbLogLevel(): SeverityLevel;
20
- setDbLogLevel(dbLogLevel: SeverityLevel): void;
21
- setDb(db: SmartDbInterface): void;
22
- setUserId(userId: string | number): void;
23
- setDbLogging(dbLogging: boolean): void;
24
- getDbLogging(): boolean;
25
- logFatal(type: SmartDbLogType, location: string, message: string | Error, data?: any): void;
26
- logError(type: SmartDbLogType, location: string, message: string | Error, data?: any): void;
27
- logWarning(type: SmartDbLogType, location: string, message: string | Error, data?: any): void;
28
- logInfo(type: SmartDbLogType, location: string, message: string | Error, data?: any): void;
29
- logDebug(type: SmartDbLogType, location: string, message: string | Error, data?: any): void;
30
- writeLog(type: SmartDbLogType, location: string, severity: SeverityCode, message: string | Error, data: unknown, timestamp?: Date | string | number): void;
31
- }
32
- export declare const smartDbLog: SmartDbLog;
package/smart-db-log.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var __importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(exports,"__esModule",{value:!0});var SmartDbLogType,smart_db_interface_1=require("./smart-db-interface"),smart_db_1=require("./smart-db"),smart_db_log_model_1=require("./model/smart-db-log-model"),_=__importStar(require("lodash"));!function(e){e.Frontend="frontend",e.Backend="backend",e.Database="database",e.UpgradeManager="upgrade-mananger",e.Other="other"}(SmartDbLogType=exports.SmartDbLogType||(exports.SmartDbLogType={}));var SmartDbLog=function(){function e(e){this.dbLogLevel=smart_db_interface_1.SeverityLevel.Info,this.consoleLogLevel=smart_db_interface_1.SeverityLevel.Error,this.userId=null,this.dbLogging=!1,this.isLogging=!1,this.db=e}return e.prototype.getConsoleLogLevel=function(){return this.consoleLogLevel},e.prototype.setConsoleLogLevel=function(e){this.consoleLogLevel=e},e.prototype.getDbLogLevel=function(){return this.dbLogLevel},e.prototype.setDbLogLevel=function(e){this.dbLogLevel=e},e.prototype.setDb=function(e){var t=this;this.db=e,this.db?this.db.exists(smart_db_log_model_1.SmartDbLogModel).then((function(e){t.dbLogging=e})).catch((function(e){throw e})):this.dbLogging=!1},e.prototype.setUserId=function(e){this.userId=e},e.prototype.setDbLogging=function(e){this.dbLogging=e},e.prototype.getDbLogging=function(){return this.dbLogging},e.prototype.logFatal=function(e,t,r,o){this.writeLog(e,t,smart_db_interface_1.SeverityCode.Fatal,r,o)},e.prototype.logError=function(e,t,r,o){this.writeLog(e,t,smart_db_interface_1.SeverityCode.Error,r,o)},e.prototype.logWarning=function(e,t,r,o){this.writeLog(e,t,smart_db_interface_1.SeverityCode.Warning,r,o)},e.prototype.logInfo=function(e,t,r,o){this.writeLog(e,t,smart_db_interface_1.SeverityCode.Info,r,o)},e.prototype.logDebug=function(e,t,r,o){this.writeLog(e,t,smart_db_interface_1.SeverityCode.Debug,r,o)},e.prototype.writeLog=function(e,t,r,o,i,a){var s=this;try{if(this.isLogging)console.error("recursive logging error:",e,t,r,o,i);else{this.isLogging=!0;var n,g,b=smart_db_interface_1.SeverityLevel.None;switch(r){case smart_db_interface_1.SeverityCode.Fatal:n=console.error,b=smart_db_interface_1.SeverityLevel.Fatal;break;case smart_db_interface_1.SeverityCode.Error:n=console.error,b=smart_db_interface_1.SeverityLevel.Error;break;case smart_db_interface_1.SeverityCode.Warning:n=console.warn,b=smart_db_interface_1.SeverityLevel.Warning;break;case smart_db_interface_1.SeverityCode.Info:n=console.info,b=smart_db_interface_1.SeverityLevel.Info;break;case smart_db_interface_1.SeverityCode.Debug:n=console.debug,b=smart_db_interface_1.SeverityLevel.Debug}if(_.isString(a)){var l=a.match(smart_db_1.SmartDb.DbTimestampRegexp),d=l&&a.match(smart_db_1.SmartDb.DbDateRegexp);g=l?l[1]:d?d[1]+".000":smart_db_1.SmartDb.toDbTimestamp(new Date)}else g=_.isDate(a)?smart_db_1.SmartDb.toDbTimestamp(a):_.isNumber(a)?smart_db_1.SmartDb.toDbTimestamp(new Date(a)):smart_db_1.SmartDb.toDbTimestamp(new Date);if(_.isObjectLike(o))if(o instanceof Error)i||(i=o),o=o.message;else try{o=JSON.stringify(o)}catch(e){o=o.toString()}if(i){if(i instanceof Error)i=i.stack;else if(_.isObject(i))try{i=JSON.stringify(i)}catch(e){i=i.toString(),this.db&&this.dbLogLevel>=b&&console.error("unable to stringify log data",i)}else i.toString?i=i.toString():(i=null,this.db&&this.dbLogLevel>=b&&console.error("unable to store log data",i));i&&(o+=" ("+i+")")}if(this.consoleLogLevel>=b){var c=e.substr(0,1).toUpperCase();e==SmartDbLogType.Database&&this.db&&n(r+"-"+c+"-"+g+": last statement:",this.db.getLastBuildData()),n(r+"-"+c+"-"+g+": "+o)}if(this.dbLogging&&this.dbLogLevel>=b)try{e==SmartDbLogType.Database&&(i||(i=JSON.stringify(this.db.getLastBuildData()))),this.db.insert(smart_db_log_model_1.SmartDbLogModel,{severity:r,type:e,location:t,info:o,data:i,user:this.userId,timestamp:new Date(g)}).catch((function(e){console.error("F-B-"+g+": unable to write the log statement below to database",e);try{n("F-B-"+g+": last statement:",s.db.getLastBuildData())}catch(e){n("F-B-"+g+": last statement not available")}}))}catch(e){console.error("unable to write to log",e)}}this.isLogging=!1}catch(e){this.isLogging=!1,console.error("fatal logging error",e)}},e}();exports.SmartDbLog=SmartDbLog,exports.smartDbLog=new SmartDbLog;
@@ -1,13 +0,0 @@
1
- import { SmartDb } from "./smart-db";
2
- import { SmartDbVersionViewModel } from "./model/smart-db-version-view-model";
3
- import { SmartDbOptions } from "./smart-db-interface";
4
- export declare class SmartDbUpgradeManager {
5
- private db;
6
- private log;
7
- constructor(db: SmartDb);
8
- hasDatabaseModule(module: string): Promise<boolean>;
9
- prepareDatabase(options: SmartDbOptions): Promise<SmartDbVersionViewModel>;
10
- private executeSqlScript;
11
- private upgradeDatabase;
12
- private executeScriptSequentially;
13
- }
@@ -1 +0,0 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(a,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function s(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}c((n=n.apply(e,t||[])).next())}))},__generator=this&&this.__generator||function(e,t){var r,n,a,i,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(a=2&i[0]?n.return:i[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,i[1])).done)return a;switch(n=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],n=0}finally{r=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}},__importStar=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(exports,"__esModule",{value:!0});var fs=__importStar(require("fs")),_=__importStar(require("lodash")),smart_db_log_1=require("./smart-db-log"),smart_db_version_view_model_1=require("./model/smart-db-version-view-model"),SmartDbUpgradeManager=function(){function e(e){this.db=e,this.log=e.getLogger()}return e.prototype.hasDatabaseModule=function(e){var t=this;return new Promise((function(r,n){t.db.exists(smart_db_version_view_model_1.SmartDbVersionViewModel).then((function(a){a?t.db.getFirst(smart_db_version_view_model_1.SmartDbVersionViewModel,{module:e}).then((function(e){r(!!e)})).catch((function(e){n(e)})):r(!1)})).catch((function(e){n(e)}))}))},e.prototype.prepareDatabase=function(e){var t=this;return new Promise((function(r,n){try{var a=fs.existsSync(e.sqlFilesDirectory)&&fs.statSync(e.sqlFilesDirectory);if(a&&a.isDirectory()){var i=e.sqlFilesDirectory+"/database-init.sql";fs.existsSync(i)?t.hasDatabaseModule(e.module).then((function(a){a?t.upgradeDatabase(e).then((function(e){r(e)})).catch((function(e){n(e)})):t.executeSqlScript(i).then((function(){t.hasDatabaseModule(e.module).then((function(a){a?(t.log.logInfo(smart_db_log_1.SmartDbLogType.UpgradeManager,"prepareDatabase","successfully initialized database for new module "+e.module),t.upgradeDatabase(e).then((function(e){r(e)})).catch((function(e){n(e)}))):n("error running database initialization script")})).catch((function(e){n(e)}))})).catch((function(e){n(e)}))})).catch((function(e){n(e)})):n("missing mandatory 'database-init.sql' file in "+i)}else n("option 'sqlFilesDirectory' must point to an existing directory (absolute or relatie to "+fs.realpathSync(".")+")")}catch(e){n(e)}}))},e.prototype.executeSqlScript=function(e){var t=fs.readFileSync(e,"utf8");return this.db.exec(t)},e.prototype.upgradeDatabase=function(e){var t=this;return new Promise((function(r,n){t.db.getFirst(smart_db_version_view_model_1.SmartDbVersionViewModel,{module:e.module}).then((function(a){a?fs.readdir(e.sqlFilesDirectory,(function(i,o){if(i)n("unable to read database files from "+e.sqlFilesDirectory);else{var s=[];o.forEach((function(e){var t=e.match(/^database-update.([0-9]{3})\..*\.sql$/);t&&(parseInt(t[1],10)>a.sequence&&s.push(e))})),s=_.sortBy(s),t.executeScriptSequentially(s,e).then((function(){t.db.getFirst(smart_db_version_view_model_1.SmartDbVersionViewModel,{module:e.module},"*","sequence DESC").then((function(e){e?r(smart_db_version_view_model_1.SmartDbVersionViewModel.from(e)):n("unable to determine final smart db version")})).catch((function(e){n(e)}))})).catch((function(e){n(e)}))}})):n("missing version entry for module "+e.module+" - add the mandatory insert into smart_db_version statement to your database creation script!")})).catch((function(e){n(e)}))}))},e.prototype.executeScriptSequentially=function(e,t){var r=this;return new Promise((function(n,a){return __awaiter(r,void 0,void 0,(function(){var r=this;return __generator(this,(function(i){switch(i.label){case 0:return e&&e.length>0?[4,this.executeSqlScript(t.sqlFilesDirectory+"/"+e[0]).then((function(){r.log.logInfo(smart_db_log_1.SmartDbLogType.UpgradeManager,"upgradeDatabase","successfully executed update script '"+e[0]+"' for module "+t.module),1==e.length&&n(!0)})).catch((function(e){a(e)}))]:[3,2];case 1:return i.sent(),e.length>1&&this.executeScriptSequentially(e.splice(1),t).then((function(e){n(e)})).catch((function(e){a(e)})),[3,3];case 2:n(!0),i.label=3;case 3:return[2]}}))}))}))},e}();exports.SmartDbUpgradeManager=SmartDbUpgradeManager;
package/smart-db.d.ts DELETED
@@ -1,74 +0,0 @@
1
- import { SmartDbLog } from "./smart-db-log";
2
- import { AbstractModel } from "./model/abstract-model";
3
- import { SmartDbVersionViewModel } from "./model/smart-db-version-view-model";
4
- import { DatabaseRow, IndexedDatabaseRows, SmartDbInterface, SmartDbOptions, SmartDbRunResult, SmartDbSqlBuildData, SqlFieldDescriptor, SqlLimit, SmartDbSqlOptions, SqlOrderBy, SqlUpdateValues, SqlValueType, SqlWhere, SmartDbTableInfo } from "./smart-db-interface";
5
- export interface SmartDbDatabase {
6
- }
7
- export interface SmartDbConnector {
8
- }
9
- export declare abstract class SmartDb implements SmartDbInterface {
10
- static readonly DbDateRegexp: RegExp;
11
- static readonly DbTimestampRegexp: RegExp;
12
- protected db: SmartDbDatabase;
13
- protected dbConnector: SmartDbConnector;
14
- protected lastError: Error;
15
- protected lastBuildData: SmartDbSqlBuildData;
16
- protected smartDbLog: SmartDbLog;
17
- private dictionaries;
18
- protected constructor(dbConnector: SmartDbConnector);
19
- static toDbDate(d: Date | number): string;
20
- static toDbTimestamp(d: Date | number): string;
21
- static toDate(d: Date | number | string): Date | null;
22
- abstract getDatabaseType(): string;
23
- abstract exists<T extends AbstractModel>(modelClass: string | (new () => T), type?: "view" | "table" | "index", indexTableName?: string): Promise<boolean>;
24
- abstract existsSync<T extends AbstractModel>(modelClass: string | (new () => T), type?: "view" | "table" | "index", indexTableName?: string): boolean;
25
- abstract exec(script: string): Promise<void>;
26
- abstract execSync(script: string): SmartDbDatabase | false;
27
- abstract close(): Promise<void>;
28
- abstract closeSync(): boolean;
29
- abstract getDbQuote(): string;
30
- abstract getTableInfo(table: string): Promise<SmartDbTableInfo>;
31
- abstract getDbConnector(): string | SmartDbConnector;
32
- initDb(appOptions: SmartDbOptions | SmartDbOptions[]): Promise<SmartDbVersionViewModel[]>;
33
- getLogger(): SmartDbLog;
34
- getDb(): SmartDbDatabase;
35
- getLastBuildData(): SmartDbSqlBuildData;
36
- get<T extends AbstractModel>(modelClass: string | (new () => T), options: SmartDbSqlOptions): Promise<T | T[] | string | string[] | DatabaseRow | SqlValueType | IndexedDatabaseRows<T>>;
37
- getSync<T extends AbstractModel>(modelClass: string | (new () => T), options: SmartDbSqlOptions): T | T[] | string | string[] | DatabaseRow | SqlValueType | IndexedDatabaseRows<T> | false;
38
- getFirst<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere, fields?: string | string[] | null, orderBy?: SqlOrderBy): Promise<T>;
39
- getFirstSync<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere, fields?: string | string[] | null, orderBy?: SqlOrderBy): T | false;
40
- getAll<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere, fields?: string | string[] | null, orderBy?: SqlOrderBy, limit?: SqlLimit): Promise<T[]>;
41
- getAllSync<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere, fields?: string | string[] | null, orderBy?: SqlOrderBy, limit?: SqlLimit): T[] | false;
42
- delete<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere): Promise<number>;
43
- deleteSync<T extends AbstractModel>(modelClass: string | (new () => T), where?: SqlWhere): number | false;
44
- update<T extends AbstractModel>(modelClass: string | (new () => T), values: SqlUpdateValues | AbstractModel, where?: SqlWhere): Promise<number>;
45
- updateSync<T extends AbstractModel>(modelClass: string | (new () => T), values: SqlUpdateValues | AbstractModel, where?: SqlWhere): number | false;
46
- insert<T extends AbstractModel>(modelClass: string | (new () => T), values: SqlUpdateValues | AbstractModel): Promise<number>;
47
- insertSync<T extends AbstractModel>(modelClass: string | (new () => T), values: SqlUpdateValues | AbstractModel): number | false;
48
- getLastError(): Error;
49
- buildSelectStatement(modelClass: string | (new () => AbstractModel), options: SmartDbSqlOptions): SmartDbSqlBuildData;
50
- toDate(d: Date | number | string): Date | null;
51
- toDbTimestamp(d: Date | number): string;
52
- toDbDate(d: Date | number): string;
53
- protected abstract statementRun(buildData: SmartDbSqlBuildData): Promise<SmartDbRunResult>;
54
- protected abstract statementRunSync(buildData: SmartDbSqlBuildData): SmartDbRunResult;
55
- protected abstract statementGet(buildData: SmartDbSqlBuildData): Promise<any>;
56
- protected abstract statementGetSync(buildData: SmartDbSqlBuildData): any;
57
- protected abstract statementGetAll(buildData: SmartDbSqlBuildData): Promise<any[]>;
58
- protected abstract statementGetAllSync(buildData: SmartDbSqlBuildData): any[];
59
- protected buildWhere(modelClass: string | (new () => AbstractModel), where: SqlWhere, op?: string): SmartDbSqlBuildData;
60
- protected buildDeleteStatement(modelClass: string | (new () => AbstractModel), where?: SqlWhere): SmartDbSqlBuildData;
61
- protected buildUpdateStatement(modelClass: string | (new () => AbstractModel), values: SqlUpdateValues | AbstractModel, where?: SqlWhere): SmartDbSqlBuildData;
62
- protected buildInsertStatement(modelClass: string | (new () => AbstractModel), values: SqlUpdateValues | AbstractModel): SmartDbSqlBuildData;
63
- protected prepareFieldValue(modelClass: string | (new () => AbstractModel), fieldOperation: SqlFieldDescriptor): string;
64
- protected prepareField(modelClass: string | (new () => AbstractModel), field: SqlValueType | SqlFieldDescriptor, values?: SqlValueType[]): string;
65
- protected buildFieldList(modelClass: string | (new () => AbstractModel), fields: (SqlValueType | SqlFieldDescriptor)[]): string[];
66
- protected buildSelectSectionStatement(modelClass: string | (new () => AbstractModel), options: SmartDbSqlOptions): SmartDbSqlBuildData;
67
- protected translateFieldName(modelClass: string | (new () => AbstractModel), field: string): string;
68
- protected makeDbValue(value: SqlValueType): SqlValueType;
69
- protected makeArgumentDbValue(value: SqlValueType): SqlValueType;
70
- protected saveExecute<T>(fn: () => T): T | false;
71
- private prepareResultRow;
72
- private prepareResultRows;
73
- private getTableName;
74
- }
package/smart-db.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});var smart_db_log_1=require("./smart-db-log"),abstract_model_1=require("./model/abstract-model"),smart_db_upgrade_manager_1=require("./smart-db-upgrade-manager"),smart_db_log_model_1=require("./model/smart-db-log-model"),smart_db_dictionary_1=require("./model/smart-db-dictionary"),smart_db_interface_1=require("./smart-db-interface"),lodash_1=__importDefault(require("lodash")),fs_1=__importDefault(require("fs")),SmartDb=function(){function e(e){this.dictionaries=[],this.dbConnector=e,this.smartDbLog=new smart_db_log_1.SmartDbLog(this)}return e.toDbDate=function(e){var t;return e&&(lodash_1.default.isNumber(e)&&(e=new Date(e)),t=e.toISOString().substr(0,19).replace("T"," ")),t},e.toDbTimestamp=function(e){var t;return e&&(lodash_1.default.isNumber(e)&&(e=new Date(e)),t=e.toISOString().substr(0,23).replace("T"," ")),t},e.toDate=function(t){var a=null;return lodash_1.default.isDate(t)?a=t:(lodash_1.default.isNumber(t)||lodash_1.default.isString(t)&&(t.match(e.DbDateRegexp)||t.match(e.DbTimestampRegexp)))&&(a=new Date(t)),a},e.prototype.initDb=function(e){var t=this;return new Promise((function(a,r){t.dictionaries.push(smart_db_dictionary_1.SmartDbDictionary);var i=new smart_db_upgrade_manager_1.SmartDbUpgradeManager(t),n="assets/"+t.getDatabaseType();fs_1.default.existsSync(__dirname+"/"+n)&&(n=__dirname+"/"+n);var l={module:"smart-db-core",sqlFilesDirectory:n};i.prepareDatabase(l).then((function(n){t.exists(smart_db_log_model_1.SmartDbLogModel).then((function(e){t.smartDbLog.setDbLogging(e)}));var l=[],o=lodash_1.default.isArray(e)?e:[e];lodash_1.default.forEach(o,(function(e){l.push(i.prepareDatabase(e)),e.smartDbDictionary&&t.dictionaries.push(e.smartDbDictionary)})),Promise.all(l).then((function(e){e.push(n),a(e)}),(function(e){r(e)}))})).catch((function(e){r(e)}))}))},e.prototype.getLogger=function(){return this.smartDbLog},e.prototype.getDb=function(){return this.db},e.prototype.getLastBuildData=function(){return this.lastBuildData},e.prototype.get=function(e,t){var a=this;return new Promise((function(r,i){t||(t={});var n=a.buildSelectStatement(e,t);t.firstOnly||t.count?a.statementGet(n).then((function(i){r(a.prepareResultRow(e,i,t))})).catch((function(e){i(e)})):a.statementGetAll(n).then((function(i){r(a.prepareResultRows(e,i,t))})).catch((function(e){i(e)}))}))},e.prototype.getSync=function(e,t){var a=this;return this.saveExecute((function(){t||(t={});var r,i=a.buildSelectStatement(e,t);if(t.firstOnly||t.count){var n=a.statementGetSync(i);r=a.prepareResultRow(e,n,t)}else{var l=a.statementGetAllSync(i);r=a.prepareResultRows(e,l,t)}return r}))},e.prototype.getFirst=function(e,t,a,r){return this.get(e,{firstOnly:!0,where:t,fields:a,orderBy:r})},e.prototype.getFirstSync=function(e,t,a,r){return this.getSync(e,{firstOnly:!0,where:t,fields:a,orderBy:r})},e.prototype.getAll=function(e,t,a,r,i){return this.get(e,{where:t,fields:a,orderBy:r,limit:i})},e.prototype.getAllSync=function(e,t,a,r,i){return this.getSync(e,{where:t,fields:a,orderBy:r,limit:i})},e.prototype.delete=function(e,t){var a=this;return new Promise((function(r,i){var n=a.buildDeleteStatement(e,t);a.statementRun(n).then((function(e){e?r(e.changes):i(a.getLastError())})).catch((function(e){i(e)}))}))},e.prototype.deleteSync=function(e,t){var a=this;return this.saveExecute((function(){var r=a.buildDeleteStatement(e,t);return a.statementRunSync(r).changes}))},e.prototype.update=function(e,t,a){var r=this;return new Promise((function(i,n){var l=r.buildUpdateStatement(e,t,a);r.statementRun(l).then((function(e){e?i(e.changes):n(r.getLastError())})).catch((function(e){n(e)}))}))},e.prototype.updateSync=function(e,t,a){var r=this;return this.saveExecute((function(){var i=r.buildUpdateStatement(e,t,a);return r.statementRunSync(i).changes}))},e.prototype.insert=function(e,t){var a=this;return new Promise((function(r,i){var n=a.buildInsertStatement(e,t);a.statementRun(n).then((function(e){e?r(e.lastId):i(a.getLastError())})).catch((function(e){i(e)}))}))},e.prototype.insertSync=function(e,t){var a=this;return this.saveExecute((function(){var r=a.buildInsertStatement(e,t);return a.statementRunSync(r).lastId}))},e.prototype.getLastError=function(){return this.lastError},e.prototype.buildSelectStatement=function(e,t){var a=this;t||(t={});var r=this.buildSelectSectionStatement(e,t);if(lodash_1.default.forEach(["union","minus","intersect"],(function(e){var i=lodash_1.default.get(t,e);i&&(lodash_1.default.isArray(i)||(i=[i]),lodash_1.default.forEach(i,(function(t){var i=a.buildSelectSectionStatement(t.model,t);r.sql+=" "+e.toUpperCase()+" ",r.append(i)})))})),t.orderBy){r.sql+=" ORDER BY ";var i=lodash_1.default.isString(t.orderBy)?t.orderBy.split(/ *, */):t.orderBy;r.sql+=i.map((function(t){var r="",i=t.match(/^(\w*) (asc|desc)$/i);return i&&(t=i[1],r=i[2].toUpperCase()),t=a.translateFieldName(e,t),r&&(t+=" "+r),t})).join(", ")}return t.limit&&(t.limit.limit&&(r.sql+=" LIMIT "+t.limit.limit.toString()),t.limit.offset&&(r.sql+=" OFFSET "+t.limit.offset.toString())),this.lastBuildData=r,r},e.prototype.toDate=function(t){return e.toDate(t)},e.prototype.toDbTimestamp=function(t){return e.toDbTimestamp(t)},e.prototype.toDbDate=function(t){return e.toDbDate(t)},e.prototype.buildWhere=function(e,t,a){var r=this,i=new smart_db_interface_1.SmartDbSqlBuildData;return t&&lodash_1.default.keys(t).length>0&&(a||(a="AND",i.sql+=" WHERE "),i.sql+=lodash_1.default.map(t,(function(t,n){var l=n.toUpperCase();if("AND"==l||"OR"==l){var o="";return(lodash_1.default.isArray(t)?t:[t]).forEach((function(t,a){var n=r.buildWhere(e,t,l);a>0&&(o+=" "+l+" "),o+=n.sql,i.values=lodash_1.default.concat(i.values,n.values)})),o="("+o+")"}if("EXPRESSION"==l){var s=[];return lodash_1.default.forEach(t,(function(t){var a,n=r.prepareField(e,t.compare,i.values),l=r.prepareField(e,t.with,i.values);a=lodash_1.default.isString(t.operation)&&smart_db_interface_1.SqlOperationType[t.operation]?smart_db_interface_1.SqlOperationType[t.operation]:t.operation||smart_db_interface_1.SqlOperationType.EQ,s.push(n+" "+a+" "+l)})),s.join(" "+a+" ")}var u=!0,d=void 0;if(lodash_1.default.isArray(t)&&(t=smart_db_interface_1.IN(t)),lodash_1.default.isObject(t)){var f=t;switch(lodash_1.default.isString(f.operation)&&smart_db_interface_1.SqlOperationType[f.operation]&&(f.operation=smart_db_interface_1.SqlOperationType[f.operation]),f.operation){case smart_db_interface_1.SqlOperationType.IN:var p=new Array(f.value.length);p.fill("?"),d=smart_db_interface_1.SqlOperationType.IN+" ("+p.join(", ")+")",i.values=lodash_1.default.concat(i.values,f.value);break;case smart_db_interface_1.SqlOperationType.IS_NULL:case smart_db_interface_1.SqlOperationType.IS_NOT_NULL:d=f.operation;break;case smart_db_interface_1.SqlOperationType.LITERAL:n=f.key;var c=f.literalOperation||smart_db_interface_1.SqlOperationType.EQ;if(c==smart_db_interface_1.SqlOperationType.IN){var _=new Array(f.value.length);_.fill("?"),d=smart_db_interface_1.SqlOperationType.IN+" ("+_.join(", ")+")",i.values=lodash_1.default.concat(i.values,f.value)}else lodash_1.default.isUndefined(f.value)?d=c:(d=c+" ?",i.values.push(r.makeDbValue(f.value)));u=!1;break;default:d=f.operation+" ?",i.values.push(r.makeDbValue(f.value))}}else null===t?d=smart_db_interface_1.SqlOperationType.IS_NULL:void 0===t?(n="1",d="= 1",u=!1):(d=lodash_1.default.isString(t)&&t.match(/[%_]/)?smart_db_interface_1.SqlOperationType.LIKE+" ?":smart_db_interface_1.SqlOperationType.EQ+" ?",i.values.push(r.makeDbValue(t)));return u?r.translateFieldName(e,n)+" "+d:n+" "+d})).join(" "+a+" ")),i},e.prototype.buildDeleteStatement=function(e,t){var a=this.getTableName(e),r=new smart_db_interface_1.SmartDbSqlBuildData("DELETE FROM");return r.sql+=" "+a,t&&r.append(this.buildWhere(e,t)),this.lastBuildData=r,r},e.prototype.buildUpdateStatement=function(e,t,a){var r=this,i=this.getTableName(e),n=new smart_db_interface_1.SmartDbSqlBuildData("UPDATE");n.sql+=" "+i+" SET ";var l=[];return t instanceof abstract_model_1.AbstractModel&&(t=t.getPlainObject(abstract_model_1.FieldNamingStyle.Database)),lodash_1.default.forOwn(t,(function(t,a){l.push(r.translateFieldName(e,a)+" = ?"),n.values.push(r.makeDbValue(t))})),n.sql+=l.join(", "),a&&n.append(this.buildWhere(e,a)),this.lastBuildData=n,n},e.prototype.buildInsertStatement=function(e,t){var a=this,r=this.getTableName(e),i=new smart_db_interface_1.SmartDbSqlBuildData("INSERT");i.sql+=" INTO "+r;var n=[];t instanceof abstract_model_1.AbstractModel&&(t=t.getPlainObject(abstract_model_1.FieldNamingStyle.Database)),lodash_1.default.forOwn(t,(function(t,r){r=a.translateFieldName(e,r),n.push(r),i.values.push(a.makeDbValue(t))}));var l=new Array(n.length);return l.fill("?"),i.sql+=" ("+n.join(", ")+") VALUES ("+l.join(", ")+")",this.lastBuildData=i,i},e.prototype.prepareFieldValue=function(e,t){var a="<undefined>";switch(t.operation){case smart_db_interface_1.SqlFieldOperationType.FIELD:a=this.translateFieldName(e,t.value);break;case smart_db_interface_1.SqlFieldOperationType.VALUE:null===t.value?a="NULL":t.literal?a=t.value:lodash_1.default.isString(t.value)?!isNaN(parseFloat(t.value))&&isFinite(t.value)||(a="'"+t.value+"'"):lodash_1.default.isNumber(t.value)?a=t.value.toString():lodash_1.default.isBoolean(t.value)?a=t.value?"1":"0":lodash_1.default.isDate(t.value)?a="'"+t.value.toISOString().substr(0,23).replace("T"," ")+"'":console.error("unhandled field data type",typeof t.value,t.value);break;case smart_db_interface_1.SqlFieldOperationType.COUNT:a=lodash_1.default.isArray(t.value)?"COUNT("+t.value.join(",")+")":"COUNT("+(t.value||"")+")";break;case smart_db_interface_1.SqlFieldOperationType.COALESCE:var r=lodash_1.default.isArray(t.value)?t.value:[t.value];a="COALESCE("+this.buildFieldList(e,r).join(",")+")"}if(t.alias){var i=this.getDbQuote();a+=" as "+i+t.alias+i}return a},e.prototype.prepareField=function(e,t,a){var r;if(null===t)r="NULL";else if(lodash_1.default.isString(t)){var i=t.match(/^'(.*)'$/);i?a?(r="?",a.push(i[1])):r=t:r=this.translateFieldName(e,t)}else t.operation?r=this.prepareFieldValue(e,t):a?(r="?",a.push(t)):r=this.makeArgumentDbValue(t).toString();return r},e.prototype.buildFieldList=function(e,t){var a=this,r=[];return lodash_1.default.forEach(t,(function(t){r.push(a.prepareField(e,t))})),r},e.prototype.buildSelectSectionStatement=function(e,t){var a,r,i=this,n=this.getTableName(e);if(lodash_1.default.isArray(t.fields))a=t.fields;else if(lodash_1.default.isString(t.fields)){var l=t.fields.trim();a=""===l||"*"==l?[]:l.split(/,/)}else a=t.fields&&t.fields.operation?[t.fields]:[];a.length>0?r=this.buildFieldList(e,a).join(", "):r="*";t.distinct&&(r="DISTINCT "+r),t.count&&(r="COUNT("+r+")");var o=new smart_db_interface_1.SmartDbSqlBuildData("SELECT "+r+" FROM "+n);if(t.where&&o.append(this.buildWhere(e,t.where)),t.groupBy){o.sql+=" GROUP BY ";var s=lodash_1.default.isArray(t.groupBy)?t.groupBy:[t.groupBy];o.sql+=s.map((function(t){return i.translateFieldName(e,t)})).join(", ")}return o},e.prototype.translateFieldName=function(e,t){if(lodash_1.default.isString(e)){var a=e,r=!1;lodash_1.default.forEach(this.dictionaries,(function(t){return t.models&&t.models[a]&&(e=t.models[a].cls,r=!0),!r}))}if(!lodash_1.default.isString(e)){var i=e.attributeMap[t];if(i)i.alias&&(t=i.alias);else{var n=e.getTableName();this.lastError=new Error("unknown field '"+t+"' in table '"+n+"'"),this.smartDbLog.logError(smart_db_log_1.SmartDbLogType.Database,"translateFieldName",this.lastError)}}return t},e.prototype.makeDbValue=function(t){return lodash_1.default.isBoolean(t)?t=t?1:0:lodash_1.default.isDate(t)&&(t=e.toDbDate(t)),t},e.prototype.makeArgumentDbValue=function(t){return lodash_1.default.isBoolean(t)?t=t?1:0:lodash_1.default.isDate(t)?t="'"+e.toDbDate(t)+"'":lodash_1.default.isString(t)&&(t="'"+t+"'"),t},e.prototype.saveExecute=function(e){var t;try{t=e()}catch(e){this.lastError=e instanceof Error?e:new Error(e||"Unknown error"),this.smartDbLog.logFatal(smart_db_log_1.SmartDbLogType.Database,"saveExecute-catch",this.lastError),t=!1}return t},e.prototype.prepareResultRow=function(e,t,a){var r;if(a.indexedBy&&this.smartDbLog.logWarning(smart_db_log_1.SmartDbLogType.Database,"AbstractModel.get","option 'indexedBy' not supported without 'all'"),t)if(a.count)r=parseInt(lodash_1.default.values(t)[0],10);else if(a.collapseRow)r=lodash_1.default.values(t).join(",");else{r=e.from(t)}return r},e.prototype.prepareResultRows=function(e,t,a){var r;if(a.indexedBy||a.collapseRow||!lodash_1.default.isString(e)){var i=e;r=a.indexedBy?{}:new Array(t.length),lodash_1.default.forEach(t,(function(e,t){var n=i.from?i.from(e):null,l=null;if(a.indexedBy&&(l=n?n.getValue(a.indexedBy):e[a.indexedBy]),a.collapseRow){var o=lodash_1.default.values(e).join(",");l?r[l]=o:r[t]=o}else l?r[l]=n||e:r[t]=n||e}))}else r=t;return r},e.prototype.getTableName=function(e){var t;if(lodash_1.default.isString(e)){var a=e;lodash_1.default.forEach(this.dictionaries,(function(e){return e.models&&e.models[a]&&(t=e.models[a].cls.getTableName()),!t})),t||(t=a)}else{if(!e||!e.getTableName)throw new Error("unknown model: "+e);t=e.getTableName()}return t},e.DbDateRegexp=/^([0-9]{4}-[01][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9])(Z| GMT| GMT[-+][0-9]{1,2})?$/,e.DbTimestampRegexp=/^([0-9]{4}-[01][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]\.[0-9]{3})(Z| GMT| GMT[-+][0-9]{1,2})?$/,e}();exports.SmartDb=SmartDb;