Improve active handling for controllers

This commit is contained in:
Tobias Reisinger 2023-11-28 00:19:15 +01:00
parent ec461a1a14
commit 6459804e1f
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
7 changed files with 87 additions and 35 deletions
emgauwa-lib/src/db

View file

@ -58,11 +58,10 @@ impl DbController {
uid: &ControllerUid,
new_name: &str,
new_relay_count: i64,
new_active: bool,
) -> Result<DbController, DatabaseError> {
match DbController::get_by_uid(conn, uid).await? {
Some(tag) => Ok(tag),
None => DbController::create(conn, uid, new_name, new_relay_count, new_active).await,
None => DbController::create(conn, uid, new_name, new_relay_count).await,
}
}
@ -94,15 +93,13 @@ impl DbController {
new_uid: &ControllerUid,
new_name: &str,
new_relay_count: i64,
new_active: bool,
) -> Result<DbController, DatabaseError> {
sqlx::query_as!(
DbController,
"INSERT INTO controllers (uid, name, relay_count, active) VALUES (?, ?, ?, ?) RETURNING *",
"INSERT INTO controllers (uid, name, relay_count) VALUES (?, ?, ?) RETURNING *",
new_uid,
new_name,
new_relay_count,
new_active,
)
.fetch_optional(conn.deref_mut())
.await?
@ -114,12 +111,28 @@ impl DbController {
conn: &mut PoolConnection<Sqlite>,
new_name: &str,
new_relay_count: i64,
) -> Result<DbController, DatabaseError> {
sqlx::query!(
"UPDATE controllers SET name = ?, relay_count = ? WHERE id = ?",
new_name,
new_relay_count,
self.id,
)
.execute(conn.deref_mut())
.await?;
Self::get(conn, self.id)
.await?
.ok_or(DatabaseError::UpdateGetError)
}
pub async fn update_active(
&self,
conn: &mut PoolConnection<Sqlite>,
new_active: bool,
) -> Result<DbController, DatabaseError> {
sqlx::query!(
"UPDATE controllers SET name = ?, relay_count = ?, active = ? WHERE id = ?",
new_name,
new_relay_count,
"UPDATE controllers SET active = ? WHERE id = ?",
new_active,
self.id,
)
@ -130,4 +143,11 @@ impl DbController {
.await?
.ok_or(DatabaseError::UpdateGetError)
}
pub async fn all_inactive(conn: &mut PoolConnection<Sqlite>) -> Result<(), DatabaseError> {
sqlx::query!("UPDATE controllers SET active = 0")
.execute(conn.deref_mut())
.await?;
Ok(())
}
}