7. select row_to_json (location)
from
(select id, ancestry, name, coordinates from locations)
as location
{"id":23727,"ancestry":"214/217/22888","name":"Olho d'Água do Piauí","coordinates":"POINT (-42.53937 -5.84854)"}
{"id":69289,"ancestry":"74/115/68153","name":"la Sentiu de Sió","coordinates":"POINT (0.86948 41.79807)"}
Tuesday, January 15, 13
8. select array_to_json (array_agg(location))
from
(select id, ancestry, name, coordinates from locations)
as location
[{"id":23727,"ancestry":"214/217/22888","name":"Olho d'Água do Piauí",
"coordinates":"POINT (-42.53937 -5.84854)"}, {"id"69289,"ancestry":"74/115/68153",
"name":"la Sentiu de Sió","coordinates":"POINT (0.86948 41.79807)"}]
Tuesday, January 15, 13
11. nodes[nil].collect { |location| prepare_node(location) }
def prepare_node(location)
node(location).
merge(prepare_children(nodes[node_key_for_children(location)]))
end
def node(location)
location.to_node_data
end
def prepare_children(children)
{ children: children.collect do |location|
prepare_node(location)
end
}
end
Tuesday, January 15, 13
18. CREATE OR REPLACE FUNCTION find_locations_with_ancestors(text, boolean)
RETURNS int[] AS
$$
DECLARE
search_result_ids int[];
all_ids int[];
pattern text;
BEGIN
pattern := '^('||$1||')|[ |,]('||$1||')';
FOR search_result_ids IN (
select (locations.id || string_to_array(locations.ancestry, '/')::int[]) as ids
from locations
where
(locations.name ~* pattern or locations.code ~* pattern or locations.alternative_name ~* pattern)
and (not($2) or locations.coordinates = ''
or locations.coordinates is null)
) LOOP
all_ids := all_ids || search_result_ids;
END LOOP;
RETURN all_ids;
END;
$$
LANGUAGE plpgsql;
Tuesday, January 15, 13
19. scope :find_with_ancestors, ->(query, only_without_coordinates) do
where('array[locations.id] <@
(select * from find_locations_with_ancestors(?, ?))',
query, only_without_coordinates)
end
Tuesday, January 15, 13
20. find_locations_with_ancestors = (quary::text, without_cordinates::boolean) ->
declare:
record_location_ids::int[]
ids::int[]
begin:
FOR record_location_ids IN
:ruby-
pattern = /^('||$1||')|[ |,]('||$1||')/
:ruby=
Location.where{
{ name: pattern, code: pattern, alternative_name: pattern }.sql_or,
‘(not($2) or locations.coordinates = '' or locations.coordinates is null)’
}.select{
id || string_to_array(ancestry, ‘/’)::int[]) as ids
}.to_sql
) LOOP
all_ids := all_ids || search_result_ids
END LOOP
RETURN all_ids
Tuesday, January 15, 13