ModelPdo.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. * @return void
  33. * @throws Minz_ConfigurationNamespaceException
  34. * @throws Minz_PDOConnectionException
  35. * @throws PDOException
  36. */
  37. private function dbConnect() {
  38. $db = Minz_Configuration::get('system')->db;
  39. $driver_options = isset($db['pdo_options']) && is_array($db['pdo_options']) ? $db['pdo_options'] : [];
  40. $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
  41. $dbServer = parse_url('db://' . $db['host']);
  42. $dsn = '';
  43. $dsnParams = empty($db['connection_uri_params']) ? '' : (';' . $db['connection_uri_params']);
  44. switch ($db['type']) {
  45. case 'mysql':
  46. $dsn = 'mysql:';
  47. if (empty($dbServer['host'])) {
  48. $dsn .= 'unix_socket=' . $db['host'];
  49. } else {
  50. $dsn .= 'host=' . $dbServer['host'];
  51. }
  52. $dsn .= ';charset=utf8mb4';
  53. if (!empty($db['base'])) {
  54. $dsn .= ';dbname=' . $db['base'];
  55. }
  56. if (!empty($dbServer['port'])) {
  57. $dsn .= ';port=' . $dbServer['port'];
  58. }
  59. $driver_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8mb4';
  60. $this->pdo = new Minz_PdoMysql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  61. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  62. break;
  63. case 'sqlite':
  64. $dsn = 'sqlite:' . join_path(DATA_PATH, 'users', $this->current_user, 'db.sqlite');
  65. $this->pdo = new Minz_PdoSqlite($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  66. $this->pdo->setPrefix('');
  67. break;
  68. case 'pgsql':
  69. $dsn = 'pgsql:host=' . (empty($dbServer['host']) ? $db['host'] : $dbServer['host']);
  70. if (!empty($db['base'])) {
  71. $dsn .= ';dbname=' . $db['base'];
  72. }
  73. if (!empty($dbServer['port'])) {
  74. $dsn .= ';port=' . $dbServer['port'];
  75. }
  76. $this->pdo = new Minz_PdoPgsql($dsn . $dsnParams, $db['user'], $db['password'], $driver_options);
  77. $this->pdo->setPrefix($db['prefix'] . $this->current_user . '_');
  78. break;
  79. default:
  80. throw new Minz_PDOConnectionException(
  81. 'Invalid database type!',
  82. $db['user'], Minz_Exception::ERROR
  83. );
  84. }
  85. self::$sharedPdo = $this->pdo;
  86. }
  87. /**
  88. * Create the connection to the database using the variables
  89. * HOST, BASE, USER and PASS variables defined in the configuration file
  90. * @param string|null $currentUser
  91. * @param Minz_Pdo|null $currentPdo
  92. * @throws Minz_ConfigurationNamespaceException
  93. * @throws Minz_PDOConnectionException
  94. */
  95. public function __construct(?string $currentUser = null, ?Minz_Pdo $currentPdo = null) {
  96. if ($currentUser === null) {
  97. $currentUser = Minz_User::name();
  98. }
  99. if ($currentPdo !== null) {
  100. $this->pdo = $currentPdo;
  101. return;
  102. }
  103. if ($currentUser == '') {
  104. throw new Minz_PDOConnectionException('Current user must not be empty!', '', Minz_Exception::ERROR);
  105. }
  106. if (self::$usesSharedPdo && self::$sharedPdo !== null && $currentUser === self::$sharedCurrentUser) {
  107. $this->pdo = self::$sharedPdo;
  108. $this->current_user = self::$sharedCurrentUser;
  109. return;
  110. }
  111. $this->current_user = $currentUser;
  112. self::$sharedCurrentUser = $currentUser;
  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->getMessage(),
  133. $db['user'], Minz_Exception::ERROR
  134. );
  135. }
  136. /**
  137. * @return void
  138. */
  139. public function beginTransaction() {
  140. $this->pdo->beginTransaction();
  141. }
  142. public function inTransaction(): bool {
  143. return $this->pdo->inTransaction();
  144. }
  145. /**
  146. * @return void
  147. */
  148. public function commit() {
  149. $this->pdo->commit();
  150. }
  151. /**
  152. * @return void
  153. */
  154. public function rollBack() {
  155. $this->pdo->rollBack();
  156. }
  157. /**
  158. * @return void
  159. */
  160. public static function clean() {
  161. self::$sharedPdo = null;
  162. self::$sharedCurrentUser = '';
  163. }
  164. /**
  165. * @param array<string,int|string|null> $values
  166. * @phpstan-return ($mode is PDO::FETCH_ASSOC ? array<array<string,int|string|null>>|null : array<int|string|null>|null)
  167. * @return array<array<string,int|string|null>>|array<int|string|null>|null
  168. */
  169. private function fetchAny(string $sql, array $values, int $mode, int $column = 0): ?array {
  170. $stm = $this->pdo->prepare($sql);
  171. $ok = $stm !== false;
  172. if ($ok && !empty($values)) {
  173. foreach ($values as $name => $value) {
  174. if (is_int($value)) $type = PDO::PARAM_INT;
  175. elseif (is_string($value)) $type = PDO::PARAM_STR;
  176. elseif (is_null($value)) $type = PDO::PARAM_NULL;
  177. else {
  178. $ok = false;
  179. break;
  180. }
  181. if (!$stm->bindValue($name, $value, $type)) {
  182. $ok = false;
  183. break;
  184. }
  185. }
  186. }
  187. if ($ok && $stm !== false && $stm->execute()) {
  188. switch ($mode) {
  189. case PDO::FETCH_COLUMN:
  190. $res = $stm->fetchAll(PDO::FETCH_COLUMN, $column);
  191. break;
  192. case PDO::FETCH_ASSOC:
  193. default:
  194. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  195. break;
  196. }
  197. if ($res !== false) {
  198. return $res;
  199. }
  200. }
  201. $callingFunction = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'] ?? '??';
  202. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  203. Minz_Log::error('SQL error ' . $callingFunction . ' ' . json_encode($info));
  204. return null;
  205. }
  206. /**
  207. * @param array<string,int|string|null> $values
  208. * @return array<array<string,int|string|null>>|null
  209. */
  210. public function fetchAssoc(string $sql, array $values = []): ?array {
  211. return $this->fetchAny($sql, $values, PDO::FETCH_ASSOC);
  212. }
  213. /**
  214. * @param array<string,int|string|null> $values
  215. * @return array<int|string|null>|null
  216. */
  217. public function fetchColumn(string $sql, int $column, array $values = []): ?array {
  218. return $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, $column);
  219. }
  220. }