Skip to content

Commit

Permalink
Transforming index options from Drizzle tables.
Browse files Browse the repository at this point in the history
Using getTableConfig instead of iterating keys.
  • Loading branch information
Chriztiaan committed Nov 15, 2024
1 parent 01039ba commit 34e8bec
Showing 1 changed file with 28 additions and 8 deletions.
36 changes: 28 additions & 8 deletions packages/drizzle-driver/src/utils/schema.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
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,
type SQLiteTableWithColumns,
type TableConfig
} from 'drizzle-orm/sqlite-core';

export function toPowerSyncTable<T extends TableConfig>(table: SQLiteTableWithColumns<T>, options?: TableV2Options) {
export function toPowerSyncTable<T extends TableConfig>(
table: SQLiteTableWithColumns<T>,
options?: Omit<TableV2Options, 'indexes'>
) {
const { columns: drizzleColumns, indexes: drizzleIndexes } = getTableConfig(table);

const columns: { [key: string]: BaseColumnType<number | string | null> } = {};
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<number | string | null>;
switch (columnValue.columnType) {
switch (drizzleColumn.columnType) {
case SQLiteText.name:
mappedType = column.text;
break;
Expand All @@ -27,9 +33,23 @@ export function toPowerSyncTable<T extends TableConfig>(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 });
}

0 comments on commit 34e8bec

Please sign in to comment.