쿼리 성능

Drizzle은 SQL 위에 구축된 얇은 TypeScript 레이어로 오버헤드가 거의 0에 가깝습니다. 실제로 0이 되도록 하려면 prepared statements API를 활용할 수 있습니다.

데이터베이스에서 쿼리를 실행할 때 다음과 같은 일들이 발생합니다:

Prepared statements를 사용하면 Drizzle ORM 측에서 SQL 연결을 한 번만 수행하고, 데이터베이스 드라이버는 쿼리를 매번 파싱하는 대신 미리 컴파일된 바이너리 SQL을 재사용할 수 있습니다. 이는 대용량 SQL 쿼리에서 극적인 성능 향상을 제공합니다.

데이터베이스 드라이버마다 prepared statements를 다르게 지원하며, 경우에 따라 Drizzle ORM은 better-sqlite3 드라이버보다 더 빠를 수 있습니다.

Prepared statement

PostgreSQL
MySQL
SQLite
SingleStore
const db = drizzle(...);

const prepared = db.select().from(customers).prepare("statement_name");

const res1 = await prepared.execute();
const res2 = await prepared.execute();
const res3 = await prepared.execute();

Placeholder

동적 런타임 값을 포함해야 할 때는 sql.placeholder(...) API를 사용할 수 있습니다

PostgreSQL
MySQL
SQLite
SingleStore
import { sql } from "drizzle-orm";

const p1 = db
  .select()
  .from(customers)
  .where(eq(customers.id, sql.placeholder('id')))
  .prepare("p1")

await p1.execute({ id: 10 }) // SELECT * FROM customers WHERE id = 10
await p1.execute({ id: 12 }) // SELECT * FROM customers WHERE id = 12

const p2 = db
  .select()
  .from(customers)
  .where(sql`lower(${customers.name}) like ${sql.placeholder('name')}`)
  .prepare("p2");

await p2.execute({ name: '%an%' }) // SELECT * FROM customers WHERE name ilike '%an%'