drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[BUG]: $dynamic queries drops the initial 'where' part of the clause

Open gerhardcit opened this issue 1 year ago • 0 comments

What version of drizzle-orm are you using?

0.30.10

What version of drizzle-kit are you using?

0.21.1

Describe the Bug

Dynamic query building does not work as indicated here: https://orm.drizzle.team/docs/dynamic-query-building

AI answers suggested this code to created a dynamic query:

To construct an optional where clause in Drizzle with optional "and" fields, including a condition only if you have specific search criteria for that field, you can utilize the dynamic query building feature of Drizzle. This feature allows you to build queries dynamically, adjusting the conditions based on the input data you have.

async function queryWithOptionalConditions(tenant: string, areaMatch?: string, suburbMatch?: string) {
    let query = db.select().from(yourTable).where(eq(yourTable.tenant, tenant));

    if (areaMatch || suburbMatch) {
        query = query.$dynamic().where(or(
            areaMatch ? eq(yourTable.area, areaMatch) : undefined,
            suburbMatch ? eq(yourTable.suburb, suburbMatch) : undefined
        ));
    }
    console.log("sql", query.toSQL());
    return await query;
}

Run it as follows:

const res = await queryWithOptionalConditions("tenant1", "area53", "")

The log printed out is this:

 select "id", "tenant", "area", "suburb"  from "owners" where "owners"."name" = ?',
  params: [ 'area53' ]

Expected behavior

the expected code should be

 select "id", "tenant", "area", "suburb"  from "owners"  where "owners"."tenant" = ? 
AND  "owners"."name" = ?',
 params: [ 'tenant1", 'area53' ]

note that the "where tenant = 'xxx" has gone missing.

Environment & setup

Testing this in sveltelkit project running on cloudflare.

Referring to this page: https://orm.drizzle.team/docs/dynamic-query-building The documentation starts with this problem:

const query = db
  .select()
  .from(users)
  .where(eq(users.id, 1))
  .where(eq(users.name, 'John')); // ❌ Type error - where() can only be invoked once

but never really address this problem of adding optional where based on the input matching fields.

It goes into adding joins, and limits etc, where it should also address the optional where fields which is classic in searching sql dbs.

gerhardcit avatar May 15 '24 06:05 gerhardcit