drop function if exists sp_add_article_category(
	p_parentid integer,
	p_article_category_name varchar );

create or replace function sp_add_article_category(
	p_parentid integer,
	p_article_category_name varchar ) returns integer as $$
declare
	retval integer;
	res varchar;
	num integer;
	_ordering integer;
	_level integer;
begin
	retval:=null;
	if p_parentid is null then
		select count(*) into num from article_categories where article_category_parentid is null;
		_ordering:=num+1;
		_level:=1;
		insert into article_categories(
			article_category_parentid,
			article_category_level,
			article_category_ordering,
			article_category_name
		) values (
			null,
			_level,
			_ordering,
			p_article_category_name );
		select currval('article_categories_article_category_id_seq') into retval;
		select sp_recalculate_tree_metadata(
			'article_categories',
			'article_category_id',
			'article_category_parentid',
			'article_category_level',
			'article_category_ordering',
			'article_category_meta_l',
			'article_category_meta_r' ) into res;
		return retval;
	else
		select count(*) into num from article_categories where article_category_parentid=p_parentid;
		_ordering:=num+1;
		select article_category_level into _level from article_categories where article_category_id=p_parentid;
		_level:=_level+1;
		insert into article_categories(
			article_category_parentid,
			article_category_level,
			article_category_ordering,
			article_category_name
		) values (
			p_parentid,
			_level,
			_ordering,
			p_article_category_name );
		select currval('article_categories_article_category_id_seq') into retval;
		select sp_recalculate_tree_metadata(
			'article_categories',
			'article_category_id',
			'article_category_parentid',
			'article_category_level',
			'article_category_ordering',
			'article_category_meta_l',
			'article_category_meta_r' ) into res;
		return retval;
	end if;
	return retval;
end;
$$ language plpgsql;

