1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//! The SQL implementation of DestructiveChangeChecker is responsible for
//! informing users about potentially destructive or impossible changes that
//! their attempted migrations contain.
//!
//! It proceeds in three steps:
//!
//! - Examine the SqlMigrationSteps in the migration, to generate a
//!   `DestructiveCheckPlan` containing destructive change checks (implementors
//!   of the `Check` trait). At this stage, there is no interaction with the
//!   database.
//! - Execute that plan (`DestructiveCheckPlan::execute`), running queries
//!   against the database to inspect its current state, depending on what
//!   information the checks require.
//! - Render the final user-facing messages based on the plan and the gathered
//!   information.

mod check;
mod database_inspection_results;
mod destructive_change_checker_flavour;
mod destructive_check_plan;
mod unexecutable_step_check;
mod warning_check;

pub(crate) use destructive_change_checker_flavour::DestructiveChangeCheckerFlavour;

use crate::{
    sql_migration::{AlterEnum, AlterTable, ColumnTypeChange, SqlMigrationStep, TableChange},
    SqlMigration, SqlSchemaConnector,
};
use destructive_check_plan::DestructiveCheckPlan;
use schema_connector::{BoxFuture, ConnectorResult, DestructiveChangeChecker, DestructiveChangeDiagnostics, Migration};
use sql_schema_describer::{walkers::TableColumnWalker, ColumnArity};
use unexecutable_step_check::UnexecutableStepCheck;
use warning_check::SqlMigrationWarningCheck;

use self::check::Column;

impl SqlSchemaConnector {
    fn check_table_drop(
        &self,
        table_name: &str,
        namespace: Option<&str>,
        plan: &mut DestructiveCheckPlan,
        step_index: usize,
    ) {
        plan.push_warning(
            SqlMigrationWarningCheck::NonEmptyTableDrop {
                table: table_name.to_owned(),
                namespace: namespace.map(str::to_owned),
            },
            step_index,
        );
    }

    /// Emit a warning when we drop a column that contains non-null values.
    fn check_column_drop(&self, column: &TableColumnWalker<'_>, plan: &mut DestructiveCheckPlan, step_index: usize) {
        plan.push_warning(
            SqlMigrationWarningCheck::NonEmptyColumnDrop {
                table: column.table().name().to_owned(),
                namespace: column.table().namespace().map(str::to_owned),
                column: column.name().to_owned(),
            },
            step_index,
        );
    }

    /// Columns cannot be added when all of the following holds:
    ///
    /// - There are existing rows
    /// - The new column is required
    /// - There is no default value for the new column
    fn check_add_column(
        &self,
        column: &TableColumnWalker<'_>,
        has_virtual_default: bool,
        plan: &mut DestructiveCheckPlan,
        step_index: usize,
    ) {
        let column_is_required_without_default = column.arity().is_required() && column.default().is_none();

        // Optional columns and columns with a default can safely be added.
        if !column_is_required_without_default {
            return;
        }

        let typed_unexecutable = if has_virtual_default {
            UnexecutableStepCheck::AddedRequiredFieldToTableWithPrismaLevelDefault(Column {
                table: column.table().name().to_owned(),
                namespace: column.table().namespace().map(str::to_owned),
                column: column.name().to_owned(),
            })
        } else {
            UnexecutableStepCheck::AddedRequiredFieldToTable(Column {
                table: column.table().name().to_owned(),
                namespace: column.table().namespace().map(str::to_owned),
                column: column.name().to_owned(),
            })
        };

        plan.push_unexecutable(typed_unexecutable, step_index);
    }

    fn plan(&self, migration: &SqlMigration) -> DestructiveCheckPlan {
        let steps = &migration.steps;
        let schemas = migration.schemas();
        let mut plan = DestructiveCheckPlan::new();

        for (step_index, step) in steps.iter().enumerate() {
            match step {
                SqlMigrationStep::AlterTable(AlterTable {
                    table_ids: table_id,
                    changes,
                }) => {
                    // The table in alter_table is the updated table, but we want to
                    // check against the current state of the table.
                    let tables = schemas.walk(*table_id);

                    for change in changes {
                        match change {
                            TableChange::DropColumn { column_id } => {
                                let column = schemas.previous.walk(*column_id);

                                self.check_column_drop(&column, &mut plan, step_index);
                            }
                            TableChange::AlterColumn(alter_column) => {
                                let columns = schemas.walk(alter_column.column_id);

                                self.flavour()
                                    .check_alter_column(alter_column, &columns, &mut plan, step_index)
                            }
                            TableChange::AddColumn {
                                column_id,
                                has_virtual_default,
                            } => {
                                let column = schemas.next.walk(*column_id);

                                self.check_add_column(&column, *has_virtual_default, &mut plan, step_index)
                            }
                            TableChange::DropPrimaryKey { .. } => plan.push_warning(
                                SqlMigrationWarningCheck::PrimaryKeyChange {
                                    table: tables.previous.name().to_owned(),
                                    namespace: tables.previous.namespace().map(str::to_owned),
                                },
                                step_index,
                            ),
                            TableChange::DropAndRecreateColumn { column_id, changes } => {
                                let columns = schemas.walk(*column_id);

                                self.flavour
                                    .check_drop_and_recreate_column(&columns, changes, &mut plan, step_index)
                            }
                            TableChange::AddPrimaryKey { .. } => (),
                            TableChange::RenamePrimaryKey { .. } => (),
                        }
                    }
                }
                SqlMigrationStep::RedefineTables(redefine_tables) => {
                    for redefine_table in redefine_tables {
                        let tables = schemas.walk(redefine_table.table_ids);

                        if redefine_table.dropped_primary_key {
                            plan.push_warning(
                                SqlMigrationWarningCheck::PrimaryKeyChange {
                                    table: tables.previous.name().to_owned(),
                                    namespace: tables.previous.namespace().map(str::to_owned),
                                },
                                step_index,
                            )
                        }

                        for added_column_idx in &redefine_table.added_columns {
                            let column = schemas.next.walk(*added_column_idx);
                            let has_virtual_default = redefine_table
                                .added_columns_with_virtual_defaults
                                .contains(added_column_idx);
                            self.check_add_column(&column, has_virtual_default, &mut plan, step_index);
                        }

                        for dropped_column_idx in &redefine_table.dropped_columns {
                            let column = schemas.previous.walk(*dropped_column_idx);
                            self.check_column_drop(&column, &mut plan, step_index);
                        }

                        for (column_ides, changes, type_change) in redefine_table.column_pairs.iter() {
                            let columns = schemas.walk(*column_ides);

                            let arity_change_is_safe = match (&columns.previous.arity(), &columns.next.arity()) {
                                // column became required
                                (ColumnArity::Nullable, ColumnArity::Required) => false,
                                // column became nullable
                                (ColumnArity::Required, ColumnArity::Nullable) => true,
                                // nothing changed
                                (ColumnArity::Required, ColumnArity::Required)
                                | (ColumnArity::Nullable, ColumnArity::Nullable)
                                | (ColumnArity::List, ColumnArity::List) => true,
                                // not supported on SQLite
                                (ColumnArity::List, _) | (_, ColumnArity::List) => unreachable!(),
                            };

                            if !changes.type_changed() && arity_change_is_safe {
                                continue;
                            }

                            if changes.arity_changed()
                                && columns.next.arity().is_required()
                                && columns.next.default().is_none()
                            {
                                plan.push_unexecutable(
                                    UnexecutableStepCheck::MadeOptionalFieldRequired(Column {
                                        table: columns.previous.table().name().to_owned(),
                                        namespace: columns.previous.table().namespace().map(str::to_owned),
                                        column: columns.previous.name().to_owned(),
                                    }),
                                    step_index,
                                );
                            }

                            match type_change {
                                Some(ColumnTypeChange::SafeCast) | None => (),
                                Some(ColumnTypeChange::RiskyCast) => {
                                    plan.push_warning(
                                        SqlMigrationWarningCheck::RiskyCast {
                                            table: columns.previous.table().name().to_owned(),
                                            namespace: columns.previous.table().namespace().map(str::to_owned),
                                            column: columns.previous.name().to_owned(),
                                            previous_type: format!("{:?}", columns.previous.column_type_family()),
                                            next_type: format!("{:?}", columns.next.column_type_family()),
                                        },
                                        step_index,
                                    );
                                }
                                Some(ColumnTypeChange::NotCastable) => plan.push_warning(
                                    SqlMigrationWarningCheck::NotCastable {
                                        table: columns.previous.table().name().to_owned(),
                                        namespace: columns.previous.table().namespace().map(str::to_owned),
                                        column: columns.previous.name().to_owned(),
                                        previous_type: format!("{:?}", columns.previous.column_type_family()),
                                        next_type: format!("{:?}", columns.next.column_type_family()),
                                    },
                                    step_index,
                                ),
                            }
                        }
                    }
                }
                SqlMigrationStep::DropTable { table_id } => {
                    let table = schemas.previous.walk(*table_id);
                    self.check_table_drop(table.name(), table.namespace(), &mut plan, step_index);
                }
                SqlMigrationStep::CreateIndex {
                    table_id: (Some(_), _),
                    index_id,
                    from_drop_and_recreate: false,
                } => {
                    let index = schemas.next.walk(*index_id);
                    if index.is_unique() {
                        plan.push_warning(
                            SqlMigrationWarningCheck::UniqueConstraintAddition {
                                table: index.table().name().to_owned(),
                                columns: index.columns().map(|col| col.as_column().name().to_owned()).collect(),
                            },
                            step_index,
                        )
                    }
                }
                SqlMigrationStep::AlterEnum(AlterEnum {
                    id,
                    created_variants: _,
                    dropped_variants,
                    previous_usages_as_default: _,
                }) if !dropped_variants.is_empty() => plan.push_warning(
                    SqlMigrationWarningCheck::EnumValueRemoval {
                        enm: schemas.next.walk(id.next).name().to_owned(),
                        values: dropped_variants.clone(),
                    },
                    step_index,
                ),
                _ => (),
            }
        }

        plan
    }
}

impl DestructiveChangeChecker for SqlSchemaConnector {
    fn check<'a>(
        &'a mut self,
        migration: &'a Migration,
    ) -> BoxFuture<'a, ConnectorResult<DestructiveChangeDiagnostics>> {
        let plan = self.plan(migration.downcast_ref());
        Box::pin(async move { plan.execute(self.flavour.as_mut()).await })
    }

    fn pure_check(&self, migration: &Migration) -> DestructiveChangeDiagnostics {
        let plan = self.plan(migration.downcast_ref());

        plan.pure_check()
    }
}