Skip to content
This repository was archived by the owner on Jan 2, 2026. It is now read-only.

Commit fc91285

Browse files
author
bitfl0wer
committed
feat: impl LocalActor::create
1 parent 261136d commit fc91285

File tree

3 files changed

+95
-2
lines changed

3 files changed

+95
-2
lines changed

.sqlx/query-4f785dcdebb1d598a4c3b0f0ba1c8d776035fffaa80baed8505f8126bb72160e.json

Lines changed: 20 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.sqlx/query-627f8b068cdf05b570baf022c5c8124e9031fb5d839a1f666202a1568e091b55.json

Lines changed: 41 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/database/models/mod.rs

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
44

55
use chrono::NaiveDateTime;
6-
use sqlx::{query, types::Uuid};
6+
use sqlx::{query, query_as, types::Uuid};
77

8-
use crate::{database::Database, errors::SonataDbError};
8+
use crate::{
9+
database::Database,
10+
errors::{Context, Errcode, Error, SonataApiError, SonataDbError},
11+
};
912

1013
#[derive(sqlx::FromRow, sqlx::Type)]
1114
pub struct PemEncoded(String);
@@ -73,6 +76,35 @@ impl LocalActor {
7376
joined_at_timestamp: record.joined,
7477
}))
7578
}
79+
80+
/// Create a new [LocalActor] in the `local_actors` table of the [Database].
81+
/// Before creating, checks, if a user specified by `local_name` already
82+
/// exists in the table, returning an [Errcode::Duplicate]-type error, if
83+
/// this is the case.
84+
///
85+
/// ## Errors
86+
///
87+
/// Other than the above, this method will error, if something is wrong with
88+
/// the Database or Database connection.
89+
pub async fn create(db: &Database, local_name: &str) -> Result<LocalActor, SonataApiError> {
90+
if LocalActor::by_local_name(db, local_name).await?.is_some() {
91+
Err(SonataApiError::Error(Error::new(
92+
Errcode::Duplicate,
93+
Some(Context::new(Some("local_name"), Some(local_name), None)),
94+
)))
95+
} else {
96+
let uaid = query!("INSERT INTO actors (type) VALUES ('local') RETURNING uaid")
97+
.fetch_one(&db.pool)
98+
.await
99+
.map_err(SonataDbError::Sqlx)?;
100+
Ok(query_as!(
101+
LocalActor,
102+
"INSERT INTO local_actors (uaid, local_name) VALUES ($1, $2) RETURNING uaid AS unique_actor_identifier, local_name, deactivated AS is_deactivated, joined AS joined_at_timestamp",
103+
uaid.uaid,
104+
local_name
105+
).fetch_one(&db.pool).await.map_err(SonataDbError::Sqlx)?)
106+
}
107+
}
76108
}
77109

78110
#[derive(sqlx::Decode, sqlx::Encode, sqlx::FromRow)]

0 commit comments

Comments
 (0)