Subversion Repositories oidplus

Rev

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

Rev Author Line No. Line
295 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
511 daniel-mar 5
 * Copyright 2019 - 2021 Daniel Marschall, ViaThinkSoft
295 daniel-mar 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
 
511 daniel-mar 20
if (!defined('INSIDE_OIDPLUS')) die();
21
 
295 daniel-mar 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
502 daniel-mar 25
        private $transactions_supported = false;
295 daniel-mar 26
 
348 daniel-mar 27
        public static function getPlugin(): OIDplusDatabasePlugin {
28
                return new OIDplusDatabasePluginPDO();
29
        }
30
 
295 daniel-mar 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 {
502 daniel-mar 43
                        if (!is_array($prepared_args)) {
44
                                throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
45
                        }
46
 
295 daniel-mar 47
                        /*
502 daniel-mar 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 {
508 daniel-mar 60
                                                if ($this->slangDetectionDone) {
61
                                                        $replace = "'".$this->getSlang()->escapeString($arg)."'"; // TODO: types
62
                                                } else {
63
                                                        $replace = "'".str_replace("'", "''", $arg)."'"; // TODO: types
64
                                                }
502 daniel-mar 65
                                        }
66
                                        $pos = strpos($sql, $needle);
67
                                        if ($pos !== false) {
68
                                                $sql = substr_replace($sql, $replace, $pos, strlen($needle));
69
                                        }
295 daniel-mar 70
                                }
502 daniel-mar 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);
295 daniel-mar 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
502 daniel-mar 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
                                }
295 daniel-mar 94
                        }
95
 
96
                        $ps = $this->conn->prepare($sql);
97
                        if (!$ps) {
502 daniel-mar 98
                                $this->last_error = $this->conn->errorInfo()[2];
360 daniel-mar 99
                                throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
295 daniel-mar 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 {
502 daniel-mar 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
                }
295 daniel-mar 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*/ {
360 daniel-mar 127
                if (!class_exists('PDO')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','PDO'));
295 daniel-mar 128
 
129
                try {
130
                        $options = [
316 daniel-mar 131
                            PDO::ATTR_ERRMODE            => PDO::ERRMODE_SILENT,
295 daniel-mar 132
                            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
133
                            PDO::ATTR_EMULATE_PREPARES   => true,
134
                        ];
135
 
136
                        // Try connecting to the database
137
                        $dsn      = OIDplus::baseConfig()->getValue('PDO_DSN',      'mysql:host=localhost;dbname=oidplus;CHARSET=UTF8');
138
                        $username = OIDplus::baseConfig()->getValue('PDO_USERNAME', 'root');
139
                        $password = OIDplus::baseConfig()->getValue('PDO_PASSWORD', '');
140
                        $this->conn = new PDO($dsn, $username, $password, $options);
141
                } catch (PDOException $e) {
142
                        $message = $e->getMessage();
360 daniel-mar 143
                        throw new OIDplusConfigInitializationException(_L('Connection to the database failed!').' '.$message);
295 daniel-mar 144
                }
145
 
146
                $this->last_error = null;
147
 
502 daniel-mar 148
                try {
149
                        @$this->conn->exec("SET NAMES 'utf8'");
150
                } catch (Exception $e) {
151
                }
152
 
153
                // We check if the DBMS supports autocommit.
154
                // Attention: Check it after you have sent a query already, because Microsoft Access doesn't seem to allow
155
                // changing auto commit once a query was executed ("Attribute cannot be set now SQLState: S1011")
156
                // Note: For some weird reason we *DO* need to redirect the output to "$dummy", otherwise it won't work!
507 daniel-mar 157
                $sql = "select name from ###config where 1=0";
158
                $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
159
                $dummy = $this->conn->query($sql);
502 daniel-mar 160
                try {
161
                        $this->conn->beginTransaction();
162
                        $this->conn->rollBack();
163
                        $this->transactions_supported = true;
164
                } catch (Exception $e) {
165
                        $this->transactions_supported = false;
166
                }
295 daniel-mar 167
        }
168
 
169
        protected function doDisconnect()/*: void*/ {
170
                $this->conn = null; // the connection will be closed by removing the reference
171
        }
172
 
173
        private $intransaction = false;
174
 
175
        public function transaction_supported(): bool {
502 daniel-mar 176
                return $this->transactions_supported;
295 daniel-mar 177
        }
178
 
179
        public function transaction_level(): int {
502 daniel-mar 180
                if (!$this->transaction_supported()) {
181
                        // TODO?
182
                        return 0;
183
                }
295 daniel-mar 184
                return $this->intransaction ? 1 : 0;
185
        }
186
 
187
        public function transaction_begin()/*: void*/ {
502 daniel-mar 188
                if (!$this->transaction_supported()) {
189
                        // TODO?
190
                        return;
191
                }
360 daniel-mar 192
                if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
295 daniel-mar 193
                $this->conn->beginTransaction();
194
                $this->intransaction = true;
195
        }
196
 
197
        public function transaction_commit()/*: void*/ {
502 daniel-mar 198
                if (!$this->transaction_supported()) {
199
                        // TODO?
200
                        return;
201
                }
295 daniel-mar 202
                $this->conn->commit();
203
                $this->intransaction = false;
204
        }
205
 
206
        public function transaction_rollback()/*: void*/ {
502 daniel-mar 207
                if (!$this->transaction_supported()) {
208
                        // TODO?
209
                        return;
210
                }
295 daniel-mar 211
                $this->conn->rollBack();
212
                $this->intransaction = false;
213
        }
507 daniel-mar 214
 
489 daniel-mar 215
}