Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

209 lines
8.5KB

  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\pgsql;
  8. use yii\base\InvalidParamException;
  9. /**
  10. * QueryBuilder is the query builder for PostgreSQL databases.
  11. *
  12. * @author Gevik Babakhani <gevikb@gmail.com>
  13. * @since 2.0
  14. */
  15. class QueryBuilder extends \yii\db\QueryBuilder
  16. {
  17. /**
  18. * @var array mapping from abstract column types (keys) to physical column types (values).
  19. */
  20. public $typeMap = [
  21. Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
  22. Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
  23. Schema::TYPE_STRING => 'varchar(255)',
  24. Schema::TYPE_TEXT => 'text',
  25. Schema::TYPE_SMALLINT => 'smallint',
  26. Schema::TYPE_INTEGER => 'integer',
  27. Schema::TYPE_BIGINT => 'bigint',
  28. Schema::TYPE_FLOAT => 'double precision',
  29. Schema::TYPE_DOUBLE => 'double precision',
  30. Schema::TYPE_DECIMAL => 'numeric(10,0)',
  31. Schema::TYPE_DATETIME => 'timestamp(0)',
  32. Schema::TYPE_TIMESTAMP => 'timestamp(0)',
  33. Schema::TYPE_TIME => 'time(0)',
  34. Schema::TYPE_DATE => 'date',
  35. Schema::TYPE_BINARY => 'bytea',
  36. Schema::TYPE_BOOLEAN => 'boolean',
  37. Schema::TYPE_MONEY => 'numeric(19,4)',
  38. ];
  39. /**
  40. * @var array map of query condition to builder methods.
  41. * These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
  42. */
  43. protected $conditionBuilders = [
  44. 'NOT' => 'buildNotCondition',
  45. 'AND' => 'buildAndCondition',
  46. 'OR' => 'buildAndCondition',
  47. 'BETWEEN' => 'buildBetweenCondition',
  48. 'NOT BETWEEN' => 'buildBetweenCondition',
  49. 'IN' => 'buildInCondition',
  50. 'NOT IN' => 'buildInCondition',
  51. 'LIKE' => 'buildLikeCondition',
  52. 'ILIKE' => 'buildLikeCondition',
  53. 'NOT LIKE' => 'buildLikeCondition',
  54. 'NOT ILIKE' => 'buildLikeCondition',
  55. 'OR LIKE' => 'buildLikeCondition',
  56. 'OR ILIKE' => 'buildLikeCondition',
  57. 'OR NOT LIKE' => 'buildLikeCondition',
  58. 'OR NOT ILIKE' => 'buildLikeCondition',
  59. 'EXISTS' => 'buildExistsCondition',
  60. 'NOT EXISTS' => 'buildExistsCondition',
  61. ];
  62. /**
  63. * Builds a SQL statement for dropping an index.
  64. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  65. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  66. * @return string the SQL statement for dropping an index.
  67. */
  68. public function dropIndex($name, $table)
  69. {
  70. return 'DROP INDEX ' . $this->db->quoteTableName($name);
  71. }
  72. /**
  73. * Builds a SQL statement for renaming a DB table.
  74. * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
  75. * @param string $newName the new table name. The name will be properly quoted by the method.
  76. * @return string the SQL statement for renaming a DB table.
  77. */
  78. public function renameTable($oldName, $newName)
  79. {
  80. return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName);
  81. }
  82. /**
  83. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  84. * The sequence will be reset such that the primary key of the next new row inserted
  85. * will have the specified value or 1.
  86. * @param string $tableName the name of the table whose primary key sequence will be reset
  87. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  88. * the next new row's primary key will have a value 1.
  89. * @return string the SQL statement for resetting sequence
  90. * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
  91. */
  92. public function resetSequence($tableName, $value = null)
  93. {
  94. $table = $this->db->getTableSchema($tableName);
  95. if ($table !== null && $table->sequenceName !== null) {
  96. // c.f. http://www.postgresql.org/docs/8.1/static/functions-sequence.html
  97. $sequence = $this->db->quoteTableName($table->sequenceName);
  98. $tableName = $this->db->quoteTableName($tableName);
  99. if ($value === null) {
  100. $key = reset($table->primaryKey);
  101. $value = "(SELECT COALESCE(MAX(\"{$key}\"),0) FROM {$tableName})+1";
  102. } else {
  103. $value = (int) $value;
  104. }
  105. return "SELECT SETVAL('$sequence',$value,false)";
  106. } elseif ($table === null) {
  107. throw new InvalidParamException("Table not found: $tableName");
  108. } else {
  109. throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
  110. }
  111. }
  112. /**
  113. * Builds a SQL statement for enabling or disabling integrity check.
  114. * @param boolean $check whether to turn on or off the integrity check.
  115. * @param string $schema the schema of the tables.
  116. * @param string $table the table name.
  117. * @return string the SQL statement for checking integrity
  118. */
  119. public function checkIntegrity($check = true, $schema = '', $table = '')
  120. {
  121. $enable = $check ? 'ENABLE' : 'DISABLE';
  122. $schema = $schema ? $schema : $this->db->getSchema()->defaultSchema;
  123. $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
  124. $command = '';
  125. foreach ($tableNames as $tableName) {
  126. $tableName = '"' . $schema . '"."' . $tableName . '"';
  127. $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
  128. }
  129. // enable to have ability to alter several tables
  130. $this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
  131. return $command;
  132. }
  133. /**
  134. * Builds a SQL statement for changing the definition of a column.
  135. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  136. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  137. * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
  138. * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
  139. * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
  140. * will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
  141. * @return string the SQL statement for changing the definition of a column.
  142. */
  143. public function alterColumn($table, $column, $type)
  144. {
  145. // https://github.com/yiisoft/yii2/issues/4492
  146. // http://www.postgresql.org/docs/9.1/static/sql-altertable.html
  147. if (!preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
  148. $type = 'TYPE ' . $this->getColumnType($type);
  149. }
  150. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN '
  151. . $this->db->quoteColumnName($column) . ' ' . $type;
  152. }
  153. /**
  154. * @inheritdoc
  155. */
  156. public function batchInsert($table, $columns, $rows)
  157. {
  158. $schema = $this->db->getSchema();
  159. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  160. $columnSchemas = $tableSchema->columns;
  161. } else {
  162. $columnSchemas = [];
  163. }
  164. $values = [];
  165. foreach ($rows as $row) {
  166. $vs = [];
  167. foreach ($row as $i => $value) {
  168. if (!is_array($value) && isset($columnSchemas[$columns[$i]])) {
  169. $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
  170. }
  171. if (is_string($value)) {
  172. $value = $schema->quoteValue($value);
  173. } elseif ($value === true) {
  174. $value = 'TRUE';
  175. } elseif ($value === false) {
  176. $value = 'FALSE';
  177. } elseif ($value === null) {
  178. $value = 'NULL';
  179. }
  180. $vs[] = $value;
  181. }
  182. $values[] = '(' . implode(', ', $vs) . ')';
  183. }
  184. foreach ($columns as $i => $name) {
  185. $columns[$i] = $schema->quoteColumnName($name);
  186. }
  187. return 'INSERT INTO ' . $schema->quoteTableName($table)
  188. . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
  189. }
  190. }