pg-mvc-service 1.0.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 (56) hide show
  1. package/README.md +1 -0
  2. package/dist/PoolManager.js +57 -0
  3. package/dist/Service.js +257 -0
  4. package/dist/clients/AwsS3Client.js +249 -0
  5. package/dist/clients/Base64Client.js +153 -0
  6. package/dist/clients/EncryptClient.js +85 -0
  7. package/dist/clients/StringClient.js +13 -0
  8. package/dist/documents/Swagger.js +94 -0
  9. package/dist/exceptions/Exception.js +53 -0
  10. package/dist/index.js +16 -0
  11. package/dist/models/MigrateDatabase.js +138 -0
  12. package/dist/models/MigrateRollback.js +146 -0
  13. package/dist/models/MigrateTable.js +51 -0
  14. package/dist/models/SqlUtils/SelectExpression.js +92 -0
  15. package/dist/models/SqlUtils/ValidateValueUtil.js +250 -0
  16. package/dist/models/SqlUtils/WhereExpression.js +256 -0
  17. package/dist/models/TableDoc.js +353 -0
  18. package/dist/models/TableModel.js +636 -0
  19. package/dist/models/Type.js +2 -0
  20. package/dist/models/Utils/DateTimeUtil.js +134 -0
  21. package/dist/models/Utils/NumberUtil.js +28 -0
  22. package/dist/models/Utils/StringUtil.js +31 -0
  23. package/dist/models/ValidateClient.js +164 -0
  24. package/dist/models/index.js +14 -0
  25. package/dist/reqestResponse/ReqResType.js +196 -0
  26. package/dist/reqestResponse/RequestType.js +742 -0
  27. package/dist/reqestResponse/ResponseType.js +380 -0
  28. package/index.d.ts +306 -0
  29. package/package.json +36 -0
  30. package/src/PoolManager.ts +48 -0
  31. package/src/Service.ts +251 -0
  32. package/src/clients/AwsS3Client.ts +229 -0
  33. package/src/clients/Base64Client.ts +155 -0
  34. package/src/clients/EncryptClient.ts +100 -0
  35. package/src/clients/StringClient.ts +14 -0
  36. package/src/documents/Swagger.ts +111 -0
  37. package/src/exceptions/Exception.ts +54 -0
  38. package/src/index.ts +7 -0
  39. package/src/models/MigrateDatabase.ts +135 -0
  40. package/src/models/MigrateRollback.ts +151 -0
  41. package/src/models/MigrateTable.ts +56 -0
  42. package/src/models/SqlUtils/SelectExpression.ts +97 -0
  43. package/src/models/SqlUtils/ValidateValueUtil.ts +270 -0
  44. package/src/models/SqlUtils/WhereExpression.ts +286 -0
  45. package/src/models/TableDoc.ts +360 -0
  46. package/src/models/TableModel.ts +713 -0
  47. package/src/models/Type.ts +59 -0
  48. package/src/models/Utils/DateTimeUtil.ts +146 -0
  49. package/src/models/Utils/NumberUtil.ts +23 -0
  50. package/src/models/Utils/StringUtil.ts +33 -0
  51. package/src/models/ValidateClient.ts +182 -0
  52. package/src/models/index.ts +7 -0
  53. package/src/reqestResponse/ReqResType.ts +242 -0
  54. package/src/reqestResponse/RequestType.ts +851 -0
  55. package/src/reqestResponse/ResponseType.ts +418 -0
  56. package/tsconfig.json +14 -0
@@ -0,0 +1,636 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.TableModel = void 0;
16
+ const ValidateValueUtil_1 = __importDefault(require("./SqlUtils/ValidateValueUtil"));
17
+ const SelectExpression_1 = __importDefault(require("./SqlUtils/SelectExpression"));
18
+ const WhereExpression_1 = __importDefault(require("./SqlUtils/WhereExpression"));
19
+ const ValidateClient_1 = __importDefault(require("./ValidateClient"));
20
+ class TableModel {
21
+ get DbName() { return this.dbName; }
22
+ get TableName() {
23
+ if (this.tableName === "") {
24
+ throw new Error("Please set the tableName for TableModel.");
25
+ }
26
+ return this.tableName;
27
+ }
28
+ get TableDescription() { return this.tableDescription; }
29
+ get Comment() { return this.comment; }
30
+ get Columns() {
31
+ if (Object.keys(this.columns).length === 0) {
32
+ throw new Error("Please set the columns for TableModel.");
33
+ }
34
+ return this.columns;
35
+ }
36
+ getColumn(key) {
37
+ if (key in this.Columns === false) {
38
+ throw new Error(`${this.TableName} does not contain ${key}.`);
39
+ }
40
+ return Object.assign(Object.assign({}, this.Columns[key]), { columnName: key, tableName: this.TableName, expression: `"${this.TableAlias}".${key}` });
41
+ }
42
+ get References() { return this.references; }
43
+ GetReferences(columnName) {
44
+ const _ = this.getColumn(columnName); // 存在チェック用
45
+ const references = [];
46
+ for (const ref of this.References) {
47
+ if (ref.columns.filter(col => col.target === columnName).length > 0) {
48
+ references.push(ref);
49
+ }
50
+ }
51
+ return references;
52
+ }
53
+ get TableAlias() {
54
+ return this.tableAlias === undefined ? this.TableName : this.tableAlias;
55
+ }
56
+ get createSqlFromJoinWhere() {
57
+ let sql = ` FROM ${this.TableName} as "${this.TableAlias}"`;
58
+ for (const join of this.joinConditions) {
59
+ sql += join.type === 'left' ? ' LEFT OUTER JOIN' : ' INNER JOIN';
60
+ sql += ` ${join.model.TableName} as "${join.model.TableAlias}" ON `;
61
+ const query = WhereExpression_1.default.createCondition(join.conditions, this, this.vars.length + 1);
62
+ sql += query.sql;
63
+ if (query.vars !== undefined) {
64
+ this.vars = [...this.vars, ...query.vars];
65
+ }
66
+ }
67
+ if (this.whereExpressions.length > 0) {
68
+ sql += " WHERE " + this.whereExpressions.join(" AND ");
69
+ }
70
+ if (this.groupExpression.length > 0) {
71
+ sql += ` GROUP BY ${this.groupExpression.join(',')}`;
72
+ }
73
+ return sql;
74
+ }
75
+ get createSqlFromJoinWhereSortLimit() {
76
+ let sql = this.createSqlFromJoinWhere;
77
+ if (this.sortExpression.length > 0) {
78
+ sql += ` ORDER BY ${this.sortExpression.join(",")}`;
79
+ }
80
+ if (this.Limit !== undefined) {
81
+ sql += ` LIMIT ${this.Limit}`;
82
+ }
83
+ if (this.Offset !== undefined) {
84
+ sql += ` OFFSET ${this.Offset}`;
85
+ }
86
+ return sql;
87
+ }
88
+ set OffsetPage(value) {
89
+ if (value > 0) {
90
+ this.Limit = this.PageCount;
91
+ this.Offset = (value - 1) * this.PageCount;
92
+ }
93
+ }
94
+ constructor(client, tableAlias) {
95
+ this.dbName = "default";
96
+ this.tableName = "";
97
+ this.tableDescription = "";
98
+ this.comment = "";
99
+ this.columns = {};
100
+ this.references = [];
101
+ this.IsOutputLog = false;
102
+ this.SortKeyword = 'asc';
103
+ this.PageCount = 10;
104
+ this.selectExpressions = [];
105
+ this.joinConditions = [];
106
+ this.whereExpressions = [];
107
+ this.groupExpression = [];
108
+ this.sortExpression = [];
109
+ this.vars = [];
110
+ this.errorMessages = {
111
+ 'string': '{name} should be entered as a string or number type.',
112
+ 'string[]': '{name} should be entered as an array of string or number types.',
113
+ 'uuid': '{name} should be entered as a UUID.',
114
+ 'uuid[]': '{name} should be entered as an array of UUIDs.',
115
+ 'number': '{name} should be entered as a number.',
116
+ 'number[]': '{name} should be entered as an array of numbers.',
117
+ 'bool': '{name} should be entered as a bool type, "true", "false", 0, or 1.',
118
+ 'bool[]': '{name} should be entered as an array of bool types, "true", "false", 0, or 1.',
119
+ 'date': '{name} should be entered in "YYYY-MM-DD" or "YYYY-MM-DD hh:mi:ss" format or as a Date type.',
120
+ 'date[]': '{name} should be entered as an array of dates in "YYYY-MM-DD" or "YYYY-MM-DD hh:mi:ss" format or as Date types.',
121
+ 'time': '{name} should be entered in "hh:mi" format or "hh:mi:ss" format.',
122
+ 'time[]': '{name} should be entered as an array of times in "hh:mi" format or "hh:mi:ss" format.',
123
+ 'timestamp': '{name} should be entered in "YYYY-MM-DD" format, "YYYY-MM-DD hh:mi:ss" format, "YYYY-MM-DDThh:mi:ss" format, or as a Date type.',
124
+ 'timestamp[]': '{name} should be entered as an array of timestamps in "YYYY-MM-DD" format, "YYYY-MM-DD hh:mi:ss" format, "YYYY-MM-DDThh:mi:ss" format, or as Date types.',
125
+ 'length': '{name} should be entered within {length} characters.',
126
+ 'null': '{name} is not allowed to be null.',
127
+ 'notInput': 'Please enter {name}.',
128
+ 'fk': 'The value of {name} does not exist in the table.',
129
+ 'idNotExist': 'The specified ID({id}) does not exist in the table.',
130
+ };
131
+ this.client = client;
132
+ if (tableAlias !== undefined && tableAlias.trim() !== '') {
133
+ this.tableAlias = tableAlias;
134
+ }
135
+ }
136
+ findId(id_1) {
137
+ return __awaiter(this, arguments, void 0, function* (id, selectColumns = "*", selectExpressions = null, keyFormat = 'snake') {
138
+ ValidateValueUtil_1.default.validateId(this.Columns, id);
139
+ let selects = [];
140
+ if (selectColumns == "*") {
141
+ for (const key of Object.keys(this.Columns)) {
142
+ selects.push(SelectExpression_1.default.create({ model: this, name: key }, null, null, keyFormat));
143
+ }
144
+ }
145
+ else if (selectColumns != null) {
146
+ for (const key of selectColumns) {
147
+ selects.push(SelectExpression_1.default.create({ model: this, name: key }, null, null, keyFormat));
148
+ }
149
+ }
150
+ if (selectExpressions != null) {
151
+ for (const expression of selectExpressions) {
152
+ selects.push(`${expression.expression} as "${expression.alias}"`);
153
+ }
154
+ }
155
+ const sql = `SELECT ${selects.join(',')} FROM ${this.TableName} WHERE id = $1`;
156
+ let datas = yield this.executeQuery(sql, [id]);
157
+ return datas.rowCount == 0 ? null : datas.rows[0];
158
+ });
159
+ }
160
+ find(pk_1) {
161
+ return __awaiter(this, arguments, void 0, function* (pk, selectColumns = "*", selectExpressions = null, keyFormat = 'snake') {
162
+ let selects = [];
163
+ if (selectColumns == "*") {
164
+ for (const key of Object.keys(this.Columns)) {
165
+ selects.push(SelectExpression_1.default.create({ model: this, name: key }, null, null, keyFormat));
166
+ }
167
+ }
168
+ else if (selectColumns != null) {
169
+ for (const key of selectColumns) {
170
+ selects.push(SelectExpression_1.default.create({ model: this, name: key }, null, null, keyFormat));
171
+ }
172
+ }
173
+ if (selectExpressions != null) {
174
+ for (const expression of selectExpressions) {
175
+ selects.push(`${expression.expression} as "${expression.alias}"`);
176
+ }
177
+ }
178
+ const conditions = [];
179
+ const vars = [];
180
+ for (const [keyColumn, column] of Object.entries(this.Columns)) {
181
+ if (column.attribute !== 'primary') {
182
+ continue;
183
+ }
184
+ if (pk[keyColumn] === undefined || pk[keyColumn] === null) {
185
+ throw new Error(`No value is set for the primary key "${this.TableName}".${keyColumn}. Please set it in the first argument.`);
186
+ }
187
+ ValidateValueUtil_1.default.validateValue(column, pk[keyColumn]);
188
+ vars.push(pk[keyColumn]);
189
+ conditions.push(`${keyColumn} = $${vars.length}`);
190
+ }
191
+ const sql = `SELECT ${selects.join(',')} FROM ${this.TableName} WHERE ${conditions.join(' AND ')}`;
192
+ let datas = yield this.executeQuery(sql, vars);
193
+ return datas.rowCount == 0 ? null : datas.rows[0];
194
+ });
195
+ }
196
+ select(param1 = "*", param2, param3) {
197
+ var _a, _b;
198
+ if (param1 === "*") {
199
+ let model = this;
200
+ let keyFormat = 'snake';
201
+ if (param2 instanceof TableModel) {
202
+ model = param2;
203
+ if (param3 === 'snake' || param3 === 'lowerCamel') {
204
+ keyFormat = param3;
205
+ }
206
+ }
207
+ else if (param2 === 'snake' || param2 === 'lowerCamel') {
208
+ keyFormat = param2;
209
+ }
210
+ for (const key of Object.keys(model.Columns)) {
211
+ this.selectExpressions.push(SelectExpression_1.default.create({ model: model, name: key }, null, null, keyFormat));
212
+ }
213
+ return;
214
+ }
215
+ if (Array.isArray(param1)) {
216
+ let model = this;
217
+ let keyFormat = 'snake';
218
+ if (param2 instanceof TableModel) {
219
+ model = param2;
220
+ if (param3 === 'snake' || param3 === 'lowerCamel') {
221
+ keyFormat = param3;
222
+ }
223
+ }
224
+ else if (param2 === 'snake' || param2 === 'lowerCamel') {
225
+ keyFormat = param2;
226
+ }
227
+ for (const key of param1) {
228
+ if (typeof key === 'string') {
229
+ this.selectExpressions.push(SelectExpression_1.default.create({ model: model, name: key }, null, null, keyFormat));
230
+ }
231
+ else {
232
+ this.selectExpressions.push(SelectExpression_1.default.create({ model: model, name: key.name }, (_a = key.func) !== null && _a !== void 0 ? _a : null, (_b = key.alias) !== null && _b !== void 0 ? _b : null, keyFormat));
233
+ }
234
+ }
235
+ return;
236
+ }
237
+ if (typeof param1 === 'string') {
238
+ const expression = param1;
239
+ if (typeof param2 !== 'string' || param2.trim() === '') {
240
+ throw new Error('If the first argument is a string, the second argument must be a non-empty string.');
241
+ }
242
+ const alias = param2;
243
+ this.selectExpressions.push(`(${expression}) as "${alias}"`);
244
+ return;
245
+ }
246
+ }
247
+ /**
248
+ * 指定された条件に基づいてテーブルを結合します。
249
+ * @param joinType 結合の種類を指定します
250
+ * @param joinBaseModel 結合する対象のBaseModelインスタンスを指定します。
251
+ * @param conditions 結合条件を指定します。条件はオブジェクトまたは文字列で指定できます。
252
+ */
253
+ join(joinType, joinModel, conditions) {
254
+ this.joinConditions.push({ type: joinType, model: joinModel, conditions: conditions });
255
+ }
256
+ where(left, operator, right) {
257
+ if (typeof left === 'string') {
258
+ if (operator === undefined || right === undefined) {
259
+ this.whereExpressions.push(left);
260
+ }
261
+ else {
262
+ const query = WhereExpression_1.default.create({ model: this, name: left }, operator, right, this.vars.length + 1);
263
+ this.whereExpressions.push(query.sql);
264
+ if (query.vars !== undefined) {
265
+ this.vars = [...this.vars, ...query.vars];
266
+ }
267
+ }
268
+ return;
269
+ }
270
+ if ('model' in left && 'name' in left) {
271
+ if (operator === undefined || right === undefined) {
272
+ throw new Error(`If left is TColumnInfo, please set operator and right.`);
273
+ }
274
+ else {
275
+ const query = WhereExpression_1.default.create(left, operator, right, this.vars.length + 1);
276
+ this.whereExpressions.push(query.sql);
277
+ if (query.vars !== undefined) {
278
+ this.vars = [...this.vars, ...query.vars];
279
+ }
280
+ }
281
+ return;
282
+ }
283
+ if (Array.isArray(left)) {
284
+ const query = WhereExpression_1.default.createCondition(left, this, this.vars.length + 1);
285
+ this.whereExpressions.push(query.sql);
286
+ if (query.vars !== undefined) {
287
+ this.vars = [...this.vars, ...query.vars];
288
+ }
289
+ }
290
+ }
291
+ groupBy(column) {
292
+ if (typeof column === 'string') {
293
+ column = { model: this, name: column };
294
+ }
295
+ this.groupExpression.push(column.model.getColumn(column.name).expression);
296
+ }
297
+ orderBy(column, sortKeyword) {
298
+ if (typeof column === 'string') {
299
+ column = { model: this, name: column };
300
+ }
301
+ this.sortExpression.push(`${column.model.getColumn(column.name).expression} ${sortKeyword}`);
302
+ }
303
+ orderByList(column, list, sortKeyword) {
304
+ if (list.length === 0) {
305
+ return;
306
+ }
307
+ if (typeof (column) == 'string') {
308
+ column = { model: this, name: column };
309
+ ;
310
+ }
311
+ const columnInfo = column.model.getColumn(column.name);
312
+ const orderConditions = [];
313
+ for (let i = 0; i < list.length; i++) {
314
+ const value = list[i];
315
+ if (value === null) {
316
+ if (columnInfo.attribute === 'nullable') {
317
+ orderConditions.push(`WHEN ${columnInfo.expression} is null THEN ${i}`);
318
+ continue;
319
+ }
320
+ throw new Error(`${this.TableName}.${columnInfo.columnName} is a non-nullable column.`);
321
+ }
322
+ ValidateValueUtil_1.default.validateValue(columnInfo, value);
323
+ switch (columnInfo.type) {
324
+ case 'number':
325
+ orderConditions.push(`WHEN ${columnInfo.expression} = ${value} THEN ${i}`);
326
+ break;
327
+ case 'uuid':
328
+ case 'string':
329
+ orderConditions.push(`WHEN ${columnInfo.expression} = '${value}' THEN ${i}`);
330
+ break;
331
+ case 'bool':
332
+ const boolValue = value === true || value === 'true' || value === 1;
333
+ orderConditions.push(`WHEN ${columnInfo.expression} = ${boolValue} THEN ${i}`);
334
+ break;
335
+ }
336
+ }
337
+ if (orderConditions.length === 0) {
338
+ return;
339
+ }
340
+ this.sortExpression.push(`CASE ${orderConditions.join(' ')} ELSE ${list.length} END ${sortKeyword}`);
341
+ }
342
+ orderBySentence(query, sortKeyword) {
343
+ this.sortExpression.push(`${query} ${sortKeyword}`);
344
+ }
345
+ executeSelect() {
346
+ return __awaiter(this, void 0, void 0, function* () {
347
+ if (this.selectExpressions.length === 0) {
348
+ this.select();
349
+ }
350
+ let sql = ` SELECT ${this.selectExpressions.join(",")} ${this.createSqlFromJoinWhereSortLimit}`;
351
+ let data = yield this.executeQuery(sql, this.vars);
352
+ return data.rows;
353
+ });
354
+ }
355
+ executeSelectWithCount() {
356
+ return __awaiter(this, void 0, void 0, function* () {
357
+ if (this.selectExpressions.length == 0) {
358
+ this.select();
359
+ }
360
+ let sql = ` SELECT ${this.selectExpressions.join(",")} ${this.createSqlFromJoinWhereSortLimit}`;
361
+ let countSql = ` SELECT COUNT(*) as "count" ${this.createSqlFromJoinWhere}`;
362
+ let tempVars = [...this.vars];
363
+ const data = yield this.executeQuery(sql, tempVars);
364
+ const countData = yield this.executeQuery(countSql, tempVars);
365
+ return { datas: data.rows, count: Number(countData.rows[0].count), lastPage: Math.ceil(Number(countData.rows[0].count) / this.PageCount) };
366
+ });
367
+ }
368
+ throwValidationError(code, message) {
369
+ throw new Error(message);
370
+ }
371
+ validateOptions(options, isInsert) {
372
+ return __awaiter(this, void 0, void 0, function* () {
373
+ if (Object.keys(options).length === 0) {
374
+ throw new Error('At least one key-value pair is required in options.');
375
+ }
376
+ for (const [key, value] of Object.entries(options)) {
377
+ const column = this.getColumn(key);
378
+ if (isInsert === false && column.attribute === 'primary') {
379
+ throw new Error(`${this.TableName}.${key} cannot be modified because it is a primary key.`);
380
+ }
381
+ const name = (column.alias === undefined || column.alias === '') ? key : column.alias;
382
+ if (value === null) {
383
+ if (column.attribute === 'nullable') {
384
+ continue;
385
+ }
386
+ this.throwValidationError("001", this.errorMessages.null.replace('{name}', name));
387
+ }
388
+ if (ValidateValueUtil_1.default.isErrorValue(column.type, value)) {
389
+ this.throwValidationError("002", this.errorMessages[column.type].replace('{name}', name));
390
+ }
391
+ if (column.type === 'string') {
392
+ if (Number.isInteger(column.length) === false) {
393
+ throw new Error(`For strings, please specify the length of the column.(column: ${column.columnName})`);
394
+ }
395
+ if (value.toString().length > column.length) {
396
+ this.throwValidationError("003", this.errorMessages.length.replace('{name}', name).replace('{length}', column.toString()));
397
+ }
398
+ }
399
+ else if (column.type === 'string[]') {
400
+ if (Number.isInteger(column.length) === false) {
401
+ throw new Error(`For strings, please specify the length of the column.(column: ${column.columnName})`);
402
+ }
403
+ // ValidateValueUtil.isErrorValue(column.type, value)で型チェックしてるのでas []にしている
404
+ for (const v of value) {
405
+ if (v.toString().length > column.length) {
406
+ this.throwValidationError("004", this.errorMessages.length.replace('{name}', name).replace('{length}', column.length.toString()));
407
+ }
408
+ }
409
+ }
410
+ }
411
+ // 外部キー制約チェック
412
+ if (isInsert) {
413
+ for (const ref of this.References) {
414
+ const refValues = ref.columns.map(col => options[col.target]);
415
+ // 全ての値がnullの場合はスキップ
416
+ if (refValues.every(value => value === null || value === undefined)) {
417
+ continue;
418
+ }
419
+ // 一部の値がnullの場合はエラー
420
+ if (refValues.some(value => value === null || value === undefined)) {
421
+ const name = ref.columns.map(col => { var _a; return (_a = this.getColumn(col.target).alias) !== null && _a !== void 0 ? _a : this.getColumn(col.target).columnName; }).join(',');
422
+ this.throwValidationError("004", this.errorMessages.fk.replace('{name}', name));
423
+ }
424
+ let refIndex = 1;
425
+ const sql = `SELECT COUNT(*) as count FROM ${ref.table} WHERE ${ref.columns.map(col => `${col.ref} = $${refIndex++}`)}`;
426
+ const datas = yield this.clientQuery(sql, refValues);
427
+ if (datas.rows[0].count == "0") {
428
+ const name = ref.columns.map(col => { var _a; return (_a = this.getColumn(col.target).alias) !== null && _a !== void 0 ? _a : this.getColumn(col.target).columnName; }).join(',');
429
+ this.throwValidationError("004", this.errorMessages.fk.replace('{name}', name));
430
+ }
431
+ }
432
+ }
433
+ });
434
+ }
435
+ validateInsert(options) {
436
+ return __awaiter(this, void 0, void 0, function* () {
437
+ for (const key in this.Columns) {
438
+ const column = this.getColumn(key);
439
+ const name = (column.alias === undefined || column.alias === '') ? key : column.alias;
440
+ if (options[key] === undefined || options[key] === null) {
441
+ // Null許容されていないカラムにNULLを入れようとしているか?
442
+ if (column.attribute === "primary" || column.attribute === "noDefault") {
443
+ this.throwValidationError("101", this.errorMessages.notInput.replace('{name}', name));
444
+ }
445
+ }
446
+ }
447
+ });
448
+ }
449
+ validateUpdate(options) {
450
+ return __awaiter(this, void 0, void 0, function* () { });
451
+ }
452
+ validateUpdateId(id, options) {
453
+ return __awaiter(this, void 0, void 0, function* () { });
454
+ }
455
+ validateDelete() {
456
+ return __awaiter(this, void 0, void 0, function* () { });
457
+ }
458
+ validateDeleteId(id) {
459
+ return __awaiter(this, void 0, void 0, function* () { });
460
+ }
461
+ executeInsert(options) {
462
+ return __awaiter(this, void 0, void 0, function* () {
463
+ yield this.validateOptions(options, true);
464
+ yield this.validateInsert(options);
465
+ const columns = [];
466
+ const vars = [];
467
+ for (const [key, value] of Object.entries(options)) {
468
+ if (value === undefined) {
469
+ throw new Error(`The insert option ${key} is undefined.`);
470
+ }
471
+ columns.push(key);
472
+ vars.push(value);
473
+ }
474
+ const params = vars.map((_, index) => `$${index + 1}`);
475
+ const sql = `INSERT INTO ${this.TableName} (${columns.join(",")}) VALUES (${params.join(",")});`;
476
+ yield this.executeQuery(sql, vars);
477
+ });
478
+ }
479
+ executeUpdate(options) {
480
+ return __awaiter(this, void 0, void 0, function* () {
481
+ yield this.validateOptions(options, false);
482
+ yield this.validateUpdate(options);
483
+ const updateExpressions = [];
484
+ for (const [key, value] of Object.entries(options)) {
485
+ const column = this.getColumn(key);
486
+ ValidateValueUtil_1.default.validateValue(column, value);
487
+ this.vars.push(value);
488
+ updateExpressions.push(`${key} = $${this.vars.length}`);
489
+ }
490
+ let sql = `UPDATE ${this.TableName} "${this.TableAlias}" SET ${updateExpressions.join(',')} `;
491
+ if (this.joinConditions.length > 0) {
492
+ const tables = [];
493
+ for (const join of this.joinConditions) {
494
+ tables.push(`${join.model.TableName} as "${join.model.TableAlias}"`);
495
+ const query = WhereExpression_1.default.createCondition(join.conditions, this, this.vars.length);
496
+ this.whereExpressions.push(query.sql);
497
+ if (query.vars !== undefined) {
498
+ this.vars = [...this.vars, ...query.vars];
499
+ }
500
+ }
501
+ sql += `FROM ${tables.join(',')} `;
502
+ }
503
+ if (this.whereExpressions.length > 0) {
504
+ sql += "WHERE " + this.whereExpressions.join(" AND ");
505
+ }
506
+ const data = yield this.executeQuery(sql, this.vars);
507
+ return data.rowCount;
508
+ });
509
+ }
510
+ executeUpdateId(id, options) {
511
+ return __awaiter(this, void 0, void 0, function* () {
512
+ ValidateValueUtil_1.default.validateId(this.Columns, id);
513
+ yield this.validateOptions(options, false);
514
+ yield this.validateUpdateId(id, options);
515
+ yield this.validateUpdate(options);
516
+ const updateExpressions = [];
517
+ const vars = [];
518
+ for (const [key, value] of Object.entries(options)) {
519
+ if (value === undefined) {
520
+ throw new Error(`The update option ${key} is undefined.`);
521
+ }
522
+ const column = this.getColumn(key);
523
+ if (column.attribute === 'primary') {
524
+ throw new Error(`The primary key ${this.TableName}.${key} cannot be changed.`);
525
+ }
526
+ vars.push(value);
527
+ updateExpressions.push(`${key} = $${vars.length}`);
528
+ }
529
+ vars.push(id);
530
+ const sql = `UPDATE ${this.TableName} SET ${updateExpressions.join(',')} WHERE id = $${vars.length}`;
531
+ const data = yield this.executeQuery(sql, vars);
532
+ if (data.rowCount !== 1) {
533
+ this.throwValidationError("201", this.errorMessages.idNotExist.replace('{id}', id));
534
+ }
535
+ });
536
+ }
537
+ executeDelete() {
538
+ return __awaiter(this, void 0, void 0, function* () {
539
+ this.validateDelete();
540
+ let sql = `DELETE FROM ${this.TableName} "${this.TableAlias}" `;
541
+ if (this.joinConditions.length > 0) {
542
+ const tables = [];
543
+ for (const join of this.joinConditions) {
544
+ tables.push(`${join.model.TableName} as "${join.model.TableAlias}"`);
545
+ const query = WhereExpression_1.default.createCondition(join.conditions, this, this.vars.length);
546
+ this.whereExpressions.push(query.sql);
547
+ if (query.vars !== undefined) {
548
+ this.vars = [...this.vars, ...query.vars];
549
+ }
550
+ sql += ` USING ${tables.join(',')} `;
551
+ }
552
+ }
553
+ if (this.whereExpressions.length > 0) {
554
+ sql += "WHERE " + this.whereExpressions.join(" AND ");
555
+ }
556
+ const datas = yield this.executeQuery(sql, this.vars);
557
+ return datas.rowCount;
558
+ });
559
+ }
560
+ executeDeleteId(id) {
561
+ return __awaiter(this, void 0, void 0, function* () {
562
+ ValidateValueUtil_1.default.validateId(this.Columns, id);
563
+ yield this.validateDeleteId(id);
564
+ let sql = `DELETE FROM ${this.TableName} WHERE id = $1`;
565
+ const datas = yield this.executeQuery(sql, [id]);
566
+ if (datas.rowCount !== 1) {
567
+ this.throwValidationError("301", this.errorMessages.idNotExist.replace('{id}', id));
568
+ }
569
+ });
570
+ }
571
+ executeQuery(param1, vars) {
572
+ return __awaiter(this, void 0, void 0, function* () {
573
+ // 初期化項目
574
+ this.selectExpressions = [];
575
+ this.whereExpressions = [];
576
+ this.joinConditions = [];
577
+ this.sortExpression = [];
578
+ this.SortKeyword = 'asc';
579
+ this.groupExpression = [];
580
+ this.vars = [];
581
+ this.Offset = undefined;
582
+ this.Limit = undefined;
583
+ this.PageCount = 10;
584
+ let sql = '';
585
+ if (typeof param1 === 'string') {
586
+ sql = param1;
587
+ }
588
+ else {
589
+ sql = param1.sql;
590
+ vars = param1.vars;
591
+ }
592
+ return yield this.clientQuery(sql, vars);
593
+ });
594
+ }
595
+ clientQuery(sql, vars) {
596
+ return __awaiter(this, void 0, void 0, function* () {
597
+ if (this.IsOutputLog) {
598
+ console.log("--- Debug Sql ----------");
599
+ console.log(sql);
600
+ console.log(vars);
601
+ }
602
+ const data = yield this.client.query(sql, vars !== null && vars !== void 0 ? vars : []);
603
+ if (this.IsOutputLog) {
604
+ console.log("- 実行結果");
605
+ if (data.rowCount == 0) {
606
+ console.log("データなし");
607
+ }
608
+ else {
609
+ let log = "";
610
+ for (let i = 0; i < data.fields.length; i++) {
611
+ log += i == 0 ? "" : ",";
612
+ log += data.fields[i].name;
613
+ }
614
+ console.log(log);
615
+ for (let i = 0; i < data.rows.length; i++) {
616
+ log = "";
617
+ for (let j = 0; j < data.fields.length; j++) {
618
+ let key = data.fields[j].name;
619
+ log += j == 0 ? "" : ",";
620
+ log += data.rows[i][key];
621
+ }
622
+ console.log(log);
623
+ }
624
+ }
625
+ }
626
+ return data;
627
+ });
628
+ }
629
+ get ValidateClient() {
630
+ if (this.validateClient === undefined) {
631
+ this.validateClient = new ValidateClient_1.default(this);
632
+ }
633
+ return this.validateClient;
634
+ }
635
+ }
636
+ exports.TableModel = TableModel;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });