JetBrains / JetBrains/Exposed

Validations

Open
#759 4 comments 3 reactions 0 assignees View on GitHub
enhancement
Dominant language
Kotlin
Stars
9.3k
Forks
798
Avg merge
4d 2h
Merged PRs (30d)
26

Description

Hi,

I have been trying out Exposed for a while and I noticed that there is no built in support for validations either on DSL or DAO side. I suppose this is by design if Exposed is a lightweight SQL library. I can see the argument on not having validations in exposed. The reality however is that I have had the need for validations in every project I have been involved with.

If exposed is not going to have support for validations what do you think would be the best approach to deal with them on application level both on DSL and DAO style? One approach could be adding them to the repository:

DAO:
```kotlin
object Events : IntIdTable() {
val startDate = date("start_date")
val endDate = date("end_date")
}

class Event(id: EntityID) : IntEntity(id) {
companion object : IntEntityClass(Events)

var startDate by Events.startDate
var endDate by Events.endDate
}

data class EventDataClass(val startDate: DateTime, val endDate: DateTime)

class EventsRepository {
fun save(event: EventDataClass) {
val errors = validate(event)
if (errors.isNotEmpty()) {
throw Exception(errors.toString())
}

Event.new {
startDate = event.startDate
endDate = event.endDate
}
}

private fun validate(event: EventDataClass): MutableList {
val errors = mutableListOf()
if (event.endDate.isBefore(event.startDate)) {
errors.add("End date is before start date")
}

return errors
}
}
```
For a developer that comes from Ruby on Rails world this code looks a bit odd. My expectation was that Event class would be the public API to create new records in DB but at least if I want to add validations it looks like it can't be the public API. Also `all()` method is not transactional so is the design idea here indeed so that in both DSL and DAO styles a repository should be implemented which is transactional?

Second question is also kind of related on validations. Is it so that there is no support for single table inheritance? In Rails what I could do is add validations but also relationships on the child models:
```ruby
class Calendar < ApplicationRecord
has_many :events
end

class Event < ApplicationRecord
belongs_to :calendar
end

class PrivateEvent < Event
belongs_to :user
end

class PublicEvent < Event

end

calendar = Calendar.create()
public_event = PublicEvent.create(calendar: calendar) # OK

calendar = Calendar.create()
private_event = PrivateEvent.create(calendar: calendar) # NOT OK: User is missing
puts private_event.errors # Prints out a validation error that user is required.
```
If there is no support in Exposed for this, ideas to implement this on application level are welcome too.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.