onyxframework / sql

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

Remove Query #38

Closed vladfaust closed 6 years ago

vladfaust commented 6 years ago

If a developer does migrations on his own, which requires SQL knowledge, why using handy Query then? Let 'em write raw SQL queries!


Pros:

Cons:


user = repo.query_one(Query(User).where(id: 42))

turns into

query = <<-SQL
  SELECT * FROM users WHERE id = $1
SQL

user = repo.query_one(User, query, 42)

and

posts = repo.query(Query(Post).join(:author).order_by(:created_at)

turns into

query = <<-SQL
  SELECT posts.*, '' AS _author, author.*
  FROM posts
  JOIN users AS author ON author.id = posts.author_id
  ORDER BY created_at
SQL

posts = repo.query(Post, query)

rfc 🤔

vladfaust commented 6 years ago

Maybe introduce some kind of queries container, which would store and validate custom queries on compilation/launch?

GET_USER = Queries.add(User, "SELECT * FROM users WHERE id = ?")
user = repo.query(GET_USER)

GET_POSTS = Queries.add([Post], <<-SQL
  SELECT posts.*, '' AS _author, author.*
  FROM posts
  JOIN users AS author ON author.id = posts.author_id
  ORDER BY created_at
SQL)
posts = repo.query(GET_POSTS)
vladfaust commented 6 years ago

How about leaving all as-is, but trying to get rid of Model class and introducing some kind of baking mechanism?

baked_query = Query(User).where(id: 0).bake # Stores "SELECT * FROM user WHERE id = ?"
user = repo.query_one(baked_query, 42) # Super-performant, right?

Update:

And it's already here:

class Foo
  QUERY = Query(User).where(id: 0).to_s # Results in plain SQL

  def foo
    user = repo.query_one(User, QUERY, 1)
  end
end
vladfaust commented 6 years ago

Thanks to dedf31756cca72f07477e49cffdaa243f7351739, repo.query(User.where(id: 42)) is now possible, which is good enough IMO :smirk: