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

/shopaholic/lib/dibi/drivers/mysql.php

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