Esempio n. 1
0
bool wxSqliteDatabase::Open(const wxString& strDatabase)
{
  ResetErrorCodes();

  //if (m_pDatabase == NULL)
  //  m_pDatabase = new sqlite3;

  wxCharBuffer databaseNameBuffer = ConvertToUnicodeStream(strDatabase);
  sqlite3* pDbPtr = (sqlite3*)m_pDatabase;
  int nReturn = sqlite3_open(databaseNameBuffer, &pDbPtr);
  m_pDatabase = pDbPtr;
  if (nReturn != SQLITE_OK)
  {
    SetErrorCode(wxSqliteDatabase::TranslateErrorCode(sqlite3_errcode((sqlite3*)m_pDatabase)));
    SetErrorMessage(ConvertFromUnicodeStream(sqlite3_errmsg((sqlite3*)m_pDatabase)));
    ThrowDatabaseException();
    return false;
  }
  return true;
}
// query database
int SqliteDatabaseLayer::RunQuery(const wxString& strQuery, bool bParseQuery)
{
  ResetErrorCodes();

  if (m_pDatabase == NULL)
    return false;

  wxArrayString QueryArray;
  if (bParseQuery)
    QueryArray = ParseQueries(strQuery);
  else
    QueryArray.push_back(strQuery);

  wxArrayString::iterator start = QueryArray.begin();
  wxArrayString::iterator stop = QueryArray.end();

  while (start != stop)
  {
    char* szErrorMessage = NULL;
    wxString strErrorMessage = _("");
    wxCharBuffer sqlBuffer = ConvertToUnicodeStream(*start);
    int nReturn = sqlite3_exec((sqlite3*)m_pDatabase, sqlBuffer, 0, 0, &szErrorMessage);
  
    if (szErrorMessage != NULL)
    {
      strErrorMessage = ConvertFromUnicodeStream(szErrorMessage);
      sqlite3_free(szErrorMessage);
    }

    if (nReturn != SQLITE_OK)
    {
      SetErrorCode(SqliteDatabaseLayer::TranslateErrorCode(sqlite3_errcode((sqlite3*)m_pDatabase)));
      SetErrorMessage(strErrorMessage);
      ThrowDatabaseException();
      return DATABASE_LAYER_QUERY_RESULT_ERROR;
    }

    start++;
  }
  return (sqlite3_changes((sqlite3*)m_pDatabase));
}
Esempio n. 3
0
// query database
int TdsDatabaseLayer::RunQuery(const wxString& strQuery, bool bParseQuery)
{
  ResetErrorCodes();

  if (m_pDatabase == NULL)
    return false;

  FreeAllocatedResultSets();

  wxArrayString QueryArray;
  if (bParseQuery)
    QueryArray = ParseQueries(strQuery);
  else
    QueryArray.push_back(strQuery);

  wxArrayString::iterator start = QueryArray.begin();
  wxArrayString::iterator stop = QueryArray.end();

  while (start != stop)
  {
    char* szErrorMessage = NULL;
    wxString strErrorMessage = wxT("");
    wxString sql = RemoveLastSemiColon(*start);
    wxCharBuffer sqlBuffer = ConvertToUnicodeStream(sql);

    //fprintf(stderr, "Running query '%s'\n", (const char*)sqlBuffer);
    int nReturn = tds_submit_query(m_pDatabase, sqlBuffer);
    if (nReturn != TDS_SUCCEED)
    {
      //fprintf(stderr, "tds_submit_query() failed for query '%s'\n", sqlBuffer);
      //fprintf(stderr, "tds_submit_query() failed for query '%s'\n", (sql).c_str());
      FreeAllocatedResultSets();
      ThrowDatabaseException();
      return false;
    }
    FreeAllocatedResultSets();

    start++;
  }
  return true;
}
Esempio n. 4
0
// PreparedStatement support
PreparedStatement* OTLDatabaseLayer::PrepareStatement(const wxString& strQuery)
{
    OTLPreparedStatement* pStatement = NULL;
    try
    {
        wxArrayString QueryArray = ParseQueries(strQuery);

        wxArrayString::iterator start = QueryArray.begin();
        wxArrayString::iterator stop = QueryArray.end();

        while (start != stop)
        {
            wxCharBuffer sqlBuffer = ConvertToUnicodeStream((*start));
            std::string strSQL(sqlBuffer);
            //fixme
            /*
               OTL::occi::Statement* pOTLStatement = m_pDatabase->createStatement(strSQL);
               if (pOTLStatement)
               {
                 pOTLStatement->setAutoCommit(m_bAutoCommit);
                 pStatement->AddStatement(pOTLStatement);
               }
            */
            start++;
        }
    }
    catch (otl_exception& e)
    {
        SetErrorCode(OTLDatabaseLayer::TranslateErrorCode(e.code));
        SetErrorMessage(ConvertFromUnicodeStream((char*)e.msg));
        wxDELETE(pStatement);
        ThrowDatabaseException();
        return NULL;
    }

    if (pStatement)
        LogStatementForCleanup(pStatement);

    return pStatement;
}
Esempio n. 5
0
wxPreparedStatement* wxOdbcDatabase::PrepareStatement( const wxString& strQuery, bool bParseQuery )
{
    ResetErrorCodes();

    wxArrayString QueryArray;
    if (bParseQuery)
      QueryArray = ParseQueries(strQuery);
    else
      QueryArray.push_back(strQuery);

    wxOdbcPreparedStatement* pReturnStatement = new wxOdbcPreparedStatement(m_pInterface, (SQLHENV)m_sqlEnvHandle, (SQLHDBC)m_sqlHDBC);

    if (pReturnStatement)
        pReturnStatement->SetEncoding(GetEncoding());

    for (unsigned int i=0; i<(QueryArray.size()); i++)
    {
//#if wxUSE_UNICODE
//        void* sqlBuffer = (void*)(QueryArray[i].c_str());
//#else
        wxCharBuffer sqlBuffer = ConvertToUnicodeStream(QueryArray[i]);
//#endif
        //wxPrintf(_("Preparing statement: '%s'\n"), sqlBuffer);

        SQLHSTMT pSqlStatement = allocStmth();
        SQLRETURN nRet = m_pInterface->GetSQLPrepare()(pSqlStatement, (SQLTCHAR*)(const char*)sqlBuffer, SQL_NTS);
        if ( nRet != SQL_SUCCESS && nRet != SQL_SUCCESS_WITH_INFO )
        {
            InterpretErrorCodes( nRet );
            m_pInterface->GetSQLFreeStmt()(pSqlStatement, SQL_CLOSE);
            ThrowDatabaseException();
            return NULL;
        }

        if ( pSqlStatement )
            pReturnStatement->AddPreparedStatement( pSqlStatement );
    }

    return pReturnStatement;
}
Esempio n. 6
0
wxDatabaseResultSet* wxPostgresDatabase::RunQueryWithResults(const wxString& strQuery)
{
    ResetErrorCodes();

    wxCharBuffer sqlBuffer = ConvertToUnicodeStream(strQuery);
    PGresult* pResultCode = m_pInterface->GetPQexec()((PGconn*)m_pDatabase, sqlBuffer);
    if ((pResultCode == NULL) || (m_pInterface->GetPQresultStatus()(pResultCode) != PGRES_TUPLES_OK))
    {
        SetErrorCode(wxPostgresDatabase::TranslateErrorCode(m_pInterface->GetPQstatus()((PGconn*)m_pDatabase)));
        SetErrorMessage(ConvertFromUnicodeStream(m_pInterface->GetPQerrorMessage()((PGconn*)m_pDatabase)));
        m_pInterface->GetPQclear()(pResultCode);
        ThrowDatabaseException();
        return NULL;
    }
    else
    {
        wxPostgresResultSet* pResultSet = new wxPostgresResultSet(m_pInterface, pResultCode);
        pResultSet->SetEncoding(GetEncoding());
        LogResultSetForCleanup(pResultSet);
        return pResultSet;
    }
}
int PostgresPreparedStatementWrapper::RunQuery()
{
  long nRows = -1;
  int nParameters = m_Parameters.GetSize();
  char** paramValues = m_Parameters.GetParamValues();
  int* paramLengths = m_Parameters.GetParamLengths();
  int* paramFormats = m_Parameters.GetParamFormats();
  int nResultFormat = 0; // 0 = text, 1 = binary (all or none on the result set, not column based)
  wxCharBuffer statementNameBuffer = ConvertToUnicodeStream(m_strStatementName);
  PGresult* pResult = m_pInterface->GetPQexecPrepared()(m_pDatabase, statementNameBuffer, nParameters, paramValues, paramLengths, paramFormats, nResultFormat);
  if (pResult != NULL)
  {
    ExecStatusType status = m_pInterface->GetPQresultStatus()(pResult);
    if ((status != PGRES_COMMAND_OK) && (status != PGRES_TUPLES_OK))
    {
      SetErrorCode(PostgresDatabaseLayer::TranslateErrorCode(status));
      SetErrorMessage(ConvertFromUnicodeStream(m_pInterface->GetPQresultErrorMessage()(pResult)));
    }

    if (GetErrorCode() == DATABASE_LAYER_OK)
    {
      wxString rowsAffected = ConvertFromUnicodeStream(m_pInterface->GetPQcmdTuples()(pResult));
      rowsAffected.ToLong(&nRows);
    }
    m_pInterface->GetPQclear()(pResult);
  }
  delete []paramValues;
  delete []paramLengths;
  delete []paramFormats;

  if (GetErrorCode() != DATABASE_LAYER_OK)
  {
    ThrowDatabaseException();
    return DATABASE_LAYER_QUERY_RESULT_ERROR;
  }

  return (int)nRows;
}
DatabaseResultSet* PostgresPreparedStatementWrapper::RunQueryWithResults()
{
  int nParameters = m_Parameters.GetSize();
  char** paramValues = m_Parameters.GetParamValues();
  int* paramLengths = m_Parameters.GetParamLengths();
  int* paramFormats = m_Parameters.GetParamFormats();
  int nResultFormat = 0; // 0 = text, 1 = binary (all or none on the result set, not column based)
  wxCharBuffer statementNameBuffer = ConvertToUnicodeStream(m_strStatementName);
  PGresult* pResult = m_pInterface->GetPQexecPrepared()(m_pDatabase, statementNameBuffer, nParameters, paramValues, paramLengths, paramFormats, nResultFormat);
  if (pResult != NULL)
  {
    ExecStatusType status = m_pInterface->GetPQresultStatus()(pResult);
    if ((status != PGRES_COMMAND_OK) && (status != PGRES_TUPLES_OK))
    {
      SetErrorCode(PostgresDatabaseLayer::TranslateErrorCode(status));
      SetErrorMessage(ConvertFromUnicodeStream(m_pInterface->GetPQresultErrorMessage()(pResult)));
    }
    else
    {
      delete []paramValues;
      delete []paramLengths;
      delete []paramFormats;

      PostgresResultSet* pResultSet = new PostgresResultSet(m_pInterface, pResult);
      pResultSet->SetEncoding(GetEncoding());
      return pResultSet;
    }
    m_pInterface->GetPQclear()(pResult);
  }
  delete []paramValues;
  delete []paramLengths;
  delete []paramFormats;

  ThrowDatabaseException();

  return NULL;
}
void wxSqlitePreparedStatement::SetParamDate(int nPosition, const wxDateTime& dateValue)
{
  ResetErrorCodes();

  if (dateValue.IsValid())
  {
    int nIndex = FindStatementAndAdjustPositionIndex(&nPosition);
    if (nIndex > -1)
    {
      sqlite3_reset(m_Statements[nIndex]);
      wxCharBuffer valueBuffer = ConvertToUnicodeStream(dateValue.Format(_("%Y-%m-%d %H:%M:%S")));
      int nReturn = sqlite3_bind_text(m_Statements[nIndex], nPosition, valueBuffer, -1, SQLITE_TRANSIENT);
      if (nReturn != SQLITE_OK)
      {
        SetErrorCode(wxSqliteDatabase::TranslateErrorCode(nReturn));
        SetErrorMessage(ConvertFromUnicodeStream(sqlite3_errmsg(m_pDatabase)));
        ThrowDatabaseException();
      }
    }
  }
  else
  {
    int nIndex = FindStatementAndAdjustPositionIndex(&nPosition);
    if (nIndex > -1)
    {
      sqlite3_reset(m_Statements[nIndex]);
      int nReturn = sqlite3_bind_null(m_Statements[nIndex], nPosition);
      if (nReturn != SQLITE_OK)
      {
        SetErrorCode(wxSqliteDatabase::TranslateErrorCode(nReturn));
        SetErrorMessage(ConvertFromUnicodeStream(sqlite3_errmsg(m_pDatabase)));
        ThrowDatabaseException();
      }
    }
  }
}
Esempio n. 10
0
void* wxOdbcParameter::GetDataPtr()
{
  const void *pReturn = NULL;
  
  switch (m_nParameterType)
  {
    case wxOdbcParameter::PARAM_STRING:
      m_CharBufferValue = ConvertToUnicodeStream(m_strValue);
      pReturn = m_CharBufferValue;
      //wxPrintf(_("Parameter: '%s'\n"), m_strValue.c_str());
      //pReturn = m_strValue.c_str();
      break;
    case wxOdbcParameter::PARAM_INT:
      pReturn = &m_nValue;
      break;
    case wxOdbcParameter::PARAM_DOUBLE:
      pReturn = &m_dblValue;
      break;
    case wxOdbcParameter::PARAM_DATETIME:
      pReturn = &m_DateValue;
      break;
    case wxOdbcParameter::PARAM_BOOL:
      pReturn = &m_bValue;
      break;
    case wxOdbcParameter::PARAM_BLOB:
      pReturn = m_BufferValue.GetData();
      break;
    case wxOdbcParameter::PARAM_NULL:
      pReturn = NULL;
      break;
    default:
      pReturn = NULL;
      break;
  };
  return (void*)pReturn;
}
Esempio n. 11
0
PreparedStatement* SqliteDatabaseLayer::PrepareStatement(const wxString& strQuery, bool bLogForCleanup)
{
  ResetErrorCodes();

  if (m_pDatabase != NULL)
  {
    SqlitePreparedStatement* pReturnStatement = new SqlitePreparedStatement((sqlite3*)m_pDatabase);
    if (pReturnStatement)
      pReturnStatement->SetEncoding(GetEncoding());
    
    wxArrayString QueryArray = ParseQueries(strQuery);

    wxArrayString::iterator start = QueryArray.begin();
    wxArrayString::iterator stop = QueryArray.end();

    while (start != stop)
    {
      const char* szTail=0;
      wxCharBuffer sqlBuffer;
      do
      {
        sqlite3_stmt* pStatement;
        wxString strSQL;
        if (szTail != 0)
        {
          strSQL = (wxChar*)szTail;
        }
        else
        {
          strSQL = (*start);
        }
        sqlBuffer = ConvertToUnicodeStream(strSQL);
#if SQLITE_VERSION_NUMBER>=3003009
        int nReturn = sqlite3_prepare_v2((sqlite3*)m_pDatabase, sqlBuffer, -1, &pStatement, &szTail);
#else
        int nReturn = sqlite3_prepare((sqlite3*)m_pDatabase, sqlBuffer, -1, &pStatement, &szTail);
#endif
   
        if (nReturn != SQLITE_OK)
        {
          SetErrorCode(SqliteDatabaseLayer::TranslateErrorCode(nReturn));
          SetErrorMessage(ConvertFromUnicodeStream(sqlite3_errmsg((sqlite3*)m_pDatabase)));
          wxDELETE(pReturnStatement);
          ThrowDatabaseException();
          return NULL;
        }
        pReturnStatement->AddPreparedStatement(pStatement);

#if wxUSE_UNICODE
      } while (strlen(szTail) > 0);
#else
      } while (wxStrlen(szTail) > 0);
#endif    
      
      start++;
    }

    if (bLogForCleanup)
      LogStatementForCleanup(pReturnStatement);
    return pReturnStatement;
  }
Esempio n. 12
0
// open database
bool OTLDatabaseLayer::Open()
{
    try
    {
        wxString tnsString = wxT("");

        if (m_strServer != wxEmptyString)
        {
            tnsString += _("Host=") + m_strServer;
            if (m_strPort != wxEmptyString)
            {
                // Add the parameter separater (colon) if needed
                if (tnsString.length() > 0)
                    tnsString += _(";");
                tnsString += _("Port=") + m_strPort;
            }
        }
        if (m_strDatabase != wxEmptyString)
        {
            // Add the parameter separater (colon) if needed
            if (tnsString.length() > 0)
                tnsString += _(";");
            tnsString += _("Service Name=") + m_strDatabase;
        }

        wxCharBuffer tnsStringBuffer = ConvertToUnicodeStream(tnsString);
        std::string strTnsString(tnsStringBuffer);

        wxString connectString = m_strUser + wxT("/") + m_strPassword;
        if (m_strDatabase != wxEmptyString)
            connectString += wxT("@") + m_strDatabase;

        try
        {
            m_database.rlogon(connectString.mb_str());
        }
        catch (otl_exception& e)
        {
            SetErrorCode(OTLDatabaseLayer::TranslateErrorCode(e.code));
            SetErrorMessage(ConvertFromUnicodeStream((char*)e.msg));
            ThrowDatabaseException();
            return false;
        }
        catch (...)
        {
            if (GetErrorCode() == DATABASE_LAYER_OK)
            {
                SetErrorCode(DATABASE_LAYER_ERROR);
                SetErrorMessage(_("Error creating database connection"));
            }
            ThrowDatabaseException();
            return false;
        }
    }
    catch (otl_exception& e)
    {
        SetErrorCode(OTLDatabaseLayer::TranslateErrorCode(e.code));
        SetErrorMessage(ConvertFromUnicodeStream((char*)e.msg));
        ThrowDatabaseException();
        return false;
    }
    return true;
}
Esempio n. 13
0
// query database
int FirebirdDatabaseLayer::RunQuery(const wxString& strQuery, bool bParseQuery)
{
  ResetErrorCodes();
  if (m_pDatabase != NULL)
  {
    wxCharBuffer sqlDebugBuffer = ConvertToUnicodeStream(strQuery);
    //wxLogDebug(_("Running query: \"%s\"\n"), (const char*)sqlDebugBuffer);

    wxArrayString QueryArray;
    if (bParseQuery)
      QueryArray = ParseQueries(strQuery);
    else
      QueryArray.push_back(strQuery);

    wxArrayString::iterator start = QueryArray.begin();
    wxArrayString::iterator stop = QueryArray.end();

    int nRows = 1;
    if (QueryArray.size() > 0)
    {
      bool bQuickieTransaction = false;
    
      if (m_pTransaction == NULL)
      {
        // If there's no transaction is progress, run this as a quick one-timer transaction
        bQuickieTransaction = true;
      }

      if (bQuickieTransaction)
      {
        BeginTransaction();
        if (GetErrorCode() != DATABASE_LAYER_OK)
        {
          wxLogError(_("Unable to start transaction"));
          ThrowDatabaseException();
          return DATABASE_LAYER_QUERY_RESULT_ERROR;
        }
      }

      while (start != stop)
      {
        wxCharBuffer sqlBuffer = ConvertToUnicodeStream(*start);
        isc_db_handle pDatabase = (isc_db_handle)m_pDatabase;
        isc_tr_handle pTransaction = (isc_tr_handle)m_pTransaction;
        //int nReturn = m_pInterface->GetIscDsqlExecuteImmediate()(*(ISC_STATUS_ARRAY*)m_pStatus, &pDatabase, &pTransaction, 0, (char*)(const char*)sqlBuffer, SQL_DIALECT_CURRENT, NULL);
        int nReturn = m_pInterface->GetIscDsqlExecuteImmediate()(*(ISC_STATUS_ARRAY*)m_pStatus, &pDatabase, &pTransaction, GetEncodedStreamLength(*start), (char*)(const char*)sqlBuffer, SQL_DIALECT_CURRENT, NULL);
        m_pDatabase = pDatabase;
        m_pTransaction = pTransaction;
        if (nReturn != 0)
        {
          InterpretErrorCodes();
          // Manually try to rollback the transaction rather than calling the member RollBack function
          //  so that we can ignore the error messages
          isc_tr_handle pTransaction = (isc_tr_handle)m_pTransaction;
          m_pInterface->GetIscRollbackTransaction()(*(ISC_STATUS_ARRAY*)m_pStatus, &pTransaction);
          m_pTransaction = NULL;

          ThrowDatabaseException();
          return DATABASE_LAYER_QUERY_RESULT_ERROR;
        }
        start++;
      }

      if (bQuickieTransaction)
      {
        Commit();
        if (GetErrorCode() != DATABASE_LAYER_OK)
        {
          ThrowDatabaseException();
          return DATABASE_LAYER_QUERY_RESULT_ERROR;
        }
      }
    }

    return nRows;
  }
  else
  {
    wxLogError(_("Database handle is NULL"));
    return DATABASE_LAYER_QUERY_RESULT_ERROR;
  }
}
// ctor
OraclePreparedStatementWrapper::OraclePreparedStatementWrapper(oracle::occi::Connection* m_pDatabase, const wxString& strSQL)
{
  wxCharBuffer sqlBuffer = ConvertToUnicodeStream(TranslateSQL(strSQL));
  std::string strStdSQL(sqlBuffer);
  m_pStatement = m_pDatabase->createStatement(strStdSQL);
}
Esempio n. 15
0
DatabaseResultSet* FirebirdDatabaseLayer::RunQueryWithResults(const wxString& strQuery)
{
  ResetErrorCodes();
  if (m_pDatabase != NULL)
  {
    wxCharBuffer sqlDebugBuffer = ConvertToUnicodeStream(strQuery);
    //wxLogDebug(_("Running query: \"%s\""), (const char*)sqlDebugBuffer);
    
    wxArrayString QueryArray = ParseQueries(strQuery);

    if (QueryArray.size() > 0)
    {
      bool bQuickieTransaction = false;
    
      if (m_pTransaction == NULL)
      {
        // If there's no transaction is progress, run this as a quick one-timer transaction
        bQuickieTransaction = true;
      }

      if (QueryArray.size() > 1)
      {
        if (bQuickieTransaction)
        {
          BeginTransaction();
          if (GetErrorCode() != DATABASE_LAYER_OK)
          {
            wxLogError(_("Unable to start transaction"));
            ThrowDatabaseException();
            return NULL;
          }
        }
      
        // Assume that only the last statement in the array returns the result set
        for (unsigned int i=0; i<QueryArray.size()-1; i++)
        {
          RunQuery(QueryArray[i], false);
          if (GetErrorCode() != DATABASE_LAYER_OK)
          {
            ThrowDatabaseException();
            return NULL;
          }
        }
      
        // Now commit all the previous queries before calling the query that returns a result set
        if (bQuickieTransaction)
        {
          Commit();
          if (GetErrorCode() != DATABASE_LAYER_OK)
          {
            ThrowDatabaseException();
            return NULL;
          }
        }
      } // End check if there are more than one query in the array
      
      isc_tr_handle pQueryTransaction = NULL;
      bool bManageTransaction = false;
      if (bQuickieTransaction)
      {
        bManageTransaction = true;
        isc_db_handle pDatabase = (isc_db_handle)m_pDatabase;
        int nReturn = m_pInterface->GetIscStartTransaction()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction, 1, &pDatabase, 0 /*tpb_length*/, NULL/*tpb*/);
        m_pDatabase = pDatabase;
        if (nReturn != 0)
        {
          InterpretErrorCodes();
          ThrowDatabaseException();
        }
      }
      else
      {
        pQueryTransaction = m_pTransaction;
      }
      
      isc_stmt_handle pStatement = NULL;
      isc_db_handle pDatabase = (isc_db_handle)m_pDatabase;
      int nReturn = m_pInterface->GetIscDsqlAllocateStatement()(*(ISC_STATUS_ARRAY*)m_pStatus, &pDatabase, &pStatement);
      m_pDatabase = pDatabase;
      if (nReturn != 0)
      {
        InterpretErrorCodes();

        // Manually try to rollback the transaction rather than calling the member RollBack function
        //  so that we can ignore the error messages
        m_pInterface->GetIscRollbackTransaction()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction);

        ThrowDatabaseException();
        return NULL;
      }
      
      wxCharBuffer sqlBuffer = ConvertToUnicodeStream(QueryArray[QueryArray.size()-1]);
      nReturn = m_pInterface->GetIscDsqlPrepare()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction, &pStatement, 0, (char*)(const char*)sqlBuffer, SQL_DIALECT_CURRENT, NULL);
      if (nReturn != 0)
      {
        InterpretErrorCodes();

        // Manually try to rollback the transaction rather than calling the member RollBack function
        //  so that we can ignore the error messages
        m_pInterface->GetIscRollbackTransaction()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction);

        ThrowDatabaseException();
        return NULL;
      }

//--------------------------------------------------------------

      XSQLDA* pOutputSqlda = (XSQLDA*)malloc(XSQLDA_LENGTH(1));
      pOutputSqlda->sqln = 1;
      pOutputSqlda->version = SQLDA_VERSION1;

      // Make sure that we have enough space allocated for the result set
      nReturn = m_pInterface->GetIscDsqlDescribe()(*(ISC_STATUS_ARRAY*)m_pStatus, &pStatement, SQL_DIALECT_CURRENT, pOutputSqlda);
      if (nReturn != 0)
      {
        free(pOutputSqlda);
        InterpretErrorCodes();

        // Manually try to rollback the transaction rather than calling the member RollBack function
        //  so that we can ignore the error messages
        m_pInterface->GetIscRollbackTransaction()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction);

        ThrowDatabaseException();
        return NULL;
      }

      if (pOutputSqlda->sqld > pOutputSqlda->sqln)
      {
        int nColumns = pOutputSqlda->sqld;
        free(pOutputSqlda);
        pOutputSqlda = (XSQLDA*)malloc(XSQLDA_LENGTH(nColumns));
        pOutputSqlda->sqln = nColumns;
        pOutputSqlda->version = SQLDA_VERSION1;
        nReturn = m_pInterface->GetIscDsqlDescribe()(*(ISC_STATUS_ARRAY*)m_pStatus, &pStatement, SQL_DIALECT_CURRENT, pOutputSqlda);
        if (nReturn != 0)
        {
          free(pOutputSqlda);
          InterpretErrorCodes();

          // Manually try to rollback the transaction rather than calling the member RollBack function
          //  so that we can ignore the error messages
          m_pInterface->GetIscRollbackTransaction()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction);

          ThrowDatabaseException();
          return NULL;
        }
      }

      // Create the result set object
      FirebirdResultSet* pResultSet = new FirebirdResultSet(m_pInterface, m_pDatabase, pQueryTransaction, pStatement, pOutputSqlda, true, bManageTransaction);
      pResultSet->SetEncoding(GetEncoding());
      if (pResultSet->GetErrorCode() != DATABASE_LAYER_OK)
      {
        SetErrorCode(pResultSet->GetErrorCode());
        SetErrorMessage(pResultSet->GetErrorMessage());
    
        // Manually try to rollback the transaction rather than calling the member RollBack function
        //  so that we can ignore the error messages
        m_pInterface->GetIscRollbackTransaction()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction);

        // Wrap the result set deletion in try/catch block if using exceptions.
        //We want to make sure the original error gets to the user
#ifndef DONT_USE_DATABASE_LAYER_EXCEPTIONS
        try
        {
#endif
        delete pResultSet;
#ifndef DONT_USE_DATABASE_LAYER_EXCEPTIONS
        }
        catch (DatabaseLayerException& e)
        {
        }
#endif

        ThrowDatabaseException();
      }
  
      // Now execute the SQL
      nReturn = m_pInterface->GetIscDsqlExecute()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction, &pStatement, SQL_DIALECT_CURRENT, NULL);
      if (nReturn != 0)
      {
        InterpretErrorCodes();

        // Manually try to rollback the transaction rather than calling the member RollBack function
        //  so that we can ignore the error messages
        m_pInterface->GetIscRollbackTransaction()(*(ISC_STATUS_ARRAY*)m_pStatus, &pQueryTransaction);

        // Wrap the result set deletion in try/catch block if using exceptions.
        //  We want to make sure the isc_dsql_execute error gets to the user
#ifndef DONT_USE_DATABASE_LAYER_EXCEPTIONS
        try
        {
#endif
        delete pResultSet;
#ifndef DONT_USE_DATABASE_LAYER_EXCEPTIONS
        }
        catch (DatabaseLayerException& e)
        {
        }
#endif
    
        ThrowDatabaseException();
        return NULL;
      }
      
//--------------------------------------------------------------

      LogResultSetForCleanup(pResultSet);
      return pResultSet;
    }
    else
      return NULL;
  }
  else
  {
    wxLogError(_("Database handle is NULL"));
    return NULL;
  }
}
Esempio n. 16
0
// Connect to the server
bool TdsDatabaseLayer::Connect()
{
	m_pLogin = tds_alloc_login();
	if (m_pLogin == NULL)
  {
		//fprintf(stderr, "tds_alloc_login() failed.\n");
    SetError(DATABASE_LAYER_ERROR, wxT("Failed to allocate login"));
    // Reset the variables so there are not mistaken as initialized
    m_pDatabase = NULL;
    m_pLogin = NULL;
    if (m_pContext)
    {
      tds_free_context(m_pContext);
      m_pContext = NULL;
    }
    ThrowDatabaseException();
		return false;
	}
  wxCharBuffer serverBuffer = ConvertToUnicodeStream(m_strServer);
  tds_set_server(m_pLogin, serverBuffer);
  wxCharBuffer loginBuffer = ConvertToUnicodeStream(m_strLogin);
	tds_set_user(m_pLogin, loginBuffer);
  wxCharBuffer passwordBuffer = ConvertToUnicodeStream(m_strPassword);
	tds_set_passwd(m_pLogin, passwordBuffer);
	tds_set_app(m_pLogin, "DatabaseLayer");
	tds_set_library(m_pLogin, "TDS-Library");
	tds_set_client_charset(m_pLogin, "UTF-8");
  switch (m_nTdsVersion)
  {
    case TDS_42:
      tds_set_version(m_pLogin, 4, 2);
      break;
    case TDS_46:
      tds_set_version(m_pLogin, 4, 6);
      break;
    case TDS_50:
      tds_set_version(m_pLogin, 5, 0);
      break;
    case TDS_70:
      tds_set_version(m_pLogin, 7, 0);
      break;
    case TDS_80:
      tds_set_version(m_pLogin, 8, 0);
      break;
    default:
      tds_set_version(m_pLogin, 0, 0);
      break;
  };
  
	m_pContext = tds_alloc_context(NULL);
  if (m_pContext == NULL)
  {
    //fprintf(stderr, "tds_alloc_context() failed.\n");
    SetError(DATABASE_LAYER_ERROR, wxT("Failed to allocate context"));
    // Reset the variables so there are not mistaken as initialized
    m_pDatabase = NULL;
    if (m_pLogin)
    {
      tds_free_login(m_pLogin);
      m_pLogin = NULL;
    }
    if (m_pContext)
    {
      tds_free_context(m_pContext);
      m_pContext = NULL;
    }
    ThrowDatabaseException();
    return false;
  }
	m_pContext->msg_handler = tsql_handle_message;
	m_pContext->err_handler = tsql_handle_error;

  // Add the context (and this databaselayer) from the lookup map
  //  used by the error handler
  TdsDatabaseLayer::AddTdsLayer(m_pContext, this);

  m_pDatabase = tds_alloc_socket(m_pContext, 512);
  if (m_pDatabase == NULL)
  {
    //fprintf(stderr, "tds_alloc_socket() failed.\n");
    SetError(DATABASE_LAYER_ERROR, wxT("Failed to allocate socket"));
    // Reset the variables so there are not mistaken as initialized
    m_pDatabase = NULL;
    if (m_pLogin)
    {
      tds_free_login(m_pLogin);
      m_pLogin = NULL;
    }
    if (m_pContext)
    {
      tds_free_context(m_pContext);
      m_pContext = NULL;
    }
    ThrowDatabaseException();
    return false;
  }
	tds_set_parent(m_pDatabase, NULL);

	TDSCONNECTION* pConnection = tds_read_config_info(NULL, m_pLogin, m_pContext->locale);
	if (!pConnection || tds_connect(m_pDatabase, pConnection) == TDS_FAIL)
  {
		if (pConnection)
    {
			tds_free_socket(m_pDatabase);
			//m_pDatabase = NULL;
			tds_free_connection(pConnection);
		}
		//fprintf(stderr, "tds_connect() failed\n");
    if (GetErrorCode() == DATABASE_LAYER_OK)
    {
      SetError(DATABASE_LAYER_ERROR, wxT("Database connection failed"));
    }
    // Reset the variables so there are not mistaken as initialized
    m_pDatabase = NULL;
    if (m_pLogin)
    {
      tds_free_login(m_pLogin);
      m_pLogin = NULL;
    }
    if (m_pContext)
    {
      tds_free_context(m_pContext);
      m_pContext = NULL;
    }
    ThrowDatabaseException();
		return false;
	}
	tds_free_connection(pConnection);

  return true;
}
Esempio n. 17
0
bool FirebirdDatabaseLayer::Open()
{
  ResetErrorCodes();

  // Set up the connection parameter string
  //int nParameterStringLength;
  //char szParameterString[512];
  //char* pParameterString = szParameterString;

  // Firebird accepts all the other ISO_8859 encoding names but ISO-8859-1 needs a little tweaking to be recognized
  //wxString encodingName = wxLocale::GetSystemEncodingName();
  
  //wxCharBuffer systemEncoding;
  //if (encodingName == wxT("ISO-8859-1"))
  // systemEncoding = "ISO8859_1";
  //else
  // systemEncoding = encodingName.mb_str(*wxConvCurrent);
  wxCharBuffer systemEncoding = "UTF-8";

  wxCSConv conv(_("UTF-8"));
  SetEncoding(&conv);
  
  //char* pDpb = new char(512);
  char* pDpb;
  short nDpbLength = 0;
  wxCharBuffer userCharBuffer = ConvertToUnicodeStream(m_strUser);
  wxCharBuffer passwordCharBuffer = ConvertToUnicodeStream(m_strPassword);
  wxCharBuffer roleCharBuffer = ConvertToUnicodeStream(m_strRole);
  
  pDpb = (char*)0;
  
  if (m_strRole == wxEmptyString)
  {
#ifdef wxUSE_UNICODE
    m_pInterface->GetIscExpandDpb()(&pDpb, &nDpbLength, isc_dpb_user_name, (const char*)userCharBuffer,
        isc_dpb_password, (const char*)passwordCharBuffer, isc_dpb_lc_ctype, (const char*)systemEncoding, NULL);
#else
    m_pInterface->GetIscExpandDpb()(&pDpb, &nDpbLength, isc_dpb_user_name, (const char*)userCharBuffer,
        isc_dpb_password, (const char*)m_strPassword.c_str(), isc_dpb_lc_ctype, (const char*)systemEncoding, NULL);
#endif
  }
  else
  {
#ifdef wxUSE_UNICODE
    m_pInterface->GetIscExpandDpb()(&pDpb, &nDpbLength, isc_dpb_user_name, (const char*)userCharBuffer,
        isc_dpb_password, (const char*)passwordCharBuffer, isc_dpb_lc_ctype, (const char*)systemEncoding,
        isc_dpb_sql_role_name, (const char*)roleCharBuffer, NULL);
#else
    m_pInterface->GetIscExpandDpb()(&pDpb, &nDpbLength, isc_dpb_user_name, (const char*)userCharBuffer,
        isc_dpb_password, (const char*)m_strPassword.c_str(), isc_dpb_lc_ctype, (const char*)systemEncoding,
        isc_dpb_sql_role_name, (const char*)roleCharBuffer, NULL);
#endif
  }
    
  // Combine the server and databsae path strings to pass into the isc_attach_databse function
  wxString strDatabaseUrl;
  if (m_strServer.IsEmpty())
    strDatabaseUrl = m_strDatabase; // Embedded database, just supply the file name
  else
    strDatabaseUrl = m_strServer + _(":") + m_strDatabase;
 
  m_pDatabase = NULL;
  m_pTransaction = NULL;

  wxCharBuffer urlBuffer = ConvertToUnicodeStream(strDatabaseUrl);
  isc_db_handle pDatabase = (isc_db_handle)m_pDatabase;
  //int nReturn = m_pInterface->GetIscAttachDatabase()(*(ISC_STATUS_ARRAY*)m_pStatus, 0, urlBuffer, &((isc_db_handle)m_pDatabase), nParameterStringLength, szParameterString);
  int nReturn = m_pInterface->GetIscAttachDatabase()(*(ISC_STATUS_ARRAY*)m_pStatus, 0, (char*)(const char*)urlBuffer, &pDatabase, nDpbLength, pDpb);
  m_pDatabase = pDatabase;
  if (nReturn != 0)
  {
    InterpretErrorCodes();
    ThrowDatabaseException();

    return false;
  }
  return true;
}