# Quotas module schema
# Copyright (C) 2009, AllWorldIT
# Copyright (C) 2008, LinuxRulz
# 
# 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
# (at your option) 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


/* Main quotas table, this defines the period the quota is over and how to track it */
CREATE TABLE quotas (
	ID			@SERIAL_TYPE@,

	PolicyID		@SERIAL_REF_TYPE@,
	
	Name			VARCHAR(255) NOT NULL,

	/* Tracking Options */
	Track			VARCHAR(255) NOT NULL,  /* Format:   <type>:<spec>

					      SenderIP - This takes a bitmask to mask the IP with. A good default is /24 

					      Sender & Recipient - Either "user@domain" (default), "user@" or "@domain" for the entire 
					      		email addy or email addy domain respectively. 
					   */

	/* Period over which this policy is valid,  this is in seconds */
	Period			@BIG_INTEGER@,

	Verdict			VARCHAR(255),
	Data			TEXT,
		
	Comment			VARCHAR(1024),
	
	Disabled		SMALLINT NOT NULL DEFAULT '0',

	FOREIGN KEY (PolicyID) REFERENCES policies(ID)
) @CREATE_TABLE_SUFFIX@;
INSERT INTO quotas (PolicyID,Name,Track,Period,Verdict) VALUES (5,'Recipient quotas','Recipient:user@domain',3600,'REJECT');
INSERT INTO quotas (PolicyID,Name,Track,Period,Verdict) VALUES (5,'Quota on all /24s','SenderIP:/24',3600,'REJECT');


/* Limits for the quota */
CREATE TABLE quotas_limits (
	ID			@SERIAL_TYPE@,

	QuotasID		@SERIAL_REF_TYPE@,

	Type			VARCHAR(255),  /* "MessageCount" or "MessageCumulativeSize" */
	CounterLimit		@BIG_INTEGER@,

	Comment			VARCHAR(1024),

	Disabled		SMALLINT NOT NULL DEFAULT '0',

	FOREIGN KEY (QuotasID) REFERENCES quotas(ID)
) @CREATE_TABLE_SUFFIX@;
INSERT INTO quotas_limits (QuotasID,Type,CounterLimit) VALUES (1,'MessageCount',10);
INSERT INTO quotas_limits (QuotasID,Type,CounterLimit) VALUES (1,'MessageCumulativeSize',8000);
INSERT INTO quotas_limits (QuotasID,Type,CounterLimit) VALUES (2,'MessageCount',12);


/* This table is used for tracking the quotas */
CREATE TABLE quotas_tracking (

	QuotasLimitsID		@SERIAL_REF_TYPE@,
	TrackKey		VARCHAR(@TRACK_KEY_LEN@),

	/* Last time this record was update */
	LastUpdate		@BIG_INTEGER@,  /* NULL means not updated yet */	

	Counter			NUMERIC(10,4),
	
	UNIQUE (QuotasLimitsID,TrackKey),
	FOREIGN KEY (QuotasLimitsID) REFERENCES quotas_limits(ID)
) @CREATE_TABLE_SUFFIX@;
CREATE INDEX quotas_tracking_idx1 ON quotas_tracking (LastUpdate);

