Created
August 7, 2019 16:05
-
-
Save MihaelIsaev/f6442bf3698572cd9170114f236c47c2 to your computer and use it in GitHub Desktop.
A swift extension for `PostgreSQLConnection` for Vapor3 to have an ability to add indexes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// DatabaseConnection+Index.swift | |
// App | |
// | |
// Created by Mihael Isaev on 18.06.2018. | |
// | |
import Foundation | |
import Vapor | |
import FluentPostgreSQL | |
public protocol IndexKP { | |
var modelName: String { get } | |
var fullPath: String { get } | |
} | |
extension KeyPath: IndexKP where Root: Model { | |
var pp: [String] { | |
if let pp = try? Root.reflectProperty(forKey: self)?.path, let pathParts = pp { | |
return pathParts | |
} | |
return [] | |
} | |
public var modelName: String { | |
return Root.entity | |
} | |
public var fullPath: String { | |
return pp.joined(separator: "->") | |
} | |
} | |
extension PostgreSQLConnection { | |
func addIndexes(_ keypaths: IndexKP...) -> EventLoopFuture<Void> { | |
return simpleQuery(keypaths.map { kp in | |
var result = "CREATE INDEX " | |
result.append("\"idx:\(kp.modelName).\(kp.fullPath)\"") | |
result.append(" ON ") | |
result.append("\"\(kp.modelName)\"") | |
result.append(" ") | |
result.append("(\"\(kp.fullPath)\")") | |
return result | |
}.joined(separator: ";")).transform(to: ()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment