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, and order by queries based on fields.
- Various return types such as counting, paging, streaming, returning (Postgres only), 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.
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 ;
pub async
async
For more details, please see the examples in the repository.
Features
postgres: Target PostgreSQL databases.mysql: Target MySQL databases.sqlite: Target SQLite databases.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 = -1explicity.- By default, if neither
tracingnorlogfeatures are declared, information will be printed to the screen using theprintln!macro.
TODO
- Add more tests and example code.
- Support more type of parameter
- More grammar check
- Integrate with
sqlx::query!marco - Better interface for
multi_querymarco
License
This project is licensed under the Apache 2.0 License.
Contributions
All PRs are welcome!