QueryBuilder.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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\base\InvalidArgumentException;
  9. use yii\base\NotSupportedException;
  10. use yii\db\Constraint;
  11. use yii\db\Exception;
  12. use yii\db\Expression;
  13. /**
  14. * QueryBuilder is the query builder for CUBRID databases (version 9.3.x and higher).
  15. *
  16. * @author Carsten Brandt <mail@cebe.cc>
  17. * @since 2.0
  18. */
  19. class QueryBuilder extends \yii\db\QueryBuilder
  20. {
  21. /**
  22. * @var array mapping from abstract column types (keys) to physical column types (values).
  23. */
  24. public $typeMap = [
  25. Schema::TYPE_PK => 'int NOT NULL AUTO_INCREMENT PRIMARY KEY',
  26. Schema::TYPE_UPK => 'int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
  27. Schema::TYPE_BIGPK => 'bigint NOT NULL AUTO_INCREMENT PRIMARY KEY',
  28. Schema::TYPE_UBIGPK => 'bigint UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
  29. Schema::TYPE_CHAR => 'char(1)',
  30. Schema::TYPE_STRING => 'varchar(255)',
  31. Schema::TYPE_TEXT => 'varchar',
  32. Schema::TYPE_TINYINT => 'smallint',
  33. Schema::TYPE_SMALLINT => 'smallint',
  34. Schema::TYPE_INTEGER => 'int',
  35. Schema::TYPE_BIGINT => 'bigint',
  36. Schema::TYPE_FLOAT => 'float(7)',
  37. Schema::TYPE_DOUBLE => 'double(15)',
  38. Schema::TYPE_DECIMAL => 'decimal(10,0)',
  39. Schema::TYPE_DATETIME => 'datetime',
  40. Schema::TYPE_TIMESTAMP => 'timestamp',
  41. Schema::TYPE_TIME => 'time',
  42. Schema::TYPE_DATE => 'date',
  43. Schema::TYPE_BINARY => 'blob',
  44. Schema::TYPE_BOOLEAN => 'smallint',
  45. Schema::TYPE_MONEY => 'decimal(19,4)',
  46. ];
  47. /**
  48. * {@inheritdoc}
  49. */
  50. protected function defaultExpressionBuilders()
  51. {
  52. return array_merge(parent::defaultExpressionBuilders(), [
  53. 'yii\db\conditions\LikeCondition' => 'yii\db\cubrid\conditions\LikeConditionBuilder',
  54. ]);
  55. }
  56. /**
  57. * {@inheritdoc}
  58. * @see https://www.cubrid.org/manual/en/9.3.0/sql/query/merge.html
  59. */
  60. public function upsert($table, $insertColumns, $updateColumns, &$params)
  61. {
  62. /** @var Constraint[] $constraints */
  63. list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
  64. if (empty($uniqueNames)) {
  65. return $this->insert($table, $insertColumns, $params);
  66. }
  67. $onCondition = ['or'];
  68. $quotedTableName = $this->db->quoteTableName($table);
  69. foreach ($constraints as $constraint) {
  70. $constraintCondition = ['and'];
  71. foreach ($constraint->columnNames as $name) {
  72. $quotedName = $this->db->quoteColumnName($name);
  73. $constraintCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
  74. }
  75. $onCondition[] = $constraintCondition;
  76. }
  77. $on = $this->buildCondition($onCondition, $params);
  78. list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
  79. $mergeSql = 'MERGE INTO ' . $this->db->quoteTableName($table) . ' '
  80. . 'USING (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') AS "EXCLUDED" (' . implode(', ', $insertNames) . ') '
  81. . "ON ($on)";
  82. $insertValues = [];
  83. foreach ($insertNames as $name) {
  84. $quotedName = $this->db->quoteColumnName($name);
  85. if (strrpos($quotedName, '.') === false) {
  86. $quotedName = '"EXCLUDED".' . $quotedName;
  87. }
  88. $insertValues[] = $quotedName;
  89. }
  90. $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')'
  91. . ' VALUES (' . implode(', ', $insertValues) . ')';
  92. if ($updateColumns === false) {
  93. return "$mergeSql WHEN NOT MATCHED THEN $insertSql";
  94. }
  95. if ($updateColumns === true) {
  96. $updateColumns = [];
  97. foreach ($updateNames as $name) {
  98. $quotedName = $this->db->quoteColumnName($name);
  99. if (strrpos($quotedName, '.') === false) {
  100. $quotedName = '"EXCLUDED".' . $quotedName;
  101. }
  102. $updateColumns[$name] = new Expression($quotedName);
  103. }
  104. }
  105. list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
  106. $updateSql = 'UPDATE SET ' . implode(', ', $updates);
  107. return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql";
  108. }
  109. /**
  110. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  111. * The sequence will be reset such that the primary key of the next new row inserted
  112. * will have the specified value or 1.
  113. * @param string $tableName the name of the table whose primary key sequence will be reset
  114. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  115. * the next new row's primary key will have a value 1.
  116. * @return string the SQL statement for resetting sequence
  117. * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
  118. */
  119. public function resetSequence($tableName, $value = null)
  120. {
  121. $table = $this->db->getTableSchema($tableName);
  122. if ($table !== null && $table->sequenceName !== null) {
  123. $tableName = $this->db->quoteTableName($tableName);
  124. if ($value === null) {
  125. $key = reset($table->primaryKey);
  126. $value = (int) $this->db->createCommand("SELECT MAX(`$key`) FROM " . $this->db->schema->quoteTableName($tableName))->queryScalar() + 1;
  127. } else {
  128. $value = (int) $value;
  129. }
  130. return 'ALTER TABLE ' . $this->db->schema->quoteTableName($tableName) . " AUTO_INCREMENT=$value;";
  131. } elseif ($table === null) {
  132. throw new InvalidArgumentException("Table not found: $tableName");
  133. }
  134. throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function buildLimit($limit, $offset)
  140. {
  141. $sql = '';
  142. // limit is not optional in CUBRID
  143. // http://www.cubrid.org/manual/90/en/LIMIT%20Clause
  144. // "You can specify a very big integer for row_count to display to the last row, starting from a specific row."
  145. if ($this->hasLimit($limit)) {
  146. $sql = 'LIMIT ' . $limit;
  147. if ($this->hasOffset($offset)) {
  148. $sql .= ' OFFSET ' . $offset;
  149. }
  150. } elseif ($this->hasOffset($offset)) {
  151. $sql = "LIMIT 9223372036854775807 OFFSET $offset"; // 2^63-1
  152. }
  153. return $sql;
  154. }
  155. /**
  156. * {@inheritdoc}
  157. * @since 2.0.8
  158. */
  159. public function selectExists($rawSql)
  160. {
  161. return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END';
  162. }
  163. /**
  164. * {@inheritdoc}
  165. * @see http://www.cubrid.org/manual/93/en/sql/schema/table.html#drop-index-clause
  166. */
  167. public function dropIndex($name, $table)
  168. {
  169. /** @var Schema $schema */
  170. $schema = $this->db->getSchema();
  171. foreach ($schema->getTableUniques($table) as $unique) {
  172. if ($unique->name === $name) {
  173. return $this->dropUnique($name, $table);
  174. }
  175. }
  176. return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
  177. }
  178. /**
  179. * {@inheritdoc}
  180. * @throws NotSupportedException this is not supported by CUBRID.
  181. */
  182. public function addCheck($name, $table, $expression)
  183. {
  184. throw new NotSupportedException(__METHOD__ . ' is not supported by CUBRID.');
  185. }
  186. /**
  187. * {@inheritdoc}
  188. * @throws NotSupportedException this is not supported by CUBRID.
  189. */
  190. public function dropCheck($name, $table)
  191. {
  192. throw new NotSupportedException(__METHOD__ . ' is not supported by CUBRID.');
  193. }
  194. /**
  195. * {@inheritdoc}
  196. * @since 2.0.8
  197. */
  198. public function addCommentOnColumn($table, $column, $comment)
  199. {
  200. $definition = $this->getColumnDefinition($table, $column);
  201. $definition = trim(preg_replace("/COMMENT '(.*?)'/i", '', $definition));
  202. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  203. . ' CHANGE ' . $this->db->quoteColumnName($column)
  204. . ' ' . $this->db->quoteColumnName($column)
  205. . (empty($definition) ? '' : ' ' . $definition)
  206. . ' COMMENT ' . $this->db->quoteValue($comment);
  207. }
  208. /**
  209. * {@inheritdoc}
  210. * @since 2.0.8
  211. */
  212. public function addCommentOnTable($table, $comment)
  213. {
  214. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' COMMENT ' . $this->db->quoteValue($comment);
  215. }
  216. /**
  217. * {@inheritdoc}
  218. * @since 2.0.8
  219. */
  220. public function dropCommentFromColumn($table, $column)
  221. {
  222. return $this->addCommentOnColumn($table, $column, '');
  223. }
  224. /**
  225. * {@inheritdoc}
  226. * @since 2.0.8
  227. */
  228. public function dropCommentFromTable($table)
  229. {
  230. return $this->addCommentOnTable($table, '');
  231. }
  232. /**
  233. * Gets column definition.
  234. *
  235. * @param string $table table name
  236. * @param string $column column name
  237. * @return null|string the column definition
  238. * @throws Exception in case when table does not contain column
  239. * @since 2.0.8
  240. */
  241. private function getColumnDefinition($table, $column)
  242. {
  243. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->db->quoteTableName($table))->queryOne();
  244. if ($row === false) {
  245. throw new Exception("Unable to find column '$column' in table '$table'.");
  246. }
  247. if (isset($row['Create Table'])) {
  248. $sql = $row['Create Table'];
  249. } else {
  250. $row = array_values($row);
  251. $sql = $row[1];
  252. }
  253. $sql = preg_replace('/^[^(]+\((.*)\).*$/', '\1', $sql);
  254. $sql = str_replace(', [', ",\n[", $sql);
  255. if (preg_match_all('/^\s*\[(.*?)\]\s+(.*?),?$/m', $sql, $matches)) {
  256. foreach ($matches[1] as $i => $c) {
  257. if ($c === $column) {
  258. return $matches[2][$i];
  259. }
  260. }
  261. }
  262. return null;
  263. }
  264. }