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
187 #[cfg(not(feature = "disable-joins"))]
188 {
189 #[derive(Entity, PartialEq, Debug)]
191 struct BookAuthorResult {
192 #[tank(name = "title")]
193 book: String,
194 #[tank(name = "name")]
195 author: String,
196 }
197 let result = executor
198 .fetch(
199 QueryBuilder::new()
200 .select(cols!(B.title, A.name))
201 .from(join!(Book B JOIN Author A ON B.author == A.author_id))
202 .where_expr(expr!(B.year < 2000))
203 .order_by(cols!(B.title DESC))
204 .build(&executor.driver()),
205 )
206 .map_ok(BookAuthorResult::from_row)
207 .map(Result::flatten)
208 .try_collect::<Vec<_>>()
209 .await
210 .expect("Failed to query books and authors joined");
211 assert_eq!(
212 result,
213 [
214 BookAuthorResult{
215 book: "The Hobbit".into(),
216 author: "J.R.R. Tolkien".into()
217 },
218 BookAuthorResult{
219 book: "Harry Potter and the Philosopher's Stone".into(),
220 author: "J.K. Rowling".into(),
221 },
222 ]
223 );
224
225 let dataset = join!(
227 Book B LEFT JOIN Author A1 ON B.author == A1.author_id
228 LEFT JOIN Author A2 ON B.co_author == A2.author_id
229 );
230 let result = executor.fetch(
231 QueryBuilder::new()
232 .select(cols!(B.title, A1.name as author, A2.name as co_author))
233 .from(dataset)
234 .where_expr(true)
235 .build(&executor.driver())
236 )
237 .try_collect::<Vec<RowLabeled>>()
238 .await
239 .expect("Failed to query books and authors joined")
240 .into_iter()
241 .map(|row| {
242 let mut iter = row.values.into_iter();
243 (
244 match iter.next().unwrap() {
245 Value::Varchar(Some(v)) => v,
246 Value::Unknown(Some(v)) => v.into(),
247 v => panic!("Expected 1st value to be non null varchar, found {v:?}"),
248 },
249 match iter.next().unwrap() {
250 Value::Varchar(Some(v)) => v,
251 Value::Unknown(Some(v)) => v.into(),
252 v => panic!("Expected 2nd value to be non null varchar, found {v:?}"),
253 },
254 match iter.next().unwrap() {
255 Value::Varchar(Some(v)) => Some(v),
256 Value::Unknown(Some(v)) => Some(v.into()),
257 Value::Varchar(None) | Value::Null => None,
258 v => panic!(
259 "Expected 3rd value to be a Some(Value::Varchar(..)) | Value::Unknown(Some(..)) | Some(Value::Null)), found {v:?}",
260 ),
261 },
262 )
263 })
264 .collect::<HashSet<_>>();
265 assert_eq!(
266 result,
267 HashSet::from_iter([
268 (
269 "Harry Potter and the Philosopher's Stone".into(),
270 "J.K. Rowling".into(),
271 None
272 ),
273 (
274 "Harry Potter and the Deathly Hallows".into(),
275 "J.K. Rowling".into(),
276 None
277 ),
278 ("The Hobbit".into(), "J.R.R. Tolkien".into(), None),
279 ("Metro 2033".into(), "Dmitrij Gluchovskij".into(), None),
280 (
281 "Hogwarts 2033".into(),
282 "J.K. Rowling".into(),
283 Some("Dmitrij Gluchovskij".into())
284 ),
285 ])
286 );
287
288 #[derive(Entity, PartialEq, Eq, Hash, Debug)]
290 struct Books {
291 pub title: Option<String>,
292 pub author: Option<String>,
293 }
294 let books = executor.fetch(
295 QueryBuilder::new()
296 .select(cols!(Book::title, Author::name as author, Book::year))
297 .from(join!(Book JOIN Author ON Book::author == Author::id))
298 .where_expr(true)
299 .build(&executor.driver())
300 )
301 .and_then(|row| async { Books::from_row(row) })
302 .try_collect::<HashSet<_>>()
303 .await
304 .expect("Could not return the books");
305 assert_eq!(
306 books,
307 HashSet::from_iter([
308 Books {
309 title: Some("Harry Potter and the Philosopher's Stone".into()),
310 author: Some("J.K. Rowling".into())
311 },
312 Books {
313 title: Some("Harry Potter and the Deathly Hallows".into()),
314 author: Some("J.K. Rowling".into())
315 },
316 Books {
317 title: Some("The Hobbit".into()),
318 author: Some("J.R.R. Tolkien".into())
319 },
320 Books {
321 title: Some("Metro 2033".into()),
322 author: Some("Dmitrij Gluchovskij".into())
323 },
324 Books {
325 title: Some("Hogwarts 2033".into()),
326 author: Some("J.K. Rowling".into())
327 },
328 ])
329 );
330 }
331
332 #[cfg(not(feature = "disable-references"))]
333 {
334 use crate::silent_logs;
336 let book = Book {
337 #[cfg(not(feature = "disable-arrays"))]
338 isbn: [9, 7, 8, 1, 7, 3, 3, 5, 6, 1, 0, 8, 0],
339 title: "My book".into(),
340 author: Uuid::parse_str("c18c04b4-1aae-48a3-9814-9b70f7a38315").unwrap(),
341 co_author: None,
342 year: 2025,
343 };
344 silent_logs! {
345 assert!(
346 book.save(executor).await.is_err(),
347 "Must fail to save book violating referential integrity"
348 );
349 }
350 }
351
352 #[cfg(not(feature = "disable-ordering"))]
353 {
354 let authors = executor.fetch(
356 QueryBuilder::new()
357 .select([Author::name])
358 .from(Author::table())
359 .where_expr(true)
360 .order_by(cols!(Author::name ASC))
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 #[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_expr(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_expr(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}