*** empty log message ***
[csql.git] / src / storage / DatabaseManagerImpl.cxx
blobb9e402ba63ed3e574b69bb02ee296c4bbc8ad1ee
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 chunkInfo->initMutex();
421 if (0 != size) chunkInfo->setSize(size);
422 if (chunkInfo->allocSize_ > PAGE_SIZE)
423 chunkInfo->curPage_ = db_->getFreePage(chunkInfo->allocSize_);
424 else
425 chunkInfo->curPage_ = db_->getFreePage();
426 if ( NULL == chunkInfo->curPage_)
428 chunkInfo->destroyMutex();
429 chunk->free(db_, ptr);
430 printError(ErrNoMemory, "Database full: No space to allocate from database");
431 return NULL;
433 PageInfo* firstPageInfo = ((PageInfo*)chunkInfo->curPage_);
434 if (chunkInfo->allocSize_ > PAGE_SIZE)
436 int multiple = os::floor(chunkInfo->allocSize_ / PAGE_SIZE);
437 int offset = ((multiple + 1) * PAGE_SIZE);
438 firstPageInfo->setPageAsUsed(offset);
440 else
442 firstPageInfo->setPageAsUsed(chunkInfo->allocSize_);
443 char *data = ((char*)firstPageInfo) + sizeof(PageInfo);
444 *(InUse*)data =0;
446 if (0 == size)
448 VarSizeInfo *varInfo = (VarSizeInfo*)(((char*)firstPageInfo) + sizeof(PageInfo));
449 varInfo->isUsed_ = 0;
450 varInfo->size_ = PAGE_SIZE - sizeof(PageInfo) - sizeof(VarSizeInfo);
453 chunkInfo->firstPage_ = chunkInfo->curPage_;
455 if (0 == size)
456 chunkInfo->setAllocType(VariableSizeAllocator);
457 else
458 chunkInfo->setAllocType(FixedSizeAllocator);
460 //TODO::Generate chunkid::use tableid
461 chunkInfo->setChunkID(db_->getUniqueIDForChunk());
462 db_->incrementChunk();
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 rv = lMgr_->getExclusiveLock(chunk, NULL);
727 if (rv !=OK)
729 systemDatabase_->releaseCheckpointMutex();
730 printError(ErrLockTimeOut, "Unable to acquire exclusive lock on the table\n");
731 return rv;
734 rv = cTable.remove(name, chunk, tptr);
735 if (OK != rv) {
736 systemDatabase_->releaseCheckpointMutex();
737 printError(ErrSysInternal, "Unable to update catalog table TABLE");
738 return ErrSysInternal;
740 printDebug(DM_Database,"Deleted from TABLE:%s",name);
742 //remove the entries in the FIELD table
743 CatalogTableFIELD cField(systemDatabase_);
744 rv = cField.remove(tptr);
745 if (OK != rv) {
746 systemDatabase_->releaseCheckpointMutex();
747 printError(ErrSysInternal, "Unable to update catalog table FIELD");
748 return ErrSysInternal;
750 printDebug(DM_Database,"Deleted from FIELD:%s",name);
752 rv = deleteUserChunk((Chunk*)chunk);
753 if (OK != rv) {
754 systemDatabase_->releaseCheckpointMutex();
755 printError(rv, "Unable to delete the chunk");
756 return rv;
758 printDebug(DM_Database,"Deleted UserChunk:%x", chunk);
760 if (vcchunk != NULL) {
761 rv = deleteUserChunk((Chunk*)vcchunk);
762 if (OK != rv) {
763 systemDatabase_->releaseCheckpointMutex();
764 printError(rv, "Unable to delete the chunk");
765 return rv;
767 printDebug(DM_Database,"Deleted UserChunk for Varchar:%x", chunk);
770 //TODO::check whether indexes are available and drop that also.
771 CatalogTableINDEX cIndex(systemDatabase_);
772 int noIndexes = cIndex.getNumIndexes(tptr);
773 for (int i =1 ; i<= noIndexes; i++) {
774 char *idxName = cIndex.getIndexName(tptr, 1);
775 dropIndexInt(idxName, false);
777 bool isFkExist=cFK.isFkTable(tptr);
778 if(isFkExist)
780 dropForeignKey(tptr,false);
782 systemDatabase_->releaseCheckpointMutex();
783 printDebug(DM_Database, "Deleted Table %s" , name);
784 logFinest(Conf::logger, "Deleted Table %s" , name);
785 rv = lMgr_->releaseLock(chunk);
786 if (rv !=OK)
788 printError(ErrLockTimeOut, "Unable to release exclusive lock on the table\n");
789 return rv;
791 return OK;
794 //Return values: NULL for table not found
795 Table* DatabaseManagerImpl::openTable(const char *name,bool checkpkfk)
797 DbRetVal ret = OK;
798 //TODO::store table handles in list so that if it is
799 //not closed by the application. destructor shall close it.
800 TableImpl *table = new TableImpl();
801 table->setDB(db_);
802 table->setSystemDB(systemDatabase_);
803 table->setLockManager(lMgr_);
804 table->setTrans(ProcessManager::getThreadTransAddr(systemDatabase_->procSlot));
806 //to store the chunk pointer of table
807 void *chunk = NULL;
808 void *vcchunk = NULL;
810 //to store the tuple pointer of the table
811 void *tptr =NULL;
813 //TODO::need to take shared lock on the table so that
814 //all ddl operation will be denied on that table
815 //which includes index creation, alter table
817 DbRetVal rv = systemDatabase_->getAllocDatabaseMutex();
818 if (OK != rv) {
819 printError(ErrSysInternal, "Unable to get database mutex");
820 delete table;
821 return NULL;
823 CatalogTableTABLE cTable(systemDatabase_);
824 ret = cTable.getChunkAndTblPtr(name, chunk, tptr, vcchunk);
825 if ( OK != ret)
827 systemDatabase_->releaseAllocDatabaseMutex();
828 delete table;
829 printError(ErrNotExists, "Table not exists %s", name);
830 return NULL;
832 CTABLE *tTuple = (CTABLE*)tptr;
833 table->setTableInfo(tTuple->tblName_, tTuple->tblID_, tTuple->length_,
834 tTuple->numFlds_, tTuple->numIndexes_,
835 tTuple->chunkPtr_, tTuple->varcharChunkPtr_);
836 /*rv = table->lock(true); //take shared lock
837 if (rv !=OK)
839 printError(ErrLockTimeOut, "Unable to acquire shared lock on the table\n");
840 systemDatabase_->releaseAllocDatabaseMutex();
841 delete table;
842 return NULL;
846 if (tTuple->numFlds_ <= 32)
848 table->isIntUsedForNULL = true;
849 table->iNullInfo = 0;
850 table->iNotNullInfo =0;
852 else
854 table->isIntUsedForNULL = false;
855 int noFields = os::align(tTuple->numFlds_);
856 table->cNullInfo = (char*) malloc(noFields);
857 table->cNotNullInfo = (char*) malloc(noFields);
858 for (int i =0 ; i < noFields; i++) table->cNullInfo[i] =0;
859 for (int i =0 ; i < noFields; i++) table->cNotNullInfo[i] =0;
863 //get field information from FIELD table
864 CatalogTableFIELD cField(systemDatabase_);
865 table->ptrToAuto = cField.getFieldInfo(tptr, table->fldList_);
867 //populate the notnull info
868 FieldIterator fIter = table->fldList_.getIterator();
869 int fldpos=1;
870 while (fIter.hasElement())
872 FieldDef *def = fIter.nextElement();
873 if (table->isIntUsedForNULL) {
874 if (def->isNull_) SETBIT(table->iNotNullInfo, fldpos-1);
876 else {
877 if (def->isNull_) table->cNotNullInfo[fldpos-1] = 1;
879 fldpos++;
882 //get the number of indexes on this table
883 //and populate the indexPtr array
884 CatalogTableINDEX cIndex(systemDatabase_);
885 table->numIndexes_ = cIndex.getNumIndexes(tptr);
886 if (table->numIndexes_) {
887 table->indexPtr_ = new char*[table->numIndexes_];
888 table->idxInfo = new IndexInfo*[table->numIndexes_];
890 else
892 table->indexPtr_ = NULL;
894 cIndex.getIndexPtrs(tptr, table->indexPtr_);
895 for (int i =0 ; i < table->numIndexes_; i++ )
897 HashIndexInfo *hIdxInfo = new HashIndexInfo();
898 CatalogTableINDEXFIELD cIndexField(systemDatabase_);
899 cIndexField.getFieldInfo(table->indexPtr_[i], hIdxInfo->idxFldList);
900 ChunkIterator citer = CatalogTableINDEX::getIterator(table->indexPtr_[i]);
901 hIdxInfo->indexPtr = table->indexPtr_[i];
902 hIdxInfo->indType = ((CINDEX*)hIdxInfo->indexPtr)->indexType_;
903 hIdxInfo->noOfBuckets = CatalogTableINDEX::getNoOfBuckets(table->indexPtr_[i]);
904 FieldIterator fIter = hIdxInfo->idxFldList.getIterator();
905 bool firstFld = true;
906 while (fIter.hasElement())
908 FieldDef *def = fIter.nextElement();
909 if (firstFld)
911 hIdxInfo->fldOffset = table->fldList_.getFieldOffset(def->fldName_);
912 hIdxInfo->type = table->fldList_.getFieldType(def->fldName_);
913 hIdxInfo->compLength = table->fldList_.getFieldLength(def->fldName_);
914 firstFld = false;
915 }else {
916 hIdxInfo->type = typeComposite;
917 hIdxInfo->compLength = hIdxInfo->compLength +
918 table->fldList_.getFieldLength(def->fldName_);
922 hIdxInfo->isUnique = CatalogTableINDEX::getUnique(table->indexPtr_[i]);
923 hIdxInfo->buckets = (Bucket*)citer.nextElement();
924 table->idxInfo[i] = (IndexInfo*) hIdxInfo;
926 systemDatabase_->releaseAllocDatabaseMutex();
927 //Foreign key Operation
928 if(checkpkfk){
929 CatalogTableFK cFk(systemDatabase_);
930 int totalFld=0;
931 table->numFkRelation_ = cFk.getNumFkTable(tptr);
932 if (table->numFkRelation_) {
933 table->isPkTbl=true;//TODO:for Delete In casecade
934 totalFld=cFk.getNoOfFkTable(tptr);
935 //printDebug(DM_TEST,"Total table is %d\n",totalFld);
936 char **fptr = new char* [totalFld];
937 cFk.getFkTableName(tptr,fptr);
938 for(int count=0; count < totalFld; count++){
939 //printDebug(DM_TEST,"FK Name is %s\n",fptr[count]);
940 Table *pkTable=openTable(fptr[count],false);
941 if (pkTable) table->tblFkList.append(pkTable);
942 else {
943 printError(ErrSysInternal, "Unable to open foreign key tables");
944 delete[] fptr;
945 pkTable->close();
946 return NULL;
949 delete[] fptr;
952 char *tblName = NULL;
953 table->isFkTbl = cFk.isFkTable(tptr);
954 if(table->isFkTbl)
956 totalFld=cFk.getNoOfPkTable(tptr);
957 char **fptr = new char* [totalFld];
958 cFk.getPkTableName(tptr,fptr);
959 for(int count=0; count<totalFld; count++){
960 //printDebug(DM_TEST,"Parent Name is %s\n",fptr[count]);
961 Table *fkTable = openTable(fptr[count],false);
962 if (fkTable) table->tblList.append(fkTable);
963 else {
964 printError(ErrSysInternal, "Unable to open foreign key tables");
965 delete[] fptr;
966 fkTable->close();
967 return NULL;
970 delete[] fptr;
973 printDebug(DM_Database,"Opening table handle name:%s chunk:%x numIndex:%d",
974 name, chunk, table->numIndexes_);
975 logFinest(Conf::logger, "Opening Table %s" , name);
976 return table;
979 List DatabaseManagerImpl::getAllTableNames(int *retval)
981 DbRetVal ret = OK;
982 //to store the tuple pointer of the table
983 void *tptr =NULL;
985 /*DbRetVal rv = systemDatabase_->getSCheckpointMutex();
986 if (OK != rv) {
987 printError(ErrSysInternal, "Unable to get checkpoint mutex");
988 if(retval) *retval = rv;
989 List tableList;
990 return tableList;
992 CatalogTableTABLE cTable(systemDatabase_);
993 List tableList = cTable.getTableList();
994 //systemDatabase_->releaseCheckpointMutex();
995 return tableList;
1001 //Return values: -1 for table not found
1002 void DatabaseManagerImpl::closeTable(Table *table)
1004 printDebug(DM_Database,"Closing table handle: %x", table);
1005 if (NULL == table) return;
1006 //table->unlock();
1007 /* TableImpl *fkTbl =NULL;
1008 ListIterator tblIter = ((TableImpl*)table)->tblList.getIterator();
1009 tblIter.reset();
1010 while (tblIter.hasElement()){
1011 fkTbl = (TableImpl *) tblIter.nextElement();
1012 closeTable(fkTbl);
1014 ((TableImpl*)table)->tblList.reset();
1015 tblIter = ((TableImpl*)table)->tblFkList.getIterator();
1016 tblIter.reset();
1017 while (tblIter.hasElement()){
1018 fkTbl = (TableImpl *) tblIter.nextElement();
1019 closeTable(fkTbl);
1021 ((TableImpl*)table)->tblFkList.reset();*/
1022 if (table) delete table; table = NULL;
1023 logFinest(Conf::logger, "Closing Table");
1026 DbRetVal DatabaseManagerImpl::createIndex(const char *indName, IndexInitInfo *info)
1028 DbRetVal rv = OK;
1029 if (!info->isUnique && info->isPrimary)
1031 printError(ErrBadCall, "Primary key cannot be non unique\n");
1032 return ErrBadCall;
1034 if (!Util::isIdentifier((char*)indName)) {
1035 printError(ErrBadArg, "Invalid character for index name");
1036 return ErrBadArg;
1039 if (info->indType == hashIndex)
1041 //Assumes info is of type HashIndexInitInfo
1042 HashIndexInitInfo *hInfo = (HashIndexInitInfo*) info;
1043 rv = createHashIndex(indName, info->tableName, info->list, hInfo->bucketSize,
1044 info->isUnique, info->isPrimary);
1046 else if (info->indType == treeIndex)
1048 HashIndexInitInfo *hInfo = (HashIndexInitInfo*) info;
1049 rv = createTreeIndex(indName, info->tableName, info->list,
1050 hInfo->bucketSize, info->isUnique, info->isPrimary);
1052 else if (info->indType == trieIndex)
1054 HashIndexInitInfo *hInfo = (HashIndexInitInfo*) info;
1055 rv = createTrieIndex(indName, info->tableName, info->list,
1056 info->isUnique, info->isPrimary);
1058 }else {
1059 printError(ErrBadCall, "Index type not supported\n");
1060 return ErrBadCall;
1062 return rv;
1066 //-1 -> Table does not exists
1067 //-2 -> Field does not exists
1068 //-3 -> bucketSize is not valid
1069 DbRetVal DatabaseManagerImpl::createHashIndex(const char *indName, const char *tblName,
1070 FieldNameList &fldList, int bucketSize, bool isUnique, bool isPrimary)
1072 //validate the bucket size
1073 if (bucketSize < 100 || bucketSize > 200000)
1075 printError(ErrBadRange, "Index Bucket size %d not in range 100-200000",
1076 bucketSize);
1077 return ErrBadRange;
1079 int totFlds = fldList.size();
1080 if (totFlds == 0)
1082 printError(ErrBadCall, "No Field name specified");
1083 return ErrBadCall;
1085 void *tptr =NULL;
1086 void *chunk = NULL;
1087 void *vcchunk = NULL;
1088 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
1089 if (OK != rv)
1091 printError(ErrSysInternal, "Unable to get database mutex");
1092 return ErrSysInternal;
1095 //check whether table exists
1096 CatalogTableTABLE cTable(systemDatabase_);
1097 cTable.getChunkAndTblPtr(tblName, chunk, tptr, vcchunk);
1098 if (NULL == tptr)
1100 systemDatabase_->releaseCheckpointMutex();
1101 printError(ErrNotExists, "Table does not exist %s", tblName);
1102 return ErrNotExists;
1105 //check whether field exists
1106 char **fptr = new char* [totFlds];
1107 CatalogTableFIELD cField(systemDatabase_);
1108 rv = cField.getFieldPtrs(fldList, tptr, fptr);
1109 if (OK != rv)
1111 delete[] fptr;
1112 systemDatabase_->releaseCheckpointMutex();
1113 //TODO::check test cases of dbapi/Index, they give wrong results
1114 //if (rv == ErrBadCall) {
1115 //// if (isPrimary) printError(ErrBadCall, "Field can have NULL values");
1116 //} else {
1117 //printError(ErrNotExists, "Field does not exist");
1118 //}
1119 //return ErrBadCall;
1120 if (rv != ErrBadCall) {
1121 printError(ErrNotExists, "Field does not exist");
1122 return ErrNotExists;
1125 for (int i=0; i <totFlds; i++)
1127 CFIELD* fInfo = (CFIELD*)fptr[i];
1128 if (fInfo->type_ == typeFloat || fInfo->type_ == typeDouble || fInfo->type_ == typeTimeStamp)
1130 printError(ErrBadArg, "HashIndex cannot be created for float or double or timestamp type");
1131 delete[] fptr;
1132 systemDatabase_->releaseCheckpointMutex();
1133 return ErrBadArg;
1135 if (!fInfo->isNull_ && isPrimary )
1137 printError(ErrBadArg, "Primary Index cannot be created on field without NOTNULL constraint");
1138 delete[] fptr;
1139 systemDatabase_->releaseCheckpointMutex();
1140 return ErrBadArg;
1142 if(isPrimary){fInfo->isPrimary_=true;fInfo->isUnique_=true;}
1143 if(isUnique){fInfo->isUnique_=true;}
1145 //create chunk to store the meta data of the index created
1146 //for latches and bucket pointers
1147 printDebug(DM_HashIndex, "Creating chunk for storing hash buckets of size %d\n",
1148 bucketSize * sizeof(Bucket));
1149 Chunk* chunkInfo = createUserChunk(bucketSize * sizeof(Bucket));
1150 if (NULL == chunkInfo)
1152 delete[] fptr;
1153 systemDatabase_->releaseCheckpointMutex();
1154 printError(ErrSysInternal, "Unable to create chunk");
1155 return ErrSysInternal;
1157 chunkInfo->setChunkName(indName);
1158 //create memory for holding the bucket pointers
1159 void *buckets = chunkInfo->allocate(db_, &rv);
1160 if (NULL == buckets)
1162 delete[] fptr;
1163 deleteUserChunk(chunkInfo);
1164 systemDatabase_->releaseCheckpointMutex();
1165 printError(rv, "Unable to allocate memory for bucket");
1166 return rv;
1168 Bucket *buck = (Bucket*) buckets;
1169 initHashBuckets(buck, bucketSize);
1171 //create chunk to store the hash index nodes
1172 Chunk* hChunk = createUserChunk(sizeof(IndexNode));
1173 if (NULL == hChunk)
1175 delete[] fptr;
1176 deleteUserChunk(chunkInfo);
1177 systemDatabase_->releaseCheckpointMutex();
1178 printError(ErrSysInternal, "Unable to create chunk for storing hash index nodes");
1179 return ErrSysInternal;
1182 hChunk->setChunkName(indName);
1183 //add row to INDEX
1184 void *tupleptr = NULL;
1185 CatalogTableINDEX cIndex(systemDatabase_);
1186 rv = cIndex.insert(indName, tptr, fldList.size(), isUnique,
1187 chunkInfo, bucketSize, hChunk, tupleptr);
1188 if (OK != rv)
1190 delete[] fptr;
1191 deleteUserChunk(hChunk);
1192 deleteUserChunk(chunkInfo);
1193 systemDatabase_->releaseCheckpointMutex();
1194 printError(ErrSysInternal, "Catalog table updation failed in INDEX table");
1195 return ErrSysInternal;
1197 //add rows to INDEXFIELD
1198 CatalogTableINDEXFIELD cIndexField(systemDatabase_);
1199 rv = cIndexField.insert(fldList, tupleptr, tptr, fptr);
1201 if (OK != rv)
1203 delete[] fptr;
1204 cIndex.remove(indName, (void *&)chunkInfo, (void *&)hChunk, (void *&)tupleptr);
1205 deleteUserChunk(hChunk);
1206 deleteUserChunk(chunkInfo);
1207 systemDatabase_->releaseCheckpointMutex();
1208 printError(ErrSysInternal, "Catalog table updation failed in INDEXFIELD table");
1209 return ErrSysInternal;
1211 delete[] fptr;
1212 systemDatabase_->releaseCheckpointMutex();
1214 //TODO:: Take table lock
1216 // Following code is written by Kishor Amballi
1217 TableImpl *tbl = (TableImpl *) openTable(tblName);
1218 if (NULL == tbl) {
1219 printError(ErrSysInternal, "Unable to open table %s", tblName);
1220 return ErrSysInternal;
1222 if (! tbl->numTuples()) {
1223 printDebug(DM_Database, "Creating Hash Index Name:%s tblname:%s buckets:%x", indName, tblName, buckets);
1224 logFinest(Conf::logger, "Creating HashIndex %s on %s with bucket size %d", indName, tblName, buckets);
1225 closeTable(tbl);
1226 return OK;
1228 HashIndexInfo *indxInfo = NULL;
1229 int i = 0;
1230 for (i = 0; i < tbl->numIndexes_; i++) {
1231 if(((HashIndexInfo *)tbl->idxInfo[i])->indexPtr == tupleptr) {
1232 indxInfo = (HashIndexInfo *) tbl->idxInfo[i];
1233 break;
1236 void *recPtr = NULL;
1237 ChunkIterator chIter = ((Chunk *)chunk)->getIterator();
1238 tbl->setLoading(true);
1239 while ((recPtr = chIter.nextElement()) != NULL) {
1240 rv = tbl->insertIndexNode(*tbl->trans, tupleptr, indxInfo, recPtr);
1241 if (rv == ErrUnique) {
1242 closeTable(tbl);
1243 dropIndex(indName);
1244 return rv;
1247 closeTable(tbl);
1248 printDebug(DM_Database, "Creating Hash Index Name:%s tblname:%s buckets:%x", indName, tblName, buckets);
1249 logFinest(Conf::logger, "Creating HashIndex %s on %s with bucket size %d", indName, tblName, buckets);
1250 return OK;
1254 DbRetVal DatabaseManagerImpl::createTreeIndex(const char *indName, const char *tblName,
1255 FieldNameList &fldList, int nodeSize, bool isUnique, bool isPrimary)
1257 if (nodeSize < 20 || nodeSize > 20000)
1259 printError(ErrBadRange,"Tree Index Node size %d not in range 20-20000",
1260 nodeSize);
1261 return ErrBadRange;
1263 int totFlds = fldList.size();
1264 if (totFlds == 0) {
1265 printError(ErrBadCall, "No Field name specified");
1266 return ErrBadCall;
1267 }else if (totFlds != 1) {
1268 printError(ErrBadCall, "Composite index not supported for Tree");
1269 return ErrBadCall;
1271 void *tptr =NULL;
1272 void *chunk = NULL;
1273 void *vcchunk = NULL;
1274 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
1275 if (OK != rv)
1277 printError(ErrSysInternal, "Unable to get database mutex");
1278 return ErrSysInternal;
1280 //check whether table exists
1282 CatalogTableTABLE cTable(systemDatabase_);
1283 cTable.getChunkAndTblPtr(tblName, chunk, tptr, vcchunk);
1284 if (NULL == tptr)
1286 systemDatabase_->releaseCheckpointMutex();
1287 printError(ErrNotExists, "Table does not exist %s", tblName);
1288 return ErrNotExists;
1290 char **fptr = new char* [totFlds];
1291 CatalogTableFIELD cField(systemDatabase_);
1292 rv = cField.getFieldPtrs(fldList, tptr, fptr);
1293 if (OK != rv)
1295 delete[] fptr;
1296 systemDatabase_->releaseCheckpointMutex();
1297 if (rv != ErrBadCall) {
1298 printError(ErrNotExists, "Field does not exist");
1299 return ErrNotExists;
1302 for (int i=0; i <totFlds; i++)
1304 CFIELD* fInfo = (CFIELD*)fptr[i];
1305 if (!fInfo->isNull_ && isPrimary )
1307 printError(ErrBadArg, "Primary Index cannot be created on field without NOTNULL constraint");
1308 delete[] fptr;
1309 systemDatabase_->releaseCheckpointMutex();
1310 return ErrBadArg;
1312 if (fInfo->type_ == typeVarchar)
1314 printError(ErrBadArg, "Tree Index not supported for varchar type. Use char data type instead.");
1315 delete[] fptr;
1316 systemDatabase_->releaseCheckpointMutex();
1317 return ErrBadArg;
1321 int chunkSize = sizeof(TreeNode)+(nodeSize * sizeof(void*));
1322 printDebug(DM_HashIndex, "Creating chunk for storing tree nodes of size %d\n", chunkSize);
1324 Chunk* chunkInfo = createUserChunk(chunkSize);
1325 if (NULL == chunkInfo)
1327 delete[] fptr;
1328 systemDatabase_->releaseCheckpointMutex();
1329 printError(ErrSysInternal, "Unable to create chunk");
1330 return ErrSysInternal;
1334 void *tupleptr = NULL;
1336 CatalogTableINDEX cIndex(systemDatabase_);
1337 rv = cIndex.insert(indName, tptr, fldList.size(), isUnique,
1338 chunkInfo, nodeSize, NULL, tupleptr);
1339 if (OK != rv)
1341 delete[] fptr;
1342 deleteUserChunk(chunkInfo);
1343 systemDatabase_->releaseCheckpointMutex();
1344 printError(ErrSysInternal, "Catalog table updation failed in INDEX table");
1345 return ErrSysInternal;
1347 CatalogTableINDEXFIELD cIndexField(systemDatabase_);
1348 rv = cIndexField.insert(fldList, tupleptr, tptr, fptr);
1350 if (OK != rv)
1352 delete[] fptr;
1353 void *hChunk = NULL;
1354 cIndex.remove(indName, (void *&)chunkInfo, (void *&)hChunk, (void *&)tupleptr);
1355 deleteUserChunk(chunkInfo);
1356 systemDatabase_->releaseCheckpointMutex();
1357 printError(ErrSysInternal, "Catalog table updation failed in INDEXFIELD table");
1358 return ErrSysInternal;
1360 delete[] fptr;
1361 systemDatabase_->releaseCheckpointMutex();
1362 //TODO::if tuples already present in this table, then create tree index '
1363 //nodes
1364 TableImpl *tbl = (TableImpl *) openTable(tblName);
1365 if (NULL == tbl) {
1366 printError(ErrSysInternal, "Unable to open table %s", tblName);
1367 return ErrSysInternal;
1369 if (! tbl->numTuples()) {
1370 printDebug(DM_Database, "Creating Tree Index Name:%s tblname:%s node size:%x",indName, tblName, nodeSize);
1371 logFinest(Conf::logger, "Creating TreeIndex %s on %s with node size %d",indName, tblName, nodeSize);
1372 closeTable(tbl);
1373 return OK;
1375 HashIndexInfo *indxInfo = NULL;
1376 int i = 0;
1377 for (i = 0; i < tbl->numIndexes_; i++) {
1378 if(((HashIndexInfo *)tbl->idxInfo[i])->indexPtr == tupleptr) {
1379 indxInfo = (HashIndexInfo *) tbl->idxInfo[i];
1380 break;
1383 void *recPtr = NULL;
1384 ChunkIterator chIter = ((Chunk *)chunk)->getIterator();
1385 tbl->setLoading(true);
1386 while ((recPtr = chIter.nextElement()) != NULL) {
1387 rv = tbl->insertIndexNode(*tbl->trans, tupleptr, indxInfo, recPtr);
1388 if (rv == ErrUnique) {
1389 dropIndex(indName);
1390 closeTable(tbl);
1391 return rv;
1394 closeTable(tbl);
1395 printDebug(DM_Database, "Creating Tree Index Name:%s tblname:%s node size:%x",
1396 indName, tblName, nodeSize);
1397 logFinest(Conf::logger, "Creating TreeIndex %s on %s with node size %d",
1398 indName, tblName, nodeSize);
1399 return OK;
1402 DbRetVal DatabaseManagerImpl::createTrieIndex(const char *indName, const char *tblName,
1403 FieldNameList &fldList, bool isUnique, bool isPrimary)
1405 int totFlds = fldList.size();
1406 void *tptr =NULL;
1407 char **fptr = new char* [totFlds];
1408 DbRetVal rv = validateIndex(tblName, fldList, &tptr, &fptr, isPrimary);
1409 if (OK != rv)
1411 delete[] fptr;
1412 return rv;
1414 rv = systemDatabase_->getXCheckpointMutex();
1415 if (OK != rv)
1417 printError(ErrSysInternal, "Unable to get database mutex");
1418 return ErrSysInternal;
1421 //below statements are actually setting values in the catalog table
1422 //thats why mutex is taken before this stmt. Do not change the order
1423 CFIELD* fInfo = (CFIELD*)fptr[0];
1424 if(isPrimary){fInfo->isPrimary_=true;fInfo->isUnique_=true;}
1425 if(isUnique){fInfo->isUnique_=true;}
1427 printDebug(DM_TrieIndex, "Creating chunk for storing trie nodes\n" );
1428 Chunk* chunkInfo = createUserChunk(sizeof(TrieNode));
1430 //chunk to store the linked list of trie values
1431 Chunk* hChunk = createUserChunk(sizeof(IndexNode));
1432 if (NULL == chunkInfo || NULL == hChunk)
1434 delete[] fptr;
1435 if (chunkInfo) deleteUserChunk(chunkInfo);
1436 systemDatabase_->releaseCheckpointMutex();
1437 printError(ErrSysInternal, "Unable to create trie node chunk");
1438 return ErrSysInternal;
1440 chunkInfo->setChunkName(indName);
1441 hChunk->setChunkName(indName);
1442 rv = updateIndexCatalogTables(indName,tptr, fptr, fldList, isUnique,
1443 chunkInfo, hChunk );
1444 delete[] fptr;
1445 if (OK != rv) {
1446 printError(ErrSysInternal, "Catalog table updation failed");
1447 deleteUserChunk(chunkInfo);
1448 deleteUserChunk(hChunk);
1449 systemDatabase_->releaseCheckpointMutex();
1450 return rv;
1452 systemDatabase_->releaseCheckpointMutex();
1453 //TODO:: create index nodes if records already exist in the table
1454 return OK;
1456 DbRetVal DatabaseManagerImpl::validateIndex(const char *tblName,
1457 FieldNameList &fldList, void **tptr, char ***fptr,
1458 bool isPrimary)
1460 int totFlds = fldList.size();
1461 if (totFlds != 1)
1463 printError(ErrBadCall, "No Field name specified or composite fields specified");
1464 return ErrBadCall;
1466 void *chunk = NULL;
1467 void *vcchunk = NULL;
1468 //check whether table exists
1469 CatalogTableTABLE cTable(systemDatabase_);
1470 cTable.getChunkAndTblPtr(tblName, chunk, *tptr, vcchunk);
1471 if (NULL == tptr)
1473 printError(ErrNotExists, "Table does not exist %s", tblName);
1474 return ErrNotExists;
1477 //check whether field exists
1478 CatalogTableFIELD cField(systemDatabase_);
1479 DbRetVal rv = cField.getFieldPtrs(fldList, *tptr, *fptr);
1480 if (OK != rv)
1482 if (rv != ErrBadCall) {
1483 printError(ErrNotExists, "Field does not exist");
1484 return ErrNotExists;
1487 CFIELD* fInfo = (CFIELD*)fptr[0];
1488 if (!(fInfo->type_ == typeInt || fInfo->type_ == typeLong || fInfo->type_ == typeLongLong || fInfo->type_ == typeString
1489 || 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));
1574 for (int i=0; i < bucketSize ; i++)
1576 buck[i].mutex_.init("Bucket");
1578 return;
1581 DbRetVal DatabaseManagerImpl::dropIndex(const char *name)
1583 return dropIndexInt(name, true);
1586 DbRetVal DatabaseManagerImpl::dropIndexInt(const char *name, bool takeLock)
1588 DbRetVal rv = OK;
1589 void *chunk = NULL, *hchunk = NULL;
1590 void *tptr =NULL;
1591 int ret = 0;
1592 if (takeLock) {
1593 rv = systemDatabase_->getXCheckpointMutex();
1594 if (OK != rv)
1596 printError(ErrSysInternal, "Unable to get database mutex");
1597 return ErrSysInternal;
1600 rv = removeIndexCatalogTables(name, chunk, hchunk, tptr);
1601 if (OK != rv)
1603 if (takeLock) systemDatabase_->releaseCheckpointMutex();
1604 return rv;
1607 CINDEX *iptr = (CINDEX*)tptr;
1608 rv = removeIndexChunks(chunk, hchunk, iptr->indexType_);
1609 if (OK != rv)
1611 if (takeLock) systemDatabase_->releaseCheckpointMutex();
1612 return rv;
1614 if (takeLock) systemDatabase_->releaseCheckpointMutex();
1616 printDebug(DM_Database, "Dropped index %s",name);
1617 logFinest(Conf::logger, "Deleted Index %s", name);
1618 return OK;
1620 DbRetVal DatabaseManagerImpl::createForeignKey(char *fKName,ForeignKeyInfo *info)
1622 DbRetVal rv = OK;
1623 int totFkFlds = info->fkFldList.size();
1624 int totPkFlds = info->pkFldList.size();
1625 if (totFkFlds==0 && totPkFlds==0) {
1626 printError(ErrBadCall, "No Field name specified");
1627 return ErrBadCall;
1629 void *tptr =NULL;
1630 void *chunk = NULL;
1631 void *vcchunk = NULL;
1632 rv = systemDatabase_->getXCheckpointMutex();
1633 if (OK != rv)
1635 printError(ErrSysInternal, "Unable to get database mutex");
1636 return ErrSysInternal;
1638 CatalogTableTABLE cTable(systemDatabase_);
1639 cTable.getChunkAndTblPtr(info->fkTableName, chunk, tptr, vcchunk);
1640 if (NULL == tptr)
1642 systemDatabase_->releaseCheckpointMutex();
1643 printError(ErrNotExists, "Table does not exist %s", info->fkTableName);
1644 return ErrNotExists;
1646 char **fptr = new char* [totFkFlds];
1647 CatalogTableFIELD cField(systemDatabase_);
1648 rv = cField.getFieldPtrs(info->fkFldList, tptr, fptr);
1649 if (OK != rv)
1651 delete[] fptr;
1652 systemDatabase_->releaseCheckpointMutex();
1653 if (rv != ErrBadCall) {
1654 printError(ErrNotExists, "Field does not exist");
1655 return ErrNotExists;
1658 void *tPkptr =NULL;
1659 void *chunkPk = NULL;
1660 void *vcchunkPk = NULL;
1661 CatalogTableTABLE c2Table(systemDatabase_);
1662 c2Table.getChunkAndTblPtr(info->pkTableName, chunkPk, tPkptr, vcchunkPk);
1663 if (NULL == tPkptr)
1665 systemDatabase_->releaseCheckpointMutex();
1666 printError(ErrNotExists, "Table does not exist %s", info->pkTableName);
1667 return ErrNotExists;
1669 char **fPkptr = new char* [totPkFlds];
1670 CatalogTableFIELD c2Field(systemDatabase_);
1671 rv = c2Field.getFieldPtrs(info->pkFldList, tPkptr, fPkptr);
1672 if (OK != rv)
1674 delete[] fptr;
1675 delete[] fPkptr;
1676 systemDatabase_->releaseCheckpointMutex();
1677 if (rv != ErrBadCall) {
1678 printError(ErrNotExists, "Field does not exist");
1679 return ErrNotExists;
1682 //Create New chunkdatanode
1683 CatalogTableFK cFK(systemDatabase_);
1684 rv = cFK.insert(fKName, tptr, tPkptr);//TODO
1685 if (OK != rv)
1687 delete[] fptr;
1688 delete[] fPkptr;
1689 systemDatabase_->releaseCheckpointMutex();
1690 printError(ErrSysInternal, "Catalog table updation failed in CFK table");
1691 return ErrSysInternal;
1694 CatalogTableFKFIELD cFKField(systemDatabase_);
1695 rv = cFKField.insert(fKName,fptr,fPkptr,totFkFlds);
1696 if (OK != rv)
1698 delete[] fptr;
1699 delete[] fPkptr;
1700 cFK.remove(tptr);
1701 systemDatabase_->releaseCheckpointMutex();
1702 printError(ErrSysInternal, "Catalog table updation failed in CFKFIELD table");
1703 return ErrSysInternal;
1705 systemDatabase_->releaseCheckpointMutex();
1706 delete[] fptr;
1707 delete[] fPkptr;
1708 return rv;
1710 DbRetVal DatabaseManagerImpl::dropForeignKey(void *tptr,bool trylock)
1712 DbRetVal rv = OK;
1713 if(trylock){
1714 rv = systemDatabase_->getXCheckpointMutex();
1715 if (OK != rv)
1717 printError(ErrSysInternal, "Unable to get database mutex");
1718 return ErrSysInternal;
1721 void *fkChunk=NULL;
1722 CatalogTableFK cFK(systemDatabase_);
1723 int total = cFK.getNoOfPkTable(tptr);
1724 //printDebug(DM_TEST,"total fk chunk %d",total);
1725 for (int i=0;i< total; i++)
1727 fkChunk = cFK.getFkCTable(tptr);
1728 if(NULL==fkChunk)
1730 if(trylock){
1731 systemDatabase_->releaseCheckpointMutex();
1733 printError(ErrSysInternal, "Catalog table not finds CFKFIELD table");
1734 return ErrSysInternal;
1736 CatalogTableFKFIELD cFKField(systemDatabase_);
1737 rv = cFKField.remove(fkChunk);
1738 if (OK != rv)
1740 if(trylock){
1741 systemDatabase_->releaseCheckpointMutex();
1743 printError(ErrSysInternal, "Catalog table updation failed in CFKFIELD table");
1744 return ErrSysInternal;
1746 rv =cFK.remove(fkChunk);
1747 if (OK != rv)
1749 if(trylock){
1750 systemDatabase_->releaseCheckpointMutex();
1752 printError(ErrSysInternal, "Catalog table updation failed for INDEX table");
1753 return ErrSysInternal;
1756 if(trylock){
1757 systemDatabase_->releaseCheckpointMutex();
1759 return rv;
1762 void DatabaseManagerImpl::printTreeIndexNodeInfo(char *name, bool flag)
1764 CatalogTableINDEX cIndex(systemDatabase_);
1765 DbRetVal rv = OK;
1766 void *chunk = NULL, *hchunk = NULL;
1767 void *tptr =NULL;
1768 rv = cIndex.get(name, chunk, hchunk, tptr);
1769 if (OK != rv) return;
1770 IndexType iType = CatalogTableINDEX::getType(tptr);
1771 if (treeIndex != iType)
1773 printf("%s is not a tree index\n ");
1774 return;
1776 Chunk *ch = (Chunk*) chunk;
1777 if(flag){ if(hchunk)((TreeNode*) hchunk)->displayAll(); }
1778 else {
1779 int offset = CatalogTableINDEX::getOffsetOfFirstField(tptr);
1780 //if(typeInt != offset) { printf("%s is not on Integer Type Field. To see info Index should be on integer type field. \n "); return;}
1781 if(hchunk) ((TreeNode*) hchunk)->displayAll(offset);
1785 DbRetVal DatabaseManagerImpl::printIndexInfo(char *name)
1787 CatalogTableINDEX cIndex(systemDatabase_);
1788 DbRetVal rv = OK;
1789 void *chunk = NULL, *hchunk = NULL;
1790 void *tptr =NULL;
1791 rv = cIndex.get(name, chunk, hchunk, tptr);
1792 if (OK != rv) return rv;
1793 printf("<IndexName> %s </IndexName>\n", name);
1794 printf("<Unique> %d </Unique>\n", CatalogTableINDEX::getUnique(tptr));
1795 IndexType iType = CatalogTableINDEX::getType(tptr);
1796 if(hashIndex == iType)
1797 printf("<Type> Hash Index </Type>\n");
1798 else if (treeIndex == iType)
1799 printf("<Type> Tree Index </Type>\n");
1800 else if (trieIndex == iType)
1801 printf("<Type> Trie Index </Type>\n");
1802 else
1803 printf("<Type> Unknown Index </Type>\n");
1805 Chunk *ch = (Chunk*) chunk;
1806 printf("<HashBucket>\n");
1807 printf(" <TotalPages> %d </TotalPages>\n", ch->totalPages());
1808 printf(" <TotalBuckets> %d </TotalBuckets> \n", CatalogTableINDEX::getNoOfBuckets(tptr));
1809 printf("</HashBucket>\n");
1810 printf("<IndexNodes>\n");
1811 if(hashIndex == iType){
1812 ch = (Chunk*) hchunk;
1813 printf(" <TotalPages> %d </TotalPages>\n", ch->totalPages());
1814 printf(" <TotalNodes> %d </TotalNodes>\n", ch->getTotalDataNodes());
1815 } else if (treeIndex == iType) {
1816 printf(" <TotalNodes> %d </TotalNodes>\n", ch->getTotalDataNodes());
1817 if(hchunk)
1818 printf(" <TotalElements> %lld </TotalElements>\n",((TreeNode*) hchunk)->getTotalElements());
1819 else
1820 printf(" <TotalElements> 0 </TotalElements>\n");
1821 } else if (trieIndex == iType)
1823 printf(" <TrieNodes> \n");
1824 printf(" <TotalPages> %d </TotalPages>\n", ch->totalPages());
1825 printf(" <TotalNodes> %d </TotalNodes>\n", ch->getTotalDataNodes());
1826 printf(" </TrieNodes> \n <TrieValues>\n");
1827 ch = (Chunk*) hchunk;
1828 printf(" <TotalPages> %d </TotalPages>\n", ch->totalPages());
1829 printf(" <TotalNodes> %d </TotalNodes>\n", ch->getTotalDataNodes());
1830 printf(" </TrieValues>\n");
1831 } else
1833 printf("Unknown Index type\n");
1835 printf("<IndexNodes>\n");
1836 return OK;
1839 DbRetVal DatabaseManagerImpl::registerThread()
1841 DbRetVal rv = OK;
1842 if (pMgr_ != NULL)
1844 printError(ErrAlready, "Process already registered\n");
1845 return ErrAlready;
1847 pMgr_ = new ProcessManager();
1848 rv = pMgr_->registerThread();
1849 if (rv ==OK) {
1850 procSlot = pMgr_->getProcSlot();
1851 systemDatabase_->setProcSlot(procSlot);
1852 printDebug(DM_Process, "Process registed with slot %d\n", procSlot);
1854 return rv;
1857 DbRetVal DatabaseManagerImpl::deregisterThread()
1859 DbRetVal rv = OK;
1860 if (pMgr_ != NULL)
1862 rv = pMgr_->deregisterThread(procSlot);
1863 delete pMgr_;
1864 pMgr_ = NULL;
1866 return rv;
1869 bool DatabaseManagerImpl::isAnyOneRegistered()
1871 if (pMgr_ != NULL) return pMgr_->isAnyOneRegistered();
1872 return true;
1876 void DatabaseManagerImpl::printUsageStatistics()
1878 pMgr_->printUsageStatistics();
1879 tMgr_->printUsageStatistics();
1880 lMgr_->printUsageStatistics();
1883 void DatabaseManagerImpl::printDebugLockInfo()
1885 lMgr_->printDebugInfo();
1888 void DatabaseManagerImpl::printDebugTransInfo()
1890 tMgr_->printDebugInfo(systemDatabase_);
1892 void DatabaseManagerImpl::printDebugProcInfo()
1894 pMgr_->printDebugInfo();
1896 void DatabaseManagerImpl::printDebugChunkInfo()
1898 printf("<NotYetImplemented> </NotYetImplemented>\n");
1900 ChunkIterator DatabaseManagerImpl::getSystemTableIterator(CatalogTableID id)
1902 Chunk *fChunk = systemDatabase_->getSystemDatabaseChunk(id);
1903 return fChunk->getIterator();
1906 Chunk* DatabaseManagerImpl::getSystemTableChunk(CatalogTableID id)
1908 return systemDatabase_->getSystemDatabaseChunk(id);
1911 int DatabaseManagerImpl::getNoOfPagesForTable(char *tblName)
1913 Table *tbl = openTable(tblName);
1914 if (NULL == tbl) {
1915 printError(ErrSysInternal, "Unable to open table %s", tblName);
1916 return 0;
1918 TableImpl *tb = (TableImpl *) tbl;
1919 int pages = 0;
1920 if (tb->numTuples()) pages = tb->pagesUsed();
1921 closeTable(tbl);
1922 return pages;
1925 DbRetVal DatabaseManagerImpl::loadRecords(char *tblName, char *buffer)
1927 // buffer should be as big as the no of pages occupied by the records
1928 Table *tbl = openTable(tblName);
1929 if (NULL == tbl) {
1930 printError(ErrSysInternal, "Unable to open table %s", tblName);
1931 return ErrSysInternal;
1933 TableImpl *tb = (TableImpl *) tbl;
1934 char *bufIter = buffer;
1935 int pages = *(int *) bufIter; bufIter += sizeof(int);
1936 Page *firstPage = ((Chunk *)(tb->chunkPtr_))->getFirstPage();
1937 PageInfo *pi = (PageInfo *) firstPage;
1938 memcpy(bufIter, pi, PAGE_SIZE);
1939 bufIter += PAGE_SIZE;
1940 for (int i = 0; i < pages - 1; i++) {
1941 Page *nPage = pi->nextPage_;
1942 memcpy(bufIter, nPage, PAGE_SIZE);
1943 bufIter += PAGE_SIZE;
1944 pi = (PageInfo *) nPage;
1946 closeTable(tbl);
1947 return OK;
1950 DbRetVal DatabaseManagerImpl::pasteRecords(char *tblName, void *buffer)
1952 // buffer should be as big as the no of pages occupied by the records
1953 Table *tbl = openTable(tblName);
1954 if (NULL == tbl) {
1955 printError(ErrSysInternal, "Unable to open table %s", tblName);
1956 return ErrSysInternal;
1958 TableImpl *tb = (TableImpl *) tbl;
1959 Database *db = tb->getDB();
1960 char *bufIter = (char *) buffer;
1961 int pages = *(int *) bufIter;
1962 bufIter += sizeof(int);
1964 Page *firstPage = ((Chunk *)(tb->chunkPtr_))->getFirstPage();
1965 PageInfo *pi = (PageInfo *) firstPage;
1966 memcpy(pi, bufIter, PAGE_SIZE);
1967 bufIter += PAGE_SIZE;
1968 while (--pages != 0) {
1969 //get a new page allocated
1970 Page *newPage = db->getFreePage();
1971 memcpy(newPage, bufIter, PAGE_SIZE);
1972 pi->nextPage_ = newPage;
1973 pi = (PageInfo *) newPage;
1975 // initialize chunk details and pageInfo
1976 ((Chunk *)tb->chunkPtr_)->curPage_ = pi;
1977 closeTable(tbl);
1978 return OK;
1981 void DatabaseManagerImpl::setCanTakeCheckPoint(bool ctcp)
1982 { systemDatabase_->setCanTakeCheckPoint(ctcp); }
1984 bool DatabaseManagerImpl::getCanTakeCheckPoint()
1985 { return systemDatabase_->getCanTakeCheckPoint(); }
1987 DbRetVal DatabaseManagerImpl::checkPoint()
1989 if (!systemDatabase_->getCanTakeCheckPoint()) {
1990 printf("Load / Cache / Replication process might be running. CheckPoint not taken\n");
1991 return ErrLoadingOn;
1993 DbRetVal rv = systemDatabase_->getXCheckpointMutex();
1994 if (OK != rv ) {
1995 printError(rv, "Unable to get checkpoint mutex");
1996 return ErrLockTimeOut;
1998 if (tMgr_ && !tMgr_->isTransactionConsistent(systemDatabase_)) {
1999 printf("not in transaction consistent point\n");
2000 systemDatabase_->releaseCheckpointMutex();
2001 return ErrLockTimeOut;
2003 rv = writeSchemaFile();
2004 if (rv != OK) {
2005 printError(ErrSysInternal, "checkpoint error");
2007 rv = db()->checkPoint();
2008 systemDatabase_->releaseCheckpointMutex();
2009 return rv;
2012 DbRetVal DatabaseManagerImpl::writeSchemaFile()
2014 DbRetVal rv = OK;
2015 FILE *fp = NULL;
2016 FILE *fp1 = NULL;
2017 int fd = -1;
2018 char schFile[MAX_FILE_LEN];
2019 char mapFile[MAX_FILE_LEN];
2020 sprintf(schFile, "%s/db.chkpt.schema1", Conf::config.getDbFile());
2021 sprintf(mapFile, "%s/db.chkpt.map1", Conf::config.getDbFile());
2022 fp = fopen(schFile, "r");
2023 if (fp != NULL) {
2024 fclose(fp);
2025 int ret = unlink(schFile);
2026 if( ret != 0) {
2027 printError(ErrOS, "checkpoint: delete schema file failed");
2028 return ErrOS;
2031 fp = fopen(schFile, "w+");
2032 if (fp == NULL) {
2033 printError(ErrOS, "Unable to create schema file for chkpt.");
2034 return ErrOS;
2036 fp1 = fopen(mapFile, "r");
2037 if (fp1 != NULL) {
2038 fclose(fp1);
2039 int ret = unlink(mapFile);
2040 if( ret != 0) {
2041 printError(ErrOS, "checkpoint: delete schema file failed");
2042 return ErrOS;
2045 fd = open(mapFile, O_WRONLY|O_CREAT, 0644);
2046 if (fd == -1) {
2047 printError(ErrOS, "checkpoint: Unable to create map file.");
2048 return ErrOS;
2050 List tableList = getAllTableNames();
2051 ListIterator iter = tableList.getIterator();
2052 Identifier *elem = NULL;
2053 int count =0;
2054 while (iter.hasElement()) {
2055 elem = (Identifier*) iter.nextElement();
2056 // if (TableConf::config.isTableCached(elem->name) == OK) continue;
2057 fprintf(fp, "CREATE TABLE %s (", elem->name);
2058 Table *table = openTable(elem->name);
2059 if (NULL == table) {
2060 printError(ErrSysInternal, "Unable to open table %s", elem->name);
2061 return ErrSysInternal;
2063 void *chunk = NULL; void *tptr = NULL; void *vcchunk = NULL;
2064 CatalogTableTABLE cTable(systemDatabase_);
2065 rv = cTable.getChunkAndTblPtr(elem->name, chunk, tptr, vcchunk);
2066 struct Object obj;
2067 strcpy(obj.name, elem->name);
2068 obj.type = Tbl;
2069 obj.bucketChunk = NULL;
2070 obj.firstPage = ((Chunk *)chunk)->getFirstPage();
2071 obj.curPage = ((Chunk *)chunk)->getCurrentPage();
2072 void *buf = &obj;
2073 write(fd, buf, sizeof(obj));
2074 FieldInfo *info = new FieldInfo();
2075 List fNameList = table->getFieldNameList();
2076 ListIterator fNameIter = fNameList.getIterator();
2077 count++;
2078 bool firstField=true;
2079 char fieldName[IDENTIFIER_LENGTH];
2080 while (fNameIter.hasElement()) {
2081 elem = (Identifier*) fNameIter.nextElement();
2082 Table::getFieldNameAlone(elem->name, fieldName);
2083 rv = table->getFieldInfo(elem->name, info);
2084 if (rv !=OK) {
2085 printf("unable to retrive info for table %s\n", elem->name);
2087 if (firstField) {
2088 fprintf(fp, "%s %s ", fieldName, AllDataType::getSQLString(info->type));
2089 firstField = false;
2090 } else
2091 fprintf(fp, ", %s %s ", fieldName, AllDataType::getSQLString(info->type));
2092 if (info->type == typeString || info->type == typeVarchar ||
2093 info->type == typeBinary)
2094 fprintf(fp, "(%d)",info->length);
2095 if (info->isNull) fprintf(fp, " NOT NULL ");
2096 if (info->isDefault) fprintf(fp, " DEFAULT '%s' ", info->defaultValueBuf);
2097 if (info->isAutoIncrement) fprintf(fp, " AUTO_INCREMENT ");
2099 fNameIter.reset();
2100 while (fNameIter.hasElement())
2101 delete ((FieldName *) fNameIter.nextElement());
2102 fNameList.reset();
2104 fprintf(fp, ");\n");
2105 table->printSQLIndexString(fp, fd);
2106 delete info;
2107 closeTable(table);
2109 ListIterator tIter = tableList.getIterator();
2110 tIter.reset();
2111 while (tIter.hasElement())
2112 delete ((FieldName *) tIter.nextElement());
2113 tableList.reset();
2115 fclose(fp);
2116 close(fd);
2117 return OK;
2120 DbRetVal DatabaseManagerImpl::recover()
2122 DbRetVal rv = OK;
2123 rv = sysDb()->recoverSystemDB();
2124 if (rv != OK) return rv;
2125 if (!Conf::config.useMmap())rv = db()->recoverUserDB();
2126 return rv;
2129 void DatabaseManagerImpl::sendSignal(int signal)
2131 ThreadInfo* tInfo = sysDb()->getThreadInfo(0);
2132 for (int i=0; i < Conf::config.getMaxProcs(); i++)
2134 if (tInfo->pid_ !=0) os::kill(tInfo->pid_, signal);
2135 tInfo++;