first commit

This commit is contained in:
guochao 2022-08-04 17:38:10 +08:00
commit 79296a634a
Signed by: guochao
GPG Key ID: 79F7306D2AA32FC3
14 changed files with 3312 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
/target
/*.db*
.envrc
.vscode
.idea

3022
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

33
Cargo.toml Normal file
View File

@ -0,0 +1,33 @@
[package]
name = "rust-template"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
sqlx = { version = "0.6.0", features = [
"mysql",
"sqlite",
"runtime-actix-native-tls",
] }
sea-orm-migration = "^0.9.0"
sea-orm = { version = "^0.9.0", features = [
"sqlx-sqlite",
"debug-print",
"runtime-actix-native-tls",
"macros",
] }
actix-web = "4"
askama_actix = {version = "0.13"}
askama = "0.11"
serde = { version = "1", features = ["derive"] }
env_logger = "0.9"
log = "0.4"
async-trait = "0.1.57"
clap = { version = "^3", features = ["derive"] }
clap_complete = "^3"

21
src/completion.rs Normal file
View File

@ -0,0 +1,21 @@
use std::{path::Path, str::FromStr};
use clap_complete::Shell;
fn print_completions<G: clap_complete::Generator>(gen: G, cmd: &mut clap::Command) {
clap_complete::generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout());
}
pub(crate) fn handle(shell: Option<Shell>, cmd: &mut clap::Command) {
let env_shell = std::env::var("SHELL").unwrap();
if let Some(shell) = shell {
print_completions(shell, cmd);
} else {
let filename = Path::new(&env_shell).file_name().unwrap();
match Shell::from_str(filename.to_str().unwrap()) {
Ok(shell) => print_completions(shell, cmd),
Err(err) => panic!("{}", err),
}
}
}

85
src/main.rs Normal file
View File

@ -0,0 +1,85 @@
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use sea_orm::{Database};
use sea_orm_migration::prelude::*;
#[derive(Parser, Clone)]
#[clap(author, version, about, long_about = None)]
struct Opts {
/// Name of the person to greet
#[clap(short, long = "database", value_parser, env)]
database_url: String,
#[clap(short, long, value_parser, env, default_value="0.0.0.0")]
address: String,
#[clap(short, long, value_parser, env, default_value="8888")]
port: u16,
#[clap(subcommand)]
commands: Option<Commands>,
}
#[derive(Subcommand, Clone)]
enum Commands {
/// Print shell completion scripts on standard output
Completion {
#[clap(arg_enum)]
shell: Option<Shell>,
},
/// Migrate database up and down
Migrate {
#[clap(subcommand)]
direction: MigrationDirection,
},
}
#[derive(Subcommand, Clone)]
enum MigrationDirection {
/// Migrate database up
Up {
steps: Option<u32>,
},
/// Do a fresh install
Fresh,
/// Remove previous tables and do a fresh install
Refresh,
}
mod completion;
mod migrations;
mod web;
#[actix_web::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Opts::parse();
env_logger::init();
if let Some(command) = args.commands.clone() {
match command {
Commands::Completion { shell } => {
let mut command = Opts::command();
completion::handle(shell, &mut command);
std::process::exit(0);
}
_ => {}
}
}
let database = Database::connect(args.clone().database_url).await?;
if let Some(command) = args.commands.clone() {
match command {
Commands::Migrate { direction } => match direction {
MigrationDirection::Up{steps} => migrations::Migrator::up(&database, steps).await?,
MigrationDirection::Fresh => migrations::Migrator::fresh(&database).await?,
MigrationDirection::Refresh => migrations::Migrator::refresh(&database).await?,
},
_ => (),
};
return Ok(());
}
web::run(database, args).await
}

View File

@ -0,0 +1,37 @@
use sea_orm::{sea_query::Table};
use sea_orm_migration::{MigrationTrait, MigrationName};
use sea_orm_migration::prelude::*;
pub struct Migration;
impl MigrationName for Migration {
fn name(&self) -> &str {
"m20220804_000001_create_user_table"
}
}
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: & sea_orm_migration::SchemaManager) -> Result<(),sea_orm::DbErr> {
manager.create_table(
Table::create()
.table(User::Table)
.col(ColumnDef::new(User::Id).integer().primary_key().auto_increment().not_null())
.col(ColumnDef::new(User::Name).string().unique_key().not_null())
.col(ColumnDef::new(User::Password).string().not_null())
.to_owned()
).await
}
async fn down(&self, manager: & sea_orm_migration::SchemaManager) -> Result<(),sea_orm::DbErr> {
manager.drop_table(Table::drop().table(User::Table).to_owned()).await
}
}
#[derive(Iden)]
pub enum User {
Table,
Id,
Name,
Password,
}

14
src/migrations/mod.rs Normal file
View File

@ -0,0 +1,14 @@
use sea_orm_migration::prelude::*;
pub struct Migrator;
mod m20220804_000001_create_user_table;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
Box::new(m20220804_000001_create_user_table::Migration),
]
}
}

5
src/web/controller.rs Normal file
View File

@ -0,0 +1,5 @@
pub(crate) struct UserController;
impl UserController {
}

31
src/web/mod.rs Normal file
View File

@ -0,0 +1,31 @@
use actix_web::{HttpServer, App};
use sea_orm::DatabaseConnection;
use crate::Opts;
mod urls;
mod model;
mod view;
mod controller;
#[derive(Debug, Clone)]
struct AppState {
database: DatabaseConnection,
}
pub(crate) async fn run(database: DatabaseConnection, opts: Opts) -> Result<(), Box<dyn std::error::Error>> {
let data = actix_web::web::Data::new(AppState {
database: database,
});
let server = HttpServer::new(move|| {
App::new()
.configure(urls::configure)
.app_data(data.clone())
}).bind((opts.address, opts.port))?;
let result = server.run().await?;
Ok(result)
}

5
src/web/model/mod.rs Normal file
View File

@ -0,0 +1,5 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.9.1
pub mod prelude;
pub mod user;

3
src/web/model/prelude.rs Normal file
View File

@ -0,0 +1,3 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.9.1
pub use super::user::Entity as User;

24
src/web/model/user.rs Normal file
View File

@ -0,0 +1,24 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.9.1
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
pub password: String,
}
#[derive(Copy, Clone, Debug, EnumIter)]
pub enum Relation {}
impl RelationTrait for Relation {
fn def(&self) -> RelationDef {
panic!("No RelationDef")
}
}
impl ActiveModelBehavior for ActiveModel {}

5
src/web/urls.rs Normal file
View File

@ -0,0 +1,5 @@
use actix_web::web::ServiceConfig;
pub(crate) fn configure(cfg: &mut ServiceConfig) -> () {
cfg.service(super::view::index_page);
}

22
src/web/view.rs Normal file
View File

@ -0,0 +1,22 @@
use actix_web::{Responder, HttpRequest};
use sea_orm::*;
use serde::{Deserialize, Serialize};
use super::AppState;
use super::model::prelude::*;
#[derive(Debug, Deserialize)]
pub struct Params {
page: Option<usize>,
posts_per_page: Option<usize>,
}
#[actix_web::get("/")]
async fn index_page(req: HttpRequest, data: actix_web::web::Data<AppState>) -> Result<impl Responder, Box<dyn std::error::Error>> {
let params = actix_web::web::Query::<Params>::from_query(req.query_string()).unwrap();
let users = User::find().paginate(&data.database, params.posts_per_page.unwrap_or(10)).fetch_page(params.page.unwrap_or(0)).await?;
Ok(actix_web::web::Json(users))
}