diff --git a/Cargo.lock b/Cargo.lock index cceb763..32d2732 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -49,6 +49,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "arrayvec" version = "0.7.6" @@ -314,6 +364,7 @@ dependencies = [ "log", "pretty_env_logger", "sea-orm", + "sea-orm-migration", "serde", "snafu", "static-serve", @@ -430,6 +481,52 @@ dependencies = [ "windows-link", ] +[[package]] +name = "clap" +version = "4.5.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6e6ff9dcd79cff5cd969a17a545d79e84ab086e444102a591e288a8aa3ce394" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa42cf4d2b7a41bc8f663a7cab4031ebafa1bf3875705bfaf8466dc60ab52c00" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "clap_lex" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32" + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -1173,6 +1270,15 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + [[package]] name = "inherent" version = "1.0.13" @@ -1195,6 +1301,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.14.0" @@ -1294,6 +1406,15 @@ version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + [[package]] name = "matchit" version = "0.8.4" @@ -1421,6 +1542,12 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "option-ext" version = "0.2.0" @@ -1930,6 +2057,23 @@ dependencies = [ "uuid", ] +[[package]] +name = "sea-orm-cli" +version = "2.0.0-rc.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78e98371444bce42bd3f61b46a14de270e9e923a3f40889edba52f1623b4cf75" +dependencies = [ + "chrono", + "clap", + "dotenvy", + "glob", + "indoc", + "regex", + "tracing", + "tracing-subscriber", + "url", +] + [[package]] name = "sea-orm-macros" version = "2.0.0-rc.28" @@ -1945,6 +2089,22 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sea-orm-migration" +version = "2.0.0-rc.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf48f4281089ce7440f30a6617e0b7083e70f248a9bc1c46ab06ba113b5f41bb" +dependencies = [ + "async-trait", + "clap", + "dotenvy", + "sea-orm", + "sea-orm-cli", + "sea-schema", + "tracing", + "tracing-subscriber", +] + [[package]] name = "sea-query" version = "1.0.0-rc.29" @@ -2124,6 +2284,15 @@ dependencies = [ "digest", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -2470,6 +2639,12 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.27.2" @@ -2556,6 +2731,15 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + [[package]] name = "time" version = "0.3.46" @@ -2760,6 +2944,21 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tracing-subscriber" +version = "0.3.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" +dependencies = [ + "matchers", + "once_cell", + "regex-automata", + "sharded-slab", + "thread_local", + "tracing", + "tracing-core", +] + [[package]] name = "typenum" version = "1.19.0" @@ -2823,6 +3022,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.20.0" diff --git a/Cargo.toml b/Cargo.toml index ee6aa80..fa96bc6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,10 +20,13 @@ serde = "1.0.228" static-serve = { git = "https://github.com/M4SS-Code/static-serve" } tokio = { version = "1.49.0", features = ["macros", "rt-multi-thread"] } sea-orm = { version = "2.0.0-rc", features = [ "runtime-tokio", "debug-print", "sqlx-sqlite"] } +sea-orm-migration = "2.0.0-rc" camino = { version = "1.2.2", features = [ "serde1" ] } toml = { version = "0.9.11", features = ["preserve_order"] } snafu = "0.8.9" xdg = "3.0.0" dirs = "6.0.0" +# backend for log pretty_env_logger = "0.5.0" +# custom logger log = "0.4.29" diff --git a/src/lib.rs b/src/lib.rs index 41b3e55..0f0024e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,13 +1,17 @@ -use axum::{Router, routing::get}; +use axum::{ + Router, + routing::{delete, get, post}, +}; use static_serve::embed_assets; use crate::state::AppState; +mod migrations; +mod models; mod routes; pub mod state; pub fn build_app(state: AppState) -> Router { - println!("{:?}", state); embed_assets!("assets", compress = true); Router::new() @@ -16,6 +20,8 @@ pub fn build_app(state: AppState) -> Router { .route("/books/{id}/edit", get(routes::book::edit)) .route("/books/new", get(routes::book::new)) .route("/users", get(routes::user::index)) + .route("/users", post(routes::user::create)) + .route("/users/{id}", post(routes::user::delete)) .nest("/assets", static_router()) .with_state(state) } diff --git a/src/main.rs b/src/main.rs index 6afd6fb..19f21d0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,7 @@ use bookforge::build_app; use bookforge::state::AppState; #[derive(Snafu, Debug)] -enum AppError { +pub enum AppError { #[snafu(display("Failed to initialize AppState"))] State { source: AppStateError, @@ -16,8 +16,9 @@ enum AppError { async fn main_inner() -> Result<(), AppError> { pretty_env_logger::init(); + let app_state = AppState::new().await.context(StateSnafu)?; - let app = build_app(AppState::new().await.context(StateSnafu)?); + let app = build_app(app_state); let listener = tokio::net::TcpListener::bind("0.0.0.0:8000").await.unwrap(); diff --git a/src/migrations/m20260126_000001_create_user_table.rs b/src/migrations/m20260126_000001_create_user_table.rs new file mode 100644 index 0000000..1b2a651 --- /dev/null +++ b/src/migrations/m20260126_000001_create_user_table.rs @@ -0,0 +1,33 @@ +use sea_orm_migration::{prelude::*, schema::*}; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(User::Table) + .if_not_exists() + .col(pk_auto(User::Id)) + .col(string(User::Name).unique_key()) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(User::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +pub enum User { + Table, + Id, + Name, +} diff --git a/src/migrations/m20260126_000002_create_book_table.rs b/src/migrations/m20260126_000002_create_book_table.rs new file mode 100644 index 0000000..9fa2293 --- /dev/null +++ b/src/migrations/m20260126_000002_create_book_table.rs @@ -0,0 +1,39 @@ +use sea_orm_migration::{prelude::*, schema::*}; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(Book::Table) + .if_not_exists() + .col(pk_auto(Book::Id)) + .col(string(Book::Title)) + .col(string(Book::Authors)) + .col(text(Book::Description)) + .col(text(Book::Comment)) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(Book::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +pub enum Book { + Table, + Id, + Title, + Authors, + Description, + Comment, +} diff --git a/src/migrations/mod.rs b/src/migrations/mod.rs new file mode 100644 index 0000000..61448b9 --- /dev/null +++ b/src/migrations/mod.rs @@ -0,0 +1,16 @@ +pub use sea_orm_migration::prelude::*; + +mod m20260126_000001_create_user_table; +mod m20260126_000002_create_book_table; + +pub struct Migrator; + +#[async_trait::async_trait] +impl MigratorTrait for Migrator { + fn migrations() -> Vec> { + vec![ + Box::new(m20260126_000001_create_user_table::Migration), + Box::new(m20260126_000002_create_book_table::Migration), + ] + } +} diff --git a/src/models/mod.rs b/src/models/mod.rs new file mode 100644 index 0000000..22d12a3 --- /dev/null +++ b/src/models/mod.rs @@ -0,0 +1 @@ +pub mod user; diff --git a/src/models/user.rs b/src/models/user.rs new file mode 100644 index 0000000..57c5a5c --- /dev/null +++ b/src/models/user.rs @@ -0,0 +1,64 @@ +use crate::routes::user::UserForm; +use crate::state::AppState; +use sea_orm::ActiveValue::Set; +use sea_orm::DeleteResult; +use sea_orm::entity::prelude::*; +use snafu::ResultExt; +use snafu::prelude::*; + +#[sea_orm::model] +#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)] +#[sea_orm(table_name = "user")] +pub struct Model { + #[sea_orm(primary_key)] + pub id: i32, + pub name: String, + // #[sea_orm(has_many)] + // pub book: HasMany, +} + +#[async_trait::async_trait] +impl ActiveModelBehavior for ActiveModel {} + +#[derive(Debug, Snafu)] +#[snafu(visibility(pub))] +pub enum UserError { + // #[snafu(display("The Content Folder (Path: {path}) does not exist"))] + // NotFound { path: String }, + #[snafu(display("Database error"))] + DB { source: sea_orm::DbErr }, +} + +#[derive(Debug)] +pub struct UserOperator { + pub state: AppState, +} + +impl UserOperator { + pub fn new(state: AppState) -> Self { + Self { state } + } + + pub async fn list(&self) -> Result, UserError> { + Entity::find().all(&self.state.db).await.context(DBSnafu) + } + + pub async fn create(&self, form: UserForm) -> Result { + let user = ActiveModel { + name: Set(form.name), + ..Default::default() + }; + + user.insert(&self.state.db).await.context(DBSnafu) + } + + pub async fn delete(&self, user_id: i32) -> Result { + let user: Option = Entity::find_by_id(user_id) + .one(&self.state.db) + .await + .context(DBSnafu)?; + let user: Model = user.unwrap(); + + user.delete(&self.state.db).await.context(DBSnafu) + } +} diff --git a/src/routes/user.rs b/src/routes/user.rs index 1ab760f..bf13548 100644 --- a/src/routes/user.rs +++ b/src/routes/user.rs @@ -1,16 +1,60 @@ use askama::Template; use askama_web::WebTemplate; +use axum::{ + Form, + extract::{Path, State}, + response::Redirect, +}; +use serde::Deserialize; +use snafu::prelude::*; -use crate::state::error::AppStateError; +use crate::{ + models::user::{self, UserOperator}, + state::{ + AppState, + error::{AppStateError, UserSnafu}, + }, +}; #[derive(Template, WebTemplate)] #[template(path = "users/index.html")] -struct UsersIndexTemplate {} - -pub async fn index() -> Result { - if 0 > 1 { - return Err(AppStateError::Error); - } - - Ok(UsersIndexTemplate {}) +struct UsersIndexTemplate { + users: Vec, +} + +pub async fn index( + State(state): State, +) -> Result { + let users = UserOperator::new(state).list().await.context(UserSnafu)?; + + Ok(UsersIndexTemplate { users }) +} + +#[derive(Deserialize)] +pub struct UserForm { + pub name: String, +} + +pub async fn create( + State(state): State, + Form(form): Form, +) -> Result { + let _user = UserOperator::new(state) + .create(form) + .await + .context(UserSnafu)?; + + Ok(Redirect::to("/users")) +} + +pub async fn delete( + State(state): State, + Path(id): Path, +) -> Result { + let _user = UserOperator::new(state) + .delete(id) + .await + .context(UserSnafu)?; + + Ok(Redirect::to("/users")) } diff --git a/src/state/error.rs b/src/state/error.rs index 6c43058..fa6970f 100644 --- a/src/state/error.rs +++ b/src/state/error.rs @@ -3,7 +3,7 @@ use askama_web::WebTemplate; use axum::response::{IntoResponse, Response}; use snafu::prelude::*; -use crate::state::config::ConfigError; +use crate::{models::user::UserError, state::config::ConfigError}; #[derive(Template, WebTemplate)] #[template(path = "error.html")] @@ -21,6 +21,14 @@ pub enum AppStateError { ConfigError { source: ConfigError, }, + #[snafu(display("Migration Error"))] + Migration { + source: sea_orm::error::DbErr, + }, + #[snafu(display("User Model Error"))] + User { + source: UserError, + }, } impl IntoResponse for AppStateError { diff --git a/src/state/mod.rs b/src/state/mod.rs index 811ca9e..1ae4694 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -1,8 +1,9 @@ use sea_orm::{Database, DatabaseConnection}; use snafu::prelude::*; -use crate::state::config::AppConfig; +use crate::{migrations::Migrator, state::config::AppConfig}; use error::*; +use sea_orm_migration::MigratorTrait; pub mod config; pub mod error; @@ -15,6 +16,7 @@ pub struct AppState { impl AppState { pub async fn new() -> Result { + log::info!("Load configurations..."); let config: AppConfig = AppConfig::new().await.context(ConfigSnafu)?; let db: DatabaseConnection = @@ -22,6 +24,10 @@ impl AppState { .await .context(SqliteSnafu)?; + log::info!("Database Loaded at : {}", config.database_path.clone()); + + Migrator::up(&db, None).await.context(MigrationSnafu)?; + Ok(Self { config, db }) } } diff --git a/templates/users/index.html b/templates/users/index.html index ec2b01c..e6ae674 100644 --- a/templates/users/index.html +++ b/templates/users/index.html @@ -2,38 +2,38 @@ {% import "components/typography.html" as typography %} {% block main %} - {{ typography::heading("All users") }} +{{ typography::heading("All users") }} - - - - - - - - - - - - - - - - - - - - - - - -
#NameNombre de livresActions
1Jean34 - - Delete - -
2Pierre34 - - Delete - -
-{% endblock %} + + + + + + + + + + + {% for user in users %} + + + + + + + {% endfor %} + +
#NameNombre de livresActions
{{ user.id }}{{ user.name }}10 +
+ +
+
+ +
+ + + + +
+ +{% endblock %} \ No newline at end of file