usenet-dl 0.3.0

Highly configurable Usenet download manager library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
//! Database lifecycle and schema migrations.

use crate::error::DatabaseError;
use crate::{Error, Result};
use sqlx::SqliteConnection;
use sqlx::sqlite::SqlitePool;
use std::path::Path;

use super::Database;

impl Database {
    /// Create a new database connection
    ///
    /// Creates the database file if it doesn't exist and runs migrations.
    pub async fn new(path: &Path) -> Result<Self> {
        // Create parent directory if it doesn't exist
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent).await.map_err(|e| {
                Error::Database(DatabaseError::ConnectionFailed(format!(
                    "Failed to create database directory: {}",
                    e
                )))
            })?;
        }

        // Connect to database with foreign key enforcement and WAL mode
        use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode};
        use std::str::FromStr;

        let options = SqliteConnectOptions::from_str(&format!("sqlite:{}", path.display()))
            .map_err(|e| {
                Error::Database(DatabaseError::ConnectionFailed(format!(
                    "Failed to parse database path: {}",
                    e
                )))
            })?
            .create_if_missing(true)
            .foreign_keys(true)
            .journal_mode(SqliteJournalMode::Wal);

        let pool = SqlitePool::connect_with(options).await.map_err(|e| {
            Error::Database(DatabaseError::ConnectionFailed(format!(
                "Failed to connect to database: {}",
                e
            )))
        })?;

        let db = Self { pool };

        // Run migrations
        db.run_migrations().await?;

        Ok(db)
    }

    /// Run database migrations
    async fn run_migrations(&self) -> Result<()> {
        let mut conn = self.pool.acquire().await.map_err(|e| {
            Error::Database(DatabaseError::ConnectionFailed(format!(
                "Failed to acquire connection: {}",
                e
            )))
        })?;

        // Create schema version table
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS schema_version (
                version INTEGER PRIMARY KEY,
                applied_at INTEGER NOT NULL
            )
            "#,
        )
        .execute(&mut *conn)
        .await
        .map_err(|e| {
            Error::Database(DatabaseError::MigrationFailed(format!(
                "Failed to create schema_version table: {}",
                e
            )))
        })?;

        // Check current version
        let current_version: Option<i64> =
            sqlx::query_scalar("SELECT MAX(version) FROM schema_version")
                .fetch_optional(&mut *conn)
                .await
                .map_err(|e| {
                    Error::Database(DatabaseError::QueryFailed(format!(
                        "Failed to query schema version: {}",
                        e
                    )))
                })?;

        let current_version = current_version.unwrap_or(0);

        // Apply migrations
        if current_version < 1 {
            Self::migrate_v1(&mut conn).await?;
        }
        if current_version < 2 {
            Self::migrate_v2(&mut conn).await?;
        }
        if current_version < 3 {
            Self::migrate_v3(&mut conn).await?;
        }
        if current_version < 4 {
            Self::migrate_v4(&mut conn).await?;
        }
        if current_version < 5 {
            Self::migrate_v5(&mut conn).await?;
        }
        if current_version < 6 {
            Self::migrate_v6(&mut conn).await?;
        }

        Ok(())
    }

    /// Migration v1: Create initial schema
    async fn migrate_v1(conn: &mut SqliteConnection) -> Result<()> {
        tracing::info!("Applying database migration v1");

        // Wrap migration in a transaction so partial failures don't leave the DB in a broken state
        sqlx::query("BEGIN")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to begin transaction: {}",
                    e
                )))
            })?;

        let result = async {
            Self::create_downloads_schema(conn).await?;
            Self::create_articles_schema(conn).await?;
            Self::create_passwords_table(conn).await?;
            Self::create_processed_nzbs_table(conn).await?;
            Self::create_history_schema(conn).await?;
            Self::record_migration(conn, 1).await?;
            Ok::<(), Error>(())
        }
        .await;

        match result {
            Ok(()) => {
                sqlx::query("COMMIT")
                    .execute(&mut *conn)
                    .await
                    .map_err(|e| {
                        Error::Database(DatabaseError::MigrationFailed(format!(
                            "Failed to commit migration v1: {}",
                            e
                        )))
                    })?;
            }
            Err(e) => {
                let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
                return Err(e);
            }
        }

        tracing::info!("Database migration v1 complete");
        Ok(())
    }

    /// Create downloads table and its indexes
    async fn create_downloads_schema(conn: &mut SqliteConnection) -> Result<()> {
        sqlx::query(
            r#"
            CREATE TABLE downloads (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                nzb_path TEXT NOT NULL,
                nzb_meta_name TEXT,
                nzb_hash TEXT,
                job_name TEXT,
                category TEXT,
                destination TEXT NOT NULL,
                post_process INTEGER NOT NULL,
                priority INTEGER NOT NULL DEFAULT 0,
                status INTEGER NOT NULL DEFAULT 0,
                progress REAL DEFAULT 0.0,
                speed_bps INTEGER DEFAULT 0,
                size_bytes INTEGER DEFAULT 0,
                downloaded_bytes INTEGER DEFAULT 0,
                error_message TEXT,
                created_at INTEGER NOT NULL,
                started_at INTEGER,
                completed_at INTEGER
            )
            "#,
        )
        .execute(&mut *conn)
        .await
        .map_err(|e| {
            Error::Database(DatabaseError::MigrationFailed(format!(
                "Failed to create downloads table: {}",
                e
            )))
        })?;

        // Create indexes
        sqlx::query("CREATE INDEX idx_downloads_status ON downloads(status)")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create index: {}",
                    e
                )))
            })?;

        sqlx::query(
            "CREATE INDEX idx_downloads_priority ON downloads(priority DESC, created_at ASC)",
        )
        .execute(&mut *conn)
        .await
        .map_err(|e| {
            Error::Database(DatabaseError::MigrationFailed(format!(
                "Failed to create index: {}",
                e
            )))
        })?;

        sqlx::query("CREATE INDEX idx_downloads_nzb_hash ON downloads(nzb_hash)")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create index: {}",
                    e
                )))
            })?;

        sqlx::query("CREATE INDEX idx_downloads_job_name ON downloads(job_name)")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create index: {}",
                    e
                )))
            })?;

        Ok(())
    }

    /// Create download_articles table and its indexes
    async fn create_articles_schema(conn: &mut SqliteConnection) -> Result<()> {
        sqlx::query(
            r#"
            CREATE TABLE download_articles (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                download_id INTEGER NOT NULL REFERENCES downloads(id) ON DELETE CASCADE,
                message_id TEXT NOT NULL,
                segment_number INTEGER NOT NULL,
                size_bytes INTEGER NOT NULL,
                status INTEGER NOT NULL DEFAULT 0,
                downloaded_at INTEGER,
                UNIQUE(download_id, message_id)
            )
            "#,
        )
        .execute(&mut *conn)
        .await
        .map_err(|e| {
            Error::Database(DatabaseError::MigrationFailed(format!(
                "Failed to create download_articles table: {}",
                e
            )))
        })?;

        // Create indexes
        sqlx::query("CREATE INDEX idx_articles_download ON download_articles(download_id)")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create index: {}",
                    e
                )))
            })?;

        sqlx::query("CREATE INDEX idx_articles_status ON download_articles(download_id, status)")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create index: {}",
                    e
                )))
            })?;

        Ok(())
    }

    /// Create passwords table
    async fn create_passwords_table(conn: &mut SqliteConnection) -> Result<()> {
        sqlx::query(
            r#"
            CREATE TABLE passwords (
                download_id INTEGER PRIMARY KEY REFERENCES downloads(id) ON DELETE CASCADE,
                correct_password TEXT NOT NULL
            )
            "#,
        )
        .execute(&mut *conn)
        .await
        .map_err(|e| {
            Error::Database(DatabaseError::MigrationFailed(format!(
                "Failed to create passwords table: {}",
                e
            )))
        })?;

        Ok(())
    }

    /// Create processed_nzbs table
    async fn create_processed_nzbs_table(conn: &mut SqliteConnection) -> Result<()> {
        sqlx::query(
            r#"
            CREATE TABLE processed_nzbs (
                path TEXT PRIMARY KEY,
                processed_at INTEGER NOT NULL
            )
            "#,
        )
        .execute(&mut *conn)
        .await
        .map_err(|e| {
            Error::Database(DatabaseError::MigrationFailed(format!(
                "Failed to create processed_nzbs table: {}",
                e
            )))
        })?;

        Ok(())
    }

    /// Create history table and its index
    async fn create_history_schema(conn: &mut SqliteConnection) -> Result<()> {
        sqlx::query(
            r#"
            CREATE TABLE history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                category TEXT,
                destination TEXT,
                status INTEGER NOT NULL,
                size_bytes INTEGER,
                download_time_secs INTEGER,
                completed_at INTEGER NOT NULL
            )
            "#,
        )
        .execute(&mut *conn)
        .await
        .map_err(|e| {
            Error::Database(DatabaseError::MigrationFailed(format!(
                "Failed to create history table: {}",
                e
            )))
        })?;

        // Create index
        sqlx::query("CREATE INDEX idx_history_completed ON history(completed_at DESC)")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create index: {}",
                    e
                )))
            })?;

        Ok(())
    }

    /// Record a migration version
    async fn record_migration(conn: &mut SqliteConnection, version: i32) -> Result<()> {
        let now = chrono::Utc::now().timestamp();
        sqlx::query("INSERT INTO schema_version (version, applied_at) VALUES (?, ?)")
            .bind(version)
            .bind(now)
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to record migration: {}",
                    e
                )))
            })?;

        Ok(())
    }

    /// Migration v2: Add runtime state table for shutdown tracking
    async fn migrate_v2(conn: &mut SqliteConnection) -> Result<()> {
        tracing::info!("Applying database migration v2");

        sqlx::query("BEGIN")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to begin transaction: {}",
                    e
                )))
            })?;

        let result = async {
            // Runtime state table for tracking clean/unclean shutdown
            sqlx::query(
                r#"
                CREATE TABLE IF NOT EXISTS runtime_state (
                    key TEXT PRIMARY KEY,
                    value TEXT NOT NULL,
                    updated_at INTEGER NOT NULL
                )
                "#,
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create runtime_state table: {}",
                    e
                )))
            })?;

            // Initialize shutdown state as unclean (will be set to clean on proper startup)
            let now = chrono::Utc::now().timestamp();
            sqlx::query(
                r#"
                INSERT INTO runtime_state (key, value, updated_at)
                VALUES ('clean_shutdown', 'false', ?)
                "#,
            )
            .bind(now)
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to initialize runtime_state: {}",
                    e
                )))
            })?;

            // Record migration
            Self::record_migration(conn, 2).await?;
            Ok::<(), Error>(())
        }
        .await;

        match result {
            Ok(()) => {
                sqlx::query("COMMIT")
                    .execute(&mut *conn)
                    .await
                    .map_err(|e| {
                        Error::Database(DatabaseError::MigrationFailed(format!(
                            "Failed to commit migration v2: {}",
                            e
                        )))
                    })?;
            }
            Err(e) => {
                let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
                return Err(e);
            }
        }

        tracing::info!("Database migration v2 complete");
        Ok(())
    }

    /// Migration v3: Add RSS feed tables
    async fn migrate_v3(conn: &mut SqliteConnection) -> Result<()> {
        tracing::info!("Applying database migration v3");

        sqlx::query("BEGIN")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to begin transaction: {}",
                    e
                )))
            })?;

        let result = async {
            // RSS feeds table
            sqlx::query(
                r#"
                CREATE TABLE IF NOT EXISTS rss_feeds (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    url TEXT NOT NULL,
                    check_interval_secs INTEGER NOT NULL DEFAULT 900,
                    category TEXT,
                    auto_download INTEGER NOT NULL DEFAULT 1,
                    priority INTEGER NOT NULL DEFAULT 0,
                    enabled INTEGER NOT NULL DEFAULT 1,
                    last_check INTEGER,
                    last_error TEXT,
                    created_at INTEGER NOT NULL
                )
                "#,
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create rss_feeds table: {}",
                    e
                )))
            })?;

            // RSS filters table (per feed)
            sqlx::query(
                r#"
                CREATE TABLE IF NOT EXISTS rss_filters (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    feed_id INTEGER NOT NULL REFERENCES rss_feeds(id) ON DELETE CASCADE,
                    name TEXT NOT NULL,
                    include_patterns TEXT,
                    exclude_patterns TEXT,
                    min_size INTEGER,
                    max_size INTEGER,
                    max_age_secs INTEGER
                )
                "#,
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create rss_filters table: {}",
                    e
                )))
            })?;

            // RSS seen items table (prevent re-downloading)
            sqlx::query(
                r#"
                CREATE TABLE IF NOT EXISTS rss_seen (
                    feed_id INTEGER NOT NULL REFERENCES rss_feeds(id) ON DELETE CASCADE,
                    guid TEXT NOT NULL,
                    seen_at INTEGER NOT NULL,
                    PRIMARY KEY (feed_id, guid)
                )
                "#,
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create rss_seen table: {}",
                    e
                )))
            })?;

            // Record migration
            Self::record_migration(conn, 3).await?;
            Ok::<(), Error>(())
        }
        .await;

        match result {
            Ok(()) => {
                sqlx::query("COMMIT")
                    .execute(&mut *conn)
                    .await
                    .map_err(|e| {
                        Error::Database(DatabaseError::MigrationFailed(format!(
                            "Failed to commit migration v3: {}",
                            e
                        )))
                    })?;
            }
            Err(e) => {
                let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
                return Err(e);
            }
        }

        tracing::info!("Database migration v3 complete");
        Ok(())
    }

    /// Migration v4: Add download_files table and file_index column to download_articles
    async fn migrate_v4(conn: &mut SqliteConnection) -> Result<()> {
        tracing::info!("Applying database migration v4");

        sqlx::query("BEGIN")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to begin transaction: {}",
                    e
                )))
            })?;

        let result = async {
            // File-level metadata table for NZB files
            sqlx::query(
                r#"
                CREATE TABLE download_files (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    download_id INTEGER NOT NULL REFERENCES downloads(id) ON DELETE CASCADE,
                    file_index INTEGER NOT NULL,
                    filename TEXT NOT NULL,
                    subject TEXT,
                    total_segments INTEGER NOT NULL,
                    UNIQUE(download_id, file_index)
                )
                "#,
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create download_files table: {}",
                    e
                )))
            })?;

            sqlx::query("CREATE INDEX idx_download_files_download ON download_files(download_id)")
                .execute(&mut *conn)
                .await
                .map_err(|e| {
                    Error::Database(DatabaseError::MigrationFailed(format!(
                        "Failed to create index: {}",
                        e
                    )))
                })?;

            // Add file_index column to existing download_articles table
            sqlx::query(
                "ALTER TABLE download_articles ADD COLUMN file_index INTEGER NOT NULL DEFAULT 0",
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to add file_index column: {}",
                    e
                )))
            })?;

            // Record migration
            Self::record_migration(conn, 4).await?;
            Ok::<(), Error>(())
        }
        .await;

        match result {
            Ok(()) => {
                sqlx::query("COMMIT")
                    .execute(&mut *conn)
                    .await
                    .map_err(|e| {
                        Error::Database(DatabaseError::MigrationFailed(format!(
                            "Failed to commit migration v4: {}",
                            e
                        )))
                    })?;
            }
            Err(e) => {
                let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
                return Err(e);
            }
        }

        tracing::info!("Database migration v4 complete");
        Ok(())
    }

    /// Migration v5: Add DirectUnpack support columns
    async fn migrate_v5(conn: &mut SqliteConnection) -> Result<()> {
        tracing::info!("Applying database migration v5");

        sqlx::query("BEGIN")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to begin transaction: {}",
                    e
                )))
            })?;

        let result = async {
            // Add direct_unpack_state to downloads table
            sqlx::query(
                "ALTER TABLE downloads ADD COLUMN direct_unpack_state INTEGER NOT NULL DEFAULT 0",
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to add direct_unpack_state column: {}",
                    e
                )))
            })?;

            // Add completed flag to download_files table
            sqlx::query(
                "ALTER TABLE download_files ADD COLUMN completed INTEGER NOT NULL DEFAULT 0",
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to add completed column: {}",
                    e
                )))
            })?;

            // Add original_filename to download_files table (for DirectRename)
            sqlx::query("ALTER TABLE download_files ADD COLUMN original_filename TEXT")
                .execute(&mut *conn)
                .await
                .map_err(|e| {
                    Error::Database(DatabaseError::MigrationFailed(format!(
                        "Failed to add original_filename column: {}",
                        e
                    )))
                })?;

            // Index for efficiently finding completed files per download
            sqlx::query(
                "CREATE INDEX idx_download_files_completed ON download_files(download_id, completed)",
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to create index: {}",
                    e
                )))
            })?;

            // Record migration
            Self::record_migration(conn, 5).await?;
            Ok::<(), Error>(())
        }
        .await;

        match result {
            Ok(()) => {
                sqlx::query("COMMIT")
                    .execute(&mut *conn)
                    .await
                    .map_err(|e| {
                        Error::Database(DatabaseError::MigrationFailed(format!(
                            "Failed to commit migration v5: {}",
                            e
                        )))
                    })?;
            }
            Err(e) => {
                let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
                return Err(e);
            }
        }

        tracing::info!("Database migration v5 complete");
        Ok(())
    }

    /// Migration v6: Add direct_unpack_extracted_count column
    async fn migrate_v6(conn: &mut SqliteConnection) -> Result<()> {
        tracing::info!("Applying database migration v6");

        sqlx::query("BEGIN")
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to begin transaction: {}",
                    e
                )))
            })?;

        let result = async {
            sqlx::query(
                "ALTER TABLE downloads ADD COLUMN direct_unpack_extracted_count INTEGER NOT NULL DEFAULT 0",
            )
            .execute(&mut *conn)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::MigrationFailed(format!(
                    "Failed to add direct_unpack_extracted_count column: {}",
                    e
                )))
            })?;

            Self::record_migration(conn, 6).await?;
            Ok::<(), Error>(())
        }
        .await;

        match result {
            Ok(()) => {
                sqlx::query("COMMIT")
                    .execute(&mut *conn)
                    .await
                    .map_err(|e| {
                        Error::Database(DatabaseError::MigrationFailed(format!(
                            "Failed to commit migration v6: {}",
                            e
                        )))
                    })?;
            }
            Err(e) => {
                let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
                return Err(e);
            }
        }

        tracing::info!("Database migration v6 complete");
        Ok(())
    }

    /// Close the database connection
    pub async fn close(self) {
        self.pool.close().await;
    }

    /// Get the underlying connection pool
    pub fn pool(&self) -> &SqlitePool {
        &self.pool
    }
}