1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
// lib.rs
mod common;
extern crate proc_macro;
use self::proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Fields};
use crate::common::dollar_values;
/// Create method for inserting struts into Sqlite database
///
/// ```rust
/// # #[tokio::main]
/// # async fn main() -> sqlx::Result<()>{
/// #[derive(Default, Debug, sqlx::FromRow, sqlxinsert::SqliteInsert)]
/// struct Car {
/// pub car_id: i32,
/// pub car_name: String,
/// }
///
/// let car = Car {
/// car_id: 33,
/// car_name: "Skoda".to_string(),
/// };
///
/// let url = "sqlite::memory:";
/// let pool = sqlx::sqlite::SqlitePoolOptions::new().connect(url).await.unwrap();
///
/// let create_table = "create table cars ( car_id INTEGER PRIMARY KEY, car_name TEXT NOT NULL )";
/// sqlx::query(create_table).execute(&pool).await.expect("Not possible to execute");
///
/// let res = car.insert_raw(&pool, "cars").await.unwrap(); // returning id
/// # Ok(())
/// # }
/// ```
///
#[cfg(feature = "sqlite")]
#[proc_macro_derive(SqliteInsert)]
pub fn derive_from_struct_sqlite(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let fields = match &input.data {
Data::Struct(DataStruct {
fields: Fields::Named(fields),
..
}) => &fields.named,
_ => panic!("expected a struct with named fields"),
};
// COMMON Atrributes
let struct_name = &input.ident;
// INSERT Attributes -> field names
let attributes = fields.iter().map(|field| &field.ident);
let attributes_vec: Vec<String> = fields
.iter()
.map(|field| {
field
.ident
.as_ref()
.map(ToString::to_string)
.unwrap_or_default()
})
.collect();
// ( id, name, hostname .. )
let columns = attributes_vec.join(",");
// ( $1, $2)
let dollars = dollar_values(attributes_vec.len());
// UPDATE Attributes -> field names for
let attributes_update = fields.iter().map(|field| &field.ident);
// name = $2, hostname = $3
let pairs: String = attributes_vec
.iter()
.enumerate()
.skip(1) // Skip the first element
.map(|(index, value)| {
let number = index + 1; // Start with $2
format!("{} = ${}", value, number)
})
.collect::<Vec<String>>()
.join(",");
TokenStream::from(quote! {
impl #struct_name {
pub fn insert_query(&self, table: &str) -> String
{
let sqlquery = format!("insert into {} ( {} ) values ( {} )", table, #columns, #dollars);
sqlquery
}
pub async fn insert_raw(&self, pool: &sqlx::SqlitePool, table: &str) -> Result<sqlx::sqlite::SqliteQueryResult, sqlx::Error> {
let sql = self.insert_query(table);
sqlx::query(&sql)
#(
.bind(&self.#attributes)
)*
.execute(pool)
.await
}
pub fn update_query(&self, table: &str) -> String
{
let sqlquery = format!("update {} set {} where id = $1", table, #pairs);
sqlquery
}
pub async fn update_raw(&self, pool: &sqlx::SqlitePool, table: &str) -> Result<sqlx::sqlite::SqliteQueryResult, sqlx::Error> {
let sql = self.update_query(table);
sqlx::query(&sql)
#(
.bind(&self.#attributes_update)
)*
.execute(pool)
.await
}
}
})
}
/// Create method for inserting struts into Postgres database
///
/// ```rust,ignore
/// # #[tokio::main]
/// # async fn main() -> sqlx::Result<()> {
///
/// #[derive(Default, Debug, std::cmp::PartialEq, sqlx::FromRow)]
/// struct Car {
/// pub id: i32,
/// pub name: String,
/// }
///
/// #[derive(Default, Debug, sqlx::FromRow, sqlxinsert::PgInsert)]
/// struct CreateCar {
/// pub name: String,
/// pub color: Option<String>,
/// }
/// impl CreateCar {
/// pub fn new<T: Into<String>>(name: T) -> Self {
/// CreateCar {
/// name: name.into(),
/// color: None,
/// }
/// }
/// }
/// let url = "postgres://user:pass@localhost:5432/test_db";
/// let pool = sqlx::postgres::PgPoolOptions::new().connect(&url).await.unwrap();
///
/// let car_skoda = CreateCar::new("Skoda");
/// let res: Car = car_skoda.insert::<Car>(pool, "cars").await?;
/// # Ok(())
/// # }
/// ```
///
#[cfg(feature = "postgres")]
#[proc_macro_derive(PgInsert)]
pub fn derive_from_struct_psql(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let fields = match &input.data {
Data::Struct(DataStruct {
fields: Fields::Named(fields),
..
}) => &fields.named,
_ => panic!("expected a struct with named fields"),
};
// COMMON Atrributes
let struct_name = &input.ident;
// INSERT Attributes -> field names
let attributes = fields.iter().map(|field| &field.ident);
let attributes_ex = fields.iter().map(|field| &field.ident);
let attributes_vec: Vec<String> = fields
.iter()
.map(|field| {
field
.ident
.as_ref()
.map(ToString::to_string)
.unwrap_or_default()
})
.collect();
// ( id, name, hostname .. )
let columns = attributes_vec.join(",");
// ( $1, $2)
let dollars = dollar_values(attributes_vec.len());
// UPDATE Attributes -> field names for
let attributes_update = fields.iter().map(|field| &field.ident);
let attributes_update_ex = fields.iter().map(|field| &field.ident);
// name = $2, hostname = $3
let pairs: String = attributes_vec
.iter()
.enumerate()
.skip(1) // Skip the first element
.map(|(index, value)| {
let number = index + 1; // Start with $2
format!("{} = ${}", value, number)
})
.collect::<Vec<String>>()
.join(",");
TokenStream::from(quote! {
impl #struct_name {
fn insert_query(&self, table: &str) -> String
{
let sqlquery = format!("insert into {} ( {} ) values ( {} ) returning *", table, #columns, #dollars); // self.value_list()); //self.values );
sqlquery
}
pub async fn insert<T>(&self, pool: &sqlx::PgPool, table: &str) -> sqlx::Result<T>
where
T: Send,
T: for<'c> sqlx::FromRow<'c, sqlx::postgres::PgRow>,
T: std::marker::Unpin
{
let sql = self.insert_query(table);
// let mut pool = pool;
let res: T = sqlx::query_as::<_,T>(&sql)
#(
.bind(&self.#attributes) // let #field_name: #field_type = Default::default();
)*
.fetch_one(pool)
.await?;
Ok(res)
}
pub async fn insert_ex<'e,E>(&self, executor: E, table: &str) -> sqlx::Result<()>
where
E: sqlx::Executor<'e,Database = sqlx::Postgres>
{
let sql = self.insert_query(table);
// let mut pool = pool;
sqlx::query(&sql)
#(
.bind(&self.#attributes_ex) // let #field_name: #field_type = Default::default();
)*
.execute(executor)
.await?;
Ok(())
}
fn update_query(&self, table: &str) -> String
{
let sqlquery = format!("update {} set {} where id = $1 returning *", table, #pairs);
sqlquery
}
pub async fn update<T>(&self, pool: &sqlx::PgPool, table: &str) -> sqlx::Result<T>
where
T: Send,
T: for<'c> sqlx::FromRow<'c, sqlx::postgres::PgRow>,
T: std::marker::Unpin
{
let sql = self.update_query(table);
// let mut pool = pool;
let res: T = sqlx::query_as::<_,T>(&sql)
#(
.bind(&self.#attributes_update)// let #field_name: #field_type = Default::default();
)*
.fetch_one(pool)
.await?;
Ok(res)
}
pub async fn update_ex<'e,E>(&self, executor: E, table: &str) -> sqlx::Result<()>
where
E: sqlx::Executor<'e,Database = sqlx::Postgres>
{
let sql = self.update_query(table);
sqlx::query(&sql)
#(
.bind(&self.#attributes_update_ex)
)*
.execute(executor)
.await?;
Ok(())
}
}
})
}