เป้าหมาย
สร้าง D1 database ออกแบบ schema ผ่าน migration ที่อยู่ใน git เขียน query แบบ prepared statement จาก Worker (กัน SQL injection) อ่าน meta.rows_read เพื่อคุมค่าใช้จ่าย และรู้ว่า D1 เหมาะ/ไม่เหมาะกับงานแบบไหน
D1 ในหนึ่งตาราง
| คืออะไร | SQLite ที่ Cloudflare ดูแลให้ เรียกจาก Worker ผ่าน binding |
| ข้อมูลอยู่ที่ไหน | DB หลัก อยู่ที่ location เดียว (เลือก hint ตอนสร้างได้ เช่น ใกล้ผู้ใช้) — Worker ทั่วโลกวิ่งมาหา |
| เด่น | SQL เต็ม (JOIN, index, transaction ใน batch), ไม่มีเซิร์ฟเวอร์, ค่าใช้จ่ายตามแถวที่อ่าน/เขียน |
| ออกแบบให้ | หลาย DB เล็กๆ (เช่น 1 DB ต่อ tenant) มากกว่า DB ใหญ่ก้อนเดียว |
| Limit | Free | Paid |
|---|---|---|
| ขนาดต่อ DB | 500 MB | 10 GB |
| จำนวน DB ต่อบัญชี | 10 | 50,000 |
| แถวที่อ่าน | 5 ล้าน / วัน | 25 พันล้าน / เดือน รวมในแพลน |
| แถวที่เขียน | 100,000 / วัน | 50 ล้าน / เดือน รวมในแพลน |
| เวลา query สูงสุด | 30 วินาที | 30 วินาที |
| bound parameters ต่อ query | 100 | 100 |
| ความยาว SQL ต่อ statement | 100 KB | 100 KB |
"แถวที่อ่าน" นับแถวที่ engine สแกน ไม่ใช่แถวที่คืน — SELECT ... WHERE email = ? ไม่มี index บนตาราง 1 ล้านแถว = อ่าน 1 ล้านแถวทุกครั้ง → index คือการประหยัดเงินโดยตรง
Migration — schema อยู่ใน git
migrations/
0001_create_entries.sql
0002_add_index.sqlwrangler d1 migrations create <DB> <ชื่อ>สร้างไฟล์เปล่าตามลำดับwrangler d1 migrations apply <DB> --local/--remoteรันไฟล์ที่ยังไม่ได้รัน (บันทึกในตารางd1_migrations)- ห้ามแก้ไฟล์ที่ apply แล้ว — แก้ด้วย migration ใหม่เสมอ
- เปลี่ยนแบบ breaking (ลบคอลัมน์) ทำ 2 ขั้น: deploy โค้ดที่ไม่ใช้คอลัมน์นั้นก่อน → แล้วค่อย migration ลบ
API ใน Worker
// อ่านแถวเดียว
const row = await env.DB.prepare("SELECT * FROM entries WHERE id = ?").bind(id).first<Entry>();
// อ่านหลายแถว + meta
const { results, meta } = await env.DB.prepare("SELECT * FROM entries ORDER BY id DESC LIMIT ?").bind(20).all<Entry>();
// เขียน
const r = await env.DB.prepare("INSERT INTO entries (name, message) VALUES (?, ?)").bind(name, msg).run();
r.meta.last_row_id; r.meta.changes;
// หลายคำสั่งแบบ atomic (ล้มทั้งชุดถ้าตัวใดพัง)
await env.DB.batch([stmt1, stmt2]);ห้ามต่อ string เป็น SQL ("... WHERE name = '" + name + "'") → SQL injection ใช้ ? + .bind() เสมอ
Backup และกู้คืน
- Time Travel (เปิดอยู่แล้วเสมอ ไม่ต้องตั้ง): ย้อนได้ 7 วัน (Free) / 30 วัน (Paid) ·
wrangler d1 time-travel info <DB>ดู bookmark ·wrangler d1 time-travel restore <DB> --timestamp <unix หรือ RFC3339>ย้อนทั้ง DB ไปจุดเวลา (คำสั่งพิมพ์ bookmark ก่อน restore ไว้ให้ย้อนกลับได้) - Export:
wrangler d1 export <DB> --remote --output backup.sqlเก็บไว้นอก Cloudflare (เช่น R2/S3)
ลองเลย 🧪
ทดลอง A — สร้าง DB + migration
cd ~/cloud-ladder
npm create cloudflare@latest -- guestbook --type=hello-world --lang=ts --no-deploy --git
cd guestbook
npx wrangler d1 create guestbook-dbผลที่ควรเห็น: ข้อความ Success พร้อม snippet d1_databases ที่มี database_id → ใส่ใน wrangler.jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "guestbook",
"main": "src/index.ts",
"compatibility_date": "2026-09-01",
"observability": { "enabled": true },
"d1_databases": [
{ "binding": "DB", "database_name": "guestbook-db", "database_id": "[DATABASE_ID]" }
]
}npx wrangler d1 migrations create guestbook-db create_entries
cat > migrations/0001_create_entries.sql <<'EOF'
CREATE TABLE entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 50),
message TEXT NOT NULL CHECK (length(message) BETWEEN 1 AND 500),
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
EOF
npx wrangler d1 migrations apply guestbook-db --local
npx wrangler d1 execute guestbook-db --local --command "INSERT INTO entries (name, message) VALUES ('ต้น', 'สวัสดีจาก D1'), ('ฝน', 'ทดสอบภาษาไทย')"
npx wrangler d1 execute guestbook-db --local --command "SELECT id, name, message FROM entries"
npx wrangler typesผลที่ควรเห็น: migration 0001_create_entries.sql ✅ และตารางที่มี 2 แถว (ต้น, ฝน)
ทดลอง B — API อ่าน/เขียน แทนที่ src/index.ts
interface Entry { id: number; name: string; message: string; created_at: string }
export default {
async fetch(request, env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/api/entries" && request.method === "GET") {
const limit = Math.min(Number(url.searchParams.get("limit") ?? 20) || 20, 100);
const { results, meta } = await env.DB
.prepare("SELECT id, name, message, created_at FROM entries ORDER BY id DESC LIMIT ?")
.bind(limit)
.all<Entry>();
return Response.json({ entries: results, rows_read: meta.rows_read });
}
if (url.pathname === "/api/entries" && request.method === "POST") {
type NewEntry = { name?: string; message?: string };
const body = await request.json<NewEntry>().catch((): NewEntry => ({}));
const name = body.name?.trim() ?? "";
const message = body.message?.trim() ?? "";
if (!name || !message) return Response.json({ error: "ต้องมี name และ message" }, { status: 400 });
try {
const r = await env.DB.prepare("INSERT INTO entries (name, message) VALUES (?, ?)").bind(name, message).run();
return Response.json({ id: r.meta.last_row_id }, { status: 201 });
} catch (err) {
console.error(JSON.stringify({ event: "insert_failed", error: String(err) }));
return Response.json({ error: "ข้อมูลไม่ผ่านเงื่อนไข (ยาวเกิน?)" }, { status: 400 });
}
}
if (url.pathname === "/api/search") {
const q = url.searchParams.get("name") ?? "";
const { results, meta } = await env.DB
.prepare("SELECT id, name, message FROM entries WHERE name = ?")
.bind(q)
.all<Entry>();
return Response.json({ results, rows_read: meta.rows_read });
}
return Response.json({ error: "not found" }, { status: 404 });
},
} satisfies ExportedHandler<Env>;npx tsc --noEmit && npx wrangler devอีก terminal
curl -s -X POST http://localhost:8787/api/entries -H "Content-Type: application/json" -d '{"name":"บี","message":"มาลงชื่อ"}'
curl -s "http://localhost:8787/api/entries?limit=5"
curl -s "http://localhost:8787/api/search?name=' OR '1'='1"ผลที่ควรเห็น:
{"id":3}
{"entries":[{"id":3,"name":"บี",...},{"id":2,...},{"id":1,...}],"rows_read":3}
{"results":[],"rows_read":3}→ ข้อความ injection ถูกมองเป็น ค่า ไม่ใช่ SQL จึงได้ผลว่าง ✅ · สังเกต rows_read ของ search = จำนวนแถวทั้งตาราง (full scan)
ทดลอง C — เพิ่ม index ด้วย migration ใหม่ แล้วดู query plan
npx wrangler d1 migrations create guestbook-db add_name_index
echo "CREATE INDEX idx_entries_name ON entries(name);" > migrations/0002_add_name_index.sql
npx wrangler d1 migrations apply guestbook-db --local
npx wrangler d1 execute guestbook-db --local --command "EXPLAIN QUERY PLAN SELECT id FROM entries WHERE name = 'ต้น'"ผลที่ควรเห็น: แผนเปลี่ยนจาก SCAN entries เป็น SEARCH entries USING INDEX idx_entries_name (name=?) → เรียก /api/search?name=ต้น ซ้ำ rows_read ลดลงเหลือเท่าจำนวนแถวที่ตรง
ทดลอง D — ขึ้นของจริง
npx wrangler d1 migrations apply guestbook-db --remote
npx wrangler deploy
curl -s -X POST "https://guestbook.[your-subdomain].workers.dev/api/entries" -H "Content-Type: application/json" -d '{"name":"prod","message":"แถวแรกบน edge"}'
npx wrangler d1 export guestbook-db --remote --output backup.sql && head -5 backup.sqlผลที่ควรเห็น: apply 2 migrations สำเร็จ, {"id":1} (DB จริงเริ่มว่าง แยกจาก DB ในเครื่อง), ไฟล์ backup.sql มี CREATE TABLE entries ...
⚠️ อย่า commit backup.sql ถ้ามีข้อมูลผู้ใช้จริง
เก็บกวาด
npx wrangler delete
npx wrangler d1 delete guestbook-db
rm -f backup.sqlกับดักที่เจอบ่อย
| อาการ | สาเหตุ / แก้ |
|---|---|
production บอก no such table |
apply migration แค่ --local → รัน --remote ก่อน deploy |
| ข้อมูลใน dev กับ production ไม่ตรงกัน | ปกติ — wrangler dev ใช้ DB จำลองในเครื่อง |
| rows read พุ่งจนเกินโควตา | query ไม่มี index / SELECT * + COUNT(*) บนตารางใหญ่ทุก request → เพิ่ม index, cache ผลใน KV |
too many SQL variables |
bind เกิน 100 ค่าใน query เดียว → แบ่ง batch |
| แก้ migration เก่าแล้วไม่มีผล | ไฟล์นั้นถูกบันทึกว่า apply แล้ว → เขียนไฟล์ใหม่ |
| ช้าเมื่อผู้ใช้อยู่ไกล | DB หลักอยู่ location เดียว → สร้างด้วย location hint ใกล้ผู้ใช้ / cache ผลอ่าน / ดู read replication |
| ข้อมูลเสียจาก deploy ผิด | ใช้ Time Travel restore และ export สำรองตามรอบ |
สรุปจำง่าย
D1 = SQLite ที่ไม่มีเซิร์ฟเวอร์ — schema ผ่าน migration ใน git, apply
--localแล้ว--remote—?+.bind()เสมอ — จ่ายตามแถวที่ สแกน จึงต้องมี index — DB เล็กหลายก้อนดีกว่าก้อนใหญ่ — สำรองด้วย Time Travel + export