From 34e8becc7e7d682ab4f016eda0ce035a3aafa481 Mon Sep 17 00:00:00 2001 From: Christiaan Landman Date: Fri, 15 Nov 2024 16:53:25 +0200 Subject: [PATCH] Transforming index options from Drizzle tables. Using getTableConfig instead of iterating keys. --- packages/drizzle-driver/src/utils/schema.ts | 36 ++++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/packages/drizzle-driver/src/utils/schema.ts b/packages/drizzle-driver/src/utils/schema.ts index cd3a37d5..db642767 100644 --- a/packages/drizzle-driver/src/utils/schema.ts +++ b/packages/drizzle-driver/src/utils/schema.ts @@ -1,5 +1,6 @@ -import { column, Table, type BaseColumnType, type TableV2Options } from '@powersync/common'; +import { column, IndexShorthand, Table, type BaseColumnType, type TableV2Options } from '@powersync/common'; import { + getTableConfig, SQLiteInteger, SQLiteReal, SQLiteText, @@ -7,16 +8,21 @@ import { type TableConfig } from 'drizzle-orm/sqlite-core'; -export function toPowerSyncTable(table: SQLiteTableWithColumns, options?: TableV2Options) { +export function toPowerSyncTable( + table: SQLiteTableWithColumns, + options?: Omit +) { + const { columns: drizzleColumns, indexes: drizzleIndexes } = getTableConfig(table); + const columns: { [key: string]: BaseColumnType } = {}; - for (const [columnName, columnValue] of Object.entries(table)) { + for (const drizzleColumn of drizzleColumns) { // Skip the id column - if (columnName === 'id') { + if (drizzleColumn.name === 'id') { continue; } let mappedType: BaseColumnType; - switch (columnValue.columnType) { + switch (drizzleColumn.columnType) { case SQLiteText.name: mappedType = column.text; break; @@ -27,9 +33,23 @@ export function toPowerSyncTable(table: SQLiteTableWithCo mappedType = column.real; break; default: - throw new Error(`Unsupported column type: ${columnValue.columnType}`); + throw new Error(`Unsupported column type: ${drizzleColumn.columnType}`); } - columns[columnName] = mappedType; + columns[drizzleColumn.name] = mappedType; + } + const indexes: IndexShorthand = {}; + + for (const index of drizzleIndexes) { + index.config; + if (!index.config.columns.length) { + continue; + } + const columns: string[] = []; + for (const indexColumn of index.config.columns) { + columns.push((indexColumn as { name: string }).name); + } + + indexes[index.config.name] = columns; } - return new Table(columns, options); + return new Table(columns, { ...options, indexes }); }