Passed
Branch php-cs-fixer (b9836a)
by Fabio
15:02
created

TMysqlMetaData::quoteTableName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * TMysqlMetaData class file.
4
 *
5
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
6
 * @link https://github.com/pradosoft/prado
7
 * @copyright Copyright &copy; 2005-2016 The PRADO Group
8
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
9
 * @package Prado\Data\Common\Mysql
10
 */
11
12
namespace Prado\Data\Common\Mysql;
13
14
/**
15
 * Load the base TDbMetaData class.
16
 */
17
use PDO;
18
use Prado\Data\Common\TDbMetaData;
19
use Prado\Data\TDbColumnCaseMode;
20
use Prado\Exceptions\TDbException;
21
use Prado\Prado;
22
23
24
/**
25
 * TMysqlMetaData loads Mysql version 4.1.x and 5.x database table and column information.
26
 *
27
 * For Mysql version 4.1.x, PHP 5.1.3 or later is required.
28
 * See http://netevil.org/node.php?nid=795&SC=1
29
 *
30
 * @author Wei Zhuo <weizho[at]gmail[dot]com>
31
 * @package Prado\Data\Common\Mysql
32
 * @since 3.1
33
 */
34
class TMysqlMetaData extends TDbMetaData
35
{
36
	private $_serverVersion = 0;
37
38
	/**
39
	 * @return string TDbTableInfo class name.
40
	 */
41
	protected function getTableInfoClass()
42
	{
43
		return '\Prado\Data\Common\Mysql\TMysqlTableInfo';
44
	}
45
46
	/**
47
	 * Quotes a table name for use in a query.
48
	 * @param string $name table name
49
	 * @return string the properly quoted table name
50
	 */
51
	public function quoteTableName($name)
52
	{
53
		return parent::quoteTableName($name, '`', '`');
54
	}
55
56
	/**
57
	 * Quotes a column name for use in a query.
58
	 * @param string $name column name
59
	 * @return string the properly quoted column name
60
	 */
61
	public function quoteColumnName($name)
62
	{
63
		return parent::quoteColumnName($name, '`', '`');
64
	}
65
66
	/**
67
	 * Quotes a column alias for use in a query.
68
	 * @param string $name column alias
69
	 * @return string the properly quoted column alias
70
	 */
71
	public function quoteColumnAlias($name)
72
	{
73
		return parent::quoteColumnAlias($name, '`', '`');
74
	}
75
76
	/**
77
	 * Get the column definitions for given table.
0 ignored issues
show
Bug introduced by
The type Prado\Data\Common\Mysql\table was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
78
	 * @param string table name.
79
	 * @return TMysqlTableInfo table information.
80
	 */
81
	protected function createTableInfo($table)
82
	{
83
		list($schemaName, $tableName) = $this->getSchemaTableName($table);
84
		$find = $schemaName === null ? "`{$tableName}`" : "`{$schemaName}`.`{$tableName}`";
85
		$colCase = $this->getDbConnection()->getColumnCase();
86
		if($colCase != TDbColumnCaseMode::Preserved)
87
			$this->getDbConnection()->setColumnCase('Preserved');
88
		$this->getDbConnection()->setActive(true);
89
		$sql = "SHOW FULL FIELDS FROM {$find}";
90
		$command = $this->getDbConnection()->createCommand($sql);
91
		$tableInfo = $this->createNewTableInfo($table);
92
		$index = 0;
93
		foreach($command->query() as $col)
94
		{
95
			$col['index'] = $index++;
96
			$this->processColumn($tableInfo, $col);
97
		}
98
		if($index === 0)
99
			throw new TDbException('dbmetadata_invalid_table_view', $table);
100
		if($colCase != TDbColumnCaseMode::Preserved)
101
			$this->getDbConnection()->setColumnCase($colCase);
102
		return $tableInfo;
103
	}
104
105
	/**
106
	 * @return float server version.
107
	 */
108
	protected function getServerVersion()
109
	{
110
		if(!$this->_serverVersion)
111
		{
112
			$version = $this->getDbConnection()->getAttribute(PDO::ATTR_SERVER_VERSION);
113
			$digits = [];
114
			preg_match('/(\d+)\.(\d+)\.(\d+)/', $version, $digits);
115
			$this->_serverVersion = floatval($digits[1] . '.' . $digits[2] . $digits[3]);
116
		}
117
		return $this->_serverVersion;
118
	}
119
120
	/**
121
	 * @param TMysqlTableInfo table information.
122
	 * @param array column information.
0 ignored issues
show
Bug introduced by
The type Prado\Data\Common\Mysql\column was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
123
	 */
124
	protected function processColumn($tableInfo, $col)
125
	{
126
		$columnId = $col['Field'];
127
128
		$info['ColumnName'] = "`$columnId`"; //quote the column names!
0 ignored issues
show
Comprehensibility Best Practice introduced by
$info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $info = array(); before regardless.
Loading history...
129
		$info['ColumnId'] = $columnId;
130
		$info['ColumnIndex'] = $col['index'];
131
		if($col['Null'] === 'YES')
132
			$info['AllowNull'] = true;
133
		if(is_int(strpos(strtolower($col['Extra']), 'auto_increment')))
0 ignored issues
show
introduced by
The condition is_int(strpos(strtolower...']), 'auto_increment')) can never be false.
Loading history...
134
			$info['AutoIncrement'] = true;
135
		if($col['Default'] !== "")
136
			$info['DefaultValue'] = $col['Default'];
137
138
		if($col['Key'] === 'PRI' || in_array($columnId, $tableInfo->getPrimaryKeys()))
139
			$info['IsPrimaryKey'] = true;
140
		if($this->isForeignKeyColumn($columnId, $tableInfo))
141
			$info['IsForeignKey'] = true;
142
143
		$info['DbType'] = $col['Type'];
144
		$match = [];
145
		//find SET/ENUM values, column size, precision, and scale
146
		if(preg_match('/\((.*)\)/', $col['Type'], $match))
147
		{
148
			$info['DbType'] = preg_replace('/\(.*\)/', '', $col['Type']);
149
150
			//find SET/ENUM values
151
			if($this->isEnumSetType($info['DbType']))
152
				$info['DbTypeValues'] = preg_split("/[',]/S", $match[1], -1, PREG_SPLIT_NO_EMPTY);
153
154
			//find column size, precision and scale
155
			$pscale = [];
156
			if(preg_match('/(\d+)(?:,(\d+))?+/', $match[1], $pscale))
157
			{
158
				if($this->isPrecisionType($info['DbType']))
159
				{
160
					$info['NumericPrecision'] = intval($pscale[1]);
161
					if(count($pscale) > 2)
162
						$info['NumericScale'] = intval($pscale[2]);
163
				}
164
				else
165
					$info['ColumnSize'] = intval($pscale[1]);
166
			}
167
		}
168
169
		$tableInfo->Columns[$columnId] = new TMysqlTableColumn($info);
170
	}
171
172
	/**
173
	 * @return boolean true if column type if "numeric", "interval" or begins with "time".
174
	 */
175
	protected function isPrecisionType($type)
176
	{
177
		$type = strtolower(trim($type));
178
		return $type === 'decimal' || $type === 'dec'
179
				|| $type === 'float' || $type === 'double'
180
				|| $type === 'double precision' || $type === 'real';
181
	}
182
183
	/**
184
	 * @return boolean true if column type if "enum" or "set".
185
	 */
186
	protected function isEnumSetType($type)
187
	{
188
		$type = strtolower(trim($type));
189
		return $type === 'set' || $type === 'enum';
190
	}
191
192
	/**
193
	 * @param string table name, may be quoted with back-ticks and may contain database name.
194
	 * @return array tuple ($schema,$table), $schema may be null.
195
	 * @throws TDbException when table name contains invalid identifier bytes.
196
	 */
197
	protected function getSchemaTableName($table)
198
	{
199
		//remove the back ticks and separate out the "database.table"
200
		$result = explode('.', str_replace('`', '', $table));
201
		foreach($result as $name)
202
		{
203
			if(!$this->isValidIdentifier($name))
204
			{
205
				$ref = 'http://dev.mysql.com/doc/refman/5.0/en/identifiers.html';
206
				throw new TDbException('dbcommon_invalid_identifier_name', $table, $ref);
207
			}
208
		}
209
		return count($result) > 1 ? $result : [null, $result[0]];
210
	}
211
212
	/**
213
	 * http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
0 ignored issues
show
Bug introduced by
The type Prado\Data\Common\Mysql\identifier was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
214
	 * @param string identifier name
215
	 * @param boolean true if valid identifier.
216
	 */
217
	protected function isValidIdentifier($name)
218
	{
219
		return !preg_match('#/|\\|.|\x00|\xFF#', $name);
220
	}
221
222
	/**
223
	 * @param string table schema name
224
	 * @param string table name.
225
	 * @return TMysqlTableInfo
226
	 */
227
	protected function createNewTableInfo($table)
228
	{
229
		list($schemaName, $tableName) = $this->getSchemaTableName($table);
230
		$info['SchemaName'] = $schemaName;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $info = array(); before regardless.
Loading history...
231
		$info['TableName'] = $tableName;
232
		if($this->getIsView($schemaName, $tableName))
233
			$info['IsView'] = true;
234
		list($primary, $foreign) = $this->getConstraintKeys($schemaName, $tableName);
235
		$class = $this->getTableInfoClass();
236
		return new $class($info, $primary, $foreign);
237
	}
238
239
	/**
240
	 * For MySQL version 5.0.1 or later we can use SHOW FULL TABLES
241
	 * http://dev.mysql.com/doc/refman/5.0/en/show-tables.html
242
	 *
243
	 * For MySQL version 5.0.1 or ealier, this always return false.
244
	 * @param string database name, null to use default connection database.
245
	 * @param string table or view name.
246
	 * @return boolean true if is view, false otherwise.
247
	 * @throws TDbException if table or view does not exist.
248
	 */
249
	protected function getIsView($schemaName, $tableName)
250
	{
251
		if($this->getServerVersion() < 5.01)
252
			return false;
253
		if($schemaName !== null)
254
			$sql = "SHOW FULL TABLES FROM `{$schemaName}` LIKE :table";
255
		else
256
			$sql = "SHOW FULL TABLES LIKE :table";
257
258
		$command = $this->getDbConnection()->createCommand($sql);
259
		$command->bindValue(':table', $tableName);
260
		try
261
		{
262
			return count($result = $command->queryRow()) > 0 && $result['Table_type'] === 'VIEW';
263
		}
264
		catch(TDbException $e)
265
		{
266
			$table = $schemaName === null?$tableName:$schemaName . '.' . $tableName;
267
			throw new TDbException('dbcommon_invalid_table_name', $table, $e->getMessage());
268
		}
269
	}
270
271
	/**
272
	 * Gets the primary and foreign key column details for the given table.
273
	 * @param string schema name
274
	 * @param string table name.
275
	 * @return array tuple ($primary, $foreign)
276
	 */
277
	protected function getConstraintKeys($schemaName, $tableName)
278
	{
279
		$table = $schemaName === null ? "`{$tableName}`" : "`{$schemaName}`.`{$tableName}`";
280
		$sql = "SHOW INDEX FROM {$table}";
281
		$command = $this->getDbConnection()->createCommand($sql);
282
		$primary = [];
283
		foreach($command->query() as $row)
284
		{
285
			if($row['Key_name'] === 'PRIMARY')
286
				$primary[] = $row['Column_name'];
287
		}
288
				// MySQL version was increased to >=5.1.21 instead of 5.x
289
				// due to a MySQL bug (http://bugs.mysql.com/bug.php?id=19588)
290
		if($this->getServerVersion() >= 5.121)
291
			$foreign = $this->getForeignConstraints($schemaName, $tableName);
292
		else
293
			$foreign = $this->findForeignConstraints($schemaName, $tableName);
294
		return [$primary,$foreign];
295
	}
296
297
	/**
298
	 * Gets foreign relationship constraint keys and table name
299
	 * @param string database name
300
	 * @param string table name
301
	 * @return array foreign relationship table name and keys.
302
	 */
303
	protected function getForeignConstraints($schemaName, $tableName)
304
	{
305
		$andSchema = $schemaName !== null ? 'AND TABLE_SCHEMA LIKE :schema' : 'AND TABLE_SCHEMA LIKE DATABASE()';
306
		$sql = <<<EOD
307
			SELECT
308
				CONSTRAINT_NAME as con,
309
				COLUMN_NAME as col,
310
				REFERENCED_TABLE_SCHEMA as fkschema,
311
				REFERENCED_TABLE_NAME as fktable,
312
				REFERENCED_COLUMN_NAME as fkcol
313
			FROM
314
				`INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE`
315
			WHERE
316
				REFERENCED_TABLE_NAME IS NOT NULL
317
				AND TABLE_NAME LIKE :table
318
				$andSchema
319
EOD;
320
		$command = $this->getDbConnection()->createCommand($sql);
321
		$command->bindValue(':table', $tableName);
322
		if($schemaName !== null)
323
			$command->bindValue(':schema', $schemaName);
324
		$fkeys = [];
325
		foreach($command->query() as $col)
326
		{
327
			$fkeys[$col['con']]['keys'][$col['col']] = $col['fkcol'];
328
			$fkeys[$col['con']]['table'] = $col['fktable'];
329
		}
330
		return count($fkeys) > 0 ? array_values($fkeys) : $fkeys;
331
	}
332
333
	/**
334
	 * @param string database name
335
	 * @param string table name
336
	 * @return string SQL command to create the table.
337
	 * @throws TDbException if PHP version is less than 5.1.3
338
	 */
339
	protected function getShowCreateTable($schemaName, $tableName)
340
	{
341
		if(version_compare(PHP_VERSION, '5.1.3', '<'))
342
			throw new TDbException('dbmetadata_requires_php_version', 'Mysql 4.1.x', '5.1.3');
343
344
		//See http://netevil.org/node.php?nid=795&SC=1
345
		$this->getDbConnection()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
346
		if($schemaName !== null)
347
			$sql = "SHOW CREATE TABLE `{$schemaName}`.`{$tableName}`";
348
		else
349
			$sql = "SHOW CREATE TABLE `{$tableName}`";
350
		$command = $this->getDbConnection()->createCommand($sql);
351
		$result = $command->queryRow();
352
		return isset($result['Create Table']) ? $result['Create Table'] : (isset($result['Create View']) ? $result['Create View'] : '');
353
	}
354
355
	/**
356
	 * Extract foreign key constraints by extracting the contraints from SHOW CREATE TABLE result.
357
	 * @param string database name
358
	 * @param string table name
359
	 * @return array foreign relationship table name and keys.
360
	 */
361
	protected function findForeignConstraints($schemaName, $tableName)
362
	{
363
		$sql = $this->getShowCreateTable($schemaName, $tableName);
364
		$matches = [];
365
		$regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+`?([^`]+)`?\s\(([^\)]+)\)/mi';
366
		preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER);
367
		$foreign = [];
368
		foreach($matches as $match)
369
		{
370
			$fields = array_map('trim', explode(',', str_replace('`', '', $match[1])));
371
			$fk_fields = array_map('trim', explode(',', str_replace('`', '', $match[3])));
372
			$keys = [];
373
			foreach($fields as $k => $v)
374
				$keys[$v] = $fk_fields[$k];
375
			$foreign[] = ['keys' => $keys, 'table' => trim($match[2])];
376
		}
377
		return $foreign;
378
	}
379
380
	/**
381
	 * @param string column name.
382
	 * @param TPgsqlTableInfo table information.
383
	 * @return boolean true if column is a foreign key.
384
	 */
385
	protected function isForeignKeyColumn($columnId, $tableInfo)
386
	{
387
		foreach($tableInfo->getForeignKeys() as $fk)
388
		{
389
			if(in_array($columnId, array_keys($fk['keys'])))
390
				return true;
391
		}
392
		return false;
393
	}
394
395
		/**
396
		 * Returns all table names in the database.
397
		 * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
398
		 * If not empty, the returned table names will be prefixed with the schema name.
399
		 * @return array all table names in the database.
400
		 */
401
	public function findTableNames($schema = '')
402
	{
403
		if($schema === '')
404
			return $this->getDbConnection()->createCommand('SHOW TABLES')->queryColumn();
405
		$names = $this->getDbConnection()->createCommand('SHOW TABLES FROM ' . $this->quoteTableName($schema))->queryColumn();
406
		foreach($names as &$name)
407
			$name = $schema . '.' . $name;
408
		return $names;
409
	}
410
}
411
412