Record validation/check constraints in Slick

54 views
Skip to first unread message

Mike Allen

unread,
Feb 24, 2020, 6:37:02 PM2/24/20
to Slick / ScalaQuery
Hi All!

I'm new to Slick, and finding it a great tool that's easy to use. Great stuff!

The main problem I'm struggling with is being able to perform record/row validation on data. Is this possible? How do I ensure that combinations of values for multiple columns in a table record is valid as part of the schema? (Equivalent to a "check constraint" in PostgreSQL, for example?)

Say I have columns latitude and longitude fields, of type Option[Double] in a table. A row would only be valid if both are defined, or if both are undefined. (I would also want to check the range of value in each field if defined too.) However, if only one is defined, and the other is undefined, then I want to reject insertions of that data.

Thanks for any assistance you can offer!

Mike

Prakash Kr.

unread,
Feb 24, 2020, 7:58:06 PM2/24/20
to Slick / ScalaQuery
Hello Mike,

For this kind of use case I will do the records check before persisting using if else or with the help of pattern matching. Eg:where a and b are the range of numbers from a to b, ValidationException is the custom exception which I assumed it.

If(longitude.isDefined && (a to b) contains longitude||latitude && latitude.isDefined)
db.run(location +=location)
else
throw new ValidationException("Longitude and latitude is required")


Regards,
Prakash

Mike Allen

unread,
Feb 25, 2020, 12:04:16 AM2/25/20
to Slick / ScalaQuery
Hi Prakash,

Thanks for your reply.

I guess my problem is that this kind of approach doesn't work for updates, and is unwieldy in practice. I will need hundreds of such checks in my real system, and I need the database to be the final arbiter of the consistency of the data, not the application.

Are you saying that there is no support for implementing checks at the schema level in Slick?

Best Regards,

Mike

Prakash Kr.

unread,
Feb 25, 2020, 12:51:11 AM2/25/20
to Slick / ScalaQuery
Hello Mike,

I don't think slick comes up with this kind of behaviour,for this we can have not null at the db level,let the db throw the expectation but still we can achieve this with the help of spark sql not with slick.

Thanks,
Prakash

Reply all
Reply to author
Forward
0 new messages