typesql-cli 0.10.0 → 0.10.1

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 (85) hide show
  1. package/cli.js +9 -20
  2. package/cli.js.map +1 -1
  3. package/code-generator.d.ts.map +1 -1
  4. package/code-generator.js +46 -111
  5. package/code-generator.js.map +1 -1
  6. package/describe-dynamic-query.d.ts.map +1 -1
  7. package/describe-dynamic-query.js +6 -13
  8. package/describe-dynamic-query.js.map +1 -1
  9. package/describe-nested-query.d.ts.map +1 -1
  10. package/describe-nested-query.js +11 -27
  11. package/describe-nested-query.js.map +1 -1
  12. package/describe-query.d.ts.map +1 -1
  13. package/describe-query.js +9 -18
  14. package/describe-query.js.map +1 -1
  15. package/drivers/libsql.d.ts.map +1 -1
  16. package/drivers/libsql.js +1 -2
  17. package/drivers/libsql.js.map +1 -1
  18. package/mysql-mapping.d.ts.map +1 -1
  19. package/mysql-mapping.js +4 -4
  20. package/mysql-mapping.js.map +1 -1
  21. package/mysql-query-analyzer/collect-constraints.d.ts.map +1 -1
  22. package/mysql-query-analyzer/collect-constraints.js +17 -24
  23. package/mysql-query-analyzer/collect-constraints.js.map +1 -1
  24. package/mysql-query-analyzer/infer-column-nullability.d.ts.map +1 -1
  25. package/mysql-query-analyzer/infer-column-nullability.js +13 -29
  26. package/mysql-query-analyzer/infer-column-nullability.js.map +1 -1
  27. package/mysql-query-analyzer/infer-param-nullability.d.ts.map +1 -1
  28. package/mysql-query-analyzer/infer-param-nullability.js +8 -10
  29. package/mysql-query-analyzer/infer-param-nullability.js.map +1 -1
  30. package/mysql-query-analyzer/parse.d.ts.map +1 -1
  31. package/mysql-query-analyzer/parse.js +15 -20
  32. package/mysql-query-analyzer/parse.js.map +1 -1
  33. package/mysql-query-analyzer/select-columns.d.ts.map +1 -1
  34. package/mysql-query-analyzer/select-columns.js +25 -43
  35. package/mysql-query-analyzer/select-columns.js.map +1 -1
  36. package/mysql-query-analyzer/traverse.d.ts.map +1 -1
  37. package/mysql-query-analyzer/traverse.js +61 -144
  38. package/mysql-query-analyzer/traverse.js.map +1 -1
  39. package/mysql-query-analyzer/types.d.ts.map +1 -1
  40. package/mysql-query-analyzer/unify.d.ts.map +1 -1
  41. package/mysql-query-analyzer/unify.js +13 -57
  42. package/mysql-query-analyzer/unify.js.map +1 -1
  43. package/mysql-query-analyzer/util.d.ts.map +1 -1
  44. package/mysql-query-analyzer/util.js +2 -3
  45. package/mysql-query-analyzer/util.js.map +1 -1
  46. package/mysql-query-analyzer/verify-multiple-result.d.ts.map +1 -1
  47. package/mysql-query-analyzer/verify-multiple-result.js +3 -7
  48. package/mysql-query-analyzer/verify-multiple-result.js.map +1 -1
  49. package/package.json +47 -46
  50. package/queryExectutor.d.ts.map +1 -1
  51. package/queryExectutor.js +37 -38
  52. package/queryExectutor.js.map +1 -1
  53. package/sql-generator.d.ts.map +1 -1
  54. package/sql-generator.js +5 -8
  55. package/sql-generator.js.map +1 -1
  56. package/sqlite-query-analyzer/code-generator.d.ts +2 -2
  57. package/sqlite-query-analyzer/code-generator.d.ts.map +1 -1
  58. package/sqlite-query-analyzer/code-generator.js +117 -219
  59. package/sqlite-query-analyzer/code-generator.js.map +1 -1
  60. package/sqlite-query-analyzer/parser.d.ts.map +1 -1
  61. package/sqlite-query-analyzer/parser.js +9 -23
  62. package/sqlite-query-analyzer/parser.js.map +1 -1
  63. package/sqlite-query-analyzer/query-executor.d.ts +1 -1
  64. package/sqlite-query-analyzer/query-executor.d.ts.map +1 -1
  65. package/sqlite-query-analyzer/query-executor.js +10 -15
  66. package/sqlite-query-analyzer/query-executor.js.map +1 -1
  67. package/sqlite-query-analyzer/replace-list-params.d.ts.map +1 -1
  68. package/sqlite-query-analyzer/replace-list-params.js +1 -2
  69. package/sqlite-query-analyzer/replace-list-params.js.map +1 -1
  70. package/sqlite-query-analyzer/sqlite-describe-nested-query.d.ts.map +1 -1
  71. package/sqlite-query-analyzer/sqlite-describe-nested-query.js +9 -22
  72. package/sqlite-query-analyzer/sqlite-describe-nested-query.js.map +1 -1
  73. package/sqlite-query-analyzer/traverse.d.ts.map +1 -1
  74. package/sqlite-query-analyzer/traverse.js +36 -95
  75. package/sqlite-query-analyzer/traverse.js.map +1 -1
  76. package/ts-dynamic-query-descriptor.d.ts.map +1 -1
  77. package/ts-dynamic-query-descriptor.js +3 -4
  78. package/ts-dynamic-query-descriptor.js.map +1 -1
  79. package/ts-nested-descriptor.d.ts.map +1 -1
  80. package/ts-nested-descriptor.js +2 -3
  81. package/ts-nested-descriptor.js.map +1 -1
  82. package/types.d.ts +6 -2
  83. package/types.d.ts.map +1 -1
  84. package/util.d.ts.map +1 -1
  85. package/util.js.map +1 -1
@@ -3,7 +3,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.generateTsCode = exports.generateCrud = exports.validateAndGenerateCode = void 0;
6
+ exports.validateAndGenerateCode = validateAndGenerateCode;
7
+ exports.generateCrud = generateCrud;
8
+ exports.generateTsCode = generateTsCode;
7
9
  const Either_1 = require("fp-ts/lib/Either");
8
10
  const parser_1 = require("./parser");
9
11
  const code_generator_1 = require("../code-generator");
@@ -25,11 +27,8 @@ function validateAndGenerateCode(client, sql, queryName, sqliteDbSchema, isCrud
25
27
  const code = generateTsCode(sql, queryName, sqliteDbSchema, client.type, isCrud);
26
28
  return code;
27
29
  }
28
- exports.validateAndGenerateCode = validateAndGenerateCode;
29
30
  function mapToColumnInfo(col, checkOptional) {
30
- const defaultValue = col.columnKey === 'PRI' && col.column_type === 'INTEGER'
31
- ? 'AUTOINCREMENT'
32
- : col.defaultValue;
31
+ const defaultValue = col.columnKey === 'PRI' && col.column_type === 'INTEGER' ? 'AUTOINCREMENT' : col.defaultValue;
33
32
  const columnInfo = {
34
33
  columnName: col.column,
35
34
  notNull: col.notNull,
@@ -46,9 +45,7 @@ function generateCrud(client, queryType, tableName, dbSchema) {
46
45
  if (keys.length === 0) {
47
46
  keys.push(...columns.filter((col) => col.columnKey === 'UNI'));
48
47
  }
49
- const keyColumnInfo = keys
50
- .map((key) => mapToColumnInfo(key, false))
51
- .map((col) => mapColumnToTsFieldDescriptor(col, client));
48
+ const keyColumnInfo = keys.map((key) => mapToColumnInfo(key, false)).map((col) => mapColumnToTsFieldDescriptor(col, client));
52
49
  const resultColumns = mapColumns(client, queryType, columnInfo, false);
53
50
  const params = columnInfo.map((col) => mapColumnToTsFieldDescriptor(col, client));
54
51
  const tsDescriptor = {
@@ -58,15 +55,12 @@ function generateCrud(client, queryType, tableName, dbSchema) {
58
55
  columns: resultColumns,
59
56
  parameterNames: [],
60
57
  parameters: queryType === 'Insert' ? params : keyColumnInfo,
61
- data: queryType === 'Update'
62
- ? params.filter((param) => { var _a; return param.name !== ((_a = keyColumnInfo[0]) === null || _a === void 0 ? void 0 : _a.name); })
63
- : []
58
+ data: queryType === 'Update' ? params.filter((param) => { var _a; return param.name !== ((_a = keyColumnInfo[0]) === null || _a === void 0 ? void 0 : _a.name); }) : []
64
59
  };
65
60
  const queryName = getQueryName(queryType, tableName);
66
61
  const code = generateCodeFromTsDescriptor(client, queryName, tsDescriptor, true, tableName);
67
62
  return code;
68
63
  }
69
- exports.generateCrud = generateCrud;
70
64
  function getQueryName(queryType, tableName) {
71
65
  const camelCaseName = (0, code_generator_1.convertToCamelCaseName)(tableName);
72
66
  const captitalizedName = (0, code_generator_1.capitalize)(camelCaseName);
@@ -90,7 +84,6 @@ function generateTsCode(sql, queryName, sqliteDbSchema, client, isCrud = false)
90
84
  const code = generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud);
91
85
  return (0, Either_1.right)(code);
92
86
  }
93
- exports.generateTsCode = generateTsCode;
94
87
  function createTsDescriptor(queryInfo, client) {
95
88
  var _a;
96
89
  const tsDescriptor = {
@@ -145,14 +138,10 @@ function mapColumns(client, queryType, columns, returning = false) {
145
138
  }
146
139
  ];
147
140
  if (queryType === 'Insert' && !returning) {
148
- return client === 'better-sqlite3'
149
- ? sqliteInsertColumns
150
- : libSqlInsertColumns;
141
+ return client === 'better-sqlite3' || client == 'bun:sqlite' ? sqliteInsertColumns : libSqlInsertColumns;
151
142
  }
152
143
  if (queryType === 'Update' || queryType === 'Delete') {
153
- return client === 'better-sqlite3'
154
- ? [sqliteInsertColumns[0]]
155
- : [libSqlInsertColumns[0]];
144
+ return client === 'better-sqlite3' || client == 'bun:sqlite' ? [sqliteInsertColumns[0]] : [libSqlInsertColumns[0]];
156
145
  }
157
146
  const escapedColumnsNames = (0, code_generator_1.renameInvalidNames)(columns.map((col) => col.columnName));
158
147
  return columns.map((col, index) => mapColumnToTsFieldDescriptor(Object.assign(Object.assign({}, col), { columnName: escapedColumnsNames[index] }), client));
@@ -223,38 +212,30 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
223
212
  const selectColumnsTypeName = `${capitalizedName}Select`;
224
213
  const whereTypeName = `${capitalizedName}Where`;
225
214
  const orderByTypeName = `${capitalizedName}OrderBy`;
226
- const generateOrderBy = tsDescriptor.orderByColumns != null &&
227
- tsDescriptor.orderByColumns.length > 0;
215
+ const generateOrderBy = tsDescriptor.orderByColumns != null && tsDescriptor.orderByColumns.length > 0;
228
216
  const uniqueParams = (0, code_generator_1.removeDuplicatedParameters2)(tsDescriptor.parameters);
229
217
  const uniqueUpdateParams = (0, code_generator_1.removeDuplicatedParameters2)(tsDescriptor.data || []);
230
- const orderByField = generateOrderBy
231
- ? `orderBy: [${orderByTypeName}, 'asc' | 'desc'][]`
232
- : undefined;
233
- const paramsTypes = (0, code_generator_1.removeDuplicatedParameters2)(tsDescriptor.dynamicQuery2 == null
234
- ? tsDescriptor.parameters
235
- : (0, ts_dynamic_query_descriptor_1.mapToDynamicParams)(tsDescriptor.parameters));
236
- let functionArguments = client === 'better-sqlite3'
237
- ? 'db: Database'
238
- : 'client: Client | Transaction';
218
+ const orderByField = generateOrderBy ? `orderBy: [${orderByTypeName}, 'asc' | 'desc'][]` : undefined;
219
+ const paramsTypes = (0, code_generator_1.removeDuplicatedParameters2)(tsDescriptor.dynamicQuery2 == null ? tsDescriptor.parameters : (0, ts_dynamic_query_descriptor_1.mapToDynamicParams)(tsDescriptor.parameters));
220
+ let functionArguments = client === 'better-sqlite3' || client == 'bun:sqlite' ? 'db: Database' : 'client: Client | Transaction';
239
221
  functionArguments += queryType === 'Update' ? `, data: ${dataTypeName}` : '';
240
222
  if (tsDescriptor.dynamicQuery2 == null) {
241
- functionArguments +=
242
- tsDescriptor.parameters.length > 0 || generateOrderBy
243
- ? `, params: ${paramsTypeName}`
244
- : '';
223
+ functionArguments += tsDescriptor.parameters.length > 0 || generateOrderBy ? `, params: ${paramsTypeName}` : '';
245
224
  }
246
225
  else {
247
226
  functionArguments += `, ${orderByField ? 'params' : 'params?'}: ${dynamicParamsTypeName}`;
248
227
  }
249
228
  const orNull = queryType === 'Select' ? ' | null' : '';
250
- const returnType = tsDescriptor.multipleRowsResult
251
- ? `${resultTypeName}[]`
252
- : `${resultTypeName}${orNull}`;
229
+ const returnType = tsDescriptor.multipleRowsResult ? `${resultTypeName}[]` : `${resultTypeName}${orNull}`;
253
230
  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)));
254
- const queryParams = allParameters.length > 0 ? `[${allParameters.join(', ')}]` : '';
231
+ const queryParamsWithoutBrackets = allParameters.length > 0 ? `${allParameters.join(', ')}` : '';
232
+ const queryParams = queryParamsWithoutBrackets !== '' ? `[${queryParamsWithoutBrackets}]` : '';
255
233
  if (client === 'better-sqlite3') {
256
234
  writer.writeLine(`import type { Database } from 'better-sqlite3';`);
257
235
  }
236
+ if (client === 'bun:sqlite') {
237
+ writer.writeLine(`import type { Database } from 'bun:sqlite';`);
238
+ }
258
239
  if (client === 'libsql') {
259
240
  writer.writeLine(`import type { Client, Transaction } from '@libsql/client';`);
260
241
  }
@@ -273,9 +254,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
273
254
  });
274
255
  writer.blankLine();
275
256
  (0, code_generator_1.writeTypeBlock)(writer, paramsTypes, paramsTypeName, false, tsDescriptor.dynamicQuery2 ? undefined : orderByField);
276
- const resultTypes = tsDescriptor.dynamicQuery2 == null
277
- ? tsDescriptor.columns
278
- : (0, ts_dynamic_query_descriptor_1.mapToDynamicResultColumns)(tsDescriptor.columns);
257
+ const resultTypes = tsDescriptor.dynamicQuery2 == null ? tsDescriptor.columns : (0, ts_dynamic_query_descriptor_1.mapToDynamicResultColumns)(tsDescriptor.columns);
279
258
  (0, code_generator_1.writeTypeBlock)(writer, resultTypes, resultTypeName, false);
280
259
  const selectFields = (0, ts_dynamic_query_descriptor_1.mapToDynamicSelectColumns)(tsDescriptor.columns);
281
260
  (0, code_generator_1.writeTypeBlock)(writer, selectFields, selectColumnsTypeName, false);
@@ -306,13 +285,9 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
306
285
  writer.blankLine();
307
286
  const asyncModified = client === 'libsql' ? 'async ' : '';
308
287
  const returnTypeModifier = client === 'libsql' ? `Promise<${returnType}>` : returnType;
309
- writer
310
- .write(`export ${asyncModified}function ${camelCaseName}(${functionArguments}): ${returnTypeModifier}`)
311
- .block(() => {
288
+ writer.write(`export ${asyncModified}function ${camelCaseName}(${functionArguments}): ${returnTypeModifier}`).block(() => {
312
289
  var _a, _b, _c, _d, _e, _f;
313
- writer
314
- .write('const where = whereConditionsToObject(params?.where);')
315
- .newLine();
290
+ writer.write('const where = whereConditionsToObject(params?.where);').newLine();
316
291
  if (orderByField != null) {
317
292
  writer.writeLine('const orderBy = orderByToObject(params.orderBy);');
318
293
  }
@@ -328,32 +303,22 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
328
303
  }
329
304
  const whereConditions = withFragment.dependOnFields.map((fieldIndex) => `where.${tsDescriptor.columns[fieldIndex].name} != null`);
330
305
  const orderByConditions = ((_a = withFragment.dependOnOrderBy) === null || _a === void 0 ? void 0 : _a.map((orderBy) => `orderBy['${orderBy}'] != null`)) || [];
331
- const allConditions = [
332
- ...selectConditions,
333
- ...whereConditions,
334
- ...orderByConditions
335
- ];
306
+ const allConditions = [...selectConditions, ...whereConditions, ...orderByConditions];
336
307
  const paramValues = withFragment.parameters.map((param) => `params?.params?.${param}`);
337
- writer
338
- .write(`if (${allConditions.join(`${node_os_1.EOL}\t|| `)})`)
339
- .block(() => {
308
+ writer.write(`if (${allConditions.join(`${node_os_1.EOL}\t|| `)})`).block(() => {
340
309
  writer.write(`withClause += EOL + \`${withFragment.fragment}\`;`);
341
310
  paramValues.forEach((paramValues) => {
342
311
  writer.writeLine(`paramsValues.push(${paramValues});`);
343
312
  });
344
313
  });
345
314
  });
346
- writer
347
- .write(`let sql = 'WITH ' + withClause + EOL + 'SELECT';`)
348
- .newLine();
315
+ writer.write(`let sql = 'WITH ' + withClause + EOL + 'SELECT';`).newLine();
349
316
  }
350
317
  else {
351
318
  writer.write(`let sql = 'SELECT';`).newLine();
352
319
  }
353
320
  (_c = tsDescriptor.dynamicQuery2) === null || _c === void 0 ? void 0 : _c.select.forEach((select, index) => {
354
- writer
355
- .write(`if (params?.select == null || params.select.${tsDescriptor.columns[index].name})`)
356
- .block(() => {
321
+ writer.write(`if (params?.select == null || params.select.${tsDescriptor.columns[index].name})`).block(() => {
357
322
  writer.writeLine(`sql = appendSelect(sql, \`${select.fragment}\`);`);
358
323
  select.parameters.forEach((param) => {
359
324
  writer.writeLine(`paramsValues.push(params?.params?.${param} ?? null);`);
@@ -372,15 +337,9 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
372
337
  }
373
338
  const whereConditions = from.dependOnFields.map((fieldIndex) => `where.${tsDescriptor.columns[fieldIndex].name} != null`);
374
339
  const orderByConditions = ((_a = from.dependOnOrderBy) === null || _a === void 0 ? void 0 : _a.map((orderBy) => `orderBy['${orderBy}'] != null`)) || [];
375
- const allConditions = [
376
- ...selectConditions,
377
- ...whereConditions,
378
- ...orderByConditions
379
- ];
340
+ const allConditions = [...selectConditions, ...whereConditions, ...orderByConditions];
380
341
  const paramValues = from.parameters.map((param) => `params?.params?.${param}`);
381
- writer
382
- .write(`if (${allConditions.join(`${node_os_1.EOL}\t|| `)})`)
383
- .block(() => {
342
+ writer.write(`if (${allConditions.join(`${node_os_1.EOL}\t|| `)})`).block(() => {
384
343
  writer.write(`sql += EOL + \`${from.fragment}\`;`);
385
344
  paramValues.forEach((paramValues) => {
386
345
  writer.writeLine(`paramsValues.push(${paramValues});`);
@@ -401,9 +360,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
401
360
  writer.writeLine('const where = whereCondition(condition);');
402
361
  (_a = tsDescriptor.dynamicQuery2) === null || _a === void 0 ? void 0 : _a.select.forEach((select, index) => {
403
362
  if (select.parameters.length > 0) {
404
- writer
405
- .write(`if (condition[0] == '${tsDescriptor.columns[index].name}')`)
406
- .block(() => {
363
+ writer.write(`if (condition[0] == '${tsDescriptor.columns[index].name}')`).block(() => {
407
364
  select.parameters.forEach((param) => {
408
365
  writer.writeLine(`paramsValues.push(params?.params?.${param} ?? null);`);
409
366
  });
@@ -434,10 +391,15 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
434
391
  .indent()
435
392
  .write(`.map(data => mapArrayTo${resultTypeName}(data, params?.select))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
436
393
  }
437
- if (client === 'libsql') {
394
+ if (client === 'bun:sqlite') {
395
+ writer.write('return db.prepare(sql)').newLine();
396
+ writer.indent().write('.values(paramsValues)').newLine();
438
397
  writer
439
- .write('return client.execute({ sql, args: paramsValues })')
440
- .newLine();
398
+ .indent()
399
+ .write(`.map(data => mapArrayTo${resultTypeName}(data, params?.select))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
400
+ }
401
+ if (client === 'libsql') {
402
+ writer.write('return client.execute({ sql, args: paramsValues })').newLine();
441
403
  writer.indent().write('.then(res => res.rows)').newLine();
442
404
  writer
443
405
  .indent()
@@ -445,15 +407,11 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
445
407
  }
446
408
  });
447
409
  writer.blankLine();
448
- writer
449
- .write(`function mapArrayTo${resultTypeName}(data: any, select?: ${selectColumnsTypeName})`)
450
- .block(() => {
410
+ writer.write(`function mapArrayTo${resultTypeName}(data: any, select?: ${selectColumnsTypeName})`).block(() => {
451
411
  writer.writeLine(`const result = {} as ${resultTypeName};`);
452
412
  writer.writeLine('let rowIndex = -1;');
453
413
  tsDescriptor.columns.forEach((tsField) => {
454
- writer
455
- .write(`if (select == null || select.${tsField.name})`)
456
- .block(() => {
414
+ writer.write(`if (select == null || select.${tsField.name})`).block(() => {
457
415
  writer.writeLine('rowIndex++;');
458
416
  writer.writeLine(`result.${tsField.name} = ${toDriver('data[rowIndex]', tsField)};`);
459
417
  });
@@ -461,9 +419,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
461
419
  writer.write('return result;');
462
420
  });
463
421
  writer.blankLine();
464
- writer
465
- .write('function appendSelect(sql: string, selectField: string)')
466
- .block(() => {
422
+ writer.write('function appendSelect(sql: string, selectField: string)').block(() => {
467
423
  writer.write(`if (sql == 'SELECT')`).block(() => {
468
424
  writer.writeLine('return sql + EOL + selectField;');
469
425
  });
@@ -472,13 +428,9 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
472
428
  });
473
429
  });
474
430
  writer.blankLine();
475
- writer
476
- .write(`function whereConditionsToObject(whereConditions?: ${whereTypeName}[])`)
477
- .block(() => {
431
+ writer.write(`function whereConditionsToObject(whereConditions?: ${whereTypeName}[])`).block(() => {
478
432
  writer.writeLine('const obj = {} as any;');
479
- writer
480
- .write('whereConditions?.forEach(condition => ')
481
- .inlineBlock(() => {
433
+ writer.write('whereConditions?.forEach(condition => ').inlineBlock(() => {
482
434
  writer.writeLine('const where = whereCondition(condition);');
483
435
  writer.write('if (where?.hasValue) ').block(() => {
484
436
  writer.writeLine('obj[condition[0]] = true;');
@@ -489,9 +441,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
489
441
  });
490
442
  if (orderByField != null) {
491
443
  writer.blankLine();
492
- writer
493
- .write(`function orderByToObject(orderBy: ${dynamicParamsTypeName}['orderBy'])`)
494
- .block(() => {
444
+ writer.write(`function orderByToObject(orderBy: ${dynamicParamsTypeName}['orderBy'])`).block(() => {
495
445
  writer.writeLine('const obj = {} as any;');
496
446
  writer.write('orderBy?.forEach(order => ').inlineBlock(() => {
497
447
  writer.writeLine('obj[order[0]] = true;');
@@ -507,9 +457,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
507
457
  writer.writeLine('values: any[];');
508
458
  });
509
459
  writer.blankLine();
510
- writer
511
- .write(`function whereCondition(condition: ${whereTypeName}): WhereConditionResult | undefined `)
512
- .block(() => {
460
+ writer.write(`function whereCondition(condition: ${whereTypeName}): WhereConditionResult | undefined `).block(() => {
513
461
  writer.blankLine();
514
462
  writer.writeLine('const selectFragment = selectFragments[condition[0]];');
515
463
  writer.writeLine('const operator = condition[1];');
@@ -542,9 +490,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
542
490
  });
543
491
  }
544
492
  });
545
- writer
546
- .write(`if (operator == 'IN' || operator == 'NOT IN') `)
547
- .block(() => {
493
+ writer.write(`if (operator == 'IN' || operator == 'NOT IN') `).block(() => {
548
494
  if ((0, code_generator_1.hasDateColumn)(tsDescriptor.columns)) {
549
495
  writer.write('return ').block(() => {
550
496
  writer.writeLine("sql: `${selectFragment} ${operator} (${condition[2]?.map(value => isDate(value) ? 'date(?)' : '?').join(', ')})`,");
@@ -560,9 +506,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
560
506
  });
561
507
  }
562
508
  });
563
- writer
564
- .write('if (NumericOperatorList.includes(operator)) ')
565
- .block(() => {
509
+ writer.write('if (NumericOperatorList.includes(operator)) ').block(() => {
566
510
  if ((0, code_generator_1.hasDateColumn)(tsDescriptor.columns)) {
567
511
  writer.writeLine('const value = isDate(condition[2]) ? condition[2]?.toISOString() : condition[2];');
568
512
  writer.writeLine(`const param = isDate(condition[2]) ? 'date(?)' : '?';`);
@@ -627,20 +571,13 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
627
571
  : `function ${camelCaseName}(${functionArguments}): ${returnType}`;
628
572
  writer.write(`export ${crudFunction}`).block(() => {
629
573
  const idColumn = tsDescriptor.parameters[0].name;
630
- writeExecuteCrudBlock(client, queryType, tableName, tsDescriptor.columns, idColumn, queryParams, paramsTypeName, dataTypeName, resultTypeName, writer);
574
+ writeExecuteCrudBlock(client, queryType, tableName, tsDescriptor.columns, idColumn, client == 'bun:sqlite' ? queryParamsWithoutBrackets : queryParams, paramsTypeName, dataTypeName, resultTypeName, writer);
631
575
  });
632
576
  }
633
- if (tsDescriptor.dynamicQuery2 == null &&
634
- !isCrud &&
635
- (queryType === 'Select' ||
636
- (queryType === 'Insert' && tsDescriptor.returning))) {
577
+ if (tsDescriptor.dynamicQuery2 == null && !isCrud && (queryType === 'Select' || (queryType === 'Insert' && tsDescriptor.returning))) {
637
578
  if (client === 'better-sqlite3') {
638
- writer
639
- .write(`export function ${camelCaseName}(${functionArguments}): ${returnType}`)
640
- .block(() => {
641
- const processedSql = tsDescriptor.orderByColumns
642
- ? (0, code_generator_1.replaceOrderByParam)(sql)
643
- : sql;
579
+ writer.write(`export function ${camelCaseName}(${functionArguments}): ${returnType}`).block(() => {
580
+ const processedSql = tsDescriptor.orderByColumns ? (0, code_generator_1.replaceOrderByParam)(sql) : sql;
644
581
  const sqlSplit = processedSql.split('\n');
645
582
  writer.write('const sql = `').newLine();
646
583
  sqlSplit.forEach((sqlLine) => {
@@ -650,18 +587,26 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
650
587
  writer.write('return db.prepare(sql)').newLine();
651
588
  writer.indent().write('.raw(true)').newLine();
652
589
  writer.indent().write(`.all(${queryParams})`).newLine();
653
- writer
654
- .indent()
655
- .write(`.map(data => mapArrayTo${resultTypeName}(data))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
590
+ writer.indent().write(`.map(data => mapArrayTo${resultTypeName}(data))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
591
+ });
592
+ }
593
+ if (client === 'bun:sqlite') {
594
+ writer.write(`export function ${camelCaseName}(${functionArguments}): ${returnType}`).block(() => {
595
+ const processedSql = tsDescriptor.orderByColumns ? (0, code_generator_1.replaceOrderByParam)(sql) : sql;
596
+ const sqlSplit = processedSql.split('\n');
597
+ writer.write('const sql = `').newLine();
598
+ sqlSplit.forEach((sqlLine) => {
599
+ writer.indent().write(sqlLine).newLine();
600
+ });
601
+ writer.indent().write('`').newLine();
602
+ writer.write('return db.prepare(sql)').newLine();
603
+ writer.indent().write(`.values(${queryParamsWithoutBrackets})`).newLine();
604
+ writer.indent().write(`.map(data => mapArrayTo${resultTypeName}(data))${tsDescriptor.multipleRowsResult ? '' : '[0]'};`);
656
605
  });
657
606
  }
658
607
  if (!isCrud && client === 'libsql') {
659
- writer
660
- .write(`export async function ${camelCaseName}(${functionArguments}): Promise<${returnType}>`)
661
- .block(() => {
662
- const processedSql = tsDescriptor.orderByColumns
663
- ? (0, code_generator_1.replaceOrderByParam)(sql)
664
- : sql;
608
+ writer.write(`export async function ${camelCaseName}(${functionArguments}): Promise<${returnType}>`).block(() => {
609
+ const processedSql = tsDescriptor.orderByColumns ? (0, code_generator_1.replaceOrderByParam)(sql) : sql;
665
610
  const sqlSplit = processedSql.split('\n');
666
611
  writer.write('const sql = `').newLine();
667
612
  sqlSplit.forEach((sqlLine) => {
@@ -673,47 +618,33 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
673
618
  if (queryType === 'Select') {
674
619
  writer.indent().write('.then(res => res.rows)').newLine();
675
620
  if (tsDescriptor.multipleRowsResult) {
676
- writer
677
- .indent()
678
- .write(`.then(rows => rows.map(row => mapArrayTo${resultTypeName}(row)));`);
621
+ writer.indent().write(`.then(rows => rows.map(row => mapArrayTo${resultTypeName}(row)));`);
679
622
  }
680
623
  else {
681
- writer
682
- .indent()
683
- .write(`.then(rows => mapArrayTo${resultTypeName}(rows[0]));`);
624
+ writer.indent().write(`.then(rows => mapArrayTo${resultTypeName}(rows[0]));`);
684
625
  }
685
626
  }
686
627
  if (queryType === 'Insert') {
687
628
  if (tsDescriptor.returning) {
688
629
  writer.indent().write('.then(res => res.rows)').newLine();
689
- writer
690
- .indent()
691
- .write(`.then(rows => mapArrayTo${resultTypeName}(rows[0]));`);
630
+ writer.indent().write(`.then(rows => mapArrayTo${resultTypeName}(rows[0]));`);
692
631
  }
693
632
  else {
694
- writer
695
- .indent()
696
- .write(`.then(res => mapArrayTo${resultTypeName}(res));`);
633
+ writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`);
697
634
  }
698
635
  }
699
636
  });
700
637
  }
701
638
  }
702
- if (!isCrud &&
703
- (queryType === 'Update' ||
704
- queryType === 'Delete' ||
705
- (queryType === 'Insert' && !tsDescriptor.returning))) {
706
- if (client === 'better-sqlite3') {
707
- writer
708
- .write(`export function ${camelCaseName}(${functionArguments}): ${resultTypeName}`)
709
- .block(() => {
710
- writeExecuteBlock(sql, queryParams, resultTypeName, writer);
639
+ if (!isCrud && (queryType === 'Update' || queryType === 'Delete' || (queryType === 'Insert' && !tsDescriptor.returning))) {
640
+ if (client === 'better-sqlite3' || client === 'bun:sqlite') {
641
+ writer.write(`export function ${camelCaseName}(${functionArguments}): ${resultTypeName}`).block(() => {
642
+ const params = client === 'better-sqlite3' ? queryParams : queryParamsWithoutBrackets;
643
+ writeExecuteBlock(sql, params, resultTypeName, writer);
711
644
  });
712
645
  }
713
646
  if (client === 'libsql') {
714
- writer
715
- .write(`export async function ${camelCaseName}(${functionArguments}): Promise<${resultTypeName}>`)
716
- .block(() => {
647
+ writer.write(`export async function ${camelCaseName}(${functionArguments}): Promise<${resultTypeName}>`).block(() => {
717
648
  const sqlSplit = sql.split('\n');
718
649
  writer.write('const sql = `').newLine();
719
650
  sqlSplit.forEach((sqlLine) => {
@@ -722,18 +653,13 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
722
653
  writer.indent().write('`').newLine();
723
654
  const executeParams = queryParams !== '' ? `{ sql, args: ${queryParams} }` : 'sql';
724
655
  writer.write(`return client.execute(${executeParams})`).newLine();
725
- writer
726
- .indent()
727
- .write(`.then(res => mapArrayTo${resultTypeName}(res));`);
656
+ writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`);
728
657
  });
729
658
  }
730
659
  }
731
- if ((queryType === 'Select' || tsDescriptor.returning) &&
732
- tsDescriptor.dynamicQuery2 == null) {
660
+ if ((queryType === 'Select' || tsDescriptor.returning) && tsDescriptor.dynamicQuery2 == null) {
733
661
  writer.blankLine();
734
- writer
735
- .write(`function mapArrayTo${resultTypeName}(data: any) `)
736
- .block(() => {
662
+ writer.write(`function mapArrayTo${resultTypeName}(data: any) `).block(() => {
737
663
  writer.write(`const result: ${resultTypeName} = `).block(() => {
738
664
  tsDescriptor.columns.forEach((col, index) => {
739
665
  const separator = index < tsDescriptor.columns.length - 1 ? ',' : '';
@@ -743,13 +669,9 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
743
669
  writer.writeLine('return result;');
744
670
  });
745
671
  }
746
- else if (client === 'libsql' &&
747
- !tsDescriptor.returning &&
748
- tsDescriptor.dynamicQuery2 == null) {
672
+ else if (client === 'libsql' && !tsDescriptor.returning && tsDescriptor.dynamicQuery2 == null) {
749
673
  writer.blankLine();
750
- writer
751
- .write(`function mapArrayTo${resultTypeName}(data: any) `)
752
- .block(() => {
674
+ writer.write(`function mapArrayTo${resultTypeName}(data: any) `).block(() => {
753
675
  writer.write(`const result: ${resultTypeName} = `).block(() => {
754
676
  tsDescriptor.columns.forEach((col, index) => {
755
677
  const separator = index < tsDescriptor.columns.length - 1 ? ',' : '';
@@ -760,9 +682,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
760
682
  });
761
683
  }
762
684
  if (tsDescriptor.orderByColumns) {
763
- const orderByType = tsDescriptor.dynamicQuery2 == null
764
- ? paramsTypeName
765
- : dynamicParamsTypeName;
685
+ const orderByType = tsDescriptor.dynamicQuery2 == null ? paramsTypeName : dynamicParamsTypeName;
766
686
  if (orderByField != null) {
767
687
  writer.blankLine();
768
688
  writer.write('const orderByFragments = ').inlineBlock(() => {
@@ -776,9 +696,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
776
696
  writer.blankLine();
777
697
  writer.writeLine(`export type ${orderByTypeName} = keyof typeof orderByFragments;`);
778
698
  writer.blankLine();
779
- writer
780
- .write(`function escapeOrderBy(orderBy: ${orderByType}['orderBy']): string`)
781
- .block(() => {
699
+ writer.write(`function escapeOrderBy(orderBy: ${orderByType}['orderBy']): string`).block(() => {
782
700
  writer.writeLine(`return orderBy.map(order => \`\${orderByFragments[order[0]]} \${order[1] == 'desc' ? 'desc' : 'asc'}\`).join(', ');`);
783
701
  });
784
702
  }
@@ -803,10 +721,8 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
803
721
  relations.forEach((relation, index) => {
804
722
  const relationType = (0, code_generator_1.generateRelationType)(capitalizedName, relation.name);
805
723
  if (index === 0) {
806
- if (client === 'better-sqlite3') {
807
- writer
808
- .write(`export function ${camelCaseName}Nested(${functionArguments}): ${relationType}[]`)
809
- .block(() => {
724
+ if (client === 'better-sqlite3' || client == 'bun:sqlite') {
725
+ writer.write(`export function ${camelCaseName}Nested(${functionArguments}): ${relationType}[]`).block(() => {
810
726
  const params = tsDescriptor.parameters.length > 0 ? ', params' : '';
811
727
  writer.writeLine(`const selectResult = ${camelCaseName}(db${params});`);
812
728
  writer.write('if (selectResult.length == 0)').block(() => {
@@ -816,9 +732,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
816
732
  });
817
733
  }
818
734
  else if (client === 'libsql') {
819
- writer
820
- .write(`export async function ${camelCaseName}Nested(${functionArguments}): Promise<${relationType}[]>`)
821
- .block(() => {
735
+ writer.write(`export async function ${camelCaseName}Nested(${functionArguments}): Promise<${relationType}[]>`).block(() => {
822
736
  const params = tsDescriptor.parameters.length > 0 ? ', params' : '';
823
737
  writer.writeLine(`const selectResult = await ${camelCaseName}(client${params});`);
824
738
  writer.write('if (selectResult.length == 0)').block(() => {
@@ -831,9 +745,7 @@ function generateCodeFromTsDescriptor(client, queryName, tsDescriptor, isCrud =
831
745
  writeCollectFunction(writer, relation, tsDescriptor.columns, capitalizedName, resultTypeName);
832
746
  });
833
747
  writer.blankLine();
834
- writer
835
- .write('const groupBy = <T, Q>(array: T[], predicate: (value: T, index: number, array: T[]) => Q) =>')
836
- .block(() => {
748
+ writer.write('const groupBy = <T, Q>(array: T[], predicate: (value: T, index: number, array: T[]) => Q) =>').block(() => {
837
749
  writer
838
750
  .write('return array.reduce((map, value, index, array) => ')
839
751
  .inlineBlock(() => {
@@ -882,18 +794,17 @@ function writeExecutSelectCrudBlock(client, tableName, idColumn, columns, queryP
882
794
  writer.write('return db.prepare(sql)').newLine();
883
795
  writer.indent().write('.raw(true)').newLine();
884
796
  writer.indent().write(`.all(${queryParams})`).newLine();
885
- writer
886
- .indent()
887
- .write(`.map(data => mapArrayTo${resultTypeName}(data))[0];`);
797
+ writer.indent().write(`.map(data => mapArrayTo${resultTypeName}(data))[0];`);
798
+ }
799
+ else if (client === 'bun:sqlite') {
800
+ writer.write('return db.prepare(sql)').newLine();
801
+ writer.indent().write(`.values(${queryParams})`).newLine();
802
+ writer.indent().write(`.map(data => mapArrayTo${resultTypeName}(data))[0];`);
888
803
  }
889
804
  else {
890
- writer
891
- .write(`return client.execute({ sql, args: ${queryParams} })`)
892
- .newLine();
805
+ writer.write(`return client.execute({ sql, args: ${queryParams} })`).newLine();
893
806
  writer.indent().write('.then(res => res.rows)').newLine();
894
- writer
895
- .indent()
896
- .write(`.then(rows => mapArrayTo${resultTypeName}(rows[0]));`);
807
+ writer.indent().write(`.then(rows => mapArrayTo${resultTypeName}(rows[0]));`);
897
808
  }
898
809
  }
899
810
  function writeExecuteInsertCrudBlock(client, tableName, paramTypeName, resultTypeName, writer) {
@@ -903,25 +814,20 @@ function writeExecuteInsertCrudBlock(client, tableName, paramTypeName, resultTyp
903
814
  writer.writeLine('const values = columns.map(col => params[col]!);');
904
815
  writer.blankLine();
905
816
  writer.writeLine('const sql = columns.length == 0');
906
- writer
907
- .indent()
908
- .write(`? \`INSERT INTO ${tableName} DEFAULT VALUES\``)
909
- .newLine();
910
- writer
911
- .indent()
912
- .write(`: \`INSERT INTO ${tableName}(\${columns.join(',')}) VALUES(\${columns.map(_ => '?').join(',')})\``)
913
- .newLine();
817
+ writer.indent().write(`? \`INSERT INTO ${tableName} DEFAULT VALUES\``).newLine();
818
+ writer.indent().write(`: \`INSERT INTO ${tableName}(\${columns.join(',')}) VALUES(\${columns.map(_ => '?').join(',')})\``).newLine();
914
819
  writer.blankLine();
915
820
  if (client === 'better-sqlite3') {
916
821
  writer.write('return db.prepare(sql)').newLine();
917
822
  writer.indent().write(`.run(values) as ${resultTypeName};`);
918
823
  }
824
+ else if (client == 'bun:sqlite') {
825
+ writer.write('return db.prepare(sql)').newLine();
826
+ writer.indent().write(`.run(...values) as ${resultTypeName};`);
827
+ }
919
828
  else {
920
829
  writer.write('return client.execute({ sql, args: values })').newLine();
921
- writer
922
- .indent()
923
- .write(`.then(res => mapArrayTo${resultTypeName}(res));`)
924
- .newLine();
830
+ writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`).newLine();
925
831
  }
926
832
  }
927
833
  function writeExecuteUpdateCrudBlock(client, tableName, idColumn, paramTypeName, resultTypeName, writer) {
@@ -932,22 +838,20 @@ function writeExecuteUpdateCrudBlock(client, tableName, idColumn, paramTypeName,
932
838
  writer.blankLine();
933
839
  writer.writeLine('const sql = `');
934
840
  writer.indent().write(`UPDATE ${tableName}`).newLine();
935
- writer
936
- .indent()
937
- .write(`SET \${columns.map(col => \`\${col} = ?\`).join(', ')}`)
938
- .newLine();
841
+ writer.indent().write(`SET \${columns.map(col => \`\${col} = ?\`).join(', ')}`).newLine();
939
842
  writer.indent().write(`WHERE ${idColumn} = ?\``).newLine();
940
843
  writer.blankLine();
941
844
  if (client === 'better-sqlite3') {
942
845
  writer.write('return db.prepare(sql)').newLine();
943
846
  writer.indent().write(`.run(values) as ${resultTypeName};`);
944
847
  }
848
+ else if (client === 'bun:sqlite') {
849
+ writer.write('return db.prepare(sql)').newLine();
850
+ writer.indent().write(`.run(...values) as ${resultTypeName};`);
851
+ }
945
852
  else {
946
853
  writer.write('return client.execute({ sql, args: values })').newLine();
947
- writer
948
- .indent()
949
- .write(`.then(res => mapArrayTo${resultTypeName}(res));`)
950
- .newLine();
854
+ writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`).newLine();
951
855
  }
952
856
  }
953
857
  function writeExecutDeleteCrudBlock(client, tableName, idColumn, queryParams, resultTypeName, writer) {
@@ -958,19 +862,15 @@ function writeExecutDeleteCrudBlock(client, tableName, idColumn, queryParams, re
958
862
  writer.blankLine();
959
863
  if (client === 'better-sqlite3') {
960
864
  writer.write('return db.prepare(sql)').newLine();
961
- writer
962
- .indent()
963
- .write(`.run(${queryParams}) as ${resultTypeName};`)
964
- .newLine();
865
+ writer.indent().write(`.run(${queryParams}) as ${resultTypeName};`).newLine();
866
+ }
867
+ else if (client === 'bun:sqlite') {
868
+ writer.write('return db.prepare(sql)').newLine();
869
+ writer.indent().write(`.run(${queryParams}) as ${resultTypeName};`).newLine();
965
870
  }
966
871
  else {
967
- writer
968
- .write(`return client.execute({ sql, args: ${queryParams} })`)
969
- .newLine();
970
- writer
971
- .indent()
972
- .write(`.then(res => mapArrayTo${resultTypeName}(res));`)
973
- .newLine();
872
+ writer.write(`return client.execute({ sql, args: ${queryParams} })`).newLine();
873
+ writer.indent().write(`.then(res => mapArrayTo${resultTypeName}(res));`).newLine();
974
874
  }
975
875
  }
976
876
  function toDriver(variableData, param) {
@@ -996,9 +896,7 @@ function writeCollectFunction(writer, relation, columns, capitalizedName, result
996
896
  const relationType = (0, code_generator_1.generateRelationType)(capitalizedName, relation.name);
997
897
  const collectFunctionName = `collect${relationType}`;
998
898
  writer.blankLine();
999
- writer
1000
- .write(`function ${collectFunctionName}(selectResult: ${resultTypeName}[]): ${relationType}[]`)
1001
- .block(() => {
899
+ writer.write(`function ${collectFunctionName}(selectResult: ${resultTypeName}[]): ${relationType}[]`).block(() => {
1002
900
  const groupBy = columns[relation.groupIndex].name;
1003
901
  writer.writeLine(`const grouped = groupBy(selectResult.filter(r => r.${groupBy} != null), r => r.${groupBy});`);
1004
902
  writer