Knex.js Hile Sayfası

Node.js için SQL sorgu oluşturucu – sorgular, şema, göçler ve işlemler.

Kurulum ve Ayarlar

Knex.js'i kurun ve veritabanı bağlantısını yapılandırın

# Knex'i ve veritabanı sürücünüzü kurun
npm install knex --save

# Veritabanı sürücüleri (birini seçin)
npm install pg          # PostgreSQL
npm install mysql2      # MySQL
npm install sqlite3     # SQLite
npm install tedious     # MSSQL
Paket kurulumu
const knex = require('knex')({
  client: 'mysql2',
  connection: {
    host: '127.0.0.1',
    port: 3306,
    user: 'your_database_user',
    password: 'your_database_password',
    database: 'myapp_test'
  },
  pool: { min: 0, max: 7 }
});
Temel yapılandırma
// Bağlantı dizesi
const knex = require('knex')({
  client: 'pg',
  connection: process.env.DATABASE_URL,
  searchPath: ['knex', 'public']
});

// SQLite bellek içi
const knex = require('knex')({
  client: 'sqlite3',
  connection: { filename: ':memory:' },
  useNullAsDefault: true
});
Alternatif bağlantı yöntemleri

Temel Sorgular

Seçme, ekleme, güncelleme ve silme işlemleri

// Tümünü seç
knex('users').select('*')
// SELECT * FROM users

// Belirli sütunları seç
knex('users').select('id', 'name', 'email')
// SELECT id, name, email FROM users

// Alias ile seç
knex('users').select('id', 'name as full_name')
// SELECT id, name as full_name FROM users

// İlk sonuç
knex('users').first('*')
// SELECT * FROM users LIMIT 1
SELECT sorguları
// Tek satır ekle
knex('users').insert({ name: 'John', email: 'john@example.com' })

// Birden fazla satır ekle
knex('users').insert([
  { name: 'John', email: 'john@example.com' },
  { name: 'Jane', email: 'jane@example.com' }
])

// Dönüş ile ekle (PostgreSQL)
knex('users')
  .insert({ name: 'John', email: 'john@example.com' })
  .returning('id')
INSERT sorguları
// Tüm satırları güncelle
knex('users').update({ status: 'active' })

// Belirli satırları güncelle
knex('users')
  .where('id', 1)
  .update({ name: 'John Updated' })

// Dönüş ile güncelle
knex('users')
  .where('id', 1)
  .update({ name: 'John' })
  .returning('*')
UPDATE sorguları
// Tüm satırları sil
knex('users').del()

// Belirli satırları sil
knex('users').where('id', 1).del()

// Dönüş ile sil
knex('users')
  .where('id', 1)
  .del()
  .returning('*')
DELETE sorguları

WHERE Koşulları

Verileri çeşitli koşullarla filtreleme

// Basit where
knex('users').where('id', 1)
knex('users').where({ id: 1, status: 'active' })

// Operatör ile where
knex('users').where('age', '>', 18)
knex('users').where('created_at', '<=', '2024-01-01')

// Çoklu koşullar (AND)
knex('users')
  .where('status', 'active')
  .where('age', '>', 18)

// OR koşulları
knex('users')
  .where('status', 'active')
  .orWhere('role', 'admin')
Temel WHERE
// Where IN
knex('users').whereIn('id', [1, 2, 3])

// Where NOT IN
knex('users').whereNotIn('status', ['banned', 'deleted'])

// Where NULL
knex('users').whereNull('deleted_at')

// Where NOT NULL
knex('users').whereNotNull('email')

// Where BETWEEN
knex('users').whereBetween('age', [18, 65])

// Where NOT BETWEEN
knex('users').whereNotBetween('age', [0, 18])
Gelişmiş WHERE
// Karmaşık iç içe koşullar
knex('users')
  .where('status', 'active')
  .where(function() {
    this.where('role', 'admin')
      .orWhere('role', 'moderator')
  })
// WHERE status = 'active' AND (role = 'admin' OR role = 'moderator')

// Where EXISTS
knex('users')
  .whereExists(function() {
    this.select('*')
      .from('orders')
      .whereRaw('orders.user_id = users.id')
  })

// Raw WHERE
knex('users').whereRaw('age > ?', [18])
Karmaşık WHERE

Birleştirmeler

Birden fazla tablodan veri birleştirme

// INNER JOIN
knex('users')
  .join('orders', 'users.id', '=', 'orders.user_id')
  .select('users.name', 'orders.total')

// LEFT JOIN
knex('users')
  .leftJoin('orders', 'users.id', 'orders.user_id')
  .select('users.name', 'orders.total')

// RIGHT JOIN
knex('users')
  .rightJoin('orders', 'users.id', 'orders.user_id')

// FULL OUTER JOIN
knex('users')
  .fullOuterJoin('orders', 'users.id', 'orders.user_id')
Temel birleştirmeler
// Çoklu koşullarla birleştir
knex('users')
  .join('orders', function() {
    this.on('users.id', '=', 'orders.user_id')
      .andOn('orders.status', '=', knex.raw('?', ['completed']))
  })

// OR koşullu birleştir
knex('users')
  .join('orders', function() {
    this.on('users.id', '=', 'orders.user_id')
      .orOn('users.email', '=', 'orders.email')
  })

// Çapraz birleştirme
knex('users').crossJoin('roles')
Gelişmiş birleştirmeler

Toplamalar ve Gruplama

Toplama fonksiyonları ve GROUP BY işlemleri

// Sayım
knex('users').count('id as total')

// Ayrı sayım
knex('users').countDistinct('email')

// Toplam
knex('orders').sum('total as revenue')

// Ortalama
knex('orders').avg('total as average_order')

// Min ve Max
knex('orders').min('total as min_order')
knex('orders').max('total as max_order')
Toplama fonksiyonları
// Group by
knex('orders')
  .select('user_id')
  .count('id as order_count')
  .groupBy('user_id')

// Birden fazla sütunla group by
knex('orders')
  .select('user_id', 'status')
  .sum('total as revenue')
  .groupBy('user_id', 'status')

// Having koşulu
knex('orders')
  .select('user_id')
  .count('id as order_count')
  .groupBy('user_id')
  .having('order_count', '>', 5)

// Raw ile having
knex('orders')
  .select('user_id')
  .sum('total as revenue')
  .groupBy('user_id')
  .havingRaw('SUM(total) > ?', [1000])
GROUP BY ve HAVING

Sıralama ve Sınırlama

Sorgu sonuçlarını sıralama ve sayfalama

// Artan sıralama
knex('users').orderBy('name')
knex('users').orderBy('name', 'asc')

// Azalan sıralama
knex('users').orderBy('created_at', 'desc')

// Çoklu sıralama sütunları
knex('users')
  .orderBy('status', 'asc')
  .orderBy('created_at', 'desc')

// Dizi ile order by
knex('users').orderBy([
  { column: 'status', order: 'asc' },
  { column: 'name', order: 'desc' }
])

// Raw ile order by
knex('users').orderByRaw('age DESC NULLS LAST')
Sıralama
// Limit
knex('users').limit(10)

// Offset
knex('users').offset(20)

// Sayfalama
knex('users')
  .limit(10)
  .offset(20)

// Distinct
knex('users').distinct('email')

// Çoklu sütunlarda distinct
knex('users').distinct('email', 'status')
Sınırlama ve sayfalama

Şema - Tablo Oluşturma

Veritabanı tablolarını tanımlama ve oluşturma

// Tablo oluştur
knex.schema.createTable('users', function(table) {
  table.increments('id').primary();
  table.string('name', 100).notNullable();
  table.string('email', 255).unique().notNullable();
  table.integer('age');
  table.boolean('is_active').defaultTo(true);
  table.timestamps(true, true);
});

// Tablo yoksa oluştur
knex.schema.createTableIfNotExists('users', function(table) {
  table.increments('id');
  table.string('email').unique();
});
Temel tablo oluşturma
// Yaygın sütun tipleri
table.increments('id')              // Otomatik artan ID
table.integer('votes')              // Tamsayı
table.bigInteger('big_votes')       // Büyük tamsayı
table.text('description')           // Metin
table.string('name', 255)           // Uzunluklu string
table.float('amount')               // Ondalık
table.decimal('price', 8, 2)        // Decimal(8,2)
table.boolean('is_admin')           // Mantıksal
table.date('birth_date')            // Tarih
table.datetime('created_at')        // Tarih-saat
table.time('alarm_time')            // Saat
table.timestamp('updated_at')       // Zaman damgası
table.json('metadata')              // JSON
table.jsonb('data')                 // JSONB (PostgreSQL)
table.uuid('id')                    // UUID
table.enum('status', ['active', 'inactive'])  // Enum
Column types
// Sütun değiştiricileri
table.string('email')
  .notNullable()           // NOT NULL
  .unique()                // UNIQUE
  .defaultTo('default')    // DEFAULT value
  .unsigned()              // UNSIGNED (for numbers)
  .index()                 // İndeks ekle
  .comment('Email address') // Yorum ekle

// Yabancı anahtarlar
table.integer('user_id')
  .unsigned()
  .notNullable()
  .references('id')
  .inTable('users')
  .onDelete('CASCADE')
  .onUpdate('CASCADE');

// Zaman damgaları yardımcıları
table.timestamps(true, true)  // created_at, updated_at
table.timestamp('created_at').defaultTo(knex.fn.now())
Sütun değiştiricileri ve kısıtlamalar

Şema - Tabloları Değiştirme

Mevcut tablo yapılarını değiştir

// Sütun ekle
knex.schema.table('users', function(table) {
  table.string('phone', 20);
});

// Birden fazla sütun ekle
knex.schema.table('users', function(table) {
  table.string('phone', 20);
  table.string('address', 255);
  table.integer('zip_code');
});

// Sütunu değiştir
knex.schema.alterTable('users', function(table) {
  table.string('email', 500).alter();
});

// Sütunu yeniden adlandır
knex.schema.table('users', function(table) {
  table.renameColumn('name', 'full_name');
});
Tabloları değiştirme
// Sütunu sil
knex.schema.table('users', function(table) {
  table.dropColumn('phone');
});

// Birden fazla sütunu sil
knex.schema.table('users', function(table) {
  table.dropColumns('phone', 'address');
});

// Tabloyu sil
knex.schema.dropTable('users');

// Tabloyu varsa sil
knex.schema.dropTableIfExists('users');

// Tabloyu yeniden adlandır
knex.schema.renameTable('users', 'customers');
Silme ve yeniden adlandırma
// Tablo var mı kontrol et
knex.schema.hasTable('users')
  .then(exists => {
    if (!exists) {
      return knex.schema.createTable('users', table => {
        table.increments('id');
      });
    }
  });

// Sütun var mı kontrol et
knex.schema.hasColumn('users', 'email')
  .then(exists => {
    if (!exists) {
      return knex.schema.table('users', table => {
        table.string('email');
      });
    }
  });
Şema kontrolleri

Şema - İndeksler ve Yabancı Anahtarlar

Veritabanı indekslerini ve ilişkileri oluştur ve yönet

// İndeks oluştur
knex.schema.table('users', function(table) {
  table.index('email');
});

// Adlandırılmış indeks oluştur
knex.schema.table('users', function(table) {
  table.index('email', 'idx_users_email');
});

// Bileşik indeks
knex.schema.table('users', function(table) {
  table.index(['status', 'created_at'], 'idx_status_created');
});

// Benzersiz indeks
knex.schema.table('users', function(table) {
  table.unique('email');
});

// İndeksi sil
knex.schema.table('users', function(table) {
  table.dropIndex('email');
  table.dropIndex([], 'idx_users_email'); // isimle
});
İndeksler
// Yabancı anahtar ekle
knex.schema.table('orders', function(table) {
  table.foreign('user_id')
    .references('id')
    .inTable('users');
});

// Eylemlerle yabancı anahtar
knex.schema.table('orders', function(table) {
  table.foreign('user_id')
    .references('id')
    .inTable('users')
    .onDelete('CASCADE')
    .onUpdate('RESTRICT');
});

// Adlandırılmış yabancı anahtar
knex.schema.table('orders', function(table) {
  table.foreign('user_id', 'fk_orders_user')
    .references('users.id');
});

// Yabancı anahtarı sil
knex.schema.table('orders', function(table) {
  table.dropForeign('user_id');
  table.dropForeign([], 'fk_orders_user'); // isimle
});
Yabancı anahtarlar

İşlemler

Birden fazla sorguyu atomik olarak çalıştır

// Temel işlem
knex.transaction(async (trx) => {
  await trx('users').insert({ name: 'John' });
  await trx('orders').insert({ user_id: 1, total: 100 });
})
.then(() => console.log('İşlem onaylandı'))
.catch((err) => console.error('İşlem başarısız:', err));

// Dönüş değeri olan işlem
const userId = await knex.transaction(async (trx) => {
  const [id] = await trx('users')
    .insert({ name: 'John' })
    .returning('id');
  
  await trx('profiles')
    .insert({ user_id: id, bio: 'Hello' });
  
  return id;
});
Temel işlemler
// Manuel işlem kontrolü
const trx = await knex.transaction();

try {
  await trx('users').insert({ name: 'John' });
  await trx('orders').insert({ user_id: 1, total: 100 });
  await trx.commit();
} catch (err) {
  await trx.rollback();
  throw err;
}

// Kaydetme noktalarıyla işlem
knex.transaction(async (trx) => {
  await trx('users').insert({ name: 'John' });
  
  const savepoint = await trx.savepoint();
  try {
    await trx('orders').insert({ user_id: 1, total: 100 });
    await savepoint.release();
  } catch (err) {
    await savepoint.rollback();
  }
});
Gelişmiş işlem kontrolü

Ham Sorgular

Gerektiğinde ham SQL çalıştır

// Basit ham sorgu
knex.raw('SELECT * FROM users WHERE id = ?', [1])

// Adlandırılmış bağlamalarla ham sorgu
knex.raw('SELECT * FROM users WHERE id = :userId', {
  userId: 1
})

// SELECT içinde ham sorgu
knex('users')
  .select(knex.raw('COUNT(*) as total'))
  .where('status', 'active')

// WHERE içinde ham sorgu
knex('users')
  .whereRaw('age > ?', [18])
  .orWhereRaw('status = ?', ['admin'])
Temel ham sorgular
// Ham güncelleme
knex('users')
  .update({
    updated_at: knex.raw('NOW()'),
    views: knex.raw('views + 1')
  })
  .where('id', 1)

// Ham ekleme
knex('users').insert({
  name: 'John',
  created_at: knex.raw('CURRENT_TIMESTAMP')
})

// Sütun referansları için knex.ref kullanımı
knex('users')
  .where('created_at', '>', knex.ref('updated_at'))
Sorgularda ham kullanım

Göçler

Veritabanı şeması için sürüm kontrolü

// Göç oluştur
npx knex migrate:make create_users_table

// Göçleri çalıştır
npx knex migrate:latest

// Son partiyi geri al
npx knex migrate:rollback

// Tüm göçleri geri al
npx knex migrate:rollback --all

// Göç durumunu kontrol et
npx knex migrate:status

// Belirli bir göçü çalıştır
npx knex migrate:up 001_create_users.js
Göç komutları
// Göç dosyası yapısı
exports.up = function(knex) {
  return knex.schema.createTable('users', function(table) {
    table.increments('id').primary();
    table.string('name', 100).notNullable();
    table.string('email', 255).unique().notNullable();
    table.timestamp('created_at').defaultTo(knex.fn.now());
  });
};

exports.down = function(knex) {
  return knex.schema.dropTable('users');
};
Göç dosyası örneği
// Çoklu işlemlerle göç
exports.up = async function(knex) {
  // users tablosu oluştur
  await knex.schema.createTable('users', table => {
    table.increments('id');
    table.string('email').unique();
  });
  
  // orders tablosu oluştur
  await knex.schema.createTable('orders', table => {
    table.increments('id');
    table.integer('user_id').unsigned();
    table.foreign('user_id').references('users.id');
  });
  
  // İlk verileri ekle
  await knex('users').insert([
    { email: 'admin@example.com' }
  ]);
};

exports.down = async function(knex) {
  await knex.schema.dropTable('orders');
  await knex.schema.dropTable('users');
};
Karmaşık göç

Veri Tohumları

Veritabanını test verileriyle doldur

// Seed dosyası oluştur
npx knex seed:make 01_users

// Tüm seed'leri çalıştır
npx knex seed:run

// Belirli bir seed'i çalıştır
npx knex seed:run --specific=01_users.js
Seed komutları
// Temel seed dosyası
exports.seed = async function(knex) {
  // Mevcut kayıtları sil
  await knex('users').del();
  
  // Seed verilerini ekle
  await knex('users').insert([
    { name: 'John Doe', email: 'john@example.com' },
    { name: 'Jane Smith', email: 'jane@example.com' },
    { name: 'Bob Johnson', email: 'bob@example.com' }
  ]);
};
Temel seed
// İlişkili seed
exports.seed = async function(knex) {
  // Tabloları doğru sırada temizle
  await knex('orders').del();
  await knex('users').del();
  
  // Kullanıcıları ekle ve ID'leri al
  const [userId1] = await knex('users')
    .insert({ name: 'John', email: 'john@example.com' })
    .returning('id');
  
  const [userId2] = await knex('users')
    .insert({ name: 'Jane', email: 'jane@example.com' })
    .returning('id');
  
  // İlgili siparişleri ekle
  await knex('orders').insert([
    { user_id: userId1, total: 100.50 },
    { user_id: userId1, total: 75.25 },
    { user_id: userId2, total: 200.00 }
  ]);
};
İlişkili seed

TypeScript Desteği

TypeScript ile tip güvenli sorgular

// Tablo tiplerini tanımla
interface User {
  id: number;
  name: string;
  email: string;
  created_at: string;
  updated_at: string;
}

interface UserInsert {
  name: string;
  email: string;
}

interface UserUpdate {
  name?: string;
  email?: string;
  updated_at?: string;
}
Tip tanımları
// Knex tiplerini genişlet
import { Knex } from 'knex';

declare module 'knex/types/tables' {
  interface Tables {
    users: User;
    users_composite: Knex.CompositeTableType<
      User,
      UserInsert,
      UserUpdate
    >;
  }
}

// Tip güvenli sorgular
const users = await knex('users').select('*');
// users, User[] tipinde

const newUser = await knex('users_composite')
  .insert({ name: 'John', email: 'john@example.com' })
  .returning('*');
Tip genişletmesi
// Genel sorgu tipleri
const getUserById = async (id: number): Promise<User | undefined> => {
  return knex<User>('users')
    .where({ id })
    .first();
};

const createUser = async (data: UserInsert): Promise<User> => {
  const [user] = await knex<User>('users')
    .insert(data)
    .returning('*');
  return user;
};

const updateUser = async (
  id: number,
  data: UserUpdate
): Promise<User | undefined> => {
  const [user] = await knex<User>('users')
    .where({ id })
    .update(data)
    .returning('*');
  return user;
};
Tiplenmiş sorgu fonksiyonları

Gelişmiş Özellikler

Gelişmiş Knex.js yetenekleri

// Upsert (ekleme veya güncelleme)
knex('users')
  .insert({ id: 1, name: 'John', email: 'john@example.com' })
  .onConflict('id')
  .merge()

// Belirli sütunlarla upsert
knex('users')
  .insert({ id: 1, name: 'John', email: 'john@example.com' })
  .onConflict('email')
  .merge(['name'])

// Insert ignore (MySQL)
knex('users')
  .insert({ email: 'john@example.com' })
  .onConflict('email')
  .ignore()
Upsert işlemleri
// WITH (Ortak Tablo İfadeleri)
knex.with('active_users', (qb) => {
  qb.select('*').from('users').where('status', 'active');
})
.select('*')
.from('active_users')
.where('age', '>', 18);

// Rekürsif CTE
knex.withRecursive('tree', (qb) => {
  qb.select('*').from('categories').where('parent_id', null)
    .union((qb2) => {
      qb2.select('c.*')
        .from('categories as c')
        .join('tree as t', 'c.parent_id', 't.id');
    });
})
.select('*').from('tree');
Ortak Tablo İfadeleri
// Alt sorgular
knex('users')
  .whereIn('id', function() {
    this.select('user_id').from('orders').where('total', '>', 100);
  })

// Seçimde alt sorgu
knex('users')
  .select('name')
  .select(
    knex('orders')
      .count('*')
      .where('orders.user_id', knex.raw('??', ['users.id']))
      .as('order_count')
  )

// FROM içinde alt sorgu
knex
  .select('*')
  .from(
    knex('users')
      .where('status', 'active')
      .as('active_users')
  )
Alt sorgular
// Pencere fonksiyonları
knex('orders')
  .select('*')
  .select(
    knex.raw('ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) as row_num')
  )

// JSON işlemleri (PostgreSQL)
knex('users')
  .select('name')
  .select(knex.raw("metadata->>'age' as age"))
  .where(knex.raw("metadata->>'city'"), 'New York')

// Dizi işlemleri (PostgreSQL)
knex('users')
  .whereRaw('? = ANY(tags)', ['javascript'])
Gelişmiş SQL özellikleri

Bağlantı ve Havuz Yönetimi

Veritabanı bağlantılarını ve havuzu yönetin

// Bağlantı havuzunu yapılandır
const knex = require('knex')({
  client: 'pg',
  connection: {
    host: '127.0.0.1',
    user: 'user',
    password: 'password',
    database: 'myapp'
  },
  pool: {
    min: 2,
    max: 10,
    acquireTimeoutMillis: 30000,
    idleTimeoutMillis: 30000
  }
});

// Bağlantı havuzunu yok et
await knex.destroy();

// Yeniden başlat
knex.initialize();
Havuz yapılandırması
// Bağlantı afterCreate kancası
const knex = require('knex')({
  client: 'pg',
  connection: { /* ... */ },
  pool: {
    afterCreate: function(conn, done) {
      conn.query('SET timezone="UTC";', function(err) {
        done(err, conn);
      });
    }
  }
});

// Dinamik bağlantı
const knex = require('knex')({
  client: 'mysql',
  connection: async () => {
    const token = await getAuthToken();
    return {
      host: 'localhost',
      user: 'user',
      password: token,
      database: 'myapp'
    };
  }
});
Bağlantı kancaları
// Sorguları hata ayıklama
const knex = require('knex')({
  client: 'pg',
  connection: { /* ... */ },
  debug: true  // Tüm sorguları kaydet
});

// Belirli sorguyu hata ayıkla
knex('users')
  .select('*')
  .debug()
  .then(rows => console.log(rows));

// Çalıştırmadan SQL al
const sql = knex('users')
  .where('id', 1)
  .toSQL();
console.log(sql.sql);      // SQL dizesi
console.log(sql.bindings); // Parametreler
Hata ayıklama
Knex.js Hile Sayfası