Skip to content
Permalink
Browse files

WITH RECURSIVE query now uses column names defined

  • Loading branch information...
dhoss committed Nov 3, 2014
1 parent 1d83c11 commit c32ef8ebdf62efd9bcdc0f556d1cbee16f1bd17d
Showing with 16 additions and 9 deletions.
  1. +6 −3 lib/treeify.rb
  2. +10 −6 spec/treeify_spec.rb
@@ -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
@@ -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
@@ -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

@@ -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
@@ -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" => []
}
]
}

0 comments on commit c32ef8e

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