【发布时间】:2019-08-07 15:59:28
【问题描述】:
我正在尝试使用 Vapor 向 PostgreSQL 表添加列索引。我找到了几个这样做的教程,但是这些代码 sn-ps 都不适用于当前版本。
【问题讨论】:
标签: postgresql vapor
我正在尝试使用 Vapor 向 PostgreSQL 表添加列索引。我找到了几个这样做的教程,但是这些代码 sn-ps 都不适用于当前版本。
【问题讨论】:
标签: postgresql vapor
您可以在以下迁移中运行 RAW SQL:
import FluentPostgreSQL
struct MigrationTest: PostgreSQLMigration {
static func revert(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
return conn.future()
}
static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
return conn.raw("CREATE INDEX test on some_table (field1, field2);").run()
}
}
要在一个迁移中添加更多语句,我这样做:
static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
let _ = conn.raw("create index if not exists idx_one (field1, field2);").run()
let _ = conn.raw("create index if not exists idx_two (field3, field4);").run()
return conn.future()
}
您不能一次添加更多语句!对于每个语句新的let _ = conn.raw().run()
在配置中
migrations.add(migration: MigrationTest.self, database: .psql)
这样做的好处是可以添加部分索引等
【讨论】:
据我所知,无法使用 Fluent 创建索引。 在我的 Vapor3 项目中,我使用我自己的带有原始查询的小扩展 https://gist.github.com/MihaelIsaev/f6442bf3698572cd9170114f236c47c2
你可以这样使用它
extension CarBrand: Migration {
public static func prepare(on connection: Database.Connection) -> Future<Void> {
return Database.create(self, on: connection) { builder in
try addProperties(to: builder)
}.flatMap { _ in
return connection.addIndexes(\CarBrand.addedByUser, \CarBrand.createdAt)
}
}
}
希望对你有帮助:)
【讨论】: