Schema.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\db\cubrid;
  8. use Yii;
  9. use yii\base\NotSupportedException;
  10. use yii\db\Constraint;
  11. use yii\db\ConstraintFinderInterface;
  12. use yii\db\ConstraintFinderTrait;
  13. use yii\db\Expression;
  14. use yii\db\ForeignKeyConstraint;
  15. use yii\db\IndexConstraint;
  16. use yii\db\TableSchema;
  17. use yii\db\Transaction;
  18. use yii\helpers\ArrayHelper;
  19. /**
  20. * Schema is the class for retrieving metadata from a CUBRID database (version 9.3.x and higher).
  21. *
  22. * @author Carsten Brandt <mail@cebe.cc>
  23. * @since 2.0
  24. */
  25. class Schema extends \yii\db\Schema implements ConstraintFinderInterface
  26. {
  27. use ConstraintFinderTrait;
  28. /**
  29. * @var array mapping from physical column types (keys) to abstract column types (values)
  30. * Please refer to [CUBRID manual](https://www.cubrid.org/manual/en/9.3.0/sql/datatype.html) for
  31. * details on data types.
  32. */
  33. public $typeMap = [
  34. // Numeric data types
  35. 'short' => self::TYPE_SMALLINT,
  36. 'smallint' => self::TYPE_SMALLINT,
  37. 'int' => self::TYPE_INTEGER,
  38. 'integer' => self::TYPE_INTEGER,
  39. 'bigint' => self::TYPE_BIGINT,
  40. 'numeric' => self::TYPE_DECIMAL,
  41. 'decimal' => self::TYPE_DECIMAL,
  42. 'float' => self::TYPE_FLOAT,
  43. 'real' => self::TYPE_FLOAT,
  44. 'double' => self::TYPE_DOUBLE,
  45. 'double precision' => self::TYPE_DOUBLE,
  46. 'monetary' => self::TYPE_MONEY,
  47. // Date/Time data types
  48. 'date' => self::TYPE_DATE,
  49. 'time' => self::TYPE_TIME,
  50. 'timestamp' => self::TYPE_TIMESTAMP,
  51. 'datetime' => self::TYPE_DATETIME,
  52. // String data types
  53. 'char' => self::TYPE_CHAR,
  54. 'varchar' => self::TYPE_STRING,
  55. 'char varying' => self::TYPE_STRING,
  56. 'nchar' => self::TYPE_CHAR,
  57. 'nchar varying' => self::TYPE_STRING,
  58. 'string' => self::TYPE_STRING,
  59. // BLOB/CLOB data types
  60. 'blob' => self::TYPE_BINARY,
  61. 'clob' => self::TYPE_BINARY,
  62. // Bit string data types
  63. 'bit' => self::TYPE_INTEGER,
  64. 'bit varying' => self::TYPE_INTEGER,
  65. // Collection data types (considered strings for now)
  66. 'set' => self::TYPE_STRING,
  67. 'multiset' => self::TYPE_STRING,
  68. 'list' => self::TYPE_STRING,
  69. 'sequence' => self::TYPE_STRING,
  70. 'enum' => self::TYPE_STRING,
  71. ];
  72. /**
  73. * @var array map of DB errors and corresponding exceptions
  74. * If left part is found in DB error message exception class from the right part is used.
  75. */
  76. public $exceptionMap = [
  77. 'Operation would have caused one or more unique constraint violations' => 'yii\db\IntegrityException',
  78. ];
  79. /**
  80. * {@inheritdoc}
  81. */
  82. protected $tableQuoteCharacter = '"';
  83. /**
  84. * {@inheritdoc}
  85. */
  86. protected function findTableNames($schema = '')
  87. {
  88. $pdo = $this->db->getSlavePdo(true);
  89. $tables = $pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE);
  90. $tableNames = [];
  91. foreach ($tables as $table) {
  92. // do not list system tables
  93. if ($table['TYPE'] != 0) {
  94. $tableNames[] = $table['NAME'];
  95. }
  96. }
  97. return $tableNames;
  98. }
  99. /**
  100. * {@inheritdoc}
  101. */
  102. protected function loadTableSchema($name)
  103. {
  104. $pdo = $this->db->getSlavePdo(true);
  105. $tableInfo = $pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE, $name);
  106. if (!isset($tableInfo[0]['NAME'])) {
  107. return null;
  108. }
  109. $table = new TableSchema();
  110. $table->fullName = $table->name = $tableInfo[0]['NAME'];
  111. $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteSimpleTableName($table->name);
  112. $columns = $this->db->createCommand($sql)->queryAll();
  113. foreach ($columns as $info) {
  114. $column = $this->loadColumnSchema($info);
  115. $table->columns[$column->name] = $column;
  116. }
  117. $primaryKeys = $pdo->cubrid_schema(\PDO::CUBRID_SCH_PRIMARY_KEY, $table->name);
  118. foreach ($primaryKeys as $key) {
  119. $column = $table->columns[$key['ATTR_NAME']];
  120. $column->isPrimaryKey = true;
  121. $table->primaryKey[] = $column->name;
  122. if ($column->autoIncrement) {
  123. $table->sequenceName = '';
  124. }
  125. }
  126. $foreignKeys = $pdo->cubrid_schema(\PDO::CUBRID_SCH_IMPORTED_KEYS, $table->name);
  127. foreach ($foreignKeys as $key) {
  128. if (isset($table->foreignKeys[$key['FK_NAME']])) {
  129. $table->foreignKeys[$key['FK_NAME']][$key['FKCOLUMN_NAME']] = $key['PKCOLUMN_NAME'];
  130. } else {
  131. $table->foreignKeys[$key['FK_NAME']] = [
  132. $key['PKTABLE_NAME'],
  133. $key['FKCOLUMN_NAME'] => $key['PKCOLUMN_NAME'],
  134. ];
  135. }
  136. }
  137. return $table;
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. protected function loadTablePrimaryKey($tableName)
  143. {
  144. $primaryKey = $this->db->getSlavePdo(true)->cubrid_schema(\PDO::CUBRID_SCH_PRIMARY_KEY, $tableName);
  145. if (empty($primaryKey)) {
  146. return null;
  147. }
  148. ArrayHelper::multisort($primaryKey, 'KEY_SEQ', SORT_ASC, SORT_NUMERIC);
  149. return new Constraint([
  150. 'name' => $primaryKey[0]['KEY_NAME'],
  151. 'columnNames' => ArrayHelper::getColumn($primaryKey, 'ATTR_NAME'),
  152. ]);
  153. }
  154. /**
  155. * {@inheritdoc}
  156. */
  157. protected function loadTableForeignKeys($tableName)
  158. {
  159. static $actionTypes = [
  160. 0 => 'CASCADE',
  161. 1 => 'RESTRICT',
  162. 2 => 'NO ACTION',
  163. 3 => 'SET NULL',
  164. ];
  165. $foreignKeys = $this->db->getSlavePdo(true)->cubrid_schema(\PDO::CUBRID_SCH_IMPORTED_KEYS, $tableName);
  166. $foreignKeys = ArrayHelper::index($foreignKeys, null, 'FK_NAME');
  167. ArrayHelper::multisort($foreignKeys, 'KEY_SEQ', SORT_ASC, SORT_NUMERIC);
  168. $result = [];
  169. foreach ($foreignKeys as $name => $foreignKey) {
  170. $result[] = new ForeignKeyConstraint([
  171. 'name' => $name,
  172. 'columnNames' => ArrayHelper::getColumn($foreignKey, 'FKCOLUMN_NAME'),
  173. 'foreignTableName' => $foreignKey[0]['PKTABLE_NAME'],
  174. 'foreignColumnNames' => ArrayHelper::getColumn($foreignKey, 'PKCOLUMN_NAME'),
  175. 'onDelete' => isset($actionTypes[$foreignKey[0]['DELETE_RULE']]) ? $actionTypes[$foreignKey[0]['DELETE_RULE']] : null,
  176. 'onUpdate' => isset($actionTypes[$foreignKey[0]['UPDATE_RULE']]) ? $actionTypes[$foreignKey[0]['UPDATE_RULE']] : null,
  177. ]);
  178. }
  179. return $result;
  180. }
  181. /**
  182. * {@inheritdoc}
  183. */
  184. protected function loadTableIndexes($tableName)
  185. {
  186. return $this->loadTableConstraints($tableName, 'indexes');
  187. }
  188. /**
  189. * {@inheritdoc}
  190. */
  191. protected function loadTableUniques($tableName)
  192. {
  193. return $this->loadTableConstraints($tableName, 'uniques');
  194. }
  195. /**
  196. * {@inheritdoc}
  197. * @throws NotSupportedException if this method is called.
  198. */
  199. protected function loadTableChecks($tableName)
  200. {
  201. throw new NotSupportedException('CUBRID does not support check constraints.');
  202. }
  203. /**
  204. * {@inheritdoc}
  205. * @throws NotSupportedException if this method is called.
  206. */
  207. protected function loadTableDefaultValues($tableName)
  208. {
  209. throw new NotSupportedException('CUBRID does not support default value constraints.');
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. public function releaseSavepoint($name)
  215. {
  216. // does nothing as cubrid does not support this
  217. }
  218. /**
  219. * Creates a query builder for the CUBRID database.
  220. * @return QueryBuilder query builder instance
  221. */
  222. public function createQueryBuilder()
  223. {
  224. return Yii::createObject(QueryBuilder::className(), [$this->db]);
  225. }
  226. /**
  227. * Loads the column information into a [[ColumnSchema]] object.
  228. * @param array $info column information
  229. * @return \yii\db\ColumnSchema the column schema object
  230. */
  231. protected function loadColumnSchema($info)
  232. {
  233. $column = $this->createColumnSchema();
  234. $column->name = $info['Field'];
  235. $column->allowNull = $info['Null'] === 'YES';
  236. $column->isPrimaryKey = false; // primary key will be set by loadTableSchema() later
  237. $column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false;
  238. $column->dbType = $info['Type'];
  239. $column->unsigned = strpos($column->dbType, 'unsigned') !== false;
  240. $column->type = self::TYPE_STRING;
  241. if (preg_match('/^([\w ]+)(?:\(([^\)]+)\))?$/', $column->dbType, $matches)) {
  242. $type = strtolower($matches[1]);
  243. $column->dbType = $type . (isset($matches[2]) ? "({$matches[2]})" : '');
  244. if (isset($this->typeMap[$type])) {
  245. $column->type = $this->typeMap[$type];
  246. }
  247. if (!empty($matches[2])) {
  248. if ($type === 'enum') {
  249. $values = preg_split('/\s*,\s*/', $matches[2]);
  250. foreach ($values as $i => $value) {
  251. $values[$i] = trim($value, "'");
  252. }
  253. $column->enumValues = $values;
  254. } else {
  255. $values = explode(',', $matches[2]);
  256. $column->size = $column->precision = (int) $values[0];
  257. if (isset($values[1])) {
  258. $column->scale = (int) $values[1];
  259. }
  260. if ($column->size === 1 && $type === 'bit') {
  261. $column->type = 'boolean';
  262. } elseif ($type === 'bit') {
  263. if ($column->size > 32) {
  264. $column->type = 'bigint';
  265. } elseif ($column->size === 32) {
  266. $column->type = 'integer';
  267. }
  268. }
  269. }
  270. }
  271. }
  272. $column->phpType = $this->getColumnPhpType($column);
  273. if ($column->isPrimaryKey) {
  274. return $column;
  275. }
  276. if (
  277. $column->type === 'timestamp' && $info['Default'] === 'SYS_TIMESTAMP' ||
  278. $column->type === 'datetime' && $info['Default'] === 'SYS_DATETIME' ||
  279. $column->type === 'date' && $info['Default'] === 'SYS_DATE' ||
  280. $column->type === 'time' && $info['Default'] === 'SYS_TIME'
  281. ) {
  282. $column->defaultValue = new Expression($info['Default']);
  283. } elseif (isset($type) && $type === 'bit') {
  284. $column->defaultValue = hexdec(trim($info['Default'], 'X\''));
  285. } else {
  286. $column->defaultValue = $column->phpTypecast($info['Default']);
  287. }
  288. return $column;
  289. }
  290. /**
  291. * Determines the PDO type for the given PHP data value.
  292. * @param mixed $data the data whose PDO type is to be determined
  293. * @return int the PDO type
  294. * @see https://www.php.net/manual/en/pdo.constants.php
  295. */
  296. public function getPdoType($data)
  297. {
  298. static $typeMap = [
  299. // php type => PDO type
  300. 'boolean' => \PDO::PARAM_INT, // PARAM_BOOL is not supported by CUBRID PDO
  301. 'integer' => \PDO::PARAM_INT,
  302. 'string' => \PDO::PARAM_STR,
  303. 'resource' => \PDO::PARAM_LOB,
  304. 'NULL' => \PDO::PARAM_NULL,
  305. ];
  306. $type = gettype($data);
  307. return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
  308. }
  309. /**
  310. * {@inheritdoc}
  311. * @see https://www.cubrid.org/manual/en/9.3.0/sql/transaction.html#database-concurrency
  312. */
  313. public function setTransactionIsolationLevel($level)
  314. {
  315. // translate SQL92 levels to CUBRID levels:
  316. switch ($level) {
  317. case Transaction::SERIALIZABLE:
  318. $level = '6'; // SERIALIZABLE
  319. break;
  320. case Transaction::REPEATABLE_READ:
  321. $level = '5'; // REPEATABLE READ CLASS with REPEATABLE READ INSTANCES
  322. break;
  323. case Transaction::READ_COMMITTED:
  324. $level = '4'; // REPEATABLE READ CLASS with READ COMMITTED INSTANCES
  325. break;
  326. case Transaction::READ_UNCOMMITTED:
  327. $level = '3'; // REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES
  328. break;
  329. }
  330. parent::setTransactionIsolationLevel($level);
  331. }
  332. /**
  333. * {@inheritdoc}
  334. */
  335. public function createColumnSchemaBuilder($type, $length = null)
  336. {
  337. return new ColumnSchemaBuilder($type, $length, $this->db);
  338. }
  339. /**
  340. * Loads multiple types of constraints and returns the specified ones.
  341. * @param string $tableName table name.
  342. * @param string $returnType return type:
  343. * - indexes
  344. * - uniques
  345. * @return mixed constraints.
  346. */
  347. private function loadTableConstraints($tableName, $returnType)
  348. {
  349. $constraints = $this->db->getSlavePdo(true)->cubrid_schema(\PDO::CUBRID_SCH_CONSTRAINT, $tableName);
  350. $constraints = ArrayHelper::index($constraints, null, ['TYPE', 'NAME']);
  351. ArrayHelper::multisort($constraints, 'KEY_ORDER', SORT_ASC, SORT_NUMERIC);
  352. $result = [
  353. 'indexes' => [],
  354. 'uniques' => [],
  355. ];
  356. foreach ($constraints as $type => $names) {
  357. foreach ($names as $name => $constraint) {
  358. $isUnique = in_array((int) $type, [0, 2], true);
  359. $result['indexes'][] = new IndexConstraint([
  360. 'isPrimary' => (bool) $constraint[0]['PRIMARY_KEY'],
  361. 'isUnique' => $isUnique,
  362. 'name' => $name,
  363. 'columnNames' => ArrayHelper::getColumn($constraint, 'ATTR_NAME'),
  364. ]);
  365. if ($isUnique) {
  366. $result['uniques'][] = new Constraint([
  367. 'name' => $name,
  368. 'columnNames' => ArrayHelper::getColumn($constraint, 'ATTR_NAME'),
  369. ]);
  370. }
  371. }
  372. }
  373. foreach ($result as $type => $data) {
  374. $this->setTableMetadata($tableName, $type, $data);
  375. }
  376. return $result[$returnType];
  377. }
  378. }