[9.x] Add support for table check constraints #41078
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull requests adds support for table check constraints (Documentation: MySQL | PostrgeSQL | SQLite | SQL Server).
In our use case, a
Booking
has manyBookingItems
, which morph to acontractor
, who can either be aHotel
or aFlight
. In case of aHotel
we need to known theroom_id
, for any othercontractor_type
theroom_id
must benull
.While we will continue to validate this in the application, this PR allows us to add another layer of integrity for the database:
All the default database drivers have support for check constraints (edit: For MySQL 5.7 The CHECK clause is parsed but ignored by all storage engines.). SQLite comes with a number of limitions:
Some similar limitations are currently covered in
Blueprint::ensureCommandsAreValid()
(link), while more recent PRs throw exceptions inside of the corresponding methods ofSQLiteGrammar
(e.g.compileSpatialIndex
(link). I followed the later approach for now.Note that the
expression
is considered "raw", meaning that it is not wrapped or parsed in any way. As long as it is valid SQL, the underlying database should handle it well.I was torn between
$table->check(...)
and$table->checkConstraint(...)
and I'm of course open for suggestions.Please let me know if there's anything to be changed, improved or clarified.
If this gets merged, I'd be happy to look into inline column checks next as in
$table->integer('age)->check('age>=21')
.