From bb545ab742c9cd3af27bc2efc0b3f36b9cd3ee07 Mon Sep 17 00:00:00 2001 From: Manuel Gugger Date: Mon, 6 Dec 2021 18:10:03 +0100 Subject: [PATCH] add sea-orm for sqlite db --- .env | 1 + Cargo.toml | 9 +- database.db | Bin 0 -> 20480 bytes migrations/20211206152819_SampleTable.sql | 1 + src/actix-admin/mod.rs | 0 src/entity/mod.rs | 38 ++++++++ src/entity/post.rs | 18 ++++ src/main.rs | 103 +++++++++++++--------- 8 files changed, 124 insertions(+), 46 deletions(-) create mode 100644 .env create mode 100644 database.db create mode 100644 migrations/20211206152819_SampleTable.sql create mode 100644 src/actix-admin/mod.rs create mode 100644 src/entity/mod.rs create mode 100644 src/entity/post.rs diff --git a/.env b/.env new file mode 100644 index 0000000..9e8fe09 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +DATABASE_URL=sqlite://database.db \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 1a2ccf4..62ae0f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "actix-web-sample-app" version = "0.1.0" -edition = "2018" +edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -17,8 +17,11 @@ base64 = "0.13.0" rand = "0.8.4" url = "2.2.2" http = "0.2.5" - +dotenv = "0.15" futures = "0.3.18" serde = "1.0.130" serde_json = "1.0.71" -serde_derive = "1.0.130" \ No newline at end of file +serde_derive = "1.0.130" + +sea-orm = { version = "^0", features = [ "sqlx-sqlite", "runtime-actix-native-tls", "macros" ], default-features = false } + diff --git a/database.db b/database.db new file mode 100644 index 0000000000000000000000000000000000000000..924e307bb287f7c567d6f6a80bb01c4446967749 GIT binary patch literal 20480 zcmeI&J#W)M7zc1WsZ+Hgq#&e-1wDeLQ5%#rqM#0dQ%oDxNlM~Kbir|xYin?lHomk$ zVkzp(P>B~YAie=>hl+&-Mi4VA-v9{)%GqfmY9W>mpz43}+r2!_b3e<&MK0gbZO&+= z)oxgvGSZk73Q0GKBuP>ZcX9H|kT`mKzsUWIznm56a`90#wkHim?@Ol_Vq4LDae)E> z2tWV=5P$##AOHafK;T3REGm)s#Du)Wt!0O~8;)3ZnJ(Mtux2e-Rc1??YG`DrSzV*R z*zu;-V3Q&;v3+W2I3AD7+gtuU*IO=k{X^(TeAREO(l}M^dX?-ZXREADg`z=)imuaQ zDVJAEOSGUZky$> z8}@43;&!X)2J7J?Nd|jqe3V4lWNlXjQ#Lo3D;U40I_dY)sELq1_cTI-FIn z+itqtavWASz5ZNYD;sKlaWIH(X}8siZqRI{R1y<52Sa+{Zl@-mjZ4{LQP0^a&xj=h$|h5`Wy zKmY;|fB*y_009U<00Izzz&{eWCl4!^G9ym-to7mDvRk$q>kc!#Pe`UxQ|V-SDw&$5 z^wpWvwVCvlgQvUKzrWdk|LSKZH2blm&z*mJ@f>|VGk;<2$(Pj1=8xxzgPrut(x=SW zv#-;8yP=0KM#a43*f&XRC=h@E1Rwwb2tWV=5P$##AOHafoG5{jurkv7Ljm9apQs0m a$v^-C5P$##AOHafKmY;|fB*#kDDVpd5b^5( literal 0 HcmV?d00001 diff --git a/migrations/20211206152819_SampleTable.sql b/migrations/20211206152819_SampleTable.sql new file mode 100644 index 0000000..8ddc1d3 --- /dev/null +++ b/migrations/20211206152819_SampleTable.sql @@ -0,0 +1 @@ +-- Add migration script here diff --git a/src/actix-admin/mod.rs b/src/actix-admin/mod.rs new file mode 100644 index 0000000..e69de29 diff --git a/src/entity/mod.rs b/src/entity/mod.rs new file mode 100644 index 0000000..e311765 --- /dev/null +++ b/src/entity/mod.rs @@ -0,0 +1,38 @@ +// setup +use sea_orm::sea_query::{ColumnDef, TableCreateStatement}; +use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult}; + +mod post; +pub use post::Entity as Post; + +// setup +async fn create_table(db: &DbConn, stmt: &TableCreateStatement) -> Result { + let builder = db.get_database_backend(); + db.execute(builder.build(stmt)).await +} + +pub async fn create_post_table(db: &DbConn) -> Result { + let stmt = sea_query::Table::create() + .table(post::Entity) + .if_not_exists() + .col( + ColumnDef::new(post::Column::Id) + .integer() + .not_null() + .auto_increment() + .primary_key(), + ) + .col( + ColumnDef::new(post::Column::Title) + .string() + .not_null(), + ) + .col( + ColumnDef::new(post::Column::Text) + .string() + .not_null(), + ) + .to_owned(); + + create_table(db, &stmt).await +} diff --git a/src/entity/post.rs b/src/entity/post.rs new file mode 100644 index 0000000..042206d --- /dev/null +++ b/src/entity/post.rs @@ -0,0 +1,18 @@ +use sea_orm::entity::prelude::*; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize)] +#[sea_orm(table_name = "posts")] +pub struct Model { + #[sea_orm(primary_key)] + #[serde(skip_deserializing)] + pub id: i32, + pub title: String, + #[sea_orm(column_type = "Text")] + pub text: String, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} + +impl ActiveModelBehavior for ActiveModel {} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 02563d3..c684f63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,14 +9,19 @@ use oauth2::{ AuthUrl, ClientId, ClientSecret, RedirectUrl, TokenUrl, }; +use std::time::{Duration}; use std::env; +use sea_orm::{{ DatabaseConnection, ConnectOptions }}; mod web_auth; +mod entity; +#[derive(Debug, Clone)] pub struct AppState { pub oauth: BasicClient, pub api_base_url: String, - pub tmpl: Tera + pub tmpl: Tera, + pub db: DatabaseConnection } fn index(session: Session, data: web::Data) -> HttpResponse { @@ -31,53 +36,65 @@ fn index(session: Session, data: web::Data) -> HttpResponse { #[actix_rt::main] async fn main() { - HttpServer::new(|| { - let oauth2_client_id = ClientId::new( - env::var("OAUTH2_CLIENT_ID") - .expect("Missing the OAUTH2_CLIENT_ID environment variable."), - ); - let oauth2_client_secret = ClientSecret::new( - env::var("OAUTH2_CLIENT_SECRET") - .expect("Missing the OAUTH2_CLIENT_SECRET environment variable."), - ); - let oauth2_server = - env::var("OAUTH2_SERVER").expect("Missing the OAUTH2_SERVER environment variable."); - - let auth_url = AuthUrl::new(format!("https://{}/oauth2/v2.0/authorize", oauth2_server)) - .expect("Invalid authorization endpoint URL"); - let token_url = TokenUrl::new(format!("https://{}/oauth2/v2.0/token", oauth2_server)) - .expect("Invalid token endpoint URL"); - - let api_base_url = "https://graph.microsoft.com/v1.0".to_string(); + dotenv::dotenv().ok(); + let oauth2_client_id = ClientId::new( + env::var("OAUTH2_CLIENT_ID") + .expect("Missing the OAUTH2_CLIENT_ID environment variable."), + ); + let oauth2_client_secret = ClientSecret::new( + env::var("OAUTH2_CLIENT_SECRET") + .expect("Missing the OAUTH2_CLIENT_SECRET environment variable."), + ); + let oauth2_server = + env::var("OAUTH2_SERVER").expect("Missing the OAUTH2_SERVER environment variable."); + + let auth_url = AuthUrl::new(format!("https://{}/oauth2/v2.0/authorize", oauth2_server)) + .expect("Invalid authorization endpoint URL"); + let token_url = TokenUrl::new(format!("https://{}/oauth2/v2.0/token", oauth2_server)) + .expect("Invalid token endpoint URL"); + + let api_base_url = "https://graph.microsoft.com/v1.0".to_string(); - // Set up the config for the OAuth2 process. - let client = BasicClient::new( - oauth2_client_id, - Some(oauth2_client_secret), - auth_url, - Some(token_url), - ) - // This example will be running its own server at 127.0.0.1:5000. - .set_redirect_uri( - RedirectUrl::new("http://localhost:5000/auth".to_string()) - .expect("Invalid redirect URL"), - ); + // Set up the config for the OAuth2 process. + let client = BasicClient::new( + oauth2_client_id, + Some(oauth2_client_secret), + auth_url, + Some(token_url), + ) + // This example will be running its own server at 127.0.0.1:5000. + .set_redirect_uri( + RedirectUrl::new("http://localhost:5000/auth".to_string()) + .expect("Invalid redirect URL"), + ); - let tera = - Tera::new( - concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*") - ).unwrap(); + let tera = + Tera::new( + concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*") + ).unwrap(); - let app_state = web::Data::new( - AppState { - oauth: client, - api_base_url, - tmpl: tera - } - ); + dotenv::dotenv().ok(); + let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file"); + let mut opt = ConnectOptions::new(db_url); + opt.max_connections(100) + .min_connections(5) + .connect_timeout(Duration::from_secs(8)) + .idle_timeout(Duration::from_secs(8)) + .sqlx_logging(true); + let conn = sea_orm::Database::connect(opt).await.unwrap(); + let _ = entity::create_post_table(&conn).await; + + let app_state = AppState { + oauth: client, + api_base_url, + tmpl: tera, + db: conn + }; + + HttpServer::new(move || { App::new() - .app_data(app_state) + .app_data(web::Data::new(app_state.clone())) .wrap(CookieSession::signed(&[0; 32]).secure(false)) .route("/", web::get().to(index)) .route("/login", web::get().to(web_auth::login))