ModelPdo.php 6.3 KB

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