sqlx-template
sqlx-template is a Rust library designed to generate database query functions using macros, based on the sqlx framework. It aims to provide a flexible, simple way to interact with databases such as MySQL, Postgres, and SQLite.
Features
- Generate functions for select, insert, update, delete, upsert, and order by queries based on fields.
- Various return types such as counting, paging, streaming, returning (with specific columns), fetch_one, fetch_all, and rows_affected.
- All generated query functions include the corresponding code in the documentation.
- Supports transactions and optimistic locking templates.
- Customizable queries with named parameters and the ability to run multiple queries.
- Import queries from files.
- Customizable logging and debugging for queries and execution time.
- Compile-time query syntax validation.
- Database-specific optimizations with
#[db("database_type")]attribute. - Enhanced RETURNING clause support with specific column selection.
- Support for placeholder parameters in WHERE conditions.
- Improved function name generation based on query parameters.
Requirements
- The generated functions depend on the
sqlxcrate, so you need to add it to your dependencies before using this library. - Columns in the database must match the names and data types of the fields in the struct.
- Structs need to derive
sqlx::FromRowandTableName.
Example Code
use ;
use ;
// Using PostgresTemplate for PostgreSQL-specific features
// Enable builder patterns for flexible queries with custom conditions
// Using individual derive macros for more control
// Enable builder pattern
pub async
async
async
// Builder Pattern Examples - Flexible and Dynamic Queries
async
For more details, please see the examples in the repository.
Available Macros
Derive Macros
InsertTemplate: Generate insert functionsUpdateTemplate: Generate update functionsSelectTemplate: Generate select/query functionsDeleteTemplate: Generate delete functionsUpsertTemplate: Generate upsert functions (INSERT ... ON CONFLICT)SqlxTemplate: Combines all above templates in one macroPostgresTemplate,MysqlTemplate,SqliteTemplate,AnyTemplate: Database-specific versionsTableName: Generate table name functionColumns: Generate column name constantsDDLTemplate: Generate DDL (CREATE/DROP TABLE) statements
Builder Pattern Attributes
#[tp_select_builder]: Generate flexible SELECT query builder#[tp_update_builder]: Generate flexible UPDATE query builder#[tp_delete_builder]: Generate flexible DELETE query builder
The builder pattern provides:
- Dynamic query construction: Build queries with optional conditions
- Type-safe field access: All field names are validated at compile time
- Flexible ordering: Multiple ordering options with asc/desc
- Pagination support: Built-in offset/limit with optional counting
- Streaming support: Handle large result sets efficiently
- SQL generation: Build SQL without executing for debugging
Procedural Macros
query: Transform SQL query into async functionselect: Transform SELECT query into async functioninsert: Transform INSERT query into async functionupdate: Transform UPDATE query into async functiondelete: Transform DELETE query into async functionmulti_query: Transform multiple SQL queries into async function- Database-specific versions:
postgres_query,mysql_query,sqlite_query, etc.
Builder Pattern Features
The builder pattern in sqlx-template provides a fluent, type-safe way to construct dynamic SQL queries:
SELECT Builder Methods
- Field conditions:
.field_name(&value).unwrap()- Exact match - String operations:
.field_name_like("pattern").unwrap(),.field_name_start_with("prefix").unwrap(),.field_name_end_with("suffix").unwrap() - Numeric comparisons:
.field_name_gt(&value).unwrap(),.field_name_gte(&value).unwrap(),.field_name_lt(&value).unwrap(),.field_name_lte(&value).unwrap() - Negation:
.field_name_not(&value).unwrap()- Not equal - Custom conditions:
.with_method_name(params).unwrap()- User-defined SQL expressions - Ordering:
.order_by_field_name_asc().unwrap(),.order_by_field_name_desc().unwrap() - Execution:
.find_all(),.find_one(),.find_page((offset, limit, count)),.stream(),.count() - SQL generation:
.build_sql()- Returns SQL string for debugging
UPDATE Builder Methods
- Set fields:
.on_field_name(&value).unwrap()- Set field to value - Where conditions:
.by_field_name(&value).unwrap()- Update condition - Custom conditions:
.with_method_name(params).unwrap()- User-defined WHERE expressions - Execution:
.execute()- Returns number of affected rows
DELETE Builder Methods
- Where conditions:
.field_name(&value).unwrap()- Delete condition - Custom conditions:
.with_method_name(params).unwrap()- User-defined WHERE expressions - Execution:
.execute()- Returns number of deleted rows
Custom Conditions
Custom conditions allow you to define complex SQL expressions that go beyond simple field comparisons:
Syntax Rules:
- Method name:
with_method_namebecomes.with_method_name(params) - Placeholders:
:param_name$Typefor typed parameters - Auto-mapping:
:param_namemaps to struct fields automatically - Multiple params: Each unique placeholder becomes a method parameter
Examples:
.with_email_domain("@company.com")→email LIKE '@company.com'.with_score_range(10, 100)→score BETWEEN 10 AND 100.with_active_org(1)→active = true AND org = 1
Advantages
- Type safety: All field names validated at compile time
- Dynamic queries: Add conditions based on runtime logic
- Clean syntax: Fluent interface for readable code
- Performance: Compiled to efficient SQL with proper placeholders
- Database agnostic: Works with PostgreSQL, MySQL, SQLite
- Custom logic: Complex SQL expressions with custom conditions
Features
tracing: Use thetracing::debug!macro for logging (requires adding thetracingcrate toCargo.toml).log: Use thelog::debug!macro for logging (requires adding thelogcrate toCargo.toml).
Notes
- If you encounter errors caused by macros in the library, try regenerating the function by copying the generated code from the function's documentation. If documentation is not available, most errors are due to syntax issues, incorrect variable names, column names, or file paths.
debug_slowapplies to all attributes using derived macros of the struct. It can be overridden by declaring thedebug_slowattribute within the attribute itself. To disable it, setdebug_slow = -1explicitly.- By default, if neither
tracingnorlogfeatures are declared, information will be printed to the screen using theprintln!macro. - Use
#[db("database_type")]to specify target database for optimized query generation. - The
tableattribute has replaced the oldtable_nameattribute.
Changelog
Changes since v0.1.1
New Features
- Enhanced RETURNING clause support: Now supports returning specific columns (e.g.,
returning = "id, email") in addition to full record returning - Upsert operations: Added
UpsertTemplatemacro for INSERT ... ON CONFLICT operations (PostgreSQL) - Database-specific macros: Added
PostgresTemplate,MysqlTemplate,SqliteTemplate,AnyTemplatefor database-specific optimizations - Placeholder support in WHERE conditions: Enhanced support for placeholder parameters in WHERE statements
- Function name improvements: Better automatic function name generation based on query parameters
- Column utilities: Added
Columnsderive macro for generating column name constants
Breaking Changes
- Table attribute change:
#[table_name = "..."]is now#[table("...")] - Database specification: Use
#[db("postgres")]instead of feature flags for database-specific behavior
Improvements
- Query validation: Enhanced compile-time query syntax validation
- Error handling: Improved error messages and debugging capabilities
- Performance: Optimized query generation for different database types
- Documentation: Comprehensive documentation updates with examples for all macros
Bug Fixes
- Fixed page count query with JOIN and GROUP BY clauses
- Fixed update operations with string fields
- Fixed function name generation conflicts
- Fixed WHERE statement handling in tp_update with specific field selections
- Fixed returning query generation
- Fixed column name errors when matching database keywords
- Fixed TableName derive with new attribute format
- Fixed placeholder handling in WHERE conditions
TODO
- Add more tests and example code.
- Support more parameter types
- Enhanced grammar checking
- Integration with
sqlx::query!macro - Better interface for
multi_querymacro
License
This project is licensed under the Apache 2.0 License.
Contributions
All PRs are welcome!