我正在使用Vapor框架用Swift编写一个web服务。
我有一个叫Item的模特。错误地说,它只具有名称和id属性。
typealias VaporModel = Content & PostgreSQLModel & Parameter
final class Item: VaporModel {
var id: Int?
var name: String
}在为模型配置了控制器并添加了路由之后,当我点击post项请求时,就会得到Model.defaultDatabase is required to use as DatabaseConnectable错误。我认为这个错误是因为我没有在Item中将Migrations添加到configure.swift中,并且在将Item与PostgreSQLMigration兼容之后也会这样做。
var migrations = MigrationConfig()
migrations.add(model: Item.self, database: .psql)
services.register(migrations)现在,我可以点击post请求并在数据库中创建项目。
因此,我理解Migration协议为模型创建默认模式,并将模型的属性作为列添加到数据库中。
现在,我想向Item类添加一个属性(如price )。现在,当我点击post请求时,我得到了column "price" of relation "Item" does not exist错误。我假设迁移协议将能够识别模式更改和表中的列(这是我在为iOS应用程序使用领域时所习惯的)。但是我错了,我阅读了迁移文档,并在迁移中实现了prepare和revert方法,如下所示。
extension Item: PostgreSQLMigration {
static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
return Database.create(self, on: conn) { creator in
creator.field(for: \.price)
}
}
static func revert(on connection: PostgreSQLConnection) -> EventLoopFuture<Void> {
return Future.map(on: connection) { }
}
} 我仍然受到同样的错误column "price" of relation "Item" does not exist的打击。我在这里错过了什么?我的迁移代码正确吗?
另外,我知道如果不对模型做任何更改,我可以注释掉迁移配置,因为它们不需要每次运行服务时都运行。对吗?
发布于 2019-05-02 06:38:52
使用您的代码,您还没有添加新的迁移。您已经实现了手动初始迁移,但是初始迁移已经按照请求运行(migrations.add(model: Item.self, database: .psql) )。为了创造一种新的迁移,你需要如下的东西:
struct ItemAddPriceMigration: Migration {
typealias Database = PostgreSQLDatabase
static func prepare(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
return Database.update(Item.self, on: conn) { builder in
builder.field(for: \.price)
}
}
static func revert(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
return conn.future()
}
}然后您需要将它添加到configure中
migrations.add(migration: ItemAddPriceMigration.self, database: .psql)
https://stackoverflow.com/questions/55944410
复制相似问题