122 lines
3.3 KiB
Rust
122 lines
3.3 KiB
Rust
use sibyl::Row;
|
|
|
|
use crate::{ServiceInner, model::{Client, ClientBody}, error::ServiceError};
|
|
|
|
impl ServiceInner {
|
|
|
|
pub async fn get_clients(&self) -> Result<Vec<Client>, ServiceError> {
|
|
let session = self.pool.get_session().await?;
|
|
let stmt = session.prepare("
|
|
SELECT
|
|
c.bankDetails,
|
|
p.personId,
|
|
p.name,
|
|
p.lastName,
|
|
p.age,
|
|
ad.street,
|
|
ad.houseNumber,
|
|
ad.postalCode,
|
|
ad.city,
|
|
ad.country
|
|
FROM Client c
|
|
INNER JOIN Person p ON p.personId = c.personId
|
|
INNER JOIN Address ad ON p.addressId = ad.addressId
|
|
").await?;
|
|
|
|
let rows = stmt.query("").await?;
|
|
|
|
let mut clients: Vec<Client> = vec![];
|
|
|
|
while let Some(row) = rows.next().await? {
|
|
clients.push(Self::map_client_row(row)?);
|
|
}
|
|
|
|
Ok(clients)
|
|
}
|
|
|
|
pub async fn get_client(&self, id: i32) -> Result<Option<Client>, ServiceError> {
|
|
let session = self.pool.get_session().await?;
|
|
let stmt = session.prepare("
|
|
SELECT
|
|
c.bankDetails,
|
|
p.personId,
|
|
p.name,
|
|
p.lastName,
|
|
p.age,
|
|
ad.street,
|
|
ad.houseNumber,
|
|
ad.postalCode,
|
|
ad.city,
|
|
ad.country
|
|
FROM Client c
|
|
INNER JOIN Person p ON p.personId = c.personId
|
|
INNER JOIN Address ad ON p.addressId = ad.addressId
|
|
WHERE p.personId = :ID
|
|
").await?;
|
|
|
|
let row = stmt.query_single(id).await?;
|
|
|
|
Ok(match row {
|
|
Some(row) => {
|
|
Some(Self::map_client_row(row)?)
|
|
},
|
|
None => None,
|
|
})
|
|
}
|
|
|
|
pub async fn set_client(&self, id: i32, client: ClientBody) -> Result<(), ServiceError> {
|
|
let session = self.pool.get_session().await?;
|
|
let stmt = session.prepare("
|
|
UPDATE CLIENT SET
|
|
bankDetails = :BANK
|
|
WHERE personId = :ID
|
|
").await?;
|
|
|
|
let changes = stmt.execute((
|
|
(":ID", id),
|
|
(":BANK", client.bank_details.clone())
|
|
)).await?;
|
|
|
|
if changes == 0 {
|
|
let stmt = session.prepare("
|
|
INSERT INTO CLIENT
|
|
(
|
|
personId,
|
|
bankDetails
|
|
)
|
|
VALUES
|
|
(
|
|
:ID,
|
|
:BANK
|
|
)
|
|
").await?;
|
|
stmt.execute((
|
|
(":ID", id),
|
|
(":BANK", client.bank_details)
|
|
)).await?;
|
|
}
|
|
session.commit().await?;
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn delete_client(&self, id: i32) -> Result<(), ServiceError> {
|
|
let session = self.pool.get_session().await?;
|
|
let stmt = session.prepare("
|
|
DELETE FROM CLIENT WHERE personId = :ID
|
|
").await?;
|
|
|
|
stmt.execute(id).await?;
|
|
|
|
session.commit().await?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn map_client_row(row: Row) -> Result<Client, ServiceError> {
|
|
Ok(Client {
|
|
id: row.get(1)?,
|
|
bank_details: row.get(0)?,
|
|
person_data: Self::map_person_row(row, 1)?,
|
|
})
|
|
}
|
|
|
|
} |