fluent-kit
fluent-kit copied to clipboard
IndexBuilder
It would be nice in Fluent 4
to have a protocol for creating Indexes as well as having an IndexBuilder
and some nice convenience methods on Model
.
Something along the lines of:
- https://github.com/asensei/vapor-fluent-mongo/blob/master/Sources/FluentMongo/IndexBuilder.swift
- https://github.com/asensei/vapor-fluent-mongo/blob/master/Sources/FluentMongo/Model%2BIndex.swift
SchemaBuilder currently supports unique indexes via unique(on:)
. Still need support for non-unique indexes.
SchemaBuilder currently supports unique indexes via
unique(on:)
. Still need support for non-unique indexes.
@tanner0101 is there any way to add non-unique indexes in a migration with latest FluentKit and Vapor 4.0?
@photovirus yes there are a couple of ways:
1: Pass a .custom
constraint containing a SQL String
to the schema builder.
private struct TestMigration: FluentKit.Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("test")
.field("id", .uuid, .identifier(auto: false))
.field("foo", .int)
.field("bar", .string)
.constraint(.custom("INDEX my_index (foo, bar)"))
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("test").delete()
}
}
Note: The API above works on the gm
branch but has not yet been released. On master
, you must append the constraint manually:
var builder = database.schema("test")
.field("id", .uuid, .identifier(auto: false))
.field("foo", .int)
.field("bar", .string)
builder.schema.createConstraints.append(.custom("INDEX my_index (foo, bar)"))
return builder.create()
2: Cast the database as SQLDatabase
then run a raw query.
struct AddMyIndexMigration: FluentKit.Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
(database as! SQLDatabase).raw("CREATE INDEX my_index ON test (foo, bar);")
}
func revert(on database: Database) -> EventLoopFuture<Void> {
(database as! SQLDatabase).raw("DROP INDEX my_index;")
}
}
This is extremely valuable, thank you so much! 😊
I ended up porting my IndexBuilder to Fluent 4.
Although, I had to hammer it in a custom query action. Using the schema constraints to define an index
didn't feel right, and a custom
schema action is not available. It still looks to me there's some value in having some sort of IndexBuilder and an additional method in the Database protocol to go with it.