Wrangler ile D1 Kullanımı
Ders 5: Wrangler ile D1 Kullanımı
Section titled “Ders 5: Wrangler ile D1 Kullanımı”Öğrenme Hedefleri
Section titled “Öğrenme Hedefleri”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
İçerik İçindekiler
Section titled “İçerik İçindekiler”Wrangler’a Giriş
Section titled “Wrangler’a Giriş”Wrangler Nedir?
Section titled “Wrangler Nedir?”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.
Kurulum
Section titled “Kurulum”# Global kurulumnpm install -g wrangler
# Versiyon kontrolüwrangler --version
# Giriş yapmawrangler loginYapılandırma Dosyası
Section titled “Yapılandırma Dosyası”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 deploymentspreview_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 settingsmigrations_dir = "migrations"migrations_table = "d1_migrations"D1 Komutları
Section titled “D1 Komutları”1. Database İşlemleri
Section titled “1. Database İşlemleri”Database Listeleme
Section titled “Database Listeleme”# Tüm veritabanlarını listelenpx wrangler d1 list
# Çıktı:# ┌─────────────────┬───────────────┬──────────────┬──────────────┐# │ name │ version │ created_at │ regions │# ├─────────────────┼───────────────┼──────────────┼──────────────┤# │ users-db │ production │ 2024-01-29 │ WEUR │# │ products-db │ production │ 2024-01-20 │ ENAM │# └─────────────────┴───────────────┴──────────────┴──────────────┘Database Oluşturma
Section titled “Database Oluşturma”# Yeni veritabanı oluşturnpx wrangler d1 create my-database
# Belirli bir bölge ile oluşturnpx wrangler d1 create my-database --location=weur
# Jurisdiction ile oluştur (GDPR compliance için)npx wrangler d1 create my-database --jurisdiction=euDatabase Bilgileri
Section titled “Database Bilgileri”# Veritabanı bilgilerini görüntülenpx wrangler d1 info my-database
# Çıktı:# ┌───────────────────┬──────────────────────────────────────┐# │ │ xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx │# ├───────────────────┼──────────────────────────────────────┤# │ name │ my-database │# ├───────────────────┼──────────────────────────────────────┤# │ version │ production │# ├───────────────────┼──────────────────────────────────────┤# │ created_at │ 2024-01-29T10:30:00.000Z │# └───────────────────┴──────────────────────────────────────┘Database Silme
Section titled “Database Silme”# Veritabanını sil (onay istenir)npx wrangler d1 delete my-database
# Onay istemeden silnpx wrangler d1 delete my-database --force2. SQL Çalıştırma
Section titled “2. SQL Çalıştırma”Tek Komut Çalıştırma
Section titled “Tek Komut Çalıştırma”# Local'de çalıştırnpx wrangler d1 execute my-database --local --command "SELECT * FROM users"
# Remote'da çalıştırnpx wrangler d1 execute my-database --remote --command "SELECT * FROM users"
# Komut dosyasından çalıştırnpx wrangler d1 execute my-database --local --file=./schema.sqlInteractive SQL
Section titled “Interactive SQL”# Local'de interactive modenpx wrangler d1 execute my-database --local --command
# Remote'da interactive modenpx wrangler d1 execute my-database --remote --command3. Backup İşlemleri
Section titled “3. Backup İşlemleri”Backup Listeleme
Section titled “Backup Listeleme”# Backup listesinpx 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 │# └─────────────────────┴──────────────────────────────────────┴────────────┴─────────┘Backup Oluşturma
Section titled “Backup Oluşturma”# Manual backup oluşturnpx 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 │# └─────────────────────┴──────────────────────────────────────┴────────────┴─────────┴───────┘Backup İndirme
Section titled “Backup İndirme”# Backup indirnpx 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!Backup Geri Yükleme
Section titled “Backup Geri Yükleme”# Backup'tan geri yüklenpx wrangler d1 backup restore my-database 123a81a2-ab91-4c2e-8ebc-64d69633faf1
# Çıktı:# Restoring my-database from backup 123a81a2-ab91-4c2e-8ebc-64d69633faf1....# Done!Migration Sistemi
Section titled “Migration Sistemi”Migration Nedir?
Section titled “Migration Nedir?”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.
Migration Komutları
Section titled “Migration Komutları”Migration Oluşturma
Section titled “Migration Oluşturma”# Yeni migration oluşturnpx wrangler d1 migrations create my-database create_users_table
# Çıktı:# ✅ Successfully created migration at migrations/0001_create_users_table.sqlOluşturulan dosya:
-- migrations/0001_create_users_table.sql
-- Migration: create_users_table-- Created at: 2024-01-29 10:30:00
-- Your SQL goes hereCREATE 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);Migration Listeleme
Section titled “Migration Listeleme”# Uygulanmamış migration'ları listelenpx wrangler d1 migrations list my-database
# Çıktı:# ├──────────────────────┬───────────────┬────────────┐# │ name │ applied_at │ status │# ├──────────────────────┼───────────────┼────────────┤# │ 0001_init_db.sql │ NULL │ pending │# │ 0002_add_posts.sql │ NULL │ pending │# └──────────────────────┴───────────────┴────────────┘Migration Uygulama
Section titled “Migration Uygulama”# Local'e uygulanpx wrangler d1 migrations apply my-database --local
# Remote'a uygulanpx 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-databaseMigration Yapısı
Section titled “Migration Yapısı”Ö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.tsMigration Best Practices
Section titled “Migration Best Practices”-- ✅ Her migration'de IF EXISTS/IF NOT EXISTS kullanınDROP 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ınPRAGMA defer_foreign_keys = ON;
-- DDL operationsALTER 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;Local Development
Section titled “Local Development”Local Development Başlatma
Section titled “Local Development Başlatma”# Local development server'ı başlatnpx wrangler dev
# Belirli bir port'ta başlatnpx wrangler dev --port 3000
# Remote bindings ile başlatnpx wrangler dev --remoteLocal D1 Kullanımı
Section titled “Local D1 Kullanımı”# Local veritabanını sorgulanpx wrangler d1 execute my-database --local --command "SELECT * FROM users"
# Local'e veri eklenpx wrangler d1 execute my-database --local --command \ "INSERT INTO users (email, username) VALUES ('test@example.com', 'test')"
# Local'i temizlerm -rf .wranglerEnvironment Variables
Section titled “Environment Variables”.dev.vars dosyası oluşturarak local environment variables tanımlayın:
API_KEY=local_api_key_123SECRET_KEY=local_secret_456DATABASE_URL=local_database_urlÖNEMLİ: .dev.vars dosyasını .gitignore ekleyin!
.dev.vars.wranglerRemote Development
Section titled “Remote Development”Remote Development Modu
Section titled “Remote Development Modu”Remote development ile production veritabanını local’den test edebilirsiniz:
# Remote mode ile başlatnpx wrangler dev --remote
# Sadece belirli binding'ler için remote modenpx wrangler dev --remote=DBRemote Sorgular
Section titled “Remote Sorgular”# Remote veritabanını sorgulanpx wrangler d1 execute my-database --remote --command "SELECT COUNT(*) FROM users"
# Remote'e migration uygulanpx wrangler d1 migrations apply my-database --remote
# Remote'e veri eklenpx wrangler d1 execute my-database --remote --file=./seed-data.sqlRemote vs Local
Section titled “Remote vs Local”| Özellik | Local | Remote |
|---|---|---|
| Veri Konumu | .wrangler/ klasörü | Production D1 |
| Kullanım | Development & Test | Production testing |
| Speed | Çok hızlı | Network’e bağlı |
| Data Persistence | Manuel silmek gerekir | Otomatik backup |
Best Practices
Section titled “Best Practices”1. Environment Yönetimi
Section titled “1. Environment Yönetimi”# ✅ Farklı environment'lar için farklı veritabanlarınpx wrangler d1 create myapp-stagingnpx 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"2. Migration Stratejisi
Section titled “2. Migration Stratejisi”# ✅ Semantic naming kullanınnpx wrangler d1 migrations create my-db initnpx wrangler d1 migrations create my-db add_users_tablenpx wrangler d1 migrations create my-db add_posts_tablenpx 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 migration3. Data Seeding
Section titled “3. Data Seeding”# ✅ Ayrı seed dosyaları kullanın# data/seed_local.sql (test verileri)# data/seed_production.sql (boş veya minimal)
# Local seednpx wrangler d1 execute my-db --local --file=./data/seed_local.sql
# Production seednpx wrangler d1 execute my-db --remote --file=./data/seed_production.sql4. Version Control
Section titled “4. Version Control”# ✅ Migration dosyalarını versiyon kontrolüne ekleyingit add migrations/
# ❌ Local veritabanı dosyalarını ekleMEyinecho ".wrangler/" >> .gitignoreecho "*.sqlite3" >> .gitignoreecho "*.db" >> .gitignore5. CI/CD Entegrasyonu
Section titled “5. CI/CD Entegrasyonu”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 --remotePratik Örnekler
Section titled “Pratik Örnekler”Örnek 1: Proje Kurulumu
Section titled “Örnek 1: Proje Kurulumu”# 1. Yeni proje oluşturnpm create cloudflare@latest my-d1-appcd my-d1-app
# 2. D1 veritabanı oluşturnpx wrangler d1 create my-database
# 3. wrangler.toml'ı güncelle# (Yukarıdaki binding bilgilerini ekleyin)
# 4. İlk migration'ı oluşturnpx 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 uygulanpx wrangler d1 migrations apply my-database --local
# 7. Local development'ı başlatnpm run devÖrnek 2: Production Deployment
Section titled “Örnek 2: Production Deployment”# 1. Remote migration'ı uygulanpx wrangler d1 migrations apply my-database --remote
# 2. Production'a deploy etnpx wrangler deploy
# 3. Production'da test etcurl https://my-d1-app.my-subdomain.workers.dev/usersÖrnek 3: Rollback
Section titled “Örnek 3: Rollback”# 1. Backup oluşturnpx 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üklenpx wrangler d1 backup list my-databasenpx wrangler d1 backup restore my-database <backup-id>Hata Ayıklama
Section titled “Hata Ayıklama”Yaygın Hatalar
Section titled “Yaygın Hatalar”# ❌ 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ınDebug Modu
Section titled “Debug Modu”# Debug modunda çalıştırWRANGLER_DEBUG=1 npx wrangler d1 execute my-db --local --command "SELECT 1"
# Logları görüntülenpx wrangler tail --format prettyBu 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
Sonraki Ders
Section titled “Sonraki Ders”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.
Kaynaklar
Section titled “Kaynaklar”Alıştırma Soruları
Section titled “Alıştırma Soruları”- Local ve Remote development arasındaki fark nedir?
- Migration sistemi neden önemlidir?
.dev.varsdosyası ne için kullanılır?- CI/CD pipeline’ında D1 migration nasıl uygulanır?
- 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ı