typesql-cli 0.21.2 → 0.22.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.
- package/codegen/sqlite.d.ts.map +1 -1
- package/codegen/sqlite.js +16 -9
- package/codegen/sqlite.js.map +1 -1
- package/mysql-query-analyzer/traverse.d.ts +4 -0
- package/mysql-query-analyzer/traverse.d.ts.map +1 -1
- package/mysql-query-analyzer/traverse.js.map +1 -1
- package/package.json +1 -1
- package/sqlite-query-analyzer/parser.js +28 -2
- package/sqlite-query-analyzer/parser.js.map +1 -1
- package/sqlite-query-analyzer/traverse.js +18 -4
- package/sqlite-query-analyzer/traverse.js.map +1 -1
- package/code-generator.d.ts +0 -43
- package/code-generator.d.ts.map +0 -1
- package/code-generator.js +0 -755
- package/code-generator.js.map +0 -1
- package/code-generator2.d.ts +0 -10
- package/code-generator2.d.ts.map +0 -1
- package/code-generator2.js +0 -963
- package/code-generator2.js.map +0 -1
- package/codegen/code-generator2.d.ts +0 -10
- package/codegen/code-generator2.d.ts.map +0 -1
- package/codegen/code-generator2.js +0 -917
- package/codegen/code-generator2.js.map +0 -1
- package/codegen/codegen-util.d.ts +0 -1
- package/codegen/codegen-util.d.ts.map +0 -1
- package/codegen/codegen-util.js +0 -2
- package/codegen/codegen-util.js.map +0 -1
- package/codegen/generic/codegen-util.d.ts +0 -8
- package/codegen/generic/codegen-util.d.ts.map +0 -1
- package/codegen/generic/codegen-util.js +0 -89
- package/codegen/generic/codegen-util.js.map +0 -1
- package/codegen/postgres-pg.d.ts +0 -10
- package/codegen/postgres-pg.d.ts.map +0 -1
- package/codegen/postgres-pg.js +0 -917
- package/codegen/postgres-pg.js.map +0 -1
- package/codegen/sqlite-code-generator.d.ts +0 -15
- package/codegen/sqlite-code-generator.d.ts.map +0 -1
- package/codegen/sqlite-code-generator.js +0 -1049
- package/codegen/sqlite-code-generator.js.map +0 -1
- package/generic/codegen-util.d.ts +0 -8
- package/generic/codegen-util.d.ts.map +0 -1
- package/generic/codegen-util.js +0 -89
- package/generic/codegen-util.js.map +0 -1
- package/postgres-pg.d.ts +0 -10
- package/postgres-pg.d.ts.map +0 -1
- package/postgres-pg.js +0 -917
- package/postgres-pg.js.map +0 -1
- package/postgres-query-analyzer/nullability-checker.d.ts +0 -3
- package/postgres-query-analyzer/nullability-checker.d.ts.map +0 -1
- package/postgres-query-analyzer/nullability-checker.js +0 -110
- package/postgres-query-analyzer/nullability-checker.js.map +0 -1
- package/rescript.d.ts +0 -1
- package/rescript.d.ts.map +0 -1
- package/rescript.js +0 -2
- package/rescript.js.map +0 -1
- package/sqlite-query-analyzer/code-generator.d.ts +0 -15
- package/sqlite-query-analyzer/code-generator.d.ts.map +0 -1
- package/sqlite-query-analyzer/code-generator.js +0 -1142
- package/sqlite-query-analyzer/code-generator.js.map +0 -1
- package/sqlite-query-analyzer/sqlite-code-generator.d.ts +0 -15
- package/sqlite-query-analyzer/sqlite-code-generator.d.ts.map +0 -1
- package/sqlite-query-analyzer/sqlite-code-generator.js +0 -1049
- package/sqlite-query-analyzer/sqlite-code-generator.js.map +0 -1
- package/sqlite.d.ts +0 -43
- package/sqlite.d.ts.map +0 -1
- package/sqlite.js +0 -755
- package/sqlite.js.map +0 -1
|
@@ -1,1142 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.validateAndGenerateCode = validateAndGenerateCode;
|
|
7
|
-
exports.generateCrud = generateCrud;
|
|
8
|
-
exports.getQueryName = getQueryName;
|
|
9
|
-
exports.generateTsCode = generateTsCode;
|
|
10
|
-
exports.mapPostgrsFieldToTsField = mapPostgrsFieldToTsField;
|
|
11
|
-
exports.mapFieldToTsField = mapFieldToTsField;
|
|
12
|
-
exports.writeCollectFunction = writeCollectFunction;
|
|
13
|
-
const Either_1 = require("fp-ts/lib/Either");
|
|
14
|
-
const parser_1 = require("./parser");
|
|
15
|
-
const code_generator_1 = require("../code-generator");
|
|
16
|
-
const code_block_writer_1 = __importDefault(require("code-block-writer"));
|
|
17
|
-
const ts_nested_descriptor_1 = require("../ts-nested-descriptor");
|
|
18
|
-
const describe_query_1 = require("../describe-query");
|
|
19
|
-
const query_executor_1 = require("./query-executor");
|
|
20
|
-
const ts_dynamic_query_descriptor_1 = require("../ts-dynamic-query-descriptor");
|
|
21
|
-
const node_os_1 = require("node:os");
|
|
22
|
-
const sqlite_1 = require("../drivers/sqlite");
|
|
23
|
-
const postgres_1 = require("../dialects/postgres");
|
|
24
|
-
function validateAndGenerateCode(client, sql, queryName, sqliteDbSchema, isCrud = false) {
|
|
25
|
-
const { sql: processedSql } = (0, describe_query_1.preprocessSql)(sql, 'sqlite');
|
|
26
|
-
const explainSqlResult = (0, query_executor_1.explainSql)(client.client, processedSql);
|
|
27
|
-
if ((0, Either_1.isLeft)(explainSqlResult)) {
|
|
28
|
-
return (0, Either_1.left)({
|
|
29
|
-
name: 'Invalid sql',
|
|
30
|
-
description: explainSqlResult.left.description
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
const code = generateTsCode(sql, queryName, sqliteDbSchema, client.type, isCrud);
|
|
34
|
-
return code;
|
|
35
|
-
}
|
|
36
|
-
function mapToColumnInfo(col, checkOptional) {
|
|
37
|
-
const defaultValue = col.columnKey === 'PRI' && col.column_type === 'INTEGER' ? 'AUTOINCREMENT' : col.defaultValue;
|
|
38
|
-
const columnInfo = {
|
|
39
|
-
name: col.column,
|
|
40
|
-
notNull: col.notNull,
|
|
41
|
-
type: col.column_type,
|
|
42
|
-
table: col.table,
|
|
43
|
-
optional: checkOptional && (!col.notNull || defaultValue != null)
|
|
44
|
-
};
|
|
45
|
-
return columnInfo;
|
|
46
|
-
}
|
|
47
|
-
function generateCrud(client, queryType, tableName, dbSchema) {
|
|
48
|
-
const columns = dbSchema.filter((col) => col.table === tableName);
|
|
49
|
-
const columnInfo = columns.map((col) => mapToColumnInfo(col, queryType === 'Insert' || queryType === 'Update'));
|
|
50
|
-
const keys = columns.filter((col) => col.columnKey === 'PRI');
|
|
51
|
-
if (keys.length === 0) {
|
|
52
|
-
keys.push(...columns.filter((col) => col.columnKey === 'UNI'));
|
|
53
|
-
}
|
|
54
|
-
const keyColumnInfo = keys.map((key) => mapToColumnInfo(key, false)).map((col) => mapColumnToTsParameterDescriptor(col, client));
|
|
55
|
-
const resultColumns = mapColumns(client, queryType, columnInfo, false);
|
|
56
|
-
const params = columnInfo.map((col) => mapColumnToTsParameterDescriptor(col, client));
|
|
57
|
-
const tsDescriptor = {
|
|
58
|
-
sql: '',
|
|
59
|
-
queryType,
|
|
60
|
-
multipleRowsResult: false,
|
|
61
|
-
columns: resultColumns,
|
|
62
|
-
parameterNames: [],
|
|
63
|
-
parameters: queryType === 'Insert' ? params : keyColumnInfo,
|
|
64
|
-
data: queryType === 'Update' ? params.filter((param) => { var _a; return param.name !== ((_a = keyColumnInfo[0]) === null || _a === void 0 ? void 0 : _a.name); }) : []
|
|
65
|
-
};
|
|
66
|
-
const queryName = getQueryName(queryType, tableName);
|
|
67
|
-
const code = generateCodeFromTsDescriptor(client, queryName, tsDescriptor, true, tableName);
|
|
68
|
-
return code;
|
|
69
|
-
}
|
|
70
|
-
function getQueryName(queryType, tableName) {
|
|
71
|
-
const camelCaseName = (0, code_generator_1.convertToCamelCaseName)(tableName);
|
|
72
|
-
const captitalizedName = (0, code_generator_1.capitalize)(camelCaseName);
|
|
73
|
-
switch (queryType) {
|
|
74
|
-
case 'Select':
|
|
75
|
-
return `selectFrom${captitalizedName}`;
|
|
76
|
-
case 'Insert':
|
|
77
|
-
return `insertInto${captitalizedName}`;
|
|
78
|
-
case 'Update':
|
|
79
|
-
return `update${captitalizedName}`;
|
|
80
|
-
case 'Delete':
|
|
81
|
-
return `deleteFrom${captitalizedName}`;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
function generateTsCode(sql, queryName, sqliteDbSchema, client, isCrud = false) {
|
|
85
|
-
const schemaDefResult = (0, parser_1.parseSql)(sql, sqliteDbSchema);
|
|
86
|
-
if ((0, Either_1.isLeft)(schemaDefResult)) {
|
|
87
|
-
return schemaDefResult;
|
|
88
|
-
}
|
|
89
|
-
const tsDescriptor = createTsDescriptor(schemaDefResult.right, client);
|
|
90
|
-
const code = generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud);
|
|
91
|
-
return (0, Either_1.right)(code);
|
|
92
|
-
}
|
|
93
|
-
function createTsDescriptor(queryInfo, client) {
|
|
94
|
-
var _a;
|
|
95
|
-
const tsDescriptor = {
|
|
96
|
-
sql: queryInfo.sql,
|
|
97
|
-
queryType: queryInfo.queryType,
|
|
98
|
-
multipleRowsResult: queryInfo.multipleRowsResult,
|
|
99
|
-
returning: queryInfo.returning,
|
|
100
|
-
columns: mapColumns(client, queryInfo.queryType, queryInfo.columns, queryInfo.returning),
|
|
101
|
-
parameterNames: [],
|
|
102
|
-
parameters: queryInfo.parameters.map((param) => mapParameterToTsFieldDescriptor(param, client)),
|
|
103
|
-
data: (_a = queryInfo.data) === null || _a === void 0 ? void 0 : _a.map((param) => mapParameterToTsFieldDescriptor(param, client)),
|
|
104
|
-
orderByColumns: queryInfo.orderByColumns
|
|
105
|
-
};
|
|
106
|
-
if (queryInfo.nestedInfo) {
|
|
107
|
-
const nestedDescriptor2 = queryInfo.nestedInfo.map((relation) => {
|
|
108
|
-
const tsRelation = {
|
|
109
|
-
groupIndex: relation.groupIndex,
|
|
110
|
-
name: relation.name,
|
|
111
|
-
fields: relation.fields.map((field) => mapFieldToTsField(queryInfo.columns, field, client)),
|
|
112
|
-
relations: relation.relations.map((relation) => (0, ts_nested_descriptor_1.mapToTsRelation2)(relation))
|
|
113
|
-
};
|
|
114
|
-
return tsRelation;
|
|
115
|
-
});
|
|
116
|
-
tsDescriptor.nestedDescriptor2 = nestedDescriptor2;
|
|
117
|
-
}
|
|
118
|
-
tsDescriptor.dynamicQuery2 = queryInfo.dynamicSqlQuery2;
|
|
119
|
-
return tsDescriptor;
|
|
120
|
-
}
|
|
121
|
-
function mapColumns(client, queryType, columns, returning = false) {
|
|
122
|
-
const resultColumns = getInsertUpdateResult(client);
|
|
123
|
-
if (queryType === 'Insert' && !returning) {
|
|
124
|
-
return resultColumns;
|
|
125
|
-
}
|
|
126
|
-
if (queryType === 'Update' || queryType === 'Delete') {
|
|
127
|
-
return [resultColumns[0]];
|
|
128
|
-
}
|
|
129
|
-
const escapedColumnsNames = (0, code_generator_1.renameInvalidNames)(columns.map((col) => col.name));
|
|
130
|
-
return columns.map((col, index) => mapColumnToTsFieldDescriptor(Object.assign(Object.assign({}, col), { name: escapedColumnsNames[index] }), client));
|
|
131
|
-
}
|
|
132
|
-
function getInsertUpdateResult(client) {
|
|
133
|
-
const sqliteInsertColumns = [
|
|
134
|
-
{
|
|
135
|
-
name: 'changes',
|
|
136
|
-
tsType: 'number',
|
|
137
|
-
notNull: true
|
|
138
|
-
},
|
|
139
|
-
{
|
|
140
|
-
name: 'lastInsertRowid',
|
|
141
|
-
tsType: 'number',
|
|
142
|
-
notNull: true
|
|
143
|
-
}
|
|
144
|
-
];
|
|
145
|
-
const libSqlInsertColumns = [
|
|
146
|
-
{
|
|
147
|
-
name: 'rowsAffected',
|
|
148
|
-
tsType: 'number',
|
|
149
|
-
notNull: true
|
|
150
|
-
},
|
|
151
|
-
{
|
|
152
|
-
name: 'lastInsertRowid',
|
|
153
|
-
tsType: 'number',
|
|
154
|
-
notNull: true
|
|
155
|
-
}
|
|
156
|
-
];
|
|
157
|
-
const d1InsertColumns = [
|
|
158
|
-
{
|
|
159
|
-
name: 'changes',
|
|
160
|
-
tsType: 'number',
|
|
161
|
-
notNull: true
|
|
162
|
-
},
|
|
163
|
-
{
|
|
164
|
-
name: 'last_row_id',
|
|
165
|
-
tsType: 'number',
|
|
166
|
-
notNull: true
|
|
167
|
-
}
|
|
168
|
-
];
|
|
169
|
-
switch (client) {
|
|
170
|
-
case 'better-sqlite3':
|
|
171
|
-
case 'bun:sqlite':
|
|
172
|
-
return sqliteInsertColumns;
|
|
173
|
-
case 'libsql':
|
|
174
|
-
return libSqlInsertColumns;
|
|
175
|
-
case 'd1':
|
|
176
|
-
return d1InsertColumns;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
function mapPostgrsFieldToTsField(columns, field) {
|
|
180
|
-
const tsField = {
|
|
181
|
-
name: field.name,
|
|
182
|
-
index: field.index,
|
|
183
|
-
tsType: (0, postgres_1.mapColumnType)(columns[field.index].type),
|
|
184
|
-
notNull: columns[field.index].notNull
|
|
185
|
-
};
|
|
186
|
-
return tsField;
|
|
187
|
-
}
|
|
188
|
-
function mapFieldToTsField(columns, field, client) {
|
|
189
|
-
const tsField = {
|
|
190
|
-
name: field.name,
|
|
191
|
-
index: field.index,
|
|
192
|
-
tsType: (0, sqlite_1.mapColumnType)(columns[field.index].type, client),
|
|
193
|
-
notNull: columns[field.index].notNull
|
|
194
|
-
};
|
|
195
|
-
return tsField;
|
|
196
|
-
}
|
|
197
|
-
function mapParameterToTsFieldDescriptor(col, client) {
|
|
198
|
-
const tsDesc = {
|
|
199
|
-
name: col.name,
|
|
200
|
-
tsType: (0, sqlite_1.mapColumnType)(col.columnType, client),
|
|
201
|
-
notNull: col.notNull ? col.notNull : false,
|
|
202
|
-
toDriver: parameterToDriver(col),
|
|
203
|
-
isArray: false
|
|
204
|
-
};
|
|
205
|
-
return tsDesc;
|
|
206
|
-
}
|
|
207
|
-
function parameterToDriver(param) {
|
|
208
|
-
if (param.columnType === 'DATE') {
|
|
209
|
-
return `${param.name}?.toISOString().split('T')[0]`;
|
|
210
|
-
}
|
|
211
|
-
if (param.columnType === 'DATE_TIME') {
|
|
212
|
-
return `${param.name}?.toISOString().split('.')[0].replace('T', ' ')`;
|
|
213
|
-
}
|
|
214
|
-
return param.name;
|
|
215
|
-
}
|
|
216
|
-
function columnToDriver(col) {
|
|
217
|
-
if (col.type === 'DATE') {
|
|
218
|
-
return `${col.name}?.toISOString().split('T')[0]`;
|
|
219
|
-
}
|
|
220
|
-
if (col.type === 'DATE_TIME') {
|
|
221
|
-
return `${col.name}?.toISOString().split('.')[0].replace('T', ' ')`;
|
|
222
|
-
}
|
|
223
|
-
return col.name;
|
|
224
|
-
}
|
|
225
|
-
function mapColumnToTsFieldDescriptor(col, client) {
|
|
226
|
-
const tsDesc = {
|
|
227
|
-
name: col.name,
|
|
228
|
-
tsType: (0, sqlite_1.mapColumnType)(col.type, client),
|
|
229
|
-
notNull: col.notNull,
|
|
230
|
-
optional: col.optional
|
|
231
|
-
};
|
|
232
|
-
return tsDesc;
|
|
233
|
-
}
|
|
234
|
-
function mapColumnToTsParameterDescriptor(col, client) {
|
|
235
|
-
const tsDesc = {
|
|
236
|
-
name: col.name,
|
|
237
|
-
tsType: (0, sqlite_1.mapColumnType)(col.type, client),
|
|
238
|
-
notNull: col.notNull,
|
|
239
|
-
optional: col.optional,
|
|
240
|
-
toDriver: columnToDriver(col),
|
|
241
|
-
isArray: false
|
|
242
|
-
};
|
|
243
|
-
return tsDesc;
|
|
244
|
-
}
|
|
245
|
-
function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud = false, tableName = '') {
|
|
246
|
-
var _a, _b;
|
|
247
|
-
const writer = new code_block_writer_1.default({
|
|
248
|
-
useTabs: true
|
|
249
|
-
});
|
|
250
|
-
const camelCaseName = (0, code_generator_1.convertToCamelCaseName)(queryName);
|
|
251
|
-
const capitalizedName = (0, code_generator_1.capitalize)(camelCaseName);
|
|
252
|
-
const queryType = tsDescriptor.queryType;
|
|
253
|
-
const sql = tsDescriptor.sql;
|
|
254
|
-
const dataTypeName = `${capitalizedName}Data`;
|
|
255
|
-
const paramsTypeName = `${capitalizedName}Params`;
|
|
256
|
-
const resultTypeName = `${capitalizedName}Result`;
|
|
257
|
-
const dynamicParamsTypeName = `${capitalizedName}DynamicParams`;
|
|
258
|
-
const selectColumnsTypeName = `${capitalizedName}Select`;
|
|
259
|
-
const whereTypeName = `${capitalizedName}Where`;
|
|
260
|
-
const orderByTypeName = `${capitalizedName}OrderBy`;
|
|
261
|
-
const generateOrderBy = tsDescriptor.orderByColumns != null && tsDescriptor.orderByColumns.length > 0;
|
|
262
|
-
const uniqueParams = (0, code_generator_1.removeDuplicatedParameters2)(tsDescriptor.parameters);
|
|
263
|
-
const uniqueUpdateParams = (0, code_generator_1.removeDuplicatedParameters2)(tsDescriptor.data || []);
|
|
264
|
-
const orderByField = generateOrderBy ? `orderBy: [${orderByTypeName}, 'asc' | 'desc'][]` : undefined;
|
|
265
|
-
const paramsTypes = (0, code_generator_1.removeDuplicatedParameters2)(tsDescriptor.dynamicQuery2 == null ? tsDescriptor.parameters : (0, ts_dynamic_query_descriptor_1.mapToDynamicParams)(tsDescriptor.parameters));
|
|
266
|
-
let functionArguments = client === 'better-sqlite3' || client === 'bun:sqlite'
|
|
267
|
-
? 'db: Database'
|
|
268
|
-
: client === 'd1'
|
|
269
|
-
? 'db: D1Database'
|
|
270
|
-
: 'client: Client | Transaction';
|
|
271
|
-
if (queryType === 'Update' && uniqueUpdateParams.length > 0) {
|
|
272
|
-
functionArguments += `, data: ${dataTypeName}`;
|
|
273
|
-
}
|
|
274
|
-
if (tsDescriptor.dynamicQuery2 == null) {
|
|
275
|
-
functionArguments += tsDescriptor.parameters.length > 0 || generateOrderBy ? `, params: ${paramsTypeName}` : '';
|
|
276
|
-
}
|
|
277
|
-
else {
|
|
278
|
-
functionArguments += `, ${orderByField ? 'params' : 'params?'}: ${dynamicParamsTypeName}`;
|
|
279
|
-
}
|
|
280
|
-
const orNull = queryType === 'Select' ? ' | null' : '';
|
|
281
|
-
const returnType = tsDescriptor.multipleRowsResult ? `${resultTypeName}[]` : `${resultTypeName}${orNull}`;
|
|
282
|
-
const allParameters = (((_a = tsDescriptor.data) === null || _a === void 0 ? void 0 : _a.map((param) => fromDriver('data', param))) || []).concat(tsDescriptor.parameters.map((param) => fromDriver('params', param)));
|
|
283
|
-
const queryParamsWithoutBrackets = allParameters.length > 0 ? `${allParameters.join(', ')}` : '';
|
|
284
|
-
const queryParams = queryParamsWithoutBrackets !== '' ? `[${queryParamsWithoutBrackets}]` : '';
|
|
285
|
-
const isDynamicQuery = tsDescriptor.dynamicQuery2 != null;
|
|
286
|
-
writeImports(writer, client, isDynamicQuery);
|
|
287
|
-
if (tsDescriptor.dynamicQuery2 != null) {
|
|
288
|
-
writer.blankLine();
|
|
289
|
-
writer.write(`export type ${dynamicParamsTypeName} = `).block(() => {
|
|
290
|
-
writer.writeLine(`select?: ${selectColumnsTypeName};`);
|
|
291
|
-
if (paramsTypes.length > 0) {
|
|
292
|
-
writer.writeLine(`params?: ${paramsTypeName};`);
|
|
293
|
-
}
|
|
294
|
-
writer.writeLine(`where?: ${whereTypeName}[];`);
|
|
295
|
-
if (orderByField) {
|
|
296
|
-
writer.writeLine(`${orderByField};`);
|
|
297
|
-
}
|
|
298
|
-
});
|
|
299
|
-
writer.blankLine();
|
|
300
|
-
(0, code_generator_1.writeTypeBlock)(writer, paramsTypes, paramsTypeName, false, tsDescriptor.dynamicQuery2 ? undefined : orderByField);
|
|
301
|
-
const resultTypes = tsDescriptor.dynamicQuery2 == null ? tsDescriptor.columns : (0, ts_dynamic_query_descriptor_1.mapToDynamicResultColumns)(tsDescriptor.columns);
|
|
302
|
-
(0, code_generator_1.writeTypeBlock)(writer, resultTypes, resultTypeName, false);
|
|
303
|
-
const selectFields = (0, ts_dynamic_query_descriptor_1.mapToDynamicSelectColumns)(tsDescriptor.columns);
|
|
304
|
-
(0, code_generator_1.writeTypeBlock)(writer, selectFields, selectColumnsTypeName, false);
|
|
305
|
-
writer.write('const selectFragments = ').inlineBlock(() => {
|
|
306
|
-
var _a;
|
|
307
|
-
(_a = tsDescriptor.dynamicQuery2) === null || _a === void 0 ? void 0 : _a.select.forEach((fragment, index) => {
|
|
308
|
-
const field = tsDescriptor.columns[index].name;
|
|
309
|
-
writer.writeLine(`${field}: \`${fragment.fragmentWitoutAlias}\`,`);
|
|
310
|
-
});
|
|
311
|
-
});
|
|
312
|
-
writer.write(' as const;');
|
|
313
|
-
writer.blankLine();
|
|
314
|
-
writer.writeLine(`const NumericOperatorList = ['=', '<>', '>', '<', '>=', '<='] as const;`);
|
|
315
|
-
writer.writeLine('type NumericOperator = typeof NumericOperatorList[number];');
|
|
316
|
-
if ((0, code_generator_1.hasStringColumn)(tsDescriptor.columns)) {
|
|
317
|
-
writer.writeLine(`type StringOperator = '=' | '<>' | '>' | '<' | '>=' | '<=' | 'LIKE';`);
|
|
318
|
-
}
|
|
319
|
-
writer.writeLine(`type SetOperator = 'IN' | 'NOT IN';`);
|
|
320
|
-
writer.writeLine(`type BetweenOperator = 'BETWEEN';`);
|
|
321
|
-
writer.blankLine();
|
|
322
|
-
writer.write(`export type ${whereTypeName} =`).indent(() => {
|
|
323
|
-
tsDescriptor.columns.forEach((col) => {
|
|
324
|
-
writer.writeLine(`| ['${col.name}', ${(0, code_generator_1.getOperator)(col.tsType)}, ${col.tsType} | null]`);
|
|
325
|
-
writer.writeLine(`| ['${col.name}', SetOperator, ${col.tsType}[]]`);
|
|
326
|
-
writer.writeLine(`| ['${col.name}', BetweenOperator, ${col.tsType} | null, ${col.tsType} | null]`);
|
|
327
|
-
});
|
|
328
|
-
});
|
|
329
|
-
writer.blankLine();
|
|
330
|
-
const asyncModified = client === 'libsql' || client === 'd1' ? 'async ' : '';
|
|
331
|
-
const returnTypeModifier = client === 'libsql' || client === 'd1' ? `Promise<${returnType}>` : returnType;
|
|
332
|
-
writer.write(`export ${asyncModified}function ${camelCaseName}(${functionArguments}): ${returnTypeModifier}`).block(() => {
|
|
333
|
-
var _a, _b, _c, _d, _e, _f;
|
|
334
|
-
writer.write('const where = whereConditionsToObject(params?.where);').newLine();
|
|
335
|
-
if (orderByField != null) {
|
|
336
|
-
writer.writeLine('const orderBy = orderByToObject(params.orderBy);');
|
|
337
|
-
}
|
|
338
|
-
writer.write('const paramsValues: any = [];').newLine();
|
|
339
|
-
const hasCte = (((_a = tsDescriptor.dynamicQuery2) === null || _a === void 0 ? void 0 : _a.with.length) || 0) > 0;
|
|
340
|
-
if (hasCte) {
|
|
341
|
-
writer.writeLine('const withClause = [];');
|
|
342
|
-
(_b = tsDescriptor.dynamicQuery2) === null || _b === void 0 ? void 0 : _b.with.forEach((withFragment, index, array) => {
|
|
343
|
-
var _a;
|
|
344
|
-
const selectConditions = withFragment.dependOnFields.map((fieldIndex) => `params.select.${tsDescriptor.columns[fieldIndex].name}`);
|
|
345
|
-
if (selectConditions.length > 0) {
|
|
346
|
-
selectConditions.unshift('params?.select == null');
|
|
347
|
-
}
|
|
348
|
-
const whereConditions = withFragment.dependOnFields.map((fieldIndex) => `where.${tsDescriptor.columns[fieldIndex].name} != null`);
|
|
349
|
-
const orderByConditions = ((_a = withFragment.dependOnOrderBy) === null || _a === void 0 ? void 0 : _a.map((orderBy) => `orderBy['${orderBy}'] != null`)) || [];
|
|
350
|
-
const allConditions = [...selectConditions, ...whereConditions, ...orderByConditions];
|
|
351
|
-
const paramValues = withFragment.parameters.map((paramIndex) => {
|
|
352
|
-
const param = tsDescriptor.parameters[paramIndex];
|
|
353
|
-
return fromDriver('params?.params?', param);
|
|
354
|
-
});
|
|
355
|
-
if (allConditions.length > 0) {
|
|
356
|
-
writer.write(`if (${allConditions.join(`${node_os_1.EOL}\t|| `)})`).block(() => {
|
|
357
|
-
writer.write(`withClause.push(\`${withFragment.fragment}\`);`);
|
|
358
|
-
paramValues.forEach((paramValues) => {
|
|
359
|
-
writer.writeLine(`paramsValues.push(${paramValues});`);
|
|
360
|
-
});
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
else {
|
|
364
|
-
writer.write(`withClause.push(\`${withFragment.fragment}\`);`);
|
|
365
|
-
paramValues.forEach((paramValues) => {
|
|
366
|
-
writer.writeLine(`paramsValues.push(${paramValues});`);
|
|
367
|
-
});
|
|
368
|
-
}
|
|
369
|
-
});
|
|
370
|
-
writer.write(`let sql = 'WITH ' + withClause.join(',' + EOL) + EOL + 'SELECT';`).newLine();
|
|
371
|
-
}
|
|
372
|
-
else {
|
|
373
|
-
writer.write(`let sql = 'SELECT';`).newLine();
|
|
374
|
-
}
|
|
375
|
-
(_c = tsDescriptor.dynamicQuery2) === null || _c === void 0 ? void 0 : _c.select.forEach((select, index) => {
|
|
376
|
-
writer.write(`if (params?.select == null || params.select.${tsDescriptor.columns[index].name})`).block(() => {
|
|
377
|
-
writer.writeLine(`sql = appendSelect(sql, \`${select.fragment}\`);`);
|
|
378
|
-
select.parameters.forEach((param) => {
|
|
379
|
-
writer.writeLine(`paramsValues.push(params?.params?.${param} ?? null);`);
|
|
380
|
-
});
|
|
381
|
-
});
|
|
382
|
-
});
|
|
383
|
-
(_d = tsDescriptor.dynamicQuery2) === null || _d === void 0 ? void 0 : _d.from.forEach((from, index) => {
|
|
384
|
-
var _a;
|
|
385
|
-
if (index === 0) {
|
|
386
|
-
writer.writeLine(`sql += EOL + \`${from.fragment}\`;`);
|
|
387
|
-
}
|
|
388
|
-
else {
|
|
389
|
-
const selectConditions = from.dependOnFields.map((fieldIndex) => `params.select.${tsDescriptor.columns[fieldIndex].name}`);
|
|
390
|
-
if (selectConditions.length > 0) {
|
|
391
|
-
selectConditions.unshift('params?.select == null');
|
|
392
|
-
}
|
|
393
|
-
const whereConditions = from.dependOnFields.map((fieldIndex) => `where.${tsDescriptor.columns[fieldIndex].name} != null`);
|
|
394
|
-
const orderByConditions = ((_a = from.dependOnOrderBy) === null || _a === void 0 ? void 0 : _a.map((orderBy) => `orderBy['${orderBy}'] != null`)) || [];
|
|
395
|
-
const allConditions = [...selectConditions, ...whereConditions, ...orderByConditions];
|
|
396
|
-
const paramValues = from.parameters.map((paramIndex) => {
|
|
397
|
-
const param = tsDescriptor.parameters[paramIndex];
|
|
398
|
-
return fromDriver('params?.params?', param);
|
|
399
|
-
});
|
|
400
|
-
if (allConditions.length > 0) {
|
|
401
|
-
writer.write(`if (${allConditions.join(`${node_os_1.EOL}\t|| `)})`).block(() => {
|
|
402
|
-
writer.write(`sql += EOL + \`${from.fragment}\`;`);
|
|
403
|
-
paramValues.forEach((paramValues) => {
|
|
404
|
-
writer.writeLine(`paramsValues.push(${paramValues});`);
|
|
405
|
-
});
|
|
406
|
-
});
|
|
407
|
-
}
|
|
408
|
-
else {
|
|
409
|
-
writer.write(`sql += EOL + \`${from.fragment}\`;`);
|
|
410
|
-
paramValues.forEach((paramValues) => {
|
|
411
|
-
writer.writeLine(`paramsValues.push(${paramValues});`);
|
|
412
|
-
});
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
});
|
|
416
|
-
writer.writeLine('sql += EOL + `WHERE 1 = 1`;');
|
|
417
|
-
(_e = tsDescriptor.dynamicQuery2) === null || _e === void 0 ? void 0 : _e.where.forEach((fragment) => {
|
|
418
|
-
const paramValues = fragment.parameters.map((paramIndex) => {
|
|
419
|
-
const param = tsDescriptor.parameters[paramIndex];
|
|
420
|
-
return `${fromDriver('params?.params?', param)} ?? null`;
|
|
421
|
-
});
|
|
422
|
-
writer.writeLine(`sql += EOL + \`${fragment.fragment}\`;`);
|
|
423
|
-
paramValues.forEach((paramValues) => {
|
|
424
|
-
writer.writeLine(`paramsValues.push(${paramValues});`);
|
|
425
|
-
});
|
|
426
|
-
});
|
|
427
|
-
writer.write('params?.where?.forEach(condition => ').inlineBlock(() => {
|
|
428
|
-
var _a;
|
|
429
|
-
writer.writeLine('const where = whereCondition(condition);');
|
|
430
|
-
(_a = tsDescriptor.dynamicQuery2) === null || _a === void 0 ? void 0 : _a.select.forEach((select, index) => {
|
|
431
|
-
if (select.parameters.length > 0) {
|
|
432
|
-
writer.write(`if (condition[0] == '${tsDescriptor.columns[index].name}')`).block(() => {
|
|
433
|
-
select.parameters.forEach((param) => {
|
|
434
|
-
writer.writeLine(`paramsValues.push(params?.params?.${param} ?? null);`);
|
|
435
|
-
});
|
|
436
|
-
});
|
|
437
|
-
}
|
|
438
|
-
});
|
|
439
|
-
writer.write('if (where?.hasValue)').block(() => {
|
|
440
|
-
writer.writeLine(`sql += EOL + 'AND ' + where.sql;`);
|
|
441
|
-
writer.write('paramsValues.push(...where.values);');
|
|
442
|
-
});
|
|
443
|
-
});
|
|
444
|
-
writer.write(');').newLine();
|
|
445
|
-
if (tsDescriptor.orderByColumns) {
|
|
446
|
-
writer.writeLine('sql += EOL + `ORDER BY ${escapeOrderBy(params.orderBy)}`;');
|
|
447
|
-
}
|
|
448
|
-
const limitOffset = (_f = tsDescriptor.dynamicQuery2) === null || _f === void 0 ? void 0 : _f.limitOffset;
|
|
449
|
-
if (limitOffset) {
|
|
450
|
-
writer.writeLine(`sql += EOL + \`${limitOffset.fragment}\`;`);
|
|
451
|
-
limitOffset.parameters.forEach((param) => {
|
|
452
|
-
writer.writeLine(`paramsValues.push(params?.params?.${param} ?? null);`);
|
|
453
|
-
});
|
|
454
|
-
}
|
|
455
|
-
if (client === 'better-sqlite3') {
|
|
456
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
457
|
-
writer.indent().write('.raw(true)').newLine();
|
|
458
|
-
writer.indent().write('.all(paramsValues)').newLine();
|
|
459
|
-
writer
|
|
460
|
-
.indent()
|
|
461
|
-
.write(`.map(data => mapArrayTo${resultTypeName}(data, params?.select))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
|
|
462
|
-
}
|
|
463
|
-
if (client === 'bun:sqlite') {
|
|
464
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
465
|
-
writer.indent().write('.values(paramsValues)').newLine();
|
|
466
|
-
writer
|
|
467
|
-
.indent()
|
|
468
|
-
.write(`.map(data => mapArrayTo${resultTypeName}(data, params?.select))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
|
|
469
|
-
}
|
|
470
|
-
if (client === 'd1') {
|
|
471
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
472
|
-
writer.indent().write('.bind(...paramsValues)').newLine();
|
|
473
|
-
writer.indent().write('.raw()').newLine();
|
|
474
|
-
writer
|
|
475
|
-
.indent()
|
|
476
|
-
.write(`.then(rows => rows.map(row => mapArrayTo${resultTypeName}(row, params?.select)))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
|
|
477
|
-
}
|
|
478
|
-
if (client === 'libsql') {
|
|
479
|
-
writer.write('return client.execute({ sql, args: paramsValues })').newLine();
|
|
480
|
-
writer.indent().write('.then(res => res.rows)').newLine();
|
|
481
|
-
writer
|
|
482
|
-
.indent()
|
|
483
|
-
.write(`.then(rows => rows.map(row => mapArrayTo${resultTypeName}(row, params?.select)))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
|
|
484
|
-
}
|
|
485
|
-
});
|
|
486
|
-
writer.blankLine();
|
|
487
|
-
writer.write(`function mapArrayTo${resultTypeName}(data: any, select?: ${selectColumnsTypeName})`).block(() => {
|
|
488
|
-
writer.writeLine(`const result = {} as ${resultTypeName};`);
|
|
489
|
-
writer.writeLine('let rowIndex = -1;');
|
|
490
|
-
tsDescriptor.columns.forEach((tsField) => {
|
|
491
|
-
writer.write(`if (select == null || select.${tsField.name})`).block(() => {
|
|
492
|
-
writer.writeLine('rowIndex++;');
|
|
493
|
-
writer.writeLine(`result.${tsField.name} = ${toDriver('data[rowIndex]', tsField)};`);
|
|
494
|
-
});
|
|
495
|
-
});
|
|
496
|
-
writer.write('return result;');
|
|
497
|
-
});
|
|
498
|
-
writer.blankLine();
|
|
499
|
-
writer.write('function appendSelect(sql: string, selectField: string)').block(() => {
|
|
500
|
-
writer.write(`if (sql.toUpperCase().endsWith('SELECT'))`).block(() => {
|
|
501
|
-
writer.writeLine('return sql + EOL + selectField;');
|
|
502
|
-
});
|
|
503
|
-
writer.write('else').block(() => {
|
|
504
|
-
writer.writeLine(`return sql + ', ' + EOL + selectField;`);
|
|
505
|
-
});
|
|
506
|
-
});
|
|
507
|
-
writer.blankLine();
|
|
508
|
-
writer.write(`function whereConditionsToObject(whereConditions?: ${whereTypeName}[])`).block(() => {
|
|
509
|
-
writer.writeLine('const obj = {} as any;');
|
|
510
|
-
writer.write('whereConditions?.forEach(condition => ').inlineBlock(() => {
|
|
511
|
-
writer.writeLine('const where = whereCondition(condition);');
|
|
512
|
-
writer.write('if (where?.hasValue) ').block(() => {
|
|
513
|
-
writer.writeLine('obj[condition[0]] = true;');
|
|
514
|
-
});
|
|
515
|
-
});
|
|
516
|
-
writer.write(');');
|
|
517
|
-
writer.writeLine('return obj;');
|
|
518
|
-
});
|
|
519
|
-
if (orderByField != null) {
|
|
520
|
-
writer.blankLine();
|
|
521
|
-
writer.write(`function orderByToObject(orderBy: ${dynamicParamsTypeName}['orderBy'])`).block(() => {
|
|
522
|
-
writer.writeLine('const obj = {} as any;');
|
|
523
|
-
writer.write('orderBy?.forEach(order => ').inlineBlock(() => {
|
|
524
|
-
writer.writeLine('obj[order[0]] = true;');
|
|
525
|
-
});
|
|
526
|
-
writer.write(');');
|
|
527
|
-
writer.writeLine('return obj;');
|
|
528
|
-
});
|
|
529
|
-
}
|
|
530
|
-
writer.blankLine();
|
|
531
|
-
writer.write('type WhereConditionResult = ').block(() => {
|
|
532
|
-
writer.writeLine('sql: string;');
|
|
533
|
-
writer.writeLine('hasValue: boolean;');
|
|
534
|
-
writer.writeLine('values: any[];');
|
|
535
|
-
});
|
|
536
|
-
writer.blankLine();
|
|
537
|
-
writer.write(`function whereCondition(condition: ${whereTypeName}): WhereConditionResult | undefined `).block(() => {
|
|
538
|
-
writer.blankLine();
|
|
539
|
-
writer.writeLine('const selectFragment = selectFragments[condition[0]];');
|
|
540
|
-
writer.writeLine('const operator = condition[1];');
|
|
541
|
-
writer.blankLine();
|
|
542
|
-
if ((0, code_generator_1.hasStringColumn)(tsDescriptor.columns)) {
|
|
543
|
-
writer.write(`if (operator == 'LIKE') `).block(() => {
|
|
544
|
-
writer.write('return ').block(() => {
|
|
545
|
-
writer.writeLine("sql: `${selectFragment} LIKE concat('%', ?, '%')`,");
|
|
546
|
-
writer.writeLine('hasValue: condition[2] != null,');
|
|
547
|
-
writer.writeLine('values: [condition[2]]');
|
|
548
|
-
});
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
writer.write(`if (operator == 'BETWEEN') `).block(() => {
|
|
552
|
-
if ((0, code_generator_1.hasDateColumn)(tsDescriptor.columns)) {
|
|
553
|
-
writer.writeLine('const value1 = isDate(condition[2]) ? condition[2]?.toISOString() : condition[2];');
|
|
554
|
-
writer.writeLine('const value2 = isDate(condition[3]) ? condition[3]?.toISOString() : condition[3];');
|
|
555
|
-
writer.writeLine(`const param = isDate(condition[2]) && isDate(condition[3]) ? 'date(?)' : '?';`);
|
|
556
|
-
writer.write('return ').block(() => {
|
|
557
|
-
writer.writeLine('sql: `${selectFragment} BETWEEN ${param} AND ${param}`,');
|
|
558
|
-
writer.writeLine('hasValue: value1 != null && value2 != null,');
|
|
559
|
-
writer.writeLine('values: [value1, value2]');
|
|
560
|
-
});
|
|
561
|
-
}
|
|
562
|
-
else {
|
|
563
|
-
writer.write('return ').block(() => {
|
|
564
|
-
writer.writeLine('sql: `${selectFragment} BETWEEN ? AND ?`,');
|
|
565
|
-
writer.writeLine('hasValue: condition[2] != null && condition[3] != null,');
|
|
566
|
-
writer.writeLine('values: [condition[2], condition[3]]');
|
|
567
|
-
});
|
|
568
|
-
}
|
|
569
|
-
});
|
|
570
|
-
writer.write(`if (operator == 'IN' || operator == 'NOT IN') `).block(() => {
|
|
571
|
-
if ((0, code_generator_1.hasDateColumn)(tsDescriptor.columns)) {
|
|
572
|
-
writer.write('return ').block(() => {
|
|
573
|
-
writer.writeLine("sql: `${selectFragment} ${operator} (${condition[2]?.map(value => isDate(value) ? 'date(?)' : '?').join(', ')})`,");
|
|
574
|
-
writer.writeLine('hasValue: condition[2] != null && condition[2].length > 0,');
|
|
575
|
-
writer.writeLine('values: condition[2].map(value => isDate(value) ? value.toISOString() : value)');
|
|
576
|
-
});
|
|
577
|
-
}
|
|
578
|
-
else {
|
|
579
|
-
writer.write('return ').block(() => {
|
|
580
|
-
writer.writeLine("sql: `${selectFragment} ${operator} (${condition[2]?.map(_ => '?').join(', ')})`,");
|
|
581
|
-
writer.writeLine('hasValue: condition[2] != null && condition[2].length > 0,');
|
|
582
|
-
writer.writeLine('values: condition[2]');
|
|
583
|
-
});
|
|
584
|
-
}
|
|
585
|
-
});
|
|
586
|
-
writer.write('if (NumericOperatorList.includes(operator)) ').block(() => {
|
|
587
|
-
if ((0, code_generator_1.hasDateColumn)(tsDescriptor.columns)) {
|
|
588
|
-
writer.writeLine('const value = isDate(condition[2]) ? condition[2]?.toISOString() : condition[2];');
|
|
589
|
-
writer.writeLine(`const param = isDate(condition[2]) ? 'date(?)' : '?';`);
|
|
590
|
-
writer.write('return ').block(() => {
|
|
591
|
-
writer.writeLine('sql: `${selectFragment} ${operator} ${param}`,');
|
|
592
|
-
writer.writeLine('hasValue: value != null,');
|
|
593
|
-
writer.writeLine('values: [value]');
|
|
594
|
-
});
|
|
595
|
-
}
|
|
596
|
-
else {
|
|
597
|
-
writer.write('return ').block(() => {
|
|
598
|
-
writer.writeLine('sql: `${selectFragment} ${operator} ?`,');
|
|
599
|
-
writer.writeLine('hasValue: condition[2] != null,');
|
|
600
|
-
writer.writeLine('values: [condition[2]]');
|
|
601
|
-
});
|
|
602
|
-
}
|
|
603
|
-
});
|
|
604
|
-
writer.writeLine('return undefined;');
|
|
605
|
-
});
|
|
606
|
-
if ((0, code_generator_1.hasDateColumn)(tsDescriptor.columns)) {
|
|
607
|
-
writer.blankLine();
|
|
608
|
-
writer.write('function isDate(value: any): value is Date').block(() => {
|
|
609
|
-
writer.writeLine('return value instanceof Date;');
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
if (tsDescriptor.dynamicQuery2 == null) {
|
|
614
|
-
if (uniqueUpdateParams.length > 0) {
|
|
615
|
-
writer.blankLine();
|
|
616
|
-
writer.write(`export type ${dataTypeName} =`).block(() => {
|
|
617
|
-
uniqueUpdateParams.forEach((field) => {
|
|
618
|
-
const optionalOp = field.optional ? '?' : '';
|
|
619
|
-
const orNull = field.notNull ? '' : ' | null';
|
|
620
|
-
writer.writeLine(`${field.name}${optionalOp}: ${field.tsType}${orNull};`);
|
|
621
|
-
});
|
|
622
|
-
});
|
|
623
|
-
}
|
|
624
|
-
if (uniqueParams.length > 0 || generateOrderBy) {
|
|
625
|
-
writer.blankLine();
|
|
626
|
-
writer.write(`export type ${paramsTypeName} =`).block(() => {
|
|
627
|
-
uniqueParams.forEach((field) => {
|
|
628
|
-
const optionalOp = field.optional ? '?' : '';
|
|
629
|
-
const orNull = field.notNull ? '' : ' | null';
|
|
630
|
-
writer.writeLine(`${field.name}${optionalOp}: ${field.tsType}${orNull};`);
|
|
631
|
-
});
|
|
632
|
-
if (generateOrderBy) {
|
|
633
|
-
writer.writeLine(`orderBy: [${orderByTypeName}, 'asc' | 'desc'][];`);
|
|
634
|
-
}
|
|
635
|
-
});
|
|
636
|
-
}
|
|
637
|
-
writer.blankLine();
|
|
638
|
-
writer.write(`export type ${resultTypeName} =`).block(() => {
|
|
639
|
-
tsDescriptor.columns.forEach((field) => {
|
|
640
|
-
const optionalOp = field.notNull ? '' : '?';
|
|
641
|
-
writer.writeLine(`${field.name}${optionalOp}: ${field.tsType};`);
|
|
642
|
-
});
|
|
643
|
-
});
|
|
644
|
-
writer.blankLine();
|
|
645
|
-
}
|
|
646
|
-
if (isCrud) {
|
|
647
|
-
const crudFunction = client === 'libsql' || client === 'd1'
|
|
648
|
-
? `async function ${camelCaseName}(${functionArguments}): Promise<${returnType}>`
|
|
649
|
-
: `function ${camelCaseName}(${functionArguments}): ${returnType}`;
|
|
650
|
-
writer.write(`export ${crudFunction}`).block(() => {
|
|
651
|
-
const idColumn = tsDescriptor.parameters[0].name;
|
|
652
|
-
writeExecuteCrudBlock(client, queryType, tableName, tsDescriptor.columns, idColumn, client === 'bun:sqlite' || client === 'd1' ? queryParamsWithoutBrackets : queryParams, paramsTypeName, dataTypeName, resultTypeName, writer);
|
|
653
|
-
});
|
|
654
|
-
if (client !== 'd1' && (queryType === 'Select' || tsDescriptor.returning)) {
|
|
655
|
-
writer.blankLine();
|
|
656
|
-
writeMapFunction(writer, { resultTypeName, columns: tsDescriptor.columns });
|
|
657
|
-
}
|
|
658
|
-
if (client === 'libsql' && queryType !== 'Select' && !tsDescriptor.returning) {
|
|
659
|
-
writer.blankLine();
|
|
660
|
-
writeMapFunctionByName(writer, { resultTypeName, columns: tsDescriptor.columns });
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
const executeFunctionParams = {
|
|
664
|
-
functionName: camelCaseName,
|
|
665
|
-
returnType,
|
|
666
|
-
resultTypeName,
|
|
667
|
-
dataTypeName,
|
|
668
|
-
sql: (0, code_generator_1.replaceOrderByParam)(sql),
|
|
669
|
-
multipleRowsResult: tsDescriptor.multipleRowsResult,
|
|
670
|
-
parameters: allParameters,
|
|
671
|
-
columns: tsDescriptor.columns,
|
|
672
|
-
queryType,
|
|
673
|
-
paramsTypeName,
|
|
674
|
-
returning: tsDescriptor.returning || false,
|
|
675
|
-
orderBy: (((_b = tsDescriptor.orderByColumns) === null || _b === void 0 ? void 0 : _b.length) || 0) > 0,
|
|
676
|
-
uniqueUpdateParams
|
|
677
|
-
};
|
|
678
|
-
if (tsDescriptor.dynamicQuery2 == null && !isCrud) {
|
|
679
|
-
writeExecFunction(writer, client, executeFunctionParams);
|
|
680
|
-
}
|
|
681
|
-
if (tsDescriptor.orderByColumns) {
|
|
682
|
-
const orderByType = tsDescriptor.dynamicQuery2 == null ? paramsTypeName : dynamicParamsTypeName;
|
|
683
|
-
if (orderByField != null) {
|
|
684
|
-
writer.blankLine();
|
|
685
|
-
writer.write('const orderByFragments = ').inlineBlock(() => {
|
|
686
|
-
var _a;
|
|
687
|
-
(_a = tsDescriptor.orderByColumns) === null || _a === void 0 ? void 0 : _a.forEach((col) => {
|
|
688
|
-
writer.writeLine(`'${col}': \`${col}\`,`);
|
|
689
|
-
});
|
|
690
|
-
});
|
|
691
|
-
writer.write(' as const;');
|
|
692
|
-
}
|
|
693
|
-
writer.blankLine();
|
|
694
|
-
writer.writeLine(`export type ${orderByTypeName} = keyof typeof orderByFragments;`);
|
|
695
|
-
writer.blankLine();
|
|
696
|
-
writer.write(`function escapeOrderBy(orderBy: ${orderByType}['orderBy']): string`).block(() => {
|
|
697
|
-
writer.writeLine(`return orderBy.map(order => \`\${orderByFragments[order[0]]} \${order[1] == 'desc' ? 'desc' : 'asc'}\`).join(', ');`);
|
|
698
|
-
});
|
|
699
|
-
}
|
|
700
|
-
if (tsDescriptor.nestedDescriptor2) {
|
|
701
|
-
const relations = tsDescriptor.nestedDescriptor2;
|
|
702
|
-
relations.forEach((relation) => {
|
|
703
|
-
const relationType = (0, code_generator_1.generateRelationType)(capitalizedName, relation.name);
|
|
704
|
-
writer.blankLine();
|
|
705
|
-
writer.write(`export type ${relationType} = `).block(() => {
|
|
706
|
-
const uniqueNameFields = (0, code_generator_1.renameInvalidNames)(relation.fields.map((f) => f.name));
|
|
707
|
-
relation.fields.forEach((field, index) => {
|
|
708
|
-
writer.writeLine(`${uniqueNameFields[index]}: ${field.tsType};`);
|
|
709
|
-
});
|
|
710
|
-
relation.relations.forEach((field) => {
|
|
711
|
-
const nestedRelationType = (0, code_generator_1.generateRelationType)(capitalizedName, field.tsType);
|
|
712
|
-
const nullableOperator = field.notNull ? '' : '?';
|
|
713
|
-
writer.writeLine(`${field.name}${nullableOperator}: ${nestedRelationType};`);
|
|
714
|
-
});
|
|
715
|
-
});
|
|
716
|
-
});
|
|
717
|
-
writer.blankLine();
|
|
718
|
-
relations.forEach((relation, index) => {
|
|
719
|
-
const relationType = (0, code_generator_1.generateRelationType)(capitalizedName, relation.name);
|
|
720
|
-
if (index === 0) {
|
|
721
|
-
if (client === 'better-sqlite3' || client === 'bun:sqlite') {
|
|
722
|
-
writer.write(`export function ${camelCaseName}Nested(${functionArguments}): ${relationType}[]`).block(() => {
|
|
723
|
-
const params = tsDescriptor.parameters.length > 0 ? ', params' : '';
|
|
724
|
-
writer.writeLine(`const selectResult = ${camelCaseName}(db${params});`);
|
|
725
|
-
writer.write('if (selectResult.length == 0)').block(() => {
|
|
726
|
-
writer.writeLine('return [];');
|
|
727
|
-
});
|
|
728
|
-
writer.writeLine(`return collect${relationType}(selectResult);`);
|
|
729
|
-
});
|
|
730
|
-
}
|
|
731
|
-
else if (client === 'libsql' || client === 'd1') {
|
|
732
|
-
writer.write(`export async function ${camelCaseName}Nested(${functionArguments}): Promise<${relationType}[]>`).block(() => {
|
|
733
|
-
const params = tsDescriptor.parameters.length > 0 ? ', params' : '';
|
|
734
|
-
const functionParam = client === 'libsql' ? `client${params}` : `db${params}`;
|
|
735
|
-
writer.writeLine(`const selectResult = await ${camelCaseName}(${functionParam});`);
|
|
736
|
-
writer.write('if (selectResult.length == 0)').block(() => {
|
|
737
|
-
writer.writeLine('return [];');
|
|
738
|
-
});
|
|
739
|
-
writer.writeLine(`return collect${relationType}(selectResult);`);
|
|
740
|
-
});
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
writeCollectFunction(writer, relation, tsDescriptor.columns, capitalizedName, resultTypeName);
|
|
744
|
-
});
|
|
745
|
-
writer.blankLine();
|
|
746
|
-
writer.write('const groupBy = <T, Q>(array: T[], predicate: (value: T, index: number, array: T[]) => Q) =>').block(() => {
|
|
747
|
-
writer
|
|
748
|
-
.write('return array.reduce((map, value, index, array) => ')
|
|
749
|
-
.inlineBlock(() => {
|
|
750
|
-
writer.writeLine('const key = predicate(value, index, array);');
|
|
751
|
-
writer.writeLine('map.get(key)?.push(value) ?? map.set(key, [value]);');
|
|
752
|
-
writer.writeLine('return map;');
|
|
753
|
-
})
|
|
754
|
-
.write(', new Map<Q, T[]>());');
|
|
755
|
-
});
|
|
756
|
-
}
|
|
757
|
-
return writer.toString();
|
|
758
|
-
}
|
|
759
|
-
function writeExecuteCrudBlock(client, queryType, tableName, columns, idColumn, queryParams, paramTypeName, dataTypeName, resultTypeName, writer) {
|
|
760
|
-
switch (queryType) {
|
|
761
|
-
case 'Select':
|
|
762
|
-
return writeExecutSelectCrudBlock(client, tableName, idColumn, columns, queryParams, resultTypeName, writer);
|
|
763
|
-
case 'Insert':
|
|
764
|
-
return writeExecuteInsertCrudBlock(client, tableName, paramTypeName, resultTypeName, writer);
|
|
765
|
-
case 'Update':
|
|
766
|
-
return writeExecuteUpdateCrudBlock(client, tableName, idColumn, dataTypeName, resultTypeName, writer);
|
|
767
|
-
case 'Delete':
|
|
768
|
-
return writeExecutDeleteCrudBlock(client, tableName, idColumn, queryParams, resultTypeName, writer);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
function writeExecutSelectCrudBlock(client, tableName, idColumn, columns, queryParams, resultTypeName, writer) {
|
|
772
|
-
writer.blankLine();
|
|
773
|
-
writer.writeLine('const sql = `SELECT');
|
|
774
|
-
columns.forEach((col, index) => {
|
|
775
|
-
const separator = index < columns.length - 1 ? ',' : '';
|
|
776
|
-
writer.indent(2).write(`${col.name}${separator}`).newLine();
|
|
777
|
-
});
|
|
778
|
-
writer.indent().write(`FROM ${tableName}`).newLine();
|
|
779
|
-
writer.indent().write(`WHERE ${idColumn} = ?\``).newLine();
|
|
780
|
-
writer.blankLine();
|
|
781
|
-
if (client === 'better-sqlite3') {
|
|
782
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
783
|
-
writer.indent().write('.raw(true)').newLine();
|
|
784
|
-
writer.indent().write(`.all(${queryParams})`).newLine();
|
|
785
|
-
writer.indent().write(`.map(data => mapArrayTo${resultTypeName}(data))[0];`);
|
|
786
|
-
}
|
|
787
|
-
else if (client === 'bun:sqlite') {
|
|
788
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
789
|
-
writer.indent().write(`.values(${queryParams})`).newLine();
|
|
790
|
-
writer.indent().write(`.map(data => mapArrayTo${resultTypeName}(data))[0];`);
|
|
791
|
-
}
|
|
792
|
-
else if (client === 'd1') {
|
|
793
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
794
|
-
writer.indent().write(`.bind(${queryParams})`).newLine();
|
|
795
|
-
writer.indent().write('.first();').newLine();
|
|
796
|
-
}
|
|
797
|
-
else {
|
|
798
|
-
writer.write(`return client.execute({ sql, args: ${queryParams} })`).newLine();
|
|
799
|
-
writer.indent().write('.then(res => res.rows)').newLine();
|
|
800
|
-
writer.indent().write(`.then(rows => mapArrayTo${resultTypeName}(rows[0]));`);
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
function writeExecuteInsertCrudBlock(client, tableName, paramTypeName, resultTypeName, writer) {
|
|
804
|
-
writer.blankLine();
|
|
805
|
-
writer.writeLine(`const keys = Object.keys(params) as Array<keyof ${paramTypeName}>;`);
|
|
806
|
-
writer.writeLine('const columns = keys.filter(key => params[key] !== undefined);');
|
|
807
|
-
writer.writeLine('const values = columns.map(col => params[col]!);');
|
|
808
|
-
writer.blankLine();
|
|
809
|
-
writer.writeLine('const sql = columns.length == 0');
|
|
810
|
-
writer.indent().write(`? \`INSERT INTO ${tableName} DEFAULT VALUES\``).newLine();
|
|
811
|
-
writer.indent().write(`: \`INSERT INTO ${tableName}(\${columns.join(',')}) VALUES(\${columns.map(_ => '?').join(',')})\``).newLine();
|
|
812
|
-
writer.blankLine();
|
|
813
|
-
if (client === 'better-sqlite3') {
|
|
814
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
815
|
-
writer.indent().write(`.run(values) as ${resultTypeName};`);
|
|
816
|
-
}
|
|
817
|
-
else if (client === 'bun:sqlite') {
|
|
818
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
819
|
-
writer.indent().write(`.run(...values) as ${resultTypeName};`);
|
|
820
|
-
}
|
|
821
|
-
else if (client === 'd1') {
|
|
822
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
823
|
-
writer.indent().write('.bind(...values)').newLine();
|
|
824
|
-
writer.indent().write('.run()').newLine();
|
|
825
|
-
writer.indent().write('.then(res => res.meta);');
|
|
826
|
-
}
|
|
827
|
-
else {
|
|
828
|
-
writer.write('return client.execute({ sql, args: values })').newLine();
|
|
829
|
-
writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`).newLine();
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
function writeExecuteUpdateCrudBlock(client, tableName, idColumn, paramTypeName, resultTypeName, writer) {
|
|
833
|
-
writer.blankLine();
|
|
834
|
-
writer.writeLine(`const keys = Object.keys(data) as Array<keyof ${paramTypeName}>;`);
|
|
835
|
-
writer.writeLine('const columns = keys.filter(key => data[key] !== undefined);');
|
|
836
|
-
writer.writeLine(`const values = columns.map(col => data[col]!).concat(params.${idColumn});`);
|
|
837
|
-
writer.blankLine();
|
|
838
|
-
writer.writeLine('const sql = `');
|
|
839
|
-
writer.indent().write(`UPDATE ${tableName}`).newLine();
|
|
840
|
-
writer.indent().write(`SET \${columns.map(col => \`\${col} = ?\`).join(', ')}`).newLine();
|
|
841
|
-
writer.indent().write(`WHERE ${idColumn} = ?\``).newLine();
|
|
842
|
-
writer.blankLine();
|
|
843
|
-
if (client === 'better-sqlite3') {
|
|
844
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
845
|
-
writer.indent().write(`.run(values) as ${resultTypeName};`);
|
|
846
|
-
}
|
|
847
|
-
else if (client === 'bun:sqlite') {
|
|
848
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
849
|
-
writer.indent().write(`.run(...values) as ${resultTypeName};`);
|
|
850
|
-
}
|
|
851
|
-
else if (client === 'd1') {
|
|
852
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
853
|
-
writer.indent().write(`.bind(params.${idColumn})`).newLine();
|
|
854
|
-
writer.indent().write('.run()').newLine();
|
|
855
|
-
writer.indent().write('.then(res => res.meta);');
|
|
856
|
-
}
|
|
857
|
-
else {
|
|
858
|
-
writer.write('return client.execute({ sql, args: values })').newLine();
|
|
859
|
-
writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`).newLine();
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
function writeExecutDeleteCrudBlock(client, tableName, idColumn, queryParams, resultTypeName, writer) {
|
|
863
|
-
writer.blankLine();
|
|
864
|
-
writer.writeLine('const sql = `DELETE');
|
|
865
|
-
writer.indent().write(`FROM ${tableName}`).newLine();
|
|
866
|
-
writer.indent().write(`WHERE ${idColumn} = ?\``).newLine();
|
|
867
|
-
writer.blankLine();
|
|
868
|
-
if (client === 'better-sqlite3') {
|
|
869
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
870
|
-
writer.indent().write(`.run(${queryParams}) as ${resultTypeName};`).newLine();
|
|
871
|
-
}
|
|
872
|
-
else if (client === 'bun:sqlite') {
|
|
873
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
874
|
-
writer.indent().write(`.run(${queryParams}) as ${resultTypeName};`).newLine();
|
|
875
|
-
}
|
|
876
|
-
else if (client === 'd1') {
|
|
877
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
878
|
-
writer.indent().write(`.bind(${queryParams})`).newLine();
|
|
879
|
-
writer.indent().write('.run()').newLine();
|
|
880
|
-
writer.indent().write('.then(res => res.meta);');
|
|
881
|
-
}
|
|
882
|
-
else {
|
|
883
|
-
writer.write(`return client.execute({ sql, args: ${queryParams} })`).newLine();
|
|
884
|
-
writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`).newLine();
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
function toDriver(variableData, param) {
|
|
888
|
-
if (param.tsType === 'Date') {
|
|
889
|
-
if (param.notNull) {
|
|
890
|
-
return `new Date(${variableData})`;
|
|
891
|
-
}
|
|
892
|
-
return `${variableData} != null ? new Date(${variableData}) : ${variableData}`;
|
|
893
|
-
}
|
|
894
|
-
if (param.tsType === 'boolean') {
|
|
895
|
-
return `${variableData} != null ? Boolean(${variableData}) : ${variableData}`;
|
|
896
|
-
}
|
|
897
|
-
return variableData;
|
|
898
|
-
}
|
|
899
|
-
function fromDriver(variableName, param) {
|
|
900
|
-
var _a;
|
|
901
|
-
if (param.tsType === 'Date') {
|
|
902
|
-
return `${variableName}.${param.toDriver}`;
|
|
903
|
-
}
|
|
904
|
-
if (param.tsType === 'boolean') {
|
|
905
|
-
const variable = `${variableName}.${param.name}`;
|
|
906
|
-
return `${variable} != null ? Number(${variable}) : ${variable}`;
|
|
907
|
-
}
|
|
908
|
-
if ((_a = param.tsType) === null || _a === void 0 ? void 0 : _a.endsWith('[]')) {
|
|
909
|
-
return `...${variableName}.${param.name}`;
|
|
910
|
-
}
|
|
911
|
-
return `${variableName}.${param.name}`;
|
|
912
|
-
}
|
|
913
|
-
function writeCollectFunction(writer, relation, columns, capitalizedName, resultTypeName) {
|
|
914
|
-
const relationType = (0, code_generator_1.generateRelationType)(capitalizedName, relation.name);
|
|
915
|
-
const collectFunctionName = `collect${relationType}`;
|
|
916
|
-
writer.blankLine();
|
|
917
|
-
writer.write(`function ${collectFunctionName}(selectResult: ${resultTypeName}[]): ${relationType}[]`).block(() => {
|
|
918
|
-
const groupBy = columns[relation.groupIndex].name;
|
|
919
|
-
writer.writeLine(`const grouped = groupBy(selectResult.filter(r => r.${groupBy} != null), r => r.${groupBy});`);
|
|
920
|
-
writer
|
|
921
|
-
.write('return [...grouped.values()].map(row => (')
|
|
922
|
-
.inlineBlock(() => {
|
|
923
|
-
relation.fields.forEach((field, index) => {
|
|
924
|
-
const uniqueNameFields = (0, code_generator_1.renameInvalidNames)(relation.fields.map((f) => f.name));
|
|
925
|
-
const separator = ',';
|
|
926
|
-
const fieldName = columns[field.index].name;
|
|
927
|
-
writer.writeLine(`${uniqueNameFields[index]}: row[0].${fieldName}!${separator}`);
|
|
928
|
-
});
|
|
929
|
-
relation.relations.forEach((fieldRelation) => {
|
|
930
|
-
const relationType = (0, code_generator_1.generateRelationType)(capitalizedName, fieldRelation.name);
|
|
931
|
-
const cardinality = fieldRelation.list ? '' : '[0]';
|
|
932
|
-
writer.writeLine(`${fieldRelation.name}: collect${relationType}(row)${cardinality},`);
|
|
933
|
-
});
|
|
934
|
-
})
|
|
935
|
-
.write('))');
|
|
936
|
-
});
|
|
937
|
-
}
|
|
938
|
-
function writeImports(writer, client, isDynamicQuery) {
|
|
939
|
-
switch (client) {
|
|
940
|
-
case 'better-sqlite3':
|
|
941
|
-
writer.writeLine(`import type { Database } from 'better-sqlite3';`);
|
|
942
|
-
if (isDynamicQuery) {
|
|
943
|
-
writer.writeLine(`import { EOL } from 'os';`);
|
|
944
|
-
}
|
|
945
|
-
return;
|
|
946
|
-
case 'libsql':
|
|
947
|
-
writer.writeLine(`import type { Client, Transaction } from '@libsql/client';`);
|
|
948
|
-
if (isDynamicQuery) {
|
|
949
|
-
writer.writeLine(`import { EOL } from 'os';`);
|
|
950
|
-
}
|
|
951
|
-
return;
|
|
952
|
-
case 'bun:sqlite':
|
|
953
|
-
writer.writeLine(`import type { Database } from 'bun:sqlite';`);
|
|
954
|
-
if (isDynamicQuery) {
|
|
955
|
-
writer.writeLine(`import { EOL } from 'os';`);
|
|
956
|
-
}
|
|
957
|
-
return;
|
|
958
|
-
case 'd1':
|
|
959
|
-
writer.writeLine(`import type { D1Database } from '@cloudflare/workers-types';`);
|
|
960
|
-
if (isDynamicQuery) {
|
|
961
|
-
writer.writeLine(`const EOL = '\\n';`);
|
|
962
|
-
}
|
|
963
|
-
return;
|
|
964
|
-
default:
|
|
965
|
-
return client;
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
function writeExecFunction(writer, client, params) {
|
|
969
|
-
const { functionName, returnType, sql, multipleRowsResult, parameters, columns, queryType, returning, paramsTypeName, resultTypeName, dataTypeName, orderBy, uniqueUpdateParams } = params;
|
|
970
|
-
let restParameters = queryType === 'Update' && uniqueUpdateParams.length > 0 ? `, data: ${dataTypeName}` : '';
|
|
971
|
-
const dynamicQuery = false;
|
|
972
|
-
if (!dynamicQuery) {
|
|
973
|
-
restParameters += parameters.length > 0 || orderBy ? `, params: ${paramsTypeName}` : '';
|
|
974
|
-
}
|
|
975
|
-
const queryParametersWithoutBrackes = parameters.join(', ');
|
|
976
|
-
const queryParams = queryParametersWithoutBrackes != '' ? `[${queryParametersWithoutBrackes}]` : '';
|
|
977
|
-
const mapFunctionParams = {
|
|
978
|
-
resultTypeName,
|
|
979
|
-
columns
|
|
980
|
-
};
|
|
981
|
-
switch (client) {
|
|
982
|
-
case 'better-sqlite3':
|
|
983
|
-
const betterSqliteArgs = 'db: Database' + restParameters;
|
|
984
|
-
if (queryType === 'Select') {
|
|
985
|
-
writer.write(`export function ${functionName}(${betterSqliteArgs}): ${returnType}`).block(() => {
|
|
986
|
-
writeSql(writer, sql);
|
|
987
|
-
if (multipleRowsResult) {
|
|
988
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
989
|
-
writer.indent().write('.raw(true)').newLine();
|
|
990
|
-
writer.indent().write(`.all(${queryParams})`).newLine();
|
|
991
|
-
writer.indent().write(`.map(data => mapArrayTo${resultTypeName}(data));`);
|
|
992
|
-
}
|
|
993
|
-
else {
|
|
994
|
-
writer.write('const res = db.prepare(sql)').newLine();
|
|
995
|
-
writer.indent().write('.raw(true)').newLine();
|
|
996
|
-
writer.indent().write(`.get(${queryParams});`).newLine();
|
|
997
|
-
writer.blankLine();
|
|
998
|
-
writer.write(`return res ? mapArrayTo${resultTypeName}(res) : null;`);
|
|
999
|
-
}
|
|
1000
|
-
});
|
|
1001
|
-
writer.blankLine();
|
|
1002
|
-
writeMapFunction(writer, mapFunctionParams);
|
|
1003
|
-
}
|
|
1004
|
-
if (queryType === 'Update' || queryType === 'Delete' || (queryType === 'Insert' && !returning)) {
|
|
1005
|
-
writer.write(`export function ${functionName}(${betterSqliteArgs}): ${resultTypeName}`).block(() => {
|
|
1006
|
-
writeSql(writer, sql);
|
|
1007
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
1008
|
-
writer.indent().write(`.run(${queryParams}) as ${resultTypeName};`);
|
|
1009
|
-
});
|
|
1010
|
-
}
|
|
1011
|
-
return;
|
|
1012
|
-
case 'libsql':
|
|
1013
|
-
const libSqlArgs = 'client: Client | Transaction' + restParameters;
|
|
1014
|
-
writer.write(`export async function ${functionName}(${libSqlArgs}): Promise<${returnType}>`).block(() => {
|
|
1015
|
-
writeSql(writer, sql);
|
|
1016
|
-
const executeParams = queryParametersWithoutBrackes !== '' ? `{ sql, args: [${queryParametersWithoutBrackes}] }` : 'sql';
|
|
1017
|
-
writer.write(`return client.execute(${executeParams})`).newLine();
|
|
1018
|
-
if (queryType === 'Select') {
|
|
1019
|
-
writer.indent().write('.then(res => res.rows)').newLine();
|
|
1020
|
-
if (multipleRowsResult) {
|
|
1021
|
-
writer.indent().write(`.then(rows => rows.map(row => mapArrayTo${resultTypeName}(row)));`);
|
|
1022
|
-
}
|
|
1023
|
-
else {
|
|
1024
|
-
writer.indent().write(`.then(rows => rows.length > 0 ? mapArrayTo${resultTypeName}(rows[0]) : null);`);
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
if (queryType === 'Insert') {
|
|
1028
|
-
if (returning) {
|
|
1029
|
-
writer.indent().write('.then(res => res.rows)').newLine();
|
|
1030
|
-
writer.indent().write(`.then(rows => mapArrayTo${resultTypeName}(rows[0]));`);
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
if (queryType === 'Update' || queryType === 'Delete' || (queryType === 'Insert' && !returning)) {
|
|
1034
|
-
writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`);
|
|
1035
|
-
}
|
|
1036
|
-
});
|
|
1037
|
-
writer.blankLine();
|
|
1038
|
-
if (queryType === 'Select' || returning) {
|
|
1039
|
-
writeMapFunction(writer, mapFunctionParams);
|
|
1040
|
-
}
|
|
1041
|
-
else {
|
|
1042
|
-
writeMapFunctionByName(writer, mapFunctionParams);
|
|
1043
|
-
}
|
|
1044
|
-
return;
|
|
1045
|
-
case 'bun:sqlite':
|
|
1046
|
-
const bunArgs = 'db: Database' + restParameters;
|
|
1047
|
-
if (queryType === 'Select') {
|
|
1048
|
-
writer.write(`export function ${functionName}(${bunArgs}): ${returnType}`).block(() => {
|
|
1049
|
-
writeSql(writer, sql);
|
|
1050
|
-
if (multipleRowsResult) {
|
|
1051
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
1052
|
-
writer.indent().write(`.values(${queryParametersWithoutBrackes})`).newLine();
|
|
1053
|
-
writer.indent().write(`.map(data => mapArrayTo${resultTypeName}(data))${multipleRowsResult ? '' : '[0]'};`);
|
|
1054
|
-
}
|
|
1055
|
-
else {
|
|
1056
|
-
writer.write('const res = db.prepare(sql)').newLine();
|
|
1057
|
-
writer.indent().write(`.values(${queryParametersWithoutBrackes});`).newLine();
|
|
1058
|
-
writer.blankLine();
|
|
1059
|
-
writer.write(`return res.length > 0 ? mapArrayTo${resultTypeName}(res[0]) : null;`);
|
|
1060
|
-
}
|
|
1061
|
-
});
|
|
1062
|
-
writer.blankLine();
|
|
1063
|
-
writeMapFunction(writer, mapFunctionParams);
|
|
1064
|
-
}
|
|
1065
|
-
if (queryType === 'Update' || queryType === 'Delete' || (queryType === 'Insert' && !returning)) {
|
|
1066
|
-
writer.write(`export function ${functionName}(${bunArgs}): ${resultTypeName}`).block(() => {
|
|
1067
|
-
writeSql(writer, sql);
|
|
1068
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
1069
|
-
writer.indent().write(`.run(${queryParametersWithoutBrackes}) as ${resultTypeName};`);
|
|
1070
|
-
});
|
|
1071
|
-
}
|
|
1072
|
-
return;
|
|
1073
|
-
case 'd1':
|
|
1074
|
-
const d1Args = 'db: D1Database' + restParameters;
|
|
1075
|
-
writer.write(`export async function ${functionName}(${d1Args}): Promise<${returnType}>`).block(() => {
|
|
1076
|
-
writeSql(writer, sql);
|
|
1077
|
-
writer.write('return db.prepare(sql)').newLine();
|
|
1078
|
-
if (queryParametersWithoutBrackes !== '') {
|
|
1079
|
-
writer.indent().write(`.bind(${queryParametersWithoutBrackes})`).newLine();
|
|
1080
|
-
}
|
|
1081
|
-
if (queryType === 'Select') {
|
|
1082
|
-
writer.indent().write('.raw({ columnNames: false })').newLine();
|
|
1083
|
-
if (multipleRowsResult) {
|
|
1084
|
-
writer.indent().write(`.then(rows => rows.map(row => mapArrayTo${resultTypeName}(row)));`);
|
|
1085
|
-
}
|
|
1086
|
-
else {
|
|
1087
|
-
writer.indent().write(`.then(rows => rows.length > 0 ? mapArrayTo${resultTypeName}(rows[0]) : null);`);
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
if (queryType === 'Insert' || queryType === 'Update' || queryType === 'Delete') {
|
|
1091
|
-
if (returning) {
|
|
1092
|
-
writer.indent().write('.raw({ columnNames: false })').newLine();
|
|
1093
|
-
writer.indent().write(`.then(rows => rows.map(row => mapArrayTo${resultTypeName}(row))[0]);`);
|
|
1094
|
-
}
|
|
1095
|
-
else {
|
|
1096
|
-
writer.indent().write('.run()').newLine();
|
|
1097
|
-
writer.indent().write(`.then(res => res.meta);`);
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
});
|
|
1101
|
-
if (queryType === 'Select' || returning) {
|
|
1102
|
-
writer.blankLine();
|
|
1103
|
-
writeMapFunction(writer, mapFunctionParams);
|
|
1104
|
-
}
|
|
1105
|
-
return;
|
|
1106
|
-
default:
|
|
1107
|
-
return client;
|
|
1108
|
-
}
|
|
1109
|
-
}
|
|
1110
|
-
function writeSql(writer, sql) {
|
|
1111
|
-
const sqlSplit = sql.split('\n');
|
|
1112
|
-
writer.write('const sql = `').newLine();
|
|
1113
|
-
sqlSplit.forEach((sqlLine) => {
|
|
1114
|
-
writer.indent().write(sqlLine).newLine();
|
|
1115
|
-
});
|
|
1116
|
-
writer.indent().write('`').newLine();
|
|
1117
|
-
}
|
|
1118
|
-
function writeMapFunction(writer, params) {
|
|
1119
|
-
const { resultTypeName, columns } = params;
|
|
1120
|
-
writer.write(`function mapArrayTo${resultTypeName}(data: any) `).block(() => {
|
|
1121
|
-
writer.write(`const result: ${resultTypeName} = `).block(() => {
|
|
1122
|
-
columns.forEach((col, index) => {
|
|
1123
|
-
const separator = index < columns.length - 1 ? ',' : '';
|
|
1124
|
-
writer.writeLine(`${col.name}: ${toDriver(`data[${index}]`, col)}${separator}`);
|
|
1125
|
-
});
|
|
1126
|
-
});
|
|
1127
|
-
writer.writeLine('return result;');
|
|
1128
|
-
});
|
|
1129
|
-
}
|
|
1130
|
-
function writeMapFunctionByName(writer, params) {
|
|
1131
|
-
const { resultTypeName, columns } = params;
|
|
1132
|
-
writer.write(`function mapArrayTo${resultTypeName}(data: any) `).block(() => {
|
|
1133
|
-
writer.write(`const result: ${resultTypeName} = `).block(() => {
|
|
1134
|
-
columns.forEach((col, index) => {
|
|
1135
|
-
const separator = index < columns.length - 1 ? ',' : '';
|
|
1136
|
-
writer.writeLine(`${col.name}: data.${col.name}${separator}`);
|
|
1137
|
-
});
|
|
1138
|
-
});
|
|
1139
|
-
writer.writeLine('return result;');
|
|
1140
|
-
});
|
|
1141
|
-
}
|
|
1142
|
-
//# sourceMappingURL=code-generator.js.map
|