( schema: Record<string, unknown>, configHelpers: (table: Table) => any, )
| 414 | } |
| 415 | |
| 416 | export function extractTablesRelationalConfig< |
| 417 | TTables extends TablesRelationalConfig, |
| 418 | >( |
| 419 | schema: Record<string, unknown>, |
| 420 | configHelpers: (table: Table) => any, |
| 421 | ): { tables: TTables; tableNamesMap: Record<string, string> } { |
| 422 | if ( |
| 423 | Object.keys(schema).length === 1 |
| 424 | && 'default' in schema |
| 425 | && !is(schema['default'], Table) |
| 426 | ) { |
| 427 | schema = schema['default'] as Record<string, unknown>; |
| 428 | } |
| 429 | |
| 430 | // table DB name -> schema table key |
| 431 | const tableNamesMap: Record<string, string> = {}; |
| 432 | // Table relations found before their tables - need to buffer them until we know the schema table key |
| 433 | const relationsBuffer: Record< |
| 434 | string, |
| 435 | { relations: Record<string, Relation>; primaryKey?: AnyColumn[] } |
| 436 | > = {}; |
| 437 | const tablesConfig: TablesRelationalConfig = {}; |
| 438 | for (const [key, value] of Object.entries(schema)) { |
| 439 | if (is(value, Table)) { |
| 440 | const dbName = getTableUniqueName(value); |
| 441 | const bufferedRelations = relationsBuffer[dbName]; |
| 442 | tableNamesMap[dbName] = key; |
| 443 | tablesConfig[key] = { |
| 444 | tsName: key, |
| 445 | dbName: value[Table.Symbol.Name], |
| 446 | schema: value[Table.Symbol.Schema], |
| 447 | columns: value[Table.Symbol.Columns], |
| 448 | relations: bufferedRelations?.relations ?? {}, |
| 449 | primaryKey: bufferedRelations?.primaryKey ?? [], |
| 450 | }; |
| 451 | |
| 452 | // Fill in primary keys |
| 453 | for ( |
| 454 | const column of Object.values( |
| 455 | (value as Table)[Table.Symbol.Columns], |
| 456 | ) |
| 457 | ) { |
| 458 | if (column.primary) { |
| 459 | tablesConfig[key]!.primaryKey.push(column); |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.((value as Table)[Table.Symbol.ExtraConfigColumns]); |
| 464 | if (extraConfig) { |
| 465 | for (const configEntry of Object.values(extraConfig)) { |
| 466 | if (is(configEntry, PrimaryKeyBuilder)) { |
| 467 | tablesConfig[key]!.primaryKey.push(...configEntry.columns); |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | } else if (is(value, Relations)) { |
| 472 | const dbName = getTableUniqueName(value.table); |
| 473 | const tableName = tableNamesMap[dbName]; |
no test coverage detected