1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17:
18:
19: App::uses('DboSource', 'Model/Datasource');
20:
21: 22: 23: 24: 25: 26: 27:
28: class Mysql extends DboSource {
29:
30: 31: 32: 33: 34:
35: public $description = "MySQL DBO Driver";
36:
37: 38: 39: 40: 41:
42: protected $_baseConfig = array(
43: 'persistent' => true,
44: 'host' => 'localhost',
45: 'login' => 'root',
46: 'password' => '',
47: 'database' => 'cake',
48: 'port' => '3306'
49: );
50:
51: 52: 53: 54: 55:
56: protected $_connection = null;
57:
58: 59: 60: 61: 62:
63: public $startQuote = "`";
64:
65: 66: 67: 68: 69:
70: public $endQuote = "`";
71:
72: 73: 74: 75: 76:
77: protected $_useAlias = true;
78:
79: 80: 81: 82: 83:
84: public $fieldParameters = array(
85: 'charset' => array('value' => 'CHARACTER SET', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault'),
86: 'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collation', 'position' => 'beforeDefault'),
87: 'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault')
88: );
89:
90: 91: 92: 93: 94:
95: public $tableParameters = array(
96: 'charset' => array('value' => 'DEFAULT CHARSET', 'quote' => false, 'join' => '=', 'column' => 'charset'),
97: 'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => '=', 'column' => 'Collation'),
98: 'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine')
99: );
100:
101: 102: 103: 104: 105:
106: public $columns = array(
107: 'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
108: 'string' => array('name' => 'varchar', 'limit' => '255'),
109: 'text' => array('name' => 'text'),
110: 'biginteger' => array('name' => 'bigint', 'limit' => '20'),
111: 'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
112: 'float' => array('name' => 'float', 'formatter' => 'floatval'),
113: 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
114: 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
115: 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
116: 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
117: 'binary' => array('name' => 'blob'),
118: 'boolean' => array('name' => 'tinyint', 'limit' => '1')
119: );
120:
121: 122: 123: 124: 125:
126: protected $_charsets = array();
127:
128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142:
143: public function connect() {
144: $config = $this->config;
145: $this->connected = false;
146:
147: $flags = array(
148: PDO::ATTR_PERSISTENT => $config['persistent'],
149: PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
150: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
151: );
152:
153: if (!empty($config['encoding'])) {
154: $flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
155: }
156: if (!empty($config['ssl_key']) && !empty($config['ssl_cert'])) {
157: $flags[PDO::MYSQL_ATTR_SSL_KEY] = $config['ssl_key'];
158: $flags[PDO::MYSQL_ATTR_SSL_CERT] = $config['ssl_cert'];
159: }
160: if (!empty($config['ssl_ca'])) {
161: $flags[PDO::MYSQL_ATTR_SSL_CA] = $config['ssl_ca'];
162: }
163: if (empty($config['unix_socket'])) {
164: $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
165: } else {
166: $dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
167: }
168:
169: try {
170: $this->_connection = new PDO(
171: $dsn,
172: $config['login'],
173: $config['password'],
174: $flags
175: );
176: $this->connected = true;
177: if (!empty($config['settings'])) {
178: foreach ($config['settings'] as $key => $value) {
179: $this->_execute("SET $key=$value");
180: }
181: }
182: } catch (PDOException $e) {
183: throw new MissingConnectionException(array(
184: 'class' => get_class($this),
185: 'message' => $e->getMessage()
186: ));
187: }
188:
189: $this->_charsets = array();
190: $this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">=");
191:
192: return $this->connected;
193: }
194:
195: 196: 197: 198: 199:
200: public function enabled() {
201: return in_array('mysql', PDO::getAvailableDrivers());
202: }
203:
204: 205: 206: 207: 208: 209:
210: public function listSources($data = null) {
211: $cache = parent::listSources();
212: if ($cache) {
213: return $cache;
214: }
215: $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']));
216:
217: if (!$result) {
218: $result->closeCursor();
219: return array();
220: }
221: $tables = array();
222:
223: while ($line = $result->fetch(PDO::FETCH_NUM)) {
224: $tables[] = $line[0];
225: }
226:
227: $result->closeCursor();
228: parent::listSources($tables);
229: return $tables;
230: }
231:
232: 233: 234: 235: 236: 237:
238: public function resultSet($results) {
239: $this->map = array();
240: $numFields = $results->columnCount();
241: $index = 0;
242:
243: while ($numFields-- > 0) {
244: $column = $results->getColumnMeta($index);
245: if ($column['len'] === 1 && (empty($column['native_type']) || $column['native_type'] === 'TINY')) {
246: $type = 'boolean';
247: } else {
248: $type = empty($column['native_type']) ? 'string' : $column['native_type'];
249: }
250: if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
251: $this->map[$index++] = array($column['table'], $column['name'], $type);
252: } else {
253: $this->map[$index++] = array(0, $column['name'], $type);
254: }
255: }
256: }
257:
258: 259: 260: 261: 262:
263: public function fetchResult() {
264: if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
265: $resultRow = array();
266: foreach ($this->map as $col => $meta) {
267: list($table, $column, $type) = $meta;
268: $resultRow[$table][$column] = $row[$col];
269: if ($type === 'boolean' && $row[$col] !== null) {
270: $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
271: }
272: }
273: return $resultRow;
274: }
275: $this->_result->closeCursor();
276: return false;
277: }
278:
279: 280: 281: 282: 283:
284: public function getEncoding() {
285: return $this->_execute('SHOW VARIABLES LIKE ?', array('character_set_client'))->fetchObject()->Value;
286: }
287:
288: 289: 290: 291: 292: 293:
294: public function getCharsetName($name) {
295: if ((bool)version_compare($this->getVersion(), "5", "<")) {
296: return false;
297: }
298: if (isset($this->_charsets[$name])) {
299: return $this->_charsets[$name];
300: }
301: $r = $this->_execute(
302: 'SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME = ?',
303: array($name)
304: );
305: $cols = $r->fetch(PDO::FETCH_ASSOC);
306:
307: if (isset($cols['CHARACTER_SET_NAME'])) {
308: $this->_charsets[$name] = $cols['CHARACTER_SET_NAME'];
309: } else {
310: $this->_charsets[$name] = false;
311: }
312: return $this->_charsets[$name];
313: }
314:
315: 316: 317: 318: 319: 320: 321:
322: public function describe($model) {
323: $key = $this->fullTableName($model, false);
324: $cache = parent::describe($key);
325: if ($cache) {
326: return $cache;
327: }
328: $table = $this->fullTableName($model);
329:
330: $fields = false;
331: $cols = $this->_execute('SHOW FULL COLUMNS FROM ' . $table);
332: if (!$cols) {
333: throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table));
334: }
335:
336: while ($column = $cols->fetch(PDO::FETCH_OBJ)) {
337: $fields[$column->Field] = array(
338: 'type' => $this->column($column->Type),
339: 'null' => ($column->Null === 'YES' ? true : false),
340: 'default' => $column->Default,
341: 'length' => $this->length($column->Type),
342: );
343: if (!empty($column->Key) && isset($this->index[$column->Key])) {
344: $fields[$column->Field]['key'] = $this->index[$column->Key];
345: }
346: foreach ($this->fieldParameters as $name => $value) {
347: if (!empty($column->{$value['column']})) {
348: $fields[$column->Field][$name] = $column->{$value['column']};
349: }
350: }
351: if (isset($fields[$column->Field]['collate'])) {
352: $charset = $this->getCharsetName($fields[$column->Field]['collate']);
353: if ($charset) {
354: $fields[$column->Field]['charset'] = $charset;
355: }
356: }
357: }
358: $this->_cacheDescription($key, $fields);
359: $cols->closeCursor();
360: return $fields;
361: }
362:
363: 364: 365: 366: 367: 368: 369: 370: 371:
372: public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
373: if (!$this->_useAlias) {
374: return parent::update($model, $fields, $values, $conditions);
375: }
376:
377: if (!$values) {
378: $combined = $fields;
379: } else {
380: $combined = array_combine($fields, $values);
381: }
382:
383: $alias = $joins = false;
384: $fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions));
385: $fields = implode(', ', $fields);
386: $table = $this->fullTableName($model);
387:
388: if (!empty($conditions)) {
389: $alias = $this->name($model->alias);
390: if ($model->name === $model->alias) {
391: $joins = implode(' ', $this->_getJoins($model));
392: }
393: }
394: $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
395:
396: if ($conditions === false) {
397: return false;
398: }
399:
400: if (!$this->execute($this->renderStatement('update', compact('table', 'alias', 'joins', 'fields', 'conditions')))) {
401: $model->onError();
402: return false;
403: }
404: return true;
405: }
406:
407: 408: 409: 410: 411: 412: 413:
414: public function delete(Model $model, $conditions = null) {
415: if (!$this->_useAlias) {
416: return parent::delete($model, $conditions);
417: }
418: $alias = $this->name($model->alias);
419: $table = $this->fullTableName($model);
420: $joins = implode(' ', $this->_getJoins($model));
421:
422: if (empty($conditions)) {
423: $alias = $joins = false;
424: }
425: $complexConditions = false;
426: foreach ((array)$conditions as $key => $value) {
427: if (strpos($key, $model->alias) === false) {
428: $complexConditions = true;
429: break;
430: }
431: }
432: if (!$complexConditions) {
433: $joins = false;
434: }
435:
436: $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
437: if ($conditions === false) {
438: return false;
439: }
440: if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
441: $model->onError();
442: return false;
443: }
444: return true;
445: }
446:
447: 448: 449: 450: 451: 452:
453: public function setEncoding($enc) {
454: return $this->_execute('SET NAMES ' . $enc) !== false;
455: }
456:
457: 458: 459: 460: 461: 462:
463: public function index($model) {
464: $index = array();
465: $table = $this->fullTableName($model);
466: $old = version_compare($this->getVersion(), '4.1', '<=');
467: if ($table) {
468: $indexes = $this->_execute('SHOW INDEX FROM ' . $table);
469:
470:
471: while ($idx = $indexes->fetch(PDO::FETCH_OBJ)) {
472: if ($old) {
473: $idx = (object)current((array)$idx);
474: }
475: if (!isset($index[$idx->Key_name]['column'])) {
476: $col = array();
477: $index[$idx->Key_name]['column'] = $idx->Column_name;
478:
479: if ($idx->Index_type === 'FULLTEXT') {
480: $index[$idx->Key_name]['type'] = strtolower($idx->Index_type);
481: } else {
482: $index[$idx->Key_name]['unique'] = intval($idx->Non_unique == 0);
483: }
484: } else {
485: if (!empty($index[$idx->Key_name]['column']) && !is_array($index[$idx->Key_name]['column'])) {
486: $col[] = $index[$idx->Key_name]['column'];
487: }
488: $col[] = $idx->Column_name;
489: $index[$idx->Key_name]['column'] = $col;
490: }
491: if (!empty($idx->Sub_part)) {
492: if (!isset($index[$idx->Key_name]['length'])) {
493: $index[$idx->Key_name]['length'] = array();
494: }
495: $index[$idx->Key_name]['length'][$idx->Column_name] = $idx->Sub_part;
496: }
497: }
498:
499: $indexes->closeCursor();
500: }
501: return $index;
502: }
503:
504: 505: 506: 507: 508: 509: 510:
511: public function alterSchema($compare, $table = null) {
512: if (!is_array($compare)) {
513: return false;
514: }
515: $out = '';
516: $colList = array();
517: foreach ($compare as $curTable => $types) {
518: $indexes = $tableParameters = $colList = array();
519: if (!$table || $table === $curTable) {
520: $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
521: foreach ($types as $type => $column) {
522: if (isset($column['indexes'])) {
523: $indexes[$type] = $column['indexes'];
524: unset($column['indexes']);
525: }
526: if (isset($column['tableParameters'])) {
527: $tableParameters[$type] = $column['tableParameters'];
528: unset($column['tableParameters']);
529: }
530: switch ($type) {
531: case 'add':
532: foreach ($column as $field => $col) {
533: $col['name'] = $field;
534: $alter = 'ADD ' . $this->buildColumn($col);
535: if (isset($col['after'])) {
536: $alter .= ' AFTER ' . $this->name($col['after']);
537: }
538: $colList[] = $alter;
539: }
540: break;
541: case 'drop':
542: foreach ($column as $field => $col) {
543: $col['name'] = $field;
544: $colList[] = 'DROP ' . $this->name($field);
545: }
546: break;
547: case 'change':
548: foreach ($column as $field => $col) {
549: if (!isset($col['name'])) {
550: $col['name'] = $field;
551: }
552: $colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
553: }
554: break;
555: }
556: }
557: $colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
558: $colList = array_merge($colList, $this->_alterTableParameters($curTable, $tableParameters));
559: $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
560: }
561: }
562: return $out;
563: }
564:
565: 566: 567: 568: 569: 570:
571: protected function _dropTable($table) {
572: return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
573: }
574:
575: 576: 577: 578: 579: 580: 581:
582: protected function _alterTableParameters($table, $parameters) {
583: if (isset($parameters['change'])) {
584: return $this->buildTableParameters($parameters['change']);
585: }
586: return array();
587: }
588:
589: 590: 591: 592: 593: 594: 595: 596:
597: public function buildIndex($indexes, $table = null) {
598: $join = array();
599: foreach ($indexes as $name => $value) {
600: $out = '';
601: if ($name === 'PRIMARY') {
602: $out .= 'PRIMARY ';
603: $name = null;
604: } else {
605: if (!empty($value['unique'])) {
606: $out .= 'UNIQUE ';
607: }
608: $name = $this->startQuote . $name . $this->endQuote;
609: }
610: if (isset($value['type']) && strtolower($value['type']) === 'fulltext') {
611: $out .= 'FULLTEXT ';
612: }
613: $out .= 'KEY ' . $name . ' (';
614:
615: if (is_array($value['column'])) {
616: if (isset($value['length'])) {
617: $vals = array();
618: foreach ($value['column'] as $column) {
619: $name = $this->name($column);
620: if (isset($value['length'])) {
621: $name .= $this->_buildIndexSubPart($value['length'], $column);
622: }
623: $vals[] = $name;
624: }
625: $out .= implode(', ', $vals);
626: } else {
627: $out .= implode(', ', array_map(array(&$this, 'name'), $value['column']));
628: }
629: } else {
630: $out .= $this->name($value['column']);
631: if (isset($value['length'])) {
632: $out .= $this->_buildIndexSubPart($value['length'], $value['column']);
633: }
634: }
635: $out .= ')';
636: $join[] = $out;
637: }
638: return $join;
639: }
640:
641: 642: 643: 644: 645: 646: 647:
648: protected function _alterIndexes($table, $indexes) {
649: $alter = array();
650: if (isset($indexes['drop'])) {
651: foreach ($indexes['drop'] as $name => $value) {
652: $out = 'DROP ';
653: if ($name === 'PRIMARY') {
654: $out .= 'PRIMARY KEY';
655: } else {
656: $out .= 'KEY ' . $this->startQuote . $name . $this->endQuote;
657: }
658: $alter[] = $out;
659: }
660: }
661: if (isset($indexes['add'])) {
662: $add = $this->buildIndex($indexes['add']);
663: foreach ($add as $index) {
664: $alter[] = 'ADD ' . $index;
665: }
666: }
667: return $alter;
668: }
669:
670: 671: 672: 673: 674: 675: 676:
677: protected function _buildIndexSubPart($lengths, $column) {
678: if ($lengths === null) {
679: return '';
680: }
681: if (!isset($lengths[$column])) {
682: return '';
683: }
684: return '(' . $lengths[$column] . ')';
685: }
686:
687: 688: 689: 690: 691: 692:
693: public function listDetailedSources($name = null) {
694: $condition = '';
695: if (is_string($name)) {
696: $condition = ' WHERE name = ' . $this->value($name);
697: }
698: $result = $this->_connection->query('SHOW TABLE STATUS ' . $condition, PDO::FETCH_ASSOC);
699:
700: if (!$result) {
701: $result->closeCursor();
702: return array();
703: }
704: $tables = array();
705: foreach ($result as $row) {
706: $tables[$row['Name']] = (array)$row;
707: unset($tables[$row['Name']]['queryString']);
708: if (!empty($row['Collation'])) {
709: $charset = $this->getCharsetName($row['Collation']);
710: if ($charset) {
711: $tables[$row['Name']]['charset'] = $charset;
712: }
713: }
714: }
715: $result->closeCursor();
716: if (is_string($name) && isset($tables[$name])) {
717: return $tables[$name];
718: }
719: return $tables;
720: }
721:
722: 723: 724: 725: 726: 727:
728: public function column($real) {
729: if (is_array($real)) {
730: $col = $real['name'];
731: if (isset($real['limit'])) {
732: $col .= '(' . $real['limit'] . ')';
733: }
734: return $col;
735: }
736:
737: $col = str_replace(')', '', $real);
738: $limit = $this->length($real);
739: if (strpos($col, '(') !== false) {
740: list($col, $vals) = explode('(', $col);
741: }
742:
743: if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
744: return $col;
745: }
746: if (($col === 'tinyint' && $limit === 1) || $col === 'boolean') {
747: return 'boolean';
748: }
749: if (strpos($col, 'bigint') !== false || $col === 'bigint') {
750: return 'biginteger';
751: }
752: if (strpos($col, 'int') !== false) {
753: return 'integer';
754: }
755: if (strpos($col, 'char') !== false || $col === 'tinytext') {
756: return 'string';
757: }
758: if (strpos($col, 'text') !== false) {
759: return 'text';
760: }
761: if (strpos($col, 'blob') !== false || $col === 'binary') {
762: return 'binary';
763: }
764: if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) {
765: return 'float';
766: }
767: if (strpos($col, 'enum') !== false) {
768: return "enum($vals)";
769: }
770: return 'text';
771: }
772:
773: 774: 775: 776: 777:
778: public function getSchemaName() {
779: return $this->config['database'];
780: }
781:
782: 783: 784: 785: 786:
787: public function nestedTransactionSupported() {
788: return $this->useNestedTransactions && version_compare($this->getVersion(), '4.1', '>=');
789: }
790:
791: }
792: