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),
});
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?
No description
2 Replies
Mykhailo
Mykhailo10mo ago
Hello, @NinjaBunny! You can find useful information here https://orm.drizzle.team/learn/guides/queries/include-or-exclude-columns
Drizzle ORM - Learn
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
NinjaBunny
NinjaBunnyOP10mo ago
I don't think this applies to relational queries as well
Want results from more Discord servers?
Add your server