Skip to content
This repository has been archived by the owner on Oct 28, 2019. It is now read-only.

Commit

Permalink
First pass at more advanced queries
Browse files Browse the repository at this point in the history
Build a query with a table. Add wheres and limits. Then build it.

In future passes I want to make things more flexible. Also need to
figure out where escaping values should go.
  • Loading branch information
paulcsmith committed Apr 5, 2017
1 parent 42137cd commit d3e7c25
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
41 changes: 41 additions & 0 deletions spec/lucky_record/query_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
require "../spec_helper"

describe "LuckyRecord::Query" do
it "selects all" do
new_query.to_sql.should eq "SELECT * FROM users"
end

it "can be limited" do
query = new_query.limit(1)
query.to_sql.should eq "SELECT * FROM users LIMIT 1"
end

it "handles simple where comparison" do
query = new_query.where_eq(:name, "'Paul'")
query.to_sql.should eq "SELECT * FROM users WHERE name = 'Paul'"
end

it "handles >" do
query = new_query.where_gt(:age, 20)
query.to_sql.should eq "SELECT * FROM users WHERE age > 20"
end

it "handles >=" do
query = new_query.where_gte(:age, 20)
query.to_sql.should eq "SELECT * FROM users WHERE age >= 20"
end

it "handles <" do
query = new_query.where_lt(:age, 20)
query.to_sql.should eq "SELECT * FROM users WHERE age < 20"
end

it "handles <=" do
query = new_query.where_lte(:age, 20)
query.to_sql.should eq "SELECT * FROM users WHERE age <= 20"
end
end

private def new_query
LuckyRecord::Query.new(table: :users)
end
62 changes: 62 additions & 0 deletions src/lucky_record/query.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
class LuckyRecord::Query
private getter :table
@limit : Int32?
@wheres = [] of String

def initialize(@table : Symbol)
end

def to_sql
sql_clauses.reject do |clause|
clause.nil? || clause.blank?
end.join(" ")
end

private def sql_clauses
[select_sql, wheres_sql, limit_sql]
end

private def select_sql
"SELECT * FROM #{table}"
end

def limit(amount)
@limit = amount
self
end

private def limit_sql
if @limit
"LIMIT #{@limit}"
end
end

def where_eq(column, value)
@wheres << "WHERE #{column} = #{value}"
self
end

def where_gt(column, value)
@wheres << "WHERE #{column} > #{value}"
self
end

def where_gte(column, value)
@wheres << "WHERE #{column} >= #{value}"
self
end

def where_lt(column, value)
@wheres << "WHERE #{column} < #{value}"
self
end

def where_lte(column, value)
@wheres << "WHERE #{column} <= #{value}"
self
end

private def wheres_sql
@wheres.join(" ")
end
end

0 comments on commit d3e7c25

Please sign in to comment.