PageRenderTime 46ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/shopaholic/lib/dibi/drivers/mysqli.php

http://github.com/jakubkulhan/shopaholic
PHP | 528 lines | 238 code | 104 blank | 186 comment | 30 complexity | b25c0d3cb1bc0cc83937f21ceb2da0ca MD5 | raw file
Possible License(s): WTFPL
  1. <?php
  2. /**
  3. * dibi - tiny'n'smart database abstraction layer
  4. * ----------------------------------------------
  5. *
  6. * Copyright (c) 2005, 2009 David Grudl (http://davidgrudl.com)
  7. *
  8. * This source file is subject to the "dibi license" that is bundled
  9. * with this package in the file license.txt.
  10. *
  11. * For more information please see http://dibiphp.com
  12. *
  13. * @copyright Copyright (c) 2005, 2009 David Grudl
  14. * @license http://dibiphp.com/license dibi license
  15. * @link http://dibiphp.com
  16. * @package dibi
  17. * @version $Id: mysqli.php 209 2009-03-19 12:18:16Z david@grudl.com $
  18. */
  19. /**
  20. * The dibi driver for MySQL database via improved extension.
  21. *
  22. * Connection options:
  23. * - 'host' - the MySQL server host name
  24. * - 'port' - the port number to attempt to connect to the MySQL server
  25. * - 'socket' - the socket or named pipe
  26. * - 'username' (or 'user')
  27. * - 'password' (or 'pass')
  28. * - 'persistent' - try to find a persistent link?
  29. * - 'database' - the database name to select
  30. * - 'charset' - character encoding to set
  31. * - 'unbuffered' - sends query without fetching and buffering the result rows automatically?
  32. * - 'options' - driver specific constants (MYSQLI_*)
  33. * - 'sqlmode' - see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
  34. * - 'lazy' - if TRUE, connection will be established only when required
  35. * - 'resource' - connection resource (optional)
  36. *
  37. * @author David Grudl
  38. * @copyright Copyright (c) 2005, 2009 David Grudl
  39. * @package dibi
  40. */
  41. class DibiMySqliDriver extends DibiObject implements IDibiDriver
  42. {
  43. /** @var mysqli Connection resource */
  44. private $connection;
  45. /** @var mysqli_result Resultset resource */
  46. private $resultSet;
  47. /** @var bool Is buffered (seekable and countable)? */
  48. private $buffered;
  49. /**
  50. * @throws DibiException
  51. */
  52. public function __construct()
  53. {
  54. if (!extension_loaded('mysqli')) {
  55. throw new DibiDriverException("PHP extension 'mysqli' is not loaded.");
  56. }
  57. }
  58. /**
  59. * Connects to a database.
  60. * @return void
  61. * @throws DibiException
  62. */
  63. public function connect(array &$config)
  64. {
  65. DibiConnection::alias($config, 'username', 'user');
  66. DibiConnection::alias($config, 'password', 'pass');
  67. DibiConnection::alias($config, 'host', 'hostname');
  68. DibiConnection::alias($config, 'options');
  69. DibiConnection::alias($config, 'database');
  70. if (isset($config['resource'])) {
  71. $this->connection = $config['resource'];
  72. } else {
  73. // default values
  74. if (!isset($config['username'])) $config['username'] = ini_get('mysqli.default_user');
  75. if (!isset($config['password'])) $config['password'] = ini_get('mysqli.default_pw');
  76. if (!isset($config['socket'])) $config['socket'] = ini_get('mysqli.default_socket');
  77. if (!isset($config['port'])) $config['port'] = NULL;
  78. if (!isset($config['host'])) {
  79. $host = ini_get('mysqli.default_host');
  80. if ($host) {
  81. $config['host'] = $host;
  82. $config['port'] = ini_get('mysqli.default_port');
  83. } else {
  84. $config['host'] = NULL;
  85. $config['port'] = NULL;
  86. }
  87. }
  88. $this->connection = mysqli_init();
  89. @mysqli_real_connect($this->connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['options']); // intentionally @
  90. if ($errno = mysqli_connect_errno()) {
  91. throw new DibiDriverException(mysqli_connect_error(), $errno);
  92. }
  93. }
  94. if (isset($config['charset'])) {
  95. $ok = FALSE;
  96. if (version_compare(PHP_VERSION , '5.1.5', '>=')) {
  97. // 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)
  98. $ok = @mysqli_set_charset($this->connection, $config['charset']); // intentionally @
  99. }
  100. if (!$ok) {
  101. $ok = @mysqli_query($this->connection, "SET NAMES '$config[charset]'"); // intentionally @
  102. if (!$ok) {
  103. throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection));
  104. }
  105. }
  106. }
  107. if (isset($config['sqlmode'])) {
  108. if (!@mysqli_query($this->connection, "SET sql_mode='$config[sqlmode]'")) { // intentionally @
  109. throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection));
  110. }
  111. }
  112. $this->buffered = empty($config['unbuffered']);
  113. }
  114. /**
  115. * Disconnects from a database.
  116. * @return void
  117. */
  118. public function disconnect()
  119. {
  120. mysqli_close($this->connection);
  121. }
  122. /**
  123. * Executes the SQL query.
  124. * @param string SQL statement.
  125. * @return IDibiDriver|NULL
  126. * @throws DibiDriverException
  127. */
  128. public function query($sql)
  129. {
  130. $this->resultSet = @mysqli_query($this->connection, $sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT); // intentionally @
  131. if (mysqli_errno($this->connection)) {
  132. throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection), $sql);
  133. }
  134. return is_object($this->resultSet) ? clone $this : NULL;
  135. }
  136. /**
  137. * Retrieves information about the most recently executed query.
  138. * @return array
  139. */
  140. public function getInfo()
  141. {
  142. $res = array();
  143. preg_match_all('#(.+?): +(\d+) *#', mysqli_info($this->connection), $matches, PREG_SET_ORDER);
  144. foreach ($matches as $m) {
  145. $res[$m[1]] = (int) $m[2];
  146. }
  147. return $res;
  148. }
  149. /**
  150. * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
  151. * @return int|FALSE number of rows or FALSE on error
  152. */
  153. public function getAffectedRows()
  154. {
  155. return mysqli_affected_rows($this->connection);
  156. }
  157. /**
  158. * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
  159. * @return int|FALSE int on success or FALSE on failure
  160. */
  161. public function getInsertId($sequence)
  162. {
  163. return mysqli_insert_id($this->connection);
  164. }
  165. /**
  166. * Begins a transaction (if supported).
  167. * @param string optinal savepoint name
  168. * @return void
  169. * @throws DibiDriverException
  170. */
  171. public function begin($savepoint = NULL)
  172. {
  173. $this->query($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
  174. }
  175. /**
  176. * Commits statements in a transaction.
  177. * @param string optinal savepoint name
  178. * @return void
  179. * @throws DibiDriverException
  180. */
  181. public function commit($savepoint = NULL)
  182. {
  183. $this->query($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
  184. }
  185. /**
  186. * Rollback changes in a transaction.
  187. * @param string optinal savepoint name
  188. * @return void
  189. * @throws DibiDriverException
  190. */
  191. public function rollback($savepoint = NULL)
  192. {
  193. $this->query($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
  194. }
  195. /**
  196. * Returns the connection resource.
  197. * @return mysqli
  198. */
  199. public function getResource()
  200. {
  201. return $this->connection;
  202. }
  203. /********************* SQL ****************d*g**/
  204. /**
  205. * Encodes data for use in a SQL statement.
  206. * @param string value
  207. * @param string type (dibi::TEXT, dibi::BOOL, ...)
  208. * @return string encoded value
  209. * @throws InvalidArgumentException
  210. */
  211. public function escape($value, $type)
  212. {
  213. switch ($type) {
  214. case dibi::TEXT:
  215. return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
  216. case dibi::BINARY:
  217. return "_binary'" . mysqli_real_escape_string($this->connection, $value) . "'";
  218. case dibi::IDENTIFIER:
  219. $value = str_replace('`', '``', $value);
  220. return '`' . str_replace('.', '`.`', $value) . '`';
  221. case dibi::BOOL:
  222. return $value ? 1 : 0;
  223. case dibi::DATE:
  224. return date("'Y-m-d'", $value);
  225. case dibi::DATETIME:
  226. return date("'Y-m-d H:i:s'", $value);
  227. default:
  228. throw new InvalidArgumentException('Unsupported type.');
  229. }
  230. }
  231. /**
  232. * Decodes data from result set.
  233. * @param string value
  234. * @param string type (dibi::BINARY)
  235. * @return string decoded value
  236. * @throws InvalidArgumentException
  237. */
  238. public function unescape($value, $type)
  239. {
  240. throw new InvalidArgumentException('Unsupported type.');
  241. }
  242. /**
  243. * Injects LIMIT/OFFSET to the SQL query.
  244. * @param string &$sql The SQL query that will be modified.
  245. * @param int $limit
  246. * @param int $offset
  247. * @return void
  248. */
  249. public function applyLimit(&$sql, $limit, $offset)
  250. {
  251. if ($limit < 0 && $offset < 1) return;
  252. // see http://dev.mysql.com/doc/refman/5.0/en/select.html
  253. $sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
  254. . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
  255. }
  256. /********************* result set ****************d*g**/
  257. /**
  258. * Returns the number of rows in a result set.
  259. * @return int
  260. */
  261. public function getRowCount()
  262. {
  263. if (!$this->buffered) {
  264. throw new DibiDriverException('Row count is not available for unbuffered queries.');
  265. }
  266. return mysqli_num_rows($this->resultSet);
  267. }
  268. /**
  269. * Fetches the row at current position and moves the internal cursor to the next position.
  270. * @param bool TRUE for associative array, FALSE for numeric
  271. * @return array array on success, nonarray if no next record
  272. * @internal
  273. */
  274. public function fetch($assoc)
  275. {
  276. return mysqli_fetch_array($this->resultSet, $assoc ? MYSQLI_ASSOC : MYSQLI_NUM);
  277. }
  278. /**
  279. * Moves cursor position without fetching row.
  280. * @param int the 0-based cursor pos to seek to
  281. * @return boolean TRUE on success, FALSE if unable to seek to specified record
  282. * @throws DibiException
  283. */
  284. public function seek($row)
  285. {
  286. if (!$this->buffered) {
  287. throw new DibiDriverException('Cannot seek an unbuffered result set.');
  288. }
  289. return mysqli_data_seek($this->resultSet, $row);
  290. }
  291. /**
  292. * Frees the resources allocated for this result set.
  293. * @return void
  294. */
  295. public function free()
  296. {
  297. mysqli_free_result($this->resultSet);
  298. $this->resultSet = NULL;
  299. }
  300. /**
  301. * Returns metadata for all columns in a result set.
  302. * @return array
  303. */
  304. public function getColumnsMeta()
  305. {
  306. static $types;
  307. if (empty($types)) {
  308. $consts = get_defined_constants(TRUE);
  309. foreach ($consts['mysqli'] as $key => $value) {
  310. if (strncmp($key, 'MYSQLI_TYPE_', 12) === 0) {
  311. $types[$value] = substr($key, 12);
  312. }
  313. }
  314. }
  315. $count = mysqli_num_fields($this->resultSet);
  316. $res = array();
  317. for ($i = 0; $i < $count; $i++) {
  318. $row = (array) mysqli_fetch_field_direct($this->resultSet, $i);
  319. $res[] = array(
  320. 'name' => $row['name'],
  321. 'table' => $row['orgtable'],
  322. 'fullname' => $row['table'] ? $row['table'] . '.' . $row['name'] : $row['name'],
  323. 'nativetype' => $types[$row['type']],
  324. 'vendor' => $row,
  325. );
  326. }
  327. return $res;
  328. }
  329. /**
  330. * Returns the result set resource.
  331. * @return mysqli_result
  332. */
  333. public function getResultResource()
  334. {
  335. return $this->resultSet;
  336. }
  337. /********************* reflection ****************d*g**/
  338. /**
  339. * Returns list of tables.
  340. * @return array
  341. */
  342. public function getTables()
  343. {
  344. /*$this->query("
  345. SELECT TABLE_NAME as name, TABLE_TYPE = 'VIEW' as view
  346. FROM INFORMATION_SCHEMA.TABLES
  347. WHERE TABLE_SCHEMA = DATABASE()
  348. ");*/
  349. $this->query("SHOW FULL TABLES");
  350. $res = array();
  351. while ($row = $this->fetch(FALSE)) {
  352. $res[] = array(
  353. 'name' => $row[0],
  354. 'view' => isset($row[1]) && $row[1] === 'VIEW',
  355. );
  356. }
  357. $this->free();
  358. return $res;
  359. }
  360. /**
  361. * Returns metadata for all columns in a table.
  362. * @param string
  363. * @return array
  364. */
  365. public function getColumns($table)
  366. {
  367. /*$table = $this->escape($table, dibi::TEXT);
  368. $this->query("
  369. SELECT *
  370. FROM INFORMATION_SCHEMA.COLUMNS
  371. WHERE TABLE_NAME = $table AND TABLE_SCHEMA = DATABASE()
  372. ");*/
  373. $this->query("SHOW COLUMNS FROM `$table`");
  374. $res = array();
  375. while ($row = $this->fetch(TRUE)) {
  376. $type = explode('(', $row['Type']);
  377. $res[] = array(
  378. 'name' => $row['Field'],
  379. 'table' => $table,
  380. 'nativetype' => strtoupper($type[0]),
  381. 'size' => isset($type[1]) ? (int) $type[1] : NULL,
  382. 'nullable' => $row['Null'] === 'YES',
  383. 'default' => $row['Default'],
  384. 'autoincrement' => $row['Extra'] === 'auto_increment',
  385. );
  386. }
  387. $this->free();
  388. return $res;
  389. }
  390. /**
  391. * Returns metadata for all indexes in a table.
  392. * @param string
  393. * @return array
  394. */
  395. public function getIndexes($table)
  396. {
  397. /*$table = $this->escape($table, dibi::TEXT);
  398. $this->query("
  399. SELECT *
  400. FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
  401. WHERE TABLE_NAME = $table AND TABLE_SCHEMA = DATABASE()
  402. AND REFERENCED_COLUMN_NAME IS NULL
  403. ");*/
  404. $this->query("SHOW INDEX FROM `$table`");
  405. $res = array();
  406. while ($row = $this->fetch(TRUE)) {
  407. $res[$row['Key_name']]['name'] = $row['Key_name'];
  408. $res[$row['Key_name']]['unique'] = !$row['Non_unique'];
  409. $res[$row['Key_name']]['primary'] = $row['Key_name'] === 'PRIMARY';
  410. $res[$row['Key_name']]['columns'][$row['Seq_in_index'] - 1] = $row['Column_name'];
  411. }
  412. $this->free();
  413. return array_values($res);
  414. }
  415. /**
  416. * Returns metadata for all foreign keys in a table.
  417. * @param string
  418. * @return array
  419. */
  420. public function getForeignKeys($table)
  421. {
  422. throw new NotImplementedException;
  423. }
  424. }