1use std::sync::LazyLock;
2use tank::{
3 AsValue, Entity, Executor, QueryBuilder, Result, cols, expr,
4 stream::{StreamExt, TryStreamExt},
5};
6use tokio::sync::Mutex;
7
8static MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
9
10#[derive(Default, Entity, PartialEq, Eq, PartialOrd, Ord, Debug)]
11struct MathTable {
12 #[tank(primary_key)]
13 id: u64,
14 read: u64,
15}
16
17pub async fn math(executor: &mut impl Executor) {
18 let _lock = MUTEX.lock().await;
19
20 MathTable::drop_table(executor, true, false)
22 .await
23 .expect("Failed to drop MathTable table");
24 MathTable::create_table(executor, false, false)
25 .await
26 .expect("Failed to create MathTable table");
27 MathTable { id: 0, read: 0 }
28 .save(executor)
29 .await
30 .expect("Could not save the dummy entry");
31
32 let result = executor
33 .fetch(
34 QueryBuilder::new()
35 .select(cols!(MathTable::id, ((42 * 6 + 56) / 7) as read))
36 .from(MathTable::table())
37 .where_expr(expr!(MathTable::id == 0))
38 .build(&executor.driver()),
39 )
40 .map_ok(MathTable::from_row)
41 .map(Result::flatten)
42 .try_collect::<Vec<_>>()
43 .await
44 .expect("Could not get the result 1");
45 assert_eq!(result, [MathTable { id: 0, read: 44 }]);
46
47 let result = executor
48 .fetch(
49 QueryBuilder::new()
50 .select(cols!(MathTable::id, ((5 - (1 << 2)) * 9 % 6) as read))
51 .from(MathTable::table())
52 .where_expr(expr!(MathTable::id == 0))
53 .build(&executor.driver()),
54 )
55 .map_ok(MathTable::from_row)
56 .map(Result::flatten)
57 .try_collect::<Vec<_>>()
58 .await
59 .expect("Could not get the result 2");
60 assert_eq!(result, [MathTable { id: 0, read: 3 }]);
61
62 let result = executor
63 .fetch(
64 QueryBuilder::new()
65 .select(cols!(MathTable::id, ((1 | 2 | 4) + 1) as read))
66 .from(MathTable::table())
67 .where_expr(expr!(MathTable::id == 0))
68 .build(&executor.driver()),
69 )
70 .map_ok(MathTable::from_row)
71 .map(Result::flatten)
72 .try_collect::<Vec<_>>()
73 .await
74 .expect("Could not get the result 3");
75 assert_eq!(result, [MathTable { id: 0, read: 8 }]);
76
77 let result = executor
78 .fetch(
79 QueryBuilder::new()
80 .select(cols!(MathTable::id, (90 > 89 && (10 & 6) == 2) as read))
81 .from(MathTable::table())
82 .where_expr(expr!(MathTable::id == 0))
83 .build(&executor.driver()),
84 )
85 .map_ok(|v| bool::try_from_value(v.values.into_iter().nth(1).unwrap()))
86 .map(Result::flatten)
87 .try_collect::<Vec<_>>()
88 .await
89 .expect("Could not get the result 4");
90 assert_eq!(result, [true]);
91
92 let result = executor
93 .fetch(
94 QueryBuilder::new()
95 .select(cols!(MathTable::id, (4 == (2, 3, 4, 5) as IN) as read))
96 .from(MathTable::table())
97 .where_expr(expr!(MathTable::id == 0))
98 .build(&executor.driver()),
99 )
100 .map_ok(|v| bool::try_from_value(v.values.into_iter().nth(1).unwrap()))
101 .map(Result::flatten)
102 .try_collect::<Vec<_>>()
103 .await
104 .expect("Could not get the result 5");
105 assert_eq!(result, [true]);
106}