drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
24.61k stars 649 forks source link

[BUG]: Better way to handle if conditions #3547

Open jakeleventhal opened 1 week ago

jakeleventhal commented 1 week ago

Report hasn't been filed before.

What version of drizzle-orm are you using?

0.27.0

What version of drizzle-kit are you using?

0.36.0

Other packages

No response

Describe the Bug

Suppose my route has an optional parameter minDate and I want to have a query like:

gte(orders.createdAt, minDate).if(minDate)

This code does not work since minDate is sometimes undefined. This forces me to add ! in the gte function. This seems like a bad pattern.

luminaryhero commented 5 days ago

You can refer to the examples given in the official documentation。 Compose a WHERE statement and then use it in a query

async function getProductsBy({
  name,
  category,
  maxPrice,
}: {
  name?: string;
  category?: string;
  maxPrice?: string;
}) {
  const filters: SQL[] = [];
  if (name) filters.push(ilike(products.name, name));
  if (category) filters.push(eq(products.category, category));
  if (maxPrice) filters.push(lte(products.price, maxPrice));
  return db
    .select()
    .from(products)
    .where(and(...filters));
}
jakeleventhal commented 5 days ago

You can refer to the examples given in the official documentation。 Compose a WHERE statement and then use it in a query

async function getProductsBy({
  name,
  category,
  maxPrice,
}: {
  name?: string;
  category?: string;
  maxPrice?: string;
}) {
  const filters: SQL[] = [];
  if (name) filters.push(ilike(products.name, name));
  if (category) filters.push(eq(products.category, category));
  if (maxPrice) filters.push(lte(products.price, maxPrice));
  return db
    .select()
    .from(products)
    .where(and(...filters));
}

This completely disregards the original post. My issue in relation to the .if API.