common.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. use crate::database::DatabaseExecutor;
  2. use crate::stmt::query;
  3. /// Migrates the migration generated by `build.rs`
  4. #[inline(always)]
  5. pub async fn migrate<C>(
  6. conn: &C,
  7. db_prefix: &str,
  8. migrations: &[(&str, &str, &str)],
  9. ) -> Result<(), cdk_common::database::Error>
  10. where
  11. C: DatabaseExecutor,
  12. {
  13. query(
  14. r#"
  15. CREATE TABLE IF NOT EXISTS migrations (
  16. name TEXT PRIMARY KEY,
  17. applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  18. )
  19. "#,
  20. )?
  21. .execute(conn)
  22. .await?;
  23. // Apply each migration if it hasn’t been applied yet
  24. for (prefix, name, sql) in migrations {
  25. if !prefix.is_empty() && *prefix != db_prefix {
  26. continue;
  27. }
  28. let is_missing = query("SELECT name FROM migrations WHERE name = :name")?
  29. .bind("name", name)
  30. .pluck(conn)
  31. .await?
  32. .is_none();
  33. if is_missing {
  34. query(sql)?.batch(conn).await?;
  35. query(r#"INSERT INTO migrations (name) VALUES (:name)"#)?
  36. .bind("name", name)
  37. .execute(conn)
  38. .await?;
  39. }
  40. }
  41. Ok(())
  42. }