PageRenderTime 42ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/db/oci/QueryBuilder.php

https://gitlab.com/brucealdridge/yii2
PHP | 260 lines | 167 code | 23 blank | 70 comment | 22 complexity | 965f46785ed7ba265f42ea10f2253361 MD5 | raw file
  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\InvalidParamException;
  9. use yii\db\Connection;
  10. use yii\db\Exception;
  11. use yii\db\Expression;
  12. /**
  13. * QueryBuilder is the query builder for Oracle databases.
  14. *
  15. * @author Qiang Xue <qiang.xue@gmail.com>
  16. * @since 2.0
  17. */
  18. class QueryBuilder extends \yii\db\QueryBuilder
  19. {
  20. /**
  21. * @var array mapping from abstract column types (keys) to physical column types (values).
  22. */
  23. public $typeMap = [
  24. Schema::TYPE_PK => 'NUMBER(10) NOT NULL PRIMARY KEY',
  25. Schema::TYPE_BIGPK => 'NUMBER(20) NOT NULL PRIMARY KEY',
  26. Schema::TYPE_STRING => 'VARCHAR2(255)',
  27. Schema::TYPE_TEXT => 'CLOB',
  28. Schema::TYPE_SMALLINT => 'NUMBER(5)',
  29. Schema::TYPE_INTEGER => 'NUMBER(10)',
  30. Schema::TYPE_BIGINT => 'NUMBER(20)',
  31. Schema::TYPE_FLOAT => 'NUMBER',
  32. Schema::TYPE_DOUBLE => 'NUMBER',
  33. Schema::TYPE_DECIMAL => 'NUMBER',
  34. Schema::TYPE_DATETIME => 'TIMESTAMP',
  35. Schema::TYPE_TIMESTAMP => 'TIMESTAMP',
  36. Schema::TYPE_TIME => 'TIMESTAMP',
  37. Schema::TYPE_DATE => 'DATE',
  38. Schema::TYPE_BINARY => 'BLOB',
  39. Schema::TYPE_BOOLEAN => 'NUMBER(1)',
  40. Schema::TYPE_MONEY => 'NUMBER(19,4)',
  41. ];
  42. /**
  43. * @inheritdoc
  44. */
  45. public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  46. {
  47. $orderBy = $this->buildOrderBy($orderBy);
  48. if ($orderBy !== '') {
  49. $sql .= $this->separator . $orderBy;
  50. }
  51. $filters = [];
  52. if ($this->hasOffset($offset)) {
  53. $filters[] = 'rowNumId > ' . $offset;
  54. }
  55. if ($this->hasLimit($limit)) {
  56. $filters[] = 'rownum <= ' . $limit;
  57. }
  58. if (empty($filters)) {
  59. return $sql;
  60. }
  61. $filter = implode(' AND ', $filters);
  62. return <<<EOD
  63. WITH USER_SQL AS ($sql),
  64. PAGINATION AS (SELECT USER_SQL.*, rownum as rowNumId FROM USER_SQL)
  65. SELECT *
  66. FROM PAGINATION
  67. WHERE $filter
  68. EOD;
  69. }
  70. /**
  71. * Builds a SQL statement for renaming a DB table.
  72. *
  73. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  74. * @param string $newName the new table name. The name will be properly quoted by the method.
  75. * @return string the SQL statement for renaming a DB table.
  76. */
  77. public function renameTable($table, $newName)
  78. {
  79. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' RENAME TO ' . $this->db->quoteTableName($newName);
  80. }
  81. /**
  82. * Builds a SQL statement for changing the definition of a column.
  83. *
  84. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  85. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  86. * @param string $type the new column type. The [[getColumnType]] method will be invoked to convert abstract column type (if any)
  87. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  88. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  89. * @return string the SQL statement for changing the definition of a column.
  90. */
  91. public function alterColumn($table, $column, $type)
  92. {
  93. $type = $this->getColumnType($type);
  94. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' MODIFY ' . $this->db->quoteColumnName($column) . ' ' . $this->getColumnType($type);
  95. }
  96. /**
  97. * Builds a SQL statement for dropping an index.
  98. *
  99. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  100. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  101. * @return string the SQL statement for dropping an index.
  102. */
  103. public function dropIndex($name, $table)
  104. {
  105. return 'DROP INDEX ' . $this->db->quoteTableName($name);
  106. }
  107. /**
  108. * @inheritdoc
  109. */
  110. public function resetSequence($table, $value = null)
  111. {
  112. $tableSchema = $this->db->getTableSchema($table);
  113. if ($tableSchema === null) {
  114. throw new InvalidParamException("Unknown table: $table");
  115. }
  116. if ($tableSchema->sequenceName === null) {
  117. return '';
  118. }
  119. if ($value !== null) {
  120. $value = (int) $value;
  121. } else {
  122. // use master connection to get the biggest PK value
  123. $value = $this->db->useMaster(function (Connection $db) use ($tableSchema) {
  124. return $db->createCommand("SELECT MAX(\"{$tableSchema->primaryKey}\") FROM \"{$tableSchema->name}\"")->queryScalar();
  125. }) + 1;
  126. }
  127. return "DROP SEQUENCE \"{$tableSchema->name}_SEQ\";"
  128. . "CREATE SEQUENCE \"{$tableSchema->name}_SEQ\" START WITH {$value} INCREMENT BY 1 NOMAXVALUE NOCACHE";
  129. }
  130. /**
  131. * @inheritdoc
  132. */
  133. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  134. {
  135. $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
  136. . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
  137. . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
  138. . ' REFERENCES ' . $this->db->quoteTableName($refTable)
  139. . ' (' . $this->buildColumns($refColumns) . ')';
  140. if ($delete !== null) {
  141. $sql .= ' ON DELETE ' . $delete;
  142. }
  143. if ($update !== null) {
  144. throw new Exception('Oracle does not support ON UPDATE clause.');
  145. }
  146. return $sql;
  147. }
  148. /**
  149. * @inheritdoc
  150. */
  151. public function insert($table, $columns, &$params)
  152. {
  153. $schema = $this->db->getSchema();
  154. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  155. $columnSchemas = $tableSchema->columns;
  156. } else {
  157. $columnSchemas = [];
  158. }
  159. $names = [];
  160. $placeholders = [];
  161. foreach ($columns as $name => $value) {
  162. $names[] = $schema->quoteColumnName($name);
  163. if ($value instanceof Expression) {
  164. $placeholders[] = $value->expression;
  165. foreach ($value->params as $n => $v) {
  166. $params[$n] = $v;
  167. }
  168. } else {
  169. $phName = self::PARAM_PREFIX . count($params);
  170. $placeholders[] = $phName;
  171. $params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
  172. }
  173. }
  174. if (empty($names) && $tableSchema !== null) {
  175. $columns = !empty($tableSchema->primaryKey) ? $tableSchema->primaryKey : reset($tableSchema->columns)->name;
  176. foreach ($columns as $name) {
  177. $names[] = $schema->quoteColumnName($name);
  178. $placeholders[] = 'DEFAULT';
  179. }
  180. }
  181. return 'INSERT INTO ' . $schema->quoteTableName($table)
  182. . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
  183. . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : ' DEFAULT VALUES');
  184. }
  185. /**
  186. * Generates a batch INSERT SQL statement.
  187. * For example,
  188. *
  189. * ~~~
  190. * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
  191. * ['Tom', 30],
  192. * ['Jane', 20],
  193. * ['Linda', 25],
  194. * ]);
  195. * ~~~
  196. *
  197. * Note that the values in each row must match the corresponding column names.
  198. *
  199. * @param string $table the table that new rows will be inserted into.
  200. * @param array $columns the column names
  201. * @param array $rows the rows to be batch inserted into the table
  202. * @return string the batch INSERT SQL statement
  203. */
  204. public function batchInsert($table, $columns, $rows)
  205. {
  206. $schema = $this->db->getSchema();
  207. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  208. $columnSchemas = $tableSchema->columns;
  209. } else {
  210. $columnSchemas = [];
  211. }
  212. $values = [];
  213. foreach ($rows as $row) {
  214. $vs = [];
  215. foreach ($row as $i => $value) {
  216. if (isset($columns[$i], $columnSchemas[$columns[$i]]) && !is_array($value)) {
  217. $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
  218. }
  219. if (is_string($value)) {
  220. $value = $schema->quoteValue($value);
  221. } elseif ($value === false) {
  222. $value = 0;
  223. } elseif ($value === null) {
  224. $value = 'NULL';
  225. }
  226. $vs[] = $value;
  227. }
  228. $values[] = '(' . implode(', ', $vs) . ')';
  229. }
  230. foreach ($columns as $i => $name) {
  231. $columns[$i] = $schema->quoteColumnName($name);
  232. }
  233. $tableAndColumns = ' INTO ' . $schema->quoteTableName($table)
  234. . ' (' . implode(', ', $columns) . ') VALUES ';
  235. return 'INSERT ALL ' . $tableAndColumns . implode($tableAndColumns, $values) . ' SELECT 1 FROM SYS.DUAL';
  236. }
  237. }