onyxframework / sql

A delightful SQL ORM ☺️
https://api.onyxframework.com/sql
MIT License
91 stars 7 forks source link

Schema expands to `property` instead of `property!` #71

Closed vladfaust closed 5 years ago

vladfaust commented 5 years ago

Currently this code:

class User
  schema users do
    pkey id : Int32
    type name : String
  end
end

Expands to "bang" properties:

class User
  property! id : Int32
  property! name : String
end

Which allows to call the properties assuming that they are not nil:

user = User.new(id: 42)
pp user.id == pp user.id?.not_nil! # OK

user = User.new(id: nil)
pp user.id # NillAssertion error in runtime

It enables writing less code, but makes becomes vulnerable to human errors like "I forgot to query id when fetching a user".

So, should the schema expand to property instead?

user = User.new(id: 42)
pp user.id # Compile-time is Int32 | Nil
pp user.id.not_nil! # Now it is Int32 only

It would make the code more safe, as the developer would be implied to explicitly state that a property is not nil, which would take some attention. He would think:

Ugh, its nilable in compile time. Oh, yes, that means that I can forget fetching it from DB. So I'd take time ensuring that the query preloads this property and only then add .not_nil! to the call.

However, it brings more bloated code with .not_nil!s everywhere. Also working with references becomes literally a nightmare:

user.id.not_nil!
post.author.not_nil!.id.not_nil!

Moreover, it's still not 100% bulletproof to human errors, as the developer may automatically type .not_nil! and still forgetting to actually preload a property.

WDYT?