Skip to main content

tank_tests/
case.rs

1use crate::silent_logs;
2use std::{collections::BTreeSet, sync::LazyLock};
3use tank::{AsValue, Entity, Executor, Result, Row, Sql, cols, expr, stream::TryStreamExt};
4use tokio::sync::Mutex;
5
6static MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
7
8#[derive(Entity, Debug, PartialEq)]
9#[tank(name = "case_orders")]
10pub struct CaseOrder {
11    #[tank(primary_key)]
12    pub id: i32,
13    pub status: i32,
14    pub amount: f64,
15}
16
17pub async fn case(executor: &mut impl Executor) -> Result<()> {
18    let _lock = MUTEX.lock().await;
19
20    // Setup
21    silent_logs! {
22        CaseOrder::drop_table(executor, true, false).await?;
23    }
24    CaseOrder::create_table(executor, true, false).await?;
25    CaseOrder::insert_many(
26        executor,
27        &[
28            CaseOrder {
29                id: 1,
30                status: 1,
31                amount: 50.0,
32            },
33            CaseOrder {
34                id: 2,
35                status: 2,
36                amount: 150.0,
37            },
38            CaseOrder {
39                id: 3,
40                status: 3,
41                amount: 20.0,
42            },
43            CaseOrder {
44                id: 4,
45                status: 9,
46                amount: 500.0,
47            },
48        ],
49    )
50    .await?;
51
52    // Find using simple condition
53    let ids = CaseOrder::find_many(
54        executor,
55        expr!(
56            (if CaseOrder::amount > 100.0 {
57                "large"
58            } else {
59                "small"
60            }) == "large"
61        ),
62        None,
63    )
64    .map_ok(|order| order.id)
65    .try_collect::<BTreeSet<_>>()
66    .await?;
67    assert_eq!(ids, BTreeSet::from([2, 4]));
68
69    // Simple CASE, with alternatives and a default
70    let closed = 3;
71    let ids = CaseOrder::find_many(
72        executor,
73        expr!(
74            (match CaseOrder::status {
75                1 => "open",
76                // status value 2 or 3 is considered "closed"
77                2 | #closed => "closed",
78                _ => "unknown",
79            }) == "closed"
80        ),
81        None,
82    )
83    .map_ok(|order| order.id)
84    .try_collect::<BTreeSet<_>>()
85    .await?;
86    assert_eq!(ids, BTreeSet::from([2, 3]));
87
88    // CASE without ELSE is NULL when no branch matches
89    let ids = CaseOrder::find_many(
90        executor,
91        expr!(
92            (match CaseOrder::status {
93                1 => "open",
94            }) == NULL as IS
95        ),
96        None,
97    )
98    .map_ok(|order| order.id)
99    .try_collect::<BTreeSet<_>>()
100    .await?;
101    assert_eq!(ids, BTreeSet::from([2, 3, 4]));
102
103    // CASE as the whole condition, and inside a logical operator
104    let ids = CaseOrder::find_many(
105        executor,
106        expr!(if CaseOrder::status == 1 {
107            true
108        } else {
109            CaseOrder::amount > 400.0
110        }),
111        None,
112    )
113    .map_ok(|order| order.id)
114    .try_collect::<BTreeSet<_>>()
115    .await?;
116    assert_eq!(ids, BTreeSet::from([1, 4]));
117
118    // Logical condition combined with a CASE statement
119    let ids = CaseOrder::find_many(
120        executor,
121        expr!(
122            CaseOrder::id > 1
123                && (match CaseOrder::status {
124                    2 => true,
125                    _ => false,
126                })
127        ),
128        None,
129    )
130    .map_ok(|order| order.id)
131    .try_collect::<BTreeSet<_>>()
132    .await?;
133    assert_eq!(ids, BTreeSet::from([2]));
134
135    // CASE in the projection
136    let mut labels = executor
137        .fetch(
138            Sql()
139                .select(cols!(
140                    CaseOrder::id,
141                    if CaseOrder::amount >= 100.0 {
142                        "large"
143                    } else {
144                        "small"
145                    } as size
146                ))
147                .from(CaseOrder::table())
148                .build(&executor.driver()),
149        )
150        .and_then(|row| async move {
151            Ok((
152                i32::decode_value(row.value(0).unwrap())?,
153                String::decode_value(row.value(1).unwrap())?,
154            ))
155        })
156        .try_collect::<Vec<_>>()
157        .await?;
158    labels.sort();
159    assert_eq!(
160        labels,
161        [
162            (1, "small".to_string()),
163            (2, "large".to_string()),
164            (3, "small".to_string()),
165            (4, "large".to_string()),
166        ]
167    );
168    Ok(())
169}