feat: sqlx

This commit is contained in:
Ahmet Kaan GÜMÜŞ 2024-12-03 21:33:42 +03:00
parent 40149b372d
commit 20af44c357
16 changed files with 135 additions and 194 deletions

1
.env Normal file
View file

@ -0,0 +1 @@
DATABASE_URL=postgres://root:root@localhost:5432/rust_forum

View file

@ -3,16 +3,22 @@ name = "rust_forum"
version = "0.1.0"
edition = "2021"
[workspace]
members = [".", "entity", "migration"]
[lints.rust]
unsafe_code = "forbid"
[profile.release]
opt-level = 3
lto = true
overflow-checks = true
codegen-units = 1
panic = "abort"
strip = "symbols"
[dependencies]
entity = { path = "entity" }
migration = { path = "migration" }
axum = "0.7.9"
chrono = { version = "0.4.38", features = ["serde"] }
sea-orm = { version = "1.1.2", features = ["macros", "runtime-tokio-rustls", "sqlx-postgres", "with-chrono", "with-json"] }
serde = { version = "1.0.215", features = ["derive"] }
serde_json = "1.0.133"
sqlx = { version = "0.8.2", features = ["chrono", "macros", "postgres", "runtime-tokio-rustls"] }
tokio = { version = "1.41.1", features = ["full"] }
tower-http = { version = "0.6.2", features = ["cors"] }

View file

@ -3,4 +3,5 @@ address = "localhost:5432"
username = "root"
password = "root"
database = "rust_forum"
backend = "postgres"
backend = "postgres"
connection_pool_size = "100"

View file

@ -1,7 +0,0 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"
[dependencies]
sea-orm = "1.1.2"

View file

@ -1 +0,0 @@

View file

@ -1,22 +0,0 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }
[dependencies.sea-orm-migration]
version = "1.1.0"
features = [
# Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
# View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
# e.g.
"runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
"sqlx-postgres", # `DATABASE_DRIVER` feature
]

View file

@ -1,41 +0,0 @@
# Running Migrator CLI
- Generate a new migration file
```sh
cargo run -- generate MIGRATION_NAME
```
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

View file

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

View file

@ -1,69 +0,0 @@
use extension::postgres::Type;
use sea_orm::{EnumIter, Iterable};
use sea_orm_migration::{prelude::*, schema::*};
#[derive(DeriveIden)]
struct Role;
#[derive(Iden, EnumIter)]
enum RoleType {
#[iden = "Default"]
Default,
#[iden = "Admin"]
Admin,
}
#[derive(DeriveIden)]
enum User {
Table,
Id,
Name,
Surname,
Gender,
BirthDate,
Email,
Role,
}
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_type(
Type::create()
.as_enum(Role)
.values(RoleType::iter())
.to_owned(),
)
.await?;
manager
.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(pk_auto(User::Id))
.col(string(User::Name))
.col(string(User::Surname))
.col(string(User::Email))
.col(date_time(User::BirthDate))
.col(boolean(User::Gender))
.col(enumeration(
User::Role,
Alias::new("role"),
RoleType::iter(),
))
.to_owned(),
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
}

View file

@ -1,6 +0,0 @@
use sea_orm_migration::prelude::*;
#[async_std::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}

View file

@ -0,0 +1,3 @@
-- Add down migration script here
DROP TABLE IF EXISTS "user";
DROP TYPE IF EXISTS role;

View file

@ -0,0 +1,12 @@
-- Add up migration script here
DROP TYPE IF EXISTS role;
CREATE TYPE role AS ENUM('Zero', 'Hero');
CREATE TABLE IF NOT EXISTS "user"(
id BIGSERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
surname VARCHAR(255) NOT NULL,
gender boolean NOT NULL,
birth_date DATE NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
role ROLE NOT NULL DEFAULT 'Zero'
);

View file

@ -5,12 +5,15 @@ pub mod user;
use std::time::Duration;
use sea_orm::{Database, DatabaseConnection};
use sqlx::{postgres::PgPoolOptions, Connection, Pool, Postgres};
use tokio::time::sleep;
use crate::DatabaseConfig;
pub async fn establish_connection() -> DatabaseConnection {
pub async fn set_database_up(database_connection: &Pool<Postgres>) {
sqlx::migrate!().run(database_connection).await.unwrap();
}
pub async fn establish_connection() -> Pool<Postgres> {
let database_config = DatabaseConfig::default();
let connection_string = format!(
"{}://{}:{}@{}/{}",
@ -20,12 +23,27 @@ pub async fn establish_connection() -> DatabaseConnection {
database_config.address,
database_config.database
);
Database::connect(connection_string).await.unwrap()
PgPoolOptions::new()
.max_connections(database_config.connection_pool_size)
.test_before_acquire(false)
.connect(&connection_string)
.await
.unwrap()
}
pub async fn is_alive() -> bool {
pub async fn is_alive(database_connection: &Pool<Postgres>) -> bool {
tokio::select! {
database_connection = database_connection.acquire() => {
match database_connection {
Ok(mut database_connection) => {
match database_connection.ping().await {
Ok(_) => true,
Err(_) => false,
}
},
Err(_) => false,
}
}
_ = sleep(Duration::from_secs(1)) => false,
}
}

View file

@ -1 +1,73 @@
use chrono::NaiveDate;
use sqlx::{Pool, Postgres};
use crate::feature::user::{Role, User};
pub async fn create_user(
name: &String,
surname: &String,
gender: bool,
birth_date: &NaiveDate,
email: &String,
database_connection: &Pool<Postgres>,
) -> Result<User, sqlx::Error> {
sqlx::query_as!(
User,
r#"
INSERT INTO "user"(name, surname, gender, birth_date, email)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, name, surname, gender, birth_date, email, role AS "role:Role"
"#,
name,
surname,
gender,
birth_date,
email
)
.fetch_one(database_connection)
.await
}
pub async fn read_user(
email: &String,
database_connection: &Pool<Postgres>,
) -> Result<User, sqlx::Error> {
sqlx::query_as!(User,
r#"
SELECT id, name, surname, gender, birth_date, email, role AS "role:Role" FROM "user" WHERE "email" = $1
"#,
email
).fetch_one(database_connection).await
}
pub async fn update_user(
id: i64,
name: &String,
surname: &String,
gender: &bool,
birth_date: &NaiveDate,
email: &String,
database_connection: &Pool<Postgres>,
) -> Result<User, sqlx::Error> {
sqlx::query_as!(User,
r#"
UPDATE "user" SET "name" = $1, "surname" = $2, "gender" = $3, "birth_date" = $4, "email" = $5 WHERE "id" = $6
RETURNING id, name, surname, gender, birth_date, email, role AS "role:Role"
"#, name, surname, gender, birth_date, email, id).fetch_one(database_connection).await
}
pub async fn delete_user(
id: i64,
database_connection: &Pool<Postgres>,
) -> Result<User, sqlx::Error> {
sqlx::query_as!(
User,
r#"
DELETE FROM "user" where id = $1
RETURNING id, name, surname, gender, birth_date, email, role AS "role:Role"
"#,
id
)
.fetch_one(database_connection)
.await
}

View file

@ -8,36 +8,20 @@ pub struct Contact {
pub website: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, sqlx::Type)]
#[sqlx(type_name = "role")]
pub enum Role {
User,
Zero,
Hero,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct User {
pub name: Vec<String>,
pub surname: Vec<String>,
pub id: i64,
pub name: String,
pub surname: String,
pub gender: bool,
pub birth_date: NaiveDate,
pub email: String,
pub role: Role,
}
impl User {
pub async fn new(
name: Vec<String>,
surname: Vec<String>,
gender: bool,
birth_date: NaiveDate,
email: String,
) -> Self {
Self {
name,
surname,
gender,
birth_date,
email,
role: Role::User,
}
}
}

View file

@ -2,7 +2,7 @@ pub mod database;
pub mod feature;
pub mod utils;
use sea_orm::DatabaseConnection;
use sqlx::{Pool, Postgres};
use utils::naive_toml_parser;
const DATABASE_CONFIG_FILE_LOCATION: &str = "./configs/database_config.toml";
@ -15,6 +15,7 @@ pub struct DatabaseConfig {
pub password: String,
pub database: String,
pub backend: String,
pub connection_pool_size: u32,
}
impl Default for DatabaseConfig {
fn default() -> Self {
@ -22,6 +23,7 @@ impl Default for DatabaseConfig {
if header == "[database_config]" {
Self {
connection_pool_size: database_configs.pop().unwrap().parse().unwrap(),
backend: database_configs.pop().unwrap(),
database: database_configs.pop().unwrap(),
password: database_configs.pop().unwrap(),
@ -55,5 +57,5 @@ impl Default for ServerConfig {
#[derive(Debug, Clone)]
pub struct AppState {
pub database_connection: DatabaseConnection,
pub database_connection: Pool<Postgres>,
}