camel-component-sql
SQL component for rust-camel integration framework
Overview
The SQL component provides comprehensive database integration for rust-camel, supporting both producer (query execution) and consumer (polling) patterns. It enables seamless interaction with SQL databases using parameterized queries, batch operations, and streaming results.
Features
- Producer Mode: Execute SQL queries (SELECT, INSERT, UPDATE, DELETE)
- Consumer Mode: Poll database tables for new rows
- Parameter Binding: Named (
:#name), positional (#), IN clause (:#in:ids), and expressions (:#${body.field}) - Batch Operations: Execute multiple inserts/updates in a single transaction
- Streaming Results: Stream large result sets as NDJSON without loading all rows into memory
- Post-Processing Hooks:
onConsume,onConsumeFailed,onConsumeBatchCompletefor consumer workflows - Connection Pooling: Configurable pool with min/max connections, idle timeout, and max lifetime
- Async Native: Built on
tokioandsqlx - Health Check: Async connection validation probe for SQL databases
Installation
Add to your Cargo.toml:
[]
= "*"
URI Format
sql:<query>?datasource=<name>&options
sql:<query>?db_url=<database-url>&options
sql:file:<path-to-sql-file>?datasource=<name>&options
sql:file:<path-to-sql-file>?db_url=<database-url>&options
<query>: SQL query with optional parameter placeholders<path-to-sql-file>: Path to a file containing the SQL query<datasource>: Named datasource from Camel.toml (alternative todb_url)<database-url>: Database connection URL
Either datasource or db_url is required (not both).
URI Options
Connection Options
| Option | Default | Description |
|---|---|---|
datasource |
- | Named datasource from Camel.toml (alternative to db_url) |
db_url |
(required if no datasource) |
Database connection URL |
maxConnections |
5 |
Maximum connections in pool |
minConnections |
1 |
Minimum connections in pool |
idleTimeoutSecs |
300 |
Idle connection timeout in seconds |
maxLifetimeSecs |
1800 |
Maximum connection lifetime in seconds |
Timeouts
No TCP connect timeout is applied at the URL level: sqlx-postgres 0.9 does not read a
connect_timeout key from the database URL (it warns "ignoring unrecognized connect parameter"
and drops it, so this component no longer appends one). A stuck connection attempt is bounded by
the pool acquire timeout, which sqlx fixes at 30 seconds and which covers the whole
acquire (queue wait plus connect), not just the TCP handshake. A connect_timeout=… key you set
in db_url yourself is passed through untouched, but sqlx-postgres 0.9 ignores it.
Named Datasources
Instead of embedding db_url in every URI, define named datasources in Camel.toml:
[]
= "postgres://user:pass@db:5432/orders"
= 20
= 2
[]
= "postgres://user:pass@db:5432/analytics"
= 5
Then reference by name in URIs:
sql:SELECT * FROM orders?datasource=orders
sql:INSERT INTO events VALUES (#, #)?datasource=analytics
Benefits:
- Shared connection pools across endpoints referencing the same datasource
- Credentials not exposed in route URIs
- Pool configuration centralized in one place
- Health checks per datasource via
PoolFactory::check()
Restrictions: When using datasource, the following pool-affecting URI parameters are rejected (set them in Camel.toml instead):
maxConnections, minConnections, idleTimeoutSecs, maxLifetimeSecs, sslMode, sslRootCert, sslCert, sslKey
Non-pool parameters like outputType, onConsume, delay etc. work normally with named datasources.
Backward compatible: Inline db_url continues to work as before.
Query Options
| Option | Default | Description |
|---|---|---|
outputType |
SelectList |
Output format: SelectList, SelectOne, StreamList |
placeholder |
# |
Character used for parameter placeholders |
inSeparator |
", " |
Separator for IN clause expansion (e.g. ", " → 1, 2, 3) |
noop |
false |
If true, preserve original body after DML operations |
Consumer Options
| Option | Default | Description |
|---|---|---|
delay |
500 |
Polling delay in milliseconds |
initialDelay |
1000 |
Initial delay before first poll (ms) |
repeatCount |
- | Max number of polls; omit for infinite. 0 = never polls |
maxMessagesPerPoll |
- | Maximum rows to process per poll |
onConsume |
- | SQL to execute after successful row processing |
onConsumeFailed |
- | SQL to execute after failed row processing |
onConsumeBatchComplete |
- | SQL to execute after batch completes |
routeEmptyResultSet |
false |
Process empty result sets |
useIterator |
true |
Process rows individually (true) or as batch (false) |
expectedUpdateCount |
- | Expected rows affected (error if mismatch) |
breakBatchOnConsumeFail |
false |
Stop batch processing on failure |
breakOnEmpty |
false |
Stop polling when a poll returns zero rows (SelectList only; StreamList warns and ignores) |
Producer Options
| Option | Default | Description |
|---|---|---|
batch |
false |
Enable batch mode (body must be array of arrays) |
useMessageBodyForSql |
false |
Use message body as SQL query |
SSL/TLS Options
TLS support is compiled in by default (sqlx tls-rustls with webpki roots). sslMode defaults to require for PostgreSQL (fail-closed) and prefer for MySQL.
Precedence: explicit endpoint sslMode > explicit URL sslmode/ssl-mode > driver default (require PG / prefer MySQL). An explicit URL value is never overwritten by the default.
| Option | Default | Description |
|---|---|---|
sslMode |
require (PG) / prefer (MySQL) |
SSL mode (e.g. require, verify-ca, verify-full) |
sslRootCert |
- | Path to CA certificate for server verification |
sslCert |
- | Path to client certificate for mTLS |
sslKey |
- | Path to client private key for mTLS |
SSL parameters are appended as query string parameters to the database URL, with database-specific key names:
| URI Parameter | PostgreSQL Key | MySQL Key |
|---|---|---|
sslMode |
sslmode |
ssl-mode |
sslRootCert |
sslrootcert |
ssl-ca |
sslCert |
sslcert |
ssl-cert |
sslKey |
sslkey |
ssl-key |
Parameter Binding
The SQL component supports multiple parameter placeholder styles:
Numeric Bind Safety (bd rc-fef4z / rc-mn139)
Numeric payloads bind per the server-described parameter encoding (probe-once per SQL text, then checked conversions); statements whose description cannot carry a payload faithfully execute uncached on a private alias with that message's own encodings. A parameter position therefore never reinterprets numeric bits. Guards that fire as typed route errors:
- an integer beyond 2^53 at a float position
(
parameter 0: integer value … exceeds 2^53 and would lose precision bound as f64), - a non-numeric JSON value at a described numeric position,
- integer range checks against the described width (
SMALLINT/INTEGER), REALoverflow/underflow.
Positional Parameters (#)
INSERT INTO users (name, age) VALUES (#, #)
Body must be a JSON array: ["Alice", 30]
Named Parameters (:#name)
SELECT * FROM users WHERE id = :#id AND status = :#status
Values resolved from body (if JSON object), headers, or properties.
IN Clause (:#in:name)
SELECT * FROM users WHERE id IN (:#in:ids)
Value must be a JSON array: [1, 2, 3] → expands to IN ($1, $2, $3).
Customize the separator with inSeparator (default ", "):
sql:SELECT * FROM users WHERE id IN (:#in:ids)?...&inSeparator=|
Produces: IN ($1|$2|$3)
Expression Parameters (:#${expr})
SELECT * FROM users WHERE id = :#${body.user_id} AND name = :#${header.userName}
Supported expressions: body.field, header.name, property.key
Usage
SELECT Query
use RouteBuilder;
use SqlComponent;
let mut ctx = new;
ctx.register_component;
let route = from
.to
.build?;
ctx.add_route_definition.await?;
Parameterized Query
// Named parameters from body
let route = from
.set_body
.to
.build?;
// Positional parameters from array body
let route = from
.set_body
.to
.build?;
Streaming Large Results
// Stream results as NDJSON (memory efficient for large datasets)
let route = from
.to
.to
.build?;
Batch Insert
// Batch insert with transaction
let route = from
.set_body
.to
.build?;
Dynamic Query from Body
// Use message body as SQL
let route = from
.set_body
.to
.build?;
Polling Consumer
// Poll for pending orders and mark as processed
let route = from
.process
.build?;
Load Query from File
// Load SQL from external file
let route = from
.to
.build?;
Exchange Headers
Input Headers
| Header | Description |
|---|---|
CamelSql.Query |
Override the SQL query from URI |
CamelSql.Parameters |
Override parameters as JSON array |
Output Headers
| Header | Direction | Description |
|---|---|---|
CamelSql.RowCount |
out | Number of rows returned by SELECT |
CamelSql.UpdateCount |
out | Number of rows affected by INSERT/UPDATE/DELETE |
Consumer Row Headers
When useIterator=true, each row's columns are also set as headers:
| Header Pattern | Description |
|---|---|
CamelSql.<column> |
Column value from current row (e.g., CamelSql.id, CamelSql.name) |
Output Types
| Type | Description | Body Format |
|---|---|---|
SelectList |
All rows as array | [{...}, {...}] |
SelectOne |
First row only | {...} or empty |
StreamList |
Stream rows on demand | NDJSON stream ({...}\n{...}\n) |
Type matrix (sqlx Any driver)
The component runs every query through sqlx's Any driver, which decodes a fixed
type set. Types outside that set fail the route with a typed error that names the
column, the driver-reported type, and the CAST workaround. SQL NULL decodes to JSON
null for every supported column type. A projection of an unsupported type (for
example NULL::numeric) fails the route with the typed error at row construction,
before any null handling. A value the server sent is never substituted with null.
| Column type (Postgres terms) | Decoded as | Notes |
|---|---|---|
| BOOLEAN | JSON boolean | |
| SMALLINT, INTEGER, BIGINT | JSON number | |
| REAL, DOUBLE PRECISION | JSON number | finite values only (REAL widens from f32); NaN/±Infinity fails the route |
| TEXT, VARCHAR, CITEXT | JSON string | |
| BYTEA | JSON string | UTF-8 content only; other bytes fail the route |
| NUMERIC, DECIMAL | typed error | CAST(col AS double precision) (approximate) or CAST(col AS text) (exact) |
| CHAR (BPCHAR), TIMESTAMPTZ, TIMESTAMP, DATE, TIME, UUID, JSON, JSONB, arrays | typed error | CAST(col AS text) |
Example: a NUMERIC column becomes readable without a driver change:
SELECT CAST(total AS double precision) AS total FROM orders
A future typed (non-Any) driver path would decode NUMERIC and TIMESTAMPTZ natively
and retire the CAST workaround. It is not implemented here.
Example: Order Processing Pipeline
use RouteBuilder;
use SqlComponent;
use CamelContext;
async
Global Configuration
Configure default connection pool settings in Camel.toml that apply to all SQL endpoints:
[]
= 5 # Maximum pool connections (default: 5)
= 1 # Minimum pool connections (default: 1)
= 300 # Idle connection timeout (default: 300)
= 1800 # Max connection lifetime (default: 1800)
= "require" # SSL mode (optional)
= "/etc/ssl/ca.pem" # CA certificate path (optional)
= "/etc/ssl/client.pem" # Client certificate path (optional)
= "/etc/ssl/client.key" # Client key path (optional)
URI parameters always override global defaults:
// Uses global pool settings
.to
// Overrides maxConnections from global config
.to
Profile-Specific Configuration
[]
= 5
= 1
[]
= 20
= 5
= 600
Health Check
The camel-component-sql component registers an async health check via AsyncHealthCheck.
- Probe: Executes a
SELECT 1validation query against the connection pool - Healthy: Connection pool returns a valid connection and query succeeds
- Degraded: Connection fails or validation query times out
Health checks are exposed via the health server:
[]
= true
= 8080
Documentation
License
Apache-2.0
Contributing
Contributions are welcome! Please see the main repository for details.