Costruttore di query SQL per Node.js – query, schema, migrazioni e transazioni.
Installa Knex.js e configura la connessione al database
# Installa knex e il driver del tuo database
npm install knex --save
# Driver del database (scegli uno)
npm install pg # PostgreSQL
npm install mysql2 # MySQL
npm install sqlite3 # SQLite
npm install tedious # MSSQLconst 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 }
});// Stringa di connessione
const knex = require('knex')({
client: 'pg',
connection: process.env.DATABASE_URL,
searchPath: ['knex', 'public']
});
// SQLite in memoria
const knex = require('knex')({
client: 'sqlite3',
connection: { filename: ':memory:' },
useNullAsDefault: true
});Operazioni di SELECT, INSERT, UPDATE e DELETE
// Seleziona tutti
knex('users').select('*')
// SELECT * FROM users
// Seleziona colonne specifiche
knex('users').select('id', 'name', 'email')
// SELECT id, name, email FROM users
// Seleziona con alias
knex('users').select('id', 'name as full_name')
// SELECT id, name as full_name FROM users
// Primo risultato
knex('users').first('*')
// SELECT * FROM users LIMIT 1// Inserisci una singola riga
knex('users').insert({ name: 'John', email: 'john@example.com' })
// Inserisci più righe
knex('users').insert([
{ name: 'John', email: 'john@example.com' },
{ name: 'Jane', email: 'jane@example.com' }
])
// Inserisci con returning (PostgreSQL)
knex('users')
.insert({ name: 'John', email: 'john@example.com' })
.returning('id')// Aggiorna tutte le righe
knex('users').update({ status: 'active' })
// Aggiorna righe specifiche
knex('users')
.where('id', 1)
.update({ name: 'John Updated' })
// Aggiorna con returning
knex('users')
.where('id', 1)
.update({ name: 'John' })
.returning('*')// Elimina tutte le righe
knex('users').del()
// Elimina righe specifiche
knex('users').where('id', 1).del()
// Elimina con returning
knex('users')
.where('id', 1)
.del()
.returning('*')Filtrare i dati con varie condizioni
// Where semplice
knex('users').where('id', 1)
knex('users').where({ id: 1, status: 'active' })
// Where con operatore
knex('users').where('age', '>', 18)
knex('users').where('created_at', '<=', '2024-01-01')
// Condizioni multiple (AND)
knex('users')
.where('status', 'active')
.where('age', '>', 18)
// Condizioni OR
knex('users')
.where('status', 'active')
.orWhere('role', 'admin')// 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])// Condizioni annidate complesse
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')
})
// Where RAW
knex('users').whereRaw('age > ?', [18])Combinare dati da più tabelle
// 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')// Join con più condizioni
knex('users')
.join('orders', function() {
this.on('users.id', '=', 'orders.user_id')
.andOn('orders.status', '=', knex.raw('?', ['completed']))
})
// Join con condizione OR
knex('users')
.join('orders', function() {
this.on('users.id', '=', 'orders.user_id')
.orOn('users.email', '=', 'orders.email')
})
// Cross join
knex('users').crossJoin('roles')Funzioni di aggregazione e operazioni GROUP BY
// Conteggio
knex('users').count('id as total')
// Conteggio distinto
knex('users').countDistinct('email')
// Somma
knex('orders').sum('total as revenue')
// Media
knex('orders').avg('total as average_order')
// Min e Max
knex('orders').min('total as min_order')
knex('orders').max('total as max_order')// Group by
knex('orders')
.select('user_id')
.count('id as order_count')
.groupBy('user_id')
// Group by più colonne
knex('orders')
.select('user_id', 'status')
.sum('total as revenue')
.groupBy('user_id', 'status')
// Clausola HAVING
knex('orders')
.select('user_id')
.count('id as order_count')
.groupBy('user_id')
.having('order_count', '>', 5)
// Having con raw
knex('orders')
.select('user_id')
.sum('total as revenue')
.groupBy('user_id')
.havingRaw('SUM(total) > ?', [1000])Ordinare e paginare i risultati delle query
// Ordinamento ascendente
knex('users').orderBy('name')
knex('users').orderBy('name', 'asc')
// Ordinamento discendente
knex('users').orderBy('created_at', 'desc')
// Più colonne di ordinamento
knex('users')
.orderBy('status', 'asc')
.orderBy('created_at', 'desc')
// Ordinamento tramite array
knex('users').orderBy([
{ column: 'status', order: 'asc' },
{ column: 'name', order: 'desc' }
])
// Ordinamento raw
knex('users').orderByRaw('age DESC NULLS LAST')// Limite
knex('users').limit(10)
// Offset
knex('users').offset(20)
// Paginazione
knex('users')
.limit(10)
.offset(20)
// Distinct
knex('users').distinct('email')
// Distinct su più colonne
knex('users').distinct('email', 'status')Definire e creare tabelle del database
// Creare tabella
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);
});
// Creare tabella se non esiste
knex.schema.createTableIfNotExists('users', function(table) {
table.increments('id');
table.string('email').unique();
});// Tipi di colonna comuni
table.increments('id') // ID auto-incrementante
table.integer('votes') // Intero
table.bigInteger('big_votes') // Intero grande
table.text('description') // Testo
table.string('name', 255) // Stringa con lunghezza
table.float('amount') // Float
table.decimal('price', 8, 2) // Decimale(8,2)
table.boolean('is_admin') // Booleano
table.date('birth_date') // Data
table.datetime('created_at') // Data e ora
table.time('alarm_time') // Ora
table.timestamp('updated_at') // Timestamp
table.json('metadata') // JSON
table.jsonb('data') // JSONB (PostgreSQL)
table.uuid('id') // UUID
table.enum('status', ['active', 'inactive']) // Enum// Modificatori di colonna
table.string('email')
.notNullable() // NON NULL
.unique() // UNICO
.defaultTo('default') // valore DEFAULT
.unsigned() // NON SIGNATO (per numeri)
.index() // Aggiungi indice
.comment('Email address') // Aggiungi commento
// Chiavi esterne
table.integer('user_id')
.unsigned()
.notNullable()
.references('id')
.inTable('users')
.onDelete('CASCADE')
.onUpdate('CASCADE');
// Helper per timestamp
table.timestamps(true, true) // created_at, updated_at
table.timestamp('created_at').defaultTo(knex.fn.now())Modifica le strutture delle tabelle esistenti
// Aggiungi colonna
knex.schema.table('users', function(table) {
table.string('phone', 20);
});
// Aggiungi più colonne
knex.schema.table('users', function(table) {
table.string('phone', 20);
table.string('address', 255);
table.integer('zip_code');
});
// Modifica colonna
knex.schema.alterTable('users', function(table) {
table.string('email', 500).alter();
});
// Rinomina colonna
knex.schema.table('users', function(table) {
table.renameColumn('name', 'full_name');
});// Elimina colonna
knex.schema.table('users', function(table) {
table.dropColumn('phone');
});
// Elimina più colonne
knex.schema.table('users', function(table) {
table.dropColumns('phone', 'address');
});
// Elimina tabella
knex.schema.dropTable('users');
// Elimina tabella se esiste
knex.schema.dropTableIfExists('users');
// Rinomina tabella
knex.schema.renameTable('users', 'customers');// Verifica se la tabella esiste
knex.schema.hasTable('users')
.then(exists => {
if (!exists) {
return knex.schema.createTable('users', table => {
table.increments('id');
});
}
});
// Verifica se la colonna esiste
knex.schema.hasColumn('users', 'email')
.then(exists => {
if (!exists) {
return knex.schema.table('users', table => {
table.string('email');
});
}
});Crea e gestisci indici di database e relazioni
// Crea indice
knex.schema.table('users', function(table) {
table.index('email');
});
// Crea indice con nome
knex.schema.table('users', function(table) {
table.index('email', 'idx_users_email');
});
// Indice composito
knex.schema.table('users', function(table) {
table.index(['status', 'created_at'], 'idx_status_created');
});
// Indice unico
knex.schema.table('users', function(table) {
table.unique('email');
});
// Elimina indice
knex.schema.table('users', function(table) {
table.dropIndex('email');
table.dropIndex([], 'idx_users_email'); // per nome
});// Aggiungi chiave esterna
knex.schema.table('orders', function(table) {
table.foreign('user_id')
.references('id')
.inTable('users');
});
// Chiave esterna con azioni
knex.schema.table('orders', function(table) {
table.foreign('user_id')
.references('id')
.inTable('users')
.onDelete('CASCADE')
.onUpdate('RESTRICT');
});
// Chiave esterna con nome
knex.schema.table('orders', function(table) {
table.foreign('user_id', 'fk_orders_user')
.references('users.id');
});
// Elimina chiave esterna
knex.schema.table('orders', function(table) {
table.dropForeign('user_id');
table.dropForeign([], 'fk_orders_user'); // per nome
});Esegui più query in modo atomico
// Transazione di base
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));
// Transazione con valore di ritorno
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;
});// Controllo manuale della transazione
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;
}
// Transazione con savepoint
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();
}
});Esegui SQL raw quando necessario
// Query raw semplice
knex.raw('SELECT * FROM users WHERE id = ?', [1])
// Query raw con binding nominati
knex.raw('SELECT * FROM users WHERE id = :userId', {
userId: 1
})
// Raw nella select
knex('users')
.select(knex.raw('COUNT(*) as total'))
.where('status', 'active')
// Raw nella where
knex('users')
.whereRaw('age > ?', [18])
.orWhereRaw('status = ?', ['admin'])// Aggiornamento raw
knex('users')
.update({
updated_at: knex.raw('NOW()'),
views: knex.raw('views + 1')
})
.where('id', 1)
// Inserimento raw
knex('users').insert({
name: 'John',
created_at: knex.raw('CURRENT_TIMESTAMP')
})
// Uso di knex.ref per riferimenti di colonna
knex('users')
.where('created_at', '>', knex.ref('updated_at'))Controllo di versione per lo schema del database
// Crea migrazione
npx knex migrate:make create_users_table
// Esegui migrazioni
npx knex migrate:latest
// Ripristina ultimo batch
npx knex migrate:rollback
// Ripristina tutte le migrazioni
npx knex migrate:rollback --all
// Verifica lo stato delle migrazioni
npx knex migrate:status
// Esegui migrazione specifica
npx knex migrate:up 001_create_users.js// Struttura del file di migrazione
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');
};// Migrazione con più operazioni
exports.up = async function(knex) {
// Crea tabella users
await knex.schema.createTable('users', table => {
table.increments('id');
table.string('email').unique();
});
// Crea tabella orders
await knex.schema.createTable('orders', table => {
table.increments('id');
table.integer('user_id').unsigned();
table.foreign('user_id').references('users.id');
});
// Inserisci dati iniziali
await knex('users').insert([
{ email: 'admin@example.com' }
]);
};
exports.down = async function(knex) {
await knex.schema.dropTable('orders');
await knex.schema.dropTable('users');
};Popola il database con dati di test
// Crea file seed
npx knex seed:make 01_users
// Esegui tutti i seed
npx knex seed:run
// Esegui seed specifico
npx knex seed:run --specific=01_users.js// File seed di base
exports.seed = async function(knex) {
// Elimina le voci esistenti
await knex('users').del();
// Inserisci dati 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' }
]);
};// Seed con relazioni
exports.seed = async function(knex) {
// Pulisci le tabelle nell'ordine corretto
await knex('orders').del();
await knex('users').del();
// Inserisci utenti e ottieni gli 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');
// Inserisci ordini correlati
await knex('orders').insert([
{ user_id: userId1, total: 100.50 },
{ user_id: userId1, total: 75.25 },
{ user_id: userId2, total: 200.00 }
]);
};Query tipizzate con TypeScript
// Definisci i tipi di tabella
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;
}// Amplia i tipi di Knex
import { Knex } from 'knex';
declare module 'knex/types/tables' {
interface Tables {
users: User;
users_composite: Knex.CompositeTableType<
User,
UserInsert,
UserUpdate
>;
}
}
// Query tipizzate
const users = await knex('users').select('*');
// users è tipizzato come User[]
const newUser = await knex('users_composite')
.insert({ name: 'John', email: 'john@example.com' })
.returning('*');// Tipi di query generici
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;
};Funzionalità avanzate di Knex.js
// Upsert (inserimento o aggiornamento)
knex('users')
.insert({ id: 1, name: 'John', email: 'john@example.com' })
.onConflict('id')
.merge()
// Upsert con colonne specifiche
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()// WITH (Espressioni di Tabella Comuni)
knex.with('active_users', (qb) => {
qb.select('*').from('users').where('status', 'active');
})
.select('*')
.from('active_users')
.where('age', '>', 18);
// CTE Ricorsivo
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');// Sottoquery
knex('users')
.whereIn('id', function() {
this.select('user_id').from('orders').where('total', '>', 100);
})
// Sottoquery nella select
knex('users')
.select('name')
.select(
knex('orders')
.count('*')
.where('orders.user_id', knex.raw('??', ['users.id']))
.as('order_count')
)
// Sottoquery nella clausola FROM
knex
.select('*')
.from(
knex('users')
.where('status', 'active')
.as('active_users')
)// Funzioni di finestra
knex('orders')
.select('*')
.select(
knex.raw('ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) as row_num')
)
// Operazioni JSON (PostgreSQL)
knex('users')
.select('name')
.select(knex.raw("metadata->>'age' as age"))
.where(knex.raw("metadata->>'city'"), 'New York')
// Operazioni su array (PostgreSQL)
knex('users')
.whereRaw('? = ANY(tags)', ['javascript'])Gestisci le connessioni al database e il pool
// Configura il pool di connessione
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
}
});
// Distruggi il pool di connessione
await knex.destroy();
// Re-inizializza
knex.initialize();// Hook afterCreate della connessione
const knex = require('knex')({
client: 'pg',
connection: { /* ... */ },
pool: {
afterCreate: function(conn, done) {
conn.query('SET timezone="UTC";', function(err) {
done(err, conn);
});
}
}
});
// Connessione dinamica
const knex = require('knex')({
client: 'mysql',
connection: async () => {
const token = await getAuthToken();
return {
host: 'localhost',
user: 'user',
password: token,
database: 'myapp'
};
}
});// Debug delle query
const knex = require('knex')({
client: 'pg',
connection: { /* ... */ },
debug: true // Registra tutte le query
});
// Debug di una query specifica
knex('users')
.select('*')
.debug()
.then(rows => console.log(rows));
// Ottieni SQL senza eseguire
const sql = knex('users')
.where('id', 1)
.toSQL();
console.log(sql.sql); // Stringa SQL
console.log(sql.bindings); // Parametri