Exemplo n.º 1
0
SWITCH_DECLARE(int) switch_core_db_bind_int(switch_core_db_stmt_t *pStmt, int i, int iValue)
{
	return sqlite3_bind_int(pStmt, i, iValue);
}
Exemplo n.º 2
0
int
CSQLiteDE::AddBin(int ExprID,
				int TransID,
				int ExpresID,
				int NthBin,
				int CtrlCounts,
				int ExprCounts)
{
int sqlite_error;
tsDEStmSQL *pStm;
int BinID;
char szQueryBinID[200];
pStm = &m_StmSQL[3];								// access sequence statements
if(m_pDB == NULL)
	return(eBSFerrInternal);
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 1, ExprID))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 2, TransID))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 3, ExpresID))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 4, NthBin))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 5, CtrlCounts))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 6, CtrlCounts))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}



if((sqlite_error = sqlite3_step(pStm->pPrepInsert))!=SQLITE_DONE)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - step prepared statement: %s", sqlite3_errmsg(m_pDB));   
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
sqlite3_reset(pStm->pPrepInsert);

if(m_bSafe)
	{
	BinID = -1;
	sprintf(szQueryBinID,"select BinID from TblBins where ExprID = %d AND TransID = %d AND ExpresID = %d AND NthBin = %d",ExprID,TransID,ExpresID,NthBin);
	sqlite3_exec(m_pDB,szQueryBinID,ExecCallbackID,&BinID,NULL);
	}
else
	BinID = (int)sqlite3_last_insert_rowid(m_pDB);	
return(BinID);
}
static int
gf_sql_update_link_flags (gf_sql_connection_t  *sql_conn,
                   char                 *gfid,
                   char                 *pargfid,
                   char                 *basename,
                   int                  update_flag,
                   gf_boolean_t         is_update_or_delete)
{
        int ret = -1;
        sqlite3_stmt *update_stmt = NULL;
        char *update_column = NULL;
        char update_str[1024] = "";


        CHECK_SQL_CONN (sql_conn, out);
        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, gfid, out);
        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, pargfid, out);
        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, basename, out);

        update_column = (is_update_or_delete) ? "LINK_UPDATE" : "W_DEL_FLAG";

        sprintf (update_str, "UPDATE "
                            GF_FILE_LINK_TABLE
                            " SET %s = ?"
                            " WHERE GF_ID = ? AND GF_PID = ? AND FNAME = ?;",
                            update_column);

        /*Prepare statement*/
        ret = sqlite3_prepare (sql_conn->sqlite3_db_conn, update_str, -1,
                                &update_stmt, 0);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_PREPARE_FAILED, "Failed preparing update "
                        "statment %s : %s", update_str,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }


        /*Bind link_update*/
        ret = sqlite3_bind_int (update_stmt, 1, update_flag);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding update_flag %d "
                        ": %s", update_flag,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind gfid*/
        ret = sqlite3_bind_text (update_stmt, 2, gfid, -1, NULL);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding gfid %s : %s",
                        gfid, sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind pargfid*/
        ret = sqlite3_bind_text (update_stmt, 3, pargfid, -1, NULL);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding parent gfid %s "
                        ": %s", pargfid,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind basename*/
        ret = sqlite3_bind_text (update_stmt, 4, basename, -1, NULL);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding basename %s : "
                        "%s", basename,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }


        /*Execute the prepare statement*/
        if (sqlite3_step(update_stmt) != SQLITE_DONE) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0, LG_MSG_EXEC_FAILED,
                        "Failed executing the prepared stmt %s : %s",
                        update_str,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        ret = 0;
out:
        /*Free prepared statement*/
        sqlite3_finalize (update_stmt);
        return ret;
}
Exemplo n.º 4
0
bool QSpatiaLiteResult::exec()
{
    const QVector<QVariant> values = boundValues();

    d->skippedStatus = false;
    d->skipRow = false;
    d->rInf.clear();
    clearValues();
    setLastError(QSqlError());

    int res = sqlite3_reset(d->stmt);
    if (res != SQLITE_OK) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("QSpatiaLiteResult",
                     "Unable to reset statement"), QSqlError::StatementError, res));
        d->finalize();
        return false;
    }
    int paramCount = sqlite3_bind_parameter_count(d->stmt);
    if (paramCount == values.count()) {
        for (int i = 0; i < paramCount; ++i) {
            res = SQLITE_OK;
            const QVariant value = values.at(i);

            if (value.isNull()) {
                res = sqlite3_bind_null(d->stmt, i + 1);
            } else {
                switch (value.type()) {
                case QVariant::ByteArray: {
                    const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
                    res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(),
                                            ba->size(), SQLITE_STATIC);
                    break; }
                case QVariant::Int:
                    res = sqlite3_bind_int(d->stmt, i + 1, value.toInt());
                    break;
                case QVariant::Double:
                    res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble());
                    break;
                case QVariant::UInt:
                case QVariant::LongLong:
                    res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong());
                    break;
                case QVariant::String: {
                    // lifetime of string == lifetime of its qvariant
                    const QString *str = static_cast<const QString*>(value.constData());
                    res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(),
                                              (str->size()) * sizeof(QChar), SQLITE_STATIC);
                    break; }
                default: {
                    QString str = value.toString();
                    // SQLITE_TRANSIENT makes sure that sqlite buffers the data
                    res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
                                              (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
                    break; }
                }
            }
            if (res != SQLITE_OK) {
                setLastError(qMakeError(d->access, QCoreApplication::translate("QSpatiaLiteResult",
                             "Unable to bind parameters"), QSqlError::StatementError, res));
                d->finalize();
                return false;
            }
        }
    } else {
        setLastError(QSqlError(QCoreApplication::translate("QSpatiaLiteResult",
                        "Parameter count mismatch"), QString(), QSqlError::StatementError));
        return false;
    }
    d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    setSelect(!d->rInf.isEmpty());
    setActive(true);
    return true;
}
Exemplo n.º 5
0
int										// returned identifier for transcript
CSQLiteDE::AddTrans(int ExprID,			// experiment identifier
		char *pszTransName,				// transcript name
		int NumExons,				    // number of exons in this transcript
		int TransLen,					// transcript length
		char *pszAnnotation)			// any associated annotations
{
int sqlite_error;
tsDEStmSQL *pStm;
int Idx;
int TransID;
tsMRATrans *pMRATrans;
tsMRATrans *pLRATrans;
char szQueryTransName[200];

if(m_pDB == NULL)
	return(eBSFerrInternal);

if(!m_NumTransMRA)
	memset(m_MRATrans,0,sizeof(m_MRATrans));

// quickly check if sequence is a recently accessed sequence and if so then return the identifier
pMRATrans = m_MRATrans;
for(Idx = 0; Idx < m_NumTransMRA; Idx++, pMRATrans++)
	{
	if(!stricmp(pszTransName,pMRATrans->szTransName))
		{
		if(pMRATrans->AccessCnt < 0x7ffffff)
			pMRATrans->AccessCnt += 10;
		return(pMRATrans->TransID);
		}
	if(pMRATrans->AccessCnt > 0)
		pMRATrans->AccessCnt -= 1;
	}

TransID = -1;
if(m_bSafe)
	{
	// not a recently accessed sequence so need to check if already known to SQLite
	sprintf(szQueryTransName,"select TransID from TblTrans where ExprID = %d AND TransName LIKE '%s'",ExprID,pszTransName);
	sqlite3_exec(m_pDB,szQueryTransName,ExecCallbackID,&TransID,NULL);
	}

if(TransID == -1)	// will be -1 if not already in database so need to add
	{
	pStm = &m_StmSQL[1];								// access sequence statements
	if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 1, ExprID))!=SQLITE_OK)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
		CloseDatabase(true);
		return(eBSFerrInternal);
		}

	if((sqlite_error = sqlite3_bind_text(pStm->pPrepInsert, 2, pszTransName,(int)strlen(pszTransName)+1,SQLITE_STATIC))!=SQLITE_OK)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
		CloseDatabase(true);
		return(eBSFerrInternal);
		}

	if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 3, NumExons))!=SQLITE_OK)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
		CloseDatabase(true);
		return(eBSFerrInternal);
		}
	
	if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 4, TransLen))!=SQLITE_OK)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
		CloseDatabase(true);
		return(eBSFerrInternal);
		}

	if((sqlite_error = sqlite3_bind_text(pStm->pPrepInsert, 5, pszAnnotation,(int)strlen(pszAnnotation)+1,SQLITE_STATIC))!=SQLITE_OK)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
		CloseDatabase(true);
		return(eBSFerrInternal);
		}

	if((sqlite_error = sqlite3_step(pStm->pPrepInsert))!=SQLITE_DONE)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - step prepared statement: %s", sqlite3_errmsg(m_pDB));   
		CloseDatabase(true);
		return(eBSFerrInternal);
		}
	sqlite3_reset(pStm->pPrepInsert);

	if(m_bSafe)
		{
		sprintf(szQueryTransName,"select TransID from TblTrans where ExprID = %d AND TransName LIKE '%s'",ExprID,pszTransName);
		sqlite3_exec(m_pDB,szQueryTransName,ExecCallbackID,&TransID,NULL);
		}
	else
		TransID = (int)sqlite3_last_insert_rowid(m_pDB);
	m_NumTrans += 1;						// number of seqs added to TblSeqs
	}

// replace lRA sequence
if(m_NumTransMRA < cMaxMRATrans)
	pMRATrans = &m_MRATrans[m_NumTransMRA++];
else
	{
	pMRATrans = m_MRATrans;
	pLRATrans = pMRATrans++;
	for(Idx = 1; Idx < m_NumTransMRA; Idx++, pMRATrans++)
		{
		if(pMRATrans->AccessCnt < pLRATrans->AccessCnt)
			pLRATrans = pMRATrans;
		}
	pMRATrans = pLRATrans;
	}
pMRATrans->AccessCnt = 1000;
pMRATrans->TransID = TransID;
strcpy(pMRATrans->szTransName,pszTransName);
return(TransID);
}
Exemplo n.º 6
0
bool
db_configuration_set_defaults (const char* location)
{
  sqlite3* db;
  sqlite3_stmt* result;
  int status;

  status = sqlite3_open (location, &db);
  if (status != SQLITE_OK) return false;

  /* Minimize disk I/O because that can be pretty expensive. */
  sqlite3_exec (db, "PRAGMA synchronous = OFF", 0, 0, 0);
  sqlite3_exec (db, "PRAGMA journal_mode = MEMORY", 0, 0, 0);
  sqlite3_exec (db, "BEGIN TRANSACTION", 0, 0, 0);

  /* Empty the table (TRUNCATE is not available in SQLite3). */
  status = sqlite3_exec (db, "DELETE FROM config", 0, 0, 0);

  /* By using a prepared statement we avoid SQL injection and double memory
   * allocation of the query string. */
  if (status == SQLITE_OK)
    status = sqlite3_prepare_v2 (db, 
      "INSERT INTO config (key, value) VALUES (?, ?)", -1, &result, NULL);

  /* Bind the values to the parameters. Apparantly the first index is 1. */
  sqlite3_bind_int (result, 1, KEY_STORAGE_PATH);

  /* Try to set '$HOME/Moefel/' as the default storage path. 
   * When $HOME is not available, fall back to the current directory. */
  char* storage_path = NULL;
  #ifndef WIN32
  char* home = getenv ("HOME");
  #else
  char* home = NULL;
  TCHAR szPath[MAX_PATH];
  SHGetFolderPath (NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, 0, szPath);
  home = (char *)&szPath;
  #endif
  if (home != NULL)
    {
      storage_path = calloc (1, strlen (home) + 9);
      strcpy (storage_path, home);
      #ifndef WIN32
      strcat (storage_path, "/Moefel/");
      #else
      strcat (storage_path, "\\Moefel\\");
      #endif
      sqlite3_bind_text (result, 2, storage_path, -1, NULL);
    }
  else
    sqlite3_bind_text (result, 2, ".", -1, NULL);

  /* Execute the query. */
  status = sqlite3_step (result);

  /* Commit the changes to the database. */
  if (status == SQLITE_DONE)
    status = sqlite3_finalize (result),
    free (storage_path);

  /* Write changes to the database. */
  if (status == SQLITE_OK) sqlite3_exec (db, "END TRANSACTION", 0, 0, 0);
  sqlite3_close(db);

  if (status != SQLITE_OK) return false;
  return true;
}
Exemplo n.º 7
0
	void sqlite3_command::bind(int index, int data) {
		if(sqlite3_bind_int(this->stmt, index, data)!=SQLITE_OK)
			throw database_error(this->con);
	}
Exemplo n.º 8
0
int main()
{
  // Build an APD index.
  MapIndexHandler<unsigned char> APDIndex;
  for(unsigned char i = 152; i < 226; i++) {
    // Skip APD channels which have never been active.
    if(i == 178 or i == 191 or i == 205) continue;
    APDIndex.InsertKey(i);
  }

  // Build a lightmap object in memory.
  // This is where we specify the lightmap binning and choice of run ranges for gain.
  LightMap::PositionFunc posFunc;
  posFunc.SetAPDIndex(APDIndex);
  posFunc.SetBinning(-210, 15, 28, -210, 15, 28, -200, 10, 40); // 1.5cm in X/Y, 1cm in Z.
  LightMap::GainFunc gainFunc;
  gainFunc.InsertGain(APDIndex, 2401, 2423); // Old 09-28-11 APD biases
  gainFunc.InsertGain(APDIndex, 2424, 2690); // FEC voltage adjustment
  gainFunc.InsertGain(APDIndex, 2691, 2852); // Ebox 1 fan installed
  gainFunc.InsertGain(APDIndex, 2853, 2891); // Ebox 2 fan installed
  gainFunc.InsertGain(APDIndex, 2892, 3117); // Power outage here.
  gainFunc.InsertGain(APDIndex, 3118, 3326); // APD board swap
  gainFunc.InsertGain(APDIndex, 3327, 3700); // Utility power swap
  gainFunc.InsertGain(APDIndex, 3701, 3949);
  gainFunc.InsertGain(APDIndex, 3950, 4140); // Ralph's diode box installed
  gainFunc.InsertGain(APDIndex, 4141, 4579);
  gainFunc.InsertGain(APDIndex, 4580, 4779);
  gainFunc.InsertGain(APDIndex, 4780, 5197); // LC filters removed from FECs
  gainFunc.InsertGain(APDIndex, 5198, 5590); // Toward end of 5590 CR temps are elevated; APD gain impacted
  gainFunc.InsertGain(APDIndex, 5591, 5892); // Run2c ends.

  // Retrieve the indices of the x, y, and z coordinates.
  const IntervalIndexHandler& xIndex = posFunc.PosIndex().MajorIndex().MajorIndex();
  const IntervalIndexHandler& yIndex = posFunc.PosIndex().MajorIndex().MinorIndex();
  const IntervalIndexHandler& zIndex = posFunc.PosIndex().MinorIndex();

  // Initialize the gain function to be identically one.
  for(size_t i = 0; i < gainFunc.NumSnapshots(); i++) {
    LightMap::GainSnapshot& gain = gainFunc.GainAtIndex(i);
    for(size_t j = 0; j < gain.APDIndex().MaxIndex(); j++) gain.GetValAt(j) = 1;
  }

  // Create a connection to the database of thorium events.
  int ret;
  sqlite3* connection;
  ret = sqlite3_open_v2("Tmp/ThoriumLightmapEvents.db",
                        &connection,
                        SQLITE_OPEN_READONLY,
                        NULL);
  if(ret != SQLITE_OK) {
    std::cerr << "Failed to open database of events." << std::endl;
    exit(1);
  }

  // Build a comma-separated list of APD columns to retrieve in each case.
  std::ostringstream QueryColumns;
  QueryColumns << "apd_" << int(APDIndex.KeyForIndex(0)) << "_magnitude";
  for(size_t i = 1; i < APDIndex.MaxIndex(); i++) {
    QueryColumns << ", apd_" << int(APDIndex.KeyForIndex(i)) << "_magnitude";
  }
  QueryColumns << " FROM events WHERE ";

  // Prepare statements to retrieve by position or by run range.
  sqlite3_stmt *prep_stmt_pos, *prep_stmt_run;
  ret = sqlite3_prepare_v2(connection,
                           std::string("SELECT runNo, " + QueryColumns.str() +
                                       "? <= xpos AND xpos < ? AND " +
                                       "? <= ypos AND ypos < ? AND " +
                                       "? <= zpos AND zpos < ?").c_str(),
                           -1,
                           &prep_stmt_pos,
                           NULL);
  if(ret != SQLITE_OK) {
    std::cerr << "Failed to prepare the position select statement." << std::endl;
    exit(1);
  }
  ret = sqlite3_prepare_v2(connection,
                           std::string("SELECT xpos, ypos, zpos, " + QueryColumns.str() +
                                       "? <= runNo AND runNo <= ?").c_str(),
                           -1,
                           &prep_stmt_run,
                           NULL);
  if(ret != SQLITE_OK) {
    std::cerr << "Failed to prepare the run select statement." << std::endl;
    exit(1);
  }

  // Iteratively converge on an appropriate lightmap -- three iterations seem to be enough.
  for(size_t iteration = 0; iteration < 3; iteration++) {

    std::cout << "Computing the position function, holding gain fixed." << std::endl;

    for(size_t posBin = 0; posBin < posFunc.PosIndex().MaxIndex(); posBin++) {

      // Get information about this position bin.
      size_t xyBin = posFunc.PosIndex().MajorIndexForIndex(posBin);
      size_t xBin = posFunc.PosIndex().MajorIndex().MajorIndexForIndex(xyBin);
      size_t yBin = posFunc.PosIndex().MajorIndex().MinorIndexForIndex(xyBin);
      size_t zBin = posFunc.PosIndex().MinorIndexForIndex(posBin);
      double xmin = xIndex.KeyForIndex(xBin);
      double xmax = xIndex.KeyForIndex(xBin+1);
      double ymin = yIndex.KeyForIndex(yBin);
      double ymax = yIndex.KeyForIndex(yBin+1);
      double zmin = zIndex.KeyForIndex(zBin);
      double zmax = zIndex.KeyForIndex(zBin+1);

      // Bind these parameters to the query.
      bool success = (
        sqlite3_bind_double(prep_stmt_pos, 1, xmin) == SQLITE_OK and
        sqlite3_bind_double(prep_stmt_pos, 2, xmax) == SQLITE_OK and
        sqlite3_bind_double(prep_stmt_pos, 3, ymin) == SQLITE_OK and
        sqlite3_bind_double(prep_stmt_pos, 4, ymax) == SQLITE_OK and
        sqlite3_bind_double(prep_stmt_pos, 5, zmin) == SQLITE_OK and
        sqlite3_bind_double(prep_stmt_pos, 6, zmax) == SQLITE_OK);
      if(not success) {
        std::cerr << "Failed to bind values to a select statement." << std::endl;
        exit(1);
      }

      // Retrieve all events which fall in this bin.
      // For each APD, we wish to compute the weighted sum of magnitudes
      // and the sum of square weights.
      LightMap::FuncVsAPD WeightedSumMagnitudes;
      LightMap::FuncVsAPD SumSquareWeights;
      for(size_t i = 0; i < APDIndex.MaxIndex(); i++) {
        WeightedSumMagnitudes[i] = 0;
        SumSquareWeights[i] = 0;
      }
      while((ret = sqlite3_step(prep_stmt_pos)) == SQLITE_ROW) {
        // Handle a row.
        int runNo = sqlite3_column_int(prep_stmt_pos, 0);
        const LightMap::GainSnapshot& gain = gainFunc.GainForRun(runNo);
        for(size_t i = 0; i < APDIndex.MaxIndex(); i++) {
          // Handle one APD for that row.
          double weight = gain.GetValAt(i);
          double apd_magnitude = sqlite3_column_double(prep_stmt_pos, 1 + i);
          WeightedSumMagnitudes[i] += weight*apd_magnitude;
          SumSquareWeights[i] += weight*weight;
        }
      }
      if(ret != SQLITE_DONE) {
        std::cerr << "Query returned failure." << std::endl;
        exit(1);
      }
      ret = sqlite3_reset(prep_stmt_pos);
      if(ret != SQLITE_OK) {
        std::cerr << "Failed to reset a statement." << std::endl;
        exit(1);
      }

      // Update the lightmap values for this bin, overwriting the old ones.
      for(size_t i = 0; i < APDIndex.MaxIndex(); i++) {
        if(WeightedSumMagnitudes[i] <= 0) posFunc.GetValAt(posBin, i) = 0;
        else posFunc.GetValAt(posBin, i) = WeightedSumMagnitudes[i]/SumSquareWeights[i];
      }
    }

    std::cout << "Done computing the position function." << std::endl;
    std::cout << "Computing the gain function, holding the position function fixed." << std::endl;

    for(size_t gainBin = 0; gainBin < gainFunc.NumSnapshots(); gainBin++) {
      LightMap::GainSnapshot& gain = gainFunc.GainAtIndex(gainBin);

      // Bind the run range parameters to the query.
      bool success = (
        sqlite3_bind_int(prep_stmt_run, 1, gain.FirstRun()) == SQLITE_OK and
        sqlite3_bind_int(prep_stmt_pos, 2, gain.LastRun()) == SQLITE_OK);
      if(not success) {
        std::cerr << "Failed to bind values to a select statement." << std::endl;
        exit(1);
      }

      // Retrieve all events which fall in this bin.
      // For each APD, we wish to compute the weighted sum of magnitudes
      // and the sum of square weights.
      LightMap::FuncVsAPD WeightedSumMagnitudes;
      LightMap::FuncVsAPD SumSquareWeights;
      for(size_t i = 0; i < APDIndex.MaxIndex(); i++) {
        WeightedSumMagnitudes[i] = 0;
        SumSquareWeights[i] = 0;
      }
      while((ret = sqlite3_step(prep_stmt_run)) == SQLITE_ROW) {
        // Handle a row.
        double xpos = sqlite3_column_double(prep_stmt_run, 0);
        double ypos = sqlite3_column_double(prep_stmt_run, 1);
        double zpos = sqlite3_column_double(prep_stmt_run, 2);

        size_t posBin = posFunc.PosIndex().IndexForKey(std::make_pair(std::make_pair(xpos, ypos), zpos));
        if(posBin >= posFunc.PosIndex().MaxIndex()) continue; // Kills events out of boundary for lightmap.
        const LightMap::FuncVsAPD& posFuncAtBin = posFunc.GetAllValsAt(posBin);

        for(size_t i = 0; i < APDIndex.MaxIndex(); i++) {
          // Handle one APD for that row.
          double weight = posFuncAtBin[i];
          double apd_magnitude = sqlite3_column_double(prep_stmt_run, 3 + i);
          WeightedSumMagnitudes[i] += weight*apd_magnitude;
          SumSquareWeights[i] += weight*weight;
        }
      }
      if(ret != SQLITE_DONE) {
        std::cerr << "Query returned failure." << std::endl;
        exit(1);
      }
      ret = sqlite3_reset(prep_stmt_run);
      if(ret != SQLITE_OK) {
        std::cerr << "Failed to reset a statement." << std::endl;
        exit(1);
      }

      // Update the gain snapshot, overwriting the old ones.
      for(size_t i = 0; i < APDIndex.MaxIndex(); i++) {
        if(WeightedSumMagnitudes[i] <= 0) gain.GetValAt(i) = 0;
        else gain.GetValAt(i) = WeightedSumMagnitudes[i]/SumSquareWeights[i];
      }
    }
    std::cout << "Done computing the gain function." << std::endl;
  } // End loop over iterations.

  // Clean up sqlite resources.
  ret = sqlite3_finalize(prep_stmt_pos);
  if(ret != SQLITE_OK) {
    std::cerr << "Failed to finalize an sqlite statement." << std::endl;
    std::cerr << "We'll finish up because we (probably) can, but this should be fixed." << std::endl;
  }
  ret = sqlite3_finalize(prep_stmt_run);
  if(ret != SQLITE_OK) {
    std::cerr << "Failed to finalize an sqlite statement." << std::endl;
    std::cerr << "We'll finish up because we (probably) can, but this should be fixed." << std::endl;
  }
  ret = sqlite3_close_v2(connection);
  if(ret != SQLITE_OK) {
    std::cerr << "Failed to close the sqlite connection." << std::endl;
    std::cerr << "We'll finish up because we (probably) can, but this should be fixed." << std::endl;
  }

  // We know relative R(x) and S(t) -- fix them using [hard-coded] laser data.
  // The laser data used is from laser run 4540.
  // NOTE: by the time of run 4540, channel 163 was already disconnected, so the number here is made up.
  // NOTE: it would be great in the future to do a better correspondence between
  // absolute gain measurements from laser runs and relative gain measurements from thorium.
  for(size_t i = 0; i < APDIndex.MaxIndex(); i++) {
    double laser_gain;
    switch(APDIndex.KeyForIndex(i)) {
      case 152: laser_gain = 201.230438146; break;
      case 153: laser_gain = 178.750438779; break;
      case 154: laser_gain = 194.228589338; break;
      case 155: laser_gain = 183.33801615; break;
      case 156: laser_gain = 218.485999976; break;
      case 157: laser_gain = 222.139259152; break;
      case 158: laser_gain = 169.982559736; break;
      case 159: laser_gain = 140.385120552; break;
      case 160: laser_gain = 137.602725389; break;
      case 161: laser_gain = 197.78183714; break;
      case 162: laser_gain = 155.478773762; break;
      case 163: laser_gain = 200; break; // FICTITIOUS, but this channel was disconnected Feb 2012.  Better guess?
      case 164: laser_gain = 175.875067527; break;
      case 165: laser_gain = 160.014408865; break;
      case 166: laser_gain = 183.408055613; break;
      case 167: laser_gain = 189.600819126; break;
      case 168: laser_gain = 160.339214431; break;
      case 169: laser_gain = 168.547991045; break;
      case 170: laser_gain = 182.670039836; break;
      case 171: laser_gain = 205.567802982; break;
      case 172: laser_gain = 195.87450621; break;
      case 173: laser_gain = 224.956647122; break;
      case 174: laser_gain = 232.062359991; break;
      case 175: laser_gain = 241.822881767; break;
      case 176: laser_gain = 194.740435753; break;
      case 177: laser_gain = 189.867775084; break;
      // case 178: laser_gain = 0; // Bad channel, omitted.
      case 179: laser_gain = 206.755206938; break;
      case 180: laser_gain = 207.822617603; break;
      case 181: laser_gain = 207.501985741; break;
      case 182: laser_gain = 218.213137769; break;
      case 183: laser_gain = 234.369354843; break;
      case 184: laser_gain = 99.908111992; break;
      case 185: laser_gain = 238.381809313; break;
      case 186: laser_gain = 225.118270743; break;
      case 187: laser_gain = 199.078450518; break;
      case 188: laser_gain = 221.863823239; break;
      case 189: laser_gain = 177.032783679; break;
      case 190: laser_gain = 196.787332164; break;
      // case 191: laser_gain = 0; // Bad channel, omitted.
      case 192: laser_gain = 194.923448865; break;
      case 193: laser_gain = 197.027984846; break;
      case 194: laser_gain = 202.757086104; break;
      case 195: laser_gain = 194.432937658; break;
      case 196: laser_gain = 208.992809367; break;
      case 197: laser_gain = 224.762562055; break;
      case 198: laser_gain = 217.696006443; break;
      case 199: laser_gain = 222.380158829; break;
      case 200: laser_gain = 218.358804472; break;
      case 201: laser_gain = 209.573057132; break;
      case 202: laser_gain = 194.684536629; break;
      case 203: laser_gain = 182.543842783; break;
      case 204: laser_gain = 193.469930111; break;
      // case 205: laser_gain = 0; // Bad channel, omitted.
      case 206: laser_gain = 193.627191472; break;
      case 207: laser_gain = 196.073150574; break;
      case 208: laser_gain = 189.597962521; break;
      case 209: laser_gain = 198.824317108; break;
      case 210: laser_gain = 222.747770671; break;
      case 211: laser_gain = 216.928470825; break;
      case 212: laser_gain = 223.437239807; break;
      case 213: laser_gain = 224.316404923; break;
      case 214: laser_gain = 216.26783603; break;
      case 215: laser_gain = 209.612423384; break;
      case 216: laser_gain = 223.041660884; break;
      case 217: laser_gain = 202.642254512; break;
      case 218: laser_gain = 213.904993632; break;
      case 219: laser_gain = 221.988942321; break;
      case 220: laser_gain = 201.427174798; break;
      case 221: laser_gain = 196.689200146; break;
      case 222: laser_gain = 191.457656123; break;
      case 223: laser_gain = 186.183873541; break;
      case 224: laser_gain = 217.033080346; break;
      case 225: laser_gain = 205.858374653; break;
      default: laser_gain = 0; // Bad or non-existent channel.
    }

    double thorium_gain = gainFunc.GainForRun(4540).GetValAt(i);

    if(laser_gain == 0 or thorium_gain == 0) continue;

    double ratio_gains = laser_gain/thorium_gain;
    for(size_t j = 0; j < gainFunc.NumSnapshots(); j++) {
      gainFunc.GainAtIndex(j).GetValAt(i) *= ratio_gains;
    }
    for(size_t j = 0; j < posFunc.PosIndex().MaxIndex(); j++) {
      posFunc.GetValAt(j, i) /= ratio_gains; // To keep the product of R and S the same.
    }
  }

  // We've generated a good (hopefully) lightmap -- now write it to file.
  std::cout << "Finished generating lightmap -- write to Tmp/LightMap.hdf5." << std::endl;
  LightMapIO::WriteLightMap("Tmp/LightMap.hdf5", posFunc, gainFunc);
  std::cout << "Done writing the lightmap to file.  Have a nice day." << std::endl;
}
Exemplo n.º 9
0
int SQLite::BindInt(sqlite3_stmt *pStmt, int pos, int value) {
  BOOST_LOG_TRIVIAL(debug) << "database::SQLite::BindInt: Function call";
  return sqlite3_bind_int(pStmt, pos, value);
}
Exemplo n.º 10
0
ActionItemPtr
ActionLog::AddRemoteAction(const Name& deviceName, sqlite3_int64 seqno, shared_ptr<Data> actionData)
{
  if (!actionData) {
    _LOG_ERROR("actionData is not valid");
    return ActionItemPtr();
  }
  ActionItemPtr action = deserializeMsg<ActionItem>(
    Buffer(actionData->getContent().value(), actionData->getContent().value_size()));

  if (!action) {
    _LOG_ERROR("action cannot be decoded");
    return ActionItemPtr();
  }

  _LOG_DEBUG("AddRemoteAction: [" << deviceName.toUri() << "] seqno: " << seqno);

  sqlite3_stmt* stmt;
  sqlite3_prepare_v2(m_db,
                     "INSERT INTO ActionLog "
                     "(device_name, seq_no, action, filename, version, action_timestamp, "
                     "file_hash, file_atime, file_mtime, file_ctime, file_chmod, file_seg_num, "
                     "parent_device_name, parent_seq_no, "
                     "action_name, action_content_object) "
                     "VALUES (?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
                     "        ?, datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), datetime(?, 'unixepoch'), ?,?, "
                     "        ?, ?, "
                     "        ?, ?);",
                     -1, &stmt, 0);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_blob(stmt, 1, deviceName.wireEncode().wire(), deviceName.wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 2, seqno);

  sqlite3_bind_int(stmt, 3, action->action());
  sqlite3_bind_text(stmt, 4, action->filename().c_str(), action->filename().size(), SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 5, action->version());
  sqlite3_bind_int64(stmt, 6, action->timestamp());

  if (action->action() == ActionItem::UPDATE) {
    sqlite3_bind_blob(stmt, 7, action->file_hash().c_str(), action->file_hash().size(),
                      SQLITE_STATIC);

    // sqlite3_bind_int64(stmt, 8, atime); // NULL
    sqlite3_bind_int64(stmt, 9, action->mtime());
    // sqlite3_bind_int64(stmt, 10, ctime); // NULL

    sqlite3_bind_int(stmt, 11, action->mode());
    sqlite3_bind_int(stmt, 12, action->seg_num());
  }

  if (action->has_parent_device_name()) {
    sqlite3_bind_blob(stmt, 13, action->parent_device_name().c_str(),
                      action->parent_device_name().size(), SQLITE_STATIC);
    sqlite3_bind_int64(stmt, 14, action->parent_seq_no());
  }

  Name actionName = Name(deviceName);
  actionName.append("action").append(m_sharedFolderName).appendNumber(seqno);

  sqlite3_bind_blob(stmt, 15, actionName.wireEncode().wire(), actionName.wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_bind_blob(stmt, 16, actionData->wireEncode().wire(), actionData->wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_step(stmt);

  // if action needs to be applied to file state, the trigger will take care of it

  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  sqlite3_finalize(stmt);

  // I had a problem including directory_name assignment as part of the initial insert.
  sqlite3_prepare_v2(m_db,
                     "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?",
                     -1, &stmt, 0);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_blob(stmt, 1, deviceName.wireEncode().wire(), deviceName.wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 2, seqno);
  sqlite3_step(stmt);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  sqlite3_finalize(stmt);

  return action;
}
Exemplo n.º 11
0
/**
 * @todo Figure out the way to minimize code duplication
 */
bool
ActionLog::LookupActionsForFile(
  const function<void(const Name& name, sqlite3_int64 seq_no, const ActionItem&)>& visitor,
  const std::string& file, int offset /*=0*/, int limit /*=-1*/)
{
  _LOG_DEBUG("LookupActionsInFolderRecursively: [" << file << "]");
  if (file.empty())
    return false;

  if (limit >= 0)
    limit += 1; // to check if there is more data

  sqlite3_stmt* stmt;
  sqlite3_prepare_v2(m_db,
                     "SELECT device_name,seq_no,action,filename,directory,version,strftime('%s', action_timestamp), "
                     "       file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num, "
                     "       parent_device_name,parent_seq_no "
                     "   FROM ActionLog "
                     "   WHERE filename=? "
                     "   ORDER BY action_timestamp DESC "
                     "   LIMIT ? OFFSET ?",
                     -1, &stmt,
                     0); // there is a small ambiguity with is_prefix matching, but should be ok for now
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_text(stmt, 1, file.c_str(), file.size(), SQLITE_STATIC);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_int(stmt, 2, limit);
  sqlite3_bind_int(stmt, 3, offset);

  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  while (sqlite3_step(stmt) == SQLITE_ROW) {
    if (limit == 1)
      break;

    ActionItem action;

    Name device_name(Block(reinterpret_cast<const uint8_t*>(sqlite3_column_blob(stmt, 0)),
                           sqlite3_column_bytes(stmt, 0)));

    sqlite3_int64 seq_no = sqlite3_column_int64(stmt, 1);
    action.set_action(static_cast<ActionItem_ActionType>(sqlite3_column_int(stmt, 2)));
    action.set_filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3)),
                        sqlite3_column_bytes(stmt, 3));
    std::string directory(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4)),
                          sqlite3_column_bytes(stmt, 4));
    action.set_version(sqlite3_column_int64(stmt, 5));
    action.set_timestamp(sqlite3_column_int64(stmt, 6));

    if (action.action() == 0) {
      action.set_file_hash(sqlite3_column_blob(stmt, 7), sqlite3_column_bytes(stmt, 7));
      action.set_mtime(sqlite3_column_int(stmt, 8));
      action.set_mode(sqlite3_column_int(stmt, 9));
      action.set_seg_num(sqlite3_column_int64(stmt, 10));
    }
    if (sqlite3_column_bytes(stmt, 11) > 0) {
      action.set_parent_device_name(sqlite3_column_blob(stmt, 11), sqlite3_column_bytes(stmt, 11));
      action.set_parent_seq_no(sqlite3_column_int64(stmt, 12));
    }

    visitor(device_name, seq_no, action);
    limit--;
  }

  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  sqlite3_finalize(stmt);

  return (limit == 1); // more data is available
}
Exemplo n.º 12
0
ActionItemPtr
ActionLog::AddLocalActionDelete(const std::string& filename)
{
  _LOG_DEBUG("Adding local action DELETE");

  sqlite3_exec(m_db, "BEGIN TRANSACTION;", 0, 0, 0);

  const Block device_name = m_syncLog->GetLocalName().wireEncode();
  sqlite3_int64 version;
  BufferPtr parent_device_name;
  sqlite3_int64 parent_seq_no = -1;

  sqlite3_int64 action_time = std::time(0);

  tie(version, parent_device_name, parent_seq_no) = GetLatestActionForFile(filename);
  if (!parent_device_name) // no records exist or file was already deleted
  {
    _LOG_DEBUG("Nothing to delete... [" << filename << "]");

    // just in case, remove data from FileState
    sqlite3_stmt* stmt;
    sqlite3_prepare_v2(m_db, "DELETE FROM FileState WHERE filename = ? ", -1, &stmt, 0);
    sqlite3_bind_text(stmt, 1, filename.c_str(), filename.size(), SQLITE_STATIC); // file

    sqlite3_step(stmt);

    _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

    sqlite3_finalize(stmt);

    sqlite3_exec(m_db, "END TRANSACTION;", 0, 0, 0);
    return ActionItemPtr();
  }
  version++;

  sqlite3_int64 seq_no = m_syncLog->GetNextLocalSeqNo();

  sqlite3_stmt* stmt;
  sqlite3_prepare_v2(m_db, "INSERT INTO ActionLog "
                           "(device_name, seq_no, action, filename, version, action_timestamp, "
                           "parent_device_name, parent_seq_no, "
                           "action_name, action_content_object) "
                           "VALUES(?, ?, ?, ?, ?, datetime(?, 'unixepoch'),"
                           "        ?, ?,"
                           "        ?, ?)",
                     -1, &stmt, 0);

  sqlite3_bind_blob(stmt, 1, device_name.wire(), device_name.size(), SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 2, seq_no);
  sqlite3_bind_int(stmt, 3, 1);
  sqlite3_bind_text(stmt, 4, filename.c_str(), filename.size(), SQLITE_STATIC); // file

  sqlite3_bind_int64(stmt, 5, version);
  sqlite3_bind_int64(stmt, 6, action_time);

  sqlite3_bind_blob(stmt, 7, parent_device_name->buf(), parent_device_name->size(), SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 8, parent_seq_no);

  ActionItemPtr item = make_shared<ActionItem>();
  item->set_action(ActionItem::DELETE);
  item->set_filename(filename);
  item->set_version(version);
  item->set_timestamp(action_time);
  item->set_parent_device_name(parent_device_name->buf(), parent_device_name->size());
  item->set_parent_seq_no(parent_seq_no);

  std::string item_msg;
  item->SerializeToString(&item_msg);

  // action name: /<device_name>/<appname>/action/<shared-folder>/<action-seq>
  Name actionName = Name("/");
  actionName.append(m_syncLog->GetLocalName()).append(m_appName).append("action");
  actionName.append(m_sharedFolderName).appendNumber(seq_no);
  _LOG_DEBUG("ActionName: " << actionName);

  shared_ptr<Data> actionData = make_shared<Data>();
  actionData->setName(actionName);
  actionData->setFreshnessPeriod(time::seconds(60));
  actionData->setContent(reinterpret_cast<const uint8_t*>(item_msg.c_str()), item_msg.size());
  m_keyChain.sign(*actionData);

  sqlite3_bind_blob(stmt, 9, actionName.wireEncode().wire(), actionName.wireEncode().size(),
                    SQLITE_STATIC);
  sqlite3_bind_blob(stmt, 10, actionData->wireEncode().wire(), actionData->wireEncode().size(),
                    SQLITE_STATIC);

  sqlite3_step(stmt);

  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  // cout << Name(parent_device_name) << endl;

  // assign name to the action, serialize action, and create content object

  sqlite3_finalize(stmt);

  // I had a problem including directory_name assignment as part of the initial insert.
  sqlite3_prepare_v2(m_db,
                     "UPDATE ActionLog SET directory=directory_name(filename) WHERE device_name=? AND seq_no=?",
                     -1, &stmt, 0);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_blob(stmt, 1, device_name.wire(), device_name.size(), SQLITE_STATIC);
  sqlite3_bind_int64(stmt, 2, seq_no);
  sqlite3_step(stmt);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  sqlite3_finalize(stmt);

  sqlite3_exec(m_db, "END TRANSACTION;", 0, 0, 0);

  return item;
}
Exemplo n.º 13
0
static int query_bfile(sqlite3* db) {
	int rc, rc2;
	sqlite3_stmt *pStmt, *pBfileStmt;
	char *photo;
	off_t offset;
	int row, id, bHdl, len, i;
	const char *sql_bfile_open =
		"SELECT id, BFILE_OPEN(photo) FROM test_bfile;";
	const char *sql_bfile_read = "SELECT BFILE_READ(?, ?, ?);";
	const char *sql_bfile_close = "SELECT BFILE_CLOSE(?);";
	const int amount = 80;

	pStmt = NULL;
	printf("\nRUNNING: query id, photo\n");

	/* BFILE_OPEN */
	rc = sqlite3_prepare(db, sql_bfile_open, -1, &pStmt, 0);
	if (rc != SQLITE_OK) {
		printf("BFILE_OPEN: prepare error\n");
		return -1;
	}

	row = 0;
	while (SQLITE_ROW == (rc = sqlite3_step(pStmt))) {
		printf("-------------row%d------------\n", ++row);

		id = sqlite3_column_int(pStmt, 0);
		bHdl = sqlite3_column_int(pStmt, 1);

		printf("id:\n%d\nphoto:\n", id);

		if ((void*)bHdl == NULL) {
			printf("NULL\n");
			continue;
		}

		offset = 0;

		/* BFILE_READ */
		rc2 = sqlite3_prepare(db, sql_bfile_read, -1, &pBfileStmt, 0);
		cleanup_if_error(rc2, cleanup_read);

		while (1) {
			rc2 = sqlite3_bind_int(pBfileStmt, 1, bHdl);
			cleanup_if_error(rc2, cleanup_read);

			rc2 = sqlite3_bind_int(pBfileStmt, 2, amount);
			cleanup_if_error(rc2, cleanup_read);

			rc2 = sqlite3_bind_int(pBfileStmt, 3, offset);
			cleanup_if_error(rc2, cleanup_read);

			rc2 = sqlite3_step(pBfileStmt);
			cleanup_if_error(rc2, cleanup_read);

			if (rc2 == SQLITE_ROW) {
				photo = 
					(char*)sqlite3_column_blob(pBfileStmt, 0);
				len = sqlite3_column_bytes(pBfileStmt, 0);

				/* EOF */
				if (len == 0)
					break;

				for(i=0; i<len; i++)
					putchar(photo[i]);
			}

			rc2 = sqlite3_reset(pBfileStmt);
			cleanup_if_error(rc2, cleanup_read);

			rc2 = sqlite3_clear_bindings(pBfileStmt);
			cleanup_if_error(rc2, cleanup_read);

			offset += amount;
		}

cleanup_read:		
		if (pBfileStmt != NULL) {
			sqlite3_finalize(pBfileStmt);
			pBfileStmt = NULL;
		}

		/* BFILE_CLOSE */
		rc2 = sqlite3_prepare(db, sql_bfile_close, -1, &pBfileStmt, 0);
		cleanup_if_error(rc2, cleanup_close);

		rc2 = sqlite3_bind_int(pBfileStmt, 1, bHdl);
		cleanup_if_error(rc2, cleanup_close);

		rc2 = sqlite3_step(pBfileStmt);

cleanup_close:
		if (pBfileStmt != NULL) {
			sqlite3_finalize(pBfileStmt);
			pBfileStmt = NULL;
		}
	}

	if (pStmt != NULL) {
		sqlite3_finalize(pStmt);
		pStmt = NULL;
	}

	if (!is_error(rc) && is_error(rc2))
		rc = rc2;

	rc = !is_error(rc) ? 0 : -1;
	return rc;
}
Exemplo n.º 14
0
void SQLiteStatement::bindInt(int index, int32_t value)
{
    sqlite3_bind_int(handle_, index, value);
}
Exemplo n.º 15
0
static int
_bind_arg(lua_State *T, int t_idx, sqlite3_stmt *stmt, int s_idx)
{
	int ret = 0;
	int kind = lua_type(T, t_idx);

kind_is_known:

	switch (kind) {
	case LUA_TNIL:
		/* Should nil mean NULL..
		ret = sqlite3_bind_null(stmt, i-1);
		break;
		..or don't bind.. */
		return SQLITE_OK;

	case LUA_TNUMBER:
		ret = sqlite3_bind_double(stmt, s_idx,
				lua_tonumber(T, t_idx));
		break;

	case LUA_TSTRING:
		{
			size_t len;
			const char *str = lua_tolstring(T, t_idx, &len);

			ret = sqlite3_bind_text(stmt, s_idx,
					str, len, SQLITE_STATIC);
		}
		break;

	case BIND_INT:
		ret = sqlite3_bind_int(stmt, s_idx,
				lua_tointeger(T, t_idx));
		break;

	case BIND_INT64:
		ret = sqlite3_bind_int(stmt, s_idx,
				lua_tointeger(T, t_idx));
		break;

	case BIND_BLOB:
		{
			size_t len;
			const char *str = lua_tolstring(T, t_idx, &len);

			ret = sqlite3_bind_blob(stmt, s_idx,
					str, len, SQLITE_STATIC);
		}
		break;

	case BIND_BLOB64:
		{
			size_t len;
			const char *str = lua_tolstring(T, t_idx, &len);

			ret = sqlite3_bind_blob64(stmt, s_idx,
					str, len, SQLITE_STATIC);
		}
		break;

	case BIND_ZEROBLOB:
			ret = sqlite3_bind_zeroblob(stmt, s_idx,
					lua_tointeger(T, t_idx));
		break;

	case BIND_ZEROBLOB64:
			ret = sqlite3_bind_zeroblob64(stmt, s_idx,
					lua_tointeger(T, t_idx));
		break;

	case LUA_TTABLE:
		{
			lua_rawgeti(T, t_idx, 1);
			kind = lua_tointeger(T, -1);
			lua_pop(T, 1);
			lua_rawgeti(T, t_idx, 2);

			t_idx = -1;
			goto kind_is_known;
		}

	default:
		(void)sqlite3_clear_bindings(stmt);
		return luaL_argerror(T, t_idx, "expected nil, number or string");
	}

	if (t_idx == -1) {
		lua_pop(T, 1);
	}

	return ret;
}
Exemplo n.º 16
0
/* migrate from the legacy db format (with the 'settings' blob) to the first version this system knows */
static gboolean _migrate_schema(dt_database_t *db, int version)
{
  gboolean all_ok = TRUE;
  const char *failing_query = NULL;
  sqlite3_stmt *stmt;
  sqlite3_stmt *innerstmt;

  if(version != 36) // if anyone shows up with an older db we can probably add extra code
    return FALSE;

  sqlite3_exec(db->handle, "BEGIN TRANSACTION", NULL, NULL, NULL);

  // remove stuff that is either no longer needed or that got renamed
  _SQLITE3_EXEC(db->handle, "DROP TABLE IF EXISTS lock", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE IF EXISTS settings", NULL, NULL, NULL); // yes, we do this in many places. because it's really important to not miss it in any code path.
  _SQLITE3_EXEC(db->handle, "DROP INDEX IF EXISTS group_id_index", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP INDEX IF EXISTS imgid_index", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE IF EXISTS mipmaps", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE IF EXISTS mipmap_timestamps", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE IF EXISTS dt_migration_table", NULL, NULL, NULL);

  // using _create_schema() and filling that with the old data doesn't work since we always want to generate version 1 tables
  ////////////////////////////// db_info
  _SQLITE3_EXEC(db->handle, "CREATE TABLE db_info (key VARCHAR PRIMARY KEY, value VARCHAR)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "INSERT OR REPLACE INTO db_info (key, value) VALUES ('version', 1)", NULL, NULL, NULL);
  ////////////////////////////// film_rolls
  _SQLITE3_EXEC(db->handle, "CREATE INDEX IF NOT EXISTS film_rolls_folder_index ON film_rolls (folder)", NULL, NULL, NULL);
  ////////////////////////////// images
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN orientation INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN focus_distance REAL", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN group_id INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN histogram BLOB", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN lightmap BLOB", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN longitude REAL", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN latitude REAL", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN color_matrix BLOB", NULL, NULL, NULL); // the color matrix
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN colorspace INTEGER", NULL, NULL, NULL); // the colorspace as specified in some image types
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN version INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE images ADD COLUMN max_version INTEGER", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE images SET orientation = -1 WHERE orientation IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE images SET focus_distance = -1 WHERE focus_distance IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE images SET group_id = id WHERE group_id IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE images SET max_version = (SELECT COUNT(*)-1 FROM images i WHERE i.filename = images.filename AND "
                            "i.film_id = images.film_id) WHERE max_version IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE images SET version = (SELECT COUNT(*) FROM images i WHERE i.filename = images.filename AND "
                            "i.film_id = images.film_id AND i.id < images.id) WHERE version IS NULL", NULL, NULL, NULL);
  // make sure we have AUTOINCREMENT on imgid --> move the whole thing away and recreate the table :(
  _SQLITE3_EXEC(db->handle, "ALTER TABLE images RENAME TO dt_migration_table", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP INDEX IF EXISTS images_group_id_index", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP INDEX IF EXISTS images_film_id_index", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "CREATE TABLE images (id INTEGER PRIMARY KEY AUTOINCREMENT, group_id INTEGER, film_id INTEGER, "
                            "width INTEGER, height INTEGER, filename VARCHAR, maker VARCHAR, model VARCHAR, "
                            "lens VARCHAR, exposure REAL, aperture REAL, iso REAL, focal_length REAL, "
                            "focus_distance REAL, datetime_taken CHAR(20), flags INTEGER, "
                            "output_width INTEGER, output_height INTEGER, crop REAL, "
                            "raw_parameters INTEGER, raw_denoise_threshold REAL, "
                            "raw_auto_bright_threshold REAL, raw_black REAL, raw_maximum REAL, "
                            "caption VARCHAR, description VARCHAR, license VARCHAR, sha1sum CHAR(40), "
                            "orientation INTEGER, histogram BLOB, lightmap BLOB, longitude REAL, "
                            "latitude REAL, color_matrix BLOB, colorspace INTEGER, version INTEGER, max_version INTEGER)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "CREATE INDEX images_group_id_index ON images (group_id)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "CREATE INDEX images_film_id_index ON images (film_id)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "INSERT INTO images (id, group_id, film_id, width, height, filename, maker, model, "
                            "lens, exposure, aperture, iso, focal_length, focus_distance, datetime_taken, flags, "
                            "output_width, output_height, crop, raw_parameters, raw_denoise_threshold, "
                            "raw_auto_bright_threshold, raw_black, raw_maximum, caption, description, license, sha1sum, "
                            "orientation, histogram, lightmap, longitude, latitude, color_matrix, colorspace, version, max_version) "
                            "SELECT id, group_id, film_id, width, height, filename, maker, model, lens, exposure, aperture, iso, "
                            "focal_length, focus_distance, datetime_taken, flags, output_width, output_height, crop, "
                            "raw_parameters, raw_denoise_threshold, raw_auto_bright_threshold, raw_black, raw_maximum, "
                            "caption, description, license, sha1sum, orientation, histogram, lightmap, longitude, "
                            "latitude, color_matrix, colorspace, version, max_version FROM dt_migration_table", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE dt_migration_table", NULL, NULL, NULL);
  ////////////////////////////// selected_images
  // selected_images should have a primary key. add it if it's missing:
  _SQLITE3_EXEC(db->handle, "CREATE TEMPORARY TABLE dt_migration_table (imgid INTEGER)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "INSERT INTO dt_migration_table SELECT imgid FROM selected_images", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE selected_images", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "CREATE TABLE selected_images (imgid INTEGER PRIMARY KEY)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "INSERT OR IGNORE INTO selected_images SELECT imgid FROM dt_migration_table", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE dt_migration_table", NULL, NULL, NULL);
  ////////////////////////////// history
  sqlite3_exec(db->handle, "ALTER TABLE history ADD COLUMN blendop_params BLOB", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE history ADD COLUMN blendop_version INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE history ADD COLUMN multi_priority INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE history ADD COLUMN multi_name VARCHAR(256)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "CREATE INDEX IF NOT EXISTS history_imgid_index ON history (imgid)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE history SET blendop_version = 1 WHERE blendop_version IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE history SET multi_priority = 0 WHERE multi_priority IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE history SET multi_name = ' ' WHERE multi_name IS NULL", NULL, NULL, NULL);
  ////////////////////////////// mask
  _SQLITE3_EXEC(db->handle, "CREATE TABLE IF NOT EXISTS mask (imgid INTEGER, formid INTEGER, form INTEGER, name VARCHAR(256), version INTEGER, "
                            "points BLOB, points_count INTEGER, source BLOB)", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE mask ADD COLUMN source BLOB", NULL, NULL, NULL); // in case the table was there already but missed that column
  ////////////////////////////// tagged_images
  _SQLITE3_EXEC(db->handle, "CREATE INDEX IF NOT EXISTS tagged_images_tagid_index ON tagged_images (tagid)", NULL, NULL, NULL);
  ////////////////////////////// styles
  _SQLITE3_EXEC(db->handle, "CREATE TABLE IF NOT EXISTS styles (id INTEGER, name VARCHAR, description VARCHAR)", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE styles ADD COLUMN id INTEGER", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE styles SET id = rowid WHERE id IS NULL", NULL, NULL, NULL);
  ////////////////////////////// style_items
  _SQLITE3_EXEC(db->handle, "CREATE TABLE IF NOT EXISTS style_items (styleid INTEGER, num INTEGER, module INTEGER, operation VARCHAR(256), op_params BLOB, "
                            "enabled INTEGER, blendop_params BLOB, blendop_version INTEGER, multi_priority INTEGER, multi_name VARCHAR(256))", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE style_items ADD COLUMN blendop_params BLOB", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE style_items ADD COLUMN blendop_version INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE style_items ADD COLUMN multi_priority INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE style_items ADD COLUMN multi_name VARCHAR(256)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE style_items SET blendop_version = 1 WHERE blendop_version IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE style_items SET multi_priority = 0 WHERE multi_priority IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE style_items SET multi_name = ' ' WHERE multi_name IS NULL", NULL, NULL, NULL);
  ////////////////////////////// color_labels
  // color_labels could have a PRIMARY KEY that we don't want
  _SQLITE3_EXEC(db->handle, "CREATE TEMPORARY TABLE dt_migration_table (imgid INTEGER, color INTEGER)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "INSERT INTO dt_migration_table SELECT imgid, color FROM color_labels", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE color_labels", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "CREATE TABLE color_labels (imgid INTEGER, color INTEGER)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "CREATE UNIQUE INDEX color_labels_idx ON color_labels (imgid, color)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "INSERT OR IGNORE INTO color_labels SELECT imgid, color FROM dt_migration_table", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "DROP TABLE dt_migration_table", NULL, NULL, NULL);
  ////////////////////////////// meta_data
  _SQLITE3_EXEC(db->handle, "CREATE TABLE IF NOT EXISTS meta_data (id INTEGER, key INTEGER, value VARCHAR)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "CREATE INDEX IF NOT EXISTS metadata_index ON meta_data (id, key)", NULL, NULL, NULL);
  ////////////////////////////// presets
  _SQLITE3_EXEC(db->handle, "CREATE TABLE IF NOT EXISTS presets (name VARCHAR, description VARCHAR, operation VARCHAR, op_version INTEGER, op_params BLOB, "
                            "enabled INTEGER, blendop_params BLOB, blendop_version INTEGER, multi_priority INTEGER, multi_name VARCHAR(256), "
                            "model VARCHAR, maker VARCHAR, lens VARCHAR, iso_min REAL, iso_max REAL, exposure_min REAL, exposure_max REAL, "
                            "aperture_min REAL, aperture_max REAL, focal_length_min REAL, focal_length_max REAL, writeprotect INTEGER, "
                            "autoapply INTEGER, filter INTEGER, def INTEGER, isldr INTEGER)", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE presets ADD COLUMN op_version INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE presets ADD COLUMN blendop_params BLOB", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE presets ADD COLUMN blendop_version INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE presets ADD COLUMN multi_priority INTEGER", NULL, NULL, NULL);
  sqlite3_exec(db->handle, "ALTER TABLE presets ADD COLUMN multi_name VARCHAR(256)", NULL, NULL, NULL);
  // the unique index only works if the db doesn't have any (name, operation, op_version) more than once. apparently there are dbs out there which do have that. :(
  sqlite3_prepare_v2(db->handle, "SELECT p.rowid, p.name, p.operation, p.op_version FROM presets p INNER JOIN "
                                 "(SELECT * FROM (SELECT rowid, name, operation, op_version, COUNT(*) AS count "
                                 "FROM presets GROUP BY name, operation, op_version) WHERE count > 1) s "
                                 "ON p.name = s.name AND p.operation = s.operation AND p.op_version = s.op_version", -1, &stmt, NULL);
  char *last_name = NULL, *last_operation = NULL;
  int last_op_version = 0;
  int i = 0;
  while(sqlite3_step(stmt) == SQLITE_ROW)
  {
    int rowid = sqlite3_column_int(stmt, 0);
    const char* name = (const char*)sqlite3_column_text(stmt, 1);
    const char* operation = (const char*)sqlite3_column_text(stmt, 2);
    int op_version = sqlite3_column_int(stmt, 3);

    // is it still the same (name, operation, op_version) triple?
    if(!last_name || strcmp(last_name, name) || !last_operation || strcmp(last_operation, operation) || last_op_version != op_version)
    {
      g_free(last_name);
      g_free(last_operation);
      last_name = g_strdup(name);
      last_operation = g_strdup(operation);
      last_op_version = op_version;
      i = 0;
    }

    // find the next free ammended version of name
    sqlite3_prepare_v2(db->handle, "SELECT name FROM presets  WHERE name = ?1 || ' (' || ?2 || ')' AND operation = ?3 AND op_version = ?4", -1, &innerstmt, NULL);
    while(1)
    {
      sqlite3_bind_text(innerstmt, 1, name, -1, SQLITE_TRANSIENT);
      sqlite3_bind_int(innerstmt, 2, i);
      sqlite3_bind_text(innerstmt, 3, operation, -1, SQLITE_TRANSIENT);
      sqlite3_bind_int(innerstmt, 4, op_version);
      if(sqlite3_step(innerstmt) != SQLITE_ROW)
        break;
      sqlite3_reset(innerstmt);
      sqlite3_clear_bindings(innerstmt);
      i++;
    }
    sqlite3_finalize(innerstmt);

    // rename preset
    const char *query = "UPDATE presets SET name = name || ' (' || ?1 || ')' WHERE rowid = ?2";
    sqlite3_prepare_v2(db->handle, query, -1, &innerstmt, NULL);
    sqlite3_bind_int(innerstmt, 1, i);
    sqlite3_bind_int(innerstmt, 2, rowid);
    if(sqlite3_step(innerstmt) != SQLITE_DONE)
    {
      all_ok = FALSE;
      failing_query = query;
      goto end;
    }
    sqlite3_finalize(innerstmt);
  }
  sqlite3_finalize(stmt);
  g_free(last_name);
  g_free(last_operation);
  // now we should be able to create the index
  _SQLITE3_EXEC(db->handle, "CREATE UNIQUE INDEX IF NOT EXISTS presets_idx ON presets (name, operation, op_version)", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE presets SET blendop_version = 1 WHERE blendop_version IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE presets SET multi_priority = 0 WHERE multi_priority IS NULL", NULL, NULL, NULL);
  _SQLITE3_EXEC(db->handle, "UPDATE presets SET multi_name = ' ' WHERE multi_name IS NULL", NULL, NULL, NULL);


  // There are systems where absolute paths don't start with '/' (like Windows).
  // Since the bug which introduced absolute paths to the db was fixed before a
  // Windows build was available this shouldn't matter though.
  sqlite3_prepare_v2(db->handle, "SELECT id, filename FROM images WHERE filename LIKE '/%'", -1, &stmt, NULL);
  sqlite3_prepare_v2(db->handle, "UPDATE images SET filename = ?1 WHERE id = ?2", -1, &innerstmt, NULL);
  while(sqlite3_step(stmt) == SQLITE_ROW)
  {
    int id           = sqlite3_column_int(stmt, 0);
    const char* path = (const char*)sqlite3_column_text(stmt, 1);
    gchar* filename  = g_path_get_basename (path);
    sqlite3_bind_text(innerstmt, 1, filename, -1, SQLITE_TRANSIENT);
    sqlite3_bind_int(innerstmt, 2, id);
    sqlite3_step(innerstmt);
    sqlite3_reset(innerstmt);
    sqlite3_clear_bindings(innerstmt);
    g_free(filename);
  }
  sqlite3_finalize(stmt);
  sqlite3_finalize(innerstmt);

  // We used to insert datetime_taken entries with '-' as date separators. Since that doesn't work well with the regular ':' when parsing
  // or sorting we changed it to ':'. This takes care to change what we have as leftovers
  _SQLITE3_EXEC(db->handle, "UPDATE images SET datetime_taken = REPLACE(datetime_taken, '-', ':') WHERE datetime_taken LIKE '%-%'", NULL, NULL, NULL);

end:
  if(all_ok)
    sqlite3_exec(db->handle, "COMMIT", NULL, NULL, NULL);
  else
  {
    fprintf(stderr, "[init] failing query: `%s'\n", failing_query);
    fprintf(stderr, "[init]   %s\n", sqlite3_errmsg(db->handle));
    sqlite3_exec(db->handle, "ROLLBACK TRANSACTION", NULL, NULL, NULL);
  }

  return all_ok;
}
Exemplo n.º 17
0
static void
album_query(bmdb_t *b, void *db)
{
    sqlite3_stmt *stmt;
    int rc;
    int album_id = atoi(b->b_query);

    rc = db_prepare(db, &stmt,
                    "SELECT album.title, artist.title "
                    "FROM album, artist "
                    "WHERE album.id = ?1 "
                    "AND artist.id = album.artist_id "
                    "AND album.ds_id = 1");

    if(rc != SQLITE_OK)
        return;

    sqlite3_bind_int(stmt, 1, album_id);

    if(db_step(stmt) == SQLITE_ROW) {
        rstr_t *album  = db_rstr(stmt, 0);
        rstr_t *artist = db_rstr(stmt, 1);

        prop_set(b->b_metadata, "title",       PROP_SET_RSTRING, album);
        prop_set(b->b_metadata, "artist_name", PROP_SET_RSTRING, artist);

        prop_t *p = prop_create_r(b->b_metadata, "album_art");
        metadata_bind_albumart(p, artist, album);
        prop_ref_dec(p);

        rstr_release(album);
        rstr_release(artist);
    }

    sqlite3_finalize(stmt);

    rc = db_prepare(db, &stmt,
                    "SELECT url, audioitem.title, track, duration, "
                    "artist.title "
                    "FROM audioitem,item,artist "
                    "WHERE audioitem.item_id = item.id "
                    "AND audioitem.artist_id = artist.id "
                    "AND album_id = ?1 "
                    "AND audioitem.ds_id = 1");

    if(rc != SQLITE_OK)
        return;

    sqlite3_bind_int(stmt, 1, album_id);

    rstr_t *ct = rstr_alloc("audio");

    while((rc = db_step(stmt)) == SQLITE_ROW) {
        add_item(b, (const char *)sqlite3_column_text(stmt, 0),
                 NULL, ct,
                 (const char *)sqlite3_column_text(stmt, 1),
                 sqlite3_column_int(stmt, 2),
                 (const char *)sqlite3_column_text(stmt, 4),
                 sqlite3_column_int(stmt, 3));

    }
    rstr_release(ct);
    sqlite3_finalize(stmt);
}
Exemplo n.º 18
0
bool PDOSqliteStatement::paramHook(PDOBoundParam* param,
                                   PDOParamEvent event_type) {
  switch (event_type) {
  case PDO_PARAM_EVT_EXEC_PRE:
    if (executed && !m_done) {
      sqlite3_reset(m_stmt);
      m_done = 1;
    }

    if (param->is_param) {
      if (param->paramno == -1) {
        param->paramno = sqlite3_bind_parameter_index(m_stmt,
                                                      param->name.c_str()) - 1;
      }

      switch (PDO_PARAM_TYPE(param->param_type)) {
      case PDO_PARAM_STMT:
        return false;

      case PDO_PARAM_NULL:
        if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
          return true;
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_INT:
      case PDO_PARAM_BOOL:
        if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
        } else {
          if (SQLITE_OK == sqlite3_bind_int(m_stmt, param->paramno + 1,
                                            param->parameter.toInt64())) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_LOB:
        if (param->parameter.isResource()) {
          Variant buf = HHVM_FN(stream_get_contents)(
                        param->parameter.toResource());
          if (!same(buf, false)) {
            param->parameter = buf;
          } else {
            pdo_raise_impl_error(dbh, this, "HY105",
                                 "Expected a stream resource");
            return false;
          }
        } else if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
          handleError(__FILE__, __LINE__);
          return false;
        }

        {
          String sparam = param->parameter.toString();
          if (SQLITE_OK == sqlite3_bind_blob(m_stmt, param->paramno + 1,
                                             sparam.data(), sparam.size(),
                                             SQLITE_STATIC)) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;

      case PDO_PARAM_STR:
      default:
        if (param->parameter.isNull()) {
          if (sqlite3_bind_null(m_stmt, param->paramno + 1) == SQLITE_OK) {
            return true;
          }
        } else {
          String sparam = param->parameter.toString();
          if (SQLITE_OK == sqlite3_bind_text(m_stmt, param->paramno + 1,
                                             sparam.data(), sparam.size(),
                                             SQLITE_STATIC)) {
            return true;
          }
        }
        handleError(__FILE__, __LINE__);
        return false;
      }
    }
    break;

  default:;
  }
  return true;
}
Exemplo n.º 19
0
void Query::bindInt(int col, int val)
{
    sqlite3_bind_int(m_Stmt, col, val);
}
Exemplo n.º 20
0
static int pdo_sqlite_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param,
		enum pdo_param_event event_type)
{
	pdo_sqlite_stmt *S = (pdo_sqlite_stmt*)stmt->driver_data;
	zval *parameter;

	switch (event_type) {
		case PDO_PARAM_EVT_EXEC_PRE:
			if (stmt->executed && !S->done) {
				sqlite3_reset(S->stmt);
				S->done = 1;
			}

			if (param->is_param) {

				if (param->paramno == -1) {
					param->paramno = sqlite3_bind_parameter_index(S->stmt, ZSTR_VAL(param->name)) - 1;
				}

				switch (PDO_PARAM_TYPE(param->param_type)) {
					case PDO_PARAM_STMT:
						return 0;

					case PDO_PARAM_NULL:
						if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
							return 1;
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;

					case PDO_PARAM_INT:
					case PDO_PARAM_BOOL:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
						} else {
							convert_to_long(parameter);
#if ZEND_LONG_MAX > 2147483647
							if (SQLITE_OK == sqlite3_bind_int64(S->stmt, param->paramno + 1, Z_LVAL_P(parameter))) {
								return 1;
							}
#else
							if (SQLITE_OK == sqlite3_bind_int(S->stmt, param->paramno + 1, Z_LVAL_P(parameter))) {
								return 1;
							}
#endif
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;

					case PDO_PARAM_LOB:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_RESOURCE) {
							php_stream *stm = NULL;
							php_stream_from_zval_no_verify(stm, parameter);
							if (stm) {
								zend_string *mem = php_stream_copy_to_mem(stm, PHP_STREAM_COPY_ALL, 0);
								zval_ptr_dtor(parameter);
								ZVAL_STR(parameter, mem ? mem : ZSTR_EMPTY_ALLOC());
							} else {
								pdo_raise_impl_error(stmt->dbh, stmt, "HY105", "Expected a stream resource");
								return 0;
							}
						} else if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
							pdo_sqlite_error_stmt(stmt);
							return 0;
						} else {
							convert_to_string(parameter);
						}

						if (SQLITE_OK == sqlite3_bind_blob(S->stmt, param->paramno + 1,
								Z_STRVAL_P(parameter),
								Z_STRLEN_P(parameter),
								SQLITE_STATIC)) {
							return 1;
						}
						return 0;

					case PDO_PARAM_STR:
					default:
						if (Z_ISREF(param->parameter)) {
							parameter = Z_REFVAL(param->parameter);
						} else {
							parameter = &param->parameter;
						}
						if (Z_TYPE_P(parameter) == IS_NULL) {
							if (sqlite3_bind_null(S->stmt, param->paramno + 1) == SQLITE_OK) {
								return 1;
							}
						} else {
							convert_to_string(parameter);
							if (SQLITE_OK == sqlite3_bind_text(S->stmt, param->paramno + 1,
									Z_STRVAL_P(parameter),
									Z_STRLEN_P(parameter),
									SQLITE_STATIC)) {
								return 1;
							}
						}
						pdo_sqlite_error_stmt(stmt);
						return 0;
				}
			}
			break;

		default:
			;
	}
	return 1;
}
Exemplo n.º 21
0
int SQLiteSTMT::BindInt(int iCol, int value) {
  return sqlite3_bind_int(handle, iCol, value);
}
Exemplo n.º 22
0
int
ctdb_check_db_mode(struct ctdb_state *state)
{
	sqlite3_stmt		*stmt;
	char			*p, wanted;
	int			rc, rv = 0, curgenid, ver = -1;

	CNDBG(CT_LOG_DB, "ctdb mode %d\n", state->ctdb_crypt);
	if (sqlite3_prepare_v2(state->ctdb_db,
	    "SELECT crypto, version FROM mode", -1, &stmt, NULL)) {
		CNDBG(CT_LOG_DB, "can't prepare mode query statement");
		goto fail;
	}
	rc = sqlite3_step(stmt);
	if (rc == SQLITE_DONE) {
		CNDBG(CT_LOG_DB, "ctdb mode not found");
		goto fail;
	} else if (rc != SQLITE_ROW) {
		CNDBG(CT_LOG_DB, "could not step(%d) %d %d %s",
		    __LINE__, rc,
		    sqlite3_extended_errcode(state->ctdb_db),
		    sqlite3_errmsg(state->ctdb_db));
		goto fail;
	}
	p = (char *)sqlite3_column_text(stmt, 0);
	if (p) {
		wanted =  state->ctdb_crypt ? 'Y' : 'N';
		if (sqlite3_column_bytes(stmt, 0) != 1) {
			CNDBG(CT_LOG_DB, "ctdb invalid length of column 1");
			goto fail;
		}
		CNDBG(CT_LOG_DB, "ctdb crypto mode %c %c", p[0], wanted);
		if (p[0] != wanted) {
			CNDBG(CT_LOG_DB, "ctdb crypto mode differs %c %c",
			    p[0], wanted);
			goto fail;
		}
	}

	/* early version of localdb didn't fill in version correctly */
	if (sqlite3_column_type(stmt, 1) == SQLITE_NULL ||
	    (ver = sqlite3_column_int(stmt, 1)) < CT_DB_VERSION) {
		if (ctdb_upgrade_db(state, ver)) {
			CNDBG(CT_LOG_DB,"failed to upgrade db!");
			goto fail;
		}
	}
	if (sqlite3_finalize(stmt)) {
		CNDBG(CT_LOG_DB, "can't finalise statement");
		goto fail;
	}

	if (sqlite3_prepare_v2(state->ctdb_db, "SELECT value FROM genid",
	    -1, &stmt, NULL)) {
		CNDBG(CT_LOG_DB, "old format db detected, reseting db");
		goto fail;
	}
	rc = sqlite3_step(stmt);
	if (rc == SQLITE_DONE) {
		CNDBG(CT_LOG_DB, "ctdb genid not found");
		goto fail;
	} else if (rc != SQLITE_ROW) {
		CNDBG(CT_LOG_DB, "could not step(%d) %d %d %s", __LINE__,
		    rc, sqlite3_extended_errcode(state->ctdb_db),
		    sqlite3_errmsg(state->ctdb_db));
		goto fail;
	}
	curgenid = sqlite3_column_int(stmt, 0);
	sqlite3_finalize(stmt);
	stmt = NULL;

	if (state->ctdb_genid == -1 || state->ctdb_genid == curgenid) {
		state->ctdb_genid = curgenid;
	} else if (state->ctdb_genid > curgenid) {
		if (sqlite3_prepare(state->ctdb_db,
		    "UPDATE genid SET value = ?", -1, &stmt, NULL)) {
			CNDBG(CT_LOG_DB, "can't prepare update genid stmt");
			goto fail;
		}
		if (sqlite3_bind_int(stmt, 1, state->ctdb_genid) != 0) {
			CNDBG(CT_LOG_DB, "can't bind update genid stmt");
			goto fail;
		}
		if (sqlite3_step(stmt) != SQLITE_DONE) {
			CNDBG(CT_LOG_DB, "didn't get done on updating genid");
			goto fail;
		}
		CNDBG(CT_LOG_DB, "updated genid from %d to %d",
		    curgenid, state->ctdb_genid);
	} else {
		CNDBG(CT_LOG_DB, "ctdb genid is %d, wanted %d", curgenid,
		    state->ctdb_genid);
		goto fail;
	}

	CNDBG(CT_LOG_DB, "Mode check successful");
	rv = 1;
fail:
	/* not much we can do if this fails */
	if (stmt != NULL && sqlite3_finalize(stmt))
		CNDBG(CT_LOG_DB, "can't finalize verification lookup");
	return rv;
}
Exemplo n.º 23
0
int												// errors if < eBSFSuccess, if positive then the ExprID
CSQLiteDE::CreateExperiment(int CSVtype,		// 0 if short form, 1 if including individual bin counts
				char *pszInFile,				// CSV file containing expression analysis results
				char *pszExprName,				// experiment identifier
				char *pszExprDescr,				// describes experiment
				char *pszCtrlConditions,		// control conditions
				char *pszExprConditions,		// experiment conditions
				int NumBins)
{
int sqlite_error;
int ExprID;
char szExprName[128];
tsDEStmSQL *pStm;

if(m_pDB == NULL)
	return(eBSFerrInternal);

m_NumTransMRA = 0;
m_NumTrans = 0;
m_NumExpres = 0;

pStm = &m_StmSQL[0];
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 1, CSVtype))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_text(pStm->pPrepInsert, 2, pszInFile,(int)strlen(pszInFile)+1,SQLITE_STATIC))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_text(pStm->pPrepInsert, 3, pszExprName,(int)strlen(pszExprName)+1,SQLITE_STATIC))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_text(pStm->pPrepInsert, 4, pszExprDescr,(int)strlen(pszExprDescr)+1,SQLITE_STATIC))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_text(pStm->pPrepInsert, 5, pszCtrlConditions,(int)strlen(pszCtrlConditions)+1,SQLITE_STATIC))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_text(pStm->pPrepInsert, 6, pszExprConditions,(int)strlen(pszExprConditions)+1,SQLITE_STATIC))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 7, NumBins))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}

if((sqlite_error = sqlite3_step(pStm->pPrepInsert))!=SQLITE_DONE)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - step prepared statement: %s", sqlite3_errmsg(m_pDB));   
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
sqlite3_reset(pStm->pPrepInsert);

	// find out the ExprID assigned to this experiment
if(m_bSafe)
	{
	ExprID = -1;
	sprintf(szExprName,"select ExprID from TblExprs where ExprName LIKE '%s'",pszExprName);
	if((sqlite_error = sqlite3_exec(m_pDB,szExprName,ExecCallbackID,&ExprID,NULL))!=SQLITE_OK)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite3_exec - getting ExprID: %s", sqlite3_errmsg(m_pDB));   
		CloseDatabase(true);
		return(eBSFerrInternal);
		}
	}
else
	ExprID = (int)sqlite3_last_insert_rowid(m_pDB);

return(ExprID);
}
Exemplo n.º 24
0
int
ctdb_insert_sha(struct ctdb_state *state, uint8_t *sha_k, uint8_t *sha_v,
    uint8_t *iv, int32_t genid)
{
	char			shatk[SHA_DIGEST_STRING_LENGTH];
	char			shatv[SHA_DIGEST_STRING_LENGTH];
	int			rv, rc;
	sqlite3_stmt		*stmt;

	rv = 0;

	if (state == NULL || state->ctdb_db == NULL)
		return rv;

	stmt = state->ctdb_stmt_insert;

	if (state->ctdb_in_transaction == 0) {
		if (ctdb_begin_transaction(state) != 0)
			return (rv);
		state->ctdb_trans_commit_rem = OPS_PER_TRANSACTION;
	}

	if (clog_mask_is_set(CT_LOG_DB)) {
		ct_sha1_encode(sha_k, shatk);
		if (sha_v == NULL)
			shatv[0] = '\0';
		else
			ct_sha1_encode(sha_v, shatv);
		CNDBG(CT_LOG_DB, "inserting for bin %s, %s", shatk, shatv);
	}
	if (sqlite3_bind_blob(stmt, 1, sha_k, SHA_DIGEST_LENGTH,
	    SQLITE_STATIC)) {
		CNDBG(CT_LOG_DB, "could not bind sha_k");
		return rv;
	}
	if (state->ctdb_crypt) {
		if (sha_v == NULL || iv == NULL)
			CABORTX("crypt mode, but no sha_v/iv");
		if (sqlite3_bind_blob(stmt, 2, sha_v,
		    SHA_DIGEST_LENGTH, SQLITE_STATIC)) {
			CNDBG(CT_LOG_DB, "could not bind sha_v");
			sqlite3_reset(stmt);
			return rv;
		}

		if (sqlite3_bind_blob(stmt, 3, iv,
		    CT_IV_LEN, SQLITE_STATIC)) {
			CNDBG(CT_LOG_DB, "could not bind iv ");
			sqlite3_reset(stmt);
			return rv;
		}
		if (sqlite3_bind_int(stmt, 4, genid) != 0) {
			CNDBG(CT_LOG_DB, "could not bind genid");
			sqlite3_reset(stmt);
			return rv;
		}
	} else {
		if (sqlite3_bind_int(stmt, 2, genid) != 0) {
			CNDBG(CT_LOG_DB, "could not bind genid");
			sqlite3_reset(stmt);
			return rv;
		}

	}

	rc = sqlite3_step(stmt);
	if (rc == SQLITE_DONE) {
		CNDBG(CT_LOG_DB, "insert completed");
		rv = 1;
	} else if (rc != SQLITE_CONSTRAINT) {
		CNDBG(CT_LOG_DB, "insert failed %d %d [%s]", rc,
		    sqlite3_extended_errcode(state->ctdb_db),
		    sqlite3_errmsg(state->ctdb_db));
	} else  {
		CNDBG(CT_LOG_DB, "sha already exists");
	}

	sqlite3_reset(stmt);

	/* inserts are more 'costly' than reads */
	state->ctdb_trans_commit_rem -= 4;
	if (state->ctdb_trans_commit_rem <= 0)
		ctdb_end_transaction(state);

	return rv;
}
Exemplo n.º 25
0
int										// returned identifier for transcript
CSQLiteDE::AddExpres(int ExprID,		// experiment identifier
		int TransID,					// transcript identifier
		int Class,
		int Score,
		int DECntsScore,
		int PearsonScore,
		int CtrlUniqueLoci,
		int ExprUniqueLoci,
		double CtrlExprLociRatio,
		double PValueMedian,
		double PValueLow95,
		double PValueHi95,
		int TotCtrlCnts,
		int TotExprCnts,
		int TotCtrlExprCnts,
		double ObsFoldChange,
		double FoldMedian,
		double FoldLow95,
		double FoldHi95,
		double ObsPearson,
		double PearsonMedian,
		double PearsonLow95,
		double PearsonHi95,
		int CtrlAndExprBins,
		int CtrlOnlyBins,
		int ExprOnlyBins)
{
tsDEStmSQL *pStm;
int sqlite_error;
int ExpresID;
char szQueryExpresID[200];

pStm = &m_StmSQL[2];								// access sequence statements
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 1, ExprID))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 2, TransID))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 3, Class))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 4, Score))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 5, DECntsScore))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 6, PearsonScore))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 7, CtrlUniqueLoci))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 8, ExprUniqueLoci))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}

if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 9, CtrlExprLociRatio))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 10, PValueMedian))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 11, PValueLow95))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 12, PValueHi95))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}

if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 13, TotCtrlCnts))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 14, TotExprCnts))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 15, TotCtrlExprCnts))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}

if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 16, ObsFoldChange))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 17, FoldMedian))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 18, FoldLow95))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 19, FoldHi95))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 20, ObsPearson))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 21, PearsonMedian))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 22, PearsonLow95))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_double(pStm->pPrepInsert, 23, PearsonHi95))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}

if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 24, CtrlAndExprBins))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 25, CtrlOnlyBins))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
if((sqlite_error = sqlite3_bind_int(pStm->pPrepInsert, 26, ExprOnlyBins))!=SQLITE_OK)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - bind prepared statement: %s", sqlite3_errmsg(m_pDB)); 
	CloseDatabase(true);
	return(eBSFerrInternal);
	}

if((sqlite_error = sqlite3_step(pStm->pPrepInsert))!=SQLITE_DONE)
	{
	gDiagnostics.DiagOut(eDLFatal,gszProcName,"sqlite - step prepared statement: %s", sqlite3_errmsg(m_pDB));   
	CloseDatabase(true);
	return(eBSFerrInternal);
	}
sqlite3_reset(pStm->pPrepInsert);

if(m_bSafe)
	{
	sprintf(szQueryExpresID,"select ExpresID from TblExpres where ExprID = %d AND TransID = %d",ExprID,TransID);
	sqlite3_exec(m_pDB,szQueryExpresID,ExecCallbackID,&ExpresID,NULL);
	}
else
	ExpresID = (int)sqlite3_last_insert_rowid(m_pDB);
m_NumExpres += 1;						// number of expressions added to TblExpres
return(ExpresID);
}
Exemplo n.º 26
0
static void bindIntParameter(sqlite3_stmt *stmt,const char *name,int value)
{
  int idx = sqlite3_bind_parameter_index(stmt, name);
  sqlite3_bind_int(stmt, idx, value);
}
Exemplo n.º 27
0
static void writeRelations(osm2olm* self, LCountry* country) {
    Tree16 pseudoIndex;
    initTree16(&pseudoIndex);
    Tree16 whishesIndex;
    initTree16(&whishesIndex);
    int found;
    printf("Writing relations for %s. Total relations: %i\n", country->polygon->name, self->relations.count);
    int iterations = 0;
    do {
        found = 0;
        for(int r = 0; r < self->relations.count; r++) {
            if(!isInTree16(&pseudoIndex, self->relations.values[r].base.info.id)) {
                if(self->relations.values[r].change != OSM_CHANGE_DELETE) {
                    if((self->relations.values[r].change == OSM_CHANGE_NONE || relationBelongsCountry(self->relations.values + r, country, &pseudoIndex))) {
                        addTree16Node(&pseudoIndex, self->relations.values[r].base.info.id, 0);
                        
                        found++;
                    } else {
                        if(self->relations.values[r].change != OSM_CHANGE_NONE) {
                            printf("Relation %i does not belongs country\n", self->relations.values[r].base.info.id);
                        } else {
                            printf("Relation %i exists in DB and was'nt changed\n", self->relations.values[r].base.info.id);
                        }
                        
                    }
                } else {
                    printf("Relation %i was deleted\n", self->relations.values[r].base.info.id);
                }
            } else {
                //printf("Relation %i already encountered\n", self->relations.values[r].base.info.id);
            }
        }
        iterations++;
    } while(found);
    printf("Relations found in %i iterations\n", iterations);
    int written = 0;
    for(int r=0;r < self->relations.count; r++) {
        if(isInTree16(&pseudoIndex, self->relations.values[r].base.info.id)){
            beginTransaction(country->db);
            addTree16Node(&(country->relationsIndex), self->relations.values[r].base.info.id, self->relations.values[r].base.info.id);
            switch (self->relations.values[r].change) {
                case OSM_CHANGE_CREATE:
                    sqlite3_bind_int(country->insertRelationStatement, 1, self->relations.values[r].base.info.id);
                    sqlite3_bind_int64(country->insertRelationStatement, 2, self->relations.values[r].base.info.timestamp);
                    sqlite3_step(country->insertRelationStatement);
                    sqlite3_reset(country->insertRelationStatement);
                    writeTags(self, &(self->relations.values[r].base.tags), country->insertRelationTagStatement, self->relations.values[r].base.info.id);
                    writeRelationMember(self->relations.values + r, country);
                    break;
                case OSM_CHANGE_DELETE:
                    deleteRelationFromCountry(country, self->relations.values[r].base.info.id);
                case OSM_CHANGE_MODIFY:
                    sqlite3_bind_int(country->insertRelationStatement, 1, self->relations.values[r].base.info.id);
                    sqlite3_bind_int64(country->insertRelationStatement, 2, self->relations.values[r].base.info.timestamp);
                    sqlite3_step(country->insertRelationStatement);
                    sqlite3_reset(country->insertRelationStatement);
                    deleteFromDbById(country->db, country->deleteRelationTagsStatement, self->relations.values[r].base.info.id);
                    writeTags(self, &(self->relations.values[r].base.tags), country->insertRelationTagStatement, self->relations.values[r].base.info.id);
                    deleteFromDbById(country->db, country->deleteRelationMembersStatement, self->relations.values[r].base.info.id);
                    writeRelationMember(self->relations.values + r, country);
                    break;
                case OSM_CHANGE_COUNT:
                case OSM_CHANGE_NONE:
                    //Just do nothing, as db is up to date
                    break;
                    
            }
            commitTransaction(country->db);
            written++;
        } else {
            deleteRelationFromCountry(country, self->relations.values[r].base.info.id);
            //printf("Skip relation %i. %s\n", self->relations.values[r].info.id, isInTree16(&pseudoIndex, self->relations.values[r].info.id) ? (relationIsFullyBelongsCountry(self->relations.values + r, country, &pseudoIndex)? "HM.." : "It does not have some members.") : "it is not in list");
        }
    }
    freeTree16(&pseudoIndex);
    printf("Relations written: %i\n", written);
}
Exemplo n.º 28
0
/*Update write/read times for both wind and unwind*/
static inline int
gf_update_time (gf_sql_connection_t    *sql_conn,
                char                    *gfid,
                gfdb_time_t             *update_time,
                gf_boolean_t            record_counter,
                gf_boolean_t            is_wind,
                gf_boolean_t            is_read)
{
        int ret = -1;
        sqlite3_stmt *update_stmt = NULL;
        char update_str[1024] = "";
        char *freq_cntr_str = NULL;

        CHECK_SQL_CONN (sql_conn, out);
        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, gfid, out);
        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, update_time, out);

        /*
         * Constructing the prepare statment string.
         *
         * */
        /*For write time*/
        if (!is_read) {
                if (is_wind) {
                        /*if record counter is on*/
                        freq_cntr_str = (record_counter) ?
                        ", WRITE_FREQ_CNTR = WRITE_FREQ_CNTR + 1" : "";

                        /*Prefectly safe as we will not go array of bound*/
                        sprintf (update_str, "UPDATE "
                                GF_FILE_TABLE
                                " SET W_SEC = ?, W_MSEC = ? "
                                " %s"/*place for read freq counters*/
                                " WHERE GF_ID = ? ;", freq_cntr_str);
                } else {
                        /*Prefectly safe as we will not go array of bound*/
                        sprintf (update_str, "UPDATE "
                                GF_FILE_TABLE
                                " SET UW_SEC = ?, UW_MSEC = ? ;");
                }
        }
        /*For Read Time update*/
        else {
                if (is_wind) {
                        /*if record counter is on*/
                        freq_cntr_str = (record_counter) ?
                        ", READ_FREQ_CNTR = READ_FREQ_CNTR + 1" : "";

                        /*Prefectly safe as we will not go array of bound*/
                        sprintf (update_str, "UPDATE "
                                GF_FILE_TABLE
                                " SET W_READ_SEC = ?, W_READ_MSEC = ? "
                                " %s"/*place for read freq counters*/
                                " WHERE GF_ID = ? ;", freq_cntr_str);
                } else {
                        /*Prefectly safe as we will not go array of bound*/
                        sprintf (update_str, "UPDATE "
                                GF_FILE_TABLE
                                " SET UW_READ_SEC = ?, UW_READ_MSEC = ? ;");
                }
        }

        /*Prepare statement*/
        ret = sqlite3_prepare (sql_conn->sqlite3_db_conn, update_str, -1,
                                &update_stmt, 0);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_PREPARE_FAILED, "Failed preparing insert "
                        "statment %s : %s", update_str,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind time secs*/
        ret = sqlite3_bind_int (update_stmt, 1, update_time->tv_sec);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding parent wind "
                        "secs %ld : %s", update_time->tv_sec,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind time msecs*/
        ret = sqlite3_bind_int (update_stmt, 2, update_time->tv_usec);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding parent wind "
                        "msecs %ld : %s", update_time->tv_usec,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind gfid*/
        ret = sqlite3_bind_text (update_stmt, 3, gfid, -1, NULL);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding gfid %s : %s",
                        gfid, sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Execute the prepare statement*/
        if (sqlite3_step (update_stmt) != SQLITE_DONE) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0, LG_MSG_EXEC_FAILED,
                        "Failed executing the prepared stmt %s : %s",
                        update_str,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        ret = 0;
out:
        /*Free prepared statement*/
        sqlite3_finalize (update_stmt);
        return ret;
}
static int
gf_sql_insert_write_wind_time (gf_sql_connection_t  *sql_conn,
                                char                 *gfid,
                                gfdb_time_t          *wind_time)
{
        int ret = -1;
        sqlite3_stmt *insert_stmt = NULL;
        char *insert_str = "INSERT INTO "
                           GF_FILE_TABLE
                           "(GF_ID, W_SEC, W_MSEC, UW_SEC, UW_MSEC)"
                           " VALUES (?, ?, ?, 0, 0);";

        CHECK_SQL_CONN (sql_conn, out);
        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, gfid, out);
        GF_VALIDATE_OR_GOTO (GFDB_STR_SQLITE3, wind_time, out);


        /*Prepare statement*/
        ret = sqlite3_prepare (sql_conn->sqlite3_db_conn, insert_str, -1,
                        &insert_stmt, 0);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_PREPARE_FAILED, "Failed preparing insert "
                        "statment %s : %s", insert_str,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind gfid*/
        ret = sqlite3_bind_text (insert_stmt, 1, gfid, -1, NULL);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding gfid %s : %s",
                        gfid, sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind wind secs*/
        ret = sqlite3_bind_int (insert_stmt, 2, wind_time->tv_sec);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding parent wind "
                        "secs %ld : %s", wind_time->tv_sec,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Bind wind msecs*/
        ret = sqlite3_bind_int (insert_stmt, 3, wind_time->tv_usec);
        if (ret != SQLITE_OK) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0,
                        LG_MSG_BINDING_FAILED, "Failed binding parent wind "
                        "msecs %ld : %s", wind_time->tv_usec,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        /*Execute the prepare statement*/
        if (sqlite3_step (insert_stmt) != SQLITE_DONE) {
                gf_msg (GFDB_STR_SQLITE3, GF_LOG_ERROR, 0, LG_MSG_EXEC_FAILED,
                        "Failed executing the prepared stmt GFID:%s %s : %s",
                        gfid, insert_str,
                        sqlite3_errmsg (sql_conn->sqlite3_db_conn));
                ret = -1;
                goto out;
        }

        ret = 0;
out:
        /*Free prepared statement*/
        sqlite3_finalize (insert_stmt);
        return ret;
}
Exemplo n.º 30
0
int main(int argc, const char * argv[])
{
    sqlite3 *database = 0;
    sqlite3_stmt *statementUpdateDisplaySize = 0;
    sqlite3_stmt *statementDisplay = 0;
    sqlite3_stmt *statementInsertKeypress = 0;
    struct winsize size = { 80, 25 };
    const char *dbname = argv[1] ? argv[1] : DEFAULT_DATABASE;
    char doQuit = 0;
    struct termios orig;
    struct termios raw;

    set_sigwinch();
    
    if (sqlite3_open(dbname, &database) != SQLITE_OK)
    {
        fputs ("could not open database file.\n", stderr);

        return 1;
    }
    else
    {
        sqlite3_stmt *stmt = 0;
        int r;
        if (sqlite3_prepare_v2(database, "select id from game;", -1, &stmt, 0) != SQLITE_OK)
        {
            puts ("database does not contain game data: importing.");

            if ((r = import_game_data (database, GAME_DATA)) < 0)
            {
                return r;
            }
        }

        if (stmt == 0)
        {
            if (sqlite3_prepare_v2(database, "select id from game;", -1, &stmt, 0) != SQLITE_OK)
            {
                fputs ("could not prepare basic statement; game database file may be corrupt:\n", stderr);
                fputs (sqlite3_errmsg(database), stderr);
                fputs ("\n", stderr);

                return 6;
            }
        }

        if (sqlite3_step(stmt) != SQLITE_ROW)
        {
            puts ("no active game session: creating new session.");

            sqlite3_finalize(stmt);
            if (sqlite3_prepare_v2(database, "insert into game (id) values (1);", -1, &stmt, 0) != SQLITE_OK)
            {
                fputs ("could not prepare basic statement; game database file may be corrupt:\n", stderr);
                fputs (sqlite3_errmsg(database), stderr);
                fputs ("\n", stderr);

                return 7;
            }

            if (sqlite3_step(stmt) == SQLITE_ERROR)
            {
                fputs ("could not create new session; game database file may be corrupt:\n", stderr);
                fputs (sqlite3_errmsg(database), stderr);
                fputs ("\n", stderr);

                return 8;
            }
        }

        sqlite3_finalize(stmt);
    }

    if (sqlite3_prepare_v2(database, "update game set columns=?1, lines=?2;", -1, &statementUpdateDisplaySize, 0) != SQLITE_OK)
    {
        fputs ("could not prepare basic statement; game database file may be corrupt:\n", stderr);
        fputs (sqlite3_errmsg(database), stderr);
        fputs ("\n", stderr);

        return 2;
    }
    if (sqlite3_prepare_v2(database, "select group_concat(diff,'') from voutputansi;", -1, &statementDisplay, 0) != SQLITE_OK)
    {
        fputs ("could not prepare basic statement; game database file may be corrupt:\n", stderr);
        fputs (sqlite3_errmsg(database), stderr);
        fputs ("\n", stderr);

        return 3;
    }
    if (sqlite3_prepare_v2(database, "insert into vkeypress (key) values (?1);", -1, &statementInsertKeypress, 0) != SQLITE_OK)
    {
        fputs ("could not prepare basic statement; game database file may be corrupt:\n", stderr);
        fputs (sqlite3_errmsg(database), stderr);
        fputs ("\n", stderr);

        return 5;
    }

    tcgetattr (0, &orig);
    tcgetattr (0, &raw);
    cfmakeraw (&raw);
    tcsetattr (0, 0, &raw);

    ioctl(0, TIOCGWINSZ, &size);

    puts("\e[2J\e[?25l");

    sqlite3_bind_int (statementUpdateDisplaySize, 1, size.ws_col);
    sqlite3_bind_int (statementUpdateDisplaySize, 2, size.ws_row);

    if (sqlite3_step(statementUpdateDisplaySize) != SQLITE_DONE)
    {
        fputs(sqlite3_errmsg(database), stderr);
    }
    sqlite3_reset(statementUpdateDisplaySize);

    do
    {
        int r;
        char key;
        while ((r = sqlite3_step(statementDisplay)) == SQLITE_ROW)
        {
            const char *output = (const char*)sqlite3_column_text(statementDisplay, 0);
            if (output != 0)
            {
                puts(output);
            }
            else
            {
                fputs(sqlite3_errmsg(database), stderr);
            }
        }

        if (r != SQLITE_DONE)
        {
            fputs(sqlite3_errmsg(database), stderr);
        }

        sqlite3_reset(statementDisplay);

        r = (int)read(0, &key, 1);

        if (didResize) goto resized;

        switch (key)
        {
            case 'Q':
                doQuit = 1;
                break;

            case 'R':
            resized:
                didResize = 0;
                ioctl(0, TIOCGWINSZ, &size);
                sqlite3_bind_int (statementUpdateDisplaySize, 1, size.ws_col);
                sqlite3_bind_int (statementUpdateDisplaySize, 2, size.ws_row);

                if (sqlite3_step(statementUpdateDisplaySize) != SQLITE_DONE)
                {
                    fputs(sqlite3_errmsg(database), stderr);
                }
                sqlite3_reset(statementUpdateDisplaySize);
        }

        if (r > 0)
        {
            char keytext[2] = { key, 0 };
            sqlite3_bind_text (statementInsertKeypress, 1, keytext, -1, SQLITE_TRANSIENT);
            if (sqlite3_step (statementInsertKeypress) != SQLITE_DONE)
            {
                puts("\e[H\e[2J\e[?25h\e[0;39m");
                tcsetattr (0, 0, &orig);
                fputs ("error inserting keypress into database:\n", stderr);
                fputs (sqlite3_errmsg(database), stderr);
                fputs ("\n", stderr);
                return -1;
            }
            sqlite3_reset (statementInsertKeypress);
        }