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

/treeview-master/libs/dibi/drivers/mysqli.php

https://github.com/indesigner/tests
PHP | 524 lines | 242 code | 105 blank | 177 comment | 31 complexity | 67c6e9c9f18821e9d4fc33818a6c9680 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0
  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
  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
  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. $ok = @mysqli_query($this->connection, "SET NAMES '$config[charset]'"); // intentionally @
  93. if (!$ok) {
  94. throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection));
  95. }
  96. }
  97. }
  98. if (isset($config['sqlmode'])) {
  99. if (!@mysqli_query($this->connection, "SET sql_mode='$config[sqlmode]'")) { // intentionally @
  100. throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection));
  101. }
  102. }
  103. $this->buffered = empty($config['unbuffered']);
  104. }
  105. /**
  106. * Disconnects from a database.
  107. * @return void
  108. */
  109. public function disconnect()
  110. {
  111. mysqli_close($this->connection);
  112. }
  113. /**
  114. * Executes the SQL query.
  115. * @param string SQL statement.
  116. * @return IDibiDriver|NULL
  117. * @throws DibiDriverException
  118. */
  119. public function query($sql)
  120. {
  121. $this->resultSet = @mysqli_query($this->connection, $sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT); // intentionally @
  122. if (mysqli_errno($this->connection)) {
  123. throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection), $sql);
  124. }
  125. return is_object($this->resultSet) ? clone $this : NULL;
  126. }
  127. /**
  128. * Retrieves information about the most recently executed query.
  129. * @return array
  130. */
  131. public function getInfo()
  132. {
  133. $res = array();
  134. preg_match_all('#(.+?): +(\d+) *#', mysqli_info($this->connection), $matches, PREG_SET_ORDER);
  135. foreach ($matches as $m) {
  136. $res[$m[1]] = (int) $m[2];
  137. }
  138. return $res;
  139. }
  140. /**
  141. * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
  142. * @return int|FALSE number of rows or FALSE on error
  143. */
  144. public function getAffectedRows()
  145. {
  146. return mysqli_affected_rows($this->connection);
  147. }
  148. /**
  149. * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
  150. * @return int|FALSE int on success or FALSE on failure
  151. */
  152. public function getInsertId($sequence)
  153. {
  154. return mysqli_insert_id($this->connection);
  155. }
  156. /**
  157. * Begins a transaction (if supported).
  158. * @param string optional savepoint name
  159. * @return void
  160. * @throws DibiDriverException
  161. */
  162. public function begin($savepoint = NULL)
  163. {
  164. $this->query($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
  165. }
  166. /**
  167. * Commits statements in a transaction.
  168. * @param string optional savepoint name
  169. * @return void
  170. * @throws DibiDriverException
  171. */
  172. public function commit($savepoint = NULL)
  173. {
  174. $this->query($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
  175. }
  176. /**
  177. * Rollback changes in a transaction.
  178. * @param string optional savepoint name
  179. * @return void
  180. * @throws DibiDriverException
  181. */
  182. public function rollback($savepoint = NULL)
  183. {
  184. $this->query($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
  185. }
  186. /**
  187. * Returns the connection resource.
  188. * @return mysqli
  189. */
  190. public function getResource()
  191. {
  192. return $this->connection;
  193. }
  194. /********************* SQL ****************d*g**/
  195. /**
  196. * Encodes data for use in a SQL statement.
  197. * @param mixed value
  198. * @param string type (dibi::TEXT, dibi::BOOL, ...)
  199. * @return string encoded value
  200. * @throws InvalidArgumentException
  201. */
  202. public function escape($value, $type)
  203. {
  204. switch ($type) {
  205. case dibi::TEXT:
  206. return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
  207. case dibi::BINARY:
  208. return "_binary'" . mysqli_real_escape_string($this->connection, $value) . "'";
  209. case dibi::IDENTIFIER:
  210. $value = str_replace('`', '``', $value);
  211. return '`' . str_replace('.', '`.`', $value) . '`';
  212. case dibi::BOOL:
  213. return $value ? 1 : 0;
  214. case dibi::DATE:
  215. return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
  216. case dibi::DATETIME:
  217. return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
  218. default:
  219. throw new InvalidArgumentException('Unsupported type.');
  220. }
  221. }
  222. /**
  223. * Decodes data from result set.
  224. * @param string value
  225. * @param string type (dibi::BINARY)
  226. * @return string decoded value
  227. * @throws InvalidArgumentException
  228. */
  229. public function unescape($value, $type)
  230. {
  231. if ($type === dibi::BINARY) {
  232. return $value;
  233. }
  234. throw new InvalidArgumentException('Unsupported type.');
  235. }
  236. /**
  237. * Injects LIMIT/OFFSET to the SQL query.
  238. * @param string &$sql The SQL query that will be modified.
  239. * @param int $limit
  240. * @param int $offset
  241. * @return void
  242. */
  243. public function applyLimit(&$sql, $limit, $offset)
  244. {
  245. if ($limit < 0 && $offset < 1) return;
  246. // see http://dev.mysql.com/doc/refman/5.0/en/select.html
  247. $sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
  248. . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
  249. }
  250. /********************* result set ****************d*g**/
  251. /**
  252. * Returns the number of rows in a result set.
  253. * @return int
  254. */
  255. public function getRowCount()
  256. {
  257. if (!$this->buffered) {
  258. throw new DibiDriverException('Row count is not available for unbuffered queries.');
  259. }
  260. return mysqli_num_rows($this->resultSet);
  261. }
  262. /**
  263. * Fetches the row at current position and moves the internal cursor to the next position.
  264. * @param bool TRUE for associative array, FALSE for numeric
  265. * @return array array on success, nonarray if no next record
  266. * @internal
  267. */
  268. public function fetch($assoc)
  269. {
  270. return mysqli_fetch_array($this->resultSet, $assoc ? MYSQLI_ASSOC : MYSQLI_NUM);
  271. }
  272. /**
  273. * Moves cursor position without fetching row.
  274. * @param int the 0-based cursor pos to seek to
  275. * @return boolean TRUE on success, FALSE if unable to seek to specified record
  276. * @throws DibiException
  277. */
  278. public function seek($row)
  279. {
  280. if (!$this->buffered) {
  281. throw new DibiDriverException('Cannot seek an unbuffered result set.');
  282. }
  283. return mysqli_data_seek($this->resultSet, $row);
  284. }
  285. /**
  286. * Frees the resources allocated for this result set.
  287. * @return void
  288. */
  289. public function free()
  290. {
  291. mysqli_free_result($this->resultSet);
  292. $this->resultSet = NULL;
  293. }
  294. /**
  295. * Returns metadata for all columns in a result set.
  296. * @return array
  297. */
  298. public function getColumnsMeta()
  299. {
  300. static $types;
  301. if (empty($types)) {
  302. $consts = get_defined_constants(TRUE);
  303. foreach ($consts['mysqli'] as $key => $value) {
  304. if (strncmp($key, 'MYSQLI_TYPE_', 12) === 0) {
  305. $types[$value] = substr($key, 12);
  306. }
  307. }
  308. }
  309. $count = mysqli_num_fields($this->resultSet);
  310. $res = array();
  311. for ($i = 0; $i < $count; $i++) {
  312. $row = (array) mysqli_fetch_field_direct($this->resultSet, $i);
  313. $res[] = array(
  314. 'name' => $row['name'],
  315. 'table' => $row['orgtable'],
  316. 'fullname' => $row['table'] ? $row['table'] . '.' . $row['name'] : $row['name'],
  317. 'nativetype' => $types[$row['type']],
  318. 'vendor' => $row,
  319. );
  320. }
  321. return $res;
  322. }
  323. /**
  324. * Returns the result set resource.
  325. * @return mysqli_result
  326. */
  327. public function getResultResource()
  328. {
  329. return $this->resultSet;
  330. }
  331. /********************* reflection ****************d*g**/
  332. /**
  333. * Returns list of tables.
  334. * @return array
  335. */
  336. public function getTables()
  337. {
  338. /*$this->query("
  339. SELECT TABLE_NAME as name, TABLE_TYPE = 'VIEW' as view
  340. FROM INFORMATION_SCHEMA.TABLES
  341. WHERE TABLE_SCHEMA = DATABASE()
  342. ");*/
  343. $this->query("SHOW FULL TABLES");
  344. $res = array();
  345. while ($row = $this->fetch(FALSE)) {
  346. $res[] = array(
  347. 'name' => $row[0],
  348. 'view' => isset($row[1]) && $row[1] === 'VIEW',
  349. );
  350. }
  351. $this->free();
  352. return $res;
  353. }
  354. /**
  355. * Returns metadata for all columns in a table.
  356. * @param string
  357. * @return array
  358. */
  359. public function getColumns($table)
  360. {
  361. /*$table = $this->escape($table, dibi::TEXT);
  362. $this->query("
  363. SELECT *
  364. FROM INFORMATION_SCHEMA.COLUMNS
  365. WHERE TABLE_NAME = $table AND TABLE_SCHEMA = DATABASE()
  366. ");*/
  367. $this->query("SHOW FULL COLUMNS FROM `$table`");
  368. $res = array();
  369. while ($row = $this->fetch(TRUE)) {
  370. $type = explode('(', $row['Type']);
  371. $res[] = array(
  372. 'name' => $row['Field'],
  373. 'table' => $table,
  374. 'nativetype' => strtoupper($type[0]),
  375. 'size' => isset($type[1]) ? (int) $type[1] : NULL,
  376. 'nullable' => $row['Null'] === 'YES',
  377. 'default' => $row['Default'],
  378. 'autoincrement' => $row['Extra'] === 'auto_increment',
  379. 'vendor' => $row,
  380. );
  381. }
  382. $this->free();
  383. return $res;
  384. }
  385. /**
  386. * Returns metadata for all indexes in a table.
  387. * @param string
  388. * @return array
  389. */
  390. public function getIndexes($table)
  391. {
  392. /*$table = $this->escape($table, dibi::TEXT);
  393. $this->query("
  394. SELECT *
  395. FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
  396. WHERE TABLE_NAME = $table AND TABLE_SCHEMA = DATABASE()
  397. AND REFERENCED_COLUMN_NAME IS NULL
  398. ");*/
  399. $this->query("SHOW INDEX FROM `$table`");
  400. $res = array();
  401. while ($row = $this->fetch(TRUE)) {
  402. $res[$row['Key_name']]['name'] = $row['Key_name'];
  403. $res[$row['Key_name']]['unique'] = !$row['Non_unique'];
  404. $res[$row['Key_name']]['primary'] = $row['Key_name'] === 'PRIMARY';
  405. $res[$row['Key_name']]['columns'][$row['Seq_in_index'] - 1] = $row['Column_name'];
  406. }
  407. $this->free();
  408. return array_values($res);
  409. }
  410. /**
  411. * Returns metadata for all foreign keys in a table.
  412. * @param string
  413. * @return array
  414. */
  415. public function getForeignKeys($table)
  416. {
  417. throw new NotImplementedException;
  418. }
  419. }