Skip to content

Instantly share code, notes, and snippets.

@hyunbinseo
Last active September 22, 2024 07:33
Show Gist options
  • Save hyunbinseo/3bea634bdff1b69d3058b044505bf009 to your computer and use it in GitHub Desktop.
Save hyunbinseo/3bea634bdff1b69d3058b044505bf009 to your computer and use it in GitHub Desktop.
Pick Drizzle ORM columns from a table with type safety
import { getTableColumns, type Table } from 'drizzle-orm';
import { integer, sqliteTable } from 'drizzle-orm/sqlite-core';
import { db } from './client.js';
export const pickTableColumns = <
T extends Table, //
const ColumnName extends keyof T['_']['columns']
>(
table: T,
columnNames: ColumnName[]
) => {
type Picked = Pick<T['_']['columns'], ColumnName>;
const picked: Partial<Picked> = {};
const columns = getTableColumns(table);
for (const columnName of columnNames) {
picked[columnName] = columns[columnName];
}
return picked as Picked;
};
const table = sqliteTable('name', {
id: integer('id').primaryKey(),
n1: integer('n1').notNull(),
n2: integer('n2')
});
// { n1: SQLiteColumn<...> }
const picked = pickTableColumns(table, ['n1']);
console.log(Object.keys(picked)); // [ 'n1' ]
// { n1: number }[];
await db.select(picked).from(table);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment