Skip to main content

tank_tests/
simple.rs

1#![allow(unused_imports)]
2use rust_decimal::{Decimal, prelude::FromPrimitive};
3use std::{
4    borrow::Cow,
5    cell::{Cell, RefCell},
6    i128,
7    pin::pin,
8    sync::{Arc, LazyLock},
9};
10use tank::{
11    Driver, DynQuery, Entity, Executor, FixedDecimal, Query, QueryBuilder, QueryResult, RawQuery,
12    RowsAffected, SqlWriter, stream::TryStreamExt,
13};
14use time::{Date, Time, macros::date};
15use tokio::sync::Mutex;
16use uuid::Uuid;
17
18static MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
19
20#[derive(Debug, Entity, PartialEq)]
21pub struct SimpleFields {
22    #[tank(primary_key)]
23    alpha: u8,
24    bravo: Option<i32>,
25    charlie: Option<i16>,
26    delta: Option<u64>,
27    echo: Option<Uuid>,
28    #[cfg(not(feature = "disable-large-integers"))]
29    foxtrot: Option<i128>,
30    golf: Option<Time>,
31    hotel: Option<Cow<'static, str>>,
32    india: Box<Option<char>>,
33    juliet: Option<bool>,
34    kilo: Option<u32>,
35    lima: Arc<Option<f32>>,
36    mike: Option<Date>,
37    november: Option<Cell<FixedDecimal<4, 2>>>,
38    oscar: Option<RefCell<FixedDecimal<8, 3>>>,
39    papa: Option<FixedDecimal<20, 1>>,
40}
41
42pub async fn simple<E: Executor>(executor: &mut E) {
43    let _lock = MUTEX.lock().await;
44
45    // Setup
46    SimpleFields::drop_table(executor, true, false)
47        .await
48        .expect("Failed to drop SimpleNullFields table");
49    SimpleFields::create_table(executor, true, true)
50        .await
51        .expect("Failed to create SimpleNullFields table");
52
53    // Simple 1
54    SimpleFields::delete_many(executor, true)
55        .await
56        .expect("Failed to clear the SimpleNullFields table");
57    let entity = SimpleFields {
58        alpha: 1,
59        bravo: 777.into(),
60        charlie: (-2).into(),
61        delta: 9876543210.into(),
62        echo: None,
63        #[cfg(not(feature = "disable-large-integers"))]
64        foxtrot: i128::MAX.into(),
65        golf: Time::from_hms(12, 0, 10).unwrap().into(),
66        hotel: Some("Hello world!".into()),
67        india: Box::new(None),
68        juliet: true.into(),
69        kilo: None,
70        lima: Arc::new(Some(3.14)),
71        mike: None,
72        november: None,
73        oscar: None,
74        papa: Some(Decimal::from_f32(45.2).unwrap().into()),
75    };
76    entity
77        .save(executor)
78        .await
79        .expect("Failed to save simple 1");
80    let entity = SimpleFields::find_one(executor, true)
81        .await
82        .expect("Failed to query simple 1")
83        .expect("Failed to find simple 1");
84    assert_eq!(entity.alpha, 1);
85    assert_eq!(entity.bravo, Some(777));
86    assert_eq!(entity.charlie, Some(-2));
87    assert_eq!(entity.delta, Some(9876543210));
88    assert_eq!(entity.echo, None);
89    #[cfg(not(feature = "disable-large-integers"))]
90    assert_eq!(
91        entity.foxtrot,
92        Some(170_141_183_460_469_231_731_687_303_715_884_105_727)
93    );
94    assert_eq!(entity.golf, Some(Time::from_hms(12, 0, 10).unwrap()));
95    assert_eq!(entity.hotel, Some("Hello world!".into()));
96    assert_eq!(*entity.india, None);
97    assert_eq!(entity.juliet, Some(true));
98    assert_eq!(entity.kilo, None);
99    assert_eq!(*entity.lima, Some(3.14));
100    assert_eq!(entity.mike, None);
101    assert_eq!(entity.november, None);
102    assert_eq!(entity.oscar, None);
103    assert_eq!(entity.papa, Some(Decimal::from_f32(45.2).unwrap().into()));
104
105    // Simple 1 - multiple statements
106    #[cfg(not(feature = "disable-multiple-statements"))]
107    {
108        let writer = executor.driver().sql_writer();
109        let mut query = DynQuery::default();
110        writer.write_delete::<SimpleFields>(&mut query, false); // Does not delete anything
111        writer.write_select(
112            &mut query,
113            &QueryBuilder::new()
114                .select(SimpleFields::columns())
115                .from(SimpleFields::table())
116                .where_expr(true),
117        );
118        {
119            let mut stream = pin!(executor.run(query));
120            let result = stream
121                .try_next()
122                .await
123                .expect("Could not process the first query correctly");
124            let Some(QueryResult::Affected(RowsAffected { rows_affected, .. })) = result else {
125                panic!("Unexpected result type:\n{result:#?}");
126            };
127            if let Some(rows_affected) = rows_affected {
128                assert_eq!(rows_affected, 0);
129            }
130            let result = stream
131                .try_next()
132                .await
133                .expect("Could not process the second query correctly");
134            let Some(QueryResult::Row(row)) = result else {
135                panic!("Unexpected result type:\n{result:#?}");
136            };
137            let value =
138                SimpleFields::from_row(row).expect("Could not decode the row into SimpleFields");
139            assert_eq!(
140                value,
141                SimpleFields {
142                    alpha: 1,
143                    bravo: 777.into(),
144                    charlie: (-2).into(),
145                    delta: 9876543210.into(),
146                    echo: None,
147                    #[cfg(not(feature = "disable-large-integers"))]
148                    foxtrot: i128::MAX.into(),
149                    golf: Time::from_hms(12, 0, 10).unwrap().into(),
150                    hotel: Some("Hello world!".into()),
151                    india: Box::new(None),
152                    juliet: true.into(),
153                    kilo: None,
154                    lima: Arc::new(Some(3.14)),
155                    mike: None,
156                    november: None,
157                    oscar: None,
158                    papa: Some(Decimal::from_f32(45.2).unwrap().into()),
159                }
160            );
161        }
162    }
163
164    // Simple 2
165    SimpleFields::delete_many(executor, true)
166        .await
167        .expect("Failed to clear the SimpleNullFields table");
168    let entity = SimpleFields {
169        alpha: 255,
170        bravo: None,
171        charlie: None,
172        delta: None,
173        echo: Some(Uuid::parse_str("5e915574-bb30-4430-98cf-c5854f61fbbd").unwrap()),
174        #[cfg(not(feature = "disable-large-integers"))]
175        foxtrot: None,
176        golf: None,
177        hotel: None,
178        india: Box::new(None),
179        juliet: None,
180        kilo: 4294967295.into(),
181        lima: Arc::new(None),
182        mike: date!(2025 - 09 - 07).into(),
183        november: Cell::new(Decimal::from_f32(1.5).unwrap().into()).into(),
184        oscar: RefCell::new(Decimal::from_f32(5080.6244).unwrap().into()).into(),
185        papa: None,
186    };
187    entity
188        .save(executor)
189        .await
190        .expect("Failed to save simple 2");
191    let entity = SimpleFields::find_one(executor, true)
192        .await
193        .expect("Failed to query simple 2")
194        .expect("Failed to find simple 2");
195    assert_eq!(entity.alpha, 255);
196    assert_eq!(entity.bravo, None);
197    assert_eq!(entity.charlie, None);
198    assert_eq!(entity.delta, None);
199    assert_eq!(
200        entity.echo,
201        Some(Uuid::parse_str("5e915574-bb30-4430-98cf-c5854f61fbbd").unwrap())
202    );
203    #[cfg(not(feature = "disable-large-integers"))]
204    assert_eq!(entity.foxtrot, None);
205    assert_eq!(entity.golf, None);
206    assert_eq!(entity.hotel, None);
207    assert_eq!(*entity.india, None);
208    assert_eq!(entity.juliet, None);
209    assert_eq!(entity.kilo, Some(4294967295));
210    assert_eq!(*entity.lima, None);
211    assert_eq!(entity.mike, Some(date!(2025 - 09 - 07)));
212    assert_eq!(
213        entity.november,
214        Some(Cell::new(Decimal::from_f32(1.5).unwrap().into()))
215    );
216    assert_eq!(
217        entity.oscar,
218        Some(RefCell::new(Decimal::from_f32(5080.6244).unwrap().into()))
219    );
220    assert_eq!(entity.papa, None);
221
222    // Simple 2 - multiple statements
223    #[cfg(not(feature = "disable-multiple-statements"))]
224    {
225        let writer = executor.driver().sql_writer();
226        let mut query = DynQuery::default();
227        writer.write_delete::<SimpleFields>(&mut query, true);
228        writer.write_insert(&mut query, [&entity], false);
229        writer.write_select(
230            &mut query,
231            &QueryBuilder::new()
232                .select(SimpleFields::columns())
233                .from(SimpleFields::table())
234                .where_expr(true),
235        );
236        {
237            let mut stream = pin!(executor.run(query));
238            let Ok(Some(QueryResult::Affected(RowsAffected { rows_affected, .. }))) =
239                stream.try_next().await
240            else {
241                panic!("Could not process the first query correctly")
242            };
243            if let Some(rows_affected) = rows_affected {
244                assert_eq!(rows_affected, 1);
245            }
246            let Ok(Some(QueryResult::Affected(RowsAffected { rows_affected, .. }))) =
247                stream.try_next().await
248            else {
249                panic!("Could not process the first query correctly")
250            };
251            if let Some(rows_affected) = rows_affected {
252                assert_eq!(rows_affected, 1);
253            }
254            let Ok(Some(QueryResult::Row(row))) = stream.try_next().await else {
255                panic!("Could not process the second query correctly")
256            };
257            let value =
258                SimpleFields::from_row(row).expect("Could not decode the row into SimpleFields");
259            assert_eq!(
260                value,
261                SimpleFields {
262                    alpha: 255,
263                    bravo: None,
264                    charlie: None,
265                    delta: None,
266                    echo: Some(Uuid::parse_str("5e915574-bb30-4430-98cf-c5854f61fbbd").unwrap()),
267                    #[cfg(not(feature = "disable-large-integers"))]
268                    foxtrot: None,
269                    golf: None,
270                    hotel: None,
271                    india: Box::new(None),
272                    juliet: None,
273                    kilo: 4294967295.into(),
274                    lima: Arc::new(None),
275                    mike: date!(2025 - 09 - 07).into(),
276                    november: Cell::new(Decimal::from_f32(1.5).unwrap().into()).into(),
277                    oscar: RefCell::new(Decimal::from_f32(5080.6244).unwrap().into()).into(),
278                    papa: None,
279                }
280            );
281        }
282    }
283}