Exemplo n.º 1
0
bool Platform::addClient()
{

	string logId;
	while (true)
	{	
		char tmpBuf[BUF_LEN];
		cout << "input the logId you want:";
		cin >> tmpBuf;
		logId = tmpBuf;
		if (logId.length() > 0 && this->judgeExistClientId(logId) == false)
			break;
	}


	//TODO:输入两次密码的验证
	string password;
	char tmpBuf[BUF_LEN];
	cout << "password:";
	cin >> tmpBuf;
	password = tmpBuf;

	if (createRecord(logId, password))
		return true;
	else
		return false;

}
Exemplo n.º 2
0
/**
* 随机构造总大小为dataSize的记录插入到table中,
* 记录ID从在[minidx, minid]之间随机生成
* @param table 数据表
* @param dataSize 记录总大小
* @param maxid 最大id 
* @param minid 最小id
* @return 记录数
*/
uint TNTCountTable::populate(Session *session, TNTTable *table, TNTOpInfo *opInfo, u64 *dataSize, u64 maxId, u64 minId) {
	assert(session->getTrans() != NULL);
	u64 volumnCnt = *dataSize;
	uint recCnt = 0;
	uint dupIdx;
	int startId = 0;
	Record *rec;
	RowId rid;
	while (true) {
		// 创建记录
		u64 id = (u64)RandomGen::nextInt((u32)minId, (u32)maxId);
		rec = createRecord((u64)recCnt, (int)startId++);
		if (volumnCnt < getRecordSize()) {
			freeRecord(rec);
			break;
		}
		// 插入记录
		rid = table->insert(session, rec->m_data, &dupIdx, opInfo);
		if (rid != INVALID_ROW_ID) {
			recCnt++;
			volumnCnt -= getRecordSize();
		}
		freeRecord(rec);
	}

	*dataSize -= volumnCnt;
	return recCnt;
}
/**
 * Deletes a record from table
 *
 * rel = table handle
 * id = id of the record to be deleted
 *
 */
RC deleteRecord(RM_TableData *rel, RID id) {

	//Sanity Checks
	if (rel == NULL) {
		THROW(RC_INVALID_HANDLE, "Table handle is invalid");
	}

	Record *record;
	//Read the record to be deleted
	createRecord(&record, rel->schema);
	RC rc = readRecord(rel, id, &record);
	if (rc != RC_OK) {
		THROW(RC_REC_MGR_DELETE_REC_FAILED, "Delete record failed");
	}

	//Set tomstone bit
	record->nullMap |= 1 << 15;

	//Write updated record
	rc = writeRecord(rel, record);
	freeRecord(record);

	if (rc == RC_OK)
		((RM_TableMgmtData *) rel->mgmtData)->tupleCount--;
	else {
		THROW(RC_REC_MGR_DELETE_REC_FAILED, "Delete record failed");
	}

	return rc;
}
Exemplo n.º 4
0
XlRecord* XlChartRecordFactory::createRecord(ChSINT2 in_nId)
{
	XlHeader header(in_nId, 0, XlRecord::BIFF_97UP);
	XlRecord* pRecord = createRecord( header );
	pRecord->setLength( pRecord->getPersistLength() );
	return pRecord;
}
Exemplo n.º 5
0
dimeRecord *
dimeRecord::createRecord(const int group_code,
			const dimeParam &param,
			dimeMemHandler * const memhandler)
{
  dimeRecord *record = createRecord(group_code, memhandler);
  if (record) record->setValue(param, memhandler);
  return record;
}
Exemplo n.º 6
0
bucket_id TNF_insert(TNF_Index* index, bucket_id id, char* data) {
	// 1. write Record, get Record addr
	size_t addr = Record_write(index->record, data, id);
	// 2. create RecordMap
	TNF_RecordAddrMap* map = createRecord(id, addr);
	// 3. insert BinTree
	Tree_add(index->tree, id, (void*)map);
	return id + 1;
}
Exemplo n.º 7
0
void LogDialog::addRecord(const Record &record)
{
    auto scrollBar = ui->listLog->verticalScrollBar();
    bool atBottom = scrollBar->value() == scrollBar->maximum();

    auto item = createRecord(record);

    if ( isFilteredOut(item, ui->lineEditSearch->text()) )
        item->setHidden(true);
    else if (atBottom && scrollBar->value() != 0)
        ui->listLog->scrollToItem(item);
}
Exemplo n.º 8
0
// setters
// change a given item by case insensitive name in the config, save the changes immediately
void ConfigManagerUnix::setConfigString(const char* configItemName, std::string outString)
{
	if(NULL == configItemName)
		return;
	if(recordExists(configItemName))
	{
		std::string str = configItemName;
		setValue(str,outString);
		return;
	}
	createRecord(configItemName,outString.c_str());
}
Exemplo n.º 9
0
void ConfigManagerUnix::setConfigLong(const char* configItemName, long outLongValue)
{
	if(NULL == configItemName)
		return;
	char buffer[40];
	std::sprintf(buffer,"%ld\n",outLongValue);
	if(recordExists(configItemName))
	{
		std::string str = configItemName;
		std::string value = buffer;
		setValue(str,value);
		return;
	}
	createRecord(configItemName,buffer);
}
Exemplo n.º 10
0
void ConfigManagerUnix::setConfigFloat(const char* configItemName, float outLongValue)
{
	if(NULL == configItemName)
		return;
	char buffer[40];
	sprintf(buffer,"%f\n",outLongValue);//long d = std::_ftoa(outLongValue,buffer,10);
	if(recordExists(configItemName))
	{
		std::string str = configItemName;
		std::string value = buffer;
		setValue(str,value);
		return;
	}
	createRecord(configItemName,buffer);
}
Exemplo n.º 11
0
void displayMenu()
{
    int mode;

    puts("Выберите команду:");
    puts("1 - Создать файл");
    puts("2 - Показать содержимое файла");
    puts("3 - Добавить запись в файл");
    puts("4 - Удалить запись из файла");
    puts("5 - Изменить запись из файла");
    puts("6 - Отсортировать по фамилии и отобразить");
    puts("7 - Показать количество телефонов с определенного года");
    scanf("%d", &mode);

    switch (mode)
    {
        case 1:
            createFile();
            displayMenu();
            break;
        case 2:
            displayFileContent();
            displayMenu();
            break;
        case 3:
            createRecord();
            displayMenu();
            break;
        case 4:
            deleteRecord();
            displayMenu();
            break;
        case 5:
            updateRecord();
            displayMenu();
            break;
        case 6:
            displayBySurname();
            displayMenu();
            break;
        case 7:
            displayCountSinceYear();
            displayMenu();
            break;
        default:
            puts("Выходим...");
    }
}
Exemplo n.º 12
0
LogDialog::LogDialog(const QList<Record> &records, const QString &format,
                     const QString &timeFormat, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LogDialog)
    , timeFormat_(timeFormat)
    , format_(format)
{
    ui->setupUi(this);
    ui->listLog->setUniformItemSizes(true);

    for (auto &record : records) {
        createRecord(record);
    }

    ui->listLog->setCurrentRow(0);
}
Exemplo n.º 13
0
void ConfigManagerUnix::setConfigBool(const char* configItemName, bool outBooleanValue)
{
	if(NULL == configItemName)
		return;
	std::string value;
	if(outBooleanValue)
		value = '1';
	else
		value = '0';
	if(recordExists(configItemName))
	{
		std::string str = configItemName;
		setValue(str,value);
		return;
	}
	createRecord(configItemName,value.c_str());
}
Exemplo n.º 14
0
int FrmCatch::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = PreviewTab::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: createRecord(); break;
        case 1: previewRow((*reinterpret_cast< QModelIndex(*)>(_a[1]))); break;
        case 2: { bool _r = onButtonClick((*reinterpret_cast< QAbstractButton*(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 3: onItemSelection(); break;
        default: ;
        }
        _id -= 4;
    }
    return _id;
}
Exemplo n.º 15
0
int FrmCatch::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = PreviewTab::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: createRecord(); break;
        case 1: previewRow((*reinterpret_cast< QModelIndex(*)>(_a[1]))); break;
        case 2: onItemSelection(); break;
        case 3: onEditLeave((*reinterpret_cast< const bool(*)>(_a[1])),(*reinterpret_cast< const bool(*)>(_a[2]))); break;
        case 4: editFinished(); break;
        default: ;
        }
        _id -= 5;
    }
    return _id;
}
Exemplo n.º 16
0
IHqlExpression * buildDiskFileViewerEcl(const char * logicalName, IHqlExpression * record)
{
    //Add filepos to the incomming record structure...
    IHqlExpression * filePosAttr = createAttribute(virtualAtom, createAttribute(filepositionAtom));
    OwnedHqlExpr filepos = createField(fileposName, makeIntType(8, false), NULL, filePosAttr);
    IHqlExpression * sizeofAttr = createAttribute(virtualAtom, createAttribute(sizeofAtom));
    OwnedHqlExpr reclen = createField(recordlenName, makeIntType(2, false), NULL, sizeofAttr);
    HqlExprArray fields;
    unwindChildren(fields, record);
    fields.append(*filepos.getLink());
    fields.append(*reclen.getLink());

    OwnedHqlExpr newRecord = createRecord(fields);
    newRecord.setown(createSymbol(createIdentifierAtom("_SourceRecord_"), newRecord.getLink(), ob_private));

    OwnedHqlExpr dataset = createNewDataset(createConstant(logicalName), newRecord.getLink(), createValue(no_thor), NULL, NULL, NULL);
    OwnedHqlExpr filtered = addFilter(dataset, filepos);
    OwnedHqlExpr projected = addSimplifyProject(filtered);
    OwnedHqlExpr output = addOutput(projected);
    return output.getClear();
}
Exemplo n.º 17
0
Record *
testRecord(Schema *schema, int a, char *b, int c)
{
	Record *result;
	Value *value;

	TEST_CHECK(createRecord(&result, schema));

	MAKE_VALUE(value, DT_INT, a);
	TEST_CHECK(setAttr(result, schema, 0, value));
	freeVal(value);

	MAKE_STRING_VALUE(value, b);
	TEST_CHECK(setAttr(result, schema, 1, value));
	freeVal(value);

	MAKE_VALUE(value, DT_INT, c);
	TEST_CHECK(setAttr(result, schema, 2, value));
	freeVal(value);

	return result;
}
Exemplo n.º 18
0
Record *
testRecord(Schema *schema, int a, char *b, int c)
{
	//printf("\n in here test");
  Record *result;
  Value *value;

  TEST_CHECK(createRecord(&result, schema));
	printf("\n created record");
  MAKE_VALUE(value, DT_INT, a);
  TEST_CHECK(setAttr(result, schema, 0, value));
  freeVal(value);

  MAKE_STRING_VALUE(value, b);
  TEST_CHECK(setAttr(result, schema, 1, value));
  freeVal(value);

  MAKE_VALUE(value, DT_INT, c);
  TEST_CHECK(setAttr(result, schema, 2, value));
 // printf("\n outta here %s",result->data);
  freeVal(value);

  return result;
}
void menu(){
    char selection[1];
    printf("\n1) Create a new record \n2) Display All Records \n3) Update a Record \n4) Exit Program \nPlease enter a valid number to make your choice:\n");
    lineFlush();
    scanf("%d",selection);
    lineFlush();
	switch(selection[0]){
		case 1:
			createRecord();
			break;
		case 2:
			displayRecords();
			break;
		case 3:
			updateRecord();
			break;
		case 4:
			exit(0);
			break;
		default:
			printf("\nIncorrect option.\n");
			break;
	}
}
Exemplo n.º 20
0
IHqlExpression * PositionTransformer::createTransformed(IHqlExpression * _expr)
{
    OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(_expr);

    switch (transformed->getOperator())
    {
    case no_table:
        {
            IHqlExpression * mode = transformed->queryChild(2);
            HqlExprArray fields;
            HqlExprArray args;

            if (mode->getOperator() == no_thor)
            {
                unwindChildren(fields, transformed->queryChild(1));
                IHqlExpression * filePosAttr = createComma(createAttribute(virtualAtom, createAttribute(filepositionAtom)), insertedAttr.getLink());
                IHqlExpression * sizeofAttr = createComma(createAttribute(virtualAtom, createAttribute(sizeofAtom)), insertedAttr.getLink());
                fields.append(*createField(fileposName, makeIntType(8, false), NULL, filePosAttr));
                fields.append(*createField(recordlenName, makeIntType(2, false), NULL, sizeofAttr));

                unwindChildren(args, transformed);
                args.replace(*createRecord(fields), 1);
                return transformed->clone(args);
            }
        }
        break;
    case no_iterate:
    case no_hqlproject:
        {
            HqlExprArray args;
            HqlExprArray assigns;
            IHqlExpression * transform = transformed->queryChild(1);
            unwindChildren(args, transformed);
            unwindChildren(assigns, transform);
            IHqlExpression * inRecord = transformed->queryChild(0)->queryRecord();
            IHqlExpression * outRecord = transform->queryRecord();

            HqlExprArray fields;
            unwindChildren(fields, outRecord);
            ForEachChild(idx, inRecord)
            {
                IHqlExpression * child = inRecord->queryChild(idx);
                if (child->hasProperty(insertedAtom))
                {
                    IHqlExpression * newTarget = createField(child->queryName(), child->getType(), LINK(child), insertedAttr.getLink());
                    fields.append(*newTarget);
                    assigns.append(*createValue(no_assign, makeVoidType(), newTarget, createSelectExpr(createValue(no_left), LINK(newTarget))));
                }
            }
            IHqlExpression * newRecord = createRecord(fields);
            args.replace(*createValue(no_transform, newRecord->getType(), assigns), 1);
            return transformed->clone(args);
        }
        break;
    case no_join:
        //only ok if join first
    case no_rollup:
    case no_newaggregate:
    case no_aggregate:
        fail();
        break;
    case no_usertable:
    case no_selectfields:
        {
            IHqlExpression * grouping = transformed->queryChild(2);
            if (grouping && (grouping->getOperator() != no_attr))
                fail();
            IHqlExpression * record = transformed->queryRecord();
            HqlExprArray fields;
            unwindChildren(fields, transformed->queryChild(1));
            ForEachChild(idx, record)
            {
                IHqlExpression * child = record->queryChild(idx);
                if (child->hasProperty(insertedAtom))
                    fields.append(*createField(child->queryName(), child->getType(), LINK(child), insertedAttr.getLink()));
            }

            HqlExprArray args;
            unwindChildren(args, transformed);
            args.replace(*createRecord(fields), 1);
            return transformed->clone(args);
        }
Exemplo n.º 21
0
XlRecord* XlParser::nextRecord()
{
    // sanity check
    if (!hasMoreElements())
    {
        ChTHROW(OC_READ_FAILED);
    }

    XlHeader  header;
    bool      isContinue  = true;

    // Main loop
    while(isContinue && m_pStream->getBytesAvailableToRead() >= XlRecord::HDR_SIZE)
    {
        //----------------------------------
        // process BIFF header
        //----------------------------------

        // synchronize location.
        m_pStream->seek(m_ulCurrentOffset, SsrwOO_START);

        // fetch next header
        m_pParserVisitor->peekAhead(header, m_bFileVersion);

        // Check ending condition
        if (header.getId() == 0 || header.getLength() > m_pStream->getBytesAvailableToRead())
        {
            m_isEndOfRecs = true;
            return NULL;
        }
        
        //-------------------------------------
        // Optimization: Seek and filter modes
        //-------------------------------------

        // 'seek' mode:
        // If the upper module requested advancement till specific
        // record (by calling advanceToElement(recType)) we skip all the
        // recs till we find requested one.
        if (m_nSeekRecord != -1 && header.getId() != m_nSeekRecord)
        {
            // shortcut - skip this record
			if ( !m_pParserVisitor->isEncapsRecord() )
			{
				m_ulCurrentOffset += header.getLength() + XlRecord::HDR_SIZE;
			}
			else
			{
				m_pParserVisitor->seekNextRecord();
				m_ulCurrentOffset = m_pStream->getPos();
			}
            continue;
        }
        // 'filter' mode:
        else if (m_bFilter == SKIP_CONTINUES && header.getId() == XlContinue::ID)
        {
            // shortcut - skip this record
			if ( !m_pParserVisitor->isEncapsRecord() )
			{
				m_ulCurrentOffset += header.getLength() + XlRecord::HDR_SIZE;
			}
			else
			{
				m_pParserVisitor->seekNextRecord();
				m_ulCurrentOffset = m_pStream->getPos();
			}
            continue;
        }

        //------------------------------------
        // process rest of the next BIFF record
        //------------------------------------

        // move past the header
		if ( m_pParserVisitor->isEncapsRecord() )
		{
			m_pParserVisitor->skipHeader();
		}
		else
		{
			m_pStream->seek(XlRecord::HDR_SIZE, SsrwOO_CUR);
		}

        // create and initialize the  record
        if (m_isUseGeneric)
        {
            ChSINT2 m_nOriginalId = header.getId();
    
            // convert this record to a generic record
            header.setId(XlGenericRecord::ID);
            m_pRecord = ChNEW XlGenericRecord(header);
            ChDOWNCAST<XlRecord, XlGenericRecord>(m_pRecord)->setOriginalId(m_nOriginalId);
        }        
        else
        {
            m_pRecord = createRecord(header, m_nStreamType);
        }

        // visit record content
        m_pRecord->accept(*m_pParserVisitor);

        // update current file offset
		if ( !m_pParserVisitor->isEncapsRecord() )
		{
			m_ulCurrentOffset += m_pRecord->getLength() + XlRecord::HDR_SIZE;
		}
		else
		{
			m_pParserVisitor->seekNextRecord();
			m_ulCurrentOffset = m_pStream->getPos();
		}

        

        // OPTIMIZATION:
        // Not relevant (to the target conversion process) records
        // will be short circuited by the record factory as GenericRecord
        // objects. There is no point of processing such a record any further.
        // Skip over it and go for the next one.
        if (m_pRecord->getId() == XlGenericRecord::ID && m_doesIgnoreGeneric)
        {
            // reset fetch engine and go after next record
            ChDELETE(m_pRecord);
            isContinue  = true;
        }
        else // done -  get out of the loop
        {
            m_nSeekRecord = -1;
            isContinue = false;
        }
    } // end of loop

	XlRecord* pReturnRecord = m_pRecord;
	m_pRecord = NULL;
    return pReturnRecord;
}
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
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.º 24
0
int main(int argc, char * argv[])
{
	FILE * file;
	char * name;
	char * group;
	char line[900][256];
	char ch;
	char type;
	char temp;
	double calories;
	double calTotal = 0;
	double vegTotal = 0, meatTotal = 0, dairyTotal = 0, grainsTotal = 0, fatTotal = 0;
	double vegTot = 0, meatTot = 0, dairyTot = 0, grainsTot = 0, fatTot = 0;
	int i;

	Food * head = (Food *)malloc(sizeof(Food));
	Food * ptr = (Food *)malloc(sizeof(Food));

	head = NULL;
	ptr = NULL;

	if (argc < 2)
	 {
		printf("No argument inputted. Exiting...\n");
		exit(0);
	}

	file = fopen(argv[1], "r");
	if (file == NULL)
	 {
		printf("Error opening file. Exiting...\n");
		exit(0);
	}
	while((ch = fgetc(file)) != EOF)
	 {
		line[i][0] = ch;
		while((ch = fgetc(file)) != '\n')
		 {
			line[i][strlen(line[i])] = ch;
			if (line[i][strlen(line[i])-1] == ',' && isdigit(line[i][strlen(line[i])-2]))
			 {
				temp = fgetc(file);
			}
		}
		name = strtok(line[i], ",");
		group = strtok(NULL, ",");
		calories = atoi(strtok(NULL, ","));
		calTotal += calories;
		type = temp;
		ptr = createRecord(name, group, calories, type);
		if (head == NULL)
		 {
			head = ptr;
		}
		else if (type == 'j')
		 {
			head = addToBack(head, ptr);
		}
		else if (type == 'h')
		 {
			head = addToFront(head, ptr);
		}

		if (strcmp(group, "vegfruit") == 0)
		 {
                vegTotal += calories;
                vegTot += 1;
		}
		else if (strcmp(group, "grains") == 0)
         {
                grainsTotal += calories;
                grainsTot += 1;
        }
		else if (strcmp(group, "dairy") == 0)
         {
                dairyTotal += calories;
                dairyTot += 1;
        }
		else if (strcmp(group, "meat") == 0)
         {
                meatTotal += calories;
                meatTot += 1;
        }
		else if (strcmp(group, "fat") == 0)
         {
                fatTotal += calories;
                fatTot += 1;
        }

		i++;
	}
	printf("%d\n", (int)calTotal);
	printf("%.0f\n", vegTotal / vegTot);
	printf("%.0f\n", meatTotal / meatTot);
	printf("%.0f\n", dairyTotal / dairyTot);
	printf("%.0f\n", grainsTotal / grainsTot);
	printf("%.0f\n", fatTotal / fatTot);
	printList(head);
	destroyList(head);

	return 0;
}
/**
 * This API allows conditional updates of the records
 *
 * rel = Table handle
 * cond = Conditional expression to be matched
 * op = Function pointer pointing to update function to be called in case a matching record is found
 */
RC updateScan(RM_TableData *rel, Expr *cond, void (*op)(Schema*, Record *)) {

	//Sanity Checks
	if (rel == NULL) {
		THROW(RC_INVALID_HANDLE, "Table handle is invalid");
	}

	// Get total number of pages this table has
	int pages = ((RM_TableMgmtData *) rel->mgmtData)->pageCount;
	RID firstFreeSlot = ((RM_TableMgmtData *) rel->mgmtData)->firstFreeSlot;
	int i, j, tuplesRead, slot;
	RID id;
	Value *result;
	Record* r;
	BM_PageHandle *pageData = (BM_PageHandle *) malloc(sizeof(BM_PageHandle));

	if (pageData == NULL) {
		THROW(RC_NOT_ENOUGH_MEMORY,
				"Not enough memory available for resource allocation");
	}

	j = 0;
	tuplesRead = 0;

	// loop through pages and get the desired records
	for (i = 1; i < pages; i++) {
		slot = 0;
		id.page = i;
		while (slot < ((RM_TableMgmtData *) rel->mgmtData)->slotCapacityPage) {
			createRecord(&r, rel->schema);
			id.slot = slot;
			RC rc = readRecord(rel, id, &r);
			if (rc != RC_OK) {
				THROW(RC_REC_MGR_DELETE_REC_FAILED, "Delete record failed");
			}

			// ignore the deleted records (tombstones) and free slots
			if ((!(r->nullMap & (1 << 15))
					|| ((firstFreeSlot.page == i)
							&& (firstFreeSlot.slot == slot)))) {
				// check if record satisfies the given condition
				evalExpr(r, rel->schema, cond, &result);
				if (result->v.boolV) {
					op(rel->schema, r);
					updateRecord(rel, r);
					j++;
					tuplesRead++;
				}
				freeVal(result);
			}

			freeRecord(r);
			slot++;
		}
	}

	free(pageData);

	//All OK
	return RC_OK;
}
Exemplo n.º 26
0
/**
* handle_client:  Main application layer thread for each client
* @author ndemarinis (Basic implementation)
*/
void *handle_client(void *data){
    struct client_handler_data *clnt = (struct client_handler_data *)data;
    
    int pipes[2]; // Make a pipe to connect to the layer stack
    uint16_t cur_seq_num = 0;
    
    pid_t clnt_pid; // PID we receive from the client before startup
    struct layer_stack *stack; // Work data for layer stack implementation

    // Grab the client's identifier
    if((recv(clnt->sock, &clnt_pid, sizeof(pid_t), 0) != sizeof(pid_t)))
      die_with_error("Error receiving PID from client!");

    stack = create_layer_stack(clnt->sock, clnt_pid, pipes); // Initialize all of our layer threads

    sleep(1); // Wait a second for the thread creation to settle


    int bytes_read;
    struct packet client_p;
    struct packet response_p;
    while(1){
        //Wait for a packet to come in
        bytes_read = read(pipe_read(pipes), &client_p, sizeof(struct packet));

	if(!bytes_read) // If we read nothing, it's time to terminate.  
	  {
	    dprintf(DID_INFO, "APP:  Read 0 bytes from layer stack.  Terminating!\n");
	    break;
	  }

        int opcode = client_p.opcode;
        //login
        if (opcode == __LOGIN_CODE){
            //payload is just the username for this opcode
            if(login(client_p.payload) == 0){
                //response code for SUCCESS
                response_p.opcode = 0x05;
                response_p.seq_num = cur_seq_num;
                cur_seq_num++;
                //no payload basic success response!
                response_p.length = 0;

                send_packet(pipes, response_p);
            } else {
                //basic response packet signaling invailed login
                response_p.opcode = __NOT_AUTHORIZED_CODE;
                response_p.seq_num = cur_seq_num;
                cur_seq_num++;
                response_p.length = 0;

                send_packet(pipes, response_p);
            }
        //create record
        } else if (opcode == __CREATE_CODE){
            //payload syntax "<firstName>,<lastName>,<location>"
            char *firstName = strtok(client_p.payload, ",");
            char *lastName = strtok(NULL, ",");
            char *location = strtok(NULL, "");

            //replace null with proper response once I determine what its for!
            char *response = malloc(10*sizeof(response));
            int resp = createRecord(firstName, lastName, location, response);
            //if a 0 was not returned an error occured
            if (resp) {
                //send an error back!
                return_error(pipes, resp, &cur_seq_num);
            } else {
                //send back the data
                return_response(pipes, response, &cur_seq_num);
            }
        //query record
        } else if (opcode == __QUERY_CODE){
            //payload syntax "NAME:<firstName>,<lastName>"
            //               "LOCATION:<location>"
            char *queryType = strtok(client_p.payload, ":");

            bodyEntry *responses;
            int resp;
            //two types of query name and location
            if (strcmp(queryType, "NAME") == 0){
                //handle queries by name
                char *firstName = strtok(NULL, ",");
                char *lastName = strtok(NULL, "");
                
		int respCount;
                //get the query response from the database
                resp = queryRecordByName(firstName, lastName, &responses, &respCount);

                //if resp is not 0 then an error occured
                if (resp){
                    //send an error back!
                    return_error(pipes, resp, &cur_seq_num);
                } else {
                    //send the information back to the client!
                    char response[respCount*(16+20+36+3)];
		    memset(response,0,sizeof(response));
                    int i, rID;
		    char recordID[10];
                    for (i = 0; i < respCount; i++){
                        rID = responses[i].id;
                        sprintf(recordID, "%09d", rID);
                        strcat(response, recordID);
                        strcat(response, ",");
                        strcat(response, responses[i].location);
                        strcat(response, ",");
                    }
                    return_response(pipes, response, &cur_seq_num);
                }
            } else if (strcmp(queryType, "LOCATION") == 0){
                //handle queries by location
                char *location = strtok(NULL, "");

		int respCount;
                //get the query response from the database
                resp = queryRecordByLocation(location, &responses, &respCount);

                //if resp is not 0 then an error occured
                if (resp){
                    //send an error back!
                    return_error(pipes, resp, &cur_seq_num);
                } else {
                    //send the information back to the client!
                    char response[respCount*(16+20+36+3)];
		    memset(response,0,sizeof(response));
                    int i, rID;
		    char recordID[10];
                    for (i = 0; i < respCount; i++){
                        rID = responses[i].id;
                        sprintf(recordID, "%09d", rID);
                        strcat(response, recordID);
                        strcat(response, ",");
                        strcat(response, responses[i].firstName);
                        strcat(response, ",");
                        strcat(response, responses[i].lastName);
                        strcat(response, ",");
                    }
                    return_response(pipes, response, &cur_seq_num);
                }
            }
        //update record
        } else if (opcode == __UPDATE_CODE){
            //payload syntax "<recordId>,<firstName>,<lastName>"
            char *recordId = strtok(client_p.payload, ",");
            char *firstName = strtok(NULL, ",");
            char *lastName = strtok(NULL, "");

            //convert recordID into an integer
            int rId = atoi(recordId);
            int resp = updateRecordName(rId, firstName, lastName);

            //if resp is not 0 then an error occured
            if (resp){
                //send an error back!
                return_error(pipes, resp, &cur_seq_num);
            } else {
                //send the information back to the client!
                //basic success packet so an empty string is given for the payload
                return_response(pipes, "", &cur_seq_num);
            }
        //add picture
        } else if (opcode == __ADD_PIC_CODE){
            /*payload syntax 1st   packet:   "<firstName>,<lastName>,<imageSize>"
                             2nd+ packets:   "<pictureData>"
                             These picture data packets will continue until the entirety of the picture has been transmitted
                             The file is complete once the server has recieved a packet ending with an EOF character
            */
            //get the name information from the first packet transmitted
            char *firstName = strtok(client_p.payload, ",");
            char *lastName = strtok(NULL, ",");
            char *imageSize = strtok(NULL, "");

            unsigned long size = atol(imageSize);

            //create an array capable of holding the entire image
            char pictureData[size];
            int i = 0;

	    // DEBUG:  Write out the file as we read it
	    FILE *out = fopen("server_output.png", "w+");

            //start recieving the picture data, continue until this entire picture has been recieved
            while(i < size - 1){
                //read in a new packet of data
                bytes_read = read(pipe_read(pipes), &client_p, sizeof(struct packet));
		dprintf(DID_APP_INFO, "APP:  Received packet of %d bytes with payload of %d bytes.\n", 
		       bytes_read, client_p.length);

                //store the picture data into the array
                memcpy(pictureData + i, client_p.payload, client_p.length);

                //increment i by the length of the payload
                i += client_p.length;
            }

	    // DEBUG:  Write out that whole array to the test file
	    printf("Received picture of %d total bytes.\n", i);
	    write(fileno(out), pictureData, i);

	    // DEBUG:  Close that file
	    fflush(out);
	    fclose(out);	    

            char add_response[10];
            int resp = addPicture(firstName, lastName, pictureData, add_response);

            if (resp){
                //send an error back!
                return_error(pipes, resp, &cur_seq_num);
            } else {
                //send the information back to the client!
                return_response(pipes, add_response, &cur_seq_num);
            }

        //connect picture
        } else if (opcode == __CONNECT_PIC_CODE){
            //payload syntax "<pictureID>,<recordID>"
            char *pictureID = strtok(client_p.payload, ",");
            char *recordID = strtok(NULL, "");

            int pID = atoi(pictureID);
            int rID = atoi(recordID);

            int resp = connectPictureToRecord(pID, rID);

            if (resp){
                //send and error back!
                return_error(pipes, resp, &cur_seq_num);
            } else {
                //send the success packet back!
                return_response(pipes, "", &cur_seq_num);
            }
        //logout!
        } else if (opcode == __LOGOUT_CODE){
            //payload syntax NONE
            //break out of the while loop containin this and allow the thread processing this client to exit
	    logout();
            break;
        //download picture
        } else if (opcode == __QUERY_PIC_CODE){
            //payload syntax "<pictureID>"
            char *pictureID = strtok(client_p.payload, "");
            int pID = atoi(pictureID);

            char pictureData[__MAX_IMAGE_SIZE];
            int resp = queryPicture(pID, pictureData);

            if (resp){
                //send an error back!
                return_error(pipes, resp, &cur_seq_num);
            } else {
                //break the image into packets and send it back to the client!
                //write the data into a tempory file handle for simple reading when breaking into packets
                //base the temporary file off of the pid to ensure uniqueness
                char filename[MAX_FILENAME_SIZE];
                int pid = getpid();
                char cpid[10];
                sprintf(cpid, "%d", pid);
                strcpy(filename, "temp_");
                strcat(filename, cpid);
                strcat(filename, ".jpg");
                //open the temp file for writing
                FILE *picture = fopen(filename, "w");
                //write the entire image to the file!
                fwrite(pictureData, 1, sizeof(pictureData), picture);

                //send a simple packet informing the client of the size of the image that it is going to recieve
                response_p.opcode = 5;
                response_p.seq_num = cur_seq_num;
                cur_seq_num++;
                sprintf(response_p.payload, "%lu", sizeof(pictureData));
                response_p.length = strlen(response_p.payload);
                send_packet(pipes, response_p);

                //read into packets and send them until the end of file is reached
                //note this uses the same packet pointer the entire time so the opcode does not need to be set again
                response_p.opcode = 5;
                while(!feof(picture)){
                    //read at most 251 bytes of the picture into the packets payload
                    int readSize = fread(response_p.payload, 1, MAX_PAYLOAD, picture);
                    //if there was no error then add the sequence number and the length to the packet then send it
                    //DO NOT SET THE SEND FLAG, this will handle it on its own since there could be multiple sends
                    if (!ferror(picture)){
                        response_p.seq_num = cur_seq_num;
                        cur_seq_num++;

                        response_p.length = (uint8_t)readSize;

                        //send this packet down to the data link layer
                        send_packet(pipes, response_p);
                    } else {
                        //an error occured return an error code so that the client can stop processing the image and drop the corrupt data
                        return_error(pipes, 1, &cur_seq_num);
                        break;
                    }
                }
                //close the picture that was being read
                fclose(picture);
                //delete the temporary file
                remove(filename);
            }
        }
    // Send it straight back
    //printf("APP:  Sending string of %d bytes:  %s\n", to_read, read_buffer);
    //write(pipe_write(pipes), read_buffer, to_read);
    }
    
    curr_clients--;
    pthread_exit(NULL);
}
Exemplo n.º 27
0
MusicRec * ParseLine(char * line)
{
    char * chunkOfLine;
    char * artist;
    char * title;
    char * size;
    char * length;
    char * lineCopy;
    int lengthInt;
    double sizeDecimal;
    int count;
    char * type;
    MusicRec * current;

    /* if its too short, exit */
    if(strlen(line) < 8)
    {
        return NULL;
    }

    /* create a copy to close */
    lineCopy = malloc(sizeof(char)*strlen(line)+1);
    strcpy(lineCopy, line);
    count = 0;

    /* split the line  by commas */
    chunkOfLine = strtok(lineCopy, ",");

    /* make sure there are 4 commas */
    while(chunkOfLine != NULL)
    {
        chunkOfLine = strtok(NULL, ",");
        count++;
    }
    free(lineCopy);
    if(count != 5)
    {

        return NULL;
    }
    
    
    /* set all the values in strings */
    artist = strtok(line, ",");
    title  = strtok(NULL, ",");
    length = strtok(NULL, ",");
    size   = strtok(NULL, ",");
    type   = strtok(NULL,",");

   
   /* if anything is not there, exit the function */ 
    if(artist  == NULL || strlen(artist) == 0 
     || title  == NULL || strlen(title)  == 0 
     || length == NULL || strlen(length) == 0 
     || size   == NULL || strlen(size)   == 0 
     || type   == NULL || strlen(type)   != 1)
    {
        return NULL;
    }

    /* convert the numbers to floats and integers */
    sizeDecimal = atof(size);
    lengthInt   = atoi(length);

    /* create the record and return it */
    current = createRecord(title, artist, sizeDecimal, lengthInt, type[0]);
    return current;

}
Exemplo n.º 28
0
/************************* Nested Join ************************************/
extern RC nested_join(JoinInfo *j1,Schema *s1,JoinInfo *j2,Schema *s2,Schema *s3,RID *res)
{

	
	int a1=j1->attrNum;
	int a2=j2->attrNum;
	int i,j,x,z=0;
	RID rel1,rel2,rel3;
	Value *v1,*v2;
	
	Record *r1= (Record*) malloc(sizeof(Record));  // To store first relation
	Record *r2= (Record*) malloc(sizeof(Record));  // to store second relation
	Record *r3;				       // To store the result
  	/*openTable(table, t1);
  	mgmtinfo=table->mgmtData;*/
  	
  	//Set pointers on both relations to scan
  	
  	int tc1= mgmtinfo->Tuplescount;
  	rel1.page=mgmtinfo->FirstPage;
  	rel1.slot=0;
  	
  	int tc2= mgmtinfo2->Tuplescount;
  	rel2.page=mgmtinfo->FirstPage;
  	rel2.slot=0;
  	
  	// Set pointer to write the result to page file
  	rel3.page=mgmtinfo3->FirstPage;
  	rel3.slot=0;
	
  	printf("\nJoined tuples are: \n");
  	// Traversing
	for(i=0;i<tc1;i++)
	{
		//printf("\n Entering here");
	   getRecord(table,rel1,r1);
	   //printf("\n Getting record");
	   getAttr(r1,s1,a1,&v1);
	   //printf("\n Here Successfully");
	   
	   //printf("\n 2nd record %d",getRecord(table3,rel3,r3));
	   //printf("\n Ok then");
	   rel2.page=mgmtinfo2->FirstPage;
	   rel2.slot=0;
	   
	   // traverses relation 2
	   for(j=0;j<tc2;j++)
	   {
	   	
	   	getRecord(table2,rel2,r2);
	  	getAttr(r2,s2,a2,&v2);
	  	//printf("\n 2nd tuple");
	  	if( v2->dt==DT_INT)
	  	{
	  	        if(v2->v.intV == v1->v.intV)
	  	        {
	  	        	//printf("\n 2nd tuple twice");
	  	        	createRecord(&r3,s3);
	  	        	print(s1,r1,v1,r3,s3);
	  	        	x=s1->numAttr;	
	  	             	print2(s2,r2,v2,r3,s3,x,a2);
	  	             	insertRecord(table3,r3);
	  	             	res[z]=r3->id;
	  	             	z++;
         			printf("\n");
         			if(rel3.slot < (mgmtinfo2->maxSlots-1))
	  	       		{
	  	      			//printf("\n Increase slot");	
	  	      			rel3.slot++; 
	  	       		}
	  	       		else
	  	  		{
	  	     
					rel3.page++;
					rel3.slot=0;	  	       
	  	       		}			
         		}			          	 
	  	}
	  	if(rel2.slot < (mgmtinfo2->maxSlots-1))
	        {
		      	//printf("\n Increase slot");	
	  	      	rel2.slot++; 
	  	}
	  	else
	  	{
			rel2.page++;
			rel2.slot=0;	  	       
      	        }
	  	       
	  }	  	
	  if(rel1.slot < (mgmtinfo->maxSlots-1))
	  {
	       		//printf("\n Increasing slots for r1");
	  	      	rel1.slot++; 
 	   }
	   else
	   {       
			rel1.page++;
			rel1.slot=0;	  	       
           }
 	 }
	
	// Free all the allocated memory
	
	free(r1);
	free(r2);
	free(v1);
	free(v2);
		
	return RC_OK;
}		
Exemplo n.º 29
0
int main(int argc, char *argv[]){
    int i;
    record* mod;
    char *command;

    fileName = argv[1];
    phoneBookFile = fopen(fileName,"r+");
    if(phoneBookFile == NULL){
        phoneBookFile = fopen(fileName,"w+");
        //printf("%s\n", "File not found, so was created");
    }

    phoneBook.size = 0;
    head = phoneBook.persons;

    rewind(phoneBookFile);
    current.id = -1;
    while (!feof(phoneBookFile)){
        fscanf(phoneBookFile, "%d", &current.id);
        current.name = read(phoneBookFile);
        current.phoneNumber = read(phoneBookFile);
        createRecord(current.id, current.name, current.phoneNumber);
    }

    maxId = (current.id > maxId) ? current.id : maxId;
    maxId++;

    while( true ){
        command = read(stdin);
        if(strcmp(command, "create") == 0){
            current.name = read(stdin);
            current.phoneNumber = read(stdin);
            if(isCorrectName(current.name) && stabilizationPhoneNumber(current.phoneNumber)){
                createRecord(maxId, current.name, current.phoneNumber);
                maxId++;
                fileUpdate();
            }
        } else if(strcmp(command, "delete") == 0){
            scanf("%d", &current.id);
            mod = getIdPrePosition(current.id);
            if(mod != NULL ){
                deleteRecord(mod);
                phoneBook.size--;
                fileUpdate();
            } else {
                //printf("%s\n", "ID not found.");
            }
        } else if(strcmp(command, "change") == 0){
            scanf("%d ", &current.id);
            mod = getIdPrePosition(current.id);
            if(mod != NULL){
                temp = mod->next;
                command = read(stdin);
                if(strcmp(command,"name") == 0){
                    current.name = read(stdin);
                    if(isCorrectName(current.name)){
                        strcpy(temp->name, current.name);
                    } else {
                        //printf("%s%s\n", "Not correct new name : ", current.name);
                    }
                } else if(strcmp(command,"number") == 0){
                    current.phoneNumber = read(stdin);
                    if(stabilizationPhoneNumber(current.phoneNumber)){
                        strcpy(temp->phoneNumber, current.phoneNumber);
                    }
                } else {
                    //printf("%s \"%s\" %s\n","Operation" , command, "is not defined");
                }
                fileUpdate();
            } else {
                //printf("%s\n", "ID not found.");
            }
        } else if(strcmp(command, "find") == 0){
            command = read(stdin);
            if(strlen(command) > 0){
                bool f1, f2, isFound;
                isFound = false;
                f1 = isCorrectName(command);
                if(!f1){
                    stabilizationPhoneNumber(command);
                } else {
                    command = alphaToLower(command);
                }
                temp = head;
                for (i = 0; i < phoneBook.size; i++){
                    f2 = false;
                    if(f1){//name
                        if(strstr(alphaToLower(temp->name), command)){
                            f2 = true;
                        }
                    } else{//number
                        if(strcmp(temp->phoneNumber, command) == 0){
                            f2 = true;
                        }
                    }
                    if(!isFound && f2){
                        isFound = true;
                    }
                    if(f2){
                        printf("%d ", temp->id);
                        printf("%s %s\n", temp->name, temp->phoneNumber);
                    }
                    temp = temp->next;
                }
                if(!isFound){
                    //printf("Not found.\n");
                }
            } else {
                //printf("%s\n", "You did not enter anything.");
            }
        } else if(strcmp(command, "exit") == 0){
            free(command);
            fclose(phoneBookFile);
            free(phoneBook.persons);
            break;
        } else {
            //printf("%s \"%s\" %s\n","Operation" , command, "is not defined");
        }
        fflush(phoneBookFile);
        fflush(stdout);
    }
    return 0;
}
Exemplo n.º 30
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();
         }
              
        
        }
        }