Standalone SQL template
This guide assumes familiarity with:
With Waddler you can also use an sql
without a database connections in cases where you want to just build a query
or compose a part of a query to reuse it in different places. Let’s check both scenarios
Building a query string and params without a database conenction
import { sql } from "waddler/mssql-core"
// You can then reuse this query in other sql statements
const sqlQuery = sql`select ${sql.identifier("id")} from ${sql.identifier("users")};`;
console.log(sqlQuery.toSQL());
{
sql: "select [id] from [users];",
params: [],
}
Building parts of a query in common functions and use it in a main sql query
// sql-builder.ts
import { SQLQuery } from "waddler";
import { sql } from "waddler/mssql-core";
export type Filters = {
email: string,
age: number,
}
export function buildFilters(filters: Filters): SQLQuery {
return sql`${sql.identifier('email')} = ${filters.email}
and ${sql.identifier('age')} = ${filters.age}`
}
// index.ts
import { waddler } from 'waddler/...'
import { buildFilters } from './sql-builder.ts'
const sql = waddler(process.env.DATABASE_URL);
await sql`select * from ${sql.identifier("users")}
where ${buildFilters({ email: 'test@gmail.com', age 21 })}`
select * from [users] where [email] = @p1 and [age] = @p2
-- params: ['test@gmail.com', 21]