diff --git a/source/libs/tdb/src/db/tdbPFile.c b/source/libs/tdb/src/db/tdbPFile.c index 144856c79a..db64ea2fe0 100644 --- a/source/libs/tdb/src/db/tdbPFile.c +++ b/source/libs/tdb/src/db/tdbPFile.c @@ -18,6 +18,7 @@ struct SPFile { char * dbFileName; char * jFileName; + int pageSize; uint8_t fid[TDB_FILE_ID_LEN]; int fd; int jfd; @@ -26,6 +27,8 @@ struct SPFile { SPgno dbOrigSize; }; +static int tdbPFileReadPage(SPFile *pFile, SPgHdr *pPage); + int tdbPFileOpen(SPCache *pCache, const char *fileName, SPFile **ppFile) { uint8_t *pPtr; SPFile * pFile; @@ -81,7 +84,13 @@ SPgHdr *tdbPFileGet(SPFile *pFile, SPgno pgno) { } tdbPCacheFetchFinish(pFile->pCache, pPage); - if (true /* not load from the file, then load the content from the file*/) { + if (pgno > pFile->dbFileSize /*TODO*/) { + memset(pPage->pData, 0, pFile->pageSize); + } else { + if (tdbPFileReadPage(pFile, pPage) < 0) { + // TODO: handle error + return NULL; + } } return pPage; @@ -100,4 +109,19 @@ int tdbPFileCommit(SPFile *pFile) { int tdbPFileRollback(SPFile *pFile) { // TODO return 0; +} + +static int tdbPFileReadPage(SPFile *pFile, SPgHdr *pPage) { + i64 offset; + int ret; + + ASSERT(memcmp(pFile->fid, pPage->pgid.fileid, TDB_FILE_ID_LEN) == 0); + + offset = (pPage->pgid.pgno - 1) * (i64)(pFile->pageSize); + ret = tdbPRead(pFile->fd, pPage->pData, pFile->pageSize, offset); + if (ret < 0) { + // TODO: handle error + return -1; + } + return 0; } \ No newline at end of file diff --git a/source/libs/tdb/src/db/tdbUtil.c b/source/libs/tdb/src/db/tdbUtil.c index 519451f757..c3467c590a 100644 --- a/source/libs/tdb/src/db/tdbUtil.c +++ b/source/libs/tdb/src/db/tdbUtil.c @@ -64,4 +64,29 @@ int tdbGetFileSize(const char *fname, int pgSize, SPgno *pSize) { *pSize = st.st_size / pgSize; return 0; +} + +int tdbPRead(int fd, void *pData, int count, i64 offset) { + void *pBuf; + int nbytes; + i64 ioffset; + int iread; + + pBuf = pData; + nbytes = count; + ioffset = offset; + while (nbytes > 0) { + iread = pread(fd, pBuf, nbytes, ioffset); + if (iread < 0) { + /* TODO */ + } else if (iread == 0) { + return (count - iread); + } + + nbytes = nbytes - iread; + pBuf = (void *)((u8 *)pBuf + iread); + ioffset += iread; + } + + return count; } \ No newline at end of file diff --git a/source/libs/tdb/src/inc/tdbUtil.h b/source/libs/tdb/src/inc/tdbUtil.h index 4526f7e350..7b190374a1 100644 --- a/source/libs/tdb/src/inc/tdbUtil.h +++ b/source/libs/tdb/src/inc/tdbUtil.h @@ -37,6 +37,8 @@ int tdbCheckFileAccess(const char *pathname, int mode); int tdbGetFileSize(const char *fname, int pgSize, SPgno *pSize); +int tdbPRead(int fd, void *pData, int count, i64 offset); + #ifdef __cplusplus } #endif