Пример #1
0
bool Database::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    {
        // guarded block for thread-safe mySQL request
        ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
        #ifdef BLIZZLIKE_DEBUG
        uint32 _s = getMSTime();
        #endif
        if (mysql_query(mMysql, sql))
        {
            sLog.outErrorDb("SQL: %s", sql);
            sLog.outErrorDb("query ERROR: %s", mysql_error(mMysql));
            return false;
        }
        else
        {
            #ifdef BLIZZLIKE_DEBUG
            sLog.outDebug("[%u ms] SQL: %s", getMSTimeDiff(_s,getMSTime()), sql );
            #endif
        }

        *pResult = mysql_store_result(mMysql);
        *pRowCount = mysql_affected_rows(mMysql);
        *pFieldCount = mysql_field_count(mMysql);
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
Пример #2
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult,
        MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount) {
    if (!m_Mysql)
        return false;

    {
        uint32 _s = 0;
        if (sLog->GetSQLDriverQueryLogging())
            _s = getMSTime();

        if (mysql_query(m_Mysql, sql)) {
            uint32 lErrno = mysql_errno(m_Mysql);
            sLog->outSQLDriver("SQL: %s", sql);
            sLog->outSQLDriver("ERROR: [%u] %s", lErrno, mysql_error(m_Mysql));

            if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection)
                return _Query(sql, pResult, pFields, pRowCount, pFieldCount); // We try again

            return false;
        } else if (sLog->GetSQLDriverQueryLogging()) {
            sLog->outSQLDriver("[%u ms] SQL: %s",
                    getMSTimeDiff(_s, getMSTime()), sql);
        }

        *pResult = mysql_store_result(m_Mysql);
        *pRowCount = mysql_affected_rows(m_Mysql);
        *pFieldCount = mysql_field_count(m_Mysql);
    }

    if (!*pResult)
        return false;

    if (!*pRowCount) {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);

    return true;
}
Пример #3
0
static t_sql_field * sql_mysql_fetch_fields(t_sql_res *result)
{
    MYSQL_FIELD *fields;
    unsigned fieldno, i;
    t_sql_field *rfields;

    if (result == NULL) {
	eventlog(eventlog_level_error, __FUNCTION__, "got NULL result");
	return NULL;
    }

    fieldno = mysql_num_fields((MYSQL_RES *)result);
    fields = mysql_fetch_fields((MYSQL_RES *)result);

    rfields = xmalloc(sizeof(t_sql_field) * (fieldno + 1));
    for(i = 0; i < fieldno; i++)
	rfields[i] = fields[i].name;
    rfields[i] = NULL;

    return rfields;
}
Пример #4
0
CMySQL_RowResult::CMySQL_RowResult(CMySQL_Connection& conn)
    : m_Connect(&conn),
      m_CurrItem(-1)
{
    m_Result = mysql_use_result(&m_Connect->m_MySQL);
    if ( !m_Result ) {
        DATABASE_DRIVER_WARNING( "Failed: mysql_use_result", 800004 );
    }

    unsigned int col_num = mysql_num_fields(m_Result);

    MYSQL_FIELD* fields = mysql_fetch_fields(m_Result);

    for (unsigned int n = 0;  n < col_num;  n++) {
        m_CachedRowInfo.Add(
            fields[n].name,
            fields[n].max_length,
            s_GetDataType(fields[n].type)
            );
    }
}
bool DatabaseMysql::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    {
        // guarded block for thread-safe mySQL request
        ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);

        uint32 _s = WorldTimer::getMSTime();

        if(mysql_query(mMysql, sql))
        {
            sLog.outErrorDb( "SQL: %s", sql );
            sLog.outErrorDb("query ERROR: %s", mysql_error(mMysql));
            return false;
        }
        else
        {
            DEBUG_FILTER_LOG(LOG_FILTER_SQL_TEXT, "[%u ms] SQL: %s", WorldTimer::getMSTimeDiff(_s,WorldTimer::getMSTime()), sql );
        }

        *pResult = mysql_store_result(mMysql);
        *pRowCount = mysql_affected_rows(mMysql);
        *pFieldCount = mysql_field_count(mMysql);
        // end guarded block
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
Пример #6
0
int KDBTools::GetFieldsName(const char cszTableName[], FIELD_NAME_VECTOR& refRetFieldNameVector)
{
    int nResult  = false;
    MYSQL_RES *pFieldSet = NULL;
    MYSQL_FIELD *pFields = NULL;
    unsigned uFieldCount = 0;

    KGLOG_PROCESS_ERROR(cszTableName);
    KGLOG_PROCESS_ERROR(cszTableName[0]);

    refRetFieldNameVector.clear();

    ASSERT(m_pDBHandle);
    pFieldSet = mysql_list_fields(m_pDBHandle, cszTableName, NULL);
    KGD_MYSQL_PROCESS_ERROR(pFieldSet, m_pDBHandle, "mysql_list_fields()");

    uFieldCount = mysql_num_fields(pFieldSet);
    KGLOG_PROCESS_ERROR(uFieldCount);

    pFields = mysql_fetch_fields(pFieldSet);
    KGLOG_PROCESS_ERROR(pFields);

    for (unsigned i = 0; i < uFieldCount; ++i)
    {
        refRetFieldNameVector.push_back(pFields[i].name);
    }

    nResult = true;
Exit0:
    if (pFieldSet)
    {
        mysql_free_result(pFieldSet);
        pFieldSet = NULL;
    }
    if (!nResult)
    {
        refRetFieldNameVector.clear();
    }
    return nResult;
}
Пример #7
0
static value alloc_result( connection *c, MYSQL_RES *r ) {
	result *res = (result*)alloc(sizeof(result));
	value o = alloc_abstract(k_result,res);
	int num_fields = mysql_num_fields(r);
	int i,j;
	MYSQL_FIELD *fields = mysql_fetch_fields(r);
	res->r = r;
	res->conv_date = c->conv_date;
	res->conv_bytes = c->conv_bytes;
	res->conv_string = c->conv_string;
	res->current = NULL;
	res->nfields = num_fields;
	res->fields_ids = (field*)alloc_private(sizeof(field)*num_fields);
	res->fields_convs = (CONV*)alloc_private(sizeof(CONV)*num_fields);	
	for(i=0;i<num_fields;i++) {
		field id;
		if( strchr(fields[i].name,'(') )
			id = val_id("???"); // looks like an inner request : prevent hashing + cashing it
		else {
			id = val_id(fields[i].name);
			for(j=0;j<i;j++)
				if( res->fields_ids[j] == id ) {
					buffer b = alloc_buffer("Error, same field ids for : ");
					buffer_append(b,fields[i].name);
					buffer_append(b,":");
					val_buffer(b,alloc_int(i));
					buffer_append(b," and ");
					buffer_append(b,fields[j].name);
					buffer_append(b,":");
					val_buffer(b,alloc_int(j));
					buffer_append(b,".");
					bfailure(b);
				}
		}
		res->fields_ids[i] = id;
		res->fields_convs[i] = convert_type(fields[i].type,fields[i].flags,fields[i].length);
	}
	val_gc(o,free_result);
	return o;
}
Пример #8
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!m_Mysql)
        return false;

    {
       boost::timer _s;

        if (mysql_query(m_Mysql, sql))
        {
            uint32 lErrno = mysql_errno(m_Mysql);
            _LOG_INFO(LOG_FILTER_SQL, "SQL: %s", sql);
            _LOG_ERROR(LOG_FILTER_SQL, "[%u] %s", lErrno, mysql_error(m_Mysql));

            if (_HandleMySQLErrno(lErrno))      // If it returns true, an error was handled successfully (i.e. reconnection)
                return _Query(sql, pResult, pFields, pRowCount, pFieldCount);    // We try again

            return false;
        }
        else
            _LOG_DEBUG(LOG_FILTER_SQL, "[%u ms] SQL: %s",(uint32)_s.elapsed(), sql);

        *pResult = mysql_store_result(m_Mysql);
        *pRowCount = mysql_affected_rows(m_Mysql);
        *pFieldCount = mysql_field_count(m_Mysql);
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);

    return true;
}
/*************************************************************************//**
Execute any query contained in the input string.

@retval false if no error. True if error

If the query is a select query which returns a value, the results have to be
retirieved by calling getNextRow()
														 
*****************************************************************************/
bool MySqlConnection::query(const std::string queryStr)
{
	// Execute the query
	int res = mysql_real_query(&connection, queryStr.c_str(), queryStr.size());
	if (res)
	{
		errorPrint();
		return true;
	}
	// Check if there are results as expected

	resetQueryResultInfo();
	result = mysql_store_result(& connection);
	if (result)  // there are rows
	{
		// Retrieve information about the results
		hasRows = true;
		num_fields = mysql_num_fields(result);
		fields = mysql_fetch_fields(result);
		// There is an issue here because mysql_store_result was called but mysql_free_results was not
		// However as we are using only insert queries in this program this should be acceptable

	}
	else  // mysql_store_result() returned nothing; should it have?
	{
		if (mysql_field_count(& connection) == 0)
		{
			// query does not return data
			// (it was not a SELECT)
			num_rows = mysql_affected_rows(&connection);
			//assert(num_rows == 1);
		}
		else // mysql_store_result() should have returned data
		{
			errorPrint();
		}
	}

	return false;
}
Пример #10
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    uint32 _s = WorldTimer::getMSTime();

    if (mysql_query(mMysql, sql))
    {
        uint32 lErrno = mysql_errno(mMysql);

        sLog.outErrorDb( "SQL: %s", sql);
        sLog.outErrorDb("[%u] %s", lErrno, mysql_error(mMysql));

        if (HandleMySQLError(lErrno)) // If error is handled, just try again
            return _Query(sql, pResult, pFields, pRowCount, pFieldCount);

        return false;
    }
    else
    {
        DEBUG_FILTER_LOG(LOG_FILTER_SQL_TEXT, "[%u ms] SQL: %s", WorldTimer::getMSTimeDiff(_s,WorldTimer::getMSTime()), sql );
    }

    *pResult = mysql_store_result(mMysql);
    *pRowCount = mysql_affected_rows(mMysql);
    *pFieldCount = mysql_field_count(mMysql);

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
Пример #11
0
static SLVAL
sl_mysql_raw_query(sl_vm_t* vm, SLVAL self, SLVAL query)
{
    mysql_t* mysql = get_mysql(vm, self);
    sl_string_t* str = sl_get_string(vm, query);

    if(mysql_real_query(&mysql->mysql, (char*)str->buff, str->buff_len)) {
        sl_mysql_check_error(vm, &mysql->mysql);
    }

    MYSQL_RES* result;
    if((result = mysql_store_result(&mysql->mysql))) {
        /* do shit */
        int ncolumns = mysql_num_fields(result);
        int nrows = mysql_num_rows(result);
        SLVAL* rows = sl_alloc(vm->arena, sizeof(SLVAL) * nrows);
        MYSQL_FIELD* fields = mysql_fetch_fields(result);
        for(int i = 0; i < nrows; i++) {
            SLVAL* cells = sl_alloc(vm->arena, sizeof(SLVAL) * ncolumns * 2);
            MYSQL_ROW row = mysql_fetch_row(result);
            size_t* lengths = mysql_fetch_lengths(result);
            for(int j = 0; j < ncolumns; j++) {
                cells[j * 2] = sl_make_cstring(vm, fields[j].name);
                if(row[j]) {
                    cells[j * 2 + 1] = sl_make_string(vm, (uint8_t*)row[j], lengths[j]);
                } else {
                    cells[j * 2 + 1] = vm->lib.nil;
                }
            }
            rows[i] = sl_make_dict(vm, ncolumns, cells);
        }
        mysql_free_result(result);
        return sl_make_array(vm, nrows, rows);
    } else {
        if(mysql_field_count(&mysql->mysql) != 0) {
            sl_mysql_check_error(vm, &mysql->mysql);
        }
        return sl_make_int(vm, mysql_affected_rows(&mysql->mysql));
    }
}
Пример #12
0
u4 AMySQLServer::_processQueryAllRows(MYSQL_RES *pmyresult, AResultSet& target)
{
  u4 rowCount = 0;
  if (pmyresult)
  {
    MYSQL_ROW myrow;
    rowCount = (int)mysql_num_rows(pmyresult);

    if (rowCount == 0)
      return 0;

    //a_Get field info
    MYSQL_FIELD *fields = mysql_fetch_fields(pmyresult);
    u4 num_fields = mysql_num_fields(pmyresult);

    //a_Set up field data
    for (u4 u=0; u<num_fields; ++u)
      target.useFieldNames().push_back(fields[u].name);

    //a_Populate results
    AString str;
    myrow = mysql_fetch_row(pmyresult);
    while (myrow)
    {
      VECTOR_AString& row = target.insertRow();
      row.reserve(num_fields);
      for(u4 field=0; field < num_fields; ++field)
      {
        row.push_back(myrow[field]);
      }
      
      myrow = mysql_fetch_row(pmyresult);
    }
  }

  mysql_free_result(pmyresult);
  return rowCount;
}
Пример #13
0
static int cursor_fetch_all(lua_State* L)
{
    Cursor* cur = check_cursor(L);
    luaL_argcheck(L, cur && cur->my_res, 1, "invalid Cursor object");
    luaL_argcheck(L, cur->fetch_all, 1, "not compatible with execute()");

    int alpha_idx = 0;
    const char* opt = lua_tostring(L, 2);
    if (opt && strcmp(opt, "a") == 0) // alphabetic table index
    {
        alpha_idx = 1;
    }

    MYSQL_RES* res = cur->my_res;
    MYSQL_ROW row = mysql_fetch_row(res);
    if (row == NULL || cur->numcols == 0) // no results
    {
        cursor_nullify(L, cur);
        return 0;
    }
    if (cur->fields == NULL)
    {
        cur->fields = mysql_fetch_fields(res);
    }
    unsigned long* lengths = mysql_fetch_lengths(res);
    luaL_argcheck(L, lengths && cur->fields, 1, "fetch fields failed");
    int num_rows = (int)mysql_num_rows(cur->my_res);
    lua_createtable(L, num_rows, 0);
    int rownum = 1;
    while (row)
    {
        result_to_table(L, cur, row, lengths, alpha_idx);
        lua_rawseti(L, -2, rownum++);
        row = mysql_fetch_row(res);
    }
    cursor_nullify(L, cur);
    return 1;
}
Пример #14
0
string DBConn::Query_all_mr_mysql(string sql, string name) {

    Json::Value root;
    Json::Value arrayObj;
    Json::Value item;
    int t = mysql_real_query(&mysql, sql.c_str(),
                             (unsigned int) strlen(sql.c_str()));
    if (t == -1) {
        cout << "query failed:%s\n" << mysql_errno(&mysql)
             << mysql_error(&mysql) << endl;
    } else {
        res = mysql_store_result(&mysql); //返回查询的全部结果集
        //获取表的列数
        //int numb=mysql_num_fields(res);
        //printf("name: %s   count: %d\n", namebuf[i], rows);

        //获取并输出表头
        field = mysql_fetch_fields(res);
        //int length=mysql_fetch_lengths(res);
        int length = mysql_num_rows(res);
        int num = 0;
        int i = 1;
        while (row = mysql_fetch_row(res)) {	//mysql_fetch_row取结果集的下一行
            for (t = 0; t < mysql_num_fields(res); t++) {	//结果集的列的数量
                if (field[t].name != "meetroom_remark") {
                    item[field[t].name] = Json::Value(row[t]);
                }
            }
            arrayObj.append(item);
            item.clear();
            num++;
        }
        root["Num"] = Json::Value(num);
        root[name] = arrayObj;
        return root.toStyledString();
    }

}
Пример #15
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    uint32 _s = WorldTimer::getMSTime();

    if(mysql_query(mMysql, sql))
    {
        sLog.outLog(LOG_DB_ERR, "SQL: %s", sql );
        sLog.outLog(LOG_DB_ERR, "query ERROR: %s", mysql_error(mMysql));
        return false;
    }
    else
    {
        uint32 queryDiff = WorldTimer::getMSTimeDiff(_s, WorldTimer::getMSTime());
        if (m_db.CheckMinLogTime(queryDiff))
            sLog.outLog(LOG_DB_DIFF, "[%u ms] SQL: %s", queryDiff, sql);

        sLog.outDebug("[%u ms] SQL: %s", queryDiff, sql);
    }

    *pResult = mysql_store_result(mMysql);
    *pRowCount = mysql_affected_rows(mMysql);
    *pFieldCount = mysql_field_count(mMysql);

    if (!*pResult)
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
Пример #16
0
bool MySQLConnection::_Query(const char* sql, MYSQL_RES** pResult, MYSQL_FIELD** pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    uint32 _s = WorldTimer::getMSTime();

    if (mysql_query(mMysql, sql))
    {
		unsigned int err = mysql_errno(mMysql);
		if (err == 2006 || err == 2003 || err == 2013)
			mysql_ping(mMysql);
        sLog.outErrorDb("SQL: %s", sql);
        sLog.outErrorDb("query ERROR: %s", mysql_error(mMysql));
        return false;
    }
    else
    {
        DEBUG_FILTER_LOG(LOG_FILTER_SQL_TEXT, "[%u ms] SQL: %s", WorldTimer::getMSTimeDiff(_s, WorldTimer::getMSTime()), sql);
    }

    *pResult = mysql_store_result(mMysql);
    *pRowCount = mysql_affected_rows(mMysql);
    *pFieldCount = mysql_field_count(mMysql);

    if (!*pResult)
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
Пример #17
0
string Database::get(string field, int line) {
    //cout << "get2: "<<field<<endl;
    int pos=-1;
    int cols = mysql_num_fields(qry);
    int lines = get_num_rows();

    fields = mysql_fetch_fields(qry);
	//cout << "lines "<< lines<<" erro "<<getError()<<endl;
    if (line <= lines) {

        for(int i=0;i<= (cols-1);++i){
            if (fields[i].name == field) {
               pos = i;
               break;
            }
        }
        mysql_data_seek(qry,line-1);
        return mysql_fetch_row(qry)[pos];

    } else {
	    return "";
    }

}
Пример #18
0
bool CMySQLController::SelectQuery(const char* strQuery)
{
	try{
		int state = mysql_query(&m_Connection, strQuery);
		if (state != 0)
		{
			printf(mysql_error(&m_Connection));
			return false;
		}
		m_pResult = mysql_store_result(&m_Connection);
		m_iNumFields = mysql_num_fields(m_pResult);
		m_pFields = mysql_fetch_fields(m_pResult);
		return true;
	}
	catch (exception& ex)
	{
		string strLog;
		stringstream strErrorMess;
		strErrorMess << ex.what() << "][" << __FILE__ << "|" << __LINE__;
		strLog = CUtilities::FormatLog(ERROR_MSG, "CMySQLController", "Find", "exception:" + strErrorMess.str());
		CUtilities::WriteErrorLog(ERROR_MSG, strLog);
		return false;
	}
}
Пример #19
0
static PyObject* wsql_result_get_description(wsql_result *self, void* closure)
{
    PyObject *result;
    MYSQL_FIELD *fields;
    unsigned int i, n;

    CHECK_RESULT(self, NULL);

    n = self->num_fields;

    if (!(result = PyTuple_New(n)))
        return NULL;

    fields = mysql_fetch_fields(self->result);

    for (i=0; i<n; ++i) {
        PyObject *field_desc;
        field_desc = Py_BuildValue("(siiiiii)",
                                   fields[i].name,
                                   (long) fields[i].type,
                                   (long) fields[i].max_length,
                                   (long) fields[i].length,
                                   (long) fields[i].length,
                                   (long) fields[i].decimals,
                                   (long) !(IS_NOT_NULL(fields[i].flags)));
        if (!field_desc)
            goto on_error;

        PyTuple_SET_ITEM(result, i, field_desc);
    }
    return result;

  on_error:
    Py_XDECREF(result);
    return NULL;
}
Пример #20
0
    void MySqlResultReader::SetupFieldBuffers() {
        //if exception is raised in this routine, all allocated memory will be freed in the class' destructor

        //retrieve fields metadata
        fieldsMetadata = mysql_fetch_fields(resultMetadata);

        //setup buffers
        fieldBuffers = new MYSQL_BIND[resultMetadata->field_count];
        memset(fieldBuffers, 0, sizeof(MYSQL_BIND) * resultMetadata->field_count);

        //for each field in the result metadata we create MYSQL_BIND struct with memory buffer in it
        for (int i = 0; i < resultMetadata->field_count; ++i) {
            MYSQL_FIELD f = fieldsMetadata[i];
            unsigned int typeLength = MySqlTypesHelper::GetMySqlTypeLength(f.type, &f);

            if (typeLength != 0) {
                fieldBuffers[i].buffer = new char[typeLength];
                fieldBuffers[i].buffer_length = typeLength;
            }
            else {
                //here the variable length buffer is needed, let's handle this in the Next() routine
                fieldBuffers[i].buffer = NULL;
                fieldBuffers[i].buffer_length = 0;
                fieldBuffers[i].length = &(fieldBuffers[i].length_value);
            }

            fieldBuffers[i].buffer_type = f.type;
            fieldBuffers[i].is_null = &(fieldBuffers[i].is_null_value);
        }

        varLengthBufs.resize(resultMetadata->field_count);

        if (mysql_stmt_bind_result(stmt, fieldBuffers)) {
            throw std::exception("mysql_stmt_bind_result failed");
        }
    }
Пример #21
0
void dump_mysql_result(MYSQL_RES * result)
{
   MYSQL_ROW row;
   MYSQL_FIELD * fields = mysql_fetch_fields(result);
   word num_fields = mysql_num_fields(result);
   word num_rows   = mysql_num_rows(result);
   word field, row_i;
   char zs[1024];

   sprintf(zs, "Result dump: %d rows of %d fields", num_rows, num_fields); _log(MINOR, zs);

   for(row_i = 0; row_i < num_rows; row_i++)
   {
      sprintf(zs, "Row %d", row_i);
      _log(MINOR, zs);
      
      row = mysql_fetch_row(result);
      for(field = 0; field < num_fields; field++)
      {
         sprintf(zs, "   %s = \"%s\"", fields[field].name, row[field]); 
         // See if we can spot a timestamp
         if(row[field][0] == '1' && strlen(row[field]) == 10)
         {
            time_t stamp = atol(row[field]);
            // Accept    Jan 2008      to      May 2033
            //        1,200,000,000         2,000,000,000
            if(stamp > 1200000000L && stamp < 2000000000L)
            {
               strcat(zs, "  ");
               strcat(zs, time_text(stamp, false ));
            }
         }               
         _log(MINOR, zs);
      }
   }
} 
Пример #22
0
bool Mysql::saveSelectResult(MysqlResult *result)
{
	unsigned int i;
	unsigned int fieldCount;
	MYSQL_FIELD *field;

	// 保存结果集
	result->res = mysql_store_result( this->db );
	if ( result->res == NULL )
	{
		this->markLastError();
		return false;
	}

	// 建立索引
	fieldCount = mysql_num_fields( result->res );
	field = mysql_fetch_fields( result->res );
	for (i=0; i<fieldCount; i++)
	{
		result->fieldMap[ field[i].name ] = i;		
	}

	return true;
}
Пример #23
0
/*
 * column_names = statement:columns()
 */
static int statement_columns(lua_State *L) {
    statement_t *statement = (statement_t *)luaL_checkudata(L, 1, DBD_MYSQL_STATEMENT);

    MYSQL_FIELD *fields;
    int i;
    int num_columns;
    int d = 1;

    if (!statement->stmt) {
        luaL_error(L, DBI_ERR_INVALID_STATEMENT);
        return 0;
    }

    fields = mysql_fetch_fields(statement->metadata);
    num_columns = mysql_num_fields(statement->metadata);
    lua_newtable(L);
    for (i = 0; i < num_columns; i++) {
	const char *name = fields[i].name;

        LUA_PUSH_ARRAY_STRING(d, name);
    }

    return 1;
}
Пример #24
0
GdaDataModel *
gda_mysql_recordset_new_direct (GdaConnection *cnc, GdaDataModelAccessFlags flags, 
				GType *col_types)
{
	GdaMysqlRecordset *model;
        MysqlConnectionData *cdata;
        gint i;
	GdaDataModelAccessFlags rflags;
	GSList *columns = NULL;

        g_return_val_if_fail (GDA_IS_CONNECTION (cnc), NULL);

	cdata = (MysqlConnectionData*) gda_connection_internal_get_provider_data_error (cnc, NULL);
	if (!cdata)
		return NULL;

	/* determine access mode: RANDOM or CURSOR FORWARD are the only supported */
	if (flags & GDA_DATA_MODEL_ACCESS_RANDOM)
		rflags = GDA_DATA_MODEL_ACCESS_RANDOM;
	else
		rflags = GDA_DATA_MODEL_ACCESS_CURSOR_FORWARD;

	/* create data model */
        model = g_object_new (GDA_TYPE_MYSQL_RECORDSET,
			      "connection", cnc,
			      "model-usage", rflags,
			      NULL);
        model->priv->cnc = cnc;
	g_object_ref (G_OBJECT(cnc));

	/* columns & types */	
	model->priv->ncols = mysql_field_count (cdata->mysql);
	model->priv->types = g_new0 (GType, model->priv->ncols);
	
	/* create columns */
	for (i = 0; i < model->priv->ncols; i++)
		columns = g_slist_prepend (columns, gda_column_new ());
	columns = g_slist_reverse (columns);

	if (col_types) {
		for (i = 0; ; i++) {
			if (col_types [i] > 0) {
				if (col_types [i] == G_TYPE_NONE)
					break;
				if (i >= model->priv->ncols) {
					g_warning (_("Column %d out of range (0-%d), ignoring its specified type"), i,
						   model->priv->ncols - 1);
					break;
				}
				else
					model->priv->types [i] = col_types [i];
			}
		}
	}

	/* fill bind result */
	MYSQL_RES *mysql_res = mysql_store_result (cdata->mysql);
	MYSQL_FIELD *mysql_fields = mysql_fetch_fields (mysql_res);
	GSList *list;

	((GdaDataSelect *) model)->advertized_nrows = mysql_affected_rows (cdata->mysql);
	for (i=0, list = columns; 
	     i < model->priv->ncols; 
	     i++, list = list->next) {
		GdaColumn *column = GDA_COLUMN (list->data);
		
		/* use C API to set columns' information using gda_column_set_*() */
		MYSQL_FIELD *field = &mysql_fields[i];
		
		GType gtype = model->priv->types [i];
		if (gtype == GDA_TYPE_NULL) {
			gtype = _gda_mysql_type_to_gda (cdata, field->type, field->charsetnr);
			model->priv->types [i] = gtype;
		}
		gda_column_set_g_type (column, gtype);
		gda_column_set_name (column, field->name);
		gda_column_set_description (column, field->name);
	}
	gda_data_select_set_columns (GDA_DATA_SELECT (model), columns);

	/* load ALL data */
	MYSQL_ROW mysql_row;
	gint rownum;
	GdaServerProvider *prov;
	prov = gda_connection_get_provider (cnc);
	for (mysql_row = mysql_fetch_row (mysql_res), rownum = 0;
	     mysql_row;
	     mysql_row = mysql_fetch_row (mysql_res), rownum++) {
		GdaRow *row = gda_row_new (model->priv->ncols);
		gint col;
		for (col = 0; col < model->priv->ncols; col++) {
			gint i = col;
		
			GValue *value = gda_row_get_value (row, i);
			GType type = model->priv->types[i];
			char *data = mysql_row[i];

			if (!data || (type == GDA_TYPE_NULL))
				continue;

			gda_value_reset_with_type (value, type);
			if (type == G_TYPE_STRING)
				g_value_set_string (value, data);
			else {
				GdaDataHandler *dh;
				gboolean valueset = FALSE;
				dh = gda_server_provider_get_data_handler_g_type (prov, cnc, type);
				if (dh) {
					GValue *tmpvalue;
					tmpvalue = gda_data_handler_get_value_from_str (dh, data, type);
					if (tmpvalue) {
						*value = *tmpvalue;
						g_free (tmpvalue);
						valueset = TRUE;
					}
				}
				if (!valueset)
					gda_row_invalidate_value (row, value);
			}
		}
		gda_data_select_take_row ((GdaDataSelect*) model, row, rownum);
	}
	mysql_free_result (mysql_res);

        return GDA_DATA_MODEL (model);
}
Пример #25
0
/*
 * the @ps struct is modified and transferred to the new data model created in
 * this function
 *
 * See MySQL's documentation "C API Prepared Statement Type Codes":
 *     http://docs.oracle.com/cd/E17952_01/refman-5.5-en/c-api-prepared-statement-type-codes.html
 */
GdaDataModel *
gda_mysql_recordset_new (GdaConnection            *cnc,
			 GdaMysqlPStmt            *ps,
			 GdaSet                   *exec_params,
			 GdaDataModelAccessFlags   flags,
			 GType                    *col_types)
{
	GdaMysqlRecordset *model;
        MysqlConnectionData *cdata;
        gint i;
	GdaDataModelAccessFlags rflags;

        g_return_val_if_fail (GDA_IS_CONNECTION (cnc), NULL);
        g_return_val_if_fail (ps != NULL, NULL);

	cdata = (MysqlConnectionData*) gda_connection_internal_get_provider_data_error (cnc, NULL);
	if (!cdata)
		return NULL;

	g_assert (ps->mysql_stmt);

	/* make sure @ps reports the correct number of columns using the API*/
        if (_GDA_PSTMT (ps)->ncols < 0)
		_GDA_PSTMT(ps)->ncols = mysql_stmt_field_count (ps->mysql_stmt);

        /* completing @ps if not yet done */
	g_assert (! ps->stmt_used);
        ps->stmt_used = TRUE;
        if (!_GDA_PSTMT (ps)->types && (_GDA_PSTMT (ps)->ncols > 0)) {
		/* create prepared statement's columns */
		for (i = 0; i < _GDA_PSTMT (ps)->ncols; i++)
			_GDA_PSTMT (ps)->tmpl_columns = g_slist_prepend (_GDA_PSTMT (ps)->tmpl_columns, 
									 gda_column_new ());
		_GDA_PSTMT (ps)->tmpl_columns = g_slist_reverse (_GDA_PSTMT (ps)->tmpl_columns);

		/* create prepared statement's types, all types are initialized to GDA_TYPE_NULL */
		_GDA_PSTMT (ps)->types = g_new (GType, _GDA_PSTMT (ps)->ncols);
		for (i = 0; i < _GDA_PSTMT (ps)->ncols; i++)
			_GDA_PSTMT (ps)->types [i] = GDA_TYPE_NULL;

		if (col_types) {
			for (i = 0; ; i++) {
				if (col_types [i] > 0) {
					if (col_types [i] == G_TYPE_NONE)
						break;
					if (i >= _GDA_PSTMT (ps)->ncols) {
						g_warning (_("Column %d out of range (0-%d), ignoring its specified type"), i,
							   _GDA_PSTMT (ps)->ncols - 1);
						break;
					}
					else
						_GDA_PSTMT (ps)->types [i] = col_types [i];
				}
			}
		}
	}

	/* get rid of old bound result if any */
	if (ps->mysql_bind_result) {
		gint i;
		for (i = 0; i < ((GdaPStmt *) ps)->ncols; ++i) {
			g_free (ps->mysql_bind_result[i].buffer);
			g_free (ps->mysql_bind_result[i].is_null);
			g_free (ps->mysql_bind_result[i].length);
		}
		g_free (ps->mysql_bind_result);
		ps->mysql_bind_result = NULL;
	}

	/* fill bind result */
	MYSQL_RES *mysql_res = mysql_stmt_result_metadata (ps->mysql_stmt);
	MYSQL_FIELD *mysql_fields = mysql_fetch_fields (mysql_res);
	
	MYSQL_BIND *mysql_bind_result = g_new0 (MYSQL_BIND, GDA_PSTMT (ps)->ncols);
	GSList *list;

	for (i=0, list = _GDA_PSTMT (ps)->tmpl_columns; 
	     i < GDA_PSTMT (ps)->ncols; 
	     i++, list = list->next) {
		GdaColumn *column = GDA_COLUMN (list->data);
		
		/* use C API to set columns' information using gda_column_set_*() */
		MYSQL_FIELD *field = &mysql_fields[i];
		
		GType gtype = _GDA_PSTMT(ps)->types[i];
		if (gtype == GDA_TYPE_NULL) {
			gtype = _gda_mysql_type_to_gda (cdata, field->type, field->charsetnr);
			_GDA_PSTMT(ps)->types[i] = gtype;
		}
		gda_column_set_g_type (column, gtype);
		gda_column_set_name (column, field->name);
		gda_column_set_description (column, field->name);
		
		/* binding results with types */
		mysql_bind_result[i].buffer_type = field->type;
		mysql_bind_result[i].is_unsigned = field->flags & UNSIGNED_FLAG ? TRUE : FALSE;
		mysql_bind_result[i].is_null = g_malloc0 (sizeof (my_bool));
		
		switch (mysql_bind_result[i].buffer_type) {
		case MYSQL_TYPE_TINY:
			mysql_bind_result[i].buffer = g_malloc0 (sizeof (signed char));
			break;
		case MYSQL_TYPE_SHORT:
			mysql_bind_result[i].buffer = g_malloc0 (sizeof (short int));
			break;
		case MYSQL_TYPE_INT24:
		case MYSQL_TYPE_LONG:
		case MYSQL_TYPE_YEAR:
			mysql_bind_result[i].buffer = g_malloc0 (sizeof (int));
			break;
		case MYSQL_TYPE_LONGLONG:
			mysql_bind_result[i].buffer = g_malloc0 (sizeof (long long));
			break;
		case MYSQL_TYPE_NULL:
			break;
		case MYSQL_TYPE_TIME:
		case MYSQL_TYPE_DATE:
		case MYSQL_TYPE_DATETIME:
		case MYSQL_TYPE_TIMESTAMP:
			mysql_bind_result[i].buffer = g_malloc0 (sizeof (MYSQL_TIME));
			break;
		case MYSQL_TYPE_FLOAT:
		case MYSQL_TYPE_DOUBLE:
			mysql_bind_result[i].buffer = g_malloc0 (sizeof (double));
			break;
		case MYSQL_TYPE_STRING:
		case MYSQL_TYPE_VAR_STRING:
		case MYSQL_TYPE_BLOB:
		case MYSQL_TYPE_TINY_BLOB:
		case MYSQL_TYPE_MEDIUM_BLOB:
		case MYSQL_TYPE_LONG_BLOB:
		case MYSQL_TYPE_DECIMAL:
		case MYSQL_TYPE_NEWDECIMAL:
		case MYSQL_TYPE_BIT:
			mysql_bind_result[i].buffer = g_malloc0 (field->max_length + 1);
			mysql_bind_result[i].buffer_length = field->max_length + 1;
			mysql_bind_result[i].length = g_malloc0 (sizeof (unsigned long));
			break;
		default:
			g_warning (_("Invalid column bind data type. %d\n"),
				   mysql_bind_result[i].buffer_type);
		}
		/*g_print ("%s(): NAME=%s, TYPE=%d, GTYPE=%s, unsigned: %d\n",
			 __FUNCTION__, field->name, field->type, g_type_name (gtype),
			 field->flags & UNSIGNED_FLAG);*/
	}
	
	if (mysql_stmt_bind_result (ps->mysql_stmt, mysql_bind_result)) {
		g_warning ("mysql_stmt_bind_result failed: %s\n",
			   mysql_stmt_error (ps->mysql_stmt));
	}
	
	mysql_free_result (mysql_res);
	ps->mysql_bind_result = mysql_bind_result;

	/* determine access mode: RANDOM or CURSOR FORWARD are the only supported */
	if (flags & GDA_DATA_MODEL_ACCESS_RANDOM)
		rflags = GDA_DATA_MODEL_ACCESS_RANDOM;
	else
		rflags = GDA_DATA_MODEL_ACCESS_CURSOR_FORWARD;

	/* create data model */
        model = g_object_new (GDA_TYPE_MYSQL_RECORDSET,
			      "connection", cnc,
			      "prepared-stmt", ps,
			      "model-usage", rflags,
			      "exec-params", exec_params, 
			      NULL);
        model->priv->cnc = cnc;
	g_object_ref (G_OBJECT(cnc));

	model->priv->mysql_stmt = ps->mysql_stmt;

	((GdaDataSelect *) model)->advertized_nrows = mysql_stmt_affected_rows (ps->mysql_stmt);

        return GDA_DATA_MODEL (model);
}
Пример #26
0
/*
 * Get and convert columns from a result
 */
int db_mysql_get_columns(db_con_t* _h, db_res_t* _r)
{
	int n, i;
	MYSQL_FIELD* fields;

	if ((!_h) || (!_r)) {
		LM_ERR("invalid parameter\n");
		return -1;
	}

	n = mysql_field_count(CON_CONNECTION(_h));
	if (!n) {
		LM_ERR("no columns\n");
		return -2;
	}
	
    RES_NAMES(_r) = (db_key_t*)pkg_malloc(sizeof(db_key_t) * n);
	if (!RES_NAMES(_r)) {
		LM_ERR("no private memory left\n");
		return -3;
	}

	RES_TYPES(_r) = (db_type_t*)pkg_malloc(sizeof(db_type_t) * n);
	if (!RES_TYPES(_r)) {
		LM_ERR("no private memory left\n");
		pkg_free(RES_NAMES(_r));
		return -4;
	}

	RES_COL_N(_r) = n;

	fields = mysql_fetch_fields(CON_RESULT(_h));
	for(i = 0; i < n; i++) {
		RES_NAMES(_r)[i] = fields[i].name;
		switch(fields[i].type) {
		case FIELD_TYPE_TINY:
		case FIELD_TYPE_SHORT:
		case FIELD_TYPE_LONG:
		case FIELD_TYPE_INT24:
		case FIELD_TYPE_LONGLONG:
		case FIELD_TYPE_DECIMAL:
		case FIELD_TYPE_TIMESTAMP:
			RES_TYPES(_r)[i] = DB_INT;
			break;

		case FIELD_TYPE_FLOAT:
		case FIELD_TYPE_DOUBLE:
			RES_TYPES(_r)[i] = DB_DOUBLE;
			break;

		case FIELD_TYPE_DATETIME:
			RES_TYPES(_r)[i] = DB_DATETIME;
			break;

		case FIELD_TYPE_BLOB:
		case FIELD_TYPE_TINY_BLOB:
		case FIELD_TYPE_MEDIUM_BLOB:
		case FIELD_TYPE_LONG_BLOB:
			RES_TYPES(_r)[i] = DB_BLOB;
			break;

		case FIELD_TYPE_SET:
			RES_TYPES(_r)[i] = DB_BITMAP;
			break;

		default:
			RES_TYPES(_r)[i] = DB_STRING;
			break;
		}		
	}
	return 0;
}
Пример #27
0
DDatabaseResult & DMySQL::exec ( const DString & query )
{
	MYSQL_RES *results;
	MYSQL_FIELD *fields;
	MYSQL_ROW row;
	m_result.clear();
	int errnb;
	uint num_fields;
	unsigned long *lengths;
	DDatabaseRow row_result;
	my_ulonglong llu;
	DString buffer;
	bool closeConnection = false;
	long int old_errnb;

	m_result.clear();

	// If connection was not initialized, try to open it
	if ( !m_opened || m_mysql == 0 )
	{
		closeConnection = true;
		open();
		// If connection was not initialized, quit
		if ( !m_opened || m_mysql == 0 )
		{
			m_result.errnb = NOT_CONNECTED;
			m_result.error = _errors[NOT_CONNECTED];
#ifdef WITH_EXCEPTIONS
			if ( m_use_dexceptions )
			{
				throw DEXCEPTION_DB ( m_result.error, m_result.errnb );
			}
#endif
			return this->m_result;
		}
	}
	m_result.last_query = query;

	// If connection was lose, exit
	errnb = mysql_ping ( m_mysql );
	if ( errnb )
	{
		m_result.errnb = CONNECTION_LOSE;
		m_result.error = _errors[CONNECTION_LOSE];
#ifdef WITH_EXCEPTIONS
		if ( m_use_dexceptions )
		{
			throw DEXCEPTION_DB ( m_result.error, m_result.errnb );
		}
#endif
		return this->m_result;
	}

	// execute query
	errnb = mysql_real_query ( m_mysql, query.c_str(), query.length() );

	if ( errnb ) // if query was not executed
	{
		m_result.errnb = QUERY_ERROR;
		m_result.error = mysql_error ( m_mysql );
#ifdef WITH_EXCEPTIONS
		if ( m_use_dexceptions )
		{
			throw DEXCEPTION_DB ( m_result.error, m_result.errnb );
		}
#endif
		return this->m_result;
	}
	// Get the last AUTO_INCREMENT
	llu = mysql_insert_id ( m_mysql );
	m_result.last_auto_increment = static_cast<long long unsigned int> ( llu );

	// Get the number of affected rows
	llu = mysql_affected_rows ( m_mysql );
	if ( llu != static_cast<my_ulonglong>(-1) )
	{
		m_result.affected_row = static_cast<long long unsigned int> ( llu );
	}

	// Get info
	// We must pass via a const char * because the pointer can be null
	// (in case of not infos are available).
	const char* str = mysql_info ( m_mysql );
	if ( str )
	{
		m_result.info = str;
	}
	else
	{
		m_result.info = "";
	}

	// Get the number of fields
	num_fields = mysql_field_count ( m_mysql );

	// Get results of query if any
	results = mysql_store_result ( m_mysql );
	if ( results )
	{
		// Get field names
		fields = mysql_fetch_fields ( results );
		while ( ( row = mysql_fetch_row ( results ) ) )
		{
			// Get the length of data by index
			lengths = mysql_fetch_lengths ( results );
			for ( unsigned int i = 0 ; i < num_fields ; i++ )
			{
				if ( lengths[i] == 0 )
				{
					buffer = "NULL";
				}
				else
				{
					buffer = row[i];
				}
				// Affect data to field name
				row_result[fields[i].name] = buffer;
			}
			m_result.rows.push_back ( row_result );
		}
		// free the result memory
		mysql_free_result ( results );
		m_result.errnb = SUCCESS;
	}
	else
	{
		if ( num_fields > 0 )
		{
			m_result.errnb = UNKNOW_ERROR;
			m_result.error = mysql_error ( m_mysql );
		}
		else
		{
			m_result.errnb = SUCCESS;
		}
	}

	if ( closeConnection )
	{
		old_errnb = m_result.errnb;
		close();
		m_result.errnb = old_errnb;
	}

	return this->m_result;
}
Пример #28
0
/*!
 * \brief Get and convert columns from a result
 *
 * Get and convert columns from a result, fills the result structure
 * with data from the database.
 * \param _h database connection
 * \param _r database result set
 * \return 0 on success, negative on failure
 */
int db_mysql_get_columns(const db1_con_t* _h, db1_res_t* _r)
{
	int col;
	MYSQL_FIELD* fields;

	if ((!_h) || (!_r)) {
		LM_ERR("invalid parameter\n");
		return -1;
	}

	RES_COL_N(_r) = mysql_field_count(CON_CONNECTION(_h));
	if (!RES_COL_N(_r)) {
		LM_ERR("no columns returned from the query\n");
		return -2;
	} else {
		LM_DBG("%d columns returned from the query\n", RES_COL_N(_r));
	}
	
	if (db_allocate_columns(_r, RES_COL_N(_r)) != 0) {
		RES_COL_N(_r) = 0;
		LM_ERR("could not allocate columns\n");
		return -3;
	}

	fields = mysql_fetch_fields(RES_RESULT(_r));
	for(col = 0; col < RES_COL_N(_r); col++) {
		RES_NAMES(_r)[col] = (str*)pkg_malloc(sizeof(str));
		if (! RES_NAMES(_r)[col]) {
			LM_ERR("no private memory left\n");
			db_free_columns(_r);
			return -4;
		}
		LM_DBG("allocate %lu bytes for RES_NAMES[%d] at %p\n",
				(unsigned long)sizeof(str), col, RES_NAMES(_r)[col]);

		/* The pointer that is here returned is part of the result structure. */
		RES_NAMES(_r)[col]->s = fields[col].name;
		RES_NAMES(_r)[col]->len = strlen(fields[col].name);

		LM_DBG("RES_NAMES(%p)[%d]=[%.*s]\n", RES_NAMES(_r)[col], col,
				RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s);

		switch(fields[col].type) {
			case MYSQL_TYPE_TINY:
			case MYSQL_TYPE_SHORT:
			case MYSQL_TYPE_LONG:
			case MYSQL_TYPE_INT24:
			case MYSQL_TYPE_TIMESTAMP:
				LM_DBG("use DB1_INT result type\n");
				RES_TYPES(_r)[col] = DB1_INT;
				break;

			case MYSQL_TYPE_LONGLONG:
				LM_DBG("use DB1_BIGINT result type\n");
				RES_TYPES(_r)[col] = DB1_BIGINT;
				break;

			case MYSQL_TYPE_FLOAT:
			case MYSQL_TYPE_DOUBLE:
				LM_DBG("use DB1_DOUBLE result type\n");
				RES_TYPES(_r)[col] = DB1_DOUBLE;
				break;

			case MYSQL_TYPE_DATETIME:
				LM_DBG("use DB1_DATETIME result type\n");
				RES_TYPES(_r)[col] = DB1_DATETIME;
				break;

			case MYSQL_TYPE_BLOB:
				LM_DBG("use DB1_BLOB result type\n");
				RES_TYPES(_r)[col] = DB1_BLOB;
				break;

			case FIELD_TYPE_SET:
				LM_DBG("use DB1_BITMAP result type\n");
				RES_TYPES(_r)[col] = DB1_BITMAP;
				break;

			case MYSQL_TYPE_DECIMAL:
			#if MYSQL_VERSION_ID > 49999
			case MYSQL_TYPE_NEWDECIMAL:
			#endif
			case MYSQL_TYPE_STRING:
			case MYSQL_TYPE_VAR_STRING:
				LM_DBG("use DB1_STRING result type\n");
				RES_TYPES(_r)[col] = DB1_STRING;
				break;

			default:
				LM_WARN("unhandled data type column (%.*s) type id (%d), "
						"use DB1_STRING as default\n", RES_NAMES(_r)[col]->len,
						RES_NAMES(_r)[col]->s, fields[col].type);
				RES_TYPES(_r)[col] = DB1_STRING;
				break;
		}
	}
	return 0;
}
Пример #29
0
/**
 * Get and convert columns from a result
 */
int db_mysql_get_columns(const db_con_t* _h, db_res_t* _r)
{
	int col;
	MYSQL_FIELD* fields;

	if ((!_h) || (!_r)) {
		LM_ERR("invalid parameter\n");
		return -1;
	}

	if (CON_HAS_PS(_h)) {
		RES_COL_N(_r) = CON_MYSQL_PS(_h)->cols_out;
	} else {
		RES_COL_N(_r) = mysql_field_count(CON_CONNECTION(_h));
	}
	if (!RES_COL_N(_r)) {
		LM_ERR("no columns returned from the query\n");
		return -2;
	} else {
		LM_DBG("%d columns returned from the query\n", RES_COL_N(_r));
	}
	
	if (db_allocate_columns(_r, RES_COL_N(_r)) != 0) {
		LM_ERR("could not allocate columns\n");
		return -3;
	}

	fields = mysql_fetch_fields(CON_RESULT(_h));
	for(col = 0; col < RES_COL_N(_r); col++) {
		/* The pointer that is here returned is part of the result structure */
		RES_NAMES(_r)[col]->s = fields[col].name;
		RES_NAMES(_r)[col]->len = strlen(fields[col].name);

		LM_DBG("RES_NAMES(%p)[%d]=[%.*s]\n", RES_NAMES(_r)[col], col,
				RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s);

		switch(fields[col].type) {
			case MYSQL_TYPE_TINY:
			case MYSQL_TYPE_SHORT:
			case MYSQL_TYPE_LONG:
			case MYSQL_TYPE_INT24:
			case MYSQL_TYPE_DECIMAL:
			#if MYSQL_VERSION_ID > 49999
			case MYSQL_TYPE_NEWDECIMAL:
			#endif
			case MYSQL_TYPE_TIMESTAMP:
				LM_DBG("use DB_INT result type\n");
				RES_TYPES(_r)[col] = DB_INT;
				break;

			case MYSQL_TYPE_FLOAT:
			case MYSQL_TYPE_DOUBLE:
				LM_DBG("use DB_DOUBLE result type\n");
				RES_TYPES(_r)[col] = DB_DOUBLE;
				break;

			case MYSQL_TYPE_DATETIME:
			case MYSQL_TYPE_DATE:
				LM_DBG("use DB_DATETIME result type\n");
				RES_TYPES(_r)[col] = DB_DATETIME;
				break;

			case MYSQL_TYPE_TINY_BLOB:
			case MYSQL_TYPE_MEDIUM_BLOB:
			case MYSQL_TYPE_LONG_BLOB:
			case MYSQL_TYPE_BLOB:
				LM_DBG("use DB_BLOB result type\n");
				RES_TYPES(_r)[col] = DB_BLOB;
				break;

			case FIELD_TYPE_SET:
				LM_DBG("use DB_BITMAP result type\n");
				RES_TYPES(_r)[col] = DB_BITMAP;
				break;

			case MYSQL_TYPE_STRING:
			case MYSQL_TYPE_VAR_STRING:
				LM_DBG("use DB_STRING result type\n");
				RES_TYPES(_r)[col] = DB_STRING;
				break;

			case MYSQL_TYPE_LONGLONG:
				LM_DBG("use DB_BIGINT result type\n");
				RES_TYPES(_r)[col] = DB_BIGINT;
				break;

			default:
				LM_WARN("unhandled data type column (%.*s) type id (%d), "
						"use DB_STRING as default\n", RES_NAMES(_r)[col]->len,
						RES_NAMES(_r)[col]->s, fields[col].type);
				RES_TYPES(_r)[col] = DB_STRING;
				break;
		}
	}
	return 0;
}
Пример #30
0
Tipo_Data *GetOneRecordAsinc(int id,int nSocket,char szSql[])
{
        MYSQL_RES *res=NULL;
        char szAux[MAX_BUFFER];
        int i;
        int nIntentos;
        nIntentos=0;
        time_t  time1,time2;
        int nLen;
	MYSQL_ROW row;
	MYSQL_FIELD *fields;
	Tipo_Data *pData=NULL;
	int num_fields;
reintenta:
        if (Conexion[id].nAbierta==0)
        {
                if (!Conexion[id].nAbierta)
               {
                            WriteError(id,"Abre Conexion BD");
                            Conexion[id].pMysqlconn=OpenDatabase(id,global.szBaseDatos,global.szIpBd,global.szPortPostgres);
               }
               if (Conexion[id].pMysqlconn==NULL)
               {
                             WriteError(id,"Falla Conexion BD");
                             return pData;
               }
               Conexion[id].nAbierta=1;
        }

	
	//sprintf(szAux,"SQL=%s Len=%i",szSql,strlen(szSql));
	//WriteLog(id,szAux);
	if ( mysql_real_query(Conexion[id].pMysqlconn,szSql,strlen(szSql)) != 0)
	{
            sprintf(szAux,"Error en PQsendQuery Mysql %s",mysql_error(Conexion[id].pMysqlconn));
            WriteLog(id,szAux);
            WriteError(id,szAux);
            fprintf(stderr, "Falla Envio de Query %s\n\r",mysql_error(Conexion[id].pMysqlconn));
	
	
            //Vamos a reabrir la conexion a la base de datos
            if (nIntentos++<2)
            {
                WriteError(id,"Reintento");
                WriteLog(id,"Reintento");
                //PQclear(res);
                CierraMysql(id);
                Conexion[id].pMysqlconn=OpenDatabase(id,global.szBaseDatos,global.szIpBd,global.szPortPostgres);
                if (Conexion[id].pMysqlconn==NULL)
                {
                        WriteLog(id,"FALLA_RECONEXION_BD");
                        Conexion[id].nAbierta=0;
                        return pData;
                }
                else
                {
                        WriteError(id,"Conexion OK");
                        WriteLog(id,"Conexion OK");
               		Conexion[id].nAbierta=1;
                        goto reintenta;
                }
             }
             else
             {
                WriteLog(id,"FALLA_FIN_REINTENTOS");
		CierraMysql(id);
                return pData;
             }
            return pData;
        }
	do
	{

        	time(&time1);
		res=mysql_use_result(Conexion[id].pMysqlconn);
		if (res==NULL)
		{	
			//WriteError(id,"Error al obtener resultado");
			mysql_free_result(res);
			return NULL;
			//CierraMysql(id);
			//return pData;
		}
	
        	num_fields = mysql_num_fields(res);

		while ((row = mysql_fetch_row(res)) != NULL)
		{
   			unsigned long *lengths;
			WriteLog(id,"Entre");
   			lengths = mysql_fetch_lengths(res);
			fields = mysql_fetch_fields(res);
			//Nombre del campo
   			for(i = 0; i < num_fields; i++) 
			{
				pData=InsertaData("<STATUS>OK</STATUS>",pData);
				pData=InsertaDataLen("<",1,pData);
				pData=InsertaData(fields[i].name,pData);
				pData=InsertaDataLen(">",1,pData);
				pData=InsertaDataLen(row[i],(int) lengths[i],pData);
				pData=InsertaDataLen("</",2,pData);
				pData=InsertaData(fields[i].name,pData);
				pData=InsertaDataLen(">",1,pData);
	   		}	
			SendSocket(id,nSocket,pData->data,strlen(pData->data));
			pData=LiberaData(pData);
		}
	} while (mysql_next_result(Conexion[id].pMysqlconn)==0);
	//sprintf(szAux,"Puntero2=%x",Conexion[id].pMysqlconn);
	//WriteLog(id,szAux);
	mysql_free_result(res);
	return NULL;
}