Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

draft: Usage of Seaorm with SELECT statements: #67

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions auth_server/src/realms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ pub async fn receive_realm_pings(auth_db: std::sync::Arc<AuthDatabase>) -> Resul
async fn get_realm_list(auth_database: std::sync::Arc<AuthDatabase>, account_id: u32) -> Result<Vec<Realm>> {
//TODO(wmxd): it will be good idea to cache the database stuff
let db_realms = auth_database.get_all_realms_with_num_characters(account_id).await?;
warn!("DB realms: {:?}", db_realms);
let testing_query_result = auth_database.sea_get_all_realms_with_num_characters(account_id).await?;
warn!("Testing query result: {:?}", testing_query_result);
let mut realms = Vec::with_capacity(db_realms.len());
for realm in db_realms {
let mut flag = Realm_RealmFlag::new(realm.flags, None);
Expand Down
2 changes: 2 additions & 0 deletions databases/wrath-auth-db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ edition = "2021"
async-std = {version="*", features=["attributes"] }
anyhow = { version = "1.0.32" }
sqlx = { version = "0.7", features=["mysql", "runtime-async-std", "tls-rustls"] }
sea-orm ={ version = "0.12", features=["sqlx-mysql", "runtime-async-std-rustls", "debug-print"] }
log = "0.4"
35 changes: 35 additions & 0 deletions databases/wrath-auth-db/src/entity/account_data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "account_data")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub account_id: u32,
pub data_type: u32,
pub time: u64,
pub decompressed_size: u32,
#[sea_orm(column_type = "Binary(BlobSize::Long)", nullable)]
pub data: Option<Vec<u8>>,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::accounts::Entity",
from = "Column::AccountId",
to = "super::accounts::Column::Id",
on_update = "Restrict",
on_delete = "Cascade"
)]
Accounts,
}

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

impl ActiveModelBehavior for ActiveModel {}
47 changes: 47 additions & 0 deletions databases/wrath-auth-db/src/entity/accounts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "accounts")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: u32,
#[sea_orm(unique)]
pub username: String,
pub sessionkey: String,
pub v: String,
pub s: String,
pub banned: u8,
}

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

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

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

impl Related<super::realms::Entity> for Entity {
fn to() -> RelationDef {
super::realm_characters::Relation::Realms.def()
}
fn via() -> Option<RelationDef> {
Some(super::realm_characters::Relation::Accounts.def().rev())
}
}

impl ActiveModelBehavior for ActiveModel {}
8 changes: 8 additions & 0 deletions databases/wrath-auth-db/src/entity/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

pub mod prelude;

pub mod account_data;
pub mod accounts;
pub mod realm_characters;
pub mod realms;
6 changes: 6 additions & 0 deletions databases/wrath-auth-db/src/entity/prelude.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

pub use super::account_data::Entity as AccountData;
pub use super::accounts::Entity as Accounts;
pub use super::realm_characters::Entity as RealmCharacters;
pub use super::realms::Entity as Realms;
47 changes: 47 additions & 0 deletions databases/wrath-auth-db/src/entity/realm_characters.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "realm_characters")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub account_id: u32,
#[sea_orm(primary_key, auto_increment = false)]
pub realm_id: u32,
pub num_characters: u8,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::accounts::Entity",
from = "Column::AccountId",
to = "super::accounts::Column::Id",
on_update = "Restrict",
on_delete = "Cascade"
)]
Accounts,
#[sea_orm(
belongs_to = "super::realms::Entity",
from = "Column::RealmId",
to = "super::realms::Column::Id",
on_update = "Restrict",
on_delete = "Cascade"
)]
Realms,
}

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

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

impl ActiveModelBehavior for ActiveModel {}
41 changes: 41 additions & 0 deletions databases/wrath-auth-db/src/entity/realms.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.10

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "realms")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: u32,
pub name: String,
pub realm_type: u8,
pub flags: u8,
pub ip: String,
#[sea_orm(column_type = "Float")]
pub population: f32,
pub timezone: u8,
pub online: u8,
}

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

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

impl Related<super::accounts::Entity> for Entity {
fn to() -> RelationDef {
super::realm_characters::Relation::Accounts.def()
}
fn via() -> Option<RelationDef> {
Some(super::realm_characters::Relation::Realms.def().rev())
}
}

impl ActiveModelBehavior for ActiveModel {}
54 changes: 47 additions & 7 deletions databases/wrath-auth-db/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,49 @@
use std::time::Duration;

use anyhow::Result;
use sqlx::Row;
use entity::{realm_characters, realms};
use sea_orm::{
sea_query::Expr, Condition, ConnectOptions, Database, DatabaseConnection, DbBackend, EntityTrait, FromQueryResult, JoinType, QuerySelect,
QueryTrait, RelationTrait,
};
mod structs;
pub use structs::{DBAccount, DBAccountData, DBRealm, DBRealmWithNumCharacters};
mod entity;
pub use entity::{accounts::Entity as Accounts, realm_characters::Entity as RealmCharacters, realms::Entity as Realms};

pub struct AuthDatabase {
// I kept both the DatabaseConnection and the sqlx::MySqlPool so you can compare them
connection_pool: sqlx::MySqlPool,
database: DatabaseConnection,
}

impl AuthDatabase {
pub async fn new(conn_string: &String, timeout: Duration) -> Result<Self> {
let mut options = ConnectOptions::new(conn_string);

options
.max_connections(5)
.acquire_timeout(timeout)
.sqlx_logging(true)
.sqlx_logging_level(log::LevelFilter::Debug);

let database = Database::connect(options).await?;

let pool = sqlx::mysql::MySqlPoolOptions::new()
.max_connections(5)
.acquire_timeout(timeout)
.connect(conn_string.as_str())
.await?;

Ok(Self { connection_pool: pool })
Ok(Self {
connection_pool: pool,
database,
})
}

pub async fn get_realm_bind_ip(&self, realm_id: i32) -> Result<String> {
let bind_ip = sqlx::query("SELECT ip FROM realms WHERE id = ?")
.bind(realm_id)
.fetch_one(&self.connection_pool)
.await?
.try_get("ip")?;
// simple example using the Entity API to find a single record
let bind_ip = Realms::find_by_id(realm_id as u32).one(&self.database).await?.unwrap().ip;

Ok(bind_ip)
}
Expand All @@ -41,6 +59,28 @@ impl AuthDatabase {
.await?)
}

// Here I kept both methods so you could compare or even interchange when running the code
pub async fn sea_get_all_realms_with_num_characters(&self, account_id: u32) -> Result<Vec<DBRealmWithNumCharacters>> {
let query_statement = Realms::find()
.column_as(realm_characters::Column::NumCharacters, "num_characters")
.join(
JoinType::LeftJoin,
realms::Relation::RealmCharacters.def().on_condition(move |_left, right| {
Condition::all().add(Expr::col((right.clone(), realm_characters::Column::AccountId)).eq(account_id))
}),
)
.build(DbBackend::MySql);

// prints the generated query
println!("Query statement: {:?}", query_statement.to_string());

let fetch_data = DBRealmWithNumCharacters::find_by_statement(query_statement.clone())
.all(&self.database)
.await?;

Ok(fetch_data)
}

pub async fn get_all_realms(&self) -> Result<Vec<DBRealm>> {
Ok(sqlx::query_as!(DBRealm, "SELECT * FROM realms").fetch_all(&self.connection_pool).await?)
}
Expand Down
5 changes: 5 additions & 0 deletions databases/wrath-auth-db/src/structs.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use sea_orm::FromQueryResult;

pub struct DBRealm {
pub id: u32,
pub name: String,
Expand All @@ -9,6 +11,9 @@ pub struct DBRealm {
pub online: u8,
}

// The Derive `FromQueryResult` macro is used to convert the result of a query into a struct.
// Helps a lot when needing to feed a complex query into a struct.
#[derive(Debug, FromQueryResult)]
pub struct DBRealmWithNumCharacters {
pub id: u32,
pub name: String,
Expand Down
1 change: 1 addition & 0 deletions databases/wrath-realm-db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ edition = "2021"
async-std = {version="*", features=["attributes"] }
anyhow = { version = "1.0.32" }
sqlx = { version = "0.7", features=["mysql", "runtime-async-std", "tls-rustls"] }
sea-orm ={ version = "0.12", features=["sqlx-mysql", "runtime-async-std-rustls", "debug-print"] }
Loading