/*********************************************************************
 *
 * 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: SQLAllocHandle.c,v 1.2 1999/12/10 01:50:30 harvey Exp $
 *
 * $Log: SQLAllocHandle.c,v $
 * Revision 1.2  1999/12/10 01:50:30  harvey
 * Updated with current sources from unixODBC cvs.
 *
 * Revision 1.13  1999/12/01 09:20:07  ngorham
 *
 * Fix some threading problems
 *
 * Revision 1.12  1999/11/15 21:42:52  ngorham
 *
 * Remove some debug info
 *
 * Revision 1.11  1999/11/13 23:40:58  ngorham
 *
 * Alter the way DM logging works
 * Upgrade the Postgres driver to 6.4.6
 *
 * Revision 1.10  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.9  1999/10/24 23:54:17  ngorham
 *
 * First part of the changes to the error reporting
 *
 * Revision 1.8  1999/10/20 23:01:41  ngorham
 *
 * Fixed problem with the connection counting
 *
 * Revision 1.7  1999/09/26 18:55:03  ngorham
 *
 * Fixed a problem where the cursor lib was being used by default
 *
 * Revision 1.6  1999/09/21 22:34:23  ngorham
 *
 * Improve performance by removing unneeded logging calls when logging is
 * disabled
 *
 * Revision 1.5  1999/09/19 22:24:33  ngorham
 *
 * Added support for the cursor library
 *
 * Revision 1.4  1999/07/10 21:10:15  ngorham
 *
 * Adjust error sqlstate from driver manager, depending on requested
 * version (ODBC2/3)
 *
 * Revision 1.3  1999/07/04 21:05:06  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:05  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.4  1999/05/09 23:27:11  nick
 * All the API done now
 *
 * 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:02:41  nick
 * Initial revision
 *
 *
 **********************************************************************/

#include "drivermanager.h"

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

/*
 * this is used so that it can be called without falling
 * fowl of any other instances in any other modules.
 */
SQLRETURN __SQLAllocHandle( SQLSMALLINT handle_type,
           SQLHANDLE input_handle,
           SQLHANDLE *output_handle,
           SQLINTEGER requested_version )
{
    if ( input_handle )
        function_entry(( void * ) input_handle );

    switch( handle_type )
    {
      case SQL_HANDLE_ENV:
        {
            DMHENV environment;

            if ( !output_handle )
                return SQL_ERROR;

            if ( !( environment = __alloc_env()))
            {
                *output_handle = SQL_NULL_HENV;
                return SQL_ERROR;
            }
            *output_handle = (SQLHANDLE) environment;

            /*
             * setup environment state
             */

            environment -> state = STATE_E1;
            environment -> requested_version = requested_version;

            /*
             * if SQLAllocEnv is called then it's probable that
             * the application wants ODBC2.X type behaviour
             *
             * In this case we don't need to set the version via
             * SQLSetEnvAttr()
             *
             */

            environment -> connection_count = 0;

            return SQL_SUCCESS;
        }
        break;

      case SQL_HANDLE_DBC:
        {
            DMHENV environment = (DMHENV) input_handle;
            DMHDBC connection;
            SQLCHAR s0[ 20 ];

            if ( output_handle )
                *output_handle = SQL_NULL_HDBC;

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

            thread_protect( SQL_HANDLE_ENV, environment );

            if ( environment -> log_handle )
            { 
                /*
                 * log that we are here
                 */

                sprintf( environment -> msg, 
                        "\n\t\tEntry:\n\t\t\tHandle Type = %d\n\t\t\tInput Handle = %p",
                        handle_type,
                        (void*)input_handle );

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

            if ( !output_handle )
            {
                dm_log_write( environment->log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: HY009" );

                __post_internal_error( &environment -> error,
                        ERROR_HY009, NULL, 
                        SQL_OV_ODBC3 );

                thread_release( SQL_HANDLE_ENV, environment );

                return function_return( environment, SQL_ERROR );
            }

            /*
             * check that a version has been requested
             */

            if ( environment -> requested_version == 0 )
            {
                dm_log_write( environment->log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: HY010" );

                __post_internal_error( &environment -> error,
                        ERROR_HY010, NULL,
                        SQL_OV_ODBC3 );

                thread_release( SQL_HANDLE_ENV, environment );

                return function_return( environment, SQL_ERROR );
            }

            connection = __alloc_dbc();
            if ( !connection )
            {
                dm_log_write( environment -> log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: HY013" );

                __post_internal_error( &environment -> error,
                    ERROR_HY013, NULL,
                    environment -> requested_version );

                thread_release( SQL_HANDLE_ENV, environment );

                return function_return( environment, SQL_ERROR );
            }
            else
            {
                connection -> log_handle = environment -> log_handle; 
            }

            /*
             * sort out the states
             */

            connection -> state = STATE_C2;
            if ( environment -> state == STATE_E1 )
            {
                environment -> state = STATE_E2;
            }
            environment -> connection_count ++;
            connection -> environment = environment;

            connection -> cursors = SQL_CUR_DEFAULT;

            *output_handle = (SQLHANDLE) connection;

            if ( environment -> log_handle )
            {
                sprintf( environment -> msg, 
                        "\n\t\tExit:[SQL_SUCCESS]\n\t\t\tOutput Handle = %p",
                        connection );

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

            thread_release( SQL_HANDLE_ENV, environment );
            return SQL_SUCCESS;
        }
        break;

      case SQL_HANDLE_STMT:
        {
            SQLRETURN ret;
            DMHDBC connection = (DMHDBC) input_handle;
            DMHSTMT statement;
            SQLCHAR s0[ 20 ];

            if ( output_handle )
                *output_handle = SQL_NULL_HSTMT;

            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\tHandle Type = %d\n\t\t\tInput Handle = %p",
                    handle_type,
                    (void*)input_handle );

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

            if ( connection -> state == STATE_C1 ||
                    connection -> state == STATE_C2 ||
                    connection -> state == STATE_C3 )
            {
                dm_log_write( connection -> log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: 08003" );

                __post_internal_error( &statement -> error,
                        ERROR_08003, NULL,
                        connection -> environment -> requested_version );

                thread_release( SQL_HANDLE_DBC, connection );

                return function_return( connection, SQL_ERROR );
            }

            statement = __alloc_stmt();
            if ( !statement )
            {
                dm_log_write( connection -> log_handle, 
                        __get_pid( s0 ), 
                        __FILE__, 
                        __LINE__, 
                        LOG_INFO, 
                        LOG_INFO, 
                        "Error: HY013" );

                __post_internal_error( &statement -> error,
                        ERROR_HY013, NULL,
                        connection -> environment -> requested_version );

                thread_release( SQL_HANDLE_DBC, connection );

                return function_return( connection, SQL_ERROR );
            }
            else
            {
                statement -> log_handle = connection -> log_handle; 
            }

            /*
             * pass the call on
             */

            if ( requested_version == SQL_OV_ODBC3 )
            {
                if ( CHECK_SQLALLOCHANDLE( connection ))
                {
                    ret = SQLALLOCHANDLE( connection,
                            SQL_HANDLE_STMT,
                            connection -> driver_dbc,
                            &statement -> driver_stmt,
                            statement );

                    if ( !SQL_SUCCEEDED( ret ))
                        __release_stmt( statement );
                }
                else if ( CHECK_SQLALLOCSTMT( connection ))
                {
                    ret = SQLALLOCSTMT( connection,
                            connection -> driver_dbc,
                            &statement -> driver_stmt,
                            statement );

                    if ( !SQL_SUCCEEDED( ret ))
                        __release_stmt( statement );
                }
                else
                {
                    dm_log_write( connection -> log_handle, 
                            __get_pid( s0 ), 
                            __FILE__, 
                            __LINE__, 
                            LOG_INFO, 
                            LOG_INFO, 
                            "Error: IM003" );

                    __post_internal_error( &statement -> error,
                            ERROR_IM003, NULL,
                            connection -> environment -> requested_version );

                    __release_stmt( statement );

                    thread_release( SQL_HANDLE_DBC, connection );

                    return function_return( connection, SQL_ERROR );
                }
            }
            else
            {
                if ( CHECK_SQLALLOCSTMT( connection ))
                {
                    ret = SQLALLOCSTMT( connection,
                            connection -> driver_dbc,
                            &statement -> driver_stmt,
                            statement );

                    if ( !SQL_SUCCEEDED( ret ))
                        __release_stmt( statement );
                }
                else if ( CHECK_SQLALLOCHANDLE( connection ))
                {
                    ret = SQLALLOCHANDLE( connection,
                            SQL_HANDLE_STMT,
                            connection -> driver_dbc,
                            &statement -> driver_stmt,
                            statement );

                    if ( !SQL_SUCCEEDED( ret ))
                        __release_stmt( statement );
                }
                else
                {
                    dm_log_write( connection -> log_handle, 
                            __get_pid( s0 ), 
                            __FILE__, 
                            __LINE__, 
                            LOG_INFO, 
                            LOG_INFO, 
                            "Error: IM003" );

                    __post_internal_error( &statement -> error,
                            ERROR_IM003, NULL,
                            connection -> environment -> requested_version );

                    __release_stmt( statement );

                    thread_release( SQL_HANDLE_DBC, connection );

                    return function_return( connection, SQL_ERROR );
                }
            }

            if ( SQL_SUCCEEDED( ret ))
            {
                /*
                 * sort out the states
                 */

                statement -> state = STATE_S1;
                if ( connection -> state == STATE_C4 )
                    connection -> state = STATE_C5;

                connection -> statement_count ++;

                statement -> connection = connection;

                *output_handle = (SQLHANDLE) statement;

                /*
                 * if we are connected to a 3 driver then
                 * we need to get the 4 implicit descriptors
                 * so we know that they are valid
                 */

                if ( connection -> driver_act_ver == 3 &&
                        CHECK_SQLGETSTMTATTR( connection ))
                {
                    SQLHDESC desc;

                    /*
                     * ARD
                     */

                    ret = SQLGETSTMTATTR( connection,
                            statement -> driver_stmt,
                            SQL_ATTR_APP_ROW_DESC,
                            &desc,
                            sizeof( desc ),
                            NULL );

                    if ( SQL_SUCCEEDED( ret ))
                    {
                        /*
                         * allocate one of our descriptors
                         * to wrap around this
                         */
                        statement -> ard = __alloc_desc();
                        if ( !statement -> ard )
                        {
                            dm_log_write( connection -> log_handle, 
                                __get_pid( s0 ), 
                                __FILE__, 
                                __LINE__, 
                                LOG_INFO, 
                                LOG_INFO, 
                                "Error: HY013" );

                            __post_internal_error( &statement -> error,
                                    ERROR_HY013, NULL,
                                    connection -> environment -> requested_version );

                            thread_release( SQL_HANDLE_DBC, connection );

                            return function_return( connection, SQL_ERROR );
                        }
                        else
                        {
                            statement -> ard -> log_handle = 
                                statement -> log_handle;
                        }
                        statement -> implicit_ard = statement -> ard;
                        statement -> ard -> implicit = 1;
                        statement -> ard -> state = STATE_D1i;
                        statement -> ard -> driver_desc = desc;
                        statement -> ard -> connection = connection;
                    }

                    /*
                     * APD
                     */

                    ret = SQLGETSTMTATTR( connection,
                            statement -> driver_stmt,
                            SQL_ATTR_APP_PARAM_DESC,
                            &desc,
                            sizeof( desc ),
                            NULL );

                    if ( SQL_SUCCEEDED( ret ))
                    {
                        /*
                         * allocate one of our descriptors
                         * to wrap around this
                         */
                        statement -> apd = __alloc_desc();
                        if ( !statement -> ard )
                        {
                            dm_log_write( connection -> log_handle, 
                                __get_pid( s0 ), 
                                __FILE__, 
                                __LINE__, 
                                LOG_INFO, 
                                LOG_INFO, 
                                "Error: HY013" );

                            __post_internal_error( &statement -> error,
                                    ERROR_HY013, NULL,
                                    connection -> environment -> requested_version );

                            thread_release( SQL_HANDLE_DBC, connection );

                            return function_return( connection, SQL_ERROR );
                        }
                        else
                        {
                            statement -> apd -> log_handle = 
                                statement -> log_handle;
                        }
                        statement -> implicit_apd = statement -> apd;
                        statement -> apd -> implicit = 1;
                        statement -> apd -> state = STATE_D1i;
                        statement -> apd -> driver_desc = desc;
                        statement -> apd -> connection = connection;
                    }

                    /*
                     * IRD
                     */

                    ret = SQLGETSTMTATTR( connection,
                            statement -> driver_stmt,
                            SQL_ATTR_IMP_ROW_DESC,
                            &desc,
                            sizeof( desc ),
                            NULL );

                    if ( SQL_SUCCEEDED( ret ))
                    {
                        /*
                         * allocate one of our descriptors
                         * to wrap around this
                         */
                        statement -> ird = __alloc_desc();
                        if ( !statement -> ird )
                        {
                            dm_log_write( connection -> log_handle, 
                                __get_pid( s0 ), 
                                __FILE__, 
                                __LINE__, 
                                LOG_INFO, 
                                LOG_INFO, 
                                "Error: HY013" );

                            __post_internal_error( &statement -> error,
                                    ERROR_HY013, NULL, 
                                    connection -> environment -> requested_version );

                            thread_release( SQL_HANDLE_DBC, connection );

                            return function_return( connection, SQL_ERROR );
                        }
                        else
                        {
                            statement -> ird -> log_handle = 
                                statement -> log_handle;
                        }
                        statement -> implicit_ird = statement -> ird;
                        statement -> ird -> implicit = 1;
                        statement -> ird -> state = STATE_D1i;
                        statement -> ird -> driver_desc = desc;
                        statement -> ird -> connection = connection;
                    }

                    /*
                     * IPD
                     */

                    ret = SQLGETSTMTATTR( connection,
                            statement -> driver_stmt,
                            SQL_ATTR_IMP_PARAM_DESC,
                            &desc,
                            sizeof( desc ),
                            NULL );

                    if ( SQL_SUCCEEDED( ret ))
                    {
                        /*
                         * allocate one of our descriptors
                         * to wrap around this
                         */
                        statement -> ipd = __alloc_desc();
                        if ( !statement -> ipd )
                        {
                            dm_log_write( connection -> log_handle, 
                                __get_pid( s0 ), 
                                __FILE__, 
                                __LINE__, 
                                LOG_INFO, 
                                LOG_INFO, 
                                "Error: HY013" );

                            __post_internal_error( &statement -> error,
                                    ERROR_HY013, NULL,
                                    connection -> environment -> requested_version );

                            thread_release( SQL_HANDLE_DBC, connection );

                            return function_return( connection, SQL_ERROR );
                        }
                        else
                        {
                            statement -> ipd -> log_handle = 
                                statement -> log_handle;
                        }
                        statement -> implicit_ipd = statement -> ipd;
                        statement -> ipd -> implicit = 1;
                        statement -> ipd -> state = STATE_D1i;
                        statement -> ipd -> driver_desc = desc;
                        statement -> ipd -> connection = connection;
                    }
                }
            }

            if ( connection -> log_handle )
            {
                sprintf( connection -> msg, 
                        "\n\t\tExit:[SQL_SUCCESS]\n\t\t\tOutput Handle = %p",
                        statement );

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

            thread_release( SQL_HANDLE_DBC, connection );

            return function_return( connection, ret );
        }
        break;

      case SQL_HANDLE_DESC:
        {
            printf( "alloc %d\n", handle_type );
            return SQL_ERROR;
        }
        break;

      default:
        return SQL_ERROR;
        break;
    }
}

SQLRETURN SQLAllocHandle( SQLSMALLINT handle_type,
           SQLHANDLE input_handle,
           SQLHANDLE *output_handle )
{
    /*
     * setting a requested version to 0
     * indicates that we are ODBC3 and the application must
     * select ODBC2 or 3 explicitly
     */

    return __SQLAllocHandle( handle_type,
            input_handle,
            output_handle,
            0 );
}
