Skip to content

Commit

Permalink
Merge pull request #14795 from craftcms/bugfix/14792-pgsql-alter-colu…
Browse files Browse the repository at this point in the history
…mn-to-boolean

fix error when altering column to boolean in pgsql
  • Loading branch information
brandonkelly authored Apr 12, 2024
2 parents 81fc545 + ba2aafe commit 2ca800f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Release Notes for Craft CMS 4

## Unreleased

- Fixed a SQL error that could occur when converting a field to a Lightswitch field on PostgreSQL. ([#14792](https://github.com/craftcms/cms/issues/14792))

## 4.8.9 - 2024-04-10

- Fixed a bug where element queries with the `relatedTo` param set to a list of element IDs were overly complex.
Expand Down
16 changes: 13 additions & 3 deletions src/services/Fields.php
Original file line number Diff line number Diff line change
Expand Up @@ -1726,9 +1726,19 @@ protected function updateColumn(
if ($existingColumn) {
// Alter it first, in case that results in an error due to incompatible column data
try {
$db->createCommand()
->alterColumn($table, $oldName, $type)
->execute();
$command = $db->createCommand()->alterColumn($table, $oldName, $type);

if (
$db->getIsPgsql() &&
$type === Schema::TYPE_BOOLEAN &&
Db::isTextualColumnType($db->getTableSchema($table)->getColumn($oldName)->dbType)
) {
$replacement = sprintf(' TYPE boolean USING CASE WHEN "%s" IS NULL THEN NULL WHEN length("%s") = 0 THEN FALSE ELSE TRUE END', $oldName, $oldName);
$sql = preg_replace('/\s+TYPE\s+boolean/i', $replacement, $command->getRawSql());
$command->setSql($sql);
}

$command->execute();
} catch (DbException $e) {
// Restart the transaction
$transaction->rollBack();
Expand Down

0 comments on commit 2ca800f

Please sign in to comment.