Esempio n. 1
0
VOID InitLibrary(BOOLEAN _LibraryMode, ULONG _VirtualFileSize, ULONG _PhysicalFileSize, int _MaxSnapshotCount)
{
    LibraryMode = _LibraryMode;
    VirtualFileSize = _VirtualFileSize;
    PhysicalFileSize = _PhysicalFileSize;
    
    TableStorage = CreatePTableArray(_MaxSnapshotCount + 1);
    CurrentTable = CreateTable();
    ReadonlyNodes = CreateTable();
    
    MapInterval(0, 0, VirtualFileSize);
    SnapshotZeroSave(0);
}
Esempio n. 2
0
extern Table *LAY_InitTable()
{  Table *LAY_table = CreateTable( "LAY", LAY_NSTRUCTS, LAY_NUNIONS );

   AddElement( LAY_LPAIR,
               "Lpair",
               Sort1( LAY_LAYOUT),
               Sort2( LAY_LAYOUT, LAY_LAYOUT),
               Sort2( "a", "b"),
               LAY_table );

   AddElement( LAY_LBRACKET,
               "Lbracket",
               Sort1( LAY_LAYOUT),
               Sort3( LAY_LAYOUT, LAY_LAYOUT, LAY_LAYOUT),
               Sort3( "open", "body", "close"),
               LAY_table );

   AddElement( LAY_HLIST,
               "Hlist",
               Sort1( LAY_LAYOUT),
               Sort1( LAY_VECLAYOUT),
               Sort1( "list"),
               LAY_table );

   AddElement( LAY_VLIST,
               "Vlist",
               Sort1( LAY_LAYOUT),
               Sort1( LAY_VECLAYOUT),
               Sort1( "list"),
               LAY_table );

   AddSort( LAY_LAYOUT, "Layout", LAY_table);

   return( LAY_table);
}
Esempio n. 3
0
/**
 * AddSamplesTable - Add a samples table into the 'samples_db'.
 * The table name is generated by concatenating db_id and table_id with '_'.
 */
void TupleSamplesStorage::AddSamplesTable(
    storage::DataTable *data_table,
    std::vector<std::unique_ptr<storage::Tuple>> &sampled_tuples) {
  auto schema = data_table->GetSchema();
  auto schema_copy = catalog::Schema::CopySchema(schema);
  std::unique_ptr<catalog::Schema> schema_ptr(schema_copy);
  auto catalog = catalog::Catalog::GetInstance();
  bool is_catalog = false;
  std::string samples_table_name = GenerateSamplesTableName(
      data_table->GetDatabaseOid(), data_table->GetOid());

  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog->CreateTable(std::string(SAMPLES_DB_NAME),
                       std::string(DEFAULT_SCHEMA_NAME), samples_table_name,
                       std::move(schema_ptr), txn, is_catalog);

  auto samples_table = catalog->GetTableWithName(
      std::string(SAMPLES_DB_NAME), std::string(DEFAULT_SCHEMA_NAME),
      samples_table_name, txn);

  for (auto &tuple : sampled_tuples) {
    InsertSampleTuple(samples_table, std::move(tuple), txn);
  }
  txn_manager.CommitTransaction(txn);
}
/**
 * Opens the database, and upgrades it if necessary.
 *
 * @param context the Context to use for opening the database
 * @param databaseFile Name of the file to be initialized.
 */
void HttpAuthDatabase::InitDatabase(
    /* [in] */ IContext* context,
    /* [in] */ String databaseFile)
{
    // try {
        context->OpenOrCreateDatabase(databaseFile, 0, NULL, (ISQLiteDatabase**)&mDatabase);
    // } catch (SQLiteException e) {
    //     // try again by deleting the old db and create a new one
    //     if (context.deleteDatabase(databaseFile)) {
    //         mDatabase = context.openOrCreateDatabase(databaseFile, 0, null);
    //     }
    // }

    if (mDatabase == NULL) {
        // Not much we can do to recover at this point
//        Log.e(LOGTAG, "Unable to open or create " + databaseFile);
        return;
    }

    Int32 version;
    mDatabase->GetVersion(&version);
    if (version != DATABASE_VERSION) {
        mDatabase->BeginTransactionNonExclusive();
        // try {
            CreateTable();
            mDatabase->SetTransactionSuccessful();
        // } finally {
        //     mDatabase.endTransaction();
        // }
    }
}
Esempio n. 5
0
void CreateAndLoadTable(LayoutType layout_type) {
  // Initialize settings
  peloton_layout_mode = layout_type;

  CreateTable();

  LoadTable();
}
Esempio n. 6
0
TEST_F(HybridIndexTests, IndexScanTest) {
  std::unique_ptr<storage::DataTable> hyadapt_table;
  CreateTable(hyadapt_table, true);
  LoadTable(hyadapt_table);

  for (size_t query_itr = 0; query_itr < query_count; query_itr++) {
    LaunchIndexScan(hyadapt_table);
  }
}
Esempio n. 7
0
Status InitMeasurementTable(MeasurementTable* measurementTable, const char* name, byte columns, byte rows)
{
    Status status = FindTable(name, &(measurementTable->table));
    if (status != OK)
    {
        status = CreateTable(name, columns, rows, &(measurementTable->table));
    }
    measurementTable->name = name;
    return status;
}
Esempio n. 8
0
void SplitSvtWafer(const Char_t *name = "StarDb/Geometry/svt/svtWafersPosition.20050101.000100.C") {
    TString Top(name);
    Top.ReplaceAll("$STAR/","");
    Top = gSystem->DirName(Top.Data());
    static const Char_t *Barrels[4] = {"InnerBarrel","MiddleBarrel","OuterBarrel","Ssd"};
    static const Char_t *Ladder = "Ladder_";
    static const Char_t *Wafer  = "Wafer_";
    TString Name(name);
    gSystem->ExpandPathName(Name);
    gSystem->Load("libStDb_Tables.so");
    TString cmd(".L ");
    cmd += Name;
    gInterpreter->ProcessLine(cmd);
    St_svtWafersPosition *table = CreateTable();
    cmd.ReplaceAll(".L ",".U ");
    gInterpreter->ProcessLine(cmd);
    table->Print(0,10);
    TString tname = gSystem->BaseName(Name);
    Int_t N = table->GetNRows();
    svtWafersPosition_st *row = table->GetTable();
    TString separator("/");
    for (Int_t i = 0; i < N; i++, row++) {
        //  Int_t Id = ladder + 100*(wafer + 10*layer);
        Int_t Id = row->ID;
        Int_t layer = Id/1000;
        if (layer > 7) layer = 7;
        Id = Id - 1000*layer;
        Int_t wafer = Id/100;
        Int_t ladder = Id%100;
        Int_t barrel = (layer-1)/2;
        TString dir(Top);
        dir += Form("/%s/%s%02i/%s%02i",Barrels[barrel],Ladder,ladder,Wafer,wafer);
        if (gSystem->AccessPathName(dir)) {
            Int_t iok = gSystem->mkdir(dir,kTRUE);
            if (iok > -1) cout << "Make directory " << dir << " done " << endl;
            else         {
                cout << "Make directory " << dir << " failed with " << iok << endl;
            }
        }
        TString ts(dir);
        ts += "/";
        ts += tname;
        ofstream out;
        St_svtWafersPosition *newtable = new St_svtWafersPosition(table->GetName(),1);
        newtable->AddAt(row);
        out.open(ts.Data());
        cout << "Create " << ts << endl;
        newtable->SavePrimitive(out,"");
        out.close();
        delete newtable;
    }
}
Esempio n. 9
0
Database::Database()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
	_rc = sqlite3_open("c://database.db", &_db);
#else
	string path=CCFileUtils::getInstance()->getWritablePath() + "begins.db";
	_rc = sqlite3_open(path.c_str(), &_db);
#endif

	CreateTable();

	_initialized = true;
	_queryP.self = this;
}
Esempio n. 10
0
DB_Error DataBaseSqlite::AddUser(shared_ptr<User> user)
{
    DB_Error ret = CreateTable("User");
    if (ret == DB_OK)
    {
        EntryList entries = m_pTableComponent->GetTableFormat("User");
        PDEBUG ("entry size: %lu\n", entries.size());
        if (!entries.empty())
        {
            string sql(INSERT_TABLE);
            sql += string("User") + VALUE + LPARENT;
            EntryList::iterator iter = entries.begin();
            EntryList::iterator end  = entries.end();
            for (; iter != end;)
            {
                sql += "@" + iter->name;
                if (++iter != end)
                {
                    sql += ", ";
                }
            }
            sql += string(RPARENT) + SEMI;

            SqliteCommand cmd(this, sql);

            // Ugly hard code!!
            PDEBUG ("Begin binding\n");
            ret = cmd.Bind("@name", user->name());
            ret = ret ? ret : cmd.Bind("@uuid", user->uuid());
            int64 date = 0;
            if (user->has_reg_date())
            {
                ret = user->reg_date();
            }
            ret = ret ? ret : cmd.Bind("@reg_date", date);

            date = 0;

            if (user->has_last_login())
            {
                date = user->last_login();
            }
            ret = ret ? ret : cmd.Bind("@last_login", date);
            // Bind others ...
            ret = ret ? ret : cmd.Execute();
            // Execute ....
        }
    }
    return ret;
}
int main(int argc, char *argv[])
{
   char buf[LINE_LEN];              
   /* word string buffer */
   char fileName[LINE_LEN];         
   /* file name buffer */
   int howManyBins;                 
   /* number of bins to create */
   TABLE *hashTable;                
   /* pointer to hash table */
   FILE *fp;

   /* Read file name from command line */
   if (argc < MIN_ARGS || sscanf(argv[FILE_ARG_IX], BUFFMT "s", fileName) != 1)
   {
      fprintf(stderr, "No file name specified on command line\n");
      return EXIT_FAILURE;
   }
   fp = OpenFile(fileName);

   /* Read bin count from command line */
   if (sscanf(argv[BINS_ARG_IX], "%d", &howManyBins) != 1)
   {
      fprintf(stderr, "No bin count specified on command line\n");
      return EXIT_FAILURE;
   }
   hashTable = CreateTable((size_t)howManyBins);  
   /* allocate table array */

   /*
    * The following loop will read one string at a time from stdin until
    * EOF is reached.  For each string read the BuildList function will
    * be called to update the hash table.
    */
   while (fscanf(fp, BUFFMT "s", buf) != EOF) 
   /* get string from file */
   {
      /* find appropriate bin */
      BIN *bin = &hashTable->firstBin[HashFunction(buf, (size_t)howManyBins)];
      NODE *newStart = BuildTree(bin->firstNode, buf, bin);                   
      /* put string in list */
      bin->firstNode = newStart;
   }
   fclose(fp);
   PrintTable(hashTable);                    
   /* print all strings */
   FreeTable(hashTable);                     
   /* free the table */
   return(EXIT_SUCCESS);
}
Esempio n. 12
0
LOCAL_C void BuildTable(TInt aCount,TBool aTransactions,TUint& aTime,TUint& aSize)
	{
	TUint size=FileSize();
	TUint time=User::TickCount();
	CreateTable();
	if (aTransactions)
		TheDatabase.Begin();
	test(TheTable.Open(TheDatabase,KTableName)==KErrNone);
	WriteRecords(aCount);
	if (aTransactions)
		test(TheDatabase.Commit()==KErrNone);
	TheTable.Close();
	aTime=User::TickCount()-time;
	aSize=FileSize()-size;
	}
Esempio n. 13
0
void DataSearchConfig::on_btn_CreateTable_clicked()
{
    if(CreateTable())
    {
        QMessageBox::information(this,
                                 tr("Succes"),
                                 tr("Table succesfully created"));
    }
    else
    {
        QMessageBox::critical(this,
                              tr("Error"),
                              tr("Table could not be created..!"));
    }
}
Esempio n. 14
0
//test read
TEST_F(SqliteWrapTest, InsertData) {

	CreateTable();

	m_sqliteDriver->execute("insert into MyTable(name) values('aaa')");

	Statement stmt(*m_sqliteDriver, "select * from MyTable");

	if (stmt.executeStep())
	{
		ASSERT_STREQ(stmt.getColumn(1).getText(), "aaa");
	}

	TrunkTable();
}
Esempio n. 15
0
/**
@SYMTestCaseID          SYSLIB-DBMS-CT-1312
@SYMTestCaseDesc        Create a table in database
@SYMTestPriority        Medium
@SYMTestActions        	Build a table and write records into the table.Test for commiting the transactions.
@SYMTestExpectedResults Test must not fail
@SYMREQ                 REQ0000
*/
LOCAL_C void BuildTable(TInt aCount)
	{
	test.Next(_L(" @SYMTestCaseID:SYSLIB-DBMS-CT-1312 "));
#ifndef __TOOLS2__
	TheTimer.Start(_L("build"));
#endif
	CreateTable();
	TheDatabase.Begin();
	test(TheTable.Open(TheDatabase,KTableName)==KErrNone);
	WriteRecords(aCount);
	test(TheDatabase.Commit()==KErrNone);
	TheTable.Close();
#ifndef __TOOLS2__
	TheTimer.Stop();
#endif
	}
Esempio n. 16
0
void CAeonEngine::MsgCreateTable (const SArchonMessage &Msg, const CHexeSecurityCtx *pSecurityCtx)

//	MsgCreateTable
//
//	Aeon.createTable {tableDesc}
//
//	{tableDesc} = { name:MyTable1 type:standard x:{keyType:utf8} y:{keyType:int32} z:{keyType:dateTime} }

	{
	CString sError;

	//	Get the table desc and table name

	CDatum dTableDesc = Msg.dPayload.GetElement(0);
	const CString &sTable = dTableDesc.GetElement(FIELD_NAME);

	//	Make sure we are allowed access to this table

	if (!ValidateTableAccess(Msg, pSecurityCtx, sTable))
		return;

	//	See if the table descriptor specifies storage volumes; if so, then we
	//	make sure that the calling service has admin rights.

	if (!dTableDesc.GetElement(FIELD_PRIMARY_VOLUME).IsNil()
			|| !dTableDesc.GetElement(FIELD_BACKUP_VOLUMES).IsNil())
		{
		if (!ValidateAdminAccess(Msg, pSecurityCtx))
			return;
		}

	//	Create

	bool bExists;
	if (!CreateTable(dTableDesc, NULL, &bExists, &sError))
		{
		if (bExists)
			SendMessageReplyError(MSG_ERROR_ALREADY_EXISTS, sError, Msg);
		else
			SendMessageReplyError(MSG_ERROR_UNABLE_TO_COMPLY, sError, Msg);
		return;
		}

	//	Done

	SendMessageReply(MSG_OK, CDatum(), Msg);
	}
Esempio n. 17
0
bool Lex::Run(const char * fileName) {
    std::ifstream fileP(fileName);
    Trastition trans = {State_start, State_start, Event_space};
    std::string buffer = "";
    char current;

    CreateTable();

    while(!fileP.eof()){
        fileP.get(current);
        buffer += current;

        trans.currentEvent = GetEventType(current);
        trans.prevState = trans.currentState;
        trans.currentState = tableTransition[trans.currentEvent][trans.currentState];

        // Ошибка
        if(trans.currentState == State_error)
        {
            console->LogError("Лексический анализатор", "Cчитан неизвестный символ");
            exit(1);
        }


        // Создание токена
        if(trans.currentState == State_createToken)
        {
            buffer.erase(buffer.length() - 1);
            AddTokenToList(buffer, GetTokenByState(trans.prevState));
            trans = {State_start, State_start, Event_space};
            buffer.clear();
        }

    }

    if(trans.currentState == State_createToken)
    {
        AddTokenToList(buffer, GetTokenByState(trans.prevState));
        trans = {State_start, State_start, Event_space};
        buffer.clear();
    }

    LogTokenList();
    fileP.close();
    return  true;
}
Esempio n. 18
0
TableValue TableValueImpl::CreateTableValue(const amqp_field_value_t &entry)
{
  switch (entry.kind)
  {
    case AMQP_FIELD_KIND_VOID:
      return TableValue();
    case AMQP_FIELD_KIND_BOOLEAN:
      return TableValue((bool)entry.value.boolean);
    case AMQP_FIELD_KIND_I8:
      return TableValue(entry.value.i8);
    case AMQP_FIELD_KIND_I16:
      return TableValue(entry.value.i16);
    case AMQP_FIELD_KIND_I32:
      return TableValue(entry.value.i32);
    case AMQP_FIELD_KIND_I64:
    case AMQP_FIELD_KIND_TIMESTAMP:
      return TableValue(entry.value.i64);
    case AMQP_FIELD_KIND_F32:
      return TableValue(entry.value.f32);
    case AMQP_FIELD_KIND_F64:
      return TableValue(entry.value.f64);
    case AMQP_FIELD_KIND_UTF8:
    case AMQP_FIELD_KIND_BYTES:
      return TableValue(std::string((char*)entry.value.bytes.bytes,
                                    entry.value.bytes.len));
    case AMQP_FIELD_KIND_ARRAY:
    {
      amqp_array_t array = entry.value.array;
      Detail::array_t new_array;

      for (int i = 0; i < array.num_entries; ++i)
      {
        new_array.push_back(CreateTableValue(array.entries[i]));
      }

      return TableValue(new_array);
    }
    case AMQP_FIELD_KIND_TABLE:
      return TableValue(CreateTable(entry.value.table));
    case AMQP_FIELD_KIND_DECIMAL:
    default:
      return TableValue();
  }
}
Esempio n. 19
0
void API::Switcher(SqlCommand* command){
  SqlCommandType command_type = command->command_type();
  Info info;
  // typedef std::chrono::high_resolution_clock Clock;
  // typedef std::chrono::milliseconds milliseconds;
  // Clock::time_point t0 = Clock::now();
  switch(command_type){
    case kSqlInvalid: { info = Info("Invalid Command, Please check your syntax."); break; }
    case kSqlCreateTable: { info = CreateTable(dynamic_cast<SqlCommandCreateTable *>(command)); break; }
    case kSqlCreateIndex: { info = CreateIndex(dynamic_cast<SqlCommandCreateIndex *>(command)); break; }
    case kSqlDeleteFrom: { info = DeleteFrom(dynamic_cast<SqlCommandDeleteFrom *>(command)); break; }
    case kSqlDropTable: { info = DropTable(dynamic_cast<SqlCommandDropTable *>(command)); break; }
    case kSqlDropIndex: { info = DropIndex(dynamic_cast<SqlCommandDropIndex *>(command)); break; }
    case kSqlInsertInto: { info = InsertInto(dynamic_cast<SqlCommandInsertInto *>(command)); break; }
    case kSqlSelectFrom: { info = SelectFrom(dynamic_cast<SqlCommandSelectFrom *>(command));break; }
  }
  info.PrintInfo();
  // Clock::time_point t1 = Clock::now();
  // milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
  // std::cout<<"time used:"<<ms.count()<<" ms."<<std::endl;
}
Esempio n. 20
0
int main(int argc, char *argv[])
{
	int i, num, data[MAX_NUM];
	srand((unsigned)time(NULL));
	for(i=0; i<INDEX_BOX; i++)//clear hashing table
	{
		indexTable[i].val = i;
		indexTable[i].next = NULL;
	}
	printf("source data : \n\t");
	for(i=0; i<MAX_NUM; i++)
	{
		data[i] = rand()%99+1;//create data with rand()
		printf("[%2d]", data[i]);//print data
		if(i%8 == 7)
			printf("\n\t");
	}
	printf("\n");
	for(i=0; i<MAX_NUM; i++)
	{
		CreateTable(data[i]);//create hashing table
	}
	while(1)
	{
		printf("please input search data(1-99), input -1 to exit: ");
		scanf("%d", &num);
		if(num == -1)
			break;
		i = FindNum(num);
		if(i == 0)
			printf("### data not found %d ###\n", num);
		else
			printf("find data %d, total find %d times\n", num, i);
	}
	printf("\nHashing table: \n");
	for(i=0; i<INDEX_BOX; i++)
		PrintData(i);
	printf("\n");
	return 0;
}
Esempio n. 21
0
void InitWithAdjMatrix(AdjMatrixGraph *graph, EdgeList *edge_list, FreeList *free_list, Table *table){
    int i, j;
    
    CreateEdgeList(edge_list, graph->m);
    for (i = 0; i < graph->n; i++){
        for (j = 0; j < i; j++){ 
        /* Adiciona arestas apenas uma vez. 
        Para adicionar duas basta colocar j < graph->n */
            if (graph->matrix[i][j] == 1){
                AddEdge(i, j, NULO, edge_list); /* Adciona aresta descolorida ao EdgeList */
            }
        }
    }
    CreateTable(table, graph->n, graph->delta);
    for (i = 0; i < table->sizeX; i++){
        for (j = 0; j < table->sizeY; j++){
            table->matrix[i][j].status = FALSE;
            table->matrix[i][j].adj = NULO;
            table->matrix[i][j].cPointer = NULL;
        }
    }
    CreateFreeList(free_list, graph->n, graph->delta, table);
}
Esempio n. 22
0
//Initialize everything
void Initialize2(char in[], char out[]){

	int tokens = 0;
	int i = 0;
	char tmp;

	//count the number of tokens in file for proper allocation
	fp = fopen(in, "r");
	while(!feof(fp)){
		tmp = fgetc(fp);
		if(tmp == ' ') tokens++;
	}

	//allocate space for our input and token variable
	token = malloc(sizeof(char*)* 12);
	input = malloc(sizeof(char*) * tokens+2);
	for(i = 0; i < tokens+2; i++){
		input[i] = malloc(sizeof(char) * 12);
	}

	fclose(fp);
	fp = fopen(in, "r");

	//read our rokens
	for(i = 0; i < tokens; i++){
		fscanf(fp, "%s", input[i]);
	}

	fclose(fp);
	fp = fopen(out, "w");

	//create our symbol table and our code list
	int tableSize = 100;
	st = CreateTable(tableSize);
	codegen = malloc(sizeof(code*) * (tableSize * 10));

}
Esempio n. 23
0
bool CDateBase::InsertData(CString id,CString time,CString data)
{
	

//	AdoInitCommand();
	CreateTable(id);

	id = "tb_"+id;

   /*具体查询*/
	char uid[50];
	strcpy(uid,id.GetBuffer(0));

	char datatime[50];
	strcpy(datatime,time.GetBuffer(0));

	char content[1024];
	strcpy(content,data.GetBuffer(0));
	
	CString szSql;
	szSql.Format("insert into %s (time,content)values('%s','%s')",uid,datatime,content);
	_variant_t vr; 
    try 
    { 
        m_pConnection->Execute((_bstr_t)szSql,&vr,adExecuteNoRecords); 
    } 
    catch(_com_error&  e)          
    {          
//		AfxMessageBox("错误!");  
        AfxMessageBox(e.Description());  
        //ado.AdoClose();
        return false;          
    } 
//	AfxMessageBox("写入数据库正确");

	return true;
}
Esempio n. 24
0
TEST_F(HybridIndexTests, HybridScanTest) {
  std::unique_ptr<storage::DataTable> hyadapt_table;
  CreateTable(hyadapt_table, false);
  LoadTable(hyadapt_table);

  std::vector<oid_t> key_attrs;

  auto tuple_schema = hyadapt_table->GetSchema();
  catalog::Schema *key_schema;
  index::IndexMetadata *index_metadata;
  bool unique;

  key_attrs = {0};
  key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs);
  key_schema->SetIndexedColumns(key_attrs);

  unique = true;

  index_metadata = new index::IndexMetadata(
      "primary_index", 123, INVALID_OID, INVALID_OID, IndexType::BWTREE,
      IndexConstraintType::PRIMARY_KEY, tuple_schema, key_schema, key_attrs,
      unique);

  std::shared_ptr<index::Index> pkey_index(
      index::IndexFactory::GetIndex(index_metadata));

  hyadapt_table->AddIndex(pkey_index);

  std::thread index_builder =
      std::thread(BuildIndex, pkey_index, hyadapt_table.get());

  for (size_t query_itr = 0; query_itr < query_count; query_itr++) {
    LaunchHybridScan(hyadapt_table);
  }

  index_builder.join();
}
Esempio n. 25
0
int SM_Manager::Exec(const char *instr) {
	vector<string> argv;
	string cur;
	cout << instr << endl;
	for (int i = 0; ; i++) {
		if (instr[i] == ' ' || instr[i] == '(' || instr[i] == ')' || instr[i] == ',' || instr[i] == 0) {
			if (cur.length() > 0) {
				argv.push_back(cur);
				cur = "";
			}
			if (instr[i] == 0){
				break;
			}
		}
		else {
			cur = cur + instr[i];
		}
	}
	if (argv.size() < 3)
		return -1;
	if (argv[0] == "CREATE" && argv[1] =="DATABASE") {
		CreateDb(argv[2].c_str());
		return 0;
	}
	if (argv[0] == "DROP" && argv[1] == "DATABASE") {
		DropDb(argv[2].c_str());
		return 0;
	}
	if (argv[0] == "USE" && argv[1] == "DATABASE") {
		CloseDb();
		OpenDb(argv[2].c_str());
		return 0;
	}
	if (argv[0] == "SHOW" && argv[1] == "DATABASE") {
		ShowDb(argv[2].c_str());
		return 0;
	}
	if (argv[0] == "CREATE" && argv[1] == "TABLE") {
		string tablename = argv[2];
		vector<AttrInfo> attrs;
		for (int i = 3; i < argv.size();) {
			AttrInfo attr;
			if (argv[i] == "PRIMARY" && argv[i + 1] == "KEY") {
				attr.primaryKey = true;
				i += 2;
			}
			cout << argv[i] << endl;
			strcpy(attr.attrName, argv[i].c_str());
			i += 1;
			if (argv[i] == "int") {
				attr.attrType = MyINT;
				attr.attrLength = 4;
				i += 1;
				cout << "lala" << endl;
			} else if (argv[i] == "float") {
				attr.attrType = FLOAT;
				attr.attrLength = 4;
				i += 1;
			} else if (argv[i] == "char") {
				attr.attrType = STRING;
				attr.attrLength = atoi(argv[i + 1].c_str());
				i += 2;
			}
			if (i + 1 < argv.size() && argv[i] == "NOT" && argv[i + 1] == "NULL") {
				attr.notNull = true;
				i += 2;
			}
			attrs.push_back(attr);
		}
		AttrInfo *x = new AttrInfo[attrs.size()];
		for (int i = 0; i < attrs.size(); i++)
			x[i] = attrs[i];
		CreateTable(tablename.c_str(), attrs.size(), x);
		delete x;
		return 0;
	}
	if (argv[0] == "DROP" && argv[1] == "TABLE") {
		DropTable(argv[2].c_str());
		return 0;
	}
	if (argv[0] == "SHOW" && argv[1] == "TABLE") {
		ShowTable(argv[2].c_str());
		return 0;
	}
	return 0;
}
Esempio n. 26
0
void create_datasetprop_popup(Widget but, void *data)
{
    set_wait_cursor();

    if (tui.top == NULL) {
        Widget menubar, menupane, fr;
        int i, j;
        char *rowlabels[MAX_SET_COLS];
        char *collabels[DATA_STAT_COLS] =
            {"Min", "at", "Max", "at", "Mean", "Stdev"};
        int column_widths[DATA_STAT_COLS] = {12, 6, 12, 6, 12, 12};
        GraceApp *gapp = (GraceApp *) data;

        tui.top = CreateDialogForm(app_shell, "Data set statistics");

        menubar = CreateMenuBar(tui.top);
        ManageChild(menubar);
        AddDialogFormChild(tui.top, menubar);

        tui.sel = CreateGraphSetSelector(tui.top,
            "Data sets:", LIST_TYPE_SINGLE);
        AddDialogFormChild(tui.top, tui.sel->frame);
        AddStorageChoiceCB(tui.sel->set_sel, changetypeCB, tui.sel);


        menupane = CreateMenu(menubar, "File", 'F', FALSE);
        CreateMenuCloseButton(menupane, tui.top);

        menupane = CreateMenu(menubar, "Help", 'H', TRUE);
        CreateMenuHelpButton(menupane, "On data sets", 's',
            tui.top, "doc/UsersGuide.html#data-sets");
        
        for (i = 0; i < MAX_SET_COLS; i++) {
            rowlabels[i] = copy_string(NULL, dataset_col_name(gapp->grace, i));
            for (j = 0; j < DATA_STAT_COLS; j++) {
                tui.rows[i][j] = NULL;
            }
        }

        fr = CreateFrame(tui.top, "Statistics");
        tui.mw = CreateTable("mw", fr, MAX_SET_COLS, DATA_STAT_COLS,
                                 MAX_SET_COLS, 4);
        TableDataSetPropInit(tui.mw);
        TableSetColLabels(tui.mw, collabels);
        TableSetColWidths(tui.mw, column_widths);
        TableSetDefaultColAlignment(tui.mw, ALIGN_END);
        TableSetDefaultColLabelAlignment(tui.mw, ALIGN_CENTER);
        TableSetRowLabels(tui.mw, rowlabels);
        TableSetDefaultRowLabelWidth(tui.mw, 3);
        TableSetDefaultRowLabelAlignment(tui.mw, ALIGN_CENTER);
        TableUpdateVisibleRowsCols(tui.mw);

        AddTableEnterCellCB(tui.mw, enterCB, NULL);

        AddDialogFormChild(tui.top, fr);
        ManageChild(tui.top);
    }
    
    RaiseWindow(GetParent(tui.top));
    unset_wait_cursor();
}
Esempio n. 27
0
void create_leval_frame(Widget but, void *data)
{
    Quark *gr = (Quark *) data;

    if (!gr) {
        return;
    }
    
    set_wait_cursor();

    levalui.gr = gr;

    if (levalui.top == NULL) {
        int i;
        Widget fr, rc1;
        int nscols;
        char *rows[MAX_SET_COLS][1];
        char **cells[MAX_SET_COLS];
        char *rowlabels[MAX_SET_COLS];
        int column_widths[1] = {50};
        int column_maxlengths[1] = {256};
        Grace *grace = grace_from_quark(gr);

        levalui.top = CreateDialogForm(app_shell, "Load & evaluate");

        fr = CreateFrame(levalui.top, "Parameter mesh ($t)");
        AddDialogFormChild(levalui.top, fr);
        rc1 = CreateHContainer(fr);
        levalui.start = CreateTextItem(rc1, 10, "Start at:");
        levalui.stop = CreateTextItem(rc1, 10, "Stop at:");
        levalui.npts = CreateTextItem(rc1, 6, "Length:");

        levalui.set_type = CreateSetTypeChoice(levalui.top, "Set type:");
        AddDialogFormChild(levalui.top, levalui.set_type->menu);
        AddOptionChoiceCB(levalui.set_type, set_type_cb, (void *) &levalui);
        
        nscols = 2;
        for (i = 0; i < nscols; i++) {
            rowlabels[i] = copy_string(NULL, dataset_col_name(grace, i));
            rowlabels[i] = concat_strings(rowlabels[i], " = ");
            if (i == 0) {
                rows[i][0] = "$t";
            } else {
                rows[i][0] = "";
            }
            cells[i] = &rows[i][0];
        }

        levalui.mw = CreateTable("mw", levalui.top,
                                 nscols, 1,
                                 MAX_SET_COLS, 1);
        TableLevalInit(levalui.mw);
        TableSetColWidths(levalui.mw, column_widths);
        TableSetColMaxlengths(levalui.mw, column_maxlengths);
        TableSetRowLabels(levalui.mw, rowlabels);
        TableSetDefaultRowLabelWidth(levalui.mw, 6);
        TableSetDefaultRowLabelAlignment(levalui.mw, ALIGN_CENTER);
        TableSetCells(levalui.mw, cells);
        TableUpdateVisibleRowsCols(levalui.mw);

        AddTableLeaveCellCB(levalui.mw, leaveCB, &levalui);

        CreateAACDialog(levalui.top, levalui.mw, leval_aac_cb, &levalui);
    }
    
    RaiseWindow(GetParent(levalui.top));
    unset_wait_cursor();
}
Esempio n. 28
0
//_____________________________________________
void KVLifeTimeTable::Initialize()
{

    TString dfile;
    dfile.Form("%s.DataFile",GetName());
    TString cl_path;
    if( !KVBase::SearchKVFile(gEnv->GetValue(dfile.Data(),""),cl_path,"data") ) {
        Error("Initialize","No file found for %s",GetName());
        return;
    }
    else {
        //Info("Initialize","%s will be read",gEnv->GetValue(dfile.Data(),""));
    }
    SetTitle(gEnv->GetValue(dfile.Data(),""));

    Int_t ntot=0;
    nucMap = new TMap(50,2);
    KVFileReader* fr = new KVFileReader();
    fr->OpenFileToRead(cl_path.Data());

    //Premier passage
    while (fr->IsOK()) {

        fr->ReadLine(" ");
        if (fr->GetNparRead()==0) break;
        else if (fr->GetReadPar(0).BeginsWith("//")) {

            kcomments+=fr->GetCurrentLine();
            kcomments+="\n";

        }
        else {
            Int_t zz = fr->GetIntReadPar(0);
            Int_t aa = fr->GetIntReadPar(1);
            GiveIndexToNucleus(zz,aa,ntot);
            ntot+=1;
        }
    }

    if ( !fr->PreparForReadingAgain() ) return;

    //Info("Initialize","Set up map for %d nuclei", ntot);
    CreateTable(ntot);

    KVLifeTime* lf = 0;
    ntot=0;
    while (fr->IsOK()) {

        fr->ReadLine(" ");
        if (fr->GetCurrentLine().IsNull()) {
            break;
        }
        else if (fr->GetNparRead()==0) {
            break;
        }
        else if (fr->GetReadPar(0).BeginsWith("//")) { }
        else {
            Double_t val = fr->GetDoubleReadPar(2);

            CreateElement(ntot);
            lf = (KVLifeTime* )GetCurrent();

            if (fr->GetNparRead()>3) {
                TString unit = fr->GetReadPar(3);
                if ( unit.EndsWith("eV") ) {
                    lf->SetResonnance(kTRUE);
                    val *= ToMeV(unit);
                }
                else {
                    lf->SetResonnance(kFALSE);
                    val *= ToSecond(unit);
                }
                if (fr->GetNparRead()>4) {
                    Int_t meas = fr->GetReadPar(4).Atoi();
                    lf->SetMeasured(meas);
                }
                else {
                    if (ntot==0) InfoOnMeasured();
                }
            }
            lf->SetValue(val);

            ntot+=1;
        }

    }

    //Info("Initialize","table initialised correctly for %d nuclei", ntot);
    fr->CloseFile();
    delete fr;

}
Esempio n. 29
0
//功能读入窗口,中枢函数,返回false的时候读入结束
bool userDatabase::userRead(){
    cout << endl << username << ">" << endl;
    switch(mySql.read()){
        case 0: return false;
        case 1:
            if(!CreateTable())  cout << "[Error] Create table error!" << endl;
                break;
        case 2:
            if(!CreateView())   cout << "[Error] Create view error!" << endl;
            break;
        case 3:
            if(!CreateIndex())  cout << "[Error] Create index error!" << endl;
            break;
        case 10:
            if(!InsertTable())  cout << "[Error] Insert error!" << endl;
                break;
        case 11:
            if(!SelectTable())  cout << "[Error] Select error!" << endl;
                break;
        case 12:
            if(!DeleteTable())  cout << "[Error] Drop table error!" << endl;
                break;
        case 13:
            if(!UpdateTable())  cout << "[Error] Update table error!" << endl;
                break;
        case 14:
            if(!DeleteData())   cout << "[Error] Delete data error!" << endl;
                break;
        case 15:
            if(!DeleteView())   cout << "[Error] Delete view error!" << endl;
                break;
        case 16:
            if(!GrantToUser())  cout << "[Error] Grant to user error!" << endl;
            break;
        case 20:
            readme.createHelp();
            break;
        case 21:
            readme.selectHelp();
            break;
        case 22:
            readme.insertHelp();
            break;
        case 23:
            readme.dropHelp();
            break;
        case 24:
            readme.updateHelp();
            break;
        case 25:
            InputAllTable();
            InputAllView();
            InputAllIndex();
            break;
        case 26:
            InputAllTable();
            break;
        case 27:
            InputAllView();
            break;
        case 28:
            InputAllIndex();
            break;
        default :
            printf("[Error] SQL input error!\n");
            break;
    }
    return true;
};
nsresult
nsPermissionManager::InitDB(PRBool aRemoveFile)
{
  nsCOMPtr<nsIFile> permissionsFile;
  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(permissionsFile));
  if (!permissionsFile)
    return NS_ERROR_UNEXPECTED;

  nsresult rv = permissionsFile->AppendNative(NS_LITERAL_CSTRING(kPermissionsFileName));
  NS_ENSURE_SUCCESS(rv, rv);

  if (aRemoveFile) {
    PRBool exists = PR_FALSE;
    rv = permissionsFile->Exists(&exists);
    NS_ENSURE_SUCCESS(rv, rv);
    if (exists) {
      rv = permissionsFile->Remove(PR_FALSE);
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  nsCOMPtr<mozIStorageService> storage = do_GetService(MOZ_STORAGE_SERVICE_CONTRACTID);
  if (!storage)
    return NS_ERROR_UNEXPECTED;

  // cache a connection to the hosts database
  rv = storage->OpenDatabase(permissionsFile, getter_AddRefs(mDBConn));
  NS_ENSURE_SUCCESS(rv, rv);

  PRBool ready;
  mDBConn->GetConnectionReady(&ready);
  if (!ready) {
    // delete and try again
    rv = permissionsFile->Remove(PR_FALSE);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = storage->OpenDatabase(permissionsFile, getter_AddRefs(mDBConn));
    NS_ENSURE_SUCCESS(rv, rv);

    mDBConn->GetConnectionReady(&ready);
    if (!ready)
      return NS_ERROR_UNEXPECTED;
  }

  PRBool tableExists = PR_FALSE;
  mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts"), &tableExists);
  if (!tableExists) {
      rv = CreateTable();
      NS_ENSURE_SUCCESS(rv, rv);

  } else {
    // table already exists; check the schema version before reading
    PRInt32 dbSchemaVersion;
    rv = mDBConn->GetSchemaVersion(&dbSchemaVersion);
    NS_ENSURE_SUCCESS(rv, rv);

    switch (dbSchemaVersion) {
    // upgrading.
    // every time you increment the database schema, you need to implement
    // the upgrading code from the previous version to the new one.
    // fall through to current version

    case 1:
      {
        // previous non-expiry version of database.  Upgrade it by adding the
        // expiration columns
        rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
              "ALTER TABLE moz_hosts ADD expireType INTEGER"));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
              "ALTER TABLE moz_hosts ADD expireTime INTEGER"));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = mDBConn->SetSchemaVersion(HOSTS_SCHEMA_VERSION);
        NS_ENSURE_SUCCESS(rv, rv);
      }

      // fall through to the next upgrade
      
    // current version.
    case HOSTS_SCHEMA_VERSION:
      break;

    case 0:
      {
        NS_WARNING("couldn't get schema version!");
          
        // the table may be usable; someone might've just clobbered the schema
        // version. we can treat this case like a downgrade using the codepath
        // below, by verifying the columns we care about are all there. for now,
        // re-set the schema version in the db, in case the checks succeed (if
        // they don't, we're dropping the table anyway).
        rv = mDBConn->SetSchemaVersion(HOSTS_SCHEMA_VERSION);
        NS_ENSURE_SUCCESS(rv, rv);
      }
      // fall through to downgrade check

    // downgrading.
    // if columns have been added to the table, we can still use the ones we
    // understand safely. if columns have been deleted or altered, just
    // blow away the table and start from scratch! if you change the way
    // a column is interpreted, make sure you also change its name so this
    // check will catch it.
    default:
      {
        // check if all the expected columns exist
        nsCOMPtr<mozIStorageStatement> stmt;
        rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
          "SELECT host, type, permission, expireType, expireTime FROM moz_hosts"),
          getter_AddRefs(stmt));
        if (NS_SUCCEEDED(rv))
          break;

        // our columns aren't there - drop the table!
        rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DROP TABLE moz_hosts"));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = CreateTable();
        NS_ENSURE_SUCCESS(rv, rv);
      }
      break;
    }
  }

  // make operations on the table asynchronous, for performance
  mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA synchronous = OFF"));

  // cache frequently used statements (for insertion, deletion, and updating)
  rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
    "INSERT INTO moz_hosts "
    "(id, host, type, permission, expireType, expireTime) "
    "VALUES (?1, ?2, ?3, ?4, ?5, ?6)"), getter_AddRefs(mStmtInsert));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
    "DELETE FROM moz_hosts "
    "WHERE id = ?1"), getter_AddRefs(mStmtDelete));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
    "UPDATE moz_hosts "
    "SET permission = ?2, expireType= ?3, expireTime = ?4 WHERE id = ?1"),
    getter_AddRefs(mStmtUpdate));
  NS_ENSURE_SUCCESS(rv, rv);

  // check whether to import or just read in the db
  if (tableExists)
    return Read();

  return Import();
}