Getting Started
Installation
Install the package, connect it to your database client, and run your first query in minutes.
Install package
Use the package manager you prefer.
npm install @gntrees/sql-builder pg
pnpm add @gntrees/sql-builder pg
yarn add @gntrees/sql-builder pgnpm install @gntrees/sql-builder pg
pnpm add @gntrees/sql-builder pg
yarn add @gntrees/sql-builder pgInitial setup
The simplest setup is passing your database URL directly to the builder.
import { sqlBuilder } from "@gntrees/sql-builder/pg"
sqlBuilder("postgresql://user:password@localhost:5432/app")import { sqlBuilder } from "@gntrees/sql-builder/pg"
sqlBuilder("postgresql://user:password@localhost:5432/app")Simple use case
Fetch active users, sorted by name, with a limit.
1const query = await q
2 .select(
3 q.c("users.id"),
4 q.c("users.name"),
5 q.c("users.email"),
6 )
7 .from(q.t("users"))
8 .where(q.c("users.status").op("=").v("active"))
9 .orderBy(q.c("users.name"))
10 .limit(10)
11 .execute()
12
13console.log(query)1const query = await q
2 .select(
3 q.c("users.id"),
4 q.c("users.name"),
5 q.c("users.email"),
6 )
7 .from(q.t("users"))
8 .where(q.c("users.status").op("=").v("active"))
9 .orderBy(q.c("users.name"))
10 .limit(10)
11 .execute()
12
13console.log(query)Custom handlers
Use these when you want full control over parameter formatting and query execution.
import { sqlBuilder } from "@gntrees/sql-builder/pg"
import { Pool } from "pg"
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
})
sqlBuilder()
// If you want to override the default execution logic.
.setExecutionHandler(async ({ sql, parameters }) => {
// implement your custom execution logic here.
const result = await pool.query(sql, parameters)
console.log("Executed SQL:", sql)
return result.rows
})
// If you want to override the default parameter formatting.
.setFormatParamHandler(({ index, value, type }) => {
// implement your custom formatting logic here. here's a simple example:
if (type === "identifier") {
return '"' + String(value).replace(/"/g, '""') + '"'
}
if (type === "literal") {
return "$" + index
}
return String(value) // fallback for other types
})import { sqlBuilder } from "@gntrees/sql-builder/pg"
import { Pool } from "pg"
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
})
sqlBuilder()
// If you want to override the default execution logic.
.setExecutionHandler(async ({ sql, parameters }) => {
// implement your custom execution logic here.
const result = await pool.query(sql, parameters)
console.log("Executed SQL:", sql)
return result.rows
})
// If you want to override the default parameter formatting.
.setFormatParamHandler(({ index, value, type }) => {
// implement your custom formatting logic here. here's a simple example:
if (type === "identifier") {
return '"' + String(value).replace(/"/g, '""') + '"'
}
if (type === "literal") {
return "$" + index
}
return String(value) // fallback for other types
})