rullst-orm-macros 2.0.0

Procedural macros for the rullst-orm ORM.
Documentation
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
use quote::quote;
use proc_macro2::TokenStream;
use crate::parser::ParsedModel;

/// Generates the magic methods for each field (where_field, order_by_field, etc)
fn generate_magic_methods(parsed: &ParsedModel) -> Vec<TokenStream> {
    let mut magic_methods = vec![];
    for field_name in &parsed.normal_fields {
        let field_name_str = field_name.to_string();
        
        let where_method = quote::format_ident!("where_{}", field_name);
        let or_where_method = quote::format_ident!("or_where_{}", field_name);
        let where_not_method = quote::format_ident!("where_not_{}", field_name);
        
        magic_methods.push(quote! {
            pub fn #where_method<T: Into<rullst_orm::EloquentValue>>(self, value: T) -> Self {
                self.where_eq(#field_name_str, value)
            }
            pub fn #or_where_method<T: Into<rullst_orm::EloquentValue>>(self, value: T) -> Self {
                self.or_where(#field_name_str, value)
            }
            pub fn #where_not_method<T: Into<rullst_orm::EloquentValue>>(self, value: T) -> Self {
                self.where_not_eq(#field_name_str, value)
            }
        });

        let order_by_method = quote::format_ident!("order_by_{}", field_name);
        let order_by_desc_method = quote::format_ident!("order_by_{}_desc", field_name);
        magic_methods.push(quote! {
            pub fn #order_by_method(self) -> Self {
                self.order_by(#field_name_str)
            }
            pub fn #order_by_desc_method(self) -> Self {
                self.order_by_desc(#field_name_str)
            }
        });
    }
    magic_methods
}

/// Generates the delete_all logic based on soft deletes
fn generate_delete_all_logic(has_soft_deletes: bool, table_name: &str) -> TokenStream {
    if has_soft_deletes {
        quote! {
            let mut query_str = format!("UPDATE {} SET deleted_at = CURRENT_TIMESTAMP", #table_name);
        }
    } else {
        quote! {
            let mut query_str = format!("DELETE FROM {}", #table_name);
        }
    }
}

pub fn generate(
    parsed: &ParsedModel,
    relation_flags: &[TokenStream],
    relation_inits: &[TokenStream],
    relation_methods: &[TokenStream],
    eager_loads: &TokenStream,
) -> TokenStream {
    let name = &parsed.name;
    let column_enum_name = quote::format_ident!("{}Column", name);
    let builder_name = quote::format_ident!("{}QueryBuilder", name);
    let table_name = &parsed.table_name;
    let has_soft_deletes = parsed.has_soft_deletes;
    let hook_after_fetch = if !parsed.after_fetch.is_empty() {
        let method = syn::Ident::new(&parsed.after_fetch, name.span());
        quote! { 
            let futures = results.iter_mut().map(|model| model.#method());
            rullst_orm::futures::future::try_join_all(futures).await?;
        }
    } else {
        quote! {}
    };

    let delete_all_logic = generate_delete_all_logic(has_soft_deletes, table_name);
    let magic_methods = generate_magic_methods(parsed);

    quote! {
        #[derive(Clone)]
        pub struct #builder_name {
            pub selects: Option<String>,
            pub is_distinct: bool,
            pub limit: Option<usize>,
            pub offset: Option<usize>,
            pub order_by: Option<String>,
            pub group_by: Option<String>,
            pub joins: Vec<String>,
            pub wheres: Vec<(String, String)>,
            pub havings: Vec<(String, String)>,
            pub bindings: Vec<rullst_orm::EloquentValue>,
            pub with_trashed: bool,
            pub only_trashed: bool,
            #[cfg(feature = "redis")]
            pub remember_ttl: Option<usize>,
            #(#relation_flags)*
        }

        impl rullst_orm::schema::SubqueryBuilder for #builder_name {
            fn to_sql(&self) -> String {
                self.to_sql()
            }
            fn bindings(&self) -> &Vec<rullst_orm::EloquentValue> {
                &self.bindings
            }
        }

        impl #builder_name {
            pub fn new() -> Self {
                Self {
                    selects: None,
                    is_distinct: false,
                    limit: None,
                    offset: None,
                    order_by: None,
                    group_by: None,
                    joins: vec![],
                    wheres: vec![],
                    havings: vec![],
                    bindings: vec![],
                    with_trashed: false,
                    only_trashed: false,
                    #[cfg(feature = "redis")]
                    remember_ttl: None,
                    #(#relation_inits)*
                }
            }

            #(#relation_methods)*

            #[cfg(feature = "redis")]
            pub fn remember(mut self, seconds: usize) -> Self {
                self.remember_ttl = Some(seconds);
                self
            }

            /// Executes a raw WHERE clause. 
            /// WARNING: Do not pass user input directly into `query` as it can cause SQL Injection.
            /// Always use parameterized bindings when dealing with user data.
            pub fn where_raw(mut self, query: &str) -> Self {
                self.wheres.push(("AND".to_string(), query.to_string()));
                self
            }

            pub fn or_where_raw(mut self, query: &str) -> Self {
                self.wheres.push(("OR".to_string(), query.to_string()));
                self
            }

            pub fn where_exists<B: rullst_orm::schema::SubqueryBuilder>(mut self, subquery: B) -> Self {
                let sql = subquery.to_sql();
                self.wheres.push(("AND".to_string(), format!("EXISTS ({})", sql)));
                for binding in subquery.bindings() {
                    self.bindings.push(binding.clone());
                }
                self
            }

            pub fn or_where_exists<B: rullst_orm::schema::SubqueryBuilder>(mut self, subquery: B) -> Self {
                let sql = subquery.to_sql();
                self.wheres.push(("OR".to_string(), format!("EXISTS ({})", sql)));
                for binding in subquery.bindings() {
                    self.bindings.push(binding.clone());
                }
                self
            }

            /// Executes a raw SELECT clause. 
            /// WARNING: Make sure to avoid user input concatenation in the select string.
            pub fn select_raw(mut self, query: &str) -> Self {
                self.selects = Some(query.to_string());
                self
            }

            pub fn distinct(mut self) -> Self {
                self.is_distinct = true;
                self
            }

            pub fn with_trashed(mut self) -> Self {
                self.with_trashed = true;
                self
            }

            pub fn only_trashed(mut self) -> Self {
                self.only_trashed = true;
                self
            }

            pub fn join_constrained<F>(mut self, table: &str, modifier: F) -> Self
            where F: FnOnce(&mut rullst_orm::JoinClause) -> &mut rullst_orm::JoinClause
            {
                let mut clause = rullst_orm::JoinClause::new("INNER");
                modifier(&mut clause);
                self.joins.push(format!("INNER JOIN {} ON {}", table, clause.to_sql()));
                for binding in clause.bindings {
                    self.bindings.push(binding);
                }
                self
            }

            pub fn join(mut self, table: &str, first: &str, operator: &str, second: &str) -> Self {
                self.joins.push(format!("INNER JOIN {} ON {} {} {}", table, first, operator, second));
                self
            }

            pub fn left_join(mut self, table: &str, first: &str, operator: &str, second: &str) -> Self {
                self.joins.push(format!("LEFT JOIN {} ON {} {} {}", table, first, operator, second));
                self
            }

            pub fn right_join(mut self, table: &str, first: &str, operator: &str, second: &str) -> Self {
                self.joins.push(format!("RIGHT JOIN {} ON {} {} {}", table, first, operator, second));
                self
            }

            pub fn where_eq<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} = ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn where_not_eq<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} != ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn where_gt<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} > ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn where_lt<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} < ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn where_like<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} LIKE ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn where_not_like<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} NOT LIKE ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn where_null(mut self, column: &str) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} IS NULL", column)));
                self
            }

            pub fn select(mut self, columns: &[&str]) -> Self {
                self.selects = Some(columns.join(", "));
                self
            }

            pub fn select_cols(mut self, cols: &[#column_enum_name]) -> Self {
                let s = cols.iter().map(|c| c.as_str()).collect::<Vec<_>>().join(", ");
                self.selects = Some(s);
                self
            }

            pub fn where_col<T: Into<rullst_orm::EloquentValue>>(mut self, col: #column_enum_name, value: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} = ?", col.as_str())));
                self.bindings.push(value.into());
                self
            }

            pub fn order_by_col(mut self, col: #column_enum_name) -> Self {
                self.order_by = Some(col.as_str().to_string());
                self
            }

            pub fn order_by_desc_col(mut self, col: #column_enum_name) -> Self {
                self.order_by = Some(format!("{} DESC", col.as_str()));
                self
            }

            pub fn where_not_null(mut self, column: &str) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} IS NOT NULL", column)));
                self
            }

            /// WARNING: Ensure `column` does not contain user input to prevent SQL Injection.
            pub fn where_in<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, values: Vec<T>) -> Self {
                if values.is_empty() { return self; }
                let placeholders = vec!["?"; values.len()].join(", ");
                self.wheres.push(("AND".to_string(), format!("{} IN ({})", column, placeholders)));
                for v in values { self.bindings.push(v.into()); }
                self
            }

            pub fn where_not_in<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, values: Vec<T>) -> Self {
                if values.is_empty() { return self; }
                let placeholders = vec!["?"; values.len()].join(", ");
                self.wheres.push(("AND".to_string(), format!("{} NOT IN ({})", column, placeholders)));
                for v in values { self.bindings.push(v.into()); }
                self
            }

            pub fn where_between<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, min: T, max: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} BETWEEN ? AND ?", column)));
                self.bindings.push(min.into());
                self.bindings.push(max.into());
                self
            }

            pub fn where_not_between<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, min: T, max: T) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} NOT BETWEEN ? AND ?", column)));
                self.bindings.push(min.into());
                self.bindings.push(max.into());
                self
            }

            pub fn where_column(mut self, first: &str, second: &str) -> Self {
                self.wheres.push(("AND".to_string(), format!("{} = {}", first, second)));
                self
            }

            pub fn or_where<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("OR".to_string(), format!("{} = ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn or_where_not_eq<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("OR".to_string(), format!("{} != ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn or_where_gt<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("OR".to_string(), format!("{} > ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn or_where_lt<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("OR".to_string(), format!("{} < ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn or_where_like<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, value: T) -> Self {
                self.wheres.push(("OR".to_string(), format!("{} LIKE ?", column)));
                self.bindings.push(value.into());
                self
            }

            pub fn or_where_null(mut self, column: &str) -> Self {
                self.wheres.push(("OR".to_string(), format!("{} IS NULL", column)));
                self
            }

            pub fn or_where_not_null(mut self, column: &str) -> Self {
                self.wheres.push(("OR".to_string(), format!("{} IS NOT NULL", column)));
                self
            }

            /// WARNING: Ensure `column` does not contain user input to prevent SQL Injection.
            pub fn or_where_in<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, values: Vec<T>) -> Self {
                if values.is_empty() { return self; }
                let placeholders = vec!["?"; values.len()].join(", ");
                self.wheres.push(("OR".to_string(), format!("{} IN ({})", column, placeholders)));
                for v in values { self.bindings.push(v.into()); }
                self
            }

            pub fn or_where_between<T: Into<rullst_orm::EloquentValue>>(mut self, column: &str, min: T, max: T) -> Self {
                self.wheres.push(("OR".to_string(), format!("{} BETWEEN ? AND ?", column)));
                self.bindings.push(min.into());
                self.bindings.push(max.into());
                self
            }

            pub fn group_by(mut self, column: &str) -> Self {
                self.group_by = Some(column.to_string());
                self
            }

            pub fn order_by(mut self, column: &str) -> Self {
                self.order_by = Some(format!("{} ASC", column));
                self
            }

            pub fn order_by_desc(mut self, column: &str) -> Self {
                self.order_by = Some(format!("{} DESC", column));
                self
            }

            pub fn limit(mut self, value: usize) -> Self {
                self.limit = Some(value);
                self
            }

            pub fn offset(mut self, value: usize) -> Self {
                self.offset = Some(value);
                self
            }

            /// WARNING: This generates the raw SQL query. Ensure all dynamic table names and column names are validated.
            pub fn to_sql(&self) -> String {
                let select_clause = match &self.selects {
                    Some(s) => s.as_str(),
                    None => "*",
                };
                let distinct = if self.is_distinct { "DISTINCT " } else { "" };
                
                // Estimate capacity: SELECT + FROM + table + joins + wheres
                let estimated_capacity = 50 + #table_name.len() + self.joins.iter().map(|j| j.len() + 1).sum::<usize>() 
                    + self.wheres.iter().map(|(o, c)| o.len() + c.len() + 4).sum::<usize>();
                let mut sql = String::with_capacity(estimated_capacity);
                
                sql.push_str("SELECT ");
                if self.is_distinct {
                    sql.push_str("DISTINCT ");
                }
                sql.push_str(select_clause);
                sql.push_str(" FROM ");
                sql.push_str(#table_name);

                for join in &self.joins {
                    sql.push(' ');
                    sql.push_str(join);
                }

                let mut first_where = true;
                if !self.wheres.is_empty() {
                    sql.push_str(" WHERE ");
                    for (op, cond) in &self.wheres {
                        if first_where {
                            sql.push('(');
                            sql.push_str(cond);
                            sql.push(')');
                            first_where = false;
                        } else {
                            sql.push(' ');
                            sql.push_str(op);
                            sql.push_str(" (");
                            sql.push_str(cond);
                            sql.push(')');
                        }
                    }
                }

                if #has_soft_deletes && !self.with_trashed {
                    if first_where {
                        sql.push_str(" WHERE ");
                    } else {
                        sql.push_str(" AND ");
                    }
                    if self.only_trashed {
                        sql.push_str("deleted_at IS NOT NULL");
                    } else {
                        sql.push_str("deleted_at IS NULL");
                    }
                }

                if let Some(group) = &self.group_by {
                    sql.push_str(" GROUP BY ");
                    sql.push_str(group);
                }

                let mut first_having = true;
                if !self.havings.is_empty() {
                    sql.push_str(" HAVING ");
                    for (op, cond) in &self.havings {
                        if first_having {
                            sql.push('(');
                            sql.push_str(cond);
                            sql.push(')');
                            first_having = false;
                        } else {
                            sql.push(' ');
                            sql.push_str(op);
                            sql.push_str(" (");
                            sql.push_str(cond);
                            sql.push(')');
                        }
                    }
                }

                if let Some(order) = &self.order_by {
                    sql.push_str(" ORDER BY ");
                    sql.push_str(order);
                }

                if let Some(limit) = self.limit {
                    sql.push_str(" LIMIT ");
                    sql.push_str(&limit.to_string());
                }
                if let Some(offset) = self.offset {
                    sql.push_str(" OFFSET ");
                    sql.push_str(&offset.to_string());
                }

                sql
            }

            pub async fn get(&self) -> Result<Vec<#name>, rullst_orm::sqlx::Error> {
                let pool = rullst_orm::Orm::read_pool();
                self.get_with_tx_internal(pool).await
            }

            pub async fn get_with_tx(&self, tx: &mut rullst_orm::sqlx::Transaction<'static, rullst_orm::EloquentDatabase>) -> Result<Vec<#name>, rullst_orm::sqlx::Error> {
                self.get_with_tx_internal(&mut **tx).await
            }

            async fn get_with_tx_internal<'e, E>(&self, executor: E) -> Result<Vec<#name>, rullst_orm::sqlx::Error> 
            where E: rullst_orm::sqlx::Executor<'e, Database = rullst_orm::EloquentDatabase>
            {
                let query_str = self.to_sql();

                #[cfg(feature = "redis")]
                {
                    if let Some(ttl) = self.remember_ttl {
                        use rullst_orm::redis::AsyncCommands;
                        let cache_key = format!("orm:cache:{}:{:?}", #table_name, (&query_str, &self.bindings));
                        let mut conn = rullst_orm::Orm::redis_manager();
                        if let Ok(cached_data) = conn.get::<_, String>(&cache_key).await {
                            if !cached_data.is_empty() {
                                if let Ok(mut results) = #name::from_cache_json_array(&cached_data) {
                                    #hook_after_fetch
                                    #eager_loads
                                    return Ok(results);
                                }
                            }
                        }
                    }
                }

                if rullst_orm::schema::is_query_log_enabled() {
                    println!("[SQL Debug] {:?} | Bindings: {:?}", query_str, self.bindings);
                }
                let mut results: Vec<#name> = {
                    let mut query = rullst_orm::sqlx::query_as::<_, #name>(rullst_orm::sqlx::AssertSqlSafe(query_str.as_str()));
                    for binding in &self.bindings {
                        match binding {
                            rullst_orm::EloquentValue::String(s) => { query = query.bind(s.clone()); }
                            rullst_orm::EloquentValue::Int(i) => { query = query.bind(*i); }
                            rullst_orm::EloquentValue::Float(f) => { query = query.bind(*f); }
                            rullst_orm::EloquentValue::Bool(b) => { query = query.bind(*b); }
                        }
                    }
                    query.fetch_all(executor).await?
                };
                
                #[cfg(feature = "redis")]
                {
                    if let Some(ttl) = self.remember_ttl {
                        use rullst_orm::redis::AsyncCommands;
                        let cache_key = format!("orm:cache:{}:{:?}", #table_name, (&query_str, &self.bindings));
                        let serialized = #name::to_cache_json_array(&results);
                        let mut conn = rullst_orm::Orm::redis_manager();
                        let _: Result<(), rullst_orm::redis::RedisError> = conn.set_ex(&cache_key, serialized, ttl as u64).await;
                    }
                }

                #hook_after_fetch
                #eager_loads
                Ok(results)
            }

            pub async fn first(&self) -> Result<Option<#name>, rullst_orm::sqlx::Error> {
                let mut builder = self.clone();
                builder.limit = Some(1);
                let results = builder.get().await?;
                Ok(results.into_iter().next())
            }

            pub async fn first_with_tx(&self, tx: &mut rullst_orm::sqlx::Transaction<'static, rullst_orm::EloquentDatabase>) -> Result<Option<#name>, rullst_orm::sqlx::Error> {
                let mut builder = self.clone();
                builder.limit = Some(1);
                let results = builder.get_with_tx(tx).await?;
                Ok(results.into_iter().next())
            }

            pub async fn paginate(&self, page: usize, per_page: usize) -> Result<rullst_orm::PaginationResult<#name>, rullst_orm::sqlx::Error> {
                let total_builder = Self {
                    selects: Some("COUNT(*)".to_string()),
                    limit: None,
                    offset: None,
                    order_by: None,
                    is_distinct: self.is_distinct.clone(),
                    joins: self.joins.clone(),
                    wheres: self.wheres.clone(),
                    havings: self.havings.clone(),
                    bindings: self.bindings.clone(),
                    group_by: self.group_by.clone(),
                    with_trashed: self.with_trashed,
                    only_trashed: self.only_trashed,
                    ..self.clone()
                };
                
                let query_str = total_builder.to_sql();
                if rullst_orm::schema::is_query_log_enabled() {
                    println!("[SQL Debug] {:?} | Bindings: {:?}", query_str, total_builder.bindings);
                }
                let pool = rullst_orm::Orm::read_pool();
                let total_row: (i64,) = {
                    let mut query = rullst_orm::sqlx::query_as::<_, (i64,)>(rullst_orm::sqlx::AssertSqlSafe(query_str.as_str()));
                    for binding in &total_builder.bindings {
                        match binding {
                            rullst_orm::EloquentValue::String(s) => { query = query.bind(s.clone()); }
                            rullst_orm::EloquentValue::Int(i) => { query = query.bind(*i); }
                            rullst_orm::EloquentValue::Float(f) => { query = query.bind(*f); }
                            rullst_orm::EloquentValue::Bool(b) => { query = query.bind(*b); }
                        }
                    }
                    query.fetch_one(pool).await?
                };
                let total = total_row.0;
                let last_page = (total as f64 / per_page as f64).ceil() as usize;
                
                let mut data_builder = self.clone();
                data_builder.limit = Some(per_page);
                if page > 1 {
                    data_builder.offset = Some((page - 1) * per_page);
                }
                let data = data_builder.get().await?;
                
                Ok(rullst_orm::PaginationResult {
                    data,
                    total,
                    per_page,
                    current_page: if page == 0 { 1 } else { page },
                    last_page,
                })
            }

            pub async fn count(&self) -> Result<i64, rullst_orm::sqlx::Error> {
                let pool = rullst_orm::Orm::read_pool();
                let mut builder = self.clone();
                builder.selects = Some("COUNT(*)".to_string());
                builder.limit = None;
                builder.offset = None;
                builder.order_by = None;
                let query_str = builder.to_sql();
                if rullst_orm::schema::is_query_log_enabled() {
                    println!("[SQL Debug] {:?} | Bindings: {:?}", query_str, builder.bindings);
                }
                
                let row: (i64,) = {
                    let mut query = rullst_orm::sqlx::query_as::<_, (i64,)>(rullst_orm::sqlx::AssertSqlSafe(query_str.as_str()));
                    for binding in &builder.bindings {
                        match binding {
                            rullst_orm::EloquentValue::String(s) => { query = query.bind(s.clone()); }
                            rullst_orm::EloquentValue::Int(i) => { query = query.bind(*i); }
                            rullst_orm::EloquentValue::Float(f) => { query = query.bind(*f); }
                            rullst_orm::EloquentValue::Bool(b) => { query = query.bind(*b); }
                        }
                    }
                    query.fetch_one(pool).await?
                };
                Ok(row.0)
            }

            pub async fn chunk<F, Fut>(&self, size: usize, mut handler: F) -> Result<(), rullst_orm::sqlx::Error>
            where
                F: FnMut(Vec<#name>) -> Fut + Send,
                Fut: std::future::Future<Output = ()> + Send,
            {
                let mut page = 1;
                loop {
                    let mut builder = self.clone();
                    builder.limit = Some(size);
                    builder.offset = Some((page - 1) * size);
                    let results = builder.get().await?;
                    let count = results.len();
                    if count == 0 { break; }
                    handler(results).await;
                    if count < size { break; }
                    page += 1;
                }
                Ok(())
            }

            pub async fn chunk_with_tx<F, Fut>(&self, size: usize, tx: &mut rullst_orm::sqlx::Transaction<'static, rullst_orm::EloquentDatabase>, mut handler: F) -> Result<(), rullst_orm::sqlx::Error>
            where
                F: FnMut(Vec<#name>) -> Fut + Send,
                Fut: std::future::Future<Output = ()> + Send,
            {
                let mut page = 1;
                loop {
                    let mut builder = self.clone();
                    builder.limit = Some(size);
                    builder.offset = Some((page - 1) * size);
                    let results = builder.get_with_tx(tx).await?;
                    let count = results.len();
                    if count == 0 { break; }
                    handler(results).await;
                    if count < size { break; }
                    page += 1;
                }
                Ok(())
            }

            pub async fn delete_all(&self) -> Result<u64, rullst_orm::sqlx::Error> {
                let pool = rullst_orm::Orm::pool();
                self.delete_all_with_tx_internal(pool).await
            }

            pub async fn delete_all_with_tx(&self, tx: &mut rullst_orm::sqlx::Transaction<'static, rullst_orm::EloquentDatabase>) -> Result<u64, rullst_orm::sqlx::Error> {
                self.delete_all_with_tx_internal(&mut **tx).await
            }

            async fn delete_all_with_tx_internal<'e, E>(&self, executor: E) -> Result<u64, rullst_orm::sqlx::Error> 
            where E: rullst_orm::sqlx::Executor<'e, Database = rullst_orm::EloquentDatabase>
            {
                #delete_all_logic
                
                if !self.wheres.is_empty() {
                    query_str.push_str(" WHERE ");
                    let mut first = true;
                    for (operator, condition) in &self.wheres {
                        if first {
                            query_str.push_str(&format!("({})", condition));
                            first = false;
                        } else {
                            query_str.push_str(&format!(" {} ({})", operator, condition));
                        }
                    }
                }

                let result = {
                    let mut query = rullst_orm::sqlx::query(rullst_orm::sqlx::AssertSqlSafe(query_str.as_str()));
                    for binding in &self.bindings {
                        match binding {
                            rullst_orm::EloquentValue::String(s) => { query = query.bind(s.clone()); }
                            rullst_orm::EloquentValue::Int(i) => { query = query.bind(*i); }
                            rullst_orm::EloquentValue::Float(f) => { query = query.bind(*f); }
                            rullst_orm::EloquentValue::Bool(b) => { query = query.bind(*b); }
                        }
                    }
                    query.execute(executor).await?
                };
                Ok(result.rows_affected())
            }

            pub async fn pluck_string(&self, column: &str) -> Result<Vec<String>, rullst_orm::sqlx::Error> {
                let pool = rullst_orm::Orm::read_pool();
                let mut builder = self.clone();
                builder.selects = Some(column.to_string());
                let query_str = builder.to_sql();
                let rows: Vec<(String,)> = {
                    let mut query = rullst_orm::sqlx::query_as::<_, (String,)>(rullst_orm::sqlx::AssertSqlSafe(query_str.as_str()));
                    for binding in &builder.bindings {
                        match binding {
                            rullst_orm::EloquentValue::String(s) => { query = query.bind(s.clone()); }
                            rullst_orm::EloquentValue::Int(i) => { query = query.bind(*i); }
                            rullst_orm::EloquentValue::Float(f) => { query = query.bind(*f); }
                            rullst_orm::EloquentValue::Bool(b) => { query = query.bind(*b); }
                        }
                    }
                    query.fetch_all(pool).await?
                };
                Ok(rows.into_iter().map(|(s,)| s).collect())
            }

            pub async fn pluck_i32(&self, column: &str) -> Result<Vec<i32>, rullst_orm::sqlx::Error> {
                let pool = rullst_orm::Orm::read_pool();
                let mut builder = self.clone();
                builder.selects = Some(column.to_string());
                let query_str = builder.to_sql();
                let rows: Vec<(i32,)> = {
                    let mut query = rullst_orm::sqlx::query_as::<_, (i32,)>(rullst_orm::sqlx::AssertSqlSafe(query_str.as_str()));
                    for binding in &builder.bindings {
                        match binding {
                            rullst_orm::EloquentValue::String(s) => { query = query.bind(s.clone()); }
                            rullst_orm::EloquentValue::Int(i) => { query = query.bind(*i); }
                            rullst_orm::EloquentValue::Float(f) => { query = query.bind(*f); }
                            rullst_orm::EloquentValue::Bool(b) => { query = query.bind(*b); }
                        }
                    }
                    query.fetch_all(pool).await?
                };
                Ok(rows.into_iter().map(|(s,)| s).collect())
            }

            #(#magic_methods)*
        }
    }
}