cstack / db_tutorial

Writing a sqlite clone from scratch in C
https://cstack.github.io/db_tutorial
MIT License
9.56k stars 968 forks source link

pager_open function optimization #68

Open muxiaobao opened 3 years ago

muxiaobao commented 3 years ago

After implementing B-tree, each node occupies exactly one page of the table, so there is no need to test whether db file is a whole number of pages in pager_open function.

Pager* pager_open(const char* filename) {

    .............

    off_t file_length = lseek(fd, 0, SEEK_END);

    Pager* pager = malloc(sizeof(Pager));
    pager->file_descriptor = fd;
    pager->file_length = file_length;
    pager->num_pages = (file_length / PAGE_SIZE);

    // if (file_length % PAGE_SIZE != 0) {
    //     printf("Db file is not a whole number of pages. Corrupt file.\n");
    //     exit(EXIT_FAILURE);
    // }

    for (uint32_t i = 0; i < TABLE_MAX_PAGES; i++) {
        pager->pages[i] = NULL;
    }