Skip to content

Wrangler ile D1 Kullanımı

Bu dersi tamamladıktan sonra:

  • Wrangler CLI’ı etkili şekilde kullanabileceksiniz
  • D1 komutları ile veritabanı yönetimini yapabileceksiniz
  • Migration sistemi ile schema versiyonlamasını öğreneceksiniz
  • Local ve remote development ortamlarını yönetebileceksiniz
  1. Wrangler’a Giriş
  2. D1 Komutları
  3. Migration Sistemi
  4. Local Development
  5. Remote Development
  6. Best Practices

Wrangler, Cloudflare Workers ve D1 ile çalışmak için resmi CLI aracıdır. Geliştirme, test ve deployment süreçlerini kolaylaştırır.

Terminal window
# Global kurulum
npm install -g wrangler
# Versiyon kontrolü
wrangler --version
# Giriş yapma
wrangler login

wrangler.toml dosyası projenizin yapılandırmasını içerir:

name = "my-d1-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"
# D1 database bindings
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# Preview database for PR deployments
preview_database_id = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyyyyyy"
# Multiple databases
[[d1_databases]]
binding = "DB2"
database_name = "my-database-2"
database_id = "zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzzz"
# Custom migrations settings
migrations_dir = "migrations"
migrations_table = "d1_migrations"

Terminal window
# Tüm veritabanlarını listele
npx wrangler d1 list
# Çıktı:
# ┌─────────────────┬───────────────┬──────────────┬──────────────┐
# │ name │ version │ created_at │ regions │
# ├─────────────────┼───────────────┼──────────────┼──────────────┤
# │ users-db │ production │ 2024-01-29 │ WEUR │
# │ products-db │ production │ 2024-01-20 │ ENAM │
# └─────────────────┴───────────────┴──────────────┴──────────────┘
Terminal window
# Yeni veritabanı oluştur
npx wrangler d1 create my-database
# Belirli bir bölge ile oluştur
npx wrangler d1 create my-database --location=weur
# Jurisdiction ile oluştur (GDPR compliance için)
npx wrangler d1 create my-database --jurisdiction=eu
Terminal window
# Veritabanı bilgilerini görüntüle
npx wrangler d1 info my-database
# Çıktı:
# ┌───────────────────┬──────────────────────────────────────┐
# │ │ xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx │
# ├───────────────────┼──────────────────────────────────────┤
# │ name │ my-database │
# ├───────────────────┼──────────────────────────────────────┤
# │ version │ production │
# ├───────────────────┼──────────────────────────────────────┤
# │ created_at │ 2024-01-29T10:30:00.000Z │
# └───────────────────┴──────────────────────────────────────┘
Terminal window
# Veritabanını sil (onay istenir)
npx wrangler d1 delete my-database
# Onay istemeden sil
npx wrangler d1 delete my-database --force
Terminal window
# Local'de çalıştır
npx wrangler d1 execute my-database --local --command "SELECT * FROM users"
# Remote'da çalıştır
npx wrangler d1 execute my-database --remote --command "SELECT * FROM users"
# Komut dosyasından çalıştır
npx wrangler d1 execute my-database --local --file=./schema.sql
Terminal window
# Local'de interactive mode
npx wrangler d1 execute my-database --local --command
# Remote'da interactive mode
npx wrangler d1 execute my-database --remote --command
Terminal window
# Backup listesi
npx wrangler d1 backup list my-database
# Çıktı:
# ┌─────────────────────┬──────────────────────────────────────┬────────────┬─────────┐
# │ created_at │ id │ num_tables │ size │
# ├─────────────────────┼──────────────────────────────────────┼────────────┼─────────┤
# │ 1 hour ago │ 123a81a2-ab91-4c2e-8ebc-64d69633faf1 │ 3 │ 95.3 kB │
# ├─────────────────────┼──────────────────────────────────────┼────────────┼─────────┤
# │ 1 day ago │ 456b91b2-bc02-5d3e-9fcd-75e797444062 │ 3 │ 94.1 kB │
# └─────────────────────┴──────────────────────────────────────┴────────────┴─────────┘
Terminal window
# Manual backup oluştur
npx wrangler d1 backup create my-database
# Çıktı:
# ┌─────────────────────┬──────────────────────────────────────┬────────────┬─────────┬───────┐
# │ created_at │ id │ num_tables │ size │ state │
# ├─────────────────────┼──────────────────────────────────────┼────────────┼─────────┼───────┤
# │ 2024-01-29T10:30:00 │ 789c92c2-cd13-6e4f-0gde-86e898555173 │ 3 │ 95.3 kB │ done │
# └─────────────────────┴──────────────────────────────────────┴────────────┴─────────┴───────┘
Terminal window
# Backup indir
npx wrangler d1 backup download my-database 123a81a2-ab91-4c2e-8ebc-64d69633faf1
# Çıktı:
# 🌀 Downloading backup 123a81a2-ab91-4c2e-8ebc-64d69633faf1 from 'my-database'
# 🌀 Saving to /path/to/my-database.123a81a.sqlite3
# 🌀 Done!
Terminal window
# Backup'tan geri yükle
npx wrangler d1 backup restore my-database 123a81a2-ab91-4c2e-8ebc-64d69633faf1
# Çıktı:
# Restoring my-database from backup 123a81a2-ab91-4c2e-8ebc-64d69633faf1....
# Done!

Migration, veritabanı schema’sını versiyonlu olarak yönetmek için kullanılan bir sistemdir. Her migration dosyası veritabanında yapılan değişiklikleri içerir.

Terminal window
# Yeni migration oluştur
npx wrangler d1 migrations create my-database create_users_table
# Çıktı:
# ✅ Successfully created migration at migrations/0001_create_users_table.sql

Oluşturulan dosya:

-- migrations/0001_create_users_table.sql
-- Migration: create_users_table
-- Created at: 2024-01-29 10:30:00
-- Your SQL goes here
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Terminal window
# Uygulanmamış migration'ları listele
npx wrangler d1 migrations list my-database
# Çıktı:
# ├──────────────────────┬───────────────┬────────────┐
# │ name │ applied_at │ status │
# ├──────────────────────┼───────────────┼────────────┤
# │ 0001_init_db.sql │ NULL │ pending │
# │ 0002_add_posts.sql │ NULL │ pending │
# └──────────────────────┴───────────────┴────────────┘
Terminal window
# Local'e uygula
npx wrangler d1 migrations apply my-database --local
# Remote'a uygula
npx wrangler d1 migrations apply my-database --remote
# Çıktı:
# ✔ Migration 0001_init_db.sql is newer than the current database version
# ✔ Successfully applied 2 migrations to my-database

Önerilen migration yapısı:

my-project/
├── migrations/
│ ├── 0001_init_db.sql
│ ├── 0002_add_users_table.sql
│ ├── 0003_add_posts_table.sql
│ └── 0004_add_indexes.sql
├── wrangler.toml
└── src/
└── index.ts
-- ✅ Her migration'de IF EXISTS/IF NOT EXISTS kullanın
DROP TABLE IF EXISTS users;
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE
);
-- ✅ Foreign key'leri defer_foreign_keys ile kullanın
PRAGMA defer_foreign_keys = ON;
-- DDL operations
ALTER TABLE users ADD COLUMN age INTEGER;
PRAGMA defer_foreign_keys = OFF;
-- ✅ Migration'leri tersine çalıştırılabilir yapın
-- (Down migration için SQL comments ekleyin)
-- DOWN: DROP TABLE users;

Terminal window
# Local development server'ı başlat
npx wrangler dev
# Belirli bir port'ta başlat
npx wrangler dev --port 3000
# Remote bindings ile başlat
npx wrangler dev --remote
Terminal window
# Local veritabanını sorgula
npx wrangler d1 execute my-database --local --command "SELECT * FROM users"
# Local'e veri ekle
npx wrangler d1 execute my-database --local --command \
"INSERT INTO users (email, username) VALUES ('[email protected]', 'test')"
# Local'i temizle
rm -rf .wrangler

.dev.vars dosyası oluşturarak local environment variables tanımlayın:

.dev.vars
API_KEY=local_api_key_123
SECRET_KEY=local_secret_456
DATABASE_URL=local_database_url

ÖNEMLİ: .dev.vars dosyasını .gitignore ekleyin!

.gitignore
.dev.vars
.wrangler

Remote development ile production veritabanını local’den test edebilirsiniz:

Terminal window
# Remote mode ile başlat
npx wrangler dev --remote
# Sadece belirli binding'ler için remote mode
npx wrangler dev --remote=DB
Terminal window
# Remote veritabanını sorgula
npx wrangler d1 execute my-database --remote --command "SELECT COUNT(*) FROM users"
# Remote'e migration uygula
npx wrangler d1 migrations apply my-database --remote
# Remote'e veri ekle
npx wrangler d1 execute my-database --remote --file=./seed-data.sql
ÖzellikLocalRemote
Veri Konumu.wrangler/ klasörüProduction D1
KullanımDevelopment & TestProduction testing
SpeedÇok hızlıNetwork’e bağlı
Data PersistenceManuel silmek gerekirOtomatik backup

Terminal window
# ✅ Farklı environment'lar için farklı veritabanları
npx wrangler d1 create myapp-staging
npx wrangler d1 create myapp-production
# wrangler.toml
[[env.production.d1_databases]]
binding = "DB"
database_name = "myapp-production"
database_id = "prod-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
[[env.staging.d1_databases]]
binding = "DB"
database_name = "myapp-staging"
database_id = "staging-yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"
Terminal window
# ✅ Semantic naming kullanın
npx wrangler d1 migrations create my-db init
npx wrangler d1 migrations create my-db add_users_table
npx wrangler d1 migrations create my-db add_posts_table
npx wrangler d1 migrations create my-db add_indexes
# ✅ Migration'leri küçük tutun
# ❌ DEĞİL: 1000 satırlık tek migration
# ✅ EVET: 10 adet 100 satırlık migration
Terminal window
# ✅ Ayrı seed dosyaları kullanın
# data/seed_local.sql (test verileri)
# data/seed_production.sql (boş veya minimal)
# Local seed
npx wrangler d1 execute my-db --local --file=./data/seed_local.sql
# Production seed
npx wrangler d1 execute my-db --remote --file=./data/seed_production.sql
Terminal window
# ✅ Migration dosyalarını versiyon kontrolüne ekleyin
git add migrations/
# ❌ Local veritabanı dosyalarını ekleMEyin
echo ".wrangler/" >> .gitignore
echo "*.sqlite3" >> .gitignore
echo "*.db" >> .gitignore
.github/workflows/deploy.yml
name: Deploy to Workers
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: cloudflare/wrangler-action@v2
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
command: d1 migrations apply MY_DB --remote

Terminal window
# 1. Yeni proje oluştur
npm create cloudflare@latest my-d1-app
cd my-d1-app
# 2. D1 veritabanı oluştur
npx wrangler d1 create my-database
# 3. wrangler.toml'ı güncelle
# (Yukarıdaki binding bilgilerini ekleyin)
# 4. İlk migration'ı oluştur
npx wrangler d1 migrations create my-database init
# 5. Migration dosyasını düzenle
# (migrations/0001_init.sql'i açın ve schema ekleyin)
# 6. Local'e uygula
npx wrangler d1 migrations apply my-database --local
# 7. Local development'ı başlat
npm run dev
Terminal window
# 1. Remote migration'ı uygula
npx wrangler d1 migrations apply my-database --remote
# 2. Production'a deploy et
npx wrangler deploy
# 3. Production'da test et
curl https://my-d1-app.my-subdomain.workers.dev/users
Terminal window
# 1. Backup oluştur
npx wrangler d1 backup create my-database
# 2. Migration'u geri al (manuel)
# Migration dosyasını tersine yazın ve tekrar uygulayın
# 3. Alternatif: Backup'tan geri yükle
npx wrangler d1 backup list my-database
npx wrangler d1 backup restore my-database <backup-id>

Terminal window
# ❌ Hata: "database not found"
# Çözüm: wrangler.toml'da database_name ve database_id kontrol edin
# ❌ Hata: "migration already applied"
# Çözüm: Migration numarasını değiştirin veya skip edin
# ❌ Hata: "local database not found"
# Çözüm: Önce migration'ı local'e uygulayın
# ❌ Hata: "permission denied"
# Çözüm: wrangler login ile tekrar giriş yapın
Terminal window
# Debug modunda çalıştır
WRANGLER_DEBUG=1 npx wrangler d1 execute my-db --local --command "SELECT 1"
# Logları görüntüle
npx wrangler tail --format pretty

Bu derste aşağıdaki konuları öğrendiniz:

✅ Wrangler CLI komutları ve kullanımı ✅ D1 veritabanı yönetimi (create, list, info, delete) ✅ SQL execution (local ve remote) ✅ Migration sistemi ve best practices ✅ Local vs Remote development ✅ Backup ve restore işlemleri ✅ CI/CD entegrasyonu

Bir sonraki dersimizde “D1 Database API” başlığı altında:

  • Workers’tan D1’e erişim
  • prepare(), batch(), exec() metodları
  • Error handling ve best practices konularını inceleyeceğiz.
  1. Local ve Remote development arasındaki fark nedir?
  2. Migration sistemi neden önemlidir?
  3. .dev.vars dosyası ne için kullanılır?
  4. CI/CD pipeline’ında D1 migration nasıl uygulanır?
  5. Backup ve restore işlemleri nasıl yapılır?

Ders Süresi: 60 dakika Zorluk Seviyesi: Orta Ön Koşullar: Ders 4: Temel SQL Komutları