vld-sqlx
SQLx integration for the vld validation library.
Validate data before inserting into the database. Provides:
| Feature | Description |
|---|---|
validate_insert::<Schema, _>(&value) |
Standalone validation before INSERT |
validate_update::<Schema, _>(&value) |
Standalone validation before UPDATE |
validate_row::<Schema, _>(&row) |
Validate data loaded from DB |
validate_rows::<Schema, _>(&rows) |
Batch validate with row index on error |
Validated<Schema, T> |
Wrapper that guarantees T passes Schema |
VldText<S> |
Validated String column — SQLx Type/Encode/Decode |
VldInt<S> |
Validated i64 column — SQLx Type/Encode/Decode |
VldFloat<S> |
Validated f64 column — SQLx Type/Encode/Decode |
VldBool<S> |
Validated bool column — SQLx Type/Encode/Decode |
Installation
[]
= "0.1"
= { = "0.1", = ["serialize"] }
= { = "0.8", = ["sqlite", "runtime-tokio"] }
Backend features
| Feature | Backend |
|---|---|
sqlite (default) |
SQLite |
postgres |
PostgreSQL |
mysql |
MySQL |
Generic SQLx trait implementations (Type, Encode, Decode) work with any backend
where the underlying primitive type (String, i64, f64, bool) is supported.
Quick Start
1. Validate before insert
use *;
schema!
let user = NewUser ;
?;
// Then insert via sqlx
query
.bind
.bind
.bind
.execute
.await?;
2. Validated wrapper
let user = NewUser ;
let validated = new?;
// The inner value is guaranteed valid
query
.bind
.bind
.bind
.execute
.await?;
3. Typed columns
Use VldText, VldInt, VldFloat, VldBool as column types in your models.
They implement SQLx Type, Encode, and Decode for seamless DB integration.
use ;
schema!
schema!
// Validates on construction
let email = new?;
let age = new?;
// Bind directly in queries
query
.bind
.bind
.execute
.await?;
// Decode from query results
let row = query
.fetch_one
.await?;
let decoded_email: = row.get;
let decoded_age: = row.get;
Works with #[derive(sqlx::FromRow)] too:
let user: User = query_as
.fetch_one
.await?;
4. Batch validation
let rows: = load_rows;
match
5. Error conversion to sqlx::Error
VldSqlxError implements Into<sqlx::Error>, so you can use ? in functions
returning Result<T, sqlx::Error>:
async
Comparison with vld-diesel
| vld-sqlx | vld-diesel | |
|---|---|---|
| ORM | SQLx (async, compile-time checks) | Diesel (sync, schema DSL) |
| Column types | VldText, VldInt, VldFloat, VldBool |
VldText, VldInt |
| Batch validation | validate_rows() with row index |
— |
| Error conversion | Into<sqlx::Error> |
— |
FromRow compat |
#[derive(sqlx::FromRow)] works |
QueryableByName works |
Running the example
License
MIT