Subversion Repositories oidplus

Rev

Rev 1116 | Rev 1159 | 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 OIDplusDatabaseConnectionPgSql 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 array
34
         */
635 daniel-mar 35
        private $already_prepared = array();
1130 daniel-mar 36
 
37
        /**
38
         * @var string|null
39
         */
635 daniel-mar 40
        private $last_error = null; // do the same like MySQL+PDO, just to be equal in the behavior
41
 
1116 daniel-mar 42
        /**
43
         * @param string $sql
44
         * @param array|null $prepared_args
45
         * @return OIDplusQueryResultPgSql
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 = @pg_query($this->conn, $sql);
52
 
53
                        if ($res === false) {
54
                                $this->last_error = pg_last_error($this->conn);
55
                                throw new OIDplusSQLException($sql, $this->error());
56
                        } else {
57
                                return new OIDplusQueryResultPgSql($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
                        // convert ? ? ? to $1 $2 $3
65
                        $sql = preg_replace_callback('@\\?@', function($found) {
66
                                static $i = 0;
67
                                $i++;
68
                                return '$'.$i;
786 daniel-mar 69
                        }, $sql, count($prepared_args));
635 daniel-mar 70
 
71
                        $prepare_name = 'OIDplus_ps_'.sha1($sql);
72
                        if (!in_array($prepare_name, $this->already_prepared)) {
73
                                $res = @pg_prepare($this->conn, $prepare_name, $sql);
74
                                if ($res === false) {
75
                                        $this->last_error = pg_last_error($this->conn);
76
                                        throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
77
                                }
78
                                $this->already_prepared[] = $prepare_name;
79
                        }
80
 
81
                        foreach ($prepared_args as &$value) {
82
                                if (is_bool($value)) $value = $value ? '1' : '0';
83
                        }
84
 
85
                        $ps = pg_execute($this->conn, $prepare_name, $prepared_args);
86
                        if ($ps === false) {
87
                                $this->last_error = pg_last_error($this->conn);
88
                                throw new OIDplusSQLException($sql, $this->error());
89
                        }
90
                        return new OIDplusQueryResultPgSql($ps);
91
                }
92
        }
93
 
1116 daniel-mar 94
        /**
95
         * @return int
96
         */
635 daniel-mar 97
        public function insert_id(): int {
98
                try {
99
                        return (int)$this->query('select lastval() as id')->fetch_object()->id;
1050 daniel-mar 100
                } catch (\Exception $e) {
635 daniel-mar 101
                        return 0;
102
                }
103
        }
104
 
1116 daniel-mar 105
        /**
106
         * @return string
107
         */
635 daniel-mar 108
        public function error(): string {
109
                $err = $this->last_error;
110
                if ($err == null) $err = '';
111
                return $err;
112
        }
113
 
1116 daniel-mar 114
        /**
115
         * @return void
116
         * @throws OIDplusConfigInitializationException
117
         * @throws OIDplusException
118
         */
635 daniel-mar 119
        protected function doConnect()/*: void*/ {
120
                if (!function_exists('pg_connect')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','PostgreSQL'));
121
 
122
                // Try connecting to the database
123
                ob_start();
124
                $err = '';
125
                try {
126
                        $host     = OIDplus::baseConfig()->getValue('PGSQL_HOST',     'localhost:5432');
127
                        $username = OIDplus::baseConfig()->getValue('PGSQL_USERNAME', 'postgres');
128
                        $password = OIDplus::baseConfig()->getValue('PGSQL_PASSWORD', '');
129
                        $database = OIDplus::baseConfig()->getValue('PGSQL_DATABASE', 'oidplus');
814 daniel-mar 130
                        $socket   = OIDplus::baseConfig()->getValue('PGSQL_SOCKET',   '');
131
                        if ($socket != '') {
132
                                $hostname = $socket;
133
                                $port = '';
134
                        } else {
135
                                list($hostname, $port) = explode(':', "$host:5432");
136
                        }
137
 
138
                        $connection_string = array();
139
                        if ($hostname != '') $connection_string[] = "host=$hostname";
140
                        if ($username != '') $connection_string[] = "user=$username";
141
                        if ($password != '') $connection_string[] = "password=$password";
142
                        if ($port     != '') $connection_string[] = "port=$port";
143
                        if ($database != '') $connection_string[] = "dbname=$database";
144
 
635 daniel-mar 145
                        // We need to use PGSQL_CONNECT_FORCE_NEW because we require two connectoins (for isolated log message queries)
814 daniel-mar 146
                        $this->conn = pg_connect(implode(' ', $connection_string), PGSQL_CONNECT_FORCE_NEW);
635 daniel-mar 147
                } finally {
148
                        # TODO: this does not seem to work?! (at least not for CLI)
149
                        $err = ob_get_contents();
150
                        ob_end_clean();
151
                }
152
 
153
                if (!$this->conn) {
863 daniel-mar 154
                        throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' ' . strip_tags($err)));
635 daniel-mar 155
                }
156
 
157
                $this->already_prepared = array();
158
                $this->last_error = null;
159
 
160
                try {
161
                        $this->query("SET NAMES 'utf8'");
1050 daniel-mar 162
                } catch (\Exception $e) {
635 daniel-mar 163
                }
164
        }
165
 
1116 daniel-mar 166
        /**
167
         * @return void
168
         */
635 daniel-mar 169
        protected function doDisconnect()/*: void*/ {
170
                $this->already_prepared = array();
171
                if (!is_null($this->conn)) {
172
                        pg_close($this->conn);
173
                        $this->conn = null;
174
                }
175
        }
176
 
1116 daniel-mar 177
        /**
178
         * @var bool
179
         */
635 daniel-mar 180
        private $intransaction = false;
181
 
1116 daniel-mar 182
        /**
183
         * @return bool
184
         */
635 daniel-mar 185
        public function transaction_supported(): bool {
186
                return true;
187
        }
188
 
1116 daniel-mar 189
        /**
190
         * @return int
191
         */
635 daniel-mar 192
        public function transaction_level(): int {
193
                return $this->intransaction ? 1 : 0;
194
        }
195
 
1116 daniel-mar 196
        /**
197
         * @return void
198
         * @throws OIDplusException
199
         */
635 daniel-mar 200
        public function transaction_begin()/*: void*/ {
201
                if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
202
                $this->query('begin transaction');
203
                $this->intransaction = true;
204
        }
205
 
1116 daniel-mar 206
        /**
207
         * @return void
208
         * @throws OIDplusException
209
         */
635 daniel-mar 210
        public function transaction_commit()/*: void*/ {
211
                $this->query('commit');
212
                $this->intransaction = false;
213
        }
214
 
1116 daniel-mar 215
        /**
216
         * @return void
217
         * @throws OIDplusException
218
         */
635 daniel-mar 219
        public function transaction_rollback()/*: void*/ {
220
                $this->query('rollback');
221
                $this->intransaction = false;
222
        }
223
 
1116 daniel-mar 224
        /**
225
         * @return string
226
         */
635 daniel-mar 227
        public function sqlDate(): string {
228
                return 'now()';
229
        }
230
 
1116 daniel-mar 231
        /**
232
         * @param bool $mustExist
233
         * @return OIDplusSqlSlangPlugin|null
234
         * @throws OIDplusConfigInitializationException
235
         */
635 daniel-mar 236
        protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
237
                $slang = OIDplus::getSqlSlangPlugin('pgsql');
238
                if (is_null($slang)) {
239
                        throw new OIDplusConfigInitializationException(_L('SQL-Slang plugin "%1" is missing. Please check if it exists in the directory "plugin/sqlSlang". If it is not existing, please recover it from an SVN snapshot or OIDplus TAR.GZ file.','pgsql'));
240
                }
241
                return $slang;
242
        }
243
}