reinhardt-query 0.1.0

SQL query builder for Reinhardt framework
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
//! SELECT statement builder
//!
//! This module provides the `SelectStatement` type for building SQL SELECT queries.

use crate::{
	expr::{Condition, ConditionHolder, IntoCondition, SimpleExpr},
	types::{
		ColumnRef, DynIden, IntoColumnRef, IntoIden, IntoTableRef, JoinExpr, JoinType, Order,
		OrderExpr, TableRef, WindowStatement,
	},
	value::{IntoValue, Value, Values},
};

use super::traits::{QueryBuilderTrait, QueryStatementBuilder, QueryStatementWriter};

/// SELECT statement builder
///
/// This struct provides a fluent API for constructing SELECT queries.
///
/// # Examples
///
/// ```rust,ignore
/// use reinhardt_query::prelude::*;
///
/// let query = Query::select()
///     .column(Expr::col("id"))
///     .column(Expr::col("name"))
///     .from("users")
///     .and_where(Expr::col("active").eq(true))
///     .order_by("name", Order::Asc)
///     .limit(10);
/// ```
#[derive(Debug, Clone, Default)]
pub struct SelectStatement {
	pub(crate) ctes: Vec<CommonTableExpr>,
	pub(crate) distinct: Option<SelectDistinct>,
	pub(crate) selects: Vec<SelectExpr>,
	pub(crate) from: Vec<TableRef>,
	pub(crate) join: Vec<JoinExpr>,
	pub(crate) r#where: ConditionHolder,
	pub(crate) groups: Vec<SimpleExpr>,
	pub(crate) having: ConditionHolder,
	pub(crate) unions: Vec<(UnionType, SelectStatement)>,
	pub(crate) orders: Vec<OrderExpr>,
	pub(crate) limit: Option<Value>,
	pub(crate) offset: Option<Value>,
	pub(crate) lock: Option<LockClause>,
	pub(crate) windows: Vec<(DynIden, WindowStatement)>,
}

/// Common Table Expression (CTE) for WITH clause
///
/// This represents a single CTE in a WITH clause.
#[derive(Debug, Clone)]
pub struct CommonTableExpr {
	/// CTE name (alias)
	pub(crate) name: DynIden,
	/// CTE query
	pub(crate) query: Box<SelectStatement>,
	/// Whether this is a RECURSIVE CTE
	pub(crate) recursive: bool,
}

/// List of distinct keywords that can be used in select statement
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SelectDistinct {
	/// SELECT ALL
	All,
	/// SELECT DISTINCT
	Distinct,
	/// SELECT DISTINCTROW (MySQL)
	DistinctRow,
	/// SELECT DISTINCT ON (PostgreSQL)
	DistinctOn(Vec<ColumnRef>),
}

/// Select expression used in select statement.
#[derive(Debug, Clone)]
pub struct SelectExpr {
	/// The expression to select.
	pub expr: SimpleExpr,
	/// Optional alias for the expression (AS clause).
	pub alias: Option<DynIden>,
}

/// List of lock types that can be used in select statement
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LockType {
	/// FOR UPDATE
	Update,
	/// FOR NO KEY UPDATE (PostgreSQL)
	NoKeyUpdate,
	/// FOR SHARE
	Share,
	/// FOR KEY SHARE (PostgreSQL)
	KeyShare,
}

/// List of lock behavior can be used in select statement
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LockBehavior {
	/// NOWAIT
	Nowait,
	/// SKIP LOCKED
	SkipLocked,
}

/// Lock clause for SELECT ... FOR UPDATE/SHARE
// NOTE: Fields are currently unused because FOR UPDATE/SHARE is not yet implemented
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct LockClause {
	pub(crate) r#type: LockType,
	pub(crate) tables: Vec<TableRef>,
	pub(crate) behavior: Option<LockBehavior>,
}

/// List of union types that can be used in union clause
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnionType {
	/// INTERSECT
	Intersect,
	/// UNION
	Distinct,
	/// EXCEPT
	Except,
	/// UNION ALL
	All,
}

impl<T> From<T> for SelectExpr
where
	T: Into<SimpleExpr>,
{
	fn from(expr: T) -> Self {
		SelectExpr {
			expr: expr.into(),
			alias: None,
		}
	}
}

impl SelectStatement {
	/// Create a new SELECT statement
	pub fn new() -> Self {
		Self::default()
	}

	/// Take the ownership of data in the current [`SelectStatement`]
	pub fn take(&mut self) -> Self {
		Self {
			ctes: std::mem::take(&mut self.ctes),
			distinct: self.distinct.take(),
			selects: std::mem::take(&mut self.selects),
			from: std::mem::take(&mut self.from),
			join: std::mem::take(&mut self.join),
			r#where: std::mem::replace(&mut self.r#where, ConditionHolder::new()),
			groups: std::mem::take(&mut self.groups),
			having: std::mem::replace(&mut self.having, ConditionHolder::new()),
			unions: std::mem::take(&mut self.unions),
			orders: std::mem::take(&mut self.orders),
			limit: self.limit.take(),
			offset: self.offset.take(),
			lock: self.lock.take(),
			windows: std::mem::take(&mut self.windows),
		}
	}

	// Column selection methods

	/// Add a column to the SELECT clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .column("id")
	///     .column("name")
	///     .from("users");
	/// ```
	pub fn column<C>(&mut self, col: C) -> &mut Self
	where
		C: IntoColumnRef,
	{
		self.selects.push(SelectExpr {
			expr: SimpleExpr::Column(col.into_column_ref()),
			alias: None,
		});
		self
	}

	/// Add multiple columns to the SELECT clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .columns(["id", "name", "email"])
	///     .from("users");
	/// ```
	pub fn columns<I, C>(&mut self, cols: I) -> &mut Self
	where
		I: IntoIterator<Item = C>,
		C: IntoColumnRef,
	{
		for col in cols {
			self.column(col);
		}
		self
	}

	/// Add an expression to the SELECT clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .expr(Expr::col("price").mul(Expr::col("quantity")))
	///     .from("orders");
	/// ```
	pub fn expr<E>(&mut self, expr: E) -> &mut Self
	where
		E: Into<SimpleExpr>,
	{
		self.selects.push(SelectExpr {
			expr: expr.into(),
			alias: None,
		});
		self
	}

	/// Add an expression with an alias to the SELECT clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .expr_as(Expr::col("price").mul(Expr::col("quantity")), "total")
	///     .from("orders");
	/// ```
	pub fn expr_as<E, A>(&mut self, expr: E, alias: A) -> &mut Self
	where
		E: Into<SimpleExpr>,
		A: IntoIden,
	{
		self.selects.push(SelectExpr {
			expr: expr.into(),
			alias: Some(alias.into_iden()),
		});
		self
	}

	// FROM clause methods

	/// Add a table to the FROM clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .column("id")
	///     .from("users");
	/// ```
	pub fn from<T>(&mut self, tbl: T) -> &mut Self
	where
		T: IntoTableRef,
	{
		self.from.push(tbl.into_table_ref());
		self
	}

	/// Add a table with alias to the FROM clause
	///
	/// Equivalent to `FROM table AS alias`.
	pub fn from_as<T, A>(&mut self, tbl: T, alias: A) -> &mut Self
	where
		T: IntoIden,
		A: IntoIden,
	{
		self.from
			.push(TableRef::TableAlias(tbl.into_iden(), alias.into_iden()));
		self
	}

	/// Add a subquery to the FROM clause
	///
	/// Equivalent to `FROM (SELECT ...) AS alias`.
	pub fn from_subquery(&mut self, query: SelectStatement, alias: impl IntoIden) -> &mut Self {
		self.from
			.push(TableRef::SubQuery(Box::new(query), alias.into_iden()));
		self
	}

	/// Clear all column selections
	pub fn clear_selects(&mut self) -> &mut Self {
		self.selects.clear();
		self
	}

	// JOIN clause methods

	/// Add a JOIN clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .from("users")
	///     .join(
	///         JoinType::InnerJoin,
	///         "orders",
	///         Expr::col(("users", "id")).equals(("orders", "user_id"))
	///     );
	/// ```
	pub fn join<T, C>(&mut self, join: JoinType, tbl: T, condition: C) -> &mut Self
	where
		T: IntoTableRef,
		C: IntoCondition,
	{
		self.join.push(JoinExpr {
			join,
			table: tbl.into_table_ref(),
			on: Some(crate::types::JoinOn::Condition(condition.into_condition())),
		});
		self
	}

	/// Add a LEFT JOIN clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .from("users")
	///     .left_join(
	///         "orders",
	///         Expr::col(("users", "id")).equals(("orders", "user_id"))
	///     );
	/// ```
	pub fn left_join<T, C>(&mut self, tbl: T, condition: C) -> &mut Self
	where
		T: IntoTableRef,
		C: IntoCondition,
	{
		self.join(JoinType::LeftJoin, tbl, condition)
	}

	/// Add a RIGHT JOIN clause
	pub fn right_join<T, C>(&mut self, tbl: T, condition: C) -> &mut Self
	where
		T: IntoTableRef,
		C: IntoCondition,
	{
		self.join(JoinType::RightJoin, tbl, condition)
	}

	/// Add a FULL OUTER JOIN clause
	pub fn full_outer_join<T, C>(&mut self, tbl: T, condition: C) -> &mut Self
	where
		T: IntoTableRef,
		C: IntoCondition,
	{
		self.join(JoinType::FullOuterJoin, tbl, condition)
	}

	/// Add an INNER JOIN clause
	pub fn inner_join<T, C>(&mut self, tbl: T, condition: C) -> &mut Self
	where
		T: IntoTableRef,
		C: IntoCondition,
	{
		self.join(JoinType::InnerJoin, tbl, condition)
	}

	/// Add a CROSS JOIN clause
	pub fn cross_join<T>(&mut self, tbl: T) -> &mut Self
	where
		T: IntoTableRef,
	{
		self.join.push(JoinExpr {
			join: JoinType::CrossJoin,
			table: tbl.into_table_ref(),
			on: None,
		});
		self
	}

	// WHERE clause methods

	/// Add a condition to the WHERE clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .from("users")
	///     .and_where(Expr::col("active").eq(true));
	/// ```
	pub fn and_where<C>(&mut self, condition: C) -> &mut Self
	where
		C: IntoCondition,
	{
		self.r#where.add_and(condition);
		self
	}

	/// Add a condition to the WHERE clause using Condition
	pub fn cond_where(&mut self, condition: Condition) -> &mut Self {
		self.r#where.add_and(condition);
		self
	}

	// GROUP BY clause methods

	/// Add a GROUP BY clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .column("category")
	///     .expr_as(Expr::count("*"), "count")
	///     .from("products")
	///     .group_by("category");
	/// ```
	pub fn group_by<C>(&mut self, col: C) -> &mut Self
	where
		C: IntoColumnRef,
	{
		self.groups.push(SimpleExpr::Column(col.into_column_ref()));
		self
	}

	/// Add a column to the GROUP BY clause (alias for `group_by`)
	pub fn group_by_col<C>(&mut self, col: C) -> &mut Self
	where
		C: IntoColumnRef,
	{
		self.group_by(col)
	}

	/// Add multiple GROUP BY columns
	pub fn group_by_columns<I, C>(&mut self, cols: I) -> &mut Self
	where
		I: IntoIterator<Item = C>,
		C: IntoColumnRef,
	{
		for col in cols {
			self.group_by(col);
		}
		self
	}

	// HAVING clause methods

	/// Add a condition to the HAVING clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .column("category")
	///     .expr_as(Expr::count("*"), "count")
	///     .from("products")
	///     .group_by("category")
	///     .and_having(Expr::count("*").gt(5));
	/// ```
	pub fn and_having<C>(&mut self, condition: C) -> &mut Self
	where
		C: IntoCondition,
	{
		self.having.add_and(condition);
		self
	}

	/// Add a condition to the HAVING clause using Condition
	pub fn cond_having(&mut self, condition: Condition) -> &mut Self {
		self.having.add_and(condition);
		self
	}

	// ORDER BY clause methods

	/// Add an ORDER BY clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .from("users")
	///     .order_by("name", Order::Asc)
	///     .order_by("created_at", Order::Desc);
	/// ```
	pub fn order_by<C>(&mut self, col: C, order: Order) -> &mut Self
	where
		C: IntoColumnRef,
	{
		use crate::types::OrderExprKind;
		self.orders.push(OrderExpr {
			expr: OrderExprKind::Expr(Box::new(SimpleExpr::Column(col.into_column_ref()))),
			order,
			nulls: None,
		});
		self
	}

	/// Add an ORDER BY clause with expression
	pub fn order_by_expr<E>(&mut self, expr: E, order: Order) -> &mut Self
	where
		E: Into<SimpleExpr>,
	{
		use crate::types::OrderExprKind;
		self.orders.push(OrderExpr {
			expr: OrderExprKind::Expr(Box::new(expr.into())),
			order,
			nulls: None,
		});
		self
	}

	// LIMIT and OFFSET methods

	/// Set the LIMIT clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .from("users")
	///     .limit(10);
	/// ```
	pub fn limit<V>(&mut self, limit: V) -> &mut Self
	where
		V: IntoValue,
	{
		self.limit = Some(limit.into_value());
		self
	}

	/// Set the OFFSET clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .from("users")
	///     .limit(10)
	///     .offset(20);
	/// ```
	pub fn offset<V>(&mut self, offset: V) -> &mut Self
	where
		V: IntoValue,
	{
		self.offset = Some(offset.into_value());
		self
	}

	// DISTINCT methods

	/// Set DISTINCT
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let query = Query::select()
	///     .distinct()
	///     .column("category")
	///     .from("products");
	/// ```
	pub fn distinct(&mut self) -> &mut Self {
		self.distinct = Some(SelectDistinct::Distinct);
		self
	}

	/// Set DISTINCT ON (PostgreSQL only)
	pub fn distinct_on<I, C>(&mut self, cols: I) -> &mut Self
	where
		I: IntoIterator<Item = C>,
		C: IntoColumnRef,
	{
		let cols: Vec<ColumnRef> = cols.into_iter().map(|c| c.into_column_ref()).collect();
		self.distinct = Some(SelectDistinct::DistinctOn(cols));
		self
	}

	// UNION methods

	/// Add a UNION clause
	pub fn union(&mut self, query: SelectStatement) -> &mut Self {
		self.unions.push((UnionType::Distinct, query));
		self
	}

	/// Add a UNION ALL clause
	pub fn union_all(&mut self, query: SelectStatement) -> &mut Self {
		self.unions.push((UnionType::All, query));
		self
	}

	/// Add an INTERSECT clause
	pub fn intersect(&mut self, query: SelectStatement) -> &mut Self {
		self.unions.push((UnionType::Intersect, query));
		self
	}

	/// Add an EXCEPT clause
	pub fn except(&mut self, query: SelectStatement) -> &mut Self {
		self.unions.push((UnionType::Except, query));
		self
	}

	// WITH (CTE) methods

	/// Add a Common Table Expression (CTE) to the WITH clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// let cte = Query::select()
	///     .column("id")
	///     .column("name")
	///     .from("users")
	///     .and_where(Expr::col("active").eq(true));
	///
	/// let query = Query::select()
	///     .with_cte("active_users", cte)
	///     .column("*")
	///     .from("active_users");
	/// ```
	pub fn with_cte<N>(&mut self, name: N, query: SelectStatement) -> &mut Self
	where
		N: IntoIden,
	{
		self.ctes.push(CommonTableExpr {
			name: name.into_iden(),
			query: Box::new(query),
			recursive: false,
		});
		self
	}

	/// Add a RECURSIVE Common Table Expression (CTE) to the WITH clause
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	///
	/// // Recursive CTE for hierarchical data
	/// let cte = Query::select()
	///     .column("id")
	///     .column("parent_id")
	///     .column("name")
	///     .from("categories")
	///     .and_where(Expr::col("parent_id").is_null())
	///     .union_all(
	///         Query::select()
	///             .column(Expr::col(("c", "id")))
	///             .column(Expr::col(("c", "parent_id")))
	///             .column(Expr::col(("c", "name")))
	///             .from_as("categories", "c")
	///             .join(
	///                 JoinType::InnerJoin,
	///                 "category_tree",
	///                 Expr::col(("c", "parent_id")).eq(Expr::col(("category_tree", "id")))
	///             )
	///     );
	///
	/// let query = Query::select()
	///     .with_recursive_cte("category_tree", cte)
	///     .column("*")
	///     .from("category_tree");
	/// ```
	pub fn with_recursive_cte<N>(&mut self, name: N, query: SelectStatement) -> &mut Self
	where
		N: IntoIden,
	{
		self.ctes.push(CommonTableExpr {
			name: name.into_iden(),
			query: Box::new(query),
			recursive: true,
		});
		self
	}

	// WINDOW methods

	/// Add a named window specification to the WINDOW clause
	///
	/// Named windows can be referenced by window functions using `OVER window_name`.
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_query::prelude::*;
	/// use reinhardt_query::types::window::WindowStatement;
	///
	/// let window = WindowStatement {
	///     partition_by: vec![Expr::col("department_id").into_simple_expr()],
	///     order_by: vec![OrderExpr {
	///         expr: Expr::col("salary").into_simple_expr(),
	///         order: Order::Desc,
	///         nulls: None,
	///     }],
	///     frame: None,
	/// };
	///
	/// let query = Query::select()
	///     .column("name")
	///     .expr_as(Expr::row_number().over_named("w"), "rank")
	///     .from("employees")
	///     .window_as("w", window);
	/// ```
	pub fn window_as<T>(&mut self, name: T, window: WindowStatement) -> &mut Self
	where
		T: IntoIden,
	{
		self.windows.push((name.into_iden(), window));
		self
	}

	// LOCK methods

	/// Set FOR UPDATE lock
	pub fn lock(&mut self, lock_type: LockType) -> &mut Self {
		self.lock = Some(LockClause {
			r#type: lock_type,
			tables: Vec::new(),
			behavior: None,
		});
		self
	}

	/// Set FOR UPDATE lock
	pub fn lock_exclusive(&mut self) -> &mut Self {
		self.lock(LockType::Update)
	}

	/// Set FOR SHARE lock
	pub fn lock_shared(&mut self) -> &mut Self {
		self.lock(LockType::Share)
	}

	// Utility methods

	/// Apply a function conditionally
	pub fn apply_if<T, F>(&mut self, val: Option<T>, func: F) -> &mut Self
	where
		F: FnOnce(&mut Self, T),
	{
		if let Some(val) = val {
			func(self, val);
		}
		self
	}

	/// Conditional execution
	pub fn conditions<T, F>(&mut self, b: bool, if_true: T, if_false: F) -> &mut Self
	where
		T: FnOnce(&mut Self),
		F: FnOnce(&mut Self),
	{
		if b {
			if_true(self)
		} else {
			if_false(self)
		}
		self
	}
}

impl QueryStatementBuilder for SelectStatement {
	fn build_any(&self, query_builder: &dyn QueryBuilderTrait) -> (String, Values) {
		use crate::backend::{
			MySqlQueryBuilder, PostgresQueryBuilder, QueryBuilder, SqliteQueryBuilder,
		};
		use std::any::Any;

		let any_builder = query_builder as &dyn Any;

		if let Some(pg) = any_builder.downcast_ref::<PostgresQueryBuilder>() {
			return pg.build_select(self);
		}

		if let Some(mysql) = any_builder.downcast_ref::<MySqlQueryBuilder>() {
			return mysql.build_select(self);
		}

		if let Some(sqlite) = any_builder.downcast_ref::<SqliteQueryBuilder>() {
			return sqlite.build_select(self);
		}

		panic!(
			"Unsupported query builder type. Use PostgresQueryBuilder, MySqlQueryBuilder, or SqliteQueryBuilder."
		);
	}
}

impl QueryStatementWriter for SelectStatement {}