Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data fetching from a View in Postgresql Using Comma Separated Input

Tags:

postgresql

Created a view , my input will be in a comma separated , input contains only the column names of the view .

My input is '"Name","Description"' like this .

I tried like this

Select unnest(string_to_array('"Name","Description"',',')) 
 From  my_test_view

Unfortunately i got result like this

"Name"
"Description"
"Name"
"Description"

this only selecting my column names . I need json output with column values . my input is dynamic

like image 604
Casisac Avatar asked Dec 02 '25 10:12

Casisac


1 Answers

Effectively, what you are trying to do is to dynamically use identifiers on a view for selecting data. You need to write a PL/pgSQL function to do that.

If you trust the input data (i.e. you are certain that the input only contains comma-separated column names) then the solution is very straightforward:

CREATE FUNCTION my_test_view_dynamic(columns text) RETURNS SET OF my_test_view AS $$
BEGIN
    RETURN QUERY EXECUTE format('SELECT %s FROM my_test_view', columns);
END;
$$ LANGUAGE plpgsql STABLE STRICT;

If you are not so sure about the sanity of the input data, check it first:

CREATE FUNCTION my_test_view_dynamic(columns text) RETURNS SET OF my_test_view AS $$
DECLARE
    c text;
    safe_names text[] := '{}'::text[];
BEGIN
    FOREACH c IN ARRAY regexp_split_to_array(columns, ',') LOOP
        safe_names := safe_names || quote_identifier(c);
    END LOOP;
    RETURN QUERY EXECUTE format('SELECT %s FROM my_test_view', concat_ws(safe_names, ','));
END;
$$ LANGUAGE plpgsql STABLE STRICT;

Then call like:

SELECT * FROM my_text_view_dynamic('"Name","Description"');
like image 178
Patrick Avatar answered Dec 06 '25 00:12

Patrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!