sqlx_insert/lib.rs
1//! SQLInsert trait and derive macro for sqlx.
2
3use async_trait::async_trait;
4
5/// Derive macro for automatically implementing [SQLInsert] trait for a struct.
6/// All struct fields that are supposed to be inserted into the database need to
7/// be: [sqlx::types::Type] + [sqlx::encode::Encode] + [Clone] + [Send] + [Sync].
8/// As of now, the proc macro supports only named struct fields.
9///
10/// Fields can be renamed using `#[sqlx_insert(rename = "new_name")]` attribute
11/// or ignored using `#[sqlx_insert(ignore)]`.
12///
13/// Database is specified by passing type to `#[sqlx_insert(database(DbType))]` attribute.
14/// The `DbType` is a type that implements [sqlx::Database] trait.
15///
16/// Table name defaults to the type name, but can be overridden using
17/// `#[sqlx_insert(table = "new_name")]` attribute.
18///
19/// Example:
20/// ```rust
21/// use sqlx::Postgres;
22/// use sqlx::Sqlite;
23/// use sqlx_insert::SQLInsert;
24///
25/// #[derive(SQLInsert, Clone, Debug)]
26/// #[sqlx_insert(table = "thingy")]
27/// #[sqlx_insert(database(Postgres, Sqlite))]
28/// pub struct Thing {
29/// id: String,
30/// name: String,
31/// amount: i32,
32/// pear: String,
33/// #[sqlx_insert(ignore)]
34/// ignore_me: Option<String>,
35/// #[sqlx_insert(rename = "param_extra")]
36/// param: String,
37/// }
38/// ```
39pub use sqlx_insert_derive::SQLInsert;
40
41/// Trait for inserting a struct into a SQL database.
42///
43/// Example:
44/// ```rust
45/// use sqlx::Postgres;
46/// use sqlx::Sqlite;
47/// use sqlx::PgConnection;
48/// use sqlx_insert::SQLInsert;
49///
50/// #[derive(SQLInsert, Clone, Debug, PartialEq)]
51/// #[sqlx_insert(database(Postgres, Sqlite))]
52/// struct MyStruct {
53/// id: i32,
54/// name: String,
55/// }
56///
57/// async fn insert_my_struct(connection: &mut PgConnection) -> sqlx::Result<()> {
58/// let my_struct = MyStruct { id: 1, name: "test".to_string() };
59/// my_struct.sql_insert(connection).await
60/// }
61///```
62#[async_trait]
63pub trait SQLInsert<DB: sqlx::Database> {
64 async fn sql_insert<'e, 'c, E: 'e + sqlx::Executor<'c, Database = DB>>(
65 &self,
66 connection: E,
67 ) -> ::sqlx::Result<()>;
68}