/*
 * This system procedure is used to return the
 * list of triggers defined from the database specified
 */
CREATE PROCEDURE psp_triggers
(   
	in :database_qual   VARCHAR(20) = DATABASE(), -- Name of the database
    in :table_name      VARCHAR(255) = null -- Name of the table
)

RETURNS
(
    TRIGGER_QUALIFIER   VARCHAR (20), -- Name of the database that contains the trigger
    TRIGGER_OWNER       VARCHAR (20),  -- owner of the trigger
    TABLE_NAME          VARCHAR(255), -- Name of the table
    TRIGGER_NAME        VARCHAR(255), -- Name of the trigger
    ISUPDATE            UTINYINT, -- Update trigger event
    ISDELETE            UTINYINT, -- Delete trigger event
    ISINSERT            UTINYINT, -- Insert trigger event
    ISAFTER             UTINYINT, -- Trigger action time - after
    ISBEFORE            UTINYINT,  -- Trigger action time - before
    REMARKS             VARCHAR(255)	-- Remarks
);

BEGIN
    -- Variable to hold the dynamic query   
    DECLARE :stmt_psp_triggers LONGVARCHAR;
    DECLARE :table_trigger VARCHAR(30);
    DECLARE :table_file  VARCHAR(30);

    -- Check if the database qualifier specified is a blank string
	if (rtrim(:database_qual) = '') then
		SIGNAL 'S1000', 'Please enter a valid database name. Database name cannot be a blank string'; 
	end if;

     -- Check if the table name specified is a blank string
	if (rtrim(:table_name) = '') then
		SIGNAL 'S1000', 'Table name cannot be a blank string'; 
	end if;
    
	SET :database_qual = IFNULL(:database_qual,DATABASE());
	/* If table name is not supplied or value is null
	   match all */
	SET :table_name = IFNULL(:table_name,'%');
	
	/* Enumerate the triggers information */
    set :table_trigger = '"' + :database_qual + '".X$Trigger' ;
    set :table_file = '"' + :database_qual + '".X$File B' ;
	
    SET :stmt_psp_triggers = ' SELECT ''' +
								:database_qual +
								''',  null, ' +
								' B.Xf$Name, ' +
								' A.Xt$Name, ' +
								' IF(A.Xt$Event = 2, 1, 0), ' + 
								' IF(A.Xt$Event = 1, 1, 0), ' +
						        ' IF(A.Xt$Event = 0, 1, 0), ' +
								' IF(A.Xt$ActionTime = 1, 1, 0), ' +
								' IF(A.Xt$ActionTime = 0, 1, 0), ' +
								' null ' +
								' FROM ' + :table_trigger +' A, ' + 
										:table_file  +
								' WHERE A.Xt$File = B.Xf$Id AND A.Xt$Name ' +
                                'LIKE ''' +	:table_name + ''';'
    exec (:stmt_psp_triggers);
END; -- End of stored procedure.
