Exemplo n.º 1
0
KDbSqlResult* SqlitePreparedStatement::execute(
    KDbPreparedStatement::Type type,
    const KDbField::List& selectFieldList,
    KDbFieldList* insertFieldList,
    const KDbPreparedStatementParameters& parameters, bool *resultOwned)
{
    Q_UNUSED(insertFieldList);
    Q_UNUSED(resultOwned);
    if (!m_sqlResult->prepared_st) {
        return nullptr;
    }

    int par = 1; // par.index counted from 1
    KDbField::ListIterator itFields(selectFieldList.constBegin());
    for (QList<QVariant>::ConstIterator it = parameters.constBegin();
         itFields != selectFieldList.constEnd();
         it += (it == parameters.constEnd() ? 0 : 1), ++itFields, par++)
    {
        if (!bindValue(*itFields, it == parameters.constEnd() ? QVariant() : *it, par))
            return nullptr;
    }

    //real execution
    const int res = sqlite3_step(m_sqlResult->prepared_st);
    if (type == KDbPreparedStatement::InsertStatement) {
        const bool ok = res == SQLITE_DONE;
        if (ok) {
            m_result = KDbResult();
        } else {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            sqliteWarning() << m_result << QString::fromLatin1(sqlite3_sql(m_sqlResult->prepared_st));
        }
        (void)sqlite3_reset(m_sqlResult->prepared_st);
        return m_sqlResult.data();
    }
    else if (type == KDbPreparedStatement::SelectStatement) {
        //! @todo fetch result
        const bool ok = res == SQLITE_ROW;
        storeResult(&m_result);
        if (ok) {
            m_result = KDbResult();
        } else {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            sqliteWarning() << m_result << QString::fromLatin1(sqlite3_sql(m_sqlResult->prepared_st));
        }
        (void)sqlite3_reset(m_sqlResult->prepared_st);
        return m_sqlResult.data();
    }
    return nullptr;
}
Exemplo n.º 2
0
bool SqliteCursor::drv_open(const KDbEscapedString& sql)
{
    //! @todo decode
    if (! d->data) {
        // this may as example be the case if SqliteConnection::drv_useDatabase()
        // wasn't called before. Normaly sqlite_compile/sqlite3_prepare
        // should handle it, but it crashes in in sqlite3SafetyOn at util.c:786
        sqliteWarning() << "SqliteCursor::drv_open(): Database handle undefined.";
        return false;
    }

    int res = sqlite3_prepare(
                  d->data,            /* Database handle */
                  sql.constData(),       /* SQL statement, UTF-8 encoded */
                  sql.length(),             /* Length of zSql in bytes. */
                  &d->prepared_st_handle,  /* OUT: Statement handle */
                  0/*const char **pzTail*/     /* OUT: Pointer to unused portion of zSql */
              );
    if (res != SQLITE_OK) {
        m_result.setServerErrorCode(res);
        storeResult();
        return false;
    }
    if (isBuffered()) {
//! @todo manage size dynamically
        d->records.resize(128);
    }

    return true;
}
Exemplo n.º 3
0
void __fastcall TfrmResultEnterEdit::bbtnAddResultClick(TObject *Sender)
{
    //Сохранить результат
    storeResult();
    //Обновить таблицу участников
    changeCompetitorSearchTableState();
    lbledtCompetitorSurname->SetFocus();
}
Exemplo n.º 4
0
bool SqliteCursor::drv_close()
{
    int res = sqlite3_finalize(d->prepared_st_handle);
    if (res != SQLITE_OK) {
        m_result.setServerErrorCode(res);
        storeResult();
        return false;
    }
    return true;
}
Exemplo n.º 5
0
bool MysqlCursor::drv_open(const KDbEscapedString& sql)
{
    if (mysql_real_query(d->mysql, sql.constData(), sql.length()) == 0) {
        if (mysql_errno(d->mysql) == 0) {
            //! @todo Add option somewhere so we can use more optimal mysql_num_rows().
            //!       In this case mysql_num_rows() does not work however.
            d->mysqlres = mysql_store_result(d->mysql);
            m_fieldCount = mysql_num_fields(d->mysqlres);
            m_fieldsToStoreInRecord = m_fieldCount;
            d->numRows = mysql_num_rows(d->mysqlres);

            m_records_in_buf = d->numRows;
            m_buffering_completed = true;
            return true;
        }
    }

    storeResult();
    return false;
}
Exemplo n.º 6
0
SEXP readBGEN2List(BGenFile* bin) {
  // Rprintf("vcfColumn.size() = %u\n", FLAG_vcfColumn.size());
  // Rprintf("vcfInfo.size() = %u\n", FLAG_infoTag.size());
  // Rprintf("vcfIndv.size() = %u\n", FLAG_indvTag.size());
  // also append sample names at the end
  // 7: chrom, pos, varId, rsId, alleles, isPhased, prob, sampleId
  int retListLen = 8;
  if (retListLen == 0) {
    return R_NilValue;
  }

  int numAllocated =
      0;  // record how many times we allocate (using PROTECT in R);
  SEXP ret;
  PROTECT(ret = allocVector(VECSXP, retListLen));
  numAllocated++;

  //  store results
  std::vector<std::string> idVec;
  std::vector<std::string> chrom;
  std::vector<int> pos;
  std::vector<std::string> varId;
  std::vector<std::string> rsId;
  std::vector<std::string> alleles;
  // std::vector<std::vector<bool> > missing;
  std::vector<bool> isPhased;
  std::vector<std::vector<double> >
      prob;  // prob[variant][each_sample * (prob1, prob2, ...)]

  // std::map<std::string, std::vector<std::string> > infoMap;

  // std::map<std::string, std::vector<std::string> > indvMap;
  /// int nRow = 0;  // # of positions that will be outputed

  // get effective sample names
  const int N = bin->getNumSample();
  std::vector<std::string> sm = bin->getSampleIdentifier();  // all sample names
  std::vector<std::string>& names = idVec;
  if (!sm.size()) {
    char buf[1024];
    for (int i = 0; i < N; ++i) {
      sprintf(buf, "sample_%d", i);
      sm.push_back(buf);
    }
  }

  const size_t sampleSize = bin->getNumEffectiveSample();
  for (size_t i = 0; i != sampleSize; ++i) {
    names.push_back(sm[bin->getEffectiveIndex(i)]);
  }

  // real working part
  int nRecord = 0;
  const int numProbValues =
      3;  // if multi-allelic/multi-haploid, this value can be different
  int maxProbValues = -1;
  while (bin->readRecord()) {
    // REprintf("read a record\n");
    const BGenVariant& var = bin->getVariant();
    const size_t sampleSize = bin->getNumEffectiveSample();

    // store results here
    nRecord++;
    chrom.push_back(var.chrom);
    pos.push_back(var.pos);
    varId.push_back(var.varid);
    rsId.push_back(var.rsid);
    alleles.push_back(toString(var.alleles, ","));
    isPhased.push_back(var.isPhased);
    prob.resize(nRecord);

    std::vector<double>& p = prob[nRecord - 1];
    p.reserve(sampleSize * numProbValues);

    for (size_t i = 0; i != sampleSize; ++i) {
      int beg = var.index[bin->getEffectiveIndex(i)];
      int end = var.index[bin->getEffectiveIndex(i) + 1];
      if (end - beg > maxProbValues) {
        maxProbValues = end - beg;
      }
      for (int j = 0; j < numProbValues; ++j) {
        if (j < numProbValues) {
          p.push_back(var.prob[beg + j]);
        } else {
          p.push_back(-9);
        }
      }
      // REprintf("beg = %d, end = %d, prob[%d][%d] len = %d\n", beg,end,
      // nRecord - 1, i, p[i].size());
    }

    // Rprintf("Done add indv\n");
  }  // end while
  if (maxProbValues > numProbValues) {
    REprintf("some sample has more than %d > %d probabilities per variant!\n",
             maxProbValues, numProbValues);
  }

  // pass value back to R (see Manual Chapter 5)
  std::vector<std::string> listNames;
  int retListIdx = 0;
  storeResult(chrom, ret, retListIdx++);
  storeResult(pos, ret, retListIdx++);
  storeResult(varId, ret, retListIdx++);
  storeResult(rsId, ret, retListIdx++);
  storeResult(alleles, ret, retListIdx++);
  storeResult(isPhased, ret, retListIdx++);
  storeResult(prob, ret, retListIdx);
  for (size_t i = 0; i != prob.size(); ++i) {
    SEXP s = VECTOR_ELT(VECTOR_ELT(ret, retListIdx), i);
    setDim(numProbValues, sampleSize, s);
  }

  retListIdx++;
  listNames.push_back("chrom");
  listNames.push_back("pos");
  listNames.push_back("varid");
  listNames.push_back("rsid");
  listNames.push_back("alleles");
  listNames.push_back("isPhased");
  listNames.push_back("probability");

  // store sample ids
  // Rprintf("set sample id");
  listNames.push_back("sampleId");
  storeResult(idVec, ret, retListIdx++);

  // Rprintf("set list names\n");
  SEXP sListNames;
  PROTECT(sListNames = allocVector(STRSXP, listNames.size()));
  numAllocated++;
  for (unsigned int i = 0; i != listNames.size(); ++i) {
    SET_STRING_ELT(sListNames, i, mkChar(listNames[i].c_str()));
  }
  setAttrib(ret, R_NamesSymbol, sListNames);

  // finish up
  UNPROTECT(numAllocated);
  // Rprintf("Unprotected: %d\n", (retListLen + 1));
  return (ret);
}
Exemplo n.º 7
0
bool SqlitePreparedStatement::bindValue(KDbField *field, const QVariant& value, int par)
{
    if (value.isNull()) {
        //no value to bind or the value is null: bind NULL
        int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        return true;
    }
    if (field->isTextType()) {
        //! @todo optimize: make a static copy so SQLITE_STATIC can be used
        const QByteArray utf8String(value.toString().toUtf8());
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    utf8String.constData(), utf8String.length(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        return true;
    }

    switch (field->type()) {
    case KDbField::Byte:
    case KDbField::ShortInteger:
    case KDbField::Integer: {
        //! @todo what about unsigned > INT_MAX ?
        bool ok;
        const int intValue = value.toInt(&ok);
        if (ok) {
            int res = sqlite3_bind_int(m_sqlResult->prepared_st, par, intValue);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        } else {
            int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        }
        break;
    }
    case KDbField::Float:
    case KDbField::Double: {
        int res = sqlite3_bind_double(m_sqlResult->prepared_st, par, value.toDouble());
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::BigInteger: {
        //! @todo what about unsigned > LLONG_MAX ?
        bool ok;
        const qint64 int64Value = value.toLongLong(&ok);
        if (ok) {
            int res = sqlite3_bind_int64(m_sqlResult->prepared_st, par, int64Value);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        } else {
            int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        }
        break;
    }
    case KDbField::Boolean: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par, value.toBool() ? "1" : "0",
                                    1, SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::Time: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    qPrintable(value.toTime().toString(Qt::ISODate)),
                                    QLatin1String("HH:MM:SS").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::Date: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    qPrintable(value.toDate().toString(Qt::ISODate)),
                                    QLatin1String("YYYY-MM-DD").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::DateTime: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                qPrintable(value.toDateTime().toString(Qt::ISODate)),
                                QLatin1String("YYYY-MM-DDTHH:MM:SS").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::BLOB: {
        const QByteArray byteArray(value.toByteArray());
        int res = sqlite3_bind_blob(m_sqlResult->prepared_st, par,
                                    byteArray.constData(), byteArray.size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    default: {
        sqliteWarning() << "unsupported field type:"
                << field->type() << "- NULL value bound to column #" << par;
        int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
    }
    } //switch
    return true;
}
Exemplo n.º 8
0
//bool xBaseConnectionInternal::db_connect(QCString host, QCString user,
//  QCString password, unsigned short int port, QString socket)
bool xBaseConnectionInternal::db_connect(const Predicate::ConnectionData& data)
{
  // we have to migrate the xbase source database into a .kexi file
  // xbase source database directory will be in connectiondata
  // we can choose a KTemporaryFile for the destination .kexi file

  KexiMigration::MigrateManager xBase2KexiMigrateManager;

  // create a temporary .kexi file
  KTemporaryFile temporaryKexiFile;
  temporaryKexiFile.setSuffix( ".kexi" );
  temporaryKexiFile.setAutoRemove( false );

  if ( !temporaryKexiFile.open() ) {
    PreDrvDbg<<"Couldn't create .kexi file for exporting from xBase to .kexi";
    return false;
  }

        tempDatabase = temporaryKexiFile.fileName();

  Predicate::ConnectionData* kexiConnectionData = 0;
  kexiConnectionData = new Predicate::ConnectionData();

  // set destination file name here.
  kexiConnectionData->driverName = Predicate::defaultFileBasedDriverName();
  kexiConnectionData->setFileName( tempDatabase );
  PreDrvDbg << "Current file name: " << tempDatabase;


  QString sourceDriverName = "xbase";
  // get the source migration driver
  KexiMigration::KexiMigrate* sourceDriver = 0;
  sourceDriver = xBase2KexiMigrateManager.driver( sourceDriverName );
  if(!sourceDriver || xBase2KexiMigrateManager.error()) {
    PreDrvDbg << "Import migrate driver error...";
    return false;
  }

  KexiMigration::Data* md = new KexiMigration::Data();
  md->keepData = true;
  md->destination = new KexiProjectData(*kexiConnectionData, tempDatabase);

  // Setup XBase connection data from input connection data passed
  //! TODO Check sanity of this
  md->source = new Predicate::ConnectionData(data);
  md->sourceName = "";

  sourceDriver->setData(md);
  if ( !sourceDriver->performImport() ) {
    PreDrvDbg<<"Import failed";
    return false;
  }

  // finished transferring xBase database into .kexi file

  // Get a driver to the destination database

  if ( internalDriver )
    internalConn = internalDriver->createConnection(*kexiConnectionData);
  else
    return false;

  if (!internalConn || internalDriver->error()) {
    internalDriver->debugError();
    return false;
  }
  if (!internalConn->connect()) {
    internalConn->debugError();
    storeResult();
    return false;
  }

        if (!internalConn->useDatabase(tempDatabase)) {
                internalConn->debugError();
                storeResult();
                return false;
        }

  // store mapping from xbase directory to .kexi file name for future use
  // Note: When a directory is specified ( as has to be done for xBase ), fileName()
  // will give directory name with an additional forward slash. dbPath() won't do so.
  // Need some more maintainable solution.

  dbMap[data.fileName()] = tempDatabase;

  return true;
}