Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
WITH RECURSIVE query now uses column names defined
  • Loading branch information
dhoss committed Nov 3, 2014
1 parent 1d83c11 commit c32ef8e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
9 changes: 6 additions & 3 deletions lib/treeify.rb
Expand Up @@ -16,7 +16,8 @@ module Treeify

class_attribute :cols
scope :roots, -> { where(parent_id: nil) }
scope :tree_for, ->(instance) { where("#{table_name}.id IN (#{tree_sql_for(instance)})").order("#{table_name}.id") }

scope :tree_for, ->(instance) { self.find_by_sql self.tree_sql_for(instance) }
scope :tree_for_ancestors, ->(instance) { where("#{table_name}.id IN (#{tree_sql_for_ancestors(instance)})").order("#{table_name}.id") }

end
Expand Down Expand Up @@ -49,17 +50,19 @@ def appropriate_column_listing(columns = columns_joined)
end

def tree_sql(instance)
cte_params = has_config_defined_cols? ? "id, path, #{columns_joined}" : "id, path"
cte_params = has_config_defined_cols? ? "id, parent_id, path, #{columns_joined}" : "id, parent_id, path"

"WITH RECURSIVE cte (#{cte_params}) AS (
SELECT id,
parent_id,
array[id] AS path#{appropriate_column_listing}
FROM #{table_name}
WHERE id = #{instance.id}
UNION ALL
SELECT #{table_name}.id,
#{table_name}.parent_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
Expand All @@ -68,7 +71,7 @@ def tree_sql(instance)

def tree_sql_for(instance)
"#{tree_sql(instance)}
SELECT id FROM cte
SELECT * FROM cte
ORDER BY path"
end

Expand Down
16 changes: 10 additions & 6 deletions spec/treeify_spec.rb
Expand Up @@ -16,15 +16,17 @@
end

it "retrieves all the columns defined in the configuration" do
expected_sql = "WITH RECURSIVE cte (id, path, name) AS (
expected_sql = "WITH RECURSIVE cte (id, parent_id, path, name) AS (
SELECT id,
parent_id,
array[id] AS path, name
FROM nodes
WHERE id = 1
UNION ALL
SELECT nodes.id,
nodes.parent_id,
cte.path || nodes.id, nodes.name
FROM nodes
JOIN cte ON nodes.parent_id = cte.id
Expand Down Expand Up @@ -133,15 +135,17 @@
subchild = child.children.first
expect(parent.descendent_tree).to match_array([
{
"id" => child.id,
"id" => child.id,
"parent_id" => parent.id,
"name" => child.name,
"path" => [parent.id, child.id],
"name" => child.name,
"children" => [
{
"id" => subchild.id,
"id" => subchild.id,
"parent_id" => child.id,
"name" => subchild.name,
"children" => []
"path" => [parent.id, child.id, subchild.id],
"name" => subchild.name,
"children" => []
}
]
}
Expand Down

0 comments on commit c32ef8e

Please sign in to comment.