1use std::sync::LazyLock;
2use tank::{
3 Entity, Executor, expr,
4 stream::{StreamExt, TryStreamExt},
5};
6use tokio::sync::Mutex;
7
8static MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
9
10#[derive(Entity, Debug, PartialEq)]
11#[tank(schema = "testing", name = "conditions")]
12struct ConditionEntry {
13 #[tank(primary_key)]
14 id: i32,
15 name: Option<String>,
16 active: bool,
17}
18
19pub async fn conditions(executor: &mut impl Executor) {
20 let _lock = MUTEX.lock().await;
21
22 ConditionEntry::drop_table(executor, true, false)
24 .await
25 .expect("Failed to drop ConditionEntry table");
26 ConditionEntry::create_table(executor, true, true)
27 .await
28 .expect("Failed to create ConditionEntry table");
29
30 let entries = vec![
32 ConditionEntry {
33 id: 1,
34 name: Some("Alice".into()),
35 active: true,
36 },
37 ConditionEntry {
38 id: 2,
39 name: Some("Bob".into()),
40 active: false,
41 },
42 ConditionEntry {
43 id: 3,
44 name: None,
45 active: true,
46 },
47 ConditionEntry {
48 id: 4,
49 name: Some("Charlie".into()),
50 active: true,
51 },
52 ];
53 ConditionEntry::insert_many(executor, &entries)
54 .await
55 .expect("Failed to insert entries");
56
57 let count = ConditionEntry::find_many(executor, expr!(name != NULL), None)
58 .map_err(|e| panic!("{e:#}"))
59 .count()
60 .await;
61 assert_eq!(count, 3, "Should find 3 entries where `name IS NOT NULL`");
62
63 let count = ConditionEntry::find_many(executor, expr!(name == NULL), None)
64 .map_err(|e| panic!("{e:#}"))
65 .count()
66 .await;
67 assert_eq!(count, 1, "Should find 1 entry where `name IS NULL`");
68
69 let count = ConditionEntry::find_many(executor, expr!(id == (1, 3, 5) as IN), None)
70 .map_err(|e| panic!("{e:#}"))
71 .count()
72 .await;
73 assert_eq!(count, 2, "Should find 2 entries with `id IN (1, 3, 5)`");
74
75 let count = ConditionEntry::find_many(executor, expr!(!active), None)
76 .map_err(|e| panic!("{e:#}"))
77 .count()
78 .await;
79 assert_eq!(count, 1, "Should find 1 inactive entry");
80
81 let count = ConditionEntry::find_many(executor, expr!(id > 3 && active == true), None)
82 .map_err(|e| panic!("{e:#}"))
83 .count()
84 .await;
85 assert_eq!(count, 1, "Should find 1 entry with `id > 3` and active");
86
87 let count =
88 ConditionEntry::find_many(executor, expr!(ConditionEntry::name == "%e" as LIKE), None)
89 .map_err(|e| panic!("{e:#}"))
90 .count()
91 .await;
92 assert_eq!(count, 2, "Should find 2 entry with `name LIKE '%e'`");
93}