ctx.sql
ctx.sql provides SQL execution and management, often used in RunJS (e.g. JSBlock, event flow) to access the database directly. It supports ad-hoc SQL, running saved SQL templates by ID, parameter binding, template variables ({{ctx.xxx}}), and result type control.
Use Cases
Note:
ctx.sqluses theflowSqlAPI to access the database; ensure the current user has execute permission on the target data source.
Permissions
Front-end logic for normal users can use ctx.sql.runById(uid, options); for dynamic SQL or template management, the current role must have SQL config permission.
Type
Common Methods
run: for debugging SQL; requires config permission.save,destroy: for managing SQL templates; require config permission.runById: available to normal users; only runs saved templates.- Call
savewhen a SQL template changes.
Options
run / runById options
save options
Template Variables and Parameter Binding
Template variables {{ctx.xxx}}
In SQL you can use {{ctx.xxx}} to reference context variables; they are resolved before execution:
Variable sources are the same as for ctx.getVar() (e.g. ctx.user.*, ctx.record.*, custom ctx.defineProperty, etc.).
Parameter binding
- Use
$namein SQL and passbind: { name: value }
Examples
Ad-hoc SQL (requires SQL config permission)
Template variables
Save template and reuse
Paginated list (SQLResource)
Relation to ctx.resource, ctx.request
ctx.sql wraps the flowSql API for SQL; ctx.request is for arbitrary API calls.
Notes
- Use parameter binding (
$name) instead of string concatenation to avoid SQL injection. - With
type: 'selectVar'the result is a scalar (e.g. forCOUNT,SUM). - Template variables
{{ctx.xxx}}are resolved before execution; ensure the context defines them.
Related
- ctx.resource: data resource; SQLResource uses flowSql internally
- ctx.initResource(): initialize SQLResource for paginated lists
- ctx.request(): generic HTTP requests

