lume 0.13.1

A simple and intuitive Query Builder inspired by Drizzle
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
#![warn(missing_docs)]

//! # Query Module
//!
//! This module provides type-safe query building and execution functionality.
//! It includes the `Query<T>` struct for building and executing database queries.

use std::{fmt::Debug, marker::PhantomData, sync::Arc};

#[cfg(feature = "mysql")]
use sqlx::MySqlPool;
#[cfg(feature = "postgres")]
use sqlx::PgPool;
#[cfg(feature = "sqlite")]
use sqlx::SqlitePool;

use crate::dialects::get_dialect;
use crate::filter::{Filter, Filtered};
use crate::helpers::{StartingSql, bind_value, build_filter_expr, get_starting_sql};
use crate::schema::{ColumnInfo, Select, Value};
use crate::{database::error::DatabaseError, row::Row, schema::Schema};

/// A type-safe query builder for database operations.
///
/// The `Query<T, S>` struct provides a fluent interface for building and executing
/// database queries with compile-time type safety.
///
/// # Type Parameters
///
/// - `T`: The schema type to query (must implement `Schema + Debug`)
/// - `S`: The selection type for column specification (must implement `Select + Debug`)
///
/// # Features
///
/// - **Type Safety**: Compile-time type checking for all query operations
/// - **Fluent Interface**: Chainable methods for building complex queries
/// - **Filtering**: Support for WHERE clause conditions
/// - **MySQL Integration**: Built-in support for MySQL database operations
///
/// # Example
///
/// ```no_run
/// use lume::define_schema;
/// use lume::database::Database;
/// use lume::filter::Filter;
/// use lume::schema::{Schema, ColumnInfo};
/// use lume::filter::eq_value;
///
/// define_schema! {
///     User {
///         id: i32 [primary_key()],
///         name: String [not_null()],
///         age: i32,
///     }
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), lume::database::error::DatabaseError> {
///     let db = Database::connect("mysql://...").await?;
///     let users = db.query::<User, SelectUser>()
///         .filter(eq_value(User::name(), Value::String("John".to_string())))
///         .execute()
///         .await?;
///     Ok(())
/// }
/// ```
#[derive(Debug)]
pub struct Query<T, S> {
    /// Phantom data to maintain schema type information
    pub(crate) table: PhantomData<T>,
    /// List of filters to apply to the query
    pub(crate) filters: Vec<Box<dyn Filtered>>,

    #[cfg(feature = "mysql")]
    /// Database connection pool
    pub(crate) conn: Arc<MySqlPool>,

    #[cfg(feature = "postgres")]
    /// Database connection pool
    pub(crate) conn: Arc<PgPool>,

    #[cfg(feature = "sqlite")]
    /// Database connection pool
    pub(crate) conn: Arc<SqlitePool>,

    pub(crate) select: Option<S>,
    pub(crate) distinct: bool,

    pub(crate) joins: Vec<JoinInfo>,

    pub(crate) limit: Option<u64>,
    pub(crate) offset: Option<u64>,
}

/// Information about a join operation
#[derive(Debug)]
pub(crate) struct JoinInfo {
    /// The table to join
    pub(crate) table_name: String,
    /// The join condition (column-to-column comparison)
    pub(crate) condition: Filter,

    pub(crate) join_type: JoinType,

    pub(crate) columns: Vec<ColumnInfo<'static>>,

    pub(crate) selected_columns: Vec<&'static str>,
}

#[derive(Debug, PartialEq)]
pub(crate) enum JoinType {
    Left,
    Inner,
    #[cfg(not(feature = "sqlite"))]
    Right,
    #[cfg(feature = "postgres")]
    Full,
    Cross,
}

impl<T: Schema + Debug, S: Select + Debug> Query<T, S> {
    #[cfg(feature = "mysql")]
    /// Creates a new query builder for the specified schema type.
    ///
    /// # Arguments
    ///
    /// - `conn`: The database connection pool
    ///
    /// # Returns
    ///
    /// A new `Query<T>` instance ready for building queries
    pub(crate) fn new(conn: Arc<MySqlPool>) -> Self {
        Self {
            table: PhantomData,
            filters: Vec::new(),
            select: None,
            distinct: false,
            limit: None,
            offset: None,
            joins: Vec::new(),
            conn,
        }
    }

    #[cfg(feature = "postgres")]
    /// Creates a new query builder for the specified schema type.
    ///
    /// # Arguments
    ///
    /// - `conn`: The database connection pool
    ///
    /// # Returns
    ///
    /// A new `Query<T>` instance ready for building queries
    pub(crate) fn new(conn: Arc<PgPool>) -> Self {
        Self {
            table: PhantomData,
            filters: Vec::new(),
            select: None,
            distinct: false,
            limit: None,
            offset: None,
            joins: Vec::new(),
            conn,
        }
    }

    #[cfg(feature = "sqlite")]
    /// Creates a new query builder for the specified schema type.
    ///
    /// # Arguments
    ///
    /// - `conn`: The database connection pool
    ///
    /// # Returns
    ///
    /// A new `Query<T>` instance ready for building queries
    pub(crate) fn new(conn: Arc<SqlitePool>) -> Self {
        Self {
            table: PhantomData,
            filters: Vec::new(),
            select: None,
            distinct: false,
            limit: None,
            offset: None,
            joins: Vec::new(),
            conn,
        }
    }

    /// Adds a filter condition to the query.
    ///
    /// This method allows chaining multiple filter conditions to build
    /// complex WHERE clauses. All filters are combined with AND logic.
    ///
    /// # Arguments
    ///
    /// - `filter`: The filter condition to add
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    /// use lume::filter::eq_value;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///         age: i32,
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let query = db.query::<User, SelectUser>()
    ///         .filter(eq_value(User::name(), Value::String("John".to_string())));
    ///     Ok(())
    /// }
    /// ```
    pub fn filter<F>(mut self, filter: F) -> Self
    where
        F: Filtered + 'static,
    {
        self.filters.push(Box::new(filter));
        self
    }

    /// Adds a limit to the query.
    ///
    /// This method adds a LIMIT clause to the SQL query, limiting the number of rows returned.
    ///
    /// # Arguments
    ///
    /// * `limit` - The maximum number of rows to return.
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    /// use lume::filter::eq_value;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let query = db.query::<User, SelectUser>().limit(10);
    ///     Ok(())
    /// }
    /// ```
    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Adds an offset to the query.
    ///
    /// This method adds an OFFSET clause to the SQL query, skipping the specified number of rows before starting to return rows.
    ///
    /// # Arguments
    ///
    /// * `offset` - The number of rows to skip before starting to return rows.
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let query = db.query::<User, SelectUser>().offset(20);
    ///     Ok(())
    /// }
    /// ```
    pub fn offset(mut self, offset: u64) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Specifies which columns to select in the query.
    ///
    /// This method accepts a selection schema that determines which columns
    /// will be included in the SELECT clause of the SQL query.
    ///
    /// # Arguments
    ///
    /// - `select_schema`: The selection schema specifying which columns to include
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining

    pub fn select(mut self, select_schema: S) -> Self {
        self.select = Some(select_schema);
        self
    }

    /// Specifies that the query should select only distinct rows for the given columns.
    ///
    /// This method works like [`select`](Self::select), but adds a `DISTINCT` clause to the SQL query,
    /// ensuring that duplicate rows are removed from the result set.
    ///
    /// # Arguments
    ///
    /// - `select_schema`: The selection schema specifying which columns to include in the DISTINCT selection.
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     // Selects only unique user names
    ///     let query = db.query::<User, SelectUser>().select_distinct(SelectUser::selected().name());
    ///     Ok(())
    /// }
    /// ```
    pub fn select_distinct(mut self, select_schema: S) -> Self {
        self.select = Some(select_schema);
        self.distinct = true;
        self
    }

    /// Adds a left join to the query.
    ///
    /// This method joins the specified schema table to the current query using a LEFT JOIN.
    /// All records from the left table (current query) are returned, along with matching
    /// records from the right table (joined table).
    ///
    /// # Arguments
    ///
    /// - `filter`: The join condition specifying how tables should be joined
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    /// use lume::filter::eq_column;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    ///
    ///     Post {
    ///         id: i32 [primary_key()],
    ///         user_id: i32,
    ///         title: String,
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let results = db.query::<User, SelectUser>()
    ///         .left_join::<Post, SelectPost>(eq_column(User::id(), Post::user_id()), SelectPost { title: true, ..Default::default() })
    ///         .execute()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn left_join<LeftJoinSchema: Schema + Debug, LeftJoinSchemaSelect: Select + Debug>(
        mut self,
        filter: Filter,
        select_schema: LeftJoinSchemaSelect,
    ) -> Self {
        self.joins.push(JoinInfo {
            table_name: LeftJoinSchema::table_name().to_string(),
            condition: filter,
            join_type: JoinType::Left,
            columns: LeftJoinSchema::get_all_columns(),
            selected_columns: select_schema.get_selected(),
        });

        self
    }

    /// Adds an inner join to the query.
    ///
    /// This method joins the specified schema table to the current query using an INNER JOIN.
    /// Only records that have matching values in both tables are returned.
    ///
    /// # Arguments
    ///
    /// - `filter`: The join condition specifying how tables should be joined
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    /// use lume::filter::eq_column;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    ///
    ///     Post {
    ///         id: i32 [primary_key()],
    ///         user_id: i32,
    ///         title: String,
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let results = db.query::<User, SelectUser>()
    ///         .inner_join::<Post, SelectPost>(eq_column(User::id(), Post::user_id()), SelectPost { title: true, ..Default::default() })
    ///         .execute()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn inner_join<InnerJoinSchema: Schema + Debug, InnerJoinSchemaSelect: Select + Debug>(
        mut self,
        filter: Filter,
        select_schema: InnerJoinSchemaSelect,
    ) -> Self {
        self.joins.push(JoinInfo {
            table_name: InnerJoinSchema::table_name().to_string(),
            condition: filter,
            join_type: JoinType::Inner,
            columns: InnerJoinSchema::get_all_columns(),
            selected_columns: select_schema.get_selected(),
        });

        self
    }

    #[cfg(not(feature = "sqlite"))]
    /// Adds a right join to the query.
    ///
    /// This method joins the specified schema table to the current query using a RIGHT JOIN.
    /// All records from the right table (joined table) are returned, along with matching
    /// records from the left table (current query).
    ///
    /// # Arguments
    ///
    /// - `filter`: The join condition specifying how tables should be joined
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    /// use lume::filter::eq_column;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    ///
    ///     Post {
    ///         id: i32 [primary_key()],
    ///         user_id: i32,
    ///         title: String,
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let results = db.query::<User, SelectUser>()
    ///         .right_join::<Post, SelectPost>(eq_column(User::id(), Post::user_id()), SelectPost { title: true, ..Default::default() })
    ///         .execute()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn right_join<RightJoinSchema: Schema + Debug, RightJoinSchemaSelect: Select + Debug>(
        mut self,
        filter: Filter,
        select_schema: RightJoinSchemaSelect,
    ) -> Self {
        self.joins.push(JoinInfo {
            table_name: RightJoinSchema::table_name().to_string(),
            condition: filter,
            join_type: JoinType::Right,
            columns: RightJoinSchema::get_all_columns(),
            selected_columns: select_schema.get_selected(),
        });

        self
    }

    #[cfg(feature = "postgres")]
    /// Adds a full outer join to the query.
    ///
    /// This method joins the specified schema table to the current query using a FULL OUTER JOIN.
    /// All records from both tables are returned, with NULL values for non-matching records.
    ///
    /// # Arguments
    ///
    /// - `filter`: The join condition specifying how tables should be joined
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::{database::Database, define_schema, filter::eq_column};
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    ///
    ///     Post {
    ///         id: i32 [primary_key()],
    ///         user_id: i32,
    ///         title: String,
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let results = db
    ///         .query::<User, SelectUser>()
    ///         .full_join::<Post, SelectPost>(
    ///             eq_column(User::id(), Post::user_id()),
    ///             SelectPost::selected(),
    ///         )
    ///         .execute()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn full_join<FullJoinSchema: Schema + Debug, FullJoinSchemaSelect: Select + Debug>(
        mut self,
        filter: Filter,
        select_schema: FullJoinSchemaSelect,
    ) -> Self {
        self.joins.push(JoinInfo {
            table_name: FullJoinSchema::table_name().to_string(),
            condition: filter,
            join_type: JoinType::Full,
            columns: FullJoinSchema::get_all_columns(),
            selected_columns: select_schema.get_selected(),
        });

        self
    }

    /// Adds a cross join to the query.
    ///
    /// This method joins the specified schema table to the current query using a CROSS JOIN.
    /// This produces a Cartesian product of all records from both tables.
    ///
    /// # Arguments
    ///
    /// - `filter`: The join condition (note: cross joins typically don't use conditions)
    ///
    /// # Returns
    ///
    /// The query builder instance for method chaining
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    ///
    ///     Post {
    ///         id: i32 [primary_key()],
    ///         user_id: i32,
    ///         title: String,
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let results = db.query::<User, SelectUser>()
    ///         .cross_join::<Post, SelectPost>(SelectPost { title: true, ..Default::default() })
    ///         .execute()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn cross_join<CrossJoinSchema: Schema + Debug, CrossJoinSchemaSelect: Select + Debug>(
        mut self,
        select_schema: CrossJoinSchemaSelect,
    ) -> Self {
        self.joins.push(JoinInfo {
            table_name: CrossJoinSchema::table_name().to_string(),
            condition: Filter::default(),
            join_type: JoinType::Cross,
            columns: CrossJoinSchema::get_all_columns(),
            selected_columns: select_schema.get_selected(),
        });

        self
    }

    /// Executes the query and returns the results.
    ///
    /// This method builds and executes the SQL query, returning type-safe
    /// row objects that can be used to access column values.
    ///
    /// # Returns
    ///
    /// - `Ok(Vec<Row<T>>)`: A vector of type-safe row objects
    /// - `Err(DatabaseError)`: If there was an error executing the query
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::define_schema;
    /// use lume::database::Database;
    /// use lume::filter::Filter;
    /// use lume::schema::{Schema, ColumnInfo};
    /// use lume::filter::eq_value;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let users = db.query::<User, SelectUser>()
    ///         .filter(eq_value(User::name(), Value::String("John".to_string())))
    ///         .execute()
    ///         .await?;
    ///
    ///     for user in users {
    ///         let name: Option<String> = user.get(User::name());
    ///         println!("User: {:?}", name);
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn execute(self) -> Result<Vec<Row<T>>, DatabaseError> {
        let mut sql = get_starting_sql(StartingSql::Select, T::table_name());

        if self.distinct {
            sql.push_str(" DISTINCT ");
        }

        let sql = Self::select_sql(sql, self.select, T::table_name(), &self.joins);
        let sql = Self::joins_sql(sql, &self.joins);
        let mut params: Vec<Value> = Vec::new();
        let mut sql = Self::filter_sql(sql, self.filters, &mut params);

        if let Some(limit) = self.limit {
            sql.push_str(&format!(" LIMIT {}", limit));
        }

        if let Some(offset) = self.offset {
            if self.limit.is_none() {
                sql.push_str(" LIMIT 18446744073709551615");
            }
            sql.push_str(&format!(" OFFSET {}", offset));
        }

        let mut conn = self
            .conn
            .acquire()
            .await
            .map_err(DatabaseError::ConnectionError)?;

        let mut query = sqlx::query(&sql);
        for v in params {
            query = bind_value(query, v);
        }

        let data = query
            .fetch_all(&mut *conn)
            .await
            .map_err(|e| DatabaseError::QueryError(e.to_string()))?;

        #[cfg(feature = "mysql")]
        let rows = Row::from_mysql_row(data, Some(&self.joins));

        #[cfg(feature = "postgres")]
        let rows = Row::from_postgres_row(data, Some(&self.joins));

        #[cfg(feature = "sqlite")]
        let rows = Row::from_sqlite_row(data, Some(&self.joins));

        Ok(rows)
    }

    pub(crate) fn select_sql(
        mut sql: String,
        select: Option<S>,
        table_name: &str,
        joins: &Vec<JoinInfo>,
    ) -> String {
        if let Some(selection) = select {
            sql.push_str(&selection.get_selected().join(", "));
        } else {
            // Default to the base table only (avoid pulling join columns twice)
            let dialect = get_dialect();
            sql.push_str(&format!("{}.*", dialect.quote_identifier(table_name)));
        }

        if !joins.is_empty() {
            for join in joins {
                for column in &join.selected_columns {
                    sql.push_str(&format!(", {}", column));
                }
            }
        }

        sql.push_str(format!(" FROM {}", get_dialect().quote_identifier(table_name)).as_str());
        sql
    }

    pub(crate) fn joins_sql(mut sql: String, joins: &Vec<JoinInfo>) -> String {
        if joins.is_empty() {
            return sql;
        }

        for join in joins {
            let join_type = match join.join_type {
                JoinType::Left => "LEFT JOIN",
                JoinType::Inner => "INNER JOIN",
                #[cfg(not(feature = "sqlite"))]
                JoinType::Right => "RIGHT JOIN",
                #[cfg(feature = "postgres")]
                JoinType::Full => "FULL JOIN",
                JoinType::Cross => "CROSS JOIN",
            };

            let join_table = &join.table_name;

            if join_type == "CROSS JOIN" {
                sql.push_str(&format!(" {} {}", join_type, join_table,));
            } else {
                sql.push_str(&format!(
                    " {} {} ON {}.{} = {}.{}",
                    join_type,
                    join_table,
                    join.condition.column_one.0,
                    join.condition.column_one.1,
                    join.condition.column_two.as_ref().unwrap().0,
                    join.condition.column_two.as_ref().unwrap().1
                ));
            }
        }

        sql
    }
    pub(crate) fn filter_sql(
        mut sql: String,
        filters: Vec<Box<dyn Filtered>>,
        params: &mut Vec<Value>,
    ) -> String {
        if filters.is_empty() {
            return sql;
        }

        sql.push_str(" WHERE ");
        let mut parts: Vec<String> = Vec::with_capacity(filters.len());
        for filter in &filters {
            parts.push(build_filter_expr(filter.as_ref(), params));
        }
        sql.push_str(&parts.join(" AND "));

        sql
    }
}