-- keywords table
drop table if exists keywords cascade;
create table keywords(
	keyword_id serial not null,
	keyword varchar(128),
	lkeyword varchar(128),
	constraint keywords_keyword_id_pkey primary key( keyword_id )
);

comment on table keywords is 'storage of keywords';
comment on column keywords.keyword_id is 'unique id of table';
comment on column keywords.keyword is 'the keyword itself';
comment on column keywords.lkeyword is 'lowercased keyword';

create index keywords_lkeyword_vpops_ind on keywords( lkeyword varchar_pattern_ops );
comment on index keywords_lkeyword_vpops_ind is 'vchar pattern ops index on lkeyword field';

-- trigger function
drop function if exists keywords_lcase();
create function keywords_lcase() returns trigger as $$
begin
	if (tg_op='INSERT') then
		new.lkeyword = lower( new.keyword );
	end if;
	if (tg_op='UPDATE') then
		if (old.keyword<>new.keyword) then
			new.lkeyword = lower( new.keyword );
		end if;
	end if;
	return new;
end;
$$ language plpgsql;
create trigger keywords_keyword_lcase_trigger before insert or update on keywords
	for each row execute procedure keywords_lcase();
comment on function keywords_lcase() is 'trigger on keywords - generate lkeyword field from keyword';

-- get/make keyword
drop function if exists sp_i_get_add_keyword( p_keyword varchar );
create function sp_i_get_add_keyword( p_keyword varchar ) returns integer as $$
declare
	retval integer;
begin
	select keyword_id from keywords into retval where lkeyword=lower(p_keyword);
	if retval is null then
		insert into keywords( keyword) values( p_keyword );
		select currval('keywords_keyword_id_seq') into retval;
	end if;
	return retval;
end;
$$ language plpgsql;

comment on function sp_i_get_add_keyword( p_keyword varchar ) is 'get or add keyword';

-- user based keywords
drop table if exists users_keywords;
create table users_keywords(
	user_id integer not null references users( user_id ),
	keyword_id integer not null references keywords( keyword_id )
);

create index users_keywords_user_id_ind on users_keywords( user_id );
comment on index users_keywords_user_id_ind is 'user_id index';

create index users_keywords_keyword_id_ind on users_keywords( keyword_id );
comment on index users_keywords_keyword_id_ind is 'keyword_id index';

