Skip to main content

SQL Templates

Every endpoint has a SQL template: a SQL file with Mustache tags. flAPI validates the request parameters, renders the template and runs it on DuckDB. This page is the short reference; the step-by-step guide with runnable examples is SQL Templating.

Quick example​

sqls/customers.yaml
url-path: /customers
request:
- field-name: segment
field-in: query
validators:
- type: enum
allowedValues: [AUTOMOBILE, BUILDING, FURNITURE, HOUSEHOLD, MACHINERY]
- field-name: min_balance
field-in: query
validators:
- type: number
min: 0
template-source: customers.sql
connection: [customers]
sqls/customers.sql
SELECT c_custkey, c_name, c_mktsegment, c_acctbal
FROM read_parquet('{{{ conn.path }}}')
WHERE ({{ params.min_balance }} IS NULL OR c_acctbal >= {{ params.min_balance }})
{{#params.segment}}
AND c_mktsegment = '{{{ params.segment }}}'
{{/params.segment}}
ORDER BY c_custkey
  • min_balance is outside any section, so both references are bound as prepared-statement parameters. Absent, it binds NULL and the filter switches itself off.
  • segment is inside a section, so it is pasted as text. The enum validator is what keeps it safe.
  • conn.path is never bound; it is always text, so it uses triple braces.
  • No LIMIT: GET endpoints are paginated, and ?limit= / ?offset= belong to the pagination.

Variables​

VariableContains
params.*Validated request parameters (query, path, header, body)
conn.*The properties of the first connection in the endpoint's connection: list
auth.*auth.username, auth.roles (comma-joined), auth.email (only with type: oidc), auth.type, auth.authenticated; empty on an anonymous request
env.*Environment variables matching template.environment-whitelist
cache.*Cache table names and, in a populate template, watermark and snapshot values

context.* does not exist: {{{ context.auth.username }}} renders as an empty string.

What is bound and what is text​

A params.* reference is bound as a ? parameter when all three hold:

  1. the field has a typed validator (int, number, boolean, date, time, string, email, uuid, enum);
  2. the reference is outside every section ({{#...}} / {{^...}});
  3. it stands where SQL expects a value (c = {{ params.x }}, c = '{{{ params.x }}}', LIKE '%{{{ params.x }}}%', IN (...)).

Everything else is pasted into the SQL as text, and the validator is the only defence there: references inside a section, names (ORDER BY {{{ params.sort }}}, FROM {{{ params.t }}}), typed literals (DATE '{{{ params.d }}}'), SQL comments, and every conn.*, auth.* and env.* variable.

WhereWriteDefence
A value, outside sections{{ params.x }} bare, or '{{{ params.x }}}'prepared-statement binding
A value, inside a section{{{ params.x }}} (quoted for strings)the validator
A column or table name{{{ params.x }}}an enum or strict regex validator
conn.*, auth.*, env.*'{{{ ... }}}', inside single quotestext, not a bound parameter: for auth.* use only claims the caller cannot edit (your own users:, a token you signed, an identity provider's immutable sub or object id)

Double braces HTML-escape​

  • {{ x }} HTML-escapes the value: &, <, >, ", ', /, ` and = become entities, so /srv/data/x.parquet turns into &#x2F;srv&#x2F;data&#x2F;x.parquet and O'Brien into O&#39;Brien.
  • {{{ x }}} inserts the value as it is.

Neither form escapes SQL. Use {{{ }}} for every conn.*, auth.* and env.* variable, and for strings inside sections. Inside quotes, never use double braces on a params.* value: outside a section '{{ params.x }}' becomes the string '?' and the request fails with 500.

Sections​

  • {{#params.x}} ... {{/params.x}} renders when x was sent.
  • {{^params.x}} ... {{/params.x}} renders when x was not sent.
  • Together they give a default: ORDER BY {{#params.sort}}{{{ params.sort }}}{{/params.sort}}{{^params.sort}}c_custkey{{/params.sort}}.

Rows for the caller​

Filter on auth.*, which flAPI sets from the credentials it checked, never on a parameter the caller sends. Use only values the caller cannot edit: your own users:, a token you signed, or an identity provider's immutable sub or object id, never preferred_username or email from an identity provider where users can change their own profile. Split the comma-joined roles (role names must not contain commas), and write the filter without a section so an anonymous request matches nothing:

SELECT id, owner, amount
FROM deals
WHERE owner = '{{{ auth.username }}}'
OR list_contains(string_split('{{{ auth.roles }}}', ','), 'admin')

See Restrict rows to the caller.

Pagination owns LIMIT​

GET endpoints are paginated by default (with-pagination: true, 100 rows per page). Do not declare limit or offset as request fields, and do not put LIMIT {{ params.limit }} or a fixed LIMIT in a paginated GET template: it applies before flAPI's offset, so ?limit=2&offset=2 returns "data": []. For a bare array with your own LIMIT, set with-pagination: false.

Check what runs​

flapii templates expand /customers --params '{"segment":"BUILDING"}'   # the SQL and its bindings
flapi -c flapi.yaml --validate-config # section balance, undeclared params

templates expand needs a server started with --config-service; see flapii CLI.

DuckDB 2.0 notes​

flAPI v26.11.23 moved from DuckDB 1.5 to DuckDB 2.0.1. A few SQL behaviours changed that can affect templates written for 1.5:

  • Lambda syntax. The single-arrow lambda x -> x + 1 is an error. Write lambda x : x + 1, e.g. list_transform(tags, lambda t : upper(t)).
  • Division by zero. // and % by zero raise an error instead of returning NULL. Guard with NULLIF(divisor, 0).
  • Transactions. Any error inside an explicit transaction aborts it.
  • MERGE / UPDATE ... FROM with several matching source rows give a nondeterministic value. Keep cache merge keys unique.
  • Output. INTERVAL values render as DuckDB's text (1 day 00:01:00); nested STRUCT/MAP key order inside a row is not specified.
  • Files. New database files and DuckLake catalogs are 2.0-only: DuckDB 1.x cannot read them. Existing 1.5 files keep working unchanged.

See DuckDB's own migration guide for the full list.

Next steps​

🍪 Cookie Settings