title | layout | updated | category | intro |
---|---|---|---|---|
Knex |
2017/sheet |
2020-06-03 |
Databases |
[Knex](http://knexjs.org/) is an SQL query builder for Node.js.
This guide targets v0.13.0.
|
{: .-three-column}
require('knex')({
client: 'pg',
connection: 'postgres://user:pass@localhost:5432/dbname'
})
See: Connect
knex.schema.createTable('user', (table) => {
table.increments('id')
table.string('name')
table.integer('age')
})
.then(() => ···)
See: Schema
knex('users')
.where({ email: '[email protected]' })
.then(rows => ···)
{: data-line="2"}
See: Select
knex('users')
.insert({ email: '[email protected]' })
{: data-line="2"}
See: Insert
knex('users')
.where({ id: 135 })
.update({ email: '[email protected]' })
{: data-line="2,3"}
See: Update
knex init
knex migrate:make migration_name
knex migrate:make migration_name -x ts # Generates a TypeScript migration file
knex migrate:latest
knex migrate:rollback
See: Migrations
knex seed:make seed_name
knex seed:make seed_name -x ts # Generates a TypeScript seed file
knex seed:run # Runs all seed files
knex seed:run --specific=seed-filename.js # Runs a specific seed file
See: Seeds
{: .-three-column}
| pg
| PostgreSQL |
| mysql
| MySQL or MariaDB |
| sqlite3
| Sqlite3 |
| mssql
| MSSQL |
Install any of these packages along with knex
.
See: Node.js installation
var knex = require('knex')({
client: 'mysql',
connection: {
host: '127.0.0.1',
user: 'your_database_user',
password: 'your_database_password',
database: 'myapp_test'
},
pool: { min: 0, max: 7 }
})
{: data-line="2,3"}
var pg = require('knex')({
client: 'pg',
connection: process.env.DATABASE_URL,
searchPath: 'knex,public',
pool: { min: 0, max: 7 }
})
{: data-line="2,3"}
var knex = require('knex')({
client: 'sqlite3',
connection: { filename: './mydb.sqlite' }
})
{: data-line="2,3"}
knex
.from('books')
.select('title', 'author', 'year')
.where('title', 'Hello')
.where({ title: 'Hello' })
.whereIn('id', [1, 2, 3])
.whereNot(···)
.whereNotIn('id', [1, 2, 3])
.whereNull('updated_at')
.whereNotNull(···)
.whereExists('updated_at')
.whereNotExists(···)
.whereBetween('votes', [1, 100])
.whereNotBetween(···)
.whereRaw('id = ?', [1])
.where(function () {
this
.where('id', 1)
.orWhere('id', '>', 10)
})
See: Where clauses
knex('users')
.join('contacts', 'users.id', '=', 'contacts.id')
.join('contacts', {'users.id': 'contacts.id'})
.join('accounts', 'accounts.type', '=', knex.raw('?', ['admin']))
.leftJoin(···)
.leftOuterJoin(···)
.rightJoin(···)
.rightOuterJoin(···)
.outerJoin(···)
.fullOuterJoin(···)
.crossJoin(···)
.joinRaw('natural full join table1')
.join('accounts', function () {
this
.on('accounts.id', '=', 'users.account_id')
.orOn('accounts.owner_id', '=', 'users.id')
.onIn('accounts.id', [1, 2, 3, 5, 8])
.onNotIn(···)
.onNull('accounts.email')
.onNotNull(···)
.onExists(function () {
this.select(···)
})
.onNotExists(···)
})
See: Join methods
knex('users')
.distinct()
.groupBy('count')
.groupByRaw('year WITH ROLLUP')
.orderBy('name', 'desc')
.orderByRaw('name DESC')
.offset(10)
.limit(20)
.having('count', '>', 100)
.havingIn('count', [1, 100])
.union(function() {
this.select(···)
})
.unionAll(···)
See: Query builder
knex('users')
.pluck('id')
.then(ids => { ··· })
knex('users')
.first()
.then(user => { ··· })
.count('active')
.count('active as is_active')
.min('age')
.max('age')
.sum('age')
.sumDistinct('age')
.avg('age')
See: Query builder
knex.schema.createTable('accounts', table => {
table.increments('id')
table.string('account_name')
table.integer('age')
table.float('age')
table.decimal('balance', 8, 2)
table.boolean('is_admin')
table.date('birthday')
table.time('created_at')
table.timestamp('created_at').defaultTo(knex.fn.now())
table.json('profile')
table.jsonb('profile')
table.uuid('id').primary()
table.unique('email')
table.unique(['email', 'company_id'])
table.dropUnique(···)
table.foreign('company_id')
.references('companies.id')
table.dropForeign(···)
table.integer('user_id')
.unsigned()
.references('users.id')
})
.then(() => ···)
{: .-setup}
See: Schema builder
knex.schema.table('accounts', table => {
table.string('first_name')
table.string('first_name').alter()
table.renameColumn('admin', 'is_admin')
table.dropColumn('admin')
table.dropTimestamps('created_at')
})
{: .-setup}
See: Schema builder
knex.schema
.renameTable('persons', 'people')
.dropTable('persons')
.hasTable('users').then(exists => ···)
.hasColumn('users', 'id').then(exists => ···)
See: Schema builder
{: .-three-column}
knex('users')
.insert({ name: 'John' })
.insert([
{ name: 'Starsky' },
{ name: 'Hutch' }
])
See: Insert
knex('users')
.where({ id: 2 })
.update({ name: 'Homer' })
See: Update
knex('users')
.where({ id: 2 })
.del()
See: Delete
./node_modules/.bin/knex init
knex migrate:make migration_name
knex migrate:make migration_name --env production
knex migrate:latest
knex migrate:latest --env production
knex migrate:rollback
knex migrate:rollback --env production
See: Migrations