bun-query-builder

API Reference

On this page 34

Complete API reference for bun-query-builder.

Core Functions

createQueryBuilder

Create a new query builder instance.

import { createQueryBuilder, buildDatabaseSchema, buildSchemaMeta } from 'bun-query-builder'

const db = createQueryBuilder<typeof schema>({
  schema: buildDatabaseSchema(models),
  meta: buildSchemaMeta(models),
  hooks?: {
    beforeCreate?: (ctx) => Promise<void>
    afterCreate?: (ctx) => Promise<void>
    beforeUpdate?: (ctx) => Promise<void>
    afterUpdate?: (ctx) => Promise<void>
    beforeDelete?: (ctx) => Promise<void>
    afterDelete?: (ctx) => Promise<void>
  }
})

buildDatabaseSchema

Build a database schema from model definitions.

const schema = buildDatabaseSchema(models)

buildSchemaMeta

Build schema metadata from model definitions.

const meta = buildSchemaMeta(models)

Query Builder Methods

SELECT Operations

MethodDescriptionExample
selectFrom(table)Start a SELECT querydb.selectFrom('users')
select(columns)Select specific columns.select(['id', 'name'])
selectRaw(fragment)Select with raw SQL (one fragment, no bindings).selectRaw(raw`COUNT(*) as count`)
distinct()Add DISTINCT modifier.distinct()
distinctOn(columns)DISTINCT ON (PostgreSQL).distinctOn('email')

WHERE Clauses

MethodDescriptionExample
where(condition)Add WHERE clause.where({ active: true })
where(col, op, val)WHERE with operator.where('age', '>=', 18)
andWhere(...)AND condition.andWhere('role', '=', 'admin')
orWhere(...)OR condition.orWhere('role', '=', 'mod')
whereIn(col, vals)WHERE IN.whereIn('id', [1, 2, 3])
whereNotIn(col, vals)WHERE NOT IN.whereNotIn('status', ['banned'])
whereBetween(col, a, b)WHERE BETWEEN.whereBetween('age', 18, 65)
whereNull(col)WHERE IS NULL.whereNull('deleted_at')
whereNotNull(col)WHERE IS NOT NULL.whereNotNull('email')
whereColumn(a, op, b)Compare columns.whereColumn('a', '=', 'b')
whereRaw(fragment)Raw WHERE clause (one fragment, no bindings).whereRaw(raw`LOWER(name) = ${name}`)

JOIN Operations

MethodDescriptionExample
join(table, a, op, b)INNER JOIN.join('posts', 'users.id', '=', 'posts.user_id')
leftJoin(...)LEFT JOIN.leftJoin('posts', ...)
rightJoin(...)RIGHT JOIN.rightJoin('posts', ...)
crossJoin(table)CROSS JOIN.crossJoin('categories')

ORDER & LIMIT

MethodDescriptionExample
orderBy(col, dir)ORDER BY.orderBy('name', 'asc')
orderByDesc(col)ORDER BY DESC.orderByDesc('created_at')
latest()Order by created_at DESC.latest()
oldest()Order by created_at ASC.oldest()
inRandomOrder()Random order.inRandomOrder()
limit(n)LIMIT.limit(10)
offset(n)OFFSET.offset(20)

Aggregations

MethodDescriptionExample
count()COUNT(*)await db.selectFrom('users').count()
sum(col)SUMawait db.selectFrom('orders').sum('total')
avg(col)AVGawait db.selectFrom('users').avg('age')
min(col)MINawait db.selectFrom('products').min('price')
max(col)MAXawait db.selectFrom('products').max('price')
groupBy(cols)GROUP BY.groupBy('department')
having(col, op, val)HAVING.having('count', '>', 5)

Execution Methods

MethodDescriptionExample
get()Execute and get all rowsawait query.get()
first()Get first rowawait query.first()
execute()Execute queryawait query.execute()
toSQL()Get SQL stringquery.toSQL()

INSERT Operations

MethodDescriptionExample
insertInto(table)Start INSERTdb.insertInto('users')
values(data)Set values.values({ name: 'John' })
returning(cols)Return columns.returning(['id'])
onConflict(col)ON CONFLICT.onConflict('email')
doUpdate(data)DO UPDATE.doUpdate({ name: 'John' })
doNothing()DO NOTHING.doNothing()
insertMany(table, rows)Bulk insertdb.insertMany('users', [...])

UPDATE Operations

MethodDescriptionExample
update(table)Start UPDATEdb.updateTable('users')
set(data)Set values.set({ active: false })
increment(col, n)Increment.increment('views', 1)
decrement(col, n)Decrement.decrement('stock', 1)
updateMany(table, where, set)Bulk updatedb.updateMany('users', {...}, {...})

DELETE Operations

MethodDescriptionExample
deleteFrom(table)Start DELETEdb.deleteFrom('users')
deleteMany(table, ids)Bulk deletedb.deleteMany('users', [1, 2, 3])

Relations

MethodDescriptionExample
with(relations)Eager load.with('posts')
withCount(relation)Count relation.withCount('comments')
has(relation)Has relation.has('posts')
doesntHave(relation)Missing relation.doesntHave('posts')
whereHas(rel, cb)Filter by relation.whereHas('posts', q => q.where(...))

Pagination

MethodDescriptionExample
paginate(perPage)Paginate resultsawait query.paginate(20)
simplePaginate(perPage)Simple paginationawait query.simplePaginate(20)
cursorPaginate(cursor, limit)Cursor paginationawait query.cursorPaginate(cursor, 20)

Chunking

MethodDescriptionExample
chunk(size, cb)Process in chunksawait query.chunk(100, cb)
chunkById(size, cb)Chunk by IDawait query.chunkById(100, cb)
eachById(cb)Process each by IDawait query.eachById(cb)

Caching

MethodDescriptionExample
cache(ttl?)Cache query.cache(5000)
clearQueryCache()Clear cacheclearQueryCache()
setQueryCacheMaxSize(n)Set cache sizesetQueryCacheMaxSize(500)

Soft Deletes

MethodDescriptionExample
withTrashed()Include soft deleted.withTrashed()
onlyTrashed()Only soft deleted.onlyTrashed()

Scopes

MethodDescriptionExample
scope(name)Apply model scope.scope('active')

Transactions

transaction

Execute queries in a transaction.

await db.transaction(async (trx) => {
  await trx.insertInto('users').values({...}).execute()
  await trx.updateTable('accounts').set({...}).execute()
})

Transaction Options

await db.transaction(async (trx) => {
  // ...
}, {
  isolationLevel: 'serializable',
  retries: 3,
  backoff: 'exponential',
  onRetry: (attempt, error) => console.log(`Retry ${attempt}`)
})

Migrations

generateMigration

Generate a migration from models.

import { generateMigration } from 'bun-query-builder'

const migration = await generateMigration('./models', {
  dialect: 'postgres',
  apply: true,
  full: true
})

executeMigration

Run every pending migration file in the corpus and record each one.

import { executeMigration } from 'bun-query-builder'

// The configured `migrationDir`.
await executeMigration()

// A corpus assembled from several directories — the application's own
// migrations plus the ones each installed package ships. Files from every
// directory are ordered together by file name, so names must be unique
// across the whole run.
await executeMigration([
  './database/migrations',
  './node_modules/loghq/database/migrations',
])

Seeders

runSeeders

Run all seeders.

import { runSeeders } from 'bun-query-builder'

await runSeeders({
  seedersDir: './database/seeders',
  verbose: true
})

runSeeder

Run a specific seeder.

import { runSeeder } from 'bun-query-builder'

await runSeeder('UserSeeder', { verbose: true })

CLI Commands

CommandDescription
qb make:model <name>Generate a model
qb migrateRun migrations
qb migrate:rollbackRollback migrations
qb migrate:freshFresh migration
qb seedRun seeders
qb make:seeder <name>Generate a seeder
qb db:infoDatabase info
qb consoleInteractive REPL
qb cache:clearClear query cache

Types

WhereOperator

type WhereOperator = '=' | '!=' | '<' | '>' | '<=' | '>=' | 'like' | 'in' | 'not in' | 'is' | 'is not'

SortDirection

type SortDirection = 'asc' | 'desc'

Hook Context

interface CreateHookContext {
  table: string
  data: Record<string, any>
}

interface UpdateHookContext {
  table: string
  data: Record<string, any>
  where: Record<string, any>
}

interface DeleteHookContext {
  table: string
  where: Record<string, any>
}

Released under the MIT License.