Schema.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db\pgsql;
  8. use yii\db\TableSchema;
  9. use yii\db\ColumnSchema;
  10. /**
  11. * Schema is the class for retrieving metadata from a PostgreSQL database
  12. * (version 9.x and above).
  13. *
  14. * @author Gevik Babakhani <[email protected]>
  15. * @since 2.0
  16. */
  17. class Schema extends \yii\db\Schema
  18. {
  19. /**
  20. * @var string the default schema used for the current session.
  21. */
  22. public $defaultSchema = 'public';
  23. /**
  24. * @var array mapping from physical column types (keys) to abstract
  25. * column types (values)
  26. */
  27. public $typeMap = [
  28. 'abstime' => self::TYPE_TIMESTAMP,
  29. 'bit' => self::TYPE_STRING,
  30. 'bool' => self::TYPE_BOOLEAN,
  31. 'boolean' => self::TYPE_BOOLEAN,
  32. 'box' => self::TYPE_STRING,
  33. 'character' => self::TYPE_STRING,
  34. 'bytea' => self::TYPE_BINARY,
  35. 'char' => self::TYPE_STRING,
  36. 'cidr' => self::TYPE_STRING,
  37. 'circle' => self::TYPE_STRING,
  38. 'date' => self::TYPE_DATE,
  39. 'real' => self::TYPE_FLOAT,
  40. 'decimal' => self::TYPE_DECIMAL,
  41. 'double precision' => self::TYPE_DECIMAL,
  42. 'inet' => self::TYPE_STRING,
  43. 'smallint' => self::TYPE_SMALLINT,
  44. 'int4' => self::TYPE_INTEGER,
  45. 'int8' => self::TYPE_BIGINT,
  46. 'integer' => self::TYPE_INTEGER,
  47. 'bigint' => self::TYPE_BIGINT,
  48. 'interval' => self::TYPE_STRING,
  49. 'json' => self::TYPE_STRING,
  50. 'line' => self::TYPE_STRING,
  51. 'macaddr' => self::TYPE_STRING,
  52. 'money' => self::TYPE_MONEY,
  53. 'name' => self::TYPE_STRING,
  54. 'numeric' => self::TYPE_STRING,
  55. 'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal!
  56. 'path' => self::TYPE_STRING,
  57. 'point' => self::TYPE_STRING,
  58. 'polygon' => self::TYPE_STRING,
  59. 'text' => self::TYPE_TEXT,
  60. 'time without time zone' => self::TYPE_TIME,
  61. 'timestamp without time zone' => self::TYPE_TIMESTAMP,
  62. 'timestamp with time zone' => self::TYPE_TIMESTAMP,
  63. 'time with time zone' => self::TYPE_TIMESTAMP,
  64. 'unknown' => self::TYPE_STRING,
  65. 'uuid' => self::TYPE_STRING,
  66. 'bit varying' => self::TYPE_STRING,
  67. 'character varying' => self::TYPE_STRING,
  68. 'xml' => self::TYPE_STRING
  69. ];
  70. /**
  71. * Creates a query builder for the PostgreSQL database.
  72. * @return QueryBuilder query builder instance
  73. */
  74. public function createQueryBuilder()
  75. {
  76. return new QueryBuilder($this->db);
  77. }
  78. /**
  79. * Resolves the table name and schema name (if any).
  80. * @param TableSchema $table the table metadata object
  81. * @param string $name the table name
  82. */
  83. protected function resolveTableNames($table, $name)
  84. {
  85. $parts = explode('.', str_replace('"', '', $name));
  86. if (isset($parts[1])) {
  87. $table->schemaName = $parts[0];
  88. $table->name = $parts[1];
  89. } else {
  90. $table->schemaName = $this->defaultSchema;
  91. $table->name = $name;
  92. }
  93. $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
  94. }
  95. /**
  96. * Quotes a table name for use in a query.
  97. * A simple table name has no schema prefix.
  98. * @param string $name table name
  99. * @return string the properly quoted table name
  100. */
  101. public function quoteSimpleTableName($name)
  102. {
  103. return strpos($name, '"') !== false ? $name : '"' . $name . '"';
  104. }
  105. /**
  106. * Loads the metadata for the specified table.
  107. * @param string $name table name
  108. * @return TableSchema|null driver dependent table metadata. Null if the table does not exist.
  109. */
  110. public function loadTableSchema($name)
  111. {
  112. $table = new TableSchema();
  113. $this->resolveTableNames($table, $name);
  114. if ($this->findColumns($table)) {
  115. $this->findConstraints($table);
  116. return $table;
  117. } else {
  118. return null;
  119. }
  120. }
  121. /**
  122. * Determines the PDO type for the given PHP data value.
  123. * @param mixed $data the data whose PDO type is to be determined
  124. * @return integer the PDO type
  125. * @see http://www.php.net/manual/en/pdo.constants.php
  126. */
  127. public function getPdoType($data)
  128. {
  129. // php type => PDO type
  130. static $typeMap = [
  131. // https://github.com/yiisoft/yii2/issues/1115
  132. // Cast boolean to integer values to work around problems with PDO casting false to string '' https://bugs.php.net/bug.php?id=33876
  133. 'boolean' => \PDO::PARAM_INT,
  134. 'integer' => \PDO::PARAM_INT,
  135. 'string' => \PDO::PARAM_STR,
  136. 'resource' => \PDO::PARAM_LOB,
  137. 'NULL' => \PDO::PARAM_NULL,
  138. ];
  139. $type = gettype($data);
  140. return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
  141. }
  142. /**
  143. * Returns all table names in the database.
  144. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  145. * @return array all table names in the database. The names have NO schema name prefix.
  146. */
  147. protected function findTableNames($schema = '')
  148. {
  149. if ($schema === '') {
  150. $schema = $this->defaultSchema;
  151. }
  152. $sql = <<<EOD
  153. SELECT table_name, table_schema FROM information_schema.tables
  154. WHERE table_schema=:schema AND table_type='BASE TABLE'
  155. EOD;
  156. $command = $this->db->createCommand($sql);
  157. $command->bindParam(':schema', $schema);
  158. $rows = $command->queryAll();
  159. $names = [];
  160. foreach ($rows as $row) {
  161. $names[] = $row['table_name'];
  162. }
  163. return $names;
  164. }
  165. /**
  166. * Collects the foreign key column details for the given table.
  167. * @param TableSchema $table the table metadata
  168. */
  169. protected function findConstraints($table)
  170. {
  171. $tableName = $this->quoteValue($table->name);
  172. $tableSchema = $this->quoteValue($table->schemaName);
  173. //We need to extract the constraints de hard way since:
  174. //http://www.postgresql.org/message-id/[email protected]
  175. $sql = <<<SQL
  176. select
  177. (select string_agg(attname,',') attname from pg_attribute where attrelid=ct.conrelid and attnum = any(ct.conkey)) as columns,
  178. fc.relname as foreign_table_name,
  179. fns.nspname as foreign_table_schema,
  180. (select string_agg(attname,',') attname from pg_attribute where attrelid=ct.confrelid and attnum = any(ct.confkey)) as foreign_columns
  181. from
  182. pg_constraint ct
  183. inner join pg_class c on c.oid=ct.conrelid
  184. inner join pg_namespace ns on c.relnamespace=ns.oid
  185. left join pg_class fc on fc.oid=ct.confrelid
  186. left join pg_namespace fns on fc.relnamespace=fns.oid
  187. where
  188. ct.contype='f'
  189. and c.relname={$tableName}
  190. and ns.nspname={$tableSchema}
  191. SQL;
  192. $constraints = $this->db->createCommand($sql)->queryAll();
  193. foreach ($constraints as $constraint) {
  194. $columns = explode(',', $constraint['columns']);
  195. $fcolumns = explode(',', $constraint['foreign_columns']);
  196. if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
  197. $foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
  198. } else {
  199. $foreignTable = $constraint['foreign_table_name'];
  200. }
  201. $citem = [$foreignTable];
  202. foreach ($columns as $idx => $column) {
  203. $citem[$column] = $fcolumns[$idx];
  204. }
  205. $table->foreignKeys[] = $citem;
  206. }
  207. }
  208. /**
  209. * Gets information about given table unique indexes.
  210. * @param TableSchema $table the table metadata
  211. * @return array with index names, columns and if it is an expression tree
  212. */
  213. protected function getUniqueIndexInformation($table)
  214. {
  215. $tableName = $this->quoteValue($table->name);
  216. $tableSchema = $this->quoteValue($table->schemaName);
  217. $sql = <<<SQL
  218. SELECT
  219. i.relname as indexname,
  220. ARRAY(
  221. SELECT pg_get_indexdef(idx.indexrelid, k + 1, True)
  222. FROM generate_subscripts(idx.indkey, 1) AS k
  223. ORDER BY k
  224. ) AS indexcolumns,
  225. idx.indexprs IS NOT NULL AS indexprs
  226. FROM pg_index idx
  227. INNER JOIN pg_class i ON i.oid = idx.indexrelid
  228. INNER JOIN pg_class c ON c.oid = idx.indrelid
  229. INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
  230. WHERE idx.indisprimary != True
  231. AND idx.indisunique = True
  232. AND c.relname = {$tableName}
  233. AND ns.nspname = {$tableSchema}
  234. ;
  235. SQL;
  236. return $this->db->createCommand($sql)->queryAll();
  237. }
  238. /**
  239. * Returns all unique indexes for the given table.
  240. * Each array element is of the following structure:
  241. *
  242. * ~~~
  243. * [
  244. * 'IndexName1' => ['col1' [, ...]],
  245. * 'IndexName2' => ['col2' [, ...]],
  246. * ]
  247. * ~~~
  248. *
  249. * @param TableSchema $table the table metadata
  250. * @return array all unique indexes for the given table.
  251. */
  252. public function findUniqueIndexes($table)
  253. {
  254. $indexes = $this->getUniqueIndexInformation($table);
  255. $uniqueIndexes = [];
  256. foreach ($indexes as $index) {
  257. $indexName = $index['indexname'];
  258. if ($index['indexprs']) {
  259. // Index is an expression like "lower(colname::text)"
  260. $indexColumns = preg_replace("/.*\(([^\:]+).*/mi", "$1", $index['indexcolumns']);
  261. } else {
  262. $indexColumns = array_map('trim', explode(',', str_replace(['{', '}'], '', $index['indexcolumns'])));
  263. }
  264. $uniqueIndexes[$indexName] = $indexColumns;
  265. }
  266. return $uniqueIndexes;
  267. }
  268. /**
  269. * Collects the metadata of table columns.
  270. * @param TableSchema $table the table metadata
  271. * @return boolean whether the table exists in the database
  272. */
  273. protected function findColumns($table)
  274. {
  275. $tableName = $this->db->quoteValue($table->name);
  276. $schemaName = $this->db->quoteValue($table->schemaName);
  277. $sql = <<<SQL
  278. SELECT
  279. d.nspname AS table_schema,
  280. c.relname AS table_name,
  281. a.attname AS column_name,
  282. t.typname AS data_type,
  283. a.attlen AS character_maximum_length,
  284. pg_catalog.col_description(c.oid, a.attnum) AS column_comment,
  285. a.atttypmod AS modifier,
  286. a.attnotnull = false AS is_nullable,
  287. CAST(pg_get_expr(ad.adbin, ad.adrelid) AS varchar) AS column_default,
  288. coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval',false) AS is_autoinc,
  289. array_to_string((select array_agg(enumlabel) from pg_enum where enumtypid=a.atttypid)::varchar[],',') as enum_values,
  290. CASE atttypid
  291. WHEN 21 /*int2*/ THEN 16
  292. WHEN 23 /*int4*/ THEN 32
  293. WHEN 20 /*int8*/ THEN 64
  294. WHEN 1700 /*numeric*/ THEN
  295. CASE WHEN atttypmod = -1
  296. THEN null
  297. ELSE ((atttypmod - 4) >> 16) & 65535
  298. END
  299. WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/
  300. WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/
  301. ELSE null
  302. END AS numeric_precision,
  303. CASE
  304. WHEN atttypid IN (21, 23, 20) THEN 0
  305. WHEN atttypid IN (1700) THEN
  306. CASE
  307. WHEN atttypmod = -1 THEN null
  308. ELSE (atttypmod - 4) & 65535
  309. END
  310. ELSE null
  311. END AS numeric_scale,
  312. CAST(
  313. information_schema._pg_char_max_length(information_schema._pg_truetypid(a, t), information_schema._pg_truetypmod(a, t))
  314. AS numeric
  315. ) AS size,
  316. a.attnum = any (ct.conkey) as is_pkey
  317. FROM
  318. pg_class c
  319. LEFT JOIN pg_attribute a ON a.attrelid = c.oid
  320. LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
  321. LEFT JOIN pg_type t ON a.atttypid = t.oid
  322. LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
  323. LEFT join pg_constraint ct on ct.conrelid=c.oid and ct.contype='p'
  324. WHERE
  325. a.attnum > 0 and t.typname != ''
  326. and c.relname = {$tableName}
  327. and d.nspname = {$schemaName}
  328. ORDER BY
  329. a.attnum;
  330. SQL;
  331. $columns = $this->db->createCommand($sql)->queryAll();
  332. if (empty($columns)) {
  333. return false;
  334. }
  335. foreach ($columns as $column) {
  336. $column = $this->loadColumnSchema($column);
  337. $table->columns[$column->name] = $column;
  338. if ($column->isPrimaryKey === true) {
  339. $table->primaryKey[] = $column->name;
  340. if ($table->sequenceName === null && preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $column->defaultValue) === 1) {
  341. $table->sequenceName = preg_replace(['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], '', $column->defaultValue);
  342. }
  343. }
  344. }
  345. return true;
  346. }
  347. /**
  348. * Loads the column information into a [[ColumnSchema]] object.
  349. * @param array $info column information
  350. * @return ColumnSchema the column schema object
  351. */
  352. protected function loadColumnSchema($info)
  353. {
  354. $column = new ColumnSchema();
  355. $column->allowNull = $info['is_nullable'];
  356. $column->autoIncrement = $info['is_autoinc'];
  357. $column->comment = $info['column_comment'];
  358. $column->dbType = $info['data_type'];
  359. $column->defaultValue = $info['column_default'];
  360. $column->enumValues = explode(',', str_replace(["''"], ["'"], $info['enum_values']));
  361. $column->unsigned = false; // has no meaning in PG
  362. $column->isPrimaryKey = $info['is_pkey'];
  363. $column->name = $info['column_name'];
  364. $column->precision = $info['numeric_precision'];
  365. $column->scale = $info['numeric_scale'];
  366. $column->size = $info['size'];
  367. if (isset($this->typeMap[$column->dbType])) {
  368. $column->type = $this->typeMap[$column->dbType];
  369. } else {
  370. $column->type = self::TYPE_STRING;
  371. }
  372. $column->phpType = $this->getColumnPhpType($column);
  373. return $column;
  374. }
  375. }