{"id":13435612,"url":"https://github.com/boltdb/bolt","last_synced_at":"2025-12-30T02:16:32.024Z","repository":{"id":12673322,"uuid":"15345331","full_name":"boltdb/bolt","owner":"boltdb","description":"An embedded key/value database for Go.","archived":true,"fork":false,"pushed_at":"2018-03-02T18:00:53.000Z","size":1326,"stargazers_count":14203,"open_issues_count":84,"forks_count":1511,"subscribers_count":347,"default_branch":"master","last_synced_at":"2024-10-29T20:35:39.033Z","etag":null,"topics":["database","go","key-value"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/boltdb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-12-20T18:26:14.000Z","updated_at":"2024-10-29T11:40:47.000Z","dependencies_parsed_at":"2022-07-12T13:33:39.915Z","dependency_job_id":null,"html_url":"https://github.com/boltdb/bolt","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/boltdb%2Fbolt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/boltdb%2Fbolt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/boltdb%2Fbolt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/boltdb%2Fbolt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/boltdb","download_url":"https://codeload.github.com/boltdb/bolt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235425032,"owners_count":18988338,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","go","key-value"],"created_at":"2024-07-31T03:00:37.434Z","updated_at":"2025-10-05T17:31:53.378Z","avatar_url":"https://github.com/boltdb.png","language":"Go","readme":"Bolt [![Coverage Status](https://coveralls.io/repos/boltdb/bolt/badge.svg?branch=master)](https://coveralls.io/r/boltdb/bolt?branch=master) [![GoDoc](https://godoc.org/github.com/boltdb/bolt?status.svg)](https://godoc.org/github.com/boltdb/bolt) ![Version](https://img.shields.io/badge/version-1.2.1-green.svg)\n====\n\nBolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas]\n[LMDB project][lmdb]. The goal of the project is to provide a simple,\nfast, and reliable database for projects that don't require a full database\nserver such as Postgres or MySQL.\n\nSince Bolt is meant to be used as such a low-level piece of functionality,\nsimplicity is key. The API will be small and only focus on getting values\nand setting values. That's it.\n\n[hyc_symas]: https://twitter.com/hyc_symas\n[lmdb]: http://symas.com/mdb/\n\n## Project Status\n\nBolt is stable, the API is fixed, and the file format is fixed. Full unit\ntest coverage and randomized black box testing are used to ensure database\nconsistency and thread safety. Bolt is currently used in high-load production\nenvironments serving databases as large as 1TB. Many companies such as\nShopify and Heroku use Bolt-backed services every day.\n\n## A message from the author\n\n\u003e The original goal of Bolt was to provide a simple pure Go key/value store and to\n\u003e not bloat the code with extraneous features. To that end, the project has been\n\u003e a success. However, this limited scope also means that the project is complete.\n\u003e \n\u003e Maintaining an open source database requires an immense amount of time and energy.\n\u003e Changes to the code can have unintended and sometimes catastrophic effects so\n\u003e even simple changes require hours and hours of careful testing and validation.\n\u003e\n\u003e Unfortunately I no longer have the time or energy to continue this work. Bolt is\n\u003e in a stable state and has years of successful production use. As such, I feel that\n\u003e leaving it in its current state is the most prudent course of action.\n\u003e\n\u003e If you are interested in using a more featureful version of Bolt, I suggest that\n\u003e you look at the CoreOS fork called [bbolt](https://github.com/coreos/bbolt).\n\n- Ben Johnson ([@benbjohnson](https://twitter.com/benbjohnson))\n\n## Table of Contents\n\n- [Getting Started](#getting-started)\n  - [Installing](#installing)\n  - [Opening a database](#opening-a-database)\n  - [Transactions](#transactions)\n    - [Read-write transactions](#read-write-transactions)\n    - [Read-only transactions](#read-only-transactions)\n    - [Batch read-write transactions](#batch-read-write-transactions)\n    - [Managing transactions manually](#managing-transactions-manually)\n  - [Using buckets](#using-buckets)\n  - [Using key/value pairs](#using-keyvalue-pairs)\n  - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket)\n  - [Iterating over keys](#iterating-over-keys)\n    - [Prefix scans](#prefix-scans)\n    - [Range scans](#range-scans)\n    - [ForEach()](#foreach)\n  - [Nested buckets](#nested-buckets)\n  - [Database backups](#database-backups)\n  - [Statistics](#statistics)\n  - [Read-Only Mode](#read-only-mode)\n  - [Mobile Use (iOS/Android)](#mobile-use-iosandroid)\n- [Resources](#resources)\n- [Comparison with other databases](#comparison-with-other-databases)\n  - [Postgres, MySQL, \u0026 other relational databases](#postgres-mysql--other-relational-databases)\n  - [LevelDB, RocksDB](#leveldb-rocksdb)\n  - [LMDB](#lmdb)\n- [Caveats \u0026 Limitations](#caveats--limitations)\n- [Reading the Source](#reading-the-source)\n- [Other Projects Using Bolt](#other-projects-using-bolt)\n\n## Getting Started\n\n### Installing\n\nTo start using Bolt, install Go and run `go get`:\n\n```sh\n$ go get github.com/boltdb/bolt/...\n```\n\nThis will retrieve the library and install the `bolt` command line utility into\nyour `$GOBIN` path.\n\n\n### Opening a database\n\nThe top-level object in Bolt is a `DB`. It is represented as a single file on\nyour disk and represents a consistent snapshot of your data.\n\nTo open your database, simply use the `bolt.Open()` function:\n\n```go\npackage main\n\nimport (\n\t\"log\"\n\n\t\"github.com/boltdb/bolt\"\n)\n\nfunc main() {\n\t// Open the my.db data file in your current directory.\n\t// It will be created if it doesn't exist.\n\tdb, err := bolt.Open(\"my.db\", 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\t...\n}\n```\n\nPlease note that Bolt obtains a file lock on the data file so multiple processes\ncannot open the same database at the same time. Opening an already open Bolt\ndatabase will cause it to hang until the other process closes it. To prevent\nan indefinite wait you can pass a timeout option to the `Open()` function:\n\n```go\ndb, err := bolt.Open(\"my.db\", 0600, \u0026bolt.Options{Timeout: 1 * time.Second})\n```\n\n\n### Transactions\n\nBolt allows only one read-write transaction at a time but allows as many\nread-only transactions as you want at a time. Each transaction has a consistent\nview of the data as it existed when the transaction started.\n\nIndividual transactions and all objects created from them (e.g. buckets, keys)\nare not thread safe. To work with data in multiple goroutines you must start\na transaction for each one or use locking to ensure only one goroutine accesses\na transaction at a time. Creating transaction from the `DB` is thread safe.\n\nRead-only transactions and read-write transactions should not depend on one\nanother and generally shouldn't be opened simultaneously in the same goroutine.\nThis can cause a deadlock as the read-write transaction needs to periodically\nre-map the data file but it cannot do so while a read-only transaction is open.\n\n\n#### Read-write transactions\n\nTo start a read-write transaction, you can use the `DB.Update()` function:\n\n```go\nerr := db.Update(func(tx *bolt.Tx) error {\n\t...\n\treturn nil\n})\n```\n\nInside the closure, you have a consistent view of the database. You commit the\ntransaction by returning `nil` at the end. You can also rollback the transaction\nat any point by returning an error. All database operations are allowed inside\na read-write transaction.\n\nAlways check the return error as it will report any disk failures that can cause\nyour transaction to not complete. If you return an error within your closure\nit will be passed through.\n\n\n#### Read-only transactions\n\nTo start a read-only transaction, you can use the `DB.View()` function:\n\n```go\nerr := db.View(func(tx *bolt.Tx) error {\n\t...\n\treturn nil\n})\n```\n\nYou also get a consistent view of the database within this closure, however,\nno mutating operations are allowed within a read-only transaction. You can only\nretrieve buckets, retrieve values, and copy the database within a read-only\ntransaction.\n\n\n#### Batch read-write transactions\n\nEach `DB.Update()` waits for disk to commit the writes. This overhead\ncan be minimized by combining multiple updates with the `DB.Batch()`\nfunction:\n\n```go\nerr := db.Batch(func(tx *bolt.Tx) error {\n\t...\n\treturn nil\n})\n```\n\nConcurrent Batch calls are opportunistically combined into larger\ntransactions. Batch is only useful when there are multiple goroutines\ncalling it.\n\nThe trade-off is that `Batch` can call the given\nfunction multiple times, if parts of the transaction fail. The\nfunction must be idempotent and side effects must take effect only\nafter a successful return from `DB.Batch()`.\n\nFor example: don't display messages from inside the function, instead\nset variables in the enclosing scope:\n\n```go\nvar id uint64\nerr := db.Batch(func(tx *bolt.Tx) error {\n\t// Find last key in bucket, decode as bigendian uint64, increment\n\t// by one, encode back to []byte, and add new key.\n\t...\n\tid = newValue\n\treturn nil\n})\nif err != nil {\n\treturn ...\n}\nfmt.Println(\"Allocated ID %d\", id)\n```\n\n\n#### Managing transactions manually\n\nThe `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`\nfunction. These helper functions will start the transaction, execute a function,\nand then safely close your transaction if an error is returned. This is the\nrecommended way to use Bolt transactions.\n\nHowever, sometimes you may want to manually start and end your transactions.\nYou can use the `DB.Begin()` function directly but **please** be sure to close\nthe transaction.\n\n```go\n// Start a writable transaction.\ntx, err := db.Begin(true)\nif err != nil {\n    return err\n}\ndefer tx.Rollback()\n\n// Use the transaction...\n_, err := tx.CreateBucket([]byte(\"MyBucket\"))\nif err != nil {\n    return err\n}\n\n// Commit the transaction and check for error.\nif err := tx.Commit(); err != nil {\n    return err\n}\n```\n\nThe first argument to `DB.Begin()` is a boolean stating if the transaction\nshould be writable.\n\n\n### Using buckets\n\nBuckets are collections of key/value pairs within the database. All keys in a\nbucket must be unique. You can create a bucket using the `DB.CreateBucket()`\nfunction:\n\n```go\ndb.Update(func(tx *bolt.Tx) error {\n\tb, err := tx.CreateBucket([]byte(\"MyBucket\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"create bucket: %s\", err)\n\t}\n\treturn nil\n})\n```\n\nYou can also create a bucket only if it doesn't exist by using the\n`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this\nfunction for all your top-level buckets after you open your database so you can\nguarantee that they exist for future transactions.\n\nTo delete a bucket, simply call the `Tx.DeleteBucket()` function.\n\n\n### Using key/value pairs\n\nTo save a key/value pair to a bucket, use the `Bucket.Put()` function:\n\n```go\ndb.Update(func(tx *bolt.Tx) error {\n\tb := tx.Bucket([]byte(\"MyBucket\"))\n\terr := b.Put([]byte(\"answer\"), []byte(\"42\"))\n\treturn err\n})\n```\n\nThis will set the value of the `\"answer\"` key to `\"42\"` in the `MyBucket`\nbucket. To retrieve this value, we can use the `Bucket.Get()` function:\n\n```go\ndb.View(func(tx *bolt.Tx) error {\n\tb := tx.Bucket([]byte(\"MyBucket\"))\n\tv := b.Get([]byte(\"answer\"))\n\tfmt.Printf(\"The answer is: %s\\n\", v)\n\treturn nil\n})\n```\n\nThe `Get()` function does not return an error because its operation is\nguaranteed to work (unless there is some kind of system failure). If the key\nexists then it will return its byte slice value. If it doesn't exist then it\nwill return `nil`. It's important to note that you can have a zero-length value\nset to a key which is different than the key not existing.\n\nUse the `Bucket.Delete()` function to delete a key from the bucket.\n\nPlease note that values returned from `Get()` are only valid while the\ntransaction is open. If you need to use a value outside of the transaction\nthen you must use `copy()` to copy it to another byte slice.\n\n\n### Autoincrementing integer for the bucket\nBy using the `NextSequence()` function, you can let Bolt determine a sequence\nwhich can be used as the unique identifier for your key/value pairs. See the\nexample below.\n\n```go\n// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.\nfunc (s *Store) CreateUser(u *User) error {\n    return s.db.Update(func(tx *bolt.Tx) error {\n        // Retrieve the users bucket.\n        // This should be created when the DB is first opened.\n        b := tx.Bucket([]byte(\"users\"))\n\n        // Generate ID for the user.\n        // This returns an error only if the Tx is closed or not writeable.\n        // That can't happen in an Update() call so I ignore the error check.\n        id, _ := b.NextSequence()\n        u.ID = int(id)\n\n        // Marshal user data into bytes.\n        buf, err := json.Marshal(u)\n        if err != nil {\n            return err\n        }\n\n        // Persist bytes to users bucket.\n        return b.Put(itob(u.ID), buf)\n    })\n}\n\n// itob returns an 8-byte big endian representation of v.\nfunc itob(v int) []byte {\n    b := make([]byte, 8)\n    binary.BigEndian.PutUint64(b, uint64(v))\n    return b\n}\n\ntype User struct {\n    ID int\n    ...\n}\n```\n\n### Iterating over keys\n\nBolt stores its keys in byte-sorted order within a bucket. This makes sequential\niteration over these keys extremely fast. To iterate over keys we'll use a\n`Cursor`:\n\n```go\ndb.View(func(tx *bolt.Tx) error {\n\t// Assume bucket exists and has keys\n\tb := tx.Bucket([]byte(\"MyBucket\"))\n\n\tc := b.Cursor()\n\n\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\tfmt.Printf(\"key=%s, value=%s\\n\", k, v)\n\t}\n\n\treturn nil\n})\n```\n\nThe cursor allows you to move to a specific point in the list of keys and move\nforward or backward through the keys one at a time.\n\nThe following functions are available on the cursor:\n\n```\nFirst()  Move to the first key.\nLast()   Move to the last key.\nSeek()   Move to a specific key.\nNext()   Move to the next key.\nPrev()   Move to the previous key.\n```\n\nEach of those functions has a return signature of `(key []byte, value []byte)`.\nWhen you have iterated to the end of the cursor then `Next()` will return a\n`nil` key.  You must seek to a position using `First()`, `Last()`, or `Seek()`\nbefore calling `Next()` or `Prev()`. If you do not seek to a position then\nthese functions will return a `nil` key.\n\nDuring iteration, if the key is non-`nil` but the value is `nil`, that means\nthe key refers to a bucket rather than a value.  Use `Bucket.Bucket()` to\naccess the sub-bucket.\n\n\n#### Prefix scans\n\nTo iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`:\n\n```go\ndb.View(func(tx *bolt.Tx) error {\n\t// Assume bucket exists and has keys\n\tc := tx.Bucket([]byte(\"MyBucket\")).Cursor()\n\n\tprefix := []byte(\"1234\")\n\tfor k, v := c.Seek(prefix); k != nil \u0026\u0026 bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\tfmt.Printf(\"key=%s, value=%s\\n\", k, v)\n\t}\n\n\treturn nil\n})\n```\n\n#### Range scans\n\nAnother common use case is scanning over a range such as a time range. If you\nuse a sortable time encoding such as RFC3339 then you can query a specific\ndate range like this:\n\n```go\ndb.View(func(tx *bolt.Tx) error {\n\t// Assume our events bucket exists and has RFC3339 encoded time keys.\n\tc := tx.Bucket([]byte(\"Events\")).Cursor()\n\n\t// Our time range spans the 90's decade.\n\tmin := []byte(\"1990-01-01T00:00:00Z\")\n\tmax := []byte(\"2000-01-01T00:00:00Z\")\n\n\t// Iterate over the 90's.\n\tfor k, v := c.Seek(min); k != nil \u0026\u0026 bytes.Compare(k, max) \u003c= 0; k, v = c.Next() {\n\t\tfmt.Printf(\"%s: %s\\n\", k, v)\n\t}\n\n\treturn nil\n})\n```\n\nNote that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.\n\n\n#### ForEach()\n\nYou can also use the function `ForEach()` if you know you'll be iterating over\nall the keys in a bucket:\n\n```go\ndb.View(func(tx *bolt.Tx) error {\n\t// Assume bucket exists and has keys\n\tb := tx.Bucket([]byte(\"MyBucket\"))\n\n\tb.ForEach(func(k, v []byte) error {\n\t\tfmt.Printf(\"key=%s, value=%s\\n\", k, v)\n\t\treturn nil\n\t})\n\treturn nil\n})\n```\n\nPlease note that keys and values in `ForEach()` are only valid while\nthe transaction is open. If you need to use a key or value outside of\nthe transaction, you must use `copy()` to copy it to another byte\nslice.\n\n### Nested buckets\n\nYou can also store a bucket in a key to create nested buckets. The API is the\nsame as the bucket management API on the `DB` object:\n\n```go\nfunc (*Bucket) CreateBucket(key []byte) (*Bucket, error)\nfunc (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)\nfunc (*Bucket) DeleteBucket(key []byte) error\n```\n\nSay you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.\n\n```go\n\n// createUser creates a new user in the given account.\nfunc createUser(accountID int, u *User) error {\n    // Start the transaction.\n    tx, err := db.Begin(true)\n    if err != nil {\n        return err\n    }\n    defer tx.Rollback()\n\n    // Retrieve the root bucket for the account.\n    // Assume this has already been created when the account was set up.\n    root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))\n\n    // Setup the users bucket.\n    bkt, err := root.CreateBucketIfNotExists([]byte(\"USERS\"))\n    if err != nil {\n        return err\n    }\n\n    // Generate an ID for the new user.\n    userID, err := bkt.NextSequence()\n    if err != nil {\n        return err\n    }\n    u.ID = userID\n\n    // Marshal and save the encoded user.\n    if buf, err := json.Marshal(u); err != nil {\n        return err\n    } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {\n        return err\n    }\n\n    // Commit the transaction.\n    if err := tx.Commit(); err != nil {\n        return err\n    }\n\n    return nil\n}\n\n```\n\n\n\n\n### Database backups\n\nBolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()`\nfunction to write a consistent view of the database to a writer. If you call\nthis from a read-only transaction, it will perform a hot backup and not block\nyour other database reads and writes.\n\nBy default, it will use a regular file handle which will utilize the operating\nsystem's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx)\ndocumentation for information about optimizing for larger-than-RAM datasets.\n\nOne common use case is to backup over HTTP so you can use tools like `cURL` to\ndo database backups:\n\n```go\nfunc BackupHandleFunc(w http.ResponseWriter, req *http.Request) {\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tw.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\t\tw.Header().Set(\"Content-Disposition\", `attachment; filename=\"my.db\"`)\n\t\tw.Header().Set(\"Content-Length\", strconv.Itoa(int(tx.Size())))\n\t\t_, err := tx.WriteTo(w)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n```\n\nThen you can backup using this command:\n\n```sh\n$ curl http://localhost/backup \u003e my.db\n```\n\nOr you can open your browser to `http://localhost/backup` and it will download\nautomatically.\n\nIf you want to backup to another file you can use the `Tx.CopyFile()` helper\nfunction.\n\n\n### Statistics\n\nThe database keeps a running count of many of the internal operations it\nperforms so you can better understand what's going on. By grabbing a snapshot\nof these stats at two points in time we can see what operations were performed\nin that time range.\n\nFor example, we could start a goroutine to log stats every 10 seconds:\n\n```go\ngo func() {\n\t// Grab the initial stats.\n\tprev := db.Stats()\n\n\tfor {\n\t\t// Wait for 10s.\n\t\ttime.Sleep(10 * time.Second)\n\n\t\t// Grab the current stats and diff them.\n\t\tstats := db.Stats()\n\t\tdiff := stats.Sub(\u0026prev)\n\n\t\t// Encode stats to JSON and print to STDERR.\n\t\tjson.NewEncoder(os.Stderr).Encode(diff)\n\n\t\t// Save stats for the next loop.\n\t\tprev = stats\n\t}\n}()\n```\n\nIt's also useful to pipe these stats to a service such as statsd for monitoring\nor to provide an HTTP endpoint that will perform a fixed-length sample.\n\n\n### Read-Only Mode\n\nSometimes it is useful to create a shared, read-only Bolt database. To this,\nset the `Options.ReadOnly` flag when opening your database. Read-only mode\nuses a shared lock to allow multiple processes to read from the database but\nit will block any processes from opening the database in read-write mode.\n\n```go\ndb, err := bolt.Open(\"my.db\", 0666, \u0026bolt.Options{ReadOnly: true})\nif err != nil {\n\tlog.Fatal(err)\n}\n```\n\n### Mobile Use (iOS/Android)\n\nBolt is able to run on mobile devices by leveraging the binding feature of the\n[gomobile](https://github.com/golang/mobile) tool. Create a struct that will\ncontain your database logic and a reference to a `*bolt.DB` with a initializing\nconstructor that takes in a filepath where the database file will be stored.\nNeither Android nor iOS require extra permissions or cleanup from using this method.\n\n```go\nfunc NewBoltDB(filepath string) *BoltDB {\n\tdb, err := bolt.Open(filepath+\"/demo.db\", 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn \u0026BoltDB{db}\n}\n\ntype BoltDB struct {\n\tdb *bolt.DB\n\t...\n}\n\nfunc (b *BoltDB) Path() string {\n\treturn b.db.Path()\n}\n\nfunc (b *BoltDB) Close() {\n\tb.db.Close()\n}\n```\n\nDatabase logic should be defined as methods on this wrapper struct.\n\nTo initialize this struct from the native language (both platforms now sync\ntheir local storage to the cloud. These snippets disable that functionality for the\ndatabase file):\n\n#### Android\n\n```java\nString path;\nif (android.os.Build.VERSION.SDK_INT \u003e=android.os.Build.VERSION_CODES.LOLLIPOP){\n    path = getNoBackupFilesDir().getAbsolutePath();\n} else{\n    path = getFilesDir().getAbsolutePath();\n}\nBoltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)\n```\n\n#### iOS\n\n```objc\n- (void)demo {\n    NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,\n                                                          NSUserDomainMask,\n                                                          YES) objectAtIndex:0];\n\tGoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);\n\t[self addSkipBackupAttributeToItemAtPath:demo.path];\n\t//Some DB Logic would go here\n\t[demo close];\n}\n\n- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString\n{\n    NSURL* URL= [NSURL fileURLWithPath: filePathString];\n    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);\n\n    NSError *error = nil;\n    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]\n                                  forKey: NSURLIsExcludedFromBackupKey error: \u0026error];\n    if(!success){\n        NSLog(@\"Error excluding %@ from backup %@\", [URL lastPathComponent], error);\n    }\n    return success;\n}\n\n```\n\n## Resources\n\nFor more information on getting started with Bolt, check out the following articles:\n\n* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch).\n* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville\n\n\n## Comparison with other databases\n\n### Postgres, MySQL, \u0026 other relational databases\n\nRelational databases structure data into rows and are only accessible through\nthe use of SQL. This approach provides flexibility in how you store and query\nyour data but also incurs overhead in parsing and planning SQL statements. Bolt\naccesses all data by a byte slice key. This makes Bolt fast to read and write\ndata by key but provides no built-in support for joining values together.\n\nMost relational databases (with the exception of SQLite) are standalone servers\nthat run separately from your application. This gives your systems\nflexibility to connect multiple application servers to a single database\nserver but also adds overhead in serializing and transporting data over the\nnetwork. Bolt runs as a library included in your application so all data access\nhas to go through your application's process. This brings data closer to your\napplication but limits multi-process access to the data.\n\n\n### LevelDB, RocksDB\n\nLevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that\nthey are libraries bundled into the application, however, their underlying\nstructure is a log-structured merge-tree (LSM tree). An LSM tree optimizes\nrandom writes by using a write ahead log and multi-tiered, sorted files called\nSSTables. Bolt uses a B+tree internally and only a single file. Both approaches\nhave trade-offs.\n\nIf you require a high random write throughput (\u003e10,000 w/sec) or you need to use\nspinning disks then LevelDB could be a good choice. If your application is\nread-heavy or does a lot of range scans then Bolt could be a good choice.\n\nOne other important consideration is that LevelDB does not have transactions.\nIt supports batch writing of key/values pairs and it supports read snapshots\nbut it will not give you the ability to do a compare-and-swap operation safely.\nBolt supports fully serializable ACID transactions.\n\n\n### LMDB\n\nBolt was originally a port of LMDB so it is architecturally similar. Both use\na B+tree, have ACID semantics with fully serializable transactions, and support\nlock-free MVCC using a single writer and multiple readers.\n\nThe two projects have somewhat diverged. LMDB heavily focuses on raw performance\nwhile Bolt has focused on simplicity and ease of use. For example, LMDB allows\nseveral unsafe actions such as direct writes for the sake of performance. Bolt\nopts to disallow actions which can leave the database in a corrupted state. The\nonly exception to this in Bolt is `DB.NoSync`.\n\nThere are also a few differences in API. LMDB requires a maximum mmap size when\nopening an `mdb_env` whereas Bolt will handle incremental mmap resizing\nautomatically. LMDB overloads the getter and setter functions with multiple\nflags whereas Bolt splits these specialized cases into their own functions.\n\n\n## Caveats \u0026 Limitations\n\nIt's important to pick the right tool for the job and Bolt is no exception.\nHere are a few things to note when evaluating and using Bolt:\n\n* Bolt is good for read intensive workloads. Sequential write performance is\n  also fast but random writes can be slow. You can use `DB.Batch()` or add a\n  write-ahead log to help mitigate this issue.\n\n* Bolt uses a B+tree internally so there can be a lot of random page access.\n  SSDs provide a significant performance boost over spinning disks.\n\n* Try to avoid long running read transactions. Bolt uses copy-on-write so\n  old pages cannot be reclaimed while an old transaction is using them.\n\n* Byte slices returned from Bolt are only valid during a transaction. Once the\n  transaction has been committed or rolled back then the memory they point to\n  can be reused by a new page or can be unmapped from virtual memory and you'll\n  see an `unexpected fault address` panic when accessing it.\n\n* Bolt uses an exclusive write lock on the database file so it cannot be\n  shared by multiple processes.\n\n* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for\n  buckets that have random inserts will cause your database to have very poor\n  page utilization.\n\n* Use larger buckets in general. Smaller buckets causes poor page utilization\n  once they become larger than the page size (typically 4KB).\n\n* Bulk loading a lot of random writes into a new bucket can be slow as the\n  page will not split until the transaction is committed. Randomly inserting\n  more than 100,000 key/value pairs into a single new bucket in a single\n  transaction is not advised.\n\n* Bolt uses a memory-mapped file so the underlying operating system handles the\n  caching of the data. Typically, the OS will cache as much of the file as it\n  can in memory and will release memory as needed to other processes. This means\n  that Bolt can show very high memory usage when working with large databases.\n  However, this is expected and the OS will release memory as needed. Bolt can\n  handle databases much larger than the available physical RAM, provided its\n  memory-map fits in the process virtual address space. It may be problematic\n  on 32-bits systems.\n\n* The data structures in the Bolt database are memory mapped so the data file\n  will be endian specific. This means that you cannot copy a Bolt file from a\n  little endian machine to a big endian machine and have it work. For most\n  users this is not a concern since most modern CPUs are little endian.\n\n* Because of the way pages are laid out on disk, Bolt cannot truncate data files\n  and return free pages back to the disk. Instead, Bolt maintains a free list\n  of unused pages within its data file. These free pages can be reused by later\n  transactions. This works well for many use cases as databases generally tend\n  to grow. However, it's important to note that deleting large chunks of data\n  will not allow you to reclaim that space on disk.\n\n  For more information on page allocation, [see this comment][page-allocation].\n\n[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638\n\n\n## Reading the Source\n\nBolt is a relatively small code base (\u003c3KLOC) for an embedded, serializable,\ntransactional key/value database so it can be a good starting point for people\ninterested in how databases work.\n\nThe best places to start are the main entry points into Bolt:\n\n- `Open()` - Initializes the reference to the database. It's responsible for\n  creating the database if it doesn't exist, obtaining an exclusive lock on the\n  file, reading the meta pages, \u0026 memory-mapping the file.\n\n- `DB.Begin()` - Starts a read-only or read-write transaction depending on the\n  value of the `writable` argument. This requires briefly obtaining the \"meta\"\n  lock to keep track of open transactions. Only one read-write transaction can\n  exist at a time so the \"rwlock\" is acquired during the life of a read-write\n  transaction.\n\n- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the\n  arguments, a cursor is used to traverse the B+tree to the page and position\n  where they key \u0026 value will be written. Once the position is found, the bucket\n  materializes the underlying page and the page's parent pages into memory as\n  \"nodes\". These nodes are where mutations occur during read-write transactions.\n  These changes get flushed to disk during commit.\n\n- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor\n  to move to the page \u0026 position of a key/value pair. During a read-only\n  transaction, the key and value data is returned as a direct reference to the\n  underlying mmap file so there's no allocation overhead. For read-write\n  transactions, this data may reference the mmap file or one of the in-memory\n  node values.\n\n- `Cursor` - This object is simply for traversing the B+tree of on-disk pages\n  or in-memory nodes. It can seek to a specific key, move to the first or last\n  value, or it can move forward or backward. The cursor handles the movement up\n  and down the B+tree transparently to the end user.\n\n- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages\n  into pages to be written to disk. Writing to disk then occurs in two phases.\n  First, the dirty pages are written to disk and an `fsync()` occurs. Second, a\n  new meta page with an incremented transaction ID is written and another\n  `fsync()` occurs. This two phase write ensures that partially written data\n  pages are ignored in the event of a crash since the meta page pointing to them\n  is never written. Partially written meta pages are invalidated because they\n  are written with a checksum.\n\nIf you have additional notes that could be helpful for others, please submit\nthem via pull request.\n\n\n## Other Projects Using Bolt\n\nBelow is a list of public, open source projects that use Bolt:\n\n* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files.\n* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard.\n* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside.\n* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.\n* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics.\n* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects.\n* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday.\n* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations.\n* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite.\n* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka \"Git meets Bitcoin\".\n* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka.\n* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed.\n* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt.\n* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site.\n* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage.\n* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters.\n* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend.\n* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.\n* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.\n* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read.\n* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics.\n* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data.\n* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash \u0026 Prometheus service monitoring system.\n* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.\n* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.\n* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \\*NIX operating systems.\n* [stow](https://github.com/djherbis/stow) -  a persistence manager for objects\n  backed by boltdb.\n* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining\n  simple tx and key scans.\n* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets.\n* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service\n* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service.\n* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners.\n* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.\n* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB.\n* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB.\n* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings.\n* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.\n* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files.\n* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.\n* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.\n* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains\n* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal.\n* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet.\n* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency.\n* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - \u003e test -\u003e release) tool, with no external dependencies\n* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB\n* [Ponzu CMS](https://ponzu-cms.org) - Headless CMS + automatic JSON API with auto-HTTPS, HTTP/2 Server Push, and flexible server framework.\n\nIf you are using Bolt in a project please send a pull request to add it to the list.\n","funding_links":[],"categories":["Database","HarmonyOS","Go","Misc","Go-lang","Key-value Data Model","\u003cspan id=\"数据库-database\"\u003e数据库 Database\u003c/span\u003e","go","數據庫","数据库","Key-Value"],"sub_categories":["Advanced Console UIs","Windows Manager","Middlewares","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e","高級控制台界面","高级控制台界面"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fboltdb%2Fbolt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fboltdb%2Fbolt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fboltdb%2Fbolt/lists"}