MySql.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\data\source\database\adapter;
  9. use PDO;
  10. use PDOException;
  11. /**
  12. * Extends the `Database` class to implement the necessary SQL-formatting and resultset-fetching
  13. * features for working with MySQL databases.
  14. *
  15. * For more information on configuring the database connection, see the `__construct()` method.
  16. *
  17. * @see lithium\data\source\database\adapter\MySql::__construct()
  18. */
  19. class MySql extends \lithium\data\source\Database {
  20. /**
  21. * MySQL column type definitions.
  22. *
  23. * @var array
  24. */
  25. protected $_columns = array(
  26. 'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
  27. 'string' => array('name' => 'varchar', 'length' => 255),
  28. 'text' => array('name' => 'text'),
  29. 'integer' => array('name' => 'int', 'length' => 11, 'formatter' => 'intval'),
  30. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  31. 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  32. 'timestamp' => array(
  33. 'name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'
  34. ),
  35. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  36. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  37. 'binary' => array('name' => 'blob'),
  38. 'boolean' => array('name' => 'tinyint', 'length' => 1)
  39. );
  40. /**
  41. * Pair of opening and closing quote characters used for quoting identifiers in queries.
  42. *
  43. * @var array
  44. */
  45. protected $_quotes = array('`', '`');
  46. /**
  47. * MySQL-specific value denoting whether or not table aliases should be used in DELETE and
  48. * UPDATE queries.
  49. *
  50. * @var boolean
  51. */
  52. protected $_useAlias = true;
  53. /**
  54. * Constructs the MySQL adapter and sets the default port to 3306.
  55. *
  56. * @see lithium\data\source\Database::__construct()
  57. * @see lithium\data\Source::__construct()
  58. * @see lithium\data\Connections::add()
  59. * @param array $config Configuration options for this class. For additional configuration,
  60. * see `lithium\data\source\Database` and `lithium\data\Source`. Available options
  61. * defined by this class:
  62. * - `'database'`: The name of the database to connect to. Defaults to 'lithium'.
  63. * - `'host'`: The IP or machine name where MySQL is running, followed by a colon,
  64. * followed by a port number or socket. Defaults to `'localhost:3306'`.
  65. * - `'persistent'`: If a persistent connection (if available) should be made.
  66. * Defaults to true.
  67. *
  68. * Typically, these parameters are set in `Connections::add()`, when adding the adapter to the
  69. * list of active connections.
  70. */
  71. public function __construct(array $config = array()) {
  72. $defaults = array('host' => 'localhost:3306', 'encoding' => null);
  73. parent::__construct($config + $defaults);
  74. }
  75. /**
  76. * Check for required PHP extension, or supported database feature.
  77. *
  78. * @param string $feature Test for support for a specific feature, i.e. `"transactions"` or
  79. * `"arrays"`.
  80. * @return boolean Returns `true` if the particular feature (or if MySQL) support is enabled,
  81. * otherwise `false`.
  82. */
  83. public static function enabled($feature = null) {
  84. if (!$feature) {
  85. return extension_loaded('pdo_mysql');
  86. }
  87. $features = array(
  88. 'arrays' => false,
  89. 'transactions' => false,
  90. 'booleans' => true,
  91. 'relationships' => true
  92. );
  93. return isset($features[$feature]) ? $features[$feature] : null;
  94. }
  95. /**
  96. * Connects to the database using the options provided to the class constructor.
  97. *
  98. * @return boolean Returns `true` if a database connection could be established, otherwise
  99. * `false`.
  100. */
  101. public function connect() {
  102. if (!$this->_config['dsn']) {
  103. $host = $this->_config['host'];
  104. list($host, $port) = explode(':', $host) + array(1 => "3306");
  105. $dsn = "mysql:host=%s;port=%s;dbname=%s";
  106. $this->_config['dsn'] = sprintf($dsn, $host, $port, $this->_config['database']);
  107. }
  108. if (!parent::connect()) {
  109. return false;
  110. }
  111. $info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  112. $this->_useAlias = (boolean) version_compare($info, "4.1", ">=");
  113. return true;
  114. }
  115. /**
  116. * Returns the list of tables in the currently-connected database.
  117. *
  118. * @param string $model The fully-name-spaced class name of the model object making the request.
  119. * @return array Returns an array of sources to which models can connect.
  120. * @filter This method can be filtered.
  121. */
  122. public function sources($model = null) {
  123. $_config = $this->_config;
  124. $params = compact('model');
  125. return $this->_filter(__METHOD__, $params, function($self, $params) use ($_config) {
  126. $name = $self->name($_config['database']);
  127. if (!$result = $self->invokeMethod('_execute', array("SHOW TABLES FROM {$name};"))) {
  128. return null;
  129. }
  130. $sources = array();
  131. while ($data = $result->next()) {
  132. $sources[] = array_shift($data);
  133. }
  134. return $sources;
  135. });
  136. }
  137. /**
  138. * Gets the column schema for a given MySQL table.
  139. *
  140. * @param mixed $entity Specifies the table name for which the schema should be returned, or
  141. * the class name of the model object requesting the schema, in which case the model
  142. * class will be queried for the correct table name.
  143. * @param array $fields Any schema data pre-defined by the model.
  144. * @param array $meta
  145. * @return array Returns an associative array describing the given table's schema, where the
  146. * array keys are the available fields, and the values are arrays describing each
  147. * field, containing the following keys:
  148. * - `'type'`: The field type name
  149. * @filter This method can be filtered.
  150. */
  151. public function describe($entity, $fields = array(), array $meta = array()) {
  152. $params = compact('entity', 'meta', 'fields');
  153. return $this->_filter(__METHOD__, $params, function($self, $params) {
  154. extract($params);
  155. if ($fields) {
  156. return $self->invokeMethod('_instance', array('schema', compact('fields')));
  157. }
  158. $name = $self->invokeMethod('_entityName', array($entity, array('quoted' => true)));
  159. $columns = $self->read("DESCRIBE {$name}", array('return' => 'array', 'schema' => array(
  160. 'field', 'type', 'null', 'key', 'default', 'extra'
  161. )));
  162. $fields = array();
  163. foreach ($columns as $column) {
  164. $match = $self->invokeMethod('_column', array($column['type']));
  165. $fields[$column['field']] = $match + array(
  166. 'null' => ($column['null'] === 'YES' ? true : false),
  167. 'default' => $column['default']
  168. );
  169. }
  170. return $self->invokeMethod('_instance', array('schema', compact('fields')));
  171. });
  172. }
  173. /**
  174. * Gets or sets the encoding for the connection.
  175. *
  176. * @param $encoding
  177. * @return mixed If setting the encoding; returns true on success, else false.
  178. * When getting, returns the encoding.
  179. */
  180. public function encoding($encoding = null) {
  181. $encodingMap = array('UTF-8' => 'utf8');
  182. if (empty($encoding)) {
  183. $query = $this->connection->query("SHOW VARIABLES LIKE 'character_set_client'");
  184. $encoding = $query->fetchColumn(1);
  185. return ($key = array_search($encoding, $encodingMap)) ? $key : $encoding;
  186. }
  187. $encoding = isset($encodingMap[$encoding]) ? $encodingMap[$encoding] : $encoding;
  188. try {
  189. $this->connection->exec("SET NAMES '{$encoding}'");
  190. return true;
  191. } catch (PDOException $e) {
  192. return false;
  193. }
  194. }
  195. /**
  196. * Converts a given value into the proper type based on a given schema definition.
  197. *
  198. * @see lithium\data\source\Database::schema()
  199. * @param mixed $value The value to be converted. Arrays will be recursively converted.
  200. * @param array $schema Formatted array from `lithium\data\source\Database::schema()`
  201. * @return mixed Value with converted type.
  202. */
  203. public function value($value, array $schema = array()) {
  204. if (($result = parent::value($value, $schema)) !== null) {
  205. return $result;
  206. }
  207. return $this->connection->quote((string) $value);
  208. }
  209. /**
  210. * Retrieves database error message and error code.
  211. *
  212. * @return array
  213. */
  214. public function error() {
  215. if ($error = $this->connection->errorInfo()) {
  216. return array($error[1], $error[2]);
  217. }
  218. }
  219. public function alias($alias, $context) {
  220. if ($context->type() === 'update' || $context->type() === 'delete') {
  221. return;
  222. }
  223. return parent::alias($alias, $context);
  224. }
  225. /**
  226. * @todo Eventually, this will need to rewrite aliases for DELETE and UPDATE queries, same with
  227. * order().
  228. * @param string $conditions
  229. * @param string $context
  230. * @param array $options
  231. * @return void
  232. */
  233. public function conditions($conditions, $context, array $options = array()) {
  234. return parent::conditions($conditions, $context, $options);
  235. }
  236. /**
  237. * Execute a given query.
  238. *
  239. * @see lithium\data\source\Database::renderCommand()
  240. * @param string $sql The sql string to execute
  241. * @param array $options Available options:
  242. * - 'buffered': If set to `false` uses mysql_unbuffered_query which
  243. * sends the SQL query query to MySQL without automatically fetching and buffering the
  244. * result rows as `mysql_query()` does (for less memory usage).
  245. * @return resource Returns the result resource handle if the query is successful.
  246. * @filter
  247. */
  248. protected function _execute($sql, array $options = array()) {
  249. $defaults = array('buffered' => true);
  250. $options += $defaults;
  251. $this->connection->exec("USE `{$this->_config['database']}`");
  252. $conn = $this->connection;
  253. $params = compact('sql', 'options');
  254. return $this->_filter(__METHOD__, $params, function($self, $params) use ($conn) {
  255. $sql = $params['sql'];
  256. $options = $params['options'];
  257. $conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, $options['buffered']);
  258. try {
  259. $resource = $conn->query($sql);
  260. } catch(PDOException $e) {
  261. $self->invokeMethod('_error', array($sql));
  262. };
  263. return $self->invokeMethod('_instance', array('result', compact('resource')));
  264. });
  265. }
  266. /**
  267. * Gets the last auto-generated ID from the query that inserted a new record.
  268. *
  269. * @param object $query The `Query` object associated with the query which generated
  270. * @return mixed Returns the last inserted ID key for an auto-increment column or a column
  271. * bound to a sequence.
  272. */
  273. protected function _insertId($query) {
  274. $resource = $this->_execute('SELECT LAST_INSERT_ID() AS insertID');
  275. list($id) = $resource->next();
  276. return ($id && $id !== '0') ? $id : null;
  277. }
  278. /**
  279. * Converts database-layer column types to basic types.
  280. *
  281. * @param string $real Real database-layer column type (i.e. `"varchar(255)"`)
  282. * @return array Column type (i.e. "string") plus 'length' when appropriate.
  283. */
  284. protected function _column($real) {
  285. if (is_array($real)) {
  286. return $real['type'] . (isset($real['length']) ? "({$real['length']})" : '');
  287. }
  288. if (!preg_match('/(?P<type>\w+)(?:\((?P<length>[\d,]+)\))?/', $real, $column)) {
  289. return $real;
  290. }
  291. $column = array_intersect_key($column, array('type' => null, 'length' => null));
  292. if (isset($column['length']) && $column['length']) {
  293. $length = explode(',', $column['length']) + array(null, null);
  294. $column['length'] = $length[0] ? intval($length[0]) : null;
  295. $length[1] ? $column['precision'] = intval($length[1]) : null;
  296. }
  297. switch (true) {
  298. case in_array($column['type'], array('date', 'time', 'datetime', 'timestamp')):
  299. return $column;
  300. case ($column['type'] === 'tinyint' && $column['length'] == '1'):
  301. case ($column['type'] === 'boolean'):
  302. return array('type' => 'boolean');
  303. break;
  304. case (strpos($column['type'], 'int') !== false):
  305. $column['type'] = 'integer';
  306. break;
  307. case (strpos($column['type'], 'char') !== false || $column['type'] === 'tinytext'):
  308. $column['type'] = 'string';
  309. break;
  310. case (strpos($column['type'], 'text') !== false):
  311. $column['type'] = 'text';
  312. break;
  313. case (strpos($column['type'], 'blob') !== false || $column['type'] === 'binary'):
  314. $column['type'] = 'binary';
  315. break;
  316. case preg_match('/float|double|decimal/', $column['type']):
  317. $column['type'] = 'float';
  318. break;
  319. default:
  320. $column['type'] = 'text';
  321. break;
  322. }
  323. return $column;
  324. }
  325. }
  326. ?>