Subversion Repositories oidplus

Rev

Rev 1116 | Rev 1160 | 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
1086 daniel-mar 5
 * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
635 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
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
635 daniel-mar 21
 
1086 daniel-mar 22
// phpcs:disable PSR1.Files.SideEffects
23
\defined('INSIDE_OIDPLUS') or die;
24
// phpcs:enable PSR1.Files.SideEffects
25
 
635 daniel-mar 26
class OIDplusDatabaseConnectionPDO extends OIDplusDatabaseConnection {
1130 daniel-mar 27
        /**
28
         * @var mixed|null
29
         */
635 daniel-mar 30
        private $conn = null;
1130 daniel-mar 31
 
32
        /**
33
         * @var string|null
34
         */
635 daniel-mar 35
        private $last_error = null; // we need that because PDO divides prepared statement errors and normal query errors, but we have only one "error()" method
1130 daniel-mar 36
 
37
        /**
38
         * @var bool
39
         */
635 daniel-mar 40
        private $transactions_supported = false;
41
 
1116 daniel-mar 42
        /**
43
         * @param string $sql
44
         * @param array|null $prepared_args
45
         * @return OIDplusQueryResultPDO
46
         * @throws OIDplusException
47
         */
48
        public function doQuery(string $sql, array $prepared_args=null): OIDplusQueryResult {
635 daniel-mar 49
                $this->last_error = null;
50
                if (is_null($prepared_args)) {
51
                        $res = $this->conn->query($sql);
52
 
53
                        if ($res === false) {
54
                                $this->last_error = $this->conn->errorInfo()[2];
55
                                throw new OIDplusSQLException($sql, $this->error());
56
                        } else {
57
                                return new OIDplusQueryResultPDO($res);
58
                        }
59
                } else {
60
                        if (!is_array($prepared_args)) {
61
                                throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
62
                        }
63
 
64
                        foreach ($prepared_args as &$value) {
65
                                // We need to manually convert booleans into strings, because there is a
66
                                // 14 year old bug that hasn't been adressed by the PDO developers:
67
                                // https://bugs.php.net/bug.php?id=57157
68
                                if (is_bool($value)) {
69
                                        if ($this->slangDetectionDone) {
70
                                                $value = $this->getSlang()->getSQLBool($value);
71
                                        } else {
72
                                                // This works for everything except Microsoft Access (which needs -1 and 0)
73
                                                // Note: We are using '1' and '0' instead of 'true' and 'false' because MySQL converts boolean to tinyint(1)
74
                                                $value = $value ? '1' : '0';
75
                                        }
76
                                }
77
                        }
78
 
79
                        $ps = $this->conn->prepare($sql);
80
                        if (!$ps) {
81
                                $this->last_error = $this->conn->errorInfo()[2];
82
                                throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
83
                        }
84
 
85
                        if (!$ps->execute($prepared_args)) {
86
                                $this->last_error = $ps->errorInfo()[2];
87
                                throw new OIDplusSQLException($sql, $this->error());
88
                        }
89
                        return new OIDplusQueryResultPDO($ps);
90
                }
91
        }
92
 
1116 daniel-mar 93
        /**
94
         * @return int
95
         * @throws OIDplusException
96
         */
635 daniel-mar 97
        public function insert_id(): int {
98
                try {
99
                        $out = @($this->conn->lastInsertId());
100
                        if ($out === false) return parent::insert_id(); // fallback method that uses the SQL slang
101
                        return $out;
1050 daniel-mar 102
                } catch (\Exception $e) {
635 daniel-mar 103
                        return parent::insert_id(); // fallback method that uses the SQL slang
104
                }
105
        }
106
 
1116 daniel-mar 107
        /**
108
         * @return string
109
         */
635 daniel-mar 110
        public function error(): string {
111
                $err = $this->last_error;
112
                if ($err == null) $err = '';
113
                return $err;
114
        }
115
 
1116 daniel-mar 116
        /**
117
         * @return void
118
         * @throws OIDplusConfigInitializationException
119
         * @throws OIDplusException
120
         */
635 daniel-mar 121
        protected function doConnect()/*: void*/ {
122
                if (!class_exists('PDO')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','PDO'));
123
 
124
                try {
125
                        $options = [
1050 daniel-mar 126
                            \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_SILENT,
127
                            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
128
                            \PDO::ATTR_EMULATE_PREPARES   => true,
635 daniel-mar 129
                        ];
130
 
131
                        // Try connecting to the database
787 daniel-mar 132
                        $dsn      = OIDplus::baseConfig()->getValue('PDO_DSN',      'mysql:host=localhost;dbname=oidplus;charset=UTF8');
635 daniel-mar 133
                        $username = OIDplus::baseConfig()->getValue('PDO_USERNAME', 'root');
134
                        $password = OIDplus::baseConfig()->getValue('PDO_PASSWORD', '');
787 daniel-mar 135
 
136
                        if (stripos($dsn,"charset=") === false) $dsn = "$dsn;charset=UTF8";
137
 
1050 daniel-mar 138
                        $this->conn = new \PDO($dsn, $username, $password, $options);
139
                } catch (\PDOException $e) {
635 daniel-mar 140
                        $message = $e->getMessage();
863 daniel-mar 141
                        throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' '.$message));
635 daniel-mar 142
                }
143
 
144
                $this->last_error = null;
145
 
146
                try {
147
                        @$this->conn->exec("SET NAMES 'utf8'");
1050 daniel-mar 148
                } catch (\Exception $e) {
635 daniel-mar 149
                }
150
 
151
                // We check if the DBMS supports autocommit.
152
                // Attention: Check it after you have sent a query already, because Microsoft Access doesn't seem to allow
153
                // changing auto commit once a query was executed ("Attribute cannot be set now SQLState: S1011")
154
                // Note: For some weird reason we *DO* need to redirect the output to "$dummy", otherwise it won't work!
155
                $sql = "select name from ###config where 1=0";
156
                $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
157
                $dummy = $this->conn->query($sql);
158
                try {
159
                        $this->conn->beginTransaction();
160
                        $this->conn->rollBack();
161
                        $this->transactions_supported = true;
1050 daniel-mar 162
                } catch (\Exception $e) {
635 daniel-mar 163
                        $this->transactions_supported = false;
164
                }
165
        }
166
 
1116 daniel-mar 167
        /**
168
         * @return void
169
         */
635 daniel-mar 170
        protected function doDisconnect()/*: void*/ {
171
                $this->conn = null; // the connection will be closed by removing the reference
172
        }
173
 
1116 daniel-mar 174
        /**
175
         * @var bool
176
         */
635 daniel-mar 177
        private $intransaction = false;
178
 
1116 daniel-mar 179
        /**
180
         * @return bool
181
         */
635 daniel-mar 182
        public function transaction_supported(): bool {
183
                return $this->transactions_supported;
184
        }
185
 
1116 daniel-mar 186
        /**
187
         * @return int
188
         */
635 daniel-mar 189
        public function transaction_level(): int {
190
                if (!$this->transaction_supported()) {
191
                        // TODO?
192
                        return 0;
193
                }
194
                return $this->intransaction ? 1 : 0;
195
        }
196
 
1116 daniel-mar 197
        /**
198
         * @return void
199
         * @throws OIDplusException
200
         */
635 daniel-mar 201
        public function transaction_begin()/*: void*/ {
202
                if (!$this->transaction_supported()) {
203
                        // TODO?
204
                        return;
205
                }
206
                if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
207
                $this->conn->beginTransaction();
208
                $this->intransaction = true;
209
        }
210
 
1116 daniel-mar 211
        /**
212
         * @return void
213
         */
635 daniel-mar 214
        public function transaction_commit()/*: void*/ {
215
                if (!$this->transaction_supported()) {
216
                        // TODO?
217
                        return;
218
                }
219
                $this->conn->commit();
220
                $this->intransaction = false;
221
        }
222
 
1116 daniel-mar 223
        /**
224
         * @return void
225
         */
635 daniel-mar 226
        public function transaction_rollback()/*: void*/ {
227
                if (!$this->transaction_supported()) {
228
                        // TODO?
229
                        return;
230
                }
231
                $this->conn->rollBack();
232
                $this->intransaction = false;
233
        }
234
 
235
}