Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. $table->foreignKeys = array_values($table->foreignKeys);
  147. return $table;
  148. }
  149. /**
  150. * Loads the column information into a [[ColumnSchema]] object.
  151. * @param array $info column information
  152. * @return ColumnSchema the column schema object
  153. */
  154. protected function loadColumnSchema($info)
  155. {
  156. $column = $this->createColumnSchema();
  157. $column->name = $info['Field'];
  158. $column->allowNull = $info['Null'] === 'YES';
  159. $column->isPrimaryKey = false; // primary key will be set by loadTableSchema() later
  160. $column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false;
  161. $column->dbType = $info['Type'];
  162. $column->unsigned = strpos($column->dbType, 'unsigned') !== false;
  163. $column->type = self::TYPE_STRING;
  164. if (preg_match('/^([\w ]+)(?:\(([^\)]+)\))?$/', $column->dbType, $matches)) {
  165. $type = strtolower($matches[1]);
  166. $column->dbType = $type . (isset($matches[2]) ? "({$matches[2]})" : '');
  167. if (isset($this->typeMap[$type])) {
  168. $column->type = $this->typeMap[$type];
  169. }
  170. if (!empty($matches[2])) {
  171. if ($type === 'enum') {
  172. $values = preg_split('/\s*,\s*/', $matches[2]);
  173. foreach ($values as $i => $value) {
  174. $values[$i] = trim($value, "'");
  175. }
  176. $column->enumValues = $values;
  177. } else {
  178. $values = explode(',', $matches[2]);
  179. $column->size = $column->precision = (int) $values[0];
  180. if (isset($values[1])) {
  181. $column->scale = (int) $values[1];
  182. }
  183. if ($column->size === 1 && $type === 'bit') {
  184. $column->type = 'boolean';
  185. } elseif ($type === 'bit') {
  186. if ($column->size > 32) {
  187. $column->type = 'bigint';
  188. } elseif ($column->size === 32) {
  189. $column->type = 'integer';
  190. }
  191. }
  192. }
  193. }
  194. }
  195. $column->phpType = $this->getColumnPhpType($column);
  196. if ($column->isPrimaryKey) {
  197. return $column;
  198. }
  199. if ($column->type === 'timestamp' && $info['Default'] === 'SYS_TIMESTAMP' ||
  200. $column->type === 'datetime' && $info['Default'] === 'SYS_DATETIME' ||
  201. $column->type === 'date' && $info['Default'] === 'SYS_DATE' ||
  202. $column->type === 'time' && $info['Default'] === 'SYS_TIME'
  203. ) {
  204. $column->defaultValue = new Expression($info['Default']);
  205. } elseif (isset($type) && $type === 'bit') {
  206. $column->defaultValue = hexdec(trim($info['Default'], 'X\''));
  207. } else {
  208. $column->defaultValue = $column->phpTypecast($info['Default']);
  209. }
  210. return $column;
  211. }
  212. /**
  213. * Returns all table names in the database.
  214. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  215. * @return array all table names in the database. The names have NO schema name prefix.
  216. */
  217. protected function findTableNames($schema = '')
  218. {
  219. $pdo = $this->db->getSlavePdo();
  220. $tables = $pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE);
  221. $tableNames = [];
  222. foreach ($tables as $table) {
  223. // do not list system tables
  224. if ($table['TYPE'] != 0) {
  225. $tableNames[] = $table['NAME'];
  226. }
  227. }
  228. return $tableNames;
  229. }
  230. /**
  231. * Determines the PDO type for the given PHP data value.
  232. * @param mixed $data the data whose PDO type is to be determined
  233. * @return integer the PDO type
  234. * @see http://www.php.net/manual/en/pdo.constants.php
  235. */
  236. public function getPdoType($data)
  237. {
  238. static $typeMap = [
  239. // php type => PDO type
  240. 'boolean' => \PDO::PARAM_INT, // PARAM_BOOL is not supported by CUBRID PDO
  241. 'integer' => \PDO::PARAM_INT,
  242. 'string' => \PDO::PARAM_STR,
  243. 'resource' => \PDO::PARAM_LOB,
  244. 'NULL' => \PDO::PARAM_NULL,
  245. ];
  246. $type = gettype($data);
  247. return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
  248. }
  249. /**
  250. * @inheritdoc
  251. * @see http://www.cubrid.org/manual/91/en/sql/transaction.html#database-concurrency
  252. */
  253. public function setTransactionIsolationLevel($level)
  254. {
  255. // translate SQL92 levels to CUBRID levels:
  256. switch ($level) {
  257. case Transaction::SERIALIZABLE:
  258. $level = '6'; // SERIALIZABLE
  259. break;
  260. case Transaction::REPEATABLE_READ:
  261. $level = '5'; // REPEATABLE READ CLASS with REPEATABLE READ INSTANCES
  262. break;
  263. case Transaction::READ_COMMITTED:
  264. $level = '4'; // REPEATABLE READ CLASS with READ COMMITTED INSTANCES
  265. break;
  266. case Transaction::READ_UNCOMMITTED:
  267. $level = '3'; // REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES
  268. break;
  269. }
  270. parent::setTransactionIsolationLevel($level);
  271. }
  272. /**
  273. * @inheritdoc
  274. */
  275. public function createColumnSchemaBuilder($type, $length = null)
  276. {
  277. return new ColumnSchemaBuilder($type, $length, $this->db);
  278. }
  279. }