Schema.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. use yii\db\Transaction;
  12. /**
  13. * Schema is the class for retrieving metadata from a CUBRID database (version 9.3.x and higher).
  14. *
  15. * @author Carsten Brandt <mail@cebe.cc>
  16. * @since 2.0
  17. */
  18. class Schema extends \yii\db\Schema
  19. {
  20. /**
  21. * @var array mapping from physical column types (keys) to abstract column types (values)
  22. * Please refer to [CUBRID manual](http://www.cubrid.org/manual/91/en/sql/datatype.html) for
  23. * details on data types.
  24. */
  25. public $typeMap = [
  26. // Numeric data types
  27. 'short' => self::TYPE_SMALLINT,
  28. 'smallint' => self::TYPE_SMALLINT,
  29. 'int' => self::TYPE_INTEGER,
  30. 'integer' => self::TYPE_INTEGER,
  31. 'bigint' => self::TYPE_BIGINT,
  32. 'numeric' => self::TYPE_DECIMAL,
  33. 'decimal' => self::TYPE_DECIMAL,
  34. 'float' => self::TYPE_FLOAT,
  35. 'real' => self::TYPE_FLOAT,
  36. 'double' => self::TYPE_DOUBLE,
  37. 'double precision' => self::TYPE_DOUBLE,
  38. 'monetary' => self::TYPE_MONEY,
  39. // Date/Time data types
  40. 'date' => self::TYPE_DATE,
  41. 'time' => self::TYPE_TIME,
  42. 'timestamp' => self::TYPE_TIMESTAMP,
  43. 'datetime' => self::TYPE_DATETIME,
  44. // String data types
  45. 'char' => self::TYPE_CHAR,
  46. 'varchar' => self::TYPE_STRING,
  47. 'char varying' => self::TYPE_STRING,
  48. 'nchar' => self::TYPE_CHAR,
  49. 'nchar varying' => self::TYPE_STRING,
  50. 'string' => self::TYPE_STRING,
  51. // BLOB/CLOB data types
  52. 'blob' => self::TYPE_BINARY,
  53. 'clob' => self::TYPE_BINARY,
  54. // Bit string data types
  55. 'bit' => self::TYPE_INTEGER,
  56. 'bit varying' => self::TYPE_INTEGER,
  57. // Collection data types (considered strings for now)
  58. 'set' => self::TYPE_STRING,
  59. 'multiset' => self::TYPE_STRING,
  60. 'list' => self::TYPE_STRING,
  61. 'sequence' => self::TYPE_STRING,
  62. 'enum' => self::TYPE_STRING,
  63. ];
  64. /**
  65. * @var array map of DB errors and corresponding exceptions
  66. * If left part is found in DB error message exception class from the right part is used.
  67. */
  68. public $exceptionMap = [
  69. 'Operation would have caused one or more unique constraint violations' => 'yii\db\IntegrityException',
  70. ];
  71. /**
  72. * @inheritdoc
  73. */
  74. public function releaseSavepoint($name)
  75. {
  76. // does nothing as cubrid does not support this
  77. }
  78. /**
  79. * Quotes a table name for use in a query.
  80. * A simple table name has no schema prefix.
  81. * @param string $name table name
  82. * @return string the properly quoted table name
  83. */
  84. public function quoteSimpleTableName($name)
  85. {
  86. return strpos($name, '"') !== false ? $name : '"' . $name . '"';
  87. }
  88. /**
  89. * Quotes a column name for use in a query.
  90. * A simple column name has no prefix.
  91. * @param string $name column name
  92. * @return string the properly quoted column name
  93. */
  94. public function quoteSimpleColumnName($name)
  95. {
  96. return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
  97. }
  98. /**
  99. * Creates a query builder for the CUBRID database.
  100. * @return QueryBuilder query builder instance
  101. */
  102. public function createQueryBuilder()
  103. {
  104. return new QueryBuilder($this->db);
  105. }
  106. /**
  107. * Loads the metadata for the specified table.
  108. * @param string $name table name
  109. * @return TableSchema driver dependent table metadata. Null if the table does not exist.
  110. */
  111. protected function loadTableSchema($name)
  112. {
  113. $pdo = $this->db->getSlavePdo();
  114. $tableInfo = $pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE, $name);
  115. if (!isset($tableInfo[0]['NAME'])) {
  116. return null;
  117. }
  118. $table = new TableSchema();
  119. $table->fullName = $table->name = $tableInfo[0]['NAME'];
  120. $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteSimpleTableName($table->name);
  121. $columns = $this->db->createCommand($sql)->queryAll();
  122. foreach ($columns as $info) {
  123. $column = $this->loadColumnSchema($info);
  124. $table->columns[$column->name] = $column;
  125. }
  126. $primaryKeys = $pdo->cubrid_schema(\PDO::CUBRID_SCH_PRIMARY_KEY, $table->name);
  127. foreach ($primaryKeys as $key) {
  128. $column = $table->columns[$key['ATTR_NAME']];
  129. $column->isPrimaryKey = true;
  130. $table->primaryKey[] = $column->name;
  131. if ($column->autoIncrement) {
  132. $table->sequenceName = '';
  133. }
  134. }
  135. $foreignKeys = $pdo->cubrid_schema(\PDO::CUBRID_SCH_IMPORTED_KEYS, $table->name);
  136. foreach ($foreignKeys as $key) {
  137. if (isset($table->foreignKeys[$key['FK_NAME']])) {
  138. $table->foreignKeys[$key['FK_NAME']][$key['FKCOLUMN_NAME']] = $key['PKCOLUMN_NAME'];
  139. } else {
  140. $table->foreignKeys[$key['FK_NAME']] = [
  141. $key['PKTABLE_NAME'],
  142. $key['FKCOLUMN_NAME'] => $key['PKCOLUMN_NAME'],
  143. ];
  144. }
  145. }
  146. return $table;
  147. }
  148. /**
  149. * Loads the column information into a [[ColumnSchema]] object.
  150. * @param array $info column information
  151. * @return ColumnSchema the column schema object
  152. */
  153. protected function loadColumnSchema($info)
  154. {
  155. $column = $this->createColumnSchema();
  156. $column->name = $info['Field'];
  157. $column->allowNull = $info['Null'] === 'YES';
  158. $column->isPrimaryKey = false; // primary key will be set by loadTableSchema() later
  159. $column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false;
  160. $column->dbType = $info['Type'];
  161. $column->unsigned = strpos($column->dbType, 'unsigned') !== false;
  162. $column->type = self::TYPE_STRING;
  163. if (preg_match('/^([\w ]+)(?:\(([^\)]+)\))?$/', $column->dbType, $matches)) {
  164. $type = strtolower($matches[1]);
  165. $column->dbType = $type . (isset($matches[2]) ? "({$matches[2]})" : '');
  166. if (isset($this->typeMap[$type])) {
  167. $column->type = $this->typeMap[$type];
  168. }
  169. if (!empty($matches[2])) {
  170. if ($type === 'enum') {
  171. $values = preg_split('/\s*,\s*/', $matches[2]);
  172. foreach ($values as $i => $value) {
  173. $values[$i] = trim($value, "'");
  174. }
  175. $column->enumValues = $values;
  176. } else {
  177. $values = explode(',', $matches[2]);
  178. $column->size = $column->precision = (int) $values[0];
  179. if (isset($values[1])) {
  180. $column->scale = (int) $values[1];
  181. }
  182. if ($column->size === 1 && $type === 'bit') {
  183. $column->type = 'boolean';
  184. } elseif ($type === 'bit') {
  185. if ($column->size > 32) {
  186. $column->type = 'bigint';
  187. } elseif ($column->size === 32) {
  188. $column->type = 'integer';
  189. }
  190. }
  191. }
  192. }
  193. }
  194. $column->phpType = $this->getColumnPhpType($column);
  195. if ($column->isPrimaryKey) {
  196. return $column;
  197. }
  198. if ($column->type === 'timestamp' && $info['Default'] === 'SYS_TIMESTAMP' ||
  199. $column->type === 'datetime' && $info['Default'] === 'SYS_DATETIME' ||
  200. $column->type === 'date' && $info['Default'] === 'SYS_DATE' ||
  201. $column->type === 'time' && $info['Default'] === 'SYS_TIME'
  202. ) {
  203. $column->defaultValue = new Expression($info['Default']);
  204. } elseif (isset($type) && $type === 'bit') {
  205. $column->defaultValue = hexdec(trim($info['Default'], 'X\''));
  206. } else {
  207. $column->defaultValue = $column->phpTypecast($info['Default']);
  208. }
  209. return $column;
  210. }
  211. /**
  212. * Returns all table names in the database.
  213. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  214. * @return array all table names in the database. The names have NO schema name prefix.
  215. */
  216. protected function findTableNames($schema = '')
  217. {
  218. $pdo = $this->db->getSlavePdo();
  219. $tables = $pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE);
  220. $tableNames = [];
  221. foreach ($tables as $table) {
  222. // do not list system tables
  223. if ($table['TYPE'] != 0) {
  224. $tableNames[] = $table['NAME'];
  225. }
  226. }
  227. return $tableNames;
  228. }
  229. /**
  230. * Determines the PDO type for the given PHP data value.
  231. * @param mixed $data the data whose PDO type is to be determined
  232. * @return int the PDO type
  233. * @see http://www.php.net/manual/en/pdo.constants.php
  234. */
  235. public function getPdoType($data)
  236. {
  237. static $typeMap = [
  238. // php type => PDO type
  239. 'boolean' => \PDO::PARAM_INT, // PARAM_BOOL is not supported by CUBRID PDO
  240. 'integer' => \PDO::PARAM_INT,
  241. 'string' => \PDO::PARAM_STR,
  242. 'resource' => \PDO::PARAM_LOB,
  243. 'NULL' => \PDO::PARAM_NULL,
  244. ];
  245. $type = gettype($data);
  246. return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
  247. }
  248. /**
  249. * @inheritdoc
  250. * @see http://www.cubrid.org/manual/91/en/sql/transaction.html#database-concurrency
  251. */
  252. public function setTransactionIsolationLevel($level)
  253. {
  254. // translate SQL92 levels to CUBRID levels:
  255. switch ($level) {
  256. case Transaction::SERIALIZABLE:
  257. $level = '6'; // SERIALIZABLE
  258. break;
  259. case Transaction::REPEATABLE_READ:
  260. $level = '5'; // REPEATABLE READ CLASS with REPEATABLE READ INSTANCES
  261. break;
  262. case Transaction::READ_COMMITTED:
  263. $level = '4'; // REPEATABLE READ CLASS with READ COMMITTED INSTANCES
  264. break;
  265. case Transaction::READ_UNCOMMITTED:
  266. $level = '3'; // REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES
  267. break;
  268. }
  269. parent::setTransactionIsolationLevel($level);
  270. }
  271. /**
  272. * @inheritdoc
  273. */
  274. public function createColumnSchemaBuilder($type, $length = null)
  275. {
  276. return new ColumnSchemaBuilder($type, $length, $this->db);
  277. }
  278. }