Skip to content

Instantly share code, notes, and snippets.

@pedantix
Created April 15, 2018 02:04
Show Gist options
  • Save pedantix/72fd1971f77a83fd12b61afe5d973353 to your computer and use it in GitHub Desktop.
Save pedantix/72fd1971f77a83fd12b61afe5d973353 to your computer and use it in GitHub Desktop.
A Gist to show how to join 3+ tables together in psql, for the Vapor 3 Framework
final class Foo: PostgreSQLModel, Migration {
var id: Int?
}
final class Bar: PostgreSQLModel, Migration {
var id: Int?
}
final class Baz: PostgreSQLModel, Migration {
var id: Int?
}
final class FizBuz: PostgreSQLModel {
var id: Int?
var fooId: Foo.ID
var barId: Bar.ID
var bazId: Baz.ID
}
extension FizBuz: Migration {
static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {
return Database.create(self, on: connection) { builder in
try addProperties(to: builder)
try builder.addReference(from: \.fooId, to: \Foo.id)
try builder.addReference(from: \.barId, to: \Bar.id)
try builder.addReference(from: \.bazId, to: \Baz.id)
}
}
}
struct FizBuzUniqueMultiIndexMigration: Migration {
typealias Database = PostgreSQLDatabase
static let indexName = "fiz_buz_ref_index"
public static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {
return Database.transaction(on: connection) { (conn) -> Future<Void> in
return try conn.query("CREATE UNIQUE INDEX \(indexName) UNIQUE(\"fooId\", \"barId\", \"bazId\");")
.map(to: Void.self, { (_) -> Void in () })
}
}
public static func revert(on connection: PostgreSQLConnection) -> Future<Void> {
return Database.transaction(on: connection) { (conn) -> Future<Void> in
return try conn.query("DROP INDEX IF EXISTS \(indexName);").map(to: Void.self, { (_) -> Void in () })
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment