92 lines
2.3 KiB
Rust
92 lines
2.3 KiB
Rust
use sqlx::Row;
|
|
|
|
pub async fn insert(
|
|
pool: &sqlx::PgPool,
|
|
message: &textsender_models::message::Message,
|
|
user_id: &uuid::Uuid,
|
|
) -> Result<uuid::Uuid, sqlx::Error> {
|
|
match sqlx::query(
|
|
r#"
|
|
INSERT INTO "messages" (content, user_id)
|
|
VALUES($1, $2) RETURNING id;
|
|
"#,
|
|
)
|
|
.bind(&message.content)
|
|
.bind(user_id)
|
|
.fetch_one(pool)
|
|
.await
|
|
{
|
|
Ok(row) => {
|
|
let id: uuid::Uuid = row.try_get("id")?;
|
|
Ok(id)
|
|
}
|
|
Err(_) => Err(sqlx::Error::RowNotFound),
|
|
}
|
|
}
|
|
|
|
pub async fn get(
|
|
pool: &sqlx::PgPool,
|
|
id: &uuid::Uuid,
|
|
) -> Result<textsender_models::message::Message, sqlx::Error> {
|
|
match sqlx::query(
|
|
r#"
|
|
SELECT id, content, user_id FROM "messages"
|
|
WHERE
|
|
id = $1;
|
|
"#,
|
|
)
|
|
.bind(id)
|
|
.fetch_one(pool)
|
|
.await
|
|
{
|
|
Ok(row) => {
|
|
let id: uuid::Uuid = row.try_get("id")?;
|
|
|
|
let content: String = row.try_get("content")?;
|
|
let user_id: uuid::Uuid = row.try_get("user_id")?;
|
|
Ok(textsender_models::message::Message {
|
|
id: Some(id),
|
|
content,
|
|
user_id: Some(user_id),
|
|
})
|
|
}
|
|
Err(_) => Err(sqlx::Error::RowNotFound),
|
|
}
|
|
}
|
|
|
|
pub async fn get_with_user_id(
|
|
pool: &sqlx::PgPool,
|
|
user_id: &uuid::Uuid,
|
|
) -> Result<Vec<textsender_models::message::Message>, sqlx::Error> {
|
|
match sqlx::query(
|
|
r#"
|
|
SELECT id, content, user_id FROM "messages"
|
|
WHERE
|
|
user_id = $1;
|
|
"#,
|
|
)
|
|
.bind(user_id)
|
|
.fetch_all(pool)
|
|
.await
|
|
{
|
|
Ok(rows) => {
|
|
let mut messages: Vec<textsender_models::message::Message> = Vec::new();
|
|
for row in rows {
|
|
let id: uuid::Uuid = row.try_get("id")?;
|
|
let content: String = row.try_get("content")?;
|
|
let user_id: uuid::Uuid = row.try_get("user_id")?;
|
|
|
|
let message = textsender_models::message::Message {
|
|
id: Some(id),
|
|
content,
|
|
user_id: Some(user_id),
|
|
};
|
|
messages.push(message);
|
|
}
|
|
|
|
Ok(messages)
|
|
}
|
|
Err(_) => Err(sqlx::Error::RowNotFound),
|
|
}
|
|
}
|