7
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
10
* Licensed under The MIT License
11
* Redistributions of files must retain the above copyright notice.
13
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
14
* @link http://cakephp.org CakePHP(tm) Project
16
* @subpackage cake.cake.libs.model.datasources.dbo
17
* @since CakePHP(tm) v 0.10.5.1790
18
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
22
* Provides common base for MySQL & MySQLi connections
25
* @subpackage cake.cake.libs.model.datasources.dbo
27
class DboMysqlBase extends DboSource {
30
* Description property.
34
var $description = "MySQL DBO Base Driver";
41
var $startQuote = "`";
51
* use alias for update and delete. Set to true if version >= 4.1
56
var $_useAlias = true;
59
* Index of basic SQL commands
64
var $_commands = array(
65
'begin' => 'START TRANSACTION',
67
'rollback' => 'ROLLBACK'
71
* List of engine specific additional field parameters used on table creating
76
var $fieldParameters = array(
77
'charset' => array('value' => 'CHARACTER SET', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault'),
78
'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collation', 'position' => 'beforeDefault'),
79
'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault')
83
* List of table engine specific parameters used on table creating
88
var $tableParameters = array(
89
'charset' => array('value' => 'DEFAULT CHARSET', 'quote' => false, 'join' => '=', 'column' => 'charset'),
90
'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => '=', 'column' => 'Collation'),
91
'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine')
95
* MySQL column definition
100
'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
101
'string' => array('name' => 'varchar', 'limit' => '255'),
102
'text' => array('name' => 'text'),
103
'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
104
'float' => array('name' => 'float', 'formatter' => 'floatval'),
105
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
106
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
107
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
108
'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
109
'binary' => array('name' => 'blob'),
110
'boolean' => array('name' => 'tinyint', 'limit' => '1')
114
* Returns an array of the fields in given table name.
116
* @param string $tableName Name of database table to inspect
117
* @return array Fields in table. Keys are name and type
119
function describe(&$model) {
120
$cache = parent::describe($model);
121
if ($cache != null) {
125
$cols = $this->query('SHOW FULL COLUMNS FROM ' . $this->fullTableName($model));
127
foreach ($cols as $column) {
128
$colKey = array_keys($column);
129
if (isset($column[$colKey[0]]) && !isset($column[0])) {
130
$column[0] = $column[$colKey[0]];
132
if (isset($column[0])) {
133
$fields[$column[0]['Field']] = array(
134
'type' => $this->column($column[0]['Type']),
135
'null' => ($column[0]['Null'] == 'YES' ? true : false),
136
'default' => $column[0]['Default'],
137
'length' => $this->length($column[0]['Type']),
139
if (!empty($column[0]['Key']) && isset($this->index[$column[0]['Key']])) {
140
$fields[$column[0]['Field']]['key'] = $this->index[$column[0]['Key']];
142
foreach ($this->fieldParameters as $name => $value) {
143
if (!empty($column[0][$value['column']])) {
144
$fields[$column[0]['Field']][$name] = $column[0][$value['column']];
147
if (isset($fields[$column[0]['Field']]['collate'])) {
148
$charset = $this->getCharsetName($fields[$column[0]['Field']]['collate']);
150
$fields[$column[0]['Field']]['charset'] = $charset;
155
$this->__cacheDescription($this->fullTableName($model, false), $fields);
160
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
162
* @param Model $model
163
* @param array $fields
164
* @param array $values
165
* @param mixed $conditions
168
function update(&$model, $fields = array(), $values = null, $conditions = null) {
169
if (!$this->_useAlias) {
170
return parent::update($model, $fields, $values, $conditions);
173
if ($values == null) {
176
$combined = array_combine($fields, $values);
179
$alias = $joins = false;
180
$fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions));
181
$fields = implode(', ', $fields);
182
$table = $this->fullTableName($model);
184
if (!empty($conditions)) {
185
$alias = $this->name($model->alias);
186
if ($model->name == $model->alias) {
187
$joins = implode(' ', $this->_getJoins($model));
190
$conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
192
if ($conditions === false) {
196
if (!$this->execute($this->renderStatement('update', compact('table', 'alias', 'joins', 'fields', 'conditions')))) {
204
* Generates and executes an SQL DELETE statement for given id/conditions on given model.
206
* @param Model $model
207
* @param mixed $conditions
208
* @return boolean Success
210
function delete(&$model, $conditions = null) {
211
if (!$this->_useAlias) {
212
return parent::delete($model, $conditions);
214
$alias = $this->name($model->alias);
215
$table = $this->fullTableName($model);
216
$joins = implode(' ', $this->_getJoins($model));
218
if (empty($conditions)) {
219
$alias = $joins = false;
221
$conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
223
if ($conditions === false) {
227
if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
235
* Sets the database encoding
237
* @param string $enc Database encoding
239
function setEncoding($enc) {
240
return $this->_execute('SET NAMES ' . $enc) != false;
244
* Returns an array of the indexes in given datasource name.
246
* @param string $model Name of model to inspect
247
* @return array Fields in table. Keys are column and unique
249
function index($model) {
251
$table = $this->fullTableName($model);
253
$indexes = $this->query('SHOW INDEX FROM ' . $table);
254
if (isset($indexes[0]['STATISTICS'])) {
255
$keys = Set::extract($indexes, '{n}.STATISTICS');
257
$keys = Set::extract($indexes, '{n}.0');
259
foreach ($keys as $i => $key) {
260
if (!isset($index[$key['Key_name']])) {
262
$index[$key['Key_name']]['column'] = $key['Column_name'];
263
$index[$key['Key_name']]['unique'] = intval($key['Non_unique'] == 0);
265
if (!is_array($index[$key['Key_name']]['column'])) {
266
$col[] = $index[$key['Key_name']]['column'];
268
$col[] = $key['Column_name'];
269
$index[$key['Key_name']]['column'] = $col;
277
* Generate a MySQL Alter Table syntax for the given Schema comparison
279
* @param array $compare Result of a CakeSchema::compare()
280
* @return array Array of alter statements to make.
282
function alterSchema($compare, $table = null) {
283
if (!is_array($compare)) {
288
foreach ($compare as $curTable => $types) {
289
$indexes = $tableParameters = $colList = array();
290
if (!$table || $table == $curTable) {
291
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
292
foreach ($types as $type => $column) {
293
if (isset($column['indexes'])) {
294
$indexes[$type] = $column['indexes'];
295
unset($column['indexes']);
297
if (isset($column['tableParameters'])) {
298
$tableParameters[$type] = $column['tableParameters'];
299
unset($column['tableParameters']);
303
foreach ($column as $field => $col) {
304
$col['name'] = $field;
305
$alter = 'ADD ' . $this->buildColumn($col);
306
if (isset($col['after'])) {
307
$alter .= ' AFTER ' . $this->name($col['after']);
313
foreach ($column as $field => $col) {
314
$col['name'] = $field;
315
$colList[] = 'DROP ' . $this->name($field);
319
foreach ($column as $field => $col) {
320
if (!isset($col['name'])) {
321
$col['name'] = $field;
323
$colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
328
$colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
329
$colList = array_merge($colList, $this->_alterTableParameters($curTable, $tableParameters));
330
$out .= "\t" . join(",\n\t", $colList) . ";\n\n";
337
* Generate a MySQL "drop table" statement for the given Schema object
339
* @param object $schema An instance of a subclass of CakeSchema
340
* @param string $table Optional. If specified only the table name given will be generated.
341
* Otherwise, all tables defined in the schema are generated.
344
function dropSchema($schema, $table = null) {
345
if (!is_a($schema, 'CakeSchema')) {
346
trigger_error(__('Invalid schema object', true), E_USER_WARNING);
350
foreach ($schema->tables as $curTable => $columns) {
351
if (!$table || $table == $curTable) {
352
$out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
359
* Generate MySQL table parameter alteration statementes for a table.
361
* @param string $table Table to alter parameters for.
362
* @param array $parameters Parameters to add & drop.
363
* @return array Array of table property alteration statementes.
364
* @todo Implement this method.
366
function _alterTableParameters($table, $parameters) {
367
if (isset($parameters['change'])) {
368
return $this->buildTableParameters($parameters['change']);
374
* Generate MySQL index alteration statements for a table.
376
* @param string $table Table to alter indexes for
377
* @param array $new Indexes to add and drop
378
* @return array Index alteration statements
380
function _alterIndexes($table, $indexes) {
382
if (isset($indexes['drop'])) {
383
foreach($indexes['drop'] as $name => $value) {
385
if ($name == 'PRIMARY') {
386
$out .= 'PRIMARY KEY';
388
$out .= 'KEY ' . $name;
393
if (isset($indexes['add'])) {
394
foreach ($indexes['add'] as $name => $value) {
396
if ($name == 'PRIMARY') {
400
if (!empty($value['unique'])) {
404
if (is_array($value['column'])) {
405
$out .= 'KEY '. $name .' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
407
$out .= 'KEY '. $name .' (' . $this->name($value['column']) . ')';
416
* Inserts multiple values into a table
418
* @param string $table
419
* @param string $fields
420
* @param array $values
422
function insertMulti($table, $fields, $values) {
423
$table = $this->fullTableName($table);
424
if (is_array($fields)) {
425
$fields = implode(', ', array_map(array(&$this, 'name'), $fields));
427
$values = implode(', ', $values);
428
$this->query("INSERT INTO {$table} ({$fields}) VALUES {$values}");
431
* Returns an detailed array of sources (tables) in the database.
433
* @param string $name Table name to get parameters
434
* @return array Array of tablenames in the database
436
function listDetailedSources($name = null) {
438
if (is_string($name)) {
439
$condition = ' LIKE ' . $this->value($name);
441
$result = $this->query('SHOW TABLE STATUS FROM ' . $this->name($this->config['database']) . $condition . ';');
446
foreach ($result as $row) {
447
$tables[$row['TABLES']['Name']] = $row['TABLES'];
448
if (!empty($row['TABLES']['Collation'])) {
449
$charset = $this->getCharsetName($row['TABLES']['Collation']);
451
$tables[$row['TABLES']['Name']]['charset'] = $charset;
455
if (is_string($name)) {
456
return $tables[$name];
463
* Converts database-layer column types to basic types
465
* @param string $real Real database-layer column type (i.e. "varchar(255)")
466
* @return string Abstract column type (i.e. "string")
468
function column($real) {
469
if (is_array($real)) {
470
$col = $real['name'];
471
if (isset($real['limit'])) {
472
$col .= '('.$real['limit'].')';
477
$col = str_replace(')', '', $real);
478
$limit = $this->length($real);
479
if (strpos($col, '(') !== false) {
480
list($col, $vals) = explode('(', $col);
483
if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
486
if (($col == 'tinyint' && $limit == 1) || $col == 'boolean') {
489
if (strpos($col, 'int') !== false) {
492
if (strpos($col, 'char') !== false || $col == 'tinytext') {
495
if (strpos($col, 'text') !== false) {
498
if (strpos($col, 'blob') !== false || $col == 'binary') {
501
if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) {
504
if (strpos($col, 'enum') !== false) {
505
return "enum($vals)";
512
* MySQL DBO driver object
514
* Provides connection and SQL generation for MySQL RDMS
517
* @subpackage cake.cake.libs.model.datasources.dbo
519
class DboMysql extends DboMysqlBase {
522
* Datasource description
526
var $description = "MySQL DBO Driver";
529
* Base configuration settings for MySQL driver
533
var $_baseConfig = array(
534
'persistent' => true,
535
'host' => 'localhost',
538
'database' => 'cake',
543
* Connects to the database using options in the given configuration array.
545
* @return boolean True if the database could be connected, else false
548
$config = $this->config;
549
$this->connected = false;
551
if (!$config['persistent']) {
552
$this->connection = mysql_connect($config['host'] . ':' . $config['port'], $config['login'], $config['password'], true);
553
$config['connect'] = 'mysql_connect';
555
$this->connection = mysql_pconnect($config['host'] . ':' . $config['port'], $config['login'], $config['password']);
558
if (mysql_select_db($config['database'], $this->connection)) {
559
$this->connected = true;
562
if (!empty($config['encoding'])) {
563
$this->setEncoding($config['encoding']);
566
$this->_useAlias = (bool)version_compare(mysql_get_server_info($this->connection), "4.1", ">=");
568
return $this->connected;
572
* Check whether the MySQL extension is installed/loaded
577
return extension_loaded('mysql');
580
* Disconnects from database.
582
* @return boolean True if the database could be disconnected, else false
584
function disconnect() {
585
if (isset($this->results) && is_resource($this->results)) {
586
mysql_free_result($this->results);
588
$this->connected = !@mysql_close($this->connection);
589
return !$this->connected;
593
* Executes given SQL statement.
595
* @param string $sql SQL statement
596
* @return resource Result resource identifier
599
function _execute($sql) {
600
return mysql_query($sql, $this->connection);
604
* Returns an array of sources (tables) in the database.
606
* @return array Array of tablenames in the database
608
function listSources() {
609
$cache = parent::listSources();
610
if ($cache != null) {
613
$result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
620
while ($line = mysql_fetch_row($result)) {
621
$tables[] = $line[0];
623
parent::listSources($tables);
629
* Returns a quoted and escaped string of $data for use in an SQL statement.
631
* @param string $data String to be prepared for use in an SQL statement
632
* @param string $column The column into which this data will be inserted
633
* @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
634
* @return string Quoted and escaped data
636
function value($data, $column = null, $safe = false) {
637
$parent = parent::value($data, $column, $safe);
639
if ($parent != null) {
642
if ($data === null || (is_array($data) && empty($data))) {
645
if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
648
if (empty($column)) {
649
$column = $this->introspectType($data);
654
return $this->boolean((bool)$data);
661
if (is_float($data)) {
662
return sprintf('%F', $data);
664
if ((is_int($data) || $data === '0') || (
665
is_numeric($data) && strpos($data, ',') === false &&
666
$data[0] != '0' && strpos($data, 'e') === false)
671
return "'" . mysql_real_escape_string($data, $this->connection) . "'";
677
* Returns a formatted error message from previous database operation.
679
* @return string Error message with error number
681
function lastError() {
682
if (mysql_errno($this->connection)) {
683
return mysql_errno($this->connection).': '.mysql_error($this->connection);
689
* Returns number of affected rows in previous database operation. If no previous operation exists,
690
* this returns false.
692
* @return integer Number of affected rows
694
function lastAffected() {
695
if ($this->_result) {
696
return mysql_affected_rows($this->connection);
702
* Returns number of rows in previous resultset. If no previous resultset exists,
703
* this returns false.
705
* @return integer Number of rows in resultset
707
function lastNumRows() {
708
if ($this->hasResult()) {
709
return mysql_num_rows($this->_result);
715
* Returns the ID generated from the previous INSERT operation.
717
* @param unknown_type $source
720
function lastInsertId($source = null) {
721
$id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
722
if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
723
return $id[0]['insertID'];
730
* Enter description here...
732
* @param unknown_type $results
734
function resultSet(&$results) {
735
if (isset($this->results) && is_resource($this->results) && $this->results != $results) {
736
mysql_free_result($this->results);
738
$this->results =& $results;
739
$this->map = array();
740
$numFields = mysql_num_fields($results);
744
while ($j < $numFields) {
745
$column = mysql_fetch_field($results, $j);
746
if (!empty($column->table) && strpos($column->name, $this->virtualFieldSeparator) === false) {
747
$this->map[$index++] = array($column->table, $column->name);
749
$this->map[$index++] = array(0, $column->name);
756
* Fetches the next row from the current result set
760
function fetchResult() {
761
if ($row = mysql_fetch_row($this->results)) {
762
$resultRow = array();
764
foreach ($row as $index => $field) {
765
list($table, $column) = $this->map[$index];
766
$resultRow[$table][$column] = $row[$index];
776
* Gets the database encoding
778
* @return string The database encoding
780
function getEncoding() {
781
return mysql_client_encoding($this->connection);
785
* Query charset by collation
787
* @param string $name Collation name
788
* @return string Character set name
790
function getCharsetName($name) {
791
if ((bool)version_compare(mysql_get_server_info($this->connection), "5", ">=")) {
792
$cols = $this->query('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= ' . $this->value($name) . ';');
793
if (isset($cols[0]['COLLATIONS']['CHARACTER_SET_NAME'])) {
794
return $cols[0]['COLLATIONS']['CHARACTER_SET_NAME'];