Postgres CTE : type character varying(255)[] in no

2020-07-03 07:52发布

问题:

I am new to SO and postgres so please excuse my ignorance. Attempting to get the cluster for a graph in postgres using a solution similar to the one in this post Find cluster given node in PostgreSQL

the only difference is my id is a UUID and I am using varchar(255) to store this id

when i try to run the query I get the following error (but not sure how to cast):

ERROR: recursive query "search_graph" column 1 has type character varying(255)[] in non-recursive term but type character varying[] overall

SQL state: 42804 Hint: Cast the output of the non-recursive term to the correct type. Character: 81

my code (basically same as previous post):

WITH RECURSIVE search_graph(path, last_profile1, last_profile2) AS (
SELECT ARRAY[id], id, id
FROM node WHERE id = '408d6b12-d03e-42c2-a2a7-066b3c060a0b'
UNION ALL
SELECT sg.path || m.toid || m.fromid, m.fromid, m.toid
FROM search_graph sg
JOIN rel m
ON (m.fromid = sg.last_profile2 AND NOT sg.path @> ARRAY[m.toid]) 
   OR (m.toid = sg.last_profile1 AND NOT sg.path @> ARRAY[m.fromid])
)

 SELECT DISTINCT unnest(path) FROM search_graph;

回答1:

Try casting the SELECT lists in the recursive and non-recursive terms to varchar.

WITH RECURSIVE search_graph(path, last_profile1, last_profile2) AS (
    SELECT ARRAY[id]::varchar[], id::varchar, id::varchar
    FROM node WHERE id = '408d6b12-d03e-42c2-a2a7-066b3c060a0b'
  UNION ALL
    SELECT (sg.path || m.toid || m.fromid)::varchar[], m.fromid::varchar, m.toid::varchar
    FROM search_graph sg
    JOIN rel m
    ON (m.fromid = sg.last_profile2 AND NOT sg.path @> ARRAY[m.toid]) 
       OR (m.toid = sg.last_profile1 AND NOT sg.path @> ARRAY[m.fromid])
)
SELECT DISTINCT unnest(path) FROM search_graph;