-- FUNCTION: public.get_grid_columns(text, integer)

-- DROP FUNCTION IF EXISTS public.get_grid_columns(text, integer);

CREATE OR REPLACE FUNCTION public.get_grid_columns(
	var_entity_name text,
	var_company_id integer)
    RETURNS jsonb
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
DECLARE
    select_columns JSONB := '[]';
    field RECORD;
BEGIN
    FOR field IN
        SELECT mgl.field_name, mgl.display_name, mgl.width as column_width, 
	    mgl.order_no, is_searchable, is_grid_column, mgl.is_sortable, mgl.field_name
        FROM master_grids mg
        JOIN master_grid_line_items mgl ON mg.id = mgl.master_grid_id
        WHERE mg.entity_name = var_entity_name AND mg.company_id = var_company_id
		ORDER BY mgl.order_no ASC
    LOOP
        select_columns := select_columns || jsonb_build_array(
			jsonb_build_array(
				field.field_name, field.display_name, field.column_width,
				field.order_no, field.is_searchable, field.is_grid_column, field.is_sortable, field.field_name
			)
		);
    END LOOP;
    RETURN select_columns;
END;
$BODY$;

-- ALTER FUNCTION public.get_grid_columns(text, integer)
--     OWNER TO postgres;
