all repos

rss-tools @ a5ac52722b131734c74504b6e6f4d9900536cac7

get rss feed from sources that(i need and) dont provide one

rss-tools/vendor/go.etcd.io/bbolt/README.md (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
we're vendoring now, 7 days ago
1
bbolt
2
=====
3
4
[![Go Report Card](https://goreportcard.com/badge/go.etcd.io/bbolt?style=flat-square)](https://goreportcard.com/report/go.etcd.io/bbolt)
5
[![Go Reference](https://pkg.go.dev/badge/go.etcd.io/bbolt.svg)](https://pkg.go.dev/go.etcd.io/bbolt)
6
[![Releases](https://img.shields.io/github/release/etcd-io/bbolt/all.svg?style=flat-square)](https://github.com/etcd-io/bbolt/releases)
7
[![LICENSE](https://img.shields.io/github/license/etcd-io/bbolt.svg?style=flat-square)](https://github.com/etcd-io/bbolt/blob/master/LICENSE)
8
9
bbolt is a fork of [Ben Johnson's][gh_ben] [Bolt][bolt] key/value
10
store. The purpose of this fork is to provide the Go community with an active
11
maintenance and development target for Bolt; the goal is improved reliability
12
and stability. bbolt includes bug fixes, performance enhancements, and features
13
not found in Bolt while preserving backwards compatibility with the Bolt API.
14
15
Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas]
16
[LMDB project][lmdb]. The goal of the project is to provide a simple,
17
fast, and reliable database for projects that don't require a full database
18
server such as Postgres or MySQL.
19
20
Since Bolt is meant to be used as such a low-level piece of functionality,
21
simplicity is key. The API will be small and only focus on getting values
22
and setting values. That's it.
23
24
[gh_ben]: https://github.com/benbjohnson
25
[bolt]: https://github.com/boltdb/bolt
26
[hyc_symas]: https://twitter.com/hyc_symas
27
[lmdb]: https://www.symas.com/symas-embedded-database-lmdb
28
29
## Project Status
30
31
Bolt is stable, the API is fixed, and the file format is fixed. Full unit
32
test coverage and randomized black box testing are used to ensure database
33
consistency and thread safety. Bolt is currently used in high-load production
34
environments serving databases as large as 1TB. Many companies such as
35
Shopify and Heroku use Bolt-backed services every day.
36
37
## Project versioning
38
39
bbolt uses [semantic versioning](http://semver.org).
40
API should not change between patch and minor releases.
41
New minor versions may add additional features to the API.
42
43
## Table of Contents
44
45
  - [Getting Started](#getting-started)
46
    - [Installing](#installing)
47
    - [Opening a database](#opening-a-database)
48
    - [Transactions](#transactions)
49
      - [Read-write transactions](#read-write-transactions)
50
      - [Read-only transactions](#read-only-transactions)
51
      - [Batch read-write transactions](#batch-read-write-transactions)
52
      - [Managing transactions manually](#managing-transactions-manually)
53
    - [Using buckets](#using-buckets)
54
    - [Using key/value pairs](#using-keyvalue-pairs)
55
    - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket)
56
    - [Iterating over keys](#iterating-over-keys)
57
      - [Prefix scans](#prefix-scans)
58
      - [Range scans](#range-scans)
59
      - [ForEach()](#foreach)
60
    - [Nested buckets](#nested-buckets)
61
    - [Database backups](#database-backups)
62
    - [Statistics](#statistics)
63
    - [Read-Only Mode](#read-only-mode)
64
    - [Mobile Use (iOS/Android)](#mobile-use-iosandroid)
65
  - [Resources](#resources)
66
  - [Comparison with other databases](#comparison-with-other-databases)
67
    - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases)
68
    - [LevelDB, RocksDB](#leveldb-rocksdb)
69
    - [LMDB](#lmdb)
70
  - [Caveats & Limitations](#caveats--limitations)
71
  - [Reading the Source](#reading-the-source)
72
  - [Known Issues](#known-issues)
73
  - [Other Projects Using Bolt](#other-projects-using-bolt)
74
75
## Getting Started
76
77
### Installing
78
79
To start using `bbolt`, install Go and run `go get`:
80
```sh
81
$ go get go.etcd.io/bbolt@latest
82
```
83
84
This will retrieve the library and update your `go.mod` and `go.sum` files.
85
86
To run the command line utility, execute:
87
```sh
88
$ go run go.etcd.io/bbolt/cmd/bbolt@latest
89
```
90
91
Run `go install` to install the `bbolt` command line utility into
92
your `$GOBIN` path, which defaults to `$GOPATH/bin` or `$HOME/go/bin` if the
93
`GOPATH` environment variable is not set.
94
```sh
95
$ go install go.etcd.io/bbolt/cmd/bbolt@latest
96
```
97
98
### Importing bbolt
99
100
To use bbolt as an embedded key-value store, import as:
101
102
```go
103
import bolt "go.etcd.io/bbolt"
104
105
db, err := bolt.Open(path, 0600, nil)
106
if err != nil {
107
  return err
108
}
109
defer db.Close()
110
```
111
112
113
### Opening a database
114
115
The top-level object in Bolt is a `DB`. It is represented as a single file on
116
your disk and represents a consistent snapshot of your data.
117
118
To open your database, simply use the `bolt.Open()` function:
119
120
```go
121
package main
122
123
import (
124
	"log"
125
126
	bolt "go.etcd.io/bbolt"
127
)
128
129
func main() {
130
	// Open the my.db data file in your current directory.
131
	// It will be created if it doesn't exist.
132
	db, err := bolt.Open("my.db", 0600, nil)
133
	if err != nil {
134
		log.Fatal(err)
135
	}
136
	defer db.Close()
137
138
	...
139
}
140
```
141
142
Please note that Bolt obtains a file lock on the data file so multiple processes
143
cannot open the same database at the same time. Opening an already open Bolt
144
database will cause it to hang until the other process closes it. To prevent
145
an indefinite wait you can pass a timeout option to the `Open()` function:
146
147
```go
148
db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
149
```
150
151
152
### Transactions
153
154
Bolt allows only one read-write transaction at a time but allows as many
155
read-only transactions as you want at a time. Each transaction has a consistent
156
view of the data as it existed when the transaction started.
157
158
Individual transactions and all objects created from them (e.g. buckets, keys)
159
are not thread safe. To work with data in multiple goroutines you must start
160
a transaction for each one or use locking to ensure only one goroutine accesses
161
a transaction at a time. Creating transaction from the `DB` is thread safe.
162
163
Transactions should not depend on one another and generally shouldn't be opened
164
simultaneously in the same goroutine. This can cause a deadlock as the read-write
165
transaction needs to periodically re-map the data file but it cannot do so while
166
any read-only transaction is open. Even a nested read-only transaction can cause
167
a deadlock, as the child transaction can block the parent transaction from releasing
168
its resources.
169
170
#### Read-write transactions
171
172
To start a read-write transaction, you can use the `DB.Update()` function:
173
174
```go
175
err := db.Update(func(tx *bolt.Tx) error {
176
	...
177
	return nil
178
})
179
```
180
181
Inside the closure, you have a consistent view of the database. You commit the
182
transaction by returning `nil` at the end. You can also rollback the transaction
183
at any point by returning an error. All database operations are allowed inside
184
a read-write transaction.
185
186
Always check the return error as it will report any disk failures that can cause
187
your transaction to not complete. If you return an error within your closure
188
it will be passed through.
189
190
191
#### Read-only transactions
192
193
To start a read-only transaction, you can use the `DB.View()` function:
194
195
```go
196
err := db.View(func(tx *bolt.Tx) error {
197
	...
198
	return nil
199
})
200
```
201
202
You also get a consistent view of the database within this closure, however,
203
no mutating operations are allowed within a read-only transaction. You can only
204
retrieve buckets, retrieve values, and copy the database within a read-only
205
transaction.
206
207
208
#### Batch read-write transactions
209
210
Each `DB.Update()` waits for disk to commit the writes. This overhead
211
can be minimized by combining multiple updates with the `DB.Batch()`
212
function:
213
214
```go
215
err := db.Batch(func(tx *bolt.Tx) error {
216
	...
217
	return nil
218
})
219
```
220
221
Concurrent Batch calls are opportunistically combined into larger
222
transactions. Batch is only useful when there are multiple goroutines
223
calling it.
224
225
The trade-off is that `Batch` can call the given
226
function multiple times, if parts of the transaction fail. The
227
function must be idempotent and side effects must take effect only
228
after a successful return from `DB.Batch()`.
229
230
For example: don't display messages from inside the function, instead
231
set variables in the enclosing scope:
232
233
```go
234
var id uint64
235
err := db.Batch(func(tx *bolt.Tx) error {
236
	// Find last key in bucket, decode as bigendian uint64, increment
237
	// by one, encode back to []byte, and add new key.
238
	...
239
	id = newValue
240
	return nil
241
})
242
if err != nil {
243
	return ...
244
}
245
fmt.Println("Allocated ID %d", id)
246
```
247
248
249
#### Managing transactions manually
250
251
The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`
252
function. These helper functions will start the transaction, execute a function,
253
and then safely close your transaction if an error is returned. This is the
254
recommended way to use Bolt transactions.
255
256
However, sometimes you may want to manually start and end your transactions.
257
You can use the `DB.Begin()` function directly but **please** be sure to close
258
the transaction.
259
260
```go
261
// Start a writable transaction.
262
tx, err := db.Begin(true)
263
if err != nil {
264
    return err
265
}
266
defer tx.Rollback()
267
268
// Use the transaction...
269
_, err := tx.CreateBucket([]byte("MyBucket"))
270
if err != nil {
271
    return err
272
}
273
274
// Commit the transaction and check for error.
275
if err := tx.Commit(); err != nil {
276
    return err
277
}
278
```
279
280
The first argument to `DB.Begin()` is a boolean stating if the transaction
281
should be writable.
282
283
284
### Using buckets
285
286
Buckets are collections of key/value pairs within the database. All keys in a
287
bucket must be unique. You can create a bucket using the `Tx.CreateBucket()`
288
function:
289
290
```go
291
db.Update(func(tx *bolt.Tx) error {
292
	b, err := tx.CreateBucket([]byte("MyBucket"))
293
	if err != nil {
294
		return fmt.Errorf("create bucket: %s", err)
295
	}
296
	return nil
297
})
298
```
299
300
You can retrieve an existing bucket using the `Tx.Bucket()` function:
301
```go
302
db.Update(func(tx *bolt.Tx) error {
303
	b := tx.Bucket([]byte("MyBucket"))
304
	if b == nil {
305
		return errors.New("bucket does not exist")
306
	}
307
	return nil
308
})
309
```
310
311
You can also create a bucket only if it doesn't exist by using the
312
`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this
313
function for all your top-level buckets after you open your database so you can
314
guarantee that they exist for future transactions.
315
316
To delete a bucket, simply call the `Tx.DeleteBucket()` function.
317
318
You can also iterate over all existing top-level buckets with `Tx.ForEach()`:
319
320
```go
321
db.View(func(tx *bolt.Tx) error {
322
	tx.ForEach(func(name []byte, b *bolt.Bucket) error {
323
		fmt.Println(string(name))
324
		return nil
325
	})
326
	return nil
327
})
328
```
329
330
### Using key/value pairs
331
332
To save a key/value pair to a bucket, use the `Bucket.Put()` function:
333
334
```go
335
db.Update(func(tx *bolt.Tx) error {
336
	b := tx.Bucket([]byte("MyBucket"))
337
	err := b.Put([]byte("answer"), []byte("42"))
338
	return err
339
})
340
```
341
342
This will set the value of the `"answer"` key to `"42"` in the `MyBucket`
343
bucket. To retrieve this value, we can use the `Bucket.Get()` function:
344
345
```go
346
db.View(func(tx *bolt.Tx) error {
347
	b := tx.Bucket([]byte("MyBucket"))
348
	v := b.Get([]byte("answer"))
349
	fmt.Printf("The answer is: %s\n", v)
350
	return nil
351
})
352
```
353
354
The `Get()` function does not return an error because its operation is
355
guaranteed to work (unless there is some kind of system failure). If the key
356
exists then it will return its byte slice value. If it doesn't exist then it
357
will return `nil`. It's important to note that you can have a zero-length value
358
set to a key which is different than the key not existing.
359
360
Use the `Bucket.Delete()` function to delete a key from the bucket:
361
362
```go
363
db.Update(func (tx *bolt.Tx) error {
364
    b := tx.Bucket([]byte("MyBucket"))
365
    err := b.Delete([]byte("answer"))
366
    return err
367
})
368
```
369
370
This will delete the key `answers` from the bucket `MyBucket`.
371
372
Please note that values returned from `Get()` are only valid while the
373
transaction is open. If you need to use a value outside of the transaction
374
then you must use `copy()` to copy it to another byte slice.
375
376
377
### Autoincrementing integer for the bucket
378
By using the `NextSequence()` function, you can let Bolt determine a sequence
379
which can be used as the unique identifier for your key/value pairs. See the
380
example below.
381
382
```go
383
// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
384
func (s *Store) CreateUser(u *User) error {
385
    return s.db.Update(func(tx *bolt.Tx) error {
386
        // Retrieve the users bucket.
387
        // This should be created when the DB is first opened.
388
        b := tx.Bucket([]byte("users"))
389
390
        // Generate ID for the user.
391
        // This returns an error only if the Tx is closed or not writeable.
392
        // That can't happen in an Update() call so I ignore the error check.
393
        id, _ := b.NextSequence()
394
        u.ID = int(id)
395
396
        // Marshal user data into bytes.
397
        buf, err := json.Marshal(u)
398
        if err != nil {
399
            return err
400
        }
401
402
        // Persist bytes to users bucket.
403
        return b.Put(itob(u.ID), buf)
404
    })
405
}
406
407
// itob returns an 8-byte big endian representation of v.
408
func itob(v int) []byte {
409
    b := make([]byte, 8)
410
    binary.BigEndian.PutUint64(b, uint64(v))
411
    return b
412
}
413
414
type User struct {
415
    ID int
416
    ...
417
}
418
```
419
420
### Iterating over keys
421
422
Bolt stores its keys in byte-sorted order within a bucket. This makes sequential
423
iteration over these keys extremely fast. To iterate over keys we'll use a
424
`Cursor`:
425
426
```go
427
db.View(func(tx *bolt.Tx) error {
428
	// Assume bucket exists and has keys
429
	b := tx.Bucket([]byte("MyBucket"))
430
431
	c := b.Cursor()
432
433
	for k, v := c.First(); k != nil; k, v = c.Next() {
434
		fmt.Printf("key=%s, value=%s\n", k, v)
435
	}
436
437
	return nil
438
})
439
```
440
441
The cursor allows you to move to a specific point in the list of keys and move
442
forward or backward through the keys one at a time.
443
444
The following functions are available on the cursor:
445
446
```
447
First()  Move to the first key.
448
Last()   Move to the last key.
449
Seek()   Move to a specific key.
450
Next()   Move to the next key.
451
Prev()   Move to the previous key.
452
```
453
454
Each of those functions has a return signature of `(key []byte, value []byte)`.
455
You must seek to a position using `First()`, `Last()`, or `Seek()` before calling
456
`Next()` or `Prev()`. If you do not seek to a position then these functions will
457
return a `nil` key.
458
459
When you have iterated to the end of the cursor, then `Next()` will return a
460
`nil` key and the cursor still points to the last element if present. When you
461
have iterated to the beginning of the cursor, then `Prev()` will return a `nil`
462
key and the cursor still points to the first element if present.
463
464
If you remove key/value pairs during iteration, the cursor may automatically
465
move to the next position if present in current node each time removing a key.
466
When you call `c.Next()` after removing a key, it may skip one key/value pair.
467
Refer to [pull/611](https://github.com/etcd-io/bbolt/pull/611) to get more detailed info.
468
469
During iteration, if the key is non-`nil` but the value is `nil`, that means
470
the key refers to a bucket rather than a value.  Use `Bucket.Bucket()` to
471
access the sub-bucket.
472
473
474
#### Prefix scans
475
476
To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`:
477
478
```go
479
db.View(func(tx *bolt.Tx) error {
480
	// Assume bucket exists and has keys
481
	c := tx.Bucket([]byte("MyBucket")).Cursor()
482
483
	prefix := []byte("1234")
484
	for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
485
		fmt.Printf("key=%s, value=%s\n", k, v)
486
	}
487
488
	return nil
489
})
490
```
491
492
#### Range scans
493
494
Another common use case is scanning over a range such as a time range. If you
495
use a sortable time encoding such as RFC3339 then you can query a specific
496
date range like this:
497
498
```go
499
db.View(func(tx *bolt.Tx) error {
500
	// Assume our events bucket exists and has RFC3339 encoded time keys.
501
	c := tx.Bucket([]byte("Events")).Cursor()
502
503
	// Our time range spans the 90's decade.
504
	min := []byte("1990-01-01T00:00:00Z")
505
	max := []byte("2000-01-01T00:00:00Z")
506
507
	// Iterate over the 90's.
508
	for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
509
		fmt.Printf("%s: %s\n", k, v)
510
	}
511
512
	return nil
513
})
514
```
515
516
Note 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.
517
518
519
#### ForEach()
520
521
You can also use the function `ForEach()` if you know you'll be iterating over
522
all the keys in a bucket:
523
524
```go
525
db.View(func(tx *bolt.Tx) error {
526
	// Assume bucket exists and has keys
527
	b := tx.Bucket([]byte("MyBucket"))
528
529
	b.ForEach(func(k, v []byte) error {
530
		fmt.Printf("key=%s, value=%s\n", k, v)
531
		return nil
532
	})
533
	return nil
534
})
535
```
536
537
Please note that keys and values in `ForEach()` are only valid while
538
the transaction is open. If you need to use a key or value outside of
539
the transaction, you must use `copy()` to copy it to another byte
540
slice.
541
542
### Nested buckets
543
544
You can also store a bucket in a key to create nested buckets. The API is the
545
same as the bucket management API on the `DB` object:
546
547
```go
548
func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
549
func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
550
func (*Bucket) DeleteBucket(key []byte) error
551
```
552
553
Say 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.
554
555
```go
556
557
// createUser creates a new user in the given account.
558
func createUser(accountID int, u *User) error {
559
    // Start the transaction.
560
    tx, err := db.Begin(true)
561
    if err != nil {
562
        return err
563
    }
564
    defer tx.Rollback()
565
566
    // Retrieve the root bucket for the account.
567
    // Assume this has already been created when the account was set up.
568
    root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))
569
570
    // Setup the users bucket.
571
    bkt, err := root.CreateBucketIfNotExists([]byte("USERS"))
572
    if err != nil {
573
        return err
574
    }
575
576
    // Generate an ID for the new user.
577
    userID, err := bkt.NextSequence()
578
    if err != nil {
579
        return err
580
    }
581
    u.ID = userID
582
583
    // Marshal and save the encoded user.
584
    if buf, err := json.Marshal(u); err != nil {
585
        return err
586
    } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {
587
        return err
588
    }
589
590
    // Commit the transaction.
591
    if err := tx.Commit(); err != nil {
592
        return err
593
    }
594
595
    return nil
596
}
597
598
```
599
600
601
602
603
### Database backups
604
605
Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()`
606
function to write a consistent view of the database to a writer. If you call
607
this from a read-only transaction, it will perform a hot backup and not block
608
your other database reads and writes.
609
610
By default, it will use a regular file handle which will utilize the operating
611
system's page cache. See the [`Tx`](https://godoc.org/go.etcd.io/bbolt#Tx)
612
documentation for information about optimizing for larger-than-RAM datasets.
613
614
One common use case is to backup over HTTP so you can use tools like `cURL` to
615
do database backups:
616
617
```go
618
func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
619
	err := db.View(func(tx *bolt.Tx) error {
620
		w.Header().Set("Content-Type", "application/octet-stream")
621
		w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
622
		w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
623
		_, err := tx.WriteTo(w)
624
		return err
625
	})
626
	if err != nil {
627
		http.Error(w, err.Error(), http.StatusInternalServerError)
628
	}
629
}
630
```
631
632
Then you can backup using this command:
633
634
```sh
635
$ curl http://localhost/backup > my.db
636
```
637
638
Or you can open your browser to `http://localhost/backup` and it will download
639
automatically.
640
641
If you want to backup to another file you can use the `Tx.CopyFile()` helper
642
function.
643
644
645
### Statistics
646
647
The database keeps a running count of many of the internal operations it
648
performs so you can better understand what's going on. By grabbing a snapshot
649
of these stats at two points in time we can see what operations were performed
650
in that time range.
651
652
For example, we could start a goroutine to log stats every 10 seconds:
653
654
```go
655
go func() {
656
	// Grab the initial stats.
657
	prev := db.Stats()
658
659
	for {
660
		// Wait for 10s.
661
		time.Sleep(10 * time.Second)
662
663
		// Grab the current stats and diff them.
664
		stats := db.Stats()
665
		diff := stats.Sub(&prev)
666
667
		// Encode stats to JSON and print to STDERR.
668
		json.NewEncoder(os.Stderr).Encode(diff)
669
670
		// Save stats for the next loop.
671
		prev = stats
672
	}
673
}()
674
```
675
676
It's also useful to pipe these stats to a service such as statsd for monitoring
677
or to provide an HTTP endpoint that will perform a fixed-length sample.
678
679
680
### Read-Only Mode
681
682
Sometimes it is useful to create a shared, read-only Bolt database. To this,
683
set the `Options.ReadOnly` flag when opening your database. Read-only mode
684
uses a shared lock to allow multiple processes to read from the database but
685
it will block any processes from opening the database in read-write mode.
686
687
```go
688
db, err := bolt.Open("my.db", 0600, &bolt.Options{ReadOnly: true})
689
if err != nil {
690
	log.Fatal(err)
691
}
692
```
693
694
### Mobile Use (iOS/Android)
695
696
Bolt is able to run on mobile devices by leveraging the binding feature of the
697
[gomobile](https://github.com/golang/mobile) tool. Create a struct that will
698
contain your database logic and a reference to a `*bolt.DB` with a initializing
699
constructor that takes in a filepath where the database file will be stored.
700
Neither Android nor iOS require extra permissions or cleanup from using this method.
701
702
```go
703
func NewBoltDB(filepath string) *BoltDB {
704
	db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
705
	if err != nil {
706
		log.Fatal(err)
707
	}
708
709
	return &BoltDB{db}
710
}
711
712
type BoltDB struct {
713
	db *bolt.DB
714
	...
715
}
716
717
func (b *BoltDB) Path() string {
718
	return b.db.Path()
719
}
720
721
func (b *BoltDB) Close() {
722
	b.db.Close()
723
}
724
```
725
726
Database logic should be defined as methods on this wrapper struct.
727
728
To initialize this struct from the native language (both platforms now sync
729
their local storage to the cloud. These snippets disable that functionality for the
730
database file):
731
732
#### Android
733
734
```java
735
String path;
736
if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
737
    path = getNoBackupFilesDir().getAbsolutePath();
738
} else{
739
    path = getFilesDir().getAbsolutePath();
740
}
741
Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)
742
```
743
744
#### iOS
745
746
```objc
747
- (void)demo {
748
    NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
749
                                                          NSUserDomainMask,
750
                                                          YES) objectAtIndex:0];
751
	GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
752
	[self addSkipBackupAttributeToItemAtPath:demo.path];
753
	//Some DB Logic would go here
754
	[demo close];
755
}
756
757
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
758
{
759
    NSURL* URL= [NSURL fileURLWithPath: filePathString];
760
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
761
762
    NSError *error = nil;
763
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
764
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];
765
    if(!success){
766
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
767
    }
768
    return success;
769
}
770
771
```
772
773
## Resources
774
775
For more information on getting started with Bolt, check out the following articles:
776
777
* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch).
778
* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville
779
780
781
## Comparison with other databases
782
783
### Postgres, MySQL, & other relational databases
784
785
Relational databases structure data into rows and are only accessible through
786
the use of SQL. This approach provides flexibility in how you store and query
787
your data but also incurs overhead in parsing and planning SQL statements. Bolt
788
accesses all data by a byte slice key. This makes Bolt fast to read and write
789
data by key but provides no built-in support for joining values together.
790
791
Most relational databases (with the exception of SQLite) are standalone servers
792
that run separately from your application. This gives your systems
793
flexibility to connect multiple application servers to a single database
794
server but also adds overhead in serializing and transporting data over the
795
network. Bolt runs as a library included in your application so all data access
796
has to go through your application's process. This brings data closer to your
797
application but limits multi-process access to the data.
798
799
800
### LevelDB, RocksDB
801
802
LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that
803
they are libraries bundled into the application, however, their underlying
804
structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes
805
random writes by using a write ahead log and multi-tiered, sorted files called
806
SSTables. Bolt uses a B+tree internally and only a single file. Both approaches
807
have trade-offs.
808
809
If you require a high random write throughput (>10,000 w/sec) or you need to use
810
spinning disks then LevelDB could be a good choice. If your application is
811
read-heavy or does a lot of range scans then Bolt could be a good choice.
812
813
One other important consideration is that LevelDB does not have transactions.
814
It supports batch writing of key/values pairs and it supports read snapshots
815
but it will not give you the ability to do a compare-and-swap operation safely.
816
Bolt supports fully serializable ACID transactions.
817
818
819
### LMDB
820
821
Bolt was originally a port of LMDB so it is architecturally similar. Both use
822
a B+tree, have ACID semantics with fully serializable transactions, and support
823
lock-free MVCC using a single writer and multiple readers.
824
825
The two projects have somewhat diverged. LMDB heavily focuses on raw performance
826
while Bolt has focused on simplicity and ease of use. For example, LMDB allows
827
several unsafe actions such as direct writes for the sake of performance. Bolt
828
opts to disallow actions which can leave the database in a corrupted state. The
829
only exception to this in Bolt is `DB.NoSync`.
830
831
There are also a few differences in API. LMDB requires a maximum mmap size when
832
opening an `mdb_env` whereas Bolt will handle incremental mmap resizing
833
automatically. LMDB overloads the getter and setter functions with multiple
834
flags whereas Bolt splits these specialized cases into their own functions.
835
836
837
## Caveats & Limitations
838
839
It's important to pick the right tool for the job and Bolt is no exception.
840
Here are a few things to note when evaluating and using Bolt:
841
842
* Bolt is good for read intensive workloads. Sequential write performance is
843
  also fast but random writes can be slow. You can use `DB.Batch()` or add a
844
  write-ahead log to help mitigate this issue.
845
846
* Bolt uses a B+tree internally so there can be a lot of random page access.
847
  SSDs provide a significant performance boost over spinning disks.
848
849
* Try to avoid long running read transactions. Bolt uses copy-on-write so
850
  old pages cannot be reclaimed while an old transaction is using them.
851
852
* Byte slices returned from Bolt are only valid during a transaction. Once the
853
  transaction has been committed or rolled back then the memory they point to
854
  can be reused by a new page or can be unmapped from virtual memory and you'll
855
  see an `unexpected fault address` panic when accessing it.
856
857
* Bolt uses an exclusive write lock on the database file so it cannot be
858
  shared by multiple processes.
859
860
* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for
861
  buckets that have random inserts will cause your database to have very poor
862
  page utilization.
863
864
* Use larger buckets in general. Smaller buckets causes poor page utilization
865
  once they become larger than the page size (typically 4KB).
866
867
* Bulk loading a lot of random writes into a new bucket can be slow as the
868
  page will not split until the transaction is committed. Randomly inserting
869
  more than 100,000 key/value pairs into a single new bucket in a single
870
  transaction is not advised.
871
872
* Bolt uses a memory-mapped file so the underlying operating system handles the
873
  caching of the data. Typically, the OS will cache as much of the file as it
874
  can in memory and will release memory as needed to other processes. This means
875
  that Bolt can show very high memory usage when working with large databases.
876
  However, this is expected and the OS will release memory as needed. Bolt can
877
  handle databases much larger than the available physical RAM, provided its
878
  memory-map fits in the process virtual address space. It may be problematic
879
  on 32-bits systems.
880
881
* The data structures in the Bolt database are memory mapped so the data file
882
  will be endian specific. This means that you cannot copy a Bolt file from a
883
  little endian machine to a big endian machine and have it work. For most
884
  users this is not a concern since most modern CPUs are little endian.
885
886
* Because of the way pages are laid out on disk, Bolt cannot truncate data files
887
  and return free pages back to the disk. Instead, Bolt maintains a free list
888
  of unused pages within its data file. These free pages can be reused by later
889
  transactions. This works well for many use cases as databases generally tend
890
  to grow. However, it's important to note that deleting large chunks of data
891
  will not allow you to reclaim that space on disk.
892
893
* Removing key/values pairs in a bucket during iteration on the bucket using
894
  cursor may not work properly. Each time when removing a key/value pair, the
895
  cursor may automatically move to the next position if present. When users
896
  call `c.Next()` after removing a key, it may skip one key/value pair.
897
  Refer to https://github.com/etcd-io/bbolt/pull/611 for more detailed info.
898
899
  For more information on page allocation, [see this comment][page-allocation].
900
901
[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638
902
903
904
## Reading the Source
905
906
Bolt is a relatively small code base (<5KLOC) for an embedded, serializable,
907
transactional key/value database so it can be a good starting point for people
908
interested in how databases work.
909
910
The best places to start are the main entry points into Bolt:
911
912
- `Open()` - Initializes the reference to the database. It's responsible for
913
  creating the database if it doesn't exist, obtaining an exclusive lock on the
914
  file, reading the meta pages, & memory-mapping the file.
915
916
- `DB.Begin()` - Starts a read-only or read-write transaction depending on the
917
  value of the `writable` argument. This requires briefly obtaining the "meta"
918
  lock to keep track of open transactions. Only one read-write transaction can
919
  exist at a time so the "rwlock" is acquired during the life of a read-write
920
  transaction.
921
922
- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the
923
  arguments, a cursor is used to traverse the B+tree to the page and position
924
  where the key & value will be written. Once the position is found, the bucket
925
  materializes the underlying page and the page's parent pages into memory as
926
  "nodes". These nodes are where mutations occur during read-write transactions.
927
  These changes get flushed to disk during commit.
928
929
- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor
930
  to move to the page & position of a key/value pair. During a read-only
931
  transaction, the key and value data is returned as a direct reference to the
932
  underlying mmap file so there's no allocation overhead. For read-write
933
  transactions, this data may reference the mmap file or one of the in-memory
934
  node values.
935
936
- `Cursor` - This object is simply for traversing the B+tree of on-disk pages
937
  or in-memory nodes. It can seek to a specific key, move to the first or last
938
  value, or it can move forward or backward. The cursor handles the movement up
939
  and down the B+tree transparently to the end user.
940
941
- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages
942
  into pages to be written to disk. Writing to disk then occurs in two phases.
943
  First, the dirty pages are written to disk and an `fsync()` occurs. Second, a
944
  new meta page with an incremented transaction ID is written and another
945
  `fsync()` occurs. This two phase write ensures that partially written data
946
  pages are ignored in the event of a crash since the meta page pointing to them
947
  is never written. Partially written meta pages are invalidated because they
948
  are written with a checksum.
949
950
If you have additional notes that could be helpful for others, please submit
951
them via pull request.
952
953
## Known Issues
954
955
- bbolt might run into data corruption issue on Linux when the feature
956
  [ext4: fast commit](https://lwn.net/Articles/842385/), which was introduced in
957
  linux kernel version v5.10, is enabled. The fixes to the issue were included in
958
  linux kernel version v5.17, please refer to links below,
959
960
  * [ext4: fast commit may miss tracking unwritten range during ftruncate](https://lore.kernel.org/linux-ext4/20211223032337.5198-3-yinxin.x@bytedance.com/)
961
  * [ext4: fast commit may not fallback for ineligible commit](https://lore.kernel.org/lkml/202201091544.W5HHEXAp-lkp@intel.com/T/#ma0768815e4b5f671e9e451d578256ef9a76fe30e)
962
  * [ext4 updates for 5.17](https://lore.kernel.org/lkml/YdyxjTFaLWif6BCM@mit.edu/)
963
964
  Please also refer to the discussion in https://github.com/etcd-io/bbolt/issues/562.
965
966
- Writing a value with a length of 0 will always result in reading back an empty `[]byte{}` value.
967
  Please refer to [issues/726#issuecomment-2061694802](https://github.com/etcd-io/bbolt/issues/726#issuecomment-2061694802).
968
969
## Other Projects Using Bolt
970
971
Below is a list of public, open source projects that use Bolt:
972
973
* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
974
* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside.
975
* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal.
976
* [boltcli](https://github.com/spacewander/boltcli) - the redis-cli for boltdb with Lua script support.
977
* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB
978
* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt.
979
* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
980
* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files.
981
* [BoltDB Viewer](https://github.com/zc310/rich_boltdb) - A BoltDB Viewer Can run on Windows、Linux、Android system.
982
* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
983
* [bstore](https://github.com/mjl-/bstore) - Database library storing Go values, with referential/unique/nonzero constraints, indices, automatic schema management with struct tags, and a query API.
984
* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet.
985
* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining
986
  simple tx and key scans.
987
* [Buildkit](https://github.com/moby/buildkit) - concurrent, cache-efficient, and Dockerfile-agnostic builder toolkit
988
* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend.
989
* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations.
990
* [🌰 Chestnut](https://github.com/jrapoport/chestnut) - Chestnut is encrypted storage for Go.
991
* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
992
* [Containerd](https://github.com/containerd/containerd) - An open and reliable container runtime
993
* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
994
* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency.
995
* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems.
996
* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka.
997
* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data.
998
* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service.
999
* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB.
1000
* [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.
1001
* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains
1002
* [gokv](https://github.com/philippgille/gokv) - Simple key-value store abstraction and implementations for Go (Redis, Consul, etcd, bbolt, BadgerDB, LevelDB, Memcached, DynamoDB, S3, PostgreSQL, MongoDB, CockroachDB and many more)
1003
* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
1004
* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics.
1005
* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters.
1006
* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed.
1007
* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies
1008
* [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.
1009
* [Key Value Access Language (KVAL)](https://github.com/kval-access-language) - A proposed grammar for key-value datastores offering a bbolt binding.
1010
* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage.
1011
* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
1012
* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
1013
* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite.
1014
* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files.
1015
* [NATS](https://github.com/nats-io/nats-streaming-server) - NATS Streaming uses bbolt for message and metadata storage.
1016
* [Portainer](https://github.com/portainer/portainer) - A lightweight service delivery platform for containerized applications that can be used to manage Docker, Swarm, Kubernetes and ACI environments.
1017
* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system.
1018
* [Rain](https://github.com/cenkalti/rain) - BitTorrent client and library.
1019
* [reef-pi](https://github.com/reef-pi/reef-pi) - reef-pi is an award winning, modular, DIY reef tank controller using easy to learn electronics based on a Raspberry Pi.
1020
* [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
1021
* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read.
1022
* [stow](https://github.com/djherbis/stow) -  a persistence manager for objects
1023
  backed by boltdb.
1024
* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB.
1025
* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings.
1026
* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics.
1027
* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects.
1028
* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
1029
* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.
1030
* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday.
1031
1032
If you are using Bolt in a project please send a pull request to add it to the list.