Query builder
Preface
The query builder is a class which is used to build up a query for execution later. For example if you need multiple wheres for a query you can chain them together on this QueryBuilder
class. The class is then modified until you want to execute the query. Models use the query builder under the hood to make all of those calls. Many model methods actually return an instance of QueryBuilder
so you can continue to chain complex queries together.
Using the query builder class directly allows you to make database calls without needing to use a model.
Getting the QueryBuilder class
To get the query builder class you can simply import the query builder. Once imported you will need to pass the connection_details
dictionary you store in your config.database
file:
You can also switch or specify connection on the fly using the on
method:
You can then start making any number of database calls.
Models
If you would like to use models you should reference the Models documentation. This is an example of using models directly with the query builder.
By default, the query builder will return dictionaries or lists depending on the result set. Here is an example of a result using only the query builder:
Fetching Records
Select
First
You can easily get the first record:
All Records
You can also simply fetch all records from a table:
The Get Method
Once you start chaining methods you should call the get()
method instead of the all()
method to execute the query.
For example, this is correct:
And this is wrong:
Wheres
You may also specify any one of these where statements:
The simplest one is a "where equals" statement. This is a query to get where username
equals Joe
AND age
equals 18
:
You can also use a dictionary to build the where method:
You can also specify comparison operators:
Where Null
Another common where clause is checking where a value is NULL
:
This will fetch all records where the admin column is NULL
.
Or the inverse:
This selects all columns where admin is NOT NULL
.
Where In
In order to fetch all records within a certain list we can pass in a list:
This will fetch all records where the age is either 18
, 21
or 25
.
Where Like
You can do a WHERE LIKE or WHERE NOT LIKE query:
Subqueries
You can make subqueries easily by passing a callable into the where method:
Conditional Queries
Sometimes you need to specify conditional statements and run queries based on the conditional values.
For example you may have code that looks like this:
Instead of writing the code above you can use the when
method. This method accepts a conditional as the first parameter and a callable as the second parameter. The code above would look like this:
If the conditional passed in the first parameter is not truthy then the second parameter will be ignored.
Limits / Offsets
It's also very simple to use both limit and/or offset a query.
Here is an example of a limit:
Here is an example of an offset:
Or here is an example of using both:
Between
You may need to get all records where column values are between 2 values:
Group By
You may want to group by a specific column:
Having
Having clauses are typically used during a group by. For example, returning all users grouped by salary where the salary is greater than 0:
You may also specify the same query but where the sum of the salary is greater than 50,000
Inner Joining
Joining is a way to take data from related tables and return it in 1 result set as well as filter anything out that doesn't have a relationship on the joining tables.
This join will create an inner join.
You can also choose a left join:
Left Join
and a right join:
Right Join
Increment
There are times where you really just need to increment a column and don't need to pull any additional information. A lot of the incrementing logic is hidden away:
Decrementing is also similiar:
Decrement
Aggregates
There are several aggregating methods you can use to aggregate columns:
Sum
Average
Count
Max
Min
Raw Queries
If some queries would be easier written raw you can easily do so for both selects and wheres:
Chunking
If you need to loop over a lot of results then consider chunking. A chunk will only pull in the specified number of records into a generator:
Getting SQL
If you want to find out the SQL that will run when the command is executed. You can use to_sql()
. This method returns the full query and is not the query that gets sent to the database. The query sent to the database is a "qmark query". This to_sql()
method is mainly for debugging purposes.
See the section below for more information on qmark queries.
Getting Qmark
Qmark is essentially just a normal SQL statement except the query is replaced with question marks. The values that should have been in the position of the question marks are stored in a tuple and sent along with the qmark query to help in sql injection. The qmark query is the actual query sent using the connection class.
Updates
Updating Records
You can update many records.
Deletes
Deleting Records
You can delete many records as well. For example, deleting all records where active is set to 0.
Available Methods
aggregate
all
between
count
create
decrement
delete
first
get
group_by
having
increment
join
left_join
limit
max
not_between
offset
order_by
right_join
select
select_raw
sum
to_qmark
to_sql
update
where
where_column
where_exists
where_has
where_in
where_not_in
where_not_null
where_null
where_raw
Last updated