drop function get_traffic_limit(varchar);

CREATE FUNCTION get_traffic_limit(varchar) RETURNS INT8 AS ' 
DECLARE 
        rec RECORD; 
        ret varchar; 
BEGIN 
        select into rec param from users_attribute where user_name = btrim($1) AND attr = ''Traffic-Limit'';
        IF NOT FOUND THEN 
                return -1; 
        ELSE 
                return rec.param;
        END IF; 
END; 
' LANGUAGE plpgsql;

DROP FUNCTION check_lost(varchar);
CREATE FUNCTION check_lost(varchar) RETURNS INT4 AS '
DECLARE rec RECORD;
BEGIN
	select into rec * from stat where stop is null and now()-update > interval ''20 min'' and user_name=$1;
	IF NOT FOUND THEN
		return 0;
	ELSE
	    UPDATE stat SET
		 stop = update
		 WHERE user_name = $1 AND acct_s_id = rec.acct_s_id AND stop IS NULL;

            UPDATE users_attribute SET param = INT8(param) - rec.inp - rec.out
                 WHERE user_name = $1 AND attr = ''Traffic-Limit'';

            UPDATE users
                    SET active = false WHERE get_traffic_limit($1) <= 0;
	    return 1;
	END IF;
END
' LANGUAGE plpgsql;