Renamed server directory to storage directory in src
[csql.git] / src / storage / Database.cxx
blobad7881cbb1b52a4ae22c9429eb30aa1c6938e85d
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;
251 pageInfo = (PageInfo*)((char*)pInfo + pageSize);
254 printDebug(DM_Alloc,"Database::getFreePage returning page:%x",pageInfo);
255 setCurrentPage((Page*) pageInfo);
256 return (Page*) pageInfo ;
259 void Database::printStatistics()
261 Page* page = getFirstPage();
262 PageInfo* pageInfo = ((PageInfo*)page);
263 int usedPageCount =0, usedMergedPageCount =0, totalPages=0;
264 printf("<DatabaseStatistics>\n");
265 printf(" <Database Name> %s </Database Name>\n", getName());
266 printf(" <Max Size> %ld </Max Size>\n", getMaxSize());
267 printf(" <First Page> %x </First Page>\n", getFirstPage());
268 while(isValidAddress((char*) pageInfo))
270 if (pageInfo == NULL) break;
271 if (1 == pageInfo->isUsed_) {
272 if ( pageInfo->nextPageAfterMerge_ == NULL) {
273 pageInfo = (PageInfo*)((char*)pageInfo + PAGE_SIZE);
274 usedPageCount++; totalPages++;
275 printDebug(DM_Alloc, "Normal Page:Moving to page:%x\n",pageInfo);
276 continue;
278 else {
279 pageInfo = (PageInfo*)pageInfo->nextPageAfterMerge_;
280 usedMergedPageCount++; totalPages++;
281 printDebug(DM_Alloc,"Merged Page:Moving to page:%x\n",pageInfo);
282 continue;
285 pageInfo = (PageInfo*)((char*)pageInfo + PAGE_SIZE);
286 printDebug(DM_Alloc,"Normal Page not used:Moving to page:%x\n",pageInfo);
287 totalPages++;
289 printf(" <Total Pages> %d </Total Pages>\n", totalPages);
290 printf(" <Used Normal Pages> %d </Used Normal Pages>\n", usedPageCount);
291 printf(" <Used Merged Pages> %d </Used Merged Pages>\n", usedMergedPageCount);
292 printf(" <Chunks Used> %d </Chunks Used>\n", getNoOfChunks());
293 printf("</DatabaseStatistics>\n");
295 return ;
299 //called only in case of system database to create and initialize the chunk
300 //information
301 DbRetVal Database::createSystemDatabaseChunk(AllocType type, size_t size, int id)
304 Chunk *chunk;
305 if (-1 == id )
307 printError(ErrSysFatal, "Database ID corrupted");
308 return ErrSysFatal;
310 chunk = getSystemDatabaseChunk(id);
312 if (FixedSizeAllocator == type) chunk->setSize(size);
313 //getDatabaseMutex();
314 if (chunk->allocSize_ > PAGE_SIZE)
315 chunk->curPage_ = getFreePage(chunk->allocSize_);
316 else
317 chunk->curPage_ = getFreePage();
318 if ( chunk->curPage_ == NULL)
320 //releaseDatabaseMutex();
321 printError(ErrNoMemory, "No free pages in database: Database full");
322 return ErrNoMemory;
325 chunk->firstPage_ = chunk->curPage_;
326 PageInfo* firstPageInfo = ((PageInfo*)chunk->firstPage_);
327 firstPageInfo->setFirstPageAsUsed();
328 chunk->setChunkID(id);
329 chunk->setAllocType(type);
330 printDebug(DM_Database, "Creating System Database Chunk:%d Size:%d",id, chunk->allocSize_);
331 if (chunk->allocSize_ > PAGE_SIZE)
333 int multiple = os::floor(chunk->allocSize_ / PAGE_SIZE);
334 int offset = ((multiple + 1) * PAGE_SIZE);
335 firstPageInfo->nextPageAfterMerge_ = ((char*)firstPageInfo)+ offset;
338 if (0 == size)
340 VarSizeInfo *varInfo = (VarSizeInfo*)(((char*)firstPageInfo) + sizeof(PageInfo));
341 varInfo->isUsed_ = 0;
342 varInfo->size_ = PAGE_SIZE - sizeof(PageInfo) - sizeof(VarSizeInfo);
345 incrementChunk();
346 //releaseDatabaseMutex();
347 return OK;
350 //This is never called currently. If situation arises will be coded later.
351 DbRetVal Database::deleteSystemDatabaseChunk(int id)
354 Chunk *chunk = getSystemDatabaseChunk(id);
355 chunk->setChunkID(-1);
356 chunk->setSize(0);
357 chunk->setAllocType(UnknownAllocator);
358 //TODO::
359 //chunk->pageList_
360 //walk though the pageList ptr and get all the page pointers
361 //then free all the pages used to store this by setting the
362 //start of page to notused
363 chunk->firstPage_ = NULL;
364 chunk->curPage_ = NULL;
365 decrementChunk();
366 return OK;
370 void Database::createAllCatalogTables()
372 //These are special chunks which hold catalog tables and other information
374 // chunk id 0 ->userChunkTable
375 // chunk id 1 ->lockBucketHash
376 // chunk id 2 ->lockTable
378 // chunk id 10->DATABASE
379 // chunk id 11->USER
380 // chunk id 12->TABLE
381 // chunk id 13->FIELD
382 // chunk id 14->ACCESS
384 createSystemTables();
385 createMetaDataTables();
387 void Database::createSystemTables()
389 createSystemDatabaseChunk(FixedSizeAllocator,
390 sizeof(Chunk), UserChunkTableId);
391 createSystemDatabaseChunk(FixedSizeAllocator,
392 sizeof(Bucket) * LOCK_BUCKET_SIZE,
393 LockTableHashBucketId);
394 createSystemDatabaseChunk(FixedSizeAllocator,
395 sizeof(Mutex)* LOCK_BUCKET_SIZE,
396 LockTableMutexId);
397 createSystemDatabaseChunk(FixedSizeAllocator,
398 sizeof(LockHashNode), LockTableId);
399 createSystemDatabaseChunk(FixedSizeAllocator,
400 sizeof(TransHasNode), TransHasTableId);
402 createSystemDatabaseChunk(VariableSizeAllocator,
403 0, UndoLogTableID);
405 void Database::createMetaDataTables()
407 createSystemDatabaseChunk(FixedSizeAllocator,
408 sizeof(DATABASEFILE), DatabaseTableId);
409 createSystemDatabaseChunk(FixedSizeAllocator,
410 sizeof(USER), UserTableId);
411 createSystemDatabaseChunk(FixedSizeAllocator,
412 sizeof(TABLE), TableTableId);
413 createSystemDatabaseChunk(FixedSizeAllocator,
414 sizeof(FIELD), FieldTableId);
415 createSystemDatabaseChunk(FixedSizeAllocator,
416 sizeof(ACCESS), AccessTableId);
417 createSystemDatabaseChunk(FixedSizeAllocator,
418 sizeof(INDEX), IndexTableId);
419 createSystemDatabaseChunk(FixedSizeAllocator,
420 sizeof(INDEXFIELD), IndexFieldTableId);
423 //used in case of system database
424 Chunk* Database::getSystemDatabaseChunk(int id)
426 size_t offset = os::alignLong(sizeof (DatabaseMetaData)) +
427 id * sizeof (Chunk);
428 return (Chunk*)(((char*) metaData_) + offset);
432 //used in case of system database
433 Transaction* Database::getSystemDatabaseTrans(int slot)
435 size_t offset = os::alignLong(sizeof (DatabaseMetaData)) +
436 os::alignLong(MAX_CHUNKS * sizeof (Chunk)) +
437 slot * sizeof (Transaction);
438 return (Transaction*)(((char*) metaData_) + offset);
441 //used in case of system database
442 ThreadInfo* Database::getThreadInfo(int slot)
444 /* size_t offset = os::alignLong(sizeof (DatabaseMetaData));
445 offset = offset + os::alignLong( MAX_CHUNKS * sizeof (Chunk));
446 offset = offset + os::alignLong( Conf::config.getMaxProcs() * sizeof(Transaction));
447 offset = offset + slot * sizeof (ThreadInfo);
448 return (ThreadInfo*)(((char*) metaData_) + offset);
451 static size_t offset = os::alignLong(sizeof (DatabaseMetaData)) +
452 os::alignLong( MAX_CHUNKS * sizeof (Chunk)) +
453 os::alignLong( Conf::config.getMaxProcs()*sizeof(Transaction));
455 size_t off = offset + slot * sizeof (ThreadInfo);
456 return (ThreadInfo*)(((char*) metaData_) + off);
460 bool Database::isValidAddress(void* addr)
462 if ((char*) addr >= ((char*)getMetaDataPtr()) + getMaxSize())
463 return false;
464 else
465 return true;
468 //should be called only on system database
469 void* Database::allocLockHashBuckets()
471 Chunk *chunk = getSystemDatabaseChunk(LockTableHashBucketId);
472 void *ptr = chunk->allocate(this);
473 if (NULL == ptr)
475 printError(ErrNoMemory, "Chunk Allocation failed for lock hash bucket catalog table");
477 return ptr;
480 Bucket* Database::getLockHashBuckets()
482 Chunk *tChunk = getSystemDatabaseChunk(LockTableHashBucketId);
483 ChunkIterator iter = tChunk->getIterator();
484 return (Bucket*)iter.nextElement();