mssql-derive
Part of the rust-mssql-driver project.
Procedural macros for SQL Server row mapping and parameter handling.
Overview
This crate provides derive macros for automatically implementing row-to-struct mapping and struct-to-parameter conversion, reducing boilerplate when working with SQL Server data.
Available Macros
| Macro | Description |
|---|---|
#[derive(FromRow)] |
Convert database rows to structs |
#[derive(ToParams)] |
Convert structs to query parameters |
#[derive(Tvp)] |
Table-valued parameter support |
FromRow
Automatically implement row-to-struct conversion:
use FromRow;
// Usage
let user: User = row.into?;
Field Attributes
| Attribute | Description |
|---|---|
#[mssql(rename = "column")] |
Map field to different column name |
#[mssql(skip)] |
Skip field (must implement Default) |
#[mssql(default)] |
Use Default if NULL or missing |
#[mssql(flatten)] |
Flatten nested FromRow struct |
Struct Attributes
| Attribute | Description |
|---|---|
#[mssql(rename_all = "case")] |
Apply naming convention to all fields |
Supported cases: snake_case, camelCase, PascalCase, SCREAMING_SNAKE_CASE
ToParams
Automatically convert structs to query parameters:
use ToParams;
let user = NewUser ;
client.execute.await?;
Tvp (Table-Valued Parameters)
Create table-valued parameters for passing collections to stored procedures:
use Tvp;
// First, create the table type in SQL Server:
// CREATE TYPE dbo.UserIdList AS TABLE (UserId INT NOT NULL);
let ids = vec!;
let tvp = new?;
client.execute.await?;
Complete Example
use ;
// Read users
let mut stream = client.query.await?;
while let Some = stream.next.await
// Update user
let update = UpdateUser ;
client.execute.await?;
Type Inference for TVPs
The macro automatically infers SQL types from Rust types:
| Rust Type | SQL Type |
|---|---|
i8, u8 |
TINYINT |
i16 |
SMALLINT |
i32 |
INT |
i64 |
BIGINT |
f32 |
REAL |
f64 |
FLOAT |
bool |
BIT |
String |
NVARCHAR(MAX) |
Uuid |
UNIQUEIDENTIFIER |
NaiveDate |
DATE |
NaiveTime |
TIME |
NaiveDateTime |
DATETIME2 |
DateTime |
DATETIMEOFFSET |
Decimal |
DECIMAL(38,10) |
License
MIT OR Apache-2.0