Hello everyone.
I'm trying to solve the following problem:Currently, I'm generating the required table with the crosstab function:
cols = 'row_n int, ' || (SELECT string_agg(col_name, ', ') FROM (SELECT 'c' || generate_series(0, col_max) || ' int' AS col_name) AS Subq);
query = 'CREATE TEMPORARY TABLE Temp_show AS SELECT * FROM CROSSTAB(''SELECT row_n, col, val FROM ' || matrix_name || ' ORDER BY 1'', ''SELECT generate_series(0, ' || col_max || ')'') AS (' || cols || ');';
cols = 'row_n int, ' || (SELECT string_agg(col_name, ', ') FROM (SELECT 'c' || generate_series(0, col_max) || ' int' AS col_name) AS Subq);
query = 'CREATE TEMPORARY TABLE Temp_show AS SELECT * FROM CROSSTAB(''SELECT row_n, col, val FROM ' || matrix_name || ' ORDER BY 1'', ''SELECT generate_series(0, ' || col_max || ')'') AS (' || cols || ');';
I have two solutions, but they need two queries. The first looks like this:
SELECT show_matrix('matrix');
SELECT * FROM Temp_show;
where show_matrix essentially executes the query defined above and returns void.
The second is
SELECT prepare_matrix('matrix');
SELECT * FROM show_matrix('matrix');
Here show_matrix returns setof needed row type; prepare_matrix creates that type and the show_matrix with the right type in "returns ...".
(EXECUTE 'CREATE TYPE needed_type AS (' || cols ||');';
CREATE FUNCTION show_matrix(text) RETURNS SETOF needed_type AS $$ ...
RETURN QUERY SELECT * FROM Temp_show;)
Both solutions need two subsequent queries, because objects from the second query don't exist before the first is executed. The trouble is that the function's returning type should
be defined as soon as function starts execution, but that type depends
on the name of a matrix - on an argument.
Triggers, to my knowledge, aren't fired on plain selects, so they can't be used to compress two lines into one; rules on select, on the other hand, allow only one action. An anyelement on the output requires an anyelement of the same type on the input, which I can't get without redefining function or some element of that type to pass as an argument to a polymorphic function...
Triggers, to my knowledge, aren't fired on plain selects, so they can't be used to compress two lines into one; rules on select, on the other hand, allow only one action. An anyelement on the output requires an anyelement of the same type on the input, which I can't get without redefining function or some element of that type to pass as an argument to a polymorphic function...
So, is there any way to solve the problem in one query?
I've started learning PostgreSQL not long ago, so I'm probably missing something obvious. I'd be grateful for any help.
Regards,
Arseniy Nestyuk.