sqlx_insert/lib.rs
1//! `SQLInsert` trait and derive macro for sqlx.
2
3/// Derive macro for automatically implementing [`SQLInsert`] trait for a struct.
4/// All struct fields that are supposed to be inserted into the database need to
5/// be: [`sqlx::types::Type`] + [`sqlx::encode::Encode`] + [Clone] + [Send] + [Sync].
6/// As of now, the proc macro supports only named struct fields.
7///
8/// Fields can be renamed using `#[sqlx_insert(rename = "new_name")]` attribute
9/// or ignored using `#[sqlx_insert(ignore)]`.
10///
11/// Database is specified by passing type to `#[sqlx_insert(database(DbType))]` attribute.
12/// The `DbType` is a type that implements [`sqlx::Database`] trait.
13///
14/// Table name defaults to the type name, but can be overridden using
15/// `#[sqlx_insert(table = "new_name")]` attribute.
16///
17/// Example:
18/// ```rust
19/// use sqlx::Postgres;
20/// use sqlx::Sqlite;
21/// use sqlx_insert::SQLInsert;
22///
23/// // If using macros feature, only a single database is supported
24/// #[derive(SQLInsert, Clone, Debug)]
25/// #[sqlx_insert(table = "thingy")]
26/// #[cfg_attr(feature = "use-macros", sqlx_insert(database(Postgres)))]
27/// #[cfg_attr(not(feature = "use-macros"), 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/// // If using macros feature, only a single database is supported
51/// #[derive(SQLInsert, Clone, Debug, PartialEq)]
52/// #[cfg_attr(feature = "use-macros", sqlx_insert(database(Postgres)))]
53/// #[cfg_attr(not(feature = "use-macros"), sqlx_insert(database(Postgres, Sqlite)))]
54/// struct MyStruct {
55/// id: i32,
56/// name: String,
57/// }
58///
59/// async fn insert_my_struct(connection: &mut PgConnection) -> sqlx::Result<()> {
60/// let my_struct = MyStruct { id: 1, name: "test".to_string() };
61/// my_struct.sql_insert(connection).await
62/// }
63///```
64pub trait SQLInsert<DB: sqlx::Database, R> {
65 fn sql_insert<'e, 'c, E: 'e + sqlx::Executor<'c, Database = DB>>(
66 &self,
67 connection: E,
68 ) -> impl std::future::Future<Output = ::sqlx::Result<R>>;
69}
70
71pub trait BatchInsert<DB: sqlx::Database>: Sized {
72 fn batch_insert<'e, 'c, E: 'e + sqlx::Executor<'c, Database = DB>>(
73 data: &[Self],
74 connection: E,
75 ) -> impl std::future::Future<Output = ::sqlx::Result<()>>;
76}