Add sql transactions

This commit is contained in:
Tobias Reisinger 2024-05-02 13:30:14 +02:00
parent 455ca50695
commit 9823511b62
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
9 changed files with 171 additions and 138 deletions
src/handlers/v1/ws/controllers

View file

@ -5,8 +5,6 @@ use emgauwa_common::models::{Controller, FromDbModel};
use emgauwa_common::types::{ControllerWsAction, EmgauwaUid, RelayStates};
use emgauwa_common::utils;
use futures::executor::block_on;
use sqlx::pool::PoolConnection;
use sqlx::Sqlite;
use crate::app_state::{Action, ConnectController, UpdateRelayStates};
use crate::handlers::v1::ws::controllers::ControllersWs;
@ -14,7 +12,6 @@ use crate::handlers::v1::ws::controllers::ControllersWs;
impl ControllersWs {
pub fn handle_register(
&mut self,
conn: &mut PoolConnection<Sqlite>,
ctx: &mut <ControllersWs as Actor>::Context,
controller: Controller,
) -> Result<(), EmgauwaError> {
@ -23,16 +20,19 @@ impl ControllersWs {
controller.c.name,
controller.c.uid
);
let mut tx = block_on(self.pool.begin())?;
let c = &controller.c;
let controller_db = block_on(DbController::get_by_uid_or_create(
conn,
&mut tx,
&c.uid,
&c.name,
c.relay_count,
))?;
block_on(controller_db.update_active(conn, true))?;
block_on(controller_db.update_active(&mut tx, true))?;
// update only the relay count
block_on(controller_db.update(conn, &controller_db.name, c.relay_count))?;
block_on(controller_db.update(&mut tx, &controller_db.name, c.relay_count))?;
for relay in &controller.relays {
log::debug!(
@ -45,7 +45,7 @@ impl ControllersWs {
}
);
let (new_relay, created) = block_on(DbRelay::get_by_controller_and_num_or_create(
conn,
&mut tx,
&controller_db,
relay.r.number,
&relay.r.name,
@ -54,7 +54,7 @@ impl ControllersWs {
let mut relay_schedules = Vec::new();
for schedule in &relay.schedules {
let (new_schedule, _) = block_on(DbSchedule::get_by_uid_or_create(
conn,
&mut tx,
schedule.uid.clone(),
&schedule.name,
&schedule.periods,
@ -63,7 +63,7 @@ impl ControllersWs {
}
block_on(DbJunctionRelaySchedule::set_schedules(
conn,
&mut tx,
&new_relay,
relay_schedules.iter().collect(),
))?;
@ -71,9 +71,9 @@ impl ControllersWs {
}
let controller_uid = &controller.c.uid;
let controller_db = block_on(DbController::get_by_uid(conn, controller_uid))?
let controller_db = block_on(DbController::get_by_uid(&mut tx, controller_uid))?
.ok_or(DatabaseError::InsertGetError)?;
let controller = Controller::from_db_model(conn, controller_db)?;
let controller = Controller::from_db_model(&mut tx, controller_db)?;
let addr = ctx.address();
self.controller_uid = Some(controller_uid.clone());
@ -91,6 +91,7 @@ impl ControllersWs {
action: ControllerWsAction::Relays(controller.relays),
}))??;
block_on(tx.commit())?;
log::debug!("Done registering controller");
Ok(())
}