-- sql/create_imap.sql
-- This file is part of Decimail; see http://decimail.org
-- (C) 2004-5 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 imap_mailbox_flags cascade;
drop view imap_subscribed_mailboxes cascade;

drop table imap_message_flags cascade;
drop index imap_message_flags_by_msg_id;
drop view imap_seen_messages cascade;
drop view imap_unseen_messages cascade;

begin;

create table imap_mailbox_flags (
	username	text	not null,
	mailbox_name	text	not null,
	flag		text	not null,

	primary key (username, mailbox_name, flag)
-- The following foreign key constraint was originally diabled because mailboxes
-- was a view, and foreign keys in views are not allowed.  mailboxes is now a
-- table, but it is regenerated when create_mailboxes.sql is run or when
-- a trigger on a table it depends on (eg users) changes.  During
-- this regeneration we really don't want all the flags to be dropped.  It may
-- be possible to make this work, but it needs investigation.
--	foreign key (username, mailbox_name) references mailboxes
--						on delete cascade
--						on update cascade
);

create view imap_subscribed_mailboxes as
	select username, mailbox_name
	from imap_mailbox_flags
	where flag='SUBSCRIBE';


create table imap_message_flags (
	username	text,
	msg_id		integer		references messages
					  on delete cascade
					  on update cascade,
	flag		text,

	primary key (username, msg_id, flag)
);

create index imap_message_flags_by_msg_id on imap_message_flags ( msg_id );
-- Helpful because of the references constraint, which is checked when
-- messages changes.


end;
