ModelPdo.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. <?php
  2. /**
  3. * MINZ - Copyright 2011 Marien Fressinaud
  4. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  5. */
  6. /**
  7. * La classe Model_sql représente le modèle interragissant avec les bases de données
  8. */
  9. class Minz_ModelPdo {
  10. /**
  11. * Partage la connexion à la base de données entre toutes les instances.
  12. */
  13. public static $usesSharedPdo = true;
  14. private static $sharedPdo = null;
  15. private static $sharedPrefix;
  16. private static $sharedCurrentUser;
  17. protected $pdo;
  18. protected $current_user;
  19. /**
  20. * Créé la connexion à la base de données à l'aide des variables
  21. * HOST, BASE, USER et PASS définies dans le fichier de configuration
  22. */
  23. public function __construct($currentUser = null, $currentPdo = null) {
  24. if ($currentUser === null) {
  25. $currentUser = Minz_Session::param('currentUser');
  26. }
  27. if ($currentPdo != null) {
  28. $this->pdo = $currentPdo;
  29. return;
  30. }
  31. if (self::$usesSharedPdo && self::$sharedPdo != null &&
  32. ($currentUser == '' || $currentUser === self::$sharedCurrentUser)) {
  33. $this->pdo = self::$sharedPdo;
  34. $this->current_user = self::$sharedCurrentUser;
  35. return;
  36. }
  37. $this->current_user = $currentUser;
  38. self::$sharedCurrentUser = $currentUser;
  39. $conf = Minz_Configuration::get('system');
  40. $db = $conf->db;
  41. $driver_options = isset($db['pdo_options']) && is_array($db['pdo_options']) ? $db['pdo_options'] : [];
  42. $dbServer = parse_url('db://' . $db['host']);
  43. $dsn = '';
  44. try {
  45. switch ($db['type']) {
  46. case 'mysql':
  47. $dsn = 'mysql:host=' . (empty($dbServer['host']) ? $db['host'] : $dbServer['host']) . ';charset=utf8mb4';
  48. if (!empty($db['base'])) {
  49. $dsn .= ';dbname=' . $db['base'];
  50. }
  51. if (!empty($dbServer['port'])) {
  52. $dsn .= ';port=' . $dbServer['port'];
  53. }
  54. $driver_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8mb4';
  55. $this->pdo = new MinzPDOMySql($dsn, $db['user'], $db['password'], $driver_options);
  56. $this->pdo->setPrefix($db['prefix'] . $currentUser . '_');
  57. break;
  58. case 'sqlite':
  59. $dsn = 'sqlite:' . join_path(DATA_PATH, 'users', $currentUser, 'db.sqlite');
  60. $this->pdo = new MinzPDOSQLite($dsn, $db['user'], $db['password'], $driver_options);
  61. $this->pdo->setPrefix('');
  62. break;
  63. case 'pgsql':
  64. $dsn = 'pgsql:host=' . (empty($dbServer['host']) ? $db['host'] : $dbServer['host']);
  65. if (!empty($db['base'])) {
  66. $dsn .= ';dbname=' . $db['base'];
  67. }
  68. if (!empty($dbServer['port'])) {
  69. $dsn .= ';port=' . $dbServer['port'];
  70. }
  71. $this->pdo = new MinzPDOPGSQL($dsn, $db['user'], $db['password'], $driver_options);
  72. $this->pdo->setPrefix($db['prefix'] . $currentUser . '_');
  73. break;
  74. default:
  75. throw new Minz_PDOConnectionException(
  76. 'Invalid database type!',
  77. $db['user'], Minz_Exception::ERROR
  78. );
  79. break;
  80. }
  81. self::$sharedPdo = $this->pdo;
  82. } catch (Exception $e) {
  83. throw new Minz_PDOConnectionException(
  84. $dsn,
  85. $db['user'], Minz_Exception::ERROR
  86. );
  87. }
  88. }
  89. public function beginTransaction() {
  90. $this->pdo->beginTransaction();
  91. }
  92. public function inTransaction() {
  93. return $this->pdo->inTransaction();
  94. }
  95. public function commit() {
  96. $this->pdo->commit();
  97. }
  98. public function rollBack() {
  99. $this->pdo->rollBack();
  100. }
  101. public static function clean() {
  102. self::$sharedPdo = null;
  103. self::$sharedCurrentUser = '';
  104. }
  105. }
  106. abstract class MinzPDO extends PDO {
  107. public function __construct($dsn, $username = null, $passwd = null, $options = null) {
  108. parent::__construct($dsn, $username, $passwd, $options);
  109. $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  110. }
  111. abstract public function dbType();
  112. private $prefix = '';
  113. public function prefix() { return $this->prefix; }
  114. public function setPrefix($prefix) { $this->prefix = $prefix; }
  115. private function autoPrefix($sql) {
  116. return str_replace('`_', '`' . $this->prefix, $sql);
  117. }
  118. protected function preSql($statement) {
  119. if (preg_match('/^(?:UPDATE|INSERT|DELETE)/i', $statement)) {
  120. invalidateHttpCache();
  121. }
  122. return $this->autoPrefix($statement);
  123. }
  124. public function lastInsertId($name = null) {
  125. if ($name != null) {
  126. $name = $this->preSql($name);
  127. }
  128. return parent::lastInsertId($name);
  129. }
  130. public function prepare($statement, $driver_options = array()) {
  131. $statement = $this->preSql($statement);
  132. return parent::prepare($statement, $driver_options);
  133. }
  134. public function exec($statement) {
  135. $statement = $this->preSql($statement);
  136. return parent::exec($statement);
  137. }
  138. public function query($statement) {
  139. $statement = $this->preSql($statement);
  140. return parent::query($statement);
  141. }
  142. }
  143. class MinzPDOMySql extends MinzPDO {
  144. public function __construct($dsn, $username = null, $passwd = null, $options = null) {
  145. parent::__construct($dsn, $username, $passwd, $options);
  146. $this->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
  147. }
  148. public function dbType() {
  149. return 'mysql';
  150. }
  151. public function lastInsertId($name = null) {
  152. return parent::lastInsertId(); //We discard the name, only used by PostgreSQL
  153. }
  154. }
  155. class MinzPDOSQLite extends MinzPDO {
  156. public function __construct($dsn, $username = null, $passwd = null, $options = null) {
  157. parent::__construct($dsn, $username, $passwd, $options);
  158. $this->exec('PRAGMA foreign_keys = ON;');
  159. }
  160. public function dbType() {
  161. return 'sqlite';
  162. }
  163. public function lastInsertId($name = null) {
  164. return parent::lastInsertId(); //We discard the name, only used by PostgreSQL
  165. }
  166. }
  167. class MinzPDOPGSQL extends MinzPDO {
  168. public function __construct($dsn, $username = null, $passwd = null, $options = null) {
  169. parent::__construct($dsn, $username, $passwd, $options);
  170. $this->exec("SET NAMES 'UTF8';");
  171. }
  172. public function dbType() {
  173. return 'pgsql';
  174. }
  175. protected function preSql($statement) {
  176. $statement = parent::preSql($statement);
  177. return str_replace(array('`', ' LIKE '), array('"', ' ILIKE '), $statement);
  178. }
  179. }