1 /***************************************************************************
2 * Copyright (C) 2007 by www.databasecache.com *
3 * Contact: praba_tuty@databasecache.com *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 ***************************************************************************/
17 #include<DatabaseManager.h>
18 #include<DatabaseManagerImpl.h>
22 #include<Transaction.h>
23 #include<CatalogTables.h>
28 #include<TableConfig.h>
32 DatabaseManagerImpl::~DatabaseManagerImpl()
34 //Note:Databases are closed by the session interface
39 void DatabaseManagerImpl::createLockManager()
41 lMgr_
= new LockManager(systemDatabase_
);
45 void DatabaseManagerImpl::createTransactionManager()
48 tMgr_
= new TransactionManager();
49 tMgr_
->setFirstTrans(systemDatabase_
->getSystemDatabaseTrans(0));
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_
;
63 printDebug(DM_Database
, "Opened system database");
67 DbRetVal
DatabaseManagerImpl::closeSystemDatabase()
70 //make them to point to system database file descriptor
71 //and database pointer
72 db_
= systemDatabase_
;
75 printDebug(DM_Database
, "Closed system database");
79 DbRetVal
DatabaseManagerImpl::createDatabase(const char *name
, size_t size
)
81 bool isMmapNeeded
= Conf::config
.useMmap();
83 if (isMmapNeeded && !Conf::config.useDurability()) {
84 printError(ErrBadArg, "If MMAP is set to true. Durability must be true.");
88 file_desc fd
= (file_desc
)-1;
90 char dbMapFile
[MAX_FILE_LEN
];
92 long fixAddr
= 399998976L;
93 bool firstTimeServer
= false;
96 printError(ErrAlready
, "Database is already created");
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();
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);
119 #if (defined MMDB && defined EMBED)
120 printError(ErrOS
, "One application is already running.");
123 printError(ErrOS
, "Shared Memory already exists");
125 printError(ErrOS
, "Shared memory create failed");
129 //switch the checkpoint
130 if (Database::getCheckpointID() == 0)
131 Database::setCheckpointID(1);
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")) {
140 sprintf(cmd, "cp %s %s/db.chkpt.data", dbMapFile, Conf::config.getDbFile());
141 int ret = system(cmd);
143 printError(ErrOS, "could not copy data file to map file");
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");
156 if(::stat(dbMapFile
, &st
) == -1) {
157 printf("Unable to retrieve the db File data\n");
159 db_
->setChkptfd((file_desc
)-1);
163 int localfd
= os::open(dbMapFile
, fileOpenCreat
,0);
167 if (st
.st_size
== 0 || st
.st_size
< size
) {
168 firstTimeServer
= true;
169 off_t flSize
= os::lseek(localfd
, size
- 1, SEEK_SET
);
172 int wSize
= os::write(localfd
, a
, 1);
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
);
190 # if (defined MMDB && defined EMBED)
191 if (0 == strcmp(name
, SYSTEMDB
)) ProcessManager::sysAddr
= rtnAddr
;
192 else ProcessManager::usrAddr
= rtnAddr
;
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);
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",
242 db_->setHashIndexChunk(chunkInfo);*/
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
;
256 shm_id
= os::shm_open(Conf::config
.getUserDbKey(), 100, 0660);
257 os::shm_remove(shm_id
);
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");
282 if (NULL
==systemDatabase_
)
284 printError(ErrNotOpen
, "System Database not open");
287 size
= Conf::config
.getMaxDbSize();
288 startaddr
= startaddr
+ Conf::config
.getMaxSysDbSize();
289 fixAddr
+= Conf::config
.getMaxSysDbSize();
293 printError(ErrAlready
, "User Database already open");
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();
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(),
319 fd
= os::openFile(dbMapFile
, fileOpenReadWrite
, 0660);
320 if ((file_desc
)-1 == fd
) {
321 printError(ErrOS
, "Mmap file could not be opened");
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
);
331 shm_id
= os::shm_open(key
, size
, 0660);
334 printError(ErrOS
, "Shared memory open failed");
337 shm_ptr
= os::shm_attach(shm_id
, startaddr
, SHM_RND
);
339 if (0 == strcmp(name
, SYSTEMDB
))
342 ProcessManager::sysAddr
= (char*) shm_ptr
;
346 ProcessManager::usrAddr
= (char*) shm_ptr
;
349 if (0 == strcmp(name
, SYSTEMDB
)) shm_ptr
= ProcessManager::sysAddr
;
350 else shm_ptr
= ProcessManager::usrAddr
;
354 rtnAddr
= (caddr_t
) shm_ptr
;
356 if (rtnAddr
< 0 || shm_ptr
== (char*)0xffffffffffffffff)
358 printError(ErrOS
, "Shared memory attach returned -ve value %x %d", shm_ptr
, errno
);
362 if (rtnAddr
< 0 || shm_ptr
== (char*)0xffffffff)
364 printError(ErrOS
, "Shared memory attach returned -ve value %x %d", shm_ptr
, errno
);
369 db_
= new Database();
370 db_
->setMetaDataPtr((DatabaseMetaData
*)rtnAddr
);
373 if (firstThread
) ProcessManager::systemDatabase
= db_
;
375 printDebug(DM_Database
, "Opening database: %s", name
);
379 DbRetVal
DatabaseManagerImpl::closeDatabase()
384 //Database is already closed
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();
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);
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
);
413 void *ptr
= chunk
->allocate(systemDatabase_
, &rv
);
416 printError(rv
, "Allocation failed for User chunk catalog table");
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_
);
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");
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
);
444 firstPageInfo
->setPageAsUsed(chunkInfo
->allocSize_
);
445 char *data
= ((char*)firstPageInfo
) + sizeof(PageInfo
);
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_
;
458 chunkInfo
->setAllocType(VariableSizeAllocator
);
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
);
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
);
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
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
);
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
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
);
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
)
541 if (!Util::isIdentifier((char*)name
)) {
542 printError(ErrBadArg
, "Invalid character for index name");
545 int fldCount
= def
.getFieldCount();
548 printError(ErrNotExists
,"Table can't be created without Field");
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
557 if (fldCount
<= 32) addSize
= 4; else addSize
= os::align(fldCount
);
558 size_t sizeofTuple
= os::alignLong(def
.getTupleSize()+addSize
);
559 rv
= systemDatabase_
->getXCheckpointMutex();
561 printError(rv
, "Unable to get Database mutex");
567 void *vcchunk
= NULL
;
569 //check whether table already exists
570 CatalogTableTABLE
cTable(systemDatabase_
);
571 cTable
.getChunkAndTblPtr(name
, chunk
, tptr
, vcchunk
);
574 systemDatabase_
->releaseCheckpointMutex();
575 printError(ErrAlready
, "Table %s already exists", name
);
579 //create a chunk to store the tuples
580 Chunk
*ptr
= createUserChunk(sizeofTuple
);
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
);
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
);
596 if (isVarcharPresent
) {
597 //creat chunk to store varchar values
598 vcptr
= createUserChunk();
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
);
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
);
621 FieldIterator iter
= def
.getFieldIterator();
622 CatalogTableFIELD
cField(systemDatabase_
);
623 rv
= cField
.insert(iter
, tblID
,tptr
);
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
);
640 DbRetVal
DatabaseManagerImpl::renameTable(const char *oldName
,const char *newName
)
643 DbRetVal rv
= systemDatabase_
->getXCheckpointMutex();
645 printError(ErrSysInternal
, "Unable to get database mutex for rename table");
646 return ErrSysInternal
;
648 CatalogTableTABLE
cTable(systemDatabase_
);
649 rv
= cTable
.renameTable(oldName
,newName
);
651 printError(ErrSysInternal
, "Unable to rename table");
652 systemDatabase_
->releaseCheckpointMutex();
653 return ErrSysInternal
;
655 systemDatabase_
->releaseCheckpointMutex();
658 DbRetVal
DatabaseManagerImpl::renameIndex(const char *oldName
,const char *newName
)
661 DbRetVal rv
= systemDatabase_
->getXCheckpointMutex();
663 printError(ErrSysInternal
, "Unable to get database mutex for rename table");
664 return ErrSysInternal
;
666 CatalogTableTABLE
cTable(systemDatabase_
);
667 rv
= cTable
.renameIndex(oldName
,newName
);
669 printError(ErrSysInternal
, "Unable to rename table");
670 systemDatabase_
->releaseCheckpointMutex();
671 return ErrSysInternal
;
673 systemDatabase_
->releaseCheckpointMutex();
677 DbRetVal
DatabaseManagerImpl::renameField(const char *tableName
,const char *oldName
,const char *newName
)
679 DbRetVal rv
= systemDatabase_
->getXCheckpointMutex();
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
);
687 printError(ErrSysInternal
, "Unable to rename field.");
688 systemDatabase_
->releaseCheckpointMutex();
689 return ErrSysInternal
;
691 systemDatabase_
->releaseCheckpointMutex();
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
)
704 void *vcchunk
= NULL
;
705 DbRetVal rv
= systemDatabase_
->getXCheckpointMutex();
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
);
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
);
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
);
730 systemDatabase_
->releaseCheckpointMutex();
731 printError(ErrLockTimeOut
, "Unable to acquire exclusive lock on the table\n");
735 rv
= cTable
.remove(name
, chunk
, tptr
);
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
);
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
);
755 systemDatabase_
->releaseCheckpointMutex();
756 printError(rv
, "Unable to delete the chunk");
759 printDebug(DM_Database
,"Deleted UserChunk:%x", chunk
);
761 if (vcchunk
!= NULL
) {
762 rv
= deleteUserChunk((Chunk
*)vcchunk
);
764 systemDatabase_
->releaseCheckpointMutex();
765 printError(rv
, "Unable to delete the chunk");
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
);
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
);
789 printError(ErrLockTimeOut
, "Unable to release exclusive lock on the table\n");
795 //Return values: NULL for table not found
796 Table
* DatabaseManagerImpl::openTable(const char *name
,bool checkpkfk
)
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();
803 table
->setSystemDB(systemDatabase_
);
804 table
->setLockManager(lMgr_
);
805 table
->setTrans(ProcessManager::getThreadTransAddr(systemDatabase_
->procSlot
));
807 //to store the chunk pointer of table
809 void *vcchunk
= NULL
;
811 //to store the tuple pointer of the table
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();
820 printError(ErrSysInternal
, "Unable to get database mutex");
824 CatalogTableTABLE
cTable(systemDatabase_
);
825 ret
= cTable
.getChunkAndTblPtr(name
, chunk
, tptr
, vcchunk
);
828 systemDatabase_
->releaseAllocDatabaseMutex();
830 printError(ErrNotExists
, "Table not exists %s", name
);
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
840 printError(ErrLockTimeOut, "Unable to acquire shared lock on the table\n");
841 systemDatabase_->releaseAllocDatabaseMutex();
847 if (tTuple
->numFlds_
<= 32)
849 table
->isIntUsedForNULL
= true;
850 table
->iNullInfo
= 0;
851 table
->iNotNullInfo
=0;
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();
871 while (fIter
.hasElement())
873 FieldDef
*def
= fIter
.nextElement();
874 if (table
->isIntUsedForNULL
) {
875 if (def
->isNull_
) SETBIT(table
->iNotNullInfo
, fldpos
-1);
878 if (def
->isNull_
) table
->cNotNullInfo
[fldpos
-1] = 1;
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_
];
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();
912 hIdxInfo
->fldOffset
= table
->fldList_
.getFieldOffset(def
->fldName_
);
913 hIdxInfo
->type
= table
->fldList_
.getFieldType(def
->fldName_
);
914 hIdxInfo
->compLength
= table
->fldList_
.getFieldLength(def
->fldName_
);
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
930 CatalogTableFK
cFk(systemDatabase_
);
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
);
944 printError(ErrSysInternal
, "Unable to open foreign key tables");
953 char *tblName
= NULL
;
954 table
->isFkTbl
= cFk
.isFkTable(tptr
);
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
);
965 printError(ErrSysInternal
, "Unable to open foreign key tables");
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
);
980 List
DatabaseManagerImpl::getAllTableNames(int *retval
)
983 //to store the tuple pointer of the table
986 /*DbRetVal rv = systemDatabase_->getSCheckpointMutex();
988 printError(ErrSysInternal, "Unable to get checkpoint mutex");
989 if(retval) *retval = rv;
993 CatalogTableTABLE
cTable(systemDatabase_
);
994 List tableList
= cTable
.getTableList();
995 //systemDatabase_->releaseCheckpointMutex();
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;
1008 /* TableImpl *fkTbl =NULL;
1009 ListIterator tblIter = ((TableImpl*)table)->tblList.getIterator();
1011 while (tblIter.hasElement()){
1012 fkTbl = (TableImpl *) tblIter.nextElement();
1015 ((TableImpl*)table)->tblList.reset();
1016 tblIter = ((TableImpl*)table)->tblFkList.getIterator();
1018 while (tblIter.hasElement()){
1019 fkTbl = (TableImpl *) tblIter.nextElement();
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
)
1030 if (!info
->isUnique
&& info
->isPrimary
)
1032 printError(ErrBadCall
, "Primary key cannot be non unique\n");
1035 if (!Util::isIdentifier((char*)indName
)) {
1036 printError(ErrBadArg
, "Invalid character for index name");
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
);
1060 printError(ErrBadCall
, "Index type not supported\n");
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",
1080 int totFlds
= fldList
.size();
1083 printError(ErrBadCall
, "No Field name specified");
1088 void *vcchunk
= NULL
;
1089 DbRetVal rv
= systemDatabase_
->getXCheckpointMutex();
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
);
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
);
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");
1118 //printError(ErrNotExists, "Field does not exist");
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");
1133 systemDatabase_
->releaseCheckpointMutex();
1136 if (!fInfo
->isNull_
&& isPrimary
)
1138 printError(ErrBadArg
, "Primary Index cannot be created on field without NOTNULL constraint");
1140 systemDatabase_
->releaseCheckpointMutex();
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
)
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
)
1164 deleteUserChunk(chunkInfo
);
1165 systemDatabase_
->releaseCheckpointMutex();
1166 printError(rv
, "Unable to allocate memory for bucket");
1169 Bucket
*buck
= (Bucket
*) buckets
;
1170 initHashBuckets(buck
, bucketSize
);
1172 //create chunk to store the hash index nodes
1173 Chunk
* hChunk
= createUserChunk(sizeof(IndexNode
));
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
);
1185 void *tupleptr
= NULL
;
1186 CatalogTableINDEX
cIndex(systemDatabase_
);
1187 rv
= cIndex
.insert(indName
, tptr
, fldList
.size(), isUnique
,
1188 chunkInfo
, bucketSize
, hChunk
, tupleptr
);
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
);
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
;
1213 systemDatabase_
->releaseCheckpointMutex();
1215 //TODO:: Take table lock
1217 // Following code is written by Kishor Amballi
1218 TableImpl
*tbl
= (TableImpl
*) openTable(tblName
);
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
);
1229 HashIndexInfo
*indxInfo
= NULL
;
1231 for (i
= 0; i
< tbl
->numIndexes_
; i
++) {
1232 if(((HashIndexInfo
*)tbl
->idxInfo
[i
])->indexPtr
== tupleptr
) {
1233 indxInfo
= (HashIndexInfo
*) tbl
->idxInfo
[i
];
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
) {
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
);
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",
1264 int totFlds
= fldList
.size();
1266 printError(ErrBadCall
, "No Field name specified");
1268 }else if (totFlds
!= 1) {
1269 printError(ErrBadCall
, "Composite index not supported for Tree");
1274 void *vcchunk
= NULL
;
1275 DbRetVal rv
= systemDatabase_
->getXCheckpointMutex();
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
);
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
);
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");
1310 systemDatabase_
->releaseCheckpointMutex();
1313 if (fInfo
->type_
== typeVarchar
)
1315 printError(ErrBadArg
, "Tree Index not supported for varchar type. Use char data type instead.");
1317 systemDatabase_
->releaseCheckpointMutex();
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
)
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
);
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
);
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
;
1362 systemDatabase_
->releaseCheckpointMutex();
1363 //TODO::if tuples already present in this table, then create tree index '
1365 TableImpl
*tbl
= (TableImpl
*) openTable(tblName
);
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
);
1376 HashIndexInfo
*indxInfo
= NULL
;
1378 for (i
= 0; i
< tbl
->numIndexes_
; i
++) {
1379 if(((HashIndexInfo
*)tbl
->idxInfo
[i
])->indexPtr
== tupleptr
) {
1380 indxInfo
= (HashIndexInfo
*) tbl
->idxInfo
[i
];
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
) {
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
);
1403 DbRetVal
DatabaseManagerImpl::createTrieIndex(const char *indName
, const char *tblName
,
1404 FieldNameList
&fldList
, bool isUnique
, bool isPrimary
)
1406 int totFlds
= fldList
.size();
1408 char **fptr
= new char* [totFlds
];
1409 DbRetVal rv
= validateIndex(tblName
, fldList
, &tptr
, &fptr
, isPrimary
);
1415 rv
= systemDatabase_
->getXCheckpointMutex();
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
)
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
);
1447 printError(ErrSysInternal
, "Catalog table updation failed");
1448 deleteUserChunk(chunkInfo
);
1449 deleteUserChunk(hChunk
);
1450 systemDatabase_
->releaseCheckpointMutex();
1453 systemDatabase_
->releaseCheckpointMutex();
1454 //TODO:: create index nodes if records already exist in the table
1457 DbRetVal
DatabaseManagerImpl::validateIndex(const char *tblName
,
1458 FieldNameList
&fldList
, void **tptr
, char ***fptr
,
1461 int totFlds
= fldList
.size();
1464 printError(ErrBadCall
, "No Field name specified or composite fields specified");
1468 void *vcchunk
= NULL
;
1469 //check whether table exists
1470 CatalogTableTABLE
cTable(systemDatabase_
);
1471 cTable
.getChunkAndTblPtr(tblName
, chunk
, *tptr
, vcchunk
);
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
);
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");
1494 if (!fInfo
->isNull_
&& isPrimary
)
1496 printError(ErrBadArg
, "Primary Index cannot be created on field without NOTNULL constraint");
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
);
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
);
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
;
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
);
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
);
1544 printError(ErrSysInternal
, "Catalog table updation failed for INDEX table");
1545 return ErrSysInternal
;
1547 printDebug(DM_Database
, "Removing from INDEXFIELD %s",name
);
1550 DbRetVal
DatabaseManagerImpl::removeIndexChunks(void* chunk
, void* hchunk
, IndexType iType
)
1552 DbRetVal rv
= deleteUserChunk((Chunk
*)chunk
);
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
);
1563 printError(ErrSysInternal
, "Unable to delete the index hash node chunk");
1564 return ErrSysInternal
;
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
);
1582 DbRetVal
DatabaseManagerImpl::dropIndex(const char *name
)
1584 return dropIndexInt(name
, true);
1587 DbRetVal
DatabaseManagerImpl::dropIndexInt(const char *name
, bool takeLock
)
1590 void *chunk
= NULL
, *hchunk
= NULL
;
1594 rv
= systemDatabase_
->getXCheckpointMutex();
1597 printError(ErrSysInternal
, "Unable to get database mutex");
1598 return ErrSysInternal
;
1601 rv
= removeIndexCatalogTables(name
, chunk
, hchunk
, tptr
);
1604 if (takeLock
) systemDatabase_
->releaseCheckpointMutex();
1608 CINDEX
*iptr
= (CINDEX
*)tptr
;
1609 rv
= removeIndexChunks(chunk
, hchunk
, iptr
->indexType_
);
1612 if (takeLock
) systemDatabase_
->releaseCheckpointMutex();
1615 if (takeLock
) systemDatabase_
->releaseCheckpointMutex();
1617 printDebug(DM_Database
, "Dropped index %s",name
);
1618 logFinest(Conf::logger
, "Deleted Index %s", name
);
1621 DbRetVal
DatabaseManagerImpl::createForeignKey(char *fKName
,ForeignKeyInfo
*info
)
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");
1632 void *vcchunk
= NULL
;
1633 rv
= systemDatabase_
->getXCheckpointMutex();
1636 printError(ErrSysInternal
, "Unable to get database mutex");
1637 return ErrSysInternal
;
1639 CatalogTableTABLE
cTable(systemDatabase_
);
1640 cTable
.getChunkAndTblPtr(info
->fkTableName
, chunk
, tptr
, vcchunk
);
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
);
1653 systemDatabase_
->releaseCheckpointMutex();
1654 if (rv
!= ErrBadCall
) {
1655 printError(ErrNotExists
, "Field does not exist");
1656 return ErrNotExists
;
1660 void *chunkPk
= NULL
;
1661 void *vcchunkPk
= NULL
;
1662 CatalogTableTABLE
c2Table(systemDatabase_
);
1663 c2Table
.getChunkAndTblPtr(info
->pkTableName
, chunkPk
, tPkptr
, vcchunkPk
);
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
);
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
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
);
1702 systemDatabase_
->releaseCheckpointMutex();
1703 printError(ErrSysInternal
, "Catalog table updation failed in CFKFIELD table");
1704 return ErrSysInternal
;
1706 systemDatabase_
->releaseCheckpointMutex();
1711 DbRetVal
DatabaseManagerImpl::dropForeignKey(void *tptr
,bool trylock
)
1715 rv
= systemDatabase_
->getXCheckpointMutex();
1718 printError(ErrSysInternal
, "Unable to get database mutex");
1719 return ErrSysInternal
;
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
);
1732 systemDatabase_
->releaseCheckpointMutex();
1734 printError(ErrSysInternal
, "Catalog table not finds CFKFIELD table");
1735 return ErrSysInternal
;
1737 CatalogTableFKFIELD
cFKField(systemDatabase_
);
1738 rv
= cFKField
.remove(fkChunk
);
1742 systemDatabase_
->releaseCheckpointMutex();
1744 printError(ErrSysInternal
, "Catalog table updation failed in CFKFIELD table");
1745 return ErrSysInternal
;
1747 rv
=cFK
.remove(fkChunk
);
1751 systemDatabase_
->releaseCheckpointMutex();
1753 printError(ErrSysInternal
, "Catalog table updation failed for INDEX table");
1754 return ErrSysInternal
;
1758 systemDatabase_
->releaseCheckpointMutex();
1763 void DatabaseManagerImpl::printTreeIndexNodeInfo(char *name
, bool flag
)
1765 CatalogTableINDEX
cIndex(systemDatabase_
);
1767 void *chunk
= NULL
, *hchunk
= 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 ");
1777 Chunk
*ch
= (Chunk
*) chunk
;
1778 if(flag
){ if(hchunk
)((TreeNode
*) hchunk
)->displayAll(); }
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_
);
1790 void *chunk
= NULL
, *hchunk
= 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");
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());
1819 printf(" <TotalElements> %lld </TotalElements>\n",((TreeNode
*) hchunk
)->getTotalElements());
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");
1834 printf("Unknown Index type\n");
1836 printf("<IndexNodes>\n");
1840 DbRetVal
DatabaseManagerImpl::registerThread()
1845 printError(ErrAlready
, "Process already registered\n");
1848 pMgr_
= new ProcessManager();
1849 rv
= pMgr_
->registerThread();
1851 procSlot
= pMgr_
->getProcSlot();
1852 systemDatabase_
->setProcSlot(procSlot
);
1853 printDebug(DM_Process
, "Process registed with slot %d\n", procSlot
);
1858 DbRetVal
DatabaseManagerImpl::deregisterThread()
1863 rv
= pMgr_
->deregisterThread(procSlot
);
1870 bool DatabaseManagerImpl::isAnyOneRegistered()
1872 if (pMgr_
!= NULL
) return pMgr_
->isAnyOneRegistered();
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();
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();
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();
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();
1931 page
= (PageInfo
*)(((PageInfo
*)page
)->nextPage_
) ;
1933 printf("</Chunk Mutexes>\n");
1934 lMgr_
->printMutexInfo();
1936 void DatabaseManagerImpl::printDebugChunkInfo()
1938 Database
*db
= sysDb();
1941 printf("<Chunk information>\n");
1942 printf(" <System Chunk >\n");
1943 chunk
=db
->getSystemDatabaseChunk(UserChunkTableId
);
1945 while(id
<MAX_CHUNKS
)
1947 chunk
=db
->getSystemDatabaseChunk(id
);
1948 if((chunk
->getChunkID())!=0){
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();
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);
1973 page
= (PageInfo
*)(((PageInfo
*)page
)->nextPage_
) ;
1975 printf(" </User Chunk >\n");
1976 printf("</Chunk information>\n");
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
);
1994 printError(ErrSysInternal
, "Unable to open table %s", tblName
);
1997 TableImpl
*tb
= (TableImpl
*) tbl
;
1999 if (tb
->numTuples()) pages
= tb
->pagesUsed();
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
);
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
;
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
);
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
;
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();
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();
2084 printError(ErrSysInternal
, "checkpoint error");
2086 rv
= db()->checkPoint();
2087 systemDatabase_
->releaseCheckpointMutex();
2091 DbRetVal
DatabaseManagerImpl::writeSchemaFile()
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");
2104 int ret
= unlink(schFile
);
2106 printError(ErrOS
, "checkpoint: delete schema file failed");
2110 fp
= fopen(schFile
, "w+");
2112 printError(ErrOS
, "Unable to create schema file for chkpt.");
2115 fp1
= fopen(mapFile
, "r");
2118 int ret
= unlink(mapFile
);
2120 printError(ErrOS
, "checkpoint: delete schema file failed");
2124 fd
= open(mapFile
, O_WRONLY
|O_CREAT
, 0644);
2126 printError(ErrOS
, "checkpoint: Unable to create map file.");
2129 List tableList
= getAllTableNames();
2130 ListIterator iter
= tableList
.getIterator();
2131 Identifier
*elem
= NULL
;
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
);
2146 strcpy(obj
.name
, elem
->name
);
2148 obj
.bucketChunk
= NULL
;
2149 obj
.firstPage
= ((Chunk
*)chunk
)->getFirstPage();
2150 obj
.curPage
= ((Chunk
*)chunk
)->getCurrentPage();
2152 write(fd
, buf
, sizeof(obj
));
2153 FieldInfo
*info
= new FieldInfo();
2154 List fNameList
= table
->getFieldNameList();
2155 ListIterator fNameIter
= fNameList
.getIterator();
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
);
2164 printf("unable to retrive info for table %s\n", elem
->name
);
2167 fprintf(fp
, "%s %s ", fieldName
, AllDataType::getSQLString(info
->type
));
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 ");
2179 while (fNameIter
.hasElement())
2180 delete ((FieldName
*) fNameIter
.nextElement());
2183 fprintf(fp
, ");\n");
2184 table
->printSQLIndexString(fp
, fd
);
2188 ListIterator tIter
= tableList
.getIterator();
2190 while (tIter
.hasElement())
2191 delete ((FieldName
*) tIter
.nextElement());
2199 DbRetVal
DatabaseManagerImpl::recover()
2202 rv
= sysDb()->recoverSystemDB();
2203 if (rv
!= OK
) return rv
;
2204 if (!Conf::config
.useMmap())rv
= db()->recoverUserDB();
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
);