ModelPdo.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. $driver_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8mb4';
  51. $this->pdo = new Minz_PdoMysql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  52. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  53. break;
  54. case 'sqlite':
  55. if (in_array($this->current_user, [null, '', Minz_User::INTERNAL_USER], true)) {
  56. $dsn = 'sqlite::memory:';
  57. } else {
  58. $dsn = 'sqlite:' . DATA_PATH . '/users/' . $this->current_user . '/db.sqlite';
  59. }
  60. $this->pdo = new Minz_PdoSqlite($dsn . $dsnParams, null, null, $driver_options);
  61. $this->pdo->setPrefix('');
  62. break;
  63. case 'pgsql':
  64. $dsn = 'pgsql:host=' . (empty($dbServer['host']) ? $db['host'] : $dbServer['host']);
  65. if (!empty($db['base'])) {
  66. $dsn .= ';dbname=' . $db['base'];
  67. }
  68. if (!empty($dbServer['port'])) {
  69. $dsn .= ';port=' . $dbServer['port'];
  70. }
  71. $this->pdo = new Minz_PdoPgsql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  72. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  73. break;
  74. default:
  75. throw new Minz_PDOConnectionException(
  76. 'Invalid database type!',
  77. $db['user'], Minz_Exception::ERROR
  78. );
  79. }
  80. if (self::$usesSharedPdo) {
  81. self::$sharedPdo = $this->pdo;
  82. }
  83. }
  84. /**
  85. * Create the connection to the database using the variables
  86. * HOST, BASE, USER and PASS variables defined in the configuration file
  87. * @throws Minz_ConfigurationException
  88. * @throws Minz_PDOConnectionException
  89. */
  90. public function __construct(?string $currentUser = null, ?Minz_Pdo $currentPdo = null) {
  91. if ($currentUser === null) {
  92. $currentUser = Minz_User::name();
  93. }
  94. if ($currentPdo !== null) {
  95. $this->pdo = $currentPdo;
  96. return;
  97. }
  98. if (self::$dummyConnection) {
  99. return;
  100. }
  101. if ($currentUser == null) {
  102. throw new Minz_PDOConnectionException('Current user must not be empty!', '', Minz_Exception::ERROR);
  103. }
  104. if (self::$usesSharedPdo && self::$sharedPdo !== null && $currentUser === self::$sharedCurrentUser) {
  105. $this->pdo = self::$sharedPdo;
  106. $this->current_user = self::$sharedCurrentUser;
  107. return;
  108. }
  109. $this->current_user = $currentUser;
  110. if (self::$usesSharedPdo) {
  111. self::$sharedCurrentUser = $currentUser;
  112. }
  113. $ex = null;
  114. //Attempt a few times to connect to database
  115. for ($attempt = 1; $attempt <= 5; $attempt++) {
  116. try {
  117. $this->dbConnect();
  118. return;
  119. } catch (PDOException $e) {
  120. $ex = $e;
  121. if (empty($e->errorInfo[0]) || $e->errorInfo[0] !== '08006') {
  122. //We are only interested in: SQLSTATE connection exception / connection failure
  123. break;
  124. }
  125. } catch (Exception $e) {
  126. $ex = $e;
  127. }
  128. sleep(2);
  129. }
  130. $db = Minz_Configuration::get('system')->db;
  131. throw new Minz_PDOConnectionException(
  132. $ex === null ? '' : $ex->getMessage(),
  133. $db['user'], Minz_Exception::ERROR
  134. );
  135. }
  136. public function beginTransaction(): void {
  137. $this->pdo->beginTransaction();
  138. }
  139. public function inTransaction(): bool {
  140. return $this->pdo->inTransaction();
  141. }
  142. public function commit(): void {
  143. $this->pdo->commit();
  144. }
  145. public function rollBack(): void {
  146. $this->pdo->rollBack();
  147. }
  148. public static function clean(): void {
  149. self::$sharedPdo = null;
  150. self::$sharedCurrentUser = '';
  151. }
  152. public function close(): void {
  153. if ($this->current_user === self::$sharedCurrentUser) {
  154. self::clean();
  155. }
  156. $this->current_user = '';
  157. unset($this->pdo);
  158. gc_collect_cycles();
  159. }
  160. /**
  161. * @param array<string,int|string|null> $values
  162. * @phpstan-return ($mode is PDO::FETCH_ASSOC ? list<array<string,int|string|null>>|null : list<int|string|null>|null)
  163. * @return list<array<string,int|string|null>>|list<int|string|null>|null
  164. */
  165. private function fetchAny(string $sql, array $values, int $mode, int $column = 0): ?array {
  166. $stm = $this->pdo->prepare($sql);
  167. $ok = $stm !== false;
  168. if ($ok && !empty($values)) {
  169. foreach ($values as $name => $value) {
  170. if (is_int($value)) {
  171. $type = PDO::PARAM_INT;
  172. } elseif (is_string($value)) {
  173. $type = PDO::PARAM_STR;
  174. } elseif (is_null($value)) {
  175. $type = PDO::PARAM_NULL;
  176. } else {
  177. $ok = false;
  178. break;
  179. }
  180. if (!$stm->bindValue($name, $value, $type)) {
  181. $ok = false;
  182. break;
  183. }
  184. }
  185. }
  186. if ($ok && $stm !== false && $stm->execute()) {
  187. switch ($mode) {
  188. case PDO::FETCH_COLUMN:
  189. $res = $stm->fetchAll(PDO::FETCH_COLUMN, $column);
  190. /** @var list<int|string|null> $res */
  191. break;
  192. case PDO::FETCH_ASSOC:
  193. default:
  194. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  195. /** @var list<array<string,int|string|null>> $res */
  196. break;
  197. }
  198. return $res;
  199. }
  200. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
  201. $calling = '';
  202. for ($i = 2; $i < 6; $i++) {
  203. if (empty($backtrace[$i]['function'])) {
  204. break;
  205. }
  206. $calling .= '|' . $backtrace[$i]['function'];
  207. }
  208. $calling = trim($calling, '|');
  209. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  210. Minz_Log::error('SQL error ' . $calling . ' ' . json_encode($info));
  211. return null;
  212. }
  213. /**
  214. * @param array<string,int|string|null> $values
  215. * @return list<array<string,int|string|null>>|null
  216. */
  217. public function fetchAssoc(string $sql, array $values = []): ?array {
  218. return $this->fetchAny($sql, $values, PDO::FETCH_ASSOC);
  219. }
  220. /**
  221. * @param array<string,int|string|null> $values
  222. * @return list<int|string|null>|null
  223. */
  224. public function fetchColumn(string $sql, int $column, array $values = []): ?array {
  225. return $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, $column);
  226. }
  227. /** For retrieving a single value without prepared statement such as `SELECT version()` */
  228. public function fetchValue(string $sql): ?string {
  229. $stm = $this->pdo->query($sql);
  230. if ($stm === false) {
  231. Minz_Log::error('SQL error ' . json_encode($this->pdo->errorInfo()) . ' during ' . $sql);
  232. return null;
  233. }
  234. $columns = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  235. if ($columns === false) {
  236. Minz_Log::error('SQL error ' . json_encode($stm->errorInfo()) . ' during ' . $sql);
  237. return null;
  238. }
  239. return is_scalar($columns[0] ?? null) ? (string)$columns[0] : null;
  240. }
  241. }