Connect
Safe SQL
Why a value can never end a command and start another in NordBase, and how to write queries, names, lists and fragments the safe way.
The NordBase libraries have one goal for SQL: a value can never end a command and start another. Not by quoting rules or escaping, but by never putting a value into SQL text at all.
Why a value can never become a command
Every value is sent as a bind parameter. The library sends the SQL text with $1, $2 placeholders, and the values travel separately in the same message (PostgreSQL's extended query protocol). PostgreSQL parses the text first and only then receives the values, so a value is always data, whatever characters it contains.
This holds for quotes, semicolons, comments, backslashes, $$ and Unicode look-alike quotes. No library code path puts a value into SQL text.
The safe form is the short form
The main API is shaped like a template, so the shortest way to write a query is also the safe one.
// Node: a tagged template
const rows = await db.sql`select id, total from orders where customer_id = ${customerId}`# Python 3.14 or newer: a t-string
rows = db.sql(t"select id, total from orders where customer_id = {customer_id}")
# Older Python: named placeholders, parsed by the library
rows = db.sql("select id, total from orders where customer_id = {customer_id}", customer_id=customer_id)// Rust: a macro that turns {customer_id} into $1 at compile time
let rows = db
.query(sql!("select id, total from orders where customer_id = {customer_id}"))
.await?;All three send select id, total from orders where customer_id = $1 and the value of customer_id as parameter 1.
On Python older than 3.14, the library parses {name} placeholders itself and never calls str.format. It cannot tell an f-string from a plain string there, so never put f in front of the query.
Plain strings are refused
Where a template is expected, a plain string is refused before anything is sent: at runtime in Node and Python, at compile time in Rust. The error shows the safe form.
// Refused: the parentheses make this a plain string with the value already inside
await db.sql(`select * from customers where email = '${email}'`)
// Safe: no parentheses, so db.sql receives the value separately
await db.sql`select * from customers where email = ${email}`# Refused on Python 3.14 or newer: an f-string is a plain string
db.sql(f"select * from customers where email = '{email}'")
# Safe: a t-string keeps the value apart
db.sql(t"select * from customers where email = {email}")Names from variables: sql.id
Values are parameters, but table, column and schema names cannot be. When a name comes from a variable, pass it through sql.id:
import { createClient, sql } from 'nordbase'
const db = createClient()
const sortable = new Set(['created_at', 'total'])
const column = sortable.has(input.sort) ? input.sort : 'created_at'
const rows = await db.sql`
select id, total, created_at from orders
order by ${sql.id(column)} desc
limit 20
`sql.id refuses an empty name and a name with a NUL character, wraps the name in double quotes and doubles any quote inside it. The name stays one name, whatever it contains. It does not decide which names are allowed, so check names from requests against a list you control, as above.
Lists: sql.join
const ids = [1042, 1043, 1047]
const rows = await db.sql`select id, status from orders where id in (${sql.join(ids)})`from nordbase import sql
ids = [1042, 1043, 1047]
rows = db.sql(t"select id, status from orders where id in ({sql.join(ids)})")Each item becomes its own parameter: where id in ($1, $2, $3).
Fragments: nested templates
Build a query from pieces by nesting templates. Each piece keeps its values as parameters.
const paidOnly = sql`and paid_at is not null`
const rows = await db.sql`
select id, total from orders
where customer_id = ${customerId}
${filter === 'paid' ? paidOnly : sql``}
order by created_at desc
`paid_only = sql(t"and paid_at is not null")
none = sql(t"")
rows = db.sql(t"""
select id, total from orders
where customer_id = {customer_id}
{paid_only if filter == "paid" else none}
order by created_at desc
""")Loops and conditions stay in your language, and the SQL stays parameterized. For many optional filters, the builder is often shorter.
One statement per call
On the routed port (5432), each call runs one statement. Text with two statements separated by ; is refused, and neither runs.
Escape hatches: db.unsafe and db.unsafeScript
Two functions take raw SQL text. Their names say what they are, and lint rules and the NordBase AI skill flag every use.
| Function | What it does | Use it for |
|---|---|---|
db.unsafe(text, params) | Runs text as written, with $1…$n bound from params | SQL text that lives in your code or a file you control, such as a query a tool generated at build time |
db.unsafeScript(text) | Runs a script of several statements | Migration files |
import { readFileSync } from 'node:fs'
// Text you wrote, values still bound as parameters
const rows = await db.unsafe('select id, total from orders where customer_id = $1', [customerId])
// A migration file from your repository
await db.unsafeScript(readFileSync('migrations/0007_add_refunds.sql', 'utf8'))In Python the script function is db.unsafe_script(text).
Never pass either one text that was built from request data, form fields, file uploads, webhook bodies or the output of an AI model. If you need dynamic SQL, use templates with sql.id, sql.join and nested fragments.
One bad example and its fix
A search endpoint that builds its query with string concatenation:
// Don't: the email becomes part of the SQL text
const rows = await db.unsafe(`select id, name from customers where email = '${email}'`, [])A request with the email x' or '1'='1 turns the condition into email = 'x' or '1'='1' and returns every customer. A value ending in '; delete from customers; -- tries to run a second command.
The fix is shorter than the bug:
// Do: the email is parameter $1, never SQL
const rows = await db.sql`select id, name from customers where email = ${email}`Now x' or '1'='1 is just an email address that matches no customer.
Document Databases
MongoDB-compatible Databases have their own kind of injection: operator objects such as { "$ne": null } hidden in request JSON. The libraries refuse them. See Document Databases.
Fixed text on Python 3.11 to 3.13
Before Python 3.14 there are no t-strings, and a plain string without placeholders could be an f-string, so db.sql refuses it. Text with no values that you wrote in code, such as select count(*) from users, runs through db.unsafe(text). That is the one accepted use of unsafe: never build that text from input. On Python 3.14 and later, use a t-string instead.