/*********************************************************************
 *
 * 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: SQLError.c,v 1.2 1999/12/10 01:50:33 harvey Exp $
 *
 * $Log: SQLError.c,v $
 * Revision 1.2  1999/12/10 01:50:33  harvey
 * Updated with current sources from unixODBC cvs.
 *
 * Revision 1.13  1999/11/13 23:40:59  ngorham
 *
 * Alter the way DM logging works
 * Upgrade the Postgres driver to 6.4.6
 *
 * Revision 1.12  1999/11/10 22:15:48  ngorham
 *
 * Fix some bugs with the DM and error reporting.
 *
 * Revision 1.11  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.10  1999/10/24 23:54:17  ngorham
 *
 * First part of the changes to the error reporting
 *
 * Revision 1.9  1999/10/14 06:49:24  ngorham
 *
 * Remove @all_includes@ from Drivers/MiniSQL/Makefile.am
 *
 * Revision 1.8  1999/09/21 22:34:24  ngorham
 *
 * Improve performance by removing unneeded logging calls when logging is
 * disabled
 *
 * Revision 1.7  1999/08/03 21:47:39  shandyb
 * Moving to automake: changed files in DriverManager
 *
 * Revision 1.6  1999/07/15 06:22:33  ngorham
 *
 * Fixed spelling mistake
 *
 * Revision 1.5  1999/07/14 19:46:04  ngorham
 *
 * Fix the error logging when SQLError or SQLGetDiagRec returns SQL_NO_DATA
 *
 * Revision 1.4  1999/07/12 19:42:05  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:54  ngorham
 *
 * Add initial thread safety code
 *
 * Revision 1.1.1.1  1999/05/29 13:41:06  sShandyb
 * first go at it
 *
 * Revision 1.3  1999/06/02 20:12:10  ngorham
 *
 * Fixed botched log entry, and removed the dos \r from the sql header files.
 *
 * Revision 1.2  1999/06/02 19:57:20  ngorham
 *
 * Added code to check if a attempt is being made to compile with a C++
 * Compiler, and issue a message.
 * Start work on the ODBC2-3 conversions.
 *
 * Revision 1.1.1.1  1999/05/27 18:23:17  pharvey
 * Imported sources
 *
 * Revision 1.3  1999/04/30 16:22:47  nick
 * Another checkpoint
 *
 * Revision 1.2  1999/04/29 21:40:58  nick
 * End of another night :-)
 *
 * Revision 1.1  1999/04/25 23:06:11  nick
 * Initial revision
 *
 *
 **********************************************************************/

#include "drivermanager.h"

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

static SQLRETURN extract_sql_error( EHEAD *head,
        SQLCHAR *sqlstate,
        SQLINTEGER *native_error,
        SQLCHAR *message_text,
        SQLSMALLINT buffer_length,
        SQLSMALLINT *text_length )
{
    ERROR *err;
    SQLRETURN ret;

    if ( sqlstate )
        strcpy( sqlstate, "00000" );

    if ( head -> sql_error_head.error_count < 1 )
    {
        return SQL_NO_DATA;
    }

    err = head -> sql_error_head.error_list_head;
    head -> sql_error_head.error_list_head = err -> next;

    /*
     * is it the last
     */
    if ( head -> sql_error_head.error_list_tail == err )
        head -> sql_error_head.error_list_tail = NULL;

    /*
     * not empty yet
     */
    if ( head -> sql_error_head.error_list_head )
    {
        head -> sql_error_head.error_list_head -> prev = NULL;
    }

    head -> sql_error_head.error_count --;

    if ( sqlstate )
    {
        strcpy( sqlstate, err -> sqlstate );
    }
    if ( buffer_length < strlen( err -> msg ) + 1 )
    {
        ret = SQL_SUCCESS_WITH_INFO;
    }
    else
    {
        ret = SQL_SUCCESS;
    }

    if ( message_text )
    {
        if ( ret == SQL_SUCCESS )
        {
            strcpy( message_text, err -> msg );
        }
        else
        {
            memcpy( message_text, err -> msg, buffer_length );
            message_text[ buffer_length - 1 ] = '\0';
        }
    }

    if ( text_length )
    {
        *text_length = strlen( err -> msg );
    }

	if ( native_error )
	{
		*native_error = err -> native_error;
	}

    /*
     * clean up
     */

    free( err -> msg );
    free( err );

    return ret;
}

SQLRETURN SQLError( SQLHENV environment_handle,
           SQLHDBC connection_handle,
           SQLHSTMT statement_handle,
           SQLCHAR *sqlstate,
           SQLINTEGER *native_error,
           SQLCHAR *message_text,
           SQLSMALLINT buffer_length,
           SQLSMALLINT *text_length )
{
    SQLRETURN ret;
    SQLCHAR s0[ 20 ], s1[ 100 ];

    if ( statement_handle )
    {
        DMHSTMT statement = ( DMHSTMT ) statement_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\tSQLState = %p\
                \n\t\t\tNative = %p\
                \n\t\t\tMessage Text = %p\
                \n\t\t\tBuffer Length = %d\
                \n\t\t\tText Len Ptr = %p",
                    statement,
                    sqlstate,
                    native_error,
                    message_text,
                    buffer_length,
                    text_length );

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

        ret = extract_sql_error( &statement -> error,
                sqlstate,
                native_error,
                message_text,
                buffer_length,
                text_length );

        if ( statement -> log_handle )
        {
            if ( SQL_SUCCEEDED( ret ))
            {
                sprintf( statement -> msg, 
                    "\n\t\tExit:[%s]\
                    \n\t\t\tSQLState = %s\
                    \n\t\t\tNative = %s\
                    \n\t\t\tMessage Text = %s",
                        __get_return_status( ret ),
                        sqlstate,
                        __ptr_as_string( s0, native_error ),
                        __sdata_as_string( s1, SQL_CHAR, 
                            text_length, message_text ));
            }
            else
            {
                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 ( connection_handle )
    {
        DMHDBC connection = ( DMHDBC ) connection_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\tSQLState = %p\
                \n\t\t\tNative = %p\
                \n\t\t\tMessage Text = %p\
                \n\t\t\tBuffer Length = %d\
                \n\t\t\tText Len Ptr = %p",
                    connection,
                    sqlstate,
                    native_error,
                    message_text,
                    buffer_length,
                    text_length );

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

        ret = extract_sql_error( &connection -> error,
                sqlstate,
                native_error,
                message_text,
                buffer_length,
                text_length );

        if ( connection -> log_handle )
        {
            if ( SQL_SUCCEEDED( ret ))
            {
                sprintf( connection -> msg, 
                    "\n\t\tExit:[%s]\
                    \n\t\t\tSQLState = %s\
                    \n\t\t\tNative = %s\
                    \n\t\t\tMessage Text = %s",
                        __get_return_status( ret ),
                        sqlstate,
                        __ptr_as_string( s0, native_error ),
                        __sdata_as_string( s1, SQL_CHAR, 
                            text_length, message_text ));
            }
            else
            {
                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 );
    }
    else if ( environment_handle )
    {
        DMHENV environment = ( DMHENV ) environment_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\tSQLState = %p\
                \n\t\t\tNative = %p\
                \n\t\t\tMessage Text = %p\
                \n\t\t\tBuffer Length = %d\
                \n\t\t\tText Len Ptr = %p",
                    environment,
                    sqlstate,
                    native_error,
                    message_text,
                    buffer_length,
                    text_length );

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

        ret = extract_sql_error( &environment -> error,
                sqlstate,
                native_error,
                message_text,
                buffer_length,
                text_length );

        if ( environment -> log_handle )
        {
            if ( SQL_SUCCEEDED( ret ))
            {
                sprintf( environment -> msg, 
                    "\n\t\tExit:[%s]\
                    \n\t\t\tSQLState = %s\
                    \n\t\t\tNative = %s\
                    \n\t\t\tMessage Text = %s",
                        __get_return_status( ret ),
                        sqlstate,
                        __ptr_as_string( s0, native_error ),
                        __sdata_as_string( s1, SQL_CHAR, 
                            text_length, message_text ));
            }
            else
            {
                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 );
    }
    else
    {
        return SQL_INVALID_HANDLE;
    }

    return ret;
}

