From 8c8ce903dbde1226ad07455e28dca90408e2fa09 Mon Sep 17 00:00:00 2001 From: subcrip Date: Fri, 29 Mar 2024 19:14:21 +0800 Subject: [PATCH] backup --- src/db.rs | 39 ++++++++++++++++++++++++++++++++++++--- src/main.rs | 16 +++++++++++++--- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/db.rs b/src/db.rs index 9569bbb..7ecd995 100644 --- a/src/db.rs +++ b/src/db.rs @@ -29,20 +29,53 @@ impl OAuthDatabase { pub mod db_tests { use super::*; + pub struct DBTestEntryType { + name: String, + age: i32, + } + + impl DBTestEntryType { + pub fn new(name: String, age: i32) -> Self { + Self { name, age } + } + } + pub struct DBTestComponents { - d: OAuthDatabase + d: Option, + dropped: bool, } impl DBTestComponents { + fn default() -> Self { + Self { d: None, dropped: false } + } pub async fn new(mut d: OAuthDatabase) -> Result { d.psql_execute("create table rust_test(name text, age int)", &[]).await?; - Ok(Self { d }) + Ok(Self { d: Some(d), dropped: false }) + } + + pub async fn create(&mut self, item: DBTestEntryType) -> Result<(), tokio_postgres::Error> { + self.d.as_mut().unwrap().psql_execute("insert into rust_test (name, age) values ($1, $2)", &[&item.name, &item.age]).await?; + Ok(()) + } + + async fn destroy(&mut self) -> Result<(), tokio_postgres::Error> { + eprintln!("destroy() called."); + self.d.as_mut().unwrap().psql_execute("drop table rust_test", &[]).await?; + eprintln!("destroy() finished."); + Ok(()) } } impl Drop for DBTestComponents { fn drop(&mut self) { - futures::executor::block_on(self.d.psql_execute("drop table rust_test", &[])).unwrap(); + eprintln!("drop() called."); + if !self.dropped { + let mut this = DBTestComponents::default(); + std::mem::swap(&mut this, self); + this.dropped = true; + tokio::spawn(async move {this.destroy().await}); + } } } } diff --git a/src/main.rs b/src/main.rs index 4651124..155239f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,8 +24,18 @@ async fn main() { println!("{}", json!(a)); } -#[tokio::test] -async fn test_table_level_operations() { +// #[tokio::test] +// async fn test_table_level_operations() { +// use db::db_tests; +// let _b = db_tests::DBTestComponents::new(db::OAuthDatabase::connect("localhost", 5432, "postgres", "configjson", "myoauth").await.unwrap()).await.unwrap(); +// } + +#[tokio::test(flavor = "multi_thread")] +async fn test_entry_level_operations() { use db::db_tests; - let _b = db_tests::DBTestComponents::new(db::OAuthDatabase::connect("localhost", 5432, "postgres", "configjson", "myoauth").await.unwrap()); + eprintln!("1"); + let mut b = db_tests::DBTestComponents::new(db::OAuthDatabase::connect("localhost", 5432, "postgres", "configjson", "myoauth").await.unwrap()).await.unwrap(); + eprintln!("2"); + assert!(matches!(b.create(db_tests::DBTestEntryType::new("subcrip".to_string(), 19)).await, Ok(()))); + eprintln!("3"); }