From 2d1efbc179b7cf0076d1f4e09c71ee4416bc7d6b Mon Sep 17 00:00:00 2001 From: Awstin Date: Tue, 4 Mar 2025 07:43:08 -0500 Subject: [PATCH] Managing SQL tables in package --- schema.sql | 36 ++++++++++++++++++++++++++++++++++++ src/lib.rs | 12 ++++++++++-- 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 schema.sql diff --git a/schema.sql b/schema.sql new file mode 100644 index 0000000..174205a --- /dev/null +++ b/schema.sql @@ -0,0 +1,36 @@ +DO $$ + BEGIN + CREATE TYPE link_type as ENUM ('article', 'blog'); + EXCEPTION + WHEN duplicate_object THEN null; + END +$$; + +CREATE TABLE IF NOT EXISTS articles ( + reference varchar(20) not null, + title varchar(50) not null, + previous varchar(20), + next varchar(20), + description text, + content text not null, + date date not null, + id serial primary key); + +CREATE TABLE IF NOT EXISTS links ( + url varchar(100) not null, + date_added date not null, + description text, + title text not null, + author varchar(50) not null, + link_type link_type not null, + id serial primary key); + +CREATE TABLE IF NOT EXISTS users ( + id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + username text NOT NULL UNIQUE, + password text NOT NULL, + admin boolean NOT NULL); + +CREATE TABLE IF NOT EXISTS sessions ( + session_token BYTEA PRIMARY KEY, + user_id integer REFERENCES users (id) ON DELETE CASCADE NOT NULL); diff --git a/src/lib.rs b/src/lib.rs index d9a5fdf..78fa71c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ #![allow(async_fn_in_trait)] use crate::database::article::load_articles; -use sqlx::PgPool; +use sqlx::{Executor, PgPool}; use std::error::Error; use tracing::info; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -11,7 +11,10 @@ mod errors; mod html; mod macros; -pub async fn run_server(pool: PgPool) -> std::io::Result<()> { +pub async fn run_server(pool: PgPool) -> Result<(), Box> { + pool.execute(include_str!("../schema.sql")) + .await?; + tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() @@ -19,11 +22,13 @@ pub async fn run_server(pool: PgPool) -> std::io::Result<()> { ) .with(tracing_subscriber::fmt::layer()) .init(); + info!("initializing router..."); let port = 21212_u16; let addr = std::net::SocketAddr::from(([0, 0, 0, 0], port)); let router = html::root::get_router(pool); info!("router initialized, now listening on port {}", port); + match axum::Server::bind(&addr) .serve(router.into_make_service()) .await @@ -35,6 +40,9 @@ pub async fn run_server(pool: PgPool) -> std::io::Result<()> { } pub async fn run_load(pool: &PgPool) -> Result<(), Box> { + pool.execute(include_str!("../schema.sql")) + .await?; + load_articles(pool).await?; Ok(()) }