/**
*   @brief read data from sybase ASE server TBL_DataUpdateFlag
*
*   @return
*/
int CSybClient::read_DataUpdateFlag(int connId, char* tablename, int flagid, stDataUpdateTime* pData)
{
    CS_CONNECTION *connection = getConnection(connId);
    if(NULL == connection || NULL == tablename) return -1;

    CLEAR_ALL_MESSAGE(connection);

	CS_RETCODE	retcode;
	CS_COMMAND	*cmd;
	CS_INT		res_type;	/* result type from ct_results */

    CS_INT      row_count = 0;

	/*
	** Use the dbname database
	*/
	//CS_CHAR usetable[64] = {0};
    //sprintf(usetable, "use %s\n", dbname);
	//if(execNoReplyCmd(connection, usetable) < 0)
	//{
    //    return -1;
    //}

	/*
	** Allocate a command handle to send the query with
	*/
    if ((retcode = ct_cmd_alloc(connection, &cmd)) != CS_SUCCEED)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        return -1;
    }

	/*
	** Define a language command.
	*/
	CS_CHAR select[256] = {0};
    sprintf(select, "select UpdateTime, UpdateFlag from %s where UpdateIndex=%d", tablename, flagid);
	retcode = ct_command(cmd, CS_LANG_CMD, select, CS_NULLTERM, CS_UNUSED);
	if (retcode != CS_SUCCEED)
	{
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        ct_cancel(NULL, cmd, CS_CANCEL_ALL);
        ct_cmd_drop(cmd);
        return -1;
	}

	/*
	** Send the command to the server
	*/
	if (ct_send(cmd) != CS_SUCCEED)
	{
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        ct_cancel(NULL, cmd, CS_CANCEL_ALL);
        ct_cmd_drop(cmd);
        return -1;
	}

	/*
	** Process the results.  Loop while ct_results() returns CS_SUCCEED.
	*/
	while ((retcode = ct_results(cmd, &res_type)) == CS_SUCCEED)
	{
		switch ((int)res_type)
		{
		case CS_CMD_SUCCEED:
			/*
			** This means no rows were returned.
			*/
			break;

		case CS_CMD_DONE:
			/*
			** This means we're done with one result set.
			*/
   			break;

		case CS_CMD_FAIL:
			/*
			** This means that the server encountered an error
			** while processing our command.
			*/
            DIAG_CLIENT_MESSAGE(connection);
            DIAG_SERVER_MESSAGE(connection);
            ct_cancel(NULL, cmd, CS_CANCEL_ALL);
            ct_cmd_drop(cmd);
            return -1;

		case CS_ROW_RESULT:
            {
                #define FIELD_UpdateTime 1 //ÒÔselect Óï¾äΪ׼
                #define FIELD_UpdateFlag 2
                CS_DATETIME updateTime;
                CS_TINYINT  updateFlag;

                CS_INT          i;
                CS_INT          rows_read;
                CS_DATAFMT      dfmt;

                /*
                ** Bind to column
                */
                dfmt.datatype  = CS_DATETIME_TYPE;
                dfmt.maxlength = CS_SIZEOF(CS_DATETIME);
                dfmt.format    = CS_FMT_UNUSED;
                dfmt.count     = 0;
                dfmt.locale    = NULL;

                retcode = ct_bind(cmd, FIELD_UpdateTime, &dfmt, &updateTime, NULL, NULL);
                if (retcode != CS_SUCCEED)
                {
                    DIAG_CLIENT_MESSAGE(connection);
                    DIAG_SERVER_MESSAGE(connection);
                    ct_cmd_drop(cmd);
                    return -1;
                }
                //
                dfmt.datatype = CS_TINYINT_TYPE;
                dfmt.maxlength= CS_SIZEOF(CS_TINYINT);
                retcode = ct_bind(cmd, FIELD_UpdateFlag, &dfmt, &updateFlag, NULL, NULL);
                if (retcode != CS_SUCCEED)
                {
                    DIAG_CLIENT_MESSAGE(connection);
                    DIAG_SERVER_MESSAGE(connection);
                    ct_cmd_drop(cmd);
                    return -1;
                }

                CS_DATEREC userdatetime;
                /*
                ** Fetch the rows.  Loop while ct_fetch() returns CS_SUCCEED or
                ** CS_ROW_FAIL
                */
                while (((retcode = ct_fetch(cmd, CS_UNUSED, CS_UNUSED, CS_UNUSED, &rows_read)) == CS_SUCCEED) ||
                       (retcode == CS_ROW_FAIL))
                {
                    /*
                    ** Increment our row count by the number of rows just fetched.
                    */
                    row_count = row_count + rows_read;

                    /*
                    ** Check if we hit a recoverable error.
                    */
                    if (retcode == CS_ROW_FAIL)
                    {
                    }

                    /*
                    ** We have a row. Loop through the columns displaying the
                    ** column values.
                    */
                    //printf("%ld rows read from TBL_DataUpdateFlag\n", (long)rows_read);
                    for (i = 0; i < rows_read; i++)
                    {
                        if(cs_dt_crack(context, CS_DATETIME_TYPE, &updateTime, &userdatetime) == CS_SUCCEED)
                        {
                            sprintf(pData->UpdateTime, "%04d-%02d-%02d %02d:%02d:%02d", userdatetime.dateyear, userdatetime.datemonth+1, userdatetime.datedmonth, userdatetime.datehour, userdatetime.dateminute, userdatetime.datesecond);
                            pData->UpdateIndex = flagid;
                            pData->UpdateFlag  = updateFlag;
                        }
                    }
                }

                /*
                ** We're done processing rows.  Let's check the final return
                ** value of ct_fetch().
                */
                switch ((int)retcode)
                {
                    case CS_END_DATA:
                        /*
                        ** Everything went fine.
                        */
                        retcode = CS_SUCCEED;
                        break;

                    case CS_FAIL:
                        /*
                        ** Something terrible happened.
                        */
                        break;

                    default:
                        /*
                        ** We got an unexpected return value.
                        */
                        break;
                }
            }
            ///////////////////////
			if (retcode != CS_SUCCEED)
			{
                DIAG_CLIENT_MESSAGE(connection);
                DIAG_SERVER_MESSAGE(connection);
                ct_cmd_drop(cmd);
				return -1;
			}
			break;

		default:
			/*
			** We got an unexpected result type.
			*/
            DIAG_CLIENT_MESSAGE(connection);
            DIAG_SERVER_MESSAGE(connection);
            ct_cancel(NULL, cmd, CS_CANCEL_ALL);
            ct_cmd_drop(cmd);
			return -1;
		}
	}

	/*
	** We're done processing results. Let's check the
	** return value of ct_results() to see if everything
	** went ok.
	*/
	switch ((int)retcode)
	{
		case CS_END_RESULTS:
			/*
			** Everything went fine.
			*/
			break;

		case CS_FAIL:
			/*
			** Something went wrong.
			*/
            DIAG_CLIENT_MESSAGE(connection);
            DIAG_SERVER_MESSAGE(connection);
            ct_cmd_drop(cmd);
			return -1;

		default:
			/*
			** We got an unexpected return value.
			*/
            DIAG_CLIENT_MESSAGE(connection);
            DIAG_SERVER_MESSAGE(connection);
            ct_cmd_drop(cmd);
			return -1;
	}

	/*
	** Drop our command structure
	*/
	if ((retcode = ct_cmd_drop(cmd)) != CS_SUCCEED)
	{
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        return -1;
	}
	return retcode == CS_SUCCEED ? row_count : -1;

}
/**
*   @brief bulk copy data from TBL_NumberPrefix
*/
int CSybClient::bulkCopyOut_NumberPrefix(int connId, char* tablename)
{
    CS_CONNECTION *connection = getConnection(connId);
    if(NULL == connection || NULL == tablename) return -1;

    CLEAR_ALL_MESSAGE(connection);

    int copiedRowCnt = 0;
    CS_RETCODE retcode;

    #define MAX_ROWS_ONETIME 1024
	CS_BLKDESC	*blkdesc;
    CS_DATAFMT	datafmt;	    /* hold the variable descriptions */
    CS_CHAR     areaCode_fieldBuf[MAX_ROWS_ONETIME][16];
	CS_CHAR 	prefix_fieldBuf[MAX_ROWS_ONETIME][32];	/* point to the data for transfer */
    CS_DATETIME updateTime_fieldBuf[MAX_ROWS_ONETIME];
    CS_TINYINT  sarNumber_fieldBuf[MAX_ROWS_ONETIME];
    CS_TINYINT  exchangeHouse_fieldBuf[MAX_ROWS_ONETIME];
    //
    CS_SMALLINT areaCode_indBuf[MAX_ROWS_ONETIME];
    CS_SMALLINT prefix_indBuf[MAX_ROWS_ONETIME];
    CS_SMALLINT updateTime_indBuf[MAX_ROWS_ONETIME];
    CS_SMALLINT sarNumber_indBuf[MAX_ROWS_ONETIME];
    CS_SMALLINT exchangeHouse_indBuf[MAX_ROWS_ONETIME];
    //
	CS_INT      areaCode_bufLen[MAX_ROWS_ONETIME];
    CS_INT      prefix_bufLen[MAX_ROWS_ONETIME];
    CS_INT      updateTime_bufLen[MAX_ROWS_ONETIME];
    CS_INT      sarNumber_bufLen[MAX_ROWS_ONETIME];
    CS_INT      exchangeHouse_bufLen[MAX_ROWS_ONETIME];
    //
	CS_INT		numrows = MAX_ROWS_ONETIME;
    //
    #define FIELD_AreaCode      1
    #define FIELD_Prefix        2
    #define FIELD_UpdateTime    3
    #define FIELD_SARNumber     5
    #define FIELD_ExchangeHouse 6

	/*
	** Ready to start the bulk copy in now that all the connections
	** have been made and have a table name.
	**
	** Start by getting the bulk descriptor and starting the initialization
	*/
	if ( (retcode = blk_alloc(connection, EX_BULK_VERSION, &blkdesc)) != CS_SUCCEED)
	{
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
		return -1;
	}

	if (blk_init(blkdesc, CS_BLK_OUT, tablename, CS_NULLTERM) == CS_FAIL)
	{
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
	}

	/*
	** Now to bind the variables to the columns and transfer the data
	*/
	datafmt.datatype = CS_CHAR_TYPE;
    datafmt.format   = CS_FMT_NULLTERM;
    datafmt.maxlength= 16;
	datafmt.count    = MAX_ROWS_ONETIME;
    datafmt.locale   = 0;//
    if (blk_bind(blkdesc, FIELD_AreaCode, &datafmt, areaCode_fieldBuf, areaCode_bufLen, areaCode_indBuf) != CS_SUCCEED)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
    }
    //
	datafmt.datatype = CS_CHAR_TYPE;
    datafmt.format   = CS_FMT_NULLTERM;
    datafmt.maxlength= 32;
    if (blk_bind(blkdesc, FIELD_Prefix, &datafmt, prefix_fieldBuf, prefix_bufLen, prefix_indBuf) != CS_SUCCEED)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
    }
    //
	datafmt.datatype = CS_DATETIME_TYPE;
    datafmt.format   = CS_FMT_UNUSED;
    datafmt.maxlength= CS_SIZEOF(CS_DATETIME);
    if (blk_bind(blkdesc, FIELD_UpdateTime, &datafmt, updateTime_fieldBuf, updateTime_bufLen, updateTime_indBuf) != CS_SUCCEED)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
    }
    //
	datafmt.datatype = CS_TINYINT_TYPE;
    datafmt.format   = CS_FMT_UNUSED;
    datafmt.maxlength= CS_SIZEOF(CS_TINYINT);
    if (blk_bind(blkdesc, FIELD_SARNumber, &datafmt, sarNumber_fieldBuf, sarNumber_bufLen, sarNumber_indBuf) != CS_SUCCEED)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
    }
    //
    if (blk_bind(blkdesc, FIELD_ExchangeHouse, &datafmt, exchangeHouse_fieldBuf, exchangeHouse_bufLen, exchangeHouse_indBuf) != CS_SUCCEED)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
    }

    //if (blk_rowxfer_mult(blkdesc, &numrows) == CS_FAIL)
	while( (retcode = blk_rowxfer_mult(blkdesc, &numrows)) == CS_SUCCEED ||
           retcode == CS_ROW_FAIL)
    {
        copiedRowCnt += numrows;
        //
        for(int ii = 0; ii < numrows; ++ii)
        {
            //
            stNumPrefix prefix;
            prefix.prefixLen = strlen(prefix_fieldBuf[ii]);
            memcpy(prefix.szPrefix, prefix_fieldBuf[ii], prefix.prefixLen);
            prefix.areaCodeLen = strlen(areaCode_fieldBuf[ii]);
            memcpy(prefix.szAreaCode, areaCode_fieldBuf[ii], prefix.areaCodeLen);
            prefix.adminCenterId = sarNumber_fieldBuf[ii];
            prefix.switchCenterId = exchangeHouse_fieldBuf[ii];
            m_pParentThread->addNumPrefix(prefix);
        }
    }
    //
    if(retcode != CS_END_DATA)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        retcode = CS_FAIL;
    }

	/*
	** ALL the rows sent so clear up
	*/
    CS_INT blktype = copiedRowCnt > 0 ? CS_BLK_ALL : CS_BLK_CANCEL;
	if ( (retcode = blk_done(blkdesc, blktype, &numrows)) == CS_FAIL)
	{
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
	}
	if ( (retcode = blk_drop(blkdesc)) == CS_FAIL)
	{
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
	}

    return retcode == CS_SUCCEED ? copiedRowCnt : -1;
}
bool SybCTnewDAImpl::Exec( Context &ctx, ParameterMapper *in, ResultMapper *out)
{
	StartTrace(SybCTnewDAImpl.Exec);
	bool bRet = false;
	DAAccessTimer(SybCTnewDAImpl.Exec, fName, ctx);
	// check if we are initialized
	bool bInitialized = false;
	if ( fgInitialized ) {
		LockUnlockEntry me(fgStructureMutex);
		bInitialized = fgInitialized;
	}
	if ( bInitialized ) {
		SemaphoreEntry aEntry(*fgpResourcesSema);
		// we need the server and user to see if there is an existing and Open SybCTnewDA
		String user, server;
		in->Get( "SybDBUser", user, ctx);
		in->Get( "SybDBHost", server, ctx);
		Trace ("USER IS:" << user );
		Trace ("Host is:" << server );
		out->Put("QuerySource", server, ctx);

		SybCTnewDA *pSyb = NULL;
		bool bIsOpen = false, bDoRetry = true;
		long lTryCount(1L);
		in->Get( "SybDBTries", lTryCount, ctx);
		if ( lTryCount < 1 ) {
			lTryCount = 1L;
		}
		// we slipped through and are ready to get a SybCT and execute a query
		// find a free SybCTnewDA, we should always get a valid SybCTnewDA here!
		while ( bDoRetry && --lTryCount >= 0 ) {
			String command;
			if ( DoGetConnection(pSyb, bIsOpen, server, user) ) {
				SybCTnewDA::DaParams daParams(&ctx, in, out, &fName);
				// test if the connection is still valid, eg. we are able to get/set connection params
				if ( bIsOpen ) {
					SybCTnewDA::DaParams outParams;
					if ( pSyb->GetConProps(CS_USERDATA, (CS_VOID **)&outParams, CS_SIZEOF(SybCTnewDA::DaParams)) != CS_SUCCEED ) {
						// try to close and reopen connection
						pSyb->Close();
						bIsOpen = false;
					}
				}
				if ( !bIsOpen ) {
					String passwd, app;
					in->Get( "SybDBPW", passwd, ctx);
					in->Get( "SybDBApp", app, ctx);
					// open new connection
					if ( !( bIsOpen = pSyb->Open( daParams, user, passwd, server, app) ) ) {
						SYSWARNING("Could not open connection to server [" << server << "] with user [" << user << "]");
					}

					// http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc31644.1502/html/sag2/sag2349.htm
					//You can enable delayed_commit for the session with the set command or the database with sp_dboption. The syntax for delayed_commit is:
					//set delayed_commit on | off | default
					//  where on enables the delayed_commit option, off disables it, and default means the database-level setting takes effect.
					//The syntax for sp_dboption is: sp_dboption database_name, 'delayed commit', [true | false]
					//  where true enables delayed_commit at the database level, and false disables the delayed_commit option. Only the DBO can set this parameter.

					// set the option delayed commit just once, after the DB connection was establisched. Further SybCTnewDAImpl::Exec() calls woun't fall here
					if (fbUseDelayedCommit) {
						// activate delayed commit
						String sParamDelayed = "set delayed_commit on";
						String sTmpResultformat;
						in->Get( "SybDBResultFormat", sTmpResultformat, ctx);
						//if ( !(bRet = pSyb->SqlExec(daParams, sParamDelayed, sTmpResultformat) ) )
						if ( !(bRet = pSyb->SqlExec(daParams, sParamDelayed, "", 0, 0) ) ) {
							SYSWARNING("could not execute the sql command " << sParamDelayed << " or it was aborted");
							// maybe a close is better here to reduce the risk of further failures
							pSyb->Close();
							bIsOpen = false;
						}
					}
				}
				if ( bIsOpen ) {
					if ( DoPrepareSQL(command, ctx, in) ) {
						String resultformat, resultsize, resultmaxrows;
						in->Get( "SybDBResultFormat", resultformat, ctx);
						in->Get( "SybDBMaxResultSize", resultsize, ctx);
						in->Get( "SybDBMaxRows", resultmaxrows, ctx);
						if ( !(bRet = pSyb->SqlExec( daParams, command, resultformat, resultsize.AsLong(0L), resultmaxrows.AsLong(-1L) ) ) ) {
							SYSWARNING("could not execute the sql command or it was aborted");
							// maybe a close is better here to reduce the risk of further failures
							pSyb->Close();
							bIsOpen = false;
						} else {
							bDoRetry = false;
						}
					} else {
						out->Put("Messages", "Rendered slot SQL resulted in an empty string", ctx);
						bDoRetry = false;
					}
				}
				DoPutbackConnection(pSyb, bIsOpen, server, user);
			} else {
				SYSERROR("unable to get SybCTnewDA");
			}
			if ( bDoRetry && lTryCount > 0 ) {
				SYSWARNING("Internally retrying to execute command [" << command << "]");
			}
		}
	} else {
		SystemLog::Error("Tried to access SybCTnewDAImpl when SybaseModule was not initialized!\n Try to add a slot SybaseModule to Modules slot and /SybaseModule { /SybCTnewDAImpl { <config> } } into Config.any");
	}
	return bRet;
}
/**
*   @brief bulk copy data from TBL_PrePaidArrears
*/
int CSybClient::bulkCopyOut_PrePaidArrears(int connId, char* tablename)
{
    CS_CONNECTION *connection = getConnection(connId);
    if(NULL == connection || NULL == tablename) return -1;

    CLEAR_ALL_MESSAGE(connection);

    int copiedRowCnt = 0;
    CS_RETCODE retcode;

    #define MAX_ROWS_ONETIME 1024
    #define FIELD_Msisdn     1
    #define FIELD_UpdateTime 2

    CS_BLKDESC  *blkdesc;
    CS_DATAFMT  datafmt;                    /* hold the variable descriptions */
    CS_CHAR     Msisdn_fieldbuf[MAX_ROWS_ONETIME][32];   /* point to the data for transfer */
    CS_DATETIME UpdateTime_fieldbuf[MAX_ROWS_ONETIME];
    CS_SMALLINT Msisdn_fieldind[MAX_ROWS_ONETIME];
    CS_SMALLINT UpdateTime_fieldind[MAX_ROWS_ONETIME];
    CS_INT      Msisdn_fieldlen[MAX_ROWS_ONETIME];
    CS_INT      UpdateTime_fieldlen[MAX_ROWS_ONETIME];
    CS_INT      numrows = MAX_ROWS_ONETIME;


    /*
    ** Ready to start the bulk copy in now that all the connections
    ** have been made and have a table name.
    **
    ** Start by getting the bulk descriptor and starting the initialization
    */
    if ( (retcode = blk_alloc(connection, EX_BULK_VERSION, &blkdesc)) != CS_SUCCEED)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        return -1;
    }

    if (blk_init(blkdesc, CS_BLK_OUT, tablename, CS_NULLTERM) == CS_FAIL)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
    }

    /*
    ** Now to bind the variables to the columns and transfer the data
    */
    datafmt.datatype = CS_CHAR_TYPE;
    datafmt.format   = CS_FMT_NULLTERM;
    datafmt.maxlength= 32;
    datafmt.count    = MAX_ROWS_ONETIME;
    datafmt.locale   = 0;//
    if (blk_bind(blkdesc, FIELD_Msisdn, &datafmt, Msisdn_fieldbuf, Msisdn_fieldlen, Msisdn_fieldind) != CS_SUCCEED) // bind OriginalNumber field
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
    }

    //
    datafmt.datatype = CS_DATETIME_TYPE;
    datafmt.format   = CS_FMT_UNUSED;
    datafmt.maxlength= CS_SIZEOF(CS_DATETIME);
    datafmt.count    = MAX_ROWS_ONETIME;
    if (blk_bind(blkdesc, FIELD_UpdateTime, &datafmt, UpdateTime_fieldbuf, UpdateTime_fieldlen, UpdateTime_fieldind) != CS_SUCCEED) // bind ChangedNumber field
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        blk_drop(blkdesc);
        return -1;
    }

    //
    CS_DATEREC userdatetime;
    //
    while( (retcode = blk_rowxfer_mult(blkdesc, &numrows)) == CS_SUCCEED ||
           retcode == CS_ROW_FAIL)
    {
        copiedRowCnt += numrows;
        for(int ii = 0; ii < numrows; ++ii)
        {
            stNumKey num;
            num.numLen = strlen(Msisdn_fieldbuf[ii]);
            memcpy(num.num, Msisdn_fieldbuf[ii], num.numLen);
            m_pParentThread->addPrePaidNum(num);
        }
    }
    //
    if(retcode != CS_END_DATA)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
        retcode = CS_FAIL;
    }

    /*
    ** ALL the rows sent so clear up
    */
    CS_INT blktype = copiedRowCnt > 0 ? CS_BLK_ALL : CS_BLK_CANCEL;
    if ( (retcode = blk_done(blkdesc, blktype, &numrows)) == CS_FAIL)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
    }
    if ( (retcode = blk_drop(blkdesc)) == CS_FAIL)
    {
        DIAG_CLIENT_MESSAGE(connection);
        DIAG_SERVER_MESSAGE(connection);
    }

    return retcode == CS_SUCCEED ? copiedRowCnt : -1;
}
Exemple #5
0
static int 
insert_test(CS_CONNECTION *conn, CS_COMMAND *cmd, int useNames)
{
	CS_CONTEXT *ctx;

	CS_RETCODE ret;
	CS_INT res_type;

	CS_DATAFMT datafmt;
	CS_DATAFMT srcfmt;
	CS_DATAFMT destfmt;
	CS_INT intvar;
	CS_FLOAT floatvar;
	CS_MONEY moneyvar;
	CS_DATEREC datevar;
	char moneystring[10];
	char dummy_name[30];
	char dummy_name2[20];
	CS_INT destlen;

	/* clear table */
	run_command(cmd, "delete #ctparam_lang");

	/*
	 * Assign values to the variables used for parameter passing.
	 */

	intvar = 2;
	floatvar = 0.12;
	strcpy(dummy_name, "joe blow");
	strcpy(dummy_name2, "");
	strcpy(moneystring, "300.90");

	/*
	 * Clear and setup the CS_DATAFMT structures used to convert datatypes.
	 */

	memset(&srcfmt, 0, sizeof(CS_DATAFMT));
	srcfmt.datatype = CS_CHAR_TYPE;
    srcfmt.maxlength = (CS_INT)strlen(moneystring);
	srcfmt.precision = 5;
	srcfmt.scale = 2;
	srcfmt.locale = NULL;

	memset(&destfmt, 0, sizeof(CS_DATAFMT));
	destfmt.datatype = CS_MONEY_TYPE;
	destfmt.maxlength = sizeof(CS_MONEY);
	destfmt.precision = 5;
	destfmt.scale = 2;
	destfmt.locale = NULL;

	/*
	 * Convert the string representing the money value
	 * to a CS_MONEY variable. Since this routine does not have the
	 * context handle, we use the property functions to get it.
	 */
	if ((ret = ct_cmd_props(cmd, CS_GET, CS_PARENT_HANDLE, &conn, CS_UNUSED, NULL)) != CS_SUCCEED) {
		fprintf(stderr, "ct_cmd_props() failed\n");
		return 1;
	}
	if ((ret = ct_con_props(conn, CS_GET, CS_PARENT_HANDLE, &ctx, CS_UNUSED, NULL)) != CS_SUCCEED) {
		fprintf(stderr, "ct_con_props() failed\n");
		return 1;
	}
	ret = cs_convert(ctx, &srcfmt, (CS_VOID *) moneystring, &destfmt, &moneyvar, &destlen);
	if (ret != CS_SUCCEED) {
		fprintf(stderr, "cs_convert() failed\n");
		return 1;
	}

	/*
	 * create the command
	 */
    if ((ret = ct_command(cmd, CS_LANG_CMD, query, (CS_INT)strlen(query),
		CS_UNUSED)) != CS_SUCCEED) 
	{
		fprintf(stderr, "ct_command(CS_LANG_CMD) failed\n");
		return 1;
	}

	/*
	 * Clear and setup the CS_DATAFMT structure, then pass
	 * each of the parameters for the query.
	 */
	memset(&datafmt, 0, sizeof(datafmt));
	if (useNames)
		strcpy(datafmt.name, "@in1");
	else
		datafmt.name[0] = 0;
	datafmt.maxlength = 255;
	datafmt.namelen = CS_NULLTERM;
	datafmt.datatype = CS_CHAR_TYPE;
	datafmt.status = CS_INPUTVALUE;

	/*
	 * The character string variable is filled in by the RPC so pass NULL
	 * for the data 0 for data length, and -1 for the indicator arguments.
	 */
    ret = ct_param(cmd, &datafmt, dummy_name, (CS_INT)strlen(dummy_name), 0);
	if (CS_SUCCEED != ret) {
		fprintf(stderr, "ct_param(char) failed\n");
		return 1;
	}

	if (useNames)
		strcpy(datafmt.name, "@in2");
	else
		datafmt.name[0] = 0;
	datafmt.maxlength = 255;
	datafmt.namelen = CS_NULLTERM;
	datafmt.datatype = CS_CHAR_TYPE;
	datafmt.status = CS_INPUTVALUE;

    ret = ct_param(cmd, &datafmt, dummy_name2, (CS_INT)strlen(dummy_name2), 0);
	if (CS_SUCCEED != ret) {
		fprintf(stderr, "ct_param(char) failed\n");
		return 1;
	}

	if (useNames)
		strcpy(datafmt.name, "@in3");
	else
		datafmt.name[0] = 0;
	datafmt.namelen = CS_NULLTERM;
	datafmt.datatype = CS_INT_TYPE;
	datafmt.status = CS_INPUTVALUE;

	ret = ct_param(cmd, &datafmt, (CS_VOID *) & intvar, CS_SIZEOF(CS_INT), 0);
	if (CS_SUCCEED != ret) {
		fprintf(stderr, "ct_param(int) failed\n");
		return 1;
	}

	if (useNames)
		strcpy(datafmt.name, "@moneyval");
	else
		datafmt.name[0] = 0;
	datafmt.namelen = CS_NULLTERM;
	datafmt.datatype = CS_MONEY_TYPE;
	datafmt.status = CS_INPUTVALUE;

	ret = ct_param(cmd, &datafmt, (CS_VOID *) & moneyvar, CS_SIZEOF(CS_MONEY), 0);
	if (CS_SUCCEED != ret) {
		fprintf(stderr, "ct_param(money) failed\n");
		return 1;
	}

	if (useNames)
		strcpy(datafmt.name, "@dateval");
	else
		datafmt.name[0] = 0;
	datafmt.namelen = CS_NULLTERM;
	datafmt.datatype = CS_DATETIME_TYPE;
	datafmt.status = CS_INPUTVALUE;
	memset(&datevar, 0, sizeof(CS_DATEREC));
	datevar.dateyear = 2003;
	datevar.datemonth = 2;
	datevar.datedmonth = 1;

	ret = ct_param(cmd, &datafmt, &datevar, 0, 0);
	if (CS_SUCCEED != ret) {
		fprintf(stderr, "ct_param(datetime) failed");
		return 1;
	}

	if (useNames)
		strcpy(datafmt.name, "@floatval");
	else
		datafmt.name[0] = 0;
	datafmt.namelen = CS_NULLTERM;
	datafmt.datatype = CS_FLOAT_TYPE;
	datafmt.status = CS_INPUTVALUE;

	ret = ct_param(cmd, &datafmt, &floatvar, 0, 0);
	if (CS_SUCCEED != ret) {
		fprintf(stderr, "ct_param(float) failed");
		return 1;
	}

	/*
	 * Send the command to the server
	 */
	if (ct_send(cmd) != CS_SUCCEED) {
		fprintf(stderr, "ct_send(CS_LANG_CMD) failed\n");
		return 1;
	}

	/*
	 * Process the results.
	 */
	while ((ret = ct_results(cmd, &res_type)) == CS_SUCCEED) {
		switch ((int) res_type) {

		case CS_CMD_SUCCEED:
		case CS_CMD_DONE:
			{
				CS_INT rowsAffected=0;
				ct_res_info(cmd, CS_ROW_COUNT, &rowsAffected, CS_UNUSED, NULL);
				if (1 != rowsAffected) 
					fprintf(stderr, "insert touched %d rows instead of 1\n", rowsAffected);
			}
			break;

		case CS_CMD_FAIL:
			/*
			 * The server encountered an error while
			 * processing our command.
			 */
			fprintf(stderr, "ct_results returned CS_CMD_FAIL.\n");
			break;

		case CS_STATUS_RESULT:
			/*
			 * The server encountered an error while
			 * processing our command.
			 */
			fprintf(stderr, "ct_results returned CS_STATUS_RESULT.\n");
			break;

		default:
			/*
			 * We got something unexpected.
			 */
			fprintf(stderr, "ct_results returned unexpected result type %d\n", res_type);
			return 1;
		}
	}
	if (ret != CS_END_RESULTS)
		fprintf(stderr, "ct_results returned unexpected result %d.\n", (int) ret);

	/* test row inserted */
	ret = run_command(cmd, "if not exists(select * from #ctparam_lang where name = 'joe blow' and name2 is not null and age = 2) select 1");
	if (ret != CS_SUCCEED) {
		fprintf(stderr, "check row inserted failed\n");
		exit(1);
	}

	return 0;
}