Skip to content

Commit

Permalink
Improve asDrizzleTable() types
Browse files Browse the repository at this point in the history
  • Loading branch information
delucis committed Apr 25, 2024
1 parent 25edcb7 commit e93cfe6
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions packages/db/src/runtime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import {
sqliteTable,
text,
} from 'drizzle-orm/sqlite-core';
import { type DBColumn, type DBTable } from '../core/types.js';
import { type SerializedSQL, isSerializedSQL } from './types.js';
import { type ColumnsConfig, type DBColumn, type DBTable, type TableConfig } from '../core/types.js';
import { type SerializedSQL, isSerializedSQL, type Table } from './types.js';
import { pathToFileURL } from './utils.js';
import { tableSchema } from '../core/schemas.js';

export type { Table } from './types.js';
export { createRemoteDatabaseClient, createLocalDatabaseClient } from './db-client.js';
Expand Down Expand Up @@ -48,7 +49,8 @@ type D1ColumnBuilder = SQLiteColumnBuilderBase<
ColumnBuilderBaseConfig<ColumnDataType, string> & { data: unknown }
>;

export function asDrizzleTable(name: string, table: DBTable) {
export function asDrizzleTable<TableName extends string = string, TColumns extends ColumnsConfig = ColumnsConfig>(name: TableName, tbl: TableConfig<TColumns>): Table<TableName, TColumns> {
const table = tableSchema.parse(tbl);
const columns: Record<string, D1ColumnBuilder> = {};
if (!Object.entries(table.columns).some(([, column]) => hasPrimaryKey(column))) {
columns['_id'] = integer('_id').primaryKey();
Expand All @@ -67,7 +69,7 @@ export function asDrizzleTable(name: string, table: DBTable) {
}
return indexes;
});
return drizzleTable;
return drizzleTable as Table<TableName, TColumns>;
}

function atLeastOne<T>(arr: T[]): arr is [T, ...T[]] {
Expand Down

0 comments on commit e93cfe6

Please sign in to comment.