PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://github.com/indesigner/tests
PHP | 514 lines | 247 code | 107 blank | 160 comment | 36 complexity | 783ee8c8c6424e4a7d7574f8a39c184e 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.
  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 (MYSQL_*)
  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 DibiMySqlDriver 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 resource Connection resource */
  38. private $connection;
  39. /** @var resource 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('mysql')) {
  49. throw new DibiDriverException("PHP extension 'mysql' 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. if (isset($config['resource'])) {
  61. $this->connection = $config['resource'];
  62. } else {
  63. // default values
  64. if (!isset($config['username'])) $config['username'] = ini_get('mysql.default_user');
  65. if (!isset($config['password'])) $config['password'] = ini_get('mysql.default_password');
  66. if (!isset($config['host'])) {
  67. $host = ini_get('mysql.default_host');
  68. if ($host) {
  69. $config['host'] = $host;
  70. $config['port'] = ini_get('mysql.default_port');
  71. } else {
  72. if (!isset($config['socket'])) $config['socket'] = ini_get('mysql.default_socket');
  73. $config['host'] = NULL;
  74. }
  75. }
  76. if (empty($config['socket'])) {
  77. $host = $config['host'] . (empty($config['port']) ? '' : ':' . $config['port']);
  78. } else {
  79. $host = ':' . $config['socket'];
  80. }
  81. if (empty($config['persistent'])) {
  82. $this->connection = @mysql_connect($host, $config['username'], $config['password'], TRUE, $config['options']); // intentionally @
  83. } else {
  84. $this->connection = @mysql_pconnect($host, $config['username'], $config['password'], $config['options']); // intentionally @
  85. }
  86. }
  87. if (!is_resource($this->connection)) {
  88. throw new DibiDriverException(mysql_error(), mysql_errno());
  89. }
  90. if (isset($config['charset'])) {
  91. $ok = FALSE;
  92. if (function_exists('mysql_set_charset')) {
  93. // affects the character set used by mysql_real_escape_string() (was added in MySQL 5.0.7 and PHP 5.2.3)
  94. $ok = @mysql_set_charset($config['charset'], $this->connection); // intentionally @
  95. }
  96. if (!$ok) {
  97. $ok = @mysql_query("SET NAMES '$config[charset]'", $this->connection); // intentionally @
  98. if (!$ok) {
  99. throw new DibiDriverException(mysql_error($this->connection), mysql_errno($this->connection));
  100. }
  101. }
  102. }
  103. if (isset($config['database'])) {
  104. if (!@mysql_select_db($config['database'], $this->connection)) { // intentionally @
  105. throw new DibiDriverException(mysql_error($this->connection), mysql_errno($this->connection));
  106. }
  107. }
  108. if (isset($config['sqlmode'])) {
  109. if (!@mysql_query("SET sql_mode='$config[sqlmode]'", $this->connection)) { // intentionally @
  110. throw new DibiDriverException(mysql_error($this->connection), mysql_errno($this->connection));
  111. }
  112. }
  113. $this->buffered = empty($config['unbuffered']);
  114. }
  115. /**
  116. * Disconnects from a database.
  117. * @return void
  118. */
  119. public function disconnect()
  120. {
  121. mysql_close($this->connection);
  122. }
  123. /**
  124. * Executes the SQL query.
  125. * @param string SQL statement.
  126. * @return IDibiDriver|NULL
  127. * @throws DibiDriverException
  128. */
  129. public function query($sql)
  130. {
  131. if ($this->buffered) {
  132. $this->resultSet = @mysql_query($sql, $this->connection); // intentionally @
  133. } else {
  134. $this->resultSet = @mysql_unbuffered_query($sql, $this->connection); // intentionally @
  135. }
  136. if (mysql_errno($this->connection)) {
  137. throw new DibiDriverException(mysql_error($this->connection), mysql_errno($this->connection), $sql);
  138. }
  139. return is_resource($this->resultSet) ? clone $this : NULL;
  140. }
  141. /**
  142. * Retrieves information about the most recently executed query.
  143. * @return array
  144. */
  145. public function getInfo()
  146. {
  147. $res = array();
  148. preg_match_all('#(.+?): +(\d+) *#', mysql_info($this->connection), $matches, PREG_SET_ORDER);
  149. foreach ($matches as $m) {
  150. $res[$m[1]] = (int) $m[2];
  151. }
  152. return $res;
  153. }
  154. /**
  155. * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
  156. * @return int|FALSE number of rows or FALSE on error
  157. */
  158. public function getAffectedRows()
  159. {
  160. return mysql_affected_rows($this->connection);
  161. }
  162. /**
  163. * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
  164. * @return int|FALSE int on success or FALSE on failure
  165. */
  166. public function getInsertId($sequence)
  167. {
  168. return mysql_insert_id($this->connection);
  169. }
  170. /**
  171. * Begins a transaction (if supported).
  172. * @param string optional savepoint name
  173. * @return void
  174. * @throws DibiDriverException
  175. */
  176. public function begin($savepoint = NULL)
  177. {
  178. $this->query($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
  179. }
  180. /**
  181. * Commits statements in a transaction.
  182. * @param string optional savepoint name
  183. * @return void
  184. * @throws DibiDriverException
  185. */
  186. public function commit($savepoint = NULL)
  187. {
  188. $this->query($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
  189. }
  190. /**
  191. * Rollback changes in a transaction.
  192. * @param string optional savepoint name
  193. * @return void
  194. * @throws DibiDriverException
  195. */
  196. public function rollback($savepoint = NULL)
  197. {
  198. $this->query($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
  199. }
  200. /**
  201. * Returns the connection resource.
  202. * @return mixed
  203. */
  204. public function getResource()
  205. {
  206. return $this->connection;
  207. }
  208. /********************* SQL ****************d*g**/
  209. /**
  210. * Encodes data for use in a SQL statement.
  211. * @param mixed value
  212. * @param string type (dibi::TEXT, dibi::BOOL, ...)
  213. * @return string encoded value
  214. * @throws InvalidArgumentException
  215. */
  216. public function escape($value, $type)
  217. {
  218. switch ($type) {
  219. case dibi::TEXT:
  220. return "'" . mysql_real_escape_string($value, $this->connection) . "'";
  221. case dibi::BINARY:
  222. return "_binary'" . mysql_real_escape_string($value, $this->connection) . "'";
  223. case dibi::IDENTIFIER:
  224. // @see http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
  225. $value = str_replace('`', '``', $value);
  226. return '`' . str_replace('.', '`.`', $value) . '`';
  227. case dibi::BOOL:
  228. return $value ? 1 : 0;
  229. case dibi::DATE:
  230. return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
  231. case dibi::DATETIME:
  232. return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
  233. default:
  234. throw new InvalidArgumentException('Unsupported type.');
  235. }
  236. }
  237. /**
  238. * Decodes data from result set.
  239. * @param string value
  240. * @param string type (dibi::BINARY)
  241. * @return string decoded value
  242. * @throws InvalidArgumentException
  243. */
  244. public function unescape($value, $type)
  245. {
  246. if ($type === dibi::BINARY) {
  247. return $value;
  248. }
  249. throw new InvalidArgumentException('Unsupported type.');
  250. }
  251. /**
  252. * Injects LIMIT/OFFSET to the SQL query.
  253. * @param string &$sql The SQL query that will be modified.
  254. * @param int $limit
  255. * @param int $offset
  256. * @return void
  257. */
  258. public function applyLimit(&$sql, $limit, $offset)
  259. {
  260. if ($limit < 0 && $offset < 1) return;
  261. // see http://dev.mysql.com/doc/refman/5.0/en/select.html
  262. $sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
  263. . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
  264. }
  265. /********************* result set ****************d*g**/
  266. /**
  267. * Returns the number of rows in a result set.
  268. * @return int
  269. */
  270. public function getRowCount()
  271. {
  272. if (!$this->buffered) {
  273. throw new DibiDriverException('Row count is not available for unbuffered queries.');
  274. }
  275. return mysql_num_rows($this->resultSet);
  276. }
  277. /**
  278. * Fetches the row at current position and moves the internal cursor to the next position.
  279. * @param bool TRUE for associative array, FALSE for numeric
  280. * @return array array on success, nonarray if no next record
  281. * @internal
  282. */
  283. public function fetch($assoc)
  284. {
  285. return mysql_fetch_array($this->resultSet, $assoc ? MYSQL_ASSOC : MYSQL_NUM);
  286. }
  287. /**
  288. * Moves cursor position without fetching row.
  289. * @param int the 0-based cursor pos to seek to
  290. * @return boolean TRUE on success, FALSE if unable to seek to specified record
  291. * @throws DibiException
  292. */
  293. public function seek($row)
  294. {
  295. if (!$this->buffered) {
  296. throw new DibiDriverException('Cannot seek an unbuffered result set.');
  297. }
  298. return mysql_data_seek($this->resultSet, $row);
  299. }
  300. /**
  301. * Frees the resources allocated for this result set.
  302. * @return void
  303. */
  304. public function free()
  305. {
  306. mysql_free_result($this->resultSet);
  307. $this->resultSet = NULL;
  308. }
  309. /**
  310. * Returns metadata for all columns in a result set.
  311. * @return array
  312. */
  313. public function getColumnsMeta()
  314. {
  315. $count = mysql_num_fields($this->resultSet);
  316. $res = array();
  317. for ($i = 0; $i < $count; $i++) {
  318. $row = (array) mysql_fetch_field($this->resultSet, $i);
  319. $res[] = array(
  320. 'name' => $row['name'],
  321. 'table' => $row['table'],
  322. 'fullname' => $row['table'] ? $row['table'] . '.' . $row['name'] : $row['name'],
  323. 'nativetype' => strtoupper($row['type']),
  324. 'vendor' => $row,
  325. );
  326. }
  327. return $res;
  328. }
  329. /**
  330. * Returns the result set resource.
  331. * @return mixed
  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("SHOW FULL TABLES");
  345. $res = array();
  346. while ($row = $this->fetch(FALSE)) {
  347. $res[] = array(
  348. 'name' => $row[0],
  349. 'view' => isset($row[1]) && $row[1] === 'VIEW',
  350. );
  351. }
  352. $this->free();
  353. return $res;
  354. }
  355. /**
  356. * Returns metadata for all columns in a table.
  357. * @param string
  358. * @return array
  359. */
  360. public function getColumns($table)
  361. {
  362. $this->query("SHOW FULL COLUMNS FROM `$table`");
  363. $res = array();
  364. while ($row = $this->fetch(TRUE)) {
  365. $type = explode('(', $row['Type']);
  366. $res[] = array(
  367. 'name' => $row['Field'],
  368. 'table' => $table,
  369. 'nativetype' => strtoupper($type[0]),
  370. 'size' => isset($type[1]) ? (int) $type[1] : NULL,
  371. 'nullable' => $row['Null'] === 'YES',
  372. 'default' => $row['Default'],
  373. 'autoincrement' => $row['Extra'] === 'auto_increment',
  374. 'vendor' => $row,
  375. );
  376. }
  377. $this->free();
  378. return $res;
  379. }
  380. /**
  381. * Returns metadata for all indexes in a table.
  382. * @param string
  383. * @return array
  384. */
  385. public function getIndexes($table)
  386. {
  387. $this->query("SHOW INDEX FROM `$table`");
  388. $res = array();
  389. while ($row = $this->fetch(TRUE)) {
  390. $res[$row['Key_name']]['name'] = $row['Key_name'];
  391. $res[$row['Key_name']]['unique'] = !$row['Non_unique'];
  392. $res[$row['Key_name']]['primary'] = $row['Key_name'] === 'PRIMARY';
  393. $res[$row['Key_name']]['columns'][$row['Seq_in_index'] - 1] = $row['Column_name'];
  394. }
  395. $this->free();
  396. return array_values($res);
  397. }
  398. /**
  399. * Returns metadata for all foreign keys in a table.
  400. * @param string
  401. * @return array
  402. */
  403. public function getForeignKeys($table)
  404. {
  405. throw new NotImplementedException;
  406. }
  407. }