drizzle-orm 0.45.1 → 0.45.2

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.
@@ -47,14 +47,16 @@ class MySqlDialect {
47
47
  await tx.execute(sql.raw(stmt));
48
48
  }
49
49
  await tx.execute(
50
- sql`insert into ${sql.identifier(migrationsTable)} (\`hash\`, \`created_at\`) values(${migration.hash}, ${migration.folderMillis})`
50
+ sql`insert into ${sql.identifier(
51
+ migrationsTable
52
+ )} (\`hash\`, \`created_at\`) values(${migration.hash}, ${migration.folderMillis})`
51
53
  );
52
54
  }
53
55
  }
54
56
  });
55
57
  }
56
58
  escapeName(name) {
57
- return `\`${name}\``;
59
+ return `\`${name.replace(/`/g, "``")}\``;
58
60
  }
59
61
  escapeParam(_num) {
60
62
  return `?`;
@@ -74,7 +76,14 @@ class MySqlDialect {
74
76
  withSqlChunks.push(sql` `);
75
77
  return sql.join(withSqlChunks);
76
78
  }
77
- buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) {
79
+ buildDeleteQuery({
80
+ table,
81
+ where,
82
+ returning,
83
+ withList,
84
+ limit,
85
+ orderBy
86
+ }) {
78
87
  const withSql = this.buildWithCTE(withList);
79
88
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
80
89
  const whereSql = where ? sql` where ${where}` : void 0;
@@ -88,18 +97,28 @@ class MySqlDialect {
88
97
  (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
89
98
  );
90
99
  const setSize = columnNames.length;
91
- return sql.join(columnNames.flatMap((colName, i) => {
92
- const col = tableColumns[colName];
93
- const onUpdateFnResult = col.onUpdateFn?.();
94
- const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));
95
- const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
96
- if (i < setSize - 1) {
97
- return [res, sql.raw(", ")];
98
- }
99
- return [res];
100
- }));
100
+ return sql.join(
101
+ columnNames.flatMap((colName, i) => {
102
+ const col = tableColumns[colName];
103
+ const onUpdateFnResult = col.onUpdateFn?.();
104
+ const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));
105
+ const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
106
+ if (i < setSize - 1) {
107
+ return [res, sql.raw(", ")];
108
+ }
109
+ return [res];
110
+ })
111
+ );
101
112
  }
102
- buildUpdateQuery({ table, set, where, returning, withList, limit, orderBy }) {
113
+ buildUpdateQuery({
114
+ table,
115
+ set,
116
+ where,
117
+ returning,
118
+ withList,
119
+ limit,
120
+ orderBy
121
+ }) {
103
122
  const withSql = this.buildWithCTE(withList);
104
123
  const setSql = this.buildUpdateSet(table, set);
105
124
  const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
@@ -206,7 +225,9 @@ class MySqlDialect {
206
225
  ))(f.field.table)) {
207
226
  const tableName = getTableName(f.field.table);
208
227
  throw new Error(
209
- `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
228
+ `Your "${f.path.join(
229
+ "->"
230
+ )}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
210
231
  );
211
232
  }
212
233
  }
@@ -216,7 +237,9 @@ class MySqlDialect {
216
237
  const selection = this.buildSelection(fieldsList, { isSingleTable });
217
238
  const tableSql = (() => {
218
239
  if (is(table, Table) && table[Table.Symbol.IsAlias]) {
219
- return sql`${sql`${sql.identifier(table[Table.Symbol.Schema] ?? "")}.`.if(table[Table.Symbol.Schema])}${sql.identifier(table[Table.Symbol.OriginalName])} ${sql.identifier(table[Table.Symbol.Name])}`;
240
+ return sql`${sql`${sql.identifier(table[Table.Symbol.Schema] ?? "")}.`.if(table[Table.Symbol.Schema])}${sql.identifier(
241
+ table[Table.Symbol.OriginalName]
242
+ )} ${sql.identifier(table[Table.Symbol.Name])}`;
220
243
  }
221
244
  return table;
222
245
  })();
@@ -234,9 +257,18 @@ class MySqlDialect {
234
257
  const tableSchema = table2[MySqlTable.Symbol.Schema];
235
258
  const origTableName = table2[MySqlTable.Symbol.OriginalName];
236
259
  const alias = tableName === origTableName ? void 0 : joinMeta.alias;
237
- const useIndexSql2 = this.buildIndex({ indexes: joinMeta.useIndex, indexFor: "USE" });
238
- const forceIndexSql2 = this.buildIndex({ indexes: joinMeta.forceIndex, indexFor: "FORCE" });
239
- const ignoreIndexSql2 = this.buildIndex({ indexes: joinMeta.ignoreIndex, indexFor: "IGNORE" });
260
+ const useIndexSql2 = this.buildIndex({
261
+ indexes: joinMeta.useIndex,
262
+ indexFor: "USE"
263
+ });
264
+ const forceIndexSql2 = this.buildIndex({
265
+ indexes: joinMeta.forceIndex,
266
+ indexFor: "FORCE"
267
+ });
268
+ const ignoreIndexSql2 = this.buildIndex({
269
+ indexes: joinMeta.ignoreIndex,
270
+ indexFor: "IGNORE"
271
+ });
240
272
  joinsArray.push(
241
273
  sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${useIndexSql2}${forceIndexSql2}${ignoreIndexSql2}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
242
274
  );
@@ -266,8 +298,14 @@ class MySqlDialect {
266
298
  const limitSql = this.buildLimit(limit);
267
299
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
268
300
  const useIndexSql = this.buildIndex({ indexes: useIndex, indexFor: "USE" });
269
- const forceIndexSql = this.buildIndex({ indexes: forceIndex, indexFor: "FORCE" });
270
- const ignoreIndexSql = this.buildIndex({ indexes: ignoreIndex, indexFor: "IGNORE" });
301
+ const forceIndexSql = this.buildIndex({
302
+ indexes: forceIndex,
303
+ indexFor: "FORCE"
304
+ });
305
+ const ignoreIndexSql = this.buildIndex({
306
+ indexes: ignoreIndex,
307
+ indexFor: "IGNORE"
308
+ });
271
309
  let lockingClausesSql;
272
310
  if (lockingClause) {
273
311
  const { config, strength } = lockingClause;
@@ -308,12 +346,16 @@ class MySqlDialect {
308
346
  const orderByValues = [];
309
347
  for (const orderByUnit of orderBy) {
310
348
  if (is(orderByUnit, MySqlColumn)) {
311
- orderByValues.push(sql.identifier(this.casing.getColumnCasing(orderByUnit)));
349
+ orderByValues.push(
350
+ sql.identifier(this.casing.getColumnCasing(orderByUnit))
351
+ );
312
352
  } else if (is(orderByUnit, SQL)) {
313
353
  for (let i = 0; i < orderByUnit.queryChunks.length; i++) {
314
354
  const chunk = orderByUnit.queryChunks[i];
315
355
  if (is(chunk, MySqlColumn)) {
316
- orderByUnit.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
356
+ orderByUnit.queryChunks[i] = sql.identifier(
357
+ this.casing.getColumnCasing(chunk)
358
+ );
317
359
  }
318
360
  }
319
361
  orderByValues.push(sql`${orderByUnit}`);
@@ -328,7 +370,13 @@ class MySqlDialect {
328
370
  const offsetSql = offset ? sql` offset ${offset}` : void 0;
329
371
  return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
330
372
  }
331
- buildInsertQuery({ table, values: valuesOrSelect, ignore, onConflict, select }) {
373
+ buildInsertQuery({
374
+ table,
375
+ values: valuesOrSelect,
376
+ ignore,
377
+ onConflict,
378
+ select
379
+ }) {
332
380
  const valuesSqlList = [];
333
381
  const columns = table[Table.Symbol.Columns];
334
382
  const colEntries = Object.entries(columns).filter(
@@ -421,7 +469,10 @@ class MySqlDialect {
421
469
  }));
422
470
  } else {
423
471
  const aliasedColumns = Object.fromEntries(
424
- Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
472
+ Object.entries(tableConfig.columns).map(([key, value]) => [
473
+ key,
474
+ aliasedTableColumn(value, tableAlias)
475
+ ])
425
476
  );
426
477
  if (config.where) {
427
478
  const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
@@ -443,7 +494,9 @@ class MySqlDialect {
443
494
  }
444
495
  }
445
496
  if (selectedColumns.length > 0) {
446
- selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
497
+ selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter(
498
+ (key) => !selectedColumns.includes(key)
499
+ );
447
500
  }
448
501
  } else {
449
502
  selectedColumns = Object.keys(tableConfig.columns);
@@ -454,7 +507,13 @@ class MySqlDialect {
454
507
  }
455
508
  let selectedRelations = [];
456
509
  if (config.with) {
457
- selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
510
+ selectedRelations = Object.entries(config.with).filter(
511
+ (entry) => !!entry[1]
512
+ ).map(([tsKey, queryConfig]) => ({
513
+ tsKey,
514
+ queryConfig,
515
+ relation: tableConfig.relations[tsKey]
516
+ }));
458
517
  }
459
518
  let extras;
460
519
  if (config.extras) {
@@ -493,14 +552,21 @@ class MySqlDialect {
493
552
  queryConfig: selectedRelationConfigValue,
494
553
  relation
495
554
  } of selectedRelations) {
496
- const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
555
+ const normalizedRelation = normalizeRelation(
556
+ schema,
557
+ tableNamesMap,
558
+ relation
559
+ );
497
560
  const relationTableName = getTableUniqueName(relation.referencedTable);
498
561
  const relationTableTsName = tableNamesMap[relationTableName];
499
562
  const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
500
563
  const joinOn2 = and(
501
564
  ...normalizedRelation.fields.map(
502
565
  (field2, i) => eq(
503
- aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
566
+ aliasedTableColumn(
567
+ normalizedRelation.references[i],
568
+ relationTableAlias
569
+ ),
504
570
  aliasedTableColumn(field2, tableAlias)
505
571
  )
506
572
  )
@@ -516,7 +582,9 @@ class MySqlDialect {
516
582
  joinOn: joinOn2,
517
583
  nestedQueryRelation: relation
518
584
  });
519
- const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
585
+ const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(
586
+ selectedRelationTsKey
587
+ );
520
588
  joins.push({
521
589
  on: sql`true`,
522
590
  table: new Subquery(builtRelation.sql, {}, relationTableAlias),
@@ -535,7 +603,9 @@ class MySqlDialect {
535
603
  }
536
604
  }
537
605
  if (selection.length === 0) {
538
- throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
606
+ throw new DrizzleError({
607
+ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`
608
+ });
539
609
  }
540
610
  let result;
541
611
  where = and(joinOn, where);
@@ -549,14 +619,16 @@ class MySqlDialect {
549
619
  if (is(nestedQueryRelation, Many)) {
550
620
  field = sql`coalesce(json_arrayagg(${field}), json_array())`;
551
621
  }
552
- const nestedSelection = [{
553
- dbKey: "data",
554
- tsKey: "data",
555
- field: field.as("data"),
556
- isJson: true,
557
- relationTableTsKey: tableConfig.tsName,
558
- selection
559
- }];
622
+ const nestedSelection = [
623
+ {
624
+ dbKey: "data",
625
+ tsKey: "data",
626
+ field: field.as("data"),
627
+ isJson: true,
628
+ relationTableTsKey: tableConfig.tsName,
629
+ selection
630
+ }
631
+ ];
560
632
  const needsSubquery = limit !== void 0 || offset !== void 0 || (orderBy?.length ?? 0) > 0;
561
633
  if (needsSubquery) {
562
634
  result = this.buildSelectQuery({
@@ -567,10 +639,12 @@ class MySqlDialect {
567
639
  path: [],
568
640
  field: sql.raw("*")
569
641
  },
570
- ...((orderBy?.length ?? 0) > 0 ? [{
571
- path: [],
572
- field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
573
- }] : [])
642
+ ...((orderBy?.length ?? 0) > 0 ? [
643
+ {
644
+ path: [],
645
+ field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
646
+ }
647
+ ] : [])
574
648
  ],
575
649
  where,
576
650
  limit,
@@ -645,7 +719,10 @@ class MySqlDialect {
645
719
  }));
646
720
  } else {
647
721
  const aliasedColumns = Object.fromEntries(
648
- Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
722
+ Object.entries(tableConfig.columns).map(([key, value]) => [
723
+ key,
724
+ aliasedTableColumn(value, tableAlias)
725
+ ])
649
726
  );
650
727
  if (config.where) {
651
728
  const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
@@ -667,7 +744,9 @@ class MySqlDialect {
667
744
  }
668
745
  }
669
746
  if (selectedColumns.length > 0) {
670
- selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
747
+ selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter(
748
+ (key) => !selectedColumns.includes(key)
749
+ );
671
750
  }
672
751
  } else {
673
752
  selectedColumns = Object.keys(tableConfig.columns);
@@ -678,7 +757,13 @@ class MySqlDialect {
678
757
  }
679
758
  let selectedRelations = [];
680
759
  if (config.with) {
681
- selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
760
+ selectedRelations = Object.entries(config.with).filter(
761
+ (entry) => !!entry[1]
762
+ ).map(([tsKey, queryConfig]) => ({
763
+ tsKey,
764
+ queryConfig,
765
+ relation: tableConfig.relations[tsKey]
766
+ }));
682
767
  }
683
768
  let extras;
684
769
  if (config.extras) {
@@ -717,29 +802,38 @@ class MySqlDialect {
717
802
  queryConfig: selectedRelationConfigValue,
718
803
  relation
719
804
  } of selectedRelations) {
720
- const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
805
+ const normalizedRelation = normalizeRelation(
806
+ schema,
807
+ tableNamesMap,
808
+ relation
809
+ );
721
810
  const relationTableName = getTableUniqueName(relation.referencedTable);
722
811
  const relationTableTsName = tableNamesMap[relationTableName];
723
812
  const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
724
813
  const joinOn2 = and(
725
814
  ...normalizedRelation.fields.map(
726
815
  (field2, i) => eq(
727
- aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
816
+ aliasedTableColumn(
817
+ normalizedRelation.references[i],
818
+ relationTableAlias
819
+ ),
728
820
  aliasedTableColumn(field2, tableAlias)
729
821
  )
730
822
  )
731
823
  );
732
- const builtRelation = this.buildRelationalQueryWithoutLateralSubqueries({
733
- fullSchema,
734
- schema,
735
- tableNamesMap,
736
- table: fullSchema[relationTableTsName],
737
- tableConfig: schema[relationTableTsName],
738
- queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
739
- tableAlias: relationTableAlias,
740
- joinOn: joinOn2,
741
- nestedQueryRelation: relation
742
- });
824
+ const builtRelation = this.buildRelationalQueryWithoutLateralSubqueries(
825
+ {
826
+ fullSchema,
827
+ schema,
828
+ tableNamesMap,
829
+ table: fullSchema[relationTableTsName],
830
+ tableConfig: schema[relationTableTsName],
831
+ queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
832
+ tableAlias: relationTableAlias,
833
+ joinOn: joinOn2,
834
+ nestedQueryRelation: relation
835
+ }
836
+ );
743
837
  let fieldSql = sql`(${builtRelation.sql})`;
744
838
  if (is(relation, Many)) {
745
839
  fieldSql = sql`coalesce(${fieldSql}, json_array())`;
@@ -772,14 +866,16 @@ class MySqlDialect {
772
866
  if (is(nestedQueryRelation, Many)) {
773
867
  field = sql`json_arrayagg(${field})`;
774
868
  }
775
- const nestedSelection = [{
776
- dbKey: "data",
777
- tsKey: "data",
778
- field,
779
- isJson: true,
780
- relationTableTsKey: tableConfig.tsName,
781
- selection
782
- }];
869
+ const nestedSelection = [
870
+ {
871
+ dbKey: "data",
872
+ tsKey: "data",
873
+ field,
874
+ isJson: true,
875
+ relationTableTsKey: tableConfig.tsName,
876
+ selection
877
+ }
878
+ ];
783
879
  const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
784
880
  if (needsSubquery) {
785
881
  result = this.buildSelectQuery({
@@ -790,10 +886,12 @@ class MySqlDialect {
790
886
  path: [],
791
887
  field: sql.raw("*")
792
888
  },
793
- ...(orderBy.length > 0 ? [{
794
- path: [],
795
- field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
796
- }] : [])
889
+ ...(orderBy.length > 0 ? [
890
+ {
891
+ path: [],
892
+ field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
893
+ }
894
+ ] : [])
797
895
  ],
798
896
  where,
799
897
  limit,