include-postgres-sql is an extension of include-sql for using Postgres SQL in Rust. It completes include-sql by providing impl_sql
macro to generate database access methods from the included SQL. include-postgres-sql uses Rust-Postgres for database access.
Write your SQL and save it in a file. For example, let's say the following is saved as library.sql
in the project's src
folder:
```sql -- name: getloanedbooks? -- Returns the list of books loaned to a patron -- # Parameters -- param: userid: &str - user ID SELECT booktitle FROM library WHERE loanedto = :userid ORDER BY 1;
-- name: loanbooks! -- Updates the book records to reflect loan to a patron -- # Parameters -- param: userid: &str - user ID -- param: bookids: i32 - book IDs UPDATE library SET loanedto = :userid , loanedon = currenttimestamp WHERE bookid IN (:book_ids); ```
And then use it in Rust as:
```rust , ignore use includepostgressql::{includesql, implsql}; use postgres::{Config, NoTls, Error};
include_sql!("src/library.sql");
fn main() -> Result<(),Error> {
let args : Vec
let mut db = Config::new().host("localhost").connect(NoTls)?;
db.get_loaned_books(user_id, |row| {
let book_title : &str = row.try_get("book_title")?;
println!("{}", book_title);
Ok(())
})?;
Ok(())
} ```
The included documentation describes the supported SQL file format and provides additional details on the generated code.