Builder State
Last updated
This page explains where the query builder keeps its state and what that means for how you call it.
State Lives in Static Fields
MySQLPool has no instances: table(), where(), and the other builder methods modify static fields on the class and return the class itself (typeof MySQLPool) for chaining (src/MySQLPool.ts:20-30).| Field | Written by |
|---|---|
tableName, currentTarget | table() |
selectAry | select() |
joinAry | innerJoin(), leftJoin(), rightJoin() |
whereAry, bindingAry | where() |
orderAry | orderBy() |
queryLimit, queryOffset | limit(), offset() |
withTotal | total() |
setAry | increase(), update() |
Every Chain Starts with table()
Only
table() calls reset() to clear these fields (src/MySQLPool.ts:117-137). Running get(), update(), or another execution method does not clear them, so:- await MySQLPool.table("users").where("id", 1).get();
- // Wrong: reuses the previous table name and WHERE, so it queries id = 1 again
- await MySQLPool.where("status", "active").get();
- // Right
- await MySQLPool.table("users").where("status", "active").get();
currentTarget persists too: calling query(sql) without a target after table("x", "write") uses the write pool.Build and Run in One Expression
The builder state is shared by the whole process.
get(), insert(), update(), and upsert() read that state synchronously before their first await, so a chain written as one expression from table() to the execution method is not affected by other concurrent requests. Keep any await out of the middle of a chain:- // Wrong: another request can call table() during the await and reset the state
- const builder = MySQLPool.table("users").where("status", "active");
- const limit = await loadPageSize();
- const rows = await builder.limit(limit).get();
- // Right: resolve the inputs first, then build and run in one expression
- const pageSize = await loadPageSize();
- const users = await MySQLPool.table("users").where("status", "active").limit(pageSize).get();