LinuxCommandLibrary

knex

TLDR

Initialize Knex project

$ npx knex init
copy
Create migration
$ npx knex migrate:make [migration_name]
copy
Run migrations
$ npx knex migrate:latest
copy
Rollback migration
$ npx knex migrate:rollback
copy
Create seed file
$ npx knex seed:make [seed_name]
copy
Run seeds
$ npx knex seed:run
copy
Show migration status
$ npx knex migrate:status
copy

SYNOPSIS

npx knex command [options]

DESCRIPTION

Knex.js is a SQL query builder for Node.js. The CLI manages database migrations and seeds, providing version-controlled schema changes.
Knex supports PostgreSQL, MySQL, SQLite3, and other databases. Migrations define schema changes; seeds populate test data.

PARAMETERS

init

Create knexfile.js configuration.
migrate:make name
Create new migration.
migrate:latest
Run pending migrations.
migrate:rollback
Undo last migration batch.
migrate:status
Show migration status.
seed:make name
Create seed file.
seed:run
Run seed files.
--env environment
Target environment.
--knexfile path
Specify knexfile path.

KNEXFILE EXAMPLE

$ module.exports = {
  development: {
    client: 'postgresql',
    connection: {
      database: 'mydb',
      user: 'user',
      password: 'password'
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  }
};
copy

CAVEATS

Database connection required for migrations. Rollbacks may cause data loss. Seed order not guaranteed. Test migrations on copy first.

HISTORY

Knex was created by Tim Griesser as a flexible SQL query builder for Node.js. It provides a foundation for ORMs like Objection.js.

SEE ALSO

node(1), prisma(1), sequelize(1)

Copied to clipboard