summaryrefslogtreecommitdiff
path: root/vendor/PicoDb/Database.php
blob: c3405f726ef0e1a590947942db97bc9e9684f48e (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php

namespace PicoDb;

class Database
{
    private $logs = array();
    private $pdo;


    public function __construct(array $settings)
    {
        if (! isset($settings['driver'])) {

            throw new \LogicException('You must define a database driver.');
        }

        switch ($settings['driver']) {

            case 'sqlite':
                require_once __DIR__.'/Drivers/Sqlite.php';
                $this->pdo = new Sqlite($settings['filename']);
                break;

            default:
                throw new \LogicException('This database driver is not supported.');
        }

        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    }


    public function setLogMessage($message)
    {
        $this->logs[] = $message;
    }


    public function getLogMessages()
    {
        return $this->logs;
    }


    public function getConnection()
    {
        return $this->pdo;
    }


    public function escapeIdentifier($value)
    {
        return $this->pdo->escapeIdentifier($value);
    }


    public function execute($sql, array $values = array())
    {
        try {

            $this->setLogMessage($sql);
            $this->setLogMessage(implode(', ', $values));

            $rq = $this->pdo->prepare($sql);
            $rq->execute($values);

            return $rq;
        }
        catch (\PDOException $e) {

            if ($this->pdo->inTransaction()) $this->pdo->rollback();
            $this->setLogMessage($e->getMessage());
            return false;
        }
    }


    public function startTransaction()
    {
        $this->pdo->beginTransaction();
    }


    public function closeTransaction()
    {
        $this->pdo->commit();
    }


    public function cancelTransaction()
    {
        $this->pdo->rollback();
    }


    public function table($table_name)
    {
        require_once __DIR__.'/Table.php';
        return new Table($this, $table_name);
    }


    public function schema()
    {
        require_once __DIR__.'/Schema.php';
        return new Schema($this);
    }
}