summaryrefslogtreecommitdiff
path: root/vendor/PicoDb/Schema.php
blob: 2f52b84632a3e5d403abac31a04aa4a8a4b6eeaf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php

namespace PicoDb;

class Schema
{
    protected $db = null;


    public function __construct(Database $db)
    {
        $this->db = $db;
    }


    public function check($last_version = 1)
    {
        $current_version = $this->db->getConnection()->getSchemaVersion();

        if ($current_version < $last_version) {

            return $this->migrateTo($current_version, $last_version);
        }

        return true;
    }


    public function migrateTo($current_version, $next_version)
    {
        try {

            $this->db->startTransaction();

            for ($i = $current_version + 1; $i <= $next_version; $i++) {

                $function_name = '\Schema\version_'.$i;

                if (function_exists($function_name)) {

                    call_user_func($function_name, $this->db->getConnection());
                    $this->db->getConnection()->setSchemaVersion($i);
                }
                else {

                    throw new \LogicException('To execute a database migration, you need to create this function: "'.$function_name.'".');
                }
            }

            $this->db->closeTransaction();
        }
        catch (\PDOException $e) {

            $this->db->cancelTransaction();
            return false;
        }

        return true;
    }
}