onyxframework / sql

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

Disallow referencing by reference instance #92

Open vladfaust opened 5 years ago

vladfaust commented 5 years ago

Currently this code can raise in runtime with NilAssertionError if user.id is nil.

class Use
  schema users do
    pkey id : Int32
  end
end

class Post
  schema posts do
    type author : User, key: "the_author_id"
  end
end

Post.where(author: user)
Post.update.set(author: user)

I propose to make things more explicit but reduce runtime errors in exchange. The .id referenced in queries is User variable, not its column name. The code would raise in compilation time if something is wrong:

Post.where("author.id": user.id!) # SELECT FROM posts WHERE the_author_id = ?
Post.update.set("author.id": user.id!) # UPDATE posts SET the_author_id = ?

This could create confusion between explicit SQL variants, though. Such a query would raise in runtime, because posts table doesn't have author.id column in the database schema:

Post.set("author.id", user.id!) # UPDATE posts SET author.id = ?

Possible workaround is bang query methods which mean explicit SQL, i.e.:

Post.set!("the_author_id", user.id)
User.where!("id IN ?, ?", {41, 42})
vladfaust commented 5 years ago

Another approach is to restrict reference types to their primary key types:

Post.set(author: user.id!)

Which makes the most sense IMO.