rqb 0.1.7

sqlx-first typed Postgres query builder.
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
use super::*;

/// Projection item in a `SELECT` or `RETURNING` list.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) struct SelectItem {
    /// Projected expression.
    pub(crate) expr: ValueExpr,
    /// Optional SQL alias.
    pub(crate) alias: Option<String>,
}

/// Sort direction for `ORDER BY`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum OrderDirection {
    /// Ascending order.
    Asc,
    /// Descending order.
    Desc,
}

/// Null placement for `ORDER BY`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NullsPosition {
    /// Render `NULLS FIRST`.
    First,
    /// Render `NULLS LAST`.
    Last,
}

/// One `ORDER BY` expression.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct OrderItem {
    /// Expression to order by.
    pub(crate) expr: ValueExpr,
    /// Sort direction.
    pub(crate) direction: OrderDirection,
    /// Optional null placement.
    pub(crate) nulls: Option<NullsPosition>,
}

/// One `GROUP BY` item.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) enum GroupByItem {
    /// Regular grouped expression.
    Expr(ValueExpr),
    /// PostgreSQL `ROLLUP`.
    Rollup(Vec<ValueExpr>),
    /// PostgreSQL `CUBE`.
    Cube(Vec<ValueExpr>),
    /// PostgreSQL `GROUPING SETS`.
    GroupingSets(Vec<Vec<ValueExpr>>),
}

/// SQL `FETCH FIRST` clause.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) struct FetchClause {
    /// Row count expression.
    pub(crate) count: ValueExpr,
    /// Whether to render `WITH TIES`.
    pub(crate) with_ties: bool,
}

/// Mutually exclusive row-limit mode for `SELECT` and set queries.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) enum RowLimit {
    /// SQL `LIMIT`.
    Limit(Param),
    /// SQL `FETCH FIRST`.
    Fetch(FetchClause),
}

/// PostgreSQL row lock mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LockMode {
    /// `FOR UPDATE`.
    Update,
    /// `FOR NO KEY UPDATE`.
    NoKeyUpdate,
    /// `FOR SHARE`.
    Share,
    /// `FOR KEY SHARE`.
    KeyShare,
}

/// PostgreSQL row lock wait behavior.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum LockWait {
    /// Wait for locked rows.
    #[default]
    Wait,
    /// Render `NOWAIT`.
    NoWait,
    /// Render `SKIP LOCKED`.
    SkipLocked,
}

/// Row lock clause for a select statement.
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use]
#[non_exhaustive]
pub(crate) struct RowLock {
    /// Lock mode.
    pub(crate) mode: LockMode,
    /// Wait behavior.
    pub(crate) wait: LockWait,
    /// Optional relation aliases in `FOR ... OF`.
    pub(crate) of: Vec<String>,
}

/// Field assignment used by insert, update, merge, and changesets.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct Assignment {
    /// Target field metadata.
    pub(crate) field: Meta,
    /// Assigned value.
    pub(crate) value: AssignmentValue,
}

/// Value accepted by write assignments.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) enum AssignmentValue {
    /// A normal expression or bind parameter.
    Expr(ValueExpr),
    /// SQL `DEFAULT` for this target column.
    Default,
}

impl From<ValueExpr> for AssignmentValue {
    fn from(value: ValueExpr) -> Self {
        Self::Expr(value)
    }
}

/// Body form for an `INSERT` statement.
///
/// Exactly one SQL body is active: explicit `VALUES`, `INSERT ... SELECT`, or
/// `DEFAULT VALUES`.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) enum InsertBody {
    /// `INSERT ... VALUES (...)`.
    Values(Vec<Assignment>),
    /// `INSERT ... SELECT`.
    Select {
        /// Target columns in insert order.
        columns: Vec<Meta>,
        /// Select source for inserted rows.
        select: Box<Select>,
    },
    /// `INSERT ... DEFAULT VALUES`.
    DefaultValues,
}

/// Converts one or more write assignments into a vector.
///
/// This supports tuple syntax for heterogeneous manual assignments:
/// `insert(users::table()).set_many((users::ID.set(id), users::EMAIL.set(email)))`.
#[doc(hidden)]
pub trait IntoAssignments {
    /// Converts this value into write assignments.
    fn into_assignments(self) -> Vec<Assignment>;

    /// Appends assignments to an existing batch.
    fn append_assignments(self, assignments: &mut Vec<Assignment>)
    where
        Self: Sized,
    {
        assignments.extend(self.into_assignments());
    }
}

impl IntoAssignments for Assignment {
    fn into_assignments(self) -> Vec<Assignment> {
        vec![self]
    }
    fn append_assignments(self, assignments: &mut Vec<Assignment>) {
        assignments.push(self);
    }
}

impl IntoAssignments for &Assignment {
    fn into_assignments(self) -> Vec<Assignment> {
        vec![self.clone()]
    }
    fn append_assignments(self, assignments: &mut Vec<Assignment>) {
        assignments.push(self.clone());
    }
}

impl IntoAssignments for Vec<Assignment> {
    fn into_assignments(self) -> Vec<Assignment> {
        self
    }
}

impl IntoAssignments for &[Assignment] {
    fn into_assignments(self) -> Vec<Assignment> {
        self.to_vec()
    }
}

impl<const N: usize> IntoAssignments for [Assignment; N] {
    fn into_assignments(self) -> Vec<Assignment> {
        self.into_iter().collect()
    }
}

macro_rules! impl_assignment_tuple {
    ($($name:ident),+ $(,)?) => {
        impl<$($name),+> IntoAssignments for ($($name,)+)
        where
            $($name: IntoAssignments,)+
        {
            #[allow(non_snake_case)]
            fn into_assignments(self) -> Vec<Assignment> {
                let mut assignments = Vec::new();
                self.append_assignments(&mut assignments);
                assignments
            }
            #[allow(non_snake_case)]
            fn append_assignments(self, assignments: &mut Vec<Assignment>) {
                let ($($name,)+) = self;
                $($name.append_assignments(assignments);)+
            }
        }
    };
}

impl_assignment_tuple!(A, B);
impl_assignment_tuple!(A, B, C);
impl_assignment_tuple!(A, B, C, D);
impl_assignment_tuple!(A, B, C, D, E);
impl_assignment_tuple!(A, B, C, D, E, F);
impl_assignment_tuple!(A, B, C, D, E, F, G);
impl_assignment_tuple!(A, B, C, D, E, F, G, H);
impl_assignment_tuple!(A, B, C, D, E, F, G, H, I);
impl_assignment_tuple!(A, B, C, D, E, F, G, H, I, J);
impl_assignment_tuple!(A, B, C, D, E, F, G, H, I, J, K);
impl_assignment_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_assignment_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_assignment_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_assignment_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_assignment_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);

/// Target of an `ON CONFLICT` clause.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) enum ConflictTarget {
    /// Conflict target by one or more columns.
    Columns {
        /// Target columns.
        fields: Vec<Meta>,
        /// Optional target predicate.
        predicate: Option<Box<BoolExpr>>,
    },
    /// Conflict target by named constraint.
    Constraint(String),
}

/// Action performed for an `ON CONFLICT` clause.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) enum ConflictAction {
    /// Render `DO NOTHING`.
    DoNothing,
    /// Render `DO UPDATE SET`.
    DoUpdate {
        /// Update assignments.
        assignments: Vec<Assignment>,
        /// Optional update predicate.
        filter: Option<Box<BoolExpr>>,
    },
}

/// Full `ON CONFLICT` clause.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) struct ConflictClause {
    /// Conflict target.
    pub(crate) target: ConflictTarget,
    /// Conflict action.
    pub(crate) action: ConflictAction,
}

/// Builder returned by `Merge::when_matched()`.
#[derive(Clone, Debug)]
#[must_use]
pub struct MatchedMergeBuilder {
    pub(super) merge: Merge,
    pub(super) condition: Option<Box<BoolExpr>>,
}

/// Builder returned by `Merge::when_not_matched()`.
#[derive(Clone, Debug)]
#[must_use]
pub struct NotMatchedMergeBuilder {
    pub(super) merge: Merge,
    pub(super) condition: Option<Box<BoolExpr>>,
}

/// Builder returned by `Merge::when_not_matched_by_source()`.
#[derive(Clone, Debug)]
#[must_use]
pub struct NotMatchedBySourceMergeBuilder {
    pub(super) merge: Merge,
    pub(super) condition: Option<Box<BoolExpr>>,
}

/// Pending column-target conflict clause on an `InsertRow` or `Insert`.
/// Completing the clause returns the same host type `I`.
#[derive(Clone, Debug)]
#[must_use]
pub struct ColumnConflictBuilder<I> {
    pub(super) insert: I,
    pub(super) fields: Vec<Meta>,
    pub(super) predicate: Option<Box<BoolExpr>>,
}

/// Pending named-constraint conflict clause on an `InsertRow` or `Insert`.
/// Completing the clause returns the same host type `I`.
#[derive(Clone, Debug)]
#[must_use]
pub struct ConstraintConflictBuilder<I> {
    pub(super) insert: I,
    pub(super) constraint: String,
}

/// Trait implemented by DTOs that can provide insert assignments.
///
/// Nullable DTO fields must match the generated field's inner Rust type:
///
/// ```compile_fail,E0277
/// rqb::schema! { table public.rows { id: int4 = i32, } }
/// #[derive(rqb::Insertable)]
/// #[rqb(table = rows)]
/// struct Wrong { id: Option<String> }
/// ```
pub trait Insertable {
    /// Returns assignments to apply to an insert statement.
    fn insert_assignments(&self) -> Vec<Assignment>;
}

impl<T> Insertable for &T
where
    T: Insertable + ?Sized,
{
    fn insert_assignments(&self) -> Vec<Assignment> {
        (**self).insert_assignments()
    }
}

/// Trait implemented by DTOs that can provide update assignments.
pub trait Changeset {
    /// Returns assignments to apply to an update statement.
    fn changeset_assignments(&self) -> Vec<Assignment>;
}

impl<T> Changeset for &T
where
    T: Changeset + ?Sized,
{
    fn changeset_assignments(&self) -> Vec<Assignment> {
        (**self).changeset_assignments()
    }
}

/// Column set accepted by `Insert::on_conflict(...)`.
///
/// Use a single field, a tuple of fields, or explicit metadata for dynamic
/// schema code.
pub trait ConflictFields {
    /// Returns the number of fields this target will push.
    fn conflict_field_count(&self) -> usize;

    /// Pushes conflict target fields into `fields`, preserving order and de-duping.
    fn push_conflict_fields(self, fields: &mut Vec<Meta>);
}

impl<T> ConflictFields for Field<T> {
    fn conflict_field_count(&self) -> usize {
        1
    }

    fn push_conflict_fields(self, fields: &mut Vec<Meta>) {
        push_column(fields, *self.meta);
    }
}

impl ConflictFields for Meta {
    fn conflict_field_count(&self) -> usize {
        1
    }

    fn push_conflict_fields(self, fields: &mut Vec<Meta>) {
        push_column(fields, self);
    }
}

impl ConflictFields for Vec<Meta> {
    fn conflict_field_count(&self) -> usize {
        self.len()
    }

    fn push_conflict_fields(self, fields: &mut Vec<Meta>) {
        for field in self {
            push_column(fields, field);
        }
    }
}

impl<const N: usize> ConflictFields for [Meta; N] {
    fn conflict_field_count(&self) -> usize {
        N
    }

    fn push_conflict_fields(self, fields: &mut Vec<Meta>) {
        for field in self {
            push_column(fields, field);
        }
    }
}

impl<A, B> ConflictFields for (A, B)
where
    A: ConflictFields,
    B: ConflictFields,
{
    fn conflict_field_count(&self) -> usize {
        self.0.conflict_field_count() + self.1.conflict_field_count()
    }

    fn push_conflict_fields(self, fields: &mut Vec<Meta>) {
        let (a, b) = self;
        a.push_conflict_fields(fields);
        b.push_conflict_fields(fields);
    }
}

impl<A, B, C> ConflictFields for (A, B, C)
where
    A: ConflictFields,
    B: ConflictFields,
    C: ConflictFields,
{
    fn conflict_field_count(&self) -> usize {
        self.0.conflict_field_count()
            + self.1.conflict_field_count()
            + self.2.conflict_field_count()
    }

    fn push_conflict_fields(self, fields: &mut Vec<Meta>) {
        let (a, b, c) = self;
        a.push_conflict_fields(fields);
        b.push_conflict_fields(fields);
        c.push_conflict_fields(fields);
    }
}

impl<A, B, C, D> ConflictFields for (A, B, C, D)
where
    A: ConflictFields,
    B: ConflictFields,
    C: ConflictFields,
    D: ConflictFields,
{
    fn conflict_field_count(&self) -> usize {
        self.0.conflict_field_count()
            + self.1.conflict_field_count()
            + self.2.conflict_field_count()
            + self.3.conflict_field_count()
    }

    fn push_conflict_fields(self, fields: &mut Vec<Meta>) {
        let (a, b, c, d) = self;
        a.push_conflict_fields(fields);
        b.push_conflict_fields(fields);
        c.push_conflict_fields(fields);
        d.push_conflict_fields(fields);
    }
}

/// Typed select statement.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct Select {
    /// CTEs attached to this select.
    pub(crate) ctes: Vec<Cte>,
    /// Root source.
    pub(crate) source: Source,
    /// Joined sources.
    pub(crate) joins: Vec<Join>,
    /// Whether to render `DISTINCT`.
    pub(crate) distinct: bool,
    /// Expressions for `DISTINCT ON`.
    pub(crate) distinct_on: Vec<ValueExpr>,
    /// Projection list.
    ///
    /// Empty means the renderer selects the root source's exposed fields.
    /// Joined fields and computed expressions are never added implicitly.
    pub(crate) projection: Vec<SelectItem>,
    /// Optional `WHERE` predicate.
    pub(crate) filter: Option<BoolExpr>,
    /// Grouping expressions.
    pub(crate) group_by: Vec<GroupByItem>,
    /// Optional `HAVING` predicate.
    pub(crate) having: Option<BoolExpr>,
    /// Ordering expressions.
    pub(crate) order: Vec<OrderItem>,
    /// Optional row-limit clause.
    pub(crate) row_limit: Option<RowLimit>,
    /// Optional `OFFSET` parameter.
    pub(crate) offset: Option<Param>,
    /// Optional row lock clause.
    pub(crate) lock: Option<RowLock>,
}

/// INSERT with a selected body, without additive single-row setters.
///
/// Start with [`insert()`] to assemble an [`InsertRow`]. Batch, SELECT and
/// DEFAULT VALUES complete its input; clauses and explicit body replacement
/// remain available on `Insert`.
///
/// Completed input cannot be overwritten through row setters:
///
/// ```compile_fail,E0599
/// # fn invalid(q: rqb::Insert, a: rqb::Assignment) {
/// q.set(a);
/// # }
/// ```
/// ```compile_fail,E0599
/// # fn invalid(q: rqb::Insert, a: rqb::Assignment) {
/// q.set_many([a]);
/// # }
/// ```
/// ```compile_fail,E0599
/// # fn invalid(q: rqb::Insert, a: rqb::Assignment) {
/// q.set_if(false, a);
/// # }
/// ```
/// ```compile_fail,E0599
/// # fn invalid(q: rqb::Insert, a: rqb::Assignment) {
/// q.set_option(None::<i32>, |_| a);
/// # }
/// ```
/// ```compile_fail,E0599
/// # fn invalid(q: rqb::Insert, dto: impl rqb::Insertable) {
/// q.values(dto);
/// # }
/// ```
/// ```compile_fail,E0599
/// # fn invalid(q: rqb::Insert, dto: impl rqb::Insertable) {
/// q.values_many([dto]);
/// # }
/// ```
///
/// Completion is one-way:
///
/// ```compile_fail,E0277
/// # fn invalid(q: rqb::Insert) {
/// let row: rqb::InsertRow = q.into();
/// # }
/// ```
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct Insert {
    /// CTEs attached to this insert.
    pub(crate) ctes: Vec<Cte>,
    /// Target table or view.
    pub(crate) target: Source,
    /// Active insert body.
    pub(crate) body: InsertBody,
    /// Optional conflict handling clause.
    pub(crate) conflict: Option<ConflictClause>,
    /// Optional `RETURNING` projection.
    pub(crate) returning: Vec<SelectItem>,
}

/// Typed update statement.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct Update {
    /// CTEs attached to this update.
    pub(crate) ctes: Vec<Cte>,
    /// Target table or view.
    pub(crate) target: Source,
    /// Assignments for `SET`.
    pub(crate) assignments: Vec<Assignment>,
    /// Optional `FROM` sources.
    pub(crate) from: Vec<Source>,
    /// Optional `WHERE` predicate.
    pub(crate) filter: Option<BoolExpr>,
    /// Optional `RETURNING` projection.
    pub(crate) returning: Vec<SelectItem>,
}

/// Typed delete statement.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct Delete {
    /// CTEs attached to this delete.
    pub(crate) ctes: Vec<Cte>,
    /// Target table or view.
    pub(crate) target: Source,
    /// Optional `USING` sources.
    pub(crate) using: Vec<Source>,
    /// Required `WHERE` predicate.
    ///
    /// Validation rejects unfiltered deletes with
    /// [`Error::DeleteWithoutFilter`](crate::Error::DeleteWithoutFilter).
    pub(crate) filter: Option<BoolExpr>,
    /// Optional `RETURNING` projection.
    pub(crate) returning: Vec<SelectItem>,
}

/// PostgreSQL `MERGE` match branch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) enum MergeWhen {
    /// `WHEN MATCHED`.
    Matched,
    /// `WHEN NOT MATCHED`.
    NotMatched,
    /// `WHEN NOT MATCHED BY SOURCE`.
    NotMatchedBySource,
}

/// Action inside a PostgreSQL `MERGE` statement.
///
/// Branch builders restrict legal actions: `WHEN MATCHED` supports
/// update/delete/do nothing, `WHEN NOT MATCHED` supports insert/do nothing, and
/// `WHEN NOT MATCHED BY SOURCE` supports update/delete/do nothing.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub(crate) enum MergeAction {
    /// `DO NOTHING`.
    DoNothing {
        /// Match branch for the action.
        when: MergeWhen,
        /// Optional branch condition.
        condition: Option<Box<BoolExpr>>,
    },
    /// `INSERT`.
    Insert {
        /// Match branch for the action.
        when: MergeWhen,
        /// Optional branch condition.
        condition: Option<Box<BoolExpr>>,
        /// Insert assignments.
        assignments: Vec<Assignment>,
    },
    /// `UPDATE SET`.
    Update {
        /// Match branch for the action.
        when: MergeWhen,
        /// Optional branch condition.
        condition: Option<Box<BoolExpr>>,
        /// Update assignments.
        assignments: Vec<Assignment>,
    },
    /// `DELETE`.
    Delete {
        /// Match branch for the action.
        when: MergeWhen,
        /// Optional branch condition.
        condition: Option<Box<BoolExpr>>,
    },
}

/// Typed PostgreSQL `MERGE` statement.
///
/// Branch builders restrict legal actions; actions render in insertion order.
/// Build-time validation rejects missing actions, unreachable branch ordering,
/// empty assignments, and invalid expressions.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct Merge {
    /// CTEs attached to this merge.
    pub(crate) ctes: Vec<Cte>,
    /// Merge target.
    pub(crate) target: Source,
    /// Merge source.
    pub(crate) using: Source,
    /// Join predicate between target and source.
    pub(crate) on: BoolExpr,
    /// Ordered merge actions.
    pub(crate) actions: Vec<MergeAction>,
    /// Optional `RETURNING` projection.
    pub(crate) returning: Vec<SelectItem>,
}

/// Server-owned raw SQL statement.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct RawStmt {
    /// Raw SQL text using rqb `?` placeholders.
    pub(crate) sql: String,
    /// Bind parameters for the raw SQL text.
    pub(crate) params: Vec<Param>,
}

/// SQL set query operator.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SetOperator {
    /// `UNION`.
    Union,
    /// `UNION ALL`.
    UnionAll,
    /// `INTERSECT`.
    Intersect,
    /// `INTERSECT ALL`.
    IntersectAll,
    /// `EXCEPT`.
    Except,
    /// `EXCEPT ALL`.
    ExceptAll,
}

/// SQL set query with optional ordering and row limits.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub struct SetQuery {
    /// Left query.
    pub(crate) left: Box<Stmt>,
    /// Set operator.
    pub(crate) operator: SetOperator,
    /// Right query.
    pub(crate) right: Box<Stmt>,
    /// Ordering after the set expression.
    pub(crate) order: Vec<OrderItem>,
    /// Optional row-limit clause.
    pub(crate) row_limit: Option<RowLimit>,
    /// Optional offset.
    pub(crate) offset: Option<Param>,
}

/// Any top-level query statement rqb can render.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub enum Stmt {
    /// Select statement.
    #[non_exhaustive]
    Select(Box<Select>),
    /// Set query.
    #[non_exhaustive]
    Set(Box<SetQuery>),
    /// Insert statement.
    #[non_exhaustive]
    Insert(Box<Insert>),
    /// Update statement.
    #[non_exhaustive]
    Update(Box<Update>),
    /// Delete statement.
    #[non_exhaustive]
    Delete(Box<Delete>),
    /// Merge statement.
    #[non_exhaustive]
    Merge(Box<Merge>),
    /// Raw SQL statement.
    #[non_exhaustive]
    Raw(Box<RawStmt>),
}