PageRenderTime 43ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/www/libs/dibi/drivers/mysql.php

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