Skip to main content

docbox_database/models/
tenant_migration.rs

1use crate::{DbExecutor, DbResult, models::tenant::TenantId};
2use chrono::{DateTime, Utc};
3use serde::Serialize;
4use sqlx::prelude::FromRow;
5
6/// Structure for tracking migrations applied to a tenant
7#[derive(Debug, Clone, FromRow, Serialize)]
8pub struct TenantMigration {
9    pub tenant_id: TenantId,
10    pub env: String,
11    pub name: String,
12    pub applied_at: DateTime<Utc>,
13}
14
15pub struct CreateTenantMigration {
16    pub tenant_id: TenantId,
17    pub env: String,
18    pub name: String,
19    pub applied_at: DateTime<Utc>,
20}
21
22impl TenantMigration {
23    /// Create a new tenant migration
24    pub async fn create(db: impl DbExecutor<'_>, create: CreateTenantMigration) -> DbResult<()> {
25        sqlx::query(
26            r#"
27            INSERT INTO "docbox_tenants_migrations" (
28                "env",
29                "tenant_id",
30                "name",
31                "applied_at"
32            )
33            VALUES ($1, $2, $3, $4)
34        "#,
35        )
36        .bind(create.env)
37        .bind(create.tenant_id)
38        .bind(create.name)
39        .bind(create.applied_at)
40        .execute(db)
41        .await?;
42
43        Ok(())
44    }
45
46    /// Find all migrations for a tenant by `tenant_id` within a specific `env`
47    pub async fn find_by_tenant(
48        db: impl DbExecutor<'_>,
49        tenant_id: TenantId,
50        env: &str,
51    ) -> DbResult<Vec<TenantMigration>> {
52        sqlx::query_as(
53            r#"SELECT * FROM "docbox_tenants_migrations" WHERE "env" = $1 AND "tenant_id" = $2"#,
54        )
55        .bind(env)
56        .bind(tenant_id)
57        .fetch_all(db)
58        .await
59    }
60}