tango-core 0.3.0

The tango schema, entities, migrations, and search contract
Documentation
use sea_orm_migration::prelude::*;

/// Fills in `captions_available` for videos harvested before that column
/// existed.
///
/// The answers were already in the database: a stored transcript document, or a
/// non-empty language list, is proof that a video has captions, and a stored
/// availability with both lists empty is proof that it has none.
///
/// What stays NULL is a video nothing has looked at, and it must. Defaulting it
/// to false would destroy the distinction the column exists to make — a
/// transcript planner that reads "unknown" as "no captions" would skip videos
/// that have them, and a planner that reads "unknown" as "maybe" would waste a
/// call on videos that do not. Both reads have to stay possible, so the unknown
/// has to stay unknown.
///
/// Resolving the remainder needs a re-harvest, which is not a migration: it
/// costs an API call or a yt-dlp invocation per video, and applying a schema
/// change would then be unpredictably expensive.
#[derive(DeriveMigrationName)]
pub struct Migration;

const UP: &str = include_str!("sql/0013_backfill_captions_available.sql");

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.get_connection().execute_unprepared(UP).await?;
        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        // Reversible, and not a no-op like the last three: the backfill's whole
        // input is columns that still exist, so the rows it touched can be
        // identified and reset. Anything that was already known before this
        // migration is left alone.
        manager
            .get_connection()
            .execute_unprepared(
                r#"
                UPDATE public.videos v
                SET captions_available = NULL
                WHERE v.captions_available IS NOT NULL
                  AND NOT (v.captions_available AND (
                        EXISTS (SELECT 1 FROM public.video_transcript_documents d
                                WHERE d.video_id = v.id)
                     OR COALESCE(v.subtitle_availability -> 'manual_langs', '[]'::jsonb) <> '[]'::jsonb
                     OR COALESCE(v.subtitle_availability -> 'auto_langs',  '[]'::jsonb) <> '[]'::jsonb
                  ))
                  AND NOT (NOT v.captions_available
                       AND v.subtitle_availability IS NOT NULL
                       AND COALESCE(v.subtitle_availability -> 'manual_langs', '[]'::jsonb) = '[]'::jsonb
                       AND COALESCE(v.subtitle_availability -> 'auto_langs',  '[]'::jsonb) = '[]'::jsonb);
                "#,
            )
            .await?;
        Ok(())
    }
}