ModelPdo.php 7.2 KB

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