Query Builder
Dataloom exposes a method called getQueryBuilder, which allows you to obtain a qb object. This object enables you to execute SQL queries directly from SQL scripts.
qb = loom.getQueryBuilder()
print(qb) # ? = Loom QB<mysql>
The qb object contains the method called run, which is used to execute SQL scripts or SQL queries.
ids = qb.run("select id from posts;", fetchall=True)
print(ids) # ? = [(1,), (2,), (3,), (4,)]
You can also execute SQL files. In the following example, we will demonstrate how you can execute SQL scripts using the qb. Let’s say we have an SQL file called qb.sql which contains the following SQL code:
We can use the query builder to execute the SQL as follows:
with open("qb.sql", "r") as reader:
sql = reader.read()
res = qb.run(
sql,
fetchall=True,
is_script=True,
)
print(res)
Tip
👍 Pro Tip: Executing a script using query builder does not return a result. The result value is always None.
The run method takes the following as arguments:
Argument |
Description |
Type |
Required |
Default |
|---|---|---|---|---|
|
SQL query to execute. |
|
Yes |
|
|
Parameters for the SQL query. |
|
|
|
|
Whether to fetch only one result. |
|
|
|
|
Whether to fetch multiple results. |
|
|
|
|
Whether to fetch all results. |
|
|
|
|
Whether the query is a mutation (insert, update, delete). |
|
|
|
|
Whether the query is a bulk operation. |
|
|
|
|
Whether to return affected rows. |
|
|
|
|
Type of operation being performed. |
|
|
|
|
Verbosity level for logging . Set this option to |
|
|
|
|
Whether the SQL is a script. |
|
|
|
Why Use Query Builder?
The query builder empowers developers to seamlessly execute
SQLqueries directly.While Dataloom primarily utilizes
subqueriesfor eager data fetching on models, developers may prefer to employ JOIN operations, which are achievable through theqbobject.