mirror of
https://github.com/knex/knex.git
synced 2025-10-09 15:06:55 +00:00
1170 lines
36 KiB
HTML
1170 lines
36 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</title>
|
||
<style>
|
||
body {
|
||
font-size: 14px;
|
||
line-height: 22px;
|
||
background: #f4f4f4;
|
||
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;
|
||
}
|
||
div.warning {
|
||
margin-top: 15px;
|
||
font: bold 11px Arial;
|
||
color: #770000;
|
||
}
|
||
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.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.1.4)</span>
|
||
</a>
|
||
<ul class="toc_section">
|
||
<li>» <a href="https://github.com/tgriesser/knex">GitHub Repository</a></li>
|
||
<li>» <a href="http://knexjs.org/docs/knex.html">Annotated Source</a></li>
|
||
</ul>
|
||
|
||
<a class="toc_title" href="#installation">
|
||
Installation
|
||
</a>
|
||
|
||
<a class="toc_title" href="#Initialize">
|
||
Initialize
|
||
</a>
|
||
<ul class="toc_section">
|
||
<li>– <a href="#Init-multi-instance">multi-instance</a></li>
|
||
</ul>
|
||
|
||
<a class="toc_title" href="#Builder">
|
||
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-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-update">update</a></li>
|
||
<li>– <a href="#Builder-del">del / delete</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><b><a href="#Builder-Interface">Interface:</a></b></li>
|
||
<li>– <a href="#Builder-then">then</a></li>
|
||
<li>– <a href="#Builder-exec">exec</a></li>
|
||
<li>– <a href="#Builder-then">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-hasTable">hasTable</a></li>
|
||
<li>– <a href="#Schema-dropTableIfExists">dropTableIfExists</a></li>
|
||
<li>– <a href="#Schema-table">table</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-increments">increments</a></li>
|
||
<li>– <a href="#Schema-integer">integer</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="#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-nullable">nullable</a></li>
|
||
<li>– <a href="#Chainable-after">after</a></li>
|
||
</ul>
|
||
|
||
<a class="toc_title" href="#Raw">
|
||
Raw
|
||
</a>
|
||
|
||
<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, transaction support, connection pooling and node.js adapters for
|
||
postgres, mysql, and sqlite3 - standardizing responses between the three.
|
||
</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>,
|
||
post questions to the <a href="https://groups.google.com/forum/?fromgroups#!forum/bookshelfjs">Google Group</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>
|
||
|
||
<h2>Latest Release: 0.1.4</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>
|
||
|
||
|
||
<p>
|
||
Special thanks to <a href="https://twitter.com/taylorotwell">Taylor Otwell</a> and his work
|
||
on the <a href="http://four.laravel.com/docs/queries">Laravel Query Builder</a>,
|
||
from which much of the code and syntax is derived.
|
||
</p>
|
||
|
||
<h2 id="installation">
|
||
Installation
|
||
</h2>
|
||
|
||
<p>
|
||
All dependencies are specified in <tt>package.json</tt> file but include <tt>underscore.js</tt>,
|
||
<tt>when.js</tt>, and the <tt>generic-pool</tt> library. 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="Initialize">Knex.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>
|
||
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 id="Init-multi-instance">
|
||
It is also possible to use Knex with multiple database connection instances if you'd like,
|
||
by creating named instances. To do this, pass the name of the connection as the first
|
||
parameter into <tt>Knex.Initialize</tt> and it will return that instance, which may
|
||
also be referenced by name under <tt>Knex.Instances</tt>.
|
||
</p>
|
||
|
||
<pre>
|
||
var SqliteDB = Knex.Initialize('sqlitedb', {
|
||
client: 'sqlite',
|
||
connection: {
|
||
database : './testdb'
|
||
}
|
||
});
|
||
|
||
var MySql2 = Knex.Initialize('mysql2', {
|
||
client: 'mysql',
|
||
connection: { ... }
|
||
});
|
||
|
||
// Knex.Instances['mysql2'] === MySql2;
|
||
// Knex.Instances['sqlitedb'] === SqliteDB;
|
||
|
||
MySql2('accounts')
|
||
.select()
|
||
.then(function(resp) {
|
||
// ...
|
||
});
|
||
|
||
SqliteDB('users')
|
||
.insert({email: 'test@email.com'})
|
||
.exec(function(err, resp) {
|
||
// ...
|
||
});
|
||
</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
|
||
return with the
|
||
</p>
|
||
|
||
<pre>
|
||
// select "title", "author", "year" from "books"
|
||
Knex('books').select('title', 'author', 'year');
|
||
|
||
// select * from "books"
|
||
Knex('books').select();
|
||
</pre>
|
||
|
||
|
||
<p id="Builder-from">
|
||
<b class="header">from</b><code>.from([tableName])</code>
|
||
<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-57">where</a></li>
|
||
<li><a href="docs/knex.html#section-58">andWhere</a></li>
|
||
<li><a href="docs/knex.html#section-59">orWhere</a></li>
|
||
<li><a href="docs/knex.html#section-60">whereRaw</a></li>
|
||
<li><a href="docs/knex.html#section-61">orWhereRaw</a></li>
|
||
<li><a href="docs/knex.html#section-62">whereExists</a></li>
|
||
<li><a href="docs/knex.html#section-63">orWhereExists</a></li>
|
||
<li><a href="docs/knex.html#section-64">whereNotExists</a></li>
|
||
<li><a href="docs/knex.html#section-65">orWhereNotExists</a></li>
|
||
<li><a href="docs/knex.html#section-66">whereIn</a></li>
|
||
<li><a href="docs/knex.html#section-67">orWhereIn</a></li>
|
||
<li><a href="docs/knex.html#section-68">whereNotIn</a></li>
|
||
<li><a href="docs/knex.html#section-69">orWhereNotIn</a></li>
|
||
<li><a href="docs/knex.html#section-70">whereNull</a></li>
|
||
<li><a href="docs/knex.html#section-71">orWhereNull</a></li>
|
||
<li><a href="docs/knex.html#section-72">whereNotNull</a></li>
|
||
<li><a href="docs/knex.html#section-73">orWhereNotNull</a></li>
|
||
<li><a href="docs/knex.html#section-74">whereBetween</a></li>
|
||
<li><a href="docs/knex.html#section-75">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)</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]
|
||
Knex('books').insert({title: 'Slaughterhouse Five'})
|
||
|
||
// Returns [2] in "mysql", "sqlite"; [2, 3] in "postgresql"
|
||
Knex('books')
|
||
.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}])
|
||
</pre>
|
||
|
||
|
||
<p id="Builder-update">
|
||
<b class="header">update</b><code>.update(data)</code>
|
||
<br />
|
||
Creates an <tt>update</tt> query, taking 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-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>
|
||
|
||
<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-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>
|
||
Knex.Transaction(function(t) {
|
||
|
||
Knex('books')
|
||
.transacting(t)
|
||
.insert({name: 'Old Books'})
|
||
.then(function(row) {
|
||
|
||
return When.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>, with an error or failed promise if
|
||
the requested table does not exist.
|
||
</p>
|
||
|
||
<pre>
|
||
Knex.Schema.hasTable('users').then(null, function() {
|
||
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-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>
|
||
|
||
|
||
<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 columns, taking a variable number of column names.
|
||
</p>
|
||
|
||
<p id="Schema-increments">
|
||
<b class="header">increments</b><code>table.increments(name)</code>
|
||
<br />
|
||
Adds an auto incrementing column. This will be used as the primary key for the column.
|
||
</p>
|
||
|
||
<p id="Schema-integer">
|
||
<b class="header">integer</b><code>table.integer(name)</code>
|
||
<br />
|
||
Adds an integer column.
|
||
</p>
|
||
|
||
<p id="Schema-text">
|
||
<b class="header">text</b><code>table.text(name)</code>
|
||
<br />
|
||
Adds a text column.
|
||
</p>
|
||
|
||
<p id="Schema-string">
|
||
<b class="header">string</b><code>table.string(name)</code>
|
||
<br />
|
||
Adds a string column.
|
||
</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-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-engine">
|
||
<b class="header">engine</b><code>table.engine(val)</code>
|
||
<br />
|
||
Sets the engine for the database, only available within a <tt>createTable</tt> call, and only
|
||
applicable to MySql.
|
||
</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 integer as index. No-op if this is chained off of a non-integer field.
|
||
</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-nullable">
|
||
<b class="header">nullable</b><code>column.nullable()</code>
|
||
<br />
|
||
Allows a field to be nullable. No-op if chained off of a non-nullable field.
|
||
</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>
|
||
|
||
<pre>
|
||
Knex.Schema.createTable('accounts', function() {
|
||
t.increments().primary();
|
||
t.string('email').unique();
|
||
});
|
||
</pre>
|
||
|
||
<h2 id="Raw">Knex.Raw</h2>
|
||
|
||
<h3 id="Raw-Expression">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="faq">F.A.Q.</h2>
|
||
|
||
<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 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.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/public/scripts/ga.js" type="text/javascript" charset="utf-8"></script>
|
||
</body>
|
||
</html>
|