Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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