Added simple database evolutions to ease future database changes

This commit is contained in:
Erik Thuning 2025-03-14 13:09:45 +01:00
parent 753f87d135
commit ee082de50a
2 changed files with 39 additions and 0 deletions

@ -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`);

@ -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;