
CREATE OR REPLACE FUNCTION
    aus_find_user_flags (integer, integer)
RETURNS
    integer
AS '
    DECLARE
        flag_row RECORD; --
        flag_row_switch TEXT; --
        flag_row_name TEXT; --
    BEGIN
        FOR flag_row IN
            SELECT * FROM aus_user_flags WHERE user_id = $2
        LOOP
            flag_row_switch := (
                CASE WHEN
                    flag_row.enabled
                THEN
                    ''true''
                ELSE
                    ''false''
                END
             ); --
             
            flag_row_name := quote_literal(flag_row.flag_name); --
        
            EXECUTE ''
                INSERT INTO tmp_all_user_flags (user_id, flag_name)
                    SELECT '' || $1 || '', '' || flag_row_name || ''
                    WHERE TRUE EXCEPT
                        SELECT user_id, flag_name
                            FROM tmp_all_user_flags; --
            ''; --
            
            EXECUTE ''
                UPDATE tmp_all_user_flags SET enabled = '' || flag_row_switch || ''
                    WHERE user_id = '' || $1 || '' AND flag_name = ''
                    || flag_row_name || ''; --
            ''; --
            
        END LOOP; --

        RETURN 1; --
    END; --
' LANGUAGE plpgsql;
