Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192use std::time::Duration;
use jiff::Timestamp;use sqlx::{PgPool, postgres::PgPoolOptions};use uuid::Uuid;
use crate::error::AppError;use crate::identifier::{ENTITLEMENTS_KEY, Identifier};use crate::net::model::Entitlements;
pub async fn init_pool(db_url: &str) -> Result<PgPool, sqlx::Error> { PgPoolOptions::new() .max_connections(10) .acquire_timeout(Duration::from_secs(5)) .connect(db_url) .await}
pub async fn run_migrations(pool: &PgPool) -> Result<(), sqlx::migrate::MigrateError> { sqlx::migrate!().run(pool).await}
pub async fn get_value( pool: &PgPool, uuid: &Uuid, id: &Identifier,) -> Result<Option<serde_json::Value>, AppError> { let value = sqlx::query_scalar!( r#" SELECT value FROM player_data WHERE uuid = $1 AND namespace = $2 AND path = $3 "#, uuid, id.namespace(), id.path() ) .fetch_optional(pool) .await?;
Ok(value)}
pub async fn fetch_entitlements(pool: &PgPool, uuid: &Uuid) -> Result<Entitlements, AppError> { let value = get_value(pool, uuid, &ENTITLEMENTS_KEY).await?;
Ok(value .and_then(|v| serde_json::from_value(v).ok()) .unwrap_or_else(Entitlements::empty))}
pub async fn upsert_value( pool: &PgPool, uuid: &Uuid, id: &Identifier, value: &serde_json::Value,) -> Result<(), AppError> { let updated_at = Timestamp::now().as_millisecond();
sqlx::query!( r#" INSERT INTO player_data (uuid, namespace, path, value, updated_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (uuid, namespace, path) DO UPDATE SET value = EXCLUDED.value, updated_at = EXCLUDED.updated_at "#, uuid, id.namespace(), id.path(), value, updated_at ) .execute(pool) .await?;
Ok(())}
pub async fn delete_all_for_player(pool: &PgPool, uuid: &Uuid) -> Result<u64, AppError> { let result = sqlx::query!( r#" DELETE FROM player_data WHERE uuid = $1 "#, uuid ) .execute(pool) .await?;
Ok(result.rows_affected())}