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...
We welcome all types of contributions, following the all-contributors specification. And please take a look at our wonderful contributors on the README!
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.
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
.
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()
.
Usage## Retrieving Results
The get
method returns an Array
of Structs
by default. Both columns
and options
are optional.
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. This method will return the value of the column directly:
If you only need a single column for the first record returned, use the value
function:
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, e.g
Queries come in many varieties—from the basic to extremely complex. In order to provide you maximum flexibility there are several ways to define the source table for you query.
from()
methodThe most common method for defining the source table is using the from()
method. For the majority of queries, the from()
method is all you need. It's syntax is very easy:
This would return all columns from the users
table.
NOTE: Alternatively, you can use the
table()
method as an alias tofrom()
.
Optionally you can specify an alias for the table by using the syntax:
This would parse the string users as u
and convert it into the correct syntax for current grammar.
Alternatively, you can use the ANSI SQL shorthand and leave out the as
keyword:
from
clause using raw SQLSometimes 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.
If you need complete control over your from
clause you can use the fromRaw()
.
For example, to provide a table hint for a SQL Server query you could use:
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.
NOTE: Using the
fromRaw()
will most likely tie your code to a specific database, so think carefully before using thefromRaw()
method if you want your project to be database agnostic.
from
clauseMany 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.
You can build queries that comprise of derived tables by using the fromSub()
method, which requires two arguments:
The alias to use for the derived table (which is how you reference your query)
Either a QueryBuilder instances or closure defining the subquery
The simplest way to create a derived table is by using a closure to define the subquery:
Alternatively you can supply a QueryBuilder instance to the fromSub()
method:
You can influence the return format of the result in two ways.
By default, qb returns an array of structs as the result of your query. This is the same as specifiying 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 closure as a returnFormat
. The results of the closure will be returned as the results of the builder.
Of course, you may not always want to select all columns from a database table. Using the from
method, you can specify a custom from
clause for the query:
Individual columns can contain fully-qualified names (i.e. "some_table.some_column"), fully-qualified names with table aliases (i.e. "alias.some_column"), and even set column aliases themselves (i.e. "some_column AS c"). Columns can be a single column, a list or columns (comma-separated), or an array of columns.
The distinct
method allows you to force the query to return distinct results:
(Note that distinct
applies to the entire query, not just certain fields.)
If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect
method:
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
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 11+
Lucee 4.5+
qb supports four major database grammars:
MSSQL (MSSQLGrammar
)
MySQL (MySQLGrammar
)
Oracle (OracleGrammar
)
Postgres (PostgresGrammar
)
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:
You can influence the return format of the result in two ways.
By default, qb returns an array of structs as the result of your query. You can turn this behavior off by setting builder.setReturningArrays( false )
for one-offs or setting returningArrays = false
in your ColdBox config.
If you want complete control over your return result, you can provide a closure as a returnFormat
. The results of the closure will be returned as the results of the builder.
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:
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
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:
By default, the correct sql type will be inferred from your parameters. 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 always pass a struct with the parameters you would pass to cfqueryparam
.
You may use the where
method on a query builder instance to add where
clauses to the query. The most basic call to where
requires three arguments. The first argument is the name of the column. The second argument is an operator, which can be any of the database's supported operators. Finally, the third argument is the value to evaluate against the column.
For example, here is a query that verifies the value of the "age" column is greater than or equal to 18:
For convenience, if you simply want to verify that a column is equal to a given value, you may pass the value directly as the second argument to the where
method:
Of course, you may use a variety of other operators when writing a where
clause:
You may chain where constraints together as well as add or
clauses to the query. The orWhere
method accepts the same arguments as the where
method:
whereBetween / whereNotBetween
The whereBetween
method verifies that a column's value is between two values:
The whereNotBetween
method verifies that a column's value lies outside of two values:
whereIn / whereNotIn (sub-queries)
The whereIn
method verifies that a given column's value is contained within the provided array or QueryBuilder object:
Array:
QueryBuilder (fetch all users whose age is in the all_ages table with a value between 17 and 21):
The whereNotIn
method verifies that the given column's value is not contained in the provided array of QueryBuilder object:
whereNull / whereNotNull
The whereNull
method verifies that the value of the given column is NULL
:
The whereNotNull
method verifies that the column's value is not NULL
:
whereExists / whereNotExists
The whereExists
method:
whereColumn
The whereColumn
method may be used to verify that two columns are equal:
You may also pass a comparison operator to the method:
WHERE (a = ? OR b = ?) AND c = ?
Here is an example of how to strategically place parentheses with OR
using closures.
The query builder also provides a variety of aggregate methods such as count
, max
, min
, and sum
. You may call any of these methods after constructing your query:
Of course, you may combine these methods with other clauses:
The orderBy
method allows you to sort the result of the query by a given column. The first argument to the orderBy
method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either asc
or desc
:
If you want to order by multiple columns, you can call orderBy
multiple times.
The groupBy
and having
methods may be used to group the query results. The having
method's signature is similar to that of the where
method:
To limit the number of results returned from the query, you may use the take
method:
Alternatively, you may use the limit
method:
To offset the number of results returned from the query, use the offset
method:
Combine limit
and offset
in one method. Pass the current page number and the number of results per page (limit
) and we'll calculate the rest.
The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join
method on a query builder instance. The first argument passed to the join
method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. Of course, as you can see, you can join to multiple tables in a single query:
Sometimes you need more control over your join
clause in order to add grammar specific instructions, such as adding SQL Server table hints to your queries.
If you need complete control over your join
clause you can use the joinRaw()
method
Since the joinRaw()
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.
NOTE: Using the
joinRaw()
will most likely tie your code to a specific database, so think carefully before using thejoinRaw()
method if you want your project to be database agnostic.NOTE: All of the
join
methods have a*Raw
equivalent method. This means you can useleftJoinRaw()
,rightJoinRaw()
, etc.
For a compound join clause, pass in the name of the table as the first argument (just as before) but instead of passing the remaining arguments describing the single join clause, we'll pass a single closure with a joinClause
argument. Consider a (contrived) example where our users
and blogs
had to match not only ID
but also type
:
If you would like to perform a "left/right join" instead of an "inner join", use the leftJoin
/ rightJoin
method. The leftJoin
/ rightJoin
method has the same signature as the join
method:
To perform a "cross join" use the crossJoin
method with the name of the table you wish to cross join to. Cross joins generate a cartesian product between the first table and the joined table:
Complex queries often contain derived tables, which are temporal, subqueries defined inline within your SQL.
To join your main table to a derived table you can use the joinSub()
methods. Each join
method has a corresponding "sub" method which you can use when you need to use a derived table (i.e. leftJoinSub()
, rightJoinSub()
, etc).
These functions differ slightly than the normal join
methods, because the first two arguments specify:
The alias to use for the derived table (which is how you reference your query)
Either a QueryBuilder instances or closure defining the subquery
The query builder also lets you create union statements on your queries. When merging multiple queries together using a union statement, there are two methods you can use merge the queries together:
union() — This method builds a SQL statement using the ANSI SQL union
clause which combines two SQL queries into a single resultset 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.
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.
IMPORTANT: The QueryBuilder instances passed to a
union
statement cannot contain a defined order. Any use of theorderBy()
method on the unioned QueryBuilder instances will result in an exception. To order the results, add anorderBy()
call to the parent source Query Builder instance.
union
using a callbackThe easiest way to combine union the results of multiple queries is by using a callback to the union
methods:
Alternatively, you can use another Query Builder instance and pass it to the union
methods:
union all
If you want to make sure that all duplicate rows are returned, use the unionAll()
method instead of union()
:
union
queriesTo order a union
query, only the parent query object can contain an orderBy()
directive. If any of the Query Builder instances passed to a union
method contain an orderBy
directive an exception will be thrown when you attempt to either execute the query or generate the SQL.
The follow shows how to order the results:
NOTE: The
orderBy()
call does have to be after the calls to theunion
methods.
union
statementsYour query can contain multiple union
methods:
if
and else
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. A better way is to use the when
helper method.
when
We can rewrite the above query like so:
Nice. We keep chainability this way and reduce the number of temporary variables we need.
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
📝 📖
💬 💻
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 |
Base | AND | OR |
where() | andWhere() | orWhere() |
whereBetween() | andWhereBetween() | orWhereBetween() |
whereColumn() | andWhereColumn() | orWhereColumn() |
whereExists() | andWhereExists() | orWhereExists() |
whereIn() | andWhereIn() | orWhereIn() |
whereNotBetween() | andWhereNotBetween() | orWhereNotBetween() |
whereNotExists() | andWhereNotExists() | orWhereNotExists() |
whereNotIn() | andWhereNotIn() | orWhereNotIn() |
whereNotNull() | andWhereNotNull() | orWhereNotNull() |
whereNull() | andWhereNull() | orWhereNull() |
whereRaw() | andWhereRaw() | orWhereRaw() |
Name | Type | Required | Default | Description |
condition | boolean | true | The condition to switch on. |
onTrue | Closure | true | The callback to execute if the condition is true. It is passed the |
onFalse | Closure | false | function( q ) { return q; } | The callback to execute if the conditions is false. It is passed the |
At times you may need to duplicate a query. Perhaps you need the count of all the records before paginating it. Using clone
you have a performant way to duplicate a query
The query builder also provides an insert
method for inserting records into the database table. The insert
method accepts an array of column names and values:
You may even insert several records into the table with a single call to insert
by passing an array of structs. Each struct represents a row to be inserted into the table:
You can also insert records by strong typing them just like using cfqueryParam
. Just adhere to the same syntax: { value : "", cfsqltype : "" }
(https://cfdocs.org/cfqueryparam)
Certain grammars have the ability to return values from an insert statement. That can be useful if you use your built-in database functions to generate primary keys that you want to retrieve.
If you attempt to use returning
on grammars that do not support it, you will recieve a UnsupportedOperation
exception.
Of course, in addition to inserting records into the database, the query builder can also update existing records using the update
method. The update
method, like the insert
method, accepts an array of column and value pairs containing the columns to be updated. You may constrain the update
query using where
clauses:
You can also use Expressions inside an update statement:
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:
Common Table Expressions (CTEs) are powerful SQL concept that allow you to create re-usable temporal resultset, 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.
NOTE: Some database engines require the
recursive
keyword is implemented anytime at least one of your CTEs is recursive, but some database engines (e.g. SQL Server and Oracle) do not require the keyword. For engines that do not require therecursive
keyword the grammar will manage adding the keyword if necessary. If your query does use recursion, you should always use thewithRecursive()
method to avoid issues with other grammars.
Building a CTE is as easy as using the with()
method with a closure:
Alternatively, you can use a QueryBuilder instance instead of a closure:
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:
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
.
An easy way to get a new query builder is to use the newQuery
method available on the builder.
The newQuery
method will keep the current grammar, return format, and utils attached to the called query builder.
The query builder may also be used to delete records from the table via the delete
method. You may constrain delete
statements by adding where
clauses before calling the delete
method:
This utilizes the where clause on a column other than the ID:
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.
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)
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)
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)
The Blueprint
object has many column types available to construct your table schema. Additionally, you can modify the columns created and .
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 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 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)
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)
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 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 (MySQL)
Create a column using a TIMESTAMP
equivalent type for your database.
Example:
SchemaBuilder
SQL (MySQL)
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)
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)
A TableIndex
can be created directly from a or from a existing . 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)
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.).
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
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 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 | 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 |
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 |
name | string |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
length | numeric |
| 1 | The length for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
length | numeric |
| 1 | The length for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
length | numeric |
| 10 | The length of the column. |
precision | numeric |
| 0 | The precision of the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
length | numeric |
| 10 | The length of the column. |
precision | numeric |
| 0 | The precision of the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
indexName | string |
| 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 |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
indexName | string |
| 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 |
| The name for the column. |
precision | numeric |
| 10 | The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The prefix for the polymorphic columns. |
Argument | Type | Required | Default | Description |
name | string |
| The prefix for the polymorphic columns. |
Argument | Type | Required | Default | Description |
sql | string |
| The sql to insert directly into the statement. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
indexName | string |
| 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 |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
length | numeric |
| 255 | The length of the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
indexName | string |
| 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 |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
length | numeric |
| 255 | The length of the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
precision | numeric |
| The precision for the column. |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
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 |
table | string |
| The referencing table name. |
Argument | Type | Required | Default | Description |
option | string |
| The strategy to use. Available values are: RESTRICT, CASCADE, SET NULL, NO ACTION, SET DEFAULT |
Argument | Type | Required | Default | Description |
option | string |
| The strategy to use. Available values are: RESTRICT, CASCADE, SET NULL, NO ACTION, SET DEFAULT |
references
onTable
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. |
Argument | Type | Required | Default | Description |
columns | any |
| A column or array of columns that represents the foreign key reference. |
Columns |
Argument | Type | Required | Default | Description |
name | string |
| The name for the column. |
indexName | string |
| 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. |
Methods |
Argument | Type | Required | Default | Description |
comment | string |
| The comment text. |