Exemple #1
0
//Compare two tuples
//Return true if equals else returns false
bool IsEqual(Tuple t1, Tuple t2)
{
	if(t1.isNull() || t2.isNull()) return false;
	Schema st1 = t1.getSchema();
	Schema st2 = t2.getSchema();
	
	if(st1!=st2) return false;

	vector<string> fieldNames = st1.getFieldNames();

	vector<string>::iterator iter;

	for(iter = fieldNames.begin(); iter!=fieldNames.end(); iter++)
	{
		if(st1.getFieldType(*iter) == INT)
		{
			if(t1.getField(*iter).integer != t2.getField(*iter).integer)
				return false;
		}
		else
		{
			string val1 = *(t1.getField(*iter).str);
			string val2 = *(t2.getField(*iter).str);
			if(val1 != val2)
				return false;
		}
	}

	return true;
}
bool IsEqualTuples(Tuple tup1, Tuple tup2)
{
	if(tup1.isNull() || tup2.isNull()) return false;
	Schema schemat1 = tup1.getSchema();
	Schema schemat2 = tup2.getSchema();

	if(schemat1!=schemat2) return false;

	vector<string> field_names = schemat1.getFieldNames();

	vector<string>::iterator myiterator;

	for(myiterator = field_names.begin(); myiterator!=field_names.end(); myiterator++)
	{
		if(schemat1.getFieldType(*myiterator) == INT)
		{
			if(tup1.getField(*myiterator).integer != tup2.getField(*myiterator).integer)
				return false;
		}
		else
		{
			string val1 = *(tup1.getField(*myiterator).str);
			string val2 = *(tup2.getField(*myiterator).str);
			if(val1 != val2)
				return false;
		}
	}

	return true;
}
Exemple #3
0
//To check whether the tuple is valid for a Natural Join
bool isJoinTuple(Tuple t1, Tuple t2, vector<string> fields1, vector<string> fields2, vector<string> op)
{
	if(op.size() == 0)
		return true;
	else for(int i=0; i<op.size(); i++)
		{
		//cout<<"Operator: "<<op[i]<<" "<<fields2[i]<<endl;
		if(op[i] == "=")
		{
			if(t1.getSchema().getFieldType(fields1[i]) == INT && (t1.getField(fields1[i]).integer == t2.getField(fields2[i]).integer))
				continue;
			else if(t1.getSchema().getFieldType(fields1[i]) == STR20 && (*(t1.getField(fields1[i]).str) == *(t2.getField(fields2[i]).str)))
					continue;
			else return false;		
		} 
		else if(op[i] == ">")
			{
				if(t1.getSchema().getFieldType(fields1[i]) == INT && (t1.getField(fields1[i]).integer > t2.getField(fields2[i]).integer))
					continue;
				else return false;
			}
			else if(op[i] ==  "<")
			{
				if(t1.getSchema().getFieldType(fields1[i]) == INT && (t1.getField(fields1[i]).integer < t2.getField(fields2[0]).integer))
					continue;
				else return false;
			}
			else return false;
		}
	return true;	
}
/*
void addTupleToBlock(Tuple tuple, MainMemory &mem) {
  //===================Block=============================
  cout << "===================Block=============================" << endl;
   
  // Set up a block in the memory
//  cout << "Clear the memory block 0" << endl;
//  Block* block_ptr=mem.getBlock(0); //access to memory block 0
//  block_ptr->clear(); //clear the block
	

  
  // A block stores at most 2 tuples in this case
  // -----------first tuple-----------
  cout << "Set the tuple at offset 0 of the memory block 0" << endl;
  block_ptr->setTuple(0,tuple); // You can also use appendTuple()
  cout << "Now the memory block 0 contains:" << endl;
  cout << *block_ptr << endl;

  cout << "The block is full? " << (block_ptr->isFull()==1?"true":"false") << endl;
  cout << "The block currently has " << block_ptr->getNumTuples() << " tuples" << endl;
  cout << "The tuple at offset 0 of the block is:" << endl;
  cout << block_ptr->getTuple(0) << endl << endl;
  
  return;
}
*/
void processInsert(string line, vector<string> cmdStr, SchemaManager schema_manager,
  MainMemory &mem) {
  
  string tableName = cmdStr[2];
  Relation* relation_ptr = schema_manager.getRelation(tableName);
  cout << "Inside the INSERT function" << endl;
  int memory_block_index=0;
  //====================Tuple=============================
  cout << "====================Tuple=============================" << endl;
  // Set up the first tuple
  Tuple tuple = relation_ptr->createTuple(); //The only way to create a tuple is to call "Relation"
  printRelation(relation_ptr);
  vector<string> insertStr = splitString(line, "\()");
  vector<string> attr = splitString(insertStr[1], ", ");
  vector<string> val = splitString(insertStr[3], ", ");
/* TODO commented unordered insert giving errors
  for (int i = 0; i < attr.size(); i++)
  {
	if (tuple.getSchema().getFieldType(i)==INT){
	  cout << "Errored?? " << endl;
	  tuple.setField(attr[i], atoi(val[i].c_str()));
	}
	else{
	  tuple.setField(attr[i], val[i]);
	}
  }
*/
  for (int i = 0; i < attr.size(); i++)
  {
    //cout << "HAHAHHAHHA " << tuple.getField(attr[i])[0] << endl << endl;
    if (tuple.getSchema().getFieldType(attr[i])==INT){
	//if (tuple.getField(attr[i])==INT){
	  cout << "Errored?? " << endl;
	  tuple.setField(attr[i], atoi(val[i].c_str()));
	}
	else{
	  tuple.setField(attr[i], val[i]);
	}
  }
  // TODO to send file
  //see that tuple was properly filled
  printTuple(tuple);
  cout << "My test function on blocks " << endl;
  memory_block_index = findBlockForTuple(mem);
  appendTupleToRelation(relation_ptr, mem, memory_block_index, tuple);
  //addTupleToBlock(tuple, mem);
  cout << "After insertion of tuble now the reation stuff is " << endl;
  printRelation(relation_ptr);
  
  // Now write the tuple in a Disk Block.
  
/*
  vector<string>::iterator it;
  cout << "Printing new things" << endl;
  for(it=str.begin(); it!=str.end(); ++it) {
    cout << *it << endl;
  }
*/
  return;
}
Exemple #5
0
bool Block::setTuple(int tuple_offset, const Tuple& tuple) { // sets new tuple value at tuple_index; returns false if tuple_index out of bound
  Schema s = tuple.getSchema();
  if (!tuples.empty()) {
    if (tuple_offset>=tuples.front().getTuplesPerBlock()) {
      cerr << "setTuple ERROR: tuple offet " << tuple_offset << " out of bound of the block" << endl;
      return false;
    }
    for (int i=0;i<tuples.size();i++) {
      if (s!=tuples[i].getSchema()) {
        cerr << "setTuple ERROR: tuples' schemas do not match" << endl;
        return false;
      }
    }
  }
  if (tuple_offset<0 || tuple_offset>=s.getTuplesPerBlock()) {
    cerr << "setTuple ERROR: tuple offet " << tuple_offset << " out of bound" << endl;
    return false;
  }
  if (tuple_offset >= tuples.size()) {
    //If there is a gap before the offset, filled it with invalid tuples
    Tuple t(tuple.schema_manager,tuple.schema_index);
    t.null();
    for (int i=tuples.size();i<tuple_offset;i++) {
      tuples.push_back(t);      
    }
    tuples.push_back(tuple);
  } else
    tuples[tuple_offset]=tuple;
  return true;
}
Exemple #6
0
bool CompareTuple::operator()(Tuple& first, Tuple& second)
{
	if(first.isNull() && second.isNull())
		return false;
	if((!first.isNull()) && second.isNull())
		return true;
	if(first.isNull() && (!second.isNull()))
		return false;

	vector<string>::iterator beg = fieldNames.begin();
	vector<string>::iterator end = fieldNames.end();
	vector<string>::iterator i;
	Schema tupleSchemaOne = first.getSchema();
	Schema tupleSchemaTwo = second.getSchema();

//	cout<< "comparing "<<first<<"  "<<second<<endl;
	if(tupleSchemaOne != tupleSchemaTwo)
		throw string("Tuple Schema Comparision Error!!!! - In PUtility::ComapreTuple::Opeartor()");
		
	for(i = beg; i!=end; i++)
	{
		string colName = *i;
		FIELD_TYPE ftype = tupleSchemaOne.getFieldType(colName);
		if(ftype == INT)
		{
			int firstVal, secVal;
			firstVal = first.getField(colName).integer;
			secVal = second.getField(colName).integer;
			if(firstVal != secVal)
				return firstVal<secVal;
		}
		else //FIELD_TYPE == STR20
		{
			string firstVal, secVal;
			firstVal = *(first.getField(colName).str); 
			secVal =  *(second.getField(colName).str);
			if(firstVal.compare(secVal) < 0) return true;
			else if(firstVal.compare(secVal) > 0) return false;
			//else == 0, continue comparing next tuple
		}
	}
	return false;
}
bool Tuple_Comparison::operator()(Tuple& tuple1, Tuple& tuple2)
{
	if(tuple1.isNull() && tuple2.isNull())
		return false;
	if((!tuple1.isNull()) && tuple2.isNull())
		return true;
	if(tuple1.isNull() && (!tuple2.isNull()))
		return false;

	vector<string>::iterator start = field_names.begin();
	vector<string>::iterator stop = field_names.end();
	vector<string>::iterator index;
	Schema schema_tuple1 = tuple1.getSchema();
	Schema schema_tuple2 = tuple2.getSchema();

//	cout<< "comparing "<<tuple1<<"  "<<tuple2<<endl;
	if(schema_tuple1 != schema_tuple2)
		throw string("Error!! Tuple comparison failed - Tuple_Comparison::operator()");

	for(index = start; index!=stop; index++)
	{
		string column_name = *index;
		FIELD_TYPE field_type = schema_tuple1.getFieldType(column_name);
		if(field_type == INT)
		{
			int value1, value2;
			value1 = tuple1.getField(column_name).integer;
			value2 = tuple2.getField(column_name).integer;
			if(value1 != value2)
				return value1<value2;
		}
		else //FIELD_TYPE == STR20
		{
			string value1, value2;
			value1 = *(tuple1.getField(column_name).str);
			value2 =  *(tuple2.getField(column_name).str);
			if(value1.compare(value2) < 0) return true;
			else if(value1.compare(value2) > 0) return false;

		}
	}
	return false;
}
Exemple #8
0
void join(Tuple tuple1, Tuple tuple2, string tableName1, string tableName2, string whereCondition, bool multi, vector<string> attributes) {
	Relation *relation = schemaManager.getRelation(tableName2+"_join");
	Tuple tuple =relation->createTuple();
	if(!multi) {
		for(int i=0;i<tuple1.getNumOfFields();i++) {
			if(tuple1.getSchema().getFieldType(i) == INT)
			tuple.setField(tableName1+"."+tuple1.getSchema().getFieldName(i), tuple1.getField(i).integer);
			else
			tuple.setField(tableName1+"."+tuple1.getSchema().getFieldName(i), *(tuple1.getField(i).str) );
		}
	}
	else {
		 for(int i=0;i<tuple1.getNumOfFields();i++) {
                        if(tuple1.getSchema().getFieldType(i) == INT)
                        tuple.setField(tuple1.getSchema().getFieldName(i), tuple1.getField(i).integer);
                        else
                        tuple.setField(tuple1.getSchema().getFieldName(i), *(tuple1.getField(i).str) );
                }
	}
	for(int i=0;i<tuple2.getNumOfFields();i++) {
	        if(tuple2.getSchema().getFieldType(i) == INT)
                tuple.setField(tableName2+"."+tuple2.getSchema().getFieldName(i), tuple2.getField(i).integer);
                else                
		tuple.setField(tableName2+"."+tuple2.getSchema().getFieldName(i), *(tuple2.getField(i).str) );
        }
	if((attributes.size()==1 && attributes[0]=="*") || multi) {
		if(whereConditionEvaluator(whereCondition, tuple)) 
		insertTuple(tableName2+"_join", tuple);
	}
	else {
		Relation *relation1 = schemaManager.getRelation(tableName2+"_joinp");
		Tuple tuplep = relation1->createTuple();
		for(int i=0;i<attributes.size();i++) {
			if(tuplep.getSchema().getFieldType(attributes[i]) == INT)
			tuplep.setField(attributes[i], tuple.getField(attributes[i]).integer);
			else
			tuplep.setField(attributes[i], *(tuple.getField(attributes[i]).str));
		}	
		if(whereConditionEvaluator(whereCondition, tuple))
		insertTuple(tableName2+"_joinp", tuplep);
	}
}
Exemple #9
0
bool compare(Tuple tuple1, Tuple tuple2) {

	Schema tupleSchema = tuple1.getSchema();
	for(int i=0;i<tuple1.getNumOfFields();i++) {
		if(tupleSchema.getFieldType(i) == INT) {
			if(tuple1.getField(i).integer != tuple2.getField(i).integer)
			return false;
		}
		else {
			if(*(tuple1.getField(i).str) != *(tuple2.getField(i).str)) 
			return false;
		}
	}
	return true;
}
Exemple #10
0
void MapTupleValues(Tuple t, string tableName)
{
	Schema tupleSchema = t.getSchema();
	vector<string> columnNames = tupleSchema.getFieldNames();
	vector<string>::iterator iter;
	for(iter = columnNames.begin(); iter!=columnNames.end(); iter++)
	{
		FIELD_TYPE ft = tupleSchema.getFieldType(*iter);
		Field value = t.getField(*iter);
		TableColumnPair tcpair = TableColumnPair(tableName, *iter);
		TableColumnPair tcpair2 = TableColumnPair(NO_TABLE, *iter);
		Value val = Value(ft, value);

		ColumnValueMap[tcpair] = val;
		ColumnValueMap[tcpair2] = val;
	}
}
void Mapping_Tuple(Tuple map_tuple, string table_name)
{
	Schema schema_tuple = map_tuple.getSchema();
	vector<string> map_column_names = schema_tuple.getFieldNames();
	vector<string>::iterator myiterator;
	for(myiterator = map_column_names.begin(); myiterator!=map_column_names.end(); myiterator++)
	{
		FIELD_TYPE field_typ = schema_tuple.getFieldType(*myiterator);
		Field value = map_tuple.getField(*myiterator);
		TColPair tcolpair1 = TColPair(table_name, *myiterator);
		TColPair tcolpair2 = TColPair(NOT_A_TABLE, *myiterator);
		FValue values = FValue(field_typ, value);

		Column_Value_Mapping[tcolpair1] = values;
		Column_Value_Mapping[tcolpair2] = values;
	}
}
void printTuple(Tuple tuple){
  // Print the information about the tuple
  cout << "Created a tuple " << tuple << " through the relation" << endl;
  cout << "The tuple is invalid? " << (tuple.isNull()?"TRUE":"FALSE") << endl;
  Schema tuple_schema = tuple.getSchema();
  cout << "The tuple has schema" << endl;
  cout << tuple_schema << endl;
  cout << "A block can allow at most " << tuple.getTuplesPerBlock() << " such tuples" << endl;
  
  cout << "The tuple has fields: " << endl;
  for (int i=0; i<tuple.getNumOfFields(); i++) {
    if (tuple_schema.getFieldType(i)==INT)
      cout << tuple.getField(i).integer << "\t";
    else
      cout << *(tuple.getField(i).str) << "\t";
  }
  cout << endl << endl;
}
void Mapping_Tuple(Tuple map_tuple)
{
	Schema schema_tuple = map_tuple.getSchema();
	vector<string> myColmNames = schema_tuple.getFieldNames();
	vector<string>::iterator myiterator;
	for(myiterator = myColmNames.begin(); myiterator!=myColmNames.end(); myiterator++)
	{
		int period_position = (*myiterator).find_first_of('.');
		int len = (*myiterator).length();
		if(period_position == string::npos) throw string("Error in column Mapping");
		string tbl_name = (*myiterator).substr(0, period_position);
		string col_name = (*myiterator).substr(period_position+1, len - period_position - 1);
		FIELD_TYPE fieldtype = schema_tuple.getFieldType(*myiterator);
		Field myvalue = map_tuple.getField(*myiterator);
		TColPair tcolpair = TColPair(tbl_name, col_name);
		FValue value = FValue(fieldtype, myvalue);
		Column_Value_Mapping[tcolpair] = value;
	}
}
Exemple #14
0
void MapTupleValues(Tuple t)
{
	Schema tupleSchema = t.getSchema();
	vector<string> columnNames = tupleSchema.getFieldNames();
	vector<string>::iterator iter;
	for(iter = columnNames.begin(); iter!=columnNames.end(); iter++)
	{
		int dotPos = (*iter).find_first_of('.');
		int len = (*iter).length();
		if(dotPos == string::npos) throw string("Error in column Mapping");
		string tableName = (*iter).substr(0, dotPos);
		string colName = (*iter).substr(dotPos+1, len - dotPos - 1);
		FIELD_TYPE ft = tupleSchema.getFieldType(*iter);
		Field value = t.getField(*iter);
		TableColumnPair tcpair = TableColumnPair(tableName, colName);
		Value val = Value(ft, value);
		ColumnValueMap[tcpair] = val;
	}
}
void processInsert(string line, vector<string> cmdStr, SchemaManager schema_manager,
  MainMemory &mem) {
  
  string tableName = cmdStr[2];
  Relation* relation_ptr = schema_manager.getRelation(tableName);
  cout << "Inside the INSERT function" << endl;
  
  //====================Tuple=============================
  cout << "====================Tuple=============================" << endl;
  // Set up the first tuple
  Tuple tuple = relation_ptr->createTuple(); //The only way to create a tuple is to call "Relation"
  //printRelation(relation_ptr);
  vector<string> insertStr = splitString(line, "\()");
  vector<string> attr = splitString(insertStr[1], ", ");
  vector<string> val = splitString(insertStr[3], ", ");

  for (int i = 0; i < attr.size(); i++)
  {
	if (tuple.getSchema().getFieldType(i)==INT){
	  tuple.setField(attr[i], atoi(val[i].c_str()));
	}
	else{
	  tuple.setField(attr[i], val[i]);
	}
  }
  //see that tuple was properly filled
  printTuple(tuple);
  
  // Now write the tuple in a Disk Block.
  
/*
  vector<string>::iterator it;
  cout << "Printing new things" << endl;
  for(it=str.begin(); it!=str.end(); ++it) {
    cout << *it << endl;
  }
*/
  return;
}
Relation* Insert(vector<string> &words, string &line, SchemaManager &schema_manager, MainMemory &mem){
	Relation* relation_ptr = schema_manager.getRelation(words[2]);

	vector<string>::iterator it = find(words.begin(), words.end(), "SELECT");
	// no select
	if (it == words.end()){
		// get insert vals
		vector<string> content = splitBy(line, "()");
		vector<string> fields = splitBy(content[1], ", ");
		vector<string> vals = splitBy(content[3], ",");
		//preProcess(vector<string>(1, words[2]), fields, schema_manager);
		preProcess(vector<string>(1, words[2]), vals, schema_manager);

		assert(fields.size() == vals.size());

		Tuple tuple = relation_ptr->createTuple();

		// standard insert doesn't have table names
		vector<string> col_names = nakedFieldNames(relation_ptr);

		// comparing 
		for (int i = 0; i < fields.size(); i++){
			for (int j = 0; j < col_names.size(); j++){
				// this is a match
				if (fields[i] == col_names[j]){
					if (tuple.getSchema().getFieldType(j) == INT){
						tuple.setField(j, atoi(vals[i].c_str()));
					}
					else{
						tuple.setField(j, vals[i]);
					}
					break;
				}
			}
		}
		appendTupleToRelation(relation_ptr, mem, tuple);
	}
	// with SELECT
	else{
		vector<string> SFW(it, words.end());	
		Relation* new_relation = Select(SFW, schema_manager, mem);
		assert(new_relation);

		vector<string> new_field_names = nakedFieldNames(new_relation);
		vector<string> field_names = nakedFieldNames(relation_ptr);

		// mapping: index of new_field_names to field_names 
		vector<int> mapping(new_field_names.size(), -1);
		for (int i = 0; i < new_field_names.size(); i++){
			for (int j = 0; j < field_names.size(); j++){
				if (new_field_names[i] == field_names[j]){
					mapping[i] = j;
					break;
				}
			}
		}

		int new_field_size = new_relation->getSchema().getNumOfFields();

		// warning: new_relation and relation_ptr might be the same!
		// get all tuples from the new_relation in one run
		vector<Tuple> new_tuples;
		for (int i = 0; i < new_relation->getNumOfBlocks(); i++){

			assert(!free_blocks.empty());
			int memory_block_index = free_blocks.front();
			free_blocks.pop();

			// read the relation block by block
			new_relation->getBlock(i, memory_block_index);
			Block* block_ptr = mem.getBlock(memory_block_index);
			assert(block_ptr);
			vector<Tuple> block_tuples = block_ptr->getTuples();
			new_tuples.insert(new_tuples.end(), block_tuples.begin(), block_tuples.end());
			if(new_tuples.empty()){
				cerr<<"Warning: Insert from SFW, No tuples in the current mem block!"<<endl;
			}
			free_blocks.push(memory_block_index);
		}

		for (int j = 0; j < new_tuples.size(); j++){
			Tuple tuple = relation_ptr->createTuple();
			for (int k = 0; k < new_field_size; k++){
				if (mapping[k] != -1){
					int idx = mapping[k];
					assert(idx < relation_ptr->getSchema().getNumOfFields() && idx >= 0);
					if (tuple.getSchema().getFieldType(idx) == INT){
						int val = new_tuples[j].getField(k).integer;
						tuple.setField(field_names[idx], val);
					}
					else{
						string *str = new_tuples[j].getField(k).str;
						tuple.setField(field_names[idx], *str);
					}
				}
			}
			appendTupleToRelation(relation_ptr, mem, tuple);
		}
		cout<<*relation_ptr<<endl;
	}
	return relation_ptr;
}
Exemple #17
0
int conditionMatches(Tuple tuple, vector<string> tokens, int op) {
	Schema schema = tuple.getSchema();
	bool flag1=false, flag2=false;
	if(ifExists(tokens[1], "\\+|\\/|\\-|\\/|\\(|\\)|\\*") || ifExists(tokens[0], "\\+|\\/|\\-|\\/|\\(|\\)|\\*")) {
		return eval(tuple, tokens, op);
	}
	for(int i=0;i<schema.getNumOfFields();i++) {
		if(schema.getFieldName(i) == tokens[0])
		flag1=true;
		if(schema.getFieldName(i) == tokens[1])
		flag2=true; 
	}
	if(flag1 && flag2) {
		if(tuple.getSchema().getFieldType(tokens[0]) == INT) {
			switch(op) {
			case 0:
				if(tuple.getField(tokens[0]).integer == tuple.getField(tokens[1]).integer)	
				return 0;
				else return 1;
			case 1:
				if(tuple.getField(tokens[0]).integer > tuple.getField(tokens[1]).integer)      
                                return 0;
                                else return 1;
			case 2:
				if(tuple.getField(tokens[0]).integer < tuple.getField(tokens[1]).integer)      
                                return 0;
                                else return 1;
			}
		}
		else {
			if(*(tuple.getField(tokens[1]).str) == *(tuple.getField(tokens[1]).str))	return 0;
			else return 1;
		}
	}
	if(flag1)
	{
		if(tuple.getSchema().getFieldType(tokens[0]) == INT) {
			int fieldValue = tuple.getField(tokens[0]).integer;
			if(isNumber(tokens[1])){
				switch (op) {
				case 0:
					if(fieldValue == stoi(tokens[1]))
					return 0; 
					else 
					return 1;
				case 1:
					if(fieldValue > stoi(tokens[1]))
					return 0;
					else
					return 1;
				case 2:
					if(fieldValue < stoi(tokens[1]))
					return 0;
					else
					return 1;
				}
			}	
		}
		else {
			regex exp("\\ *\"(.*)\"");
			cmatch match;
			if(regex_match(tokens[1].c_str(),match,exp))
			{
				string* fieldValue = tuple.getField(tokens[0]).str;
				if(*fieldValue == match[1])
				return 0;
				else 
				return 1;
			}
		}
	}
	return 0;	
}