Skip to content

Instantly share code, notes, and snippets.

@royguo
Created May 18, 2016 12:18
Show Gist options
  • Save royguo/e109daf64e8a12a5ee7772a62de3c623 to your computer and use it in GitHub Desktop.
Save royguo/e109daf64e8a12a5ee7772a62de3c623 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <terark/db/db_table.hpp>
#include <terark/io/MemStream.hpp>
#include <terark/io/DataIO.hpp>
#include <terark/io/RangeStream.hpp>
#include <terark/lcast.hpp>
#include "user.hpp"
// g++-4.9 -std=c++1y 3.write_read_delete.cpp -lterark-db-r -lboost_system -lterark-fsa_all-r -lboost_filesystem -Iinclude
// Write data into user_table
int main(){
std::cout<<"Hello Terark, We will write data into db.user_table"<<std::endl;
// open table
static const char* dbtable = "db/user_table";
terark::db::CompositeTablePtr tab = terark::db::CompositeTable::open(dbtable);
// write data (1000 records)
terark::NativeDataOutput<terark::AutoGrownMemIO> rowBuilder;
terark::db::DbContextPtr ctx = tab->createDbContext();
test_ns::User u = {};
int count = 1000;
for(int i = 1; i <= count; i++) {
u.id = i;
u.name = "TestName " + i;
u.description = "Description " + i;
u.age = (i + 10);
u.update_time = 1463472964753 + i;
// insert row
rowBuilder.rewind();
rowBuilder<<u;
terark::fstring binRow(rowBuilder.begin(), rowBuilder.tell());
if (ctx->insertRow(binRow) < 0) {
printf("Insert failed: %s\n", ctx->errMsg.c_str());
}
}
// read data(1000 records)
terark::valvec<terark::byte> nameVal; // column value
terark::valvec<terark::byte> descVal; // column value
terark::valvec<terark::llong> idvec; // id vector of index
size_t indexId = tab->getIndexId("id");
size_t nameColumnId = tab->getColumnId("name");
size_t descColumnId = tab->getColumnId("description");
std::cout<<"name colId = "<<nameColumnId<<", desc colId ="<<descColumnId<<std::endl;
if (indexId >= tab->getIndexNum()) {
fprintf(stderr, "ERROR: index 'id' does not exist\n");
terark::db::CompositeTable::safeStopAndWaitForCompress();
return 0;
}
// iterate ids, read name and description values
for(int i = 1; i <= count; i++) {
terark::fstring key = terark::fstring((char*)&i, 4);
ctx->indexSearchExact(indexId, key, &idvec);
// print ids
// std::cout<<tab->getIndexSchema(indexId).toJsonStr(key).c_str()<<std::endl;
for (auto recId : idvec) {
ctx->selectOneColumn(recId, nameColumnId, &nameVal);
ctx->selectOneColumn(recId, descColumnId, &descVal);
printf("%.*s ", (int)nameVal.size(), nameVal.data());
printf("%.*s\n", (int)descVal.size(), descVal.data());
}
}
// delete data(1000 records)
for(int i = 1; i <= count; i++) {
terark::fstring key = terark::fstring((char*)&i, 4);
ctx->indexSearchExact(indexId, key, &idvec);
for (auto recId : idvec) {
ctx->removeRow(recId);
// std::cout<<"delete row : "<<recId<<std::endl;
}
}
// close table
terark::db::CompositeTable::safeStopAndWaitForCompress();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment