Programmatically get columns from table

Hi all I'm wondering if it's possible to programmatically return columns from a table.

For example

import { z } from "zod";
import { SelectUserSchema } from "../db/schema";

type UserColumns = z.infer<typeof SelectUserSchema>;

type UserColumnParams = Partial<Record<keyof UserColumns, boolean>>;

export function getUserColumns<T extends Partial<UserColumnParams>>(data: T) {
  const columns: Record<keyof UserColumnParams, boolean> = {
    createdAt: false,
    email: false,
    id: false,
    firstName: false,
    lastName: false,
    updatedAt: false,
    password: false,
  };

  for (const key in data) {
    if (data[key]) {
      columns[key as keyof UserColumnParams] = true;
    }
  }

  return columns;
}


const user = await db.query.users.findFirst({
  columns: getUserColumns({
    id: true,
    email: true,
    firstName: true,
    lastName: true,
  }),
  where: eq(userModel.id, id),
});


In doing so, the result is this image posted below.

Is there a way I can do this programmatically or do I have to reference every value manually?
CleanShot_2024-03-10_at_14.37.56.png
Was this page helpful?