Introduction to storage
easy 24 minHow a database keeps data: pages on disk, a buffer pool of pages in memory, indexes that find the right page, and a write-ahead log that makes a commit survive a crash.
A buffer pool with a write-ahead log
Read it, run it, change a line and run it again.
Loading editor…
The log is flushed at commit and before a dirty page is written out. A crash throws away the pool, and recovery replays committed records.
The same in Go
package walimport "os"// Record is one entry of a write-ahead log.type Record struct { LSN uint64 // log sequence number TxID uint64 Type string // "INSERT", "UPDATE", "DELETE", "COMMIT" TableID uint32 PageID uint32 Offset uint16 OldData []byte // for undo NewData []byte // for redo}type WAL struct{ file *os.File }// Append writes sequentially. Call Flush before confirming a commit.func (w *WAL) Append(encoded []byte) error { _, err := w.file.Write(encoded) return err}func (w *WAL) Flush() error { return w.file.Sync() }// Recover repeats history, then removes what never committed, newest first.func Recover(records []Record, redo, undo func(Record)) { committed := map[uint64]bool{} for _, r := range records { if r.Type == "COMMIT" { committed[r.TxID] = true continue } redo(r) } for i := len(records) - 1; i >= 0; i-- { r := records[i] if r.Type != "COMMIT" && !committed[r.TxID] { undo(r) } }}