Skip to content

Commit

Permalink
Make the sample migration not destroy data (#962)
Browse files Browse the repository at this point in the history
  • Loading branch information
gwynne committed Feb 7, 2024
1 parent ed73175 commit 288b3ac
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions docs/fluent/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,15 +380,34 @@ We can make the necessary database schema adjustments with the following migrati
```swift
struct UserNameMigration: AsyncMigration {
func prepare(on database: Database) async throws {
try await database.schema("users")
.field("first_name", .string, .required)
.field("last_name", .string, .required)
.update()

// It is not currently possible to express this update without using custom SQL.
// This also doesn't try to deal with splitting the name into first and last,
// as that requires database-specific syntax.
try await User.query(on: database)
.set(["first_name": .sql(embed: "name"))
.run()

try await database.schema("users")
.deleteField("name")
.field("first_name", .string)
.field("last_name", .string)
.update()
}

func revert(on database: Database) async throws {
try await database.schema("users").delete()
try await database.schema("users")
.field("name", .string, .required)
.update()
try await User.query(on: database)
.set(["name": .sql(embed: "concat(first_name, ' ', last_name)"))
.run()
try await database.schema("users")
.deleteField("first_name")
.deleteField("last_name")
.update()
}
}
```
Expand Down

0 comments on commit 288b3ac

Please sign in to comment.