Subversion-Projekte lars-tiefland.prado

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/**
3
 * TMysqlMetaData class file.
4
 *
5
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
6
 * @link http://www.pradosoft.com/
7
 * @copyright Copyright &copy; 2005-2008 PradoSoft
8
 * @license http://www.pradosoft.com/license/
9
 * @version $Id: TMysqlMetaData.php 2541 2008-10-21 15:05:13Z qiang.xue $
10
 * @package System.Data.Common.Mysql
11
 */
12
 
13
/**
14
 * Load the base TDbMetaData class.
15
 */
16
Prado::using('System.Data.Common.TDbMetaData');
17
Prado::using('System.Data.Common.Mysql.TMysqlTableInfo');
18
 
19
/**
20
 * TMysqlMetaData loads Mysql version 4.1.x and 5.x database table and column information.
21
 *
22
 * For Mysql version 4.1.x, PHP 5.1.3 or later is required.
23
 * See http://netevil.org/node.php?nid=795&SC=1
24
 *
25
 * @author Wei Zhuo <weizho[at]gmail[dot]com>
26
 * @version $Id: TMysqlMetaData.php 2541 2008-10-21 15:05:13Z qiang.xue $
27
 * @package System.Data.Commom.Sqlite
28
 * @since 3.1
29
 */
30
class TMysqlMetaData extends TDbMetaData
31
{
32
	private $_serverVersion=0;
33
 
34
	/**
35
	 * @return string TDbTableInfo class name.
36
	 */
37
	protected function getTableInfoClass()
38
	{
39
		return 'TMysqlTableInfo';
40
	}
41
 
42
	/**
43
	 * Get the column definitions for given table.
44
	 * @param string table name.
45
	 * @return TMysqlTableInfo table information.
46
	 */
47
	protected function createTableInfo($table)
48
	{
49
		list($schemaName,$tableName) = $this->getSchemaTableName($table);
50
		$find = $schemaName===null ? "`{$tableName}`" : "`{$schemaName}`.`{$tableName}`";
51
		$this->getDbConnection()->setActive(true);
52
		$sql = "SHOW FULL FIELDS FROM {$find}";
53
		$command = $this->getDbConnection()->createCommand($sql);
54
		$tableInfo = $this->createNewTableInfo($table);
55
		$index=0;
56
		foreach($command->query() as $col)
57
		{
58
			$col['index'] = $index++;
59
			$this->processColumn($tableInfo,$col);
60
		}
61
		if($index===0)
62
			throw new TDbException('dbmetadata_invalid_table_view', $table);
63
		return $tableInfo;
64
	}
65
 
66
	/**
67
	 * @return float server version.
68
	 */
69
	protected function getServerVersion()
70
	{
71
		if(!$this->_serverVersion)
72
		{
73
			$version = $this->getDbConnection()->getAttribute(PDO::ATTR_SERVER_VERSION);
74
			$digits=array();
75
			preg_match('/(\d+)\.(\d+)\.(\d+)/', $version, $digits);
76
			$this->_serverVersion=floatval($digits[1].'.'.$digits[2].$digits[3]);
77
		}
78
		return $this->_serverVersion;
79
	}
80
 
81
	/**
82
	 * @param TMysqlTableInfo table information.
83
	 * @param array column information.
84
	 */
85
	protected function processColumn($tableInfo, $col)
86
	{
87
		$columnId = $col['Field'];
88
 
89
		$info['ColumnName'] = "`$columnId`"; //quote the column names!
90
		$info['ColumnId'] = $columnId;
91
		$info['ColumnIndex'] = $col['index'];
92
		if($col['Null']==='YES')
93
			$info['AllowNull'] = true;
94
		if(is_int(strpos(strtolower($col['Extra']), 'auto_increment')))
95
			$info['AutoIncrement']=true;
96
		if($col['Default']!=="")
97
			$info['DefaultValue'] = $col['Default'];
98
 
99
		if($col['Key']==='PRI' || in_array($columnId, $tableInfo->getPrimaryKeys()))
100
			$info['IsPrimaryKey'] = true;
101
		if($this->isForeignKeyColumn($columnId, $tableInfo))
102
			$info['IsForeignKey'] = true;
103
 
104
		$info['DbType'] = $col['Type'];
105
		$match=array();
106
		//find SET/ENUM values, column size, precision, and scale
107
		if(preg_match('/\((.*)\)/', $col['Type'], $match))
108
		{
109
			$info['DbType']= preg_replace('/\(.*\)/', '', $col['Type']);
110
 
111
			//find SET/ENUM values
112
			if($this->isEnumSetType($info['DbType']))
113
				$info['DbTypeValues'] = preg_split('/\s*,\s*|\s+/', preg_replace('/\'|"/', '', $match[1]));
114
 
115
			//find column size, precision and scale
116
			$pscale = array();
117
			if(preg_match('/(\d+)(?:,(\d+))?+/', $match[1], $pscale))
118
			{
119
				if($this->isPrecisionType($info['DbType']))
120
				{
121
					$info['NumericPrecision'] = intval($pscale[1]);
122
					if(count($pscale) > 2)
123
						$info['NumericScale'] = intval($pscale[2]);
124
				}
125
				else
126
					$info['ColumnSize'] = intval($pscale[1]);
127
			}
128
		}
129
 
130
		$tableInfo->Columns[$columnId] = new TMysqlTableColumn($info);
131
	}
132
 
133
	/**
134
	 * @return boolean true if column type if "numeric", "interval" or begins with "time".
135
	 */
136
	protected function isPrecisionType($type)
137
	{
138
		$type = strtolower(trim($type));
139
		return $type==='decimal' || $type==='dec'
140
				|| $type==='float' || $type==='double'
141
				|| $type==='double precision' || $type==='real';
142
	}
143
 
144
	/**
145
	 * @return boolean true if column type if "enum" or "set".
146
	 */
147
	protected function isEnumSetType($type)
148
	{
149
		$type = strtolower(trim($type));
150
		return $type==='set' || $type==='enum';
151
	}
152
 
153
	/**
154
	 * @param string table name, may be quoted with back-ticks and may contain database name.
155
	 * @return array tuple ($schema,$table), $schema may be null.
156
	 * @throws TDbException when table name contains invalid identifier bytes.
157
	 */
158
	protected function getSchemaTableName($table)
159
	{
160
		//remove the back ticks and separate out the "database.table"
161
		$result = explode('.', str_replace('`', '', $table));
162
		foreach($result as $name)
163
		{
164
			if(!$this->isValidIdentifier($name))
165
			{
166
				$ref = 'http://dev.mysql.com/doc/refman/5.0/en/identifiers.html';
167
				throw new TDbException('dbcommon_invalid_identifier_name', $table, $ref);
168
			}
169
		}
170
		return count($result) > 1 ? $result : array(null, $result[0]);
171
	}
172
 
173
	/**
174
	 * http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
175
	 * @param string identifier name
176
	 * @param boolean true if valid identifier.
177
	 */
178
	protected function isValidIdentifier($name)
179
	{
180
		return !preg_match('#/|\\|.|\x00|\xFF#', $name);
181
	}
182
 
183
	/**
184
	 * @param string table schema name
185
	 * @param string table name.
186
	 * @return TMysqlTableInfo
187
	 */
188
	protected function createNewTableInfo($table)
189
	{
190
		list($schemaName,$tableName) = $this->getSchemaTableName($table);
191
		$info['SchemaName'] = $schemaName;
192
		$info['TableName'] = $tableName;
193
		if($this->getIsView($schemaName,$tableName))
194
			$info['IsView'] = true;
195
		list($primary, $foreign) = $this->getConstraintKeys($schemaName, $tableName);
196
		$class = $this->getTableInfoClass();
197
		return new $class($info,$primary,$foreign);
198
	}
199
 
200
	/**
201
	 * For MySQL version 5.0.1 or later we can use SHOW FULL TABLES
202
	 * http://dev.mysql.com/doc/refman/5.0/en/show-tables.html
203
	 *
204
	 * For MySQL version 5.0.1 or ealier, this always return false.
205
	 * @param string database name, null to use default connection database.
206
	 * @param string table or view name.
207
	 * @return boolean true if is view, false otherwise.
208
	 * @throws TDbException if table or view does not exist.
209
	 */
210
	protected function getIsView($schemaName,$tableName)
211
	{
212
		if($this->getServerVersion()<5.01)
213
			return false;
214
		if($schemaName!==null)
215
			$sql = "SHOW FULL TABLES FROM `{$schemaName}` LIKE ':table'";
216
		else
217
			$sql = "SHOW FULL TABLES LIKE ':table'";
218
 
219
		$command = $this->getDbConnection()->createCommand($sql);
220
		$command->bindValue(':table', $tableName);
221
		try
222
		{
223
			return count($result = $command->queryRow()) > 0 && $result['Table_type']==='VIEW';
224
		}
225
		catch(TDbException $e)
226
		{
227
			$table = $schemaName===null?$tableName:$schemaName.'.'.$tableName;
228
			throw new TDbException('dbcommon_invalid_table_name',$table,$e->getMessage());
229
		}
230
	}
231
 
232
	/**
233
	 * Gets the primary and foreign key column details for the given table.
234
	 * @param string schema name
235
	 * @param string table name.
236
	 * @return array tuple ($primary, $foreign)
237
	 */
238
	protected function getConstraintKeys($schemaName, $tableName)
239
	{
240
		$table = $schemaName===null ? "`{$tableName}`" : "`{$schemaName}`.`{$tableName}`";
241
		$sql = "SHOW INDEX FROM {$table}";
242
		$command = $this->getDbConnection()->createCommand($sql);
243
		$primary = array();
244
		foreach($command->query() as $row)
245
		{
246
			if($row['Key_name']==='PRIMARY')
247
				$primary[] = $row['Column_name'];
248
		}
249
        // MySQL version was increased to >=5.1.21 instead of 5.x
250
        // due to a MySQL bug (http://bugs.mysql.com/bug.php?id=19588)
251
		if($this->getServerVersion() >= 5.121)
252
			$foreign = $this->getForeignConstraints($schemaName,$tableName);
253
		else
254
			$foreign = $this->findForeignConstraints($schemaName,$tableName);
255
		return array($primary,$foreign);
256
	}
257
 
258
	/**
259
	 * Gets foreign relationship constraint keys and table name
260
	 * @param string database name
261
	 * @param string table name
262
	 * @return array foreign relationship table name and keys.
263
	 */
264
	protected function getForeignConstraints($schemaName, $tableName)
265
	{
266
		$andSchema = $schemaName !== null ? 'AND TABLE_SCHEMA = :schema' : '';
267
		$sql = <<<EOD
268
			SELECT
269
				CONSTRAINT_NAME as con,
270
				COLUMN_NAME as col,
271
				REFERENCED_TABLE_SCHEMA as fkschema,
272
				REFERENCED_TABLE_NAME as fktable,
273
				REFERENCED_COLUMN_NAME as fkcol
274
			FROM
275
				 `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE`
276
			WHERE
277
				REFERENCED_TABLE_NAME IS NOT NULL
278
				AND TABLE_NAME = :table
279
				$andSchema
280
EOD;
281
		$command = $this->getDbConnection()->createCommand($sql);
282
		$command->bindValue(':table', $tableName);
283
		if($schemaName!==null)
284
			$command->bindValue(':schema', $schemaName);
285
		$fkeys=array();
286
		foreach($command->query() as $col)
287
		{
288
			$fkeys[$col['con']]['keys'][$col['col']] = $col['fkcol'];
289
			$fkeys[$col['con']]['table'] = $col['fktable'];
290
		}
291
		return count($fkeys) > 0 ? array_values($fkeys) : $fkeys;
292
	}
293
 
294
	/**
295
	 * @param string database name
296
	 * @param string table name
297
	 * @return string SQL command to create the table.
298
	 * @throws TDbException if PHP version is less than 5.1.3
299
	 */
300
	protected function getShowCreateTable($schemaName, $tableName)
301
	{
302
		if(version_compare(PHP_VERSION,'5.1.3','<'))
303
			throw new TDbException('dbmetadata_requires_php_version', 'Mysql 4.1.x', '5.1.3');
304
 
305
		//See http://netevil.org/node.php?nid=795&SC=1
306
		$this->getDbConnection()->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
307
		if($schemaName!==null)
308
			$sql = "SHOW CREATE TABLE `{$schemaName}`.`{$tableName}`";
309
		else
310
			$sql = "SHOW CREATE TABLE `{$tableName}`";
311
		$command = $this->getDbConnection()->createCommand($sql);
312
		$result = $command->queryRow();
313
		return $result['Create Table'];
314
	}
315
 
316
	/**
317
	 * Extract foreign key constraints by extracting the contraints from SHOW CREATE TABLE result.
318
	 * @param string database name
319
	 * @param string table name
320
	 * @return array foreign relationship table name and keys.
321
	 */
322
	protected function findForeignConstraints($schemaName, $tableName)
323
	{
324
		$sql = $this->getShowCreateTable($schemaName, $tableName);
325
		$matches =array();
326
		$regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+`?([^`]+)`?\s\(([^\)]+)\)/mi';
327
		preg_match_all($regexp,$sql,$matches,PREG_SET_ORDER);
328
		$foreign = array();
329
		foreach($matches as $match)
330
		{
331
			$fields = array_map('trim',explode(',',str_replace('`','',$match[1])));
332
			$fk_fields = array_map('trim',explode(',',str_replace('`','',$match[3])));
333
			$keys=array();
334
			foreach($fields as $k=>$v)
335
				$keys[$v] = $fk_fields[$k];
336
			$foreign[] = array('keys' => $keys, 'table' => trim($match[2]));
337
		}
338
		return $foreign;
339
	}
340
 
341
	/**
342
	 * @param string column name.
343
	 * @param TPgsqlTableInfo table information.
344
	 * @return boolean true if column is a foreign key.
345
	 */
346
	protected function isForeignKeyColumn($columnId, $tableInfo)
347
	{
348
		foreach($tableInfo->getForeignKeys() as $fk)
349
		{
350
			if(in_array($columnId, array_keys($fk['keys'])))
351
				return true;
352
		}
353
		return false;
354
	}
355
}
356