summaryrefslogtreecommitdiff
path: root/framework/Data/Common/Sqlite/TSqliteMetaData.php
blob: 9bc345f3f864a5b6da3f4823d3461844d568b8ba (plain)
1
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
<?php
/**
 * TSqliteMetaData class file.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005-2014 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @package System.Data.Common.Sqlite
 */

/**
 * Load the base TDbMetaData class.
 */
Prado::using('System.Data.Common.TDbMetaData');
Prado::using('System.Data.Common.Sqlite.TSqliteTableInfo');

/**
 * TSqliteMetaData loads SQLite database table and column information.
 *
 * @author Wei Zhuo <weizho[at]gmail[dot]com>
 * @package System.Data.Commom.Sqlite
 * @since 3.1
 */
class TSqliteMetaData extends TDbMetaData
{
	/**
	 * @return string TDbTableInfo class name.
	 */
	protected function getTableInfoClass()
	{
		return 'TSqliteTableInfo';
	}

	/**
	 * Quotes a table name for use in a query.
	 * @param string $name table name
	 * @return string the properly quoted table name
	 */
	public function quoteTableName($name)
	{
		return parent::quoteTableName($name, "'", "'");
	}

	/**
	 * Quotes a column name for use in a query.
	 * @param string $name column name
	 * @return string the properly quoted column name
	 */
	public function quoteColumnName($name)
	{
		return parent::quoteColumnName($name, '"', '"');
	}

	/**
	 * Quotes a column alias for use in a query.
	 * @param string $name column alias
	 * @return string the properly quoted column alias
	 */
	public function quoteColumnAlias($name)
	{
		return parent::quoteColumnAlias($name, '"', '"');
	}

	/**
	 * Get the column definitions for given table.
	 * @param string table name.
	 * @return TPgsqlTableInfo table information.
	 */
	protected function createTableInfo($tableName)
	{
		$tableName = str_replace("'",'',$tableName);
		$this->getDbConnection()->setActive(true);
		$table = $this->getDbConnection()->quoteString($tableName);
		$sql = "PRAGMA table_info({$table})";
		$command = $this->getDbConnection()->createCommand($sql);
		$foreign = $this->getForeignKeys($table);
		$index=0;
		$columns=array();
		$primary=array();
		foreach($command->query() as $col)
		{
			$col['index'] = $index++;
			$column = $this->processColumn($col, $foreign);
			$columns[$col['name']] = $column;
			if($column->getIsPrimaryKey())
				$primary[] = $col['name'];
		}
		$info['TableName'] = $tableName;
		if($this->getIsView($tableName))
			$info['IsView'] = true;
		if(count($columns)===0)
			throw new TDbException('dbmetadata_invalid_table_view', $tableName);
		$class = $this->getTableInfoClass();
		$tableInfo = new $class($info,$primary,$foreign);
		$tableInfo->getColumns()->copyFrom($columns);
		return $tableInfo;
	}

	/**
	 * @param string table name.
	 * @return boolean true if the table is a view.
	 */
	protected function getIsView($tableName)
	{
		$sql = 'SELECT count(*) FROM sqlite_master WHERE type="view" AND name= :table';
		$this->getDbConnection()->setActive(true);
		$command = $this->getDbConnection()->createCommand($sql);
		$command->bindValue(':table', $tableName);
		return intval($command->queryScalar()) === 1;
	}

	/**
	 * @param array column information.
	 * @param array foreign key details.
	 * @return TSqliteTableColumn column details.
	 */
	protected function processColumn($col, $foreign)
	{
		$columnId = $col['name']; //use column name as column Id

		$info['ColumnName'] = '"'.$columnId.'"'; //quote the column names!
		$info['ColumnId'] = $columnId;
		$info['ColumnIndex'] = $col['index'];

		if($col['notnull']!=='99')
			$info['AllowNull'] = true;

		if($col['pk']==='1')
			$info['IsPrimaryKey'] = true;
		if($this->isForeignKeyColumn($columnId, $foreign))
			$info['IsForeignKey'] = true;

		if($col['dflt_value']!==null)
			$info['DefaultValue'] = $col['dflt_value'];

		$type = strtolower($col['type']);
		$info['AutoIncrement'] = $type==='integer' && $col['pk']==='1';

		$info['DbType'] = $type;
		$match=array();
		if(is_int($pos=strpos($type, '(')) && preg_match('/\((.*)\)/', $type, $match))
		{
			$ps = explode(',', $match[1]);
			if(count($ps)===2)
			{
				$info['NumericPrecision'] = intval($ps[0]);
				$info['NumericScale'] = intval($ps[1]);
			}
			else
				$info['ColumnSize']=intval($match[1]);
			$info['DbType'] = substr($type,0,$pos);
		}

		return new TSqliteTableColumn($info);
	}

	/**
	 *
	 *
	 * @param string quoted table name.
	 * @return array foreign key details.
	 */
	protected function getForeignKeys($table)
	{
		$sql = "PRAGMA foreign_key_list({$table})";
		$command = $this->getDbConnection()->createCommand($sql);
		$fkeys = array();
		foreach($command->query() as $col)
		{
			$fkeys[$col['table']]['keys'][$col['from']] = $col['to'];
			$fkeys[$col['table']]['table'] = $col['table'];
		}
		return count($fkeys) > 0 ? array_values($fkeys) : $fkeys;
	}

	/**
	 * @param string column name.
	 * @param array foreign key column names.
	 * @return boolean true if column is a foreign key.
	 */
	protected function isForeignKeyColumn($columnId, $foreign)
	{
		foreach($foreign as $fk)
		{
			if(in_array($columnId, array_keys($fk['keys'])))
				return true;
		}
		return false;
	}
        
        /**
	 * Returns all table names in the database.
	 * @param string $schema the schema of the tables. This is not used for sqlite database.
	 * @return array all table names in the database.
	 */
	public function findTableNames($schema='')
	{
		$sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
		return $this->getDbConnection()->createCommand($sql)->queryColumn();
	}
}