Macro impl_sql

Source
macro_rules! impl_sql {
    ( $sql_name:ident = $( { $kind:tt $name:ident ($($variant:tt $param:ident $ptype:tt)*) $doc:literal $s:tt $( $text:tt )+ } ),+ ) => { ... };
}
Expand description

Generates Rust code to use included SQL.

This macro defines a trait with methods to access data and implements it for postgres::Client and postgres::Transaction.

This macro recognizes and generates 5 variants of database access methods using the following selectors:

  • ? - methods that process rows retrieved by SELECT,
  • ^ - methods that return raw rows retrieved by SELECT,
  • % - methods that return vector of structs (a struct per returned row)
  • ! - methods that execute all other non-SELECT methods, and
  • -> - methods that execute RETURNING statements and provide access to returned data.

For SELECT statements (?) like:

-- name: get_loaned_books?
-- param: user_id: &str
SELECT book_title FROM library WHERE loaned_to = :user_id

The method with the following signature is generated:

fn get_loaned_books<F>(&self, user_id: &str, row_callback: F) -> Result<(),postgres::Error>
where F: FnMut(postgres::Row) -> Result<(),postgres::Error>;

For SELECT statements (^):

-- name: get_loaned_books^
-- param: user_id: &str
SELECT book_title FROM library WHERE loaned_to = :user_id

The method with the following signature is generated:

fn get_loaned_books<'a>(&'a self, user_id: &str) -> Result<postgres::RowIter<'a>,postgres::Error>;

For SELECT statements (%):

-- name: get_loaned_books%
-- param: user_id: &str
SELECT book_title FROM library WHERE loaned_to = :user_id

The method with the following signature is generated:

fn get_loaned_books<R>(&self, user_id: &str) -> Result<Vec<R>,postgres::Error>
where R: TryFrom<postres::Row>, postgres::Error: From<R::Error>;

For non-select statements (!) - INSERT, UPDATE, DELETE, etc. - like:

-- name: loan_books!
-- param: user_id: &str
-- param: book_ids: i32
UPDATE library
   SET loaned_to = :user_id
     , loaned_on = current_timestamp
 WHERE book_id IN (:book_ids)

The method with the following signature is generated:

fn loan_books(&self, user_id: &str, book_ids: &[i32]) -> Result<u64,postgres::Error>;

For DELETE, INSERT, and UPDATE statements that return data via RETURNING clause (->) like:

-- name: add_new_book->
-- param: isbn: &str
-- param: book_title: &str
INSERT INTO library (isbn, book_title)
VALUES (:isbn, :book_title)
RETURNING book_id

The method with the following signature is generated:

fn add_new_book(&self, isbn: &str, book_title: &str) -> Result<postgres::Row,postgres::Error>;

§Tokio-Postgres

Note that when include-postgres-sql is used with the tokio feature, the generated methods will be async.