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>
26 #include<AggTableImpl.h> //for AggType
28 void Table::getFieldNameAlone(char *fname
, char *name
) {
30 char *fullname
= fname
;
31 while(*fullname
!= '\0')
33 if (*fullname
== '.') { dotFound
= true; break; }
36 if (dotFound
) strcpy(name
, ++fullname
); else strcpy(name
, fname
);
39 void Table::getTableNameAlone(char *fname
, char *name
) {
42 bool dotFound
= false;
45 if (*name
== '.') { *name
='\0'; dotFound
= true; break; }
48 if (!dotFound
) strcpy(start
, "");
52 DbRetVal
TableImpl::bindFld(const char *name
, void *val
, bool isNullExpl
)
54 if (name
[0] == '*' ) return OK
;
55 //set it in the field list
56 char fieldName
[IDENTIFIER_LENGTH
];
57 getFieldNameAlone((char*)name
, fieldName
);
58 DbRetVal rv
= fldList_
.updateBindVal(fieldName
, val
, isNullExpl
);
60 printError(ErrNotExists
, "Field %s does not exist", fieldName
);
66 int TableImpl::getFldPos(char *name
)
68 return fldList_
.getFieldPosition(name
);
70 void TableImpl::setAliasName(char *name
)
72 strcpy(aliasName
, name
);
75 bool TableImpl::hasIndex(char* fName
)
77 if (NULL
== indexPtr_
) return false;
78 for (int i
=0; i
< numIndexes_
; i
++)
80 HashIndexInfo
* info
= (HashIndexInfo
*) idxInfo
[i
];
81 FieldIterator iter
= info
->idxFldList
.getIterator();
84 FieldDef
*def
= iter
.nextElement();
85 if(strcmp(def
->fldName_
, fName
) == 0)
86 if(!iter
.hasElement())//neglet if it is composite index
93 IndexType
TableImpl::getIndexType(char *fName
, int *pos
)
95 if (NULL
== indexPtr_
) return unknownIndex
;
96 for (int i
=0; i
< numIndexes_
; i
++)
98 HashIndexInfo
* info
= (HashIndexInfo
*) idxInfo
[i
];
99 FieldIterator iter
= info
->idxFldList
.getIterator();
100 if(iter
.hasElement())
102 FieldDef
*def
= iter
.nextElement();
103 if(strcmp(def
->fldName_
, fName
) == 0)
104 if(!iter
.hasElement()) {//neglet if it is composite index
106 return info
->indType
;
113 void TableImpl::addPredicate(char *fName
, ComparisionOp op
, void *buf
)
115 char fieldName
[IDENTIFIER_LENGTH
];
116 Table::getFieldNameAlone(fName
, fieldName
);
117 PredicateImpl
*pred
= (PredicateImpl
*) pred_
;
118 PredicateImpl
*newPred
= new PredicateImpl();
119 newPred
->setTerm(fName
, op
, buf
);
120 if (NULL
== pred
) { pred_
= newPred
; predList
.append(newPred
); return; }
121 if (pred
->isSingleTerm())
123 bool res
= pred
->appendIfSameFld(fName
, op
, buf
);
129 PredicateImpl
*bothPred
= new PredicateImpl();
130 bothPred
->setTerm(pred
, OpAnd
, newPred
);
131 predList
.append(bothPred
);
135 DbRetVal
TableImpl::trySharedLock(void *curTuple
, Transaction
**trans
)
137 DbRetVal lockRet
= OK
;
138 int tries
= Conf::config
.getMutexRetries();
139 while((lockRet
= lMgr_
->getSharedLock(curTuple_
, trans
)) == ErrLockTimeOut
)
142 if (tries
<=0) break;
146 DbRetVal
TableImpl::tryExclusiveLock(void *curTuple
, Transaction
**trans
)
148 DbRetVal lockRet
= OK
;
149 int tries
= Conf::config
.getMutexRetries();
150 while((lockRet
= lMgr_
->getExclusiveLock(curTuple_
, trans
)) == ErrLockTimeOut
)
153 if (tries
<=0) break;
158 DbRetVal
TableImpl::getCheckpointMutex()
162 int totalTries
= Conf::config
.getMutexRetries();
163 struct timeval timeout
, timeval
;
164 timeout
.tv_sec
= Conf::config
.getMutexSecs();
165 timeout
.tv_usec
= Conf::config
.getMutexUSecs();
167 while (tries
< totalTries
)
169 rv
= sysDB_
->getSCheckpointMutex();
171 timeval
.tv_sec
= timeout
.tv_sec
;
172 timeval
.tv_usec
= timeout
.tv_usec
;
173 os::select(0,0,0,0,&timeval
);
176 if (tries
== totalTries
) {
177 printError(ErrLockTimeOut
, "Checkpoint server is running. Retry after sometime.");
178 return ErrLockTimeOut
;
183 void TableImpl::printInfo()
185 printf(" <TableName> %s </TableName>\n", tblName_
);
186 printf(" <TupleCount> %d </TupleCount>\n", numTuples());
187 printf(" <PagesUsed> %d </PagesUsed>\n", pagesUsed());
188 printf(" <SpaceUsed> %d </SpaceUsed>\n", spaceUsed());
189 printf(" <Indexes> %d <Indexes>\n", numIndexes_
);
190 printf(" <TupleLength> %d </TupleLength>\n", length_
);
191 printf(" <Fields> %d </Fields>\n", numFlds_
);
192 printf(" <Indexes>\n");
193 for (int i
=0; i
<numIndexes_
; i
++)
194 printf("<IndexName> %s </IndexName>\n", CatalogTableINDEX::getName(indexPtr_
[i
]));
195 printf(" </Indexes>\n");
199 DbRetVal
TableImpl::copyValuesFromBindBuffer(void *tuplePtr
, bool isInsert
)
201 //Iterate through the bind list and copy the value here
202 FieldIterator fIter
= fldList_
.getIterator();
203 char *colPtr
= (char*) tuplePtr
;
205 while (fIter
.hasElement())
207 FieldDef
*def
= fIter
.nextElement();
208 if(def
->isAutoIncrement_
&& isInsert
)
210 if (OK
!= takeTableMutex())
212 printError(ErrLockTimeOut
,
213 " Unable to take table mutex for increment key");
214 return ErrLockTimeOut
;
216 AllDataType::copyVal(&tempAutoVal
,ptrToAuto
, def
->type_
, def
->length_
);
217 if(def
->bindVal_
==NULL
)
219 AllDataType::increment(colPtr
, &tempAutoVal
, def
->type_
);
220 AllDataType::copyVal(ptrToAuto
,colPtr
, def
->type_
,
222 colPtr
= colPtr
+ def
->length_
;
225 if(AllDataType::compareVal(def
->bindVal_
, &tempAutoVal
,
226 OpGreaterThan
, def
->type_
))
228 AllDataType::copyVal(ptrToAuto
,def
->bindVal_
, def
->type_
,
231 AllDataType::copyVal(colPtr
, def
->bindVal_
, def
->type_
,
233 colPtr
= colPtr
+ def
->length_
;
240 if (def
->isNull_
&& !def
->isDefault_
&& NULL
== def
->bindVal_
&&
243 printError(ErrNullViolation
,
244 "NOT NULL constraint violation for field %s", def
->fldName_
);
245 return ErrNullViolation
;
247 if (def
->isDefault_
&& NULL
== def
->bindVal_
&& isInsert
)
249 if (! def
->isNullExplicit_
) {
250 if (def
->type_
== typeVarchar
) {
253 ((Chunk
*) vcChunkPtr_
)->allocate(db_
, def
->length_
, &rv
);
254 *(long *)colPtr
= (long)ptr
;
255 AllDataType::convert(typeString
, def
->defaultValueBuf_
,
256 def
->type_
, ptr
, def
->length_
);
258 void *dest
= AllDataType::alloc(def
->type_
, def
->length_
);
259 AllDataType::convert(typeString
, def
->defaultValueBuf_
,
260 def
->type_
, dest
, def
->length_
);
261 AllDataType::copyVal(colPtr
, dest
, def
->type_
,
267 *(long *) colPtr
= 0L;
269 if (def
->type_
!= typeVarchar
) colPtr
= colPtr
+ def
->length_
;
270 else colPtr
= colPtr
+ sizeof(void *);
277 if (NULL
!= def
->bindVal_
)
279 if(!isInsert
&& isFldNull(fldpos
)){clearNullBit(fldpos
);}
280 // strncpy((char*)colPtr, (char*)def->bindVal_, def->length_);
281 // *(((char*)colPtr) + (def->length_-1)) = '\0';
282 strcpy((char*)colPtr
, (char*)def
->bindVal_
);
284 else if (!def
->isNull_
&& isInsert
) setNullBit(fldpos
);
285 colPtr
= colPtr
+ def
->length_
;
288 if (NULL
!= def
->bindVal_
)
290 if(!isInsert
&& isFldNull(fldpos
)){clearNullBit(fldpos
);}
291 DbRetVal rv
= AllDataType::strToValue(colPtr
,
292 (char *) def
->bindVal_
, def
->type_
, def
->length_
);
293 if (rv
!= OK
) return ErrBadArg
;
294 } else if (!def
->isNull_
&& isInsert
&& !def
->bindVal_
) {
297 colPtr
= colPtr
+ def
->length_
;
300 if (NULL
!= def
->bindVal_
) {
301 if (!isInsert
&& isFldNull(fldpos
)) {clearNullBit(fldpos
);}
304 if (*(long *) colPtr
!= 0L)
305 ((Chunk
*) vcChunkPtr_
)->free(db_
,
306 (void *)*(long *)colPtr
);
307 *(long *) colPtr
= 0L;
309 if (strcmp((char *)def
->bindVal_
,"") != 0) {
311 ((Chunk
*) vcChunkPtr_
)->allocate(db_
,
313 if (rv
!= OK
) return ErrBadArg
;
314 *(long *)colPtr
= (long)ptr
;
315 strcpy((char *)ptr
, (char *)def
->bindVal_
);
316 } else { setNullBit(fldpos
); }
317 } else if (!def
->isNull_
&& isInsert
) setNullBit(fldpos
);
318 colPtr
= colPtr
+ sizeof(void *);
321 if (NULL
!= def
->bindVal_
) {
322 if(!isInsert
&& isFldNull(fldpos
)){clearNullBit(fldpos
);}
323 AllDataType::copyVal(colPtr
, def
->bindVal_
, def
->type_
);
324 } else { if (!def
->isNull_
&& isInsert
) setNullBit(fldpos
); }
325 colPtr
= colPtr
+ def
->length_
;
334 DbRetVal
TableImpl::copyValuesToBindBuffer(void *tuplePtr
)
336 //Iterate through the bind list and copy the value here
337 char *colPtr
= (char*) tuplePtr
;
338 FieldDef
*def
= NULL
;
339 for (int i
= 0; i
< numBindFlds_
; i
++) {
340 def
= (FieldDef
*) bindListArray_
[i
];
341 colPtr
= (char *) tuplePtr
+ def
->offset_
;
342 if (def
->type_
!= typeVarchar
)
343 AllDataType::copyVal(def
->bindVal_
, colPtr
, def
->type_
,
346 char *ptr
= (char *) *(long *) colPtr
;
347 if (ptr
!= NULL
) strcpy((char *)def
->bindVal_
, ptr
);
353 void TableImpl::printSQLIndexString(FILE *fp
, int fd
)
355 if (fp
== NULL
) fp
= stdout
;
356 CatalogTableINDEXFIELD
cIndexField(sysDB_
);
357 char fName
[IDENTIFIER_LENGTH
];
358 char idxName
[IDENTIFIER_LENGTH
];
359 char *fldName
= fName
;
361 for (int i
= 0; i
< numIndexes_
; i
++)
363 CINDEX
*iptr
= (CINDEX
*) indexPtr_
[i
];
364 sprintf(idxName
,"%s_idx_Auto_increment",getName());
365 if(strcmp(iptr
->indName_
,idxName
)==0){ continue; }
366 if (Conf::config
.useDurability()) {
368 strcpy(obj
.name
, iptr
->indName_
);
369 if (iptr
->indexType_
== hashIndex
) {
371 obj
.bucketChunk
= ((Chunk
*)iptr
->chunkPtr_
)->getFirstPage();
372 obj
.firstPage
= ((Chunk
*)iptr
->hashNodeChunk_
)->getFirstPage();
373 obj
.curPage
= ((Chunk
*)iptr
->hashNodeChunk_
)->getCurrentPage();
374 } else if (iptr
->indexType_
== treeIndex
) {
376 obj
.firstPage
= ((Chunk
*)iptr
->chunkPtr_
)->getFirstPage();
377 obj
.curPage
= ((Chunk
*)iptr
->chunkPtr_
)->getCurrentPage();
378 long nodes
= ((Chunk
*)iptr
->chunkPtr_
)->getTotalDataNodes();
380 ChunkIterator cIter
= ((Chunk
*)iptr
->chunkPtr_
)->getIterator();
381 obj
.bucketChunk
= cIter
.nextElement();
382 } else obj
.bucketChunk
= NULL
;
386 write(fd
, buf
, sizeof(obj
));
388 fprintf(fp
, "CREATE INDEX %s on %s ( ", iptr
->indName_
, getName());
390 cIndexField
.getFieldInfo(iptr
, fldList
);
391 FieldIterator fIter
= fldList
.getIterator();
392 bool firstFld
= true;
393 while(fIter
.hasElement())
395 FieldDef
*def
= fIter
.nextElement();
396 if (firstFld
) { fprintf(fp
, " %s ", def
->fldName_
); firstFld
= false; }
397 else fprintf(fp
, " ,%s ", def
->fldName_
);
402 if (iptr
->indexType_
== hashIndex
) fprintf(fp
, " HASH ");
403 else if (iptr
->indexType_
== treeIndex
) fprintf(fp
, " TREE ");
404 else fprintf(fp
, " TRIE ");
406 HashIndexInfo
* hInfo
= (HashIndexInfo
*)idxInfo
[i
];
407 if (hInfo
->isUnique
) fprintf(fp
, " UNIQUE");
408 if(hInfo
->noOfBuckets
!= 1009 &&
409 hInfo
->noOfBuckets
!=0) fprintf(fp
, " SIZE %d ",((HashIndexInfo
*) idxInfo
[i
])->noOfBuckets
);
415 void TableImpl::setTableInfo(char *name
, int tblid
, size_t length
,
416 int numFld
, int numIdx
, void *chunk
, void *vcchunk
)
418 strcpy(tblName_
, name
);
422 numIndexes_
= numIdx
;
424 vcChunkPtr_
= vcchunk
;
427 long TableImpl::spaceUsed()
429 Chunk
*chk
= (Chunk
*)chunkPtr_
;
430 long totSize
= chk
->getTotalDataNodes() * chk
->getSize();
431 totSize
= totSize
+ (chk
->totalPages() * sizeof (PageInfo
));
435 int TableImpl::pagesUsed()
437 Chunk
*chk
= (Chunk
*)chunkPtr_
;
438 return chk
->totalPages();
441 List
TableImpl::getFieldNameList()
444 FieldIterator fIter
= fldList_
.getIterator();
445 char fieldName
[IDENTIFIER_LENGTH
];
446 while (fIter
.hasElement())
448 FieldDef
*def
= fIter
.nextElement();
449 Identifier
*elem
= new Identifier();
450 Table::getFieldNameAlone(def
->fldName_
, fieldName
);
451 sprintf(elem
->name
, "%s.%s", getName(), fieldName
);
452 fldNameList
.append(elem
);
456 DbRetVal
TableImpl::close()
458 if (iter
) { iter
->close(); delete iter
; iter
= NULL
; }
459 TableImpl
*fkTbl
=NULL
;
460 ListIterator tblIter
= tblList
.getIterator();
462 while (tblIter
.hasElement()){
463 fkTbl
= (TableImpl
*) tblIter
.nextElement();
467 tblIter
= tblFkList
.getIterator();
469 while (tblIter
.hasElement()){
470 fkTbl
= (TableImpl
*) tblIter
.nextElement();
474 printDebug(DM_Database
,"Closing table handle: %x", this);
477 ListIterator pIter
= predList
.getIterator();
478 while (pIter
.hasElement())
480 PredicateImpl
*pImpl
= (PredicateImpl
*) pIter
.nextElement();
485 logFinest(Conf::logger
, "Closing Table");
489 DbRetVal
TableImpl::takeTableMutex()
491 struct timeval timeout
, timeval
;
492 timeout
.tv_sec
= Conf::config
.getMutexSecs();
493 timeout
.tv_usec
= Conf::config
.getMutexUSecs();
495 int totalTries
= Conf::config
.getMutexRetries() *2;
497 while (tries
< totalTries
)
499 ret
= sysDB_
->getAllocDatabaseMutex();
501 timeval
.tv_sec
= timeout
.tv_sec
;
502 timeval
.tv_usec
= timeout
.tv_usec
;
503 os::select(0, 0, 0, 0, &timeval
);
506 if (tries
>= totalTries
) return ErrLockTimeOut
;
509 DbRetVal
TableImpl::releaseTableMutex()
511 sysDB_
->releaseAllocDatabaseMutex();
515 DbRetVal
TableImpl::lock(bool shared
)
521 ret = lMgr_->getSharedLock(chunkPtr_, NULL);
523 ret = lMgr_->getExclusiveLock(chunkPtr_, NULL);
526 printError(ret, "Could not exclusive lock on the table %x", chunkPtr_);
528 //do not append for S to X upgrade
529 if (!ProcessManager::hasLockList.exists(chunkPtr_))
530 ProcessManager::hasLockList.append(chunkPtr_);
535 DbRetVal
TableImpl::unlock()
538 if (!ProcessManager::hasLockList.exists(chunkPtr_)) return OK;
539 DbRetVal ret = lMgr_->releaseLock(chunkPtr_);
542 printError(ret, "Could not release exclusive lock on the table %x", chunkPtr_);
545 ProcessManager::hasLockList.remove(chunkPtr_);
551 TableImpl::~TableImpl()
553 if (NULL
!= iter
) { delete iter
; iter
= NULL
; }
554 if (NULL
!= indexPtr_
) { delete[] indexPtr_
; indexPtr_
= NULL
; }
557 for (int i
= 0; i
< numIndexes_
; i
++) delete idxInfo
[i
];
561 if (numFlds_
> 32 && cNullInfo
!= NULL
) {
562 free(cNullInfo
); cNullInfo
= NULL
;
564 if (bindList_
.size()) bindList_
.reset();
565 if (bindListArray_
) { free (bindListArray_
); bindListArray_
= NULL
; }
566 fldList_
.removeAll();
570 void *TableImpl::getBindFldAddr(const char *name
)
572 return fldList_
.getBindField(name
);
574 bool TableImpl::isTableInvolved(char *tblName
)
576 //printf("Table isTableInvolved called for %s with %s\n", tblName, getName());
577 if (0 == strcmp(getName(), tblName
)) return true; else return false;
580 void TableImpl::setCondition(Condition
*p
)
582 isPlanCreated
= false;
583 ListIterator pIter
= predList
.getIterator();
584 while (pIter
.hasElement())
586 PredicateImpl
*pImpl
= (PredicateImpl
*) pIter
.nextElement();
591 if (p
) pred_
= p
->getPredicate(); else pred_
= NULL
;
594 void TableImpl::setPredicate(Predicate
*pred
)
596 if (NULL
== pred_
) { pred_
= pred
; return; }
598 Predicate
*curPred
= pred_
;
599 PredicateImpl
*newPred
= new PredicateImpl();
600 newPred
->setTerm(curPred
, OpAnd
, pred
);
601 newPred
->setTable(this);
605 void TableImpl::printPlan(int space
)
607 char spaceBuf
[IDENTIFIER_LENGTH
];
608 memset(spaceBuf
, 32, IDENTIFIER_LENGTH
);
609 spaceBuf
[space
] = '\0';
610 printf("%s <TABLE-NODE>\n", spaceBuf
);
611 printf("%s <NAME> %s </NAME>\n", spaceBuf
, getName());
612 printf("%s <ScanType> %s </ScanType>\n", spaceBuf
, ScanTypeNames
[scanType_
]);
613 PredicateImpl
*pred
= (PredicateImpl
*)pred_
;
614 if (pred
) pred
->print(space
+2);
615 printf("%s </TABLE-NODE>\n", spaceBuf
);
617 void TableImpl::printSQLForeignString()
620 FieldNameList pkFieldList
,fkFieldList
;
623 void *chunkPk
= NULL
;
624 void *vcchunkPk
= NULL
;
625 CatalogTableTABLE
cTable(sysDB_
);
626 TableImpl
*fkTbl
=NULL
;
627 ListIterator tblIter
= tblList
.getIterator();
630 while (tblIter
.hasElement()){
631 fkTbl
= (TableImpl
*) tblIter
.nextElement();
632 rv
= cTable
.getChunkAndTblPtr(fkTbl
->getName(), chunkPk
, tPkptr
,vcchunkPk
);
633 if ( OK
!= rv
){return ;}
634 rv
= cTable
.getChunkAndTblPtr(getName(), chunkPk
, tFkptr
, vcchunkPk
);
635 if ( OK
!= rv
){return ;}
636 CatalogTableFK
cFk(sysDB_
);
637 rv
= cFk
.getPkFkFieldInfo(tPkptr
,tFkptr
,pkFieldList
,fkFieldList
);
638 if ( OK
!= rv
){return;}
639 pkFieldList
.resetIter();
640 fkFieldList
.resetIter();
641 char *fldName
= NULL
;
642 bool firstField
=true;
643 if(!firstFK
) printf(", ");
644 printf(", FOREIGN KEY ( ");
645 while((fldName
= fkFieldList
.nextFieldName())!= NULL
)
648 printf("%s",fldName
);
652 printf(",%s",fldName
);
654 printf(" ) REFERENCES %s ( ",fkTbl
->getName());
656 while((fldName
= pkFieldList
.nextFieldName())!= NULL
)
659 printf("%s",fldName
);
663 printf(",%s",fldName
);
667 pkFieldList
.removeAll();
668 fkFieldList
.removeAll();
672 DbRetVal
TableImpl::compact()
675 int ret
=((Chunk
*)chunkPtr_
)->compact(db_
->procSlot
);
676 if(ret
!=0) return ErrLockTimeOut
;
678 if (NULL
!= vcChunkPtr_
) {
679 ret
= ((Chunk
*)vcChunkPtr_
)->compact(db_
->procSlot
);
680 if(ret
!=0) return ErrLockTimeOut
;
683 if (NULL
!= indexPtr_
)
687 for (i
= 0; i
< numIndexes_
; i
++)
689 rv
= compactIndexNode(indexPtr_
[i
]);
691 printError(rv
, "Error in compacting index Node");
699 DbRetVal
TableImpl::compactIndexNode( void *indexPtr
)
701 CINDEX
*iptr
= (CINDEX
*)indexPtr
;
703 printDebug(DM_Table
, "Inside insertIndexNode type %d", iptr
->indexType_
);
704 if( hashIndex
== (iptr
->indexType_
) )
706 ret1
=((Chunk
*)iptr
->hashNodeChunk_
)->compact(db_
->procSlot
);
708 return ErrLockTimeOut
;
710 }else if (treeIndex
== (iptr
->indexType_
))
712 ret1
=((Chunk
*)iptr
->chunkPtr_
)->compact(db_
->procSlot
);
714 return ErrLockTimeOut
;
716 } else if ( trieIndex
== (iptr
->indexType_
))
718 ret1
=((Chunk
*)iptr
->chunkPtr_
)->compact(db_
->procSlot
);
720 return ErrLockTimeOut
;
722 ret1
=((Chunk
*)iptr
->hashNodeChunk_
)->compact(db_
->procSlot
);
724 return ErrLockTimeOut
;