Database

Query Builder

Fluent SQL query builder with parameterized values, grouped where clauses, joins, soft deletes and identifier safety checks.

2 min readUpdated DocumentationEdit this page
On this page5

Create a builder

QueryBuilder runs against a connection's driver. Pass the driver type so placeholders match the database (? for SQLite/MySQL, $1, $2, … for Postgres).

TypeScript
TS
1import { createConnection, QueryBuilder } from '@axiljs/orm'
2
3const db = await createConnection({ driver: 'postgres', url: process.env.DATABASE_URL })
4const qb = () => new QueryBuilder(db.getDriver(), 'postgres')

SELECT

TypeScript
TS
1const users = await qb()
2  .select('id', 'name', 'email')
3  .from('users')
4  .where('active', true)
5  .orderBy('name', 'ASC')
6  .limit(10)
7  .all()
8
9const user  = await qb().select('*').from('users').where('id', 1).first()
10const total = await qb().from('users').where('age', '>', 18).count()

Also available: join / leftJoin / rightJoin, orWhere, grouped where(q => …), whereIn, whereNotIn, whereNull, whereNotNull, whereBetween, whereNotBetween, whereLike, groupBy, having, offset, useSoftDeletes() / withTrashed() / onlyTrashed(), and toSQL() to inspect the generated SQL and params.

INSERT

TypeScript
TS
await qb().insert('users', { name: 'Tariq', email: 'tariq@axiljs.dev' }).execute()

UPDATE

TypeScript
TS
await qb().update('users').set({ name: 'Tariq Mehmood' }).where('id', 1).execute()

DELETE

TypeScript
TS
await qb().delete('users').where('id', 1).execute()

Warning

All values are parameterized. Column names in where*() and orderBy() are validated and throw UnsafeIdentifierError if unsafe, but select(), groupBy(), having() and join() are not validated. Never pass user input to them, and never concatenate user input into SQL.

Tip

Models extending BaseModel have their own builder via Model.query() (exported as ModelQueryBuilder), with the same where clauses.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY