QueryBuilder.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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\oci;
  8. use yii\base\InvalidArgumentException;
  9. use yii\db\Connection;
  10. use yii\db\Constraint;
  11. use yii\db\Exception;
  12. use yii\db\Expression;
  13. use yii\db\Query;
  14. use yii\helpers\StringHelper;
  15. use yii\db\ExpressionInterface;
  16. /**
  17. * QueryBuilder is the query builder for Oracle databases.
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class QueryBuilder extends \yii\db\QueryBuilder
  23. {
  24. /**
  25. * @var array mapping from abstract column types (keys) to physical column types (values).
  26. */
  27. public $typeMap = [
  28. Schema::TYPE_PK => 'NUMBER(10) NOT NULL PRIMARY KEY',
  29. Schema::TYPE_UPK => 'NUMBER(10) UNSIGNED NOT NULL PRIMARY KEY',
  30. Schema::TYPE_BIGPK => 'NUMBER(20) NOT NULL PRIMARY KEY',
  31. Schema::TYPE_UBIGPK => 'NUMBER(20) UNSIGNED NOT NULL PRIMARY KEY',
  32. Schema::TYPE_CHAR => 'CHAR(1)',
  33. Schema::TYPE_STRING => 'VARCHAR2(255)',
  34. Schema::TYPE_TEXT => 'CLOB',
  35. Schema::TYPE_TINYINT => 'NUMBER(3)',
  36. Schema::TYPE_SMALLINT => 'NUMBER(5)',
  37. Schema::TYPE_INTEGER => 'NUMBER(10)',
  38. Schema::TYPE_BIGINT => 'NUMBER(20)',
  39. Schema::TYPE_FLOAT => 'NUMBER',
  40. Schema::TYPE_DOUBLE => 'NUMBER',
  41. Schema::TYPE_DECIMAL => 'NUMBER',
  42. Schema::TYPE_DATETIME => 'TIMESTAMP',
  43. Schema::TYPE_TIMESTAMP => 'TIMESTAMP',
  44. Schema::TYPE_TIME => 'TIMESTAMP',
  45. Schema::TYPE_DATE => 'DATE',
  46. Schema::TYPE_BINARY => 'BLOB',
  47. Schema::TYPE_BOOLEAN => 'NUMBER(1)',
  48. Schema::TYPE_MONEY => 'NUMBER(19,4)',
  49. ];
  50. /**
  51. * {@inheritdoc}
  52. */
  53. protected function defaultExpressionBuilders()
  54. {
  55. return array_merge(parent::defaultExpressionBuilders(), [
  56. 'yii\db\conditions\InCondition' => 'yii\db\oci\conditions\InConditionBuilder',
  57. 'yii\db\conditions\LikeCondition' => 'yii\db\oci\conditions\LikeConditionBuilder',
  58. ]);
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  64. {
  65. $orderBy = $this->buildOrderBy($orderBy);
  66. if ($orderBy !== '') {
  67. $sql .= $this->separator . $orderBy;
  68. }
  69. $filters = [];
  70. if ($this->hasOffset($offset)) {
  71. $filters[] = 'rowNumId > ' . $offset;
  72. }
  73. if ($this->hasLimit($limit)) {
  74. $filters[] = 'rownum <= ' . $limit;
  75. }
  76. if (empty($filters)) {
  77. return $sql;
  78. }
  79. $filter = implode(' AND ', $filters);
  80. return <<<EOD
  81. WITH USER_SQL AS ($sql),
  82. PAGINATION AS (SELECT USER_SQL.*, rownum as rowNumId FROM USER_SQL)
  83. SELECT *
  84. FROM PAGINATION
  85. WHERE $filter
  86. EOD;
  87. }
  88. /**
  89. * Builds a SQL statement for renaming a DB table.
  90. *
  91. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  92. * @param string $newName the new table name. The name will be properly quoted by the method.
  93. * @return string the SQL statement for renaming a DB table.
  94. */
  95. public function renameTable($table, $newName)
  96. {
  97. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' RENAME TO ' . $this->db->quoteTableName($newName);
  98. }
  99. /**
  100. * Builds a SQL statement for changing the definition of a column.
  101. *
  102. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  103. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  104. * @param string $type the new column type. The [[getColumnType]] method will be invoked to convert abstract column type (if any)
  105. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  106. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  107. * @return string the SQL statement for changing the definition of a column.
  108. */
  109. public function alterColumn($table, $column, $type)
  110. {
  111. $type = $this->getColumnType($type);
  112. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' MODIFY ' . $this->db->quoteColumnName($column) . ' ' . $this->getColumnType($type);
  113. }
  114. /**
  115. * Builds a SQL statement for dropping an index.
  116. *
  117. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  118. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  119. * @return string the SQL statement for dropping an index.
  120. */
  121. public function dropIndex($name, $table)
  122. {
  123. return 'DROP INDEX ' . $this->db->quoteTableName($name);
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function executeResetSequence($table, $value = null)
  129. {
  130. $tableSchema = $this->db->getTableSchema($table);
  131. if ($tableSchema === null) {
  132. throw new InvalidArgumentException("Unknown table: $table");
  133. }
  134. if ($tableSchema->sequenceName === null) {
  135. throw new InvalidArgumentException("There is no sequence associated with table: $table");
  136. }
  137. if ($value !== null) {
  138. $value = (int) $value;
  139. } else {
  140. if (count($tableSchema->primaryKey)>1) {
  141. throw new InvalidArgumentException("Can't reset sequence for composite primary key in table: $table");
  142. }
  143. // use master connection to get the biggest PK value
  144. $value = $this->db->useMaster(function (Connection $db) use ($tableSchema) {
  145. return $db->createCommand(
  146. 'SELECT MAX("' . $tableSchema->primaryKey[0] . '") FROM "'. $tableSchema->name . '"'
  147. )->queryScalar();
  148. }) + 1;
  149. }
  150. //Oracle needs at least two queries to reset sequence (see adding transactions and/or use alter method to avoid grants' issue?)
  151. $this->db->createCommand('DROP SEQUENCE "' . $tableSchema->sequenceName . '"')->execute();
  152. $this->db->createCommand('CREATE SEQUENCE "' . $tableSchema->sequenceName . '" START WITH ' . $value
  153. . ' INCREMENT BY 1 NOMAXVALUE NOCACHE')->execute();
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  159. {
  160. $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
  161. . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
  162. . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
  163. . ' REFERENCES ' . $this->db->quoteTableName($refTable)
  164. . ' (' . $this->buildColumns($refColumns) . ')';
  165. if ($delete !== null) {
  166. $sql .= ' ON DELETE ' . $delete;
  167. }
  168. if ($update !== null) {
  169. throw new Exception('Oracle does not support ON UPDATE clause.');
  170. }
  171. return $sql;
  172. }
  173. /**
  174. * {@inheritdoc}
  175. */
  176. protected function prepareInsertValues($table, $columns, $params = [])
  177. {
  178. list($names, $placeholders, $values, $params) = parent::prepareInsertValues($table, $columns, $params);
  179. if (!$columns instanceof Query && empty($names)) {
  180. $tableSchema = $this->db->getSchema()->getTableSchema($table);
  181. if ($tableSchema !== null) {
  182. $columns = !empty($tableSchema->primaryKey) ? $tableSchema->primaryKey : [reset($tableSchema->columns)->name];
  183. foreach ($columns as $name) {
  184. $names[] = $this->db->quoteColumnName($name);
  185. $placeholders[] = 'DEFAULT';
  186. }
  187. }
  188. }
  189. return [$names, $placeholders, $values, $params];
  190. }
  191. /**
  192. * {@inheritdoc}
  193. * @see https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606
  194. */
  195. public function upsert($table, $insertColumns, $updateColumns, &$params)
  196. {
  197. /** @var Constraint[] $constraints */
  198. list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
  199. if (empty($uniqueNames)) {
  200. return $this->insert($table, $insertColumns, $params);
  201. }
  202. $onCondition = ['or'];
  203. $quotedTableName = $this->db->quoteTableName($table);
  204. foreach ($constraints as $constraint) {
  205. $constraintCondition = ['and'];
  206. foreach ($constraint->columnNames as $name) {
  207. $quotedName = $this->db->quoteColumnName($name);
  208. $constraintCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
  209. }
  210. $onCondition[] = $constraintCondition;
  211. }
  212. $on = $this->buildCondition($onCondition, $params);
  213. list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
  214. if (!empty($placeholders)) {
  215. $usingSelectValues = [];
  216. foreach ($insertNames as $index => $name) {
  217. $usingSelectValues[$name] = new Expression($placeholders[$index]);
  218. }
  219. $usingSubQuery = (new Query())
  220. ->select($usingSelectValues)
  221. ->from('DUAL');
  222. list($usingValues, $params) = $this->build($usingSubQuery, $params);
  223. }
  224. $mergeSql = 'MERGE INTO ' . $this->db->quoteTableName($table) . ' '
  225. . 'USING (' . (isset($usingValues) ? $usingValues : ltrim($values, ' ')) . ') "EXCLUDED" '
  226. . "ON ($on)";
  227. $insertValues = [];
  228. foreach ($insertNames as $name) {
  229. $quotedName = $this->db->quoteColumnName($name);
  230. if (strrpos($quotedName, '.') === false) {
  231. $quotedName = '"EXCLUDED".' . $quotedName;
  232. }
  233. $insertValues[] = $quotedName;
  234. }
  235. $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')'
  236. . ' VALUES (' . implode(', ', $insertValues) . ')';
  237. if ($updateColumns === false) {
  238. return "$mergeSql WHEN NOT MATCHED THEN $insertSql";
  239. }
  240. if ($updateColumns === true) {
  241. $updateColumns = [];
  242. foreach ($updateNames as $name) {
  243. $quotedName = $this->db->quoteColumnName($name);
  244. if (strrpos($quotedName, '.') === false) {
  245. $quotedName = '"EXCLUDED".' . $quotedName;
  246. }
  247. $updateColumns[$name] = new Expression($quotedName);
  248. }
  249. }
  250. list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
  251. $updateSql = 'UPDATE SET ' . implode(', ', $updates);
  252. return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql";
  253. }
  254. /**
  255. * Generates a batch INSERT SQL statement.
  256. *
  257. * For example,
  258. *
  259. * ```php
  260. * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
  261. * ['Tom', 30],
  262. * ['Jane', 20],
  263. * ['Linda', 25],
  264. * ]);
  265. * ```
  266. *
  267. * Note that the values in each row must match the corresponding column names.
  268. *
  269. * @param string $table the table that new rows will be inserted into.
  270. * @param array $columns the column names
  271. * @param array|\Generator $rows the rows to be batch inserted into the table
  272. * @return string the batch INSERT SQL statement
  273. */
  274. public function batchInsert($table, $columns, $rows, &$params = [])
  275. {
  276. if (empty($rows)) {
  277. return '';
  278. }
  279. $schema = $this->db->getSchema();
  280. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  281. $columnSchemas = $tableSchema->columns;
  282. } else {
  283. $columnSchemas = [];
  284. }
  285. $values = [];
  286. foreach ($rows as $row) {
  287. $vs = [];
  288. foreach ($row as $i => $value) {
  289. if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
  290. $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
  291. }
  292. if (is_string($value)) {
  293. $value = $schema->quoteValue($value);
  294. } elseif (is_float($value)) {
  295. // ensure type cast always has . as decimal separator in all locales
  296. $value = StringHelper::floatToString($value);
  297. } elseif ($value === false) {
  298. $value = 0;
  299. } elseif ($value === null) {
  300. $value = 'NULL';
  301. } elseif ($value instanceof ExpressionInterface) {
  302. $value = $this->buildExpression($value, $params);
  303. }
  304. $vs[] = $value;
  305. }
  306. $values[] = '(' . implode(', ', $vs) . ')';
  307. }
  308. if (empty($values)) {
  309. return '';
  310. }
  311. foreach ($columns as $i => $name) {
  312. $columns[$i] = $schema->quoteColumnName($name);
  313. }
  314. $tableAndColumns = ' INTO ' . $schema->quoteTableName($table)
  315. . ' (' . implode(', ', $columns) . ') VALUES ';
  316. return 'INSERT ALL ' . $tableAndColumns . implode($tableAndColumns, $values) . ' SELECT 1 FROM SYS.DUAL';
  317. }
  318. /**
  319. * {@inheritdoc}
  320. * @since 2.0.8
  321. */
  322. public function selectExists($rawSql)
  323. {
  324. return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END FROM DUAL';
  325. }
  326. /**
  327. * {@inheritdoc}
  328. * @since 2.0.8
  329. */
  330. public function dropCommentFromColumn($table, $column)
  331. {
  332. return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . " IS ''";
  333. }
  334. /**
  335. * {@inheritdoc}
  336. * @since 2.0.8
  337. */
  338. public function dropCommentFromTable($table)
  339. {
  340. return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . " IS ''";
  341. }
  342. }