┌───────────────────────────┐ ┌─────────────────────────────┐
│ Drizzle ORM │ │ HTTP Server with Database │
└─┬─────────────────────────┘ └─────────────────────────┬───┘
│ ^ │
│-- 1. Build query 2. Send built query --│ │
│ │ │
│ ┌───────────────────────────┐ │ │
└─────────────>│ │─────┘ │
│ HTTP Proxy Driver │ │
┌──────────────│ │<─────────────┬───────────┘
│ └───────────────────────────┘ │
│ 3. Execute a query + send raw results back
│-- 4. Map data and return
│
vDrizzle HTTP 프록시
This guide assumes familiarity with:
- Drizzle의 데이터베이스 연결 기초
HTTP 프록시의 작동 방식과 필요한 이유
Drizzle 프록시는 데이터베이스와의 드라이버 통신을 직접 구현해야 할 때 사용됩니다. 기존 드라이버에 쿼리 단계에서 커스텀 로직을 추가하는 등 여러 경우에 사용할 수 있습니다. 가장 일반적인 사용 사례는 HTTP 드라이버로, 데이터베이스가 있는 서버로 쿼리를 전송하고, 데이터베이스에서 쿼리를 실행한 후, Drizzle ORM이 결과로 매핑할 수 있는 원시 데이터를 응답으로 반환합니다
내부적으로 어떻게 작동하나요?
Drizzle ORM은 SQL 실행을 위한 비동기 콜백 함수를 간단히 사용하는 것도 지원합니다.
sql은 플레이스홀더가 포함된 쿼리 문자열입니다.params는 매개변수 배열입니다.method는 SQL 문에 따라run,all,values또는get중 하나로 설정됩니다.
Drizzle은 항상 반환 값으로 {rows: string[][]} 또는 {rows: string[]}를 기대합니다.
method가get일 때는{rows: string[]}형태로 값을 반환해야 합니다.- 그 외의 경우에는
{rows: string[][]}형태로 반환해야 합니다.
PostgreSQL
MySQL
SQLite
// Example of driver implementation
import { drizzle } from 'drizzle-orm/pg-proxy';
const db = drizzle(async (sql, params, method) => {
try {
const rows = await axios.post('http://localhost:3000/query', { sql, params, method });
return { rows: rows.data };
} catch (e: any) {
console.error('Error from pg proxy server: ', e.response.data)
return { rows: [] };
}
});// Example of server implementation
import { Client } from 'pg';
import express from 'express';
const app = express();
app.use(express.json());
const port = 3000;
const client = new Client('postgres://postgres:postgres@localhost:5432/postgres');
app.post('/query', async (req, res) => {
const { sql, params, method } = req.body;
// prevent multiple queries
const sqlBody = sql.replace(/;/g, '');
try {
const result = await client.query({
text: sqlBody,
values: params,
rowMode: method === 'all' ? 'array': undefined,
});
res.send(result.rows);
} catch (e: any) {
res.status(500).json({ error: e });
}
res.status(500).json({ error: 'Unknown method value' });
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});