;
This commit is contained in:
1 parent
9268833a3c
commit
314b7445a1
27 files changed
+1830
No files matched your search
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "chronos-database"
|
||||
version = { workspace = true }
|
||||
edition = "2021"
|
||||
authors = ["Chronos Team"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
homepage = "https://github.com/chronos/chronos"
|
||||
repository = "https://github.com/chronos/chronos"
|
||||
|
||||
[dependencies]
|
||||
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
thiserror = "1.0"
|
||||
anyhow = "1.0"
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Database schema and migrations for Chronos
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::{PgPool, Row};
|
||||
use chrono::Utc;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Database migration manager
|
||||
pub struct MigrationManager {
|
||||
pool: PgPool,
|
||||
}
|
||||
|
||||
impl MigrationManager {
|
||||
/// Create a new migration manager
|
||||
pub fn new(pool: PgPool) -> Self {
|
||||
MigrationManager { pool }
|
||||
}
|
||||
|
||||
/// Run all pending migrations
|
||||
pub async fn run_migrations(&self) -> Result<(), sqlx::Error> {
|
||||
// Users table
|
||||
sqlx::query!(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username VARCHAR(255) UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
role VARCHAR(50) NOT NULL DEFAULT 'viewer',
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
)
|
||||
"#
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
// Sessions table
|
||||
sqlx::query!(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||
token TEXT UNIQUE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
)
|
||||
"#
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
// Create indexes
|
||||
sqlx::query!(
|
||||
r#"
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
|
||||
"#
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user