Overview
A SQL Macro is a predefined SQL fragment that is expanded during rule compilation. It behaves like a boolean function when called in a rule.Why use SQL Macros?
- Database performance: Checks are executed as part of the primary query.
- Complexity management: Move complex logic out of rules and into reusable SQL.
- Transactional safety: Macros execute within the same transaction as the request.
- Context awareness: Macros have access to the currently authenticated user.
Core Concepts
1. Naming
Macro names must start with@ when called in a rule, but are defined without it.
Example: Defined as owns_record, called as @owns_record().
2. Parameters
Macros can accept parameters. Use$1, $2, etc., in your SQL query to reference them.
Parameters are passed from the rule expression.
3. Context Variables
Macros can also reference context variables directly in the SQL:@request.auth.id: Current user ID@request.auth.account_id: Current account ID
Built-in Macros
SnackBase comes with several high-performance macros pre-installed:| Macro | SQL Equivalent (approx) | Description |
|---|---|---|
@has_role("name") | @request.auth.role = $1 | Checks if user has a specific role |
@has_group("name") | EXISTS(SELECT 1 FROM group_members ...) | Checks group membership |
@owns_record() | created_by = @request.auth.id | Checks if user created the record |
@is_creator() | created_by = @request.auth.id | Alias for @owns_record |
Creating Custom Macros
Example: @is_project_member(project_id)
- Name:
is_project_member - Description: Checks if a user is a member of a project.
- SQL Query:
Security Constraints
To ensure system stability, SQL macros are subject to the following rules:- SELECT only: Only
SELECTstatements are allowed.INSERT,UPDATE,DELETEwill be rejected. - Timeout: Macros have a 5-second execution timeout.
- Parameter Binding: All parameters are bound safely to prevent SQL injection.
- Read-Only: Macros execute in a read-only transaction context.
API Management
List Macros
GET /api/v1/macros
Create Macro
POST /api/v1/macros
Payload:
Test Macro
POST /api/v1/macros/{id}/test
Allows testing a macro with specific parameter values before using it in a rule.
Best Practices
- Return Booleans: Custom SQL macros should always return a result that can be interpreted as a boolean (usually
count(*) > 0orEXISTS(...)). - Index Columns: Ensure columns used in
WHEREclauses (likeuser_id,project_id) are indexed. - Account Isolation: Always include
account_id = @request.auth.account_idin your queries to maintain proper isolation. - Descriptive Names: Use names like
is_subscriber,can_approve_invoiceto make rules self-documenting.