summaryrefslogtreecommitdiff
path: root/src/channel/repo/channels.rs
diff options
context:
space:
mode:
authorOwen Jacobson <owen@grimoire.ca>2024-09-13 00:26:03 -0400
committerOwen Jacobson <owen@grimoire.ca>2024-09-13 02:42:27 -0400
commit067e3da1900d052a416c56e1c047640aa23441ae (patch)
tree8baad4240d2532216f2530f5c974479e557c675a /src/channel/repo/channels.rs
parent5d76d0712e07040d9aeeebccb189d75636a07c7a (diff)
Transmit messages via `/:chan/send` and `/:chan/events`.
Diffstat (limited to 'src/channel/repo/channels.rs')
-rw-r--r--src/channel/repo/channels.rs87
1 files changed, 87 insertions, 0 deletions
diff --git a/src/channel/repo/channels.rs b/src/channel/repo/channels.rs
new file mode 100644
index 0000000..6fb0c23
--- /dev/null
+++ b/src/channel/repo/channels.rs
@@ -0,0 +1,87 @@
+use std::fmt;
+
+use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction};
+
+use crate::error::BoxedError;
+use crate::id::Id as BaseId;
+
+pub trait Provider {
+ fn channels(&mut self) -> Channels;
+}
+
+impl<'c> Provider for Transaction<'c, Sqlite> {
+ fn channels(&mut self) -> Channels {
+ Channels(self)
+ }
+}
+
+pub struct Channels<'t>(&'t mut SqliteConnection);
+
+#[derive(Debug)]
+pub struct Channel {
+ pub id: Id,
+ pub name: String,
+}
+
+impl<'c> Channels<'c> {
+ /// Create a new channel.
+ pub async fn create(&mut self, name: &str) -> Result<Id, BoxedError> {
+ let id = Id::generate();
+
+ let channel = sqlx::query_scalar!(
+ r#"
+ insert
+ into channel (id, name)
+ values ($1, $2)
+ returning id as "id: Id"
+ "#,
+ id,
+ name,
+ )
+ .fetch_one(&mut *self.0)
+ .await?;
+
+ Ok(channel)
+ }
+
+ pub async fn all(&mut self) -> Result<Vec<Channel>, BoxedError> {
+ let channels = sqlx::query_as!(
+ Channel,
+ r#"
+ select
+ channel.id as "id: Id",
+ channel.name
+ from channel
+ order by channel.name
+ "#,
+ )
+ .fetch_all(&mut *self.0)
+ .await?;
+
+ Ok(channels)
+ }
+}
+
+/// Stable identifier for a [Channel]. Prefixed with `C`.
+#[derive(Clone, Debug, Eq, Hash, PartialEq, sqlx::Type, serde::Deserialize, serde::Serialize)]
+#[sqlx(transparent)]
+#[serde(transparent)]
+pub struct Id(BaseId);
+
+impl From<BaseId> for Id {
+ fn from(id: BaseId) -> Self {
+ Self(id)
+ }
+}
+
+impl Id {
+ pub fn generate() -> Self {
+ BaseId::generate("C")
+ }
+}
+
+impl fmt::Display for Id {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.0.fmt(f)
+ }
+}