• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vzakharchenko / forge-sql-orm / 17374211750

01 Sep 2025 09:58AM UTC coverage: 86.819% (+0.1%) from 86.696%
17374211750

Pull #565

github

web-flow
Merge 3e06606ef into 60685a987
Pull Request #565: Remove moment

267 of 329 branches covered (81.16%)

Branch coverage included in aggregate %.

18 of 23 new or added lines in 3 files covered. (78.26%)

1103 of 1249 relevant lines covered (88.31%)

11.14 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.69
/src/utils/sqlUtils.ts
1
import { AnyColumn, Column, isTable, SQL, sql, StringChunk } from "drizzle-orm";
1✔
2
import { AnyMySqlTable, MySqlCustomColumn } from "drizzle-orm/mysql-core/index";
3
import { DateTime } from "luxon";
1✔
4
import { PrimaryKeyBuilder } from "drizzle-orm/mysql-core/primary-keys";
5
import { AnyIndexBuilder } from "drizzle-orm/mysql-core/indexes";
6
import { CheckBuilder } from "drizzle-orm/mysql-core/checks";
7
import { ForeignKeyBuilder } from "drizzle-orm/mysql-core/foreign-keys";
8
import { UniqueConstraintBuilder } from "drizzle-orm/mysql-core/unique-constraint";
9
import type { SelectedFields } from "drizzle-orm/mysql-core/query-builders/select.types";
10
import { MySqlTable } from "drizzle-orm/mysql-core";
11
import { isSQLWrapper } from "drizzle-orm/sql/sql";
1✔
12

13
/**
14
 * Interface representing table metadata information
15
 */
16
export interface MetadataInfo {
17
  /** The name of the table */
18
  tableName: string;
19
  /** Record of column names and their corresponding column definitions */
20
  columns: Record<string, AnyColumn>;
21
  /** Array of index builders */
22
  indexes: AnyIndexBuilder[];
23
  /** Array of check constraint builders */
24
  checks: CheckBuilder[];
25
  /** Array of foreign key builders */
26
  foreignKeys: ForeignKeyBuilder[];
27
  /** Array of primary key builders */
28
  primaryKeys: PrimaryKeyBuilder[];
29
  /** Array of unique constraint builders */
30
  uniqueConstraints: UniqueConstraintBuilder[];
31
  /** Array of all extra builders */
32
  extras: any[];
33
}
34

35
/**
36
 * Interface for config builder data
37
 */
38
interface ConfigBuilderData {
39
  value?: any;
40
  [key: string]: any;
41
}
42

43
/**
44
 * Parses a date string into a Date object using the specified format
45
 * @param value - The date string to parse or Date
46
 * @param format - The format to use for parsing
47
 * @returns Date object
48
 */
49

50
export const parseDateTime = (value: string | Date, format: string): Date => {
1✔
51
  let result: Date;
9✔
52
  if (value instanceof Date) {
9✔
53
    return value;
1✔
54
  }
1✔
55
  // 1. Try to parse using the provided format (strict mode)
56
  const dt = DateTime.fromFormat(value, format);
8✔
57
  if (dt.isValid) {
9✔
58
    result = dt.toJSDate();
4✔
59
  } else {
4✔
60
    // 2. Try to parse as ISO string
61
    const isoDt = DateTime.fromISO(value);
4✔
62
    if (isoDt.isValid) {
4!
NEW
63
      result = isoDt.toJSDate();
×
64
    } else {
4✔
65
      // 3. Fallback: use native Date constructor
66
      result = new Date(value);
4✔
67
    }
4✔
68
  }
4✔
69
  // 4. Ensure the result is a valid Date object
70
  if (isNaN(result.getTime())) {
9!
71
    result = new Date(value);
×
72
  }
✔
73
  return result;
8✔
74
};
8✔
75

76
/**
77
 * Gets primary keys from the schema.
78
 * @template T - The type of the table schema
79
 * @param {T} table - The table schema
80
 * @returns {[string, AnyColumn][]} Array of primary key name and column pairs
81
 */
82
export function getPrimaryKeys<T extends AnyMySqlTable>(table: T): [string, AnyColumn][] {
1✔
83
  const { columns, primaryKeys } = getTableMetadata(table);
14✔
84

85
  // First try to find primary keys in columns
86
  const columnPrimaryKeys = Object.entries(columns).filter(([, column]) => column.primary) as [
14✔
87
    string,
88
    AnyColumn,
89
  ][];
90

91
  if (columnPrimaryKeys.length > 0) {
14✔
92
    return columnPrimaryKeys;
10✔
93
  }
10✔
94

95
  // If no primary keys found in columns, check primary key builders
96
  if (Array.isArray(primaryKeys) && primaryKeys.length > 0) {
14✔
97
    // Collect all primary key columns from all primary key builders
98
    const primaryKeyColumns = new Set<[string, AnyColumn]>();
4✔
99

100
    primaryKeys.forEach((primaryKeyBuilder) => {
4✔
101
      // Get primary key columns from each builder
102
      Object.entries(columns)
4✔
103
        .filter(([, column]) => {
4✔
104
          // @ts-ignore - PrimaryKeyBuilder has internal columns property
105
          return primaryKeyBuilder.columns.includes(column);
8✔
106
        })
4✔
107
        .forEach(([name, column]) => {
4✔
108
          primaryKeyColumns.add([name, column]);
4✔
109
        });
4✔
110
    });
4✔
111

112
    return Array.from(primaryKeyColumns);
4✔
113
  }
4!
114

115
  return [];
×
116
}
×
117

118
/**
119
 * Processes foreign keys from both foreignKeysSymbol and extraSymbol
120
 * @param table - The table schema
121
 * @param foreignKeysSymbol - Symbol for foreign keys
122
 * @param extraSymbol - Symbol for extra configuration
123
 * @returns Array of foreign key builders
124
 */
125
function processForeignKeys(
41✔
126
  table: AnyMySqlTable,
41✔
127
  foreignKeysSymbol: symbol | undefined,
41✔
128
  extraSymbol: symbol | undefined,
41✔
129
): ForeignKeyBuilder[] {
41✔
130
  const foreignKeys: ForeignKeyBuilder[] = [];
41✔
131

132
  // Process foreign keys from foreignKeysSymbol
133
  if (foreignKeysSymbol) {
41✔
134
    // @ts-ignore
135
    const fkArray: any[] = table[foreignKeysSymbol];
41✔
136
    if (fkArray) {
41✔
137
      fkArray.forEach((fk) => {
41✔
138
        if (fk.reference) {
×
139
          const item = fk.reference(fk);
×
140
          foreignKeys.push(item);
×
141
        }
×
142
      });
41✔
143
    }
41✔
144
  }
41✔
145

146
  // Process foreign keys from extraSymbol
147
  if (extraSymbol) {
41✔
148
    // @ts-ignore
149
    const extraConfigBuilder = table[extraSymbol];
41✔
150
    if (extraConfigBuilder && typeof extraConfigBuilder === "function") {
41✔
151
      const configBuilderData = extraConfigBuilder(table);
16✔
152
      if (configBuilderData) {
16✔
153
        const configBuilders = Array.isArray(configBuilderData)
16✔
154
          ? configBuilderData
16!
155
          : Object.values(configBuilderData).map(
×
156
              (item) => (item as ConfigBuilderData).value ?? item,
×
157
            );
×
158

159
        configBuilders.forEach((builder) => {
16✔
160
          if (!builder?.constructor) return;
16!
161

162
          const builderName = builder.constructor.name.toLowerCase();
16✔
163
          if (builderName.includes("foreignkeybuilder")) {
16!
164
            foreignKeys.push(builder);
×
165
          }
×
166
        });
16✔
167
      }
16✔
168
    }
16✔
169
  }
41✔
170

171
  return foreignKeys;
41✔
172
}
41✔
173

174
/**
175
 * Extracts table metadata from the schema.
176
 * @param {AnyMySqlTable} table - The table schema
177
 * @returns {MetadataInfo} Object containing table metadata
178
 */
179
export function getTableMetadata(table: AnyMySqlTable): MetadataInfo {
1✔
180
  const symbols = Object.getOwnPropertySymbols(table);
41✔
181
  const nameSymbol = symbols.find((s) => s.toString().includes("Name"));
41✔
182
  const columnsSymbol = symbols.find((s) => s.toString().includes("Columns"));
41✔
183
  const foreignKeysSymbol = symbols.find((s) => s.toString().includes("ForeignKeys)"));
41✔
184
  const extraSymbol = symbols.find((s) => s.toString().includes("ExtraConfigBuilder"));
41✔
185

186
  // Initialize builders arrays
187
  const builders = {
41✔
188
    indexes: [] as AnyIndexBuilder[],
41✔
189
    checks: [] as CheckBuilder[],
41✔
190
    foreignKeys: [] as ForeignKeyBuilder[],
41✔
191
    primaryKeys: [] as PrimaryKeyBuilder[],
41✔
192
    uniqueConstraints: [] as UniqueConstraintBuilder[],
41✔
193
    extras: [] as any[],
41✔
194
  };
41✔
195

196
  // Process foreign keys
197
  builders.foreignKeys = processForeignKeys(table, foreignKeysSymbol, extraSymbol);
41✔
198

199
  // Process extra configuration if available
200
  if (extraSymbol) {
41✔
201
    // @ts-ignore
202
    const extraConfigBuilder = table[extraSymbol];
41✔
203
    if (extraConfigBuilder && typeof extraConfigBuilder === "function") {
41✔
204
      const configBuilderData = extraConfigBuilder(table);
16✔
205
      if (configBuilderData) {
16✔
206
        // Convert configBuilderData to array if it's an object
207
        const configBuilders = Array.isArray(configBuilderData)
16✔
208
          ? configBuilderData
16!
209
          : Object.values(configBuilderData).map(
×
210
              (item) => (item as ConfigBuilderData).value ?? item,
×
211
            );
×
212

213
        // Process each builder
214
        configBuilders.forEach((builder) => {
16✔
215
          if (!builder?.constructor) return;
16!
216

217
          const builderName = builder.constructor.name.toLowerCase();
16✔
218

219
          // Map builder types to their corresponding arrays
220
          const builderMap = {
16✔
221
            indexbuilder: builders.indexes,
16✔
222
            checkbuilder: builders.checks,
16✔
223
            primarykeybuilder: builders.primaryKeys,
16✔
224
            uniqueconstraintbuilder: builders.uniqueConstraints,
16✔
225
          };
16✔
226

227
          // Add builder to appropriate array if it matches any type
228
          for (const [type, array] of Object.entries(builderMap)) {
16✔
229
            if (builderName.includes(type)) {
48✔
230
              array.push(builder);
16✔
231
              break;
16✔
232
            }
16✔
233
          }
48✔
234

235
          // Always add to extras array
236
          builders.extras.push(builder);
16✔
237
        });
16✔
238
      }
16✔
239
    }
16✔
240
  }
41✔
241

242
  return {
41✔
243
    tableName: nameSymbol ? (table as any)[nameSymbol] : "",
41!
244
    columns: columnsSymbol ? ((table as any)[columnsSymbol] as Record<string, AnyColumn>) : {},
41!
245
    ...builders,
41✔
246
  };
41✔
247
}
41✔
248

249
/**
250
 * Generates SQL statements for dropping tables and/or their sequences.
251
 *
252
 * @param tables - List of table names to generate DROP statements for.
253
 * @param options - Configuration object:
254
 *   - sequence: whether to drop associated sequences (default: true)
255
 *   - table: whether to drop tables themselves (default: true)
256
 * @returns Array of SQL statements for dropping the specified objects
257
 */
258
export function generateDropTableStatements(
1✔
259
  tables: string[],
4✔
260
  options?: { sequence: boolean; table: boolean },
4✔
261
): string[] {
4✔
262
  const dropStatements: string[] = [];
4✔
263
  const validOptions = options ?? { sequence: true, table: true };
4✔
264
  if (!validOptions.sequence && !validOptions.table) {
4!
265
    console.warn('No drop operations requested: both "table" and "sequence" options are false');
×
266
    return [];
×
267
  }
×
268
  tables.forEach((tableName) => {
4✔
269
    if (validOptions.table) {
6✔
270
      dropStatements.push(`DROP TABLE IF EXISTS \`${tableName}\`;`);
6✔
271
    }
6✔
272
    if (validOptions.sequence) {
6✔
273
      dropStatements.push(`DROP SEQUENCE IF EXISTS \`${tableName}\`;`);
6✔
274
    }
6✔
275
  });
4✔
276

277
  return dropStatements;
4✔
278
}
4✔
279

280
type AliasColumnMap = Record<string, AnyColumn>;
281

282
function mapSelectTableToAlias(
6✔
283
  table: MySqlTable,
6✔
284
  uniqPrefix: string,
6✔
285
  aliasMap: AliasColumnMap,
6✔
286
): any {
6✔
287
  const { columns, tableName } = getTableMetadata(table);
6✔
288
  const selectionsTableFields: Record<string, unknown> = {};
6✔
289
  Object.keys(columns).forEach((name) => {
6✔
290
    const column = columns[name] as AnyColumn;
23✔
291
    const uniqName = `a_${uniqPrefix}_${tableName}_${column.name}`.toLowerCase();
23✔
292
    const fieldAlias = sql.raw(uniqName);
23✔
293
    selectionsTableFields[name] = sql`${column} as \`${fieldAlias}\``;
23✔
294
    aliasMap[uniqName] = column;
23✔
295
  });
6✔
296
  return selectionsTableFields;
6✔
297
}
6✔
298

299
function isDrizzleColumn(column: any): boolean {
26✔
300
  return column && typeof column === "object" && "table" in column;
26✔
301
}
26✔
302

303
export function mapSelectAllFieldsToAlias(
1✔
304
  selections: any,
32✔
305
  name: string,
32✔
306
  uniqName: string,
32✔
307
  fields: any,
32✔
308
  aliasMap: AliasColumnMap,
32✔
309
): any {
32✔
310
  if (isTable(fields)) {
32✔
311
    selections[name] = mapSelectTableToAlias(fields as MySqlTable, uniqName, aliasMap);
6✔
312
  } else if (isDrizzleColumn(fields)) {
32✔
313
    const column = fields as Column;
14✔
314
    const uniqAliasName = `a_${uniqName}_${column.name}`.toLowerCase();
14✔
315
    let aliasName = sql.raw(uniqAliasName);
14✔
316
    selections[name] = sql`${column} as \`${aliasName}\``;
14✔
317
    aliasMap[uniqAliasName] = column;
14✔
318
  } else if (isSQLWrapper(fields)) {
26✔
319
    selections[name] = fields;
5✔
320
  } else {
12✔
321
    const innerSelections: any = {};
7✔
322
    Object.entries(fields).forEach(([iname, ifields]) => {
7✔
323
      mapSelectAllFieldsToAlias(innerSelections, iname, `${uniqName}_${iname}`, ifields, aliasMap);
14✔
324
    });
7✔
325
    selections[name] = innerSelections;
7✔
326
  }
7✔
327
  return selections;
32✔
328
}
32✔
329
export function mapSelectFieldsWithAlias<TSelection extends SelectedFields>(
1✔
330
  fields: TSelection,
6✔
331
): { selections: TSelection; aliasMap: AliasColumnMap } {
6✔
332
  if (!fields) {
6!
333
    throw new Error("fields is empty");
×
334
  }
×
335
  const aliasMap: AliasColumnMap = {};
6✔
336
  const selections: any = {};
6✔
337
  Object.entries(fields).forEach(([name, fields]) => {
6✔
338
    mapSelectAllFieldsToAlias(selections, name, name, fields, aliasMap);
18✔
339
  });
6✔
340
  return { selections, aliasMap };
6✔
341
}
6✔
342

343
function getAliasFromDrizzleAlias(value: unknown): string | undefined {
110✔
344
  const isSQL =
110✔
345
    value !== null && typeof value === "object" && isSQLWrapper(value) && "queryChunks" in value;
110✔
346
  if (isSQL) {
110✔
347
    const sql = value as SQL;
84✔
348
    const queryChunks = sql.queryChunks;
84✔
349
    if (queryChunks.length > 3) {
84✔
350
      const aliasNameChunk = queryChunks[queryChunks.length - 2];
74✔
351
      if (isSQLWrapper(aliasNameChunk) && "queryChunks" in aliasNameChunk) {
74✔
352
        const aliasNameChunkSql = aliasNameChunk as SQL;
74✔
353
        if (aliasNameChunkSql.queryChunks?.length === 1 && aliasNameChunkSql.queryChunks[0]) {
74✔
354
          const queryChunksStringChunc = aliasNameChunkSql.queryChunks[0];
74✔
355
          if ("value" in queryChunksStringChunc) {
74✔
356
            const values = (queryChunksStringChunc as StringChunk).value;
74✔
357
            if (values && values.length === 1) {
74✔
358
              return values[0];
74✔
359
            }
74✔
360
          }
74✔
361
        }
74✔
362
      }
74✔
363
    }
74✔
364
  }
84✔
365
  return undefined;
36✔
366
}
36✔
367

368
function transformValue(
74✔
369
  value: unknown,
74✔
370
  alias: string,
74✔
371
  aliasMap: Record<string, AnyColumn>,
74✔
372
): unknown {
74✔
373
  const column = aliasMap[alias];
74✔
374
  if (!column) return value;
74!
375

376
  let customColumn = column as MySqlCustomColumn<any>;
74✔
377
  // @ts-ignore
378
  const fromDriver = customColumn?.mapFrom;
74✔
379
  if (fromDriver && value !== null && value !== undefined) {
74✔
380
    return fromDriver(value);
14✔
381
  }
14✔
382
  return value;
60✔
383
}
60✔
384

385
function transformObject(
38✔
386
  obj: Record<string, unknown>,
38✔
387
  selections: Record<string, unknown>,
38✔
388
  aliasMap: Record<string, AnyColumn>,
38✔
389
): Record<string, unknown> {
38✔
390
  const result: Record<string, unknown> = {};
38✔
391

392
  for (const [key, value] of Object.entries(obj)) {
38✔
393
    const selection = selections[key];
110✔
394
    const alias = getAliasFromDrizzleAlias(selection);
110✔
395
    if (alias && aliasMap[alias]) {
110✔
396
      result[key] = transformValue(value, alias, aliasMap);
74✔
397
    } else if (selection && typeof selection === "object" && !isSQLWrapper(selection)) {
110✔
398
      result[key] = transformObject(
26✔
399
        value as Record<string, unknown>,
26✔
400
        selection as Record<string, unknown>,
26✔
401
        aliasMap,
26✔
402
      );
26✔
403
    } else {
36✔
404
      result[key] = value;
10✔
405
    }
10✔
406
  }
110✔
407

408
  return result;
38✔
409
}
38✔
410

411
export function applyFromDriverTransform<T, TSelection>(
1✔
412
  rows: T[],
6✔
413
  selections: TSelection,
6✔
414
  aliasMap: Record<string, AnyColumn>,
6✔
415
): T[] {
6✔
416
  return rows.map((row) => {
6✔
417
    const transformed = transformObject(
12✔
418
      row as Record<string, unknown>,
12✔
419
      selections as Record<string, unknown>,
12✔
420
      aliasMap,
12✔
421
    ) as Record<string, unknown>;
12✔
422

423
    return processNullBranches(transformed) as unknown as T;
12✔
424
  });
6✔
425
}
6✔
426

427
function processNullBranches(obj: Record<string, unknown>): Record<string, unknown> | null {
42✔
428
  if (obj === null || typeof obj !== "object") {
42!
429
    return obj;
×
430
  }
×
431

432
  // Skip built-in objects like Date, Array, etc.
433
  if (obj.constructor && obj.constructor.name !== "Object") {
42✔
434
    return obj;
4✔
435
  }
4✔
436

437
  const result: Record<string, unknown> = {};
38✔
438
  let allNull = true;
38✔
439

440
  for (const [key, value] of Object.entries(obj)) {
42✔
441
    if (value === null || value === undefined) {
110✔
442
      result[key] = null;
5✔
443
      continue;
5✔
444
    }
5✔
445

446
    if (typeof value === "object") {
110✔
447
      const processed = processNullBranches(value as Record<string, unknown>);
30✔
448
      result[key] = processed;
30✔
449
      if (processed !== null) {
30✔
450
        allNull = false;
29✔
451
      }
29✔
452
    } else {
110✔
453
      result[key] = value;
75✔
454
      allNull = false;
75✔
455
    }
75✔
456
  }
110✔
457

458
  return allNull ? null : result;
42✔
459
}
42✔
460

461
export function formatLimitOffset(limitOrOffset: number): number {
1✔
462
  if (typeof limitOrOffset !== "number" || isNaN(limitOrOffset)) {
5✔
463
    throw new Error("limitOrOffset must be a valid number");
2✔
464
  }
2✔
465
  return sql.raw(`${limitOrOffset}`) as unknown as number;
3✔
466
}
3✔
467

468
export function nextVal(sequenceName: string): number {
1✔
469
  return sql.raw(`NEXTVAL(${sequenceName})`) as unknown as number;
3✔
470
}
3✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc