typesql-cli 0.9.6 → 0.10.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 (110) hide show
  1. package/README.md +2 -3
  2. package/cli.js +87 -78
  3. package/cli.js.map +1 -1
  4. package/code-generator.d.ts +7 -7
  5. package/code-generator.d.ts.map +1 -1
  6. package/code-generator.js +257 -193
  7. package/code-generator.js.map +1 -1
  8. package/describe-dynamic-query.d.ts +1 -1
  9. package/describe-dynamic-query.d.ts.map +1 -1
  10. package/describe-dynamic-query.js +51 -39
  11. package/describe-dynamic-query.js.map +1 -1
  12. package/describe-nested-query.d.ts +2 -2
  13. package/describe-nested-query.d.ts.map +1 -1
  14. package/describe-nested-query.js +43 -24
  15. package/describe-nested-query.js.map +1 -1
  16. package/describe-query.d.ts +4 -4
  17. package/describe-query.d.ts.map +1 -1
  18. package/describe-query.js +29 -21
  19. package/describe-query.js.map +1 -1
  20. package/drivers/libsql.d.ts +2 -2
  21. package/drivers/libsql.d.ts.map +1 -1
  22. package/drivers/libsql.js +3 -3
  23. package/drivers/libsql.js.map +1 -1
  24. package/mysql-mapping.d.ts +1 -1
  25. package/mysql-mapping.d.ts.map +1 -1
  26. package/mysql-mapping.js +9 -9
  27. package/mysql-mapping.js.map +1 -1
  28. package/mysql-query-analyzer/collect-constraints.d.ts +4 -4
  29. package/mysql-query-analyzer/collect-constraints.d.ts.map +1 -1
  30. package/mysql-query-analyzer/collect-constraints.js +21 -16
  31. package/mysql-query-analyzer/collect-constraints.js.map +1 -1
  32. package/mysql-query-analyzer/infer-column-nullability.d.ts +2 -2
  33. package/mysql-query-analyzer/infer-column-nullability.d.ts.map +1 -1
  34. package/mysql-query-analyzer/infer-column-nullability.js +81 -67
  35. package/mysql-query-analyzer/infer-column-nullability.js.map +1 -1
  36. package/mysql-query-analyzer/infer-param-nullability.d.ts +2 -2
  37. package/mysql-query-analyzer/infer-param-nullability.d.ts.map +1 -1
  38. package/mysql-query-analyzer/infer-param-nullability.js +11 -10
  39. package/mysql-query-analyzer/infer-param-nullability.js.map +1 -1
  40. package/mysql-query-analyzer/parse.d.ts +2 -2
  41. package/mysql-query-analyzer/parse.d.ts.map +1 -1
  42. package/mysql-query-analyzer/parse.js +39 -32
  43. package/mysql-query-analyzer/parse.js.map +1 -1
  44. package/mysql-query-analyzer/select-columns.d.ts +4 -4
  45. package/mysql-query-analyzer/select-columns.d.ts.map +1 -1
  46. package/mysql-query-analyzer/select-columns.js +76 -53
  47. package/mysql-query-analyzer/select-columns.js.map +1 -1
  48. package/mysql-query-analyzer/traverse.d.ts +4 -4
  49. package/mysql-query-analyzer/traverse.d.ts.map +1 -1
  50. package/mysql-query-analyzer/traverse.js +312 -206
  51. package/mysql-query-analyzer/traverse.js.map +1 -1
  52. package/mysql-query-analyzer/types.d.ts +5 -5
  53. package/mysql-query-analyzer/types.d.ts.map +1 -1
  54. package/mysql-query-analyzer/unify.d.ts +2 -2
  55. package/mysql-query-analyzer/unify.d.ts.map +1 -1
  56. package/mysql-query-analyzer/unify.js +533 -491
  57. package/mysql-query-analyzer/unify.js.map +1 -1
  58. package/mysql-query-analyzer/util.d.ts.map +1 -1
  59. package/mysql-query-analyzer/util.js +2 -3
  60. package/mysql-query-analyzer/util.js.map +1 -1
  61. package/mysql-query-analyzer/verify-multiple-result.d.ts +2 -2
  62. package/mysql-query-analyzer/verify-multiple-result.d.ts.map +1 -1
  63. package/mysql-query-analyzer/verify-multiple-result.js +12 -8
  64. package/mysql-query-analyzer/verify-multiple-result.js.map +1 -1
  65. package/package.json +46 -45
  66. package/queryExectutor.d.ts +4 -4
  67. package/queryExectutor.d.ts.map +1 -1
  68. package/queryExectutor.js +11 -13
  69. package/queryExectutor.js.map +1 -1
  70. package/sql-generator.d.ts +2 -2
  71. package/sql-generator.d.ts.map +1 -1
  72. package/sql-generator.js +29 -25
  73. package/sql-generator.js.map +1 -1
  74. package/sqlite-query-analyzer/code-generator.d.ts +5 -5
  75. package/sqlite-query-analyzer/code-generator.d.ts.map +1 -1
  76. package/sqlite-query-analyzer/code-generator.js +372 -221
  77. package/sqlite-query-analyzer/code-generator.js.map +1 -1
  78. package/sqlite-query-analyzer/parser.d.ts +4 -4
  79. package/sqlite-query-analyzer/parser.d.ts.map +1 -1
  80. package/sqlite-query-analyzer/parser.js +30 -17
  81. package/sqlite-query-analyzer/parser.js.map +1 -1
  82. package/sqlite-query-analyzer/query-executor.d.ts +5 -5
  83. package/sqlite-query-analyzer/query-executor.d.ts.map +1 -1
  84. package/sqlite-query-analyzer/query-executor.js +39 -25
  85. package/sqlite-query-analyzer/query-executor.js.map +1 -1
  86. package/sqlite-query-analyzer/replace-list-params.d.ts +1 -1
  87. package/sqlite-query-analyzer/replace-list-params.d.ts.map +1 -1
  88. package/sqlite-query-analyzer/replace-list-params.js +4 -3
  89. package/sqlite-query-analyzer/replace-list-params.js.map +1 -1
  90. package/sqlite-query-analyzer/sqlite-describe-nested-query.d.ts +4 -4
  91. package/sqlite-query-analyzer/sqlite-describe-nested-query.d.ts.map +1 -1
  92. package/sqlite-query-analyzer/sqlite-describe-nested-query.js +33 -18
  93. package/sqlite-query-analyzer/sqlite-describe-nested-query.js.map +1 -1
  94. package/sqlite-query-analyzer/traverse.d.ts +5 -5
  95. package/sqlite-query-analyzer/traverse.d.ts.map +1 -1
  96. package/sqlite-query-analyzer/traverse.js +249 -160
  97. package/sqlite-query-analyzer/traverse.js.map +1 -1
  98. package/ts-dynamic-query-descriptor.d.ts +1 -1
  99. package/ts-dynamic-query-descriptor.d.ts.map +1 -1
  100. package/ts-dynamic-query-descriptor.js +4 -4
  101. package/ts-dynamic-query-descriptor.js.map +1 -1
  102. package/ts-nested-descriptor.d.ts +4 -4
  103. package/ts-nested-descriptor.d.ts.map +1 -1
  104. package/ts-nested-descriptor.js +11 -11
  105. package/ts-nested-descriptor.js.map +1 -1
  106. package/types.d.ts +13 -14
  107. package/types.d.ts.map +1 -1
  108. package/util.d.ts.map +1 -1
  109. package/util.js.map +1 -1
  110. package/utility-types.d.ts.map +1 -1
package/code-generator.js CHANGED
@@ -36,8 +36,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  };
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
38
  exports.generateTsFileFromContent = exports.generateTsFile = exports.convertToCamelCaseName = exports.capitalize = exports.writeFile = exports.replaceOrderByParam = exports.hasDateColumn = exports.hasStringColumn = exports.escapeInvalidTsField = exports.renameInvalidNames = exports.removeDuplicatedParameters2 = exports.removeDuplicatedParameters = exports.generateTsDescriptor = exports.writeTypeBlock = exports.generateRelationType = exports.getOperator = exports.generateTsCodeForMySQL = void 0;
39
- const fs_1 = __importDefault(require("fs"));
40
- const path_1 = __importStar(require("path"));
39
+ const node_fs_1 = __importDefault(require("node:fs"));
40
+ const node_path_1 = __importStar(require("node:path"));
41
41
  const camelcase_1 = __importDefault(require("camelcase"));
42
42
  const Either_1 = require("fp-ts/lib/Either");
43
43
  const mysql_mapping_1 = require("./mysql-mapping");
@@ -45,37 +45,38 @@ const describe_query_1 = require("./describe-query");
45
45
  const code_block_writer_1 = __importDefault(require("code-block-writer"));
46
46
  const ts_nested_descriptor_1 = require("./ts-nested-descriptor");
47
47
  const ts_dynamic_query_descriptor_1 = require("./ts-dynamic-query-descriptor");
48
- const os_1 = require("os");
48
+ const node_os_1 = require("node:os");
49
49
  const code_generator_1 = require("./sqlite-query-analyzer/code-generator");
50
- function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
50
+ function generateTsCodeForMySQL(tsDescriptor, fileName, crud = false) {
51
51
  var _a;
52
52
  const writer = new code_block_writer_1.default();
53
53
  const camelCaseName = convertToCamelCaseName(fileName);
54
54
  const capitalizedName = capitalize(camelCaseName);
55
- const dataTypeName = capitalizedName + 'Data';
56
- const paramsTypeName = capitalizedName + 'Params';
57
- const resultTypeName = capitalizedName + 'Result';
58
- const dynamicParamsTypeName = capitalizedName + 'DynamicParams';
59
- const selectColumnsTypeName = capitalizedName + 'Select';
60
- const whereTypeName = capitalizedName + 'Where';
61
- const orderByTypeName = capitalizedName + 'OrderBy';
62
- const generateOrderBy = tsDescriptor.orderByColumns != null && tsDescriptor.orderByColumns.length > 0;
55
+ const dataTypeName = `${capitalizedName}Data`;
56
+ const paramsTypeName = `${capitalizedName}Params`;
57
+ const resultTypeName = `${capitalizedName}Result`;
58
+ const dynamicParamsTypeName = `${capitalizedName}DynamicParams`;
59
+ const selectColumnsTypeName = `${capitalizedName}Select`;
60
+ const whereTypeName = `${capitalizedName}Where`;
61
+ const orderByTypeName = `${capitalizedName}OrderBy`;
62
+ const generateOrderBy = tsDescriptor.orderByColumns != null &&
63
+ tsDescriptor.orderByColumns.length > 0;
63
64
  // Import declarations
64
- if (target == 'deno') {
65
- writer.writeLine(`import { Client } from "https://deno.land/x/mysql/mod.ts";`);
66
- }
67
- else {
68
- writer.writeLine(`import type { Connection } from 'mysql2/promise';`);
69
- if (tsDescriptor.dynamicQuery != null) {
70
- writer.writeLine(`import { EOL } from 'os';`);
71
- }
65
+ writer.writeLine(`import type { Connection } from 'mysql2/promise';`);
66
+ if (tsDescriptor.dynamicQuery != null) {
67
+ writer.writeLine(`import { EOL } from 'os';`);
72
68
  }
73
69
  writer.blankLine();
74
- if (tsDescriptor.data) { //update
70
+ if (tsDescriptor.data) {
71
+ //update
75
72
  writeTypeBlock(writer, tsDescriptor.data, dataTypeName, crud);
76
73
  }
77
- const orderByField = generateOrderBy ? `orderBy: [${orderByTypeName}, ...${orderByTypeName}[]]` : undefined;
78
- const paramsTypes = tsDescriptor.dynamicQuery == null ? tsDescriptor.parameters : (0, ts_dynamic_query_descriptor_1.mapToDynamicParams)(tsDescriptor.parameters);
74
+ const orderByField = generateOrderBy
75
+ ? `orderBy: [${orderByTypeName}, ...${orderByTypeName}[]]`
76
+ : undefined;
77
+ const paramsTypes = tsDescriptor.dynamicQuery == null
78
+ ? tsDescriptor.parameters
79
+ : (0, ts_dynamic_query_descriptor_1.mapToDynamicParams)(tsDescriptor.parameters);
79
80
  if (tsDescriptor.dynamicQuery != null) {
80
81
  writer.write(`export type ${dynamicParamsTypeName} = `).block(() => {
81
82
  writer.writeLine(`select?: ${selectColumnsTypeName};`);
@@ -90,12 +91,14 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
90
91
  writer.blankLine();
91
92
  }
92
93
  writeTypeBlock(writer, paramsTypes, paramsTypeName, false, tsDescriptor.dynamicQuery ? undefined : orderByField);
93
- const resultTypes = tsDescriptor.dynamicQuery == null ? tsDescriptor.columns : (0, ts_dynamic_query_descriptor_1.mapToDynamicResultColumns)(tsDescriptor.columns);
94
+ const resultTypes = tsDescriptor.dynamicQuery == null
95
+ ? tsDescriptor.columns
96
+ : (0, ts_dynamic_query_descriptor_1.mapToDynamicResultColumns)(tsDescriptor.columns);
94
97
  writeTypeBlock(writer, resultTypes, resultTypeName, false);
95
98
  if (tsDescriptor.dynamicQuery) {
96
99
  const selectFields = (0, ts_dynamic_query_descriptor_1.mapToDynamicSelectColumns)(tsDescriptor.columns);
97
100
  writeTypeBlock(writer, selectFields, selectColumnsTypeName, false);
98
- writer.write(`const selectFragments = `).inlineBlock(() => {
101
+ writer.write('const selectFragments = ').inlineBlock(() => {
99
102
  var _a;
100
103
  (_a = tsDescriptor.dynamicQuery) === null || _a === void 0 ? void 0 : _a.select.forEach((fragment, index) => {
101
104
  const field = tsDescriptor.columns[index].name;
@@ -105,17 +108,16 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
105
108
  writer.write(' as const;');
106
109
  if (orderByField != null) {
107
110
  writer.blankLine();
108
- writer.write(`const orderByFragments = `).inlineBlock(() => {
109
- var _a;
110
- (_a = tsDescriptor.orderByColumns) === null || _a === void 0 ? void 0 : _a.forEach((col) => {
111
+ writer.write('const orderByFragments = ').inlineBlock(() => {
112
+ for (const col of tsDescriptor.orderByColumns || []) {
111
113
  writer.writeLine(`'${col}': \`${col}\`,`);
112
- });
114
+ }
113
115
  });
114
116
  writer.write(' as const;');
115
117
  }
116
118
  writer.blankLine();
117
119
  writer.writeLine(`const NumericOperatorList = ['=', '<>', '>', '<', '>=', '<='] as const;`);
118
- writer.writeLine(`type NumericOperator = typeof NumericOperatorList[number];`);
120
+ writer.writeLine('type NumericOperator = typeof NumericOperatorList[number];');
119
121
  if (hasStringColumn(tsDescriptor.columns)) {
120
122
  writer.writeLine(`type StringOperator = '=' | '<>' | '>' | '<' | '>=' | '<=' | 'LIKE';`);
121
123
  }
@@ -123,41 +125,55 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
123
125
  writer.writeLine(`type BetweenOperator = 'BETWEEN';`);
124
126
  writer.blankLine();
125
127
  writer.write(`export type ${whereTypeName} =`).indent(() => {
126
- tsDescriptor.columns.forEach(col => {
128
+ for (const col of tsDescriptor.columns) {
127
129
  writer.writeLine(`| ['${col.name}', ${getOperator(col.tsType)}, ${col.tsType} | null]`);
128
130
  writer.writeLine(`| ['${col.name}', SetOperator, ${col.tsType}[]]`);
129
131
  writer.writeLine(`| ['${col.name}', BetweenOperator, ${col.tsType} | null, ${col.tsType} | null]`);
130
- });
132
+ }
131
133
  });
132
134
  writer.blankLine();
133
135
  }
134
136
  let functionReturnType = resultTypeName;
135
- functionReturnType += tsDescriptor.multipleRowsResult ? '[]' : tsDescriptor.queryType == 'Select' ? ' | null' : '';
136
- let functionArguments = target == 'deno' ? 'client: Client' : 'connection: Connection';
137
- functionArguments += tsDescriptor.data && tsDescriptor.data.length > 0 ? ', data: ' + dataTypeName : '';
137
+ functionReturnType += tsDescriptor.multipleRowsResult
138
+ ? '[]'
139
+ : tsDescriptor.queryType === 'Select'
140
+ ? ' | null'
141
+ : '';
142
+ let functionArguments = 'connection: Connection';
143
+ functionArguments +=
144
+ tsDescriptor.data && tsDescriptor.data.length > 0
145
+ ? `, data: ${dataTypeName}`
146
+ : '';
138
147
  if (tsDescriptor.dynamicQuery == null) {
139
- functionArguments += tsDescriptor.parameters.length > 0 || generateOrderBy ? ', params: ' + paramsTypeName : '';
148
+ functionArguments +=
149
+ tsDescriptor.parameters.length > 0 || generateOrderBy
150
+ ? `, params: ${paramsTypeName}`
151
+ : '';
140
152
  }
141
153
  else {
142
154
  functionArguments += `, ${orderByField ? 'params' : 'params?'}: ${dynamicParamsTypeName}`;
143
155
  }
144
- const allParameters = tsDescriptor.data ? tsDescriptor.data.map((field, index) => {
145
- //:nameIsSet, :name, :valueIsSet, :value....
146
- if (crud && index % 2 == 0) {
147
- const nextField = tsDescriptor.data[index + 1];
148
- return `data.${nextField.name} !== undefined`;
149
- }
150
- return 'data.' + field.name;
151
- }) : [];
152
- allParameters.push(...tsDescriptor.parameterNames.map((paramName) => generateParam(target, paramName)));
153
- const queryParams = allParameters.length > 0 ? ', [' + allParameters.join(', ') + ']' : '';
156
+ const allParameters = tsDescriptor.data
157
+ ? tsDescriptor.data.map((field, index) => {
158
+ //:nameIsSet, :name, :valueIsSet, :value....
159
+ if (crud && index % 2 === 0) {
160
+ const nextField = tsDescriptor.data[index + 1];
161
+ return `data.${nextField.name} !== undefined`;
162
+ }
163
+ return `data.${field.name}`;
164
+ })
165
+ : [];
166
+ allParameters.push(...tsDescriptor.parameterNames.map((paramName) => generateParam(paramName)));
167
+ const queryParams = allParameters.length > 0 ? `, [${allParameters.join(', ')}]` : '';
154
168
  const escapedBackstick = scapeBackStick(tsDescriptor.sql);
155
169
  const processedSql = replaceOrderByParam(escapedBackstick);
156
170
  const sqlSplit = processedSql.split('\n');
157
- writer.write(`export async function ${camelCaseName}(${functionArguments}): Promise<${functionReturnType}>`).block(() => {
171
+ writer
172
+ .write(`export async function ${camelCaseName}(${functionArguments}): Promise<${functionReturnType}>`)
173
+ .block(() => {
158
174
  if (tsDescriptor.dynamicQuery == null) {
159
175
  writer.writeLine('const sql = `');
160
- sqlSplit.forEach(sqlLine => {
176
+ sqlSplit.forEach((sqlLine) => {
161
177
  writer.indent().write(sqlLine);
162
178
  writer.newLine();
163
179
  });
@@ -165,34 +181,36 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
165
181
  writer.blankLine();
166
182
  }
167
183
  else {
168
- writer.writeLine(`const where = whereConditionsToObject(params?.where);`);
184
+ writer.writeLine('const where = whereConditionsToObject(params?.where);');
169
185
  if (orderByField != null) {
170
- writer.writeLine(`const orderBy = orderByToObject(params.orderBy);`);
186
+ writer.writeLine('const orderBy = orderByToObject(params.orderBy);');
171
187
  }
172
188
  writer.writeLine('const paramsValues: any = [];');
173
189
  if (tsDescriptor.dynamicQuery.with) {
174
190
  writer.writeLine(`let withClause = '';`);
175
- tsDescriptor.dynamicQuery.with.forEach(withFragment => {
191
+ tsDescriptor.dynamicQuery.with.forEach((withFragment) => {
176
192
  generateDynamicQueryFrom(writer, 'withClause', withFragment, tsDescriptor.columns);
177
193
  });
178
194
  }
179
195
  writer.writeLine(`let sql = 'SELECT';`);
180
- tsDescriptor.dynamicQuery.select.forEach(fragment => {
181
- writer.write(`if (params?.select == null || ${fragment.dependOnFields.map(fieldIndex => 'params.select.' + tsDescriptor.columns[fieldIndex].name).join('&&')})`).block(() => {
196
+ tsDescriptor.dynamicQuery.select.forEach((fragment) => {
197
+ writer
198
+ .write(`if (params?.select == null || ${fragment.dependOnFields.map((fieldIndex) => `params.select.${tsDescriptor.columns[fieldIndex].name}`).join('&&')})`)
199
+ .block(() => {
182
200
  writer.write(`sql = appendSelect(sql, \`${fragment.fragment}\`);`);
183
201
  });
184
202
  });
185
- tsDescriptor.dynamicQuery.from.forEach(fragment => {
203
+ tsDescriptor.dynamicQuery.from.forEach((fragment) => {
186
204
  generateDynamicQueryFrom(writer, 'sql', fragment, tsDescriptor.columns, tsDescriptor.orderByColumns != null);
187
205
  });
188
- writer.writeLine(`sql += EOL + \`WHERE 1 = 1\`;`);
189
- tsDescriptor.dynamicQuery.where.forEach(fragment => {
190
- const ifParamConditions = fragment.dependOnParams.map(param => 'params?.params?.' + param + ' != null');
191
- const paramValues = fragment.parameters.map(param => 'params.params.' + param);
206
+ writer.writeLine('sql += EOL + `WHERE 1 = 1`;');
207
+ tsDescriptor.dynamicQuery.where.forEach((fragment) => {
208
+ const ifParamConditions = fragment.dependOnParams.map((param) => `params?.params?.${param} != null`);
209
+ const paramValues = fragment.parameters.map((param) => `params.params.${param}`);
192
210
  if (ifParamConditions.length > 0) {
193
211
  writer.write(`if (${ifParamConditions.join(' || ')})`).block(() => {
194
212
  writer.writeLine(`sql += EOL + \`${fragment.fragment}\`;`);
195
- paramValues.forEach(paramValues => {
213
+ paramValues.forEach((paramValues) => {
196
214
  writer.writeLine(`paramsValues.push(${paramValues});`);
197
215
  });
198
216
  });
@@ -206,11 +224,11 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
206
224
  writer.writeLine(`sql = 'WITH ' + withClause + EOL + sql;`);
207
225
  });
208
226
  }
209
- writer.write(`params?.where?.forEach(condition => `).inlineBlock(() => {
210
- writer.writeLine(`const where = whereCondition(condition);`);
211
- writer.write(`if (where?.hasValue)`).block(() => {
227
+ writer.write('params?.where?.forEach(condition => ').inlineBlock(() => {
228
+ writer.writeLine('const where = whereCondition(condition);');
229
+ writer.write('if (where?.hasValue)').block(() => {
212
230
  writer.writeLine(`sql += EOL + 'AND ' + where.sql;`);
213
- writer.write(`paramsValues.push(...where.values);`);
231
+ writer.write('paramsValues.push(...where.values);');
214
232
  });
215
233
  });
216
234
  writer.write(');');
@@ -218,40 +236,44 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
218
236
  writer.writeLine('sql += EOL + `ORDER BY ${escapeOrderBy(params.orderBy)}`;');
219
237
  }
220
238
  }
221
- const singleRowSelect = tsDescriptor.queryType == 'Select' && tsDescriptor.multipleRowsResult === false;
222
- if (target == 'deno') {
223
- writer.writeLine(`return client.query(sql${queryParams})`);
224
- writer.indent().write(`.then(res => res${singleRowSelect ? '[0]' : ''});`);
225
- }
226
- else {
227
- if (tsDescriptor.queryType == 'Select') {
228
- if (tsDescriptor.dynamicQuery == null) {
229
- writer.writeLine(`return connection.query({sql, rowsAsArray: true}${queryParams})`);
230
- writer.indent().write(`.then(res => res[0] as any[])`);
231
- writer.newLine().indent().write(`.then(res => res.map(data => mapArrayTo${resultTypeName}(data)))`);
232
- }
233
- else {
234
- writer.writeLine(`return connection.query({ sql, rowsAsArray: true }, paramsValues)`);
235
- writer.indent().write(`.then(res => res[0] as any[])`);
236
- writer.newLine().indent().write(`.then(res => res.map(data => mapArrayTo${resultTypeName}(data, params?.select)))`);
237
- }
238
- }
239
- else {
240
- writer.writeLine(`return connection.query(sql${queryParams})`);
241
- writer.indent().write(`.then(res => res[0] as ${resultTypeName})`);
242
- }
243
- if (tsDescriptor.queryType == 'Select' && tsDescriptor.multipleRowsResult == false) {
244
- writer.newLine().indent().write(`.then(res => res[0]);`);
239
+ const singleRowSelect = tsDescriptor.queryType === 'Select' &&
240
+ tsDescriptor.multipleRowsResult === false;
241
+ if (tsDescriptor.queryType === 'Select') {
242
+ if (tsDescriptor.dynamicQuery == null) {
243
+ writer.writeLine(`return connection.query({sql, rowsAsArray: true}${queryParams})`);
244
+ writer.indent().write('.then(res => res[0] as any[])');
245
+ writer
246
+ .newLine()
247
+ .indent()
248
+ .write(`.then(res => res.map(data => mapArrayTo${resultTypeName}(data)))`);
245
249
  }
246
250
  else {
247
- writer.write(';');
251
+ writer.writeLine('return connection.query({ sql, rowsAsArray: true }, paramsValues)');
252
+ writer.indent().write('.then(res => res[0] as any[])');
253
+ writer
254
+ .newLine()
255
+ .indent()
256
+ .write(`.then(res => res.map(data => mapArrayTo${resultTypeName}(data, params?.select)))`);
248
257
  }
249
258
  }
259
+ else {
260
+ writer.writeLine(`return connection.query(sql${queryParams})`);
261
+ writer.indent().write(`.then(res => res[0] as ${resultTypeName})`);
262
+ }
263
+ if (tsDescriptor.queryType === 'Select' &&
264
+ tsDescriptor.multipleRowsResult === false) {
265
+ writer.newLine().indent().write('.then(res => res[0]);');
266
+ }
267
+ else {
268
+ writer.write(';');
269
+ }
250
270
  });
251
- if (target == 'node' && tsDescriptor.queryType == 'Select') {
271
+ if (tsDescriptor.queryType === 'Select') {
252
272
  writer.blankLine();
253
273
  if (tsDescriptor.dynamicQuery == null) {
254
- writer.write(`function mapArrayTo${resultTypeName}(data: any)`).block(() => {
274
+ writer
275
+ .write(`function mapArrayTo${resultTypeName}(data: any)`)
276
+ .block(() => {
255
277
  writer.write(`const result: ${resultTypeName} =`).block(() => {
256
278
  tsDescriptor.columns.forEach((tsField, index) => {
257
279
  writer.writeLine(`${tsField.name}: data[${index}]${commaSeparator(tsDescriptor.columns.length, index)}`);
@@ -261,85 +283,101 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
261
283
  });
262
284
  }
263
285
  else {
264
- writer.write(`function mapArrayTo${resultTypeName}(data: any, select?: ${selectColumnsTypeName})`).block(() => {
286
+ writer
287
+ .write(`function mapArrayTo${resultTypeName}(data: any, select?: ${selectColumnsTypeName})`)
288
+ .block(() => {
265
289
  writer.writeLine(`const result = {} as ${resultTypeName};`);
266
- writer.writeLine(`let rowIndex = 0;`);
290
+ writer.writeLine('let rowIndex = 0;');
267
291
  tsDescriptor.columns.forEach((tsField) => {
268
- writer.write(`if (select == null || select.${tsField.name})`).block(() => {
292
+ writer
293
+ .write(`if (select == null || select.${tsField.name})`)
294
+ .block(() => {
269
295
  writer.writeLine(`result.${tsField.name} = data[rowIndex++];`);
270
296
  });
271
297
  });
272
298
  writer.write('return result;');
273
299
  });
274
300
  writer.blankLine();
275
- writer.write(`function appendSelect(sql: string, selectField: string)`).block(() => {
301
+ writer
302
+ .write('function appendSelect(sql: string, selectField: string)')
303
+ .block(() => {
276
304
  writer.write(`if (sql == 'SELECT')`).block(() => {
277
- writer.writeLine(`return sql + EOL + selectField;`);
305
+ writer.writeLine('return sql + EOL + selectField;');
278
306
  });
279
- writer.write(`else`).block(() => {
307
+ writer.write('else').block(() => {
280
308
  writer.writeLine(`return sql + ', ' + EOL + selectField;`);
281
309
  });
282
310
  });
283
311
  writer.blankLine();
284
- writer.write(`function whereConditionsToObject(whereConditions?: ${whereTypeName}[])`).block(() => {
285
- writer.writeLine(`const obj = {} as any;`);
286
- writer.write(`whereConditions?.forEach(condition => `).inlineBlock(() => {
287
- writer.writeLine(`const where = whereCondition(condition);`);
288
- writer.write(`if (where?.hasValue) `).block(() => {
289
- writer.writeLine(`obj[condition[0]] = true;`);
312
+ writer
313
+ .write(`function whereConditionsToObject(whereConditions?: ${whereTypeName}[])`)
314
+ .block(() => {
315
+ writer.writeLine('const obj = {} as any;');
316
+ writer
317
+ .write('whereConditions?.forEach(condition => ')
318
+ .inlineBlock(() => {
319
+ writer.writeLine('const where = whereCondition(condition);');
320
+ writer.write('if (where?.hasValue) ').block(() => {
321
+ writer.writeLine('obj[condition[0]] = true;');
290
322
  });
291
323
  });
292
324
  writer.write(');');
293
- writer.writeLine(`return obj;`);
325
+ writer.writeLine('return obj;');
294
326
  });
295
327
  if (orderByField != null) {
296
328
  writer.blankLine();
297
329
  writer.write(`function orderByToObject(${orderByField})`).block(() => {
298
- writer.writeLine(`const obj = {} as any;`);
299
- writer.write(`orderBy?.forEach(order => `).inlineBlock(() => {
300
- writer.writeLine(`obj[order.column] = true;`);
330
+ writer.writeLine('const obj = {} as any;');
331
+ writer.write('orderBy?.forEach(order => ').inlineBlock(() => {
332
+ writer.writeLine('obj[order.column] = true;');
301
333
  });
302
334
  writer.write(');');
303
- writer.writeLine(`return obj;`);
335
+ writer.writeLine('return obj;');
304
336
  });
305
337
  }
306
338
  writer.blankLine();
307
- writer.write(`type WhereConditionResult = `).block(() => {
339
+ writer.write('type WhereConditionResult = ').block(() => {
308
340
  writer.writeLine('sql: string;');
309
341
  writer.writeLine('hasValue: boolean;');
310
342
  writer.writeLine('values: any[];');
311
343
  });
312
344
  writer.blankLine();
313
- writer.write(`function whereCondition(condition: ${whereTypeName}): WhereConditionResult | undefined `).block(() => {
345
+ writer
346
+ .write(`function whereCondition(condition: ${whereTypeName}): WhereConditionResult | undefined `)
347
+ .block(() => {
314
348
  writer.blankLine();
315
349
  writer.writeLine('const selectFragment = selectFragments[condition[0]];');
316
350
  writer.writeLine('const operator = condition[1];');
317
351
  writer.blankLine();
318
352
  if (hasStringColumn(tsDescriptor.columns)) {
319
353
  writer.write(`if (operator == 'LIKE') `).block(() => {
320
- writer.write(`return `).block(() => {
321
- writer.writeLine('sql: `${selectFragment} LIKE concat(\'%\', ?, \'%\')`,');
354
+ writer.write('return ').block(() => {
355
+ writer.writeLine("sql: `${selectFragment} LIKE concat('%', ?, '%')`,");
322
356
  writer.writeLine('hasValue: condition[2] != null,');
323
357
  writer.writeLine('values: [condition[2]]');
324
358
  });
325
359
  });
326
360
  }
327
361
  writer.write(`if (operator == 'BETWEEN') `).block(() => {
328
- writer.write(`return `).block(() => {
362
+ writer.write('return ').block(() => {
329
363
  writer.writeLine('sql: `${selectFragment} BETWEEN ? AND ?`,');
330
364
  writer.writeLine('hasValue: condition[2] != null && condition[3] != null,');
331
365
  writer.writeLine('values: [condition[2], condition[3]]');
332
366
  });
333
367
  });
334
- writer.write(`if (operator == 'IN' || operator == 'NOT IN') `).block(() => {
335
- writer.write(`return `).block(() => {
368
+ writer
369
+ .write(`if (operator == 'IN' || operator == 'NOT IN') `)
370
+ .block(() => {
371
+ writer.write('return ').block(() => {
336
372
  writer.writeLine('sql: `${selectFragment} ${operator} (?)`,');
337
373
  writer.writeLine('hasValue: condition[2] != null && condition[2].length > 0,');
338
374
  writer.writeLine('values: [condition[2]]');
339
375
  });
340
376
  });
341
- writer.write(`if (NumericOperatorList.includes(operator)) `).block(() => {
342
- writer.write(`return `).block(() => {
377
+ writer
378
+ .write('if (NumericOperatorList.includes(operator)) ')
379
+ .block(() => {
380
+ writer.write('return ').block(() => {
343
381
  writer.writeLine('sql: `${selectFragment} ${operator} ?`,');
344
382
  writer.writeLine('hasValue: condition[2] != null,');
345
383
  writer.writeLine('values: [condition[2]]');
@@ -349,19 +387,21 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
349
387
  }
350
388
  }
351
389
  if (generateOrderBy) {
352
- const orderByColumnsType = (_a = tsDescriptor.orderByColumns) === null || _a === void 0 ? void 0 : _a.map(col => `'${col}'`).join(' | ');
390
+ const orderByColumnsType = (_a = tsDescriptor.orderByColumns) === null || _a === void 0 ? void 0 : _a.map((col) => `'${col}'`).join(' | ');
353
391
  writer.blankLine();
354
392
  writer.write(`export type ${orderByTypeName} = `).block(() => {
355
393
  if (tsDescriptor.dynamicQuery == null) {
356
394
  writer.writeLine(`column: ${orderByColumnsType};`);
357
395
  }
358
396
  else {
359
- writer.writeLine(`column: keyof typeof orderByFragments;`);
397
+ writer.writeLine('column: keyof typeof orderByFragments;');
360
398
  }
361
399
  writer.writeLine(`direction: 'asc' | 'desc';`);
362
400
  });
363
401
  writer.blankLine();
364
- writer.write(`function escapeOrderBy(orderBy: ${orderByTypeName}[]): string`).block(() => {
402
+ writer
403
+ .write(`function escapeOrderBy(orderBy: ${orderByTypeName}[]): string`)
404
+ .block(() => {
365
405
  if (tsDescriptor.dynamicQuery == null) {
366
406
  writer.writeLine(`return orderBy.map(order => \`\\\`\${order.column}\\\` \${order.direction == 'desc' ? 'desc' : 'asc' }\`).join(', ');`);
367
407
  }
@@ -376,12 +416,12 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
376
416
  const relationType = generateRelationType(capitalizedName, relation.name);
377
417
  writer.blankLine();
378
418
  writer.write(`export type ${relationType} = `).block(() => {
379
- const uniqueNameFields = renameInvalidNames(relation.fields.map(f => f.name));
419
+ const uniqueNameFields = renameInvalidNames(relation.fields.map((f) => f.name));
380
420
  relation.fields.forEach((field, index) => {
381
- if (field.type == 'field') {
421
+ if (field.type === 'field') {
382
422
  writer.writeLine(`${uniqueNameFields[index]}: ${field.tsType};`);
383
423
  }
384
- if (field.type == 'relation') {
424
+ if (field.type === 'relation') {
385
425
  const nestedRelationType = generateRelationType(capitalizedName, field.tsType);
386
426
  const nullableOperator = field.notNull ? '' : '?';
387
427
  writer.writeLine(`${field.name}${nullableOperator}: ${nestedRelationType};`);
@@ -391,9 +431,12 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
391
431
  });
392
432
  relations.forEach((relation, index) => {
393
433
  const relationType = generateRelationType(capitalizedName, relation.name);
394
- if (index == 0) { //first
434
+ if (index === 0) {
435
+ //first
395
436
  writer.blankLine();
396
- writer.write(`export async function ${camelCaseName}Nested(${functionArguments}): Promise<${relationType}[]>`).block(() => {
437
+ writer
438
+ .write(`export async function ${camelCaseName}Nested(${functionArguments}): Promise<${relationType}[]>`)
439
+ .block(() => {
397
440
  const params = tsDescriptor.parameters.length > 0 ? ', params' : '';
398
441
  writer.writeLine(`const selectResult = await ${camelCaseName}(connection${params});`);
399
442
  writer.write('if (selectResult.length == 0)').block(() => {
@@ -405,26 +448,30 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
405
448
  const collectFunctionName = `collect${relationType}`;
406
449
  const mapFunctionName = `mapTo${relationType}`;
407
450
  writer.blankLine();
408
- writer.write(`function ${collectFunctionName}(selectResult: ${resultTypeName}[]): ${relationType}[]`).block(() => {
451
+ writer
452
+ .write(`function ${collectFunctionName}(selectResult: ${resultTypeName}[]): ${relationType}[]`)
453
+ .block(() => {
409
454
  const groupKey = tsDescriptor.columns[relation.groupKeyIndex].name;
410
455
  writer.writeLine(`const grouped = groupBy(selectResult.filter(r => r.${groupKey} != null), r => r.${groupKey});`);
411
456
  writer.writeLine(`return [...grouped.values()].map(r => ${mapFunctionName}(r))`);
412
457
  });
413
458
  writer.blankLine();
414
- writer.write(`function ${mapFunctionName}(selectResult: ${resultTypeName}[]): ${relationType}`).block(() => {
415
- writer.writeLine(`const firstRow = selectResult[0];`);
459
+ writer
460
+ .write(`function ${mapFunctionName}(selectResult: ${resultTypeName}[]): ${relationType}`)
461
+ .block(() => {
462
+ writer.writeLine('const firstRow = selectResult[0];');
416
463
  writer.write(`const result: ${relationType} = `).block(() => {
417
- const uniqueNameFields = renameInvalidNames(relation.fields.map(f => f.name));
464
+ const uniqueNameFields = renameInvalidNames(relation.fields.map((f) => f.name));
418
465
  relation.fields.forEach((field, index) => {
419
466
  const separator = commaSeparator(relation.fields.length, index);
420
- if (field.type == 'field') {
467
+ if (field.type === 'field') {
421
468
  const fieldName = tsDescriptor.columns[field.index].name;
422
- writer.writeLine(`${uniqueNameFields[index]}: firstRow.${fieldName}!` + separator);
469
+ writer.writeLine(`${uniqueNameFields[index]}: firstRow.${fieldName}!${separator}`);
423
470
  }
424
- if (field.type == 'relation') {
471
+ if (field.type === 'relation') {
425
472
  const nestedRelationType = generateRelationType(capitalizedName, field.name);
426
473
  const cardinality = field.list ? '' : '[0]';
427
- writer.writeLine(`${field.name}: collect${nestedRelationType}(selectResult)${cardinality}` + separator);
474
+ writer.writeLine(`${field.name}: collect${nestedRelationType}(selectResult)${cardinality}${separator}`);
428
475
  }
429
476
  });
430
477
  });
@@ -432,12 +479,17 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
432
479
  });
433
480
  });
434
481
  writer.blankLine();
435
- writer.write('const groupBy = <T, Q>(array: T[], predicate: (value: T, index: number, array: T[]) => Q) =>').block(() => {
436
- writer.write('return array.reduce((map, value, index, array) => ').inlineBlock(() => {
482
+ writer
483
+ .write('const groupBy = <T, Q>(array: T[], predicate: (value: T, index: number, array: T[]) => Q) =>')
484
+ .block(() => {
485
+ writer
486
+ .write('return array.reduce((map, value, index, array) => ')
487
+ .inlineBlock(() => {
437
488
  writer.writeLine('const key = predicate(value, index, array);');
438
489
  writer.writeLine('map.get(key)?.push(value) ?? map.set(key, [value]);');
439
490
  writer.writeLine('return map;');
440
- }).write(', new Map<Q, T[]>());');
491
+ })
492
+ .write(', new Map<Q, T[]>());');
441
493
  });
442
494
  }
443
495
  return writer.toString();
@@ -445,45 +497,52 @@ function generateTsCodeForMySQL(tsDescriptor, fileName, target, crud = false) {
445
497
  exports.generateTsCodeForMySQL = generateTsCodeForMySQL;
446
498
  function generateDynamicQueryFrom(writer, sqlVar, fragment, columns, includeOrderBy = false) {
447
499
  var _a;
448
- const selectConditions = fragment.dependOnFields.map(fieldIndex => 'params.select.' + columns[fieldIndex].name);
500
+ const selectConditions = fragment.dependOnFields.map((fieldIndex) => `params.select.${columns[fieldIndex].name}`);
449
501
  if (selectConditions.length > 0) {
450
502
  selectConditions.unshift('params?.select == null');
451
503
  }
452
- const paramConditions = fragment.dependOnParams.map(param => 'params.params?.' + param + ' != null');
453
- const whereConditions = fragment.dependOnFields.map(fieldIndex => 'where.' + columns[fieldIndex].name + ' != null');
454
- const orderByConditions = includeOrderBy ? ((_a = fragment.dependOnOrderBy) === null || _a === void 0 ? void 0 : _a.map(orderBy => 'orderBy[\'' + orderBy + '\'] != null')) || [] : [];
455
- const allConditions = [...selectConditions, ...paramConditions, ...whereConditions, ...orderByConditions];
456
- const paramValues = fragment.parameters.map(param => 'params?.params?.' + param);
504
+ const paramConditions = fragment.dependOnParams.map((param) => `params.params?.${param} != null`);
505
+ const whereConditions = fragment.dependOnFields.map((fieldIndex) => `where.${columns[fieldIndex].name} != null`);
506
+ const orderByConditions = includeOrderBy
507
+ ? ((_a = fragment.dependOnOrderBy) === null || _a === void 0 ? void 0 : _a.map((orderBy) => `orderBy['${orderBy}'] != null`)) || []
508
+ : [];
509
+ const allConditions = [
510
+ ...selectConditions,
511
+ ...paramConditions,
512
+ ...whereConditions,
513
+ ...orderByConditions
514
+ ];
515
+ const paramValues = fragment.parameters.map((param) => `params?.params?.${param}`);
457
516
  if (allConditions.length > 0) {
458
- writer.write(`if (${allConditions.join(os_1.EOL + ' || ')})`).block(() => {
517
+ writer.write(`if (${allConditions.join(`${node_os_1.EOL} || `)})`).block(() => {
459
518
  writer.write(`${sqlVar} += EOL + \`${fragment.fragment}\`;`);
460
- paramValues.forEach(paramValues => {
461
- writer.writeLine(`paramsValues.push(${paramValues});`);
462
- });
519
+ for (const paramValue of paramValues) {
520
+ writer.writeLine(`paramsValues.push(${paramValue});`);
521
+ }
463
522
  });
464
523
  }
465
524
  else {
466
525
  writer.writeLine(`${sqlVar} += EOL + \`${fragment.fragment}\`;`);
467
- paramValues.forEach(paramValues => {
468
- writer.writeLine(`paramsValues.push(${paramValues});`);
469
- });
526
+ for (const paramValue of paramValues) {
527
+ writer.writeLine(`paramsValues.push(${paramValue});`);
528
+ }
470
529
  }
471
530
  }
472
531
  function getOperator(type) {
473
- if (type == 'number' || type == 'Date') {
532
+ if (type === 'number' || type === 'Date') {
474
533
  return 'NumericOperator';
475
534
  }
476
535
  return 'StringOperator';
477
536
  }
478
537
  exports.getOperator = getOperator;
479
- function generateParam(target, param) {
480
- if (target == 'node' && param.isList) {
538
+ function generateParam(param) {
539
+ if (param.isList) {
481
540
  return `params.${param.name}.length == 0? null : params.${param.name}`;
482
541
  }
483
542
  return `params.${param.name}`;
484
543
  }
485
544
  function generateRelationType(capitalizedName, relationName) {
486
- return capitalizedName + 'Nested' + capitalizeStr(relationName);
545
+ return `${capitalizedName}Nested${capitalizeStr(relationName)}`;
487
546
  }
488
547
  exports.generateRelationType = generateRelationType;
489
548
  function writeTypeBlock(writer, fields, typeName, updateCrud, extraField) {
@@ -492,15 +551,16 @@ function writeTypeBlock(writer, fields, typeName, updateCrud, extraField) {
492
551
  writer.write(`export type ${typeName} =`).block(() => {
493
552
  fields.forEach((tsField, index) => {
494
553
  // :nameSet, :name, valueSet, :value...
495
- if (updateCrud && index % 2 != 0) { //only odd fields (:name, :value)
496
- writer.writeLine(tsFieldToStr(tsField, true) + ';');
554
+ if (updateCrud && index % 2 !== 0) {
555
+ //only odd fields (:name, :value)
556
+ writer.writeLine(`${tsFieldToStr(tsField, true)};`);
497
557
  }
498
558
  else if (!updateCrud) {
499
- writer.writeLine(tsFieldToStr(tsField, false) + ';');
559
+ writer.writeLine(`${tsFieldToStr(tsField, false)};`);
500
560
  }
501
561
  });
502
562
  if (extraField) {
503
- writer.write(extraField + ';');
563
+ writer.write(`${extraField};`);
504
564
  }
505
565
  });
506
566
  writer.blankLine();
@@ -510,13 +570,13 @@ exports.writeTypeBlock = writeTypeBlock;
510
570
  function tsFieldToStr(tsField, isCrudUpdate) {
511
571
  if (isCrudUpdate) {
512
572
  //all fields are optionals
513
- return tsField.name + '?: ' + tsField.tsType + (tsField.notNull == false ? ' | null' : '');
573
+ return `${tsField.name}?: ${tsField.tsType}${tsField.notNull === false ? ' | null' : ''}`;
514
574
  }
515
575
  return tsField.name + (tsField.notNull ? ': ' : '?: ') + tsField.tsType;
516
576
  }
517
577
  function generateTsDescriptor(queryInfo) {
518
578
  var _a;
519
- const escapedColumnsNames = renameInvalidNames(queryInfo.columns.map(col => col.columnName));
579
+ const escapedColumnsNames = renameInvalidNames(queryInfo.columns.map((col) => col.columnName));
520
580
  const columns = queryInfo.columns.map((col, columnIndex) => {
521
581
  const tsDesc = {
522
582
  name: escapedColumnsNames[columnIndex],
@@ -525,15 +585,15 @@ function generateTsDescriptor(queryInfo) {
525
585
  };
526
586
  return tsDesc;
527
587
  });
528
- const parameterNames = queryInfo.parameters.map(p => {
588
+ const parameterNames = queryInfo.parameters.map((p) => {
529
589
  const paramInfo = {
530
590
  name: p.name,
531
- isList: p.columnType.endsWith('[]') ? true : false
591
+ isList: !!p.columnType.endsWith('[]')
532
592
  };
533
593
  return paramInfo;
534
594
  });
535
595
  const uniqueParams = removeDuplicatedParameters(queryInfo.parameters);
536
- const escapedParametersNames = renameInvalidNames(uniqueParams.map(col => col.name));
596
+ const escapedParametersNames = renameInvalidNames(uniqueParams.map((col) => col.name));
537
597
  const parameters = uniqueParams.map((col, paramIndex) => {
538
598
  const arraySymbol = col.list ? '[]' : '';
539
599
  const tsDesc = {
@@ -543,7 +603,9 @@ function generateTsDescriptor(queryInfo) {
543
603
  };
544
604
  return tsDesc;
545
605
  });
546
- const escapedDataNames = queryInfo.data ? renameInvalidNames(queryInfo.data.map(col => col.name)) : [];
606
+ const escapedDataNames = queryInfo.data
607
+ ? renameInvalidNames(queryInfo.data.map((col) => col.name))
608
+ : [];
547
609
  const data = (_a = queryInfo.data) === null || _a === void 0 ? void 0 : _a.map((col, dataIndex) => {
548
610
  const tsDesc = {
549
611
  name: escapedDataNames[dataIndex],
@@ -560,7 +622,7 @@ function generateTsDescriptor(queryInfo) {
560
622
  orderByColumns: queryInfo.orderByColumns,
561
623
  parameterNames,
562
624
  parameters,
563
- data,
625
+ data
564
626
  };
565
627
  if (queryInfo.nestedResultInfo) {
566
628
  const nestedDescriptor = (0, ts_nested_descriptor_1.createNestedTsDescriptor)(queryInfo.columns, queryInfo.nestedResultInfo);
@@ -578,10 +640,11 @@ function generateTsDescriptor(queryInfo) {
578
640
  exports.generateTsDescriptor = generateTsDescriptor;
579
641
  function removeDuplicatedParameters(parameters) {
580
642
  const columnsCount = new Map();
581
- parameters.forEach(param => {
643
+ parameters.forEach((param) => {
582
644
  const dupParam = columnsCount.get(param.name);
583
- if (dupParam != null) { //duplicated - two parameter null and notNull, resturn the null param (notNull == false)
584
- if (param.notNull == false) {
645
+ if (dupParam != null) {
646
+ //duplicated - two parameter null and notNull, resturn the null param (notNull == false)
647
+ if (param.notNull === false) {
585
648
  columnsCount.set(param.name, param);
586
649
  }
587
650
  // return param;
@@ -596,10 +659,11 @@ exports.removeDuplicatedParameters = removeDuplicatedParameters;
596
659
  //TODO - remove duplicated code
597
660
  function removeDuplicatedParameters2(parameters) {
598
661
  const columnsCount = new Map();
599
- parameters.forEach(param => {
662
+ parameters.forEach((param) => {
600
663
  const dupParam = columnsCount.get(param.name);
601
- if (dupParam != null) { //duplicated - two parameter null and notNull, resturn the null param (notNull == false)
602
- if (param.notNull == false) {
664
+ if (dupParam != null) {
665
+ //duplicated - two parameter null and notNull, resturn the null param (notNull == false)
666
+ if (param.notNull === false) {
603
667
  columnsCount.set(param.name, param);
604
668
  }
605
669
  // return param;
@@ -613,23 +677,21 @@ function removeDuplicatedParameters2(parameters) {
613
677
  exports.removeDuplicatedParameters2 = removeDuplicatedParameters2;
614
678
  function renameInvalidNames(columnNames) {
615
679
  const columnsCount = new Map();
616
- return columnNames.map(columnName => {
680
+ return columnNames.map((columnName) => {
617
681
  if (columnsCount.has(columnName)) {
618
682
  const count = columnsCount.get(columnName) + 1;
619
683
  columnsCount.set(columnName, count);
620
- const newName = columnName + '_' + count;
684
+ const newName = `${columnName}_${count}`;
621
685
  return escapeInvalidTsField(newName);
622
686
  }
623
- else {
624
- columnsCount.set(columnName, 1);
625
- return escapeInvalidTsField(columnName);
626
- }
687
+ columnsCount.set(columnName, 1);
688
+ return escapeInvalidTsField(columnName);
627
689
  });
628
690
  }
629
691
  exports.renameInvalidNames = renameInvalidNames;
630
692
  function scapeBackStick(sql) {
631
693
  const pattern = /`/g;
632
- return sql.replace(pattern, "\\`");
694
+ return sql.replace(pattern, '\\`');
633
695
  }
634
696
  function escapeInvalidTsField(columnName) {
635
697
  const validPattern = /^[a-zA-Z0-9_$]+$/g;
@@ -640,28 +702,28 @@ function escapeInvalidTsField(columnName) {
640
702
  }
641
703
  exports.escapeInvalidTsField = escapeInvalidTsField;
642
704
  function mapColumnType(columnType) {
643
- if (columnType == 'any')
705
+ if (columnType === 'any')
644
706
  return 'any';
645
707
  const types = [].concat(columnType);
646
- const mappedTypes = types.map(type => (0, mysql_mapping_1.converToTsType)(type));
708
+ const mappedTypes = types.map((type) => (0, mysql_mapping_1.converToTsType)(type));
647
709
  return mappedTypes.join(' | '); // number | string
648
710
  }
649
711
  function hasStringColumn(columns) {
650
- return columns.some(c => c.tsType == 'string');
712
+ return columns.some((c) => c.tsType === 'string');
651
713
  }
652
714
  exports.hasStringColumn = hasStringColumn;
653
715
  function hasDateColumn(columns) {
654
- return columns.some(c => c.tsType == 'Date');
716
+ return columns.some((c) => c.tsType === 'Date');
655
717
  }
656
718
  exports.hasDateColumn = hasDateColumn;
657
719
  function replaceOrderByParam(sql) {
658
720
  const patern = /(.*order\s+by\s*)(\?)(.\n$)*/i;
659
- const newSql = sql.replace(patern, "$1${escapeOrderBy(params.orderBy)}$3");
721
+ const newSql = sql.replace(patern, '$1${escapeOrderBy(params.orderBy)}$3');
660
722
  return newSql;
661
723
  }
662
724
  exports.replaceOrderByParam = replaceOrderByParam;
663
725
  function writeFile(filePath, tsContent) {
664
- fs_1.default.writeFileSync(filePath, tsContent);
726
+ node_fs_1.default.writeFileSync(filePath, tsContent);
665
727
  }
666
728
  exports.writeFile = writeFile;
667
729
  function capitalize(name) {
@@ -669,7 +731,7 @@ function capitalize(name) {
669
731
  }
670
732
  exports.capitalize = capitalize;
671
733
  function capitalizeStr(name) {
672
- if (name.length == 0)
734
+ if (name.length === 0)
673
735
  return name;
674
736
  return name.charAt(0).toUpperCase() + name.slice(1);
675
737
  }
@@ -680,16 +742,18 @@ function convertToCamelCaseName(name) {
680
742
  exports.convertToCamelCaseName = convertToCamelCaseName;
681
743
  function generateTsFile(client, sqlFile, dbSchema, isCrudFile) {
682
744
  return __awaiter(this, void 0, void 0, function* () {
683
- const sqlContent = fs_1.default.readFileSync(sqlFile, 'utf8');
684
- if (sqlContent.trim() == '') { //ignore empty file
745
+ const sqlContent = node_fs_1.default.readFileSync(sqlFile, 'utf8');
746
+ if (sqlContent.trim() === '') {
747
+ //ignore empty file
685
748
  return;
686
749
  }
687
- const fileName = (0, path_1.parse)(sqlFile).name;
688
- const dirPath = (0, path_1.parse)(sqlFile).dir;
750
+ const fileName = (0, node_path_1.parse)(sqlFile).name;
751
+ const dirPath = (0, node_path_1.parse)(sqlFile).dir;
689
752
  const queryName = convertToCamelCaseName(fileName);
690
- const tsContentResult = client.type == 'mysql' ? yield generateTsFileFromContent(client, queryName, sqlContent, 'node', isCrudFile)
753
+ const tsContentResult = client.type === 'mysql2'
754
+ ? yield generateTsFileFromContent(client, queryName, sqlContent, isCrudFile)
691
755
  : (0, code_generator_1.validateAndGenerateCode)(client, sqlContent, queryName, dbSchema, isCrudFile);
692
- const tsFilePath = path_1.default.resolve(dirPath, fileName) + ".ts";
756
+ const tsFilePath = `${node_path_1.default.resolve(dirPath, fileName)}.ts`;
693
757
  if ((0, Either_1.isLeft)(tsContentResult)) {
694
758
  console.error('ERROR: ', tsContentResult.left.description);
695
759
  console.error('at ', sqlFile);
@@ -701,19 +765,19 @@ function generateTsFile(client, sqlFile, dbSchema, isCrudFile) {
701
765
  });
702
766
  }
703
767
  exports.generateTsFile = generateTsFile;
704
- function generateTsFileFromContent(client_1, queryName_1, sqlContent_1, target_1) {
705
- return __awaiter(this, arguments, void 0, function* (client, queryName, sqlContent, target, crud = false) {
768
+ function generateTsFileFromContent(client_1, queryName_1, sqlContent_1) {
769
+ return __awaiter(this, arguments, void 0, function* (client, queryName, sqlContent, crud = false) {
706
770
  const queryInfoResult = yield (0, describe_query_1.parseSql)(client, sqlContent);
707
771
  if ((0, Either_1.isLeft)(queryInfoResult)) {
708
772
  return queryInfoResult;
709
773
  }
710
774
  const tsDescriptor = generateTsDescriptor(queryInfoResult.right);
711
- const tsContent = generateTsCodeForMySQL(tsDescriptor, queryName, target, crud);
775
+ const tsContent = generateTsCodeForMySQL(tsDescriptor, queryName, crud);
712
776
  return (0, Either_1.right)(tsContent);
713
777
  });
714
778
  }
715
779
  exports.generateTsFileFromContent = generateTsFileFromContent;
716
780
  function commaSeparator(length, index) {
717
- return length > 1 && index != length - 1 ? ',' : '';
781
+ return length > 1 && index !== length - 1 ? ',' : '';
718
782
  }
719
783
  //# sourceMappingURL=code-generator.js.map