-- sql/actions/subjects.sql
-- This file is part of Decimail; see http://decimail.org
-- (C) 2005 Philip Endecott
 
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 

drop table subjects cascade;
drop view subjects_mailboxes cascade;
drop trigger subjects_changed on subjects cascade;
delete from actions where mailbox_pattern='Subjects/%';

begin;

create table subjects (
    username  text  not null,
    subject   text  not null,
    primary key (username, subject)
);

-- To make it possible to create new mailboxes under Subjects/ there
-- must be at least one mailbox already present, since empty folders are
-- not found by Decimail's LIST command.  So you'll need to run something
-- like this:

-- insert into subjects (username, subject) values ('your-username-here', 'Hello');


create view subject_mailboxes as select
    username,
    ('Subjects/' || subject) as mailbox_name,
    ('select m.msg_id from u_messages m '
      'where subject_tsidx @@ to_tsquery(''default'',''' || subject || ''')') as query
    from subjects;


create trigger subjects_changed
	after insert or update or delete on subjects
	for each statement
	execute procedure update_mailboxes();


insert into actions (mailbox_pattern, create_action, delete_action,
                     rename_action)
values ('Subjects/%',
        'insert into subjects (username,subject) values (''$U'',replace(''$MB'',''Subjects/'',''''))',
        'delete from subjects where username=''$U'' and subject=replace(''$MB'',''Subjects/'','''')',
        'update subjects set subject=replace(''$NMB'',''Subjects/'','''') where username=''$U'' and subject=replace(''$OMB'',''Subjects/'','''')');


end;
