xref: /webtrees/app/Services/MigrationService.php (revision e873f434551745f888937263ff89e80db3b0f785)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22use Fisharebest\Webtrees\DB;
23use Fisharebest\Webtrees\Schema\MigrationInterface;
24use Fisharebest\Webtrees\Schema\SeedDefaultResnTable;
25use Fisharebest\Webtrees\Schema\SeedGedcomTable;
26use Fisharebest\Webtrees\Schema\SeedUserTable;
27use Fisharebest\Webtrees\Site;
28use PDOException;
29
30/**
31 * Update the database schema.
32 */
33class MigrationService
34{
35    /**
36     * Run a series of scripts to bring the database schema up to date.
37     *
38     * @param string $namespace      Where to find our MigrationXXX classes
39     * @param string $schema_name    Which schema to update.
40     * @param int    $target_version Upgrade to this version
41     *
42     * @return bool  Were any updates applied
43     * @throws PDOException
44     */
45    public function updateSchema(string $namespace, string $schema_name, int $target_version): bool
46    {
47        try {
48            $current_version = (int) Site::getPreference($schema_name);
49        } catch (PDOException) {
50            // During initial installation, the site_preference table won’t exist.
51            $current_version = 0;
52        }
53
54        $updates_applied = false;
55
56        // Update the schema, one version at a time.
57        while ($current_version < $target_version) {
58            $class = $namespace . '\\Migration' . $current_version;
59            /** @var MigrationInterface $migration */
60            $migration = new $class();
61            $migration->upgrade();
62            $current_version++;
63            Site::setPreference($schema_name, (string) $current_version);
64            $updates_applied = true;
65        }
66
67        return $updates_applied;
68    }
69
70    /**
71     *  Write default data to the database.
72     *
73     * @return void
74     */
75    public function seedDatabase(): void
76    {
77        (new SeedUserTable())->run();
78        (new SeedGedcomTable())->run();
79        (new SeedDefaultResnTable())->run();
80    }
81}
82