/*
 * This stored procedure is used to determine the metadata version of the
 * given database. It is not exposed to the users and is only used by some of
 * the system stored procedures.
 */
 
CREATE PROCEDURE psp_database_version (
	in :database_qual   VARCHAR(20) = DATABASE(), -- Name of the database
	out :version        INTEGER -- metadata version    
) WITH DEFAULT HANDLER    
AS
BEGIN

    -- Variable to hold the dynamic query    
    DECLARE :version_query  LONGVARCHAR;

	-- This variable stores the size of Xf$Name column.
    -- This size will be used to determine whether the database is using V1
    -- metadata or V2 metadata
	DECLARE :col_size           INTEGER;

	-- This variable stores X$Field table name concatenated with 
	-- the database qualifier in the form dbname.tablename
    DECLARE :field_table_name    VARCHAR(30);

    -- If the database qualifier is null, then use the current database
	if (:database_qual is null) then
		set :database_qual = DATABASE();
	end if;
	
    -- 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;

    SET :field_table_name = '"' + :database_qual + '".X$Field';
    
    CREATE TABLE #vt (col_size INTEGER);
    SET :version_query = 'INSERT INTO #vt SELECT Xe$Size FROM ' 
                         + :field_table_name + ' WHERE Xe$Name = ''Xf$Name'' ';
    exec(:version_query);

    if (SQLSTATE = 'S1000') then
        SIGNAL 'S1000', 'Unable to open table: X$Field';
    end if;

	SELECT col_size INTO :col_size FROM #vt;

    if (:col_size = 20) then  
        -- Metadata version is V1
        SET :version = 1;        
    else 
        if (:col_size = 128) then  
            -- Metadata version is V2
            SET :version = 2;
        end if;                     
    end if;
END; -- End of stored procedure.

