UNPKG

4.82 kBMarkdownView Raw
1# [knex.js](https://knex.github.io/documentation/)
2
3[![npm version](http://img.shields.io/npm/v/knex.svg)](https://npmjs.org/package/knex)
4[![npm downloads](https://img.shields.io/npm/dm/knex.svg)](https://npmjs.org/package/knex)
5![](https://github.com/knex/knex/workflows/CI/badge.svg)
6[![Coverage Status](https://coveralls.io/repos/knex/knex/badge.svg?branch=master)](https://coveralls.io/r/knex/knex?branch=master)
7[![Dependencies Status](https://img.shields.io/librariesio/github/knex/knex)](https://libraries.io/npm/knex)
8[![Gitter chat](https://badges.gitter.im/tgriesser/knex.svg)](https://gitter.im/tgriesser/knex)
9
10> **A SQL query builder that is _flexible_, _portable_, and _fun_ to use!**
11
12A batteries-included, multi-dialect (PostgreSQL, MySQL, CockroachDB, MSSQL, SQLite3, Oracle (including Oracle Wallet Authentication)) query builder for
13Node.js, featuring:
14
15- [transactions](https://knex.github.io/documentation/#Transactions)
16- [connection pooling](https://knex.github.io/documentation/#Installation-pooling)
17- [streaming queries](https://knex.github.io/documentation/#Interfaces-Streams)
18- both a [promise](https://knex.github.io/documentation/#Interfaces-Promises) and [callback](https://knex.github.io/documentation/#Interfaces-Callbacks) API
19- a [thorough test suite](https://github.com/knex/knex/actions)
20
21Node.js versions 12+ are supported.
22
23- Take a look at the [full documentation](https://knex.github.io/documentation) to get started!
24- Browse the [list of plugins and tools](https://github.com/knex/knex/blob/master/ECOSYSTEM.md) built for knex
25- Check out our [recipes wiki](https://github.com/knex/knex/wiki/Recipes) to search for solutions to some specific problems
26- In case of upgrading from an older version, see [migration guide](https://github.com/knex/knex/blob/master/UPGRADING.md)
27
28You can report bugs and discuss features on the [GitHub issues page](https://github.com/knex/knex/issues) or send tweets to [@kibertoad](http://twitter.com/kibertoad).
29
30For support and questions, join our [Gitter channel](https://gitter.im/tgriesser/knex).
31
32For knex-based Object Relational Mapper, see:
33
34- https://github.com/Vincit/objection.js
35- https://github.com/mikro-orm/mikro-orm
36- https://bookshelfjs.org
37
38To see the SQL that Knex will generate for a given query, you can use [Knex Query Lab](https://michaelavila.com/knex-querylab/)
39
40## Examples
41
42We have several examples [on the website](http://knexjs.org). Here is the first one to get you started:
43
44```js
45const knex = require('knex')({
46 client: 'sqlite3',
47 connection: {
48 filename: './data.db',
49 },
50});
51
52try {
53 // Create a table
54 await knex.schema
55 .createTable('users', (table) => {
56 table.increments('id');
57 table.string('user_name');
58 })
59 // ...and another
60 .createTable('accounts', (table) => {
61 table.increments('id');
62 table.string('account_name');
63 table.integer('user_id').unsigned().references('users.id');
64 });
65
66 // Then query the table...
67 const insertedRows = await knex('users').insert({ user_name: 'Tim' });
68
69 // ...and using the insert id, insert into the other table.
70 await knex('accounts').insert({
71 account_name: 'knex',
72 user_id: insertedRows[0],
73 });
74
75 // Query both of the rows.
76 const selectedRows = await knex('users')
77 .join('accounts', 'users.id', 'accounts.user_id')
78 .select('users.user_name as user', 'accounts.account_name as account');
79
80 // map over the results
81 const enrichedRows = selectedRows.map((row) => ({ ...row, active: true }));
82
83 // Finally, add a catch statement
84} catch (e) {
85 console.error(e);
86}
87```
88
89## TypeScript example
90
91```ts
92import { Knex, knex } from 'knex';
93
94interface User {
95 id: number;
96 age: number;
97 name: string;
98 active: boolean;
99 departmentId: number;
100}
101
102const config: Knex.Config = {
103 client: 'sqlite3',
104 connection: {
105 filename: './data.db',
106 },
107};
108
109const knexInstance = knex(config);
110
111try {
112 const users = await knex<User>('users').select('id', 'age');
113} catch (err) {
114 // error handling
115}
116```
117
118## Usage as ESM module
119
120If you are launching your Node application with `--experimental-modules`, `knex.mjs` should be picked up automatically and named ESM import should work out-of-the-box.
121Otherwise, if you want to use named imports, you'll have to import knex like this:
122
123```js
124import { knex } from 'knex/knex.mjs';
125```
126
127You can also just do the default import:
128
129```js
130import knex from 'knex';
131```
132
133If you are not using TypeScript and would like the IntelliSense of your IDE to work correctly, it is recommended to set the type explicitly:
134
135```js
136/**
137 * @type {Knex}
138 */
139const database = knex({
140 client: 'mysql',
141 connection: {
142 host: '127.0.0.1',
143 user: 'your_database_user',
144 password: 'your_database_password',
145 database: 'myapp_test',
146 },
147});
148database.migrate.latest();
149```