ModelPdo.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  6. */
  7. /**
  8. * The Model_sql class represents the model for interacting with databases.
  9. */
  10. class Minz_ModelPdo {
  11. /**
  12. * Shares the connection to the database between all instances.
  13. */
  14. public static bool $usesSharedPdo = true;
  15. /**
  16. * If true, the connection to the database will be a dummy one. Useful for unit tests.
  17. */
  18. public static bool $dummyConnection = false;
  19. private static ?Minz_Pdo $sharedPdo = null;
  20. private static string $sharedCurrentUser = '';
  21. protected Minz_Pdo $pdo;
  22. protected ?string $current_user;
  23. /**
  24. * @throws Minz_ConfigurationNamespaceException
  25. * @throws Minz_PDOConnectionException
  26. * @throws PDOException
  27. */
  28. private function dbConnect(): void {
  29. $db = Minz_Configuration::get('system')->db;
  30. $driver_options = isset($db['pdo_options']) && is_array($db['pdo_options']) ? $db['pdo_options'] : [];
  31. $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
  32. $dbServer = parse_url('db://' . $db['host']);
  33. $dsn = '';
  34. $dsnParams = empty($db['connection_uri_params']) ? '' : (';' . $db['connection_uri_params']);
  35. switch ($db['type']) {
  36. case 'mysql':
  37. $dsn = 'mysql:';
  38. if (empty($dbServer['host'])) {
  39. $dsn .= 'unix_socket=' . $db['host'];
  40. } else {
  41. $dsn .= 'host=' . $dbServer['host'];
  42. }
  43. $dsn .= ';charset=utf8mb4';
  44. if (!empty($db['base'])) {
  45. $dsn .= ';dbname=' . $db['base'];
  46. }
  47. if (!empty($dbServer['port'])) {
  48. $dsn .= ';port=' . $dbServer['port'];
  49. }
  50. if (class_exists('Pdo\Mysql')) {
  51. assert(is_int(Pdo\Mysql::ATTR_INIT_COMMAND)); // For PHPStan with PHP 8.4+
  52. $driver_options[Pdo\Mysql::ATTR_INIT_COMMAND] = 'SET NAMES utf8mb4';
  53. } else {
  54. $driver_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8mb4'; // PHP < 8.4
  55. }
  56. $this->pdo = new Minz_PdoMysql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  57. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  58. break;
  59. case 'sqlite':
  60. if (in_array($this->current_user, [null, '', Minz_User::INTERNAL_USER], true)) {
  61. $dsn = 'sqlite::memory:';
  62. } else {
  63. $dsn = 'sqlite:' . DATA_PATH . '/users/' . $this->current_user . '/db.sqlite';
  64. }
  65. $this->pdo = new Minz_PdoSqlite($dsn . $dsnParams, null, null, $driver_options);
  66. $this->pdo->setPrefix('');
  67. break;
  68. case 'pgsql':
  69. $dsn = 'pgsql:host=' . (empty($dbServer['host']) ? $db['host'] : $dbServer['host']);
  70. if (!empty($db['base'])) {
  71. $dsn .= ';dbname=' . $db['base'];
  72. }
  73. if (!empty($dbServer['port'])) {
  74. $dsn .= ';port=' . $dbServer['port'];
  75. }
  76. $this->pdo = new Minz_PdoPgsql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  77. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  78. break;
  79. default:
  80. throw new Minz_PDOConnectionException('Invalid database type!', is_string($db['user'] ?? null) ? $db['user'] : '', Minz_Exception::ERROR);
  81. }
  82. if (self::$usesSharedPdo) {
  83. self::$sharedPdo = $this->pdo;
  84. }
  85. }
  86. /**
  87. * Create the connection to the database using the variables
  88. * HOST, BASE, USER and PASS variables defined in the configuration file
  89. * @throws Minz_ConfigurationException
  90. * @throws Minz_PDOConnectionException
  91. */
  92. public function __construct(?string $currentUser = null, ?Minz_Pdo $currentPdo = null) {
  93. if ($currentUser === null) {
  94. $currentUser = Minz_User::name();
  95. }
  96. if ($currentPdo !== null) {
  97. $this->pdo = $currentPdo;
  98. return;
  99. }
  100. if (self::$dummyConnection) {
  101. return;
  102. }
  103. if ($currentUser == null) {
  104. throw new Minz_PDOConnectionException('Current user must not be empty!', '', Minz_Exception::ERROR);
  105. }
  106. if (self::$usesSharedPdo && self::$sharedPdo !== null && $currentUser === self::$sharedCurrentUser) {
  107. $this->pdo = self::$sharedPdo;
  108. $this->current_user = self::$sharedCurrentUser;
  109. return;
  110. }
  111. $this->current_user = $currentUser;
  112. if (self::$usesSharedPdo) {
  113. self::$sharedCurrentUser = $currentUser;
  114. }
  115. $ex = null;
  116. //Attempt a few times to connect to database
  117. for ($attempt = 1; $attempt <= 5; $attempt++) {
  118. try {
  119. $this->dbConnect();
  120. return;
  121. } catch (PDOException $e) {
  122. $ex = $e;
  123. if (empty($e->errorInfo[0]) || $e->errorInfo[0] !== '08006') {
  124. //We are only interested in: SQLSTATE connection exception / connection failure
  125. break;
  126. }
  127. } catch (Exception $e) {
  128. $ex = $e;
  129. }
  130. sleep(2);
  131. }
  132. $db = Minz_Configuration::get('system')->db;
  133. throw new Minz_PDOConnectionException(
  134. $ex === null ? '' : $ex->getMessage(),
  135. $db['user'], Minz_Exception::ERROR
  136. );
  137. }
  138. public function beginTransaction(): void {
  139. $this->pdo->beginTransaction();
  140. }
  141. public function inTransaction(): bool {
  142. return $this->pdo->inTransaction();
  143. }
  144. public function commit(): void {
  145. $this->pdo->commit();
  146. }
  147. public function rollBack(): void {
  148. $this->pdo->rollBack();
  149. }
  150. public static function clean(): void {
  151. self::$sharedPdo = null;
  152. self::$sharedCurrentUser = '';
  153. }
  154. public function close(): void {
  155. if ($this->current_user === self::$sharedCurrentUser) {
  156. self::clean();
  157. }
  158. $this->current_user = '';
  159. unset($this->pdo);
  160. gc_collect_cycles();
  161. }
  162. /**
  163. * If $values is not empty, will use a prepared statement, otherwise will execute the query directly.
  164. * @param array<string,int|string|null> $values
  165. * @phpstan-return ($mode is PDO::FETCH_ASSOC ? list<array<string,int|string|null>>|null : list<int|string|null>|null)
  166. * @return list<array<string,int|string|null>>|list<int|string|null>|null
  167. */
  168. private function fetchAny(string $sql, array $values, int $mode, int $column = 0): ?array {
  169. $ok = true;
  170. $stm = false;
  171. if (empty($values)) {
  172. $stm = $this->pdo->query($sql);
  173. } else {
  174. $stm = $this->pdo->prepare($sql);
  175. $ok = $stm !== false;
  176. if ($ok) {
  177. foreach ($values as $name => $value) {
  178. if (is_int($value)) {
  179. $type = PDO::PARAM_INT;
  180. } elseif (is_string($value)) {
  181. $type = PDO::PARAM_STR;
  182. } elseif (is_null($value)) {
  183. $type = PDO::PARAM_NULL;
  184. } else {
  185. $ok = false;
  186. break;
  187. }
  188. if (!$stm->bindValue($name, $value, $type)) {
  189. $ok = false;
  190. break;
  191. }
  192. }
  193. }
  194. if ($ok && $stm !== false) {
  195. $stm = $stm->execute() ? $stm : false;
  196. }
  197. }
  198. if ($ok && $stm !== false) {
  199. switch ($mode) {
  200. case PDO::FETCH_COLUMN:
  201. $res = $stm->fetchAll(PDO::FETCH_COLUMN, $column);
  202. /** @var list<int|string|null> $res */
  203. break;
  204. case PDO::FETCH_ASSOC:
  205. default:
  206. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  207. /** @var list<array<string,int|string|null>> $res */
  208. break;
  209. }
  210. return $res;
  211. }
  212. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
  213. $calling = '';
  214. for ($i = 2; $i < 6; $i++) {
  215. if (empty($backtrace[$i]['function'])) {
  216. break;
  217. }
  218. $calling .= '|' . $backtrace[$i]['function'];
  219. }
  220. $calling = trim($calling, '|');
  221. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  222. Minz_Log::error('SQL error ' . $calling . ' ' . json_encode($info));
  223. return null;
  224. }
  225. /**
  226. * @param array<string,int|string|null> $values
  227. * @return list<array<string,bool|int|string|null>>|null
  228. */
  229. public function fetchAssoc(string $sql, array $values = []): ?array {
  230. return $this->fetchAny($sql, $values, PDO::FETCH_ASSOC);
  231. }
  232. /**
  233. * @param array<string,int|string|null> $values
  234. * @return list<int|string|null>|null
  235. */
  236. public function fetchColumn(string $sql, int $column, array $values = []): ?array {
  237. return $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, $column);
  238. }
  239. /**
  240. * For retrieving a single integer value with or without prepared statement such as `SELECT COUNT(*) FROM ...`
  241. * @param array<string,int|string|null> $values Array of values to bind. If not empty, will use a prepared statement
  242. */
  243. public function fetchInt(string $sql, array $values = []): ?int {
  244. $column = $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, column: 0);
  245. return is_numeric($column[0] ?? null) ? (int)$column[0] : null;
  246. }
  247. /**
  248. * For retrieving a single value with or without prepared statement such as `SELECT version()`
  249. * @param array<string,int|string|null> $values Array of values to bind. If not empty, will use a prepared statement
  250. */
  251. public function fetchString(string $sql, array $values = []): ?string {
  252. $column = $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, column: 0);
  253. return is_scalar($column[0] ?? null) ? (string)$column[0] : null;
  254. }
  255. #[Deprecated('Use `fetchString()` instead.')]
  256. public function fetchValue(string $sql): ?string {
  257. return $this->fetchString($sql);
  258. }
  259. }