ModelPdo.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. private static ?Minz_Pdo $sharedPdo = null;
  16. private static ?string $sharedCurrentUser;
  17. protected Minz_Pdo $pdo;
  18. protected ?string $current_user;
  19. /**
  20. * @throws Minz_ConfigurationNamespaceException
  21. * @throws Minz_PDOConnectionException
  22. * @throws PDOException
  23. */
  24. private function dbConnect(): void {
  25. $db = Minz_Configuration::get('system')->db;
  26. $driver_options = isset($db['pdo_options']) && is_array($db['pdo_options']) ? $db['pdo_options'] : [];
  27. $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
  28. $dbServer = parse_url('db://' . $db['host']);
  29. $dsn = '';
  30. $dsnParams = empty($db['connection_uri_params']) ? '' : (';' . $db['connection_uri_params']);
  31. switch ($db['type']) {
  32. case 'mysql':
  33. $dsn = 'mysql:';
  34. if (empty($dbServer['host'])) {
  35. $dsn .= 'unix_socket=' . $db['host'];
  36. } else {
  37. $dsn .= 'host=' . $dbServer['host'];
  38. }
  39. $dsn .= ';charset=utf8mb4';
  40. if (!empty($db['base'])) {
  41. $dsn .= ';dbname=' . $db['base'];
  42. }
  43. if (!empty($dbServer['port'])) {
  44. $dsn .= ';port=' . $dbServer['port'];
  45. }
  46. $driver_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8mb4';
  47. $this->pdo = new Minz_PdoMysql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  48. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  49. break;
  50. case 'sqlite':
  51. $dsn = 'sqlite:' . DATA_PATH . '/users/' . $this->current_user . '/db.sqlite';
  52. $this->pdo = new Minz_PdoSqlite($dsn . $dsnParams, null, null, $driver_options);
  53. $this->pdo->setPrefix('');
  54. break;
  55. case 'pgsql':
  56. $dsn = 'pgsql:host=' . (empty($dbServer['host']) ? $db['host'] : $dbServer['host']);
  57. if (!empty($db['base'])) {
  58. $dsn .= ';dbname=' . $db['base'];
  59. }
  60. if (!empty($dbServer['port'])) {
  61. $dsn .= ';port=' . $dbServer['port'];
  62. }
  63. $this->pdo = new Minz_PdoPgsql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  64. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  65. break;
  66. default:
  67. throw new Minz_PDOConnectionException(
  68. 'Invalid database type!',
  69. $db['user'], Minz_Exception::ERROR
  70. );
  71. }
  72. self::$sharedPdo = $this->pdo;
  73. }
  74. /**
  75. * Create the connection to the database using the variables
  76. * HOST, BASE, USER and PASS variables defined in the configuration file
  77. * @param string|null $currentUser
  78. * @param Minz_Pdo|null $currentPdo
  79. * @throws Minz_ConfigurationException
  80. * @throws Minz_PDOConnectionException
  81. */
  82. public function __construct(?string $currentUser = null, ?Minz_Pdo $currentPdo = null) {
  83. if ($currentUser === null) {
  84. $currentUser = Minz_User::name();
  85. }
  86. if ($currentPdo !== null) {
  87. $this->pdo = $currentPdo;
  88. return;
  89. }
  90. if ($currentUser == '') {
  91. throw new Minz_PDOConnectionException('Current user must not be empty!', '', Minz_Exception::ERROR);
  92. }
  93. if (self::$usesSharedPdo && self::$sharedPdo !== null && $currentUser === self::$sharedCurrentUser) {
  94. $this->pdo = self::$sharedPdo;
  95. $this->current_user = self::$sharedCurrentUser;
  96. return;
  97. }
  98. $this->current_user = $currentUser;
  99. self::$sharedCurrentUser = $currentUser;
  100. $ex = null;
  101. //Attempt a few times to connect to database
  102. for ($attempt = 1; $attempt <= 5; $attempt++) {
  103. try {
  104. $this->dbConnect();
  105. return;
  106. } catch (PDOException $e) {
  107. $ex = $e;
  108. if (empty($e->errorInfo[0]) || $e->errorInfo[0] !== '08006') {
  109. //We are only interested in: SQLSTATE connection exception / connection failure
  110. break;
  111. }
  112. } catch (Exception $e) {
  113. $ex = $e;
  114. }
  115. sleep(2);
  116. }
  117. $db = Minz_Configuration::get('system')->db;
  118. throw new Minz_PDOConnectionException(
  119. $ex === null ? '' : $ex->getMessage(),
  120. $db['user'], Minz_Exception::ERROR
  121. );
  122. }
  123. public function beginTransaction(): void {
  124. $this->pdo->beginTransaction();
  125. }
  126. public function inTransaction(): bool {
  127. return $this->pdo->inTransaction();
  128. }
  129. public function commit(): void {
  130. $this->pdo->commit();
  131. }
  132. public function rollBack(): void {
  133. $this->pdo->rollBack();
  134. }
  135. public static function clean(): void {
  136. self::$sharedPdo = null;
  137. self::$sharedCurrentUser = '';
  138. }
  139. /**
  140. * @param array<string,int|string|null> $values
  141. * @phpstan-return ($mode is PDO::FETCH_ASSOC ? array<array<string,int|string|null>>|null : array<int|string|null>|null)
  142. * @return array<array<string,int|string|null>>|array<int|string|null>|null
  143. */
  144. private function fetchAny(string $sql, array $values, int $mode, int $column = 0): ?array {
  145. $stm = $this->pdo->prepare($sql);
  146. $ok = $stm !== false;
  147. if ($ok && !empty($values)) {
  148. foreach ($values as $name => $value) {
  149. if (is_int($value)) {
  150. $type = PDO::PARAM_INT;
  151. } elseif (is_string($value)) {
  152. $type = PDO::PARAM_STR;
  153. } elseif (is_null($value)) {
  154. $type = PDO::PARAM_NULL;
  155. } else {
  156. $ok = false;
  157. break;
  158. }
  159. if (!$stm->bindValue($name, $value, $type)) {
  160. $ok = false;
  161. break;
  162. }
  163. }
  164. }
  165. if ($ok && $stm !== false && $stm->execute()) {
  166. switch ($mode) {
  167. case PDO::FETCH_COLUMN:
  168. $res = $stm->fetchAll(PDO::FETCH_COLUMN, $column);
  169. break;
  170. case PDO::FETCH_ASSOC:
  171. default:
  172. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  173. break;
  174. }
  175. if ($res !== false) {
  176. return $res;
  177. }
  178. }
  179. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
  180. $calling = '';
  181. for ($i = 2; $i < 6; $i++) {
  182. if (empty($backtrace[$i]['function'])) {
  183. break;
  184. }
  185. $calling .= '|' . $backtrace[$i]['function'];
  186. }
  187. $calling = trim($calling, '|');
  188. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  189. Minz_Log::error('SQL error ' . $calling . ' ' . json_encode($info));
  190. return null;
  191. }
  192. /**
  193. * @param array<string,int|string|null> $values
  194. * @return array<array<string,int|string|null>>|null
  195. */
  196. public function fetchAssoc(string $sql, array $values = []): ?array {
  197. return $this->fetchAny($sql, $values, PDO::FETCH_ASSOC);
  198. }
  199. /**
  200. * @param array<string,int|string|null> $values
  201. * @return array<int|string|null>|null
  202. */
  203. public function fetchColumn(string $sql, int $column, array $values = []): ?array {
  204. return $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, $column);
  205. }
  206. }