Drizzle | 쿼리의 조건부 필터
PostgreSQL
MySQL
SQLite
This guide assumes familiarity with:

쿼리에서 조건부 필터를 전달하려면 아래와 같이 .where() 메서드와 논리 연산자를 사용할 수 있습니다:

import { ilike } from 'drizzle-orm';

const db = drizzle(...)

const searchPosts = async (term?: string) => {
  await db
    .select()
    .from(posts)
    .where(term ? ilike(posts.title, term) : undefined);
};

await searchPosts();
await searchPosts('AI');
select * from posts;
select * from posts where title ilike 'AI';

조건부 필터를 결합하려면 아래와 같이 and() 또는 or() 연산자를 사용할 수 있습니다:

import { and, gt, ilike, inArray } from 'drizzle-orm';

const searchPosts = async (term?: string, categories: string[] = [], views = 0) => {
  await db
    .select()
    .from(posts)
    .where(
      and(
        term ? ilike(posts.title, term) : undefined,
        categories.length > 0 ? inArray(posts.category, categories) : undefined,
        views > 100 ? gt(posts.views, views) : undefined,
      ),
    );
};

await searchPosts();
await searchPosts('AI', ['Tech', 'Art', 'Science'], 200);
select * from posts;
select * from posts
  where (
    title ilike 'AI'
    and category in ('Tech', 'Science', 'Art')
    and views > 200
  );

프로젝트의 다른 부분에서 조건부 필터를 결합해야 하는 경우, 변수를 만들고 필터를 추가한 다음 아래와 같이 and() 또는 or() 연산자와 함께 .where() 메서드에서 사용할 수 있습니다:

import { SQL, ... } from 'drizzle-orm';

const searchPosts = async (filters: SQL[]) => {
  await db
    .select()
    .from(posts)
    .where(and(...filters));
};

const filters: SQL[] = [];
filters.push(ilike(posts.title, 'AI'));
filters.push(inArray(posts.category, ['Tech', 'Art', 'Science']));
filters.push(gt(posts.views, 200));

await searchPosts(filters);

Drizzle은 유용하고 유연한 API를 제공하여 맞춤형 솔루션을 만들 수 있습니다. 다음은 사용자 정의 필터 연산자를 만드는 방법입니다:

import { AnyColumn, ... } from 'drizzle-orm';

// length less than
const lenlt = (column: AnyColumn, value: number) => {
  return sql`length(${column}) < ${value}`;
};

const searchPosts = async (maxLen = 0, views = 0) => {
  await db
    .select()
    .from(posts)
    .where(
      and(
        maxLen ? lenlt(posts.title, maxLen) : undefined,
        views > 100 ? gt(posts.views, views) : undefined,
      ),
    );
};

await searchPosts(8);
await searchPosts(8, 200);
select * from posts where length(title) < 8;
select * from posts where (length(title) < 8 and views > 200);

Drizzle 필터 연산자는 내부적으로 단순히 SQL 표현식입니다. 다음은 Drizzle에서 lt 연산자가 구현된 방법의 예시입니다:

const lt = (left, right) => {
  return sql`${left} < ${bindIfParam(right, left)}`; // bindIfParam is internal magic function
};