aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJakob Stendahl <jakob.stendahl@outlook.com>2022-02-14 21:18:15 +0100
committerJakob Stendahl <jakob.stendahl@outlook.com>2022-02-14 21:18:15 +0100
commitfa01748d66089b8b2c33db3973f14b678361f739 (patch)
treeffb21d803c0fc2c4ad4819fdc82e34a75dabee07
parent2096790f3904371c9ff6090f1ff846593c7df9c4 (diff)
downloadRSS-watcher-fa01748d66089b8b2c33db3973f14b678361f739.tar.gz
RSS-watcher-fa01748d66089b8b2c33db3973f14b678361f739.zip
:card_file_box: Make migration pattern for database
-rw-r--r--src/database.rs61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/database.rs b/src/database.rs
index 21699e2..67157ae 100644
--- a/src/database.rs
+++ b/src/database.rs
@@ -95,6 +95,49 @@ fn table_create(conn: &mut Conn) {
}
/**
+ * Select the row in the table describing the database version.
+ */
+fn get_db_version(conn: &mut Conn) -> i64 {
+ let q = "SELECT `last_fetch` from `rss-watcher-feeds` WHERE `id`=0 AND `url` LIKE 'version'";
+ let res: Result<Option<i64>> = conn.query_first(q);
+ if let Err(x) = res {
+ error!("Could not get current version from database ({:#?})...", x);
+ process::exit(1);
+ }
+ let res_res = res.unwrap();
+ if let None = res_res {
+ error!("Row with id=0 and url='version' does not exist, something is wrong!");
+ error!("Please fix your database manually!");
+ process::exit(1);
+ }
+ return res_res.unwrap();
+}
+
+/**
+ * Run migrations v2.
+ */
+fn run_migrations_v2(tx: &mut Transaction, version: i64) {
+ if version < 2 {
+ warn!("Running migrations to v2");
+ let mut q;
+ q = "ALTER TABLE `rss_watcher`.`rss-watcher-feeds` \
+ CHANGE COLUMN `title` `title` VARCHAR(255) NOT NULL DEFAULT '{{title}}: {{entry.title}}' , \
+ CHANGE COLUMN `message` `message` VARCHAR(255) NOT NULL DEFAULT '{{entry.summary}}';";
+
+ if let Err(x) = tx.query_drop(q) {
+ error!("Could not run database migration to v2...! ({:#?}", x);
+ process::exit(1);
+ }
+
+ q = "UPDATE `rss-watcher-feeds` SET `last_fetch`=2 WHERE `id`=0";
+ if let Err(x) = tx.query_drop(q) {
+ error!("Could not run database migration to v2...! ({:#?}", x);
+ process::exit(1);
+ }
+ }
+}
+
+/**
* Bootstrap the database, this will make sure tables exists,
* create them if not and run migrations if nececarry.
*/
@@ -112,6 +155,24 @@ pub fn bootstrap() {
table_create(&mut conn);
}
+ let version = get_db_version(&mut conn);
+ if version < 2 {
+ let res_tx = conn.start_transaction(TxOpts::default());
+ if let Err(x) = res_tx {
+ error!("Could not create transaction for updating last fetch time! {:#?}", x);
+ return;
+ }
+ let mut tx = res_tx.unwrap();
+
+ run_migrations_v2(&mut tx, version);
+
+ if let Err(x) = tx.commit() {
+ warn!("Could not commit update! ({:#?}", x);
+ }
+ } else {
+ info!("Database is up to date, no migrations to run.");
+ }
+
info!("Database should now be bootstrapped");
info!("We are assuming that the table has the correct columns");
info!("If not, we are going to get sql errors");