ModelPdo.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. * @var bool
  13. */
  14. public static $usesSharedPdo = true;
  15. /**
  16. * @var Minz_Pdo|null
  17. */
  18. private static $sharedPdo;
  19. /**
  20. * @var string|null
  21. */
  22. private static $sharedCurrentUser;
  23. /**
  24. * @var Minz_Pdo
  25. */
  26. protected $pdo;
  27. /**
  28. * @var string|null
  29. */
  30. protected $current_user;
  31. /**
  32. * @throws Minz_ConfigurationNamespaceException
  33. * @throws Minz_PDOConnectionException
  34. * @throws PDOException
  35. */
  36. private function dbConnect(): void {
  37. $db = Minz_Configuration::get('system')->db;
  38. $driver_options = isset($db['pdo_options']) && is_array($db['pdo_options']) ? $db['pdo_options'] : [];
  39. $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
  40. $dbServer = parse_url('db://' . $db['host']);
  41. $dsn = '';
  42. $dsnParams = empty($db['connection_uri_params']) ? '' : (';' . $db['connection_uri_params']);
  43. switch ($db['type']) {
  44. case 'mysql':
  45. $dsn = 'mysql:';
  46. if (empty($dbServer['host'])) {
  47. $dsn .= 'unix_socket=' . $db['host'];
  48. } else {
  49. $dsn .= 'host=' . $dbServer['host'];
  50. }
  51. $dsn .= ';charset=utf8mb4';
  52. if (!empty($db['base'])) {
  53. $dsn .= ';dbname=' . $db['base'];
  54. }
  55. if (!empty($dbServer['port'])) {
  56. $dsn .= ';port=' . $dbServer['port'];
  57. }
  58. $driver_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8mb4';
  59. $this->pdo = new Minz_PdoMysql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  60. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  61. break;
  62. case 'sqlite':
  63. $dsn = 'sqlite:' . join_path(DATA_PATH, 'users', $this->current_user, 'db.sqlite');
  64. $this->pdo = new Minz_PdoSqlite($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  65. $this->pdo->setPrefix('');
  66. break;
  67. case 'pgsql':
  68. $dsn = 'pgsql:host=' . (empty($dbServer['host']) ? $db['host'] : $dbServer['host']);
  69. if (!empty($db['base'])) {
  70. $dsn .= ';dbname=' . $db['base'];
  71. }
  72. if (!empty($dbServer['port'])) {
  73. $dsn .= ';port=' . $dbServer['port'];
  74. }
  75. $this->pdo = new Minz_PdoPgsql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  76. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  77. break;
  78. default:
  79. throw new Minz_PDOConnectionException(
  80. 'Invalid database type!',
  81. $db['user'], Minz_Exception::ERROR
  82. );
  83. }
  84. self::$sharedPdo = $this->pdo;
  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. * @param string|null $currentUser
  90. * @param Minz_Pdo|null $currentPdo
  91. * @throws Minz_ConfigurationNamespaceException
  92. * @throws Minz_PDOConnectionException
  93. */
  94. public function __construct(?string $currentUser = null, ?Minz_Pdo $currentPdo = null) {
  95. if ($currentUser === null) {
  96. $currentUser = Minz_User::name();
  97. }
  98. if ($currentPdo !== null) {
  99. $this->pdo = $currentPdo;
  100. return;
  101. }
  102. if ($currentUser == '') {
  103. throw new Minz_PDOConnectionException('Current user must not be empty!', '', Minz_Exception::ERROR);
  104. }
  105. if (self::$usesSharedPdo && self::$sharedPdo !== null && $currentUser === self::$sharedCurrentUser) {
  106. $this->pdo = self::$sharedPdo;
  107. $this->current_user = self::$sharedCurrentUser;
  108. return;
  109. }
  110. $this->current_user = $currentUser;
  111. self::$sharedCurrentUser = $currentUser;
  112. $ex = null;
  113. //Attempt a few times to connect to database
  114. for ($attempt = 1; $attempt <= 5; $attempt++) {
  115. try {
  116. $this->dbConnect();
  117. return;
  118. } catch (PDOException $e) {
  119. $ex = $e;
  120. if (empty($e->errorInfo[0]) || $e->errorInfo[0] !== '08006') {
  121. //We are only interested in: SQLSTATE connection exception / connection failure
  122. break;
  123. }
  124. } catch (Exception $e) {
  125. $ex = $e;
  126. }
  127. sleep(2);
  128. }
  129. $db = Minz_Configuration::get('system')->db;
  130. throw new Minz_PDOConnectionException(
  131. $ex->getMessage(),
  132. $db['user'], Minz_Exception::ERROR
  133. );
  134. }
  135. public function beginTransaction(): void {
  136. $this->pdo->beginTransaction();
  137. }
  138. public function inTransaction(): bool {
  139. return $this->pdo->inTransaction();
  140. }
  141. public function commit(): void {
  142. $this->pdo->commit();
  143. }
  144. public function rollBack(): void {
  145. $this->pdo->rollBack();
  146. }
  147. public static function clean(): void {
  148. self::$sharedPdo = null;
  149. self::$sharedCurrentUser = '';
  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. $callingFunction = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'] ?? '??';
  192. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  193. Minz_Log::error('SQL error ' . $callingFunction . ' ' . json_encode($info));
  194. return null;
  195. }
  196. /**
  197. * @param array<string,int|string|null> $values
  198. * @return array<array<string,int|string|null>>|null
  199. */
  200. public function fetchAssoc(string $sql, array $values = []): ?array {
  201. return $this->fetchAny($sql, $values, PDO::FETCH_ASSOC);
  202. }
  203. /**
  204. * @param array<string,int|string|null> $values
  205. * @return array<int|string|null>|null
  206. */
  207. public function fetchColumn(string $sql, int $column, array $values = []): ?array {
  208. return $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, $column);
  209. }
  210. }