1959716 DMLThreadTest fails to read records sometimes
[csql.git] / src / server / Database.cxx
blob17e47576bdda1cea46228b7cb7865bc422a0a5d1
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<os.h>
18 #include<CatalogTables.h>
19 #include<Transaction.h>
20 #include<Lock.h>
21 #include<Debug.h>
22 #include<Config.h>
23 #include<Process.h>
25 const char* Database::getName()
27 return metaData_->dbName_;
30 int Database::getDatabaseID()
32 return metaData_->dbID_;
35 long Database::getMaxSize()
37 return metaData_->maxSize_;
40 long Database::getCurrentSize()
42 return metaData_->curSize_;
45 Page* Database::getCurrentPage()
47 return metaData_->curPage_;
50 Page* Database::getFirstPage()
52 return metaData_->firstPage_;
55 int Database::getNoOfChunks()
57 return metaData_->noOfChunks_;
59 Chunk* Database::getHashIndexChunk()
61 return metaData_->hashIndexChunk_;
64 void Database::setDatabaseID(int id)
66 metaData_->dbID_ = id;
68 void Database::setName(const char *name)
70 strcpy(metaData_->dbName_ , name);
72 void Database::setCurrentSize(long size)
74 metaData_->curSize_ = size;
76 void Database::setCurrentPage(Page *page)
78 metaData_->curPage_ = page;
80 void Database::setFirstPage(Page *page)
82 metaData_->firstPage_ = page;
84 void Database::setMaxSize(long size)
86 metaData_->maxSize_ = size;
88 void Database::setNoOfChunks(int chunks)
90 metaData_->noOfChunks_ = chunks;
92 void Database::setHashIndexChunk(Chunk *ch)
94 metaData_->hashIndexChunk_ = ch;
98 int Database::initAllocDatabaseMutex()
100 return metaData_->dbAllocMutex_.init("allocdb");
102 DbRetVal Database::getAllocDatabaseMutex(bool procAccount)
104 int ret= metaData_->dbAllocMutex_.getLock(procAccount);
105 if (ret) return ErrLockTimeOut; else return OK;
107 DbRetVal Database::releaseAllocDatabaseMutex(bool procAccount)
109 metaData_->dbAllocMutex_.releaseLock(procAccount);
110 return OK;
115 int Database::initTransTableMutex()
117 return metaData_->dbTransTableMutex_.init("transtable");
119 DbRetVal Database::getTransTableMutex()
121 int ret = metaData_->dbTransTableMutex_.getLock(procSlot);
122 if (ret) return ErrLockTimeOut; else return OK;
124 DbRetVal Database::releaseTransTableMutex()
126 metaData_->dbTransTableMutex_.releaseLock(procSlot);
127 return OK;
132 int Database::initProcessTableMutex()
134 return metaData_->dbProcTableMutex_.init("proctable");
136 DbRetVal Database::getProcessTableMutex(bool procAccount)
138 int ret = metaData_->dbProcTableMutex_.getLock(-1, procAccount);
139 if (ret) return ErrLockTimeOut; else return OK;
141 DbRetVal Database::releaseProcessTableMutex(bool procAccount)
143 metaData_->dbProcTableMutex_.releaseLock(-1, procAccount);
144 return OK;
149 int Database::initDatabaseMutex()
151 return metaData_->dbMutex_.init("db");
153 DbRetVal Database::getDatabaseMutex(bool procAccount)
155 int ret = metaData_->dbMutex_.getLock(procSlot, procAccount);
156 if (ret) return ErrLockTimeOut; else return OK;
158 DbRetVal Database::releaseDatabaseMutex(bool procAccount)
160 metaData_->dbMutex_.releaseLock(procSlot, procAccount);
161 return OK;
164 // Gets the free page
165 // Each page is segmented by PAGE_SIZE, so it checks the pageInfo
166 // of each page to determine if the page is free
167 // Algorithm is to scan through the pageInfo objects stored at
168 // address (db start address + i * PAGE_SIZE) where i = 1..n till end
169 // database
170 // But in case of large tuples, pages are merged, so there wont be
171 // PageInfo object on pages which are merged.
172 // These pages are skipped by checking the nextPageAfterMerge_ of PageInfo
174 //NOTE::IMPORTANT::assumes alloc database lock is taken before calling this
175 Page* Database::getFreePage()
177 //Page* page = getFirstPage();
178 Page* page = getCurrentPage();
179 //printDebug(DM_Alloc, "Database::getFreePage firstPage:%x",page);
180 printDebug(DM_Alloc, "Database::getFreePage currentpage:%x",page);
181 PageInfo* pageInfo = ((PageInfo*)page);
182 char* endAddr = ((char*)getMetaDataPtr()) + getMaxSize();
183 int pageSize = PAGE_SIZE;
184 while( 1 == pageInfo->isUsed_)
186 //If any pages are merged to store data larger than PAGE_SIZE
187 //move to the next page after the merge and check whether it is used
188 if ( pageInfo->nextPageAfterMerge_ == NULL) {
189 pageInfo = (PageInfo*)((char*)pageInfo + pageSize);
190 printDebug(DM_Alloc,"Normal Page:Moving to page:%x",pageInfo);
192 else {
193 pageInfo = (PageInfo*)pageInfo->nextPageAfterMerge_;
194 printDebug(DM_Alloc,"Merged Page:Moving to page:%x",pageInfo);
196 if ((char*)pageInfo >= endAddr)
198 //printError(ErrSysInternal,"Invalid address %x",pageInfo);
199 return NULL;
203 if (!isValidAddress(((char*) pageInfo) + pageSize))
205 printError(ErrSysInternal, "Invalid address %x",((char*) pageInfo) + pageSize);
206 return NULL;
208 setCurrentPage((Page*) pageInfo);
209 printDebug(DM_Alloc,"Database::getFreePage returning page:%x",pageInfo);
210 return (Page*) pageInfo ;
213 //Used by tuples more than PAGE_SIZE
214 //NOTE::IMPORTANT::assumes alloc database lock is taken before calling this
215 Page* Database::getFreePage(size_t size)
217 Page* page = getFirstPage();
218 PageInfo* pageInfo = ((PageInfo*)page);
219 int multiple = size / PAGE_SIZE;
220 int offset = ((multiple + 1) * PAGE_SIZE);
221 printDebug(DM_Alloc, "Database::getFreePage firstPage:%x size:%ld",page, size);
222 char* endAddr = ((char*)getMetaDataPtr()) + getMaxSize();
223 int pageSize = PAGE_SIZE;
224 while(true){
225 while( 1 == pageInfo->isUsed_)
227 //If any pages are merged to store data larger than PAGE_SIZE
228 //move to the next page after the merge and check whether it is used
229 if ( pageInfo->nextPageAfterMerge_ == NULL) {
230 pageInfo = (PageInfo*)((char*)pageInfo + pageSize);
231 printDebug(DM_Alloc,"Normal Page:Moving to page:%x",pageInfo);
233 else {
234 pageInfo = (PageInfo*)pageInfo->nextPageAfterMerge_;
235 printDebug(DM_Alloc,"Merged Page:Moving to page:%x",pageInfo);
238 int i = 0;
239 PageInfo *pInfo = pageInfo;
240 if ((((char*)pInfo) + offset) >= endAddr)
242 printError(ErrSysInternal,"Invalid address %x",((char*)pInfo) + offset);
243 return NULL;
245 for (i = 0; i< multiple + 1; i++)
247 if (1 == pInfo->isUsed_) break;
248 pInfo = (PageInfo*)((char*)pInfo + pageSize);
250 if ( i == (multiple + 1)) break;
253 printDebug(DM_Alloc,"Database::getFreePage returning page:%x",pageInfo);
254 setCurrentPage((Page*) pageInfo);
255 return (Page*) pageInfo ;
258 void Database::printStatistics()
260 Page* page = getFirstPage();
261 PageInfo* pageInfo = ((PageInfo*)page);
262 int usedPageCount =0, usedMergedPageCount =0, totalPages=0;
263 printf("<DatabaseStatistics>\n");
264 printf(" <Database Name> %s </Database Name>\n", getName());
265 printf(" <Max Size> %ld </Max Size>\n", getMaxSize());
266 printf(" <First Page> %x </First Page>\n", getFirstPage());
267 while(isValidAddress((char*) pageInfo))
269 if (pageInfo == NULL) break;
270 if (1 == pageInfo->isUsed_) {
271 if ( pageInfo->nextPageAfterMerge_ == NULL) {
272 pageInfo = (PageInfo*)((char*)pageInfo + PAGE_SIZE);
273 usedPageCount++; totalPages++;
274 printDebug(DM_Alloc, "Normal Page:Moving to page:%x\n",pageInfo);
275 continue;
277 else {
278 pageInfo = (PageInfo*)pageInfo->nextPageAfterMerge_;
279 usedMergedPageCount++; totalPages++;
280 printDebug(DM_Alloc,"Merged Page:Moving to page:%x\n",pageInfo);
281 continue;
284 pageInfo = (PageInfo*)((char*)pageInfo + PAGE_SIZE);
285 printDebug(DM_Alloc,"Normal Page not used:Moving to page:%x\n",pageInfo);
286 totalPages++;
288 printf(" <Total Pages> %d </Total Pages>\n", totalPages);
289 printf(" <Used Normal Pages> %d </Used Normal Pages>\n", usedPageCount);
290 printf(" <Used Merged Pages> %d </Used Merged Pages>\n", usedMergedPageCount);
291 printf(" <Chunks Used> %d </Chunks Used>\n", getNoOfChunks());
292 printf("</DatabaseStatistics>\n");
294 return ;
298 //called only in case of system database to create and initialize the chunk
299 //information
300 DbRetVal Database::createSystemDatabaseChunk(AllocType type, size_t size, int id)
303 Chunk *chunk;
304 if (-1 == id )
306 printError(ErrSysFatal, "Database ID corrupted");
307 return ErrSysFatal;
309 chunk = getSystemDatabaseChunk(id);
311 if (FixedSizeAllocator == type) chunk->setSize(size);
312 //getDatabaseMutex();
313 if (chunk->allocSize_ > PAGE_SIZE)
314 chunk->curPage_ = getFreePage(chunk->allocSize_);
315 else
316 chunk->curPage_ = getFreePage();
317 if ( chunk->curPage_ == NULL)
319 //releaseDatabaseMutex();
320 printError(ErrNoMemory, "No free pages in database: Database full");
321 return ErrNoMemory;
324 chunk->firstPage_ = chunk->curPage_;
325 PageInfo* firstPageInfo = ((PageInfo*)chunk->firstPage_);
326 firstPageInfo->setFirstPageAsUsed();
327 chunk->setChunkID(id);
328 chunk->setAllocType(type);
329 printDebug(DM_Database, "Creating System Database Chunk:%d Size:%d",id, chunk->allocSize_);
330 if (chunk->allocSize_ > PAGE_SIZE)
332 int multiple = os::floor(chunk->allocSize_ / PAGE_SIZE);
333 int offset = ((multiple + 1) * PAGE_SIZE);
334 firstPageInfo->nextPageAfterMerge_ = ((char*)firstPageInfo)+ offset;
337 if (0 == size)
339 VarSizeInfo *varInfo = (VarSizeInfo*)(((char*)firstPageInfo) + sizeof(PageInfo));
340 varInfo->isUsed_ = 0;
341 varInfo->size_ = PAGE_SIZE - sizeof(PageInfo) - sizeof(VarSizeInfo);
344 incrementChunk();
345 //releaseDatabaseMutex();
346 return OK;
349 //This is never called currently. If situation arises will be coded later.
350 DbRetVal Database::deleteSystemDatabaseChunk(int id)
353 Chunk *chunk = getSystemDatabaseChunk(id);
354 chunk->setChunkID(-1);
355 chunk->setSize(0);
356 chunk->setAllocType(UnknownAllocator);
357 //TODO::
358 //chunk->pageList_
359 //walk though the pageList ptr and get all the page pointers
360 //then free all the pages used to store this by setting the
361 //start of page to notused
362 chunk->firstPage_ = NULL;
363 chunk->curPage_ = NULL;
364 decrementChunk();
365 return OK;
369 void Database::createAllCatalogTables()
371 //These are special chunks which hold catalog tables and other information
373 // chunk id 0 ->userChunkTable
374 // chunk id 1 ->lockBucketHash
375 // chunk id 2 ->lockTable
377 // chunk id 10->DATABASE
378 // chunk id 11->USER
379 // chunk id 12->TABLE
380 // chunk id 13->FIELD
381 // chunk id 14->ACCESS
383 createSystemTables();
384 createMetaDataTables();
386 void Database::createSystemTables()
388 createSystemDatabaseChunk(FixedSizeAllocator,
389 sizeof(Chunk), UserChunkTableId);
390 createSystemDatabaseChunk(FixedSizeAllocator,
391 sizeof(Bucket) * LOCK_BUCKET_SIZE,
392 LockTableHashBucketId);
393 createSystemDatabaseChunk(FixedSizeAllocator,
394 sizeof(Mutex)* LOCK_BUCKET_SIZE,
395 LockTableMutexId);
396 createSystemDatabaseChunk(FixedSizeAllocator,
397 sizeof(LockHashNode), LockTableId);
398 createSystemDatabaseChunk(FixedSizeAllocator,
399 sizeof(TransHasNode), TransHasTableId);
401 createSystemDatabaseChunk(VariableSizeAllocator,
402 0, UndoLogTableID);
404 void Database::createMetaDataTables()
406 createSystemDatabaseChunk(FixedSizeAllocator,
407 sizeof(DATABASEFILE), DatabaseTableId);
408 createSystemDatabaseChunk(FixedSizeAllocator,
409 sizeof(USER), UserTableId);
410 createSystemDatabaseChunk(FixedSizeAllocator,
411 sizeof(TABLE), TableTableId);
412 createSystemDatabaseChunk(FixedSizeAllocator,
413 sizeof(FIELD), FieldTableId);
414 createSystemDatabaseChunk(FixedSizeAllocator,
415 sizeof(ACCESS), AccessTableId);
416 createSystemDatabaseChunk(FixedSizeAllocator,
417 sizeof(INDEX), IndexTableId);
418 createSystemDatabaseChunk(FixedSizeAllocator,
419 sizeof(INDEXFIELD), IndexFieldTableId);
422 //used in case of system database
423 Chunk* Database::getSystemDatabaseChunk(int id)
425 size_t offset = os::alignLong(sizeof (DatabaseMetaData)) +
426 id * sizeof (Chunk);
427 return (Chunk*)(((char*) metaData_) + offset);
431 //used in case of system database
432 Transaction* Database::getSystemDatabaseTrans(int slot)
434 size_t offset = os::alignLong(sizeof (DatabaseMetaData)) +
435 os::alignLong(MAX_CHUNKS * sizeof (Chunk)) +
436 slot * sizeof (Transaction);
437 return (Transaction*)(((char*) metaData_) + offset);
440 //used in case of system database
441 ThreadInfo* Database::getThreadInfo(int slot)
443 /* size_t offset = os::alignLong(sizeof (DatabaseMetaData));
444 offset = offset + os::alignLong( MAX_CHUNKS * sizeof (Chunk));
445 offset = offset + os::alignLong( Conf::config.getMaxProcs() * sizeof(Transaction));
446 offset = offset + slot * sizeof (ThreadInfo);
447 return (ThreadInfo*)(((char*) metaData_) + offset);
450 static size_t offset = os::alignLong(sizeof (DatabaseMetaData)) +
451 os::alignLong( MAX_CHUNKS * sizeof (Chunk)) +
452 os::alignLong( Conf::config.getMaxProcs()*sizeof(Transaction));
454 size_t off = offset + slot * sizeof (ThreadInfo);
455 return (ThreadInfo*)(((char*) metaData_) + off);
459 bool Database::isValidAddress(void* addr)
461 if ((char*) addr >= ((char*)getMetaDataPtr()) + getMaxSize())
462 return false;
463 else
464 return true;
467 //should be called only on system database
468 void* Database::allocLockHashBuckets()
470 Chunk *chunk = getSystemDatabaseChunk(LockTableHashBucketId);
471 void *ptr = chunk->allocate(this);
472 if (NULL == ptr)
474 printError(ErrNoMemory, "Chunk Allocation failed for lock hash bucket catalog table");
476 return ptr;
479 Bucket* Database::getLockHashBuckets()
481 Chunk *tChunk = getSystemDatabaseChunk(LockTableHashBucketId);
482 ChunkIterator iter = tChunk->getIterator();
483 return (Bucket*)iter.nextElement();