Skip to content
Permalink
Browse files

added functionality to build WITH RECURSIVE query properly with colum…

…n names included in the query
  • Loading branch information...
dhoss committed Nov 3, 2014
1 parent da2acb4 commit 1d83c11df782a0f3cb9f9a7edf017e58e94a7fe3
Showing with 37 additions and 6 deletions.
  1. +26 −3 lib/treeify.rb
  2. +11 −3 spec/treeify_spec.rb
@@ -27,17 +27,40 @@ def tree_config(hash = {})
self.cols = hash[:cols]
end

def columns_joined(char=",")
self.cols.join(char)
end

def columns_with_table_name
self.cols.map{|c|
c = "#{table_name}.#{c}"
}.join(",")
end

def has_config_defined_cols?
!self.cols.empty?
end

# sort of hacky, but check to see if we have any columns defined in the config
# if we do, return the string of columns, formatted appropriately
# otherwise, just return an empty string
def appropriate_column_listing(columns = columns_joined)
has_config_defined_cols? == true ? ", #{columns}" : ""
end

def tree_sql(instance)
"WITH RECURSIVE cte (id, path) AS (
cte_params = has_config_defined_cols? ? "id, path, #{columns_joined}" : "id, path"

"WITH RECURSIVE cte (#{cte_params}) AS (
SELECT id,
array[id] AS path
array[id] AS path#{appropriate_column_listing}
FROM #{table_name}
WHERE id = #{instance.id}
UNION ALL
SELECT #{table_name}.id,
cte.path || #{table_name}.id
cte.path || #{table_name}.id#{appropriate_column_listing(columns_with_table_name)}
FROM #{table_name}
JOIN cte ON #{table_name}.parent_id = cte.id
)"
@@ -16,24 +16,32 @@
end

it "retrieves all the columns defined in the configuration" do
expected_sql = "WITH RECURSIVE cte (id, path) AS (
expected_sql = "WITH RECURSIVE cte (id, path, name) AS (
SELECT id,
array[id] AS path
array[id] AS path, name
FROM nodes
WHERE id = 1
UNION ALL
SELECT nodes.id,
cte.path || nodes.id
cte.path || nodes.id, nodes.name
FROM nodes
JOIN cte ON nodes.parent_id = cte.id
)"
expect(Node.tree_sql(Node.first)).to eq(expected_sql)
end
end

describe "Utility methods" do
it "joins the columns with a characer" do
pending "Still trying to get this working"
Treeify.cols << :another_test_column
expect(Treeify.columns_joined(",")).to eq("another_test_column,name")
end
end


describe "Down the tree" do
subject(:parent) { Node.roots.first }
it "retrieves its descendents" do

0 comments on commit 1d83c11

Please sign in to comment.
You can’t perform that action at this time.