|
1 | | -import { column, IndexShorthand, Table, type BaseColumnType, type TableV2Options } from '@powersync/common'; |
| 1 | +import { column, IndexShorthand, Schema, Table, type BaseColumnType, type TableV2Options } from '@powersync/common'; |
| 2 | +import { isTable, Relations } from 'drizzle-orm'; |
2 | 3 | import { |
3 | 4 | getTableConfig, |
4 | 5 | SQLiteInteger, |
@@ -53,3 +54,35 @@ export function toPowerSyncTable<T extends TableConfig>( |
53 | 54 | } |
54 | 55 | return new Table(columns, { ...options, indexes }); |
55 | 56 | } |
| 57 | + |
| 58 | +export type DrizzleTablePowerSyncOptions = Omit<TableV2Options, 'indexes'>; |
| 59 | + |
| 60 | +export type DrizzleTableWithPowerSyncOptions = { |
| 61 | + tableDefinition: SQLiteTableWithColumns<any>; |
| 62 | + options?: DrizzleTablePowerSyncOptions | undefined; |
| 63 | +}; |
| 64 | + |
| 65 | +export function toPowerSyncSchema( |
| 66 | + schemaEntries: Record<string, SQLiteTableWithColumns<any> | Relations | DrizzleTableWithPowerSyncOptions> |
| 67 | +) { |
| 68 | + const tables: Record<string, Table> = {}; |
| 69 | + for (const schemaEntry of Object.values(schemaEntries)) { |
| 70 | + let maybeTable: SQLiteTableWithColumns<any> | Relations | undefined = undefined; |
| 71 | + let maybeOptions: DrizzleTablePowerSyncOptions | undefined = undefined; |
| 72 | + |
| 73 | + if (typeof schemaEntry === 'object' && 'tableDefinition' in schemaEntry) { |
| 74 | + const tableWithOptions = schemaEntry as DrizzleTableWithPowerSyncOptions; |
| 75 | + maybeTable = tableWithOptions.tableDefinition; |
| 76 | + maybeOptions = tableWithOptions.options; |
| 77 | + } else { |
| 78 | + maybeTable = schemaEntry; |
| 79 | + } |
| 80 | + |
| 81 | + if (isTable(maybeTable)) { |
| 82 | + const { name } = getTableConfig(maybeTable); |
| 83 | + tables[name] = toPowerSyncTable(maybeTable as SQLiteTableWithColumns<TableConfig>, maybeOptions); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return new Schema(tables); |
| 88 | +} |
0 commit comments