1 /***************************************************************************
2 * Copyright (C) 2007 by www.databasecache.com *
3 * Contact: praba_tuty@databasecache.com *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 ***************************************************************************/
17 #include<CatalogTables.h>
23 #include<PredicateImpl.h>
27 DbRetVal
TableImpl::bindFld(const char *name
, void *val
)
29 //set it in the field list
30 DbRetVal rv
= fldList_
.updateBindVal(name
, val
);
32 printError(ErrNotExists
, "Field %s does not exist", name
);
38 bool TableImpl::isFldNull(const char *name
){
39 int colpos
= fldList_
.getFieldPosition(name
);
42 printError(ErrNotExists
, "Field %s does not exist", name
);
46 return isFldNull(colpos
);
49 bool TableImpl::isFldNull(int colpos
)
51 if (!curTuple_
) return false;
52 if (colpos
<1 || colpos
> numFlds_
) return false;
53 char *nullOffset
= (char*)curTuple_
- 4;
54 if (isIntUsedForNULL
) {
55 int nullVal
= *(int*)((char*)curTuple_
+ (length_
- 4));
56 if (BITSET(nullVal
, colpos
)) return true;
59 char *nullOffset
= (char*)curTuple_
- os::align(numFlds_
);
60 if (nullOffset
[colpos
-1]) return true;
64 void TableImpl::markFldNull(char const* name
)
66 int colpos
= fldList_
.getFieldPosition(name
);
69 printError(ErrNotExists
, "Field %s does not exist", name
);
75 void TableImpl::markFldNull(int fldpos
)
77 if (fldpos
<1 || fldpos
> numFlds_
) return;
78 if (isIntUsedForNULL
) {
79 if (!BITSET(iNotNullInfo
, fldpos
)) SETBIT(iNullInfo
, fldpos
);
82 if (!BITSET(iNotNullInfo
, fldpos
)) cNullInfo
[fldpos
-1] = 1;
86 void TableImpl::clearFldNull(const char *name
)
88 int colpos
= fldList_
.getFieldPosition(name
);
91 printError(ErrNotExists
, "Field %s does not exist", name
);
98 void TableImpl::clearFldNull(int colpos
)
100 if (colpos
<1 || colpos
> numFlds_
) return;
101 if (isIntUsedForNULL
) {
102 CLEARBIT(iNullInfo
, colpos
);
105 cNullInfo
[colpos
-1] = 0;
110 DbRetVal
TableImpl::execute()
114 printError(ErrAlready
,"Scan already open:Close and re execute");
117 //table ptr is set in predicate because it needs to access the
118 //type and length to evaluate
121 PredicateImpl
*pred
= (PredicateImpl
*) pred_
;
122 pred
->setTable(this);
129 printError(ErrSysInternal
,"Unable to create the plan");
130 return ErrSysInternal
;
133 iter
= new TupleIterator(pred_
, scanType_
, idxInfo
[useIndex_
], chunkPtr_
, sysDB_
->procSlot
);
134 else if (scanType_
== fullTableScan
)
135 iter
= new TupleIterator(pred_
, scanType_
, NULL
, chunkPtr_
, sysDB_
->procSlot
);
138 printError(ErrSysFatal
,"Unable to create tuple iterator");//should never happen
144 printError(ErrSysInternal
,"Unable to open the iterator");
145 return ErrSysInternal
;
151 DbRetVal
TableImpl::createPlan()
154 //will do early return here. plan is generated only when setPredicate is called.
155 if (scanType_
== unknownScan
) return ErrSysFatal
; //this should never happen
159 //if there are no predicates then go for full scan
160 //if there are no indexes then go for full scan
161 if (NULL
== pred_
|| NULL
== indexPtr_
)
163 scanType_
= fullTableScan
;
164 isPlanCreated
= true;
167 if (NULL
!= indexPtr_
)
169 PredicateImpl
*pred
= (PredicateImpl
*)pred_
;
170 printDebug(DM_Predicate
, "predicate does not involve NOT , OR operator");
171 if (!pred
->isNotOrInvolved())
173 printDebug(DM_Predicate
, "predicate does not involve NOT , OR operator");
174 for (int i
=0; i
< numIndexes_
; i
++)
176 char *fName
= ((SingleFieldHashIndexInfo
*)idxInfo
[i
])->fldName
;
177 if (pred
->pointLookupInvolved(fName
))
179 printDebug(DM_Predicate
, "point lookup involved for field %s",fName
);
180 scanType_
= hashIndexScan
;
182 isPlanCreated
= true;
188 scanType_
= fullTableScan
;
189 isPlanCreated
= true;
193 void* TableImpl::fetch()
196 if (NULL
== curTuple_
) return curTuple_
;
197 copyValuesToBindBuffer(curTuple_
);
200 void* TableImpl::fetch(DbRetVal
&rv
)
203 if (NULL
== curTuple_
) return curTuple_
;
204 copyValuesToBindBuffer(curTuple_
);
208 void* TableImpl::fetchNoBind()
212 printError(ErrNotOpen
,"Scan not open or Scan is closed\n");
215 curTuple_
= iter
->next();
216 if (NULL
== curTuple_
)
220 DbRetVal lockRet
= OK
;
221 if ((*trans
)->isoLevel_
== READ_REPEATABLE
) {
222 lockRet
= lMgr_
->getSharedLock(curTuple_
, trans
);
225 printError(lockRet
, "Unable to get the lock for the tuple %x", curTuple_
);
231 else if ((*trans
)->isoLevel_
== READ_COMMITTED
)
233 //if iso level is read committed, operation duration lock is sufficent
234 //so release it here itself.
236 struct timeval timeout
;
237 timeout
.tv_sec
= Conf::config
.getMutexSecs();
238 timeout
.tv_usec
= Conf::config
.getMutexUSecs();
242 lockRet
= lMgr_
->isExclusiveLocked( curTuple_
, trans
, status
);
245 printError(lockRet
, "Unable to get the lock for the tuple %x", curTuple_
);
251 if (tries
== 0) break;
252 os::select(0, 0, 0, 0, &timeout
);
257 printError(lockRet
, "Unable to get the lock for the tuple %x", curTuple_
);
265 void* TableImpl::fetchNoBind(DbRetVal
&rv
)
270 printError(ErrNotOpen
,"Scan not open or Scan is closed\n");
274 curTuple_
= iter
->next();
275 if (NULL
== curTuple_
)
279 DbRetVal lockRet
= OK
;
280 if ((*trans
)->isoLevel_
== READ_REPEATABLE
) {
281 lockRet
= lMgr_
->getSharedLock(curTuple_
, trans
);
284 printError(lockRet
, "Unable to get the lock for the tuple %x", curTuple_
);
291 else if ((*trans
)->isoLevel_
== READ_COMMITTED
)
293 //if iso level is read committed, operation duration lock is sufficent
294 //so release it here itself.
296 struct timeval timeout
;
297 timeout
.tv_sec
= Conf::config
.getMutexSecs();
298 timeout
.tv_usec
= Conf::config
.getMutexUSecs();
302 lockRet
= lMgr_
->isExclusiveLocked( curTuple_
, trans
, status
);
305 printError(lockRet
, "Unable to get the lock for the tuple %x", curTuple_
);
312 if (tries
== 0) break;
313 os::select(0, 0, 0, 0, &timeout
);
318 printError(lockRet
, "Unable to get the lock for the tuple %x", curTuple_
);
327 DbRetVal
TableImpl::insertTuple()
330 void *tptr
= ((Chunk
*)chunkPtr_
)->allocate(db_
, &ret
);
333 printError(ret
, "Unable to allocate from chunk");
337 ret
= lMgr_
->getExclusiveLock(tptr
, trans
);
340 ((Chunk
*)chunkPtr_
)->free(db_
, tptr
);
341 printError(ret
, "Could not get lock for the insert tuple %x", tptr
);
342 return ErrLockTimeOut
;
346 ret
= copyValuesFromBindBuffer(tptr
);
349 printError(ret
, "Unable to copy values from bind buffer");
350 (*trans
)->removeFromHasList(db_
, tptr
);
351 lMgr_
->releaseLock(tptr
);
352 ((Chunk
*)chunkPtr_
)->free(db_
, tptr
);
360 *(int*)((char*)(tptr
) + (length_
-addSize
)) = iNullInfo
;
364 addSize
= os::align(numFlds_
);
365 os::memcpy(((char*)(tptr
) + (length_
-addSize
)), cNullInfo
, addSize
);
368 //int tupleSize = length_ + addSize;
369 if (NULL
!= indexPtr_
)
373 for (i
= 0; i
< numIndexes_
; i
++)
375 ret
= insertIndexNode(*trans
, indexPtr_
[i
], idxInfo
[i
], tptr
);
376 if (ret
!= OK
) { printError(ret
, "Error in inserting to index"); break;}
378 if (i
!= numIndexes_
)
380 for (int j
= 0; j
< i
; j
++)
381 deleteIndexNode(*trans
, indexPtr_
[j
], idxInfo
[j
], tptr
);
382 lMgr_
->releaseLock(tptr
);
383 (*trans
)->removeFromHasList(db_
, tptr
);
384 ((Chunk
*)chunkPtr_
)->free(db_
, tptr
);
385 printError(ret
, "Unable to insert index node for tuple %x", tptr
);
390 ret
= (*trans
)->appendUndoLog(sysDB_
, InsertOperation
, tptr
, length_
);
394 DbRetVal
TableImpl::deleteTuple()
396 if (NULL
== curTuple_
)
398 printError(ErrNotOpen
, "Scan not open: No Current tuple");
401 DbRetVal ret
= lMgr_
->getExclusiveLock(curTuple_
, trans
);
404 printError(ret
, "Could not get lock for the delete tuple %x", curTuple_
);
405 return ErrLockTimeOut
;
408 if (NULL
!= indexPtr_
)
412 for (i
= 0; i
< numIndexes_
; i
++)
414 ret
= deleteIndexNode(*trans
, indexPtr_
[i
], idxInfo
[i
], curTuple_
);
415 if (ret
!= OK
) break;
417 if (i
!= numIndexes_
)
419 for (int j
= 0; j
< i
; j
++)
420 insertIndexNode(*trans
, indexPtr_
[j
], idxInfo
[j
], curTuple_
);
421 lMgr_
->releaseLock(curTuple_
);
422 (*trans
)->removeFromHasList(db_
, curTuple_
);
423 printError(ret
, "Unable to insert index node for tuple %x", curTuple_
);
427 ((Chunk
*)chunkPtr_
)->free(db_
, curTuple_
);
429 ret
= (*trans
)->appendUndoLog(sysDB_
, DeleteOperation
, curTuple_
, length_
);
433 int TableImpl::deleteWhere()
435 int tuplesDeleted
= 0;
438 if (rv
!=OK
) return (int) rv
;
441 if (rv
!= OK
) { tuplesDeleted
= (int)rv
; break; }
442 if (NULL
== curTuple_
) break;
445 printError(rv
, "Error: Could only delete %d tuples", tuplesDeleted
);
452 return tuplesDeleted
;
455 int TableImpl::truncate()
457 //take exclusive lock on the table
458 //get the chunk ptr of the table
459 //traverse the tablechunks and free all the pages except the first one
460 //get the chunk ptr of all its indexes
461 //traverse the indexchunks and free all the pages except the first one
466 Predicate
* tmpPred
= pred_
;
468 isPlanCreated
= false;
469 int tuplesDeleted
= deleteWhere();
470 isPlanCreated
= false;
472 return tuplesDeleted
;
475 DbRetVal
TableImpl::updateTuple()
477 if (NULL
== curTuple_
)
479 printError(ErrNotOpen
, "Scan not open: No Current tuple");
482 DbRetVal ret
= lMgr_
->getExclusiveLock(curTuple_
, trans
);
485 printError(ret
, "Could not get lock for the update tuple %x", curTuple_
);
486 return ErrLockTimeOut
;
488 if (NULL
!= indexPtr_
)
491 //TODO::If it fails while updating index node, we have to undo all the updates
492 //on other indexes on the table.Currently it will leave the database in an
493 //inconsistent state.
494 for (int i
= 0; i
< numIndexes_
; i
++)
496 ret
= updateIndexNode(*trans
, indexPtr_
[i
], idxInfo
[i
], curTuple_
);
499 lMgr_
->releaseLock(curTuple_
);
500 (*trans
)->removeFromHasList(db_
, curTuple_
);
501 printError(ret
, "Unable to update index node for tuple %x", curTuple_
);
507 ret
= (*trans
)->appendUndoLog(sysDB_
, UpdateOperation
, curTuple_
, length_
);
508 if (ret
!= OK
) return ret
;
513 *(int*)((char*)(curTuple_
) + (length_
-addSize
)) |= iNullInfo
;
517 addSize
= os::align(numFlds_
);
518 //TODO::Do not do blind memcpy. It should OR each and every char
519 //os::memcpy(((char*)(curTuple_) + (length_-addSize)), cNullInfo, addSize);
523 DbRetVal rv
= copyValuesFromBindBuffer(curTuple_
, false);
525 lMgr_
->releaseLock(curTuple_
);
526 (*trans
)->removeFromHasList(db_
, curTuple_
);
532 void TableImpl::printInfo()
534 printf(" <TableName> %s </TableName>\n", tblName_
);
535 printf(" <TupleCount> %d </TupleCount>\n", numTuples());
536 printf(" <PagesUsed> %d </PagesUsed>\n", pagesUsed());
537 printf(" <SpaceUsed> %d </SpaceUsed>\n", spaceUsed());
538 printf(" <Indexes> %d <Indexes>\n", numIndexes_
);
539 printf(" <TupleLength> %d </TupleLength>\n", length_
);
540 printf(" <Fields> %d </Fields>\n", numFlds_
);
541 printf(" <Indexes>\n");
542 for (int i
=0; i
<numIndexes_
; i
++)
543 printf("<IndexName> %s </IndexName>\n", CatalogTableINDEX::getName(indexPtr_
[i
]));
544 printf(" </Indexes>\n");
548 DbRetVal
TableImpl::copyValuesFromBindBuffer(void *tuplePtr
, bool isInsert
)
550 //Iterate through the bind list and copy the value here
551 FieldIterator fIter
= fldList_
.getIterator();
552 char *colPtr
= (char*) tuplePtr
;
554 while (fIter
.hasElement())
556 FieldDef def
= fIter
.nextElement();
557 if (def
.isNull_
&& !def
.isDefault_
&& NULL
== def
.bindVal_
&& isInsert
)
559 printError(ErrNullViolation
, "NOT NULL constraint violation for field %s\n", def
.fldName_
);
560 return ErrNullViolation
;
562 if (def
.isDefault_
&& NULL
== def
.bindVal_
&& isInsert
)
564 void *dest
= AllDataType::alloc(def
.type_
, def
.length_
);
565 AllDataType::convert(typeString
, def
.defaultValueBuf_
, def
.type_
, dest
);
566 AllDataType::copyVal(colPtr
, dest
, def
.type_
, def
.length_
);
567 colPtr
= colPtr
+ os::align(AllDataType::size(def
.type_
, def
.length_
));
575 if (NULL
!= def
.bindVal_
)
577 strcpy((char*)colPtr
, (char*)def
.bindVal_
);
578 *(((char*)colPtr
) + (def
.length_
-1)) = '\0';
580 else if (!def
.isNull_
&& isInsert
) setNullBit(fldpos
);
581 colPtr
= colPtr
+ os::align(def
.length_
);
584 if (NULL
!= def
.bindVal_
)
585 os::memcpy((char*)colPtr
, (char*)def
.bindVal_
, def
.length_
);
586 else if (!def
.isNull_
&& isInsert
) setNullBit(fldpos
);
587 colPtr
= colPtr
+ os::align(def
.length_
);
590 if (NULL
!= def
.bindVal_
)
591 AllDataType::copyVal(colPtr
, def
.bindVal_
, def
.type_
);
592 else { if (!def
.isNull_
&& isInsert
) setNullBit(fldpos
); }
593 colPtr
= colPtr
+ os::align(AllDataType::size(def
.type_
));
600 void TableImpl::setNullBit(int fldpos
)
602 if (isIntUsedForNULL
)
603 SETBIT(iNullInfo
, fldpos
);
605 cNullInfo
[fldpos
-1] = 1;
607 DbRetVal
TableImpl::copyValuesToBindBuffer(void *tuplePtr
)
609 //Iterate through the bind list and copy the value here
610 FieldIterator fIter
= fldList_
.getIterator();
611 char *colPtr
= (char*) tuplePtr
;
612 while (fIter
.hasElement())
614 FieldDef def
= fIter
.nextElement();
618 if (NULL
!= def
.bindVal_
)
619 strcpy((char*)def
.bindVal_
, (char*)colPtr
);
620 colPtr
= colPtr
+ os::align(def
.length_
);
623 if (NULL
!= def
.bindVal_
)
624 os::memcpy((char*)def
.bindVal_
, (char*)colPtr
, def
.length_
);
625 colPtr
= colPtr
+ os::align(def
.length_
);
628 if (NULL
!= def
.bindVal_
)
629 AllDataType::copyVal(def
.bindVal_
, colPtr
, def
.type_
);
630 colPtr
= colPtr
+ os::align(AllDataType::size(def
.type_
));
637 //-1 index not supported
638 DbRetVal
TableImpl::insertIndexNode(Transaction
*tr
, void *indexPtr
, IndexInfo
*info
, void *tuple
)
640 INDEX
*iptr
= (INDEX
*)indexPtr
;
642 printDebug(DM_Table
, "Inside insertIndexNode type %d", iptr
->indexType_
);
643 Index
* idx
= Index::getIndex(iptr
->indexType_
);
644 ret
= idx
->insert(this, tr
, indexPtr
, info
, tuple
,undoFlag
);
648 DbRetVal
TableImpl::deleteIndexNode(Transaction
*tr
, void *indexPtr
, IndexInfo
*info
, void *tuple
)
650 INDEX
*iptr
= (INDEX
*)indexPtr
;
652 Index
* idx
= Index::getIndex(iptr
->indexType_
);
653 ret
= idx
->remove(this, tr
, indexPtr
, info
, tuple
, undoFlag
);
656 void TableImpl::printSQLIndexString()
658 CatalogTableINDEXFIELD
cIndexField(sysDB_
);
659 char fName
[IDENTIFIER_LENGTH
];
660 char *fldName
= fName
;
662 for (int i
= 0; i
< numIndexes_
; i
++)
664 INDEX
*iptr
= (INDEX
*) indexPtr_
[i
];
665 cIndexField
.getFieldNameAndType((void*)iptr
, fldName
, type
);
666 printf("CREATE INDEX %s on %s ( %s ) ", iptr
->indName_
, getName(), fldName
);
667 if (((SingleFieldHashIndexInfo
*) idxInfo
[i
])->isUnique
) printf(" UNIQUE;\n"); else printf(";\n");
672 DbRetVal
TableImpl::updateIndexNode(Transaction
*tr
, void *indexPtr
, IndexInfo
*info
, void *tuple
)
674 INDEX
*iptr
= (INDEX
*)indexPtr
;
676 Index
* idx
= Index::getIndex(iptr
->indexType_
);
677 //TODO::currently it updates irrespective of whether the key changed or not
678 //because of this commenting the whole index update code. relook at it and uncomment
680 //ret = idx->update(this, tr, indexPtr, info, tuple, undoFlag);
686 void TableImpl::setTableInfo(char *name
, int tblid
, size_t length
,
687 int numFld
, int numIdx
, void *chunk
)
689 strcpy(tblName_
, name
);
693 numIndexes_
= numIdx
;
697 long TableImpl::spaceUsed()
699 Chunk
*chk
= (Chunk
*)chunkPtr_
;
700 long totSize
= chk
->getTotalDataNodes() * chk
->getSize();
701 totSize
= totSize
+ (chk
->totalPages() * sizeof (PageInfo
));
705 int TableImpl::pagesUsed()
707 Chunk
*chk
= (Chunk
*)chunkPtr_
;
708 return chk
->totalPages();
711 long TableImpl::numTuples()
713 return ((Chunk
*)chunkPtr_
)->getTotalDataNodes();
716 List
TableImpl::getFieldNameList()
719 FieldIterator fIter
= fldList_
.getIterator();
720 while (fIter
.hasElement())
722 FieldDef def
= fIter
.nextElement();
723 Identifier
*elem
= new Identifier();
724 strcpy(elem
->name
, def
.fldName_
);
725 fldNameList
.append(elem
);
729 DbRetVal
TableImpl::close()
733 printError(ErrNotOpen
,"Scan not open");
741 DbRetVal
TableImpl::lock(bool shared
)
747 ret = lMgr_->getSharedLock(chunkPtr_, NULL);
749 ret = lMgr_->getExclusiveLock(chunkPtr_, NULL);
752 printError(ret, "Could not exclusive lock on the table %x", chunkPtr_);
754 //do not append for S to X upgrade
755 if (!ProcessManager::hasLockList.exists(chunkPtr_))
756 ProcessManager::hasLockList.append(chunkPtr_);
761 DbRetVal
TableImpl::unlock()
764 if (!ProcessManager::hasLockList.exists(chunkPtr_)) return OK;
765 DbRetVal ret = lMgr_->releaseLock(chunkPtr_);
768 printError(ret, "Could not release exclusive lock on the table %x", chunkPtr_);
771 ProcessManager::hasLockList.remove(chunkPtr_);
777 TableImpl::~TableImpl()
779 if (NULL
!= iter
) { delete iter
; iter
= NULL
; }
780 if (NULL
!= indexPtr_
) { delete[] indexPtr_
; indexPtr_
= NULL
; }
783 for (int i
= 0; i
< numIndexes_
; i
++) delete idxInfo
[i
];
787 if (numFlds_
> 31 && cNullInfo
!= NULL
) { free(cNullInfo
); cNullInfo
= NULL
; }
789 fldList_
.removeAll();