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<DatabaseManager.h>
18 #include<DatabaseManagerImpl.h>
22 #include<Transaction.h>
23 #include<CatalogTables.h>
31 DatabaseManagerImpl::~DatabaseManagerImpl()
33 //Note:Databases are closed by the session interface
35 ListIterator iter
= tableHandleList
.getIterator();
36 while ((tbl
= (Table
*)iter
.nextElement()) != NULL
) delete tbl
;
37 tableHandleList
.reset();
42 void DatabaseManagerImpl::createLockManager()
44 lMgr_
= new LockManager(systemDatabase_
);
48 void DatabaseManagerImpl::createTransactionManager()
51 tMgr_
= new TransactionManager();
52 tMgr_
->setFirstTrans(systemDatabase_
->getSystemDatabaseTrans(0));
55 void DatabaseManagerImpl::setProcSlot()
57 systemDatabase_
->setProcSlot(procSlot
);
58 db_
->setProcSlot(procSlot
);
60 DbRetVal
DatabaseManagerImpl::openSystemDatabase()
62 DbRetVal rv
= openDatabase(SYSTEMDB
);
63 if (rv
!= OK
) return rv
;
64 systemDatabase_
= db_
;
66 printDebug(DM_Database
, "Opened system database");
67 logFinest(logger
, "Opened system database");
71 DbRetVal
DatabaseManagerImpl::closeSystemDatabase()
74 //make them to point to system database file descriptor
75 //and database pointer
76 db_
= systemDatabase_
;
79 printDebug(DM_Database
, "Closed system database");
80 logFinest(logger
, "Closed System database");
84 DbRetVal
DatabaseManagerImpl::createDatabase(const char *name
, size_t size
)
88 printError(ErrAlready
, "Database is already created");
91 caddr_t rtnAddr
= (caddr_t
) NULL
;
92 shared_memory_id shm_id
= 0;
94 char *startaddr
= (char*)Conf::config
.getMapAddress();
95 shared_memory_key key
= 0;
96 if (0 == strcmp(name
, SYSTEMDB
))
99 key
= Conf::config
.getSysDbKey();
103 startaddr
= startaddr
+ Conf::config
.getMaxSysDbSize();
104 key
= Conf::config
.getUserDbKey();
106 shm_id
= os::shm_create(key
, size
, 0666);
109 if (errno
== EEXIST
) {
110 printError(ErrOS
, "Shared Memory already exists");
112 printError(ErrOS
, "Shared memory create failed");
116 void *shm_ptr
= os::shm_attach(shm_id
, startaddr
, SHM_RND
);
117 rtnAddr
= (caddr_t
) shm_ptr
;
118 if (rtnAddr
< 0 || shm_ptr
== (char*)0xffffffff)
120 printError(ErrOS
, "Shared memory attach returned -ve value %d", rtnAddr
);
123 memset(shm_ptr
, 0, size
);
124 db_
= new Database();
125 printDebug(DM_Database
, "Creating database:%s",name
);
127 //TODO:for user database do not have transtable and processtable mutex
128 db_
->setMetaDataPtr((DatabaseMetaData
*)rtnAddr
);
129 db_
->setDatabaseID(1);
131 db_
->setMaxSize(size
);
132 db_
->setNoOfChunks(0);
133 db_
->initAllocDatabaseMutex();
134 db_
->initTransTableMutex();
135 db_
->initDatabaseMutex();
136 db_
->initProcessTableMutex();
137 db_
->setUniqueChunkID(100);
138 //compute the first page after book keeping information
139 size_t offset
= os::alignLong(sizeof (DatabaseMetaData
));
140 //Only for system db chunk array, trans array and proc array will be there
141 if (0 == strcmp(name
, SYSTEMDB
))
143 offset
= offset
+ os::alignLong( MAX_CHUNKS
* sizeof (Chunk
));
144 offset
= offset
+ os::alignLong( Conf::config
.getMaxProcs() * sizeof(Transaction
));
145 offset
= offset
+ os::alignLong( Conf::config
.getMaxProcs() * sizeof(ThreadInfo
));
147 int multiple
= os::floor(offset
/ PAGE_SIZE
);
148 char *curPage
= (((char*)rtnAddr
) + ((multiple
+ 1) * PAGE_SIZE
));
150 db_
->setCurrentPage(curPage
);
151 db_
->setFirstPage(curPage
);
153 if (0 == strcmp(name
, SYSTEMDB
)) return OK
;
155 /*Allocate new chunk to store hash index nodes
156 Chunk *chunkInfo = createUserChunk(sizeof(HashIndexNode));
157 if (NULL == chunkInfo)
159 printError(ErrSysInternal, "Failed to allocate hash index nodes chunk");
160 return ErrSysInternal;
162 printDebug(DM_Database, "Creating Chunk for storing Hash index nodes %x",
165 db_->setHashIndexChunk(chunkInfo);*/
166 logFinest(logger
, "Created database %s" , name
);
171 DbRetVal
DatabaseManagerImpl::deleteDatabase(const char *name
)
173 shared_memory_id shm_id
= 0;
174 if (0 == strcmp(name
, SYSTEMDB
))
176 shm_id
= os::shm_open(Conf::config
.getSysDbKey(), 100, 0666);
177 os::shmctl(shm_id
, IPC_RMID
);
178 delete systemDatabase_
;
179 systemDatabase_
= NULL
;
181 shm_id
= os::shm_open(Conf::config
.getUserDbKey(), 100, 0666);
182 os::shmctl(shm_id
, IPC_RMID
);
186 logFinest(logger
, "Deleted database %s" , name
);
190 DbRetVal
DatabaseManagerImpl::openDatabase(const char *name
)
192 long size
= Conf::config
.getMaxSysDbSize();
193 char *startaddr
= (char*)Conf::config
.getMapAddress();
194 if (0 == strcmp(name
, SYSTEMDB
))
196 if (NULL
!=systemDatabase_
)
198 printError(ErrAlready
, "System Database already open");
204 if (NULL
==systemDatabase_
)
206 printError(ErrNotOpen
, "System Database not open");
209 size
= Conf::config
.getMaxDbSize();
210 startaddr
= startaddr
+ Conf::config
.getMaxSysDbSize();
214 printError(ErrAlready
, "User Database already open");
217 //system db should be opened before user database files
218 caddr_t rtnAddr
= (caddr_t
) NULL
;
220 shared_memory_id shm_id
= 0;
221 shared_memory_key key
= 0;
223 if (0 == strcmp(name
, SYSTEMDB
))
224 key
= Conf::config
.getSysDbKey();
226 key
= Conf::config
.getUserDbKey();
229 int ret
= ProcessManager::mutex
.getLock(-1, false);
230 //If you are not getting lock ret !=0, it means somebody else is there.
231 //he will close the database.
234 printError(ErrSysInternal
, "Another thread calling open:Wait and then Retry\n");
235 return ErrSysInternal
;
237 void *shm_ptr
= NULL
;
238 bool firstThread
= false;
239 //printf("PRABA::DEBUG:: opendb %d %s\n", ProcessManager::noThreads, name);
240 if (ProcessManager::noThreads
== 0 && 0 == strcmp(name
, SYSTEMDB
)
241 || ProcessManager::noThreads
== 1 && 0 != strcmp(name
, SYSTEMDB
) ) {
242 shm_id
= os::shm_open(key
, size
, 0666);
245 printError(ErrOS
, "Shared memory open failed");
246 ProcessManager::mutex
.releaseLock(-1, false);
249 shm_ptr
= os::shm_attach(shm_id
, startaddr
, SHM_RND
);
250 if (0 == strcmp(name
, SYSTEMDB
))
253 ProcessManager::sysAddr
= (char*) shm_ptr
;
257 ProcessManager::usrAddr
= (char*) shm_ptr
;
260 if (0 == strcmp(name
, SYSTEMDB
))
261 shm_ptr
= ProcessManager::sysAddr
;
263 shm_ptr
= ProcessManager::usrAddr
;
265 ProcessManager::mutex
.releaseLock(-1, false);
268 rtnAddr
= (caddr_t
) shm_ptr
;
270 if (rtnAddr
< 0 || shm_ptr
== (char*)0xffffffff)
272 printError(ErrOS
, "Shared memory attach returned -ve value %x %d", shm_ptr
, errno
);
275 db_
= new Database();
276 db_
->setMetaDataPtr((DatabaseMetaData
*)rtnAddr
);
278 if (firstThread
) ProcessManager::systemDatabase
= db_
;
280 printDebug(DM_Database
, "Opening database: %s", name
);
281 logFinest(logger
, "Opened database %s" , name
);
285 DbRetVal
DatabaseManagerImpl::closeDatabase()
290 //Database is already closed
293 printDebug(DM_Database
, "Closing database: %s",(char*)db_
->getName());
294 //check if this is the last thread to be deregistered
295 int ret
= ProcessManager::mutex
.getLock(-1, false);
296 //If you are not getting lock ret !=0, it means somebody else is there.
297 //he will close the database.
299 //printf("PRABA::FOR DEBUG closedb %d %s\n", ProcessManager::noThreads, (char*)db_->getName());
300 if (ProcessManager::noThreads
== 0 && 0 == strcmp((char*)db_
->getName(), SYSTEMDB
)
301 || ProcessManager::noThreads
== 1 && 0 != strcmp((char*)db_
->getName(), SYSTEMDB
) ) {
302 os::shm_detach((char*)db_
->getMetaDataPtr());
305 ProcessManager::mutex
.releaseLock(-1, false);
306 logFinest(logger
, "Closed database");
311 //Assumes that system database mutex is taken before calling this.
312 Chunk
* DatabaseManagerImpl::createUserChunk(size_t size
)
314 //Allocate new node in system database to store
315 Chunk
*chunk
= getSystemTableChunk(UserChunkTableId
);
317 void *ptr
= chunk
->allocate(systemDatabase_
, &rv
);
320 printError(rv
, "Allocation failed for User chunk catalog table");
323 Chunk
*chunkInfo
= (Chunk
*)ptr
;
324 chunkInfo
->initMutex();
325 if (0 != size
) chunkInfo
->setSize(size
);
326 if (chunkInfo
->allocSize_
> PAGE_SIZE
)
327 chunkInfo
->curPage_
= db_
->getFreePage(chunkInfo
->allocSize_
);
329 chunkInfo
->curPage_
= db_
->getFreePage();
330 if ( NULL
== chunkInfo
->curPage_
)
332 chunkInfo
->destroyMutex();
333 chunk
->free(db_
, ptr
);
334 printError(ErrNoMemory
, "Database full: No space to allocate from database");
337 PageInfo
* firstPageInfo
= ((PageInfo
*)chunkInfo
->curPage_
);
338 if (chunkInfo
->allocSize_
> PAGE_SIZE
)
340 int multiple
= os::floor(chunkInfo
->allocSize_
/ PAGE_SIZE
);
341 int offset
= ((multiple
+ 1) * PAGE_SIZE
);
342 firstPageInfo
->setPageAsUsed(offset
);
346 firstPageInfo
->setPageAsUsed(chunkInfo
->allocSize_
);
347 char *data
= ((char*)firstPageInfo
) + sizeof(PageInfo
);
352 VarSizeInfo
*varInfo
= (VarSizeInfo
*)(((char*)firstPageInfo
) + sizeof(PageInfo
));
353 varInfo
->isUsed_
= 0;
354 varInfo
->size_
= PAGE_SIZE
- sizeof(PageInfo
) - sizeof(VarSizeInfo
);
357 chunkInfo
->firstPage_
= chunkInfo
->curPage_
;
360 chunkInfo
->setAllocType(VariableSizeAllocator
);
362 chunkInfo
->setAllocType(FixedSizeAllocator
);
364 //TODO::Generate chunkid::use tableid
365 chunkInfo
->setChunkID(db_
->getUniqueIDForChunk());
366 db_
->incrementChunk();
367 printDebug(DM_Database
, "Creating new User chunk chunkID:%d size: %d firstPage:%x",
368 -1, chunkInfo
->allocSize_
, firstPageInfo
);
373 //Assumes that system database mutex is taken before calling this.
374 DbRetVal
DatabaseManagerImpl::deleteUserChunk(Chunk
*chunk
)
376 //Go to the pages and set them to notUsed
377 Page
*page
= chunk
->firstPage_
;
378 PageInfo
* pageInfo
= ((PageInfo
*)page
);
379 //Here...sure that atleast one page will be there even no tuples
380 //are inserted.so not checking if pageInfo == NULL
381 while( pageInfo
->nextPage_
!= NULL
)
383 PageInfo
*prev
= pageInfo
;
384 pageInfo
= (PageInfo
*)(pageInfo
->nextPage_
);
385 //sets pageInfo->isUsed_ = 0 and pageInfo->hasFreeSpace_ = 0
386 //and initializes the page content to zero
387 if(NULL
== pageInfo
->nextPageAfterMerge_
)
388 os::memset(prev
, 0, PAGE_SIZE
);
391 int size
= (char*) pageInfo
->nextPageAfterMerge_
- (char*) pageInfo
;
392 os::memset(prev
, 0, size
);
394 printDebug(DM_Database
,"deleting user chunk:%x clearing page %x",chunk
, prev
);
396 //The above loop wont execute for the last page
397 //and for the case where table has only one page
398 if(NULL
== pageInfo
->nextPageAfterMerge_
)
399 os::memset(pageInfo
, 0, PAGE_SIZE
);
402 int size
= (char*) pageInfo
->nextPageAfterMerge_
- (char*) pageInfo
;
403 os::memset(pageInfo
, 0, size
);
405 printDebug(DM_Database
,"deleting user chunk:%x clearing page %x",chunk
, pageInfo
);
406 chunk
->chunkID_
= -1;
407 chunk
->allocSize_
= 0;
408 chunk
->curPage_
= NULL
;
409 chunk
->firstPage_
= NULL
;
410 chunk
->destroyMutex();
411 db_
->decrementChunk();
412 printDebug(DM_Database
,"deleting user chunk:%x",chunk
);
416 //-1 -> Unable to create chunk. No memory
417 //-2 -> Unable to update the catalog tables
418 DbRetVal
DatabaseManagerImpl::createTable(const char *name
, TableDef
&def
)
421 int fldCount
= def
.getFieldCount();
422 //If total field count is less than 32, then 1 integer is used to store all null
423 //information, if it is more then 1 char is used to store null information
425 //This is to done to reduce cpu cycles for small tables
427 if (fldCount
< 31) addSize
= 4; else addSize
= os::align(fldCount
);
428 size_t sizeofTuple
= os::align(def
.getTupleSize())+addSize
;
430 rv
= systemDatabase_
->getDatabaseMutex();
432 printError(rv
, "Unable to get Database mutex");
439 //check whether table already exists
440 CatalogTableTABLE
cTable(systemDatabase_
);
441 cTable
.getChunkAndTblPtr(name
, chunk
, tptr
);
444 systemDatabase_
->releaseDatabaseMutex();
445 printError(ErrAlready
, "Table %s already exists", name
);
449 //create a chunk to store the tuples
450 Chunk
*ptr
= createUserChunk(sizeofTuple
);
453 systemDatabase_
->releaseDatabaseMutex();
454 printError(ErrNoResource
, "Unable to create user chunk");
455 return ErrNoResource
;
457 printDebug(DM_Database
,"Created UserChunk:%x", ptr
);
459 ptr
->setChunkName(name
);
461 int tblID
= ((Chunk
*)ptr
)->getChunkID();
462 rv
= cTable
.insert(name
, tblID
, sizeofTuple
,
463 def
.getFieldCount(), ptr
, tptr
);
466 deleteUserChunk(ptr
);
467 systemDatabase_
->releaseDatabaseMutex();
468 printError(ErrSysInternal
, "Unable to update catalog table TABLE");
469 return ErrSysInternal
;
471 printDebug(DM_Database
,"Inserted into TABLE:%s",name
);
473 FieldIterator iter
= def
.getFieldIterator();
474 CatalogTableFIELD
cField(systemDatabase_
);
475 rv
= cField
.insert(iter
, tblID
,tptr
);
478 deleteUserChunk(ptr
);
479 void *cptr
, *ttptr
;//Dummy as remove below needs both these OUT params
480 cTable
.remove(name
, cptr
, ttptr
);
481 systemDatabase_
->releaseDatabaseMutex();
482 printError(ErrSysInternal
, "Unable to update catalog table FIELD");
483 return ErrSysInternal
;
485 printDebug(DM_Database
,"Inserted into FIELD:%s",name
);
486 systemDatabase_
->releaseDatabaseMutex();
487 printDebug(DM_Database
,"Table Created:%s",name
);
488 logFinest(logger
, "Table Created %s" , name
);
492 //TODO::If any operation fails in between, then we may have some
493 //dangling tuples, say we have have rows in INDEX table
494 //which will not have any corresponding entries in TABLE
495 //CHANGE the sequence so that it deletes from the bottom as
496 //opposed to start from top as is written now
497 DbRetVal
DatabaseManagerImpl::dropTable(const char *name
)
501 DbRetVal rv
= systemDatabase_
->getDatabaseMutex();
503 printError(ErrSysInternal
, "Unable to get database mutex");
504 return ErrSysInternal
;
507 //remove the entry in TABLE
508 CatalogTableTABLE
cTable(systemDatabase_
);
509 rv
= cTable
.getChunkAndTblPtr(name
, chunk
, tptr
);
511 systemDatabase_
->releaseDatabaseMutex();
512 printError(ErrSysInternal
, "Table %s does not exist", name
);
513 return ErrSysInternal
;
515 rv
= lMgr_
->getExclusiveLock(chunk
, NULL
);
518 systemDatabase_
->releaseDatabaseMutex();
519 printError(ErrLockTimeOut
, "Unable to acquire exclusive lock on the table\n");
523 rv
= cTable
.remove(name
, chunk
, tptr
);
525 systemDatabase_
->releaseDatabaseMutex();
526 printError(ErrSysInternal
, "Unable to update catalog table TABLE");
527 return ErrSysInternal
;
529 printDebug(DM_Database
,"Deleted from TABLE:%s",name
);
531 //remove the entries in the FIELD table
532 CatalogTableFIELD
cField(systemDatabase_
);
533 rv
= cField
.remove(tptr
);
535 systemDatabase_
->releaseDatabaseMutex();
536 printError(ErrSysInternal
, "Unable to update catalog table FIELD");
537 return ErrSysInternal
;
539 printDebug(DM_Database
,"Deleted from FIELD:%s",name
);
541 rv
= deleteUserChunk((Chunk
*)chunk
);
543 systemDatabase_
->releaseDatabaseMutex();
544 printError(rv
, "Unable to delete the chunk");
547 printDebug(DM_Database
,"Deleted UserChunk:%x", chunk
);
549 //TODO::check whether indexes are available and drop that also.
550 CatalogTableINDEX
cIndex(systemDatabase_
);
551 int noIndexes
= cIndex
.getNumIndexes(tptr
);
552 for (int i
=1 ; i
<= noIndexes
; i
++) {
553 char *idxName
= cIndex
.getIndexName(tptr
, 1);
554 dropIndexInt(idxName
, false);
556 Chunk
*chunkNode
= systemDatabase_
->getSystemDatabaseChunk(UserChunkTableId
);
557 chunkNode
->free(systemDatabase_
, (Chunk
*) chunk
);
558 systemDatabase_
->releaseDatabaseMutex();
559 printDebug(DM_Database
, "Deleted Table %s" , name
);
560 logFinest(logger
, "Deleted Table %s" , name
);
561 rv
= lMgr_
->releaseLock(chunk
);
564 printError(ErrLockTimeOut
, "Unable to release exclusive lock on the table\n");
570 //Return values: NULL for table not found
571 Table
* DatabaseManagerImpl::openTable(const char *name
)
574 //TODO::store table handles in list so that if it is
575 //not closed by the application. destructor shall close it.
576 TableImpl
*table
= new TableImpl();
578 table
->setSystemDB(systemDatabase_
);
579 table
->setLockManager(lMgr_
);
580 table
->setTrans(ProcessManager::getThreadTransAddr(systemDatabase_
->procSlot
));
582 //to store the chunk pointer of table
585 //to store the tuple pointer of the table
588 //TODO::need to take shared lock on the table so that
589 //all ddl operation will be denied on that table
590 //which includes index creation, alter table
592 DbRetVal rv
= systemDatabase_
->getDatabaseMutex();
594 printError(ErrSysInternal
, "Unable to get database mutex");
598 CatalogTableTABLE
cTable(systemDatabase_
);
599 ret
= cTable
.getChunkAndTblPtr(name
, chunk
, tptr
);
602 systemDatabase_
->releaseDatabaseMutex();
604 printError(ErrNotExists
, "Table not exists %s", name
);
607 TABLE
*tTuple
= (TABLE
*)tptr
;
608 table
->setTableInfo(tTuple
->tblName_
, tTuple
->tblID_
, tTuple
->length_
,
609 tTuple
->numFlds_
, tTuple
->numIndexes_
, tTuple
->chunkPtr_
);
610 /*rv = table->lock(true); //take shared lock
613 printError(ErrLockTimeOut, "Unable to acquire shared lock on the table\n");
614 systemDatabase_->releaseDatabaseMutex();
620 if (tTuple
->numFlds_
< 31)
622 table
->isIntUsedForNULL
= true;
623 table
->iNullInfo
= 0;
624 table
->iNotNullInfo
=0;
628 table
->isIntUsedForNULL
= false;
629 int noFields
= os::align(tTuple
->numFlds_
);
630 table
->cNullInfo
= (char*) malloc(noFields
);
631 table
->cNotNullInfo
= (char*) malloc(noFields
);
632 for (int i
=0 ; i
< noFields
; i
++) table
->cNullInfo
[i
] =0;
633 for (int i
=0 ; i
< noFields
; i
++) table
->cNotNullInfo
[i
] =0;
637 //get field information from FIELD table
638 CatalogTableFIELD
cField(systemDatabase_
);
639 cField
.getFieldInfo(tptr
, table
->fldList_
);
641 //populate the notnull info
642 FieldIterator fIter
= table
->fldList_
.getIterator();
644 while (fIter
.hasElement())
646 FieldDef def
= fIter
.nextElement();
647 if (table
->isIntUsedForNULL
) {
648 if (def
.isNull_
) SETBIT(table
->iNotNullInfo
, fldpos
);
651 if (def
.isNull_
) table
->cNotNullInfo
[fldpos
-1] = 1;
656 //get the number of indexes on this table
657 //and populate the indexPtr array
658 CatalogTableINDEX
cIndex(systemDatabase_
);
659 table
->numIndexes_
= cIndex
.getNumIndexes(tptr
);
660 if (table
->numIndexes_
) {
661 table
->indexPtr_
= new char*[table
->numIndexes_
];
662 table
->idxInfo
= new IndexInfo
*[table
->numIndexes_
];
666 table
->indexPtr_
= NULL
;
668 cIndex
.getIndexPtrs(tptr
, table
->indexPtr_
);
669 for (int i
=0 ; i
< table
->numIndexes_
; i
++ )
671 HashIndexInfo
*hIdxInfo
= new HashIndexInfo();
672 CatalogTableINDEXFIELD
cIndexField(systemDatabase_
);
673 cIndexField
.getFieldInfo(table
->indexPtr_
[i
], hIdxInfo
->idxFldList
);
674 ChunkIterator citer
= CatalogTableINDEX::getIterator(table
->indexPtr_
[i
]);
675 hIdxInfo
->indexPtr
= table
->indexPtr_
[i
];
676 hIdxInfo
->noOfBuckets
= CatalogTableINDEX::getNoOfBuckets(table
->indexPtr_
[i
]);
677 FieldIterator fIter
= hIdxInfo
->idxFldList
.getIterator();
678 bool firstFld
= true;
679 while (fIter
.hasElement())
681 FieldDef def
= fIter
.nextElement();
684 hIdxInfo
->fldOffset
= table
->fldList_
.getFieldOffset(def
.fldName_
);
685 hIdxInfo
->type
= table
->fldList_
.getFieldType(def
.fldName_
);
686 hIdxInfo
->compLength
= table
->fldList_
.getFieldLength(def
.fldName_
);
689 hIdxInfo
->type
= typeComposite
;
690 hIdxInfo
->compLength
= hIdxInfo
->compLength
+
691 table
->fldList_
.getFieldLength(def
.fldName_
);
695 hIdxInfo
->isUnique
= CatalogTableINDEX::getUnique(table
->indexPtr_
[i
]);
696 hIdxInfo
->buckets
= (Bucket
*)citer
.nextElement();
697 table
->idxInfo
[i
] = (IndexInfo
*) hIdxInfo
;
699 systemDatabase_
->releaseDatabaseMutex();
700 // lMgr-> tTuple->chunkPtr_
701 printDebug(DM_Database
,"Opening table handle name:%s chunk:%x numIndex:%d",
702 name
, chunk
, table
->numIndexes_
);
703 logFinest(logger
, "Opening Table %s" , name
);
705 tableHandleList
.append(table
);
712 List
DatabaseManagerImpl::getAllTableNames()
715 //to store the tuple pointer of the table
718 DbRetVal rv
= systemDatabase_
->getDatabaseMutex();
720 printError(ErrSysInternal
, "Unable to get database mutex");
724 CatalogTableTABLE
cTable(systemDatabase_
);
725 List tableList
= cTable
.getTableList();
726 systemDatabase_
->releaseDatabaseMutex();
733 //Return values: -1 for table not found
734 void DatabaseManagerImpl::closeTable(Table
*table
)
736 printDebug(DM_Database
,"Closing table handle: %x", table
);
737 if (NULL
== table
) return;
739 tableHandleList
.remove(table
, false);
740 logFinest(logger
, "Closing Table");
743 DbRetVal
DatabaseManagerImpl::createIndex(const char *indName
, IndexInitInfo
*info
)
746 if (!info
->isUnique
&& info
->isPrimary
)
748 printError(ErrBadCall
, "Primary key cannot be non unique\n");
751 if (info
->indType
== hashIndex
)
753 //Assumes info is of type HashIndexInitInfo
754 HashIndexInitInfo
*hInfo
= (HashIndexInitInfo
*) info
;
755 rv
= createHashIndex(indName
, info
->tableName
, info
->list
, hInfo
->bucketSize
,
756 info
->isUnique
, info
->isPrimary
);
758 else if (info
->indType
== treeIndex
)
761 printError(ErrNotYet
, "Tree Index not supported\n");
764 printError(ErrBadCall
, "Index type not supported\n");
771 //-1 -> Table does not exists
772 //-2 -> Field does not exists
773 //-3 -> bucketSize is not valid
774 DbRetVal
DatabaseManagerImpl::createHashIndex(const char *indName
, const char *tblName
,
775 FieldNameList
&fldList
, int bucketSize
, bool isUnique
, bool isPrimary
)
777 //validate the bucket size
778 if (bucketSize
< 100 || bucketSize
> 200000)
780 printError(ErrBadRange
, "Index Bucket size %d not in range 100-200000",
784 int totFlds
= fldList
.size();
787 printError(ErrBadCall
, "No Field name specified");
792 DbRetVal rv
= systemDatabase_
->getDatabaseMutex();
795 printError(ErrSysInternal
, "Unable to get database mutex");
796 return ErrSysInternal
;
799 //check whether table exists
800 CatalogTableTABLE
cTable(systemDatabase_
);
801 cTable
.getChunkAndTblPtr(tblName
, chunk
, tptr
);
804 systemDatabase_
->releaseDatabaseMutex();
805 printError(ErrNotExists
, "Table does not exist %s", tblName
);
809 //check whether field exists
810 char **fptr
= new char* [totFlds
];
811 CatalogTableFIELD
cField(systemDatabase_
);
812 rv
= cField
.getFieldPtrs(fldList
, tptr
, fptr
);
816 systemDatabase_
->releaseDatabaseMutex();
817 //TODO::check test cases of dbapi/Index, they give wrong results
818 //if (rv == ErrBadCall) {
819 //// if (isPrimary) printError(ErrBadCall, "Field can have NULL values");
821 //printError(ErrNotExists, "Field does not exist");
824 if (rv
!= ErrBadCall
) {
825 printError(ErrNotExists
, "Field does not exist");
829 for (int i
=0; i
<totFlds
; i
++)
831 FIELD
* fInfo
= (FIELD
*)fptr
[i
];
832 if (fInfo
->type_
== typeFloat
|| fInfo
->type_
== typeDouble
|| fInfo
->type_
== typeTimeStamp
)
834 printError(ErrBadArg
, "HashIndex cannot be created for float or double or timestamp type");
836 systemDatabase_
->releaseDatabaseMutex();
839 if (!fInfo
->isNull_
&& isPrimary
)
841 printError(ErrBadArg
, "Primary Index cannot be created on field without NOTNULL constraint");
843 systemDatabase_
->releaseDatabaseMutex();
847 //create chunk to store the meta data of the index created
848 //for latches and bucket pointers
849 printDebug(DM_HashIndex
, "Creating chunk for storing hash buckets of size %d\n",
850 bucketSize
* sizeof(Bucket
));
851 Chunk
* chunkInfo
= createUserChunk(bucketSize
* sizeof(Bucket
));
852 if (NULL
== chunkInfo
)
855 systemDatabase_
->releaseDatabaseMutex();
856 printError(ErrSysInternal
, "Unable to create chunk");
857 return ErrSysInternal
;
859 chunkInfo
->setChunkName(indName
);
860 //create memory for holding the bucket pointers
861 void *buckets
= chunkInfo
->allocate(db_
, &rv
);
865 deleteUserChunk(chunkInfo
);
866 systemDatabase_
->releaseDatabaseMutex();
867 printError(rv
, "Unable to allocate memory for bucket");
870 Bucket
*buck
= (Bucket
*) buckets
;
871 initHashBuckets(buck
, bucketSize
);
873 //create chunk to store the hash index nodes
874 Chunk
* hChunk
= createUserChunk(sizeof(HashIndexNode
));
878 deleteUserChunk(chunkInfo
);
879 systemDatabase_
->releaseDatabaseMutex();
880 printError(ErrSysInternal
, "Unable to create chunk for storing hash index nodes");
881 return ErrSysInternal
;
883 hChunk
->setChunkName(indName
);
885 void *tupleptr
= NULL
;
886 CatalogTableINDEX
cIndex(systemDatabase_
);
887 rv
= cIndex
.insert(indName
, tptr
, fldList
.size(), isUnique
,
888 chunkInfo
, bucketSize
, hChunk
, tupleptr
);
892 deleteUserChunk(hChunk
);
893 deleteUserChunk(chunkInfo
);
894 systemDatabase_
->releaseDatabaseMutex();
895 printError(ErrSysInternal
, "Catalog table updation failed in INDEX table");
896 return ErrSysInternal
;
898 //add rows to INDEXFIELD
899 CatalogTableINDEXFIELD
cIndexField(systemDatabase_
);
900 rv
= cIndexField
.insert(fldList
, tupleptr
, tptr
, fptr
);
905 cIndex
.remove(indName
, (void *&)chunkInfo
, (void *&)hChunk
, (void *&)tupleptr
);
906 deleteUserChunk(hChunk
);
907 deleteUserChunk(chunkInfo
);
908 systemDatabase_
->releaseDatabaseMutex();
909 printError(ErrSysInternal
, "Catalog table updation failed in INDEXFIELD table");
910 return ErrSysInternal
;
913 systemDatabase_
->releaseDatabaseMutex();
915 //TODO:: Take table lock
917 // Following code is written by Kishor Amballi
918 TableImpl
*tbl
= (TableImpl
*) openTable(tblName
);
919 if (! tbl
->numTuples()) {
920 printDebug(DM_Database
, "Creating Hash Index Name:%s tblname:%s buckets:%x", indName
, tblName
, buckets
);
921 logFinest(logger
, "Creating HashIndex %s on %s with bucket size %d", indName
, tblName
, buckets
);
924 HashIndexInfo
*indxInfo
= NULL
;
926 for (i
= 0; i
< tbl
->numIndexes_
; i
++) {
927 if(((HashIndexInfo
*)tbl
->idxInfo
[i
])->indexPtr
== tupleptr
) {
928 indxInfo
= (HashIndexInfo
*) tbl
->idxInfo
[i
];
933 ChunkIterator chIter
= ((Chunk
*)chunk
)->getIterator();
934 while ((recPtr
= chIter
.nextElement()) != NULL
) {
935 rv
= tbl
->insertIndexNode(*tbl
->trans
, tupleptr
, indxInfo
, recPtr
);
936 if (rv
== ErrUnique
) {
943 printDebug(DM_Database
, "Creating Hash Index Name:%s tblname:%s buckets:%x", indName
, tblName
, buckets
);
944 logFinest(logger
, "Creating HashIndex %s on %s with bucket size %d", indName
, tblName
, buckets
);
948 void DatabaseManagerImpl::initHashBuckets(Bucket
*buck
, int bucketSize
)
950 os::memset((void*)buck
, 0, bucketSize
* sizeof(Bucket
));
952 for (int i
=0; i
< bucketSize
; i
++)
954 buck
[i
].mutex_
.init("Bucket");
959 DbRetVal
DatabaseManagerImpl::dropIndex(const char *name
)
961 return dropIndexInt(name
, true);
964 DbRetVal
DatabaseManagerImpl::dropIndexInt(const char *name
, bool takeLock
)
967 void *chunk
= NULL
, *hchunk
= NULL
;
971 rv
= systemDatabase_
->getDatabaseMutex();
974 printError(ErrSysInternal
, "Unable to get database mutex");
975 return ErrSysInternal
;
979 //remove the entry in INDEX
980 CatalogTableINDEX
cIndex(systemDatabase_
);
981 rv
= cIndex
.remove(name
, chunk
, hchunk
, tptr
);
984 if (takeLock
) systemDatabase_
->releaseDatabaseMutex();
985 printError(ErrSysInternal
, "Catalog table updation failed for INDEX table");
986 return ErrSysInternal
;
988 printDebug(DM_Database
, "Removing from INDEX %s",name
);
989 //remove the entries in the INDEXFIELD table
990 CatalogTableINDEXFIELD
cIndexField(systemDatabase_
);
991 rv
= cIndexField
.remove(tptr
);
994 if (takeLock
) systemDatabase_
->releaseDatabaseMutex();
995 printError(ErrSysInternal
, "Catalog table updation failed for INDEX table");
996 return ErrSysInternal
;
998 printDebug(DM_Database
, "Removing from INDEXFIELD %s",name
);
1000 //delete the index chunk
1001 rv
= deleteUserChunk((Chunk
*)chunk
);
1004 if (takeLock
) systemDatabase_
->releaseDatabaseMutex();
1005 printError(ErrSysInternal
, "Unable to delete the index chunk");
1006 return ErrSysInternal
;
1008 //delete the index hash node chunk
1009 rv
= deleteUserChunk((Chunk
*)hchunk
);
1012 if (takeLock
) systemDatabase_
->releaseDatabaseMutex();
1013 printError(ErrSysInternal
, "Unable to delete the index hash node chunk");
1014 return ErrSysInternal
;
1016 if (takeLock
) systemDatabase_
->releaseDatabaseMutex();
1017 Chunk
*chunkNode
= systemDatabase_
->getSystemDatabaseChunk(UserChunkTableId
);
1018 chunkNode
->free(systemDatabase_
, (Chunk
*) chunk
);
1019 chunkNode
->free(systemDatabase_
, (Chunk
*) hchunk
);
1021 //TODO::If tuples present in this table, then
1022 //free all hash index nodes for this table.
1023 //free all nodes in list of all buckets
1026 printDebug(DM_Database
, "Dropped hash index %s",name
);
1027 logFinest(logger
, "Deleted Index %s", name
);
1030 DbRetVal
DatabaseManagerImpl::printIndexInfo(char *name
)
1032 CatalogTableINDEX
cIndex(systemDatabase_
);
1034 void *chunk
= NULL
, *hchunk
= NULL
;
1036 rv
= cIndex
.get(name
, chunk
, hchunk
, tptr
);
1037 if (OK
!= rv
) return rv
;
1038 printf("<IndexName> %s </IndexName>\n", name
);
1039 printf("<Unique> %d </Unique>\n", CatalogTableINDEX::getUnique(tptr
));
1040 Chunk
*ch
= (Chunk
*) chunk
;
1041 printf("<HashBucket>\n");
1042 printf(" <TotalPages> %d </TotalPages>\n", ch
->totalPages());
1043 printf(" <TotalBuckets> %d </TotalBuckets> \n", CatalogTableINDEX::getNoOfBuckets(tptr
));
1044 printf("</HashBucket>\n");
1046 ch
= (Chunk
*) hchunk
;
1047 printf("<IndexNodes>\n");
1048 printf(" <TotalPages> %d </TotalPages>\n", ch
->totalPages());
1049 printf(" <TotalNodes> %d </TotalNodes>\n", ch
->getTotalDataNodes());
1050 printf("<IndexNodes>\n");
1054 DbRetVal
DatabaseManagerImpl::registerThread()
1059 printError(ErrAlready
, "Process already registered\n");
1062 pMgr_
= new ProcessManager();
1063 rv
= pMgr_
->registerThread();
1064 if (rv
==OK
) { procSlot
= pMgr_
->getProcSlot();
1065 printDebug(DM_Process
, "Process registed with slot %d\n", procSlot
);
1070 DbRetVal
DatabaseManagerImpl::deregisterThread()
1075 rv
= pMgr_
->deregisterThread(procSlot
);
1082 bool DatabaseManagerImpl::isAnyOneRegistered()
1084 if (pMgr_
!= NULL
) return pMgr_
->isAnyOneRegistered();
1089 void DatabaseManagerImpl::printUsageStatistics()
1091 pMgr_
->printUsageStatistics();
1092 tMgr_
->printUsageStatistics();
1093 lMgr_
->printUsageStatistics();
1096 void DatabaseManagerImpl::printDebugLockInfo()
1098 lMgr_
->printDebugInfo();
1101 void DatabaseManagerImpl::printDebugTransInfo()
1103 tMgr_
->printDebugInfo(systemDatabase_
);
1105 void DatabaseManagerImpl::printDebugProcInfo()
1107 pMgr_
->printDebugInfo();
1109 void DatabaseManagerImpl::printDebugChunkInfo()
1111 printf("<NotYetImplemented> </NotYetImplemented>\n");
1113 ChunkIterator
DatabaseManagerImpl::getSystemTableIterator(CatalogTableID id
)
1115 Chunk
*fChunk
= systemDatabase_
->getSystemDatabaseChunk(id
);
1116 return fChunk
->getIterator();
1119 Chunk
* DatabaseManagerImpl::getSystemTableChunk(CatalogTableID id
)
1121 return systemDatabase_
->getSystemDatabaseChunk(id
);