From 8696dcc0afdc0896081405df13c887384500961b Mon Sep 17 00:00:00 2001 From: Kjetil Orbekk Date: Mon, 2 Jan 2023 11:58:49 -0500 Subject: Insert table in db on creation --- server/src/table.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 52 insertions(+), 10 deletions(-) (limited to 'server/src') diff --git a/server/src/table.rs b/server/src/table.rs index 7e49c7f..d2eff51 100644 --- a/server/src/table.rs +++ b/server/src/table.rs @@ -9,7 +9,8 @@ use protocol::{ simple_bots::{AlwaysPassBiddingBot, RandomPlayingBot}, }; use rand::random; -use sqlx::PgPool; +use sqlx::{PgPool, Postgres, Transaction}; +use uuid::Uuid; use crate::error::BridgeError; @@ -24,7 +25,9 @@ pub trait Table { self: Box, card: Card, ) -> Result, BridgeError>; - async fn new_deal(self: Box) -> Result, BridgeError>; + async fn new_deal( + self: Box, + ) -> Result, BridgeError>; } pub struct InMemoryTable { @@ -73,7 +76,9 @@ impl Table for InMemoryTable { Ok(Box::new(Self { state: game.into() })) } - async fn new_deal(self: Box) -> Result, BridgeError> { + async fn new_deal( + self: Box, + ) -> Result, BridgeError> { Ok(Box::new(Self { state: GameState::new(random(), random()).into(), })) @@ -116,11 +121,37 @@ pub struct DbTable { } impl DbTable { - pub fn new(db: PgPool) -> Self { - Self { + pub async fn new(db: PgPool, id: Uuid) -> Result { + let mut txn = db.begin().await?; + if let Some(_) = + sqlx::query!("select id from bridge_table where id = $1", id) + .fetch_optional(&mut txn) + .await? + { + return Self::restore(db, txn, id).await; + } + + sqlx::query!("insert into bridge_table (id) values($1)", id) + .execute(&mut txn) + .await?; + + txn.commit().await?; + Ok(Self { db, inner: Box::new(InMemoryTable::new()), - } + }) + } + + pub async fn restore( + db: PgPool, + txn: Transaction<'_, Postgres>, + id: Uuid, + ) -> Result { + txn.rollback().await?; + Ok(Self { + db, + inner: Box::new(InMemoryTable::new()), + }) } } @@ -134,17 +165,28 @@ impl Table for DbTable { self: Box, bid: Bid, ) -> Result, BridgeError> { - Ok(Box::new(Self { inner: self.inner.bid(bid).await?, ..*self })) + Ok(Box::new(Self { + inner: self.inner.bid(bid).await?, + ..*self + })) } async fn play( self: Box, card: Card, ) -> Result, BridgeError> { - Ok(Box::new(Self { inner: self.inner.play(card).await?, ..*self })) + Ok(Box::new(Self { + inner: self.inner.play(card).await?, + ..*self + })) } - async fn new_deal(self: Box) -> Result, BridgeError> { - Ok(Box::new(Self { inner: self.inner.new_deal().await?, ..*self })) + async fn new_deal( + self: Box, + ) -> Result, BridgeError> { + Ok(Box::new(Self { + inner: self.inner.new_deal().await?, + ..*self + })) } } -- cgit v1.2.3