Example #1
2
int main() {
	Five arr[50000];
	int idx = 0;
	FILE * fp;
	char * line = NULL;
	size_t len = 0;
	size_t read;
	int begin = stampstart();
	fp = fopen("50000.csv", "r");
	if (fp == NULL) {
		exit(EXIT_FAILURE);
	}
	char* buf = (char*)malloc(sizeof(char)*128);
	while((read = getline(&line, &len, fp)) != -1) {
		Five five;
		five.firstname = (char*)malloc(sizeof(char)*128);
		five.lastname = (char*)malloc(sizeof(char)*128);
		five.company = (char*)malloc(sizeof(char)*128);
		five.road = (char*)malloc(sizeof(char)*128);
		five.city = (char*)malloc(sizeof(char)*128);
		five.state = (char*)malloc(sizeof(char)*128);
		five.stateaka = (char*)malloc(sizeof(char)*128);
		five.telefon = (char*)malloc(sizeof(char)*128);
		five.fax = (char*)malloc(sizeof(char)*128);
		five.email = (char*)malloc(sizeof(char)*128);
		five.web = (char*)malloc(sizeof(char)*128);
		int r = sscanf(line, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],\"%[^,],%[^,],%[^,],%[^,],%[^,]\n",
			five.firstname, five.lastname, five.company, five.road, five.city, five.state, five.stateaka, 
			buf, five.telefon, five.fax, five.email, five.web);
		five.zip = atoi(buf);
		five.firstname = five.firstname+1;
		five.firstname[strlen(five.firstname)-1] = '\0';
		five.lastname = five.lastname+1;
		five.lastname[strlen(five.lastname)-1] = '\0';
		five.company = five.company+1;
		five.company[strlen(five.company)-1] = '\0';
		five.road = five.road+1;
		five.road[strlen(five.road)-1] = '\0';
		five.city = five.city+1;
		five.city[strlen(five.city)-1] = '\0';
		five.state = five.state+1;
		five.state[strlen(five.state)-1] = '\0';
		five.stateaka = five.stateaka+1;
		five.stateaka[strlen(five.stateaka)-1] = '\0';
		five.telefon = five.telefon+1;
		five.telefon[strlen(five.telefon)-1] = '\0';
		five.fax = five.fax+1;
		five.fax[strlen(five.fax)-1] = '\0';
		five.email = five.email+1;
		five.email[strlen(five.email)-1] = '\0';
		five.web = five.web+1;
		five.web[strlen(five.web)-1] = '\0';
		if(r != 12) {
			printf("%d %s\n", r, line);
			return 1;
		}

		arr[idx++] = five;
	}
	free(buf);
	if (line) {
		free(line);
	}
	//printf("csv time %d\n", stampstop(begin));
	begin = stampstart();

	sqlite3 *db;
	int ret = sqlite3_open("testtable.db",&db);
	assert(ret == SQLITE_OK);
	//gettimeofday(&start, NULL);

	ret = sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, NULL);
	assert(ret == SQLITE_OK);

	const char* istmt  = "INSERT INTO Person(Firstname, Lastname, Company, Address, County, City, State, Zip, PhoneWork, PhonePrivat, Mail, Www) Values(?,?,?,?,?,?,?,?,?,?,?,?);";
	//const char* istmt2  = "INSERT INTO Person(Firstname, Lastname, Company, Address, County, City, State, Zip, PhoneWork, PhonePrivat, Mail, Www) Values(%s,%s,%s,%s,%s,%s,%s,%d,%s,%s,%s,%s);\n";
	sqlite3_stmt* stmt;
	const char* ozTest;
	ret = sqlite3_prepare_v2(db, istmt, strlen(istmt), &stmt, &ozTest);
	assert(ret == SQLITE_OK);
	for(int i = 0; i < idx; ++i) {
		int j = 1;
		/*printf(istmt2, arr[i].firstname, arr[i].lastname, 
			arr[i].company, arr[i].road, arr[i].city, arr[i].state, arr[i].stateaka, arr[i].zip, 
			arr[i].telefon, arr[i].fax, arr[i].email, arr[i].web
		);*/
		sqlite3_bind_text(stmt, j++, arr[i].firstname, strlen(arr[i].firstname), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].lastname, strlen(arr[i].lastname), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].company, strlen(arr[i].company), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].road, strlen(arr[i].road), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].city, strlen(arr[i].city), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].state, strlen(arr[i].state), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].stateaka, strlen(arr[i].stateaka), NULL);
		sqlite3_bind_int(stmt, j++, arr[i].zip);
		sqlite3_bind_text(stmt, j++, arr[i].telefon, strlen(arr[i].telefon), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].fax, strlen(arr[i].fax), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].email, strlen(arr[i].email), NULL);
		sqlite3_bind_text(stmt, j++, arr[i].web, strlen(arr[i].web), NULL);
		assert(j == 13);
		ret = sqlite3_step(stmt);
		if(ret != SQLITE_DONE) {
			printf("%d \"%s\"\n", ret, sqlite3_errmsg(db));
			printf("%s %s %s %s %s %s %s %d %s %s %s %s\n", arr[i].firstname, arr[i].lastname, 
				arr[i].company, arr[i].road, arr[i].city, arr[i].state, arr[i].stateaka, arr[i].zip, 
				arr[i].telefon, arr[i].fax, arr[i].email, arr[i].web
			);
			return 1;
		}
		sqlite3_reset(stmt);
	}
	sqlite3_exec(db, "END TRANSACTION;", NULL, NULL, NULL);
	printf("%d\n", stampstop(begin));
	sqlite3_close(db);
	return 0;
}
Example #2
0
static tb_bool_t tb_database_sqlite3_statement_bind(tb_database_sql_impl_t* database, tb_database_sql_statement_ref_t statement, tb_database_sql_value_t const* list, tb_size_t size)
{
    // check
    tb_database_sqlite3_t* sqlite = tb_database_sqlite3_cast(database);
    tb_assert_and_check_return_val(sqlite && sqlite->database && statement && list && size, tb_false);

    // the param count
    tb_size_t param_count = (tb_size_t)sqlite3_bind_parameter_count((sqlite3_stmt*)statement);
    tb_assert_and_check_return_val(size == param_count, tb_false);
   
    // walk
    tb_size_t i = 0;
    for (i = 0; i < size; i++)
    {
        // the value
        tb_database_sql_value_t const* value = &list[i];

        // done
        tb_int_t    ok = SQLITE_ERROR;
        tb_byte_t*  data = tb_null;
        switch (value->type)
        {
        case TB_DATABASE_SQL_VALUE_TYPE_TEXT:
            tb_trace_i("sqlite3: test %lu %s", i, value->u.text.data);
            ok = sqlite3_bind_text((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.text.data, (tb_int_t)tb_database_sql_value_size(value), tb_null);
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_INT64:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT64:
            ok = sqlite3_bind_int64((sqlite3_stmt*)statement, (tb_int_t)(i + 1), tb_database_sql_value_int64(value));
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_INT32:
        case TB_DATABASE_SQL_VALUE_TYPE_INT16:
        case TB_DATABASE_SQL_VALUE_TYPE_INT8:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT32:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT16:
        case TB_DATABASE_SQL_VALUE_TYPE_UINT8:
            ok = sqlite3_bind_int((sqlite3_stmt*)statement, (tb_int_t)(i + 1), (tb_int_t)tb_database_sql_value_int32(value));
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB16:
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB8:
            ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.blob.data, (tb_int_t)value->u.blob.size, tb_null);
            break;
        case TB_DATABASE_SQL_VALUE_TYPE_BLOB32:
            {
                if (value->u.blob.stream)
                {
                    // done
                    do
                    {
                        // the stream size
                        tb_hong_t size = tb_stream_size(value->u.blob.stream);
                        tb_assert_and_check_break(size >= 0);

                        // make data
                        data = tb_malloc0_bytes((tb_size_t)size);
                        tb_assert_and_check_break(data);

                        // read data
                        if (!tb_stream_bread(value->u.blob.stream, data, (tb_size_t)size)) break;

                        // bind it
                        ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), data, (tb_int_t)size, tb_database_sqlite3_statement_bind_exit);

                    } while (0);
                }
                else ok = sqlite3_bind_blob((sqlite3_stmt*)statement, (tb_int_t)(i + 1), value->u.blob.data, (tb_int_t)value->u.blob.size, tb_null);
            }
            break;
#ifdef TB_CONFIG_TYPE_HAVE_FLOAT
        case TB_DATABASE_SQL_VALUE_TYPE_FLOAT:
        case TB_DATABASE_SQL_VALUE_TYPE_DOUBLE:
            ok = sqlite3_bind_double((sqlite3_stmt*)statement, (tb_int_t)(i + 1), (tb_double_t)tb_database_sql_value_double(value));
            break;
#endif
        case TB_DATABASE_SQL_VALUE_TYPE_NULL:
            ok = sqlite3_bind_null((sqlite3_stmt*)statement, (tb_int_t)(i + 1));
            break;
        default:
            tb_trace_e("statement: bind: unknown value type: %lu", value->type);
            break;
        }

        // failed?
        if (SQLITE_OK != ok)
        {
            // exit data
            if (data) tb_free(data);
            data = tb_null;

            // save state
            sqlite->base.state = tb_database_sqlite3_state_from_errno(sqlite3_errcode(sqlite->database));

            // trace
            tb_trace_e("statement: bind value[%lu] failed, error[%d]: %s", i, sqlite3_errcode(sqlite->database), sqlite3_errmsg(sqlite->database));
            break;
        }
    }

    // ok?
    return (i == size)? tb_true : tb_false;
}
Example #3
0
 int statement::bind(int idx, char const* value, bool fstatic)
 {
   return sqlite3_bind_text(stmt_, idx, value, std::strlen(value), fstatic ? SQLITE_STATIC : SQLITE_TRANSIENT);
 }
QString QgsMapLayer::saveNamedStyle( const QString theURI, bool & theResultFlag )
{
  QString myErrorMessage;

  QDomImplementation DomImplementation;
  QDomDocumentType documentType =
    DomImplementation.createDocumentType(
      "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" );
  QDomDocument myDocument( documentType );
  QDomElement myRootNode = myDocument.createElement( "qgis" );
  myRootNode.setAttribute( "version", QString( "%1" ).arg( QGis::QGIS_VERSION ) );
  myDocument.appendChild( myRootNode );

  // use scale dependent visibility flag
  myRootNode.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 );
  myRootNode.setAttribute( "minimumScale", minimumScale() );
  myRootNode.setAttribute( "maximumScale", maximumScale() );

  // <transparencyLevelInt>
  QDomElement transparencyLevelIntElement = myDocument.createElement( "transparencyLevelInt" );
  QDomText    transparencyLevelIntText    = myDocument.createTextNode( QString::number( getTransparency() ) );
  transparencyLevelIntElement.appendChild( transparencyLevelIntText );
  myRootNode.appendChild( transparencyLevelIntElement );
  // now append layer node to map layer node

  QString errorMsg;
  if ( !writeSymbology( myRootNode, myDocument, errorMsg ) )
  {
    return tr( "Could not save symbology because:\n%1" ).arg( errorMsg );
  }

  // check if the uri is a file or ends with .qml,
  // which indicates that it should become one
  // everything else goes to the database
  QString filename;

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = theURI.split( "|" );
    filename = theURIParts[0];
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    filename = QUrl::fromEncoded( theURI.toAscii() ).toLocalFile();
  }
  else
  {
    filename = theURI;
  }

  QFileInfo myFileInfo( filename );
  if ( myFileInfo.exists() || filename.endsWith( ".qml", Qt::CaseInsensitive ) )
  {
    QFileInfo myDirInfo( myFileInfo.path() );  //excludes file name
    if ( !myDirInfo.isWritable() )
    {
      return tr( "The directory containing your dataset needs to be writable!" );
    }

    // now construct the file name for our .qml style file
    QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".qml";

    QFile myFile( myFileName );
    if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
    {
      QTextStream myFileStream( &myFile );
      // save as utf-8 with 2 spaces for indents
      myDocument.save( myFileStream, 2 );
      myFile.close();
      theResultFlag = true;
      return tr( "Created default style file as %1" ).arg( myFileName );
    }
    else
    {
      theResultFlag = false;
      return tr( "ERROR: Failed to created default style file as %1. Check file permissions and retry." ).arg( myFileName );
    }
  }
  else
  {
    QString qml = myDocument.toString();

    // read from database
    sqlite3 *myDatabase;
    sqlite3_stmt *myPreparedStatement;
    const char *myTail;
    int myResult;

    myResult = sqlite3_open( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( "qgis.qmldb" ).toUtf8().data(), &myDatabase );
    if ( myResult != SQLITE_OK )
    {
      return tr( "User database could not be opened." );
    }

    QByteArray param0 = theURI.toUtf8();
    QByteArray param1 = qml.toUtf8();

    QString mySql = "create table if not exists tbl_styles(style varchar primary key,qml varchar)";
    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
    if ( myResult == SQLITE_OK )
    {
      if ( sqlite3_step( myPreparedStatement ) != SQLITE_DONE )
      {
        sqlite3_finalize( myPreparedStatement );
        sqlite3_close( myDatabase );
        theResultFlag = false;
        return tr( "The style table could not be created." );
      }
    }

    sqlite3_finalize( myPreparedStatement );

    mySql = "insert into tbl_styles(style,qml) values (?,?)";
    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
    if ( myResult == SQLITE_OK )
    {
      if ( sqlite3_bind_text( myPreparedStatement, 1, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK &&
           sqlite3_bind_text( myPreparedStatement, 2, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK &&
           sqlite3_step( myPreparedStatement ) == SQLITE_DONE )
      {
        theResultFlag = true;
        myErrorMessage = tr( "The style %1 was saved to database" ).arg( theURI );
      }
    }

    sqlite3_finalize( myPreparedStatement );

    if ( !theResultFlag )
    {
      QString mySql = "update tbl_styles set qml=? where style=?";
      myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
      if ( myResult == SQLITE_OK )
      {
        if ( sqlite3_bind_text( myPreparedStatement, 2, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK &&
             sqlite3_bind_text( myPreparedStatement, 1, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK &&
             sqlite3_step( myPreparedStatement ) == SQLITE_DONE )
        {
          theResultFlag = true;
          myErrorMessage = tr( "The style %1 was updated in the database." ).arg( theURI );
        }
        else
        {
          theResultFlag = false;
          myErrorMessage = tr( "The style %1 could not be updated in the database." ).arg( theURI );
        }
      }
      else
      {
        theResultFlag = false;
        myErrorMessage = tr( "The style %1 could not be inserted into database." ).arg( theURI );
      }

      sqlite3_finalize( myPreparedStatement );
    }

    sqlite3_close( myDatabase );
  }

  return myErrorMessage;
}
Example #5
0
void Binder::bind(std::size_t pos, const std::string& val)
{
	int rc = sqlite3_bind_text(_pStmt, (int) pos, val.c_str(), (int) val.size()*sizeof(char), SQLITE_TRANSIENT);
	checkReturn(rc);
}
Example #6
0
 Statement& bind_text(const std::string& value) {
     if (SQLITE_OK != sqlite3_bind_text(m_statement, m_bindnum++, value.c_str(), -1, SQLITE_STATIC)) {
         throw Sqlite::Exception("Can't bind text value", m_db.errmsg());
     }
     return *this;
 }
Example #7
0
bool index_lookup_identifier(const char *identifier, id_sub_type sub_type)
{
   bool retval = true;
   sqlite3_stmt *stmt_lookup_identifier;
   int result;

   switch (sub_type)
   {
      default:
      case IST_REFERENCE:
      {
         result = sqlite3_prepare_v2(cpd.index,
                                     "SELECT Files.Filename,Refs.Line,Refs.ColumnStart,Refs.Scope,Refs.Type,Refs.Identifier "
                                     "FROM Files JOIN Refs ON Files.rowid=Refs.Filerow "
                                     "WHERE Refs.Identifier GLOB ?",
                                     -1,
                                     &stmt_lookup_identifier,
                                     NULL);
         break;
      }
      case IST_DEFINITION:
      {
         result = sqlite3_prepare_v2(cpd.index,
                                     "SELECT Files.Filename,Defs.Line,Defs.ColumnStart,Defs.Scope,Defs.Type,Defs.Identifier "
                                     "FROM Files JOIN Defs ON Files.rowid=Defs.Filerow "
                                     "WHERE Defs.Identifier GLOB ?",
                                     -1,
                                     &stmt_lookup_identifier,
                                     NULL);
         break;
      }
      case IST_DECLARATION:
      {
         result = sqlite3_prepare_v2(cpd.index,
                                     "SELECT Files.Filename,Decls.Line,Decls.ColumnStart,Decls.Scope,Decls.Type,Decls.Identifier "
                                     "FROM Files JOIN Decls ON Files.rowid=Decls.Filerow "
                                     "WHERE Decls.Identifier GLOB ?",
                                     -1,
                                     &stmt_lookup_identifier,
                                     NULL);
         break;
      }
   }

   if (result == SQLITE_OK)
   {
      result = sqlite3_bind_text(stmt_lookup_identifier,
                                 1,
                                 identifier != NULL ? identifier : "%",
                                 -1,
                                 SQLITE_STATIC);
   }

   if (result == SQLITE_OK)
   {
      do
      {
         result = sqlite3_step(stmt_lookup_identifier);
         if (result == SQLITE_ROW)
         {
            const char *filename = reinterpret_cast<const char*>(sqlite3_column_text(stmt_lookup_identifier, 0));
            UINT32 line = (UINT32) sqlite3_column_int64(stmt_lookup_identifier, 1);
            UINT32 column_start = (UINT32) sqlite3_column_int64(stmt_lookup_identifier, 2);
            const char *scope = reinterpret_cast<const char*>(sqlite3_column_text(stmt_lookup_identifier, 3));
            id_type type = (id_type) sqlite3_column_int64(stmt_lookup_identifier, 4);
            const char *identifier = reinterpret_cast<const char*>(sqlite3_column_text(stmt_lookup_identifier, 5));
            output_identifier(
               filename,
               line,
               column_start,
               scope,
               type,
               sub_type,
               identifier);
         }
      } while (result == SQLITE_ROW);

      if (result == SQLITE_DONE)
      {
         result = SQLITE_OK;
      }
   }

   if (result != SQLITE_OK)
   {
      const char *errstr = sqlite3_errstr(result);
      LOG_FMT(LERR, "index_lookup_identifier: access error (%d: %s)\n", result, errstr != NULL ? errstr : "");
      retval = false;
   }

   (void) sqlite3_finalize(stmt_lookup_identifier);

   return retval;
}
SSMRESULT CEvaluationEngine::updateModelData(IN int modelId, IN int dataId,
        IN ModelPropertyVec *pModelValues)
{
    SSMRESULT res = SSM_E_FAIL;
    std::stringstream sstream;
    std::string         strSQL;
    sqlite3_stmt        *stmt = NULL;
    unsigned int        i = 1;

    sstream << "update [ModelData" << modelId << "] set lastTime=CURRENT_TIMESTAMP, ";

    for (ModelPropertyVec::iterator itor = pModelValues->begin();
         itor != pModelValues->end(); ++itor)
    {
        sstream << itor->propertyName << "=?";

        if (itor < pModelValues->end() - 1)
        {
            sstream << ",";
        }
    }

    sstream << " where dataId = " << dataId << ";" << std::ends;

    strSQL = sstream.str();
    CHK_SQLITE(sqlite3_prepare_v2(m_pSQLite3, strSQL.c_str(), strSQL.length(), &stmt, NULL), SQLITE_OK);

    for (ModelPropertyVec::iterator itor = pModelValues->begin();
         itor != pModelValues->end(); ++itor)
    {
        switch (itor->propertyType)
        {
            case ModelProperty::TYPE_NUMERIC:
            case ModelProperty::TYPE_INTEGER:
                CHK_SQLITE(sqlite3_bind_int(stmt, i, atoi(itor->propertyValue.c_str())), SQLITE_OK);
                break;

            case ModelProperty::TYPE_REAL:
                CHK_SQLITE(sqlite3_bind_double(stmt, i, atof(itor->propertyValue.c_str())), SQLITE_OK);
                break;

            case ModelProperty::TYPE_TEXT:
                CHK_SQLITE(sqlite3_bind_text(stmt, i, itor->propertyValue.c_str(), itor->propertyValue.size(),
                                             SQLITE_STATIC), SQLITE_OK);
                break;

            default:
                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
        }

        i++;
    }

    CHK_SQLITE(sqlite3_step(stmt), SQLITE_DONE);

    CHK_SQLITE(sqlite3_finalize(stmt), SQLITE_OK);

    res = SSM_S_OK;

CLEANUP:
    return res;
}
Example #9
0
static int
show(lms_t *lms, const char *orig_path)
{
    const char *sql = ("SELECT id, path, size FROM files WHERE path LIKE ? "
                       "AND dtime = 0");
    char buf[PATH_MAX + 2];
    char path[PATH_MAX];
    const char *db_path;
    sqlite3 *db;
    sqlite3_stmt *stmt = NULL;
    int r, len;

    if (!realpath(orig_path, path)) {
        len = strlen(orig_path);
        if (len + 1 < PATH_MAX)
            memcpy(path, orig_path, len + 1);
        else {
            fprintf(stderr, "ERROR: path is too long: %s\n", orig_path);
            return -1;
        }
    }

    len = strlen(path);
    if (len + sizeof("/%") >= PATH_MAX) {
        fprintf(stderr, "ERROR: path is too long: \"%s\" + /%%\n", path);
        return -1;
    }

    db_path = lms_get_db_path(lms);
    if (sqlite3_open(db_path, &db) != SQLITE_OK) {
        fprintf(stderr, "ERROR: could not open DB \"%s\": %s\n",
                db_path, sqlite3_errmsg(db));
        r = -1;
        goto close_and_exit;
    }

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        fprintf(stderr, "ERROR: could not prepare \"%s\": %s\n", sql,
                sqlite3_errmsg(db));
        r = -1;
        goto close_and_exit;
    }

    memcpy(buf, path, len);
    if (len > 0 && path[len - 1] != '/') {
        buf[len] = '/';
        len++;
    }
    buf[len] = '%';
    len++;
    buf[len] = '\0';

    if (sqlite3_bind_text(stmt, 1, buf, len, SQLITE_STATIC) != SQLITE_OK) {
        fprintf(stderr, "ERROR: could not bind path query '%s'\n", buf);
        r = -1;
        goto close_and_exit;
    }

    printf("BEGIN: all files starting with directory '%s'\n", path);

    while ((r = sqlite3_step(stmt)) == SQLITE_ROW) {
        uint64_t id;
        const char *p;
        size_t size;

        id = sqlite3_column_int64(stmt, 0);
        p = sqlite3_column_blob(stmt, 1);
        size = sqlite3_column_int(stmt, 2);

        printf("%" PRIu64 " \"%s\" %zd\n", id, p, size);
    }
    printf("END: all files starting with directory '%s'\n", path);

    if (r == SQLITE_DONE)
        r = 0;
    else if (r == SQLITE_ERROR) {
        fprintf(stderr, "ERROR: could not step statement: %s\n",
                sqlite3_errmsg(db));
        r = -1;
    } else {
        fprintf(stderr, "ERROR: unknow step return value: %d\n", r);
        r = 0;
    }

close_and_exit:
    if (stmt)
        sqlite3_finalize(stmt);
    sqlite3_close(db);

    return r;
}
Example #10
0
int main(int argc, char *argv[]) {
	if (argc != 2) {
		showUsage(argv[0]);
		return 1;
	}

	if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
		showUsage(argv[0]);
		return 0;
	}
	if (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0) {
		showCopyright(argv[0]);
		return 0;
	}

	char *temp = (char *)malloc(strlen(argv[1]) + 1 + 1);
	sprintf(temp, "%s%%", argv[1]);
	char *term = correctSlash(temp);
	free(temp);

	sqlite3 *db = getDatabase();
	if (!db) {
		showError("no database-connection");
		free(term);
		return 1;
	}

	int rc;
	sqlite3_stmt *stmt;

	rc = sqlite3_prepare_v2(db, "SELECT name FROM directory WHERE name LIKE ? ORDER BY name ASC;", -1, &stmt, NULL);
	if (rc != SQLITE_OK) {
		showError(sqlite3_errmsg(db));
		sqlite3_finalize(stmt);
		sqlite3_close(db);
		free(term);
		return 1;
	}
	rc = sqlite3_bind_text(stmt, 1, term, strlen(term), SQLITE_STATIC);
	if (rc != SQLITE_OK) {
		showError(sqlite3_errmsg(db));
		sqlite3_finalize(stmt);
		sqlite3_close(db);
		free(term);
		return 1;
	}

	size_t count = 0;
	const char *dir;
	while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
		++count;
		dir = (char *)sqlite3_column_text(stmt, 0);
		printf("%s\n", dir);
		if (dropFile(db, dir)) {
			showError(sqlite3_errmsg(db));
			sqlite3_finalize(stmt);
			sqlite3_close(db);
			free(term);
			return 1;
		}
		if (dropDirectory(db, dir)) {
			showError(sqlite3_errmsg(db));
			sqlite3_finalize(stmt);
			sqlite3_close(db);
			free(term);
			return 1;
		}
	}

	switch (count) {
		case 0:
			printf("no directory dropped\n");
			break;
		case 1:
			printf("1 directory dropped\n");
			break;
		default:
			printf("%ld directories dropped\n", count);
	}

	sqlite3_finalize(stmt);
	sqlite3_close(db);

	return 0;
}
SSMRESULT CEvaluationEngine::addModelData(IN int modelId, IN int parentModelId, IN int parentDataId,
        IN ModelPropertyVec *pModelValues, OUT int *pDataId)
{
    SSMRESULT           res = SSM_E_FAIL;
    std::stringstream   sstream;
    std::string         strSQL;
    sqlite3_stmt        *stmt = NULL;
    int                 lPos = 0;
    unsigned int        i;

    sstream << "insert into [ModelData" << modelId << "] (";

    for (ModelPropertyVec::iterator itor = pModelValues->begin();
         itor != pModelValues->end(); ++itor)
    {
        sstream << itor->propertyName;

        if (itor < pModelValues->end() - 1)
        {
            sstream << ",";
        }
    }

    sstream << ") values (";

    for (i = 0; i < pModelValues->size(); i++)
    {
        sstream << "?";

        if (i < pModelValues->size() - 1)
        {
            sstream << ",";
        }
    }

    sstream << ");" << std::ends;

    strSQL = sstream.str();
    CHK_SQLITE(sqlite3_prepare_v2(m_pSQLite3, strSQL.c_str(), strSQL.length(), &stmt, NULL), SQLITE_OK);
    sstream.str("");

    i = 1;
    for (ModelPropertyVec::iterator itor = pModelValues->begin();
         itor != pModelValues->end(); ++itor)
    {
        switch (itor->propertyType)
        {
            case ModelProperty::TYPE_NUMERIC:
            case ModelProperty::TYPE_INTEGER:
                CHK_SQLITE(sqlite3_bind_int(stmt, i, atoi(itor->propertyValue.c_str())), SQLITE_OK);
                break;

            case ModelProperty::TYPE_REAL:
                CHK_SQLITE(sqlite3_bind_double(stmt, i, atof(itor->propertyValue.c_str())), SQLITE_OK);
                break;

            case ModelProperty::TYPE_TEXT:
                CHK_SQLITE(sqlite3_bind_text(stmt, i, itor->propertyValue.c_str(), itor->propertyValue.size(),
                                             SQLITE_STATIC), SQLITE_OK);
                break;

            default:
                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
        }

        i++;
    }

    m_mtxDataRelation.lock();

    CHK_SQLITE(sqlite3_step(stmt), SQLITE_DONE);

    CHK_SQLITE(sqlite3_finalize(stmt), SQLITE_OK);

    SSM_CLEANUP_ASSERT(executeSQL_IntReturn("select last_insert_rowid();", pDataId));

    sstream << "select lPos from [DataRelation] where modelId = " << parentModelId << " and dataId = "
            << parentDataId << ";" << std::ends;
    SSM_CLEANUP_ASSERT(executeSQL_IntReturn(sstream.str(), &lPos));
    sstream.str("");

    sstream << "update [DataRelation] set rPos = rPos + 2 where rPos > " << lPos << ";" << std::ends;
    SSM_CLEANUP_ASSERT(executeSQL_NoReturn(sstream.str()));
    sstream.str("");

    sstream << "update [DataRelation] set lPos = lPos + 2 where lPos > " << lPos << ";" << std::ends;
    SSM_CLEANUP_ASSERT(executeSQL_NoReturn(sstream.str()));
    sstream.str("");

    sstream << "insert into [DataRelation] values (null, " << modelId << ", " << lPos + 1 << ", " <<
            lPos + 2 <<
            ", " << *pDataId << ");" << std::ends;
    SSM_CLEANUP_ASSERT(executeSQL_NoReturn(sstream.str()));

CLEANUP:
    m_mtxDataRelation.unlock();
    return res;
}
Example #12
0
static void dbd_sqlite3_bbind(apr_dbd_prepared_t * statement,
                              const void **values)
{
    sqlite3_stmt *stmt = statement->stmt;
    int i, j;
    apr_dbd_type_e type;

    for (i = 0, j = 0; i < statement->nargs; i++, j++) {
        type = (values[j] == NULL ? APR_DBD_TYPE_NULL : statement->types[i]);

        switch (type) {
        case APR_DBD_TYPE_TINY:
            sqlite3_bind_int(stmt, i + 1, *(char*)values[j]);
            break;
        case APR_DBD_TYPE_UTINY:
            sqlite3_bind_int(stmt, i + 1, *(unsigned char*)values[j]);
            break;
        case APR_DBD_TYPE_SHORT:
            sqlite3_bind_int(stmt, i + 1, *(short*)values[j]);
            break;
        case APR_DBD_TYPE_USHORT:
            sqlite3_bind_int(stmt, i + 1, *(unsigned short*)values[j]);
            break;
        case APR_DBD_TYPE_INT:
            sqlite3_bind_int(stmt, i + 1, *(int*)values[j]);
            break;
        case APR_DBD_TYPE_UINT:
            sqlite3_bind_int(stmt, i + 1, *(unsigned int*)values[j]);
            break;
        case APR_DBD_TYPE_LONG:
            sqlite3_bind_int64(stmt, i + 1, *(long*)values[j]);
            break;
        case APR_DBD_TYPE_ULONG:
            sqlite3_bind_int64(stmt, i + 1, *(unsigned long*)values[j]);
            break;
        case APR_DBD_TYPE_LONGLONG:
            sqlite3_bind_int64(stmt, i + 1, *(apr_int64_t*)values[j]);
            break;
        case APR_DBD_TYPE_ULONGLONG:
            sqlite3_bind_int64(stmt, i + 1, *(apr_uint64_t*)values[j]);
            break;
        case APR_DBD_TYPE_FLOAT:
            sqlite3_bind_double(stmt, i + 1, *(float*)values[j]);
            break;
        case APR_DBD_TYPE_DOUBLE:
            sqlite3_bind_double(stmt, i + 1, *(double*)values[j]);
            break;
        case APR_DBD_TYPE_STRING:
        case APR_DBD_TYPE_TEXT:
        case APR_DBD_TYPE_TIME:
        case APR_DBD_TYPE_DATE:
        case APR_DBD_TYPE_DATETIME:
        case APR_DBD_TYPE_TIMESTAMP:
        case APR_DBD_TYPE_ZTIMESTAMP:
            sqlite3_bind_text(stmt, i + 1, values[j], strlen(values[j]),
                              SQLITE_STATIC);
            break;
        case APR_DBD_TYPE_BLOB:
        case APR_DBD_TYPE_CLOB:
            {
            char *data = (char*)values[j];
            apr_size_t size = *(apr_size_t*)values[++j];

            sqlite3_bind_blob(stmt, i + 1, data, size, SQLITE_STATIC);

            /* skip table and column */
            j += 2;
            }
            break;
        case APR_DBD_TYPE_NULL:
        default:
            sqlite3_bind_null(stmt, i + 1);
            break;
        }
    }

    return;
}
Example #13
0
bool SqlitePreparedStatement::bindValue(KDbField *field, const QVariant& value, int par)
{
    if (value.isNull()) {
        //no value to bind or the value is null: bind NULL
        int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        return true;
    }
    if (field->isTextType()) {
        //! @todo optimize: make a static copy so SQLITE_STATIC can be used
        const QByteArray utf8String(value.toString().toUtf8());
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    utf8String.constData(), utf8String.length(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        return true;
    }

    switch (field->type()) {
    case KDbField::Byte:
    case KDbField::ShortInteger:
    case KDbField::Integer: {
        //! @todo what about unsigned > INT_MAX ?
        bool ok;
        const int intValue = value.toInt(&ok);
        if (ok) {
            int res = sqlite3_bind_int(m_sqlResult->prepared_st, par, intValue);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        } else {
            int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        }
        break;
    }
    case KDbField::Float:
    case KDbField::Double: {
        int res = sqlite3_bind_double(m_sqlResult->prepared_st, par, value.toDouble());
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::BigInteger: {
        //! @todo what about unsigned > LLONG_MAX ?
        bool ok;
        const qint64 int64Value = value.toLongLong(&ok);
        if (ok) {
            int res = sqlite3_bind_int64(m_sqlResult->prepared_st, par, int64Value);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        } else {
            int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        }
        break;
    }
    case KDbField::Boolean: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par, value.toBool() ? "1" : "0",
                                    1, SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::Time: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    qPrintable(value.toTime().toString(Qt::ISODate)),
                                    QLatin1String("HH:MM:SS").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::Date: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    qPrintable(value.toDate().toString(Qt::ISODate)),
                                    QLatin1String("YYYY-MM-DD").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::DateTime: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                qPrintable(value.toDateTime().toString(Qt::ISODate)),
                                QLatin1String("YYYY-MM-DDTHH:MM:SS").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::BLOB: {
        const QByteArray byteArray(value.toByteArray());
        int res = sqlite3_bind_blob(m_sqlResult->prepared_st, par,
                                    byteArray.constData(), byteArray.size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    default: {
        sqliteWarning() << "unsupported field type:"
                << field->type() << "- NULL value bound to column #" << par;
        int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
    }
    } //switch
    return true;
}
Example #14
0
int __dbfile_sync_config(sqlite3 *db, unsigned int block_size)
{
	int ret;
	sqlite3_stmt *stmt = NULL;

	ret = sqlite3_prepare_v2(db,
				 "INSERT INTO config VALUES (?1, ?2)", -1,
				 &stmt, NULL);
	if (ret) {
		perror_sqlite(ret, "preparing statement");
		return ret;
	}

	ret = sqlite3_bind_text(stmt, 1, "version_major", -1, SQLITE_STATIC);
	if (ret)
		goto out;
	ret = sqlite3_bind_int(stmt, 2, DB_FILE_MAJOR);
	if (ret)
		goto out;
	ret = sqlite3_step(stmt);
	if (ret != SQLITE_DONE)
		goto out;
	sqlite3_reset(stmt);

	ret = sqlite3_bind_text(stmt, 1, "version_minor", -1, SQLITE_STATIC);
	if (ret)
		goto out;
	ret = sqlite3_bind_int(stmt, 2, DB_FILE_MINOR);
	if (ret)
		goto out;
	ret = sqlite3_step(stmt);
	if (ret != SQLITE_DONE)
		goto out;
	sqlite3_reset(stmt);

	ret = sqlite3_bind_text(stmt, 1, "hash_type", -1, SQLITE_STATIC);
	if (ret)
		goto out;
	ret = sqlite3_bind_text(stmt, 2, hash_type, 8, SQLITE_TRANSIENT);
	if (ret)
		goto out;
	ret = sqlite3_step(stmt);
	if (ret != SQLITE_DONE)
		goto out;
	sqlite3_reset(stmt);

	ret = sqlite3_bind_text(stmt, 1, "block_size", -1, SQLITE_STATIC);
	if (ret)
		goto out;
	ret = sqlite3_bind_int(stmt, 2, block_size);
	if (ret)
		goto out;
	ret = sqlite3_step(stmt);
	if (ret != SQLITE_DONE)
		goto out;
	sqlite3_reset(stmt);

	ret = 0;
out:
	sqlite3_finalize(stmt);

	if (ret) {
		perror_sqlite(ret, "binding");
	}

	return ret;
}
Example #15
0
 void Statement::BindCString(int col, const char* val) 
 {
   CheckOk(sqlite3_bind_text(GetStatement(), col + 1, val, -1, SQLITE_TRANSIENT),
           ErrorCode_BadParameterType);
 }
Example #16
0
// Bind a text value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const char* apValue)
{
    int ret = sqlite3_bind_text(mStmtPtr, aIndex, apValue, -1, SQLITE_TRANSIENT);
    check(ret);
}
Example #17
0
void Database::Statement::bind(int parameter, const String &value)
{
	if(!parameter) return;
	if(sqlite3_bind_text(mStmt, parameter, value.c_str(), -1, SQLITE_TRANSIENT) != SQLITE_OK)
		throw DatabaseException(mDb, String("Unable to bind parameter ") + String::number(parameter));  
}
Example #18
0
// Bind a string value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const std::string& aValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_text(mStmtPtr, index, aValue.c_str(), static_cast<int>(aValue.size()), SQLITE_TRANSIENT);
    check(ret);
}
Example #19
0
/* Returns true if the file needs to be analyzed */
bool index_prepare_for_file(fp_data& fpd)
{
   int result;
   bool retval = true;
   sqlite3_int64 filerow = 0;

   result = sqlite3_bind_text(cpd.stmt_lookup_file,
                              1,
                              fpd.filename,
                              -1,
                              SQLITE_STATIC);

   if (result == SQLITE_OK)
   {
      result = sqlite3_step(cpd.stmt_lookup_file);
   }

   if (result == SQLITE_ROW)
   {
      filerow = sqlite3_column_int64(cpd.stmt_lookup_file, 0);
      const char *ingest =
         (const char *) sqlite3_column_text(cpd.stmt_lookup_file, 1);

      if (strcmp(fpd.digest, ingest) == 0)
      {
         LOG_FMT(LNOTE, "File %s(%s) exists in index at filerow %" PRId64 " with same digest\n", fpd.filename, fpd.digest, (int64_t) filerow);
         result = SQLITE_OK;
         retval = false;
      }
      else
      {
         LOG_FMT(LNOTE, "File %s(%s) exists in index at filerow %" PRId64 " with different digest (%s)\n", fpd.filename, fpd.digest, (int64_t) filerow, ingest);
         result = index_replace_file(fpd.digest, fpd.filename);
         if (result == SQLITE_OK)
         {
            result = index_prune_entries(filerow);
         }
      }
   }
   else if (result == SQLITE_DONE)
   {
      result = index_insert_file(fpd.digest, fpd.filename, &filerow);
      LOG_FMT(LNOTE, "File %s(%s) does not exist in index, inserted at filerow %" PRId64 "\n", fpd.filename, fpd.digest, (int64_t) filerow);
   }

   if (result == SQLITE_OK)
   {
      result = sqlite3_bind_int64(cpd.stmt_insert_reference,
                                  1,
                                  filerow);
   }

   if (result == SQLITE_OK)
   {
      result = sqlite3_bind_int64(cpd.stmt_insert_definition,
                                  1,
                                  filerow);
   }

   if (result == SQLITE_OK)
   {
      result = sqlite3_bind_int64(cpd.stmt_insert_declaration,
                                  1,
                                  filerow);
   }

   if (result != SQLITE_OK)
   {
      const char *errstr = sqlite3_errstr(result);
      LOG_FMT(LERR, "index_prepare_for_file: access error (%d: %s)\n", result, errstr != NULL ? errstr : "");
      retval = false;
   }

   (void) sqlite3_reset(cpd.stmt_lookup_file);

   return retval;
}
Example #20
0
// Bind a text value to a parameter "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const char* apName, const char* apValue)
{
    int index = sqlite3_bind_parameter_index(mStmtPtr, apName);
    int ret   = sqlite3_bind_text(mStmtPtr, index, apValue, -1, SQLITE_TRANSIENT);
    check(ret);
}
Example #21
0
static krb5_error_code KRB5_CALLCONV
scc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
{
    krb5_scache *sfrom = SCACHE(from);
    krb5_scache *sto = SCACHE(to);
    krb5_error_code ret;

    if (strcmp(sfrom->file, sto->file) != 0) {
	krb5_set_error_message(context, KRB5_CC_BADNAME,
			       N_("Can't handle cross database "
				  "credential move: %s -> %s", ""),
			       sfrom->file, sto->file);
	return KRB5_CC_BADNAME;
    }

    ret = make_database(context, sfrom);
    if (ret)
	return ret;

    ret = exec_stmt(context, sfrom->db,
		    "BEGIN IMMEDIATE TRANSACTION", KRB5_CC_IO);
    if (ret) return ret;

    if (sto->cid != SCACHE_INVALID_CID) {
	/* drop old cache entry */

	sqlite3_bind_int(sfrom->dcache, 1, sto->cid);
	do {
	    ret = sqlite3_step(sfrom->dcache);
	} while (ret == SQLITE_ROW);
	sqlite3_reset(sfrom->dcache);
	if (ret != SQLITE_DONE) {
	    krb5_set_error_message(context, KRB5_CC_IO,
				   N_("Failed to delete old cache: %d", ""),
				   (int)ret);
	    goto rollback;
	}
    }

    sqlite3_bind_text(sfrom->ucachen, 1, sto->name, -1, NULL);
    sqlite3_bind_int(sfrom->ucachen, 2, sfrom->cid);

    do {
	ret = sqlite3_step(sfrom->ucachen);
    } while (ret == SQLITE_ROW);
    sqlite3_reset(sfrom->ucachen);
    if (ret != SQLITE_DONE) {
	krb5_set_error_message(context, KRB5_CC_IO,
			       N_("Failed to update new cache: %d", ""),
			       (int)ret);
	goto rollback;
    }

    sto->cid = sfrom->cid;

    ret = exec_stmt(context, sfrom->db, "COMMIT", KRB5_CC_IO);
    if (ret) return ret;

    scc_free(sfrom);

    return 0;

rollback:
    exec_stmt(context, sfrom->db, "ROLLBACK", 0);
    scc_free(sfrom);

    return KRB5_CC_IO;
}
Example #22
0
// Bind a string value to a parameter "?", "?NNN", ":VVV", "@VVV" or "$VVV" in the SQL prepared statement
void Statement::bind(const int aIndex, const std::string& aValue)
{
    int ret = sqlite3_bind_text(mStmtPtr, aIndex, aValue.c_str(), static_cast<int>(aValue.size()), SQLITE_TRANSIENT);
    check(ret);
}
Example #23
0
	/*
		Binds a string to a parameter
	*/
	bool StatementPrivate::bind(unsigned int index, char const * text) const {
		return sqlite3_bind_text(stmt_, index, text, -1, SQLITE_TRANSIENT) == SQLITE_OK;
	}
int main( int argc, const char* argv[])
{  
  const char* key = "123";
  const char* create = "CREATE TABLE t1( id TEXT PRIMARY KEY, a TEXT, b TEXT);";
  const char* insert = "INSERT INTO t1 (id,a,b) VALUES (1,'a','b');";
  const char* localPath = "./attach-local.db";
  const char* remotePath = "./attach-remote.db";
  const char* rekeyPath = "./attach-rekey.db";
  const char* attach_sql = "ATTACH DATABASE ? AS rekey KEY ?;";
  int rc;
  sqlite3 *local_db, *remote_db;  
  char *errorPointer;
  sqlite3_stmt *stmt;
  
  // create the remote db with legacy settings
  if (sqlite3_open(remotePath, &remote_db) != SQLITE_OK) {
    ERROR(("sqlite3_open failed for %s: %s\n", remotePath, sqlite3_errmsg(remote_db)))
    exit(1);
  }
  sqlite3_key(remote_db, key, strlen(key));
  sqlite3_exec(remote_db, "PRAGMA kdf_iter = 4000;", NULL, 0, NULL);
  sqlite3_exec(remote_db, create, NULL, 0, NULL);
  sqlite3_exec(remote_db, insert, NULL, 0, NULL);
  // close it to write it out to storage...
  sqlite3_close(remote_db);
  
  // create the local db with current settings
  if (sqlite3_open(localPath, &local_db) != SQLITE_OK) {
    ERROR(("sqlite3_open failed for %s: %s\n", localPath, sqlite3_errmsg(local_db)))
    exit(1);
  }
  sqlite3_key(local_db, key, strlen(key));
  sqlite3_exec(local_db, "PRAGMA kdf_iter = 64000;", NULL, 0, NULL);
  sqlite3_exec(local_db, create, NULL, 0, NULL);
  sqlite3_exec(local_db, insert, NULL, 0, NULL);
  // close it to write it out to storage...
  sqlite3_close(local_db);
  
  // upgrade the remote db via rekey
  if (sqlite3_open(remotePath, &remote_db) != SQLITE_OK) {
    ERROR(("sqlite3_open failed for %s: %s\n", remotePath, sqlite3_errmsg(remote_db)))
    exit(1);
  }
  sqlite3_key(remote_db, key, strlen(key));
  sqlite3_exec(remote_db, "PRAGMA kdf_iter = 4000;", NULL, 0, NULL);
  if (sqlite3_exec(remote_db, "SELECT * FROM sqlite_master;", NULL, 0, &errorPointer) != SQLITE_OK) {
    ERROR(("select from sqlite_master failed: %s\n", errorPointer));
    sqlite3_free(errorPointer);
    exit(1);
  }
  // prepare stmt for attach
  rc = sqlite3_prepare_v2(remote_db, attach_sql, -1, &stmt, NULL);
  if (rc != SQLITE_OK) {
    ERROR(("sqlite3_prepare_v2 failed for %s: %s\n", attach_sql, sqlite3_errmsg(remote_db)))
    exit(1);
  }
  // "ATTACH DATABASE ? AS rekey KEY ?;";
  sqlite3_bind_text(stmt, 1, rekeyPath, -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 2, key, -1, SQLITE_TRANSIENT);
  if (sqlite3_step(stmt) != SQLITE_DONE) {
    ERROR(("rekey attach failed: %s\n", sqlite3_errmsg(remote_db)));
    sqlite3_free(errorPointer);
    sqlite3_finalize(stmt);
    exit(1);
  }
  sqlite3_finalize(stmt);
  sqlite3_exec(remote_db, "PRAGMA rekey.kdf_iter = 64000;", NULL, 0, NULL);
  rc = sqlite3_exec(remote_db, "SELECT sqlcipher_export('rekey');", NULL, 0, NULL);
  if (rc != SQLITE_OK) {
    ERROR(("sqlcipher_export failed: %s\n", sqlite3_errmsg(remote_db)))
    exit(1);
  }
  sqlite3_close(remote_db);
  // re-open local_db and attach rekeyed database
  if (sqlite3_open(localPath, &local_db) != SQLITE_OK) {
    ERROR(("sqlite3_open failed for %s: %s\n", localPath, sqlite3_errmsg(local_db)))
    exit(1);
  }
  sqlite3_key(local_db, key, strlen(key));
  sqlite3_exec(local_db, "PRAGMA kdf_iter = 64000;", NULL, 0, NULL);
  if (sqlite3_exec(local_db, "SELECT * FROM sqlite_master;", NULL, 0, &errorPointer) != SQLITE_OK) {
    ERROR(("select from sqlite_master failed: %s\n", errorPointer));
    sqlite3_free(errorPointer);
    exit(1);
  }
  // prepare stmt for attach on local_db
  // This is the heart of our test: does attaching this rekey'd db succeed or fail?
  rc = sqlite3_prepare_v2(local_db, attach_sql, -1, &stmt, NULL);
  if (rc != SQLITE_OK) {
    ERROR(("sqlite3_prepare_v2 failed for %s: %s\n", attach_sql, sqlite3_errmsg(remote_db)))
    exit(1);
  }
  // "ATTACH DATABASE ? AS rekey KEY ?;";
  sqlite3_bind_text(stmt, 1, rekeyPath, -1, SQLITE_TRANSIENT);
  sqlite3_bind_text(stmt, 2, key, -1, SQLITE_TRANSIENT);
  if (sqlite3_step(stmt) != SQLITE_DONE) {
    ERROR(("rekey attach to local failed: %s\n", sqlite3_errmsg(local_db)));
    sqlite3_free(errorPointer);
    sqlite3_finalize(stmt);
    exit(1);
  }
  sqlite3_finalize(stmt);
  sqlite3_close(local_db);
    
  return 0;
}
Example #25
0
int main(int argc, char **argv){
  const char *zFileToRead = 0;  /* Input file.  NULL for stdin */
  const char *zDbName = 0;      /* Name of the database file to create */
  int useWithoutRowid = 0;      /* True for --without-rowid */
  int iMode = MODE_INSERT;      /* One of MODE_xxxxx */
  int useNocase = 0;            /* True for --nocase */
  int doTrace = 0;              /* True for --trace */
  int showStats = 0;            /* True for --stats */
  int showSummary = 0;          /* True for --summary */
  int showTimer = 0;            /* True for --timer */
  int cacheSize = 0;            /* Desired cache size.  0 means default */
  int pageSize = 0;             /* Desired page size.  0 means default */
  int commitInterval = 0;       /* How often to commit.  0 means never */
  int noSync = 0;               /* True for --nosync */
  const char *zJMode = 0;       /* Journal mode */
  int nOp = 0;                  /* Operation counter */
  int i, j;                     /* Loop counters */
  sqlite3 *db;                  /* The SQLite database connection */
  char *zSql;                   /* Constructed SQL statement */
  sqlite3_stmt *pInsert = 0;    /* The INSERT statement */
  sqlite3_stmt *pUpdate = 0;    /* The UPDATE statement */
  sqlite3_stmt *pSelect = 0;    /* The SELECT statement */
  sqlite3_stmt *pDelete = 0;    /* The DELETE statement */
  FILE *in;                     /* The open input file */
  int rc;                       /* Return code from an SQLite interface */
  int iCur, iHiwtr;             /* Statistics values, current and "highwater" */
  sqlite3_int64 sumCnt = 0;     /* Sum in QUERY mode */
  sqlite3_int64 startTime;
  char zInput[2000];            /* A single line of input */

  /* Process command-line arguments */
  for(i=1; i<argc; i++){
    const char *z = argv[i];
    if( z[0]=='-' ){
      do{ z++; }while( z[0]=='-' );
      if( strcmp(z,"without-rowid")==0 ){
        useWithoutRowid = 1;
      }else if( strcmp(z,"replace")==0 ){
        iMode = MODE_REPLACE;
      }else if( strcmp(z,"select")==0 ){
        iMode = MODE_SELECT;
      }else if( strcmp(z,"insert")==0 ){
        iMode = MODE_INSERT;
      }else if( strcmp(z,"update")==0 ){
        iMode = MODE_UPDATE;
      }else if( strcmp(z,"delete")==0 ){
        iMode = MODE_DELETE;
      }else if( strcmp(z,"query")==0 ){
        iMode = MODE_QUERY;
      }else if( strcmp(z,"nocase")==0 ){
        useNocase = 1;
      }else if( strcmp(z,"trace")==0 ){
        doTrace = 1;
      }else if( strcmp(z,"nosync")==0 ){
        noSync = 1;
      }else if( strcmp(z,"stats")==0 ){
        showStats = 1;
      }else if( strcmp(z,"summary")==0 ){
        showSummary = 1;
      }else if( strcmp(z,"timer")==0 ){
        showTimer = i;
      }else if( strcmp(z,"cachesize")==0 && i<argc-1 ){
        i++;
        cacheSize = atoi(argv[i]);
      }else if( strcmp(z,"pagesize")==0 && i<argc-1 ){
        i++;
        pageSize = atoi(argv[i]);
      }else if( strcmp(z,"commit")==0 && i<argc-1 ){
        i++;
        commitInterval = atoi(argv[i]);
      }else if( strcmp(z,"journal")==0 && i<argc-1 ){
        zJMode = argv[++i];
      }else{
        fatal_error("unknown option: %s\n", argv[i]);
      }
    }else if( zDbName==0 ){
      zDbName = argv[i];
    }else if( zFileToRead==0 ){
      zFileToRead = argv[i];
    }else{
      fatal_error("surplus argument: %s\n", argv[i]);
    }
  }
  if( zDbName==0 ){
    fatal_error("Usage: %s [--options] DATABASE [INPUTFILE]\n", argv[0]);
  }
  startTime = realTime();

  /* Open the database and the input file */
  if( sqlite3_open(zDbName, &db) ){
    fatal_error("Cannot open database file: %s\n", zDbName);
  }
  if( zFileToRead ){
    in = fopen(zFileToRead, "rb");
    if( in==0 ){
      fatal_error("Could not open input file \"%s\"\n", zFileToRead);
    }
  }else{
    in = stdin;
  }

  /* Set database connection options */
  if( doTrace ) sqlite3_trace(db, traceCallback, 0);
  if( pageSize ){
    zSql = sqlite3_mprintf("PRAGMA page_size=%d", pageSize);
    sqlite3_exec(db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }
  if( cacheSize ){
    zSql = sqlite3_mprintf("PRAGMA cache_size=%d", cacheSize);
    sqlite3_exec(db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }
  if( noSync ) sqlite3_exec(db, "PRAGMA synchronous=OFF", 0, 0, 0);
  if( zJMode ){
    zSql = sqlite3_mprintf("PRAGMA journal_mode=%s", zJMode);
    sqlite3_exec(db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }


  /* Construct the "wordcount" table into which to put the words */
  if( sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, 0) ){
    fatal_error("Could not start a transaction\n");
  }
  zSql = sqlite3_mprintf(
     "CREATE TABLE IF NOT EXISTS wordcount(\n"
     "  word TEXT PRIMARY KEY COLLATE %s,\n"
     "  cnt INTEGER\n"
     ")%s",
     useNocase ? "nocase" : "binary",
     useWithoutRowid ? " WITHOUT ROWID" : ""
  );
  if( zSql==0 ) fatal_error("out of memory\n");
  rc = sqlite3_exec(db, zSql, 0, 0, 0);
  if( rc ) fatal_error("Could not create the wordcount table: %s.\n",
                       sqlite3_errmsg(db));
  sqlite3_free(zSql);

  /* Prepare SQL statements that will be needed */
  if( iMode==MODE_QUERY ){
    rc = sqlite3_prepare_v2(db,
          "SELECT cnt FROM wordcount WHERE word=?1",
          -1, &pSelect, 0);
    if( rc ) fatal_error("Could not prepare the SELECT statement: %s\n",
                          sqlite3_errmsg(db));
  }
  if( iMode==MODE_SELECT ){
    rc = sqlite3_prepare_v2(db,
          "SELECT 1 FROM wordcount WHERE word=?1",
          -1, &pSelect, 0);
    if( rc ) fatal_error("Could not prepare the SELECT statement: %s\n",
                          sqlite3_errmsg(db));
    rc = sqlite3_prepare_v2(db,
          "INSERT INTO wordcount(word,cnt) VALUES(?1,1)",
          -1, &pInsert, 0);
    if( rc ) fatal_error("Could not prepare the INSERT statement: %s\n",
                         sqlite3_errmsg(db));
  }
  if( iMode==MODE_SELECT || iMode==MODE_UPDATE || iMode==MODE_INSERT ){
    rc = sqlite3_prepare_v2(db,
          "UPDATE wordcount SET cnt=cnt+1 WHERE word=?1",
          -1, &pUpdate, 0);
    if( rc ) fatal_error("Could not prepare the UPDATE statement: %s\n",
                         sqlite3_errmsg(db));
  }
  if( iMode==MODE_INSERT ){
    rc = sqlite3_prepare_v2(db,
          "INSERT OR IGNORE INTO wordcount(word,cnt) VALUES(?1,1)",
          -1, &pInsert, 0);
    if( rc ) fatal_error("Could not prepare the INSERT statement: %s\n",
                         sqlite3_errmsg(db));
  }
  if( iMode==MODE_UPDATE ){
    rc = sqlite3_prepare_v2(db,
          "INSERT OR IGNORE INTO wordcount(word,cnt) VALUES(?1,0)",
          -1, &pInsert, 0);
    if( rc ) fatal_error("Could not prepare the INSERT statement: %s\n",
                         sqlite3_errmsg(db));
  }
  if( iMode==MODE_REPLACE ){
    rc = sqlite3_prepare_v2(db,
          "REPLACE INTO wordcount(word,cnt)"
          "VALUES(?1,coalesce((SELECT cnt FROM wordcount WHERE word=?1),0)+1)",
          -1, &pInsert, 0);
    if( rc ) fatal_error("Could not prepare the REPLACE statement: %s\n",
                          sqlite3_errmsg(db));
  }
  if( iMode==MODE_DELETE ){
    rc = sqlite3_prepare_v2(db,
          "DELETE FROM wordcount WHERE word=?1",
          -1, &pDelete, 0);
    if( rc ) fatal_error("Could not prepare the DELETE statement: %s\n",
                         sqlite3_errmsg(db));
  }

  /* Process the input file */
  while( fgets(zInput, sizeof(zInput), in) ){
    for(i=0; zInput[i]; i++){
      if( !isalpha(zInput[i]) ) continue;
      for(j=i+1; isalpha(zInput[j]); j++){}

      /* Found a new word at zInput[i] that is j-i bytes long. 
      ** Process it into the wordcount table.  */
      if( iMode==MODE_DELETE ){
        sqlite3_bind_text(pDelete, 1, zInput+i, j-i, SQLITE_STATIC);
        if( sqlite3_step(pDelete)!=SQLITE_DONE ){
          fatal_error("DELETE failed: %s\n", sqlite3_errmsg(db));
        }
        sqlite3_reset(pDelete);
      }else if( iMode==MODE_SELECT ){
        sqlite3_bind_text(pSelect, 1, zInput+i, j-i, SQLITE_STATIC);
        rc = sqlite3_step(pSelect);
        sqlite3_reset(pSelect);
        if( rc==SQLITE_ROW ){
          sqlite3_bind_text(pUpdate, 1, zInput+i, j-i, SQLITE_STATIC);
          if( sqlite3_step(pUpdate)!=SQLITE_DONE ){
            fatal_error("UPDATE failed: %s\n", sqlite3_errmsg(db));
          }
          sqlite3_reset(pUpdate);
        }else if( rc==SQLITE_DONE ){
          sqlite3_bind_text(pInsert, 1, zInput+i, j-i, SQLITE_STATIC);
          if( sqlite3_step(pInsert)!=SQLITE_DONE ){
            fatal_error("Insert failed: %s\n", sqlite3_errmsg(db));
          }
          sqlite3_reset(pInsert);
        }else{
          fatal_error("SELECT failed: %s\n", sqlite3_errmsg(db));
        }
      }else if( iMode==MODE_QUERY ){
        sqlite3_bind_text(pSelect, 1, zInput+i, j-i, SQLITE_STATIC);
        if( sqlite3_step(pSelect)==SQLITE_ROW ){
          sumCnt += sqlite3_column_int64(pSelect, 0);
        }
        sqlite3_reset(pSelect);
      }else{
        sqlite3_bind_text(pInsert, 1, zInput+i, j-i, SQLITE_STATIC);
        if( sqlite3_step(pInsert)!=SQLITE_DONE ){
          fatal_error("INSERT failed: %s\n", sqlite3_errmsg(db));
        }
        sqlite3_reset(pInsert);
        if( iMode==MODE_UPDATE
         || (iMode==MODE_INSERT && sqlite3_changes(db)==0)
        ){
          sqlite3_bind_text(pUpdate, 1, zInput+i, j-i, SQLITE_STATIC);
          if( sqlite3_step(pUpdate)!=SQLITE_DONE ){
            fatal_error("UPDATE failed: %s\n", sqlite3_errmsg(db));
          }
          sqlite3_reset(pUpdate);
        }
      }
      i = j-1;

      /* Increment the operation counter.  Do a COMMIT if it is time. */
      nOp++;
      if( commitInterval>0 && (nOp%commitInterval)==0 ){
        sqlite3_exec(db, "COMMIT; BEGIN IMMEDIATE", 0, 0, 0);
      }
    }
  }
  sqlite3_exec(db, "COMMIT", 0, 0, 0);
  if( zFileToRead ) fclose(in);
  sqlite3_finalize(pInsert);
  sqlite3_finalize(pUpdate);
  sqlite3_finalize(pSelect);
  sqlite3_finalize(pDelete);

  if( iMode==MODE_QUERY ){
    printf("sum of cnt: %lld\n", sumCnt);
    rc = sqlite3_prepare_v2(db,"SELECT sum(cnt*cnt) FROM wordcount", -1,
                            &pSelect, 0);
    if( rc==SQLITE_OK && sqlite3_step(pSelect)==SQLITE_ROW ){
      printf("double-check: %lld\n", sqlite3_column_int64(pSelect, 0));
    }
    sqlite3_finalize(pSelect);
  }


  if( showTimer ){
    sqlite3_int64 elapseTime = realTime() - startTime;
    fprintf(stderr, "%3d.%03d wordcount", (int)(elapseTime/1000),
                                   (int)(elapseTime%1000));
    for(i=1; i<argc; i++) if( i!=showTimer ) fprintf(stderr, " %s", argv[i]);
    fprintf(stderr, "\n");
  }

  if( showSummary ){
    sqlite3_create_function(db, "checksum", -1, SQLITE_UTF8, 0,
                            0, checksumStep, checksumFinalize);
    sqlite3_exec(db, 
      "SELECT 'count(*):  ', count(*) FROM wordcount;\n"
      "SELECT 'sum(cnt):  ', sum(cnt) FROM wordcount;\n"
      "SELECT 'max(cnt):  ', max(cnt) FROM wordcount;\n"
      "SELECT 'avg(cnt):  ', avg(cnt) FROM wordcount;\n"
      "SELECT 'sum(cnt=1):', sum(cnt=1) FROM wordcount;\n"
      "SELECT 'top 10:    ', group_concat(word, ', ') FROM "
         "(SELECT word FROM wordcount ORDER BY cnt DESC, word LIMIT 10);\n"
      "SELECT 'checksum:  ', checksum(word, cnt) FROM "
         "(SELECT word, cnt FROM wordcount ORDER BY word);\n"
      "PRAGMA integrity_check;\n",
      printResult, 0, 0);
  }

  /* Database connection statistics printed after both prepared statements
  ** have been finalized */
  if( showStats ){
    sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, 0);
    printf("-- Lookaside Slots Used:        %d (max %d)\n", iCur,iHiwtr);
    sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, 0);
    printf("-- Successful lookasides:       %d\n", iHiwtr);
    sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur,&iHiwtr,0);
    printf("-- Lookaside size faults:       %d\n", iHiwtr);
    sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur,&iHiwtr,0);
    printf("-- Lookaside OOM faults:        %d\n", iHiwtr);
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, 0);
    printf("-- Pager Heap Usage:            %d bytes\n", iCur);
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
    printf("-- Page cache hits:             %d\n", iCur);
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
    printf("-- Page cache misses:           %d\n", iCur); 
    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
    printf("-- Page cache writes:           %d\n", iCur); 
    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, 0);
    printf("-- Schema Heap Usage:           %d bytes\n", iCur); 
    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, 0);
    printf("-- Statement Heap Usage:        %d bytes\n", iCur); 
  }

  sqlite3_close(db);

  /* Global memory usage statistics printed after the database connection
  ** has closed.  Memory usage should be zero at this point. */
  if( showStats ){
    sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, 0);
    printf("-- Memory Used (bytes):         %d (max %d)\n", iCur,iHiwtr);
    sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, 0);
    printf("-- Outstanding Allocations:     %d (max %d)\n", iCur,iHiwtr);
    sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, 0);
    printf("-- Pcache Overflow Bytes:       %d (max %d)\n", iCur,iHiwtr);
    sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, 0);
    printf("-- Scratch Overflow Bytes:      %d (max %d)\n", iCur,iHiwtr);
    sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, 0);
    printf("-- Largest Allocation:          %d bytes\n",iHiwtr);
    sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, 0);
    printf("-- Largest Pcache Allocation:   %d bytes\n",iHiwtr);
    sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, 0);
    printf("-- Largest Scratch Allocation:  %d bytes\n", iHiwtr);
  }
  return 0;
}
Example #26
0
int bind_execution_sql(sqlite3_stmt * stmt, std::string unique_id, int start_time, int end_time) {
    sqlite3_bind_text(stmt, 1, unique_id.c_str(), -1, SQLITE_TRANSIENT);
    sqlite3_bind_int(stmt, 2, start_time);
    sqlite3_bind_int(stmt, 3, end_time);
    return step_stmt(stmt);
}
Example #27
0
int main(int argc, char *argv[])
{
    DB *primary, *block_db;
    DBC *cur, *tmp_cur;
    DbRecord *rp;
    DbField *f;
    sqlite3 *sql_db;
    sqlite3_stmt *ppStmt;
    DBT key, pkey, data, uid;
    int sql_ret;
    sqlite3_int64 mem_lim = 1*1024*1024;
    mem_lim *= 1024;
    u_int32_t numrecs = 0, numblocks=0;
    //DB_BTREE_STAT *stat;
    //char sql_query[256];
    //sprintf(sql_query, "update %s set Invnum_N = ? where invnum = ?;", table);
    char * sql_query = "update invpat_8_sort set Invnum_N = ? where invnum = ?;";
    //char sql_file[128];
    //sprintf(sql_file, "sqlite_dbs/%s", database);
    char *sql_file = "sqlite_dbs/invpatC.v8.sqlite3";
    //char *sql_query2 = "select * from invpat where Patent = ? and InvSeq = ?;";
    db_recno_t dup_count;

    int custom_block=0;
    int has_max = 0;
    u_int32_t start_rec = 0, end_block = 0;
    char ch;

    memset(&key, 0, sizeof(key));
    memset(&pkey, 0, sizeof(pkey));
    memset(&data, 0, sizeof(data));
    memset(&uid, 0, sizeof(uid));

    sqlite_db_env_open(NULL);
    sqlite_db_primary_open(&primary, "primary", DB_BTREE, 32*1024, DB_CREATE, 0, compare_uint32);
    sqlite_db_secondary_open(primary, &block_db, "block_idx", 8*1024, DB_DUPSORT, blocking_callback, compare_uint32);
    //primary->stat(primary, NULL, &stat, 0);
    //printf("numkeys in primary: %lu\n", (u_long)stat->bt_nkeys);
    //free(stat);
    sqlite3_open(sql_file, &sql_db);
    sqlite3_exec(sql_db, "PRAGMA synchronous=0;", NULL, NULL, NULL);
    //sqlite3_exec(sql_db, "PRAGMA cache_size=200;", NULL, NULL, NULL);

    block_db->cursor(block_db, NULL, &cur, 0);

    printf("Starting writes!\n");

    while ((ch = getopt(argc, argv, "b:n:x:")) != EOF)
		switch (ch) {
		case 'b':
            key.data = optarg;
            key.size = strlen(optarg)+1;
            printf("%s, %u\n", key.data, key.size);
            custom_block = 1;
            if(DB_NOTFOUND == cur->pget(cur, &key, &pkey, &data, DB_SET)){
                printf("Block not found\n");
                return(EXIT_FAILURE);
            }
			break;
        case 'n':
            start_rec = (u_int32_t)atol(optarg);
            break;
        case 'x':
            end_block = (u_int32_t)atol(optarg);
            has_max = 1;
            break;
        }
    argc -= optind;
	argv += optind;

    if (*argv != NULL)
		return (EXIT_FAILURE);

    sql_ret = sqlite3_prepare_v2(sql_db, sql_query, -1, &ppStmt, NULL);

    while(DB_NOTFOUND != cur->pget(cur, &key, &pkey, &data,
                (custom_block? DB_SET : DB_NEXT_NODUP))){
        if(has_max && numblocks++ >= end_block) break;
        do{
            if(!(++numrecs % 10000)){
                primary->sync(primary, 0);
                block_db->sync(primary, 0);
                dbenv->memp_sync(dbenv, NULL);
                cur->dup(cur, &tmp_cur, DB_POSITION);
                tmp_cur->pget(tmp_cur, &key, &pkey, &data, DB_CURRENT);
                cur->close(cur);
                cur = tmp_cur;
                sqlite3_finalize(ppStmt);
                sqlite3_close(sql_db);
                sqlite3_open(sql_file, &sql_db);
                sqlite3_exec(sql_db, "PRAGMA synchronous=0;", NULL, NULL, NULL);
                sql_ret = sqlite3_prepare_v2(sql_db, sql_query, -1, &ppStmt, NULL);
                printf("\t %lu records processed...\n", (ulong)numrecs);
                //printf("\t Using %lld bytes of memory...\n", sqlite3_memory_used());
            }

            cur->count(cur, &dup_count, 0);
            if(numrecs < start_rec) continue;

            if(custom_block || (strncmp(((DbRecord*)data.data)->Invnum_N, "", 1) &&
               strcmp(((DbRecord*)data.data)->Invnum_N, ((DbRecord*)data.data)->Invnum))){
                
                //printf("Invnum_N = %s\n", ((DbRecord *)data.data)->Invnum_N);
                //printf("Patent = %s\n", ((DbRecord*)data.data)->Patent);
                //printf("InvSeq = %lu\n", (u_long)((DbRecord*)data.data)->InvSeq);
                
                sql_ret = sqlite3_prepare_v2(sql_db, sql_query, -1, &ppStmt, NULL);
                //sql_ret = sqlite3_prepare_v2(sql_db, sql_query2, -1, &ppStmt, NULL);
                /*if(numrecs > 920000){
                    if(has_tag((DbRecord*)data.data)==NULL)
                        printf("HUZZAH!\n");
                    printf("Invnum_N: %s\n", has_tag((DbRecord *)data.data));
                    printf("%d\n", sql_ret);
                }*/
                if((sql_ret = sqlite3_bind_text(ppStmt, 1, ((DbRecord *)data.data)->Invnum_N,  -1, SQLITE_STATIC))!=0)//strlen(((DbRecord *)data.data)->Invnum_N)+1
                    printf("Bind complaint: %d\n", sql_ret);
                index_callback(NULL, NULL, &data, &uid);
                if((sql_ret = sqlite3_bind_text(ppStmt, 2, (char*)uid.data, -1, SQLITE_STATIC))!=0)
                    printf("Bind complaint: %d\n", sql_ret);
                //if((sql_ret=sqlite3_bind_int(ppStmt, 3, (int)((DbRecord *)data.data)->InvSeq))!=0)
                //    printf("Bind complaint: %d\n", sql_ret);
                //if((sql_ret = sqlite3_step(ppStmt))!=SQLITE_ROW)
                //    printf("No results! %d\n", sql_ret);
                if((sql_ret = sqlite3_step(ppStmt))!=SQLITE_DONE)
                    printf("Step complaint: %d\n", sql_ret);
                sqlite3_clear_bindings(ppStmt);
                sqlite3_reset(ppStmt);
        
            } 
        } while(DB_NOTFOUND !=
            cur->pget(cur, &key, &pkey, &data, DB_NEXT_DUP));
        if(custom_block) break;
    }
    sqlite3_finalize(ppStmt);
    cur->close(cur);
    block_db->close(block_db, 0);
    primary->close(primary, 0);
    sqlite3_close(sql_db);
    return(0);
}
/**
 * This function is invoked as:
 *
 *  _TOKENIZE('<token_table>', <data_row_id>, <data>, <delimiter>,
 *             <use_token_index>, <data_tag>)
 *
 * If <use_token_index> is omitted, it is treated as 0.
 * If <data_tag> is omitted, it is treated as NULL.
 *
 * It will split <data> on each instance of <delimiter> and insert each token
 * into <token_table>. The following columns in <token_table> are used:
 * token TEXT, source INTEGER, token_index INTEGER, tag (any type)
 * The token_index column is not required if <use_token_index> is 0.
 * The tag column is not required if <data_tag> is NULL.
 *
 * One row is inserted for each token in <data>.
 * In each inserted row, 'source' is <data_row_id>.
 * In the first inserted row, 'token' is the hex collation key of
 * the entire <data> string, and 'token_index' is 0.
 * In each row I (where 1 <= I < N, and N is the number of tokens in <data>)
 * 'token' will be set to the hex collation key of the I:th token (0-based).
 * If <use_token_index> != 0, 'token_index' is set to I.
 * If <data_tag> is not NULL, 'tag' is set to <data_tag>.
 *
 * In other words, there will be one row for the entire string,
 * and one row for each token except the first one.
 *
 * The function returns the number of tokens generated.
 */
static void tokenize(sqlite3_context * context, int argc, sqlite3_value ** argv)
{
    //ALOGD("enter tokenize");
    int err;
    int useTokenIndex = 0;
    int useDataTag = 0;

    if (!(argc >= 4 || argc <= 6)) {
        ALOGE("Tokenize requires 4 to 6 arguments");
        sqlite3_result_null(context);
        return;
    }

    if (argc > 4) {
        useTokenIndex = sqlite3_value_int(argv[4]);
    }

    if (argc > 5) {
        useDataTag = (sqlite3_value_type(argv[5]) != SQLITE_NULL);
    }

    sqlite3 * handle = sqlite3_context_db_handle(context);
    UCollator* collator = (UCollator*)sqlite3_user_data(context);
    char const * tokenTable = (char const *)sqlite3_value_text(argv[0]);
    if (tokenTable == NULL) {
        ALOGE("tokenTable null");
        sqlite3_result_null(context);
        return;
    }

    // Get or create the prepared statement for the insertions
    sqlite3_stmt * statement = (sqlite3_stmt *)sqlite3_get_auxdata(context, 0);
    if (!statement) {
        char const * tokenIndexCol = useTokenIndex ? ", token_index" : "";
        char const * tokenIndexParam = useTokenIndex ? ", ?" : "";
        char const * dataTagCol = useDataTag ? ", tag" : "";
        char const * dataTagParam = useDataTag ? ", ?" : "";
        char * sql = sqlite3_mprintf("INSERT INTO %s (token, source%s%s) VALUES (?, ?%s%s);",
                tokenTable, tokenIndexCol, dataTagCol, tokenIndexParam, dataTagParam);
        err = sqlite3_prepare_v2(handle, sql, -1, &statement, NULL);
        sqlite3_free(sql);
        if (err) {
            ALOGE("prepare failed");
            sqlite3_result_null(context);
            return;
        }
        // This binds the statement to the table it was compiled against, which is argv[0].
        // If this function is ever called with a different table the finalizer will be called
        // and sqlite3_get_auxdata() will return null above, forcing a recompile for the new table.
        sqlite3_set_auxdata(context, 0, statement, tokenize_auxdata_delete);
    } else {
        // Reset the cached statement so that binding the row ID will work properly
        sqlite3_reset(statement);
    }

    // Bind the row ID of the source row
    int64_t rowID = sqlite3_value_int64(argv[1]);
    err = sqlite3_bind_int64(statement, 2, rowID);
    if (err != SQLITE_OK) {
        ALOGE("bind failed");
        sqlite3_result_null(context);
        return;
    }

    // Bind <data_tag> to the tag column
    if (useDataTag) {
        int dataTagParamIndex = useTokenIndex ? 4 : 3;
        err = sqlite3_bind_value(statement, dataTagParamIndex, argv[5]);
        if (err != SQLITE_OK) {
            ALOGE("bind failed");
            sqlite3_result_null(context);
            return;
        }
    }

    // Get the raw bytes for the string to tokenize
    // the string will be modified by following code
    // however, sqlite did not reuse the string, so it is safe to not dup it
    UChar * origData = (UChar *)sqlite3_value_text16(argv[2]);
    if (origData == NULL) {
        sqlite3_result_null(context);
        return;
    }

    // Get the raw bytes for the delimiter
    const UChar * delim = (const UChar *)sqlite3_value_text16(argv[3]);
    if (delim == NULL) {
        ALOGE("can't get delimiter");
        sqlite3_result_null(context);
        return;
    }

    UChar * token = NULL;
    UChar *state;
    int numTokens = 0;

    do {
        if (numTokens == 0) {
            token = origData;
        }

        // Reset the program so we can use it to perform the insert
        sqlite3_reset(statement);
        UErrorCode status = U_ZERO_ERROR;
        char keybuf[1024];
        uint32_t result = ucol_getSortKey(collator, token, -1, (uint8_t*)keybuf, sizeof(keybuf)-1);
        if (result > sizeof(keybuf)) {
            // TODO allocate memory for this super big string
            ALOGE("ucol_getSortKey needs bigger buffer %d", result);
            break;
        }
        uint32_t keysize = result-1;
        uint32_t base16Size = keysize*2;
        char *base16buf = (char*)malloc(base16Size);
        base16Encode(base16buf, keybuf, keysize);
        err = sqlite3_bind_text(statement, 1, base16buf, base16Size, SQLITE_STATIC);

        if (err != SQLITE_OK) {
            ALOGE(" sqlite3_bind_text16 error %d", err);
            free(base16buf);
            break;
        }

        if (useTokenIndex) {
            err = sqlite3_bind_int(statement, 3, numTokens);
            if (err != SQLITE_OK) {
                ALOGE(" sqlite3_bind_int error %d", err);
                free(base16buf);
                break;
            }
        }

        err = sqlite3_step(statement);
        free(base16buf);

        if (err != SQLITE_DONE) {
            ALOGE(" sqlite3_step error %d", err);
            break;
        }
        numTokens++;
        if (numTokens == 1) {
            // first call
            u_strtok_r(origData, delim, &state);
        }
    } while ((token = u_strtok_r(NULL, delim, &state)) != NULL);
    sqlite3_result_int(context, numTokens);
}
Example #29
0
bool DbNote::insertTable(Note & note)
{
    sqlite3_stmt *statement;
    string stmnt =
        "insert into NoteTable (date,NoteText,NoteTitle,NoteRef,KatKey) values (?,?,?,?,?)";

    if (!openDB())
    {
        throw SQLError("Can't open the DB-Connection");
        return false;
    }
    int req = sqlite3_prepare_v2(db, stmnt.c_str(), stmnt.length(), &statement,
                                 0);
    if (req != SQLITE_OK)
    {
        throw SQLError("Preparing Insert-Statement failed");
        return false;
    }
    req = sqlite3_bind_text(statement, 1,
                            (note.getDate().getDateString()).c_str(),
                            (note.getDate().getDateString()).length(), SQLITE_TRANSIENT);
    if (req != SQLITE_OK)
    {
        throw SQLError("Binding Date into insert statement failed");
        return false;
    }
    req = sqlite3_bind_text(statement, 2, (note.getNoteText()).c_str(),
                            (note.getNoteText()).length(), SQLITE_TRANSIENT);
    if (req != SQLITE_OK)
    {
        throw SQLError("Binding note text into insert statement failed");
        return false;
    }
    req = sqlite3_bind_text(statement, 3, (note.getNotetitle()).c_str(),
                            (note.getNotetitle()).length(), SQLITE_TRANSIENT);
    if (req != SQLITE_OK)
    {
        throw SQLError("Binding note title into insert statement failed");
        return false;
    }
    req = sqlite3_bind_int(statement, 4, note.getNoteRef());
    if (req != SQLITE_OK)
    {
        throw SQLError("Binding note ref into insert statement failed");
        return false;
    }
    req = sqlite3_bind_int(statement, 5, note.getKatKey());
    if (req != SQLITE_OK)
    {
        throw SQLError(
            "Binding note category key into insert statement failed");
        return false;
    }
    req = sqlite3_step(statement);
    if (req != SQLITE_DONE)
    {
        throw SQLError("execute of insert statement failed");
        return false;
    }
    sqlite3_finalize(statement);
    sqlite3_close(db);
    return true;
}
Example #30
0
void standard_use_type::do_use()
{
  int result=SQLITE_OK;

  convert_to_base();

  switch (m_type)
  {
  case x_null:
    result = sqlite3_bind_null (m_st->m_stmt, m_iParam);
    break;

  case x_bool:
    result = sqlite3_bind_int (m_st->m_stmt, m_iParam, as <bool> (m_data)?1:0 );
    break;

  case x_char:
    result = sqlite3_bind_int (m_st->m_stmt, m_iParam, as <char> (m_data));
    break;

  case x_short:
    result = sqlite3_bind_int (m_st->m_stmt, m_iParam, as <short> (m_data));
    break;

  case x_int:
    result = sqlite3_bind_int (m_st->m_stmt, m_iParam, as <int> (m_data));
    break;

  case x_long:
    result = sqlite3_bind_int (m_st->m_stmt, m_iParam, as <long> (m_data));
    break;

  case x_int64:
    result = sqlite3_bind_int64 (m_st->m_stmt, m_iParam, as <int64> (m_data));
    break;

  case x_uchar:
    result = sqlite3_bind_int (m_st->m_stmt, m_iParam, as <unsigned char> (m_data));
    break;

  case x_ushort:
    result = sqlite3_bind_int (m_st->m_stmt, m_iParam, as <unsigned short> (m_data));
    break;

  case x_uint:
    result = sqlite3_bind_int64 (m_st->m_stmt, m_iParam, as <unsigned int> (m_data));
    break;

  case x_ulong:
    result = sqlite3_bind_int64 (m_st->m_stmt, m_iParam, as <unsigned long> (m_data));
    break;

  case x_uint64:
    result = sqlite3_bind_int64 (m_st->m_stmt, m_iParam, as <sqlite3_uint64, sqlite3_int64> (m_data));
    break;

  case x_float:
    result = sqlite3_bind_double (m_st->m_stmt, m_iParam, as <float> (m_data));
    break;

  case x_double:
    result = sqlite3_bind_double (m_st->m_stmt, m_iParam, as <double> (m_data));
    break;

  case x_cstring:
    result = sqlite3_bind_text (m_st->m_stmt, m_iParam, as <char*> (m_data), -1, SQLITE_STATIC);
    break;

  case x_cwstring:
    result = sqlite3_bind_text16 (m_st->m_stmt, m_iParam, as <wchar_t*> (m_data), -1, SQLITE_STATIC);
    break;

  case x_stdstring:
    {
      std::string const& s = as <std::string> (m_data);
      result = sqlite3_bind_text (m_st->m_stmt,
                                  m_iParam,
                                  s.c_str(),
                                  s.size() * sizeof(s[0]), 
                                  SQLITE_STATIC);
    }
    break;

  case x_stdwstring:
    {
      std::wstring const& s = as <std::wstring> (m_data);
      result = sqlite3_bind_text16 (m_st->m_stmt,
                                    m_iParam,
                                    s.c_str(),
                                    s.size() * sizeof(s[0]),
                                    SQLITE_STATIC);
    }
    break;

  case x_juceString:
    {
      String const& s = as <String> (m_data);
      result = sqlite3_bind_text (m_st->m_stmt,
                                  m_iParam,
                                  s.toUTF8(),
                                  -1,
                                  SQLITE_STATIC);
    }
    break;

  case x_stdtm:
  case x_blob:
  default:
    Throw (Error().fail (__FILE__, __LINE__, Error::badParameter));
  }

  if (result != SQLITE_OK)
    Throw (detail::sqliteError(__FILE__, __LINE__, result));
}