Compare commits
3 Commits
787a32eabc
...
d18ce42938
| Author | SHA1 | Date |
|---|---|---|
|
|
d18ce42938 | |
|
|
3402cb799d | |
|
|
efc04fa8e5 |
|
|
@ -11,5 +11,7 @@ axum = "0.7"
|
|||
askama = "0.12"
|
||||
askama_axum = "0.4"
|
||||
tower-http = { version = "0.5", features = ["fs"] }
|
||||
diesel = { version = "2.1", features = ["postgres", "chrono"] }
|
||||
deadpool-diesel = {version = "0.5", features = ["postgres"]}
|
||||
r2d2_postgres = "0.18"
|
||||
deadpool-r2d2 = {version = "0.3", features = ["rt_tokio_1"]}
|
||||
deadpool = "0.10"
|
||||
thiserror = "1.0"
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
# For documentation on how to configure this file,
|
||||
# see https://diesel.rs/guides/configuring-diesel-cli
|
||||
|
||||
[print_schema]
|
||||
file = "src/schema.rs"
|
||||
custom_type_derives = ["diesel::query_builder::QueryId"]
|
||||
|
||||
[migrations_directory]
|
||||
dir = "migrations"
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
-- This file was automatically created by Diesel to setup helper functions
|
||||
-- and other internal bookkeeping. This file is safe to edit, any future
|
||||
-- changes will be added to existing projects as new migrations.
|
||||
|
||||
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
|
||||
DROP FUNCTION IF EXISTS diesel_set_updated_at();
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
-- This file was automatically created by Diesel to setup helper functions
|
||||
-- and other internal bookkeeping. This file is safe to edit, any future
|
||||
-- changes will be added to existing projects as new migrations.
|
||||
|
||||
|
||||
|
||||
|
||||
-- Sets up a trigger for the given table to automatically set a column called
|
||||
-- `updated_at` whenever the row is modified (unless `updated_at` was included
|
||||
-- in the modified columns)
|
||||
--
|
||||
-- # Example
|
||||
--
|
||||
-- ```sql
|
||||
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
|
||||
--
|
||||
-- SELECT diesel_manage_updated_at('users');
|
||||
-- ```
|
||||
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
|
||||
BEGIN
|
||||
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
|
||||
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
IF (
|
||||
NEW IS DISTINCT FROM OLD AND
|
||||
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
|
||||
) THEN
|
||||
NEW.updated_at := current_timestamp;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
|
@ -1 +0,0 @@
|
|||
DROP TABLE users;
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
CREATE TABLE users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username VARCHAR NOT NULL,
|
||||
real_name VARCHAR NOT NULL,
|
||||
email VARCHAR NOT NULL,
|
||||
password_hash VARCHAR NOT NULL,
|
||||
password_salt VARCHAR NOT NULL
|
||||
);
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
use {
|
||||
crate::db::Database,
|
||||
askama::Template,
|
||||
axum::{extract::State, routing::get, Router},
|
||||
};
|
||||
|
||||
pub fn routes() -> Router<Database> {
|
||||
Router::new().route("/", get(root))
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "index.html")]
|
||||
struct IndexTemplate<'a> {
|
||||
title: &'a str,
|
||||
}
|
||||
|
||||
async fn root<'a>(State(database): State<Database>) -> IndexTemplate<'a> {
|
||||
println!("Found {} users", database.log_num_users().await);
|
||||
IndexTemplate { title: "LocalHub" }
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
use {std::env, thiserror::Error};
|
||||
|
||||
const ENV_VAR_PREFIX: &str = "LOCALHUB_";
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("The environment variable \"{0}\" must be set.")]
|
||||
MissingEnvironmentVariable(String),
|
||||
}
|
||||
|
||||
pub struct Config {
|
||||
pub database_url: String,
|
||||
pub static_file_path: String,
|
||||
}
|
||||
|
||||
fn get_config_string(variable: &str) -> Result<String, Error> {
|
||||
let full_var = format!("{ENV_VAR_PREFIX}{variable}");
|
||||
env::var(&full_var).map_err(|_| Error::MissingEnvironmentVariable(full_var))
|
||||
}
|
||||
|
||||
pub fn get_config() -> Result<Config, Error> {
|
||||
Ok(Config {
|
||||
database_url: get_config_string("DATABASE_URL")?,
|
||||
static_file_path: get_config_string("STATIC_FILE_PATH")?,
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
use {
|
||||
deadpool, deadpool_r2d2::Runtime, thiserror::Error,
|
||||
};
|
||||
|
||||
type PgManager = deadpool_r2d2::Manager<
|
||||
r2d2_postgres::PostgresConnectionManager<r2d2_postgres::postgres::NoTls>,
|
||||
>;
|
||||
type PgPool = deadpool_r2d2::Pool<PgManager>;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("Could not initialize DB connection pool.")]
|
||||
ConnectionPoolError(#[from] deadpool::managed::BuildError),
|
||||
#[error("Error with Postgres database")]
|
||||
PostrgesError(#[from] r2d2_postgres::postgres::Error)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Database {
|
||||
pg_pool: PgPool,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
pub fn create_pool(connection_url: &str, max_size: usize) -> Result<Database, Error> {
|
||||
let pg_config: r2d2_postgres::postgres::Config = connection_url.parse()?;
|
||||
let r2d2_manager = r2d2_postgres::PostgresConnectionManager::new(
|
||||
pg_config,
|
||||
r2d2_postgres::postgres::NoTls,
|
||||
);
|
||||
let manager = PgManager::new(r2d2_manager, Runtime::Tokio1);
|
||||
let pg_pool = PgPool::builder(manager).max_size(max_size).build()?;
|
||||
Ok(Database { pg_pool })
|
||||
}
|
||||
|
||||
pub async fn log_num_users(&self) -> usize {
|
||||
self.pg_pool
|
||||
.get()
|
||||
.await
|
||||
.unwrap()
|
||||
.interact(|conn| {
|
||||
let results = conn.query("SELECT * FROM users;", &[]).unwrap();
|
||||
results.len()
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
71
src/main.rs
71
src/main.rs
|
|
@ -1,46 +1,45 @@
|
|||
use {
|
||||
askama::Template,
|
||||
axum::{extract::State, routing::get, Router},
|
||||
deadpool_diesel::postgres::{Manager, Pool, Runtime},
|
||||
std::env,
|
||||
tower_http::services::ServeDir,
|
||||
};
|
||||
use {thiserror::Error, tower_http::services::ServeDir};
|
||||
|
||||
mod models;
|
||||
mod schema;
|
||||
mod app;
|
||||
mod config;
|
||||
mod db;
|
||||
|
||||
use config::get_config;
|
||||
use db::Database;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let db_pool_manager = Manager::new(env::var("LOCALHUB_DATABASE_URL")?, Runtime::Tokio1);
|
||||
let db_pool = Pool::builder(db_pool_manager).max_size(8).build()?;
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error("Loading configuration: \"{0}\"")]
|
||||
MissingConfigError(#[from] config::Error),
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(root))
|
||||
#[error("Database error: {0}")]
|
||||
DatabaseError(#[from] db::Error),
|
||||
|
||||
#[error("{0}")]
|
||||
IOError(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
std::process::exit(match runtime.block_on(localhub_main()) {
|
||||
Ok(()) => 0,
|
||||
Err(err) => {
|
||||
eprintln!("ERROR: {}", err);
|
||||
1
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn localhub_main() -> Result<(), Error> {
|
||||
let config = get_config()?;
|
||||
|
||||
let db_pool = Database::create_pool(&config.database_url, 2)?;
|
||||
|
||||
let app = app::routes()
|
||||
.with_state(db_pool)
|
||||
.nest_service(
|
||||
"/static",
|
||||
ServeDir::new(env::var("LOCALHUB_STATIC_FILE_PATH")?),
|
||||
);
|
||||
.nest_service("/static", ServeDir::new(&config.static_file_path));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "index.html")]
|
||||
struct IndexTemplate<'a> {
|
||||
title: &'a str,
|
||||
}
|
||||
|
||||
async fn root<'a>(State(db_pool): State<Pool>) -> IndexTemplate<'a> {
|
||||
use self::models::*;
|
||||
use diesel::prelude::*;
|
||||
let db_conn = db_pool.get().await.unwrap();
|
||||
db_conn.interact(|conn| {
|
||||
let results = schema::users::table.select(User::as_select()).load(conn).unwrap();
|
||||
println!("Found {} users", results.len());
|
||||
}).await.unwrap();
|
||||
IndexTemplate { title: "LocalHub" }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
use diesel::prelude::*;
|
||||
|
||||
#[derive(Queryable, Selectable)]
|
||||
#[diesel(table_name = crate::schema::users)]
|
||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
||||
pub struct User {
|
||||
pub id: i32,
|
||||
pub username: String,
|
||||
pub real_name: String,
|
||||
pub email: String,
|
||||
pub password_hash: String,
|
||||
pub password_salt: String,
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
// @generated automatically by Diesel CLI.
|
||||
|
||||
diesel::table! {
|
||||
users (id) {
|
||||
id -> Int4,
|
||||
username -> Varchar,
|
||||
real_name -> Varchar,
|
||||
email -> Varchar,
|
||||
password_hash -> Varchar,
|
||||
password_salt -> Varchar,
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue