|
| 1 | +package migrations |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/pocketbase/pocketbase/core" |
| 5 | + m "github.com/pocketbase/pocketbase/migrations" |
| 6 | +) |
| 7 | + |
| 8 | +func init() { |
| 9 | + m.Register(func(app core.App) error { |
| 10 | + // add up queries... |
| 11 | + collection, err := app.FindCollectionByNameOrId("users") |
| 12 | + if err != nil { |
| 13 | + return err |
| 14 | + } |
| 15 | + |
| 16 | + collection.Fields.Add(&core.TextField{ |
| 17 | + Name: "stripe_customer_id", |
| 18 | + Required: false, |
| 19 | + }) |
| 20 | + |
| 21 | + field := collection.Fields.GetByName("name") |
| 22 | + |
| 23 | + if textField, ok := field.(*core.TextField); ok { |
| 24 | + textField.Required = true |
| 25 | + } |
| 26 | + |
| 27 | + collection.Indexes = append(collection.Indexes, |
| 28 | + "CREATE UNIQUE INDEX `idx_stripe_customer_id` ON `users` (`stripe_customer_id`) WHERE `stripe_customer_id` != ''", |
| 29 | + ) |
| 30 | + return app.Save(collection) |
| 31 | + }, func(app core.App) error { |
| 32 | + // 回滚逻辑:移除字段和索引 |
| 33 | + collection, err := app.FindCollectionByNameOrId("users") |
| 34 | + if err != nil { |
| 35 | + return nil |
| 36 | + } |
| 37 | + |
| 38 | + collection.Fields.RemoveByName("stripe_customer_id") |
| 39 | + |
| 40 | + // 移除索引 (从切片中滤掉) |
| 41 | + newIndexes := []string{} |
| 42 | + for _, idx := range collection.Indexes { |
| 43 | + if idx != "CREATE UNIQUE INDEX `idx_stripe_customer_id` ON `users` (`stripe_customer_id`) WHERE `stripe_customer_id` != ''" { |
| 44 | + newIndexes = append(newIndexes, idx) |
| 45 | + } |
| 46 | + } |
| 47 | + collection.Indexes = newIndexes |
| 48 | + |
| 49 | + return app.Save(collection) |
| 50 | + }) |
| 51 | +} |
0 commit comments