Subversion Repositories oidplus

Rev

Rev 635 | Rev 789 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
635 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
5
 * Copyright 2019 - 2021 Daniel Marschall, ViaThinkSoft
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
 
20
if (!defined('INSIDE_OIDPLUS')) die();
21
 
22
class OIDplusDatabaseConnectionPDO extends OIDplusDatabaseConnection {
23
        private $conn = null;
24
        private $last_error = null; // we need that because PDO divides prepared statement errors and normal query errors, but we have only one "error()" method
25
        private $transactions_supported = false;
26
 
27
        public static function getPlugin(): OIDplusDatabasePlugin {
28
                return new OIDplusDatabasePluginPDO();
29
        }
30
 
31
        public function doQuery(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult {
32
                $this->last_error = null;
33
                if (is_null($prepared_args)) {
34
                        $res = $this->conn->query($sql);
35
 
36
                        if ($res === false) {
37
                                $this->last_error = $this->conn->errorInfo()[2];
38
                                throw new OIDplusSQLException($sql, $this->error());
39
                        } else {
40
                                return new OIDplusQueryResultPDO($res);
41
                        }
42
                } else {
43
                        if (!is_array($prepared_args)) {
44
                                throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
45
                        }
46
 
47
                        /*
48
                        // Not required because PDO can emulate prepared statements by itself
49
                        if ($this->forcePrepareEmulation()) {
50
                                $sql = str_replace('?', chr(1), $sql);
51
                                foreach ($prepared_args as $arg) {
52
                                        $needle = chr(1);
53
                                        if (is_bool($arg)) {
54
                                                if ($this->slangDetectionDone) {
55
                                                        $replace = $this->getSlang()->getSQLBool($arg);
56
                                                } else {
57
                                                        $replace = $arg ? '1' : '0';
58
                                                }
59
                                        } else {
60
                                                if ($this->slangDetectionDone) {
61
                                                        $replace = "'".$this->getSlang()->escapeString($arg)."'"; // TODO: types
62
                                                } else {
63
                                                        $replace = "'".str_replace("'", "''", $arg)."'"; // TODO: types
64
                                                }
65
                                        }
66
                                        $pos = strpos($sql, $needle);
67
                                        if ($pos !== false) {
68
                                                $sql = substr_replace($sql, $replace, $pos, strlen($needle));
69
                                        }
70
                                }
71
                                $sql = str_replace(chr(1), '?', $sql);
72
                                $ps = $this->conn->query($sql);
73
                                if (!$ps) {
74
                                        $this->last_error = $this->error();
75
                                        throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
76
                                }
77
                                return new OIDplusQueryResultPDO($ps);
78
                        }
79
                        */
80
 
81
                        foreach ($prepared_args as &$value) {
82
                                // We need to manually convert booleans into strings, because there is a
83
                                // 14 year old bug that hasn't been adressed by the PDO developers:
84
                                // https://bugs.php.net/bug.php?id=57157
85
                                if (is_bool($value)) {
86
                                        if ($this->slangDetectionDone) {
87
                                                $value = $this->getSlang()->getSQLBool($value);
88
                                        } else {
89
                                                // This works for everything except Microsoft Access (which needs -1 and 0)
90
                                                // Note: We are using '1' and '0' instead of 'true' and 'false' because MySQL converts boolean to tinyint(1)
91
                                                $value = $value ? '1' : '0';
92
                                        }
93
                                }
94
                        }
95
 
96
                        $ps = $this->conn->prepare($sql);
97
                        if (!$ps) {
98
                                $this->last_error = $this->conn->errorInfo()[2];
99
                                throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
100
                        }
101
 
102
                        if (!$ps->execute($prepared_args)) {
103
                                $this->last_error = $ps->errorInfo()[2];
104
                                throw new OIDplusSQLException($sql, $this->error());
105
                        }
106
                        return new OIDplusQueryResultPDO($ps);
107
                }
108
        }
109
 
110
        public function insert_id(): int {
111
                try {
112
                        $out = @($this->conn->lastInsertId());
113
                        if ($out === false) return parent::insert_id(); // fallback method that uses the SQL slang
114
                        return $out;
115
                } catch (Exception $e) {
116
                        return parent::insert_id(); // fallback method that uses the SQL slang
117
                }
118
        }
119
 
120
        public function error(): string {
121
                $err = $this->last_error;
122
                if ($err == null) $err = '';
123
                return $err;
124
        }
125
 
126
        protected function doConnect()/*: void*/ {
127
                if (!class_exists('PDO')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','PDO'));
128
 
129
                try {
130
                        $options = [
131
                            PDO::ATTR_ERRMODE            => PDO::ERRMODE_SILENT,
132
                            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
133
                            PDO::ATTR_EMULATE_PREPARES   => true,
134
                        ];
135
 
136
                        // Try connecting to the database
787 daniel-mar 137
                        $dsn      = OIDplus::baseConfig()->getValue('PDO_DSN',      'mysql:host=localhost;dbname=oidplus;charset=UTF8');
635 daniel-mar 138
                        $username = OIDplus::baseConfig()->getValue('PDO_USERNAME', 'root');
139
                        $password = OIDplus::baseConfig()->getValue('PDO_PASSWORD', '');
787 daniel-mar 140
 
141
                        if (stripos($dsn,"charset=") === false) $dsn = "$dsn;charset=UTF8";
142
 
635 daniel-mar 143
                        $this->conn = new PDO($dsn, $username, $password, $options);
144
                } catch (PDOException $e) {
145
                        $message = $e->getMessage();
146
                        throw new OIDplusConfigInitializationException(_L('Connection to the database failed!').' '.$message);
147
                }
148
 
149
                $this->last_error = null;
150
 
151
                try {
152
                        @$this->conn->exec("SET NAMES 'utf8'");
153
                } catch (Exception $e) {
154
                }
155
 
156
                // We check if the DBMS supports autocommit.
157
                // Attention: Check it after you have sent a query already, because Microsoft Access doesn't seem to allow
158
                // changing auto commit once a query was executed ("Attribute cannot be set now SQLState: S1011")
159
                // Note: For some weird reason we *DO* need to redirect the output to "$dummy", otherwise it won't work!
160
                $sql = "select name from ###config where 1=0";
161
                $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
162
                $dummy = $this->conn->query($sql);
163
                try {
164
                        $this->conn->beginTransaction();
165
                        $this->conn->rollBack();
166
                        $this->transactions_supported = true;
167
                } catch (Exception $e) {
168
                        $this->transactions_supported = false;
169
                }
170
        }
171
 
172
        protected function doDisconnect()/*: void*/ {
173
                $this->conn = null; // the connection will be closed by removing the reference
174
        }
175
 
176
        private $intransaction = false;
177
 
178
        public function transaction_supported(): bool {
179
                return $this->transactions_supported;
180
        }
181
 
182
        public function transaction_level(): int {
183
                if (!$this->transaction_supported()) {
184
                        // TODO?
185
                        return 0;
186
                }
187
                return $this->intransaction ? 1 : 0;
188
        }
189
 
190
        public function transaction_begin()/*: void*/ {
191
                if (!$this->transaction_supported()) {
192
                        // TODO?
193
                        return;
194
                }
195
                if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
196
                $this->conn->beginTransaction();
197
                $this->intransaction = true;
198
        }
199
 
200
        public function transaction_commit()/*: void*/ {
201
                if (!$this->transaction_supported()) {
202
                        // TODO?
203
                        return;
204
                }
205
                $this->conn->commit();
206
                $this->intransaction = false;
207
        }
208
 
209
        public function transaction_rollback()/*: void*/ {
210
                if (!$this->transaction_supported()) {
211
                        // TODO?
212
                        return;
213
                }
214
                $this->conn->rollBack();
215
                $this->intransaction = false;
216
        }
217
 
218
}