Schema.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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\cubrid;
  8. use yii\db\Expression;
  9. use yii\db\TableSchema;
  10. use yii\db\ColumnSchema;
  11. /**
  12. * Schema is the class for retrieving metadata from a CUBRID database (version 9.1.x and higher).
  13. *
  14. * @author Carsten Brandt <[email protected]>
  15. * @since 2.0
  16. */
  17. class Schema extends \yii\db\Schema
  18. {
  19. /**
  20. * @var array mapping from physical column types (keys) to abstract column types (values)
  21. * Please refer to [CUBRID manual](http://www.cubrid.org/manual/91/en/sql/datatype.html) for
  22. * details on data types.
  23. */
  24. public $typeMap = [
  25. // Numeric data types
  26. 'short' => self::TYPE_SMALLINT,
  27. 'smallint' => self::TYPE_SMALLINT,
  28. 'int' => self::TYPE_INTEGER,
  29. 'integer' => self::TYPE_INTEGER,
  30. 'bigint' => self::TYPE_BIGINT,
  31. 'numeric' => self::TYPE_DECIMAL,
  32. 'decimal' => self::TYPE_DECIMAL,
  33. 'float' => self::TYPE_FLOAT,
  34. 'real' => self::TYPE_FLOAT,
  35. 'double' => self::TYPE_FLOAT,
  36. 'double precision' => self::TYPE_FLOAT,
  37. 'monetary' => self::TYPE_MONEY,
  38. // Date/Time data types
  39. 'date' => self::TYPE_DATE,
  40. 'time' => self::TYPE_TIME,
  41. 'timestamp' => self::TYPE_TIMESTAMP,
  42. 'datetime' => self::TYPE_DATETIME,
  43. // String data types
  44. 'char' => self::TYPE_STRING,
  45. 'varchar' => self::TYPE_STRING,
  46. 'char varying' => self::TYPE_STRING,
  47. 'nchar' => self::TYPE_STRING,
  48. 'nchar varying' => self::TYPE_STRING,
  49. 'string' => self::TYPE_STRING,
  50. // BLOB/CLOB data types
  51. 'blob' => self::TYPE_BINARY,
  52. 'clob' => self::TYPE_BINARY,
  53. // Bit string data types
  54. 'bit' => self::TYPE_STRING,
  55. 'bit varying' => self::TYPE_STRING,
  56. // Collection data types (considered strings for now)
  57. 'set' => self::TYPE_STRING,
  58. 'multiset' => self::TYPE_STRING,
  59. 'list' => self::TYPE_STRING,
  60. 'sequence' => self::TYPE_STRING,
  61. 'enum' => self::TYPE_STRING,
  62. ];
  63. /**
  64. * Quotes a table name for use in a query.
  65. * A simple table name has no schema prefix.
  66. * @param string $name table name
  67. * @return string the properly quoted table name
  68. */
  69. public function quoteSimpleTableName($name)
  70. {
  71. return strpos($name, '"') !== false ? $name : '"' . $name . '"';
  72. }
  73. /**
  74. * Quotes a column name for use in a query.
  75. * A simple column name has no prefix.
  76. * @param string $name column name
  77. * @return string the properly quoted column name
  78. */
  79. public function quoteSimpleColumnName($name)
  80. {
  81. return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
  82. }
  83. /**
  84. * Quotes a string value for use in a query.
  85. * Note that if the parameter is not a string, it will be returned without change.
  86. * @param string $str string to be quoted
  87. * @return string the properly quoted string
  88. * @see http://www.php.net/manual/en/function.PDO-quote.php
  89. */
  90. public function quoteValue($str)
  91. {
  92. if (!is_string($str)) {
  93. return $str;
  94. }
  95. $this->db->open();
  96. // workaround for broken PDO::quote() implementation in CUBRID 9.1.0 http://jira.cubrid.org/browse/APIS-658
  97. $version = $this->db->pdo->getAttribute(\PDO::ATTR_CLIENT_VERSION);
  98. if (version_compare($version, '8.4.4.0002', '<') || $version[0] == '9' && version_compare($version, '9.2.0.0002', '<=')) {
  99. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  100. } else {
  101. return $this->db->pdo->quote($str);
  102. }
  103. }
  104. /**
  105. * Creates a query builder for the CUBRID database.
  106. * @return QueryBuilder query builder instance
  107. */
  108. public function createQueryBuilder()
  109. {
  110. return new QueryBuilder($this->db);
  111. }
  112. /**
  113. * Loads the metadata for the specified table.
  114. * @param string $name table name
  115. * @return TableSchema driver dependent table metadata. Null if the table does not exist.
  116. */
  117. protected function loadTableSchema($name)
  118. {
  119. $this->db->open();
  120. $tableInfo = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE, $name);
  121. if (!isset($tableInfo[0]['NAME'])) {
  122. return null;
  123. }
  124. $table = new TableSchema();
  125. $table->fullName = $table->name = $tableInfo[0]['NAME'];
  126. $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteSimpleTableName($table->name);
  127. $columns = $this->db->createCommand($sql)->queryAll();
  128. foreach ($columns as $info) {
  129. $column = $this->loadColumnSchema($info);
  130. $table->columns[$column->name] = $column;
  131. }
  132. $primaryKeys = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_PRIMARY_KEY, $table->name);
  133. foreach ($primaryKeys as $key) {
  134. $column = $table->columns[$key['ATTR_NAME']];
  135. $column->isPrimaryKey = true;
  136. $table->primaryKey[] = $column->name;
  137. if ($column->autoIncrement) {
  138. $table->sequenceName = '';
  139. }
  140. }
  141. $foreignKeys = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_IMPORTED_KEYS, $table->name);
  142. foreach ($foreignKeys as $key) {
  143. if (isset($table->foreignKeys[$key['FK_NAME']])) {
  144. $table->foreignKeys[$key['FK_NAME']][$key['FKCOLUMN_NAME']] = $key['PKCOLUMN_NAME'];
  145. } else {
  146. $table->foreignKeys[$key['FK_NAME']] = [
  147. $key['PKTABLE_NAME'],
  148. $key['FKCOLUMN_NAME'] => $key['PKCOLUMN_NAME']
  149. ];
  150. }
  151. }
  152. $table->foreignKeys = array_values($table->foreignKeys);
  153. return $table;
  154. }
  155. /**
  156. * Loads the column information into a [[ColumnSchema]] object.
  157. * @param array $info column information
  158. * @return ColumnSchema the column schema object
  159. */
  160. protected function loadColumnSchema($info)
  161. {
  162. $column = new ColumnSchema();
  163. $column->name = $info['Field'];
  164. $column->allowNull = $info['Null'] === 'YES';
  165. $column->isPrimaryKey = false; // primary key will be set by loadTableSchema() later
  166. $column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false;
  167. $column->dbType = strtolower($info['Type']);
  168. $column->unsigned = strpos($column->dbType, 'unsigned') !== false;
  169. $column->type = self::TYPE_STRING;
  170. if (preg_match('/^([\w ]+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  171. $type = $matches[1];
  172. if (isset($this->typeMap[$type])) {
  173. $column->type = $this->typeMap[$type];
  174. }
  175. if (!empty($matches[2])) {
  176. if ($type === 'enum') {
  177. $values = explode(',', $matches[2]);
  178. foreach ($values as $i => $value) {
  179. $values[$i] = trim($value, "'");
  180. }
  181. $column->enumValues = $values;
  182. } else {
  183. $values = explode(',', $matches[2]);
  184. $column->size = $column->precision = (int)$values[0];
  185. if (isset($values[1])) {
  186. $column->scale = (int)$values[1];
  187. }
  188. }
  189. }
  190. }
  191. $column->phpType = $this->getColumnPhpType($column);
  192. if ($column->type === 'timestamp' && $info['Default'] === 'CURRENT_TIMESTAMP' ||
  193. $column->type === 'datetime' && $info['Default'] === 'SYS_DATETIME' ||
  194. $column->type === 'date' && $info['Default'] === 'SYS_DATE' ||
  195. $column->type === 'time' && $info['Default'] === 'SYS_TIME'
  196. ) {
  197. $column->defaultValue = new Expression($info['Default']);
  198. } else {
  199. $column->defaultValue = $column->typecast($info['Default']);
  200. }
  201. return $column;
  202. }
  203. /**
  204. * Returns all table names in the database.
  205. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  206. * @return array all table names in the database. The names have NO schema name prefix.
  207. */
  208. protected function findTableNames($schema = '')
  209. {
  210. $this->db->open();
  211. $tables = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE);
  212. $tableNames = [];
  213. foreach ($tables as $table) {
  214. // do not list system tables
  215. if ($table['TYPE'] != 0) {
  216. $tableNames[] = $table['NAME'];
  217. }
  218. }
  219. return $tableNames;
  220. }
  221. /**
  222. * Determines the PDO type for the given PHP data value.
  223. * @param mixed $data the data whose PDO type is to be determined
  224. * @return integer the PDO type
  225. * @see http://www.php.net/manual/en/pdo.constants.php
  226. */
  227. public function getPdoType($data)
  228. {
  229. static $typeMap = [
  230. // php type => PDO type
  231. 'boolean' => \PDO::PARAM_INT, // PARAM_BOOL is not supported by CUBRID PDO
  232. 'integer' => \PDO::PARAM_INT,
  233. 'string' => \PDO::PARAM_STR,
  234. 'resource' => \PDO::PARAM_LOB,
  235. 'NULL' => \PDO::PARAM_NULL,
  236. ];
  237. $type = gettype($data);
  238. return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
  239. }
  240. }