/*********************************************************************
 *
 * This is based on code created by Peter Harvey,
 * (pharvey@codebydesign.com).
 *
 * Modified and extended by Nick Gorham
 * (nick@easysoft.com).
 *
 * Any bugs or problems should be considered the fault of Nick and not
 * Peter.
 *
 * copyright (c) 1999 Nick Gorham
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 **********************************************************************
 *
 * $Id: SQLGetDiagField.c,v 1.2 1999/12/10 01:50:35 harvey Exp $
 *
 * $Log: SQLGetDiagField.c,v $
 * Revision 1.2  1999/12/10 01:50:35  harvey
 * Updated with current sources from unixODBC cvs.
 *
 * Revision 1.8  1999/11/17 21:08:58  ngorham
 *
 * Fix Bug with the ODBC 3 error handling
 *
 * Revision 1.7  1999/11/13 23:40:59  ngorham
 *
 * Alter the way DM logging works
 * Upgrade the Postgres driver to 6.4.6
 *
 * Revision 1.6  1999/11/10 03:51:33  ngorham
 *
 * Update the error reporting in the DM to enable ODBC 3 and 2 calls to
 * work at the same time
 *
 * Revision 1.5  1999/09/21 22:34:25  ngorham
 *
 * Improve performance by removing unneeded logging calls when logging is
 * disabled
 *
 * Revision 1.4  1999/07/12 19:42:06  ngorham
 *
 * Finished off SQLGetDiagField.c and fixed a but that caused SQLError to
 * fail with Perl and PHP, connect errors were not being returned because
 * I was checking to the environment being set, they were setting the
 * statement and the environment. The order of checking has been changed.
 *
 * Revision 1.3  1999/07/04 21:05:07  ngorham
 *
 * Add LGPL Headers to code
 *
 * Revision 1.2  1999/06/30 23:56:55  ngorham
 *
 * Add initial thread safety code
 *
 * Revision 1.1.1.1  1999/05/29 13:41:07  sShandyb
 * first go at it
 *
 * Revision 1.1.1.1  1999/05/27 18:23:17  pharvey
 * Imported sources
 *
 * Revision 1.5  1999/05/09 23:27:11  nick
 * All the API done now
 *
 * Revision 1.4  1999/05/04 22:41:12  nick
 * and another night ends
 *
 * Revision 1.3  1999/05/03 19:50:43  nick
 * Another check point
 *
 * Revision 1.2  1999/04/30 16:22:47  nick
 * Another checkpoint
 *
 * Revision 1.1  1999/04/25 23:06:11  nick
 * Initial revision
 *
 *
 **********************************************************************/

#include "drivermanager.h"

static char const rcsid[]= "$RCSfile: SQLGetDiagField.c,v $ $Revision: 1.2 $";

static SQLRETURN extract_sql_error_field( EHEAD *head,
                SQLSMALLINT rec_number,
                SQLSMALLINT diag_identifier,
                SQLPOINTER diag_info_ptr,
                SQLSMALLINT buffer_length,
                SQLSMALLINT *string_length_ptr )
{
    ERROR *ptr;

    /*
     * check the header fields first
     */

    switch( diag_identifier )
    {
      case SQL_DIAG_CURSOR_ROW_COUNT:
      case SQL_DIAG_ROW_COUNT:
        {
            SQLINTEGER val;
            SQLRETURN ret;

            if ( head -> handle_type != SQL_HANDLE_STMT )
            {
                return SQL_ERROR;
            }
            if ( CHECK_SQLGETDIAGFIELD( __get_connection( head )))
            {
                ret = SQLGETDIAGFIELD( __get_connection( head ),
                        SQL_HANDLE_STMT,
                        __get_driver_handle( head ),
                        0,
                        diag_identifier,
                        diag_info_ptr,
                        buffer_length,
                        string_length_ptr );

                return ret;
            }
            else if ( CHECK_SQLROWCOUNT( __get_connection( head )))
            {
                ret = SQLROWCOUNT( __get_connection( head ),
                    __get_driver_handle( head ),
                    &val );

                if ( !SQL_SUCCEEDED( ret ))
                {
                    return ret;
                }
            }
            else
            {
                val = 0;
            }

            if ( diag_info_ptr )
            {
                memcpy( diag_info_ptr, &val, sizeof( val ));
            }
        }
        return SQL_SUCCESS;

      case SQL_DIAG_DYNAMIC_FUNCTION:
        {
            SQLRETURN ret;

            if ( head -> handle_type != SQL_HANDLE_STMT )
            {
                return SQL_ERROR;
            }
            if ( CHECK_SQLGETDIAGFIELD( __get_connection( head )))
            {
                ret = SQLGETDIAGFIELD( __get_connection( head ),
                        SQL_HANDLE_STMT,
                        __get_driver_handle( head ),
                        0,
                        diag_identifier,
                        diag_info_ptr,
                        buffer_length,
                        string_length_ptr );

                return ret;
            }
            if ( diag_info_ptr )
            {
                strcpy( diag_info_ptr, "" );
            }
        }
        return SQL_SUCCESS;

      case SQL_DIAG_DYNAMIC_FUNCTION_CODE:
        {
            SQLINTEGER val;
            SQLRETURN ret;

            if ( head -> handle_type != SQL_HANDLE_STMT )
            {
                return SQL_ERROR;
            }
            if ( CHECK_SQLGETDIAGFIELD( __get_connection( head )))
            {
                ret = SQLGETDIAGFIELD( __get_connection( head ),
                        SQL_HANDLE_STMT,
                        __get_driver_handle( head ),
                        0,
                        diag_identifier,
                        diag_info_ptr,
                        buffer_length,
                        string_length_ptr );

                return ret;
            }
            else
            {
                val = SQL_DIAG_UNKNOWN_STATEMENT;
            }

            if ( diag_info_ptr )
            {
                memcpy( diag_info_ptr, &val, sizeof( val ));
            }
        }
        return SQL_SUCCESS;

      case SQL_DIAG_NUMBER:
        {
            SQLINTEGER val;
            
            val = head -> sql_diag_head.internal_count + 
                head -> sql_diag_head.error_count;

            if ( diag_info_ptr )
            {
                memcpy( diag_info_ptr, &val, sizeof( val ));
            }
        }
        return SQL_SUCCESS;

      case SQL_DIAG_RETURNCODE:
        {
            if ( diag_info_ptr )
            {
                memcpy( diag_info_ptr, &head -> return_code, 
                        sizeof( head -> return_code ));
            }
        }
        return SQL_SUCCESS;
    }

    /*
     * else check the records
     */

    if ( rec_number < 1 )
    {
        return SQL_ERROR;
    }

    if ( rec_number <= head -> sql_diag_head.internal_count )
    {
        /*
         * local errors
         */

        ptr = head -> sql_diag_head.internal_list_head;
        while( rec_number > 1 )
        {
            ptr = ptr -> next;
            rec_number --;
        }
    }
    else if ( rec_number <= head -> sql_diag_head.internal_count + 
            head -> sql_diag_head.error_count )
    {
        rec_number -= head -> sql_diag_head.internal_count;

        if ( CHECK_SQLGETDIAGFIELD( __get_connection( head )))
        {
            return SQLGETDIAGFIELD( __get_connection( head ),
                    head -> handle_type,
                    __get_driver_handle( head ),
                    rec_number,
                    diag_identifier,
                    diag_info_ptr,
                    buffer_length,
                    string_length_ptr );
        }
        else
        {
            ptr = head -> sql_diag_head.error_list_head;
            while( rec_number > 1 )
            {
                ptr = ptr -> next;
                rec_number --;
            }
        }
    }
    else
    {
        return SQL_NO_DATA;
    }

    /*
     * if we are here ptr should point to the error
     * record
     */

    switch( diag_identifier )
    {
      case SQL_DIAG_CLASS_ORIGIN:
        {
            char *str;
            int ret = SQL_SUCCESS;

            if ( strncmp( ptr -> sqlstate, "IM", 2 ) == 0 )
            {
                str = "ISO 9075";
            }
            else
            {
                str = "ODBC 3.0";
            }

            if ( diag_info_ptr )
            {
                if ( buffer_length >= strlen( str ) + 1 )
                {
                    strcpy( diag_info_ptr, str );
                }
                else
                {
                    ret = SQL_SUCCESS_WITH_INFO;
                    memcpy( diag_info_ptr, str, buffer_length - 1 );
                    (( char * ) diag_info_ptr )[ buffer_length ] = '\0';
                }
            }
            if ( string_length_ptr )
            {
                *string_length_ptr = strlen( str );
            }
            return ret;
        }
        break;

      case SQL_DIAG_COLUMN_NUMBER:
        {
            SQLINTEGER val = SQL_COLUMN_NUMBER_UNKNOWN;

            if ( diag_info_ptr )
            {
                memcpy( diag_info_ptr, &val, sizeof( val ));
            }
            return SQL_SUCCESS;
        }
        break;

      case SQL_DIAG_CONNECTION_NAME:
        {
            char *str;
            int ret = SQL_SUCCESS;

            str = "";

            if ( diag_info_ptr )
            {
                if ( buffer_length >= strlen( str ) + 1 )
                {
                    strcpy( diag_info_ptr, str );
                }
                else
                {
                    ret = SQL_SUCCESS_WITH_INFO;
                    memcpy( diag_info_ptr, str, buffer_length - 1 );
                    (( char * ) diag_info_ptr )[ buffer_length ] = '\0';
                }
            }
            if ( string_length_ptr )
            {
                *string_length_ptr = strlen( str );
            }
            return ret;
        }
        break;

      case SQL_DIAG_MESSAGE_TEXT:
        {
            char *str;
            int ret = SQL_SUCCESS;

            str = ptr -> msg;

            if ( diag_info_ptr )
            {
                if ( buffer_length >= strlen( str ) + 1 )
                {
                    strcpy( diag_info_ptr, str );
                }
                else
                {
                    ret = SQL_SUCCESS_WITH_INFO;
                    memcpy( diag_info_ptr, str, buffer_length - 1 );
                    (( char * ) diag_info_ptr )[ buffer_length ] = '\0';
                }
            }
            if ( string_length_ptr )
            {
                *string_length_ptr = strlen( str );
            }
            return ret;
        }
        break;

      case SQL_DIAG_NATIVE:
        {
            SQLINTEGER val = ptr -> native_error;

            if ( diag_info_ptr )
            {
                memcpy( diag_info_ptr, &val, sizeof( val ));
            }
            return SQL_SUCCESS;
        }
        break;

      case SQL_DIAG_ROW_NUMBER:
        {
            SQLINTEGER val = SQL_ROW_NUMBER_UNKNOWN;

            if ( diag_info_ptr )
            {
                memcpy( diag_info_ptr, &val, sizeof( val ));
            }
            return SQL_SUCCESS;
        }
        break;

      case SQL_DIAG_SERVER_NAME:
        {
            char *str;
            int ret = SQL_SUCCESS;

            str = "";

            if ( diag_info_ptr )
            {
                if ( buffer_length >= strlen( str ) + 1 )
                {
                    strcpy( diag_info_ptr, str );
                }
                else
                {
                    ret = SQL_SUCCESS_WITH_INFO;
                    memcpy( diag_info_ptr, str, buffer_length - 1 );
                    (( char * ) diag_info_ptr )[ buffer_length ] = '\0';
                }
            }
            if ( string_length_ptr )
            {
                *string_length_ptr = strlen( str );
            }
            return ret;
        }
        break;

      case SQL_DIAG_SQLSTATE:
        {
            char *str;
            int ret = SQL_SUCCESS;

            str = ptr -> sqlstate;

            if ( diag_info_ptr )
            {
                if ( buffer_length >= strlen( str ) + 1 )
                {
                    strcpy( diag_info_ptr, str );
                }
                else
                {
                    ret = SQL_SUCCESS_WITH_INFO;
                    memcpy( diag_info_ptr, str, buffer_length - 1 );
                    (( char * ) diag_info_ptr )[ buffer_length ] = '\0';
                }
            }
            if ( string_length_ptr )
            {
                *string_length_ptr = strlen( str );
            }
            return ret;
        }
        break;

      case SQL_DIAG_SUBCLASS_ORIGIN:
        {
            char *str;
            int ret = SQL_SUCCESS;

            str = "";

            if ( diag_info_ptr )
            {
                if ( buffer_length >= strlen( str ) + 1 )
                {
                    strcpy( diag_info_ptr, str );
                }
                else
                {
                    ret = SQL_SUCCESS_WITH_INFO;
                    memcpy( diag_info_ptr, str, buffer_length - 1 );
                    (( char * ) diag_info_ptr )[ buffer_length ] = '\0';
                }
            }
            if ( string_length_ptr )
            {
                *string_length_ptr = strlen( str );
            }
            return ret;
        }
        break;
    }

    return SQL_SUCCESS;
}

SQLRETURN SQLGetDiagField( SQLSMALLINT handle_type,
        SQLHANDLE handle,
        SQLSMALLINT rec_number,
        SQLSMALLINT diag_identifier,
        SQLPOINTER diag_info_ptr,
        SQLSMALLINT buffer_length,
        SQLSMALLINT *string_length_ptr )
{
    SQLRETURN ret;
    SQLCHAR s0[ 20 ], s1[ 100 ];

    if ( handle_type == SQL_HANDLE_ENV )
    {
        DMHENV environment = ( DMHENV ) handle;

        if ( !__validate_env( environment ))
        {
            return SQL_INVALID_HANDLE;
        }

        thread_protect( SQL_HANDLE_ENV, environment );

        if ( environment -> log_handle )
        {
            sprintf( environment -> msg, 
                "\n\t\tEntry:\
                \n\t\t\tEnvironment = %p\
                \n\t\t\tRec Number = %d\
                \n\t\t\tDiag Ident = %p\
                \n\t\t\tDiag Info Ptr = %p\
                \n\t\t\tBuffer Length = %d\
                \n\t\t\tString Len Ptr = %p",
                    environment,
                    rec_number,
                    diag_identifier,
                    diag_info_ptr,
                    buffer_length,
                    string_length_ptr );

            dm_log_write( environment -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    environment -> msg );
        }

        ret = extract_sql_error_field( &environment -> error,
                rec_number,
                diag_identifier,
                diag_info_ptr,
                buffer_length,
                string_length_ptr );

        if ( environment -> log_handle )
        {
            sprintf( environment -> msg, 
                    "\n\t\tExit:[%s]",
                        __get_return_status( ret ));

            dm_log_write( environment -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    environment -> msg );
        }

        thread_release( SQL_HANDLE_ENV, environment );

        return ret;
    }
    else if ( handle_type == SQL_HANDLE_DBC )
    {
        DMHDBC connection = ( DMHDBC ) handle;

        if ( !__validate_dbc( connection ))
        {
            return SQL_INVALID_HANDLE;
        }

        thread_protect( SQL_HANDLE_DBC, connection );

        if ( connection -> log_handle )
        {
            sprintf( connection -> msg, 
                "\n\t\tEntry:\
                \n\t\t\tConnection = %p\
                \n\t\t\tRec Number = %d\
                \n\t\t\tDiag Ident = %p\
                \n\t\t\tDiag Info Ptr = %p\
                \n\t\t\tBuffer Length = %d\
                \n\t\t\tString Len Ptr = %p",
                    connection,
                    rec_number,
                    diag_identifier,
                    diag_info_ptr,
                    buffer_length,
                    string_length_ptr );

            dm_log_write( connection -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    connection -> msg );
        }

        ret = extract_sql_error_field( &connection -> error,
                rec_number,
                diag_identifier,
                diag_info_ptr,
                buffer_length,
                string_length_ptr );

        if ( connection -> log_handle )
        {
            sprintf( connection -> msg, 
                    "\n\t\tExit:[%s]",
                        __get_return_status( ret ));

            dm_log_write( connection -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    connection -> msg );
        }

        thread_release( SQL_HANDLE_DBC, connection );

        return ret;
    }
    else if ( handle_type == SQL_HANDLE_STMT )
    {
        DMHSTMT statement = ( DMHSTMT ) handle;

        if ( !__validate_stmt( statement ))
        {
            return SQL_INVALID_HANDLE;
        }

        thread_protect( SQL_HANDLE_STMT, statement );

        if ( statement -> log_handle )
        {
            sprintf( statement -> msg, 
                "\n\t\tEntry:\
                \n\t\t\tStatement = %p\
                \n\t\t\tRec Number = %d\
                \n\t\t\tDiag Ident = %p\
                \n\t\t\tDiag Info Ptr = %p\
                \n\t\t\tBuffer Length = %d\
                \n\t\t\tString Len Ptr = %p",
                    statement,
                    rec_number,
                    diag_identifier,
                    diag_info_ptr,
                    buffer_length,
                    string_length_ptr );

            dm_log_write( statement -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    statement -> msg );
        }

        ret = extract_sql_error_field( &statement -> error,
                rec_number,
                diag_identifier,
                diag_info_ptr,
                buffer_length,
                string_length_ptr );

        if ( statement -> log_handle )
        {
            sprintf( statement -> msg, 
                    "\n\t\tExit:[%s]",
                        __get_return_status( ret ));

            dm_log_write( statement -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    statement -> msg );
        }

        thread_release( SQL_HANDLE_STMT, statement );

        return ret;
    }
    else if ( handle_type == SQL_HANDLE_DESC )
    {
        DMHDESC descriptor = ( DMHDESC ) handle;

        if ( !__validate_desc( descriptor ))
        {
            return SQL_INVALID_HANDLE;
        }

        thread_protect( SQL_HANDLE_DESC, descriptor );

        if ( descriptor -> log_handle )
        {
            sprintf( descriptor -> msg, 
                "\n\t\tEntry:\
                \n\t\t\tDescriptor = %p\
                \n\t\t\tRec Number = %d\
                \n\t\t\tDiag Ident = %p\
                \n\t\t\tDiag Info Ptr = %p\
                \n\t\t\tBuffer Length = %d\
                \n\t\t\tString Len Ptr = %p",
                    descriptor,
                    rec_number,
                    diag_identifier,
                    diag_info_ptr,
                    buffer_length,
                    string_length_ptr );

            dm_log_write( descriptor -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    descriptor -> msg );
        }

        ret = extract_sql_error_field( &descriptor -> error,
                rec_number,
                diag_identifier,
                diag_info_ptr,
                buffer_length,
                string_length_ptr );

        if ( descriptor -> log_handle )
        {
            sprintf( descriptor -> msg, 
                    "\n\t\tExit:[%s]",
                        __get_return_status( ret ));

            dm_log_write( descriptor -> log_handle, 
                    __get_pid( s0 ), 
                    __FILE__, 
                    __LINE__, 
                    LOG_INFO, 
                    LOG_INFO, 
                    descriptor -> msg );
        }

        thread_release( SQL_HANDLE_DESC, descriptor );

        return ret;
    }
    return SQL_NO_DATA;
}

