mirror of
https://github.com/knex/knex.git
synced 2025-08-01 13:22:04 +00:00
1711 lines
60 KiB
HTML
1711 lines
60 KiB
HTML
<!DOCTYPE HTML>
|
||
<html>
|
||
<head>
|
||
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
|
||
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
|
||
<meta name="viewport" content="width=device-width">
|
||
<link rel="canonical" href="http://knexjs.org" />
|
||
<link rel="icon" href="docs/images/favicon.ico" />
|
||
<title>Knex.js - A Query Builder for Javascript</title>
|
||
<style>
|
||
body {
|
||
font-size: 14px;
|
||
line-height: 22px;
|
||
background: #FEFFFC;
|
||
color: #000;
|
||
font-family: Helvetica Neue, Helvetica, Arial;
|
||
}
|
||
.interface {
|
||
font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
|
||
}
|
||
div#sidebar {
|
||
background: #fff;
|
||
position: fixed;
|
||
top: 0; left: 0; bottom: 0;
|
||
width: 200px;
|
||
overflow-y: auto;
|
||
overflow-x: hidden;
|
||
-webkit-overflow-scrolling: touch;
|
||
padding: 15px 0 30px 30px;
|
||
border-right: 1px solid #bbb;
|
||
box-shadow: 0 0 20px #ccc; -webkit-box-shadow: 0 0 20px #ccc; -moz-box-shadow: 0 0 20px #ccc;
|
||
}
|
||
a.toc_title, a.toc_title:visited {
|
||
display: block;
|
||
color: black;
|
||
font-weight: bold;
|
||
margin-top: 15px;
|
||
}
|
||
a.toc_title:hover {
|
||
text-decoration: underline;
|
||
}
|
||
#sidebar .version {
|
||
font-size: 10px;
|
||
font-weight: normal;
|
||
}
|
||
ul.toc_section {
|
||
font-size: 11px;
|
||
line-height: 14px;
|
||
margin: 5px 0 0 0;
|
||
padding-left: 0px;
|
||
list-style-type: none;
|
||
font-family: Lucida Grande;
|
||
}
|
||
.toc_section li {
|
||
cursor: pointer;
|
||
margin: 0 0 3px 0;
|
||
}
|
||
.toc_section li a {
|
||
text-decoration: none;
|
||
color: black;
|
||
}
|
||
.toc_section li a:hover {
|
||
text-decoration: underline;
|
||
}
|
||
div.container {
|
||
width: 550px;
|
||
margin: 40px 0 50px 260px;
|
||
}
|
||
div.container ul.small {
|
||
font-size: 12px;
|
||
}
|
||
img#logo {
|
||
width: 450px;
|
||
}
|
||
.warning {
|
||
font-size: 12px;
|
||
line-height: 18px;
|
||
font-style: italic;
|
||
}
|
||
p {
|
||
margin: 20px 0;
|
||
width: 550px;
|
||
}
|
||
a, a:visited {
|
||
color: #444;
|
||
}
|
||
a:active, a:hover {
|
||
color: #000;
|
||
}
|
||
h1, h2, h3, h4, h5, h6 {
|
||
padding-top: 20px;
|
||
}
|
||
h2 {
|
||
font-size: 20px;
|
||
}
|
||
b.header {
|
||
font-size: 16px;
|
||
line-height: 30px;
|
||
}
|
||
span.small {
|
||
font-size: 12px;
|
||
font-style: italic;
|
||
}
|
||
span.alias {
|
||
font-size: 14px;
|
||
font-style: italic;
|
||
margin-left: 20px;
|
||
}
|
||
table, tr, td {
|
||
margin: 0; padding: 0;
|
||
}
|
||
td {
|
||
padding: 2px 12px 2px 0;
|
||
}
|
||
table .rule {
|
||
height: 1px;
|
||
background: #ccc;
|
||
margin: 5px 0;
|
||
}
|
||
ul {
|
||
list-style-type: circle;
|
||
padding: 0 0 0 20px;
|
||
}
|
||
li {
|
||
width: 500px;
|
||
margin-bottom: 10px;
|
||
}
|
||
code, pre, tt {
|
||
font-family: Monaco, Consolas, "Lucida Console", monospace;
|
||
font-size: 12px;
|
||
line-height: 18px;
|
||
font-style: normal;
|
||
}
|
||
tt {
|
||
padding: 0px 3px;
|
||
background: #fff;
|
||
border: 1px solid #ddd;
|
||
zoom: 1;
|
||
}
|
||
code {
|
||
margin-left: 20px;
|
||
}
|
||
pre {
|
||
font-size: 12px;
|
||
padding: 2px 0 2px 15px;
|
||
border-left: 5px solid #bbb;
|
||
margin: 0px 0 30px;
|
||
}
|
||
@media only screen and (-webkit-min-device-pixel-ratio: 1.5) and (max-width: 640px),
|
||
only screen and (-o-min-device-pixel-ratio: 3/2) and (max-width: 640px),
|
||
only screen and (min-device-pixel-ratio: 1.5) and (max-width: 640px) {
|
||
img {
|
||
max-width: 100%;
|
||
}
|
||
div#sidebar {
|
||
-webkit-overflow-scrolling: initial;
|
||
position: relative;
|
||
width: 90%;
|
||
height: 120px;
|
||
left: 0;
|
||
top: -7px;
|
||
padding: 10px 0 10px 30px;
|
||
border: 0;
|
||
}
|
||
img#logo {
|
||
width: auto;
|
||
height: auto;
|
||
}
|
||
div.container {
|
||
margin: 0;
|
||
width: 100%;
|
||
}
|
||
p, div.container ul {
|
||
max-width: 98%;
|
||
overflow-x: scroll;
|
||
}
|
||
pre {
|
||
overflow: scroll;
|
||
}
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<div id="sidebar" class="interface">
|
||
|
||
<a class="toc_title" href="#">
|
||
Knex.js <span class="version">(0.5.0)</span>
|
||
</a>
|
||
<ul class="toc_section">
|
||
<li>» <a href="https://github.com/tgriesser/knex">GitHub Repository</a></li>
|
||
<li>» <a href="docs/knex.html">Annotated Source</a></li>
|
||
<li>» <a href="#changelog">Change Log</a></li>
|
||
</ul>
|
||
|
||
<a class="toc_title" href="#Installation">
|
||
Installation
|
||
</a>
|
||
|
||
<a class="toc_title" href="#Upgrading">
|
||
Upgrading
|
||
</a>
|
||
|
||
<a class="toc_title" href="#Initialize">
|
||
Initialize
|
||
</a>
|
||
|
||
<a class="toc_title" href="#Builder">
|
||
Query Builder
|
||
</a>
|
||
<ul class="toc_section">
|
||
<li>– <a href="#Builder-main"><b>constructor</b></a></li>
|
||
<li>– <a href="#Builder-select">select</a></li>
|
||
<li>– <a href="#Builder-column">column</a></li>
|
||
<li>– <a href="#Builder-from">from</a></li>
|
||
<li>– <a href="#Builder-where">where <b>+18 methods</b></a></li>
|
||
<li>– <a href="#Builder-distinct">distinct</a></li>
|
||
<li>– <a href="#Builder-join">join</a></li>
|
||
<li>– <a href="#Builder-groupBy">groupBy</a></li>
|
||
<li>– <a href="#Builder-orderBy">orderBy</a></li>
|
||
<li>– <a href="#Builder-having">having</a></li>
|
||
<li>– <a href="#Builder-offset">offset</a></li>
|
||
<li>– <a href="#Builder-limit">limit</a></li>
|
||
<li>– <a href="#Builder-union">union</a></li>
|
||
<li>– <a href="#Builder-unionAll">unionAll</a></li>
|
||
<li>– <a href="#Builder-insert">insert</a></li>
|
||
<li>– <a href="#Builder-returning">returning</a></li>
|
||
<li>– <a href="#Builder-update">update</a></li>
|
||
<li>– <a href="#Builder-del">del / delete</a></li>
|
||
<li>– <a href="#Builder-transacting">transacting</a></li>
|
||
<li> – <a href="#Builder-forUpdate">forUpdate</a></li>
|
||
<li> – <a href="#Builder-forShare">forShare</a></li>
|
||
<li>– <a href="#Builder-count">count</a></li>
|
||
<li>– <a href="#Builder-min">min</a></li>
|
||
<li>– <a href="#Builder-max">max</a></li>
|
||
<li>– <a href="#Builder-sum">sum</a></li>
|
||
<li>– <a href="#Builder-increment">increment</a></li>
|
||
<li>– <a href="#Builder-decrement">decrement</a></li>
|
||
<li>– <a href="#Builder-truncate">truncate</a></li>
|
||
<li>– <a href="#Builder-debug">debug</a></li>
|
||
<li>– <a href="#Builder-options">options</a></li>
|
||
<li><b><a href="#Builder-Interface">Interface:</a></b></li>
|
||
<li>– <a href="#Builder-tap">tap</a></li>
|
||
<li>– <a href="#Builder-then">then</a></li>
|
||
<li>– <a href="#Builder-exec">exec</a></li>
|
||
<li>– <a href="#Builder-toString">toString</a></li>
|
||
</ul>
|
||
|
||
<a class="toc_title" href="#Transaction">
|
||
Transaction
|
||
</a>
|
||
|
||
<a class="toc_title" href="#Schema">
|
||
Schema
|
||
</a>
|
||
<ul class="toc_section">
|
||
<li>– <a href="#Schema-createTable">createTable</a></li>
|
||
<li>– <a href="#Schema-renameTable">renameTable</a></li>
|
||
<li>– <a href="#Schema-dropTable">dropTable</a></li>
|
||
<li>– <a href="#Schema-hasColumn">hasColumn</a></li>
|
||
<li>– <a href="#Schema-hasTable">hasTable</a></li>
|
||
<li>– <a href="#Schema-dropTableIfExists">dropTableIfExists</a></li>
|
||
<li>– <a href="#Schema-table">table</a></li>
|
||
<li>– <a href="#Schema-charset">charset</a></li>
|
||
<li>– <a href="#Schema-collate">collate</a></li>
|
||
<li><b><a href="#Schema-Building">Schema Building:</a></b></li>
|
||
<li>– <a href="#Schema-dropColumn">dropColumn</a></li>
|
||
<li>– <a href="#Schema-dropColumns">dropColumns</a></li>
|
||
<li>– <a href="#Schema-renameColumn">renameColumn</a></li>
|
||
<li>– <a href="#Schema-increments">increments</a></li>
|
||
<li>– <a href="#Schema-integer">integer</a></li>
|
||
<li>– <a href="#Schema-bigInteger">bigInteger</a></li>
|
||
<li>– <a href="#Schema-text">text</a></li>
|
||
<li>– <a href="#Schema-string">string</a></li>
|
||
<li>– <a href="#Schema-float">float</a></li>
|
||
<li>– <a href="#Schema-decimal">decimal</a></li>
|
||
<li>– <a href="#Schema-boolean">boolean</a></li>
|
||
<li>– <a href="#Schema-date">date</a></li>
|
||
<li>– <a href="#Schema-dateTime">dateTime</a></li>
|
||
<li>– <a href="#Schema-time">time</a></li>
|
||
<li>– <a href="#Schema-timestamp">timestamp</a></li>
|
||
<li>– <a href="#Schema-binary">binary</a></li>
|
||
<li>– <a href="#Schema-enum">enum / enu</a></li>
|
||
<li>– <a href="#Schema-json">json</a></li>
|
||
<li>– <a href="#Schema-uuid">uuid</a></li>
|
||
<li>– <a href="#Schema-comment">comment</a></li>
|
||
<li>– <a href="#Schema-engine">engine</a></li>
|
||
<li>– <a href="#Schema-charset">charset</a></li>
|
||
<li>– <a href="#Schema-collate">collate</a></li>
|
||
<li>– <a href="#Schema-specificType">specificType</a></li>
|
||
<li><a href="#Chainable"><b>Chainable:</b></li>
|
||
<li>– <a href="#Chainable-index">index</a></li>
|
||
<li>– <a href="#Chainable-primary">primary</a></li>
|
||
<li>– <a href="#Chainable-unique">unique</a></li>
|
||
<li>– <a href="#Chainable-defaultTo">defaultTo</a></li>
|
||
<li>– <a href="#Chainable-unsigned">unsigned</a></li>
|
||
<li>– <a href="#Chainable-notNullable">notNullable</a></li>
|
||
<li>– <a href="#Chainable-nullable">nullable</a></li>
|
||
<li>– <a href="#Chainable-after">after</a></li>
|
||
<li>– <a href="#Chainable-comment">comment</a></li>
|
||
</ul>
|
||
|
||
<a class="toc_title" href="#Raw">
|
||
Raw
|
||
</a>
|
||
<ul class="toc_section">
|
||
<li>– <a href="#Raw-Expressions">Raw Expressions</a></li>
|
||
<li>– <a href="#Raw-Queries">Raw Queries</a></li>
|
||
</ul>
|
||
|
||
<a class="toc_title" href="#Migrate">
|
||
Migrate
|
||
</a>
|
||
<ul class="toc_section">
|
||
<li>– <a href="#Migrate-make">make</a></li>
|
||
<li>– <a href="#Migrate-latest">latest</a></li>
|
||
<li>– <a href="#Migrate-rollback">rollback</a></li>
|
||
<li>– <a href="#Migrate-currentVersion">currentVersion</a></li>
|
||
</ul>
|
||
|
||
<a class="toc_title" href="#faq">
|
||
F.A.Q.
|
||
</a>
|
||
|
||
<a class="toc_title" href="#changelog">
|
||
Change Log
|
||
</a>
|
||
|
||
</div>
|
||
|
||
<div class="container">
|
||
|
||
<p>
|
||
<img id="logo" src="docs/images/knex.png" alt="Knex.js">
|
||
</p>
|
||
|
||
<p>
|
||
Knex.js is a query builder for <b>Postgres</b>, <b>MySQL</b> and <b>SQLite3</b>, designed to be flexible,
|
||
portable, and fun to use. It features both traditional node style <a href="#Builder-exec">callbacks</a>
|
||
as well as a <a href="#Builder-then">promise</a> interface for cleaner async flow control, full featured
|
||
query and schema builders, <b>transaction support</b>, connection pooling and standardized responses between
|
||
different query clients and dialects.
|
||
</p>
|
||
|
||
<p>
|
||
The project is <a href="http://github.com/tgriesser/knex">hosted on GitHub</a>,
|
||
and the <a href="docs/knex.html">annotated source code</a> is available,
|
||
and has a comprehensive <a href="https://travis-ci.org/tgriesser/knex">test suite</a>.
|
||
</p>
|
||
|
||
<p>
|
||
Knex is available for use under the <a href="http://github.com/tgriesser/knex/blob/master/LICENSE">MIT software license</a>.
|
||
</p>
|
||
|
||
<p>
|
||
You can report bugs and discuss features on the
|
||
<a href="http://github.com/tgriesser/knex/issues">GitHub issues page</a>,
|
||
add pages to the <a href="https://github.com/tgriesser/knex/wiki">wiki</a>
|
||
or send tweets to <a href="http://twitter.com/tgriesser">@tgriesser</a>.
|
||
</p>
|
||
|
||
<p>
|
||
Thanks to all of the great <a href="https://github.com/tgriesser/knex/graphs/contributors">contributions</a> to the project.
|
||
</a>
|
||
|
||
<p class="warning">
|
||
Special thanks to <a href="https://twitter.com/taylorotwell">Taylor Otwell</a> and his work
|
||
on the <a href="http://laravel.com/docs/queries">Laravel Query Builder</a>,
|
||
from which much of the code and syntax is derived.
|
||
</p>
|
||
|
||
|
||
<h2>Latest Release: 0.5.0 - <span class="small"><a href="#changelog">Change Log</a></span></h2>
|
||
|
||
<p>
|
||
Current Develop —
|
||
<a href="https://travis-ci.org/tgriesser/knex">
|
||
<img src="https://travis-ci.org/tgriesser/knex.png?branch=master" alt="Travis Badge">
|
||
</a>
|
||
</p>
|
||
|
||
<h2 id="Installation">
|
||
Installation
|
||
</h2>
|
||
|
||
<p>
|
||
All dependencies are specified in <tt>package.json</tt> file but include <tt>lodash</tt>,
|
||
<tt>bluebird</tt>, and the <tt>generic-pool-redux</tt> libraries. You then need to install
|
||
either <tt>mysql</tt>, <tt>pg</tt>, or <tt>sqlite3</tt> from <tt>npm</tt> if you wish
|
||
to use one of these databases with node.js, or create your own client
|
||
adapter and specify it in <a href="#Initialize">knex.initialize</a>.
|
||
</p>
|
||
|
||
<pre>
|
||
$ npm install knex
|
||
|
||
# Then add one of the following:
|
||
$ npm install mysql
|
||
$ npm install pg
|
||
$ npm install sqlite3
|
||
</pre>
|
||
|
||
<h2 id="Upgrading">Upgrading from 0.4.x</h2>
|
||
|
||
<p>
|
||
Minor changes from the 0.4.x series, include the fact that aggregate functions are
|
||
no longer aliased as "aggregate", but rather left as-is, unless explicitly aliased.
|
||
See <a href="https://github.com/tgriesser/knex/pull/110">this ticket</a> for more info.
|
||
</p>
|
||
|
||
<p>
|
||
If you are upgrading Knex from 0.2.x to 0.4.x, you'll notice that some things have broken.
|
||
Luckily, with a few quick fixes to your code, you should be up and runnning in no-time.
|
||
<ul>
|
||
<li>
|
||
Global state is no longer stored in the library, an instance is returned from <tt>Knex.initialize</tt>,
|
||
so you will need to call this once and then reference this <tt>knex</tt> client elsewhere in your application.
|
||
</li>
|
||
<li>
|
||
Lowercasing of <tt>knex.raw</tt>, <tt>knex.transaction</tt>, and <tt>knex.schema</tt>.
|
||
</li>
|
||
<li>
|
||
Created columns are now nullable by default, unless <tt>notNullable</tt> is chained as an option.
|
||
</li>
|
||
<li>
|
||
Keys created with <tt>increments</tt> are now assumed to be unsigned (MySQL) by default.
|
||
</li>
|
||
<li>
|
||
The <tt>destroyAllNow</tt> is no longer called by the library on <tt>process.exit</tt> event. If you need to call
|
||
it explicitly yourself, you may use <tt>knex.client.destroyPool</tt>
|
||
</li>
|
||
</ul>
|
||
</p>
|
||
|
||
<h2 id="Initialize">Initialize</h2>
|
||
|
||
<p>
|
||
<tt>Knex.initialize</tt> is the initializing function that must be called prior to using
|
||
Knex, accepting a few parameters. The <tt>client</tt> parameter is required
|
||
and determines which client adapter will be used with the library.
|
||
</p>
|
||
|
||
<pre>
|
||
var knex = Knex.initialize({
|
||
client: 'mysql',
|
||
connection: {
|
||
host : '127.0.0.1',
|
||
user : 'your_database_user',
|
||
password : 'your_database_password',
|
||
database : 'myapp_test',
|
||
charset : 'utf8'
|
||
}
|
||
});
|
||
</pre>
|
||
|
||
<p class="warning">
|
||
An initialize should only ever happen once in your application, as it creates a connection pool
|
||
for the current database, you should use the instance returned from the initialize call throughout
|
||
your library.
|
||
</p>
|
||
|
||
<p>
|
||
You'll need to store this instance created by the <tt>initialize</tt> somewhere in the application
|
||
you can reference it. A common pattern to follow is to set the client as a property on the <tt>Knex</tt>
|
||
library when your application starts, so you can easily reference it later:
|
||
</p>
|
||
|
||
<pre>
|
||
// When the app starts
|
||
var Knex = require('knex');
|
||
Knex.knex = Knex.initialize({
|
||
client: 'pg',
|
||
connection: {
|
||
// your connection config
|
||
}
|
||
});
|
||
|
||
// elsewhere, to use the client:
|
||
var knex = require('knex').knex;
|
||
|
||
knex('table').where('id', 1).select().then(...
|
||
</pre>
|
||
|
||
Note: When you use the SQLite3 adapter, there is a filename required, not a network connection. For example:
|
||
|
||
<pre>
|
||
var knex = Knex.initialize({
|
||
client: 'sqlite3',
|
||
connection: {
|
||
filename: "./mydb.sqlite"
|
||
}
|
||
});
|
||
</pre>
|
||
|
||
|
||
<h2 id="Builder">knex.builder</h2>
|
||
|
||
<p>
|
||
The <tt>knex.builder</tt> is the interface used for building and executing standard SQL queries,
|
||
such as <tt>select</tt>, <tt>insert</tt>, <tt>update</tt>, <tt>delete</tt>. The query is run
|
||
by specifying a <a href="#Builder-table">tableName</a>, adding additional query parameters, and
|
||
executing the query with one of the public interface methods.
|
||
</p>
|
||
|
||
<p id="Builder-main">
|
||
<b class="header">knex</b><code>knex(tableName)...</code>
|
||
<br />
|
||
The <b>Knex</b> query builder starts off by specifying a <b>tableName</b> you wish to query against,
|
||
which returns a chainable interface, similar to a jQuery chain. You can then call any additional
|
||
query builder methods needed to construct the query, eventually calling either
|
||
<a href="#Builder-then">then</a> or <a href="#Builder-exec">exec</a>, to execute the query with a
|
||
promise or a callback, respectively.
|
||
</p>
|
||
|
||
<p id="Builder-select">
|
||
<b class="header">select</b><code>.select([*columns])</code>
|
||
<br />
|
||
Creates a <tt>select</tt> query, taking an optional array of <b>columns</b> for the query, eventually
|
||
defaulting to <tt>*</tt> if none are specified when the query is built. The response of a select call will
|
||
resolve with an array of objects selected from the database.
|
||
</p>
|
||
|
||
<pre>
|
||
// select "title", "author", "year" from "books"
|
||
Knex('books').select('title', 'author', 'year');
|
||
|
||
// select * from "books"
|
||
Knex('books').select();
|
||
</pre>
|
||
|
||
<p id="Builder-column">
|
||
<b class="header">column</b><code>.column(columns)</code>
|
||
<br />
|
||
Specifically set the <b>columns</b> to be selected on a select query, taking an array or a list of of column names.
|
||
</p>
|
||
|
||
<pre>
|
||
// select "title", "author", "year" from "books"
|
||
Knex('books').column('title', 'author', 'year').select();
|
||
|
||
// or:
|
||
Knex('books').column(['title', 'author', 'year']).select();
|
||
</pre>
|
||
|
||
<p id="Builder-from">
|
||
<b class="header">from</b><code>.from([tableName])</code> <span class="alias">Alias: <b>into</b></span>
|
||
<br />
|
||
Specifies the table used in the current query, replacing the current table name if
|
||
one has already been specified. This is typically used in the sub-queries performed
|
||
in the advanced <a href="#Builder-where">where</a> or <a href="#Builder-union">union</a> methods.
|
||
</p>
|
||
|
||
<p id="Builder-where">
|
||
<b class="header">where</b><code>.where(~dynamic~)</code>
|
||
<br />
|
||
There are several helpers for creating dynamic <tt>where</tt> clauses on queries. Take a look at a few
|
||
examples to see how these may be mixed and matched to create fluent constraints on the query.
|
||
</p>
|
||
|
||
<pre>
|
||
|
||
// Basic Uses:
|
||
|
||
// objects
|
||
Knex('users').where({
|
||
first_name: 'Test',
|
||
last_name: 'User'
|
||
}).select('id').then(...
|
||
|
||
// key, value
|
||
Knex('users').where('id', 1).select('first_name', 'last_name').then(...
|
||
|
||
// operators: '=', '<', '>', '<=', '>=', 'like', 'not like', 'between', 'ilike'
|
||
Knex('users').where('votes', '>', 100).exec(function(err, resp) { ... });
|
||
|
||
// chained with "andWhere" / "orWhere"
|
||
Knex('users').where('votes', '>', 100)
|
||
.andWhere('status', 'active')
|
||
.orWhere('name', 'John')
|
||
.then(function(resp) { ... })
|
||
|
||
// Even more where types (see list below):
|
||
|
||
Knex('users').whereBetween('votes', [1, 100]).exec(...
|
||
|
||
Knex('users').whereIn('id', [1, 2, 3]).then(...
|
||
|
||
Knex('users').whereNotIn('id', [1, 2, 3]).then(...
|
||
|
||
Knex('users').whereNull('updated_at').exec(...
|
||
|
||
</pre>
|
||
|
||
<p>
|
||
<b>Grouped Where Clauses:</b>
|
||
</p>
|
||
|
||
<pre>
|
||
// select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
|
||
Knex('users')
|
||
.where('name', '=', 'John')
|
||
.orWhere(function() {
|
||
this.where('votes', '>', 100).andWhere('title', '<>', 'Admin');
|
||
})
|
||
.then(function() {...
|
||
</pre>
|
||
|
||
<p>
|
||
<b>Exists Statements:</b>
|
||
</p>
|
||
|
||
<pre>
|
||
Knex('users')
|
||
.whereExists(function() {
|
||
this.select(Knex.raw(1))
|
||
.from('orders')
|
||
.whereRaw('orders.user_id = users.id');
|
||
})
|
||
.then(...
|
||
</pre>
|
||
|
||
<p>
|
||
Most of the where clauses may also accept a function as the second argument, to generate a sub-select
|
||
on the query:
|
||
</p>
|
||
|
||
<pre>
|
||
|
||
// select author_id, content from comments where author_id in (select id from accounts where type = 'admin')
|
||
Knex('comments').whereIn('author_id', function() {
|
||
|
||
this.select('id').from('accounts').where('type', 'admin');
|
||
|
||
}).select('author_id', 'content').then(...
|
||
</pre>
|
||
|
||
<p>
|
||
These different where clauses may be joined together in any number of ways to make valid SQL statements.
|
||
</p>
|
||
|
||
<ul class="small">
|
||
<li><a href="docs/knex.html#section-56">where</a></li>
|
||
<li><a href="docs/knex.html#section-57">andWhere</a></li>
|
||
<li><a href="docs/knex.html#section-58">orWhere</a></li>
|
||
<li><a href="docs/knex.html#section-59">whereRaw</a></li>
|
||
<li><a href="docs/knex.html#section-60">orWhereRaw</a></li>
|
||
<li><a href="docs/knex.html#section-61">whereExists</a></li>
|
||
<li><a href="docs/knex.html#section-62">orWhereExists</a></li>
|
||
<li><a href="docs/knex.html#section-63">whereNotExists</a></li>
|
||
<li><a href="docs/knex.html#section-64">orWhereNotExists</a></li>
|
||
<li><a href="docs/knex.html#section-65">whereIn</a></li>
|
||
<li><a href="docs/knex.html#section-66">orWhereIn</a></li>
|
||
<li><a href="docs/knex.html#section-67">whereNotIn</a></li>
|
||
<li><a href="docs/knex.html#section-68">orWhereNotIn</a></li>
|
||
<li><a href="docs/knex.html#section-69">whereNull</a></li>
|
||
<li><a href="docs/knex.html#section-70">orWhereNull</a></li>
|
||
<li><a href="docs/knex.html#section-71">whereNotNull</a></li>
|
||
<li><a href="docs/knex.html#section-72">orWhereNotNull</a></li>
|
||
<li><a href="docs/knex.html#section-73">whereBetween</a></li>
|
||
<li><a href="docs/knex.html#section-74">orWhereBetween</a></li>
|
||
</ul>
|
||
</p>
|
||
|
||
<p id="Builder-distinct">
|
||
<b class="header">distinct</b><code>.distinct()</code>
|
||
<br />
|
||
Sets a <tt>distinct</tt> clause on the query.
|
||
</p>
|
||
|
||
<pre>
|
||
// select distinct 'first_name' from customers
|
||
knex('customers')
|
||
.distinct('first_name', 'last_name')
|
||
.select()
|
||
</pre>
|
||
|
||
<p id="Builder-join">
|
||
<b class="header">join</b><code>.join(table, first, operator, second, [type])</code>
|
||
<br />
|
||
The <tt>join</tt> builder can be used to specify joins between tables,
|
||
with the first argument being the joining <b>table</b>, the next three arguments
|
||
being the <b>first</b> join column, the join <b>operator</b> and the <b>second</b>
|
||
join column, respectively. The last argument is optional and spefies the type of join.
|
||
</p>
|
||
|
||
<pre>
|
||
knex('users')
|
||
.join('contacts', 'users.id', '=', 'contacts.user_id')
|
||
.join('orders', 'users.id', '=', 'orders.user_id', 'outer')
|
||
.select('users.id', 'contacts.phone', 'orders.price')
|
||
.then(function() { ... });
|
||
</pre>
|
||
|
||
<p>
|
||
For grouped joins, specify a function as the second argument for the
|
||
join query, and use <tt>on</tt> and <tt>orOn</tt> to create joins that are
|
||
grouped with parentheses.
|
||
</p>
|
||
|
||
<pre>
|
||
knex('users')
|
||
.join('contacts', function() {
|
||
this.on('users.id', '=', 'contacts.user_id').orOn(...);
|
||
})
|
||
.exec(function(err, resp) { ... });
|
||
</pre>
|
||
|
||
</p>
|
||
|
||
<p id="Builder-groupBy">
|
||
<b class="header">groupBy</b><code>.groupBy(*names)</code>
|
||
<br />
|
||
Adds a <tt>group by</tt> clause to the query.
|
||
</p>
|
||
|
||
<p id="Builder-orderBy">
|
||
<b class="header">orderBy</b><code>.orderBy(column, [direction])</code>
|
||
<br />
|
||
Adds an <tt>order by</tt> clause to the query.
|
||
</p>
|
||
|
||
<p id="Builder-having">
|
||
<b class="header">having</b><code>.having(column, operator, value)</code>
|
||
<br />
|
||
Adds a <tt>having</tt> clause to the query.
|
||
|
||
<pre>
|
||
knex('users')
|
||
.groupBy('count')
|
||
.orderBy('name', 'desc')
|
||
.having('count', '>', 100)
|
||
.select()
|
||
|
||
</pre>
|
||
</p>
|
||
|
||
<p id="Builder-offset">
|
||
<b class="header">offset</b><code>.offset(value)</code>
|
||
<br />
|
||
Adds an <tt>offset</tt> clause to the query.
|
||
</p>
|
||
|
||
<p id="Builder-limit">
|
||
<b class="header">limit</b><code>.limit(value)</code>
|
||
<br />
|
||
Adds a <tt>limit</tt> clause to the query.
|
||
</p>
|
||
|
||
<pre>
|
||
knex('users')
|
||
.limit(10)
|
||
.offset(30)
|
||
.select()
|
||
</pre>
|
||
|
||
<p id="Builder-union">
|
||
<b class="header">union</b><code>.union(query)</code>
|
||
<br />
|
||
Creates a <tt>union</tt> query, taking a callback to build the union statement.
|
||
</p>
|
||
|
||
<p id="Builder-unionAll">
|
||
<b class="header">unionAll</b><code>.unionAll(query)</code>
|
||
<br />
|
||
Creates a <tt>union all</tt> query, with the same method signature as
|
||
the <a href="#Builder-union">union</a> method.
|
||
</p>
|
||
|
||
<pre>
|
||
knex('users').whereNull('last_name').union(function() {
|
||
|
||
this.select('*').from('users').whereNull('first_name');
|
||
|
||
}).select().then(function() { ... });
|
||
</pre>
|
||
|
||
<p id="Builder-insert">
|
||
<b class="header">insert</b><code>.insert(data, [returning])</code>
|
||
<br />
|
||
Creates an <tt>insert</tt> query, taking either a hash of properties to be inserted into the row, or
|
||
an array of inserts, to be executed as a single insert command. Resolves the promise / fulfills the callback
|
||
with an array containing the first insert id of the inserted model, or an array containing all inserted <tt>ids</tt>
|
||
for postgresql.
|
||
</p>
|
||
|
||
<pre>
|
||
// Returns [1] in "mysql", "sqlite"; [] in "postgresql" unless the 'returning' parameter is set.
|
||
knex('books').insert({title: 'Slaughterhouse Five'})
|
||
|
||
// Returns [2] in "mysql", "sqlite"; [2, 3] in "postgresql"
|
||
knex('books')
|
||
.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], 'id')
|
||
</pre>
|
||
|
||
<p id="Builder-returning">
|
||
<b class="header">returning</b><code>.returning(column)</code>
|
||
<br />
|
||
Only utilitzed by PostgreSQL databases, the returning method specifies which column should be returned
|
||
by the <a href="#Builder-insert">insert</a> method.
|
||
</p>
|
||
|
||
<pre>
|
||
// Returns [1]
|
||
knex('books')
|
||
.returning('id')
|
||
.insert({title: 'Slaughterhouse Five'})
|
||
|
||
// Returns [2] in "mysql", "sqlite"; [2, 3] in "postgresql"
|
||
knex('books')
|
||
.returning('id')
|
||
.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}])
|
||
</pre>
|
||
|
||
<p id="Builder-update">
|
||
<b class="header">update</b><code>.update(data) / .update(key, value)</code>
|
||
<br />
|
||
Creates an <tt>update</tt> query, taking either a single property / value, or a hash of properties
|
||
to be updated based on the other query constraints. Resolves the promise / fulfills the
|
||
callback with the number of affected rows for the query.
|
||
</p>
|
||
|
||
<pre>
|
||
knex('books')
|
||
.where('published_date', '<', 2000)
|
||
.update({
|
||
status: 'archived'
|
||
})
|
||
.then(...
|
||
</pre>
|
||
|
||
<p id="Builder-del">
|
||
<b class="header">del / delete</b><code>.del()</code>
|
||
<br />
|
||
Aliased to <tt>del</tt> as <tt>delete</tt> is a reserved word in javascript, this method deletes
|
||
one or more rows, based on other conditions specified in the query. Resolves the promise / fulfills the
|
||
callback with the number of affected rows for the query.
|
||
</p>
|
||
|
||
<pre>
|
||
knex('accounts')
|
||
.where('activated', false)
|
||
.del()
|
||
</pre>
|
||
|
||
<p id="Builder-transacting">
|
||
<b class="header">transacting</b><code>.transacting(transactionObj)</code>
|
||
<br />
|
||
Used by <a href="#Transaction">knex.transaction</a>, the transacting method may be chained to any
|
||
query and passed the object you wish to join the query as part of the transaction for.
|
||
</p>
|
||
|
||
<pre>
|
||
var Promise = require('bluebird');
|
||
|
||
knex.transaction(function(t) {
|
||
|
||
knex('books')
|
||
.transacting(t)
|
||
.insert({name: 'Old Books'})
|
||
.then(function(row) {
|
||
|
||
return Promise.all(_.map([
|
||
{title: 'Canterbury Tales'},
|
||
{title: 'Moby Dick'},
|
||
{title: 'Hamlet'}
|
||
], function(info) {
|
||
|
||
info.row_id = row.id;
|
||
|
||
// Some validation could take place here.
|
||
return knex('book').transacting(t).insert(info);
|
||
|
||
}));
|
||
})
|
||
.then(function() {
|
||
t.commit('You saved 3 books');
|
||
}, t.rollback);
|
||
|
||
}).then(function(resp) {
|
||
console.log(resp);
|
||
}, function(err) {
|
||
console.log(err.message);
|
||
});
|
||
</pre>
|
||
|
||
<p id="Builder-forUpdate">
|
||
<b class="header">forUpdate</b><code>.transacting(t).forUpdate()</code>
|
||
<br />
|
||
Dynamically added after a <a href="#Builder-transacting">transaction</a> is specified,
|
||
the <tt>forUpdate</tt> adds a <tt>FOR UPDATE</tt> in PostgreSQL and MySQL during a select statement.
|
||
</p>
|
||
|
||
<p id="Builder-forShare">
|
||
<b class="header">forShare</b><code>.transacting(t).forShare()</code>
|
||
<br />
|
||
Dynamically added after a <a href="#Builder-transacting">transaction</a> is specified,
|
||
the <tt>forShare</tt> adds a <tt>FOR SHARE</tt> in PostgreSQL and a <tt>LOCK IN SHARE MODE</tt>
|
||
for MySQL during a select statement.
|
||
</p>
|
||
|
||
<p id="Builder-count">
|
||
<b class="header">count</b><code>.count(column)</code>
|
||
<br />
|
||
Performs a count on the specified <b>column</b>.
|
||
</p>
|
||
|
||
<p id="Builder-min">
|
||
<b class="header">min</b><code>.min(column)</code>
|
||
<br />
|
||
Gets the minimum value for the specified <b>column</b>.
|
||
</p>
|
||
|
||
<p id="Builder-max">
|
||
<b class="header">max</b><code>.max(column)</code>
|
||
<br />
|
||
Gets the maximum value for the specified <b>column</b>.
|
||
</p>
|
||
|
||
<p id="Builder-sum">
|
||
<b class="header">sum</b><code>.sum(column)</code>
|
||
<br />
|
||
Retrieve the sum of the values of a given <b>column</b>.
|
||
</p>
|
||
|
||
<p id="Builder-increment">
|
||
<b class="header">increment</b><code>.increment(column, amount)</code>
|
||
<br />
|
||
Increments a <b>column</b> value by the specified <b>amount</b>.
|
||
</p>
|
||
|
||
<p id="Builder-decrement">
|
||
<b class="header">decrement</b><code>.decrement(column, amount)</code>
|
||
<br />
|
||
Decrements a <b>column</b> value by the specified <b>amount</b>.
|
||
</p>
|
||
|
||
<p id="Builder-truncate">
|
||
<b class="header">truncate</b><code>.truncate()</code>
|
||
<br />
|
||
Truncates the current table.
|
||
</p>
|
||
|
||
<p id="Builder-debug">
|
||
<b class="header">debug</b><code>.debug()</code>
|
||
<br />
|
||
Turns on debugging for the current query chain.
|
||
</p>
|
||
|
||
<p id="Builder-options">
|
||
<b class="header">options</b><code>.options()</code>
|
||
<br />
|
||
Allows for mixing in additional options as defined by database client specific libraries:
|
||
</p>
|
||
|
||
<pre>
|
||
knex('accounts as a1')
|
||
.join('accounts as a2', function() {
|
||
this.on('a1.email', '<>', 'a2.email');
|
||
}, 'left')
|
||
.select(['a1.email', 'a2.email'])
|
||
.where(Knex.Raw('a1.id = 1'))
|
||
.option({ nestTables: true, rowMode: 'array' })
|
||
.limit(2);
|
||
</pre>
|
||
|
||
<h3 id="Builder-Interface">Builder Interface Methods:</h3>
|
||
|
||
<p id="Builder-then">
|
||
<b class="header">then</b><code>.then(onFulfilled, onRejected)</code>
|
||
<br />
|
||
Coerces the current query builder chain into a promise state, accepting the resolve
|
||
and reject handlers as specified by the <a href="http://promises-aplus.github.com/promises-spec">Promises/A+ spec</a>.
|
||
As stated in the spec, more than one call to the <tt>then</tt> method for the current query chain will resolve
|
||
with the same value, in the order they were called; the query will not be executed multiple times.
|
||
</p>
|
||
|
||
<p id="Builder-exec">
|
||
<b class="header">exec</b><code>.exec(callback)</code>
|
||
<br />
|
||
If you'd prefer a callback interface over promises, the <b>exec</b> function
|
||
accepts a standard node style callback for executing the query chain. Note that as
|
||
with the <a href="#Builder-then">then</a> method, subsequent calls to the same
|
||
query chain will return the same result.
|
||
</p>
|
||
|
||
<p id="Builder-tap">
|
||
<b class="header">tap</b><code>.tap(onFulfilled, onRejected)</code>
|
||
<br />
|
||
Similar to the <a href="https://github.com/cujojs/when/blob/master/docs/api.md#tap">tap</a> functionality in when.js,
|
||
this will execute side effects on the resolved response, ultimately returning a promise that fulfills with the original
|
||
value. A thrown error or rejected promise will cause the promise to transition into a rejected state.
|
||
</p>
|
||
<pre>
|
||
// Using only .then()
|
||
query.then(function(x) {
|
||
doSideEffectsHere(x);
|
||
return x;
|
||
});
|
||
|
||
// Using .tap()
|
||
promise.tap(doSideEffectsHere);
|
||
</pre>
|
||
|
||
<p id="Builder-toString">
|
||
<b class="header">toString</b><code>.toString()</code>
|
||
<br />
|
||
Returns an array of query strings filled out with the
|
||
correct values based on bindings, etc. Useful for debugging.
|
||
</p>
|
||
|
||
<h2 id="Transaction">knex.transaction</h2>
|
||
|
||
<p>
|
||
Transactions are handled by passing a handler function into <tt>knex.transaction</tt>.
|
||
The handler function accepts a single argument, the promise for committing or rolling back
|
||
the transaction. This argument is then passed into any queries which are involved in the current
|
||
transcaction, working by explicitly passing the .
|
||
</p>
|
||
|
||
<pre>
|
||
var Promise = require('bluebird');
|
||
|
||
knex.transaction(function(t) {
|
||
|
||
knex('books')
|
||
.transacting(t)
|
||
.insert({name: 'Old Books'})
|
||
.then(function(row) {
|
||
|
||
return Promise.all(_.map([
|
||
{title: 'Canterbury Tales'},
|
||
{title: 'Moby Dick'},
|
||
{title: 'Hamlet'}
|
||
], function(info) {
|
||
|
||
info.row_id = row.id;
|
||
|
||
// Some validation could take place here.
|
||
return knex('book').transacting(t).insert(info);
|
||
|
||
}));
|
||
})
|
||
.then(t.commit, t.rollback);
|
||
|
||
}).then(function() {
|
||
console.log('3 new books saved.');
|
||
}, function() {
|
||
console.log('Error saving the books.');
|
||
});
|
||
</pre>
|
||
|
||
<h2 id="Schema">knex.schema</h2>
|
||
|
||
<p id="Schema-createTable">
|
||
<b class="header">createTable</b><code>knex.schema.createTable(tableName, callback)</code>
|
||
<br />
|
||
Creates a new table on the database, with a callback function to modify the table's
|
||
structure, using the <a href="#Schema-Building">schema-building</a> commands.
|
||
</p>
|
||
|
||
<pre>
|
||
knex.schema.createTable('users', function (table) {
|
||
table.string('name');
|
||
table.timestamps();
|
||
}).then(function () {
|
||
console.log('Users Table is Created!');
|
||
});
|
||
</pre>
|
||
|
||
<p id="Schema-renameTable">
|
||
<b class="header">renameTable</b><code>knex.schema.renameTable(from, to)</code>
|
||
<br />
|
||
Renames a table <b>from</b> a current tableName <b>to</b> another.
|
||
</p>
|
||
|
||
<p id="Schema-dropTable">
|
||
<b class="header">dropTable</b><code>knex.schema.dropTable(tableName)</code>
|
||
<br />
|
||
Drops a table, specified by <b>tableName</b>.
|
||
</p>
|
||
|
||
<p id="Schema-hasTable">
|
||
<b class="header">hasTable</b><code>knex.schema.hasTable(tableName)</code>
|
||
<br />
|
||
Checks for a table's existence by <b>tableName</b>, resolving with a boolean to
|
||
signal if the table exists.
|
||
</p>
|
||
|
||
<pre>
|
||
knex.schema.hasTable('users').then(function(exists) {
|
||
if (!exists) {
|
||
return knex.schema.createTable('users', function(t) {
|
||
t.increments('id').primary();
|
||
t.string('first_name', 100);
|
||
t.string('last_name', 100);
|
||
t.text('bio');
|
||
});
|
||
}
|
||
});
|
||
</pre>
|
||
|
||
<p id="Schema-hasColumn">
|
||
<b class="header">hasColumn</b><code>knex.schema.hasColumn(tableName, columnName)</code>
|
||
<br />
|
||
Checks if a column exists in the current table, resolves the promise with a boolean, <tt>true</tt>
|
||
if the column exists, <tt>false</tt> otherwise.
|
||
</p>
|
||
|
||
<p id="Schema-dropTableIfExists">
|
||
<b class="header">dropTableIfExists</b><code>knex.schema.dropTableIfExists(tableName)</code>
|
||
<br />
|
||
Drops a table conditionally if the table exists, specified by <tt>tableName</tt>.
|
||
</p>
|
||
|
||
<p id="Schema-table">
|
||
<b class="header">table</b><code>knex.schema.table(tableName, callback)</code>
|
||
<br />
|
||
Chooses a database table, and then modifies the table, using the <a href="#Schema-Building">Schema Building</a>
|
||
functions inside of the callback.
|
||
</p>
|
||
|
||
<pre>
|
||
knex.schema.table('users', function (table) {
|
||
table.dropColumn('name');
|
||
table.string('first_name');
|
||
table.string('last_name');
|
||
}).then(function () {
|
||
console.log('Users Table is Updated!');
|
||
});
|
||
</pre>
|
||
|
||
<p id="Schema-dropTableIfExists">
|
||
<b class="header">dropTableIfExists</b><code>knex.schema.dropTableIfExists(tableName)</code>
|
||
<br />
|
||
Drops a table conditionally if the table exists, specified by <tt>tableName</tt>.
|
||
</p>
|
||
|
||
<h3 id="Schema-Building">Schema Building:</h3>
|
||
|
||
<p id="Schema-dropColumn">
|
||
<b class="header">dropColumn</b><code>table.dropColumn(name)</code>
|
||
<br />
|
||
Drops a column, specified by the column's <b>name</b>
|
||
</p>
|
||
|
||
<p id="Schema-dropColumns">
|
||
<b class="header">dropColumns</b><code>table.dropColumns(*columns)</code>
|
||
<br />
|
||
Drops multiple <b>columns</b>, taking a variable number of column names.
|
||
</p>
|
||
|
||
<p id="Schema-renameColumn">
|
||
<b class="header">renameColumn</b><code>table.renameColumn(from, to)</code>
|
||
<br />
|
||
Renames a column <b>from</b> one name <b>to</b> another.
|
||
</p>
|
||
|
||
<p id="Schema-increments">
|
||
<b class="header">increments</b><code>table.increments(name)</code>
|
||
<br />
|
||
Adds an auto incrementing column, in PostgreSQL this is a <tt>serial</tt>. This will be used as the primary key for the column. Also available is a <tt>bigIncrements</tt> if you wish to add a bigint incrementing number (in PostgreSQL <tt>bigserial</tt>).
|
||
</p>
|
||
|
||
<p id="Schema-integer">
|
||
<b class="header">integer</b><code>table.integer(name)</code>
|
||
<br />
|
||
Adds an integer column.
|
||
</p>
|
||
|
||
<p id="Schema-bigInteger">
|
||
<b class="header">integer</b><code>table.integer(name)</code>
|
||
<br />
|
||
In MySQL or PostgreSQL, adds a <tt>bigint</tt> column,
|
||
otherwise adds a normal integer.
|
||
</p>
|
||
|
||
<p id="Schema-text">
|
||
<b class="header">text</b><code>table.text(name, [textType])</code>
|
||
<br />
|
||
Adds a text column, with optional textType for MySql text datatype preference.
|
||
<br />
|
||
textType may be <tt>mediumtext</tt> or <tt>longtext</tt>, otherwise defaults to text.
|
||
</p>
|
||
|
||
<p id="Schema-string">
|
||
<b class="header">string</b><code>table.string(name, [length])</code>
|
||
<br />
|
||
Adds a string column, with optional length defaulting to 255.
|
||
</p>
|
||
|
||
<p id="Schema-float">
|
||
<b class="header">float</b><code>table.float(column, [precision], [scale])</code>
|
||
<br />
|
||
Adds a float column, with optional precision and scale.
|
||
</p>
|
||
|
||
<p id="Schema-decimal">
|
||
<b class="header">decimal</b><code>table.decimal(column, [precision], [scale])</code>
|
||
<br />
|
||
Adds a decimal column, with optional precision and scale.
|
||
</p>
|
||
|
||
<p id="Schema-boolean">
|
||
<b class="header">boolean</b><code>table.boolean(name)</code>
|
||
<br />
|
||
Adds a boolean column.
|
||
</p>
|
||
|
||
<p id="Schema-date">
|
||
<b class="header">date</b><code>table.date(name)</code>
|
||
<br />
|
||
Adds a date column.
|
||
</p>
|
||
|
||
<p id="Schema-dateTime">
|
||
<b class="header">dateTime</b><code>table.dateTime(name)</code>
|
||
<br />
|
||
Adds a dateTime column.
|
||
</p>
|
||
|
||
<p id="Schema-time">
|
||
<b class="header">time</b><code>table.time(name)</code>
|
||
<br />
|
||
Adds a time column.
|
||
</p>
|
||
|
||
<p id="Schema-timestamp">
|
||
<b class="header">timestamp</b><code>table.timestamp(name)</code>
|
||
<br />
|
||
Adds a timestamp column.
|
||
</p>
|
||
|
||
<p id="Schema-timestamps">
|
||
<b class="header">timestamps</b><code>table.timestamps()</code>
|
||
<br />
|
||
Adds a <tt>created_at</tt> and <tt>updated_at</tt> column on the database,
|
||
setting these each to <a href="#Schema-dateTime">dateTime</a> types.
|
||
</p>
|
||
|
||
<p id="Schema-binary">
|
||
<b class="header">binary</b><code>table.binary(name)</code>
|
||
<br />
|
||
Adds a binary column.
|
||
</p>
|
||
|
||
<p id="Schema-enum">
|
||
<b class="header">enum / enu</b><code>table.enu(col, values)</code>
|
||
<br />
|
||
Adds a enum column, (aliased to <tt>enu</tt>, as enum is a reserved word in javascript).
|
||
</p>
|
||
|
||
<p id="Schema-json">
|
||
<b class="header">json</b><code>table.json(name)</code>
|
||
<br />
|
||
Adds a json column, using the built-in json type in postgresql, defaulting to a text column
|
||
in older versions of postgresql or in unsupported databases.
|
||
</p>
|
||
|
||
<p id="Schema-uuid">
|
||
<b class="header">uuid</b><code>table.uuid(name)</code>
|
||
<br />
|
||
Adds a uuid column - this uses the built-in uuid type in postgresql, and falling back to a
|
||
<tt>char(36)</tt> in other databases.
|
||
</p>
|
||
|
||
<p id="Schema-comment">
|
||
<b class="header">comment</b><code>table.comment(value)</code>
|
||
<br />
|
||
Sets the comment for a table.
|
||
</p>
|
||
|
||
<p id="Schema-engine">
|
||
<b class="header">engine</b><code>table.engine(val)</code>
|
||
<br />
|
||
Sets the engine for the database table, only available within a <tt>createTable</tt> call, and only
|
||
applicable to MySQL.
|
||
</p>
|
||
|
||
<p id="Schema-charset">
|
||
<b class="header">charset</b><code>table.charset(val)</code>
|
||
<br />
|
||
Sets the charset for the database table, only available within a <tt>createTable</tt> call, and only
|
||
applicable to MySQL.
|
||
</p>
|
||
|
||
<p id="Schema-collate">
|
||
<b class="header">collate</b><code>table.collate(val)</code>
|
||
<br />
|
||
Sets the collation for the database table, only available within a <tt>createTable</tt> call, and only
|
||
applicable to MySQL.
|
||
</p>
|
||
|
||
<p id="Schema-specificType">
|
||
<b class="header">specificType</b><code>table.specificType(column, value)</code>
|
||
<br />
|
||
Sets a specific type for the column creation, if you'd like to add a column type that isn't supported here.
|
||
</p>
|
||
|
||
<h3 id="Chainable">Chainable Methods:</h3>
|
||
|
||
<p>
|
||
The following three methods may be chained on the schema building methods, as modifiers to the column.
|
||
</p>
|
||
|
||
<p id="Chainable-index">
|
||
<b class="header">index</b><code>column.index()</code>
|
||
<br />
|
||
Specifies an field as an index. No-op if this is chained off of a field that cannot be indexed.
|
||
</p>
|
||
|
||
<p id="Chainable-primary">
|
||
<b class="header">primary</b><code>column.primary()</code>
|
||
<br />
|
||
Sets the field as the primary key for the table.
|
||
</p>
|
||
|
||
<p id="Chainable-unique">
|
||
<b class="header">unique</b><code>column.unique()</code>
|
||
<br />
|
||
Sets the column as unique.
|
||
</p>
|
||
|
||
<p id="Chainable-defaultTo">
|
||
<b class="header">defaultTo</b><code>column.defaultTo(value)</code>
|
||
<br />
|
||
Sets the default value for the column on an insert.
|
||
</p>
|
||
|
||
<p id="Chainable-unsigned">
|
||
<b class="header">unsigned</b><code>column.unsigned()</code>
|
||
<br />
|
||
Specifies an integer as unsigned. No-op if this is chained off of a non-integer field.
|
||
</p>
|
||
|
||
<p id="Chainable-notNullable">
|
||
<b class="header">notNullable</b><code>column.notNullable()</code>
|
||
<br />
|
||
Adds a <tt>not null</tt> on the current column being created.
|
||
</p>
|
||
|
||
<p id="Chainable-nullable">
|
||
<b class="header">nullable</b><code>column.nullable()</code>
|
||
<br />
|
||
Default on column creation, this explicitly sets a field to be nullable.
|
||
</p>
|
||
|
||
<p id="Chainable-after">
|
||
<b class="header">after</b><code>column.after(field)</code>
|
||
<br />
|
||
Sets the column to be inserted after another, only used in MySQL alter tables.
|
||
</p>
|
||
|
||
<p id="Chainable-comment">
|
||
<b class="header">comment</b><code>column.comment(value)</code>
|
||
<br />
|
||
Sets the comment for a column.
|
||
</p>
|
||
|
||
<pre>
|
||
knex.schema.createTable('accounts', function() {
|
||
t.increments().primary();
|
||
t.string('email').unique();
|
||
});
|
||
</pre>
|
||
|
||
<h2 id="Raw">knex.raw</h2>
|
||
|
||
<h3 id="Raw-Expressions">Raw Expressions:</h3>
|
||
|
||
<p>
|
||
Sometimes you may need to use a raw expression in a query. These expressions will be injected
|
||
into the query as strings, so be careful not to create any SQL injection points!
|
||
To create a raw expression, you may use the <tt>knex.raw</tt> function.
|
||
</p>
|
||
|
||
<pre>
|
||
knex('users')
|
||
.select(knex.raw('count(*) as user_count, status'))
|
||
.where('status', '<>', 1)
|
||
.groupBy('status')
|
||
.then(...
|
||
</pre>
|
||
|
||
<h3 id="Raw-Queries">Raw Queries:</h3>
|
||
|
||
<p>
|
||
The <tt>knex.raw</tt> may also be used to build a full query and execute it, as a
|
||
standard query builder query would be executed. The benefit of this is that it uses the connection
|
||
pool and provides a standard interface for the different client libraries.
|
||
Note that the response will be whatever the underlying sql library would typically return on a
|
||
normal query, so you may need to look at the documentation for the base library the queries are
|
||
executing against to determine how to handle the response.
|
||
</p>
|
||
|
||
<pre>
|
||
knex.raw('select * from users where id = 1').then(function(resp) {
|
||
...
|
||
});
|
||
</pre>
|
||
|
||
<h2 id="Migrate">knex.migrate</h2>
|
||
|
||
<p>
|
||
<tt>knex.migrate</tt> is the class utilized by the knex migrations cli. Each method
|
||
takes an optional <tt>config</tt> object, which may specify specifies the <tt>database</tt>,
|
||
<tt>directory</tt>, and <tt>tableName</tt> for the migrations. Check <a href="https://github.com/tgriesser/knex/blob/master/bin/readme.md">here</a> for more information about the migration CLI tool.
|
||
</p>
|
||
|
||
<p id="Migrate-make">
|
||
<b class="header">make</b><code>knex.migrate.make(name, [config])</code>
|
||
<br />
|
||
Creates a new migration, with the <b>name</b> of the migration being added.
|
||
</p>
|
||
|
||
<p id="Migrate-latest">
|
||
<b class="header">latest</b><code>knex.migrate.latest([config])</code>
|
||
<br />
|
||
Runs all migrations that have not yet been run.
|
||
</p>
|
||
|
||
<p id="Migrate-rollback">
|
||
<b class="header">rollback</b><code>knex.migrate.rollback([config])</code>
|
||
<br />
|
||
Rolls back the latest migration group.
|
||
</p>
|
||
|
||
<p id="Migrate-currentVersion">
|
||
<b class="header">currentVersion</b><code>knex.migrate.currentVersion()</code>
|
||
<br />
|
||
Retrieves and returns the current migration version, as a promise.
|
||
If there aren't any migrations run yet, returns "none" as the value for the currentVersion.
|
||
</p>
|
||
|
||
<h2 id="faq">F.A.Q.</h2>
|
||
|
||
<p id="faq-contribute">
|
||
<b class="header">How do I help contribute?</b><br />
|
||
Glad you ask! Pull requests, or feature requests, though not always implemented, are a great way
|
||
to help make Knex even better than it is now. If you're looking for something specific to help out with,
|
||
there's a number of unit tests that aren't implemented yet, the library could never have too many of those.
|
||
If you want to submit a fix or feature, take a look at the <a href="https://github.com/tgriesser/knex/blob/master/CONTRIBUTING.md">
|
||
Contributing</a> readme in the Github and go ahead and open a ticket.
|
||
</p>
|
||
|
||
<p id="faq-debug">
|
||
<b class="header">How do I debug?</b><br />
|
||
If you pass <tt>{debug: true}</tt> as one of the options in your initialize settings, you can see all of the query calls being made. Sometimes you need to dive a bit further into
|
||
the various calls and see what all is going on behind the scenes. I'd recommend
|
||
<a href="https://github.com/dannycoates/node-inspector">node-inspector</a>, which allows you to debug code with <tt>debugger</tt> statements like you would in the browser.
|
||
</p>
|
||
|
||
<p>
|
||
Knex uses it's own copy of the "bluebird" promise library, you can read up <a href="https://github.com/petkaantonov/bluebird#error-handling">here</a> for more on debugging these promises... but in short, adding:
|
||
</p>
|
||
|
||
<pre>
|
||
process.stderr.on('data', function() {
|
||
console.log(arguments);
|
||
});
|
||
</pre>
|
||
|
||
<p>At the start of your application code will catch any errors not otherwise caught in the normal promise chain handlers, which is very helpful in debugging.
|
||
</p>
|
||
|
||
<p id="faq-tests">
|
||
<b class="header">How do I run the test suite?</b><br />
|
||
The test suite looks for an environment variable called <tt>KNEX_TEST</tt> for the path to the database
|
||
configuration. If you run the following command:
|
||
<tt>$ export KNEX_TEST='/path/to/your/knex_config.js'</tt>, replacing with the path to your config file, and the config file is valid, the test suite should run with <tt>npm test</tt>. If you're going to add a test, you may want to follow similar patterns, used in the test suite,
|
||
setting <tt>$ export KNEX_DEV=1</tt> to save the outputs data from the tests into the <tt>shared/output.js</tt> file.
|
||
</p>
|
||
|
||
<p id="faq-nonode">
|
||
<b class="header">Can I use Knex outside of Node.js</b><br />
|
||
While there isn't a client adapter yet, it should be possible to run
|
||
it could be adapted to work with other javascript environments supporting a <tt>sqlite3</tt>
|
||
database, by providing a custom <a href="http://knexjs.org/#Adapters">Knex adapter</a>.
|
||
</p>
|
||
|
||
<h2 id="changelog">Change Log</h2>
|
||
|
||
<p>
|
||
<b class="header">0.5.0</b> — <small><i>Nov 25, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.13...0.5.0">Diff</a><br />
|
||
<ul>
|
||
<li>Initial pass at a <a href="#Migrate">migration</a> api.</li>
|
||
<li>Aggregate methods are no longer aliased as "aggregate",
|
||
but may now be aliased and have more than one aggregate in a query (#108, #110).</li>
|
||
<li>Adding bigint and bigserial to PostgreSQL (#111).</li>
|
||
<li>Bugfix on increment/decrement values (#100).</li>
|
||
<li>Bugfix with having method (#107).</li>
|
||
<li>Switched from when.js to <a href="https://github.com/petkaantonov/bluebird">bluebird</a> for promise implementation, with shim for backward compatibility.</li>
|
||
<li>Switched from underscore to lodash, for semver reliability.</li>
|
||
</ul>
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.13</b> — <small><i>Oct 31, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.12...0.4.13">Diff</a><br />
|
||
Fix for aggregate methods on <tt>toString</tt> and <tt>clone</tt>, (#98).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.12</b> — <small><i>Oct 29, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.11...0.4.12">Diff</a><br />
|
||
Fix incorrect values passed to <tt>float</tt> in MySQL and <tt>decimal</tt>
|
||
in PostgreSQL.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.11</b> — <small><i>Oct 15, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.10...0.4.11">Diff</a><br />
|
||
Fix potential sql injection vulnerability in <tt>orderBy</tt>, thanks to @sebgie.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.10</b> — <small><i>Oct 14, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.9...0.4.10">Diff</a><br />
|
||
<ul>
|
||
<li>Added <a href="#Builder-forUpdate">forUpdate</a> and <a href="#Builder-forShare">forShare</a> for select modes in transactions. (#84)</li>
|
||
<li>Fix bug where current query chain type is not copied on <a href="#Builder-clone">clone</a>. (#90)</li>
|
||
<li>Charset and collate are now added as methods on the schema builder. (#89)</li>
|
||
<li>Added <tt>into</tt> as an alias of <a href="#Builder-from">from</a>, for builder syntax of: <tt>insert(value).into(tableName)</tt></li>
|
||
<li>Internal pool fixes. (#90)</li>
|
||
</ul>
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.9</b> — <small><i>Oct 7, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.8...0.4.9">Diff</a><br />
|
||
<ul>
|
||
<li>Fix for documentation of <a href="#Schema-hasColumn">hasColumn</a>, ensure that <tt>hasColumn</tt> works with MySQL (#87).</li>
|
||
<li>More cleanup of error messages, showing the original error message concatenated with the sql and bindings.</li>
|
||
</ul>
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.8</b> — <small><i>Oct 2, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.7...0.4.8">Diff</a><br />
|
||
Connections are no longer pushed back into the pool if they never existed to begin with (#85).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.7</b> — <small><i>Sep 27, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.6...0.4.7">Diff</a><br />
|
||
The <a href="#Builder-column">column</a> is now a documented method on the builder api, and takes either an individual column or an array of columns to select.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.6</b> — <small><i>Sep 25, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.5...0.4.6">Diff</a><br />
|
||
Standardizing handling of errors for easier debugging, as noted in (#39).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.5</b> — <small><i>Sep 24, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.4...0.4.5">Diff</a><br />
|
||
Fix for <tt>hasTable</tt> always returning true in MySQL (#82), fix where sql queries were duplicated with multiple calls on <tt>toSql</tt> with the
|
||
schema builder.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.4</b> — <small><i>Sep 22, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.3...0.4.4">Diff</a><br />
|
||
Fix for <tt>debug</tt> method not properly debugging individual queries.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.3</b> — <small><i>Sep 18, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.2...0.4.3">Diff</a><br />
|
||
Fix for underscore not being defined in various grammar files.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.2</b> — <small><i>Sep 17, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.1...0.4.2">Diff</a><br />
|
||
Fix for an error being thrown when an initialized <tt>ClientBase</tt> instance was passed into <tt>Knex.initialize</tt>. <tt>pool.destroy</tt> now optionally accepts a callback to notify when it has completed draining and destroying all connections.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.1</b> — <small><i>Sep 16, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.4.0...0.4.1">Diff</a><br />
|
||
Cleanup from the 0.4.0 release, fix a potential exploit in "where" clauses pointed out by <a href="http://themoll.com">Andri Möll</a>, fix for clients
|
||
not being properly released from the pool #70, fix for <tt>where("foo", "<>", null)</tt> doing an "IS NULL" statement.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.4.0</b> — <small><i>Sep 13, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.2.6...0.4.0">Diff</a> — <a href="http://htmlpreview.github.com/?https://raw.github.com/tgriesser/knex/0.4.0/index.html">Docs</a><br />
|
||
<b>Breaking Changes:</b>
|
||
<ul>
|
||
<li>
|
||
Global state is no longer stored in the library, an instance is returned from <tt>Knex.initialize</tt>,
|
||
so you will need to call this once and then reference this <tt>knex</tt> client elsewhere in your application.
|
||
</li>
|
||
<li>
|
||
Lowercasing of <tt>knex.raw</tt>, <tt>knex.transaction</tt>, and <tt>knex.schema</tt>.
|
||
</li>
|
||
<li>
|
||
Created columns are now nullable by default, unless <tt>notNullable</tt> is chained as an option.
|
||
</li>
|
||
<li>
|
||
Keys created with <tt>increments</tt> are now assumed to be unsigned (MySQL) by default.
|
||
</li>
|
||
<li>
|
||
The <tt>destroyAllNow</tt> is no longer called by the library on <tt>process.exit</tt> event. If you need to call
|
||
it explicitly yourself, you may use <tt>knex.client.destroyPool</tt>
|
||
</li>
|
||
</ul>
|
||
Schema: Added <a href="#Schema-hasColumn">hasColumn</a>, <a href="#Schema-renameColumn">renameColumn</a>, <a href="Schema-bigInteger">bigInteger</a>,
|
||
<a href="Schema-specificType">specificType</a>.
|
||
General: Refactoring the library to support UMD and eventual use on the client. Added <a href="#Builder-options">options</a> method for adding additional
|
||
parameters specific to individual database libraries, #64.
|
||
Bugfixes: Case insensitive where operators (e.g.) <tt>LIKE, BETWEEN, NOT LIKE</tt> are now supported.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.2.6</b> — <small><i>Aug 29, 2013</i></small> — <a href="https://github.com/tgriesser/knex/compare/0.2.5...0.2.6">Diff</a> — <a href="http://htmlpreview.github.com/?https://raw.github.com/tgriesser/knex/0.2.5/index.html">Docs</a><br />
|
||
Reject the transaction promise if the transaction "commit" fails, (#50).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.2.5</b> — <small><i>Aug 25, 2013</i></small><br />
|
||
Fix error if a callback isn't specified for <tt>exec</tt>, (#49).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.2.4</b> — <small><i>Aug 22, 2013</i></small><br />
|
||
Fix SQLite3 delete not returning affected row count, (#45).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.2.3</b> — <small><i>Aug 22, 2013</i></small><br />
|
||
Fix insert with default values in PostgreSQL and SQLite3, (#44).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.2.2</b> — <small><i>Aug 20, 2013</i></small><br />
|
||
Allowing <tt>Raw</tt> queries to be passed as the primary table names.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.2.1</b> — <small><i>Aug 13, 2013</i></small><br />
|
||
Fix for an array passed to <tt>insert</tt> being mutated.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.2.0</b> — <small><i>Aug 7, 2013</i></small><br />
|
||
<b>Breaking changes:</b>
|
||
<ul>
|
||
<li>
|
||
<a href="#Schema-hasTable">hasTable</a> now returns a boolean rather than a failed promise.
|
||
</li>
|
||
<li>
|
||
Changed syntax for insert in postgresql, where the <tt>id</tt> is not assumed on inserts (#18).
|
||
The second parameter of <a href="#Builder-insert">insert</a> is now required to return an array of insert id's for the last insert.
|
||
</li>
|
||
<li>
|
||
The <a href="#Schema-timestamp">timestamp</a> method on the schema builder now uses a <tt>dateTime</tt> rather than a <tt>timestamp</tt>.
|
||
</li>
|
||
</ul>
|
||
Restored basic binding support on <tt>Raw</tt> queries (#19).
|
||
Added support for the JSON and UUID datatypes in postgres (#20).
|
||
Fix enabling enum in postgresql (#21).
|
||
Added foreign key support (#24).
|
||
Bugfix for column ordering on insert (#31).
|
||
Other minor bugfixes, documentation cleanup, & tweaks.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.8</b> — <small><i>July 7, 2013</i></small><br />
|
||
Somehow missing the <tt>!=</tt> operator. Using <tt>_.find</tt> rather than <tt>_.where</tt> in <tt>getCommandsByName</tt>(#22).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.7</b> — <small><i>June 12, 2013</i></small><br />
|
||
Ensures unhandled errors in the <tt>exec</tt> callback interface are re-thrown.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.6</b> — <small><i>June 9, 2013</i></small><br />
|
||
Renaming <tt>beforeCreate</tt> to <tt>afterCreate</tt>. Better handling of errors in the connection pooling.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.5</b> — <small><i>June 9, 2013</i></small><br />
|
||
Added the ability to specify <tt>beforeCreate</tt> and <tt>beforeDestroy</tt> hooks on the initialize's <tt>options.pool</tt>
|
||
to perform any necessary database setup/teardown on connections before use (#14). <tt>where</tt> and <tt>having</tt>
|
||
may now accept <tt>Knex.Raw</tt> instances, for consistency (#15). Added an <tt>orHaving</tt> method to the builder.
|
||
The ability to specify bindings on Raw queries has been removed.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.4</b> — <small><i>May 22, 2013</i></small><br />
|
||
<tt>defaultTo</tt> now accepts <tt>"false"</tt> for boolean columns, allows for empty strings as default values.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.3</b> — <small><i>May 18, 2013</i></small><br />
|
||
Enabling table aliases (#11). Fix for issues with transactions not functioning (#12).
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.2</b> — <small><i>May 15, 2013</i></small><br />
|
||
Bug fixes for <tt>groupBy</tt> (#7). Mysql using collation, charset config settings in <tt>createTable</tt>.
|
||
Added engine on <tt>schemaBuilder</tt> specifier (#6). Other doc fixes, tests.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.1</b> — <small><i>May 14, 2013</i></small><br />
|
||
Bug fixes for sub-queries, minor changes to initializing "main" instance, adding "pg" as
|
||
a valid parameter for the client name in the connection settings.
|
||
</p>
|
||
|
||
<p>
|
||
<b class="header">0.1.0</b> — <small><i>May 13, 2013</i></small><br />
|
||
Initial Knex release.
|
||
</p>
|
||
|
||
</div>
|
||
<script src="docs/assets/ga.js" type="text/javascript" charset="utf-8"></script>
|
||
<script src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.8/require.js"></script>
|
||
<script src="knex-built.js"></script>
|
||
</body>
|
||
</html>
|