| 1 | use rusqlite::{Connection, Transaction}; |
| 2 | |
| 3 | use crate::error::{Error, Result}; |
| 4 | use crate::search; |
| 5 | |
| 6 | struct Migration { |
| 7 | script: &'static str, |
| 8 | after: Option<fn(&Transaction<'_>) -> Result<()>>, |
| 9 | } |
| 10 | |
| 11 | const MIGRATIONS: &[Migration] = &[ |
| 12 | Migration { |
| 13 | script: include_str!("migrations/0001_initial.sql"), |
| 14 | after: None, |
| 15 | }, |
| 16 | Migration { |
| 17 | script: include_str!("migrations/0002_delta_and_meta.sql"), |
| 18 | after: None, |
| 19 | }, |
| 20 | Migration { |
| 21 | script: include_str!("migrations/0003_previews_avatars_folders.sql"), |
| 22 | after: None, |
| 23 | }, |
| 24 | Migration { |
| 25 | script: include_str!("migrations/0004_images_and_search.sql"), |
| 26 | after: Some(search::backfill), |
| 27 | }, |
| 28 | Migration { |
| 29 | script: include_str!("migrations/0005_team_layout.sql"), |
| 30 | after: None, |
| 31 | }, |
| 32 | Migration { |
| 33 | script: include_str!("migrations/0006_presence.sql"), |
| 34 | after: None, |
| 35 | }, |
| 36 | Migration { |
| 37 | script: include_str!("migrations/0007_sender_application.sql"), |
| 38 | after: None, |
| 39 | }, |
| 40 | Migration { |
| 41 | script: include_str!("migrations/0008_activity.sql"), |
| 42 | after: None, |
| 43 | }, |
| 44 | Migration { |
| 45 | script: include_str!("migrations/0009_muted.sql"), |
| 46 | after: None, |
| 47 | }, |
| 48 | ]; |
| 49 | |
| 50 | pub fn latest_version() -> i64 { |
| 51 | MIGRATIONS.len() as i64 |
| 52 | } |
| 53 | |
| 54 | pub fn migrate(connection: &mut Connection) -> Result<()> { |
| 55 | let found: i64 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?; |
| 56 | if found > latest_version() { |
| 57 | return Err(Error::SchemaTooNew { |
| 58 | found, |
| 59 | supported: latest_version(), |
| 60 | }); |
| 61 | } |
| 62 | for (index, migration) in MIGRATIONS.iter().enumerate().skip(found as usize) { |
| 63 | let transaction = connection.transaction()?; |
| 64 | transaction.execute_batch(migration.script)?; |
| 65 | if let Some(after) = migration.after { |
| 66 | after(&transaction)?; |
| 67 | } |
| 68 | transaction.pragma_update(None, "user_version", index as i64 + 1)?; |
| 69 | transaction.commit()?; |
| 70 | } |
| 71 | Ok(()) |
| 72 | } |