SQLResource
A Resource for executing queries based on saved SQL configurations or dynamic SQL, with data sourced from interfaces such as flowSql:run / flowSql:runById. It is suitable for reports, statistics, custom SQL lists, and other scenarios. Unlike MultiRecordResource, SQLResource does not depend on collections; it executes SQL queries directly and supports pagination, parameter binding, template variables ({{ctx.xxx}}), and result type control.
Inheritance: FlowResource → APIResource → BaseRecordResource → SQLResource.
Creation: ctx.makeResource('SQLResource') or ctx.initResource('SQLResource'). To execute based on a saved configuration, use setFilterByTk(uid) (the UID of the SQL template). For debugging, use setDebug(true) + setSQL(sql) to execute SQL directly. In RunJS, ctx.api is injected by the runtime environment.
Use Cases
Data Format
getData()returns different formats based onsetSQLType():selectRows(default): Array, multiple row results.selectRow: Single object.selectVar: Scalar value (e.g., COUNT, SUM).
getMeta()returns metadata such as pagination:page,pageSize,count,totalPage, etc.
SQL Configuration and Execution Modes
Parameters and Context
Pagination
In SQL, you can use {{ctx.limit}} and {{ctx.offset}} to reference pagination parameters. SQLResource injects limit and offset into the context automatically.
Data Fetching and Events
Examples
Executing via Saved Template (runById)
Debug Mode: Executing SQL Directly (runBySQL)
Pagination and Navigation
Result Types
Using Template Variables
Listening to the refresh Event
Notes
- runById requires saving the template first: The UID used in
setFilterByTk(uid)must be a SQL template ID already saved in the admin interface. You can save it viactx.sql.save({ uid, sql }). - Debug mode requires permissions:
setDebug(true)usesflowSql:run, which requires the current role to have SQL configuration permissions.runByIdonly requires the user to be logged in. - Refresh Debouncing: Multiple calls to
refresh()within the same event loop will only execute the last one to avoid redundant requests. - Parameter Binding for Injection Prevention: Use
setBind()with:nameor?placeholders instead of string concatenation to prevent SQL injection.
Related
- ctx.sql - SQL execution and management;
ctx.sql.runByIdis suitable for simple one-off queries. - ctx.resource - The resource instance in the current context.
- ctx.initResource() - Initializes and binds to
ctx.resource. - ctx.makeResource() - Creates a new resource instance without binding.
- APIResource - General API resource.
- MultiRecordResource - Designed for collections and lists.

