Expand description
This library allows one to use named arguments in PostgreSQL queries. This library is especially aimed at supporting rust-postgres. A macro is provided to rewrite queries with named arguments, into a query and its positional arguments.
§Query Argument Syntax
The macro uses struct syntax for the named arguments.
The struct name Args is required to support rustfmt and rust-analyzer.
As can be seen from the example below, shorthand field initialization is also allowed for named arguments.
let location = "netherlands";
let period = Period {
start: 2020,
end: 2030,
};
let (query, args) = query_args!(
r"
SELECT location, time, report
FROM weather_reports
WHERE location = $location
AND time BETWEEN $start AND $end
ORDER BY location, time DESC
",
Args {
location,
start: period.start,
end: period.end,
}
);let rows = client.query(query, args).await?;§Insert Syntax
For INSERT’s a special syntax is supported, which helps to avoid mismatches
between the list of column names and the values:
let location = "sweden";
let time = "monday";
let report = "sunny";
let (query, args) = query_args!(
r"
INSERT INTO weather_reports
( $[location, time, report] )
VALUES
( $[..] )
",
Args {
location,
time,
report
}
);client.execute(query, args).await?;§Fragment Syntax
let select = fragment!("
SELECT location, time, report
FROM weather_reports
");
let location = "sweden";
let (query, args) = query_args!(
r"
${select}
WHERE location = $location
",
Args {
location,
},
Sql {
select,
}
);§IDE Support
First, the syntax used by this macro is compatible with rustfmt. Run rustfmt as you would normally and it will format the macro.
Second, the macro is implemented in a way that is rust-analyzer “friendly”. This means that rust-analyzer knows which arguments are required and can complete them. Use the code action “Fill struct fields” or ask rust-analyzer to complete a field name.
Macros§
- fragment
- This macro creates a
Fragmentfrom a string literal. - query_
args - The macro returns a tuple containing the query and the parameter slice that can be used to call the various query methods provided by rust_postgres/tokio_postgres.
Structs§
- Fragment
- Helper type to safely build queries from string literals.