1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25:
26: 27: 28: 29: 30: 31:
32: class DboMysqlBase extends DboSource {
33: 34: 35: 36: 37:
38: var $description = "MySQL DBO Base Driver";
39: 40: 41: 42: 43:
44: var $startQuote = "`";
45: 46: 47: 48: 49:
50: var $endQuote = "`";
51: 52: 53: 54: 55: 56:
57: var $_useAlias = true;
58: 59: 60: 61: 62: 63:
64: var $_commands = array(
65: 'begin' => 'START TRANSACTION',
66: 'commit' => 'COMMIT',
67: 'rollback' => 'ROLLBACK'
68: );
69: 70: 71: 72: 73:
74: var $columns = array(
75: 'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
76: 'string' => array('name' => 'varchar', 'limit' => '255'),
77: 'text' => array('name' => 'text'),
78: 'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
79: 'float' => array('name' => 'float', 'formatter' => 'floatval'),
80: 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
81: 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
82: 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
83: 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
84: 'binary' => array('name' => 'blob'),
85: 'boolean' => array('name' => 'tinyint', 'limit' => '1')
86: );
87: 88: 89: 90: 91: 92:
93: function describe(&$model) {
94: $cache = parent::describe($model);
95: if ($cache != null) {
96: return $cache;
97: }
98: $fields = false;
99: $cols = $this->query('DESCRIBE ' . $this->fullTableName($model));
100:
101: foreach ($cols as $column) {
102: $colKey = array_keys($column);
103: if (isset($column[$colKey[0]]) && !isset($column[0])) {
104: $column[0] = $column[$colKey[0]];
105: }
106: if (isset($column[0])) {
107: $fields[$column[0]['Field']] = array(
108: 'type' => $this->column($column[0]['Type']),
109: 'null' => ($column[0]['Null'] == 'YES' ? true : false),
110: 'default' => $column[0]['Default'],
111: 'length' => $this->length($column[0]['Type']),
112: );
113: if (!empty($column[0]['Key']) && isset($this->index[$column[0]['Key']])) {
114: $fields[$column[0]['Field']]['key'] = $this->index[$column[0]['Key']];
115: }
116: }
117: }
118: $this->__cacheDescription($this->fullTableName($model, false), $fields);
119: return $fields;
120: }
121: 122: 123: 124: 125: 126: 127: 128: 129:
130: function update(&$model, $fields = array(), $values = null, $conditions = null) {
131: if (!$this->_useAlias) {
132: return parent::update($model, $fields, $values, $conditions);
133: }
134:
135: if ($values == null) {
136: $combined = $fields;
137: } else {
138: $combined = array_combine($fields, $values);
139: }
140:
141: $alias = $joins = false;
142: $fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions));
143: $fields = implode(', ', $fields);
144: $table = $this->fullTableName($model);
145:
146: if (!empty($conditions)) {
147: $alias = $this->name($model->alias);
148: if ($model->name == $model->alias) {
149: $joins = implode(' ', $this->_getJoins($model));
150: }
151: }
152: $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
153:
154: if ($conditions === false) {
155: return false;
156: }
157:
158: if (!$this->execute($this->renderStatement('update', compact('table', 'alias', 'joins', 'fields', 'conditions')))) {
159: $model->onError();
160: return false;
161: }
162: return true;
163: }
164: 165: 166: 167: 168: 169: 170:
171: function delete(&$model, $conditions = null) {
172: if (!$this->_useAlias) {
173: return parent::delete($model, $conditions);
174: }
175: $alias = $this->name($model->alias);
176: $table = $this->fullTableName($model);
177: $joins = implode(' ', $this->_getJoins($model));
178:
179: if (empty($conditions)) {
180: $alias = $joins = false;
181: }
182: $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
183:
184: if ($conditions === false) {
185: return false;
186: }
187:
188: if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
189: $model->onError();
190: return false;
191: }
192: return true;
193: }
194: 195: 196: 197: 198:
199: function setEncoding($enc) {
200: return $this->_execute('SET NAMES ' . $enc) != false;
201: }
202: 203: 204: 205: 206: 207:
208: function index($model) {
209: $index = array();
210: $table = $this->fullTableName($model);
211: if ($table) {
212: $indexes = $this->query('SHOW INDEX FROM ' . $table);
213: if (isset($indexes[0]['STATISTICS'])) {
214: $keys = Set::extract($indexes, '{n}.STATISTICS');
215: } else {
216: $keys = Set::extract($indexes, '{n}.0');
217: }
218: foreach ($keys as $i => $key) {
219: if (!isset($index[$key['Key_name']])) {
220: $col = array();
221: $index[$key['Key_name']]['column'] = $key['Column_name'];
222: $index[$key['Key_name']]['unique'] = intval($key['Non_unique'] == 0);
223: } else {
224: if (!is_array($index[$key['Key_name']]['column'])) {
225: $col[] = $index[$key['Key_name']]['column'];
226: }
227: $col[] = $key['Column_name'];
228: $index[$key['Key_name']]['column'] = $col;
229: }
230: }
231: }
232: return $index;
233: }
234: 235: 236: 237: 238: 239:
240: function alterSchema($compare, $table = null) {
241: if (!is_array($compare)) {
242: return false;
243: }
244: $out = '';
245: $colList = array();
246: foreach ($compare as $curTable => $types) {
247: $indexes = array();
248: if (!$table || $table == $curTable) {
249: $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
250: foreach ($types as $type => $column) {
251: if (isset($column['indexes'])) {
252: $indexes[$type] = $column['indexes'];
253: unset($column['indexes']);
254: }
255: switch ($type) {
256: case 'add':
257: foreach ($column as $field => $col) {
258: $col['name'] = $field;
259: $alter = 'ADD '.$this->buildColumn($col);
260: if (isset($col['after'])) {
261: $alter .= ' AFTER '. $this->name($col['after']);
262: }
263: $colList[] = $alter;
264: }
265: break;
266: case 'drop':
267: foreach ($column as $field => $col) {
268: $col['name'] = $field;
269: $colList[] = 'DROP '.$this->name($field);
270: }
271: break;
272: case 'change':
273: foreach ($column as $field => $col) {
274: if (!isset($col['name'])) {
275: $col['name'] = $field;
276: }
277: $colList[] = 'CHANGE '. $this->name($field).' '.$this->buildColumn($col);
278: }
279: break;
280: }
281: }
282: $colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
283: $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
284: }
285: }
286: return $out;
287: }
288: 289: 290: 291: 292: 293: 294: 295:
296: function dropSchema($schema, $table = null) {
297: if (!is_a($schema, 'CakeSchema')) {
298: trigger_error(__('Invalid schema object', true), E_USER_WARNING);
299: return null;
300: }
301: $out = '';
302: foreach ($schema->tables as $curTable => $columns) {
303: if (!$table || $table == $curTable) {
304: $out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
305: }
306: }
307: return $out;
308: }
309: 310: 311: 312: 313: 314: 315:
316: function _alterIndexes($table, $indexes) {
317: $alter = array();
318: if (isset($indexes['drop'])) {
319: foreach($indexes['drop'] as $name => $value) {
320: $out = 'DROP ';
321: if ($name == 'PRIMARY') {
322: $out .= 'PRIMARY KEY';
323: } else {
324: $out .= 'KEY ' . $name;
325: }
326: $alter[] = $out;
327: }
328: }
329: if (isset($indexes['add'])) {
330: foreach ($indexes['add'] as $name => $value) {
331: $out = 'ADD ';
332: if ($name == 'PRIMARY') {
333: $out .= 'PRIMARY ';
334: $name = null;
335: } else {
336: if (!empty($value['unique'])) {
337: $out .= 'UNIQUE ';
338: }
339: }
340: if (is_array($value['column'])) {
341: $out .= 'KEY '. $name .' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
342: } else {
343: $out .= 'KEY '. $name .' (' . $this->name($value['column']) . ')';
344: }
345: $alter[] = $out;
346: }
347: }
348: return $alter;
349: }
350: 351: 352: 353: 354: 355: 356:
357: function insertMulti($table, $fields, $values) {
358: $table = $this->fullTableName($table);
359: if (is_array($fields)) {
360: $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
361: }
362: $values = implode(', ', $values);
363: $this->query("INSERT INTO {$table} ({$fields}) VALUES {$values}");
364: }
365: 366: 367: 368: 369: 370:
371: function column($real) {
372: if (is_array($real)) {
373: $col = $real['name'];
374: if (isset($real['limit'])) {
375: $col .= '('.$real['limit'].')';
376: }
377: return $col;
378: }
379:
380: $col = str_replace(')', '', $real);
381: $limit = $this->length($real);
382: if (strpos($col, '(') !== false) {
383: list($col, $vals) = explode('(', $col);
384: }
385:
386: if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
387: return $col;
388: }
389: if (($col == 'tinyint' && $limit == 1) || $col == 'boolean') {
390: return 'boolean';
391: }
392: if (strpos($col, 'int') !== false) {
393: return 'integer';
394: }
395: if (strpos($col, 'char') !== false || $col == 'tinytext') {
396: return 'string';
397: }
398: if (strpos($col, 'text') !== false) {
399: return 'text';
400: }
401: if (strpos($col, 'blob') !== false || $col == 'binary') {
402: return 'binary';
403: }
404: if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) {
405: return 'float';
406: }
407: if (strpos($col, 'enum') !== false) {
408: return "enum($vals)";
409: }
410: return 'text';
411: }
412: }
413:
414: 415: 416: 417: 418: 419: 420: 421:
422: class DboMysql extends DboMysqlBase {
423: 424: 425: 426: 427:
428: var $description = "MySQL DBO Driver";
429: 430: 431: 432: 433:
434: var $_baseConfig = array(
435: 'persistent' => true,
436: 'host' => 'localhost',
437: 'login' => 'root',
438: 'password' => '',
439: 'database' => 'cake',
440: 'port' => '3306',
441: 'connect' => 'mysql_pconnect'
442: );
443: 444: 445: 446: 447:
448: function connect() {
449: $config = $this->config;
450: $this->connected = false;
451:
452: if (!$config['persistent']) {
453: $this->connection = mysql_connect($config['host'] . ':' . $config['port'], $config['login'], $config['password'], true);
454: $config['connect'] = 'mysql_connect';
455: } else {
456: $this->connection = mysql_pconnect($config['host'] . ':' . $config['port'], $config['login'], $config['password']);
457: }
458:
459: if (mysql_select_db($config['database'], $this->connection)) {
460: $this->connected = true;
461: }
462:
463: if (!empty($config['encoding'])) {
464: $this->setEncoding($config['encoding']);
465: }
466:
467: $this->_useAlias = (bool)version_compare(mysql_get_server_info($this->connection), "4.1", ">=");
468:
469: return $this->connected;
470: }
471: 472: 473: 474: 475:
476: function enabled() {
477: return extension_loaded('mysql');
478: }
479: 480: 481: 482: 483:
484: function disconnect() {
485: if (isset($this->results) && is_resource($this->results)) {
486: mysql_free_result($this->results);
487: }
488: $this->connected = !@mysql_close($this->connection);
489: return !$this->connected;
490: }
491: 492: 493: 494: 495: 496: 497:
498: function _execute($sql) {
499: return mysql_query($sql, $this->connection);
500: }
501: 502: 503: 504: 505:
506: function listSources() {
507: $cache = parent::listSources();
508: if ($cache != null) {
509: return $cache;
510: }
511: $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
512:
513: if (!$result) {
514: return array();
515: } else {
516: $tables = array();
517:
518: while ($line = mysql_fetch_array($result)) {
519: $tables[] = $line[0];
520: }
521: parent::listSources($tables);
522: return $tables;
523: }
524: }
525: 526: 527: 528: 529: 530: 531: 532:
533: function value($data, $column = null, $safe = false) {
534: $parent = parent::value($data, $column, $safe);
535:
536: if ($parent != null) {
537: return $parent;
538: }
539: if ($data === null || (is_array($data) && empty($data))) {
540: return 'NULL';
541: }
542: if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
543: return "''";
544: }
545: if (empty($column)) {
546: $column = $this->introspectType($data);
547: }
548:
549: switch ($column) {
550: case 'boolean':
551: return $this->boolean((bool)$data);
552: break;
553: case 'integer':
554: case 'float':
555: if ($data === '') {
556: return 'NULL';
557: }
558: if ((is_int($data) || is_float($data) || $data === '0') || (
559: is_numeric($data) && strpos($data, ',') === false &&
560: $data[0] != '0' && strpos($data, 'e') === false)) {
561: return $data;
562: }
563: default:
564: $data = "'" . mysql_real_escape_string($data, $this->connection) . "'";
565: break;
566: }
567: return $data;
568: }
569: 570: 571: 572: 573:
574: function lastError() {
575: if (mysql_errno($this->connection)) {
576: return mysql_errno($this->connection).': '.mysql_error($this->connection);
577: }
578: return null;
579: }
580: 581: 582: 583: 584: 585:
586: function lastAffected() {
587: if ($this->_result) {
588: return mysql_affected_rows($this->connection);
589: }
590: return null;
591: }
592: 593: 594: 595: 596: 597:
598: function lastNumRows() {
599: if ($this->hasResult()) {
600: return mysql_num_rows($this->_result);
601: }
602: return null;
603: }
604: 605: 606: 607: 608: 609:
610: function lastInsertId($source = null) {
611: $id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
612: if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
613: return $id[0]['insertID'];
614: }
615:
616: return null;
617: }
618: 619: 620: 621: 622:
623: function resultSet(&$results) {
624: if (isset($this->results) && is_resource($this->results) && $this->results != $results) {
625: mysql_free_result($this->results);
626: }
627: $this->results =& $results;
628: $this->map = array();
629: $numFields = mysql_num_fields($results);
630: $index = 0;
631: $j = 0;
632:
633: while ($j < $numFields) {
634:
635: $column = mysql_fetch_field($results,$j);
636: if (!empty($column->table)) {
637: $this->map[$index++] = array($column->table, $column->name);
638: } else {
639: $this->map[$index++] = array(0, $column->name);
640: }
641: $j++;
642: }
643: }
644: 645: 646: 647: 648:
649: function fetchResult() {
650: if ($row = mysql_fetch_row($this->results)) {
651: $resultRow = array();
652: $i = 0;
653: foreach ($row as $index => $field) {
654: list($table, $column) = $this->map[$index];
655: $resultRow[$table][$column] = $row[$index];
656: $i++;
657: }
658: return $resultRow;
659: } else {
660: return false;
661: }
662: }
663: 664: 665: 666: 667:
668: function getEncoding() {
669: return mysql_client_encoding($this->connection);
670: }
671: }
672: ?>