]> git.mxchange.org Git - friendica.git/blob - tests/Util/Database/StaticDatabase.php
Fix paging on List and Public timelines honoring order type
[friendica.git] / tests / Util / Database / StaticDatabase.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Test\Util\Database;
23
24 use Friendica\Database\Database;
25 use Friendica\Database\DatabaseException;
26 use PDO;
27 use PDOException;
28
29 /**
30  * Overrides the Friendica database class for re-using the connection
31  * for different tests
32  *
33  * Overrides functionality to enforce one transaction per call (for nested transactions)
34  */
35 class StaticDatabase extends Database
36 {
37         /**
38          * @var ExtendedPDO
39          */
40         private static $staticConnection;
41
42         /** @var bool  */
43         private $_locked = false;
44
45         /**
46          * Override the behaviour of connect, due there is just one, static connection at all
47          *
48          * @return bool Success
49          */
50         public function connect(): bool
51         {
52                 if (!is_null($this->connection) && $this->connected()) {
53                         return true;
54                 }
55
56                 if (!isset(self::$staticConnection)) {
57                         self::statConnect($_SERVER);
58                 }
59
60                 $this->driver = 'pdo';
61                 $this->connection = self::$staticConnection;
62                 $this->connected = true;
63                 $this->emulate_prepares = false;
64
65                 return $this->connected;
66         }
67
68         /**
69          * Override the transaction since there are now hierachical transactions possible
70          *
71          * @return bool
72          */
73         public function transaction(): bool
74         {
75                 if (!$this->in_transaction && !$this->connection->beginTransaction()) {
76                         return false;
77                 }
78
79                 $this->in_transaction = true;
80                 return true;
81         }
82
83         /** Mock for locking tables */
84         public function lock($table): bool
85         {
86                 if ($this->_locked) {
87                         return false;
88                 }
89
90                 $this->in_transaction = true;
91                 $this->_locked = true;
92
93                 return true;
94         }
95
96         /** Mock for unlocking tables */
97         public function unlock(): bool
98         {
99                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
100                 $this->performCommit();
101
102                 $this->in_transaction = false;
103                 $this->_locked = false;
104
105                 return true;
106         }
107
108         /**
109          * Does a commit
110          *
111          * @return bool Was the command executed successfully?
112          */
113         public function commit(): bool
114         {
115                 if (!$this->performCommit()) {
116                         return false;
117                 }
118                 $this->in_transaction = false;
119                 return true;
120         }
121
122         /**
123          * Setup of the global, static connection
124          * Either through explicit calling or through implicit using the Database
125          *
126          * @param array $server $_SERVER variables
127          *
128          * @throws \Exception
129          */
130         public static function statConnect(array $server)
131         {
132                 // Init variables
133                 $db_host = $db_user = $db_data = $db_pw = '';
134
135                 // Use environment variables for mysql if they are set beforehand
136                 if (!empty($server['MYSQL_HOST'])
137                     && (!empty($server['MYSQL_USERNAME']) || !empty($server['MYSQL_USER']))
138                     && $server['MYSQL_PASSWORD'] !== false
139                     && !empty($server['MYSQL_DATABASE']))
140                 {
141                         $db_host = $server['MYSQL_HOST'];
142                         if (!empty($server['MYSQL_PORT'])) {
143                                 $db_host .= ':' . $server['MYSQL_PORT'];
144                         }
145
146                         if (!empty($server['MYSQL_USERNAME'])) {
147                                 $db_user = $server['MYSQL_USERNAME'];
148                         } else {
149                                 $db_user = $server['MYSQL_USER'];
150                         }
151                         $db_pw = (string) $server['MYSQL_PASSWORD'];
152                         $db_data = $server['MYSQL_DATABASE'];
153                 }
154
155                 if (empty($db_host) || empty($db_user) || empty($db_data)) {
156                         throw new DatabaseException('Either one of the following settings are missing: Host, User or Database', 999, 'CONNECT');
157                 }
158
159                 $port       = 0;
160                 $serveraddr = trim($db_host);
161                 $serverdata = explode(':', $serveraddr);
162                 $server     = $serverdata[0];
163                 if (count($serverdata) > 1) {
164                         $port = (int) trim($serverdata[1]);
165                 }
166                 $server  = trim($server);
167                 $user    = trim($db_user);
168                 $pass    = trim($db_pw);
169                 $db      = trim($db_data);
170
171                 if (!(strlen($server) && strlen($user) && strlen($db))) {
172                         return;
173                 }
174
175                 $connect = "mysql:host=" . $server . ";dbname=" . $db;
176
177                 if ($port > 0) {
178                         $connect .= ";port=" . $port;
179                 }
180
181                 try {
182                         self::$staticConnection = @new ExtendedPDO($connect, $user, $pass);
183                         self::$staticConnection->setAttribute(PDO::ATTR_AUTOCOMMIT,0);
184                 } catch (PDOException $e) {
185                         /*
186                          * @TODO Try to find a way to log this exception as it contains valueable information
187                          * @nupplaphil@github.com comment:
188                          *
189                          * There is no easy possibility to add a logger here, that's why
190                          * there isn't any yet and instead a placeholder.. This execution
191                          * point is a critical state during a testrun, and tbh I'd like to
192                          * leave here no further logic (yet) because I spent hours debugging
193                          * cases, where transactions weren't fully closed and
194                          * strange/unpredictable errors occur (sometimes -mainly during
195                          * debugging other errors :) ...)
196                          */
197                 }
198         }
199
200         /**
201          * @return ExtendedPDO The global, static connection
202          */
203         public static function getGlobConnection()
204         {
205                 return self::$staticConnection;
206         }
207
208         /**
209          * Perform a global rollback for every nested transaction of the static connection
210          */
211         public static function statRollback()
212         {
213                 if (isset(self::$staticConnection)) {
214                         while (self::$staticConnection->getTransactionDepth() > 0) {
215                                 self::$staticConnection->rollBack();
216                         }
217                 }
218         }
219 }