Fluent ORM - add unique constraint for a key?

(Benjamin Mayo) #1

I'm just getting started with using Vapor and Fluent. I have created models, inserted those into the database, and performing queries. However, I would like to specify that one of my model properties is unique across the table (but not the id).

How can this be achieved? I am currently relying on Model automatically creating the table schemas. I'm struggling to find where I can intercept it to augment a unique constraint.

I'm using PostgreSQL if that makes any difference.

(Tim) #2

@benjaminmayo you can do it like so: https://github.com/raywenderlich/vapor-til/blob/master/Sources/App/Models/User.swift#L70

The addProperties function adds all the columns to the table using default types and then you can add the unique constraints after. Note that you'll need to wipe the DB to get it to run the migration again to start with

(Benjamin Mayo) #3

Thank you!

Ugh, obvious in hindsight. I'd found addProperties(to:) before posting but what I didn't grok was the auto-conformance was calling that method from prepare(_:). One thing I've found is that Xcode struggles to effectively navigate through the deep conformance graphs that Vapor (and its siblings) rely on so much, which makes it particularly hard to get your bearings on what needs to be 'overridden' where.