init creates a new database file and initializes its meta pages.
()
| 644 | |
| 645 | // init creates a new database file and initializes its meta pages. |
| 646 | func (db *DB) init() error { |
| 647 | // Create two meta pages on a buffer. |
| 648 | buf := make([]byte, db.pageSize*4) |
| 649 | for i := 0; i < 2; i++ { |
| 650 | p := db.pageInBuffer(buf, common.Pgid(i)) |
| 651 | p.SetId(common.Pgid(i)) |
| 652 | p.SetFlags(common.MetaPageFlag) |
| 653 | |
| 654 | // Initialize the meta page. |
| 655 | m := p.Meta() |
| 656 | m.SetMagic(common.Magic) |
| 657 | m.SetVersion(common.Version) |
| 658 | m.SetPageSize(uint32(db.pageSize)) |
| 659 | m.SetFreelist(2) |
| 660 | m.SetRootBucket(common.NewInBucket(3, 0)) |
| 661 | m.SetPgid(4) |
| 662 | m.SetTxid(common.Txid(i)) |
| 663 | m.SetChecksum(m.Sum64()) |
| 664 | } |
| 665 | |
| 666 | // Write an empty freelist at page 3. |
| 667 | p := db.pageInBuffer(buf, common.Pgid(2)) |
| 668 | p.SetId(2) |
| 669 | p.SetFlags(common.FreelistPageFlag) |
| 670 | p.SetCount(0) |
| 671 | |
| 672 | // Write an empty leaf page at page 4. |
| 673 | p = db.pageInBuffer(buf, common.Pgid(3)) |
| 674 | p.SetId(3) |
| 675 | p.SetFlags(common.LeafPageFlag) |
| 676 | p.SetCount(0) |
| 677 | |
| 678 | // Write the buffer to our data file. |
| 679 | if _, err := db.ops.writeAt(buf, 0); err != nil { |
| 680 | db.Logger().Errorf("writeAt failed: %w", err) |
| 681 | return err |
| 682 | } |
| 683 | if err := fdatasync(db); err != nil { |
| 684 | db.Logger().Errorf("[GOOS: %s, GOARCH: %s] fdatasync failed: %w", runtime.GOOS, runtime.GOARCH, err) |
| 685 | return err |
| 686 | } |
| 687 | |
| 688 | return nil |
| 689 | } |
| 690 | |
| 691 | // Close releases all database resources. |
| 692 | // It will block waiting for any open transactions to finish |
no test coverage detected