changing lock bucket size
[csql.git] / src / storage / DatabaseManagerImpl.cxx
blobe43a0aa15571d4fe16858d0712032622da601280
1 /***************************************************************************
2 * Copyright (C) 2007 by www.databasecache.com *
3 * Contact: praba_tuty@databasecache.com *
4 * *
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. *
9 * *
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. *
14 * *
15 ***************************************************************************/
16 #include<Database.h>
17 #include<DatabaseManager.h>
18 #include<DatabaseManagerImpl.h>
19 #include<os.h>
20 #include<Table.h>
21 #include<TableImpl.h>
22 #include<Transaction.h>
23 #include<CatalogTables.h>
24 #include<Index.h>
25 #include<Lock.h>
26 #include<Debug.h>
27 #include<Config.h>
28 #include<TableConfig.h>
29 #include<Process.h>
32 DatabaseManagerImpl::~DatabaseManagerImpl()
34 //Note:Databases are closed by the session interface
35 delete tMgr_;
36 delete lMgr_;
39 void DatabaseManagerImpl::createLockManager()
41 lMgr_ = new LockManager(systemDatabase_);
42 return;
45 void DatabaseManagerImpl::createTransactionManager()
48 tMgr_ = new TransactionManager();
49 tMgr_->setFirstTrans(systemDatabase_->getSystemDatabaseTrans(0));
50 return;
52 void DatabaseManagerImpl::setProcSlot()
54 systemDatabase_->setProcSlot(procSlot);
55 db_->setProcSlot(procSlot);
57 DbRetVal DatabaseManagerImpl::openSystemDatabase()
59 DbRetVal rv = openDatabase(SYSTEMDB);
60 if (rv != OK) return rv;
61 systemDatabase_ = db_;
62 db_ = NULL;
63 printDebug(DM_Database, "Opened system database");
64 return OK;
67 DbRetVal DatabaseManagerImpl::closeSystemDatabase()
69 Database *db = db_;
70 //make them to point to system database file descriptor
71 //and database pointer
72 db_ = systemDatabase_;
73 closeDatabase();
74 db_ = db;
75 printDebug(DM_Database, "Closed system database");
76 return OK;
79 DbRetVal DatabaseManagerImpl::createDatabase(const char *name, size_t size)
81 bool isMmapNeeded = Conf::config.useMmap();
82 /*
83 if (isMmapNeeded && !Conf::config.useDurability()) {
84 printError(ErrBadArg, "If MMAP is set to true. Durability must be true.");
85 return ErrBadArg;
88 file_desc fd = (file_desc)-1;
89 char cmd[1024];
90 char dbMapFile[MAX_FILE_LEN];
91 struct stat st;
92 long fixAddr = 399998976L;
93 bool firstTimeServer = false;
94 if (NULL != db_ )
96 printError(ErrAlready, "Database is already created");
97 return ErrAlready;
99 caddr_t rtnAddr = (caddr_t) NULL;
100 void *mapAddr = NULL;
101 shared_memory_id shm_id = 0;
103 char *startaddr = (char*)Conf::config.getMapAddress();
104 shared_memory_key key = 0;
105 if (0 == strcmp(name, SYSTEMDB))
108 key = Conf::config.getSysDbKey();
110 else
112 startaddr = startaddr + Conf::config.getMaxSysDbSize();
113 key = Conf::config.getUserDbKey();
115 if (!isMmapNeeded || (isMmapNeeded && 0 == strcmp(name, SYSTEMDB))) {
116 shm_id = os::shm_create(key, size, 0660);
117 if (-1 == shm_id) {
118 if (errno == EEXIST)
119 #if (defined MMDB && defined EMBED)
120 printError(ErrOS, "One application is already running.");
121 return ErrOS;
122 #else
123 printError(ErrOS, "Shared Memory already exists");
124 #endif
125 printError(ErrOS, "Shared memory create failed");
126 exit(0);
128 } else {
129 //switch the checkpoint
130 if (Database::getCheckpointID() == 0)
131 Database::setCheckpointID(1);
132 else
133 Database::setCheckpointID(0);
134 int chkptID=Database::getCheckpointID();
137 sprintf(dbMapFile, "%s/db.chkpt.data%d", Conf::config.getDbFile(), chkptID);
138 /*if (FILE *file = fopen(dbMapFile, "r")) {
139 fclose(file);
140 sprintf(cmd, "cp %s %s/db.chkpt.data", dbMapFile, Conf::config.getDbFile());
141 int ret = system(cmd);
142 if (ret != 0) {
143 printError(ErrOS, "could not copy data file to map file");
144 return ErrOS;
147 sprintf(dbMapFile, "%s/db.chkpt.data", Conf::config.getDbFile());
151 fd = os::openFile(dbMapFile, fileOpenCreat, 0660);
152 if ((file_desc) -1 == fd) {
153 printError(ErrOS, "Mmap file could not be opened");
154 return ErrOS;
156 if(::stat(dbMapFile, &st) == -1) {
157 printf("Unable to retrieve the db File data\n");
158 os::closeFile(fd);
159 db_->setChkptfd((file_desc)-1);
160 return ErrOS;
162 #ifdef WINNT
163 int localfd = os::open(dbMapFile, fileOpenCreat,0);
164 #else
165 int localfd = fd;
166 #endif
167 if (st.st_size == 0 || st.st_size < size) {
168 firstTimeServer = true;
169 off_t flSize = os::lseek(localfd, size - 1, SEEK_SET);
171 char *a = "0";
172 int wSize = os::write(localfd, a, 1);
173 #ifdef WINNT
174 os::close(localfd);
175 #endif
176 mapAddr = os::mmap((void *)(fixAddr + Conf::config.getMaxSysDbSize()), size,
177 mapProtRead | mapProtWrite, mapFixed | mapShared, fd, 0);
178 rtnAddr = (caddr_t) mapAddr;
179 printDebug(DM_Database, "Mapped db file address = %x", mapAddr);
181 void *shm_ptr = NULL;
182 if (!isMmapNeeded || isMmapNeeded && 0 == strcmp(name, SYSTEMDB)) {
183 shm_ptr = os::shm_attach(shm_id, startaddr, SHM_RND);
184 rtnAddr = (caddr_t) shm_ptr;
185 if (rtnAddr < 0 || shm_ptr == (char*)0xffffffff)
187 printError(ErrOS, "Shared memory attach returned -ve value %d", rtnAddr);
188 return ErrOS;
190 # if (defined MMDB && defined EMBED)
191 if (0 == strcmp(name, SYSTEMDB)) ProcessManager::sysAddr = rtnAddr;
192 else ProcessManager::usrAddr = rtnAddr;
193 # endif
195 db_ = new Database();
196 printDebug(DM_Database, "Creating database:%s",name);
198 /*if (!isMmapNeeded || isMmapNeeded && 0 == strcmp(name, SYSTEMDB)) {
199 memset(shm_ptr, 0, size );
202 //TODO:for user database do not have transtable and processtable mutex
203 db_->setMetaDataPtr((DatabaseMetaData*)rtnAddr);
204 db_->setDatabaseID(1);
205 db_->setName(name);
206 db_->setMaxSize(size);
207 db_->setNoOfChunks(0);
208 db_->initAllocDatabaseMutex();
209 db_->initTransTableMutex();
210 db_->initCheckpointMutex();
211 db_->initProcessTableMutex();
212 db_->initPrepareStmtMutex();
213 db_->setUniqueChunkID(100);
214 //compute the first page after book keeping information
215 size_t offset = os::alignLong(sizeof (DatabaseMetaData));
216 //Only for system db chunk array, trans array and proc array will be there
217 if (0 == strcmp(name, SYSTEMDB))
219 db_->setCanTakeCheckPoint(true);
220 offset = offset + os::alignLong( MAX_CHUNKS * sizeof (Chunk));
221 offset = offset + os::alignLong( Conf::config.getMaxProcs() * sizeof(Transaction));
222 offset = offset + os::alignLong( Conf::config.getMaxProcs() * sizeof(ThreadInfo));
224 int multiple = os::floor(offset / PAGE_SIZE);
225 char *curPage = (((char*)rtnAddr) + ((multiple + 1) * PAGE_SIZE));
227 db_->setCurrentPage(curPage);
228 db_->setFirstPage(curPage);
230 if (0 == strcmp(name, SYSTEMDB)) return OK;
232 /*Allocate new chunk to store hash index nodes
233 Chunk *chunkInfo = createUserChunk(sizeof(IndexNode));
234 if (NULL == chunkInfo)
236 printError(ErrSysInternal, "Failed to allocate hash index nodes chunk");
237 return ErrSysInternal;
239 printDebug(DM_Database, "Creating Chunk for storing Hash index nodes %x",
240 chunkInfo);
242 db_->setHashIndexChunk(chunkInfo);*/
243 return OK;
246 DbRetVal DatabaseManagerImpl::deleteDatabase(const char *name)
248 shared_memory_id shm_id = 0;
249 if (0 == strcmp(name, SYSTEMDB))
251 shm_id = os::shm_open(Conf::config.getSysDbKey(), 100, 0660);
252 os::shm_remove(shm_id);
253 delete systemDatabase_;
254 systemDatabase_ = NULL;
255 } else {
256 shm_id = os::shm_open(Conf::config.getUserDbKey(), 100, 0660);
257 os::shm_remove(shm_id);
258 delete db_;
259 db_ = NULL;
261 return OK;
264 DbRetVal DatabaseManagerImpl::openDatabase(const char *name)
266 bool isMmapNeeded = Conf::config.useMmap();
267 char dbMapFile[1024];
268 file_desc fd = (file_desc)-1;
269 long size = Conf::config.getMaxSysDbSize();
270 char *startaddr = (char*)Conf::config.getMapAddress();
271 long fixAddr = 399998976L;
272 if (0 == strcmp(name , SYSTEMDB))
274 if (NULL !=systemDatabase_)
276 printError(ErrAlready, "System Database already open");
277 return ErrAlready;
280 else
282 if (NULL ==systemDatabase_)
284 printError(ErrNotOpen, "System Database not open");
285 return ErrNotOpen;
287 size = Conf::config.getMaxDbSize();
288 startaddr = startaddr + Conf::config.getMaxSysDbSize();
289 fixAddr += Conf::config.getMaxSysDbSize();
291 if (NULL != db_)
293 printError(ErrAlready, "User Database already open");
294 return ErrAlready;
296 //system db should be opened before user database files
297 caddr_t rtnAddr = (caddr_t) NULL;
299 shared_memory_id shm_id = 0;
300 shared_memory_key key = 0;
302 if (0 == strcmp(name, SYSTEMDB))
303 key = Conf::config.getSysDbKey();
304 else
305 key = Conf::config.getUserDbKey();
308 void *shm_ptr = NULL;
309 void *mapAddr = NULL;
310 bool firstThread = false;
311 if ( ( ProcessManager::noThreads == 0 && 0 == strcmp(name, SYSTEMDB) ||
312 ProcessManager::noThreads == 1 && 0 != strcmp(name, SYSTEMDB) ) )
314 if(isMmapNeeded && 0 != strcmp(name, SYSTEMDB)){
315 //: Attach to Map File
316 int curChkptID = Database::getCheckpointID();
317 sprintf(dbMapFile, "%s/db.chkpt.data%d", Conf::config.getDbFile(),
318 curChkptID);
319 fd = os::openFile(dbMapFile, fileOpenReadWrite, 0660);
320 if ((file_desc)-1 == fd) {
321 printError(ErrOS, "Mmap file could not be opened");
322 return ErrOS;
324 mapAddr = os::mmap((void *)fixAddr, size, mapProtRead | mapProtWrite,
325 mapFixed | mapShared, fd, 0);
327 shm_ptr= (caddr_t) mapAddr;
328 printDebug(DM_Database, "Mapped db file address = %x", mapAddr);
329 }else
331 shm_id = os::shm_open(key, size, 0660);
332 if (shm_id == -1 )
334 printError(ErrOS, "Shared memory open failed");
335 return ErrOS;
337 shm_ptr = os::shm_attach(shm_id, startaddr, SHM_RND);
339 if (0 == strcmp(name, SYSTEMDB))
341 firstThread = true;
342 ProcessManager::sysAddr = (char*) shm_ptr;
344 else
346 ProcessManager::usrAddr = (char*) shm_ptr;
348 } else {
349 if (0 == strcmp(name, SYSTEMDB)) shm_ptr = ProcessManager::sysAddr;
350 else shm_ptr = ProcessManager::usrAddr;
354 rtnAddr = (caddr_t) shm_ptr;
355 #if defined (x86_64)
356 if (rtnAddr < 0 || shm_ptr == (char*)0xffffffffffffffff)
358 printError(ErrOS, "Shared memory attach returned -ve value %x %d", shm_ptr, errno);
359 return ErrOS;
361 #else
362 if (rtnAddr < 0 || shm_ptr == (char*)0xffffffff)
364 printError(ErrOS, "Shared memory attach returned -ve value %x %d", shm_ptr, errno);
365 return ErrOS;
367 #endif
369 db_ = new Database();
370 db_->setMetaDataPtr((DatabaseMetaData*)rtnAddr);
371 db_->setChkptfd(fd);
373 if (firstThread) ProcessManager::systemDatabase = db_;
375 printDebug(DM_Database, "Opening database: %s", name);
376 return OK;
379 DbRetVal DatabaseManagerImpl::closeDatabase()
382 if (NULL == db_)
384 //Database is already closed
385 return OK;
387 printDebug(DM_Database, "Closing database: %s",(char*)db_->getName());
388 //check if this is the last thread to be deregistered
389 int ret =0;// ProcessManager::mutex.getLock(-1, false);
390 //If you are not getting lock ret !=0, it means somebody else is there.
391 //he will close the database.
392 if (0 != strcmp((char*)db_->getName(), SYSTEMDB)) {
393 file_desc fd = db_->getChkptfd();
394 os::closeFile(fd);
396 if (ret == 0) {
397 if (ProcessManager::noThreads == 0 && 0 == strcmp((char*)db_->getName(), SYSTEMDB)
398 || ProcessManager::noThreads == 1 && 0 != strcmp((char*)db_->getName(), SYSTEMDB) ) {
399 os::shm_detach((char*)db_->getMetaDataPtr());
402 // ProcessManager::mutex.releaseLock(-1, false);
403 delete db_;
404 db_ = NULL;
405 return OK;
407 //Assumes that system database mutex is taken before calling this.
408 Chunk* DatabaseManagerImpl::createUserChunk(size_t size)
410 //Allocate new node in system database to store
411 Chunk *chunk = getSystemTableChunk(UserChunkTableId);
412 DbRetVal rv = OK;
413 void *ptr = chunk->allocate(systemDatabase_, &rv);
414 if (NULL == ptr)
416 printError(rv, "Allocation failed for User chunk catalog table");
417 return NULL;
419 Chunk *chunkInfo = (Chunk*)ptr;
420 int id = db_->getUniqueIDForChunk();
421 db_->incrementChunk();
422 chunkInfo->initMutex(id);
423 if (0 != size) chunkInfo->setSize(size);
424 if (chunkInfo->allocSize_ > PAGE_SIZE)
425 chunkInfo->curPage_ = db_->getFreePage(chunkInfo->allocSize_);
426 else
427 chunkInfo->curPage_ = db_->getFreePage();
428 if ( NULL == chunkInfo->curPage_)
430 chunkInfo->destroyMutex();
431 chunk->free(db_, ptr);
432 printError(ErrNoMemory, "Database full: No space to allocate from database");
433 return NULL;
435 PageInfo* firstPageInfo = ((PageInfo*)chunkInfo->curPage_);
436 if (chunkInfo->allocSize_ > PAGE_SIZE)
438 int multiple = os::floor(chunkInfo->allocSize_ / PAGE_SIZE);
439 int offset = ((multiple + 1) * PAGE_SIZE);
440 firstPageInfo->setPageAsUsed(offset);
442 else
444 firstPageInfo->setPageAsUsed(chunkInfo->allocSize_);
445 char *data = ((char*)firstPageInfo) + sizeof(PageInfo);
446 *(InUse*)data =0;
448 if (0 == size)
450 VarSizeInfo *varInfo = (VarSizeInfo*)(((char*)firstPageInfo) + sizeof(PageInfo));
451 varInfo->isUsed_ = 0;
452 varInfo->size_ = PAGE_SIZE - sizeof(PageInfo) - sizeof(VarSizeInfo);
455 chunkInfo->firstPage_ = chunkInfo->curPage_;
457 if (0 == size)
458 chunkInfo->setAllocType(VariableSizeAllocator);
459 else
460 chunkInfo->setAllocType(FixedSizeAllocator);
462 chunkInfo->setChunkID(id);
463 chunkInfo->setPageDirty(firstPageInfo);
464 printDebug(DM_Database, "Creating new User chunk chunkID:%d size: %d firstPage:%x",
465 -1, chunkInfo->allocSize_, firstPageInfo);
467 return chunkInfo;
470 //Assumes that system database mutex is taken before calling this.
471 DbRetVal DatabaseManagerImpl::deleteUserChunk(Chunk *chunk)
473 //Go to the pages and set them to notUsed
474 Page *page = chunk->firstPage_;
475 PageInfo* pageInfo = ((PageInfo*)page);
476 //Here...sure that atleast one page will be there even no tuples
477 //are inserted.so not checking if pageInfo == NULL
478 while( pageInfo->nextPage_ != NULL)
480 PageInfo *prev = pageInfo;
481 pageInfo = (PageInfo*)(pageInfo->nextPage_);
482 //sets pageInfo->isUsed_ = 0 and pageInfo->hasFreeSpace_ = 0
483 //and initializes the page content to zero
484 if(NULL == pageInfo->nextPageAfterMerge_){
485 os::memset(prev, 0, PAGE_SIZE);
486 SETBIT(prev->flags, IS_DIRTY);
489 else
491 int size = (char*) pageInfo->nextPageAfterMerge_ - (char*) pageInfo;
492 char *iter = (char*)prev, *end=(char*)pageInfo->nextPageAfterMerge_;
493 os::memset(prev, 0, size);
494 //set dirty bit for all pages in merged pages
495 while(iter <= end)
497 PageInfo *info = (PageInfo*) iter;
498 SETBIT(info->flags, IS_DIRTY);
499 iter = iter + PAGE_SIZE;
502 printDebug(DM_Database,"deleting user chunk:%x clearing page %x",chunk, prev);
504 //The above loop wont execute for the last page
505 //and for the case where table has only one page
506 if(NULL == pageInfo->nextPageAfterMerge_) {
507 os::memset(pageInfo, 0, PAGE_SIZE);
508 SETBIT(pageInfo->flags, IS_DIRTY);
510 else
512 int size = (char*) pageInfo->nextPageAfterMerge_ - (char*) pageInfo;
513 char *iter = (char*)pageInfo, *end=(char*)pageInfo->nextPageAfterMerge_;
514 os::memset(pageInfo, 0, size);
515 //set dirty bit for all pages in merged pages
516 while(iter <= end)
518 PageInfo *info = (PageInfo*) iter;
519 SETBIT(info->flags, IS_DIRTY);
520 iter = iter + PAGE_SIZE;
523 printDebug(DM_Database,"deleting user chunk:%x clearing page %x",chunk, pageInfo);
524 chunk->chunkID_ = -1;
525 chunk->allocSize_ = 0;
526 chunk->curPage_ = NULL;
527 chunk->firstPage_ = NULL;
528 chunk->destroyMutex();
529 db_->decrementChunk();
530 Chunk *userChunk = getSystemTableChunk(UserChunkTableId);
531 userChunk->free(systemDatabase_,chunk);
532 printDebug(DM_Database,"deleting user chunk:%x",chunk);
533 return OK;
536 //-1 -> Unable to create chunk. No memory
537 //-2 -> Unable to update the catalog tables
538 DbRetVal DatabaseManagerImpl::createTable(const char *name, TableDef &def)
540 DbRetVal rv = OK;
541 if (!Util::isIdentifier((char*)name)) {
542 printError(ErrBadArg, "Invalid character for index name");
543 return ErrBadArg;
545 int fldCount = def.getFieldCount();
546 if(0==fldCount)
548 printError(ErrNotExists,"Table can't be created without Field");
549 return ErrNotExists;
552 //If total field count is within 32, then 1 integer is used to store all
553 // null information, if it is more then 1 char is used to store null
554 // information of each field
555 //This is to done to reduce cpu cycles for small tables
556 int addSize = 0;
557 if (fldCount <= 32) addSize = 4; else addSize = os::align(fldCount);
558 size_t sizeofTuple = os::alignLong(def.getTupleSize()+addSize);
559 rv = systemDatabase_->getXCheckpointMutex();
560 if (OK != rv ) {
561 printError(rv, "Unable to get Database mutex");
562 return rv;
565 void *tptr =NULL;
566 void *chunk = NULL;
567 void *vcchunk = NULL;
569 //check whether table already exists
570 CatalogTableTABLE cTable(systemDatabase_);
571 cTable.getChunkAndTblPtr(name, chunk, tptr, vcchunk);
572 if (NULL != tptr)
574 systemDatabase_->releaseCheckpointMutex();
575 printError(ErrAlready, "Table %s already exists", name);
576 return ErrAlready;
579 //create a chunk to store the tuples
580 Chunk *ptr = createUserChunk(sizeofTuple);
581 if (NULL == ptr)
583 systemDatabase_->releaseCheckpointMutex();
584 printError(ErrNoResource, "Unable to create user chunk");
585 return ErrNoResource;
587 printDebug(DM_Database,"Created UserChunk:%x", ptr);
588 ptr->setChunkName(name);
589 //add row to TABLE
590 int tblID = ((Chunk*)ptr)->getChunkID();
592 //check whether varchar is present in table
593 FieldIterator fiter = def.getFieldIterator();
594 bool isVarcharPresent = def.isVarcharPresentInSchema(fiter);
595 Chunk *vcptr = NULL;
596 if (isVarcharPresent) {
597 //creat chunk to store varchar values
598 vcptr = createUserChunk();
599 if (NULL == vcptr)
601 deleteUserChunk(ptr);
602 systemDatabase_->releaseCheckpointMutex();
603 printError(ErrNoResource, "Unable to create user chunk for varchar");
604 return ErrNoResource;
606 printDebug(DM_Database,"Created UserChunk for Varchar:%x", vcptr);
607 vcptr->setChunkName(name);
609 rv = cTable.insert(name, tblID, sizeofTuple,
610 def.getFieldCount(), ptr, tptr, vcptr);
611 if (OK != rv)
613 deleteUserChunk(ptr);
614 if (vcptr) deleteUserChunk(vcptr);
615 systemDatabase_->releaseCheckpointMutex();
616 printError(ErrSysInternal, "Unable to update catalog table TABLE");
617 return ErrSysInternal;
619 printDebug(DM_Database,"Inserted into TABLE:%s",name);
620 //add rows to FIELD
621 FieldIterator iter = def.getFieldIterator();
622 CatalogTableFIELD cField(systemDatabase_);
623 rv = cField.insert(iter, tblID ,tptr);
624 if (OK != rv)
626 deleteUserChunk(ptr);
627 if (vcptr) deleteUserChunk(vcptr);
628 void *cptr, *ttptr;//Dummy as remove below needs both these OUT params
629 cTable.remove(name, cptr, ttptr);
630 systemDatabase_->releaseCheckpointMutex();
631 printError(ErrSysInternal, "Unable to update catalog table FIELD");
632 return ErrSysInternal;
634 printDebug(DM_Database,"Inserted into FIELD:%s",name);
635 systemDatabase_->releaseCheckpointMutex();
636 printDebug(DM_Database,"Table Created:%s",name);
637 logFinest(Conf::logger, "Table Created %s" , name);
638 return OK;
640 DbRetVal DatabaseManagerImpl::renameTable(const char *oldName,const char *newName)
642 void *chunk = NULL;
643 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
644 if (OK != rv) {
645 printError(ErrSysInternal, "Unable to get database mutex for rename table");
646 return ErrSysInternal;
648 CatalogTableTABLE cTable(systemDatabase_);
649 rv = cTable.renameTable(oldName,newName);
650 if (OK != rv) {
651 printError(ErrSysInternal, "Unable to rename table");
652 systemDatabase_->releaseCheckpointMutex();
653 return ErrSysInternal;
655 systemDatabase_->releaseCheckpointMutex();
656 return OK;
658 DbRetVal DatabaseManagerImpl::renameIndex(const char *oldName,const char *newName)
660 void *chunk = NULL;
661 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
662 if (OK != rv) {
663 printError(ErrSysInternal, "Unable to get database mutex for rename table");
664 return ErrSysInternal;
666 CatalogTableTABLE cTable(systemDatabase_);
667 rv = cTable.renameIndex(oldName,newName);
668 if (OK != rv) {
669 printError(ErrSysInternal, "Unable to rename table");
670 systemDatabase_->releaseCheckpointMutex();
671 return ErrSysInternal;
673 systemDatabase_->releaseCheckpointMutex();
674 return OK;
677 DbRetVal DatabaseManagerImpl::renameField(const char *tableName,const char *oldName,const char *newName)
679 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
680 if (OK != rv) {
681 printError(ErrSysInternal, "Unable to get database mutex for rename table");
682 return ErrSysInternal;
684 CatalogTableFIELD fTable(systemDatabase_);
685 rv = fTable.renameField(tableName, oldName, newName);
686 if (OK != rv) {
687 printError(ErrSysInternal, "Unable to rename field.");
688 systemDatabase_->releaseCheckpointMutex();
689 return ErrSysInternal;
691 systemDatabase_->releaseCheckpointMutex();
692 return rv;
695 //TODO::If any operation fails in between, then we may have some
696 //dangling tuples, say we have have rows in INDEX table
697 //which will not have any corresponding entries in TABLE
698 //CHANGE the sequence so that it deletes from the bottom as
699 //opposed to start from top as is written now
700 DbRetVal DatabaseManagerImpl::dropTable(const char *name)
702 void *chunk = NULL;
703 void *tptr =NULL;
704 void *vcchunk = NULL;
705 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
706 if (OK != rv) {
707 printError(ErrSysInternal, "Unable to get database mutex");
708 return ErrSysInternal;
710 //remove the entry in TABLE
711 CatalogTableTABLE cTable(systemDatabase_);
712 rv = cTable.getChunkAndTblPtr(name, chunk, tptr, vcchunk);
713 if (OK != rv) {
714 systemDatabase_->releaseCheckpointMutex();
715 printError(ErrSysInternal, "Table %s does not exist", name);
716 return ErrSysInternal;
718 CatalogTableFK cFK(systemDatabase_);
719 int noOfRelation =cFK.getNumFkTable(tptr);
720 if(noOfRelation)
722 printError(ErrSysInternal, "Unable to drop table due to relation exist.Drop child table...");
723 systemDatabase_->releaseCheckpointMutex();
724 return ErrSysInternal;
726 Transaction **trans = ProcessManager::getThreadTransAddr(systemDatabase_->procSlot);
727 rv = lMgr_->getExclusiveLock(chunk, trans);
728 if (rv !=OK)
730 systemDatabase_->releaseCheckpointMutex();
731 printError(ErrLockTimeOut, "Unable to acquire exclusive lock on the table\n");
732 return rv;
735 rv = cTable.remove(name, chunk, tptr);
736 if (OK != rv) {
737 systemDatabase_->releaseCheckpointMutex();
738 printError(ErrSysInternal, "Unable to update catalog table TABLE");
739 return ErrSysInternal;
741 printDebug(DM_Database,"Deleted from TABLE:%s",name);
743 //remove the entries in the FIELD table
744 CatalogTableFIELD cField(systemDatabase_);
745 rv = cField.remove(tptr);
746 if (OK != rv) {
747 systemDatabase_->releaseCheckpointMutex();
748 printError(ErrSysInternal, "Unable to update catalog table FIELD");
749 return ErrSysInternal;
751 printDebug(DM_Database,"Deleted from FIELD:%s",name);
753 rv = deleteUserChunk((Chunk*)chunk);
754 if (OK != rv) {
755 systemDatabase_->releaseCheckpointMutex();
756 printError(rv, "Unable to delete the chunk");
757 return rv;
759 printDebug(DM_Database,"Deleted UserChunk:%x", chunk);
761 if (vcchunk != NULL) {
762 rv = deleteUserChunk((Chunk*)vcchunk);
763 if (OK != rv) {
764 systemDatabase_->releaseCheckpointMutex();
765 printError(rv, "Unable to delete the chunk");
766 return rv;
768 printDebug(DM_Database,"Deleted UserChunk for Varchar:%x", chunk);
771 //TODO::check whether indexes are available and drop that also.
772 CatalogTableINDEX cIndex(systemDatabase_);
773 int noIndexes = cIndex.getNumIndexes(tptr);
774 for (int i =1 ; i<= noIndexes; i++) {
775 char *idxName = cIndex.getIndexName(tptr, 1);
776 dropIndexInt(idxName, false);
778 bool isFkExist=cFK.isFkTable(tptr);
779 if(isFkExist)
781 dropForeignKey(tptr,false);
783 systemDatabase_->releaseCheckpointMutex();
784 printDebug(DM_Database, "Deleted Table %s" , name);
785 logFinest(Conf::logger, "Deleted Table %s" , name);
786 rv = lMgr_->releaseLock(chunk);
787 if (rv !=OK)
789 printError(ErrLockTimeOut, "Unable to release exclusive lock on the table\n");
790 return rv;
792 return OK;
795 //Return values: NULL for table not found
796 Table* DatabaseManagerImpl::openTable(const char *name,bool checkpkfk)
798 DbRetVal ret = OK;
799 //TODO::store table handles in list so that if it is
800 //not closed by the application. destructor shall close it.
801 TableImpl *table = new TableImpl();
802 table->setDB(db_);
803 table->setSystemDB(systemDatabase_);
804 table->setLockManager(lMgr_);
805 table->setTrans(ProcessManager::getThreadTransAddr(systemDatabase_->procSlot));
807 //to store the chunk pointer of table
808 void *chunk = NULL;
809 void *vcchunk = NULL;
811 //to store the tuple pointer of the table
812 void *tptr =NULL;
814 //TODO::need to take shared lock on the table so that
815 //all ddl operation will be denied on that table
816 //which includes index creation, alter table
818 DbRetVal rv = systemDatabase_->getAllocDatabaseMutex();
819 if (OK != rv) {
820 printError(ErrSysInternal, "Unable to get database mutex");
821 delete table;
822 return NULL;
824 CatalogTableTABLE cTable(systemDatabase_);
825 ret = cTable.getChunkAndTblPtr(name, chunk, tptr, vcchunk);
826 if ( OK != ret)
828 systemDatabase_->releaseAllocDatabaseMutex();
829 delete table;
830 printError(ErrNotExists, "Table not exists %s", name);
831 return NULL;
833 CTABLE *tTuple = (CTABLE*)tptr;
834 table->setTableInfo(tTuple->tblName_, tTuple->tblID_, tTuple->length_,
835 tTuple->numFlds_, tTuple->numIndexes_,
836 tTuple->chunkPtr_, tTuple->varcharChunkPtr_);
837 /*rv = table->lock(true); //take shared lock
838 if (rv !=OK)
840 printError(ErrLockTimeOut, "Unable to acquire shared lock on the table\n");
841 systemDatabase_->releaseAllocDatabaseMutex();
842 delete table;
843 return NULL;
847 if (tTuple->numFlds_ <= 32)
849 table->isIntUsedForNULL = true;
850 table->iNullInfo = 0;
851 table->iNotNullInfo =0;
853 else
855 table->isIntUsedForNULL = false;
856 int noFields = os::align(tTuple->numFlds_);
857 table->cNullInfo = (char*) malloc(noFields);
858 table->cNotNullInfo = (char*) malloc(noFields);
859 for (int i =0 ; i < noFields; i++) table->cNullInfo[i] =0;
860 for (int i =0 ; i < noFields; i++) table->cNotNullInfo[i] =0;
864 //get field information from FIELD table
865 CatalogTableFIELD cField(systemDatabase_);
866 table->ptrToAuto = cField.getFieldInfo(tptr, table->fldList_);
868 //populate the notnull info
869 FieldIterator fIter = table->fldList_.getIterator();
870 int fldpos=1;
871 while (fIter.hasElement())
873 FieldDef *def = fIter.nextElement();
874 if (table->isIntUsedForNULL) {
875 if (def->isNull_) SETBIT(table->iNotNullInfo, fldpos-1);
877 else {
878 if (def->isNull_) table->cNotNullInfo[fldpos-1] = 1;
880 fldpos++;
883 //get the number of indexes on this table
884 //and populate the indexPtr array
885 CatalogTableINDEX cIndex(systemDatabase_);
886 table->numIndexes_ = cIndex.getNumIndexes(tptr);
887 if (table->numIndexes_) {
888 table->indexPtr_ = new char*[table->numIndexes_];
889 table->idxInfo = new IndexInfo*[table->numIndexes_];
891 else
893 table->indexPtr_ = NULL;
895 cIndex.getIndexPtrs(tptr, table->indexPtr_);
896 for (int i =0 ; i < table->numIndexes_; i++ )
898 HashIndexInfo *hIdxInfo = new HashIndexInfo();
899 CatalogTableINDEXFIELD cIndexField(systemDatabase_);
900 cIndexField.getFieldInfo(table->indexPtr_[i], hIdxInfo->idxFldList);
901 ChunkIterator citer = CatalogTableINDEX::getIterator(table->indexPtr_[i]);
902 hIdxInfo->indexPtr = table->indexPtr_[i];
903 hIdxInfo->indType = ((CINDEX*)hIdxInfo->indexPtr)->indexType_;
904 hIdxInfo->noOfBuckets = CatalogTableINDEX::getNoOfBuckets(table->indexPtr_[i]);
905 FieldIterator fIter = hIdxInfo->idxFldList.getIterator();
906 bool firstFld = true;
907 while (fIter.hasElement())
909 FieldDef *def = fIter.nextElement();
910 if (firstFld)
912 hIdxInfo->fldOffset = table->fldList_.getFieldOffset(def->fldName_);
913 hIdxInfo->type = table->fldList_.getFieldType(def->fldName_);
914 hIdxInfo->compLength = table->fldList_.getFieldLength(def->fldName_);
915 firstFld = false;
916 }else {
917 hIdxInfo->type = typeComposite;
918 hIdxInfo->compLength = hIdxInfo->compLength +
919 table->fldList_.getFieldLength(def->fldName_);
923 hIdxInfo->isUnique = CatalogTableINDEX::getUnique(table->indexPtr_[i]);
924 hIdxInfo->buckets = (Bucket*)citer.nextElement();
925 table->idxInfo[i] = (IndexInfo*) hIdxInfo;
927 systemDatabase_->releaseAllocDatabaseMutex();
928 //Foreign key Operation
929 if(checkpkfk){
930 CatalogTableFK cFk(systemDatabase_);
931 int totalFld=0;
932 table->numFkRelation_ = cFk.getNumFkTable(tptr);
933 if (table->numFkRelation_) {
934 table->isPkTbl=true;//TODO:for Delete In casecade
935 totalFld=cFk.getNoOfFkTable(tptr);
936 //printDebug(DM_TEST,"Total table is %d\n",totalFld);
937 char **fptr = new char* [totalFld];
938 cFk.getFkTableName(tptr,fptr);
939 for(int count=0; count < totalFld; count++){
940 //printDebug(DM_TEST,"FK Name is %s\n",fptr[count]);
941 Table *pkTable=openTable(fptr[count],false);
942 if (pkTable) table->tblFkList.append(pkTable);
943 else {
944 printError(ErrSysInternal, "Unable to open foreign key tables");
945 delete[] fptr;
946 pkTable->close();
947 return NULL;
950 delete[] fptr;
953 char *tblName = NULL;
954 table->isFkTbl = cFk.isFkTable(tptr);
955 if(table->isFkTbl)
957 totalFld=cFk.getNoOfPkTable(tptr);
958 char **fptr = new char* [totalFld];
959 cFk.getPkTableName(tptr,fptr);
960 for(int count=0; count<totalFld; count++){
961 //printDebug(DM_TEST,"Parent Name is %s\n",fptr[count]);
962 Table *fkTable = openTable(fptr[count],false);
963 if (fkTable) table->tblList.append(fkTable);
964 else {
965 printError(ErrSysInternal, "Unable to open foreign key tables");
966 delete[] fptr;
967 fkTable->close();
968 return NULL;
971 delete[] fptr;
974 printDebug(DM_Database,"Opening table handle name:%s chunk:%x numIndex:%d",
975 name, chunk, table->numIndexes_);
976 logFinest(Conf::logger, "Opening Table %s" , name);
977 return table;
980 List DatabaseManagerImpl::getAllTableNames(int *retval)
982 DbRetVal ret = OK;
983 //to store the tuple pointer of the table
984 void *tptr =NULL;
986 /*DbRetVal rv = systemDatabase_->getSCheckpointMutex();
987 if (OK != rv) {
988 printError(ErrSysInternal, "Unable to get checkpoint mutex");
989 if(retval) *retval = rv;
990 List tableList;
991 return tableList;
993 CatalogTableTABLE cTable(systemDatabase_);
994 List tableList = cTable.getTableList();
995 //systemDatabase_->releaseCheckpointMutex();
996 return tableList;
1002 //Return values: -1 for table not found
1003 void DatabaseManagerImpl::closeTable(Table *table)
1005 printDebug(DM_Database,"Closing table handle: %x", table);
1006 if (NULL == table) return;
1007 //table->unlock();
1008 /* TableImpl *fkTbl =NULL;
1009 ListIterator tblIter = ((TableImpl*)table)->tblList.getIterator();
1010 tblIter.reset();
1011 while (tblIter.hasElement()){
1012 fkTbl = (TableImpl *) tblIter.nextElement();
1013 closeTable(fkTbl);
1015 ((TableImpl*)table)->tblList.reset();
1016 tblIter = ((TableImpl*)table)->tblFkList.getIterator();
1017 tblIter.reset();
1018 while (tblIter.hasElement()){
1019 fkTbl = (TableImpl *) tblIter.nextElement();
1020 closeTable(fkTbl);
1022 ((TableImpl*)table)->tblFkList.reset();*/
1023 if (table) delete table; table = NULL;
1024 logFinest(Conf::logger, "Closing Table");
1027 DbRetVal DatabaseManagerImpl::createIndex(const char *indName, IndexInitInfo *info)
1029 DbRetVal rv = OK;
1030 if (!info->isUnique && info->isPrimary)
1032 printError(ErrBadCall, "Primary key cannot be non unique\n");
1033 return ErrBadCall;
1035 if (!Util::isIdentifier((char*)indName)) {
1036 printError(ErrBadArg, "Invalid character for index name");
1037 return ErrBadArg;
1040 if (info->indType == hashIndex)
1042 //Assumes info is of type HashIndexInitInfo
1043 HashIndexInitInfo *hInfo = (HashIndexInitInfo*) info;
1044 rv = createHashIndex(indName, info->tableName, info->list, hInfo->bucketSize,
1045 info->isUnique, info->isPrimary);
1047 else if (info->indType == treeIndex)
1049 HashIndexInitInfo *hInfo = (HashIndexInitInfo*) info;
1050 rv = createTreeIndex(indName, info->tableName, info->list,
1051 hInfo->bucketSize, info->isUnique, info->isPrimary);
1053 else if (info->indType == trieIndex)
1055 HashIndexInitInfo *hInfo = (HashIndexInitInfo*) info;
1056 rv = createTrieIndex(indName, info->tableName, info->list,
1057 info->isUnique, info->isPrimary);
1059 }else {
1060 printError(ErrBadCall, "Index type not supported\n");
1061 return ErrBadCall;
1063 return rv;
1067 //-1 -> Table does not exists
1068 //-2 -> Field does not exists
1069 //-3 -> bucketSize is not valid
1070 DbRetVal DatabaseManagerImpl::createHashIndex(const char *indName, const char *tblName,
1071 FieldNameList &fldList, int bucketSize, bool isUnique, bool isPrimary)
1073 //validate the bucket size
1074 if (bucketSize < 100 || bucketSize > 200000)
1076 printError(ErrBadRange, "Index Bucket size %d not in range 100-200000",
1077 bucketSize);
1078 return ErrBadRange;
1080 int totFlds = fldList.size();
1081 if (totFlds == 0)
1083 printError(ErrBadCall, "No Field name specified");
1084 return ErrBadCall;
1086 void *tptr =NULL;
1087 void *chunk = NULL;
1088 void *vcchunk = NULL;
1089 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
1090 if (OK != rv)
1092 printError(ErrSysInternal, "Unable to get database mutex");
1093 return ErrSysInternal;
1096 //check whether table exists
1097 CatalogTableTABLE cTable(systemDatabase_);
1098 cTable.getChunkAndTblPtr(tblName, chunk, tptr, vcchunk);
1099 if (NULL == tptr)
1101 systemDatabase_->releaseCheckpointMutex();
1102 printError(ErrNotExists, "Table does not exist %s", tblName);
1103 return ErrNotExists;
1106 //check whether field exists
1107 char **fptr = new char* [totFlds];
1108 CatalogTableFIELD cField(systemDatabase_);
1109 rv = cField.getFieldPtrs(fldList, tptr, fptr);
1110 if (OK != rv)
1112 delete[] fptr;
1113 systemDatabase_->releaseCheckpointMutex();
1114 //TODO::check test cases of dbapi/Index, they give wrong results
1115 //if (rv == ErrBadCall) {
1116 //// if (isPrimary) printError(ErrBadCall, "Field can have NULL values");
1117 //} else {
1118 //printError(ErrNotExists, "Field does not exist");
1119 //}
1120 //return ErrBadCall;
1121 if (rv != ErrBadCall) {
1122 printError(ErrNotExists, "Field does not exist");
1123 return ErrNotExists;
1126 for (int i=0; i <totFlds; i++)
1128 CFIELD* fInfo = (CFIELD*)fptr[i];
1129 if (fInfo->type_ == typeFloat || fInfo->type_ == typeDouble || fInfo->type_ == typeTimeStamp)
1131 printError(ErrBadArg, "HashIndex cannot be created for float or double or timestamp type");
1132 delete[] fptr;
1133 systemDatabase_->releaseCheckpointMutex();
1134 return ErrBadArg;
1136 if (!fInfo->isNull_ && isPrimary )
1138 printError(ErrBadArg, "Primary Index cannot be created on field without NOTNULL constraint");
1139 delete[] fptr;
1140 systemDatabase_->releaseCheckpointMutex();
1141 return ErrBadArg;
1143 if(isPrimary){fInfo->isPrimary_=true;fInfo->isUnique_=true;}
1144 if(isUnique){fInfo->isUnique_=true;}
1146 //create chunk to store the meta data of the index created
1147 //for latches and bucket pointers
1148 printDebug(DM_HashIndex, "Creating chunk for storing hash buckets of size %d\n",
1149 bucketSize * sizeof(Bucket));
1150 Chunk* chunkInfo = createUserChunk(bucketSize * sizeof(Bucket));
1151 if (NULL == chunkInfo)
1153 delete[] fptr;
1154 systemDatabase_->releaseCheckpointMutex();
1155 printError(ErrSysInternal, "Unable to create chunk");
1156 return ErrSysInternal;
1158 chunkInfo->setChunkName(indName);
1159 //create memory for holding the bucket pointers
1160 void *buckets = chunkInfo->allocate(db_, &rv);
1161 if (NULL == buckets)
1163 delete[] fptr;
1164 deleteUserChunk(chunkInfo);
1165 systemDatabase_->releaseCheckpointMutex();
1166 printError(rv, "Unable to allocate memory for bucket");
1167 return rv;
1169 Bucket *buck = (Bucket*) buckets;
1170 initHashBuckets(buck, bucketSize);
1172 //create chunk to store the hash index nodes
1173 Chunk* hChunk = createUserChunk(sizeof(IndexNode));
1174 if (NULL == hChunk)
1176 delete[] fptr;
1177 deleteUserChunk(chunkInfo);
1178 systemDatabase_->releaseCheckpointMutex();
1179 printError(ErrSysInternal, "Unable to create chunk for storing hash index nodes");
1180 return ErrSysInternal;
1183 hChunk->setChunkName(indName);
1184 //add row to INDEX
1185 void *tupleptr = NULL;
1186 CatalogTableINDEX cIndex(systemDatabase_);
1187 rv = cIndex.insert(indName, tptr, fldList.size(), isUnique,
1188 chunkInfo, bucketSize, hChunk, tupleptr);
1189 if (OK != rv)
1191 delete[] fptr;
1192 deleteUserChunk(hChunk);
1193 deleteUserChunk(chunkInfo);
1194 systemDatabase_->releaseCheckpointMutex();
1195 printError(ErrSysInternal, "Catalog table updation failed in INDEX table");
1196 return ErrSysInternal;
1198 //add rows to INDEXFIELD
1199 CatalogTableINDEXFIELD cIndexField(systemDatabase_);
1200 rv = cIndexField.insert(fldList, tupleptr, tptr, fptr);
1202 if (OK != rv)
1204 delete[] fptr;
1205 cIndex.remove(indName, (void *&)chunkInfo, (void *&)hChunk, (void *&)tupleptr);
1206 deleteUserChunk(hChunk);
1207 deleteUserChunk(chunkInfo);
1208 systemDatabase_->releaseCheckpointMutex();
1209 printError(ErrSysInternal, "Catalog table updation failed in INDEXFIELD table");
1210 return ErrSysInternal;
1212 delete[] fptr;
1213 systemDatabase_->releaseCheckpointMutex();
1215 //TODO:: Take table lock
1217 // Following code is written by Kishor Amballi
1218 TableImpl *tbl = (TableImpl *) openTable(tblName);
1219 if (NULL == tbl) {
1220 printError(ErrSysInternal, "Unable to open table %s", tblName);
1221 return ErrSysInternal;
1223 if (! tbl->numTuples()) {
1224 printDebug(DM_Database, "Creating Hash Index Name:%s tblname:%s buckets:%x", indName, tblName, buckets);
1225 logFinest(Conf::logger, "Creating HashIndex %s on %s with bucket size %d", indName, tblName, buckets);
1226 closeTable(tbl);
1227 return OK;
1229 HashIndexInfo *indxInfo = NULL;
1230 int i = 0;
1231 for (i = 0; i < tbl->numIndexes_; i++) {
1232 if(((HashIndexInfo *)tbl->idxInfo[i])->indexPtr == tupleptr) {
1233 indxInfo = (HashIndexInfo *) tbl->idxInfo[i];
1234 break;
1237 void *recPtr = NULL;
1238 ChunkIterator chIter = ((Chunk *)chunk)->getIterator();
1239 tbl->setLoading(true);
1240 while ((recPtr = chIter.nextElement()) != NULL) {
1241 rv = tbl->insertIndexNode(*tbl->trans, tupleptr, indxInfo, recPtr);
1242 if (rv == ErrUnique) {
1243 closeTable(tbl);
1244 dropIndex(indName);
1245 return rv;
1248 closeTable(tbl);
1249 printDebug(DM_Database, "Creating Hash Index Name:%s tblname:%s buckets:%x", indName, tblName, buckets);
1250 logFinest(Conf::logger, "Creating HashIndex %s on %s with bucket size %d", indName, tblName, buckets);
1251 return OK;
1255 DbRetVal DatabaseManagerImpl::createTreeIndex(const char *indName, const char *tblName,
1256 FieldNameList &fldList, int nodeSize, bool isUnique, bool isPrimary)
1258 if (nodeSize < 20 || nodeSize > 20000)
1260 printError(ErrBadRange,"Tree Index Node size %d not in range 20-20000",
1261 nodeSize);
1262 return ErrBadRange;
1264 int totFlds = fldList.size();
1265 if (totFlds == 0) {
1266 printError(ErrBadCall, "No Field name specified");
1267 return ErrBadCall;
1268 }else if (totFlds != 1) {
1269 printError(ErrBadCall, "Composite index not supported for Tree");
1270 return ErrBadCall;
1272 void *tptr =NULL;
1273 void *chunk = NULL;
1274 void *vcchunk = NULL;
1275 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
1276 if (OK != rv)
1278 printError(ErrSysInternal, "Unable to get database mutex");
1279 return ErrSysInternal;
1281 //check whether table exists
1283 CatalogTableTABLE cTable(systemDatabase_);
1284 cTable.getChunkAndTblPtr(tblName, chunk, tptr, vcchunk);
1285 if (NULL == tptr)
1287 systemDatabase_->releaseCheckpointMutex();
1288 printError(ErrNotExists, "Table does not exist %s", tblName);
1289 return ErrNotExists;
1291 char **fptr = new char* [totFlds];
1292 CatalogTableFIELD cField(systemDatabase_);
1293 rv = cField.getFieldPtrs(fldList, tptr, fptr);
1294 if (OK != rv)
1296 delete[] fptr;
1297 systemDatabase_->releaseCheckpointMutex();
1298 if (rv != ErrBadCall) {
1299 printError(ErrNotExists, "Field does not exist");
1300 return ErrNotExists;
1303 for (int i=0; i <totFlds; i++)
1305 CFIELD* fInfo = (CFIELD*)fptr[i];
1306 if (!fInfo->isNull_ && isPrimary )
1308 printError(ErrBadArg, "Primary Index cannot be created on field without NOTNULL constraint");
1309 delete[] fptr;
1310 systemDatabase_->releaseCheckpointMutex();
1311 return ErrBadArg;
1313 if (fInfo->type_ == typeVarchar)
1315 printError(ErrBadArg, "Tree Index not supported for varchar type. Use char data type instead.");
1316 delete[] fptr;
1317 systemDatabase_->releaseCheckpointMutex();
1318 return ErrBadArg;
1322 int chunkSize = sizeof(TreeNode)+(nodeSize * sizeof(void*));
1323 printDebug(DM_HashIndex, "Creating chunk for storing tree nodes of size %d\n", chunkSize);
1325 Chunk* chunkInfo = createUserChunk(chunkSize);
1326 if (NULL == chunkInfo)
1328 delete[] fptr;
1329 systemDatabase_->releaseCheckpointMutex();
1330 printError(ErrSysInternal, "Unable to create chunk");
1331 return ErrSysInternal;
1335 void *tupleptr = NULL;
1337 CatalogTableINDEX cIndex(systemDatabase_);
1338 rv = cIndex.insert(indName, tptr, fldList.size(), isUnique,
1339 chunkInfo, nodeSize, NULL, tupleptr);
1340 if (OK != rv)
1342 delete[] fptr;
1343 deleteUserChunk(chunkInfo);
1344 systemDatabase_->releaseCheckpointMutex();
1345 printError(ErrSysInternal, "Catalog table updation failed in INDEX table");
1346 return ErrSysInternal;
1348 CatalogTableINDEXFIELD cIndexField(systemDatabase_);
1349 rv = cIndexField.insert(fldList, tupleptr, tptr, fptr);
1351 if (OK != rv)
1353 delete[] fptr;
1354 void *hChunk = NULL;
1355 cIndex.remove(indName, (void *&)chunkInfo, (void *&)hChunk, (void *&)tupleptr);
1356 deleteUserChunk(chunkInfo);
1357 systemDatabase_->releaseCheckpointMutex();
1358 printError(ErrSysInternal, "Catalog table updation failed in INDEXFIELD table");
1359 return ErrSysInternal;
1361 delete[] fptr;
1362 systemDatabase_->releaseCheckpointMutex();
1363 //TODO::if tuples already present in this table, then create tree index '
1364 //nodes
1365 TableImpl *tbl = (TableImpl *) openTable(tblName);
1366 if (NULL == tbl) {
1367 printError(ErrSysInternal, "Unable to open table %s", tblName);
1368 return ErrSysInternal;
1370 if (! tbl->numTuples()) {
1371 printDebug(DM_Database, "Creating Tree Index Name:%s tblname:%s node size:%x",indName, tblName, nodeSize);
1372 logFinest(Conf::logger, "Creating TreeIndex %s on %s with node size %d",indName, tblName, nodeSize);
1373 closeTable(tbl);
1374 return OK;
1376 HashIndexInfo *indxInfo = NULL;
1377 int i = 0;
1378 for (i = 0; i < tbl->numIndexes_; i++) {
1379 if(((HashIndexInfo *)tbl->idxInfo[i])->indexPtr == tupleptr) {
1380 indxInfo = (HashIndexInfo *) tbl->idxInfo[i];
1381 break;
1384 void *recPtr = NULL;
1385 ChunkIterator chIter = ((Chunk *)chunk)->getIterator();
1386 tbl->setLoading(true);
1387 while ((recPtr = chIter.nextElement()) != NULL) {
1388 rv = tbl->insertIndexNode(*tbl->trans, tupleptr, indxInfo, recPtr);
1389 if (rv == ErrUnique) {
1390 dropIndex(indName);
1391 closeTable(tbl);
1392 return rv;
1395 closeTable(tbl);
1396 printDebug(DM_Database, "Creating Tree Index Name:%s tblname:%s node size:%x",
1397 indName, tblName, nodeSize);
1398 logFinest(Conf::logger, "Creating TreeIndex %s on %s with node size %d",
1399 indName, tblName, nodeSize);
1400 return OK;
1403 DbRetVal DatabaseManagerImpl::createTrieIndex(const char *indName, const char *tblName,
1404 FieldNameList &fldList, bool isUnique, bool isPrimary)
1406 int totFlds = fldList.size();
1407 void *tptr =NULL;
1408 char **fptr = new char* [totFlds];
1409 DbRetVal rv = validateIndex(tblName, fldList, &tptr, &fptr, isPrimary);
1410 if (OK != rv)
1412 delete[] fptr;
1413 return rv;
1415 rv = systemDatabase_->getXCheckpointMutex();
1416 if (OK != rv)
1418 printError(ErrSysInternal, "Unable to get database mutex");
1419 return ErrSysInternal;
1422 //below statements are actually setting values in the catalog table
1423 //thats why mutex is taken before this stmt. Do not change the order
1424 CFIELD* fInfo = (CFIELD*)fptr[0];
1425 if(isPrimary){fInfo->isPrimary_=true;fInfo->isUnique_=true;}
1426 if(isUnique){fInfo->isUnique_=true;}
1428 printDebug(DM_TrieIndex, "Creating chunk for storing trie nodes\n" );
1429 Chunk* chunkInfo = createUserChunk(sizeof(TrieNode));
1431 //chunk to store the linked list of trie values
1432 Chunk* hChunk = createUserChunk(sizeof(IndexNode));
1433 if (NULL == chunkInfo || NULL == hChunk)
1435 delete[] fptr;
1436 if (chunkInfo) deleteUserChunk(chunkInfo);
1437 systemDatabase_->releaseCheckpointMutex();
1438 printError(ErrSysInternal, "Unable to create trie node chunk");
1439 return ErrSysInternal;
1441 chunkInfo->setChunkName(indName);
1442 hChunk->setChunkName(indName);
1443 rv = updateIndexCatalogTables(indName,tptr, fptr, fldList, isUnique,
1444 chunkInfo, hChunk );
1445 delete[] fptr;
1446 if (OK != rv) {
1447 printError(ErrSysInternal, "Catalog table updation failed");
1448 deleteUserChunk(chunkInfo);
1449 deleteUserChunk(hChunk);
1450 systemDatabase_->releaseCheckpointMutex();
1451 return rv;
1453 systemDatabase_->releaseCheckpointMutex();
1454 //TODO:: create index nodes if records already exist in the table
1455 return OK;
1457 DbRetVal DatabaseManagerImpl::validateIndex(const char *tblName,
1458 FieldNameList &fldList, void **tptr, char ***fptr,
1459 bool isPrimary)
1461 int totFlds = fldList.size();
1462 if (totFlds != 1)
1464 printError(ErrBadCall, "No Field name specified or composite fields specified");
1465 return ErrBadCall;
1467 void *chunk = NULL;
1468 void *vcchunk = NULL;
1469 //check whether table exists
1470 CatalogTableTABLE cTable(systemDatabase_);
1471 cTable.getChunkAndTblPtr(tblName, chunk, *tptr, vcchunk);
1472 if (NULL == tptr)
1474 printError(ErrNotExists, "Table does not exist %s", tblName);
1475 return ErrNotExists;
1478 //check whether field exists
1479 CatalogTableFIELD cField(systemDatabase_);
1480 DbRetVal rv = cField.getFieldPtrs(fldList, *tptr, *fptr);
1481 if (OK != rv)
1483 if (rv != ErrBadCall) {
1484 printError(ErrNotExists, "Field does not exist");
1485 return ErrNotExists;
1488 CFIELD* fInfo = (CFIELD*)*fptr[0];
1489 if (!(fInfo->type_ == typeInt || fInfo->type_ == typeLongLong || fInfo->type_ == typeString || fInfo->type_ == typeVarchar))
1491 printError(ErrBadArg, "Trie Index cannot be created for float or double or timestamp type");
1492 return ErrBadArg;
1494 if (!fInfo->isNull_ && isPrimary )
1496 printError(ErrBadArg, "Primary Index cannot be created on field without NOTNULL constraint");
1497 return ErrBadArg;
1500 return OK;
1503 DbRetVal DatabaseManagerImpl::updateIndexCatalogTables(const char *indName,
1504 void *tptr, char **fptr, FieldNameList &fldList,
1505 bool isUnique, Chunk* chunkInfo, Chunk* hChunk )
1507 void *tupleptr = NULL;
1508 CatalogTableINDEX cIndex(systemDatabase_);
1509 DbRetVal rv = cIndex.insert(indName, tptr, fldList.size(), isUnique,
1510 chunkInfo, 0, hChunk, tupleptr);
1511 if (OK != rv)
1513 printError(ErrSysInternal, "Catalog table updation failed in INDEX table");
1514 return ErrSysInternal;
1516 CatalogTableINDEXFIELD cIndexField(systemDatabase_);
1517 rv = cIndexField.insert(fldList, tupleptr, tptr, fptr);
1518 if (OK != rv)
1520 //rollback the previous operation
1521 cIndex.remove(indName, (void *&)chunkInfo, (void *&)hChunk, (void *&)tupleptr);
1522 printError(ErrSysInternal, "Catalog table updation failed in INDEXFIELD table");
1523 return ErrSysInternal;
1525 return rv;
1528 DbRetVal DatabaseManagerImpl::removeIndexCatalogTables(const char *name, void *&chunk, void *&hchunk, void *&tptr)
1530 //remove the entry in INDEX
1531 CatalogTableINDEX cIndex(systemDatabase_);
1532 DbRetVal rv = cIndex.remove(name, chunk, hchunk, tptr);
1533 if (OK != rv)
1535 printError(ErrSysInternal, "Catalog table updation failed for INDEX table");
1536 return ErrSysInternal;
1538 printDebug(DM_Database, "Removing from INDEX %s",name);
1539 //remove the entries in the INDEXFIELD table
1540 CatalogTableINDEXFIELD cIndexField(systemDatabase_);
1541 rv = cIndexField.remove(tptr);
1542 if (OK != rv)
1544 printError(ErrSysInternal, "Catalog table updation failed for INDEX table");
1545 return ErrSysInternal;
1547 printDebug(DM_Database, "Removing from INDEXFIELD %s",name);
1548 return OK;
1550 DbRetVal DatabaseManagerImpl::removeIndexChunks(void* chunk, void* hchunk, IndexType iType)
1552 DbRetVal rv = deleteUserChunk((Chunk*)chunk);
1553 if (OK != rv)
1555 printError(ErrSysInternal, "Unable to delete the index chunk");
1556 return ErrSysInternal;
1558 //delete the index hash node chunk
1559 if (iType == hashIndex || iType == trieIndex) {
1560 rv = deleteUserChunk((Chunk*)hchunk);
1561 if (OK != rv)
1563 printError(ErrSysInternal, "Unable to delete the index hash node chunk");
1564 return ErrSysInternal;
1567 return OK;
1570 void DatabaseManagerImpl::initHashBuckets(Bucket *buck, int bucketSize)
1572 os::memset((void*)buck, 0, bucketSize * sizeof(Bucket));
1573 char mutName[IDENTIFIER_LENGTH];
1574 for (int i=0; i < bucketSize ; i++)
1576 sprintf(mutName, "BKT:%d",i);
1577 buck[i].mutex_.init(mutName);
1579 return;
1582 DbRetVal DatabaseManagerImpl::dropIndex(const char *name)
1584 return dropIndexInt(name, true);
1587 DbRetVal DatabaseManagerImpl::dropIndexInt(const char *name, bool takeLock)
1589 DbRetVal rv = OK;
1590 void *chunk = NULL, *hchunk = NULL;
1591 void *tptr =NULL;
1592 int ret = 0;
1593 if (takeLock) {
1594 rv = systemDatabase_->getXCheckpointMutex();
1595 if (OK != rv)
1597 printError(ErrSysInternal, "Unable to get database mutex");
1598 return ErrSysInternal;
1601 rv = removeIndexCatalogTables(name, chunk, hchunk, tptr);
1602 if (OK != rv)
1604 if (takeLock) systemDatabase_->releaseCheckpointMutex();
1605 return rv;
1608 CINDEX *iptr = (CINDEX*)tptr;
1609 rv = removeIndexChunks(chunk, hchunk, iptr->indexType_);
1610 if (OK != rv)
1612 if (takeLock) systemDatabase_->releaseCheckpointMutex();
1613 return rv;
1615 if (takeLock) systemDatabase_->releaseCheckpointMutex();
1617 printDebug(DM_Database, "Dropped index %s",name);
1618 logFinest(Conf::logger, "Deleted Index %s", name);
1619 return OK;
1621 DbRetVal DatabaseManagerImpl::createForeignKey(char *fKName,ForeignKeyInfo *info)
1623 DbRetVal rv = OK;
1624 int totFkFlds = info->fkFldList.size();
1625 int totPkFlds = info->pkFldList.size();
1626 if (totFkFlds==0 && totPkFlds==0) {
1627 printError(ErrBadCall, "No Field name specified");
1628 return ErrBadCall;
1630 void *tptr =NULL;
1631 void *chunk = NULL;
1632 void *vcchunk = NULL;
1633 rv = systemDatabase_->getXCheckpointMutex();
1634 if (OK != rv)
1636 printError(ErrSysInternal, "Unable to get database mutex");
1637 return ErrSysInternal;
1639 CatalogTableTABLE cTable(systemDatabase_);
1640 cTable.getChunkAndTblPtr(info->fkTableName, chunk, tptr, vcchunk);
1641 if (NULL == tptr)
1643 systemDatabase_->releaseCheckpointMutex();
1644 printError(ErrNotExists, "Table does not exist %s", info->fkTableName);
1645 return ErrNotExists;
1647 char **fptr = new char* [totFkFlds];
1648 CatalogTableFIELD cField(systemDatabase_);
1649 rv = cField.getFieldPtrs(info->fkFldList, tptr, fptr);
1650 if (OK != rv)
1652 delete[] fptr;
1653 systemDatabase_->releaseCheckpointMutex();
1654 if (rv != ErrBadCall) {
1655 printError(ErrNotExists, "Field does not exist");
1656 return ErrNotExists;
1659 void *tPkptr =NULL;
1660 void *chunkPk = NULL;
1661 void *vcchunkPk = NULL;
1662 CatalogTableTABLE c2Table(systemDatabase_);
1663 c2Table.getChunkAndTblPtr(info->pkTableName, chunkPk, tPkptr, vcchunkPk);
1664 if (NULL == tPkptr)
1666 systemDatabase_->releaseCheckpointMutex();
1667 printError(ErrNotExists, "Table does not exist %s", info->pkTableName);
1668 return ErrNotExists;
1670 char **fPkptr = new char* [totPkFlds];
1671 CatalogTableFIELD c2Field(systemDatabase_);
1672 rv = c2Field.getFieldPtrs(info->pkFldList, tPkptr, fPkptr);
1673 if (OK != rv)
1675 delete[] fptr;
1676 delete[] fPkptr;
1677 systemDatabase_->releaseCheckpointMutex();
1678 if (rv != ErrBadCall) {
1679 printError(ErrNotExists, "Field does not exist");
1680 return ErrNotExists;
1683 //Create New chunkdatanode
1684 CatalogTableFK cFK(systemDatabase_);
1685 rv = cFK.insert(fKName, tptr, tPkptr);//TODO
1686 if (OK != rv)
1688 delete[] fptr;
1689 delete[] fPkptr;
1690 systemDatabase_->releaseCheckpointMutex();
1691 printError(ErrSysInternal, "Catalog table updation failed in CFK table");
1692 return ErrSysInternal;
1695 CatalogTableFKFIELD cFKField(systemDatabase_);
1696 rv = cFKField.insert(fKName,fptr,fPkptr,totFkFlds);
1697 if (OK != rv)
1699 delete[] fptr;
1700 delete[] fPkptr;
1701 cFK.remove(tptr);
1702 systemDatabase_->releaseCheckpointMutex();
1703 printError(ErrSysInternal, "Catalog table updation failed in CFKFIELD table");
1704 return ErrSysInternal;
1706 systemDatabase_->releaseCheckpointMutex();
1707 delete[] fptr;
1708 delete[] fPkptr;
1709 return rv;
1711 DbRetVal DatabaseManagerImpl::dropForeignKey(void *tptr,bool trylock)
1713 DbRetVal rv = OK;
1714 if(trylock){
1715 rv = systemDatabase_->getXCheckpointMutex();
1716 if (OK != rv)
1718 printError(ErrSysInternal, "Unable to get database mutex");
1719 return ErrSysInternal;
1722 void *fkChunk=NULL;
1723 CatalogTableFK cFK(systemDatabase_);
1724 int total = cFK.getNoOfPkTable(tptr);
1725 //printDebug(DM_TEST,"total fk chunk %d",total);
1726 for (int i=0;i< total; i++)
1728 fkChunk = cFK.getFkCTable(tptr);
1729 if(NULL==fkChunk)
1731 if(trylock){
1732 systemDatabase_->releaseCheckpointMutex();
1734 printError(ErrSysInternal, "Catalog table not finds CFKFIELD table");
1735 return ErrSysInternal;
1737 CatalogTableFKFIELD cFKField(systemDatabase_);
1738 rv = cFKField.remove(fkChunk);
1739 if (OK != rv)
1741 if(trylock){
1742 systemDatabase_->releaseCheckpointMutex();
1744 printError(ErrSysInternal, "Catalog table updation failed in CFKFIELD table");
1745 return ErrSysInternal;
1747 rv =cFK.remove(fkChunk);
1748 if (OK != rv)
1750 if(trylock){
1751 systemDatabase_->releaseCheckpointMutex();
1753 printError(ErrSysInternal, "Catalog table updation failed for INDEX table");
1754 return ErrSysInternal;
1757 if(trylock){
1758 systemDatabase_->releaseCheckpointMutex();
1760 return rv;
1763 void DatabaseManagerImpl::printTreeIndexNodeInfo(char *name, bool flag)
1765 CatalogTableINDEX cIndex(systemDatabase_);
1766 DbRetVal rv = OK;
1767 void *chunk = NULL, *hchunk = NULL;
1768 void *tptr =NULL;
1769 rv = cIndex.get(name, chunk, hchunk, tptr);
1770 if (OK != rv) return;
1771 IndexType iType = CatalogTableINDEX::getType(tptr);
1772 if (treeIndex != iType)
1774 printf("%s is not a tree index\n ");
1775 return;
1777 Chunk *ch = (Chunk*) chunk;
1778 if(flag){ if(hchunk)((TreeNode*) hchunk)->displayAll(); }
1779 else {
1780 int offset = CatalogTableINDEX::getOffsetOfFirstField(tptr);
1781 //if(typeInt != offset) { printf("%s is not on Integer Type Field. To see info Index should be on integer type field. \n "); return;}
1782 if(hchunk) ((TreeNode*) hchunk)->displayAll(offset);
1786 DbRetVal DatabaseManagerImpl::printIndexInfo(char *name)
1788 CatalogTableINDEX cIndex(systemDatabase_);
1789 DbRetVal rv = OK;
1790 void *chunk = NULL, *hchunk = NULL;
1791 void *tptr =NULL;
1792 rv = cIndex.get(name, chunk, hchunk, tptr);
1793 if (OK != rv) return rv;
1794 printf("<IndexName> %s </IndexName>\n", name);
1795 printf("<Unique> %d </Unique>\n", CatalogTableINDEX::getUnique(tptr));
1796 IndexType iType = CatalogTableINDEX::getType(tptr);
1797 if(hashIndex == iType)
1798 printf("<Type> Hash Index </Type>\n");
1799 else if (treeIndex == iType)
1800 printf("<Type> Tree Index </Type>\n");
1801 else if (trieIndex == iType)
1802 printf("<Type> Trie Index </Type>\n");
1803 else
1804 printf("<Type> Unknown Index </Type>\n");
1806 Chunk *ch = (Chunk*) chunk;
1807 printf("<HashBucket>\n");
1808 printf(" <TotalPages> %d </TotalPages>\n", ch->totalPages());
1809 printf(" <TotalBuckets> %d </TotalBuckets> \n", CatalogTableINDEX::getNoOfBuckets(tptr));
1810 printf("</HashBucket>\n");
1811 printf("<IndexNodes>\n");
1812 if(hashIndex == iType){
1813 ch = (Chunk*) hchunk;
1814 printf(" <TotalPages> %d </TotalPages>\n", ch->totalPages());
1815 printf(" <TotalNodes> %d </TotalNodes>\n", ch->getTotalDataNodes());
1816 } else if (treeIndex == iType) {
1817 printf(" <TotalNodes> %d </TotalNodes>\n", ch->getTotalDataNodes());
1818 if(hchunk)
1819 printf(" <TotalElements> %lld </TotalElements>\n",((TreeNode*) hchunk)->getTotalElements());
1820 else
1821 printf(" <TotalElements> 0 </TotalElements>\n");
1822 } else if (trieIndex == iType)
1824 printf(" <TrieNodes> \n");
1825 printf(" <TotalPages> %d </TotalPages>\n", ch->totalPages());
1826 printf(" <TotalNodes> %d </TotalNodes>\n", ch->getTotalDataNodes());
1827 printf(" </TrieNodes> \n <TrieValues>\n");
1828 ch = (Chunk*) hchunk;
1829 printf(" <TotalPages> %d </TotalPages>\n", ch->totalPages());
1830 printf(" <TotalNodes> %d </TotalNodes>\n", ch->getTotalDataNodes());
1831 printf(" </TrieValues>\n");
1832 } else
1834 printf("Unknown Index type\n");
1836 printf("<IndexNodes>\n");
1837 return OK;
1840 DbRetVal DatabaseManagerImpl::registerThread()
1842 DbRetVal rv = OK;
1843 if (pMgr_ != NULL)
1845 printError(ErrAlready, "Process already registered\n");
1846 return ErrAlready;
1848 pMgr_ = new ProcessManager();
1849 rv = pMgr_->registerThread();
1850 if (rv ==OK) {
1851 procSlot = pMgr_->getProcSlot();
1852 systemDatabase_->setProcSlot(procSlot);
1853 printDebug(DM_Process, "Process registed with slot %d\n", procSlot);
1855 return rv;
1858 DbRetVal DatabaseManagerImpl::deregisterThread()
1860 DbRetVal rv = OK;
1861 if (pMgr_ != NULL)
1863 rv = pMgr_->deregisterThread(procSlot);
1864 delete pMgr_;
1865 pMgr_ = NULL;
1867 return rv;
1870 bool DatabaseManagerImpl::isAnyOneRegistered()
1872 if (pMgr_ != NULL) return pMgr_->isAnyOneRegistered();
1873 return true;
1877 void DatabaseManagerImpl::printUsageStatistics()
1879 pMgr_->printUsageStatistics();
1880 tMgr_->printUsageStatistics();
1881 lMgr_->printUsageStatistics();
1884 void DatabaseManagerImpl::printDebugLockInfo()
1886 lMgr_->printDebugInfo();
1889 void DatabaseManagerImpl::printDebugTransInfo()
1891 tMgr_->printDebugInfo(systemDatabase_);
1893 void DatabaseManagerImpl::printDebugProcInfo()
1895 pMgr_->printDebugInfo();
1897 void DatabaseManagerImpl::printDebugMutexInfo()
1899 Database *db = sysDb();
1900 db->printDebugMutexInfo();
1901 Chunk *chunk;
1902 int id=1;
1903 printf("<Chunk Mutexes>\n");
1904 chunk=db->getSystemDatabaseChunk(UserChunkTableId);
1905 while(id<MAX_CHUNKS)
1907 chunk=db->getSystemDatabaseChunk(id);
1908 if((chunk->getChunkID())!=0){
1909 chunk->printMutexInfo();
1911 id++;
1913 chunk=db->getSystemDatabaseChunk(UserChunkTableId);
1914 size_t size=chunk->getSize();
1915 int noOfDataNodes=os::floor((PAGE_SIZE - sizeof(PageInfo))/size);
1916 Page* page=chunk->getFirstPage();
1917 int i=0;
1918 Chunk *chk;
1919 while(page)
1921 char *data = ((char*)page) + sizeof(PageInfo);
1922 for (i = 0; i< noOfDataNodes; i++)
1924 if (*((InUse*)data) == 1)
1926 chk=(Chunk*)((InUse*)data+1);
1927 chk->printMutexInfo();
1929 data = data + size;
1931 page = (PageInfo*)(((PageInfo*)page)->nextPage_) ;
1933 printf("</Chunk Mutexes>\n");
1934 lMgr_->printMutexInfo();
1936 void DatabaseManagerImpl::printDebugChunkInfo()
1938 Database *db = sysDb();
1939 Chunk *chunk;
1940 int id=1;
1941 printf("<Chunk information>\n");
1942 printf(" <System Chunk >\n");
1943 chunk=db->getSystemDatabaseChunk(UserChunkTableId);
1944 chunk->print();
1945 while(id<MAX_CHUNKS)
1947 chunk=db->getSystemDatabaseChunk(id);
1948 if((chunk->getChunkID())!=0){
1949 chunk->print();
1951 id++;
1953 printf(" </System Chunk >\n");
1954 printf(" <User Chunk >\n");
1955 chunk=db->getSystemDatabaseChunk(UserChunkTableId);
1956 size_t size=chunk->getSize();
1957 int noOfDataNodes=os::floor((PAGE_SIZE - sizeof(PageInfo))/size);
1958 Page* page=chunk->getFirstPage();
1959 int i=0;
1960 Chunk *chk;
1961 while(page)
1963 char *data = ((char*)page) + sizeof(PageInfo);
1964 for (i = 0; i< noOfDataNodes; i++)
1966 if (*((InUse*)data) == 1)
1968 chk=(Chunk*)((InUse*)data+1);
1969 chk->print();
1971 data = data + size;
1973 page = (PageInfo*)(((PageInfo*)page)->nextPage_) ;
1975 printf(" </User Chunk >\n");
1976 printf("</Chunk information>\n");
1977 return;
1979 ChunkIterator DatabaseManagerImpl::getSystemTableIterator(CatalogTableID id)
1981 Chunk *fChunk = systemDatabase_->getSystemDatabaseChunk(id);
1982 return fChunk->getIterator();
1985 Chunk* DatabaseManagerImpl::getSystemTableChunk(CatalogTableID id)
1987 return systemDatabase_->getSystemDatabaseChunk(id);
1990 int DatabaseManagerImpl::getNoOfPagesForTable(char *tblName)
1992 Table *tbl = openTable(tblName);
1993 if (NULL == tbl) {
1994 printError(ErrSysInternal, "Unable to open table %s", tblName);
1995 return 0;
1997 TableImpl *tb = (TableImpl *) tbl;
1998 int pages = 0;
1999 if (tb->numTuples()) pages = tb->pagesUsed();
2000 closeTable(tbl);
2001 return pages;
2004 DbRetVal DatabaseManagerImpl::loadRecords(char *tblName, char *buffer)
2006 // buffer should be as big as the no of pages occupied by the records
2007 Table *tbl = openTable(tblName);
2008 if (NULL == tbl) {
2009 printError(ErrSysInternal, "Unable to open table %s", tblName);
2010 return ErrSysInternal;
2012 TableImpl *tb = (TableImpl *) tbl;
2013 char *bufIter = buffer;
2014 int pages = *(int *) bufIter; bufIter += sizeof(int);
2015 Page *firstPage = ((Chunk *)(tb->chunkPtr_))->getFirstPage();
2016 PageInfo *pi = (PageInfo *) firstPage;
2017 memcpy(bufIter, pi, PAGE_SIZE);
2018 bufIter += PAGE_SIZE;
2019 for (int i = 0; i < pages - 1; i++) {
2020 Page *nPage = pi->nextPage_;
2021 memcpy(bufIter, nPage, PAGE_SIZE);
2022 bufIter += PAGE_SIZE;
2023 pi = (PageInfo *) nPage;
2025 closeTable(tbl);
2026 return OK;
2029 DbRetVal DatabaseManagerImpl::pasteRecords(char *tblName, void *buffer)
2031 // buffer should be as big as the no of pages occupied by the records
2032 Table *tbl = openTable(tblName);
2033 if (NULL == tbl) {
2034 printError(ErrSysInternal, "Unable to open table %s", tblName);
2035 return ErrSysInternal;
2037 TableImpl *tb = (TableImpl *) tbl;
2038 Database *db = tb->getDB();
2039 char *bufIter = (char *) buffer;
2040 int pages = *(int *) bufIter;
2041 bufIter += sizeof(int);
2043 Page *firstPage = ((Chunk *)(tb->chunkPtr_))->getFirstPage();
2044 PageInfo *pi = (PageInfo *) firstPage;
2045 memcpy(pi, bufIter, PAGE_SIZE);
2046 bufIter += PAGE_SIZE;
2047 while (--pages != 0) {
2048 //get a new page allocated
2049 Page *newPage = db->getFreePage();
2050 memcpy(newPage, bufIter, PAGE_SIZE);
2051 pi->nextPage_ = newPage;
2052 pi = (PageInfo *) newPage;
2054 // initialize chunk details and pageInfo
2055 ((Chunk *)tb->chunkPtr_)->curPage_ = pi;
2056 closeTable(tbl);
2057 return OK;
2060 void DatabaseManagerImpl::setCanTakeCheckPoint(bool ctcp)
2061 { systemDatabase_->setCanTakeCheckPoint(ctcp); }
2063 bool DatabaseManagerImpl::getCanTakeCheckPoint()
2064 { return systemDatabase_->getCanTakeCheckPoint(); }
2066 DbRetVal DatabaseManagerImpl::checkPoint()
2068 if (!systemDatabase_->getCanTakeCheckPoint()) {
2069 printf("Load / Cache / Replication process might be running. CheckPoint not taken\n");
2070 return ErrLoadingOn;
2072 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
2073 if (OK != rv ) {
2074 printError(rv, "Unable to get checkpoint mutex");
2075 return ErrLockTimeOut;
2077 if (tMgr_ && !tMgr_->isTransactionConsistent(systemDatabase_)) {
2078 printf("not in transaction consistent point\n");
2079 systemDatabase_->releaseCheckpointMutex();
2080 return ErrLockTimeOut;
2082 rv = writeSchemaFile();
2083 if (rv != OK) {
2084 printError(ErrSysInternal, "checkpoint error");
2086 rv = db()->checkPoint();
2087 systemDatabase_->releaseCheckpointMutex();
2088 return rv;
2091 DbRetVal DatabaseManagerImpl::writeSchemaFile()
2093 DbRetVal rv = OK;
2094 FILE *fp = NULL;
2095 FILE *fp1 = NULL;
2096 int fd = -1;
2097 char schFile[MAX_FILE_LEN];
2098 char mapFile[MAX_FILE_LEN];
2099 sprintf(schFile, "%s/db.chkpt.schema1", Conf::config.getDbFile());
2100 sprintf(mapFile, "%s/db.chkpt.map1", Conf::config.getDbFile());
2101 fp = fopen(schFile, "r");
2102 if (fp != NULL) {
2103 fclose(fp);
2104 int ret = unlink(schFile);
2105 if( ret != 0) {
2106 printError(ErrOS, "checkpoint: delete schema file failed");
2107 return ErrOS;
2110 fp = fopen(schFile, "w+");
2111 if (fp == NULL) {
2112 printError(ErrOS, "Unable to create schema file for chkpt.");
2113 return ErrOS;
2115 fp1 = fopen(mapFile, "r");
2116 if (fp1 != NULL) {
2117 fclose(fp1);
2118 int ret = unlink(mapFile);
2119 if( ret != 0) {
2120 printError(ErrOS, "checkpoint: delete schema file failed");
2121 return ErrOS;
2124 fd = open(mapFile, O_WRONLY|O_CREAT, 0644);
2125 if (fd == -1) {
2126 printError(ErrOS, "checkpoint: Unable to create map file.");
2127 return ErrOS;
2129 List tableList = getAllTableNames();
2130 ListIterator iter = tableList.getIterator();
2131 Identifier *elem = NULL;
2132 int count =0;
2133 while (iter.hasElement()) {
2134 elem = (Identifier*) iter.nextElement();
2135 // if (TableConf::config.isTableCached(elem->name) == OK) continue;
2136 fprintf(fp, "CREATE TABLE %s (", elem->name);
2137 Table *table = openTable(elem->name);
2138 if (NULL == table) {
2139 printError(ErrSysInternal, "Unable to open table %s", elem->name);
2140 return ErrSysInternal;
2142 void *chunk = NULL; void *tptr = NULL; void *vcchunk = NULL;
2143 CatalogTableTABLE cTable(systemDatabase_);
2144 rv = cTable.getChunkAndTblPtr(elem->name, chunk, tptr, vcchunk);
2145 struct Object obj;
2146 strcpy(obj.name, elem->name);
2147 obj.type = Tbl;
2148 obj.bucketChunk = NULL;
2149 obj.firstPage = ((Chunk *)chunk)->getFirstPage();
2150 obj.curPage = ((Chunk *)chunk)->getCurrentPage();
2151 void *buf = &obj;
2152 write(fd, buf, sizeof(obj));
2153 FieldInfo *info = new FieldInfo();
2154 List fNameList = table->getFieldNameList();
2155 ListIterator fNameIter = fNameList.getIterator();
2156 count++;
2157 bool firstField=true;
2158 char fieldName[IDENTIFIER_LENGTH];
2159 while (fNameIter.hasElement()) {
2160 elem = (Identifier*) fNameIter.nextElement();
2161 Table::getFieldNameAlone(elem->name, fieldName);
2162 rv = table->getFieldInfo(elem->name, info);
2163 if (rv !=OK) {
2164 printf("unable to retrive info for table %s\n", elem->name);
2166 if (firstField) {
2167 fprintf(fp, "%s %s ", fieldName, AllDataType::getSQLString(info->type));
2168 firstField = false;
2169 } else
2170 fprintf(fp, ", %s %s ", fieldName, AllDataType::getSQLString(info->type));
2171 if (info->type == typeString || info->type == typeVarchar ||
2172 info->type == typeBinary)
2173 fprintf(fp, "(%d)",info->length);
2174 if (info->isNull) fprintf(fp, " NOT NULL ");
2175 if (info->isDefault) fprintf(fp, " DEFAULT '%s' ", info->defaultValueBuf);
2176 if (info->isAutoIncrement) fprintf(fp, " AUTO_INCREMENT ");
2178 fNameIter.reset();
2179 while (fNameIter.hasElement())
2180 delete ((FieldName *) fNameIter.nextElement());
2181 fNameList.reset();
2183 fprintf(fp, ");\n");
2184 table->printSQLIndexString(fp, fd);
2185 delete info;
2186 closeTable(table);
2188 ListIterator tIter = tableList.getIterator();
2189 tIter.reset();
2190 while (tIter.hasElement())
2191 delete ((FieldName *) tIter.nextElement());
2192 tableList.reset();
2194 fclose(fp);
2195 close(fd);
2196 return OK;
2199 DbRetVal DatabaseManagerImpl::recover()
2201 DbRetVal rv = OK;
2202 rv = sysDb()->recoverSystemDB();
2203 if (rv != OK) return rv;
2204 if (!Conf::config.useMmap())rv = db()->recoverUserDB();
2205 return rv;
2208 void DatabaseManagerImpl::sendSignal(int signal)
2210 ThreadInfo* tInfo = sysDb()->getThreadInfo(0);
2211 for (int i=0; i < Conf::config.getMaxProcs(); i++)
2213 if (tInfo->pid_ !=0) os::kill(tInfo->pid_, signal);
2214 tInfo++;