You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

310 lines
12KB

  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. * Defines a UNIQUE index for [[createIndex()]].
  19. * @since 2.0.6
  20. */
  21. const INDEX_UNIQUE = 'unique';
  22. /**
  23. * Defines a B-tree index for [[createIndex()]].
  24. * @since 2.0.6
  25. */
  26. const INDEX_B_TREE = 'btree';
  27. /**
  28. * Defines a hash index for [[createIndex()]].
  29. * @since 2.0.6
  30. */
  31. const INDEX_HASH = 'hash';
  32. /**
  33. * Defines a GiST index for [[createIndex()]].
  34. * @since 2.0.6
  35. */
  36. const INDEX_GIST = 'gist';
  37. /**
  38. * Defines a GIN index for [[createIndex()]].
  39. * @since 2.0.6
  40. */
  41. const INDEX_GIN = 'gin';
  42. /**
  43. * @var array mapping from abstract column types (keys) to physical column types (values).
  44. */
  45. public $typeMap = [
  46. Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
  47. Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
  48. Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
  49. Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
  50. Schema::TYPE_CHAR => 'char(1)',
  51. Schema::TYPE_STRING => 'varchar(255)',
  52. Schema::TYPE_TEXT => 'text',
  53. Schema::TYPE_SMALLINT => 'smallint',
  54. Schema::TYPE_INTEGER => 'integer',
  55. Schema::TYPE_BIGINT => 'bigint',
  56. Schema::TYPE_FLOAT => 'double precision',
  57. Schema::TYPE_DOUBLE => 'double precision',
  58. Schema::TYPE_DECIMAL => 'numeric(10,0)',
  59. Schema::TYPE_DATETIME => 'timestamp(0)',
  60. Schema::TYPE_TIMESTAMP => 'timestamp(0)',
  61. Schema::TYPE_TIME => 'time(0)',
  62. Schema::TYPE_DATE => 'date',
  63. Schema::TYPE_BINARY => 'bytea',
  64. Schema::TYPE_BOOLEAN => 'boolean',
  65. Schema::TYPE_MONEY => 'numeric(19,4)',
  66. ];
  67. /**
  68. * @var array map of query condition to builder methods.
  69. * These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
  70. */
  71. protected $conditionBuilders = [
  72. 'NOT' => 'buildNotCondition',
  73. 'AND' => 'buildAndCondition',
  74. 'OR' => 'buildAndCondition',
  75. 'BETWEEN' => 'buildBetweenCondition',
  76. 'NOT BETWEEN' => 'buildBetweenCondition',
  77. 'IN' => 'buildInCondition',
  78. 'NOT IN' => 'buildInCondition',
  79. 'LIKE' => 'buildLikeCondition',
  80. 'ILIKE' => 'buildLikeCondition',
  81. 'NOT LIKE' => 'buildLikeCondition',
  82. 'NOT ILIKE' => 'buildLikeCondition',
  83. 'OR LIKE' => 'buildLikeCondition',
  84. 'OR ILIKE' => 'buildLikeCondition',
  85. 'OR NOT LIKE' => 'buildLikeCondition',
  86. 'OR NOT ILIKE' => 'buildLikeCondition',
  87. 'EXISTS' => 'buildExistsCondition',
  88. 'NOT EXISTS' => 'buildExistsCondition',
  89. ];
  90. /**
  91. * Builds a SQL statement for creating a new index.
  92. * @param string $name the name of the index. The name will be properly quoted by the method.
  93. * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
  94. * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
  95. * separate them with commas or use an array to represent them. Each column name will be properly quoted
  96. * by the method, unless a parenthesis is found in the name.
  97. * @param boolean|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or [[INDEX_UNIQUE]] to create
  98. * a unique index, `false` to make a non-unique index using the default index type, or one of the following constants to specify
  99. * the index method to use: [[INDEX_B_TREE]], [[INDEX_HASH]], [[INDEX_GIST]], [[INDEX_GIN]].
  100. * @return string the SQL statement for creating a new index.
  101. * @see http://www.postgresql.org/docs/8.2/static/sql-createindex.html
  102. */
  103. public function createIndex($name, $table, $columns, $unique = false)
  104. {
  105. if ($unique === self::INDEX_UNIQUE || $unique === true) {
  106. $index = false;
  107. $unique = true;
  108. } else {
  109. $index = $unique;
  110. $unique = false;
  111. }
  112. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') .
  113. $this->db->quoteTableName($name) . ' ON ' .
  114. $this->db->quoteTableName($table) .
  115. ($index !== false ? " USING $index" : '') .
  116. ' (' . $this->buildColumns($columns) . ')';
  117. }
  118. /**
  119. * Builds a SQL statement for dropping an index.
  120. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  121. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  122. * @return string the SQL statement for dropping an index.
  123. */
  124. public function dropIndex($name, $table)
  125. {
  126. return 'DROP INDEX ' . $this->db->quoteTableName($name);
  127. }
  128. /**
  129. * Builds a SQL statement for renaming a DB table.
  130. * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
  131. * @param string $newName the new table name. The name will be properly quoted by the method.
  132. * @return string the SQL statement for renaming a DB table.
  133. */
  134. public function renameTable($oldName, $newName)
  135. {
  136. return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName);
  137. }
  138. /**
  139. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  140. * The sequence will be reset such that the primary key of the next new row inserted
  141. * will have the specified value or 1.
  142. * @param string $tableName the name of the table whose primary key sequence will be reset
  143. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  144. * the next new row's primary key will have a value 1.
  145. * @return string the SQL statement for resetting sequence
  146. * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
  147. */
  148. public function resetSequence($tableName, $value = null)
  149. {
  150. $table = $this->db->getTableSchema($tableName);
  151. if ($table !== null && $table->sequenceName !== null) {
  152. // c.f. http://www.postgresql.org/docs/8.1/static/functions-sequence.html
  153. $sequence = $this->db->quoteTableName($table->sequenceName);
  154. $tableName = $this->db->quoteTableName($tableName);
  155. if ($value === null) {
  156. $key = reset($table->primaryKey);
  157. $value = "(SELECT COALESCE(MAX(\"{$key}\"),0) FROM {$tableName})+1";
  158. } else {
  159. $value = (int) $value;
  160. }
  161. return "SELECT SETVAL('$sequence',$value,false)";
  162. } elseif ($table === null) {
  163. throw new InvalidParamException("Table not found: $tableName");
  164. } else {
  165. throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
  166. }
  167. }
  168. /**
  169. * Builds a SQL statement for enabling or disabling integrity check.
  170. * @param boolean $check whether to turn on or off the integrity check.
  171. * @param string $schema the schema of the tables.
  172. * @param string $table the table name.
  173. * @return string the SQL statement for checking integrity
  174. */
  175. public function checkIntegrity($check = true, $schema = '', $table = '')
  176. {
  177. $enable = $check ? 'ENABLE' : 'DISABLE';
  178. $schema = $schema ? $schema : $this->db->getSchema()->defaultSchema;
  179. $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
  180. $viewNames = $this->db->getSchema()->getViewNames($schema);
  181. $tableNames = array_diff($tableNames, $viewNames);
  182. $command = '';
  183. foreach ($tableNames as $tableName) {
  184. $tableName = '"' . $schema . '"."' . $tableName . '"';
  185. $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
  186. }
  187. // enable to have ability to alter several tables
  188. $this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
  189. return $command;
  190. }
  191. /**
  192. * Builds a SQL statement for changing the definition of a column.
  193. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  194. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  195. * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
  196. * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
  197. * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
  198. * will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
  199. * @return string the SQL statement for changing the definition of a column.
  200. */
  201. public function alterColumn($table, $column, $type)
  202. {
  203. // https://github.com/yiisoft/yii2/issues/4492
  204. // http://www.postgresql.org/docs/9.1/static/sql-altertable.html
  205. if (!preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
  206. $type = 'TYPE ' . $this->getColumnType($type);
  207. }
  208. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN '
  209. . $this->db->quoteColumnName($column) . ' ' . $type;
  210. }
  211. /**
  212. * @inheritdoc
  213. */
  214. public function insert($table, $columns, &$params)
  215. {
  216. return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
  217. }
  218. /**
  219. * @inheritdoc
  220. */
  221. public function update($table, $columns, $condition, &$params)
  222. {
  223. return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
  224. }
  225. /**
  226. * Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
  227. * @param string $table the table that data will be saved into.
  228. * @param array $columns the column data (name => value) to be saved into the table.
  229. * @return array normalized columns
  230. * @since 2.0.9
  231. */
  232. private function normalizeTableRowData($table, $columns)
  233. {
  234. if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
  235. $columnSchemas = $tableSchema->columns;
  236. foreach ($columns as $name => $value) {
  237. if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) {
  238. $columns[$name] = [$value, \PDO::PARAM_LOB]; // explicitly setup PDO param type for binary column
  239. }
  240. }
  241. }
  242. return $columns;
  243. }
  244. /**
  245. * @inheritdoc
  246. */
  247. public function batchInsert($table, $columns, $rows)
  248. {
  249. if (empty($rows)) {
  250. return '';
  251. }
  252. $schema = $this->db->getSchema();
  253. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  254. $columnSchemas = $tableSchema->columns;
  255. } else {
  256. $columnSchemas = [];
  257. }
  258. $values = [];
  259. foreach ($rows as $row) {
  260. $vs = [];
  261. foreach ($row as $i => $value) {
  262. if (isset($columns[$i], $columnSchemas[$columns[$i]]) && !is_array($value)) {
  263. $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
  264. }
  265. if (is_string($value)) {
  266. $value = $schema->quoteValue($value);
  267. } elseif ($value === true) {
  268. $value = 'TRUE';
  269. } elseif ($value === false) {
  270. $value = 'FALSE';
  271. } elseif ($value === null) {
  272. $value = 'NULL';
  273. }
  274. $vs[] = $value;
  275. }
  276. $values[] = '(' . implode(', ', $vs) . ')';
  277. }
  278. foreach ($columns as $i => $name) {
  279. $columns[$i] = $schema->quoteColumnName($name);
  280. }
  281. return 'INSERT INTO ' . $schema->quoteTableName($table)
  282. . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
  283. }
  284. }