Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: migrating after altering an Enum type and chaing the default value of an Enum[] column no longer crashes on Postgres #3379

Merged
merged 4 commits into from
Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@ impl SqlRenderer for PostgresFlavour {
render_cockroach_alter_enum(alter_enum, schemas, step);
})
} else {
render_postgres_alter_enum(alter_enum, schemas)
let flavour = self;
render_postgres_alter_enum(alter_enum, schemas, flavour)
}
}

Expand Down Expand Up @@ -883,7 +884,11 @@ fn render_default<'a>(default: &'a DefaultValue, full_data_type: &str) -> Cow<'a
}
}

fn render_postgres_alter_enum(alter_enum: &AlterEnum, schemas: Pair<&SqlSchema>) -> Vec<String> {
fn render_postgres_alter_enum(
alter_enum: &AlterEnum,
schemas: Pair<&SqlSchema>,
flavour: &PostgresFlavour,
) -> Vec<String> {
if alter_enum.dropped_variants.is_empty() {
let mut stmts: Vec<String> = alter_enum
.created_variants
Expand Down Expand Up @@ -1006,26 +1011,22 @@ fn render_postgres_alter_enum(alter_enum: &AlterEnum, schemas: Pair<&SqlSchema>)

// Reinstall dropped defaults that need to be reinstalled
{
for (prev_colidx, next_colidx) in alter_enum
for (columns, next_default) in alter_enum
.previous_usages_as_default
.iter()
.filter_map(|(prev, next)| next.map(|next| (prev, next)))
.filter_map(|(prev, next)| next.map(|next| schemas.walk(Pair::new(*prev, next))))
.filter_map(|columns| columns.next.default().map(|next_default| (columns, next_default)))
{
let columns = schemas.walk(Pair::new(*prev_colidx, next_colidx));
let table_name = columns.previous.table().name();
let column_name = columns.previous.name();
let default_str = columns
.next
.default()
.and_then(|default| default.as_value())
.and_then(|value| value.as_enum_value())
.expect("We should only be setting a changed default if there was one on the previous schema and in the next with the same enum.");
let data_type = render_column_type(columns.next, flavour);
let default_str = render_default(next_default, &data_type);

let set_default = format!(
"ALTER TABLE {table_name} ALTER COLUMN {column_name} SET DEFAULT '{default}'",
"ALTER TABLE {table_name} ALTER COLUMN {column_name} SET DEFAULT {default}",
table_name = Quoted::postgres_ident(&table_name),
column_name = Quoted::postgres_ident(&column_name),
default = escape_string_literal(default_str),
default = default_str,
);

stmts.push(set_default);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,8 @@ fn push_column_for_model_enum_scalar_field(
table_id,
sql::Column {
name: field.database_name().to_owned(),

// TODO: replace "pure" with "with_full_data_type"
jkomyno marked this conversation as resolved.
Show resolved Hide resolved
jkomyno marked this conversation as resolved.
Show resolved Hide resolved
tpe: sql::ColumnType::pure(
sql::ColumnTypeFamily::Enum(ctx.enum_ids[&r#enum.id]),
column_arity(field.ast_field().arity),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ impl SchemaPushAssertion {
self.assert_no_warning().assert_executable()
}

#[track_caller]
pub fn assert_no_warning(self) -> Self {
assert!(
self.result.warnings.is_empty(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::borrow::Cow;

use migration_engine_tests::test_api::*;
use prisma_value::PrismaValue;

const BASIC_ENUM_DM: &str = r#"
model Cat {
Expand Down Expand Up @@ -534,3 +537,85 @@ fn mapped_enum_defaults_must_work(api: TestApi) {
api.schema_push(schema).send().assert_green();
api.schema_push(schema).send().assert_green().assert_no_steps();
}

#[test_connector(tags(Postgres), exclude(CockroachDb))]
fn alter_enum_and_change_default_must_work(api: TestApi) {
let plain_dm = r#"
datasource db {
provider = "postgres"
url = "postgres://meowmeowmeow"
}
model Cat {
id Int @id
moods Mood[] @default([])
}
enum Mood {
SLEEPY
MOODY
}
"#;

api.schema_push(plain_dm).send().assert_green();

let custom_dm = r#"
datasource test {
provider = "postgres"
url = "postgres://meowmeowmeow"
}
model Cat {
id Int @id
moods Mood[] @default([SLEEPY])
}
enum Mood {
HUNGRY
SLEEPY
}
"#;

// recall: schema_push doesn't run if it has warnings. You need to specify "force(true)"
api.schema_push(custom_dm).force(true).send().assert_warnings(&[Cow::from(
"The values [MOODY] on the enum `Mood` will be removed. If these variants are still used in the database, this will fail.",
)]);
api.schema_push(custom_dm).send().assert_green().assert_no_steps();

api.assert_schema().assert_table("Cat", |table| {
table.assert_column("moods", |col| {
col.assert_default_value(&PrismaValue::List(vec![PrismaValue::Enum("SLEEPY".to_string())]))
})
});

// we repeat the same tests with migrations, so we can observe the generated SQL statements.
api.reset().send_sync();
api.assert_schema().assert_tables_count(0);

let dir = api.create_migrations_directory();
api.create_migration("plain", &plain_dm, &dir).send_sync();

api.create_migration("custom", &custom_dm, &dir)
.send_sync()
.assert_migration_directories_count(2)
.assert_migration("custom", move |migration| {
let expected_script = expect![[r#"
/*
Warnings:

- The values [MOODY] on the enum `Mood` will be removed. If these variants are still used in the database, this will fail.

*/
-- AlterEnum
BEGIN;
CREATE TYPE "Mood_new" AS ENUM ('HUNGRY', 'SLEEPY');
ALTER TABLE "Cat" ALTER COLUMN "moods" DROP DEFAULT;
ALTER TABLE "Cat" ALTER COLUMN "moods" TYPE "Mood_new"[] USING ("moods"::text::"Mood_new"[]);
ALTER TYPE "Mood" RENAME TO "Mood_old";
ALTER TYPE "Mood_new" RENAME TO "Mood";
DROP TYPE "Mood_old";
ALTER TABLE "Cat" ALTER COLUMN "moods" SET DEFAULT ARRAY['SLEEPY']::"Mood"[];
COMMIT;

-- AlterTable
ALTER TABLE "Cat" ALTER COLUMN "moods" SET DEFAULT ARRAY['SLEEPY']::"Mood"[];
"#]];
migration.expect_contents(expected_script)
});
}