Exemplo n.º 1
0
// ************************************************************ 
void
testCreateTableAndInsert (void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2}
  };
  int numInserts = 9, i;
  Record *r;
  RID *rids;
  Schema *schema;
  testName = "test creating a new table and inserting tuples";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  //printf("\n Testing create table");
  TEST_CHECK(createTable("test_table_r.txt",schema));
  //printf("\n Testing open Table");
  TEST_CHECK(openTable(table, "test_table_r.txt"));
 printf("\n Opened "); 
  // insert rows into table
   for(i = 0; i < numInserts; i++)
    {
    	printf("\n Inserting");
      r = fromTestRecord(schema, inserts[i]);
      	
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
    }

 TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_r.txt"));
	printf("\n Opened successsfully");
  // randomly retrieve records from the table and compare to inserted ones
  for(i = 0; i < 1000; i++)
    {
      int pos = rand() % numInserts;
      RID rid = rids[pos];
      printf("\n getting records");
      TEST_CHECK(getRecord(table, rid, r));
      ASSERT_EQUALS_RECORDS(fromTestRecord(schema, inserts[pos]), r, schema, "compare records");
    }
  
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r.txt"));
  TEST_CHECK(shutdownRecordManager());

  free(rids);
  free(table);
  TEST_DONE();
}
Exemplo n.º 2
0
void testUnuseSchema(database* db)
{
    try
    {
        db->close();
        bool ret = db->open(makeUri(PROTOCOL, HOSTNAME, DBNAMEV3, _T("")), TYPE_SCHEMA_BDF,TD_OPEN_NORMAL);
        BOOST_CHECK_MESSAGE(ret == true, "db open stat = " << db->stat());
        table_ptr tb = openTable(db, _T("nulltest"), TD_OPEN_NORMAL);
        tb->setKeyNum(0);
        tb->clearBuffer();
        fields& fds = tb->fields();
        fds[(short)0] = 1;
        tb->seek();
        BOOST_CHECK_MESSAGE(tb->stat() == 0, "UnuseSchema seek stat = " << tb->stat());
        for (short i = 1 ;i < (short)fds.size(); ++i)
            BOOST_CHECK_MESSAGE(fds[i].isNull() == true, "UnuseSchema isNull field num = " << i);

        //open second table
        table_ptr tb2 = openTable(db, _T("nulltest"), TD_OPEN_NORMAL);
        BOOST_CHECK_MESSAGE(db->stat() == 0, "UnuseSchema openTable stat = " << db->stat());

        //shared tabledef
        BOOST_CHECK_MESSAGE(db->dbDef()->tableCount() == 1, "tableCount = " << db->dbDef()->tableCount());

        tb2->setKeyNum(0);
        tb2->clearBuffer(table::defaultNull);

        //default values
        fields& fds2 = tb2->fields();
        for (short i = 1 ;i < (short)fds.size(); ++i)
        {
            bool v = true;
            int dv = 0;
            if (i == 0 || i == 5 || i == 6) v = false;
            BOOST_CHECK_MESSAGE(fds2[i].isNull() == v, "defaultValue isNull field num = " << i);
            if (i == 5) dv = -1;
                    
            if (i == 6) dv = -123456;
            BOOST_CHECK_MESSAGE(fds2[i].i() == dv, "defaultValue defaultValue field num = " 
                    << i << " " << fds2[i].i());
        }
    
        fds2[(short)0] = 1;
        tb2->seek();
        BOOST_CHECK_MESSAGE(tb2->stat() == 0, "UnuseSchema seek stat = " << tb2->stat());
        for (short i = 1 ;i < (short)fds2.size(); ++i)
            BOOST_CHECK_MESSAGE(fds2[i].isNull() == true, "UnuseSchema isNull field num = " << i);
    
        db->openTable(_T("abc"));
        BOOST_CHECK_MESSAGE(db->stat() == STATUS_TABLE_NOTOPEN, "openTable stat = " << db->stat());
    }
    catch (bzs::rtl::exception& e)
    {
        _tprintf(_T("testUnuseSchema Error ! %s\n"), (*getMsg(e)).c_str());
    }
}
Exemplo n.º 3
0
extern RC OpenJoinManager (Schema *s1,char *t1,Schema *s2,char *t2,Schema *s3,char *t3){

	mgmtinfo =(tablemgmt*)malloc(sizeof(tablemgmt));
	mgmtinfo2 =(tablemgmt*)malloc(sizeof(tablemgmt));
	table = (RM_TableData *) malloc(sizeof(RM_TableData));
 	table2 = (RM_TableData *) malloc(sizeof(RM_TableData));
 	table3 = (RM_TableData *) malloc(sizeof(RM_TableData));
 	openTable(table, t1);
  	mgmtinfo=table->mgmtData;
  	openTable(table2, t2);
  	mgmtinfo2=table2->mgmtData;
  	openTable(table3, t3);
  	mgmtinfo3=table3->mgmtData;
    return RC_OK;
}
Exemplo n.º 4
0
void testFielddefs(database* db)
{
    short ret = createTestDataBase(db);
    BOOST_CHECK_MESSAGE(0 == ret, "createTestDataBase stat = " << ret);
    if (ret) return;
    ret = createTestTable(db);
    BOOST_CHECK_MESSAGE(0 == ret, "createTestTable stat = " << ret);
    if (ret) return;
    try
    {
        short tableid = 1;
        table_ptr tb = openTable(db, tableid, TD_OPEN_NORMAL);
        
        //Check nullbit
        const tabledef* td = tb->tableDef();
        const fielddef* fd = &td->fieldDefs[1];
        BOOST_CHECK_MESSAGE(fd->nullbit() == 0, "Invalid nullbit = " << (int)fd->nullbit());
        BOOST_CHECK_MESSAGE(fd->nullbytes() == 2, "Invalid nullbytes = " << (int)fd->nullbytes());

        fd = &td->fieldDefs[8]; //fd8
        BOOST_CHECK_MESSAGE(fd->nullbit() == 7, "Invalid nullbit = " << (int)fd->nullbit());
        BOOST_CHECK_MESSAGE(fd->nullbytes() == 2, "Invalid nullbytes = " << (int)fd->nullbytes());
        //fielddefs copy test
        fielddefs& fds = *fielddefs::create();
        fds.addAllFields(tb->tableDef());
        fd = &fds[1];
        BOOST_CHECK_MESSAGE(fd->nullbit() == 0, "Invalid nullbit = " << (int)fd->nullbit());
        BOOST_CHECK_MESSAGE(fd->nullbytes() == 2, "Invalid nullbytes = " << (int)fd->nullbytes());

        // Append join field, nullbytes and nullbit specify only append fields.
        query q;
        q.select(_T("fd8"));
        tb->setQuery(&q);
        fds.addSelectedFields(tb.get());
        fd = &fds[(int)fds.size() -1];
        BOOST_CHECK_MESSAGE(fd->nullbit() == 0, "Invalid nullbit = " << (int)fd->nullbit());
        BOOST_CHECK_MESSAGE(fd->nullbytes() == 1, "Invalid nullbytes = " << (int)fd->nullbytes());
        
        //One more join 
        q.reset().select(_T("fd2"), _T("fd3"), _T("fd4"), _T("fd5"), _T("fd6"));
        tb->setQuery(&q);
        fds.addSelectedFields(tb.get());
        fd = &fds[(int)fds.size() -1];
        BOOST_CHECK_MESSAGE(fd->nullbit() == 4, "Invalid nullbit = " << (int)fd->nullbit());
        BOOST_CHECK_MESSAGE(fd->nullbytes() == 1, "Invalid nullbytes = " << (int)fd->nullbytes());

        //One more join 
        q.reset().select(_T("fd1"), _T("fd2"), _T("fd3"), _T("fd4"), _T("fd5"), _T("fd6"), _T("fd7"), _T("fd8"));
        tb->setQuery(&q);
        fds.addSelectedFields(tb.get());
        fd = &fds[(int)fds.size() -1];
        BOOST_CHECK_MESSAGE(fd->nullbit() == 7, "Invalid nullbit = " << (int)fd->nullbit());
        BOOST_CHECK_MESSAGE(fd->nullbytes() == 1, "Invalid nullbytes = " << (int)fd->nullbytes());
        fds.release();
    }
    catch (bzs::rtl::exception& e)
    {
        _tprintf(_T("Error ! %s\n"), (*getMsg(e)).c_str());
    }
}
Exemplo n.º 5
0
void MainWindow::openDB()
{
	QString dbName = QFileDialog::getOpenFileName(this,tr("Open An Exsisted RankView Database"),m_lastOpenPath,tr("RankView DB (*.rkv);;All Files (*)"));
	if(!dbName.isEmpty())
		if(setCurrentDB(dbName))
			openTable();
}
Exemplo n.º 6
0
Table::Table(QWidget *parent) :
    QWidget(parent),tableSize(0)
{
    table = new QTableWidget(0,5,this);
    QStringList labels;
    labels << "Mark" << "Color" << "Year" << "Status" << "Date of last repair";
    table->setHorizontalHeaderLabels(labels);

    newcartage = new QPushButton ("New cartage");
    save = new QPushButton ("Save");
    open = new QPushButton ("Open");

    connect(newcartage, SIGNAL(clicked()), this, SLOT(makeNewCartage()));
    connect(save, SIGNAL(clicked()), this, SLOT(saveTable()));
    connect(open, SIGNAL(clicked()), this, SLOT(openTable()));
    connect((QObject*)table->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(sortTable(int)));
    connect((QObject*)table->verticalHeader(), SIGNAL(sectionDoubleClicked(int)), this,SLOT(deleteDialogCartage()));
    connect(table, SIGNAL(cellChanged(int,int)), this, SLOT(changeData(int,int)));

    mainlayout = new QGridLayout;
    mainlayout->addWidget(table,0,0,1,3);
    mainlayout->addWidget(newcartage,1,0);
    mainlayout->addWidget(save,1,1);
    mainlayout->addWidget(open,1,2);
    setLayout(mainlayout);

}
Exemplo n.º 7
0
void testFieldValue(database* db)
{
    try
    {
        short tableid = 1;
        table_ptr tb = openTable(db, tableid, TD_OPEN_NORMAL);
        tb->clearBuffer();
        for (int i = 1; i < tb->tableDef()->fieldCount; ++i)
        {
            tb->setFVNull(i, true);
            BOOST_CHECK_MESSAGE(tb->getFVNull(i) == true, "Invalid getFVNull i = " << i);
            tb->setFVNull(i, false);
            BOOST_CHECK_MESSAGE(tb->getFVNull(i) == false, "Invalid getFVNull i = " << i);
        }

        // field 0 is not nullable
        short index = 0;
        tb->setFVNull(index, true);
        BOOST_CHECK_MESSAGE(tb->getFVNull(index) == false, "Invalid getFVNull(0) ");
        tb->setFVNull(index, false);
        BOOST_CHECK_MESSAGE(tb->getFVNull(index) == false, "Invalid getFVNull(0) ");
 
    }
    catch (bzs::rtl::exception& e)
    {
        _tprintf(_T("Error ! %s\n"), (*getMsg(e)).c_str());
    }
}
Exemplo n.º 8
0
void testTableStore(database* db)
{
    try
    {
        // All null test
        short tableid = 1;
        table_ptr tb = openTable(db, tableid, TD_OPEN_NORMAL);
        tb->setKeyNum(0);
        tb->clearBuffer();
        fields& fds = tb->fields();
        
        fds[(short)0] = 1;
        for (short i = 1 ;i < (short)fds.size(); ++i)
        {
            fds[i] = _T("123");
            fds[i].setNull(true);
        }
        tb->insert();
        BOOST_CHECK_MESSAGE(tb->stat() == 0, "testStore insert stat = " << tb->stat());
        
        tb->clearBuffer();
        fds[(short)0] = 1;
        tb->seek();
        BOOST_CHECK_MESSAGE(tb->stat() == 0, "testStore seek stat = " << tb->stat());
        for (short i = 1 ;i < (short)fds.size(); ++i)
            BOOST_CHECK_MESSAGE(fds[i].isNull() == true, "testStore isNull field num = " << i);

        // All not null test
        tb->clearBuffer(table::defaultNull);
        fds[(short)0] = 2;
        for (short i = 1 ;i < (short)fds.size(); ++i)
            fds[i].setNull(false);
        tb->insert();
        BOOST_CHECK_MESSAGE(tb->stat() == 0, "testStore insert stat = " << tb->stat());

        tb->clearBuffer(table::defaultNull);
        
        fds[(short)0] = 2;
        tb->seek();
        BOOST_CHECK_MESSAGE(tb->stat() == 0, "testStore seek stat = " << tb->stat());
        for (short i = 1 ;i < (short)fds.size(); ++i)
        {
            BOOST_CHECK_MESSAGE(fds[i].isNull() == false, "testStore isNull field num = " << i);
            //Test Default value
            __int64 dv = 0;
            if (i == 5) dv = -1;
            if (i == 6) dv = -123456;
            if (i != 10) //ignore timestamp
                BOOST_CHECK_MESSAGE(fds[i].i64() == dv, "testStore defaultValue field num = " 
                    << i << " " << fds[i].i64());
        }
    }
    catch (bzs::rtl::exception& e)
    {
        _tprintf(_T("Error ! %s\n"), (*getMsg(e)).c_str());
    }
}
Exemplo n.º 9
0
RC testTombstone(void)
{
	RM_TableData *table = (RM_TableData *)malloc(sizeof(RM_TableData));
	TestRecord inserts[] = {
		{ 1, "aaaa", 3 },
		{ 2, "bbbb", 2 },
		{ 3, "cccc", 1 },
		{ 4, "dddd", 3 },
		{ 5, "eeee", 5 },
		{ 6, "ffff", 1 },
		{ 7, "gggg", 3 },
		{ 8, "hhhh", 3 },
		{ 9, "iiii", 2 },
		{ 10, "jjjj", 5 },
	};
	int numInserts = 10, numUpdates = 3, numDeletes = 5, numFinal = 5, i;
	Record *r;
	RID *rids;
	Schema *schema;
	testName = "test creating a new table and insert,update,delete tuples";
	schema = testSchema();
	rids = (RID *)malloc(sizeof(RID) * numInserts);

	TEST_CHECK(initRecordManager(NULL));
	TEST_CHECK(createTable("test_table_r", schema));
	TEST_CHECK(openTable(table, "test_table_r"));

	// insert rows into table
	for (i = 0; i < numInserts; i++)
	{
		r = fromTestRecord(schema, inserts[i]);
		TEST_CHECK(insertRecord(table, r));
		rids[i] = r->id;
	}

	TEST_CHECK(deleteRecord(table, rids[9]));
	RID id;
	id.page = rids[9].page;
	id.slot = rids[10].slot;
	int isTombstone = checkIfTombstoneEncountered(table, rids[9]);

	TEST_CHECK(closeTable(table));
	TEST_CHECK(deleteTable("test_table_r"));
	TEST_CHECK(shutdownRecordManager());

	free(table);
	if (isTombstone == 1) {
		return RC_OK;
	}
	else {
		return RC_NOT_A_TOMBSTONE;
	}

}
Exemplo n.º 10
0
/* Desc of nulltest table timestampNull = false

| Field | Type          | Null | Key | Default              | Extra
+-------+---------------+------+-----+----------------------+-------------------
| id    | int(11)       | NO   | PRI | NULL                 |
| fd1   | int(11)       | YES  | UNI | NULL                 |
| fd2   | int(11)       | YES  |     | NULL                 |
| fd3   | int(11)       | YES  |     | NULL                 |
| fd4   | int(11)       | YES  |     | NULL                 |
| fd5   | int(11)       | NO   |     | -1                   |
| fd6   | varchar(16)   | YES  |     | NULL                 |
| fd7   | varbinary(50) | YES  |     | NULL                 |
| fd8   | timestamp(6)  | NO   |     | CURRENT_TIMESTAMP(6) | on update CURRENT_TIMESTAMP(6) |
| fd9   | datetime(6)   | YES  |     | NULL                 |
| fd10  | timestamp(6)  | YES  |     | CURRENT_TIMESTAMP(6) | on update CURRENT_TIMESTAMP(6) |
| fd11  | datetime(6)   | NO   |     | NULL                 | on update CURRENT_TIMESTAMP(6) |
+-------+---------------+------+-----+----------------------+-------------------
*/
void testTimestamp(database* db)
{
    try
    {
        short tableid = 1;
        {
            table_ptr tb = openTable(db, tableid, TD_OPEN_NORMAL+TD_OPEN_MASK_MYSQL_NULL);
            tb->setKeyNum(0);
            tb->clearBuffer();
            fields& fds = tb->fields();
            fds[(short)0] = 1;
            for (short i = 1 ;i < (short)fds.size(); ++i)
                fds[i].setNull(true);
            tb->insert();
            BOOST_CHECK_MESSAGE(tb->stat() == 0, "testTimestamp insert stat = " << tb->stat());
        
            tb->clearBuffer();
            fds[(short)0] = 1;
            tb->seek();
            BOOST_CHECK_MESSAGE(tb->stat() == 0, "testTimestamp seek stat = " << tb->stat());

            __int64 v = fds[_T("fd8")].i64();
            BOOST_CHECK_MESSAGE(v != 0, "Timestamp is 0 ");
            
            BOOST_CHECK_MESSAGE(fds[_T("fd10")].isNull() == true, "Timestamp2 not null" );

            Sleep(10);
            tb->update();
            BOOST_CHECK_MESSAGE(tb->stat() == 0, "testTimestamp update stat = " << tb->stat());
            tb->seek();

            if (canDatatimeTimeStamp(tb.get(), 8))
                BOOST_CHECK_MESSAGE(fds[_T("fd8")].i64() != v, "Timestamp not udapte ");
            BOOST_CHECK_MESSAGE(fds[_T("fd8")].i64() != 0, "Timestamp is zero ");

        }

    }
    catch (bzs::rtl::exception& e)
    {
        _tprintf(_T("Error ! %s\n"), (*getMsg(e)).c_str());
    }
}
Exemplo n.º 11
0
void testDefaultValue(database* db, bool timestampNull)
{
    try
    {
        short tableid = 1;
        table_ptr tb = openTable(db, tableid, TD_OPEN_NORMAL+TD_OPEN_MASK_MYSQL_NULL);
        tb->setKeyNum(0);
        tb->clearBuffer(table::defaultNull);
        fields& fds = tb->fields();
        if (timestampNull)
        {
            for (short i = 0 ;i < (short)fds.size(); ++i)
            {
                bool v = true;
                int dv = 0;
                if (i == 0 || i == 5 || i == 6) v = false;
                BOOST_CHECK_MESSAGE(fds[i].isNull() == v, "testDefaultValue isNull field num = " << i);
                if (i == 5) dv = -1;
                    
                if (i == 6) dv = -123456;
                BOOST_CHECK_MESSAGE(fds[i].i() == dv, "testDefaultValue defaultValue field num = " 
                        << i << " " << fds[i].i());
            }
        }else
        {
            int dfs[13] = {0, 0, 0, 0, 0, -1, -123456, 0, 3, 0, 0, 1, 0};
            for (short i = 1 ;i < (short)fds.size(); ++i)
            {
                BOOST_CHECK_MESSAGE(fds[i].isNull() == (dfs[i] == 0), "testDefaultValue isNull field num = " << i);
                if ((dfs[i] < 0) || i == 12)
                    BOOST_CHECK_MESSAGE(fds[i].i() == dfs[i], "testDefaultValue i() field num = " << i);
                else if ((dfs[i]  < 3))
                    BOOST_CHECK_MESSAGE(fds[i].i64() == 0, "testDefaultValue i64() field num = " << i);
            }
        }
    }
    catch (bzs::rtl::exception& e)
    {
        _tprintf(_T("Error ! %s\n"), (*getMsg(e)).c_str());
    }
}
Exemplo n.º 12
0
void printtable(char* tableName){
    RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
    Record *r = (Record *) malloc(sizeof(Record));
    openTable(table, tableName);
    int i;
    printf("#######################################################\n");
    for(i=0;i<table->schema->numAttr;i++){
        printf("%-15s", table->schema->attrNames[i]);
    }
    printf("\n");
    
    RM_ScanHandle *sc = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
    startScan(table, sc, NULL);
    Value* v;
    while(next(sc, r) == RC_OK){
        for(i=0;i<table->schema->numAttr;i++){
            if(table->schema->dataTypes[i] == DT_INT)
            {
                getAttr(r,table->schema,i,&v);
                printf("%-15d",v->v.intV);
            } else if(table->schema->dataTypes[i] == DT_STRING)
            {
                getAttr(r,table->schema,i,&v);
                printf("%-15s",v->v.stringV);
            } else if(table->schema->dataTypes[i] == DT_FLOAT)
            {
                getAttr(r,table->schema,i,&v);
                printf("%-15fl",v->v.floatV);
            } else if(table->schema->dataTypes[i] == DT_BOOL)
            {
                getAttr(r,table->schema,i,&v);
                printf("%-15s",v->v.boolV ? "true" : "false");
            }
        }
        printf("\n");
    }
    
    printf("#######################################################\n");
}
bool rspfVpfFeatureClassSchema::openSchema(rspfVpfCoverage* coverage)
{
   theCoverage = coverage;
   bool result = false;
   if(theCoverage)
   {
      theSchemaTableName = theCoverage->getPath().dirCat("fcs");
      if(theSchemaTableName.exists())
      {
         result = openTable(theSchemaTableName);
         if(result)
         {
            result = validateColumnNames();
         }
         if(result)
         {
            setFeatureClassMapping();
         }
      }
   }
   
   return result;
}
Exemplo n.º 14
0
int main (int *argc, char **argv) {
  char *tab;
  char *accession;

  SRAMgr const *sra;
  SRATable const *tbl;
  spotid_t nspots;
  rc_t rc;

  tab = argv[1];
  accession = argv[2];

  rc = openTable(tab, &sra, &tbl, &nspots);
  if (rc != 0) {
    return rc;
  }
  printf("There are %d spots\n", nspots);

  //  rc = getReads(tbl, accession, 10);
  rc = getBases(tbl, 1, 10);
  if (rc != 0) {
    closeTable(sra, tbl);
    return 1;
  }

  printf("\n");
  rc = getQuals(tbl, 1, 10);
  if (rc != 0) {
    closeTable(sra, tbl);
    return 1;
  }

  getInfo(tbl, 1, 10);
  getRanges(tbl);
  closeTable(sra, tbl);
  return 0;
}
void testUserInterface()
{
	int attrNum=0;
	int keys[]={};

	printf("Enter the number of attributes: \n");
	scanf("%d",&attrNum);
	int attrTypes[attrNum];
	int attrSize[attrNum];
	DataType dt[attrNum];
	char *attrName[attrNum];
	int numRec;
	int j;

	for(j=0 ; j< attrNum ; j++){
		printf("Enter the attribute name for %d attribute :",j+1);
		attrName[j]=malloc(100);
		scanf("%s",attrName[j]);

		printf("Enter the type of attribute for %d attribute \n int : 0 \n string : 1 \n Float : 2 \n Boolean : 3 \n",j+1);
		scanf("%d",&attrTypes[j]);

		if(attrTypes[j]==0)
			dt[j] = DT_INT;
		else if(attrTypes[j]==1)
			dt[j] = DT_STRING;
		else if(attrTypes[j]==2)
			dt[j] = DT_FLOAT;
		else if(attrTypes[j]==3)
			dt[j] = DT_BOOL;

		if(attrTypes[j]!= 1){
			attrSize[j] = 0;
		}else{
			printf("Enter the size of the string attribute \n");
			scanf("%d",&attrSize[j]);
		}

	}


	Schema *schema;
	schema = createSchema(attrNum, attrName, dt, attrSize, 0 ,keys);

	RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
	  TestRecord inserts[] = {
	    {1, "aaaa", 3},
	    {2, "bbbb", 2},
	    {3, "cccc", 1},
	    {4, "dddd", 3},
	    {5, "eeee", 5},
	    {6, "ffff", 1},
	    {7, "gggg", 3},
	    {8, "hhhh", 3},
	    {9, "iiii", 2}
	  };
	  int numInserts = 9, i;
	  Record *r;
	  RID *rids;
	  testName = "testing user interface";

	  rids = (RID *) malloc(sizeof(RID) * numInserts);

	  TEST_CHECK(initRecordManager(NULL));
	  TEST_CHECK(createTable("test_table_r",schema));
	  TEST_CHECK(openTable(table, "test_table_r"));

	  // insert rows into table
	  for(i = 0; i < numInserts; i++)
	    {
	      r = fromTestRecord(schema, inserts[i]);
	      TEST_CHECK(insertRecord(table,r));
	      rids[i] = r->id;
	    }

	  TEST_CHECK(closeTable(table));
	  TEST_CHECK(openTable(table, "test_table_r"));

	  // randomly retrieve records from the table and compare to inserted ones with (int,string,int) format.
	  if(attrNum <= 3)
	  {
		for(i = 0; i < 1000; i++)
	    {
	      int pos = rand() % numInserts;
	      RID rid = rids[pos];
	      TEST_CHECK(getRecord(table, rid, r));
	      ASSERT_EQUALS_RECORDS(fromTestRecord(schema, inserts[pos]), r, schema, "compare records");
	    }
	  }

	  TEST_CHECK(closeTable(table));
	  TEST_CHECK(deleteTable("test_table_r"));
	  TEST_CHECK(shutdownRecordManager());

	  free(rids);
	  free(table);
	  TEST_DONE();

}
void testScansTwo (void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  bool foundScan[] = {
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE,
    FALSE
  };
  int numInserts = 10, i;
  Record *r;
  RID *rids;
  Schema *schema;
  RM_ScanHandle *sc = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
  Expr *sel, *left, *right, *first, *se;
  int rc;

  testName = "test creating a new table and inserting tuples";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_r",schema));
  TEST_CHECK(openTable(table, "test_table_r"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
  {
    r = fromTestRecord(schema, inserts[i]);
    TEST_CHECK(insertRecord(table,r)); 
    rids[i] = r->id;
  }

  TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_r"));

  // Select 1 record with INT in condition a=2.
  MAKE_CONS(left, stringToValue("i2"));
  MAKE_ATTRREF(right, 0);
  MAKE_BINOP_EXPR(sel, left, right, OP_COMP_EQUAL);
  createRecord(&r, schema);
  TEST_CHECK(startScan(table, sc, sel));
  while((rc = next(sc, r)) == RC_OK)
  {
     ASSERT_EQUALS_RECORDS(fromTestRecord(schema, inserts[1]), r, schema, "compare records");
  }
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc));
  
  // Select 1 record with STRING in condition b='ffff'.
  MAKE_CONS(left, stringToValue("sffff"));
  MAKE_ATTRREF(right, 1);
  MAKE_BINOP_EXPR(sel, left, right, OP_COMP_EQUAL);
  createRecord(&r, schema);
  TEST_CHECK(startScan(table, sc, sel));
  while((rc = next(sc, r)) == RC_OK)
  {
     ASSERT_EQUALS_RECORDS(fromTestRecord(schema, inserts[5]), r, schema, "compare records");
     serializeRecord(r, schema);
  }
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc));
  
  // Select all records, with condition being false
  MAKE_CONS(left, stringToValue("i4"));
  MAKE_ATTRREF(right, 2);
  MAKE_BINOP_EXPR(first, right, left, OP_COMP_SMALLER);
  MAKE_UNOP_EXPR(se, first, OP_BOOL_NOT);
  TEST_CHECK(startScan(table, sc, se));
    while((rc = next(sc, r)) == RC_OK)
    {
     serializeRecord(r, schema);
     for(i = 0; i < numInserts; i++)
     {
       if (memcmp(fromTestRecord(schema, inserts[i])->data,r->data,getRecordSize(schema)) == 0)
	     foundScan[i] = TRUE;
     }
    }
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc));
  
  ASSERT_TRUE(!foundScan[0], "not greater than four");
  ASSERT_TRUE(foundScan[4], "greater than four");
  ASSERT_TRUE(foundScan[9], "greater than four");

  // clean up
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r"));
  TEST_CHECK(shutdownRecordManager());

  freeRecord(r);
  free(table);
  free(sc);
  freeExpr(sel);
  TEST_DONE();
}
void testScans (void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  TestRecord scanOneResult[] = { 
    {3, "cccc", 1},
    {6, "ffff", 1},
  };
  bool foundScan[] = {
    FALSE,
    FALSE
  };
  int numInserts = 10, scanSizeOne = 2, i;
  Record *r;
  RID *rids;
  Schema *schema;
  RM_ScanHandle *sc = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
  Expr *sel, *left, *right;
  int rc;

  testName = "test creating a new table and inserting tuples";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_r",schema));
  TEST_CHECK(openTable(table, "test_table_r"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
  {
      r = fromTestRecord(schema, inserts[i]);
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
  }

  TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_r"));

  // run some scans
  MAKE_CONS(left, stringToValue("i1"));
  MAKE_ATTRREF(right, 2);
  MAKE_BINOP_EXPR(sel, left, right, OP_COMP_EQUAL);

  TEST_CHECK(startScan(table, sc, sel));
  while((rc = next(sc, r)) == RC_OK)
  {
      for(i = 0; i < scanSizeOne; i++)
      {
          if (memcmp(fromTestRecord(schema, scanOneResult[i])->data,r->data,getRecordSize(schema)) == 0)
              foundScan[i] = TRUE;
      }
  }
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc));
  for(i = 0; i < scanSizeOne; i++)
    ASSERT_TRUE(foundScan[i], "check for scan result");
  
  // clean up
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r"));
  TEST_CHECK(shutdownRecordManager());

  free(table);
  free(sc);
  freeExpr(sel);
  TEST_DONE();
}
void 
testInsertManyRecords(void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  TestRecord realInserts[10000];
  TestRecord updates[] = {
    {3333, "iiii", 6}
  };
  int numInserts = 10000, i, numcheck=50;
  int randomRec = 3333;
  Record *r;
  RID *rids;
  Schema *schema;
  testName = "test creating a new table and inserting 10000 records then updating record from rids[3333]";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_t",schema));
  TEST_CHECK(openTable(table, "test_table_t"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
    {
      realInserts[i] = inserts[i%10];
      realInserts[i].a = i;
      r = fromTestRecord(schema, realInserts[i]);
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
    }
  TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_t"));

  // retrieve records from the table and compare to expected final stage
  for(i = 0; i < numcheck; i++)
    {
      RID rid = rids[i];
      TEST_CHECK(getRecord(table, rid, r));
      ASSERT_EQUALS_RECORDS(fromTestRecord(schema, realInserts[i]), r, schema, "compare records");
    }
  
  r = fromTestRecord(schema, updates[0]);
  r->id = rids[randomRec];
  TEST_CHECK(updateRecord(table,r));
  TEST_CHECK(getRecord(table, rids[randomRec], r)); 
  ASSERT_EQUALS_RECORDS(fromTestRecord(schema, updates[0]), r, schema, "compare records");
   
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_t"));
  TEST_CHECK(shutdownRecordManager());

  freeRecord(r);
  free(table);
  TEST_DONE();
}
void 
testUpdateTable (void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  TestRecord updates[] = {
    {1, "iiii", 6},
    {2, "iiii", 6},
    {3, "iiii", 6}
  };
  int deletes[] = {
    9,
    6,
    7,
    8,
    5
  };
  TestRecord finalR[] = {
    {1, "iiii", 6},
    {2, "iiii", 6},
    {3, "iiii", 6},
    {4, "dddd", 3},
    {5, "eeee", 5},
  };
  int numInserts = 10, numUpdates = 3, numDeletes = 5, numFinal = 5, i;
  Record *r;
  RID *rids;
  Schema *schema;
  testName = "test creating a new table and insert,update,delete tuples";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_r",schema));
  TEST_CHECK(openTable(table, "test_table_r"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
    {
      r = fromTestRecord(schema, inserts[i]);
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
    }

  // delete rows from table
  for(i = 0; i < numDeletes; i++)
    {
      TEST_CHECK(deleteRecord(table,rids[deletes[i]]));
    }

  // update rows into table
  for(i = 0; i < numUpdates; i++)
    {
      r = fromTestRecord(schema, updates[i]);
      r->id = rids[i];
      TEST_CHECK(updateRecord(table,r)); 
    }

  TEST_CHECK(closeTable(table));
  TEST_CHECK(openTable(table, "test_table_r"));

  // retrieve records from the table and compare to expected final stage
  for(i = 0; i < numFinal; i++)
    {
      RID rid = rids[i];
      TEST_CHECK(getRecord(table, rid, r));
      ASSERT_EQUALS_RECORDS(fromTestRecord(schema, finalR[i]), r, schema, "compare records");
    }
  
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r"));
  TEST_CHECK(shutdownRecordManager());

  free(table);
  TEST_DONE();
}
void
testMultipleScans(void)
{
  RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
  TestRecord inserts[] = { 
    {1, "aaaa", 3}, 
    {2, "bbbb", 2},
    {3, "cccc", 1},
    {4, "dddd", 3},
    {5, "eeee", 5},
    {6, "ffff", 1},
    {7, "gggg", 3},
    {8, "hhhh", 3},
    {9, "iiii", 2},
    {10, "jjjj", 5},
  };
  int numInserts = 10, i, scanOne=0, scanTwo=0;
  Record *r;
  RID *rids;
  Schema *schema;
  testName = "test running muliple scans ";
  schema = testSchema();
  rids = (RID *) malloc(sizeof(RID) * numInserts);
  RM_ScanHandle *sc1 = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
  RM_ScanHandle *sc2 = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
  Expr *se1, *left, *right;
  int rc,rc2;
  
  TEST_CHECK(initRecordManager(NULL));
  TEST_CHECK(createTable("test_table_r",schema));
  TEST_CHECK(openTable(table, "test_table_r"));
  
  // insert rows into table
  for(i = 0; i < numInserts; i++)
  {
      r = fromTestRecord(schema, inserts[i]);
      TEST_CHECK(insertRecord(table,r)); 
      rids[i] = r->id;
  }

  // Mix 2 scans with c=3 as condition
  MAKE_CONS(left, stringToValue("i3"));
  MAKE_ATTRREF(right, 2);
  MAKE_BINOP_EXPR(se1, left, right, OP_COMP_EQUAL);
  createRecord(&r, schema);
  TEST_CHECK(startScan(table, sc1, se1));
  TEST_CHECK(startScan(table, sc2, se1));
  if ((rc2 = next(sc2, r)) == RC_OK)
    scanTwo++;
  i = 0;
  while((rc = next(sc1, r)) == RC_OK)
  {
      scanOne++;
      i++;
      if (i % 3 == 0)
          if ((rc2 = next(sc2, r)) == RC_OK)
              scanTwo++;
  }
  while((rc2 = next(sc2, r)) == RC_OK)
    scanTwo++;

  ASSERT_TRUE(scanOne == scanTwo, "scans returned same number of tuples");
  if (rc != RC_NO_TUPLES)
    TEST_CHECK(rc);
  TEST_CHECK(closeScan(sc1));
  TEST_CHECK(closeScan(sc2));
 
  TEST_CHECK(closeTable(table));
  TEST_CHECK(deleteTable("test_table_r"));
  TEST_CHECK(shutdownRecordManager());

  free(rids);
  free(table);
  TEST_DONE();
}
Exemplo n.º 21
0
void
testCheckingPrimaryKeyWithSingleAttribute(void)
{
    //just like test_assign3_1.c we insert records in the same way at first.
    RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
    TestRecord inserts[] = {
        {1, "aaaa", 3},
        {2, "bbbb", 2},
        {3, "cccc", 1},
        {4, "dddd", 3},
        {5, "eeee", 5},
        {6, "ffff", 1},
        {7, "gggg", 3},
        {8, "hhhh", 3},
        {9, "iiii", 2},
        {10, "jjjj", 5},
    };
    TestRecord realInserts[10000];
    int numInserts = 100, i;
    Record *r;
    RID *rids;
    Schema *schema;
    testName = "test checking primary key with single attribute";

    //this schema is exactly the same as test_assign3_1.c, this primary key only have 1 attibute.
    schema = testSchema();
    rids = (RID *) malloc(sizeof(RID) * numInserts);

    TEST_CHECK(initRecordManager(NULL));
    TEST_CHECK(createTable("test_table_t",schema));
    TEST_CHECK(openTable(table, "test_table_t"));

    for(i = 0; i <numInserts; i++)
    {
        realInserts[i] = inserts[i%10];
        realInserts[i].a = i;
        r = fromTestRecord(schema, realInserts[i]);

        printf("inserting record {%d,\"%s\",%d}",realInserts[i].a,realInserts[i].b,realInserts[i].c);
        //Extra Credit: Check primary key constraints.
        //check whether there exists a tuple that have the same key attribute value with this new record.
        if (CheckPrimaryKey(table, r)==RC_OK) {
            printf("  Success!\n");
        }
        else {
            printf("   Failed! A tuple with same attribute value already exists!\n");
        }
        TEST_CHECK(insertRecord(table,r));
        rids[i] = r->id;
    }

    //here is the code to check distinct,we insert some records that are already exist in the file, if detected, the checking function will return a RC value differen from RC_OK.
    TestRecord newInsert;
    newInsert=inserts[0];
    newInsert.a=0;
    r=fromTestRecord(schema, newInsert);
    printf("inserting record {%d,\"%s\",%d}",newInsert.a,newInsert.b,newInsert.c);
    //Extra Credit: Check primary key constraints.
    //check whether there exists a tuple that have the same key attribute value with this new record.
    if (CheckPrimaryKey(table, r)==RC_OK) {
        printf("  Success!\n");
    }
    else {
        printf("   Failed! A tuple with same attribute value already exists!\n");
    }
    insertRecord(table,r);


    TEST_CHECK(closeTable(table));
    TEST_CHECK(deleteTable("test_table_t"));
    TEST_CHECK(shutdownRecordManager());

    freeRecord(r);
    free(table);
    TEST_DONE();
}
Exemplo n.º 22
0
int
main (void) 
{
    initRecordManager(NULL);
    int in;
    int cl = 0;
    while(cl == 0){
        printf("What to do:\n1.Add new table\n2.insert\n3.update\n4.delete\n5.scan\n6.print table\n7.close\n");
        in=0;
        scanf("%d",&in);
        RM_TableData *table;
        Record *result,*r;
        Value *value,*v;
        int i,j;
        switch(in)
        {
            case 0:
                printf("invalid input\n");
                break;
            case 1:
                printf("\nAdding new table:\n");
                printf("Table name: ");
                char tbn[50];
                scanf("%s",tbn);
                char* tbnp = (char *) malloc(sizeof(char)*sizeof(tbn));
                memcpy(tbnp,tbn,sizeof(tbn));
                printf("number of attributes: ");
                int nat = 0;
                scanf("%d",&nat);
                printf("number of keys: ");
                int nk = 0;
                scanf("%d",&nk);
                Schema *sch;
                char **names = (char **) malloc(sizeof(char*) * nat);
                DataType* dt = (DataType *) malloc(sizeof(DataType) * nat);
                int* sizes = (int *) malloc(sizeof(int) * nat);
                int* keys = (int *) malloc(sizeof(int) * nk);
                int kptr = 0;
                for(i=0;i<nat;i++){
                    printf("Attribute %d name:  ", i+1);
                    char buf[100];
                    scanf("%s", buf);
                    char* tmp = (char *) malloc(sizeof(char)*sizeof(buf));
                    memcpy(tmp,buf,sizeof(buf));
                    names[i] = tmp;
                    printf("Attribute %d datatype: [I/S/F/B]: ", i+1);
                    char dtp;
                    scanf(" %c", &dtp);
                    //printf("\ndtp = %c", dtp);
                    switch(dtp)
                    {
                        case 'I':
                            dt[i] = DT_INT;
                            sizes[i] = 0;
                            break;
                        case 'S':
                            dt[i] = DT_STRING;
                            printf("Attribute %d length:  ", i+1);
                            scanf("%d",&sizes[i]);
                            printf("length is: %d\n", sizes[i]);
                            break;
                        case 'F':
                            dt[i] = DT_FLOAT;
                            sizes[i] = 0;
                            break;
                        case 'B':
                            dt[i] = DT_BOOL;
                            sizes[i] = 0;
                            break;
                            
                    }
                    printf("Is Attribute %d a key?: [Y/N] ", i+1);
                    char isk;
                    scanf(" %c", &isk);
                    if(isk == 'Y'){
                        keys[kptr] = i;
                        kptr++;
                    }
                    //printf("schema add: %s,%d,%c\n",names[i],sizes[i],isk);
                }
                sch = createSchema(nat,names,dt,sizes,nk,keys);
                createTable(tbnp,sch);
                break;
            case 2:
                printf("Insert record\n");
                printf("table name: ");
                char buf2[100];
                scanf("%s", buf2);
                char* tmp2 = (char *) malloc(sizeof(char)*sizeof(buf2));
                memcpy(tmp2,buf2,sizeof(buf2));
                table = (RM_TableData *) malloc(sizeof(RM_TableData));
                openTable(table, tmp2);
                createRecord(&result, table->schema);
               for(i=0;i<table->schema->numAttr;i++){
                    if(table->schema->dataTypes[i] == DT_INT)
                    {
                        printf("intput int attr[%d/%d] value -- %s: ", i+1,table->schema->numAttr,table->schema->attrNames[i]);
                        int intt = 0;
                        scanf("%d",&intt);
                        //printf("\n%d is %d\n", i, intt);
                        MAKE_VALUE(value,DT_INT,intt);
                        setAttr(result, table->schema, i, value);
                        freeVal(value);
                    } else if (table->schema->dataTypes[i] == DT_STRING)
                    {
                        printf("intput string attr[%d/%d] value -- %s: ", i+1,table->schema->numAttr,table->schema->attrNames[i]);
                        char instrbuf[100];
                        scanf("%s",instrbuf);
                        char* instr = (char *) malloc(sizeof(char)*sizeof(instrbuf));
                        memcpy(instr,instrbuf,sizeof(instrbuf));
                        MAKE_STRING_VALUE(value,instr);
                        setAttr(result, table->schema, i, value);
                        freeVal(value);
                    } else if (table->schema->dataTypes[i] == DT_FLOAT)
                    {
                        printf("intput float attr[%d/%d] value -- %s: ", i+1,table->schema->numAttr,table->schema->attrNames[i]);
                        float infl;
                        scanf("%fl",&infl);
                        MAKE_VALUE(value,DT_FLOAT,infl);
                        setAttr(result, table->schema, i, value);
                        freeVal(value);
                    } else if (table->schema->dataTypes[i] == DT_BOOL)
                    {
                        printf("intput boolean attr[%d/%d] value -- %s [T/F]: ", i+1,table->schema->numAttr,table->schema->attrNames[i]);
                        char inbl;
                        scanf(" %c",&inbl);
                        if(inbl == 'T'){
                            MAKE_VALUE(value,DT_BOOL,true);
                        }
                        else if (inbl == 'F'){
                            MAKE_VALUE(value,DT_BOOL,false);
                        }
                        setAttr(result, table->schema, i, value);
                        freeVal(value);
                    }
                    if(i==table->schema->numAttr-1){
                        printf("\n");
                    }
                }
                insertRecord(table,result);
                
                break;
            case 3:
                printf("update record\n");
                printf("table name: ");
                char buf3[100];
                scanf("%s", buf3);
                char* tmp3 = (char *) malloc(sizeof(char)*sizeof(buf3));
                memcpy(tmp3,buf3,sizeof(buf3));
                table = (RM_TableData *) malloc(sizeof(RM_TableData));
                openTable(table, tmp3);
                createRecord(&result, table->schema);
                
                r = (Record *) malloc(sizeof(Record));
                RM_ScanHandle *sc = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
                startScan(table, sc, NULL);
                
                printf("Select record to update: \n");
                j=0;
                int rids[100][2];
                while(next(sc, r) == RC_OK){
                    printf("(%d)   ",j+1);
                    rids[j][0] = r->id.page;
                    rids[j][1] = r->id.slot;
                    for(i=0;i<table->schema->numAttr;i++){
                        if(table->schema->dataTypes[i] == DT_INT)
                        {
                            getAttr(r,table->schema,i,&v);
                            printf("%-15d",v->v.intV);
                        } else if(table->schema->dataTypes[i] == DT_STRING)
                        {
                            getAttr(r,table->schema,i,&v);
                            printf("%-15s",v->v.stringV);
                        } else if(table->schema->dataTypes[i] == DT_FLOAT)
                        {
                            getAttr(r,table->schema,i,&v);
                            printf("%-15fl",v->v.floatV);
                        } else if(table->schema->dataTypes[i] == DT_BOOL)
                        {
                            getAttr(r,table->schema,i,&v);
                            printf("%-15s",v->v.boolV ? "true" : "false");
                        }
                    }
                    printf("\n");
                    j++;
                }
                
                int sele;
                scanf("%d", &sele);
                sele--;
                if(sele >= 0 && sele < j+1){
                    createRecord(&result, table->schema);
                    for(i=0;i<table->schema->numAttr;i++){
                        if(table->schema->dataTypes[i] == DT_INT)
                        {
                            printf("intput int attr[%d/%d] value -- %s: ", i+1,table->schema->numAttr,table->schema->attrNames[i]);
                            int intt = 0;
                            scanf("%d",&intt);
                            //printf("\n%d is %d\n", i, intt);
                            MAKE_VALUE(value,DT_INT,intt);
                            setAttr(result, table->schema, i, value);
                            freeVal(value);
                        } else if (table->schema->dataTypes[i] == DT_STRING)
                        {
                            printf("intput string attr[%d/%d] value -- %s: ", i+1,table->schema->numAttr,table->schema->attrNames[i]);
                            char instrbuf[100];
                            scanf("%s",instrbuf);
                            char* instr = (char *) malloc(sizeof(char)*sizeof(instrbuf));
                            memcpy(instr,instrbuf,sizeof(instrbuf));
                            MAKE_STRING_VALUE(value,instr);
                            setAttr(result, table->schema, i, value);
                            freeVal(value);
                        } else if (table->schema->dataTypes[i] == DT_FLOAT)
                        {
                            printf("intput float attr[%d/%d] value -- %s: ", i+1,table->schema->numAttr,table->schema->attrNames[i]);
                            float infl;
                            scanf("%fl",&infl);
                            MAKE_VALUE(value,DT_FLOAT,infl);
                            setAttr(result, table->schema, i, value);
                            freeVal(value);
                        } else if (table->schema->dataTypes[i] == DT_BOOL)
                        {
                            printf("intput boolean attr[%d/%d] value -- %s [T/F]: ", i+1,table->schema->numAttr,table->schema->attrNames[i]);
                            char inbl;
                            scanf(" %c",&inbl);
                            if(inbl == 'T'){
                                MAKE_VALUE(value,DT_BOOL,true);
                            }
                            else if (inbl == 'F'){
                                MAKE_VALUE(value,DT_BOOL,false);
                            }
                            setAttr(result, table->schema, i, value);
                            freeVal(value);
                        }
                        if(i==table->schema->numAttr-1){
                            printf("\n");
                        }
                    }
                    result->id.page = rids[sele][0];
                    result->id.slot = rids[sele][1];
                    updateRecord(table,result);
                }
                break;
            case 4:
                printf("delete record\n");
                printf("table name: ");
                char buf4[100];
                scanf("%s", buf4);
                char* tmp4 = (char *) malloc(sizeof(char)*sizeof(buf3));
                memcpy(tmp4,buf4,sizeof(buf4));
                table = (RM_TableData *) malloc(sizeof(RM_TableData));
                openTable(table, tmp4);
                createRecord(&result, table->schema);
                
                r = (Record *) malloc(sizeof(Record));
                RM_ScanHandle *sc2 = (RM_ScanHandle *) malloc(sizeof(RM_ScanHandle));
                startScan(table, sc2, NULL);
                
                printf("Select record to delete: \n");
                j=0;
                int rids2[100][2];
                while(next(sc2, r) == RC_OK){
                    printf("(%d)   ",j+1);
                    rids2[j][0] = r->id.page;
                    rids2[j][1] = r->id.slot;
                    for(i=0;i<table->schema->numAttr;i++){
                        if(table->schema->dataTypes[i] == DT_INT)
                        {
                            getAttr(r,table->schema,i,&v);
                            printf("%-15d",v->v.intV);
                        } else if(table->schema->dataTypes[i] == DT_STRING)
                        {
                            getAttr(r,table->schema,i,&v);
                            printf("%-15s",v->v.stringV);
                        } else if(table->schema->dataTypes[i] == DT_FLOAT)
                        {
                            getAttr(r,table->schema,i,&v);
                            printf("%-15fl",v->v.floatV);
                        } else if(table->schema->dataTypes[i] == DT_BOOL)
                        {
                            getAttr(r,table->schema,i,&v);
                            printf("%-15s",v->v.boolV ? "true" : "false");
                        }
                    }
                    printf("\n");
                    j++;
                }
                
                int sele2;
                scanf("%d", &sele2);
                sele2--;
                if(sele2 >= 0 && sele2 < j+1){
                    RID rid;
                    rid.page = rids[sele2][0];
                    rid.slot = rids[sele2][1];
                    deleteRecord(table,rid);
                }
                break;
            case 5:
                printf("scan\n");
                break;
            case 6:
                printf("table name: ");
                char buf[100];
                scanf("%s", buf);
                char* tmp = (char *) malloc(sizeof(char)*sizeof(buf));
                memcpy(tmp,buf,sizeof(buf));
                printtable(buf);
                break;
            case 7:
                cl = 1;
                break;
            default:
                printf("invalid input\n");
                break;
        }
    }
}
Exemplo n.º 23
0
void PBObserver::onGameInfo(RMessage *msg)
{
	PBLobbyDriver *drv = PBLobbyDriver::fromMessage(msg);

	Q_ASSERT(drv);

	PBSiteGameInfo *gi= _games->gameInfo(msg->getString("gameId"));
	
	PBGameInfo temp;
	msg->get(&temp);

	if(!gi->owner())	// if not observed by anyone
	{
		if(gi->canOpen())
		{	if(drv->canHandleMoreTables())
			{
				gi->setOwner(drv);	// locks the game
				gi->setLastUpdateTime(QTime::currentTime());
				gi->updateState(&temp);
				qLog(Debug)<<"LOCKED "<<gi->gameId()<<" by "<<gi->ownerId();
				openTable(msg, gi);
			}
		}else
		{
			qLog(Debug)<<"CLOSETOURNEY_NOT_OWNER_CANT_OPEN "<<gi->gameId();
			closeTourney(msg, gi);
		}
		
	}else
	{
		PBLobbyDriver *obsDrv = gi->owner();

		if(drv==obsDrv)
		{
			gi->updateState(&temp);
			if(gi->tableOpened())
			{
				gi->setNeedTableOpened(-1); // opened ok
				if(gi->tourneyOpened())
				{
					qLog(Debug)<<"CLOSETOURNEY_TOPEN "<<gi->gameId()<<" OWN="<<gi->ownerId();
					closeTourney(msg,gi);
				}
			}
			else if(gi->canOpen())
			{
				qLog(Debug)<<"REOBSERVE "<<gi->gameId()<<" by "<<gi->ownerId();
				// was closde by someone manualy
				openTable(msg, gi);
			}else{
				// not opend, cannot open - unlock
				qLog(Debug)<<"CLOSETOURNEY_CANTOPEN, UNLOCK "<<gi->gameId()<<" "<<gi->ownerId();
				gi->setOwner(0); // unlock
				gi->setTableOpened(0);
				gi->setTourneyOpened(0);
			}
			gi->setLastUpdateTime(QTime::currentTime());
		}else   // locked by	 other driver
		{
			qLog(Debug)<<"CLOSE "<<gi->gameId()<<" locked by "<<gi->ownerId()<<" upd from "<<gi->driver();
			closeTourney(msg, gi);
		}
	}
	
	_games->dump();
}
Exemplo n.º 24
0
/*
 * AUTHOR: Nikhil  
 * DESC: Parse the sql stmts and execute the respective methods
 */
int main(int argc, char *argv[]){

    char readline[ARRAY_LENGTH];
    char temparray[ARRAY_LENGTH];
    char *temp;
    char *temp1;
    char *tableName;
    char *length;
    int charLength;
    int numattr=0,k,count=0,numTuples=0;
    Schema *schema;
    RID *rids;
    char columns[ARRAY_LENGTH][ARRAY_LENGTH];
    
   
    int i=0,j=0;
    
        if(fork() == 0) {
			execv("/usr/bin/clear", argv);
			exit(1);
		}
	else wait(NULL);
        
        printf("\n SQL parser\n");
        
        while(1){
        printf("\n >>");
        
        fflush(stdin);
        gets(readline);
        
        memcpy(temparray,readline,sizeof(readline));
        
        if(strstr(readline,"create table") || strstr(readline,"CREATE TABLE")){
        
            parser(readline,argv);
            
            tableName=strtok(argv[2],"(");
            
            temp=strstr(temparray,"(");
            
            temp++;
            
            temp1=strtok(temp,",");
            while(temp1!=NULL){
                strcpy(columns[i],temp1);
            temp1=strtok(NULL,",");
            i++;
            }
            j=i;
            numattr=j;
   strcpy(columns[i-1],strtok(columns[i-1],")"));

    char* colname[numattr];
    char* datatype[numattr];
    DataType dt[numattr];
    int sizes[numattr];
     int keyattr[numattr];
            for(i=0;i<j;i++){
          
       
                parser(columns[i],argv);
                
                colname[i]=argv[0];
                datatype[i]=argv[1];
                if(strstr(Upper(datatype[i]),"VARCHAR")) {
                     dt[i]=DT_STRING;
                    length=strtok(datatype[i],"(");
                    length=strtok(NULL,"(");
                    charLength=strtok(length,")");
                    if(length==NULL){
                    
                        printf("\nWrong Format");
                                 break;
                    }
                        sizes[i]=atoi(charLength);
                }
                        if(strstr(Upper(datatype[i]),"INT")){
                        dt[i]=DT_INT;
                        }
                         else if(strstr(Upper(datatype[i]),"FLOAT")){
                            dt[i]=DT_FLOAT;
                        }
                    else if(strstr(Upper(datatype[i]),"BOOL")){
                            dt[i]=DT_BOOL;                        }
                
                
                else{
                 sizes[i]=0;
                }
                
                if(strstr(Upper(datatype[i]),"PRIMARYKEY")){
                    
                keyattr[i]=1;
                    
                }
                else{
                 keyattr[i]=0;
                }
               
                
            }
     
     for(k=0;k<sizeof(keyattr)/sizeof(keyattr[0]);k++){
         if(keyattr[i]==1){
             count++;
          
          }
   
     }
     if(count>0){
         
         printf("wrong format...cannot contain more than one primary key");
         break;
     
     }
 
     schema=testSchema(numattr,colname,dt,sizes,keyattr);
     initRecordManager(NULL);
     createTable(Upper(tableName),schema);
     printf("Table Created Successfully");
     shutdownRecordManager();

        }
        
        if(strstr(Upper(readline),"INSERT INTO")){
        
              parser(readline,argv);
            
            tableName=strtok(argv[2],"(");
            
            temp=strtok(temparray,"(");
            temp=strtok(NULL,"(");
            strcpy(columns[0],temp);
       strcpy(columns[0],strtok(columns[0],")"));
       
        char* values[i];
        i=0;
       values[0]=strtok(columns[0],",");
       while(values[i]!=NULL){
           i++;
          values[i]=strtok(NULL,",");
       }
       
             numTuples=i;
             rids = (RID *) malloc(sizeof(RID) * numTuples);
             RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
             initRecordManager(NULL);
        int fd = open(Upper(tableName), O_WRONLY);    
        if(fd<0){
            printf("Database Doesn't Exist");
            break;
        }

                openTable(table, tableName);
                schema=table->schema;
                 Record *result;
                 Value *value;
                createRecord(&result, schema);
                for(i = 0; i < numTuples; i++)
                {
                  if(schema->dataTypes[i]==DT_INT || schema->dataTypes[i]==DT_FLOAT || schema->dataTypes[i]==DT_BOOL){
                  MAKE_VALUE(value, schema->dataTypes[i], atoi(values[i]));
                  }
                  if(schema->dataTypes[i]==DT_STRING){
                  MAKE_STRING_VALUE(value, values[i]);
                  }
               
                   setAttr(result, schema, i, value);
                   freeVal(value);
                 
                }
                  insertRecord(table,result); 
                  rids[i] = result->id;
printf("Inserted Successfully");
               closeTable(table);
               shutdownRecordManager();
              
             
                  }
        
         if(strstr(Upper(readline),"UPDATE TABLE")){
             
           parser(readline,argv);
            
            tableName=strtok(argv[2],"(");
            
            temp1=strtok(temparray,"(");
            temp=strtok(NULL,"(");
            strcpy(columns[0],temp);
       strcpy(columns[0],strtok(columns[0],")"));
       
       temp1=strtok(temp1,"=");
       temp1=strtok(NULL,"=");
       
        char* values[i];
        i=0;
       values[0]=strtok(columns[0],",");
       while(values[i]!=NULL){
           i++;
          values[i]=strtok(NULL,",");
       }
       
             numTuples=i;
             rids = (RID *) malloc(sizeof(RID) * numTuples);
             RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
             initRecordManager(NULL);
        int fd = open(Upper(tableName), O_WRONLY);    
        if(fd<0){
            printf("Database Doesn't Exist");
            break;
        }
       
                openTable(table, Upper(tableName));
                schema=table->schema;
                               
                  Record *result;
                  Value *value;
                  createRecord(&result, schema);
                for(i = 0; i < numTuples; i++)

                {
                  if(schema->dataTypes[i]==DT_INT || schema->dataTypes[i]==DT_FLOAT || schema->dataTypes[i]==DT_BOOL){
                  MAKE_VALUE(value, schema->dataTypes[i], atoi(values[i]));
                  }
                  if(schema->dataTypes[i]==DT_STRING){
                  MAKE_STRING_VALUE(value, values[i]);
                  }
               
                   setAttr(result, schema, i, value);
                   freeVal(value);
            
                   
                }
                       result->id=rids[i] ;
                   updateRecord(table,result);
printf("Updated Successfully");
               closeTable(table);
               shutdownRecordManager();
               
         }
        
         if(strstr(Upper(readline),"DELETE FROM")){
             
           parser(readline,argv);
            
            tableName=strtok(argv[2],"(");
            
            temp=strtok(temparray,"(");
            temp=strtok(NULL,"(");
            strcpy(columns[0],temp);
       strcpy(columns[0],strtok(columns[0],")"));
       
       int r_id=atoi(columns[0]);
             numTuples=i;
             rids = (RID *) malloc(sizeof(RID) * numTuples);
RM_TableData *table = (RM_TableData *) malloc(sizeof(RM_TableData));
                           initRecordManager(NULL);
        int fd = open(Upper(tableName), O_WRONLY);    
        if(fd<0){
            printf("Database Doesn't Exist");
            break;
        }

                openTable(table, Upper(tableName));
                schema=table->schema;
               deleteRecord(table,rids[r_id]);
printf("Deleted Successfully");
               closeTable(table);
               shutdownRecordManager();
         }
              
        
        }
        }