Skip to content

Commit

Permalink
Add migrations and entity models
Browse files Browse the repository at this point in the history
  • Loading branch information
ndelvalle committed Jul 14, 2024
1 parent 90db08e commit be4898f
Show file tree
Hide file tree
Showing 18 changed files with 1,677 additions and 933 deletions.
1,710 changes: 1,274 additions & 436 deletions Cargo.lock

Large diffs are not rendered by default.

11 changes: 8 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ version = "0.1.0"
authors = ["ndelvalle <[email protected]>"]
edition = "2021"

[workspace]
members = [".", "entity", "migration"]


[dependencies]
entity = { path = "entity" }
migration = { path = "migration" } # depends on your needs

config = "0.14.0"
serde = { version = "1.0.202", features = ["derive"] }
serde_json = "1.0.116"
serde_derive = "1.0.152"
# Wait for wither to relase a new version.
# https://github.com/thedodd/wither/pull/89#issuecomment-1023644443
wither = { git = "https://github.com/thedodd/wither", rev = "52fd503" }
futures = "0.3.30"
thiserror = "1.0.61"
axum = { version = "0.6.20", features = ["headers"] }
Expand All @@ -35,6 +39,7 @@ bcrypt = "0.15.1"
validator = { version = "0.18.1", features = ["derive"] }
mime = "0.3.17"
bytes = "1.6.0"
sea-orm = "0.12.15"

[dev-dependencies]
assert-json-diff = "2.0.2"
Expand Down
6 changes: 1 addition & 5 deletions config/default.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
{
"environment": "development",

"server": {
"port": 8080
},

"database": {
"uri": "mongodb://localhost:27017",
"uri": "postgresql://localhost:5432/rustdis",
"name": "rustapi"
},

"auth": {
"secret": "secret"
},

"logger": {
"level": "debug"
}
Expand Down
3 changes: 1 addition & 2 deletions config/production.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"environment": "production",

"logger": {
"level": "info"
}
}
}
5 changes: 1 addition & 4 deletions config/test.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
{
"environment": "test",

"server": {
"port": 8088
},

"database": {
"uri": "mongodb://localhost:27017",
"uri": "postgresql://localhost:5432/rustdis",
"name": "rustapi-test"
},

"logger": {
"level": "error"
}
Expand Down
34 changes: 17 additions & 17 deletions entity/src/entities/cat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,30 @@ use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "cat")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub created_at: DateTime,
pub updated_at: DateTime,
pub user: Uuid,
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub created_at: DateTime,
pub updated_at: DateTime,
pub user: Uuid,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::User",
to = "super::user::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
User,
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::User",
to = "super::user::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
User,
}

impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
fn to() -> RelationDef {
Relation::User.def()
}
}

impl ActiveModelBehavior for ActiveModel {}
26 changes: 13 additions & 13 deletions entity/src/entities/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,26 @@ use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub email: String,
pub password: String,
pub created_at: DateTime,
pub updated_at: DateTime,
pub locked_at: Option<DateTime>,
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub name: String,
pub email: String,
pub password: String,
pub created_at: DateTime,
pub updated_at: DateTime,
pub locked_at: Option<DateTime>,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::cat::Entity")]
Cat,
#[sea_orm(has_many = "super::cat::Entity")]
Cat,
}

impl Related<super::cat::Entity> for Entity {
fn to() -> RelationDef {
Relation::Cat.def()
}
fn to() -> RelationDef {
Relation::Cat.def()
}
}

impl ActiveModelBehavior for ActiveModel {}
4 changes: 3 additions & 1 deletion entity/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
mod entities;
pub use entities::*;

pub use entities::cat;
pub use entities::user;
80 changes: 40 additions & 40 deletions migration/src/m20240527_080925_create_users_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,49 +5,49 @@ pub struct Migration;

#[derive(DeriveIden)]
pub enum User {
Table,
Id,
Name,
Email,
Password,
CreatedAt,
UpdatedAt,
LockedAt,
Table,
Id,
Name,
Email,
Password,
CreatedAt,
UpdatedAt,
LockedAt,
}

#[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(ColumnDef::new(User::Id).uuid().not_null().primary_key())
.col(ColumnDef::new(User::Name).string().not_null())
.col(ColumnDef::new(User::Email).string().not_null())
.col(ColumnDef::new(User::Password).string().not_null())
.col(
ColumnDef::new(User::CreatedAt)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(User::UpdatedAt)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.col(ColumnDef::new(User::LockedAt).timestamp())
.to_owned(),
)
.await
}
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(ColumnDef::new(User::Id).uuid().not_null().primary_key())
.col(ColumnDef::new(User::Name).string().not_null())
.col(ColumnDef::new(User::Email).string().not_null())
.col(ColumnDef::new(User::Password).string().not_null())
.col(
ColumnDef::new(User::CreatedAt)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(User::UpdatedAt)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.col(ColumnDef::new(User::LockedAt).timestamp())
.to_owned(),
)
.await
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
}
82 changes: 41 additions & 41 deletions migration/src/m20240530_082146_create_cats_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,50 +8,50 @@ pub struct Migration;

#[derive(DeriveIden)]
enum Cat {
Table,
Id,
User,
Name,
CreatedAt,
UpdatedAt,
Table,
Id,
User,
Name,
CreatedAt,
UpdatedAt,
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Cat::Table)
.if_not_exists()
.col(ColumnDef::new(Cat::Id).uuid().not_null().primary_key())
.col(ColumnDef::new(Cat::Name).string().not_null())
.col(
ColumnDef::new(Cat::CreatedAt)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Cat::UpdatedAt)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.col(ColumnDef::new(Cat::User).uuid().not_null())
.foreign_key(
ForeignKey::create()
.from(Cat::Table, Cat::User)
.to(User::Table, User::Id),
)
.to_owned(),
)
.await
}
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Cat::Table)
.if_not_exists()
.col(ColumnDef::new(Cat::Id).uuid().not_null().primary_key())
.col(ColumnDef::new(Cat::Name).string().not_null())
.col(
ColumnDef::new(Cat::CreatedAt)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Cat::UpdatedAt)
.timestamp()
.not_null()
.default(Expr::current_timestamp()),
)
.col(ColumnDef::new(Cat::User).uuid().not_null())
.foreign_key(
ForeignKey::create()
.from(Cat::Table, Cat::User)
.to(User::Table, User::Id),
)
.to_owned(),
)
.await
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Cat::Table).to_owned())
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Cat::Table).to_owned())
.await
}
}
30 changes: 17 additions & 13 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
use mongodb::Database;
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use tokio::sync::OnceCell;
use wither::mongodb;

use std::time::Duration;

use crate::settings::SETTINGS;

static CONNECTION: OnceCell<Database> = OnceCell::const_new();
static CONNECTION: OnceCell<DatabaseConnection> = OnceCell::const_new();

pub async fn connection() -> &'static DatabaseConnection {
CONNECTION
.get_or_init(|| async {
let uri = SETTINGS.database.uri.as_str();
let mut opt = ConnectOptions::new(uri);

pub async fn connection() -> &'static Database {
CONNECTION
.get_or_init(|| async {
let db_uri = SETTINGS.database.uri.as_str();
let db_name = SETTINGS.database.name.as_str();
opt.min_connections(100)
.max_connections(1)
.connect_timeout(Duration::from_secs(10));

mongodb::Client::with_uri_str(db_uri)
Database::connect(opt)
.await
.expect("Failed to connect to PostgreSQL")
})
.await
.expect("Failed to initialize MongoDB connection")
.database(db_name)
})
.await
}
Loading

0 comments on commit be4898f

Please sign in to comment.