Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Installation is easy through CommandBox and ForgeBox. Simply type box install qb
to get started.
To start a new query, instantiate a new Builder: wirebox.getInstance('QueryBuilder@qb')
.
By default, qb uses a generic Grammar. You can specify your specific grammar in ColdBox by setting the defaultGrammar
in your moduleSettings
.
The grammars provided by qb are:
MySQLGrammar
OracleGrammar
PostgresGrammar
SqlServerGrammar
If you are not using WireBox, just make sure to wire up the Builder
object with the correct grammar:
Note: These instructions assume a basic knowledge of FW/1, a working FW/1 application structure with qb installed in the
/subsystems
directory (manually or via CommandBox), and a database configured to run with your application.
Once the application structure is setup, now we need to wire up qb to a bean factory using DI/1.
First we will add a mapping in Application.cfc
.
Next we need to tell DI/1 where qb's components are and how to reference them for later use in the application. We can do so by defining the configuration settings in the variables.framework.subsystems
struct in Application.cfc
. The example below makes use of a load listener to declare each component instance and pass in any constructor arguments.
Now that everything is configured, you can launch your application with CommandBox by entering start
in the terminal or use whatever method you're accustomed to.
To access qb from your application's code, you can call on it by using getBeanFactory()
.
A query builder is a stateful, transient object. That means that if you want to execute two different queries, you need two separate instances of QueryBuilder
.
As such, be careful when injecting QueryBuilder in to a component. If the component is a singleton, you will need to create the QueryBuilder inline or use a provider. This applies to ColdBox handlers as well.
While the above may seem innoculous, it can run in to issues as multiple requests come in to your application. Each request is sharing the same query builder instance and subsequent requests will have unintended results as the where
clause keeps growing request after request.
The solution is to either create the QueryBuilder inline, ensuring that each request has its own query to execute:
Or to use a WireBox provider to create a new query each time it is accessed:
One caveat when using a WireBox Provider: WireBox Providers proxy methods on to a new instance of the provided mapping on all methods except get
. get
is a method on the Provider itself. If you call get
as the first method on a Provider it will return a new instance of QueryBuilder, not execute the query. In those (rare) cases you will need to call query.get().get()
.
Once you have access to a QueryBuilder instance, you can create a new query using the same datasource, utils, returnFormat, paginationCollector, columnFormatter, and defaultOptions as the current QueryBuilder instance.
qb is a fluent query builder for CFML. It is heavily inspired by Eloquent from Laravel.
Using qb, you can:
Quickly scaffold simple queries
Make complex, out-of-order queries possible
Abstract away differences between database engines
Adobe ColdFusion 2016+
Lucee 5+
qb supports four major database grammars:
MySQL (MySQLGrammar
)
Oracle (OracleGrammar
)
Postgres (PostgresGrammar
)
Microsoft SQL Server (SqlServerGrammar
)
Installation is easy through CommandBox and ForgeBox. Simply type box install qb
to get started.
Compare these two examples:
The differences become even more stark when we introduce more complexity:
With qb you can easily handle setting order by statements before the columns you want or join statements after a where clause:
qb enables you to explore new ways of organizing your code by letting you pass around a query builder object that will compile down to the right SQL without you having to keep track of the order, whitespace, or other SQL gotchas!
Here's a gist with an example of the powerful models you can create with this! https://gist.github.com/elpete/80d641b98025f16059f6476561d88202
To start a new query, instantiate a new Builder: wirebox.getInstance('QueryBuilder@qb')
.
By default, qb uses a generic Grammar. You can specify your specific grammar in ColdBox by setting the defaultGrammar
in your moduleSettings
.
If you are not using WireBox, just make sure to wire up the Builder
object with the correct grammar:
This isn't a breaking change that will affect most people. In fact, it will most likely improve your code.
Previously, when using the control flow function, you were fully responsible for the wrapping of your where statements. For example, the following query:
Would generate the following SQL:
The problem with this statement is that the OR
can short circuit the active
check.
The fix is to wrap the LIKE
statements in parenthesis. This is done in qb using a function callback to where
.
When using the when
control flow function, it was easy to miss this. This is because you are already in a closure - it looks the same as when using where
to group the clauses.
In qb 8.0.0, when
will automatically group added where clauses when needed. That means our original example now produces the SQL we probably expected.
Grouping is not needed if there is no OR
combinator. In these cases no grouping is added.
If you had already wrapped your expression in a group inside the when
callback, nothing changes. Your code works as before. The OR
combinator check only works on the top most level of added where clauses.
Additionally, if you do not add any where clauses inside a when
callback, nothing changes from qb 7.
The breaking change part is if you were relying on these statements residing at the same level without grouping. In those cases, you may pass the withoutScoping
flag to the when
callback.
Support for Lucee 4.5 and Adobe ColdFusion 11 has been dropped. If you need support for these engines, please remain on an earlier version of qb.
MSSQLGrammar
was visually too close to MySQLGrammar
and was hard to differentiate quickly. SqlServerGrammar
is much more unique and easily identifiable. Additionally, more people that use this library refer to their database engine as "SQL Server" than "MSSQL".
Variadic parameter support was the ability to pass any number of arguments to certain methods like select
.
This code came with a slight performance cost and readability cost. That, combined with the fact that the above syntax is very close to an array, we are dropping support for variadic parameters. To migrate, wrap instances of variadic parameters in an array:
In previous versions, the value passed to defaultGrammar
was used to look up a mapping in the @qb
namespace. This made it difficult to add or use grammars that weren't part of qb. (You could get around this be registering your custom grammar in the @qb
namespace, but doing so seemed strange.)
To migrate this code, change your defaultGrammar
to be the full WireBox mapping in your moduleSettings
:
A defaultValue
parameter and optional exception throwing was added to value
. This pushed the options
struct to the end of the method. If you are using positional parameters with value
, you will need to update your method calls to either use named parameters or the new positions.
callback
to query
All methods that could conceivably take a subquery as well as a value now accept a closure or another builder instance to use as a subquery. This led to changing the callback
argument to query
in the following cases:
whereSub
whereInSub
whereExists
orWhereExists
whereNotExists
andWhereNotExists
orWhereNotExists
whereNullSub
orderBySub
subSelect
If you are using named parameters with any of the above methods you will need to migrate your method calls.
Version v5.0.0
brings support for SchemaBuilder
inside qb
. To avoid naming confusion, Builder
was renamed to QueryBuilder
. Any references in your code to Builder@qb
need to be updated to QueryBuilder@qb
.
Adds a where clause to a query.
Any of the following operators can be used in a where clause.
When using the "="
constraint, you can use a shortcut and define the value as the second argument.
To group where statements together, pass a function to the where clause as the only parameter.
This grouping can be nested as many levels as you require.
A Function or QueryBuilder can be used as a subselect expression when passed to value
.
Adds a where between clause to the query.
If a function or QueryBuilder is passed it is used as a subselect expression.
Adds a where clause to a query that compares two columns.
Just as with where
, when using "="
as the operator you can use a shorthand passing the second column in as the operator and leaving the second column null
.
Expressions
can be passed in place of either column.
Adds a where exists clause to the query.
It can be configured with a function.
It can also be configured with a QueryBuilder instance.
Adds a where in clause to the query.
The values passed to whereIn
can be a single value, a list of values, or an array of values.
Some database grammars have a hard limit on the number of parameters passed to a SQL statement. Keep this in mind while writing your queries.
If a list of values is passed in, it is converted to an array of values using a single comma (","
) delimiter.
Expressions
can be freely mixed in with other values.
A function or QueryBuilder instance can be passed to be used as a subquery expression instead of a list of values.
You may find a whereExists
method performs better for you than a whereIn
with a subquery.
Shorthand to add a raw SQL statement to the where clauses.
Adds a where null clause to the query.
qb uses onMissingMethod
to provide a few different helpers when working with where...
methods.
Every where...
method in qb can be called prefixed with either and
or or
. Doing so will call the original method using the corresponding combinator.
If you call a method starting with where
that does not match an existing qb method, qb will instead call the where
method using the rest of the method name as the first column name. (The rest of the arguments will be shifted to account for this.) This also applies to andWhere{Column}
and orWhere{Column}
method signatures.
You may not always want to select all columns from a database table. You can influence the select list of a query with the following methods.
Individual columns can contain fully-qualified names (some_table.some_column
), table aliases (alias.some_column
), and even set column aliases themselves (some_column AS c
). The columns
argument can be a single column, a list of columns (comma-separated), or an array of columns.
When calling select
any previous columns are discarded. If you want to incrementally select columns, use the addSelect
method.
If you pass no columns to this method, it will default to "*"
.
Calling distinct will cause the query to be executed with the DISTINCT
keyword.
distinct
applies to the entire query, not just certain fields.
This method adds the columns passed to it to the currently selected columns.
If the QueryBuilder
is currently selecting all columns ("*"
) when this method is called, the incoming columns will becoming the only columns selected.
A shortcut to use a raw expression in the select clause.
The expression is added to the other already selected columns.
The method lets you pass either a callback or a QueryBuilder
instance to be used as a subselect expression. If a callback is passed it will be passed a new query instance as the only parameter.
The subselect is added to the other already selected columns.
Clears out the selected columns for a query along with any configured select bindings.
Clears out the selected columns for a query along with any configured select bindings. Then adds an Expression or array of expressions to the already selected columns.
Ignore select bindings for aggregate queries.
Allow spaces in table aliases.
Split FLOAT and DECIMAL column types in SQL Server.
Clear orderBy bindings when calling clearOrders
.
Trim table definitions before searching for aliases. Makes qb more lenient with extra whitespace.
📹
callbacks now automatically scope and group where clauses when an
OR
combinator is used.
Expose nested where functions to enable advanced query manipulation in downstream libraries like Quick.
Fixes for OracleGrammar including table aliases and wrapped subqueries.
Handle enhanced numeric checks with Secure Profile enabled.
Allow raw statements in basic where clauses.
Handle multi-word columns in queryRemoveColumns
.
Remove elvis operator due to ACF compatibility issues
Compatibility fix for ACF 2018 and listLast
parsing.
Ignore table qualifiers for insert and update.
Fix a bug with preventDuplicateJoins when using the closure syntax with a join.
Add executionTime to the data output from BaseGrammar, including being available in interceptors.
Fix a case where a column was not wrapped correctly when a where
used a subquery for the value.
Avoid duplicate
function due to cbORM / Hibernate bugs when used in the same application.
Split off a private whereBasic
method. This is used in Quick to provide extra sql type features.
Fixed an issue using column formatters with update
and insert
.
Using a new preventDuplicateJoins
setting in the module settings, qb can detect duplicate joins and ignore them. This is especially useful in a heavily filtered and dynamic query where you may or may not need the join at all or more than one column may need the same join. preventDuplicateJoins
defaults to false
, so it is opt-in. It may be turned on by default in a future breaking release of qb.
You can now use two shortcut methods: orderByAsc
and orderByDesc
. Additionally, orderBySub
or using orderBy
with a closure or builder instance will respect the direction argument.
Fix for null values breaking the new checkIsActuallyNumeric
method in QueryUtils
.
Add a parameterLimit
public property to SqlServerGrammar
. This property is used in Quick to split up eager loading to work around the 2100 param limit of SQL Server.
Lambdas (arrow functions) are now allowed wherever closures are allowed.
Drop support for Lucee 4.5 and Adobe ColdFusion 11.
MSSQLGrammar
renamed to SqlServerGrammar
Remove variadic parameters support in builder functions like select
.
The defaultGrammar
mapping needs to be the full WireBox mapping, including the @qb
, if needed.
For instance, MSSQLGrammar
would become MSSQLGrammar@qb
.
This will allow for other grammars to be more easily contributed via third party modules.
The argument names of forPage
changed to match the new paginate
method.
Add defaultValue
and optional exception throwing to value
. (This changed the argument order.)
All methods that could conceivably take a subquery as well as a value now accept a closure or another builder instance to use as a subquery. (This changed the argument names in some instances.)
Completely revamped documentation! (You're looking at it right now.)
Preserve column case and order when converting a query to an array using the default "array"
return format.
Allow closures to be used in left and right joins.
Add raw
in alterTable
segments.
Add dropAllObjects
support for SqlServerGrammar
and OracleGrammar
to support migrate fresh
from cfmigrations.
Add a renameTable
alias for rename
.
Remove default constraints when dropping columns with a default on SqlServerGrammar
.
Add more column types and column helpers to SchemaBuilder
, including:
datetimeTz
lineString
nullableTimestamps
point
polygon
softDeletes
softDeletesTz
timeTz
timestamps
timestampTz
timestampsTz
withCurrent
To migrate, replace any instances of MSSQLGrammar
with SqlServerGrammar
. Make sure to also append the @qb
namespace, if needed,
Using the where
method will parameterize the value
passed. If you want to constrain a column to another column, use the method.
You can also pass an as the value.
You may also use statements to simplify this further.
This method is simply an alias for with the combinator set to "and"
.
This method is simply an alias for with the combinator set to "or"
.
Adds a where not in clause to the query. This behaves identically to the method with the negate
flag set to true
. See the documentation for for usage and examples.
Adds a where not in clause to the query. This behaves identically to the method with the negate
flag set to true
. See the documentation for for usage and examples.
A shortcut for calling with "like"
set as the operator.
Any value in the list or array can also be passed using a to have more control over the parameter settings.
Adds a where not in clause to the query. This behaves identically to the whereIn
method with the negate
flag set to true
. See the documentation for for usage and examples.
Adds a where not in clause to the query. This behaves identically to the method with the negate
flag set to true
. See the documentation for for usage and examples.
(To learn more about raw and expressions, check out the docs on .)
Clears out the selected columns for a query along with any configured select bindings. Then sets a selection of columns to select from the query. Any valid argument to can be passed here.
Combine and orderBy
with a new method.
Clear current selected columns with .
Combine and either or with and respectively.
Allow nullable in MySQL.
Return 0 on null .
Match type hints to documentation for functions
Passed along the options struct to the method when calling .
Allow for space-delimited directions like column DESC
.
Add helpful message when trying to use a closure with instead of .
and now work with
Correctly format RETURNING clauses with and ignoring table qualifiers.
Add support for and data types to .
Fix wrapping of types for Postgres.
Include current_timestamp default for columns in SchemaBuilder.
Add a method. Any already configured orders are cleared. Any orders added after this call will be added as normal.
now can take an array of expressions.
Enhance order by's with more direction options ()
Fix using whereBetween
with query param structs ()
Ignore orders in aggregate queries ()
Format with cfformat ()
Improve column wrapping with trimming ()
Prefer the parent query over magic methods when the parent query has the exact method. ()
Switch to using .
Allow passing query options in to paginate ()
Fix for inserting null values directly ()
Use cfformat for automatic formatting ()
Add a type to the onMissingMethod exception ()
Correctly wrap in MySQLGrammar
.
Publish qb apidocs to .
Allow a to be set. A parent query will receive any method calls that are not found on the Query Builder instance. This is especially useful for instances like to allow Quick features like scopes to be available inside any closures.
Add an method.
Allow for fully-qualified column names (table_name.column.name
) in the and methods.
Please see the for more information on these changes.
Add new flag to to replace question marks (?
) with cfqueryparam
-compatible structs for debugging.
Add a new method to generate a pagination struct alongside the results. This can be customized using a custom .
Allow raw values in calls.
Allow to be configure at a Query Builder level. This also enables custom QueryBuilders
a la .
Add a method.
Provide an method to programmatically build the SET
clause of an update query.
to grab records from the database in small sets.
Valid Operators |
= | < | > |
<= | >= | <> |
!= | like | like binary |
not like | between | ilike |
& | | | ^ |
<< | >> | rlike |
regexp | not regexp | ~ |
~* | !~ | !~* |
similar to | not similar to |
Name | Type | Required | Default | Description |
columns | string | array |
| ​ | A single column, list of columns, or array of columns to add to the select. |
Name | Type | Required | Default | Description |
expression | any |
| ​ | The raw expression for the select statement. |
bindings | array |
|
| Any bindings needed for the raw expression. |
Name | Type | Required | Default | Description |
alias | string |
| ​ | The alias for the subselect expression. |
query | Function | QueryBuilder |
| The callback or query to use in the subselect. |
Name | Type | Required | Default | Description |
No arguments | `` |
Name | Type | Required | Default | Description |
columns | string | array |
| ​ | A single column, list of columns, or array of columns to retrieve. |
Name | Type | Required | Default | Description |
expression | any |
| ​ | The raw expression for the select statement. |
bindings | array |
|
| Any bindings needed for the raw expression. |
query.raw
) in update statements.Name | Type | Required | Default | Description |
columns | string | array |
| ​ | A single column, list of columns, or array of columns to retrieve. |
Name | Type | Required | Default | Description |
state | boolean |
| ​ | Value to set the distinct flag. |
Table of Contents |
Name | Type | Required | Default | Description |
column |
|
operator |
| The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the |
value | any |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
column |
|
operator |
| The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the |
value | any |
|
Name | Type | Required | Default | Description |
column |
|
operator |
| The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the |
value | any |
|
Name | Type | Required | Default | Description |
column | string | Expression |
|
start | any | Function | QueryBuilder |
| The beginning value of the BETWEEN statement. If a function or QueryBuilder is passed it is used as a subselect expression. |
end | any | Function | QueryBuilder |
| The end value of the BETWEEN statement. If a function or QueryBuilder is passed it is used as a subselect expression. |
combinator | string |
|
|
negate | boolean |
|
| False for BETWEEN, True for NOT BETWEEN. |
Name | Type | Required | Default | Description |
column | string | Expression |
|
start | any | Function | QueryBuilder |
| The beginning value of the BETWEEN statement. If a function or QueryBuilder is passed it is used as a subselect expression. |
end | any | Function | QueryBuilder |
| The end value of the BETWEEN statement. If a function or QueryBuilder is passed it is used as a subselect expression. |
combinator | string |
|
|
Name | Type | Required | Default | Description |
first |
|
operator |
| The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the |
second | string | Expression |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
query | Function | QueryBuilder |
| A function or QueryBuilder instance to be used as the exists subquery. |
combinator | string |
|
|
negate | boolean |
|
| False for EXISTS, True for NOT EXISTS. |
Name | Type | Required | Default | Description |
query | Function | QueryBuilder |
| A function or QueryBuilder instance to be used as the not exists subquery. |
combinator | string |
|
|
Name | Type | Required | Default | Description |
column |
|
value | any |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
column | string | Expression |
|
values |
|
combinator | string |
|
|
negate | boolean |
|
| False for IN, True for NOT IN. |
Name | Type | Required | Default | Description |
column | string | Expression |
|
values |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
sql | string |
| The raw SQL to add to the query. |
whereBindings | array |
|
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
column | string | Expression |
|
combinator | string |
|
|
negate | boolean |
|
| False for NULL, True for NOT NULL. |
Name | Type | Required | Default | Description |
column | string | Expression |
|
combinator | string |
|
|
negate | boolean |
|
| False for NULL, True for NOT NULL. |
Join clauses range from simple to complex including joining complete subqueries on multiple conditions. qb has your back with all of these use cases.
Applies a join to the query. The simplest join is to a table based on two columns:
When doing a simple join using =
as the operator, you can omit it and pass just the column names:
``Expressions
are also supported as the table
argument (though you may prefer the readability of the joinRaw
method):
Using raw
will most likely tie your code to a specific database, so think carefully before using the raw
method if you want your project to be database agnostic.
When you need to specify more clauses to join, you can pass a function as the second argument:
You can specify where
clauses in your joins as well.
Conditions inside a join clause can be grouped using a function.
A preconfigured JoinClause
can also be passed to the join function. This allows you to extract shared pieces of code out to different functions.
Adds a join to another table based on a WHERE
clause instead of an ON
clause. WHERE
clauses introduce parameters and parameter bindings whereas on
clauses join between columns and don't need parameter bindings.
For simple joins, this specifies a column on which to join the two tables:
For complex joins, a function can be passed to first
. This allows multiple on
and where
conditions to be applied to the join. See the documentation for join
for more information.
Uses the raw SQL provided to as the table for the join clause. All the other functionality of joinRaw
matches the join
method. Additionally, there are leftJoinRaw
, rightJoinRaw
, and crossJoinRaw
methods available.
Using joinRaw
will most likely tie your code to a specific database, so think carefully before using the joinRaw
method if you want your project to be database agnostic.
Adds a join to a derived table. All the functionality of the join
method applies to constrain the query. The derived table can be defined using a QueryBuilder
instance:
Alternatively, a function may be used to define the derived table:
Complex join conditions are also possible by passing a function as the third parameter:
Uses the raw SQL provided to as the table for the left join clause. All the other functionality of leftJoinRaw
matches the join
method.
Using leftJoinRaw
will most likely tie your code to a specific database, so think carefully before using the leftJoinRaw
method if you want your project to be database agnostic.
Adds a left join to a derived table. All the functionality of the joinSub
method applies to define and constrain the query.
Uses the raw SQL provided to as the table for the right join clause. All the other functionality of rightJoinRaw
matches the join
method.
Using rightJoinRaw
will most likely tie your code to a specific database, so think carefully before using the rightJoinRaw
method if you want your project to be database agnostic.
Adds a right join to a derived table. All the functionality of the joinSub
method applies to define and constrain the query.
Uses the raw SQL provided to as the table for the cross join clause. Cross joins cannot be further constrained with on
or where
clauses.
Using crossJoinRaw
will most likely tie your code to a specific database, so think carefully before using the crossJoinRaw
method if you want your project to be database agnostic.
Adds a cross join to a derived table. The derived table can be defined using a QueryBuilder
instance or a function just as with joinSub
. Cross joins cannot be constrained, however.
Creates a new JoinClause
. A JoinClause
is a specialized version of a QueryBuilder
. You may call on
or orOn
to constrain the JoinClause
. You may also call any where
methods.
Creating a JoinClause
directly is useful when you need to share a join between different queries. You can create and configure the JoinClause
in a function and pass it to queries as needed.
Although a JoinClause
can be passed to join
, leftJoin
, rightJoin
, and crossJoin
, the type of the JoinClause
will override the type of the function.
A JoinClause
is a specialized version of a QueryBuilder
. You may call on
or orOn
to constrain the JoinClause
. You may also call any where
methods.
Applies a join condition to the JoinClause
. An alias for whereColumn
.
Applies a join condition to the JoinClause
using an or
combinator. An alias for orWhereColumn
.
Used to set the base table for the query.
You can optionally specify an alias for the table.
An alias for from
where you like how calling table
looks.
Sometimes you need more control over your from
clause in order to add grammar specific instructions, such as adding SQL Server table hints to your queries.
Since the fromRaw()
takes your string verbatim, it's important that you make sure your SQL declaration is escaped properly. Failure to properly escape your table names may result in SQL errors.
Using fromRaw
will most likely tie your code to a specific database, so think carefully before using the fromRaw
method if you want your project to be database agnostic.
Many database engines allow you to define User Defined Functions. For example, SQL Server allows you to define UDFs that will return a table. In these type of cases, it may be necessary to bind parameters to your from
clause.
You can bind parameters to the fromRaw()
method by passing a secondary argument that is an array of the parameters to bind.
Complex queries often contain derived tables. Derived tables are essentially a temporal table defined as a subquery in the from
statement.
In additional a function callback, a separate QueryBuilder
instance can be passed to the fromSub
method.
Sets the limit value for the query.
Sets the limit value for the query. Alias for limit
.
Sets the offset value for the query.
Helper method to calculate the limit and offset given a page number and count per page.
This method combines forPage
, count
, and get
to create a pagination struct alongside the results. Information on the paginate
method, including custom pagination collectors, can be found in the Retreiving Results section of the documentation.
The query builder also lets you create union statements on your queries using either UNION
or UNION ALL
strategies.
The union
methods take either a Query Builder instance or a closure which you use to define a new QueryBuilder instance.
Union statements are added in the order in which the union
methods are invoked, but the union
statements can be in any order in your API call stack. This means you can safely declare your union
method calls before the select
, from
and orderBy
calls on the source Query Builder instance.
union()
— This method builds a SQL statement using the UNION
clause which combines two SQL queries into a single result set containing all the matching rows. The two queries must have the same defined columns and compatible data types or the SQL engine will generate an error. The union
clause only returns unique rows.
unionAll()
— This builds a SQL statement using the UNION ALL
clause. This is the same as union
but includes duplicate rows.
IMPORTANT: The QueryBuilder instances passed to a union
statement cannot contain a defined order. Any use of the orderBy()
method on the unioned QueryBuilder instances will result in an OrderByNotAllowed
exception. To order the results, add an orderBy()
call to the parent source Query Builder instance.
Adds a UNION statement to the query.
Adding multiple union statements will append it to the query.
It can also add union queries as QueryBuilder instances.
Adds a UNION ALL statement to the query.
Adding multiple unionAll
statements will append it to the query.
It can also add union queries as QueryBuilder instances.
The orderBy
method seems simple but has a lot of depth depending on the type of arguments you pass in.
Calling orderBy
multiple times appends to the order list.
Calling orderBy
multiple times will append to the order list.
You can also provide an Expression
.
You can order with a subquery using either a function or a QueryBuilder instance.
Clears the currently configured orders for the query. Usually used by downstream libraries like Quick.
Clears the currently configured orders for the query and sets the new orders passed in. Any valid argument to orderBy
can be passed here. Usually used by downstream libraries like Quick.
Common Table Expressions (CTEs) are powerful SQL concept that allow you to create re-usable temporal result sets, which can be referenced as a table within your SQL. CTEs are available in many common database engines and are available in latest versions of all of the support grammars.
CTEs come in two basic types:
Non-recursive — These are statements that do not reference themselves, in simplified terms they are like a derived table that can be referenced by a user-defined name.
Recursive — Recursive CTEs reference themselves and are generally used for creating hierarchical data—such as creating a parent/child relationship within a table.
While all of the grammars currently support CTEs, there is enough difference between the various databases implementations of CTEs that unless your CTEs are fairly basic, using CTEs within your project will most likely tie your project to a specific database, unless you account for the differences in your code.
However, CTEs are can be extremely useful to solve certain use cases.
To add CTEs to your queries, you have two methods available:
with()
— Allows you to define a non-recursive CTE.
withRecursive()
— Allows you to define a recursive CTE.
Some database engines require the recursive
keyword anytime at least one of your CTEs is recursive, but some database engines (e.g. SQL Server and Oracle) do not require the keyword. qb will manage adding the keyword, if necessary. If your query does use recursion you should use the withRecursive()
method to avoid issues when migrating grammars.
You can build a CTE using a function:
Alternatively, you can use a QueryBuilder instance instead of a function:
A single query can reference multiple CTEs:
IMPORTANT — The way the SQL in a recursive CTEs are written, using them in your code is likely to lock in you in to a specific database engine, unless you structure your code to build the correct SQL based on the current grammar being used.
Here is an example of building a recursive CTE using SQL Server which would return all parent/child rows and show their generation/level depth:
Passing a single string will group by that one column.
You can also pass a list of column names. A single comma (","
) will be used as the delimiter.
An array of column names can be provided.
Calling groupBy
multiple times will to the current groups.
An Expression
can be passed in place of a column.
Adds a having clause to a query.
Expressions
can be used in place of the column or the value.
If you store the builder object in a variable, you can use if
and else
statements like you would expect.
This works, but breaks chainability. To keep chainability you can use the when
helper method.
when
The when
helper is used to allow conditional statements when defining queries without using if statements and having to store temporary variables.
You can pass a third argument to be called in the else
case.
when
callbacks are automatically scoped and grouped. That means that if a where clause is added inside the callback with an OR
combinator the clauses will automatically be grouped (have parenthesis put around them.) You can disable this feature by passing withoutScoping = true
to the when
callback.
When passing a parameter to qb, it will infer the sql type to be used. If you pass a number, CF_SQL_NUMERIC
will be used. If it is a date, CF_SQL_TIMESTAMP
, and so forth. If you need more control, you can pass a struct with the parameters you would pass to .
You can pass include any parameters you would use with including null
, list
, etc. This applies anywhere parameters are used including where
, update
, and insert
methods.
This can be used when inserting or updating records as well.
If you need to inspect the bindings for the current query you can retrieve them in order using the getBindings
method.
Use these methods only for debugging. Modifying the bindings directly will likely cause issues when executing your query. Adding or removing bindings should be done using the public API.
This method returns the current bindings in order to be used for the query.
You can also retrieve the bindings associated to their corresponding types.
This method returns the current bindings to be used for the query associated to their corresponding types.
Each query execution method allows for the passing of an options struct. This is the same struct you would pass to .
qb allows you to specify default options when creating the QueryBuilder instance using the defaultOptions
argument. You can combine this with WireBox to create custom QueryBuilder instances pointing to different datasources and even different grammars.
When mapping to components provided by modules, such as qb, use the interception point inside your config/WireBox.cfc
to ensure all modules are fully loaded and available.
In Application.cfc
you can specify your default datasource which will be used by qb. If you want to retrieve data from other datasources you can specify this in all retrieval functions by using the extra options parameter such as:
If you also want to use a non-default SQL Grammar you have to specify this when creating your QueryBuilder
.
At times you may need to duplicate a query. Using clone
you have a performant way to duplicate a query without using the duplicate
method.
Raw expressions are the qb escape hatch. While qb strives to provide ways to execute the majority of queries, you will occasionally need to provide raw sql values that are not processed by qb. These SQL snippets are called raw
or Expressions
in qb.
raw
expressions are useful, but shoud be used only if there is not another way to accomplish the same action using other qb methods. This is because a raw
expression has the potential to use syntax specific to one database grammar or another, preventing you from easily switching from one grammar to another, one of the major benefits of using qb.
The first way to retrieve an Expression
is to call the raw
method on the QueryBuilder
object.
The sql snippet passed to raw
is not processed by qb at all. With that in mind, it is important to follow all best practices and security recommendations with the sql you use with raw
.
Expressions can be passed to most qb methods, like select
, from
, where
, or orderBy
, among others. Additionally, qb provides some convenience methods to add raw values in different parts of the query:
The get
method is the most common method used for retrieving results. It executes using the configured QueryBuilder
and returns the results.
get
can also take a list or array of columns to use as a shortcut. If any are passed, those columns will be used instead of any columns previously set on the QueryBuilder
.
If you just need to retrieve a single row from the database table, you may use the first
method. This method will return a single record (a Struct
by default). If no row is found an empty Struct
will be returned by default.
If you don't even need an entire row, you may extract a single value from each record using the values
method. The values
method will return the column of your choosing as a simple array.
This method is similar to values
except it only returns a single, simple value. Where values
calls get
under the hood, this method calls first
.
If no records are returned from the query, one of two things will happen. If the throwWhenNotFound
boolean is set to true
, a RecordCountException
will be thrown. Otherwise the defaultValue
provided to the method will be returned.
Large datasets can be broken up and retrieved in chunks. This allows you to work with a subset of results at once to keep your memory footprint under control.
chunk
can be called on any query like you would call get
. You can stop the retrieving and processing early by returning false
from the callback.
Generates a pagination struct along with the results of the executed query. It does this by calling both count
and forPage
.
You can set your custom pagination collector either in the constructor using the paginationCollector
argument or by calling setPaginationCollector
on a query builder instance.
This call must come after setting the query's table using or .
You can insert a single record by passing a struct:
You can specify any options such as the SQL type by passing a struct with the parameters you would pass to .
Raw values can be supplied to an insert statement.
Multiple rows can be inserted in a batch by passing an array of structs to insert
.
This is not the same as looping over and array and calling insert
in the loop. Using an array with insert
will batch the inserts in one SQL call. Looping over an array and calling insert
each time will create a SQL request for each item in the array. Bottom line, pass your array to insert
!
returning
is only supported in PostgresGrammar
and SqlServerGrammar
. Using this method on unsupported grammars will result in an UnsupportedOperation
exception. Be aware that using this method constrains your grammar choices.
Specifies columns to be returned from the insert query.
Updates a table with a struct of column and value pairs.
You can update a column based on another column using a raw expression.
Null values can be inserted by using queryparam syntax:
if you are using Lucee with full null support the following (easier) syntax is also allowed:
Performs an update statement if the configured query returns true
for exists
. Otherwise, performs an insert statement.
If an update statement is performed qb applies a limit( 1 )
to the update statement.
If the configured query returns 0 records, then an insert statement is performed.
Deletes all records that the query returns.
The id
argument is a convenience to delete a single record by id.
The query builder also provides a variety of aggregate methods such as count
, max
, min
, and sum
. These methods take the headache out of setting up these common aggregate functions.
When executing any of the aggregate functions, any where
restrictions on your query will still be applied.
Instead of returning a query, these methods return a simple value.
Returns true
if the query returns any rows. Returns false
otherwise.
Returns an integer number of rows returned by the query.
Returns the maximum value for the given column.
Returns the minimum value for the given column.
Returns the sum of all returned rows for the given column.
We welcome all types of contributions!
The most common type of contribution is to fix an incorrect SQL generation for a database grammar.
To debug what SQL is being ran, you can always call toSQL
on any QueryBuilder
or SchemaBuilder
object. Additionally, you can listen to the preQBExecute
interception point for the generated SQL.
Each of the database grammars have two tests — {Grammar}QueryBuilderSpec.cfc
and {Grammar}SchemaBuilderSpec.cfc
. These tests run the same qb syntax across the different grammars. In each test are methods that return SQL strings like so:
If you find an issue with the SQL generated from a grammar, please file a pull request with the correct SQL in these tests. It's okay if you don't submit a fix as well. (But we'd greatly appreciate it!) Doing so will help expedite the fix.
If you want to add support for a new database grammar, simply copy these two tests from an existing grammar, rename them, change the getBuilder
method to return your new grammar, and fill out the SQL as it should be. That will guide your implementation to be 100% compatible with the other grammars in qb.
string | | Function
The name of the column or with which to constrain the query. A function can be passed to begin a nested where statement.
string |
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the and methods instead.
string | | Function
The name of the column or with which to constrain the query. A function can be passed to begin a nested where statement.
string |
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
string | | Function
The name of the column or with which to constrain the query. A function can be passed to begin a nested where statement.
string |
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
The name of the column or with which to constrain the query.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column or with which to constrain the query.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
string |
The name of the first column or with which to constrain the query.
string |
The name of the second column or with which to constrain the query.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
string |
The name of the column or with which to constrain the query.
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column or with which to constrain the query.
string | array | | Function | QueryBuilder
A single value, list of values, or array of values to constrain a column with. may be used in any place a value is used. Alternatively, a function or QueryBuilder instance can be passed in to be used as a subquery expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column or with which to constrain the query.
string | array | | Function | QueryBuilder
A single value, list of values, or array of values to constrain a column with. may be used in any place a value is used. Alternatively, a function or QueryBuilder instance can be passed in to be used as a subquery expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
Any bindings needed for the raw SQL. Bindings can be simple values or .
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column to check if it is NULL. Can also pass an .
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column to check if it is NULL. Can also pass an .
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
Bindings are the values that will be sent as parameters to a prepared SQL statement. This protects you from In CFML, this uses to parameterize the values.
You can view the current SQL for the query with bindings inline for debugging purposes using the method.
A pagination collector is the name given to the struct returned from calling the method. It can be a struct or a component. It needs one function defined and will be passed the following parameters.
By default, qb ships with as its pagination collector. The return format of cbpaginator
is the example shown above.
This call must come after setting the query's table using or .
You can specify any options such as the SQL type by passing a struct with the parameters you would pass to .
Any constraining of the update query should be done using the appropriate statement before calling update
.
Adds values to a later , similar to .
Table of Contents
Name
Type
Required
Default
Description
table
string | Expression | JoinClause
true
​
The name of the table or a Expression
object from which the query is based. Alternatively, a configured JoinClause
instance can be passed.
first
string | Expression | Function
false
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
type
string
false
"inner"
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use the dedicated joinWhere
or a join closure where possible.
Name
Type
Required
Default
Description
table
string
true
​
The raw SQL string to use as the table.
first
string | Expression | Function
false
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
type
string
false
"inner"
Name
Type
Required
Default
Description
table
string
true
​
The raw SQL string to use as the table.
first
string | Expression | Function
false
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
type
string
false
"inner"
The type of the join. Passing this as an argument is discouraged for readability. Use the dedicated methods like leftJoinRaw
and rightJoinRaw
where possible.
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use a closure to define the where clauses where possible.
Name
Type
Required
Default
Description
alias
string
true
The alias for the derived table.
input
Function | QueryBuilder
true
​
Either a QueryBuilder
instance or a function to define the derived query.
first
string | Expression | Function
true
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
type
string
false
"inner"
The type of the join. Passing this as an argument is discouraged for readability. Use the dedicated methods like leftJoinSub
and rightJoinSub
where possible.
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use a closure to define the where clauses where possible.
Name
Type
Required
Default
Description
table
string | Expression | JoinClause
true
​
The name of the table or a Expression
object from which the query is based. Alternatively, a configured JoinClause
instance can be passed.
(Note: a JoinClause
instance may have a different join type than a left
join. The JoinClause
instance's join type will be used.)
first
string | Expression | Function
false
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use a closure to define the where clauses where possible.
Name
Type
Required
Default
Description
table
string
true
​
The raw SQL string to use as the table.
first
string | Expression | Function
false
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use a closure to define the where clauses where possible.
Name
Type
Required
Default
Description
alias
string
true
The alias for the derived table.
input
Function | QueryBuilder
true
​
Either a QueryBuilder
instance or a function to define the derived query.
first
string | Expression | Function
true
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use a closure to define the where clauses where possible.
Name
Type
Required
Default
Description
table
string | Expression | JoinClause
true
​
The name of the table or a Expression
object from which the query is based. Alternatively, a configured JoinClause
instance can be passed.
(Note: a JoinClause
instance may have a different join type than a right
join. The JoinClause
instance's join type will be used.)
first
string | Expression | Function
false
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use a closure to define the where clauses where possible.
Name
Type
Required
Default
Description
table
string
true
​
The raw SQL string to use as the table.
first
string | Expression | Function
false
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use a closure to define the where clauses where possible.
Name
Type
Required
Default
Description
alias
string
true
The alias for the derived table.
input
Function | QueryBuilder
true
​
Either a QueryBuilder
instance or a function to define the derived query.
first
string | Expression | Function
true
The first column or Expression
to join the table on. Alternatively, a function can be passed to configure complex join statements.
operator
string
false
"="
The boolean operator for the join clause.
second
string | Expression
false
The second column or Expression
to join the table on.
where
boolean
false
false
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use a closure to define the where clauses where possible.
Name
Type
Required
Default
Description
table
string | Expression | JoinClause
true
​
The name of the table or a Expression
object from which the query is based. Alternatively, a configured JoinClause
instance can be passed.
(Note: a JoinClause
instance may have a different join type than a cross
join. The JoinClause
instance's join type will be used.)
Name
Type
Required
Default
Description
table
string
true
​
The raw SQL string to use as the table.
Name
Type
Required
Default
Description
alias
string
true
The alias for the derived table.
input
Function | QueryBuilder
true
​
Either a QueryBuilder
instance or a function to define the derived query.
Name
Type
Required
Default
Description
table
string | Expression
true
​
The name of the table or a Expression
object from which the query is based.
type
string
false
"inner"
The type of the join. Valid types are inner
, left
, right
, or cross
.
Name
Type
Required
Default
Description
first
string | Expression | Function
false
The first column or Expression
of the condition. Alternatively, a function can be passed to nest conditions with parenthesis.
operator
string
false
"="
The boolean operator for the condition.
second
string | Expression
false
The second column or Expression
of the condition.
combinator
string
false
"and"
The boolean combinator for the clause (e.g. "and" or "or").
Name
Type
Required
Default
Description
first
string | Expression | Function
false
The first column or Expression
of the condition. Alternatively, a function can be passed to nest conditions with parenthesis.
operator
string
false
"="
The boolean operator for the condition.
second
string | Expression
false
The second column or Expression
of the condition.
Name
Type
Required
Default
Description
from
string | Expression
true
​
The name of the table or a Expression object from which the query is based.
Name
Type
Required
Default
Description
table
string | Expression
true
​
The name of the table or a Expression object from which the query is based.
Name
Type
Required
Default
Description
from
string
true
​
The sql snippet to use as the table.
bindings
array
false
[]
Any bindings needed for the expression.
Name
Type
Required
Default
Description
alias
string
true
​
The alias for the derived table.
input
Function | QueryBuilder
true
Either a QueryBuilder
instance or a closure to define the derived query.
Name
Type
Required
Default
Description
value
numeric
true
The limit value for the query.
Name
Type
Required
Default
Description
value
numeric
true
The limit value for the query.
Name
Type
Required
Default
Description
value
numeric
true
The offset value for the query.
Name
Type
Required
Default
Description
page
numeric
true
The page number to retrieve.
maxRows
numeric
true
The number of records per page. If a number less than 0 is passed, 0 is used instead.
Name
Type
Required
Default
Description
input
Function | QueryBuilder
true
The function or QueryBuilder instance to use as the unioned query.
all
boolean
false
false
Determines if statement should be a "UNION ALL". Passing this as an argument is discouraged. Use the dedicated unionAll
where possible.
Name
Type
Required
Default
Description
input
Function | QueryBuilder
true
The function or QueryBuilder instance to use as the unioned query.
Name
Type
Required
Default
Description
column
any
true
The name of the column to order by. An Expression
can be passed as well.
direction
string
false
"asc"
The direction by which to order the query. Accepts "asc"
or "desc"
.
Name
Type
Required
Default
Description
column
any
true
The list of the columns to order by. Each column can optionally declare it's sort direction after a pipe delimiter. (e.g. `"height
desc"`).
direction
string
false
"asc"
The direction by which to order the query. Accepts "asc"
or "desc"
. This value will be used as the default value for all entries in the column list that fail to specify a direction for a specific column.
Name
Type
Required
Default
Description
column
any
true
The array of the columns to order by. Each column can optionally declare it's sort direction after a pipe delimiter. (e.g. `"height
desc"`).
direction
string
false
"asc"
The direction by which to order the query. Accepts "asc"
or "desc"
. This value will be used as the default value for all entries in the column array that fail to specify a direction for a specific column.
Name
Type
Required
Default
Description
column
any
true
The array of the columns to order by. Each column can optionally declare it's sort direction using a struct. The struct should have a column key and an optional direction key. (e.g. { column = "favorite_color", direction = "desc" }
).
direction
string
false
"asc"
The direction by which to order the query. Accepts "asc"
or "desc"
. This value will be used as the default value for all entries in the column array that fail to specify a direction for a specific column.
Name
Type
Required
Default
Description
column
any
true
The name of the column to order by. An Expression
can be passed as well. An array can be passed with any combination of simple values, array, struct, or list for each entry in the array (an example with all possible value styles: column = [ "last_name", [ "age", "desc" ], { column = "favorite_color", direction = "desc" }, "height|desc" ];. The column argument can also just accept a comman delimited list with a pipe ( | ) as the secondary delimiter denoting the direction of the order by. The pipe delimiter is also used when parsing the column argument when it is passed as an array and the entry in the array is a pipe delimited string.
direction
string
false
"asc"
Ignored when using a Function or QueryBuilder instance.
Name
Type
Required
Default
Description
No arguments
Name
Type
Required
Default
Description
column
any
true
The name of the column to order by. An Expression
can be passed as well.
direction
string
false
"asc"
The direction by which to order the query. Accepts "asc"
or "desc"
.
Name
Type
Required
Default
Description
name
string
true
The name of the CTE.
input
QueryBuilder | Function
true
Either a QueryBuilder instance or a function to define the derived query.
columns
Array<String>
false
[]
An optional array containing the columns to include in the CTE.
recursive
boolean
false
false
Determines if the CTE statement should be a recursive CTE. Passing this as an argument is discouraged. Use the dedicated withRecursive
where possible.
Name
Type
Required
Default
Description
name
string
true
The name of the CTE.
input
QueryBuilder | Function
true
Either a QueryBuilder instance or a function to define the derived query.
columns
Array<String>
false
[]
An optional array containing the columns to include in the CTE.
Name
Type
Required
Default
Description
groups
string | array
true
A single column name, a list of column names, or an array of column names to group by. An Expression
can be passed as well.
Name
Type
Required
Default
Description
column
string | Expression
true
The name of the column or Expression
with which to constrain the query.
operator
any
false
The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the operator
and the value
left null as a shortcut for equals (e.g. where( "column", 1 ) == where( "column", "=", 1 ) ).
value
any
false
The value with which to constrain the column. An Expression
can be passed as well.
combinator
string
false
"and"
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andHaving
and orHaving
methods instead.
Name | Type | Required | Default | Description |
No arguments |
Name | Type | Required | Default | Description |
No arguments |
Name | Type | Required | Default | Description |
column | string |
| The name of the column to retrieve. |
options | struct |
|
| Any additional |
Name | Type | Required | Default | Description |
column | string |
| The name of the column to retrieve. |
defaultValue | string |
| (empty string) | The default value returned if there are no records returned for the query. |
throwWhenNotFound | boolean |
|
| If |
options | struct |
|
| Any additional |
Name | Type | Default | Description |
max | numeric | The number of results to return in each chunk. |
callback | Function | The function that will be called with each chunk. |
options | struct |
| Any additional |
Name | Type | Required | Default | Description |
page | numeric |
|
| The page number to retrieve. |
maxRows | numeric |
|
| The number of records per page. If a number less than 0 is passed, 0 is used instead. |
options | struct |
|
| Any additional |
Name | Type | Description |
totalRecords | numeric | The total records count. |
results | any | The results of the query execution. It will be passed as whatever return format the user has defined. |
page | numeric | The current page number. |
maxRows | numeric | The maximum number of rows retrieved per page. |
Name | Type | Required | Default | Description |
columns | string | array |
| A single column, a list or columns, or an array of columns to return from the inserted query. |
Name | Type | Required | Default | Description |
values | struct |
| A struct of column and value pairs to add to the update clause. |
Name | Type | Required | Default | Description |
values | struct |
| A struct of column and value pairs to either update or insert. |
options | boolean |
|
| Any additional |
toSql | boolean |
|
| If |
Name | Type | Required | Default | Description |
column | string |
| The column on which to find the max. |
options | struct |
|
| Any additional |
Name | Type | Required | Default | Description |
column | string |
| The column on which to find the min. |
options | struct |
|
| Any additional |
Name | Type | Required | Default | Description |
column | string |
| The column to sum. |
options | struct |
|
| Any additional |
Name | Type | Required | Default | Description |
condition | boolean | true | The condition to switch on. |
onTrue | Function | true | The callback to execute if the condition is true. It is passed the |
onFalse | Function | false | function( q ) { return q; } | The callback to execute if the conditions is false. It is passed the |
withoutScoping | boolean | false |
| Flag to turn off the automatic scoping of where clauses during the callback. |
Name | Type | Required | Default | Description |
sql | string | true | The raw sql to wrap up in an Expression. |
Name | Type | Required | Default | Description |
columns | string | array | false | A shortcut parameter to retrieve only these columns overriding any columns previously set on the QueryBuilder. |
options | struct | false |
| Any additional |
Name | Type | Required | Default | Description |
options | struct |
|
| Any additional |
Name | Type | Required | Default | Description |
values | struct | array<struct> |
| A struct or array of structs to insert in to the table. |
options | struct |
|
| Any additional |
toSQL | boolean |
|
| If |
Name | Type | Required | Default | Description |
options | struct |
|
| Any additional |
Name | Type | Required | Default | Description |
column | string |
|
| The column on which to count records. |
options | struct |
|
| Any additional |
Available as an advanced option for framework authors, qb will call out to a column formatter prior to processing a column as part of the SQL query. This allows frameworks like Quick to define queries using aliases and transform them to columns during execution.
You can provide your own column formatter function to qb through the init
method or by calling setColumnFormatter
. It is a function that takes a column string and returns a string
Name | Type | Required | Default | Description |
values | struct |
|
|
options | struct |
|
| Any additional |
toSQL | boolean |
|
| If |
Name | Type | Required | Default | Description |
id | any |
|
idColumn | string |
|
| The name of the id column for the delete shorthand. |
options | boolean |
|
| Any additional |
toSql | boolean |
|
| If |
Two interception points are available from QB: preQBExecute
and postQBExecute
. These fire before and after the queryExecute
call, respectively.
The following information is available in the interceptData
struct:
The following information is available in the interceptData
struct:
The Blueprint
object has many column types available to construct your table schema. Additionally, you can modify the columns created with an additional set of methods and indexes.
Create an auto-incrementing column using an unsigned BIGINT
type. This column is also set as the primary key for the table.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a BIGINT
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a BIT
equivalent type for your database. The length can be specified as the second argument.
Example (default length):
SchemaBuilder
SQL (MySQL)
Example (custom length):
SchemaBuilder
SQL (MySQL)
Create a column using a BOOLEAN
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a CHAR
equivalent type for your database.
Example (default length):
SchemaBuilder
SQL (MySQL)
Example (custom length):
SchemaBuilder
SQL (MySQL)
Create a column using a DATE
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a DATETIME
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a timezone-specific DATETIME
equivalent type for your database.
Some databases do not have the concept of a timezone-specific datetime. Those databases will use a normal DATETIME
type.
Example:
SchemaBuilder
SQL (SQL Server)
Create a column using a DECIMAL
equivalent type for your database. The length and precision can be specified as the second and third arguments.
Example (with defaults):
SchemaBuilder
SQL (MySQL)
Example (with length):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a ENUM
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a FLOAT
equivalent type for your database. The length and precision can be specified as the second and third arguments.
Example (with defaults):
SchemaBuilder
SQL (MySQL)
Example (with length):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create an auto-incrementing column using an unsigned INTEGER
type. This column is also set as the primary key for the table.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a INTEGER
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a JSON
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a LINESTRING
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a LONGTEXT
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Create an auto-incrementing column using an unsigned MEDIUMINT
type. This column is also set as the primary key for the table.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a MEDIUMINT
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a MEDIUMTEXT
equivalent type for your database. For databases that distinguish between unicode and non-unicode fields, creates a non-unicode field.
Example:
SchemaBuilder
SQL (MySQL)
SQL (MSSQL)
Create a column using a MONEY
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
SQL (MSSQL)
Creates the necessary columns for a polymorphic relationship. It takes the name provided and creates an _id
and an _type
column.
If you want different names for your polymorphic relationship columns, feel free to call other schema builder methods individually.
Example:
SchemaBuilder
SQL (MySQL)
Creates the necessary columns for a polymorphic relationship. It takes the name provided and creates an _id
and an _type
column. The only difference between this method and morphs
is that the columns created here are nullable.
If you want different names for your polymorphic relationship columns, feel free to call other schema builder methods individually.
Example:
SchemaBuilder
SQL (MySQL)
Creates the createdDate
and modifiedDate
TIMESTAMP
columns. It creates the columns as nullable.
If you want different names for your timestamp columns, feel free to call other schema builder methods individually.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a POINT
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a POLYGON
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
An escape hatch to directly insert any sql in to the statement.
Example:
SchemaBuilder
SQL (MySQL)
Create an auto-incrementing column using an unsigned SMALLINT
type. This column is also set as the primary key for the table.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a SMALLINT
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a SMALLMONEY
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
SQL (MSSQL)
Creates a nullable deletedDate
TIMESTAMP
column.
If you want different names for your timestamp column, feel free to call other schema builder methods individually.
Example:
SchemaBuilder
SQL (MySQL)
Creates a nullable deletedDate
timezone-specific TIMESTAMP
column.
If you want different names for your timestamp column, feel free to call other schema builder methods individually.
Example:
SchemaBuilder
SQL (SQL Server)
Create a column using a VARCHAR
equivalent type for your database. For databases that distinguish between unicode- and non-unicode string data types, this function will create a non-unicode string.
Example (with defaults):
SchemaBuilder
SQL (MySQL)
Example (with length):
SchemaBuilder
SQL (MySQL)
Create a column using a TEXT
equivalent type for your database. For databases that distinguish between unicode- and non-unicode string data types, this function will create a non-unicode text field.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a TIME
equivalent type for your database.
Example:
SchemaBuilder
SQL (Postgres)
Create a column using a timezone-specific TIME
equivalent type for your database.
Example:
SchemaBuilder
SQL (Postgres)
Create a column using a TIMESTAMP
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
Creates the createdDate
and modifiedDate
TIMESTAMP
columns.
If you want different names for your timestamp columns, feel free to call other schema builder methods individually.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a timezone-specific TIMESTAMP
equivalent type for your database.
Example:
SchemaBuilder
SQL (Postgres)
Creates the createdDate
and modifiedDate
timezone-specific TIMESTAMP
columns.
If you want different names for your timestamp columns, feel free to call other schema builder methods individually.
Example:
SchemaBuilder
SQL (Postgres)
Create an auto-incrementing column using an unsigned TINYINT
type. This column is also set as the primary key for the table.
Example:
SchemaBuilder
SQL (MySQL)
Create a column using a TINYINT
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a LONGTEXT
equivalent type for your database. For databases that distinguish between unicode- and non-unicode string data types, this function will create a unicode text field.
Example:
SchemaBuilder
SQL (MySQL)
SQL (MSSQL)
Create a unicode-enabled column using a MEDIUMTEXT
equivalent type for your database. For databases that distinguish between unicode- and non-unicode string data types, this function will create a unicode text field.
Example:
SchemaBuilder
SQL (MySQL)
SQL (MSSQL)
Create a column using a NVARCHAR
equivalent type for your database. For databases that distinguish between unicode- and non-unicode string data types, this function will create a unicode string.
Example (with defaults):
SchemaBuilder
SQL (MySQL)
SQL (MSSQL)
Example (with length):
SchemaBuilder
SQL (MySQL)
SQL (MSSQL)
Create a column using a NTEXT
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
SQL (MSSQL)
Create a column using a UNSIGNED BIGINT
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a UNSIGNED INTEGER
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a UNSIGNED MEDIUMINT
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a UNSIGNED SMALLINT
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
Create a column using a UNSIGNED TINYINT
equivalent type for your database.
Example (no precision):
SchemaBuilder
SQL (MySQL)
Example (with precision):
SchemaBuilder
SQL (MySQL)
SQL Server: Create a column using a uniqueidentifier
.
MySQL and Others: Create a column using a CHAR
equivalent type for your database and a length of 36. Used in conjunction with the CFML createUUID
method.
Example:
SchemaBuilder
MySQL (SQL Server)
SQL (MySQL)
This method allows you to create a table object.
The majority of the work comes from calling methods on the Blueprint
object. A Blueprint
defines the columns and indexes for your tables.
Example:
This would convert to the following SQL in MySQL:
Only one table can be created at a time. If you wanted to create multiple tables, you would call create
multiple times.
The callback
argument is where you define the schema of your table. It is passed a Blueprint
object. This is commonly aliased as table
in the callback. Blueprint
defines the field, index and constraint methods to build your table. You can find a comprehensive list of all available methods here for columns and here for indexes and constraints.
Returns the SQL that would be executed for the current query.
The bindings for the query are represented by question marks (?
) just as when using queryExecute
. qb can replace each question mark with the corresponding cfqueryparam
-compatible struct by passing showBindings = true
to the method.
If you want to show the SQL that would be executed for the update
, insert
, updateOrInsert
, or delete
methods, you can pass a toSQL = true
flag to those methods. Please see those individual methods for more information.
Executes a callback with a clone of the current query passed to it. Any changes to the passed query is ignored and the original query returned.
While not strictly a debugging method, tap
makes it easy to see the changes to a query after each call without introducing temporary variables.
Starting in cbDebugger 2.0.0 you can view all your qb queries for a request. This is enabled by default if you have qb installed. Make sure your debug output is configured correctly and scroll to the bottom of the page to find the debug output.
qb is set to log all queries to a debug log out of the box. To enable this behavior, configure LogBox to allow debug logging from qb's grammar classes.
qb can be quite chatty when executing many database queries. Make sure that this logging is only enabled for your development environments using ColdBox's environment controls.
ColdBox Interception Points can also be used for logging, though you may find it easier to use LogBox. See the documentation for qb's Interception Points for more information.
QB ships with a schema builder to help you build your database objects. This provides a few benefits:
The syntax is expressive and fluent, making it easy to understand what is being executed
The syntax is database-agnostic. Specific quirks are isolated in a Grammar file, making it easy to migrate between engines.
You start with a SchemaBuilder
object. The SchemaBuilder
takes the same Grammar that a QueryBuilder
takes.
Note: the
SchemaBuilder
is a transient, and a new one should be created for each operation.
The SchemaBuilder
has four main methods to start your database object creation:
Create a new table in the database.
The majority of the work comes from calling methods on the Blueprint
object. A Blueprint
defines the columns and indexes for your tables.
Example:
SchemaBuilder
SQL (MySQL)
Alter an existing table in the database.
In addition to using the columns and indexes off of the passed-in Blueprint
object, the Blueprint
contains helpers such as addConstraint
, removeConstraint
, addColumn
, renameColumn
, and dropColumn
to assist in altering existing tables.
Example:
SchemaBuilder
SQL (MySQL)
Drop a table from the database.
Example:
SchemaBuilder
SQL (MySQL)
SchemaBuilder
as well:rename
Rename a table from an old name to a new name
Example:
SchemaBuilder
SQL (MySQL)
hasTable
Check if a table exists in the database.
Example:
SchemaBuilder
SQL (MySQL)
hasColumn
Check if a column exists in a table in the database.
Example:
SchemaBuilder
SQL (MySQL)
A TableIndex
can be created directly from a Blueprint
or from a existing Column
. The TableIndex
includes methods for further configuring the index which is required when defining foreign keys.
Set the referencing column for a foreign key relationship. For example, id
for a country_id
column.
Example:
SchemaBuilder
SQL (MySQL)
Sets the referencing table for a foreign key relationship. For example, countries
for a country_id
column.
Example:
SchemaBuilder
SQL (MySQL)
Set the strategy for updating foreign keys when the parent key is updated.
Example:
SchemaBuilder
SQL (MySQL)
Set the strategy for updating foreign keys when the parent key is deleted.
Example:
SchemaBuilder
SQL (MySQL)
When from the Blueprint
object, a Column
object is returned. This column
gives you access to a few modifier commands to further configure the column.
Attach a comment to the column.
Example:
SchemaBuilder
SQL (MySQL)
Sets a default value for the column.
Note: The value is not escaped, allowing you to specify functions like NOW()
or literals like 1
. To specify a literal string, wrap the value in quotes.
Example:
SchemaBuilder
SQL (MySQL)
Sets the column to allow null values.
All columns are created as NOT NULL
by default. As such, there is no notNull
method.
Example:
SchemaBuilder
SQL (MySQL)
Adds the column as a primary key for the table.
Example:
SchemaBuilder
SQL (MySQL)
Creates a foreign key constraint for the column.
Example:
SchemaBuilder
SQL (MySQL)
Sets the column as unsigned.
Example:
SchemaBuilder
SQL (MySQL)
Sets the column to have the UNIQUE constraint.
Example:
SchemaBuilder
SQL (MySQL)
Sets the column to have the a default value of CURRENT_TIMESTAMP
.
Example:
SchemaBuilder
SQL (Postgres)
Sometimes you want to add constraints on a table level, rather than a column level. The following methods will let you accomplish that.
Create a generic index from one or more columns.
Example:
SchemaBuilder
SQL (MySQL)
Example:
SchemaBuilder
SQL (MySQL)
Create a primary key constraint from one or more columns.
Example:
SchemaBuilder
SQL (MySQL)
Create a unique constraint from one or more columns.
Example:
SchemaBuilder
SQL (MySQL)
The alter method loads up an existing table in order to make modifications. These modifications may include adding, renaming, or dropping columns and constraints.
To begin altering an existing table, call the alter
method off of the SchemaBuilder
. This method takes a callback as the second parameter that is passed a Blueprint
object, much like the method.
Calling multiple methods inside a single
alter
callback creates multiple SQL statements to be executed. qb takes care of this execution for you by default.
The following methods off of Blueprint
let you modify the table inside the callback:
Add a new column to an existing table. Takes a Column
instance as the only argument.
Any instance of Column
is valid like those returned by the (integer
, string
, etc.) as well as the (unsigned
, nullable
, etc.).
Example:
SchemaBuilder
SQL (MySQL)
An escape hatch to directly insert any sql in to the statement.
Example:
SchemaBuilder
SQL (MySQL)
Drop a column on an existing table.
Example:
SchemaBuilder
SQL (MySQL)
Modify an existing column on a table.
Example:
SchemaBuilder
SQL (MySQL)
Rename a column on a table. A full Column
instance is required as the second argument for Grammars that need to redeclare the column definition when renaming.
Example:
SchemaBuilder
SQL (MySQL)
Example:
SchemaBuilder
SQL (MySQL)
Drop an existing table constraint.
Example:
SchemaBuilder
SQL (MySQL)
Rename an existing table constraint.
Example:
SchemaBuilder
SQL (MySQL)
Rename an existing table.
Example:
SchemaBuilder
SQL (MySQL)
An alias for renameTable
.
Example:
SchemaBuilder
SQL (MySQL)
returnFormat
refers to the transformation your executed query makes (if any) before being returned to you. You can choose one of three return formats:
"array"
"query"
A custom function
By default, qb returns an array of structs as the result of your query. This is the same as specifying array
as your returnFormat
:
You can get the original query object that CFML generates by setting the returnFormat
to query
:
If you want complete control over your return result, you can provide a function as a returnFormat
. The results of the function will be returned as the results of the builder.
A struct of column and value pairs to update. These column and value pairs are appended to any already set with the method.
A convenience argument for `where( "id", "=", arguments.id ). The query can be constrained by normal methods as well.
The primaryKey
method returns a Additional methods can be chained off of it.
IMPORTANT: Additional configuration of the foreign constraint is done by calling methods on the returned
Create a foreign key constraint from one or more columns. Follow up this call with calls to the TableIndex
's and methods.
Add an index or key to an existing table. Any TableIndex
instance is valid, like those created by the (unique
, index
, primaryKey
, etc.).
Name
Type
Description
sql
String
The SQL string to execute.
bindings
Struct
The struct of bindings (keys and values) for the query.
options
Struct
Any options to pass along to queryExecute
.
returnObject
String
The type to return: query
or result
.
Name
Type
Description
sql
String
The SQL string to execute.
bindings
Struct
The struct of bindings (keys and values) for the query.
options
Struct
Any options to pass along to queryExecute
.
returnObject
String
The type to return: query
or result
.
query
Query | null
The query object or null
if there isn't one.
result
Struct
The query result struct.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
indexName
string
false
The name for the primary key index. If no name is passed in, the name will be dynamically created based off of the table name and column name.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
length
numeric
false
1
The length for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
length
numeric
false
1
The length for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
length
numeric
false
10
The length of the column.
precision
numeric
false
0
The precision of the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
length
numeric
false
10
The length of the column.
precision
numeric
false
0
The precision of the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
indexName
string
false
The name for the primary key index. If no name is passed in, the name will be dynamically created based off of the table name and column name.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
indexName
string
false
The name for the primary key index. If no name is passed in, the name will be dynamically created based off of the table name and column name.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
10
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The prefix for the polymorphic columns.
Argument
Type
Required
Default
Description
name
string
true
The prefix for the polymorphic columns.
Argument
Type
Required
Default
Description
No arguments
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
sql
string
true
The sql to insert directly into the statement.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
indexName
string
false
The name for the primary key index. If no name is passed in, the name will be dynamically created based off of the table name and column name.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
No arguments
Argument
Type
Required
Default
Description
No arguments
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
length
numeric
false
255
The length of the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
No arguments
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
No arguments
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
indexName
string
false
The name for the primary key index. If no name is passed in, the name will be dynamically created based off of the table name and column name.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
length
numeric
false
255
The length of the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
precision
numeric
false
The precision for the column.
Argument
Type
Required
Default
Description
name
string
true
The name for the column.
Argument
Type
Required
Default
Description
table
string
true
The name of the table to create.
callback
function
true
A callback function used to define the table body. It is passed a Blueprint
as the only argument.
options
struct
false
{}
Options to pass to queryExecute
.
execute
boolean
false
true
Run the query immediately after building it.
Name
Type
Required
Default
Description
showBindings
boolean
false
​false
If true, the bindings for the query will be substituted back in where the question marks (?
) appear.
Name
Type
Required
Default
Description
callback
Function
true
​
A function to execute with a clone of the current query.
Argument
Type
Required
Default
Description
table
string
true
The name of the table to create.
callback
function
true
A callback function used to define the table body. It is passed a Blueprint
as the only argument.
options
struct
false
{}
Options to pass to queryExecute
.
execute
boolean
false
true
Run the query immediately after building it.
Argument
Type
Required
Default
Description
table
string
true
The name of the table to alter.
callback
function
true
A callback function used to define the changes to the table. It is passed a Blueprint
as the only argument.
options
struct
false
{}
Options to pass to queryExecute
.
execute
boolean
false
true
Run the query immediately after building it.
Argument
Type
Required
Default
Description
table
string
true
The name of the table to drop.
options
struct
false
{}
Options to pass to queryExecute
.
execute
boolean
false
true
Run the query immediately after building it.
Argument
Type
Required
Default
Description
from
string
true
The old table name.
to
string
true
The new table name.
options
struct
false
{}
Options to pass to queryExecute
.
execute
boolean
false
true
Run the query immediately after building it.
Argument
Type
Required
Default
Description
name
string
true
The name of the table to check.
options
struct
false
{}
Options to pass to queryExecute
.
execute
boolean
false
true
Run the query immediately after building it.
Argument
Type
Required
Default
Description
table
string
true
The name of the table to check for the column in.
column
string
true
The column to check for in the table.
options
struct
false
{}
Options to pass to queryExecute
.
execute
boolean
false
true
Run the query immediately after building it.
Argument
Type
Required
Default
Description
columns
any
true
A column or array of columns that represents the foreign key reference.
Argument
Type
Required
Default
Description
table
string
true
The referencing table name.
Argument
Type
Required
Default
Description
option
string
true
The strategy to use. Available values are: RESTRICT, CASCADE, SET NULL, NO ACTION, SET DEFAULT
Argument
Type
Required
Default
Description
option
string
true
The strategy to use. Available values are: RESTRICT, CASCADE, SET NULL, NO ACTION, SET DEFAULT
Argument | Type | Required | Default | Description |
value | string |
| The default value. |
Argument | Type | Required | Default | Description |
No arguments |
Argument | Type | Required | Default | Description |
indexName | string |
| A derived name built from the table name and column name. | The name to use for the primary key constraint. |
Argument | Type | Required | Default | Description |
value | string |
| The default value. |
Argument | Type | Required | Default | Description |
No arguments |
Argument | Type | Required | Default | Description |
No arguments |
Argument | Type | Required | Default | Description |
No arguments |
Argument | Type | Required | Default | Description |
columns | string or array |
| The column or array of columns that references a key or keys on another table. |
name | string |
| A generated name consisting of the table name and column name(s). | The name of the foreign key constraint. |
Argument | Type | Required | Default | Description |
columns | string or array |
| The column or array of columns that make up the primary key. |
name | string |
| A generated name consisting of the table name and column name(s). | The name of the primary key constraint. |
Argument | Type | Required | Default | Description |
columns | string or array |
| The column or array of columns that make up the unique constraint. |
name | string |
| A generated name consisting of the table name and column name(s). | The name of the unique constraint. |
Argument | Type | Required | Default | Description |
sql | string |
| The sql to insert directly into the statement. |
Argument | Type | Required | Default | Description |
name | string |
| The name of the column to drop. |
Argument | Type | Required | Default | Description |
name | string |
| The name of the column to modify. |
column |
|
| A column object to replace the named column. |
Argument | Type | Required | Default | Description |
name | string |
| The current name of a column. |
column |
|
| A column object with the new column name and definition. |
Argument | Type | Required | Default | Description |
constraint |
|
| The |
Argument | Type | Required | Default | Description |
name | string OR |
| The name of the constraint to drop. You can alternatively pass a |
Argument | Type | Required | Default | Description |
oldName | string OR |
| The old or current name of the constraint to rename. You can alternatively pass a |
newName | string OR |
| The new name of the constraint. You can alternatively pass a |
Argument | Type | Required | Default | Description |
oldName | string |
| The old or current name of the table to rename. |
newName | string |
| The new name of the table. |
Argument | Type | Required | Default | Description |
oldName | string |
| The old or current name of the table to rename. |
newName | string |
| The new name of the table. |
references
onTable
Argument | Type | Required | Default | Description |
comment | string |
| The comment text. |
Argument | Type | Required | Default | Description |
columns | string or array |
| The column or array of columns that make up the index. |
name | string |
| A generated name consisting of the table name and column name(s). | The name of the index constraint. |
Argument | Type | Required | Default | Description |
table | string |
| The name of the table to alter. |
callback | function |
| A callback function used to define the alterations to the table. It is passed a |
options | struct |
|
| Options to pass to |
execute | boolean |
|
| Run the query immediately after building it. |
Argument | Type | Required | Default | Description |
column |
|
| A column object to add to the table. |
Argument | Type | Required | Default | Description |
table | string |
| The name of the table to drop. |
options | struct |
|
| Options to pass to |
execute | boolean |
|
| Run the query immediately after building it. |
Argument | Type | Required | Default | Description |
table | string |
| The name of the table to drop. |
options | struct |
|
| Options to pass to |
execute | boolean |
|
| Run the query immediately after building it. |