tank_tests/
books.rs

1#![allow(unused_imports)]
2use std::{collections::HashSet, pin::pin, sync::LazyLock};
3use tank::{
4    DynQuery, AsValue, DataSet, Driver, Entity, Executor, Passive, Query, QueryBuilder, QueryResult,
5    RowLabeled, SqlWriter, Value, cols, expr, join, stream::{StreamExt, TryStreamExt}
6};
7use tokio::sync::Mutex;
8use uuid::Uuid;
9
10static MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
11
12#[derive(Entity, Debug, Clone, PartialEq)]
13#[tank(schema = "testing", name = "authors")]
14pub struct Author {
15    #[tank(primary_key, name = "author_id")]
16    pub id: Passive<Uuid>,
17    pub name: String,
18    pub country: String,
19    pub books_published: Option<u16>,
20}
21
22#[derive(Entity, Debug, Clone, PartialEq)]
23#[tank(schema = "testing", name = "books", primary_key = (Self::title, Self::author))]
24pub struct Book {
25    #[cfg(not(feature = "disable-arrays"))]
26    pub isbn: [u8; 13],
27    #[tank(column_type = (mysql = "VARCHAR(255)"))]
28    pub title: String,
29    /// Main author
30    #[tank(references = Author::id)]
31    pub author: Uuid,
32    #[tank(references = Author::id)]
33    pub co_author: Option<Uuid>,
34    pub year: i32,
35}
36
37pub async fn books<E: Executor>(executor: &mut E) {
38    let _lock = MUTEX.lock().await;
39
40    // Setup
41    Book::drop_table(executor, true, false)
42        .await
43        .expect("Failed to drop Book table");
44    Author::drop_table(executor, true, false)
45        .await
46        .expect("Failed to drop Author table");
47    Author::create_table(executor, false, true)
48        .await
49        .expect("Failed to create Author table");
50    Book::create_table(executor, false, true)
51        .await
52        .expect("Failed to create Book table");
53
54    // Author objects
55    let authors = vec![
56        Author {
57            id: Uuid::parse_str("f938f818-0a40-4ce3-8fbc-259ac252a1b5")
58                .unwrap()
59                .into(),
60            name: "J.K. Rowling".into(),
61            country: "UK".into(),
62            books_published: 24.into(),
63        },
64        Author {
65            id: Uuid::parse_str("a73bc06a-ff89-44b9-a62f-416ebe976285")
66                .unwrap()
67                .into(),
68            name: "J.R.R. Tolkien".into(),
69            country: "USA".into(),
70            books_published: 6.into(),
71        },
72        Author {
73            id: Uuid::parse_str("6b2f56a1-316d-42b9-a8ba-baca42c5416c")
74                .unwrap()
75                .into(),
76            name: "Dmitrij Gluchovskij".into(),
77            country: "Russia".into(),
78            books_published: 7.into(),
79        },
80        Author {
81            id: Uuid::parse_str("d3d3d3d3-d3d3-d3d3-d3d3-d3d3d3d3d3d3")
82                .unwrap()
83                .into(),
84            name: "Linus Torvalds".into(),
85            country: "Finland".into(),
86            books_published: None,
87        },
88    ];
89    let rowling_id = authors[0].id.clone().unwrap();
90    let tolkien_id = authors[1].id.clone().unwrap();
91    let gluchovskij_id = authors[2].id.clone().unwrap();
92
93    // Book objects
94    let books = vec![
95        Book {
96            #[cfg(not(feature = "disable-arrays"))]
97            isbn: [9, 7, 8, 0, 7, 4, 7, 5, 3, 2, 6, 9, 9],
98            title: "Harry Potter and the Philosopher's Stone".into(),
99            author: rowling_id,
100            co_author: None,
101            year: 1937,
102        },
103        Book {
104            #[cfg(not(feature = "disable-arrays"))]
105            isbn: [9, 7, 8, 0, 7, 4, 7, 5, 9, 1, 0, 5, 4],
106            title: "Harry Potter and the Deathly Hallows".into(),
107            author: rowling_id,
108            co_author: None,
109            year: 2007,
110        },
111        Book {
112            #[cfg(not(feature = "disable-arrays"))]
113            isbn: [9, 7, 8, 0, 6, 1, 8, 2, 6, 0, 3, 0, 0],
114            title: "The Hobbit".into(),
115            author: tolkien_id,
116            co_author: None,
117            year: 1996,
118        },
119        Book {
120            #[cfg(not(feature = "disable-arrays"))]
121            isbn: [9, 7, 8, 5, 1, 7, 0, 5, 9, 6, 7, 8, 2],
122            title: "Metro 2033".into(),
123            author: gluchovskij_id,
124            co_author: None,
125            year: 2002,
126        },
127        Book {
128            #[cfg(not(feature = "disable-arrays"))]
129            isbn: [9, 7, 8, 0, 0, 2, 3, 4, 5, 6, 7, 8, 9],
130            title: "Hogwarts 2033".into(),
131            author: rowling_id,
132            co_author: gluchovskij_id.into(),
133            year: 2026,
134        },
135    ];
136
137    // Insert
138    let result = Author::insert_many(executor, authors.iter())
139        .await
140        .expect("Failed to insert authors");
141    if let Some(affected) = result.rows_affected {
142        assert_eq!(affected, 4);
143    }
144    let result = Book::insert_many(executor, books.iter())
145        .await
146        .expect("Failed to insert books");
147    if let Some(affected) = result.rows_affected {
148        assert_eq!(affected, 5);
149    }
150
151    // Find authors
152    let author = Author::find_pk(
153        executor,
154        &(&(&Uuid::parse_str("f938f818-0a40-4ce3-8fbc-259ac252a1b5")
155            .unwrap()
156            .into(),)),
157    )
158    .await
159    .expect("Failed to query author by pk");
160    assert_eq!(
161        author,
162        Some(Author {
163            id: Uuid::parse_str("f938f818-0a40-4ce3-8fbc-259ac252a1b5")
164                .unwrap()
165                .into(),
166            name: "J.K. Rowling".into(),
167            country: "UK".into(),
168            books_published: 24.into(),
169        })
170    );
171
172    let author = Author::find_one(executor, expr!(Author::name == "Linus Torvalds"))
173        .await
174        .expect("Failed to query author by pk");
175    assert_eq!(
176        author,
177        Some(Author {
178            id: Uuid::parse_str("d3d3d3d3-d3d3-d3d3-d3d3-d3d3d3d3d3d3")
179                .unwrap()
180                .into(),
181            name: "Linus Torvalds".into(),
182            country: "Finland".into(),
183            books_published: None,
184        })
185    );
186
187    // Get books before 2000
188    let result = executor
189        .fetch(
190            QueryBuilder::new()
191                .select(&[expr!(B.title), expr!(A.name)])
192                .from(join!(Book B JOIN Author A ON B.author == A.author_id))
193                .where_condition(expr!(B.year < 2000))
194                .build(&executor.driver()),
195        )
196        .try_collect::<Vec<RowLabeled>>()
197        .await
198        .expect("Failed to query books and authors joined")
199        .into_iter()
200        .map(|row| {
201            let mut iter = row.values.into_iter();
202            (
203                match iter.next().unwrap() {
204                    Value::Varchar(Some(v)) => v,
205                    Value::Unknown(Some(v)) => v.into(),
206                    v => panic!("Expected first value to be non null varchar, found {v:?}"),
207                },
208                match iter.next().unwrap() {
209                    Value::Varchar(Some(v)) => v,
210                    Value::Unknown(Some(v)) => v.into(),
211                    v => panic!("Expected second value to be non null varchar, found {v:?}"),
212                },
213            )
214        })
215        .collect::<HashSet<_>>();
216    assert_eq!(
217        result,
218        HashSet::from_iter([
219            (
220                "Harry Potter and the Philosopher's Stone".into(),
221                "J.K. Rowling".into()
222            ),
223            ("The Hobbit".into(), "J.R.R. Tolkien".into()),
224        ])
225    );
226
227    // Get all books with their authors
228    let dataset = join!(
229        Book B LEFT JOIN Author A1 ON B.author == A1.author_id
230            LEFT JOIN Author A2 ON B.co_author == A2.author_id
231    );
232    let result = executor.fetch(
233            QueryBuilder::new()
234                .select(cols!(B.title, A1.name as author, A2.name as co_author))
235                .from(dataset)
236                .where_condition(true)
237                .build(&executor.driver())
238        ) 
239        .try_collect::<Vec<RowLabeled>>()
240        .await
241        .expect("Failed to query books and authors joined")
242        .into_iter()
243        .map(|row| {
244            let mut iter = row.values.into_iter();
245            (
246                match iter.next().unwrap() {
247                    Value::Varchar(Some(v)) => v,
248                    Value::Unknown(Some(v)) => v.into(),
249                    v => panic!("Expected 1st value to be non null varchar, found {v:?}"),
250                },
251                match iter.next().unwrap() {
252                    Value::Varchar(Some(v)) => v,
253                    Value::Unknown(Some(v)) => v.into(),
254                    v => panic!("Expected 2nd value to be non null varchar, found {v:?}"),
255                },
256                match iter.next().unwrap() {
257                    Value::Varchar(Some(v)) => Some(v),
258                    Value::Unknown(Some(v)) => Some(v.into()),
259                    Value::Varchar(None) | Value::Null => None,
260                    v => panic!(
261                        "Expected 3rd value to be a Some(Value::Varchar(..)) | Value::Unknown(Some(..)) | Some(Value::Null)), found {v:?}",
262                    ),
263                },
264            )
265        })
266        .collect::<HashSet<_>>();
267    assert_eq!(
268        result,
269        HashSet::from_iter([
270            (
271                "Harry Potter and the Philosopher's Stone".into(),
272                "J.K. Rowling".into(),
273                None
274            ),
275            (
276                "Harry Potter and the Deathly Hallows".into(),
277                "J.K. Rowling".into(),
278                None
279            ),
280            ("The Hobbit".into(), "J.R.R. Tolkien".into(), None),
281            ("Metro 2033".into(), "Dmitrij Gluchovskij".into(), None),
282            (
283                "Hogwarts 2033".into(),
284                "J.K. Rowling".into(),
285                Some("Dmitrij Gluchovskij".into())
286            ),
287        ])
288    );
289
290    // Get book and author pairs
291    #[derive(Debug, Entity, PartialEq, Eq, Hash)]
292    struct Books {
293        pub title: Option<String>,
294        pub author: Option<String>,
295    }
296    let books = executor.fetch(
297            QueryBuilder::new()
298                .select(cols!(Book::title, Author::name as author, Book::year))
299                .from(join!(Book JOIN Author ON Book::author == Author::id))
300                .where_condition(true)
301                .build(&executor.driver())
302        )
303        .and_then(|row| async { Books::from_row(row) })
304        .try_collect::<HashSet<_>>()
305        .await
306        .expect("Could not return the books");
307    assert_eq!(
308        books,
309        HashSet::from_iter([
310            Books {
311                title: Some("Harry Potter and the Philosopher's Stone".into()),
312                author: Some("J.K. Rowling".into())
313            },
314            Books {
315                title: Some("Harry Potter and the Deathly Hallows".into()),
316                author: Some("J.K. Rowling".into())
317            },
318            Books {
319                title: Some("The Hobbit".into()),
320                author: Some("J.R.R. Tolkien".into())
321            },
322            Books {
323                title: Some("Metro 2033".into()),
324                author: Some("Dmitrij Gluchovskij".into())
325            },
326            Books {
327                title: Some("Hogwarts 2033".into()),
328                author: Some("J.K. Rowling".into())
329            },
330        ])
331    );
332
333    #[cfg(not(feature = "disable-references"))]
334    {
335        // Insert book violating referential integrity
336        use crate::silent_logs;
337        let book = Book {
338            #[cfg(not(feature = "disable-arrays"))]
339            isbn: [9, 7, 8, 1, 7, 3, 3, 5, 6, 1, 0, 8, 0],
340            title: "My book".into(),
341            author: Uuid::parse_str("c18c04b4-1aae-48a3-9814-9b70f7a38315").unwrap(),
342            co_author: None,
343            year: 2025,
344        };
345        silent_logs! {
346            assert!(
347                book.save(executor).await.is_err(),
348                "Must fail to save book violating referential integrity"
349            );
350        }
351    }
352
353    #[cfg(not(feature = "disable-ordering"))]
354    {
355        // Authors names alphabetical order
356        let authors = executor.fetch(
357            QueryBuilder::new()
358                .select(cols!(Author::name ASC))
359                .from(Author::table())
360                .where_condition(true)
361                .build(&executor.driver())
362            )
363            .and_then(|row| async move { AsValue::try_from_value((*row.values)[0].clone()) })
364            .try_collect::<Vec<String>>()
365            .await
366            .expect("Could not return the ordered names of the authors");
367        assert_eq!(
368            authors,
369            vec![
370                "Dmitrij Gluchovskij".to_string(),
371                "J.K. Rowling".to_string(),
372                "J.R.R. Tolkien".to_string(),
373                "Linus Torvalds".to_string(),
374            ]
375        )
376    }
377
378    // Multiple statements
379    #[cfg(not(feature = "disable-multiple-statements"))]
380    {
381        let mut query = DynQuery::default();
382        let writer = executor.driver().sql_writer();
383        writer.write_select(
384            &mut query,
385            &QueryBuilder::new()
386                .select(Book::columns())
387                .from(Book::table())
388                .where_condition(expr!(Book::title == "Metro 2033"))
389                .limit(Some(1))
390        );
391        writer.write_select(
392            &mut query,
393            &QueryBuilder::new()
394                .select(Book::columns())
395                .from(Book::table())
396                .where_condition(expr!(Book::title == "Harry Potter and the Deathly Hallows"))
397                .limit(Some(1))
398        );
399        let mut stream = pin!(executor.run(query));
400        let Some(Ok(QueryResult::Row(row))) = stream.next().await else {
401            panic!("Could not get the first row")
402        };
403        let book = Book::from_row(row).expect("Could not get the book from row");
404        assert_eq!(
405            book,
406            Book {
407                #[cfg(not(feature = "disable-arrays"))]
408                isbn: [9, 7, 8, 5, 1, 7, 0, 5, 9, 6, 7, 8, 2],
409                title: "Metro 2033".into(),
410                author: gluchovskij_id,
411                co_author: None,
412                year: 2002,
413            }
414        );
415        let Some(Ok(QueryResult::Row(row))) = stream.next().await else {
416            panic!("Could not get the second row")
417        };
418        let book = Book::from_row(row).expect("Could not get the book from row");
419        assert_eq!(
420            book,
421            Book {
422                #[cfg(not(feature = "disable-arrays"))]
423                isbn: [9, 7, 8, 0, 7, 4, 7, 5, 9, 1, 0, 5, 4],
424                title: "Harry Potter and the Deathly Hallows".into(),
425                author: rowling_id,
426                co_author: None,
427                year: 2007,
428            }
429        );
430        assert!(
431            stream.next().await.is_none(),
432            "The stream should return only two rows"
433        )
434    }
435}