fluent-kit icon indicating copy to clipboard operation
fluent-kit copied to clipboard

IndexBuilder

Open valeriomazzeo opened this issue 6 years ago • 5 comments

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

valeriomazzeo avatar Feb 14 '19 15:02 valeriomazzeo

SchemaBuilder currently supports unique indexes via unique(on:). Still need support for non-unique indexes.

tanner0101 avatar May 08 '20 13:05 tanner0101

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 avatar May 22 '20 22:05 photovirus

@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;")
    }
}

tanner0101 avatar May 28 '20 20:05 tanner0101

This is extremely valuable, thank you so much! 😊

photovirus avatar May 28 '20 20:05 photovirus

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.

valeriomazzeo avatar May 28 '20 23:05 valeriomazzeo