Refactor a PL/pgSQL function to return the output of various SELECT queries

后端 未结 4 1271
执笔经年
执笔经年 2020-11-22 00:05

I wrote a function that outputs a PostgreSQL SELECT query well formed in text form. Now I don\'t want to output a text anymore, but actually run the generated <

4条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 00:07

    # copy paste me into bash shell directly
    clear; IFS='' read -r -d '' sql_code << 'EOF_SQL_CODE'
    CREATE OR REPLACE FUNCTION func_get_all_users_roles()
      -- define the return type of the result set as table
      -- those datatypes must match the ones in the src
      RETURNS TABLE (
                     id           bigint
                   , email        varchar(200)
                   , password     varchar(200)
                   , roles        varchar(100)) AS
    $func$
    BEGIN
       RETURN QUERY 
       -- start the select clause
       SELECT users.id, users.email, users.password, roles.name as roles
       FROM user_roles
       LEFT JOIN roles ON (roles.guid = user_roles.roles_guid)
       LEFT JOIN users ON (users.guid = user_roles.users_guid)
       -- stop the select clause
    ;
    END
    $func$  LANGUAGE plpgsql;
    EOF_SQL_CODE
    # create the function
    psql -d db_name -c "$sql_code"; 
    
    # call the function 
    psql -d db_name -c "select * from func_get_all_users_roles() "
    

提交回复
热议问题