/*
 * This system procedure return the primary key information
 * for the given table(s) from the database specified.
 */
CREATE PROCEDURE psp_pkeys
(   
	in :database_qual   VARCHAR(20) = DATABASE(), -- Name of the database
    in :table_name      VARCHAR(255) -- Name of the table 
)

RETURNS
(
    TABLE_QUALIFIER     VARCHAR (20), -- Name of the database that contains the table
    TABLE_OWNER         VARCHAR (20),  -- owner of the table
    TABLE_NAME          VARCHAR(255), -- Name of the table
    COLUMN_NAME         VARCHAR(255), -- Name of the column
    COLUMN_SEQ          USMALLINT, -- Sequence of the column
    PK_NAME             VARCHAR(255)  -- Name of the primary key name
);

BEGIN
    -- Variable to hold the dynamic query
    DECLARE :stmt_psp_pkeys LONGVARCHAR;

    -- 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;
    
    -- Check if the table_name is null
    if (:table_name is null) then
    	SIGNAL 'S1000', 'Table name cannot be null'; 
    end if;
    
    -- If database qualifier is null, use current database
	SET :database_qual = IFNULL(:database_qual, DATABASE());

	/* Enumerate the primary key information */
	
	SET :stmt_psp_pkeys =	' SELECT ''' +
							:database_qual +	/* TABLE_QUALIFIER */ 
							''', null, ' +		/* TABLE_OWNER */	
							' A.Xf$Name, ' +	/* TABLE_NAME */
							' B.Xe$Name, ' +	/* COLUMN_NAME */
							' C.Xi$Part, ' +	/* COLUMN_SEQUENCE */
							' D.Xe$Name	' +		/* PKEY_NAME */
							' FROM "' + :database_qual + '".X$File A, "' +
										:database_qual + '".X$Field B, "' + 
										:database_qual + '".X$Index C, "' + 
										:database_qual + '".X$Field D ' +
							' WHERE A.Xf$Name LIKE ''' + :table_name +
							''' AND A.Xf$Id = C.Xi$File AND ' +
    						' C.Xi$Flags & 16384 = 16384 AND ' + -- Check whether it is a primary key
    						' D.Xe$DataType = 227 AND ' + -- Check whether it is a index key
      						' C.Xi$Field = B.Xe$Id AND ' +
							' D.Xe$Offset = C.Xi$Number AND ' +
							' D.Xe$File = A.Xf$Id ' +
							' ORDER BY D.Xe$Name, C.Xi$Part ';

    exec (:stmt_psp_pkeys);

END; -- End of the stored procedure.       
