add sqlite database and message editing support

This commit is contained in:
2023-11-11 15:44:05 +01:00
parent e892fb0c5b
commit e1adadc843
11 changed files with 501 additions and 344 deletions
+39
View File
@@ -0,0 +1,39 @@
pub mod models;
pub mod schema;
use anyhow::format_err;
use diesel::prelude::*;
use diesel::SqliteConnection;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use log::debug;
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
pub struct Database {
conn: SqliteConnection,
}
impl Database {
fn new(conn: SqliteConnection) -> Self {
Self { conn }
}
pub fn connect(url: &str) -> anyhow::Result<Self> {
let mut connection = SqliteConnection::establish(url)
.map_err(|err| format_err!("Unable to connect to database at {url}: {err}"))?;
debug!("Established connection to SQLite database at {url}");
let migration_versions = connection
.run_pending_migrations(MIGRATIONS)
.map_err(|err| format_err!("Unable to run database migrations: {err}"))?;
if !migration_versions.is_empty() {
debug!("Ran database migrations for versions {migration_versions:?}");
}
Ok(Self::new(connection))
}
pub fn conn(&mut self) -> &mut SqliteConnection {
&mut self.conn
}
}
+51
View File
@@ -0,0 +1,51 @@
use super::schema::*;
use chrono::NaiveDateTime;
use diesel::{Insertable, Queryable};
use getset::Getters;
use serenity::model::id::{MessageId, WebhookId};
use std::borrow::Cow;
#[derive(Queryable, Getters)]
pub struct Post {
#[getset(get = "pub")]
announcement_id: String,
webhook_id: i64,
message_id: i64,
#[getset(get = "pub")]
last_updated: NaiveDateTime,
}
impl Post {
pub fn webhook_id(&self) -> WebhookId {
WebhookId(u64::from_le_bytes(self.webhook_id.to_le_bytes()))
}
pub fn message_id(&self) -> MessageId {
MessageId(u64::from_le_bytes(self.message_id.to_le_bytes()))
}
}
#[derive(Insertable)]
#[diesel(table_name = posts)]
pub struct NewPost<'a> {
announcement_id: Cow<'a, str>,
webhook_id: i64,
message_id: i64,
last_updated: NaiveDateTime,
}
impl<'a> NewPost<'a> {
pub fn new(
announcement_id: impl Into<Cow<'a, str>>,
webhook_id: WebhookId,
message_id: MessageId,
last_updated: NaiveDateTime,
) -> Self {
Self {
announcement_id: announcement_id.into(),
webhook_id: i64::from_le_bytes(webhook_id.0.to_le_bytes()),
message_id: i64::from_le_bytes(message_id.0.to_le_bytes()),
last_updated,
}
}
}
+10
View File
@@ -0,0 +1,10 @@
// @generated automatically by Diesel CLI.
diesel::table! {
posts (announcement_id, webhook_id) {
announcement_id -> Text,
webhook_id -> BigInt,
message_id -> BigInt,
last_updated -> Timestamp,
}
}