#![allow(dead_code)]
use pg_worm::prelude::*;
#[derive(Model)]
struct Book {
#[column(primary_key, auto)]
id: i64,
title: String,
sub_title: Option<String>,
pages: Vec<String>,
author_id: i64,
}
#[derive(Model)]
struct Author {
#[column(primary_key, auto)]
id: i64,
name: String,
}
#[tokio::test]
async fn complete_procedure() -> Result<(), pg_worm::Error> {
Connection::build("postgres://postgres:postgres@localhost:5432")
.max_pool_size(16)
.connect()?;
force_create_table!(Author, Book).await?;
Author::insert("Stephen King").await?;
Author::insert("Martin Luther King").await?;
Author::insert("Karl Marx").await?;
Book::insert(
"Foo - Part I",
"Subtitle".to_string(),
vec!["Page 1".to_string()],
1,
)
.await?;
Book::insert("Foo - Part II", None, vec![], 2).await?;
Book::insert("Foo - Part III", None, vec![], 3).await?;
let books = Book::select().await?;
assert_eq!(books.len(), 3);
let manifesto = Book::select_one()
.where_(Book::title.eq(&"The Communist Manifesto".into()))
.where_(Book::pages.contains(&"You have nothing to lose but your chains!".into()))
.where_(Book::id.gt(&3))
.await?;
assert!(manifesto.is_none());
let books_updated = Book::update()
.set(Book::title, &"The name of this book is a secret".into())
.await?;
assert_eq!(books_updated, 3);
let king_books = Book::query(
r#"
SELECT * FROM book
JOIN author ON author.id = book.author_id
WHERE POSITION(? in author.name) > 0
"#,
vec![&"King".to_string()],
)
.await?;
assert_eq!(king_books.len(), 2);
let page_1 = "Page 1".to_string();
let page_2 = "Page 2".to_string();
let pages = vec![&page_1, &page_2];
let any_page = Book::select_one()
.where_(Book::pages.contains_any(&pages))
.await?;
assert!(any_page.is_some());
let both_pages = Book::select_one()
.where_(Book::pages.contains_all(&pages))
.await?;
assert!(both_pages.is_none());
let transaction = Transaction::begin().await?;
transaction.execute(Book::delete()).await?;
let all_books_in_tx = transaction.execute(Book::select()).await?;
assert_eq!(all_books_in_tx.len(), 0);
let all_books_outside_tx = Book::select().await?;
assert_eq!(all_books_outside_tx.len(), 3);
transaction.commit().await?;
let all_books_after_tx = Book::select().await?;
assert_eq!(all_books_after_tx.len(), 0);
Ok(())
}