use welds::errors::Result;
use welds::errors::WeldsError;
use welds::migrations::{MigrationStep, TableState, create_table, types::Type, up};
use welds::prelude::*;
use welds_connections::Transaction;
fn db_setup(_: &TableState) -> Result<MigrationStep> {
let m = create_table("people")
.id(|c| c("id", Type::Int))
.column(|c| c("name", Type::String));
Ok(MigrationStep::new("db_setup", m))
}
#[derive(WeldsModel, Debug)]
#[welds(table = "people")]
struct Person {
#[welds(primary_key)]
id: i32,
name: String,
}
#[async_std::main]
async fn main() -> Result<()> {
pretty_env_logger::init();
let client = welds::connections::connect("sqlite::memory:").await?;
up(&client, &[db_setup]).await?;
let _ = create_with_errors(&client).await;
let count = Person::all().count(&client).await?;
assert_eq!(count, 0);
println!("PEOPLE COUNT: {}", count);
let _ = create_person(&client).await;
let count = Person::all().count(&client).await?;
assert_eq!(count, 1);
println!("PEOPLE COUNT: {}", count);
Ok(())
}
async fn create_with_errors(client: &dyn TransactStart) -> Result<()> {
let transaction = client.begin().await?;
create_person_inner_alt(&transaction).await?;
Err(WeldsError::RowNotFound)?
}
async fn create_person(client: &dyn TransactStart) -> Result<()> {
let transaction = client.begin().await?;
create_person_inner(&transaction).await?;
transaction.commit().await?;
Ok(())
}
async fn create_person_inner(transaction: &dyn Client) -> Result<()> {
let mut p = DbState::new_uncreated(Person {
id: 0,
name: "Bobby".to_owned(),
});
p.save(transaction).await?;
Ok(())
}
async fn create_person_inner_alt<'t>(transaction: &Transaction<'t>) -> Result<()> {
let mut p = DbState::new_uncreated(Person {
id: 0,
name: "Bobby".to_owned(),
});
p.save(transaction).await?;
Ok(())
}