PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/database/classes/kohana/database/mysql.php

https://bitbucket.org/seyar/kinda.local
PHP | 379 lines | 277 code | 49 blank | 53 comment | 24 complexity | bd93253947a8b345ab3a51945d6c8b1d MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. /**
  3. * MySQL database connection.
  4. *
  5. * @package Kohana/Database
  6. * @category Drivers
  7. * @author Kohana Team
  8. * @copyright (c) 2008-2009 Kohana Team
  9. * @license http://kohanaphp.com/license
  10. */
  11. class Kohana_Database_MySQL extends Database {
  12. // Database in use by each connection
  13. protected static $_current_databases = array();
  14. // Use SET NAMES to set the character set
  15. protected static $_set_names;
  16. // Identifier for this connection within the PHP driver
  17. protected $_connection_id;
  18. // MySQL uses a backtick for identifiers
  19. protected $_identifier = '`';
  20. public function connect()
  21. {
  22. if ($this->_connection)
  23. return;
  24. if (Database_MySQL::$_set_names === NULL)
  25. {
  26. // Determine if we can use mysql_set_charset(), which is only
  27. // available on PHP 5.2.3+ when compiled against MySQL 5.0+
  28. Database_MySQL::$_set_names = ! function_exists('mysql_set_charset');
  29. }
  30. // Extract the connection parameters, adding required variabels
  31. extract($this->_config['connection'] + array(
  32. 'database' => '',
  33. 'hostname' => '',
  34. 'username' => '',
  35. 'password' => '',
  36. 'persistent' => FALSE,
  37. ));
  38. // Prevent this information from showing up in traces
  39. unset($this->_config['connection']['username'], $this->_config['connection']['password']);
  40. try
  41. {
  42. if ($persistent)
  43. {
  44. // Create a persistent connection
  45. $this->_connection = mysql_pconnect($hostname, $username, $password);
  46. }
  47. else
  48. {
  49. // Create a connection and force it to be a new link
  50. $this->_connection = mysql_connect($hostname, $username, $password, TRUE);
  51. }
  52. }
  53. catch (ErrorException $e)
  54. {
  55. // No connection exists
  56. $this->_connection = NULL;
  57. throw new Database_Exception(':error', array(
  58. ':error' => mysql_error(),
  59. ),
  60. mysql_errno());
  61. }
  62. // \xFF is a better delimiter, but the PHP driver uses underscore
  63. $this->_connection_id = sha1($hostname.'_'.$username.'_'.$password);
  64. $this->_select_db($database);
  65. if ( ! empty($this->_config['charset']))
  66. {
  67. // Set the character set
  68. $this->set_charset($this->_config['charset']);
  69. }
  70. }
  71. /**
  72. * Select the database
  73. *
  74. * @param string Database
  75. * @return void
  76. */
  77. protected function _select_db($database)
  78. {
  79. if ( ! mysql_select_db($database, $this->_connection))
  80. {
  81. // Unable to select database
  82. throw new Database_Exception(':error',
  83. array(':error' => mysql_error($this->_connection)),
  84. mysql_errno($this->_connection));
  85. }
  86. Database_MySQL::$_current_databases[$this->_connection_id] = $database;
  87. }
  88. public function disconnect()
  89. {
  90. try
  91. {
  92. // Database is assumed disconnected
  93. $status = TRUE;
  94. if (is_resource($this->_connection))
  95. {
  96. if ($status = mysql_close($this->_connection))
  97. {
  98. // Clear the connection
  99. $this->_connection = NULL;
  100. }
  101. }
  102. }
  103. catch (Exception $e)
  104. {
  105. // Database is probably not disconnected
  106. $status = ! is_resource($this->_connection);
  107. }
  108. return $status;
  109. }
  110. public function set_charset($charset)
  111. {
  112. // Make sure the database is connected
  113. $this->_connection or $this->connect();
  114. if (Database_MySQL::$_set_names === TRUE)
  115. {
  116. // PHP is compiled against MySQL 4.x
  117. $status = (bool) mysql_query('SET NAMES '.$this->quote($charset), $this->_connection);
  118. }
  119. else
  120. {
  121. // PHP is compiled against MySQL 5.x
  122. $status = mysql_set_charset($charset, $this->_connection);
  123. }
  124. if ($status === FALSE)
  125. {
  126. throw new Database_Exception(':error',
  127. array(':error' => mysql_error($this->_connection)),
  128. mysql_errno($this->_connection));
  129. }
  130. }
  131. public function query($type, $sql, $as_object = FALSE, array $params = NULL)
  132. {
  133. // Make sure the database is connected
  134. $this->_connection or $this->connect();
  135. if ( ! empty($this->_config['profiling']))
  136. {
  137. // Benchmark this query for the current instance
  138. $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
  139. }
  140. if ( ! empty($this->_config['connection']['persistent']) AND $this->_config['connection']['database'] !== Database_MySQL::$_current_databases[$this->_connection_id])
  141. {
  142. // Select database on persistent connections
  143. $this->_select_db($this->_config['connection']['database']);
  144. }
  145. // Execute the query
  146. if (($result = mysql_query($sql, $this->_connection)) === FALSE)
  147. {
  148. if (isset($benchmark))
  149. {
  150. // This benchmark is worthless
  151. Profiler::delete($benchmark);
  152. }
  153. throw new Database_Exception(':error [ :query ]',
  154. array(':error' => mysql_error($this->_connection), ':query' => $sql),
  155. mysql_errno($this->_connection));
  156. }
  157. if (isset($benchmark))
  158. {
  159. Profiler::stop($benchmark);
  160. }
  161. // Set the last query
  162. $this->last_query = $sql;
  163. if ($type === Database::SELECT)
  164. {
  165. // Return an iterator of results
  166. return new Database_MySQL_Result($result, $sql, $as_object, $params);
  167. }
  168. elseif ($type === Database::INSERT)
  169. {
  170. // Return a list of insert id and rows created
  171. return array(
  172. mysql_insert_id($this->_connection),
  173. mysql_affected_rows($this->_connection),
  174. );
  175. }
  176. else
  177. {
  178. // Return the number of rows affected
  179. return mysql_affected_rows($this->_connection);
  180. }
  181. }
  182. public function datatype($type)
  183. {
  184. static $types = array
  185. (
  186. 'blob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '65535'),
  187. 'bool' => array('type' => 'bool'),
  188. 'bigint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '18446744073709551615'),
  189. 'datetime' => array('type' => 'string'),
  190. 'decimal unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'),
  191. 'double' => array('type' => 'float'),
  192. 'double precision unsigned' => array('type' => 'float', 'min' => '0'),
  193. 'double unsigned' => array('type' => 'float', 'min' => '0'),
  194. 'enum' => array('type' => 'string'),
  195. 'fixed' => array('type' => 'float', 'exact' => TRUE),
  196. 'fixed unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'),
  197. 'float unsigned' => array('type' => 'float', 'min' => '0'),
  198. 'int unsigned' => array('type' => 'int', 'min' => '0', 'max' => '4294967295'),
  199. 'integer unsigned' => array('type' => 'int', 'min' => '0', 'max' => '4294967295'),
  200. 'longblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '4294967295'),
  201. 'longtext' => array('type' => 'string', 'character_maximum_length' => '4294967295'),
  202. 'mediumblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '16777215'),
  203. 'mediumint' => array('type' => 'int', 'min' => '-8388608', 'max' => '8388607'),
  204. 'mediumint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '16777215'),
  205. 'mediumtext' => array('type' => 'string', 'character_maximum_length' => '16777215'),
  206. 'national varchar' => array('type' => 'string'),
  207. 'numeric unsigned' => array('type' => 'float', 'exact' => TRUE, 'min' => '0'),
  208. 'nvarchar' => array('type' => 'string'),
  209. 'point' => array('type' => 'string', 'binary' => TRUE),
  210. 'real unsigned' => array('type' => 'float', 'min' => '0'),
  211. 'set' => array('type' => 'string'),
  212. 'smallint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '65535'),
  213. 'text' => array('type' => 'string', 'character_maximum_length' => '65535'),
  214. 'tinyblob' => array('type' => 'string', 'binary' => TRUE, 'character_maximum_length' => '255'),
  215. 'tinyint' => array('type' => 'int', 'min' => '-128', 'max' => '127'),
  216. 'tinyint unsigned' => array('type' => 'int', 'min' => '0', 'max' => '255'),
  217. 'tinytext' => array('type' => 'string', 'character_maximum_length' => '255'),
  218. 'year' => array('type' => 'string'),
  219. );
  220. $type = str_replace(' zerofill', '', $type);
  221. if (isset($types[$type]))
  222. return $types[$type];
  223. return parent::datatype($type);
  224. }
  225. public function list_tables($like = NULL)
  226. {
  227. if (is_string($like))
  228. {
  229. // Search for table names
  230. $result = $this->query(Database::SELECT, 'SHOW TABLES LIKE '.$this->quote($like), FALSE);
  231. }
  232. else
  233. {
  234. // Find all table names
  235. $result = $this->query(Database::SELECT, 'SHOW TABLES', FALSE);
  236. }
  237. $tables = array();
  238. foreach ($result as $row)
  239. {
  240. $tables[] = reset($row);
  241. }
  242. return $tables;
  243. }
  244. public function list_columns($table, $like = NULL, $add_prefix = TRUE)
  245. {
  246. // Quote the table name
  247. $table = ($add_prefix === TRUE) ? $this->quote_table($table) : $table;
  248. if (is_string($like))
  249. {
  250. // Search for column names
  251. $result = $this->query(Database::SELECT, 'SHOW FULL COLUMNS FROM '.$table.' LIKE '.$this->quote($like), FALSE);
  252. }
  253. else
  254. {
  255. // Find all column names
  256. $result = $this->query(Database::SELECT, 'SHOW FULL COLUMNS FROM '.$table, FALSE);
  257. }
  258. $count = 0;
  259. $columns = array();
  260. foreach ($result as $row)
  261. {
  262. list($type, $length) = $this->_parse_type($row['Type']);
  263. $column = $this->datatype($type);
  264. $column['column_name'] = $row['Field'];
  265. $column['column_default'] = $row['Default'];
  266. $column['data_type'] = $type;
  267. $column['is_nullable'] = ($row['Null'] == 'YES');
  268. $column['ordinal_position'] = ++$count;
  269. switch ($column['type'])
  270. {
  271. case 'float':
  272. if (isset($length))
  273. {
  274. list($column['numeric_precision'], $column['numeric_scale']) = explode(',', $length);
  275. }
  276. break;
  277. case 'int':
  278. if (isset($length))
  279. {
  280. // MySQL attribute
  281. $column['display'] = $length;
  282. }
  283. break;
  284. case 'string':
  285. switch ($column['data_type'])
  286. {
  287. case 'binary':
  288. case 'varbinary':
  289. $column['character_maximum_length'] = $length;
  290. break;
  291. case 'char':
  292. case 'varchar':
  293. $column['character_maximum_length'] = $length;
  294. case 'text':
  295. case 'tinytext':
  296. case 'mediumtext':
  297. case 'longtext':
  298. $column['collation_name'] = $row['Collation'];
  299. break;
  300. case 'enum':
  301. case 'set':
  302. $column['collation_name'] = $row['Collation'];
  303. $column['options'] = explode('\',\'', substr($length, 1, -1));
  304. break;
  305. }
  306. break;
  307. }
  308. // MySQL attributes
  309. $column['comment'] = $row['Comment'];
  310. $column['extra'] = $row['Extra'];
  311. $column['key'] = $row['Key'];
  312. $column['privileges'] = $row['Privileges'];
  313. $columns[$row['Field']] = $column;
  314. }
  315. return $columns;
  316. }
  317. public function escape($value)
  318. {
  319. // Make sure the database is connected
  320. $this->_connection or $this->connect();
  321. if (($value = mysql_real_escape_string( (string) $value, $this->_connection)) === FALSE)
  322. {
  323. throw new Database_Exception(':error',
  324. array(':error' => mysql_errno($this->_connection)),
  325. mysql_error($this->_connection));
  326. }
  327. // SQL standard is to use single-quotes for all values
  328. return "'$value'";
  329. }
  330. } // End Database_MySQL