【问题标题】:How to add an index to a postgres table?如何将索引添加到 postgres 表?
【发布时间】:2019-08-07 15:59:28
【问题描述】:

我正在尝试使用 Vapor 向 PostgreSQL 表添加列索引。我找到了几个这样做的教程,但是这些代码 sn-ps 都不适用于当前版本。

【问题讨论】:

    标签: postgresql vapor


    【解决方案1】:

    您可以在以下迁移中运行 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)
    

    这样做的好处是可以添加部分索引等

    【讨论】:

    • 感谢您的解决方案。是否可以为每个结构添加多个语句?当我尝试将更多 SQL 语句添加到 raw 中时出现错误。因为我必须创建很多结构并注册所有它们......
    • @G.Marc 我已经更新了答案部分如何在一次迁移中使用多个语句。
    【解决方案2】:

    据我所知,无法使用 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)
            }
        }
    }
    

    希望对你有帮助:)

    【讨论】:

    • 顺便说一下,你也可以看看 SwifQL lib 来制作你自己的灵活原始查询github.com/MihaelIsaev/SwifQL
    • 感谢这个解决方案,但我想我会选择原始的,因为我有更多的灵活性。不幸的是,这两种解决方案都不是很好的框架。
    • 原始查询很灵活但不是强类型,这就是我创建 SwifQL 的原因:)
    猜你喜欢
    • 2012-12-23
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多