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, Clone, PartialEq, Debug)]
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, Clone, PartialEq, Debug)]
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 #[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 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 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 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 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 let id = Uuid::parse_str("f938f818-0a40-4ce3-8fbc-259ac252a1b5").unwrap().as_value();
153 let author = Author::find_one(
154 executor,
155 expr!(Author::id == #id)
156 )
157 .await
158 .expect("Failed to query author by pk");
159 assert_eq!(
160 author,
161 Some(Author {
162 id: Uuid::parse_str("f938f818-0a40-4ce3-8fbc-259ac252a1b5")
163 .unwrap()
164 .into(),
165 name: "J.K. Rowling".into(),
166 country: "UK".into(),
167 books_published: 24.into(),
168 })
169 );
170
171 let author = Author::find_one(executor, expr!(Author::name == "Linus Torvalds"))
172 .await
173 .expect("Failed to query author by pk");
174 assert_eq!(
175 author,
176 Some(Author {
177 id: Uuid::parse_str("d3d3d3d3-d3d3-d3d3-d3d3-d3d3d3d3d3d3")
178 .unwrap()
179 .into(),
180 name: "Linus Torvalds".into(),
181 country: "Finland".into(),
182 books_published: None,
183 })
184 );
185
186 #[derive(Entity, PartialEq, Debug)]
188 struct BookAuthorResult {
189 #[tank(name = "title")]
190 book: String,
191 #[tank(name = "name")]
192 author: String,
193 }
194 let result = executor
195 .fetch(
196 QueryBuilder::new()
197 .select(cols!(B.title, A.name))
198 .from(join!(Book B JOIN Author A ON B.author == A.author_id))
199 .where_expr(expr!(B.year < 2000))
200 .order_by(cols!(B.title DESC))
201 .build(&executor.driver()),
202 )
203 .map_ok(BookAuthorResult::from_row)
204 .map(Result::flatten)
205 .try_collect::<Vec<_>>()
206 .await
207 .expect("Failed to query books and authors joined");
208 assert_eq!(
209 result,
210 [
211 BookAuthorResult{
212 book: "The Hobbit".into(),
213 author: "J.R.R. Tolkien".into()
214 },
215 BookAuthorResult{
216 book: "Harry Potter and the Philosopher's Stone".into(),
217 author: "J.K. Rowling".into(),
218 },
219 ]
220 );
221
222 let dataset = join!(
224 Book B LEFT JOIN Author A1 ON B.author == A1.author_id
225 LEFT JOIN Author A2 ON B.co_author == A2.author_id
226 );
227 let result = executor.fetch(
228 QueryBuilder::new()
229 .select(cols!(B.title, A1.name as author, A2.name as co_author))
230 .from(dataset)
231 .where_expr(true)
232 .build(&executor.driver())
233 )
234 .try_collect::<Vec<RowLabeled>>()
235 .await
236 .expect("Failed to query books and authors joined")
237 .into_iter()
238 .map(|row| {
239 let mut iter = row.values.into_iter();
240 (
241 match iter.next().unwrap() {
242 Value::Varchar(Some(v)) => v,
243 Value::Unknown(Some(v)) => v.into(),
244 v => panic!("Expected 1st value to be non null varchar, found {v:?}"),
245 },
246 match iter.next().unwrap() {
247 Value::Varchar(Some(v)) => v,
248 Value::Unknown(Some(v)) => v.into(),
249 v => panic!("Expected 2nd value to be non null varchar, found {v:?}"),
250 },
251 match iter.next().unwrap() {
252 Value::Varchar(Some(v)) => Some(v),
253 Value::Unknown(Some(v)) => Some(v.into()),
254 Value::Varchar(None) | Value::Null => None,
255 v => panic!(
256 "Expected 3rd value to be a Some(Value::Varchar(..)) | Value::Unknown(Some(..)) | Some(Value::Null)), found {v:?}",
257 ),
258 },
259 )
260 })
261 .collect::<HashSet<_>>();
262 assert_eq!(
263 result,
264 HashSet::from_iter([
265 (
266 "Harry Potter and the Philosopher's Stone".into(),
267 "J.K. Rowling".into(),
268 None
269 ),
270 (
271 "Harry Potter and the Deathly Hallows".into(),
272 "J.K. Rowling".into(),
273 None
274 ),
275 ("The Hobbit".into(), "J.R.R. Tolkien".into(), None),
276 ("Metro 2033".into(), "Dmitrij Gluchovskij".into(), None),
277 (
278 "Hogwarts 2033".into(),
279 "J.K. Rowling".into(),
280 Some("Dmitrij Gluchovskij".into())
281 ),
282 ])
283 );
284
285 #[derive(Debug, Entity, PartialEq, Eq, Hash)]
287 struct Books {
288 pub title: Option<String>,
289 pub author: Option<String>,
290 }
291 let books = executor.fetch(
292 QueryBuilder::new()
293 .select(cols!(Book::title, Author::name as author, Book::year))
294 .from(join!(Book JOIN Author ON Book::author == Author::id))
295 .where_expr(true)
296 .build(&executor.driver())
297 )
298 .and_then(|row| async { Books::from_row(row) })
299 .try_collect::<HashSet<_>>()
300 .await
301 .expect("Could not return the books");
302 assert_eq!(
303 books,
304 HashSet::from_iter([
305 Books {
306 title: Some("Harry Potter and the Philosopher's Stone".into()),
307 author: Some("J.K. Rowling".into())
308 },
309 Books {
310 title: Some("Harry Potter and the Deathly Hallows".into()),
311 author: Some("J.K. Rowling".into())
312 },
313 Books {
314 title: Some("The Hobbit".into()),
315 author: Some("J.R.R. Tolkien".into())
316 },
317 Books {
318 title: Some("Metro 2033".into()),
319 author: Some("Dmitrij Gluchovskij".into())
320 },
321 Books {
322 title: Some("Hogwarts 2033".into()),
323 author: Some("J.K. Rowling".into())
324 },
325 ])
326 );
327
328 #[cfg(not(feature = "disable-references"))]
329 {
330 use crate::silent_logs;
332 let book = Book {
333 #[cfg(not(feature = "disable-arrays"))]
334 isbn: [9, 7, 8, 1, 7, 3, 3, 5, 6, 1, 0, 8, 0],
335 title: "My book".into(),
336 author: Uuid::parse_str("c18c04b4-1aae-48a3-9814-9b70f7a38315").unwrap(),
337 co_author: None,
338 year: 2025,
339 };
340 silent_logs! {
341 assert!(
342 book.save(executor).await.is_err(),
343 "Must fail to save book violating referential integrity"
344 );
345 }
346 }
347
348 #[cfg(not(feature = "disable-ordering"))]
349 {
350 let authors = executor.fetch(
352 QueryBuilder::new()
353 .select([Author::name])
354 .from(Author::table())
355 .where_expr(true)
356 .order_by(cols!(Author::name ASC))
357 .build(&executor.driver())
358 )
359 .and_then(|row| async move { AsValue::try_from_value((*row.values)[0].clone()) })
360 .try_collect::<Vec<String>>()
361 .await
362 .expect("Could not return the ordered names of the authors");
363 assert_eq!(
364 authors,
365 vec![
366 "Dmitrij Gluchovskij".to_string(),
367 "J.K. Rowling".to_string(),
368 "J.R.R. Tolkien".to_string(),
369 "Linus Torvalds".to_string(),
370 ]
371 )
372 }
373
374 #[cfg(not(feature = "disable-multiple-statements"))]
376 {
377 let mut query = DynQuery::default();
378 let writer = executor.driver().sql_writer();
379 writer.write_select(
380 &mut query,
381 &QueryBuilder::new()
382 .select(Book::columns())
383 .from(Book::table())
384 .where_expr(expr!(Book::title == "Metro 2033"))
385 .limit(Some(1))
386 );
387 writer.write_select(
388 &mut query,
389 &QueryBuilder::new()
390 .select(Book::columns())
391 .from(Book::table())
392 .where_expr(expr!(Book::title == "Harry Potter and the Deathly Hallows"))
393 .limit(Some(1))
394 );
395 let mut stream = pin!(executor.run(query));
396 let Some(Ok(QueryResult::Row(row))) = stream.next().await else {
397 panic!("Could not get the first row")
398 };
399 let book = Book::from_row(row).expect("Could not get the book from row");
400 assert_eq!(
401 book,
402 Book {
403 #[cfg(not(feature = "disable-arrays"))]
404 isbn: [9, 7, 8, 5, 1, 7, 0, 5, 9, 6, 7, 8, 2],
405 title: "Metro 2033".into(),
406 author: gluchovskij_id,
407 co_author: None,
408 year: 2002,
409 }
410 );
411 let Some(Ok(QueryResult::Row(row))) = stream.next().await else {
412 panic!("Could not get the second row")
413 };
414 let book = Book::from_row(row).expect("Could not get the book from row");
415 assert_eq!(
416 book,
417 Book {
418 #[cfg(not(feature = "disable-arrays"))]
419 isbn: [9, 7, 8, 0, 7, 4, 7, 5, 9, 1, 0, 5, 4],
420 title: "Harry Potter and the Deathly Hallows".into(),
421 author: rowling_id,
422 co_author: None,
423 year: 2007,
424 }
425 );
426 assert!(
427 stream.next().await.is_none(),
428 "The stream should return only two rows"
429 )
430 }
431}