Skip to content

Drizzle ORM

Drizzle เป็น ORM และ SQL query builder ที่มีน้ำหนักเบาและปลอดภัยด้านประเภท (type-safe) สำหรับ TypeScript และ JavaScript

คุณสมบัติหลัก

  • ความปลอดภัยของประเภท: รองรับ TypeScript เต็มรูปแบบด้วยการอนุมานประเภทอัตโนมัติ
  • ไวยากรณ์แบบ SQL: เขียนคำสั่งที่ดูเหมือน SQL แต่ปลอดภัยด้านประเภท
  • น้ำหนักเบา: มีโอเวอร์เฮดน้อยกว่าเมื่อเทียบกับ ORM แบบดั้งเดิม
  • การประกาศโครงสร้าง: กำหนดโครงสร้างฐานข้อมูลของคุณใน TypeScript
  • การย้ายฐานข้อมูล: รองรับการย้ายฐานข้อมูลในตัว

การเปรียบเทียบกับ ORM อื่นๆ

คุณสมบัติDrizzlePrismaTypeORM
ความปลอดภัยประเภท
ประสิทธิภาพ⚡ เร็ว🐢 ช้า🐢 ช้า
การควบคุม SQLเต็มรูปแบบบางส่วนบางส่วน
โครงสร้างมาก่อน

การติดตั้งและการตั้งค่าเบื้องต้น

  1. ติดตั้งแพ็คเกจที่จำเป็น:
bash
npm install drizzle-orm postgres
npm install -D drizzle-kit
  1. สร้างไฟล์การกำหนดค่า drizzle.config.ts:
ts
import type { Config } from 'drizzle-kit';

export default {
  schema: './src/db/schema.ts',
  out: './drizzle',
  driver: 'pg',
  dbCredentials: {
    connectionString: process.env.DATABASE_URL!,
  },
} satisfies Config;

การใช้งานพื้นฐาน

basic_usage.ts
ts
// กำหนดโครงสร้าง
import { pgTable, serial, text } from 'drizzle-orm/pg-core';

const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
});

// ส่งคำสั่งไปยังฐานข้อมูล
const result = await db.select().from(users).where(eq(users.name, 'John'));

ตัวอย่างการใช้งาน

1. ไฟล์ schema.ts - กำหนดโครงสร้างฐานข้อมูล

schema.ts
ts
// schema.ts
import { pgTable, serial, text, integer } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  age: integer('age'),
});

export const posts = pgTable('posts', {
  id: serial('id').primaryKey(),
  title: text('title').notNull(),
  content: text('content'),
  authorId: integer('author_id').references(() => users.id),
});

2. ไฟล์ db.ts - การเชื่อมต่อฐานข้อมูล

db.ts
ts
// db.ts
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import * as schema from './schema';

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

export const db = drizzle(pool, { schema });

3. ไฟล์ queries.ts - ตัวอย่างคำสั่ง查询

queries.ts
ts
// queries.ts
import { db } from './db';
import { eq, and, or } from 'drizzle-orm';
import { users, posts } from './schema';

// ตัวอย่างคำสั่งค้นหา
async function getUserWithPosts(userId: number) {
  return await db.query.users.findMany({
    where: eq(users.id, userId),
    with: {
      posts: true
    }
  });
}

การกำหนด Schema

ts
import { pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core';

// กำหนดตารางผู้ใช้
const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').unique(),
  createdAt: timestamp('created_at').defaultNow(),
  updatedAt: timestamp('updated_at').defaultNow(),
});

// กำหนดตารางบทความ
const posts = pgTable('posts', {
  id: serial('id').primaryKey(),
  title: text('title').notNull(),
  content: text('content'),
  authorId: integer('author_id').references(() => users.id),
  createdAt: timestamp('created_at').defaultNow(),
});

การ Query ข้อมูล

ts
// Query พื้นฐาน
const allUsers = await db.select().from(users);

// Query พร้อมเงื่อนไข
const adultUsers = await db
  .select()
  .from(users)
  .where(gte(users.age, 18));

// Join ตาราง
const userPosts = await db
  .select({
    userName: users.name,
    postTitle: posts.title,
    createdAt: posts.createdAt
  })
  .from(users)
  .leftJoin(posts, eq(users.id, posts.authorId));

การเปรียบเทียบอย่างละเอียด

คุณลักษณะDrizzlePrismaTypeORMKysely
Type Safety⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Performance⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
SQL Control⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Migrations⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Relations⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

Best Practices

  1. แยก Schema ออกเป็นไฟล์เล็กๆ: จัดกลุ่มตารางที่เกี่ยวข้องกันไว้ในไฟล์เดียวกัน
  2. ใช้ Type Inference: ใช้ inferSelectModel และ inferInsertModel เพื่อได้ type ที่ปลอดภัย
  3. จัดการ Connection อย่างเหมาะสม: ใช้ connection pool และปิด connection เมื่อไม่ใช้งาน
  4. ใช้ Prepared Statements: สำหรับ query ที่ใช้บ่อย

การแก้ไขปัญหาทั่วไป

ปัญหา: Type error เมื่อ query relation วิธีแก้: ใช้ relations config ใน schema:

ts
const users = pgTable('users', {
  // ...
}, (table) => ({
  posts: many(posts)
}));

ปัญหา: Migration ล้มเหลว วิธีแก้: ตรวจสอบ SQL ที่ generate และรันแบบ manual หากจำเป็น

แหล่งเรียนรู้เพิ่มเติม

Last updated: