Ściągawka Knex.js

Budowniczy zapytań SQL dla Node.js – zapytania, schematy, migracje i transakcje.

Instalacja i konfiguracja

Zainstaluj Knex.js i skonfiguruj połączenie z bazą danych

# Zainstaluj knex i sterownik bazy danych
npm install knex --save

# Sterowniki baz danych (wybierz jeden)
npm install pg          # PostgreSQL
npm install mysql2      # MySQL
npm install sqlite3     # SQLite
npm install tedious     # MSSQL
Instalacja pakietu
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 }
});
Podstawowa konfiguracja
// Łańcuch połączenia
const knex = require('knex')({
  client: 'pg',
  connection: process.env.DATABASE_URL,
  searchPath: ['knex', 'public']
});

// SQLite w pamięci
const knex = require('knex')({
  client: 'sqlite3',
  connection: { filename: ':memory:' },
  useNullAsDefault: true
});
Alternatywne metody połączenia

Podstawowe zapytania

Operacje SELECT, INSERT, UPDATE i DELETE

// Wybierz wszystkie
knex('users').select('*')
// SELECT * FROM users

// Wybierz konkretne kolumny
knex('users').select('id', 'name', 'email')
// SELECT id, name, email FROM users

// Wybierz z aliasem
knex('users').select('id', 'name as full_name')
// SELECT id, name as full_name FROM users

// Pierwszy wynik
knex('users').first('*')
// SELECT * FROM users LIMIT 1
Zapytania SELECT
// Wstaw pojedynczy wiersz
knex('users').insert({ name: 'John', email: 'john@example.com' })

// Wstaw wiele wierszy
knex('users').insert([
  { name: 'John', email: 'john@example.com' },
  { name: 'Jane', email: 'jane@example.com' }
])

// Wstaw z zwracaniem (PostgreSQL)
knex('users')
  .insert({ name: 'John', email: 'john@example.com' })
  .returning('id')
Zapytania INSERT
// Zaktualizuj wszystkie wiersze
knex('users').update({ status: 'active' })

// Zaktualizuj określone wiersze
knex('users')
  .where('id', 1)
  .update({ name: 'John Updated' })

// Aktualizacja z zwracaniem
knex('users')
  .where('id', 1)
  .update({ name: 'John' })
  .returning('*')
Zapytania UPDATE
// Usuń wszystkie wiersze
knex('users').del()

// Usuń określone wiersze
knex('users').where('id', 1).del()

// Usuwanie z zwracaniem
knex('users')
  .where('id', 1)
  .del()
  .returning('*')
Zapytania DELETE

Klauzule WHERE

Filtrowanie danych przy użyciu różnych warunków

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

// Where z operatorem
knex('users').where('age', '>', 18)
knex('users').where('created_at', '<=', '2024-01-01')

// Wiele warunków (AND)
knex('users')
  .where('status', 'active')
  .where('age', '>', 18)

// Warunki OR
knex('users')
  .where('status', 'active')
  .orWhere('role', 'admin')
Podstawowe WHERE
// Gdzie IN
knex('users').whereIn('id', [1, 2, 3])

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

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

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

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

// Gdzie NOT BETWEEN
knex('users').whereNotBetween('age', [0, 18])
Zaawansowane WHERE
// Złożone zagnieżdżone warunki
knex('users')
  .where('status', 'active')
  .where(function() {
    this.where('role', 'admin')
      .orWhere('role', 'moderator')
  })
// WHERE status = 'active' AND (role = 'admin' OR role = 'moderator')

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

// Surowe WHERE
knex('users').whereRaw('age > ?', [18])
Złożone WHERE

Łączenia

Łączenie danych z wielu tabel

// 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')
Podstawowe łączenia
// Łączenie z wieloma warunkami
knex('users')
  .join('orders', function() {
    this.on('users.id', '=', 'orders.user_id')
      .andOn('orders.status', '=', knex.raw('?', ['completed']))
  })

// Łączenie z warunkiem OR
knex('users')
  .join('orders', function() {
    this.on('users.id', '=', 'orders.user_id')
      .orOn('users.email', '=', 'orders.email')
  })

// Cross join
knex('users').crossJoin('roles')
Zaawansowane łączenia

Agregacje i grupowanie

Funkcje agregujące i operacje GROUP BY

// Liczba
knex('users').count('id as total')

// Liczba unikalna
knex('users').countDistinct('email')

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

// Średnia
knex('orders').avg('total as average_order')

// Min i Max
knex('orders').min('total as min_order')
knex('orders').max('total as max_order')
Funkcje agregujące
// Grupowanie
knex('orders')
  .select('user_id')
  .count('id as order_count')
  .groupBy('user_id')

// Grupowanie po wielu kolumnach
knex('orders')
  .select('user_id', 'status')
  .sum('total as revenue')
  .groupBy('user_id', 'status')

// Klauzula HAVING
knex('orders')
  .select('user_id')
  .count('id as order_count')
  .groupBy('user_id')
  .having('order_count', '>', 5)

// HAVING z raw
knex('orders')
  .select('user_id')
  .sum('total as revenue')
  .groupBy('user_id')
  .havingRaw('SUM(total) > ?', [1000])
GROUP BY i HAVING

Sortowanie i ograniczanie

Sortowanie i paginacja wyników zapytań

// Sortowanie rosnące
knex('users').orderBy('name')
knex('users').orderBy('name', 'asc')

// Sortowanie malejące
knex('users').orderBy('created_at', 'desc')

// Wielokrotne kolumny sortowania
knex('users')
  .orderBy('status', 'asc')
  .orderBy('created_at', 'desc')

// Sortowanie przy użyciu tablicy
knex('users').orderBy([
  { column: 'status', order: 'asc' },
  { column: 'name', order: 'desc' }
])

// Sortowanie raw
knex('users').orderByRaw('age DESC NULLS LAST')
Sortowanie
// Limit
knex('users').limit(10)

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

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

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

// Distinct na wielu kolumnach
knex('users').distinct('email', 'status')
Ograniczanie i paginacja

Schemat – tworzenie tabel

Definiowanie i tworzenie tabel w bazie danych

// Tworzenie tabeli
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);
});

// Tworzenie tabeli, jeśli nie istnieje
knex.schema.createTableIfNotExists('users', function(table) {
  table.increments('id');
  table.string('email').unique();
});
Podstawowe tworzenie tabel
// Typowe typy kolumn
table.increments('id')              // Autoinkrementujący ID
table.integer('votes')              // Liczba całkowita
table.bigInteger('big_votes')       // Duża liczba całkowita
table.text('description')           // Tekst
table.string('name', 255)           // Ciąg znaków o określonej długości
table.float('amount')               // Liczba zmiennoprzecinkowa
table.decimal('price', 8, 2)        // Decimal(8,2)
table.boolean('is_admin')           // Boolean
table.date('birth_date')            // Data
table.datetime('created_at')        // Data i czas
table.time('alarm_time')            // Czas
table.timestamp('updated_at')       // Znacznik czasu
table.json('metadata')              // JSON
table.jsonb('data')                 // JSONB (PostgreSQL)
table.uuid('id')                    // UUID
table.enum('status', ['active', 'inactive'])  // Enum
Typy kolumn
// Modyfikatory kolumn
table.string('email')
  .notNullable()           // NOT NULL
  .unique()                // UNIKATOWY
  .defaultTo('default')    // Wartość domyślna
  .unsigned()              // UNSIGNED (dla liczb)
  .index()                 // Dodaj indeks
  .comment('Email address') // Dodaj komentarz

// Klucze obce
table.integer('user_id')
  .unsigned()
  .notNullable()
  .references('id')
  .inTable('users')
  .onDelete('CASCADE')
  .onUpdate('CASCADE');

// Pomocnicze znaczniki czasu
table.timestamps(true, true)  // created_at, updated_at
table.timestamp('created_at').defaultTo(knex.fn.now())
Modyfikatory kolumn i ograniczenia

Schemat - Modyfikowanie tabel

Modyfikuj istniejące struktury tabel

// Dodaj kolumnę
knex.schema.table('users', function(table) {
  table.string('phone', 20);
});

// Dodaj wiele kolumn
knex.schema.table('users', function(table) {
  table.string('phone', 20);
  table.string('address', 255);
  table.integer('zip_code');
});

// Zmodyfikuj kolumnę
knex.schema.alterTable('users', function(table) {
  table.string('email', 500).alter();
});

// Zmień nazwę kolumny
knex.schema.table('users', function(table) {
  table.renameColumn('name', 'full_name');
});
Modyfikowanie tabel
// Usuń kolumnę
knex.schema.table('users', function(table) {
  table.dropColumn('phone');
});

// Usuń wiele kolumn
knex.schema.table('users', function(table) {
  table.dropColumns('phone', 'address');
});

// Usuń tabelę
knex.schema.dropTable('users');

// Usuń tabelę, jeśli istnieje
knex.schema.dropTableIfExists('users');

// Zmień nazwę tabeli
knex.schema.renameTable('users', 'customers');
Usuwanie i zmiana nazw
// Sprawdź, czy tabela istnieje
knex.schema.hasTable('users')
  .then(exists => {
    if (!exists) {
      return knex.schema.createTable('users', table => {
        table.increments('id');
      });
    }
  });

// Sprawdź, czy kolumna istnieje
knex.schema.hasColumn('users', 'email')
  .then(exists => {
    if (!exists) {
      return knex.schema.table('users', table => {
        table.string('email');
      });
    }
  });
Sprawdzenia schematu

Schemat - Indeksy i Klucze Obce

Twórz i zarządzaj indeksami bazy danych oraz relacjami

// Utwórz indeks
knex.schema.table('users', function(table) {
  table.index('email');
});

// Utwórz nazwany indeks
knex.schema.table('users', function(table) {
  table.index('email', 'idx_users_email');
});

// Indeks złożony
knex.schema.table('users', function(table) {
  table.index(['status', 'created_at'], 'idx_status_created');
});

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

// Usuń indeks
knex.schema.table('users', function(table) {
  table.dropIndex('email');
  table.dropIndex([], 'idx_users_email'); // po nazwie
});
Indeksy
// Dodaj klucz obcy
knex.schema.table('orders', function(table) {
  table.foreign('user_id')
    .references('id')
    .inTable('users');
});

// Klucz obcy z akcjami
knex.schema.table('orders', function(table) {
  table.foreign('user_id')
    .references('id')
    .inTable('users')
    .onDelete('CASCADE')
    .onUpdate('RESTRICT');
});

// Nazwany klucz obcy
knex.schema.table('orders', function(table) {
  table.foreign('user_id', 'fk_orders_user')
    .references('users.id');
});

// Usuń klucz obcy
knex.schema.table('orders', function(table) {
  table.dropForeign('user_id');
  table.dropForeign([], 'fk_orders_user'); // po nazwie
});
Klucze obce

Transakcje

Wykonuj wiele zapytań atomowo

// Podstawowa transakcja
knex.transaction(async (trx) => {
  await trx('users').insert({ name: 'John' });
  await trx('orders').insert({ user_id: 1, total: 100 });
})
.then(() => console.log('Transaction committed'))
.catch((err) => console.error('Transaction failed:', err));

// Transakcja z wartością zwracaną
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;
});
Podstawowe transakcje
// Ręczna kontrola transakcji
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;
}

// Transakcja z punktami zapisu
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();
  }
});
Zaawansowana kontrola transakcji

Zapytania surowe

Wykonuj surowe zapytania SQL w razie potrzeby

// Proste zapytanie surowe
knex.raw('SELECT * FROM users WHERE id = ?', [1])

// Zapytanie surowe z nazwanymi powiązaniami
knex.raw('SELECT * FROM users WHERE id = :userId', {
  userId: 1
})

// Surowe w SELECT
knex('users')
  .select(knex.raw('COUNT(*) as total'))
  .where('status', 'active')

// Surowe w WHERE
knex('users')
  .whereRaw('age > ?', [18])
  .orWhereRaw('status = ?', ['admin'])
Podstawowe zapytania surowe
// Surowa aktualizacja
knex('users')
  .update({
    updated_at: knex.raw('NOW()'),
    views: knex.raw('views + 1')
  })
  .where('id', 1)

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

// Użycie knex.ref do odwołań do kolumn
knex('users')
  .where('created_at', '>', knex.ref('updated_at'))
Surowe w zapytaniach

Migracje

Kontrola wersji schematu bazy danych

# Utwórz migrację
npx knex migrate:make create_users_table

# Uruchom migracje
npx knex migrate:latest

# Cofnij ostatnią partię
npx knex migrate:rollback

# Cofnij wszystkie migracje
npx knex migrate:rollback --all

# Sprawdź status migracji
npx knex migrate:status

# Uruchom konkretną migrację
npx knex migrate:up 001_create_users.js
Polecenia migracji
// Struktura pliku migracji
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');
};
Przykład pliku migracji
// Migracja z wieloma operacjami
exports.up = async function(knex) {
  // Utwórz tabelę users
  await knex.schema.createTable('users', table => {
    table.increments('id');
    table.string('email').unique();
  });
  
  // Utwórz tabelę orders
  await knex.schema.createTable('orders', table => {
    table.increments('id');
    table.integer('user_id').unsigned();
    table.foreign('user_id').references('users.id');
  });
  
  // Wstaw początkowe dane
  await knex('users').insert([
    { email: 'admin@example.com' }
  ]);
};

exports.down = async function(knex) {
  await knex.schema.dropTable('orders');
  await knex.schema.dropTable('users');
};
Migracja złożona

Ziarna

Wypełnij bazę danych danymi testowymi

# Utwórz plik seed
npx knex seed:make 01_users

# Uruchom wszystkie seedy
npx knex seed:run

# Uruchom konkretny seed
npx knex seed:run --specific=01_users.js
Polecenia seedów
// Podstawowy plik seed
exports.seed = async function(knex) {
  // Usuń istniejące rekordy
  await knex('users').del();
  
  // Wstaw dane seed
  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' }
  ]);
};
Podstawowy seed
// Seed z relacjami
exports.seed = async function(knex) {
  // Wyczyść tabele w odpowiedniej kolejności
  await knex('orders').del();
  await knex('users').del();
  
  // Wstaw użytkowników i pobierz ich ID
  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');
  
  // Wstaw powiązane zamówienia
  await knex('orders').insert([
    { user_id: userId1, total: 100.50 },
    { user_id: userId1, total: 75.25 },
    { user_id: userId2, total: 200.00 }
  ]);
};
Seed z relacjami

Wsparcie TypeScript

Zapytania typowo-bezpieczne z TypeScript

// Define table types
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;
}
Definicje typów
// Rozszerz typy Knex
import { Knex } from 'knex';

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

// Zapytania typowo-bezpieczne
const users = await knex('users').select('*');
// users is typed as User[]

const newUser = await knex('users_composite')
  .insert({ name: 'John', email: 'john@example.com' })
  .returning('*');
Rozszerzenie typów
// Ogólne typy zapytań
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;
};
Typowane funkcje zapytań

Zaawansowane funkcje

Zaawansowane możliwości Knex.js

// Upsert (wstawianie lub aktualizacja)
knex('users')
  .insert({ id: 1, name: 'John', email: 'john@example.com' })
  .onConflict('id')
  .merge()

// Upsert z określonymi kolumnami
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()
Operacje Upsert
// WITH (wyrażenia wspólne - CTE)
knex.with('active_users', (qb) => {
  qb.select('*').from('users').where('status', 'active');
})
.select('*')
.from('active_users')
.where('age', '>', 18);

// Rekurencyjny 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');
Wyrażenia wspólne (CTE)
// Podzapytania
knex('users')
  .whereIn('id', function() {
    this.select('user_id').from('orders').where('total', '>', 100);
  })

// Podzapytanie w SELECT
knex('users')
  .select('name')
  .select(
    knex('orders')
      .count('*')
      .where('orders.user_id', knex.raw('??', ['users.id']))
      .as('order_count')
  )

// Podzapytanie w FROM
knex
  .select('*')
  .from(
    knex('users')
      .where('status', 'active')
      .as('active_users')
  )
Podzapytania
// Funkcje okna
knex('orders')
  .select('*')
  .select(
    knex.raw('ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) as row_num')
  )

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

// Operacje na tablicach (PostgreSQL)
knex('users')
  .whereRaw('? = ANY(tags)', ['javascript'])
Zaawansowane funkcje SQL

Zarządzanie połączeniami i pulą

Zarządzaj połączeniami bazodanowymi i pulą

// Konfiguracja puli połączeń
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
  }
});

// Zniszczenie puli połączeń
await knex.destroy();

// Ponowne inicjalizowanie
knex.initialize();
Konfiguracja puli
// Hook afterCreate połączenia
const knex = require('knex')({
  client: 'pg',
  connection: { /* ... */ },
  pool: {
    afterCreate: function(conn, done) {
      conn.query('SET timezone="UTC";', function(err) {
        done(err, conn);
      });
    }
  }
});

// Dynamiczne połączenie
const knex = require('knex')({
  client: 'mysql',
  connection: async () => {
    const token = await getAuthToken();
    return {
      host: 'localhost',
      user: 'user',
      password: token,
      database: 'myapp'
    };
  }
});
Hooki połączeń
// Debugowanie zapytań
const knex = require('knex')({
  client: 'pg',
  connection: { /* ... */ },
  debug: true  // Logowanie wszystkich zapytań
});

// Debugowanie konkretnego zapytania
knex('users')
  .select('*')
  .debug()
  .then(rows => console.log(rows));

// Pobranie SQL bez wykonywania
const sql = knex('users')
  .where('id', 1)
  .toSQL();
console.log(sql.sql);      // Ciąg SQL
console.log(sql.bindings); // Parametry
Debugowanie
Ściągawka Knex.js