From 3bb48c3c59cbc1817707363a04b0ec947691a2a0 Mon Sep 17 00:00:00 2001 From: Awstin Date: Sun, 28 Apr 2024 14:20:23 -0400 Subject: [PATCH] Accessing articles from database --- src/database/mod.rs | 61 +++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 6 +++++ 2 files changed, 67 insertions(+) create mode 100644 src/database/mod.rs diff --git a/src/database/mod.rs b/src/database/mod.rs new file mode 100644 index 0000000..f254faf --- /dev/null +++ b/src/database/mod.rs @@ -0,0 +1,61 @@ +use serde::{Deserialize, Serialize}; +use surrealdb::{ + engine::remote::ws::{Client, Ws}, + opt::auth::Root, + sql::Thing, + Result, Surreal, +}; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Article { + title: String, + content: String, + previous: Option, + next: Option, + date: Option, +} + +#[derive(Debug, Deserialize)] +pub struct ArticleMetadata { + pub id: Thing, + title: String, + previous: Option, + next: Option, + date: Option, +} + +#[derive(Debug, Deserialize)] +struct Record { + #[allow(dead_code)] + id: Thing, +} + +pub async fn connect() -> Result> { + // Connect to the server + let db = Surreal::new::("127.0.0.1:8080").await?; + + // Signin as a namespace, database, or root user + db.signin(Root { + username: "root", + password: "root", + }) + .await?; + + // Select a specific namespace / database + db.use_ns("test").use_db("test").await?; + Ok(db) +} + +pub async fn get_all_articles(connection: &Surreal) -> Result> { + let mut response = connection + .query("SELECT id, title, previous, next, date FROM article ORDER BY date DESC") + .await?; + let articles: Vec = response.take(0)?; + Ok(articles) +} + +pub async fn get_article(connection: &Surreal, id: String) -> Result<()> { + let response: Vec
= connection.select(("article", id)).await?.expect("Hopefully something else has not gone terribly wrong"); + dbg!(response); + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs index 1b79d19..c315f49 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,15 @@ use anyhow::Context; +use surrealdb::{engine::remote::ws::Client, Surreal}; use tracing::info; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; mod html; +mod database; pub async fn run() -> anyhow::Result<()> { + let connection: Surreal = database::connect().await?; + let mut articles: Vec = database::get_all_articles(&connection).await?; + database::get_article(&connection, articles.pop().unwrap().id.id.to_string()).await?; + tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env()