PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/www/libs/dibi/drivers/mysqli.php

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