Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lateral joins #48

Merged
merged 4 commits into from
Nov 8, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions spec/model/model_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ module ModelSpec
u.categories.to_sql.should eq "SELECT DISTINCT ON (\"model_categories\".\"id\") \"model_categories\".* " +
"FROM \"model_categories\" " +
"INNER JOIN \"model_posts\" ON " +
"((\"model_posts\".\"category_id\" = \"model_categories\".\"id\")) " +
"(\"model_posts\".\"category_id\" = \"model_categories\".\"id\") " +
"WHERE (\"model_posts\".\"user_id\" = 1)"
u.categories.count.should eq(1)
end
Expand All @@ -506,7 +506,7 @@ module ModelSpec

Post.query.join(:model_users) { model_posts.user_id == model_users.id }.to_sql
.should eq "SELECT \"model_posts\".* FROM \"model_posts\" INNER JOIN \"model_users\" " +
"ON ((\"model_posts\".\"user_id\" = \"model_users\".\"id\"))"
"ON (\"model_posts\".\"user_id\" = \"model_users\".\"id\")"
end
end

Expand All @@ -520,7 +520,7 @@ module ModelSpec

user_with_a_post_minimum.to_sql.should eq \
"SELECT DISTINCT \"model_users\".* FROM \"model_users\" INNER JOIN " +
"\"model_posts\" ON ((\"model_posts\".\"user_id\" = \"model_users\".\"id\"))"
"\"model_posts\" ON (\"model_posts\".\"user_id\" = \"model_users\".\"id\")"

user_with_a_post_minimum.with_posts.each { } # Should just execute
end
Expand Down
4 changes: 2 additions & 2 deletions spec/sql/delete_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ module DeleteSpec
r = delete_request.from(:table).where({id: complex_query})
r.to_sql.should eq "DELETE FROM \"table\" WHERE \"id\" IN (SELECT * " +
"FROM \"users\" " +
"INNER JOIN \"role_users\" ON ((\"role_users\".\"user_id\" = \"users\".\"id\")) " +
"INNER JOIN \"roles\" ON ((\"role_users\".\"role_id\" = \"roles\".\"id\")) " +
"INNER JOIN \"role_users\" ON (\"role_users\".\"user_id\" = \"users\".\"id\") " +
"INNER JOIN \"roles\" ON (\"role_users\".\"role_id\" = \"roles\".\"id\") " +
"WHERE \"role\" IN ('admin', 'superadmin') " +
"ORDER BY priority DESC, name ASC " +
"LIMIT 1)"
Expand Down
10 changes: 8 additions & 2 deletions spec/sql/select_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@ module SelectSpec
r = select_request.from(:users).where { users.id.in?(complex_query.clear_select.select(:id)) }
r.to_sql.should eq "SELECT * FROM \"users\" WHERE \"users\".\"id\" IN (" +
"SELECT \"id\" FROM \"users\" INNER JOIN \"role_users\" ON " +
"((\"role_users\".\"user_id\" = \"users\".\"id\")) INNER JOIN \"roles\"" +
" ON ((\"role_users\".\"role_id\" = \"roles\".\"id\")) WHERE \"role\" IN" +
"(\"role_users\".\"user_id\" = \"users\".\"id\") INNER JOIN \"roles\"" +
" ON (\"role_users\".\"role_id\" = \"roles\".\"id\") WHERE \"role\" IN" +
" ('admin', 'superadmin') ORDER BY priority DESC, " +
"name ASC LIMIT 50 OFFSET 50)"
end
Expand All @@ -268,6 +268,12 @@ module SelectSpec
r.to_sql.should eq "SELECT * FROM \"users\" FOR SHARE"
end

it "can join lateral" do
Clear::SQL::SelectQuery.new.from(:a)
.inner_join(:b, lateral: true) { a.b_id == b.id }.to_sql
.should eq %(SELECT * FROM "a" INNER JOIN LATERAL "b" ON ("a"."b_id" = "b"."id"))
end

it "can use & as AND and | as OR" do
r = select_request.from(:users).where {
((raw("users.id") > 100) & (raw("users.visible") == true)) |
Expand Down
6 changes: 3 additions & 3 deletions src/clear/extensions/enum/enum.cr
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ module Clear
when Slice(UInt8)
::\{{@type}}.from_string(String.new(x))
else
raise Clear::ErrorMessages.converter_error(x.class.name, "::{{@type}}")
raise Clear::ErrorMessages.converter_error(x.class.name, "::\{{@type}}")
end
end

Expand All @@ -101,10 +101,10 @@ module Clear
end
end

Clear::Model::Converter.add_converter("{{name.id}}", ::Clear::Model::Converter::\{{@type}}Converter)
Clear::Model::Converter.add_converter("\{{@type}}", ::Clear::Model::Converter::\{{@type}}Converter)
end

end


end
end
1 change: 1 addition & 0 deletions src/clear/migration/migration.cr
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
###
module Clear::Migration
include Clear::ErrorMessages

module Helper; end

include Helper
Expand Down
9 changes: 5 additions & 4 deletions src/clear/model/collection.cr
Original file line number Diff line number Diff line change
Expand Up @@ -273,18 +273,19 @@ module Clear::Model
end

# Get the last row from the collection query.
# if not found, return `nil`
# if not found, throw an error
def last!(fetch_columns = false) : T
last(fetch_columns).not_nil!
end

protected def join_impl(name, type, clear_expr)
# TODO: not sure about that...
# Redefinition of `join_impl` to avoid ambiguity on the column
# name if no specific column have been selected.
protected def join_impl(name, type, lateral, clear_expr)
if @columns.empty?
self.select("#{Clear::SQL.escape(T.table)}.*")
end

super(name, type, clear_expr)
super(name, type, lateral, clear_expr)
end

# Get the last row from the collection query.
Expand Down
11 changes: 8 additions & 3 deletions src/clear/sql/fragment/join.cr
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ module Clear::SQL
property type : String
property from : Selectable
property condition : Clear::Expression::Node?
property lateral : Bool

def initialize(@from, @condition = nil, type : Symbolic = :inner)
def initialize(@from, @condition = nil, @lateral = false, type : Symbolic = :inner)
@type = if type.is_a?(Symbol)
TYPE[type] || raise Clear::ErrorMessages.query_building_error("Type of join unknown: `#{type}`")
else
Expand All @@ -23,9 +24,13 @@ module Clear::SQL
def to_sql
c = condition
if c
"#{type} #{SQL.sel_str(from)} ON (#{c.resolve})"
[type,
lateral ? "LATERAL" : nil,
SQL.sel_str(from),
"ON",
c.resolve].compact.join(" ")
else
"#{type} #{SQL.sel_str(from)}"
{type, SQL.sel_str(from)}.join(" ")
end
end
end
Expand Down
4 changes: 1 addition & 3 deletions src/clear/sql/insert_query.cr
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ class Clear::SQL::InsertQuery

if @returning.nil?
s = to_sql
Clear::SQL.log_query(s) do
Clear::SQL.execute(connection_name, s)
end
Clear::SQL.execute(connection_name, s)
else
# return {} of String => ::Clear::SQL::Any
fetch(connection_name) { |x| o = x }
Expand Down
24 changes: 12 additions & 12 deletions src/clear/sql/query/join.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,28 @@ module Clear::SQL::Query::Join
getter joins : Array(SQL::Join)
end

protected def join_impl(name : Symbolic, type, clear_expr)
name = ( name.is_a?(Symbol) ? Clear::SQL.escape(name.to_s) : name )
protected def join_impl(name : Symbolic, type, lateral, clear_expr)
name = (name.is_a?(Symbol) ? Clear::SQL.escape(name.to_s) : name)

joins << Clear::SQL::Join.new(name, clear_expr, type)
joins << Clear::SQL::Join.new(name, clear_expr, lateral, type)
change!
end

def join(name : Symbolic, type = :inner, &block)
join_impl(name, type, Clear::Expression.ensure_node!(with Clear::Expression.new yield))
def join(name : Symbolic, type = :inner, lateral = false, &block)
join_impl(name, type, lateral, Clear::Expression.ensure_node!(with Clear::Expression.new yield))
end

def join(name : Symbolic, type = :inner)
join_impl(name, type, nil)
def join(name : Symbolic, type = :inner, lateral = false)
join_impl(name, type, lateral, nil)
end

def cross_join(name : Symbolic)
join(name, :cross)
def cross_join(name : Symbolic, lateral = false)
join(name, :cross, lateral = false)
end

{% for j in ["left", "right", "full_outer"] %}
def {{j.id}}_join(name : Symbolic, &block)
join_impl(name, :{{j.id}}, Clear::Expression.ensure_node!(with Clear::Expression.new yield))
{% for j in ["left", "right", "full_outer", "inner"] %}
def {{j.id}}_join(name : Symbolic, lateral = false, &block)
join_impl(name, :{{j.id}}, lateral, Clear::Expression.ensure_node!(with Clear::Expression.new yield))
end
{% end %}

Expand Down