smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
pager.cc
Go to the documentation of this file.
2
3#include <fcntl.h>
4#include <sys/stat.h>
5#include <unistd.h>
6
7#include <cerrno>
8#include <cstdio>
9#include <cstdlib>
10#include <cstring>
11#include <string>
12
13#include "absl/status/status.h"
14#include "absl/strings/str_cat.h"
15
16namespace smollergraph {
17namespace {
18
19// A page that can't be read or written once the file is open leaves nothing
20// sensible to carry on with, so the program stops and says why.
21[[noreturn]] void Fail(const char* what) {
22 std::fprintf(stderr, "smollergraph: %s: %s\n", what, std::strerror(errno));
23 std::abort();
24}
25
26} // namespace
27
29 if (fd_ >= 0) close(fd_);
30}
31
32absl::Status Pager::Open(const std::string& path) {
33 return Adopt(open(path.c_str(), O_RDWR | O_CREAT, 0644), path);
34}
35
36absl::Status Pager::OpenTemporary() {
37 char path[] = "/tmp/smollergraph-XXXXXX";
38 int fd = mkstemp(path);
39 // Without a name, the file lasts as long as it's open.
40 if (fd >= 0) unlink(path);
41 return Adopt(fd, "a temporary file");
42}
43
44absl::Status Pager::Adopt(int fd, std::string_view name) {
45 struct stat info;
46 if (fd < 0 || fstat(fd, &info) != 0) {
47 // ErrnoToStatus picks the status code that goes with the system's error.
48 absl::Status status =
49 absl::ErrnoToStatus(errno, absl::StrCat("can't open ", name));
50 if (fd >= 0) close(fd);
51 return status;
52 }
53 if (fd_ >= 0) close(fd_);
54 fd_ = fd;
55 page_count_ = static_cast<PageId>(info.st_size / kPageSize);
56 return absl::OkStatus();
57}
58
59void Pager::Read(PageId id, Page& page) const {
60 off_t offset = static_cast<off_t>(id) * kPageSize;
61 if (pread(fd_, page.data(), kPageSize, offset) !=
62 static_cast<ssize_t>(kPageSize)) {
63 Fail("can't read a page");
64 }
65 ++reads_;
66}
67
68void Pager::Write(PageId id, const Page& page) {
69 off_t offset = static_cast<off_t>(id) * kPageSize;
70 if (pwrite(fd_, page.data(), kPageSize, offset) !=
71 static_cast<ssize_t>(kPageSize)) {
72 Fail("can't write a page");
73 }
74 if (id >= page_count_) page_count_ = id + 1;
75 ++writes_;
76}
77
78} // namespace smollergraph
void Read(PageId id, Page &page) const
Reads page id, which has to be below page_count().
Definition pager.cc:59
absl::Status Open(const std::string &path)
Opens the file at path, creating it when it isn't there.
Definition pager.cc:32
absl::Status OpenTemporary()
Opens a file with no name, which is deleted once it's closed.
Definition pager.cc:36
void Write(PageId id, const Page &page)
Writes page id. Writing the page at page_count() adds it to the file.
Definition pager.cc:68
std::array< std::byte, kPageSize > Page
Definition pager.h:20
uint32_t PageId
Definition pager.h:19
constexpr size_t kPageSize
What the database reads and writes at a time: 4 KiB, the size of a block on most file systems and dis...
Definition pager.h:17
Path path
Definition plan.cc:115