PageRenderTime 34ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/dibi/drivers/mysqli.php

https://code.google.com/
PHP | 460 lines | 211 code | 100 blank | 149 comment | 31 complexity | 057dff8ff25ced03299b1e0c60072e27 MD5 | raw file
Possible License(s): Apache-2.0, GPL-2.0
  1. <?php
  2. /**
  3. * This file is part of the "dibi" - smart database abstraction layer.
  4. *
  5. * Copyright (c) 2005, 2010 David Grudl (http://davidgrudl.com)
  6. *
  7. * This source file is subject to the "dibi license", and/or
  8. * GPL license. For more information please see http://dibiphp.com
  9. * @package dibi\drivers
  10. */
  11. require_once dirname(__FILE__) . '/mysql.reflector.php';
  12. /**
  13. * The dibi driver for MySQL database via improved extension.
  14. *
  15. * Driver options:
  16. * - host => the MySQL server host name
  17. * - port (int) => the port number to attempt to connect to the MySQL server
  18. * - socket => the socket or named pipe
  19. * - username (or user)
  20. * - password (or pass)
  21. * - database => the database name to select
  22. * - options (array) => array of driver specific constants (MYSQLI_*) and values {@see mysqli_options}
  23. * - flags (int) => driver specific constants (MYSQLI_CLIENT_*) {@see mysqli_real_connect}
  24. * - charset => character encoding to set (default is utf8)
  25. * - persistent (bool) => try to find a persistent link?
  26. * - unbuffered (bool) => sends query without fetching and buffering the result rows automatically?
  27. * - sqlmode => see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
  28. * - resource (mysqli) => existing connection resource
  29. * - lazy, profiler, result, substitutes, ... => see DibiConnection options
  30. *
  31. * @author David Grudl
  32. * @package dibi\drivers
  33. */
  34. class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
  35. {
  36. const ERROR_ACCESS_DENIED = 1045;
  37. const ERROR_DUPLICATE_ENTRY = 1062;
  38. const ERROR_DATA_TRUNCATED = 1265;
  39. /** @var mysqli Connection resource */
  40. private $connection;
  41. /** @var mysqli_result Resultset resource */
  42. private $resultSet;
  43. /** @var bool Is buffered (seekable and countable)? */
  44. private $buffered;
  45. /**
  46. * @throws DibiException
  47. */
  48. public function __construct()
  49. {
  50. if (!extension_loaded('mysqli')) {
  51. throw new DibiDriverException("PHP extension 'mysqli' is not loaded.");
  52. }
  53. }
  54. /**
  55. * Connects to a database.
  56. * @return void
  57. * @throws DibiException
  58. */
  59. public function connect(array &$config)
  60. {
  61. mysqli_report(MYSQLI_REPORT_OFF);
  62. if (isset($config['resource'])) {
  63. $this->connection = $config['resource'];
  64. } else {
  65. // default values
  66. if (!isset($config['charset'])) $config['charset'] = 'utf8';
  67. if (!isset($config['username'])) $config['username'] = ini_get('mysqli.default_user');
  68. if (!isset($config['password'])) $config['password'] = ini_get('mysqli.default_pw');
  69. if (!isset($config['socket'])) $config['socket'] = ini_get('mysqli.default_socket');
  70. if (!isset($config['port'])) $config['port'] = NULL;
  71. if (!isset($config['host'])) {
  72. $host = ini_get('mysqli.default_host');
  73. if ($host) {
  74. $config['host'] = $host;
  75. $config['port'] = ini_get('mysqli.default_port');
  76. } else {
  77. $config['host'] = NULL;
  78. $config['port'] = NULL;
  79. }
  80. }
  81. $foo = & $config['flags'];
  82. $foo = & $config['database'];
  83. $this->connection = mysqli_init();
  84. if (isset($config['options'])) {
  85. if (is_scalar($config['options'])) {
  86. $config['flags'] = $config['options']; // back compatibility
  87. trigger_error(__CLASS__ . ": configuration item 'options' must be array; for constants MYSQLI_CLIENT_* use 'flags'.", E_USER_NOTICE);
  88. } else {
  89. foreach ((array) $config['options'] as $key => $value) {
  90. mysqli_options($this->connection, $key, $value);
  91. }
  92. }
  93. }
  94. @mysqli_real_connect($this->connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['flags']); // intentionally @
  95. if ($errno = mysqli_connect_errno()) {
  96. throw new DibiDriverException(mysqli_connect_error(), $errno);
  97. }
  98. }
  99. if (isset($config['charset'])) {
  100. $ok = FALSE;
  101. if (version_compare(PHP_VERSION , '5.1.5', '>=')) {
  102. // affects the character set used by mysql_real_escape_string() (was added in MySQL 5.0.7 and PHP 5.0.5, fixed in PHP 5.1.5)
  103. $ok = @mysqli_set_charset($this->connection, $config['charset']); // intentionally @
  104. }
  105. if (!$ok) {
  106. $this->query("SET NAMES '$config[charset]'");
  107. }
  108. }
  109. if (isset($config['sqlmode'])) {
  110. $this->query("SET sql_mode='$config[sqlmode]'");
  111. }
  112. $this->query("SET time_zone='" . date('P') . "'");
  113. $this->buffered = empty($config['unbuffered']);
  114. }
  115. /**
  116. * Disconnects from a database.
  117. * @return void
  118. */
  119. public function disconnect()
  120. {
  121. mysqli_close($this->connection);
  122. }
  123. /**
  124. * Executes the SQL query.
  125. * @param string SQL statement.
  126. * @return IDibiResultDriver|NULL
  127. * @throws DibiDriverException
  128. */
  129. public function query($sql)
  130. {
  131. $this->resultSet = @mysqli_query($this->connection, $sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT); // intentionally @
  132. if (mysqli_errno($this->connection)) {
  133. throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection), $sql);
  134. }
  135. return is_object($this->resultSet) ? clone $this : NULL;
  136. }
  137. /**
  138. * Retrieves information about the most recently executed query.
  139. * @return array
  140. */
  141. public function getInfo()
  142. {
  143. $res = array();
  144. preg_match_all('#(.+?): +(\d+) *#', mysqli_info($this->connection), $matches, PREG_SET_ORDER);
  145. if (preg_last_error()) throw new PcreException;
  146. foreach ($matches as $m) {
  147. $res[$m[1]] = (int) $m[2];
  148. }
  149. return $res;
  150. }
  151. /**
  152. * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
  153. * @return int|FALSE number of rows or FALSE on error
  154. */
  155. public function getAffectedRows()
  156. {
  157. return mysqli_affected_rows($this->connection);
  158. }
  159. /**
  160. * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
  161. * @return int|FALSE int on success or FALSE on failure
  162. */
  163. public function getInsertId($sequence)
  164. {
  165. return mysqli_insert_id($this->connection);
  166. }
  167. /**
  168. * Begins a transaction (if supported).
  169. * @param string optional savepoint name
  170. * @return void
  171. * @throws DibiDriverException
  172. */
  173. public function begin($savepoint = NULL)
  174. {
  175. $this->query($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
  176. }
  177. /**
  178. * Commits statements in a transaction.
  179. * @param string optional savepoint name
  180. * @return void
  181. * @throws DibiDriverException
  182. */
  183. public function commit($savepoint = NULL)
  184. {
  185. $this->query($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
  186. }
  187. /**
  188. * Rollback changes in a transaction.
  189. * @param string optional savepoint name
  190. * @return void
  191. * @throws DibiDriverException
  192. */
  193. public function rollback($savepoint = NULL)
  194. {
  195. $this->query($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
  196. }
  197. /**
  198. * Returns the connection resource.
  199. * @return mysqli
  200. */
  201. public function getResource()
  202. {
  203. return $this->connection;
  204. }
  205. /**
  206. * Returns the connection reflector.
  207. * @return IDibiReflector
  208. */
  209. public function getReflector()
  210. {
  211. return new DibiMySqlReflector($this);
  212. }
  213. /********************* SQL ****************d*g**/
  214. /**
  215. * Encodes data for use in a SQL statement.
  216. * @param mixed value
  217. * @param string type (dibi::TEXT, dibi::BOOL, ...)
  218. * @return string encoded value
  219. * @throws InvalidArgumentException
  220. */
  221. public function escape($value, $type)
  222. {
  223. switch ($type) {
  224. case dibi::TEXT:
  225. return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
  226. case dibi::BINARY:
  227. return "_binary'" . mysqli_real_escape_string($this->connection, $value) . "'";
  228. case dibi::IDENTIFIER:
  229. return '`' . str_replace('`', '``', $value) . '`';
  230. case dibi::BOOL:
  231. return $value ? 1 : 0;
  232. case dibi::DATE:
  233. return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
  234. case dibi::DATETIME:
  235. return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
  236. default:
  237. throw new InvalidArgumentException('Unsupported type.');
  238. }
  239. }
  240. /**
  241. * Encodes string for use in a LIKE statement.
  242. * @param string
  243. * @param int
  244. * @return string
  245. */
  246. public function escapeLike($value, $pos)
  247. {
  248. $value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\n\r\\'%_");
  249. return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
  250. }
  251. /**
  252. * Decodes data from result set.
  253. * @param string value
  254. * @param string type (dibi::BINARY)
  255. * @return string decoded value
  256. * @throws InvalidArgumentException
  257. */
  258. public function unescape($value, $type)
  259. {
  260. if ($type === dibi::BINARY) {
  261. return $value;
  262. }
  263. throw new InvalidArgumentException('Unsupported type.');
  264. }
  265. /**
  266. * Injects LIMIT/OFFSET to the SQL query.
  267. * @param string &$sql The SQL query that will be modified.
  268. * @param int $limit
  269. * @param int $offset
  270. * @return void
  271. */
  272. public function applyLimit(&$sql, $limit, $offset)
  273. {
  274. if ($limit < 0 && $offset < 1) return;
  275. // see http://dev.mysql.com/doc/refman/5.0/en/select.html
  276. $sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
  277. . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
  278. }
  279. /********************* result set ****************d*g**/
  280. /**
  281. * Returns the number of rows in a result set.
  282. * @return int
  283. */
  284. public function getRowCount()
  285. {
  286. if (!$this->buffered) {
  287. throw new DibiDriverException('Row count is not available for unbuffered queries.');
  288. }
  289. return mysqli_num_rows($this->resultSet);
  290. }
  291. /**
  292. * Fetches the row at current position and moves the internal cursor to the next position.
  293. * @param bool TRUE for associative array, FALSE for numeric
  294. * @return array array on success, nonarray if no next record
  295. */
  296. public function fetch($assoc)
  297. {
  298. return mysqli_fetch_array($this->resultSet, $assoc ? MYSQLI_ASSOC : MYSQLI_NUM);
  299. }
  300. /**
  301. * Moves cursor position without fetching row.
  302. * @param int the 0-based cursor pos to seek to
  303. * @return boolean TRUE on success, FALSE if unable to seek to specified record
  304. * @throws DibiException
  305. */
  306. public function seek($row)
  307. {
  308. if (!$this->buffered) {
  309. throw new DibiDriverException('Cannot seek an unbuffered result set.');
  310. }
  311. return mysqli_data_seek($this->resultSet, $row);
  312. }
  313. /**
  314. * Frees the resources allocated for this result set.
  315. * @return void
  316. */
  317. public function free()
  318. {
  319. mysqli_free_result($this->resultSet);
  320. $this->resultSet = NULL;
  321. }
  322. /**
  323. * Returns metadata for all columns in a result set.
  324. * @return array
  325. */
  326. public function getResultColumns()
  327. {
  328. static $types;
  329. if (empty($types)) {
  330. $consts = get_defined_constants(TRUE);
  331. foreach ($consts['mysqli'] as $key => $value) {
  332. if (strncmp($key, 'MYSQLI_TYPE_', 12) === 0) {
  333. $types[$value] = substr($key, 12);
  334. }
  335. }
  336. $types[MYSQLI_TYPE_TINY] = $types[MYSQLI_TYPE_SHORT] = $types[MYSQLI_TYPE_LONG] = 'INT';
  337. }
  338. $count = mysqli_num_fields($this->resultSet);
  339. $columns = array();
  340. for ($i = 0; $i < $count; $i++) {
  341. $row = (array) mysqli_fetch_field_direct($this->resultSet, $i);
  342. $columns[] = array(
  343. 'name' => $row['name'],
  344. 'table' => $row['orgtable'],
  345. 'fullname' => $row['table'] ? $row['table'] . '.' . $row['name'] : $row['name'],
  346. 'nativetype' => $types[$row['type']],
  347. 'vendor' => $row,
  348. );
  349. }
  350. return $columns;
  351. }
  352. /**
  353. * Returns the result set resource.
  354. * @return mysqli_result
  355. */
  356. public function getResultResource()
  357. {
  358. return $this->resultSet;
  359. }
  360. }