1use proc_macro::TokenStream;
2use proc_macro2;
3use quote::quote;
4use syn::{parse::Parser, parse_macro_input, Data, DataStruct, DeriveInput, Fields, Meta};
5
6#[proc_macro_derive(ModelMeta, attributes(model))]
30pub fn derive_model_meta(input: TokenStream) -> TokenStream {
31 let input = parse_macro_input!(input as DeriveInput);
32 let name = &input.ident;
33
34 let mut table_name = None;
36 let mut pk_field = None;
37 let mut soft_delete_field = None;
38
39 for attr in &input.attrs {
40 if attr.path().is_ident("model") {
41 if let syn::Meta::List(list) = &attr.meta {
43 let parser = syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated;
45 if let Ok(metas) = parser.parse2(list.tokens.clone()) {
46 for meta in metas {
47 if let Meta::NameValue(nv) = meta {
48 if nv.path.is_ident("table") {
49 if let syn::Expr::Lit(syn::ExprLit {
50 lit: syn::Lit::Str(s),
51 ..
52 }) = nv.value
53 {
54 table_name = Some(s.value());
55 }
56 } else if nv.path.is_ident("pk") {
57 if let syn::Expr::Lit(syn::ExprLit {
58 lit: syn::Lit::Str(s),
59 ..
60 }) = nv.value
61 {
62 pk_field = Some(s.value());
63 }
64 } else if nv.path.is_ident("soft_delete") {
65 if let syn::Expr::Lit(syn::ExprLit {
66 lit: syn::Lit::Str(s),
67 ..
68 }) = nv.value
69 {
70 soft_delete_field = Some(s.value());
71 }
72 }
73 }
74 }
75 }
76 } else if let syn::Meta::NameValue(nv) = &attr.meta {
77 if nv.path.is_ident("table") {
79 if let syn::Expr::Lit(syn::ExprLit {
80 lit: syn::Lit::Str(s),
81 ..
82 }) = &nv.value
83 {
84 table_name = Some(s.value());
85 }
86 } else if nv.path.is_ident("pk") {
87 if let syn::Expr::Lit(syn::ExprLit {
88 lit: syn::Lit::Str(s),
89 ..
90 }) = &nv.value
91 {
92 pk_field = Some(s.value());
93 }
94 } else if nv.path.is_ident("soft_delete") {
95 if let syn::Expr::Lit(syn::ExprLit {
96 lit: syn::Lit::Str(s),
97 ..
98 }) = &nv.value
99 {
100 soft_delete_field = Some(s.value());
101 }
102 }
103 }
104 }
105 }
106
107 let table = table_name.unwrap_or_else(|| {
109 let s = name.to_string();
110 let mut result = String::new();
112 for (i, c) in s.chars().enumerate() {
113 if c.is_uppercase() && i > 0 {
114 result.push('_');
115 }
116 result.push(c.to_ascii_lowercase());
117 }
118 result
119 });
120
121 let pk = pk_field.unwrap_or_else(|| "id".to_string());
123
124 let expanded = if let Some(soft_delete) = soft_delete_field {
126 let soft_delete_lit = syn::LitStr::new(&soft_delete, proc_macro2::Span::call_site());
128 quote! {
129 impl sqlxplus::Model for #name {
130 const TABLE: &'static str = #table;
131 const PK: &'static str = #pk;
132 const SOFT_DELETE_FIELD: Option<&'static str> = Some(#soft_delete_lit);
133 }
134 }
135 } else {
136 quote! {
138 impl sqlxplus::Model for #name {
139 const TABLE: &'static str = #table;
140 const PK: &'static str = #pk;
141 const SOFT_DELETE_FIELD: Option<&'static str> = None;
142 }
143 }
144 };
145
146 TokenStream::from(expanded)
147}
148
149#[proc_macro_derive(CRUD, attributes(model, skip))]
175pub fn derive_crud(input: TokenStream) -> TokenStream {
176 let input = parse_macro_input!(input as DeriveInput);
177 let name = &input.ident;
178
179 let mut pk_field = None;
181 for attr in &input.attrs {
182 if attr.path().is_ident("model") {
183 if let syn::Meta::List(list) = &attr.meta {
184 let parser = syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated;
185 if let Ok(metas) = parser.parse2(list.tokens.clone()) {
186 for meta in metas {
187 if let Meta::NameValue(nv) = meta {
188 if nv.path.is_ident("pk") {
189 if let syn::Expr::Lit(syn::ExprLit {
190 lit: syn::Lit::Str(s),
191 ..
192 }) = nv.value
193 {
194 pk_field = Some(s.value());
195 }
196 }
197 }
198 }
199 }
200 } else if let syn::Meta::NameValue(nv) = &attr.meta {
201 if nv.path.is_ident("pk") {
202 if let syn::Expr::Lit(syn::ExprLit {
203 lit: syn::Lit::Str(s),
204 ..
205 }) = &nv.value
206 {
207 pk_field = Some(s.value());
208 }
209 }
210 }
211 }
212 }
213 let pk = pk_field.unwrap_or_else(|| "id".to_string());
215
216 let fields = match &input.data {
218 Data::Struct(DataStruct {
219 fields: Fields::Named(fields),
220 ..
221 }) => &fields.named,
222 _ => {
223 return syn::Error::new_spanned(
224 name,
225 "CRUD derive only supports structs with named fields",
226 )
227 .to_compile_error()
228 .into();
229 }
230 };
231
232 let mut pk_ident_opt: Option<&syn::Ident> = None;
236
237 let mut insert_normal_field_names: Vec<&syn::Ident> = Vec::new();
239 let mut insert_normal_field_columns: Vec<syn::LitStr> = Vec::new();
240 let mut insert_option_field_names: Vec<&syn::Ident> = Vec::new();
241 let mut insert_option_field_columns: Vec<syn::LitStr> = Vec::new();
242
243 let mut update_normal_field_names: Vec<&syn::Ident> = Vec::new();
245 let mut update_normal_field_columns: Vec<syn::LitStr> = Vec::new();
246 let mut update_option_field_names: Vec<&syn::Ident> = Vec::new();
247 let mut update_option_field_columns: Vec<syn::LitStr> = Vec::new();
248
249 for field in fields {
250 let field_name = field.ident.as_ref().unwrap();
251 let field_name_str = field_name.to_string();
252
253 let mut skip = false;
255 for attr in &field.attrs {
256 if attr.path().is_ident("skip") || attr.path().is_ident("model") {
257 skip = true;
258 break;
259 }
260 }
261
262 if !skip {
263 if field_name_str == pk {
264 pk_ident_opt = Some(field_name);
266 } else {
267 let is_opt = is_option_type(&field.ty);
269 let col_lit = syn::LitStr::new(&field_name_str, proc_macro2::Span::call_site());
270
271 if is_opt {
272 insert_option_field_names.push(field_name);
273 insert_option_field_columns.push(col_lit.clone());
274
275 update_option_field_names.push(field_name);
276 update_option_field_columns.push(col_lit);
277 } else {
278 insert_normal_field_names.push(field_name);
279 insert_normal_field_columns.push(col_lit.clone());
280
281 update_normal_field_names.push(field_name);
282 update_normal_field_columns.push(col_lit);
283 }
284 }
285 }
286 }
287
288 let pk_ident = pk_ident_opt.expect("Primary key field not found in struct");
290
291 let expanded = quote! {
293 #[async_trait::async_trait]
295 impl sqlxplus::Crud for #name {
296 async fn insert<'e, 'c: 'e, DB, E>(&self, executor: E) -> sqlxplus::Result<sqlxplus::crud::Id>
298 where
299 DB: sqlx::Database + sqlxplus::DatabaseInfo,
300 for<'a> DB::Arguments<'a>: sqlx::IntoArguments<'a, DB>,
301 E: sqlxplus::DatabaseType<DB = DB>
302 + sqlx::Executor<'c, Database = DB>
303 + Send,
304 i64: sqlx::Type<DB> + for<'r> sqlx::Decode<'r, DB>,
305 usize: sqlx::ColumnIndex<DB::Row>,
306 String: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
308 i64: for<'b> sqlx::Encode<'b, DB>,
309 i32: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
310 i16: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
311 Option<String>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
312 Option<i64>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
313 Option<i32>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
314 Option<i16>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
315 chrono::DateTime<chrono::Utc>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
316 Option<chrono::DateTime<chrono::Utc>>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
317 serde_json::Value: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
318 Option<serde_json::Value>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
319 {
320 use sqlxplus::Model;
321 use sqlxplus::DatabaseInfo;
322 use sqlxplus::db_pool::DbDriver;
323 let table = Self::TABLE;
324 let escaped_table = DB::escape_identifier(table);
325
326 let mut columns: Vec<&str> = Vec::new();
328 let mut placeholders: Vec<String> = Vec::new();
329 let mut placeholder_index = 0;
330
331 #(
333 columns.push(#insert_normal_field_columns);
334 placeholders.push(DB::placeholder(placeholder_index));
335 placeholder_index += 1;
336 )*
337
338 #(
340 if self.#insert_option_field_names.is_some() {
341 columns.push(#insert_option_field_columns);
342 placeholders.push(DB::placeholder(placeholder_index));
343 placeholder_index += 1;
344 }
345 )*
346
347 let sql = match DB::get_driver() {
349 DbDriver::Postgres => {
350 let pk = Self::PK;
351 let escaped_pk = DB::escape_identifier(pk);
352 format!(
353 "INSERT INTO {} ({}) VALUES ({}) RETURNING {}",
354 escaped_table,
355 columns.join(", "),
356 placeholders.join(", "),
357 escaped_pk
358 )
359 }
360 _ => {
361 format!(
362 "INSERT INTO {} ({}) VALUES ({})",
363 escaped_table,
364 columns.join(", "),
365 placeholders.join(", ")
366 )
367 }
368 };
369
370 match DB::get_driver() {
372 DbDriver::Postgres => {
373 let mut query = sqlx::query_scalar::<_, i64>(&sql);
374 #(
376 query = query.bind(&self.#insert_normal_field_names);
377 )*
378 #(
380 if let Some(ref val) = self.#insert_option_field_names {
381 query = query.bind(val);
382 }
383 )*
384 let id: i64 = query.fetch_one(executor).await?;
385 Ok(id)
386 }
387 DbDriver::MySql => {
388 let mut query = sqlx::query(&sql);
389 #(
391 query = query.bind(&self.#insert_normal_field_names);
392 )*
393 #(
395 if let Some(ref val) = self.#insert_option_field_names {
396 query = query.bind(val);
397 }
398 )*
399 let result = query.execute(executor).await?;
400 unsafe {
404 use sqlx::mysql::MySqlQueryResult;
405 let ptr: *const DB::QueryResult = &result;
406 let mysql_ptr = ptr as *const MySqlQueryResult;
407 Ok((*mysql_ptr).last_insert_id() as i64)
408 }
409 }
410 DbDriver::Sqlite => {
411 let mut query = sqlx::query(&sql);
412 #(
414 query = query.bind(&self.#insert_normal_field_names);
415 )*
416 #(
418 if let Some(ref val) = self.#insert_option_field_names {
419 query = query.bind(val);
420 }
421 )*
422 let result = query.execute(executor).await?;
423 unsafe {
425 use sqlx::sqlite::SqliteQueryResult;
426 let ptr: *const DB::QueryResult = &result;
427 let sqlite_ptr = ptr as *const SqliteQueryResult;
428 Ok((*sqlite_ptr).last_insert_rowid() as i64)
429 }
430 }
431 }
432 }
433
434 async fn update<'e, 'c: 'e, DB, E>(&self, executor: E) -> sqlxplus::Result<()>
436 where
437 DB: sqlx::Database + sqlxplus::DatabaseInfo,
438 for<'a> DB::Arguments<'a>: sqlx::IntoArguments<'a, DB>,
439 E: sqlxplus::DatabaseType<DB = DB>
440 + sqlx::Executor<'c, Database = DB>
441 + Send,
442 String: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
444 i64: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
445 i32: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
446 i16: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
447 Option<String>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
448 Option<i64>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
449 Option<i32>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
450 Option<i16>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
451 chrono::DateTime<chrono::Utc>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
452 Option<chrono::DateTime<chrono::Utc>>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
453 serde_json::Value: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
454 Option<serde_json::Value>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
455 {
456 use sqlxplus::Model;
457 use sqlxplus::DatabaseInfo;
458 let table = Self::TABLE;
459 let pk = Self::PK;
460 let escaped_table = DB::escape_identifier(table);
461 let escaped_pk = DB::escape_identifier(pk);
462
463 let mut set_parts: Vec<String> = Vec::new();
465 let mut placeholder_index = 0;
466
467 #(
469 set_parts.push(format!("{} = {}", DB::escape_identifier(#update_normal_field_columns), DB::placeholder(placeholder_index)));
470 placeholder_index += 1;
471 )*
472
473 #(
475 if self.#update_option_field_names.is_some() {
476 set_parts.push(format!("{} = {}", DB::escape_identifier(#update_option_field_columns), DB::placeholder(placeholder_index)));
477 placeholder_index += 1;
478 }
479 )*
480
481 if set_parts.is_empty() {
482 return Ok(());
483 }
484
485 let sql = format!(
486 "UPDATE {} SET {} WHERE {} = {}",
487 escaped_table,
488 set_parts.join(", "),
489 escaped_pk,
490 DB::placeholder(placeholder_index)
491 );
492
493 let mut query = sqlx::query(&sql);
494 #(
496 query = query.bind(&self.#update_normal_field_names);
497 )*
498 #(
500 if let Some(ref val) = self.#update_option_field_names {
501 query = query.bind(val);
502 }
503 )*
504 query = query.bind(&self.#pk_ident);
505 query.execute(executor).await?;
506 Ok(())
507 }
508
509 async fn update_with_none<'e, 'c: 'e, DB, E>(&self, executor: E) -> sqlxplus::Result<()>
511 where
512 DB: sqlx::Database + sqlxplus::DatabaseInfo,
513 for<'a> DB::Arguments<'a>: sqlx::IntoArguments<'a, DB>,
514 E: sqlxplus::DatabaseType<DB = DB>
515 + sqlx::Executor<'c, Database = DB>
516 + Send,
517 String: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
519 i64: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
520 i32: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
521 i16: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
522 Option<String>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
523 Option<i64>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
524 Option<i32>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
525 Option<i16>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
526 chrono::DateTime<chrono::Utc>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
527 Option<chrono::DateTime<chrono::Utc>>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
528 serde_json::Value: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
529 Option<serde_json::Value>: sqlx::Type<DB> + for<'b> sqlx::Encode<'b, DB>,
530 {
531 use sqlxplus::Model;
532 use sqlxplus::DatabaseInfo;
533 use sqlxplus::db_pool::DbDriver;
534 let table = Self::TABLE;
535 let pk = Self::PK;
536 let escaped_table = DB::escape_identifier(table);
537 let escaped_pk = DB::escape_identifier(pk);
538
539 let mut set_parts: Vec<String> = Vec::new();
541 let mut placeholder_index = 0;
542
543 #(
545 set_parts.push(format!("{} = {}", DB::escape_identifier(#update_normal_field_columns), DB::placeholder(placeholder_index)));
546 placeholder_index += 1;
547 )*
548
549 match DB::get_driver() {
551 DbDriver::Sqlite => {
552 #(
554 if self.#update_option_field_names.is_some() {
555 set_parts.push(format!("{} = {}", DB::escape_identifier(#update_option_field_columns), DB::placeholder(placeholder_index)));
556 placeholder_index += 1;
557 }
558 )*
559 }
560 _ => {
561 #(
563 if self.#update_option_field_names.is_some() {
564 set_parts.push(format!("{} = {}", DB::escape_identifier(#update_option_field_columns), DB::placeholder(placeholder_index)));
565 placeholder_index += 1;
566 } else {
567 set_parts.push(format!("{} = DEFAULT", DB::escape_identifier(#update_option_field_columns)));
568 }
569 )*
570 }
571 }
572
573 if set_parts.is_empty() {
574 return Ok(());
575 }
576
577 let sql = format!(
578 "UPDATE {} SET {} WHERE {} = {}",
579 escaped_table,
580 set_parts.join(", "),
581 escaped_pk,
582 DB::placeholder(placeholder_index)
583 );
584
585 let mut query = sqlx::query(&sql);
586 #(
588 query = query.bind(&self.#update_normal_field_names);
589 )*
590 #(
592 if let Some(ref val) = self.#update_option_field_names {
593 query = query.bind(val);
594 }
595 )*
596 query = query.bind(&self.#pk_ident);
597 query.execute(executor).await?;
598 Ok(())
599 }
600 }
601 };
602
603 TokenStream::from(expanded)
604}
605
606fn is_option_type(ty: &syn::Type) -> bool {
608 if let syn::Type::Path(type_path) = ty {
609 if let Some(seg) = type_path.path.segments.last() {
610 if seg.ident == "Option" {
611 if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
612 return args.args.len() == 1;
613 }
614 }
615 }
616 }
617 false
618}