From ee082de50a61a474b8d82ffb24409f584e5d7dd1 Mon Sep 17 00:00:00 2001 From: Erik Thuning <boooink@gmail.com> Date: Fri, 14 Mar 2025 13:09:45 +0100 Subject: [PATCH] Added simple database evolutions to ease future database changes --- evolutions/001-event-initiator.sql | 3 +++ include/functions.php | 36 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 evolutions/001-event-initiator.sql diff --git a/evolutions/001-event-initiator.sql b/evolutions/001-event-initiator.sql new file mode 100644 index 0000000..086b474 --- /dev/null +++ b/evolutions/001-event-initiator.sql @@ -0,0 +1,3 @@ +alter table `event` add column `initiator` bigint(20); +alter table `event` add constraint `e_f_initiator` + foreign key(`initiator`) references `user`(`id`); diff --git a/include/functions.php b/include/functions.php index 727da89..64ea49c 100644 --- a/include/functions.php +++ b/include/functions.php @@ -312,6 +312,42 @@ if($db->connect_errno) { $error = 'Failed to connect to db. The error was: '.$db->connect_error; throw new Exception($error); } +evolve_db(); + +function evolve_db() { + global $db; + + $init = prepare(<<<SQL + create table if not exists `evolutions` + (`filename` varchar(64) not null, + primary key(`filename`), + `apply_date` bigint(20) not null, + `index` bigint(20) not null auto_increment, + key(`index`)) + SQL); + execute($init); + + $applied = prepare('select `filename`, `index` from `evolutions`'); + execute($applied); + $applied_files = array(); + foreach(result_list($applied) as $row) { + $applied_files[$row['filename']] = $row['index']; + } + + begin_trans(); + foreach(glob("./evolutions/*.sql") as $path) { + $filename = basename($path); + if(!array_key_exists($filename, $applied_files)) { + $db->multi_query(file_get_contents($path)); + $save = prepare('insert into `evolutions` + (`filename`, `apply_date`) + values (?, ?)'); + bind($save, 'si', $filename, time()); + execute($save); + } + } + commit_trans(); +} function prepare($statement) { global $db;