├── .gitignore ├── LICENSE ├── README.md └── cmd ├── boltdb ├── bolthold │ ├── lookups_test.go │ └── readme.md ├── increment │ └── main.go ├── insert │ └── main.go └── readme.md ├── experiments └── byteindex │ ├── byteindex.go │ ├── byteindex_test.go │ └── keylist.go ├── leveldb ├── increment │ └── level.go └── insert │ └── level.go └── pogreb-bench ├── badgerdb.go ├── bbolt.go ├── benchmark.go ├── bolt.go ├── bytesize.go ├── data ├── .DS_Store └── empty ├── engine.go ├── engine_test.go ├── goleveldb.go ├── main.go ├── pogreb.go └── tiedot.go /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Go Embeddable Store 2 | ============ 3 | 4 | Go is a compiled language with a number of high-performance data stores that can be compiled with Go into a single binary. These databases are called "in-process" or "embedded". 5 | 6 | By default, most apps slap MongoDB or MySQL/MariaDB into an application for storing state. Since we left the `.net/node/php/ruby/python` world we can have our database bundled right into our application. For smaller projects, which do not need a globally distributed / sharded database, this is a great devops win. 7 | 8 | Embedded databases are propbably not for you if: 9 | 10 | - building a serverless app (AWS lambda / Zeit Now) 11 | - dealing with >1 Million HTTP requests a day 12 | - have highly concurrent request patterns 13 | 14 | These benchmarks and tests are off for a variety of reasons including differing levels of durability/sync and feature-scope. I recommend people default to `bbolt` for a general store. 15 | 16 | # Embeddable Go Databases 17 | 18 | ### boltdb - https://github.com/boltdb/bolt 19 | 20 | Solid, well-tested, development is locked. Each transaction has a consistent view of the data as it existed when the transaction started. Slowest of the bunch. Largest file size. Slowest (due to consistent-data views). 21 | 22 | - [Blast](https://github.com/mosuka/blast) - full text search and indexing server cluster via [Raft](https://github.com/hashicorp/raft) 23 | - [Storm](https://github.com/asdine/storm) - ORM-ish layer for database access 24 | 25 | ### bbolt - https://github.com/etcd-io/bbolt 26 | 27 | Fork of boltdb to add new features. 28 | 29 | - [BoltHold](https://github.com/timshannon/bolthold/) - simple querying and indexing layer 30 | - [Storm](https://github.com/asdine/storm/) - query-builder, indexes, and struct storage 31 | - [Buckets](https://github.com/joyrexus/buckets) - simple access layer 32 | 33 | ### pogreb - https://github.com/akrylysov/pogreb 34 | 35 | Optimized store for random lookups. *No support for range/prefix scans*. Slow in this benchmark. [More...](https://artem.krylysov.com/blog/2018/03/24/pogreb-key-value-store/) 36 | 37 | ### goleveldb - https://github.com/syndtr/goleveldb 38 | 39 | Well tested. Smallest storage size. 40 | 41 | - [ledisdb](http://ledisdb.com/) - redis-like abstraction over it 42 | 43 | ### badgerdb - https://github.com/dgraph-io/badger 44 | 45 | Fastest engine for random lookups and inserts. 46 | 47 | - Graph engine [dgraph](https://github.com/dgraph-io/dgraph) built upon it. [More...](https://blog.dgraph.io/post/badger/) 48 | - [Cete document store](https://github.com/1lann/cete) 49 | 50 | ### keydb - https://github.com/robaho/keydb 51 | 52 | Not tested. 53 | 54 | # More Complex Engines 55 | 56 | ### tiedot - https://github.com/HouzuoGuo/tiedot/ 57 | 58 | Tiedot is a document store, it really can't be compared to these other databases correctly. Included only for loose reference. Super-fast write speeds. Huge storage requirements. 59 | 60 | # Non-Go Embeddable Databases (Cgo) 61 | 62 | - RocksDB 63 | - LMDB 64 | - hyperleveldb 65 | 66 | ### SQLite 67 | 68 | Not tested. Multiple versions exist, most wrap the C code. 69 | 70 | `database/sql` driver 71 | - https://github.com/mattn/go-sqlite3 72 | 73 | no `database/sql` driver 74 | - https://github.com/crawshaw/sqlite 75 | - https://github.com/bvinc/go-sqlite-lite 76 | 77 | 78 | Comparison between [bvinc/go-sqlite-lite & crawshaw/sqlite](https://www.reddit.com/r/golang/comments/96yd0t/gosqlitelite_a_new_light_weight_sqlite_package/e44eoym/). 79 | 80 | 81 | # Sample Results 82 | 83 | Number of keys: 5000 84 | Minimum key size: 32, maximum key size: 64 85 | Minimum value size: 128, maximum value size: 1024 86 | Concurrency: 3 87 | 88 | Running tiedot benchmark... 89 | Put: 0.022 sec, 226300 ops/sec 90 | Get: 0.001 sec, 3552460 ops/sec 91 | Put + Get time: 0.024 sec 92 | File size: 512.00MB 93 | 94 | Running pogreb benchmark... 95 | Put: 0.142 sec, 35293 ops/sec 96 | Get: 0.002 sec, 2489791 ops/sec 97 | Put + Get time: 0.144 sec 98 | File size: 4.25MB 99 | 100 | Running goleveldb benchmark... 101 | Put: 0.035 sec, 144902 ops/sec 102 | Get: 0.009 sec, 568586 ops/sec 103 | Put + Get time: 0.043 sec 104 | File size: 3.05MB 105 | 106 | Running bolt benchmark... 107 | Put: 15.868 sec, 315 ops/sec 108 | Get: 0.004 sec, 1136989 ops/sec 109 | Put + Get time: 15.873 sec 110 | File size: 8.00MB 111 | 112 | Running bbolt benchmark... 113 | Put: 14.710 sec, 339 ops/sec 114 | Get: 0.006 sec, 874240 ops/sec 115 | Put + Get time: 14.716 sec 116 | File size: 8.00MB 117 | 118 | 119 | ## Articles 120 | 121 | - https://tech.townsourced.com/post/boltdb-vs-badger/ 122 | - https://www.voltdb.com/blog/2015/04/01/foundationdbs-lesson-fast-key-value-store-not-enough/ 123 | - https://petewarden.com/2010/10/01/how-i-ended-up-using-s3-as-my-database/ 124 | - https://hackernoon.com/what-i-learnt-from-building-3-high-traffic-web-applications-on-an-embedded-key-value-store-68d47249774f 125 | - https://www.cockroachlabs.com/docs/stable/architecture/storage-layer.html 126 | - https://github.com/kval-access-language/kval-language-specification 127 | 128 | ## Indexing data 129 | 130 | - https://github.com/blevesearch/bleve ([Video](https://www.youtube.com/watch?v=OynPw4aOlV0)) 131 | - http://roaringbitmap.org/ 132 | - https://www.pilosa.com/docs/latest/data-model/ 133 | - https://github.com/Xeoncross/keyset 134 | 135 | ## Encoding/Decoding 136 | 137 | If inserting complex data types (structs, maps, slices...) into a key/value store you must encode/decode them first. 138 | 139 | 1. `protobuf` provides performance, correctness and interoperability. Requires you to generate protobuf files. 140 | 2. `gob` is the next fastest format with the smallest data size. More for streaming protocols where you don't want to have to have a pre-shared schema. Poor interoperability. 141 | 2. `json` the default. Reasonable performance. Highest interoperability. 142 | 3. `xml` is to be avoided. 143 | 144 | - https://github.com/alecthomas/go_serialization_benchmarks 145 | 146 | 147 | # Other benchmarks 148 | 149 | - [badgerdb, goleveldb, boltdb, bboltdb, buntdb, rocksdb, cznic/kv, map](https://github.com/smallnest/kvbench) 150 | - [badgerdb, goleveldb, boltdb benchmark](https://github.com/zchee/go-benchmarks/blob/master/db/db_bench_test.go) by zchee. 151 | - [badgerdb, goleveldb, boltdb, rocksdb benchmark](https://github.com/dgraph-io/badger-bench) by dgraph. (High-Quality) 152 | - [goleveldb, boltdb, pogreb write/put benchmark](https://gist.github.com/mattn/3990033f7bc8a57cd5b86edefb254332) by mattn. 153 | 154 | # Guides 155 | 156 | - [Expiring boltdb items](http://178.62.97.106/expiring-boltdb-items/) 157 | - [range and prefix scans in boltdb](https://bl.ocks.org/joyrexus/22c3ef0984ed957f54b9) 158 | - [map callbacks to range/prefix scans in Boltdb](https://github.com/joyrexus/buckets/blob/master/rangescan.go) 159 | - [building hash, set, and list using Boltdb](https://github.com/xyproto/simplebolt/blob/master/simplebolt.go) 160 | -------------------------------------------------------------------------------- /cmd/boltdb/bolthold/lookups_test.go: -------------------------------------------------------------------------------- 1 | package lookups 2 | 3 | import ( 4 | "math/rand" 5 | "os" 6 | "testing" 7 | "time" 8 | 9 | randomdata "github.com/Pallinder/go-randomdata" 10 | "github.com/timshannon/bolthold" 11 | "go.etcd.io/bbolt" 12 | ) 13 | 14 | type Employee struct { 15 | ID string `boltholdKey:"ID"` 16 | FirstName string 17 | LastName string 18 | Division string 19 | Bio string 20 | Age int 21 | Created time.Time 22 | } 23 | 24 | func newEmployee() *Employee { 25 | return &Employee{ 26 | FirstName: randomdata.FirstName(randomdata.Male), 27 | LastName: randomdata.LastName(), 28 | Division: randomdata.Day(), 29 | Bio: randomdata.Paragraph(), 30 | Age: rand.Intn(100), // 0 is ok for our test 31 | Created: time.Now(), 32 | } 33 | } 34 | 35 | func TestLookups(t *testing.T) { 36 | 37 | _ = &Employee{} 38 | 39 | /* 40 | filename := "test1.db" 41 | 42 | // Remove before test instead of after so we can review the file 43 | os.Remove(filename) 44 | 45 | // Remove db after testing 46 | defer os.Remove(filename) 47 | 48 | s, err := bolthold.Open(filename, 0666, nil) 49 | if err != nil { 50 | t.Error(err) 51 | } 52 | 53 | // Batch insert records 54 | err = s.Bolt().Update(func(tx *bbolt.Tx) error { 55 | for i := 0; i < 50000; i++ { 56 | err = s.TxInsert(tx, bolthold.NextSequence(), newEmployee()) 57 | if err != nil { 58 | return err 59 | } 60 | } 61 | 62 | return nil 63 | }) 64 | 65 | if err != nil { 66 | t.Error(err) 67 | } 68 | 69 | result, err := s.FindAggregate(&Employee{}, nil, "Division") 70 | 71 | for i := range result { 72 | var division string 73 | employee := &Employee{} 74 | 75 | result[i].Group(&division) 76 | result[i].Min("Created", employee) 77 | 78 | fmt.Printf("The most senior employee in the %s division is %s.\n", 79 | division, employee.FirstName+" "+employee.LastName) 80 | } 81 | */ 82 | 83 | } 84 | 85 | func BenchmarkLookups(b *testing.B) { 86 | 87 | filename := "test.db" 88 | 89 | // Remove before test instead of after so we can review the file 90 | os.Remove(filename) 91 | 92 | // Remove db after testing 93 | // defer os.Remove(filename) 94 | 95 | s, err := bolthold.Open(filename, 0666, nil) 96 | if err != nil { 97 | b.Error(err) 98 | } 99 | 100 | // Batch insert records 101 | err = s.Bolt().Update(func(tx *bbolt.Tx) error { 102 | for i := 0; i < 50000; i++ { 103 | err = s.TxInsert(tx, bolthold.NextSequence(), newEmployee()) 104 | if err != nil { 105 | return err 106 | } 107 | } 108 | 109 | return nil 110 | }) 111 | 112 | if err != nil { 113 | b.Error(err) 114 | } 115 | 116 | // Show time in "seconds" because "5756004313 ns" is hard to read 117 | timer := func(name string, f func(*testing.B)) func(*testing.B) { 118 | return func(b *testing.B) { 119 | start := time.Now() 120 | f(b) 121 | b.Logf("%f seconds\n", time.Since(start).Seconds()) 122 | } 123 | } 124 | 125 | b.Run("LessThan", timer("LessThan", func(b *testing.B) { 126 | var result []Employee 127 | 128 | for i := 0; i < b.N; i++ { 129 | _ = s.Find(&result, bolthold.Where("Age").Lt(10)) 130 | } 131 | })) 132 | 133 | b.Run("ComplexClause", timer("LessThan", func(b *testing.B) { 134 | var result []Employee 135 | 136 | for i := 0; i < b.N; i++ { 137 | _ = s.Find(&result, bolthold.Where("FirstName").Eq("John").And("Age").Lt(10).Or( 138 | bolthold.Where("Division").In("Saturday", "Sunday"), 139 | ).SortBy("LastName")) 140 | } 141 | })) 142 | 143 | b.Run("Division", timer("DivisionAggregate", func(b *testing.B) { 144 | 145 | result, err := s.FindAggregate(&Employee{}, nil, "Division") 146 | 147 | if err != nil { 148 | b.Error(err) 149 | } 150 | 151 | for i := range result { 152 | var division string 153 | employee := &Employee{} 154 | 155 | result[i].Group(&division) 156 | result[i].Min("Created", employee) 157 | _ = employee 158 | 159 | // fmt.Printf("The most senior employee in the %s division is %s.\n", 160 | // division, employee.FirstName+" "+employee.LastName) 161 | } 162 | 163 | })) 164 | 165 | b.Run("Second", func(b *testing.B) { 166 | time.Sleep(time.Second * 20) 167 | }) 168 | 169 | } 170 | -------------------------------------------------------------------------------- /cmd/boltdb/bolthold/readme.md: -------------------------------------------------------------------------------- 1 | ## Bolthold Lookups 2 | 3 | https://github.com/timshannon/bolthold is a library to wrap bbolt with encoding/decoding, indexing, and a query wrapper. 4 | 5 | This saves us from needing to create the extra boiler plate to get estimated benchmarks for searching through a collection of objects. 6 | 7 | ## Lookup 8 | 9 | Here we create 50k structs and search for about 10% of them. 10 | 11 | Searching for ~5k of the small structs takes about `3ms` on my machine as shown below. 12 | 13 | ## Run 14 | 15 | go test --bench=. --benchmem -cpu 1 16 | 17 | goos: darwin 18 | goarch: amd64 19 | pkg: github.com/Xeoncross/go-embeddable-stores/cmd/boltdb/bolthold 20 | BenchmarkLookups 500 3243333 ns/op 932139 B/op 22485 allocs/op 21 | -------------------------------------------------------------------------------- /cmd/boltdb/increment/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "os" 7 | "sync" 8 | "time" 9 | 10 | bolt "github.com/coreos/bbolt" 11 | ) 12 | 13 | func main() { 14 | path := "test.db" 15 | 16 | os.RemoveAll(path) 17 | db, _ := bolt.Open(path, 0600, nil) 18 | defer db.Close() 19 | 20 | db.Update(func(tx *bolt.Tx) error { 21 | tx.CreateBucket([]byte("MyBucket")) 22 | return nil 23 | }) 24 | 25 | var wg sync.WaitGroup 26 | key := []byte("keyhere") 27 | 28 | start := time.Now() 29 | 30 | var i uint64 31 | for i = 0; i < 10000; i++ { 32 | wg.Add(1) 33 | go func(i uint64) { 34 | _, err := incr(db, key) 35 | if err != nil { 36 | fmt.Println(err) 37 | } 38 | // fmt.Println("goroutine", i, id) 39 | wg.Done() 40 | }(i) 41 | } 42 | 43 | wg.Wait() 44 | 45 | fmt.Println(time.Since(start)) 46 | 47 | fmt.Println(i) 48 | err := db.View(func(tx *bolt.Tx) (err error) { 49 | bucket := tx.Bucket([]byte("MyBucket")) 50 | b := bucket.Get(key) 51 | var id int64 52 | if len(b) != 0 { 53 | id = ByteToInt64(b) 54 | } 55 | fmt.Println(b, "=", id) 56 | return 57 | }) 58 | 59 | if err != nil { 60 | fmt.Println(err) 61 | } 62 | 63 | } 64 | 65 | func incr(db *bolt.DB, key []byte) (id int64, err error) { 66 | // mu.Lock() 67 | // defer mu.Unlock() 68 | 69 | err = db.Update(func(tx *bolt.Tx) (err error) { 70 | bucket := tx.Bucket([]byte("MyBucket")) 71 | b := bucket.Get(key) 72 | if len(b) != 0 { 73 | id = ByteToInt64(b) 74 | } 75 | id += 1 76 | err = bucket.Put(key, Int64ToByte(id)) 77 | return 78 | }) 79 | 80 | return 81 | } 82 | 83 | func Int64ToByte(id int64) (b []byte) { //, err error) { 84 | b = make([]byte, 8) 85 | binary.BigEndian.PutUint64(b, uint64(id)) 86 | return 87 | } 88 | 89 | func ByteToInt64(b []byte) int64 { 90 | x := binary.BigEndian.Uint64(b) 91 | return int64(x) 92 | } 93 | -------------------------------------------------------------------------------- /cmd/boltdb/insert/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "math/rand" 6 | "os" 7 | "runtime" 8 | "strconv" 9 | "time" 10 | 11 | bolt "github.com/coreos/bbolt" 12 | ) 13 | 14 | func main() { 15 | path := "test.db" 16 | 17 | os.RemoveAll(path) 18 | db, _ := bolt.Open(path, 0600, nil) 19 | defer db.Close() 20 | 21 | db.Update(func(tx *bolt.Tx) error { 22 | tx.CreateBucket([]byte("test")) 23 | return nil 24 | }) 25 | 26 | valueSize := 16 27 | 28 | for i := 0; i < 1000000; i++ { 29 | go func(i int) { 30 | db.Batch(func(tx *bolt.Tx) error { 31 | key := strconv.Itoa(i) 32 | b := tx.Bucket([]byte("test")) 33 | b.Put([]byte(key), getBytes(valueSize)) 34 | if i%100000 == 0 { 35 | alloc, sys := getMemUsage() 36 | log.Printf("Key = '%v', Alloc = %4vM, Sys = %4vM, Goroutines = %d", key, alloc, sys, runtime.NumGoroutine()) 37 | } 38 | return nil 39 | }) 40 | }(i) 41 | time.Sleep(time.Microsecond) 42 | } 43 | } 44 | 45 | func getBytes(n int) []byte { 46 | b := make([]byte, n) 47 | if _, err := rand.Read(b); err != nil { 48 | panic("Can't read from rand.Read") 49 | } 50 | return b 51 | } 52 | 53 | func getMemUsage() (uint64, uint64) { 54 | var m runtime.MemStats 55 | runtime.ReadMemStats(&m) 56 | return bToMb(m.Alloc), bToMb(m.Sys) 57 | } 58 | 59 | func bToMb(b uint64) uint64 { 60 | return b / 1024 / 1024 61 | } 62 | -------------------------------------------------------------------------------- /cmd/boltdb/readme.md: -------------------------------------------------------------------------------- 1 | # Transactions & Batches 2 | 3 | BoltDB / bbolt are fast when spawning 1k goroutines inserting records as shown in this benchmark. Memory usage stays around 20MB (Alloc) for me while only taking 10 seconds to insert 1m key/values. 4 | -------------------------------------------------------------------------------- /cmd/experiments/byteindex/byteindex.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "encoding/binary" 7 | "encoding/gob" 8 | "fmt" 9 | ) 10 | 11 | func main() { 12 | 13 | // The actual index is a N * 8 []byte long slice of values 14 | var index []byte 15 | 16 | var generatedIds []uint64 17 | 18 | for i := 0; i < 10; i++ { 19 | // Generate a bunch of random 64bit numbers (in []byte form) 20 | // id := rand.Int63() 21 | ib := make([]byte, 8) 22 | rand.Read(ib) 23 | 24 | id := binary.BigEndian.Uint64(ib) 25 | generatedIds = append(generatedIds, id) 26 | 27 | index = append(index, ib...) 28 | } 29 | 30 | fmt.Println("index", index) 31 | fmt.Println("generatedIds", generatedIds) 32 | 33 | var ids []uint64 34 | for i := 0; i < len(index); i += 8 { 35 | id := binary.BigEndian.Uint64(index[i : i+8]) 36 | ids = append(ids, id) 37 | } 38 | 39 | fmt.Println("ids", ids) 40 | } 41 | 42 | func MarshalByte(v []uint64) (index []byte, err error) { 43 | for _, id := range v { 44 | b := make([]byte, 8) 45 | binary.BigEndian.PutUint64(b, id) 46 | index = append(index, b...) 47 | } 48 | return 49 | } 50 | 51 | func UnmarshalByte(index []byte) (ids []uint64, err error) { 52 | for i := 0; i < len(index); i += 8 { 53 | id := binary.BigEndian.Uint64(index[i : i+8]) 54 | ids = append(ids, id) 55 | } 56 | return 57 | } 58 | 59 | func MarshalGob(v []uint64) ([]byte, error) { 60 | b := new(bytes.Buffer) 61 | err := gob.NewEncoder(b).Encode(v) 62 | if err != nil { 63 | return nil, err 64 | } 65 | return b.Bytes(), nil 66 | } 67 | 68 | func UnmarshalGob(data []byte) (ids []uint64, err error) { 69 | b := bytes.NewBuffer(data) 70 | err = gob.NewDecoder(b).Decode(&ids) 71 | return 72 | } 73 | 74 | // This is slower than keylist because the bytes are not ordered so we have 75 | // to search the whole thing 76 | // ByteIndex is an index where every 64bits/8bytes is an object's ID 77 | type ByteIndex []byte 78 | 79 | // Add a 64bit integer (in byte form) to the index 80 | func (b *ByteIndex) Add(id []byte) { 81 | // Make sure this ID isn't already here 82 | for i := 0; i < len((*b)); i += 8 { 83 | if bytes.Equal(id, (*b)[i:i+8]) { 84 | return 85 | } 86 | } 87 | 88 | (*b) = append((*b), id...) 89 | } 90 | 91 | // Remove a 64bit integer (in []byte form) from the index 92 | func (b *ByteIndex) Remove(id []byte) { 93 | for i := 0; i < len((*b)); i += 8 { 94 | if bytes.Equal(id, (*b)[i:i+8]) { 95 | (*b) = append((*b)[:i], (*b)[i+8:]...) 96 | } 97 | } 98 | } 99 | 100 | func (b *ByteIndex) Find(id []byte) (i int) { 101 | for i = 0; i < len((*b)); i += 8 { 102 | if bytes.Equal(id, (*b)[i:i+8]) { 103 | return 104 | } 105 | } 106 | return -1 107 | } 108 | 109 | // func MarshalByte(v []uint64) (index []byte, err error) { 110 | // for _, id := range v { 111 | // b := make([]byte, 8) 112 | // binary.BigEndian.PutUint64(b, id) 113 | // index = append(index, b...) 114 | // } 115 | // return 116 | // } 117 | // 118 | // func UnmarshalByte(index []byte) (ids []uint64, err error) { 119 | // for i := 0; i < len(index); i += 8 { 120 | // id := binary.BigEndian.Uint64(index[i : i+8]) 121 | // ids = append(ids, id) 122 | // } 123 | // return 124 | // } 125 | -------------------------------------------------------------------------------- /cmd/experiments/byteindex/byteindex_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "math/rand" 6 | "testing" 7 | ) 8 | 9 | func BenchmarkByte(b *testing.B) { 10 | rand.Seed(1) // Same every run 11 | 12 | for n := 0; n < b.N; n++ { 13 | 14 | // Generate a bunch of ids 15 | var ids []uint64 16 | for i := 0; i < 10000; i++ { 17 | id := rand.Int63() 18 | ids = append(ids, uint64(id)) 19 | } 20 | 21 | index, err := MarshalByte(ids) 22 | if err != nil { 23 | b.Error(err) 24 | } 25 | 26 | var decodedIds []uint64 27 | decodedIds, err = UnmarshalByte(index) 28 | if err != nil { 29 | b.Error(err) 30 | } 31 | 32 | // fmt.Println("ids", ids) 33 | // fmt.Println("decodedIds", decodedIds) 34 | 35 | if testEq(decodedIds, ids) == false { 36 | b.Error("mis-match") 37 | } 38 | } 39 | } 40 | 41 | func BenchmarkGob(b *testing.B) { 42 | rand.Seed(1) // Same every run 43 | 44 | for n := 0; n < b.N; n++ { 45 | 46 | // Generate a bunch of ids 47 | var ids []uint64 48 | for i := 0; i < 10000; i++ { 49 | id := rand.Int63() 50 | ids = append(ids, uint64(id)) 51 | } 52 | 53 | index, err := MarshalGob(ids) 54 | if err != nil { 55 | b.Error(err) 56 | } 57 | 58 | var decodedIds []uint64 59 | decodedIds, err = UnmarshalGob(index) 60 | if err != nil { 61 | b.Error(err) 62 | } 63 | 64 | // fmt.Println("ids", ids) 65 | // fmt.Println("decodedIds", decodedIds) 66 | 67 | if testEq(decodedIds, ids) == false { 68 | b.Error("mis-match") 69 | } 70 | } 71 | } 72 | 73 | // Slower because of a lack of search 74 | // func BenchmarkByteIndexAdd(b *testing.B) { 75 | // for n := 0; n < b.N; n++ { 76 | // bi := &ByteIndex{} 77 | // for i := 0; i < 100000; i++ { 78 | // id := make([]byte, 8) 79 | // rand.Read(id) 80 | // bi.Add(id) 81 | // } 82 | // } 83 | // } 84 | 85 | // func BenchmarkByteIndexRemove(b *testing.B) { 86 | // for n := 0; n < b.N; n++ { 87 | // bi := &ByteIndex{} 88 | // var ids [][]byte 89 | // for i := 0; i < 100000; i++ { 90 | // id := make([]byte, 8) 91 | // rand.Read(id) 92 | // bi.Add(id) 93 | // bi.Find(id) 94 | // ids = append(ids, id) 95 | // } 96 | // 97 | // for _, id := range ids { 98 | // bi.Remove(id) 99 | // } 100 | // } 101 | // } 102 | 103 | // func BenchmarkKeyListAdd(b *testing.B) { 104 | // for n := 0; n < b.N; n++ { 105 | // kl := &keyList{} 106 | // for i := 0; i < 100000; i++ { 107 | // id := make([]byte, 8) 108 | // rand.Read(id) 109 | // kl.add(id) 110 | // } 111 | // } 112 | // } 113 | 114 | // func BenchmarkKeyListRemove(b *testing.B) { 115 | // for n := 0; n < b.N; n++ { 116 | // kl := &keyList{} 117 | // var ids [][]byte 118 | // for i := 0; i < 100000; i++ { 119 | // 120 | // id := make([]byte, 8) 121 | // rand.Read(id) 122 | // kl.add(id) 123 | // kl.in(id) 124 | // ids = append(ids, id) 125 | // } 126 | // 127 | // for _, id := range ids { 128 | // kl.remove(id) 129 | // } 130 | // } 131 | // } 132 | 133 | func BenchmarkKeyListMarshalByte(b *testing.B) { 134 | 135 | kl := &keyList{} 136 | for i := 0; i < 100000; i++ { 137 | id := make([]byte, 8) 138 | rand.Read(id) 139 | kl.add(id) 140 | } 141 | 142 | b.ResetTimer() 143 | 144 | b.Run("Byte", func(b *testing.B) { 145 | for n := 0; n < b.N; n++ { 146 | data, err := kl.MarshalToByte() 147 | if err != nil { 148 | b.Error(err) 149 | } 150 | 151 | kl = &keyList{} 152 | err = kl.UnmarshalFromByte(data) 153 | if err != nil { 154 | b.Error(err) 155 | } 156 | 157 | if len(*kl) != 100000 { 158 | b.Error("Error decoding") 159 | } 160 | } 161 | }) 162 | 163 | b.Run("Gob", func(b *testing.B) { 164 | for n := 0; n < b.N; n++ { 165 | data, err := kl.MarshalToGob() 166 | if err != nil { 167 | b.Error(err) 168 | } 169 | 170 | kl = &keyList{} 171 | err = kl.UnmarshalFromGob(data) 172 | if err != nil { 173 | b.Error(err) 174 | } 175 | 176 | if len(*kl) != 100000 { 177 | b.Error("Error decoding") 178 | } 179 | } 180 | }) 181 | } 182 | 183 | // func BenchmarkKeyListMarshalGob(b *testing.B) { 184 | // 185 | // kl := &keyList{} 186 | // for i := 0; i < 100000; i++ { 187 | // id := make([]byte, 8) 188 | // rand.Read(id) 189 | // kl.add(id) 190 | // } 191 | // 192 | // b.ResetTimer() 193 | // 194 | // for n := 0; n < b.N; n++ { 195 | // data, err := kl.MarshalToGob() 196 | // if err != nil { 197 | // b.Error(err) 198 | // } 199 | // 200 | // kl = &keyList{} 201 | // err = kl.UnmarshalFromGob(data) 202 | // if err != nil { 203 | // b.Error(err) 204 | // } 205 | // 206 | // if len(*kl) != 100000 { 207 | // b.Error("Error decoding") 208 | // } 209 | // } 210 | // } 211 | 212 | func TestByteIndex(t *testing.T) { 213 | bi := &ByteIndex{} 214 | 215 | id := make([]byte, 8) 216 | rand.Read(id) 217 | bi.Add(id) 218 | 219 | id2 := make([]byte, 8) 220 | rand.Read(id2) 221 | bi.Add(id2) 222 | 223 | id3 := make([]byte, 8) 224 | rand.Read(id3) 225 | bi.Add(id3) 226 | 227 | // fmt.Println("id", id) 228 | // fmt.Println("id2", id2) 229 | // fmt.Println("id3", id3) 230 | // fmt.Println("ByteIndex", bi) 231 | 232 | if !bytes.Equal((*bi)[0:8], id) { 233 | t.Error("ID not saved") 234 | } 235 | 236 | i := bi.Find(id) 237 | if i == -1 { 238 | t.Error("ID not found") 239 | } 240 | 241 | if i != 0 { 242 | t.Errorf("ID not in correct location: %d", i) 243 | } 244 | 245 | bi.Remove(id) 246 | // fmt.Println("ByteIndex", bi) 247 | 248 | if !bytes.Equal((*bi)[8:16], id3) { 249 | t.Error("ID not removed") 250 | } 251 | 252 | } 253 | 254 | func testEq(a, b []uint64) bool { 255 | // If one is nil, the other must also be nil. 256 | if (a == nil) != (b == nil) { 257 | return false 258 | } 259 | 260 | if len(a) != len(b) { 261 | return false 262 | } 263 | 264 | for i := range a { 265 | if a[i] != b[i] { 266 | return false 267 | } 268 | } 269 | 270 | return true 271 | } 272 | -------------------------------------------------------------------------------- /cmd/experiments/byteindex/keylist.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/gob" 6 | "sort" 7 | ) 8 | 9 | /* 10 | BenchmarkByte-8 3000 380887 ns/op 1155563 B/op 64 allocs/op 11 | BenchmarkGob-8 2000 624693 ns/op 1055519 B/op 228 allocs/op 12 | BenchmarkByteIndex-8 20000 127662 ns/op 164 B/op 1 allocs/op 13 | BenchmarkKeyList-8 500000 626237 ns/op 290 B/op 1 allocs/op 14 | BenchmarkKeyListMarshalByte/Byte-8 100 13880275 ns/op 19249168 B/op 66 allocs/op 15 | BenchmarkKeyListMarshalByte/Gob-8 100 17191247 ns/op 12861329 B/op 200221 allocs/op 16 | */ 17 | 18 | // Because keyList is sorted the lookup times are much faster than ByteIndex. 19 | // Helps speed up adding and removing indexes 20 | 21 | // https://github.com/timshannon/bolthold/blob/master/index.go#L108 22 | // https://play.golang.org/p/U1zVINjzOJf 23 | // https://gist.github.com/schmohlio/615ab4d47bc01020786ef58aec622fdf 24 | 25 | // keyList is a slice of unique, sorted keys([]byte) such as what an index points to 26 | type keyList [][]byte 27 | 28 | func (v *keyList) add(key []byte) { 29 | i := sort.Search(len(*v), func(i int) bool { 30 | return bytes.Compare((*v)[i], key) >= 0 31 | }) 32 | 33 | if i < len(*v) && bytes.Equal((*v)[i], key) { 34 | // already added 35 | return 36 | } 37 | 38 | *v = append(*v, nil) 39 | copy((*v)[i+1:], (*v)[i:]) 40 | (*v)[i] = key 41 | } 42 | 43 | func (v *keyList) remove(key []byte) { 44 | i := sort.Search(len(*v), func(i int) bool { 45 | return bytes.Compare((*v)[i], key) >= 0 46 | }) 47 | 48 | if i < len(*v) { 49 | copy((*v)[i:], (*v)[i+1:]) 50 | (*v)[len(*v)-1] = nil 51 | *v = (*v)[:len(*v)-1] 52 | } 53 | } 54 | 55 | func (v *keyList) in(key []byte) bool { 56 | i := sort.Search(len(*v), func(i int) bool { 57 | return bytes.Compare((*v)[i], key) >= 0 58 | }) 59 | 60 | return (i < len(*v) && bytes.Equal((*v)[i], key)) 61 | } 62 | 63 | func (v *keyList) MarshalToByte() (index []byte, err error) { 64 | // Create a byte array large enough, then fill it with each value 65 | index = make([]byte, len((*v))*8) 66 | for i, id := range *v { 67 | copy(id[0:], index[i:i+8]) 68 | // index[i] = id[0] 69 | // index[i+1] = id[1] 70 | // index[i+2] = id[2] 71 | // index[i+3] = id[3] 72 | // index[i+4] = id[4] 73 | // index[i+5] = id[5] 74 | // index[i+6] = id[6] 75 | // index[i+7] = id[7] 76 | } 77 | return 78 | } 79 | 80 | func (v *keyList) MarshalToByte2() (index []byte, err error) { 81 | // return append([]byte{}, ((*v)...)), nil 82 | for _, id := range *v { 83 | index = append(index, id...) 84 | } 85 | return 86 | } 87 | 88 | func (v *keyList) UnmarshalFromByte(index []byte) error { 89 | (*v) = make([][]byte, len(index)/8) 90 | for i := 0; i < len(index); i += 8 { 91 | // (*v) = append((*v), index[i:i+8]) 92 | (*v)[i/8] = index[i : i+8] 93 | } 94 | return nil 95 | } 96 | 97 | func (v *keyList) UnmarshalFromByte2(index []byte) error { 98 | (*v) = make([][]byte, len(index)/8) 99 | for i := 0; i < len(index); i += 8 { 100 | (*v) = append((*v), index[i:i+8]) 101 | } 102 | return nil 103 | } 104 | 105 | func (v *keyList) MarshalToGob() (index []byte, err error) { 106 | b := new(bytes.Buffer) 107 | err = gob.NewEncoder(b).Encode(v) 108 | if err != nil { 109 | return nil, err 110 | } 111 | return b.Bytes(), nil 112 | } 113 | 114 | func (v *keyList) UnmarshalFromGob(index []byte) error { 115 | b := bytes.NewBuffer(index) 116 | return gob.NewDecoder(b).Decode(&v) 117 | } 118 | -------------------------------------------------------------------------------- /cmd/leveldb/increment/level.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "log" 7 | "sync" 8 | 9 | "github.com/syndtr/goleveldb/leveldb" 10 | "github.com/syndtr/goleveldb/leveldb/opt" 11 | ) 12 | 13 | var mu sync.Mutex 14 | 15 | func main() { 16 | db, err := leveldb.OpenFile("database", nil) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | 21 | var wg sync.WaitGroup 22 | key := []byte("keyhere") 23 | 24 | var i uint64 25 | for i = 0; i < 10; i++ { 26 | wg.Add(1) 27 | go func(i uint64) { 28 | id, err := incr(db, key) 29 | if err != nil { 30 | fmt.Println(err) 31 | } 32 | fmt.Println("goroutine", i, id) 33 | wg.Done() 34 | }(i) 35 | } 36 | 37 | wg.Wait() 38 | 39 | fmt.Println(i) 40 | id, err := db.Get(key, &opt.ReadOptions{}) 41 | if err != nil { 42 | fmt.Println(err) 43 | } 44 | fmt.Println(id, "=", ByteToInt64(id)) 45 | 46 | } 47 | 48 | func incr(db *leveldb.DB, key []byte) (id int64, err error) { 49 | mu.Lock() 50 | defer mu.Unlock() 51 | 52 | // May or may not exist 53 | b, err := db.Get(key, &opt.ReadOptions{DontFillCache: true}) 54 | if err == nil { 55 | return 56 | } 57 | if len(b) != 0 { 58 | id = ByteToInt64(b) 59 | } 60 | 61 | id += 1 62 | err = db.Put(key, Int64ToByte(id), &opt.WriteOptions{Sync: true}) 63 | if err != nil { 64 | return 65 | } 66 | 67 | return 68 | } 69 | 70 | // func incr(db *leveldb.DB, key []byte) (id int64, err error) { 71 | // mu.Lock() 72 | // defer mu.Unlock() 73 | // 74 | // tx, err := db.OpenTransaction() 75 | // if err != nil { 76 | // return 77 | // } 78 | // 79 | // // May or may not exist 80 | // b, err := tx.Get(key, &opt.ReadOptions{DontFillCache: true}) 81 | // if err == nil { 82 | // tx.Discard() 83 | // return 84 | // } 85 | // if len(b) != 0 { 86 | // id = ByteToInt64(b) 87 | // } 88 | // 89 | // id += 1 90 | // err = tx.Put(key, Int64ToByte(id), &opt.WriteOptions{Sync: true}) 91 | // if err != nil { 92 | // return 93 | // } 94 | // 95 | // err = tx.Commit() 96 | // return 97 | // } 98 | 99 | func Int64ToByte(id int64) (b []byte) { //, err error) { 100 | b = make([]byte, 8) 101 | binary.BigEndian.PutUint64(b, uint64(id)) 102 | return 103 | } 104 | 105 | func ByteToInt64(b []byte) int64 { 106 | x := binary.BigEndian.Uint64(b) 107 | return int64(x) 108 | } 109 | -------------------------------------------------------------------------------- /cmd/leveldb/insert/level.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/binary" 6 | "log" 7 | 8 | "github.com/syndtr/goleveldb/leveldb" 9 | ) 10 | 11 | func main() { 12 | db, err := leveldb.OpenFile("leveldb", nil) 13 | if err != nil { 14 | log.Fatal(err) 15 | } 16 | 17 | var key, batchSize uint64 18 | batchSize = 100000 19 | 20 | for { 21 | insertKeys(db, key, key+batchSize) 22 | deleteKeys(db, key, key+batchSize) 23 | key += batchSize 24 | } 25 | 26 | } 27 | 28 | func randomBytes(n int) ([]byte, error) { 29 | b := make([]byte, n) 30 | _, err := rand.Read(b) 31 | return b, err 32 | } 33 | 34 | func dbKey(index uint64) []byte { 35 | key := make([]byte, 8) 36 | binary.BigEndian.PutUint64(key, index) 37 | return key 38 | } 39 | 40 | func insertKeys(db *leveldb.DB, startKey uint64, endKey uint64) { 41 | for i := startKey; i < endKey; i++ { 42 | data, _ := randomBytes(256) 43 | db.Put(dbKey(i), data, nil) 44 | if i%10000 == 0 { 45 | log.Printf("Inserted %d records", i) 46 | } 47 | } 48 | } 49 | 50 | func deleteKeys(db *leveldb.DB, startKey uint64, endKey uint64) { 51 | for i := startKey; i < endKey; i++ { 52 | db.Delete(dbKey(i), nil) 53 | if i%10000 == 0 { 54 | log.Printf("Deleted %d records", i) 55 | } 56 | } 57 | } 58 | 59 | // func Int64ToByte(id int64) (b []byte) { //, err error) { 60 | // b = make([]byte, 8) 61 | // binary.BigEndian.PutUint64(b, uint64(id)) 62 | // return 63 | // } 64 | // 65 | // func ByteToInt64(b []byte) int64 { 66 | // x := binary.BigEndian.Uint64(b) 67 | // return int64(x) 68 | // } 69 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/badgerdb.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/dgraph-io/badger" 7 | ) 8 | 9 | func newBadgerdb(path string) (kvEngine, error) { 10 | opts := badger.DefaultOptions 11 | opts.SyncWrites = true 12 | opts.Dir = path 13 | opts.ValueDir = path 14 | db, err := badger.Open(opts) 15 | return &badgerdbEngine{db: db, path: path}, err 16 | } 17 | 18 | type badgerdbEngine struct { 19 | path string 20 | db *badger.DB 21 | } 22 | 23 | func (db *badgerdbEngine) Put(key []byte, value []byte) error { 24 | return db.db.Update(func(tx *badger.Txn) error { 25 | return tx.Set(key, value) 26 | }) 27 | } 28 | 29 | func (db *badgerdbEngine) Get(key []byte) ([]byte, error) { 30 | var val []byte 31 | err := db.db.View(func(txn *badger.Txn) error { 32 | item, err := txn.Get(key) 33 | if err != nil { 34 | return err 35 | } 36 | v, err := item.Value() 37 | if err != nil { 38 | return err 39 | } 40 | val = v 41 | return nil 42 | }) 43 | return val, err 44 | } 45 | 46 | func (db *badgerdbEngine) Close() error { 47 | return db.db.Close() 48 | } 49 | 50 | func (db *badgerdbEngine) FileSize() (int64, error) { 51 | return dirSize(db.path) 52 | } 53 | 54 | func (db *badgerdbEngine) Cleanup() error { 55 | return os.RemoveAll(db.path) 56 | } 57 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/bbolt.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/etcd-io/bbolt" 7 | ) 8 | 9 | var bboltBucketName = []byte("benchmark") 10 | 11 | type bboltEngine struct { 12 | db *bbolt.DB 13 | path string 14 | // bucket *bbolt.Bucket 15 | } 16 | 17 | func newBBolt(path string) (kvEngine, error) { 18 | db, err := bbolt.Open(path, 0600, nil) 19 | if err != nil { 20 | return nil, err 21 | } 22 | // db.NoSync = false // default to sync for each write 23 | 24 | err = db.Update(func(tx *bbolt.Tx) (err error) { 25 | _, err = tx.CreateBucketIfNotExists(bboltBucketName) 26 | return err 27 | }) 28 | return &bboltEngine{db: db, path: path}, err 29 | } 30 | 31 | func (db *bboltEngine) Put(key []byte, value []byte) error { 32 | return db.db.Update(func(tx *bbolt.Tx) error { 33 | b := tx.Bucket(bboltBucketName) 34 | return b.Put(key, value) 35 | }) 36 | // return db.bucket.Put(key, value) 37 | } 38 | 39 | func (db *bboltEngine) Get(key []byte) ([]byte, error) { 40 | var val []byte 41 | err := db.db.View(func(tx *bbolt.Tx) error { 42 | b := tx.Bucket(bboltBucketName) 43 | val = b.Get(key) 44 | return nil 45 | }) 46 | return val, err 47 | // return db.bucket.Get(key), nil 48 | } 49 | 50 | // https://github.com/bboltdb/bbolt#prefix-scans 51 | // func (db *bboltEngine) Search(key []byte) error { 52 | // return db.db.View(func(tx *bbolt.Tx) error { 53 | // c := tx.Bucket(key).Cursor() 54 | // 55 | // suffix := []byte("1234") 56 | // for k, v := c.Seek(suffix); bytes.HasSuffix(k, suffix); k, v = c.Next() { 57 | // fmt.Printf("key=%s, value=%s\n", k, v) 58 | // } 59 | // 60 | // return nil 61 | // }) 62 | // } 63 | 64 | func (db *bboltEngine) Close() error { 65 | return db.db.Close() 66 | } 67 | 68 | func (db *bboltEngine) FileSize() (int64, error) { 69 | return dirSize(db.path) 70 | } 71 | 72 | func (db *bboltEngine) Cleanup() error { 73 | return os.Remove(db.path) 74 | } 75 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/benchmark.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "math/rand" 7 | "path" 8 | "runtime" 9 | "sync" 10 | "time" 11 | 12 | "github.com/akrylysov/pogreb" 13 | ) 14 | 15 | func randKey(minL int, maxL int) string { 16 | n := rand.Intn(maxL-minL+1) + minL 17 | buf := make([]byte, n) 18 | for i := 0; i < n; i++ { 19 | buf[i] = byte(rand.Intn(95) + 32) 20 | } 21 | return string(buf) 22 | } 23 | 24 | func randValue(rnd *rand.Rand, src []byte, minS int, maxS int) []byte { 25 | n := rnd.Intn(maxS-minS+1) + minS 26 | return src[:n] 27 | } 28 | 29 | func forceGC() { 30 | runtime.GC() 31 | time.Sleep(time.Millisecond * 500) 32 | } 33 | 34 | func shuffle(a [][]byte) { 35 | for i := len(a) - 1; i > 0; i-- { 36 | j := rand.Intn(i + 1) 37 | a[i], a[j] = a[j], a[i] 38 | } 39 | } 40 | 41 | func generateKeys(count int, minL int, maxL int) [][]byte { 42 | keys := make([][]byte, 0, count) 43 | seen := make(map[string]struct{}, count) 44 | for len(keys) < count { 45 | k := randKey(minL, maxL) 46 | if _, ok := seen[k]; ok { 47 | continue 48 | } 49 | seen[k] = struct{}{} 50 | keys = append(keys, []byte(k)) 51 | } 52 | return keys 53 | } 54 | 55 | func concurrentBatch(keys [][]byte, concurrency int, cb func(gid int, batch [][]byte) error) error { 56 | wg := &sync.WaitGroup{} 57 | batchSize := len(keys) / concurrency 58 | wg.Add(concurrency) 59 | var err error 60 | for i := 0; i < concurrency; i++ { 61 | batchStart := i * batchSize 62 | batchEnd := (i + 1) * batchSize 63 | if batchEnd > len(keys) { 64 | batchEnd = len(keys) 65 | } 66 | // FIX panic: runtime error: slice bounds out of range 67 | go func(gid int, batch [][]byte) { 68 | err = cb(gid, batch) 69 | wg.Done() 70 | }(i, keys[batchStart:batchEnd]) 71 | } 72 | wg.Wait() 73 | return err 74 | } 75 | 76 | func printStats(db *pogreb.DB) { 77 | fmt.Printf("%+v\n", db.Metrics()) 78 | } 79 | 80 | func showProgress(gid int, i int, total int) { 81 | if i%50000 == 0 { 82 | fmt.Printf("Goroutine %d. Processed %d from %d items...\n", gid, i, total) 83 | } 84 | } 85 | 86 | func benchmark(engine string, dir string, numKeys int, minKS int, maxKS int, minVS int, maxVS int, concurrency int, progress bool) error { 87 | ctr, err := getEngineCtr(engine) 88 | if err != nil { 89 | return err 90 | } 91 | 92 | dbpath := path.Join(dir, "bench_"+engine) 93 | db, err := ctr(dbpath) 94 | if err != nil { 95 | return err 96 | } 97 | 98 | // fmt.Printf("Number of keys: %d\n", numKeys) 99 | // fmt.Printf("Minimum key size: %d, maximum key size: %d\n", minKS, maxKS) 100 | // fmt.Printf("Minimum value size: %d, maximum value size: %d\n", minVS, maxVS) 101 | // fmt.Printf("Concurrency: %d\n", concurrency) 102 | fmt.Printf("Running %s benchmark...\n", engine) 103 | 104 | keys := generateKeys(numKeys, minKS, maxKS) 105 | valSrc := make([]byte, maxVS) 106 | if _, err := rand.Read(valSrc); err != nil { 107 | return err 108 | } 109 | forceGC() 110 | 111 | start := time.Now() 112 | err = concurrentBatch(keys, concurrency, func(gid int, batch [][]byte) error { 113 | rnd := rand.New(rand.NewSource(int64(rand.Uint64()))) 114 | for i, k := range batch { 115 | if err := db.Put(k, randValue(rnd, valSrc, minVS, maxVS)); err != nil { 116 | return err 117 | } 118 | if progress { 119 | showProgress(gid, i, len(batch)) 120 | } 121 | } 122 | return nil 123 | }) 124 | if err != nil { 125 | return err 126 | } 127 | if err := db.Close(); err != nil { 128 | return err 129 | } 130 | endsecs := time.Since(start).Seconds() 131 | totalalsecs := endsecs 132 | fmt.Printf("Put: %.3f sec, %d ops/sec\n", endsecs, int(float64(numKeys)/endsecs)) 133 | // if pdb, ok := db.(*pogreb.DB); ok { 134 | // printStats(pdb) 135 | // } 136 | shuffle(keys) 137 | db, err = ctr(dbpath) 138 | if err != nil { 139 | return err 140 | } 141 | forceGC() 142 | 143 | start = time.Now() 144 | err = concurrentBatch(keys, concurrency, func(gid int, batch [][]byte) error { 145 | for i, k := range batch { 146 | v, err := db.Get(k) 147 | if err != nil { 148 | return err 149 | } 150 | if v == nil { 151 | return errors.New("key doesn't exist") 152 | } 153 | if progress { 154 | showProgress(gid, i, len(batch)) 155 | } 156 | } 157 | return nil 158 | }) 159 | if err != nil { 160 | return err 161 | } 162 | endsecs = time.Since(start).Seconds() 163 | totalalsecs += endsecs 164 | fmt.Printf("Get: %.3f sec, %d ops/sec\n", endsecs, int(float64(numKeys)/endsecs)) 165 | fmt.Printf("Put + Get time: %.3f sec\n", totalalsecs) 166 | sz, err := db.FileSize() 167 | if err != nil { 168 | return err 169 | } 170 | fmt.Printf("File size: %s\n", byteSize(sz)) 171 | // if pdb, ok := db.(*pogreb.DB); ok { 172 | // printStats(pdb) 173 | // } 174 | 175 | err = db.Close() 176 | if err != nil { 177 | return err 178 | } 179 | 180 | return db.Cleanup() 181 | } 182 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/bolt.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/boltdb/bolt" 7 | ) 8 | 9 | var boltBucketName = []byte("benchmark") 10 | 11 | type boltEngine struct { 12 | db *bolt.DB 13 | path string 14 | // bucket *bolt.Bucket 15 | } 16 | 17 | func newBolt(path string) (kvEngine, error) { 18 | db, err := bolt.Open(path, 0600, nil) 19 | if err != nil { 20 | return nil, err 21 | } 22 | db.NoSync = false 23 | 24 | err = db.Update(func(tx *bolt.Tx) (err error) { 25 | _, err = tx.CreateBucketIfNotExists(boltBucketName) 26 | return err 27 | }) 28 | return &boltEngine{db: db, path: path}, err 29 | } 30 | 31 | func (db *boltEngine) Put(key []byte, value []byte) error { 32 | return db.db.Update(func(tx *bolt.Tx) error { 33 | b := tx.Bucket(boltBucketName) 34 | return b.Put(key, value) 35 | }) 36 | // return db.bucket.Put(key, value) 37 | } 38 | 39 | func (db *boltEngine) Get(key []byte) ([]byte, error) { 40 | var val []byte 41 | err := db.db.View(func(tx *bolt.Tx) error { 42 | b := tx.Bucket(boltBucketName) 43 | val = b.Get(key) 44 | return nil 45 | }) 46 | return val, err 47 | // return db.bucket.Get(key), nil 48 | } 49 | 50 | // https://github.com/boltdb/bolt#prefix-scans 51 | // func (db *boltEngine) Search(key []byte) error { 52 | // return db.db.View(func(tx *bolt.Tx) error { 53 | // c := tx.Bucket(key).Cursor() 54 | // 55 | // suffix := []byte("1234") 56 | // for k, v := c.Seek(suffix); bytes.HasSuffix(k, suffix); k, v = c.Next() { 57 | // fmt.Printf("key=%s, value=%s\n", k, v) 58 | // } 59 | // 60 | // return nil 61 | // }) 62 | // } 63 | 64 | func (db *boltEngine) Close() error { 65 | return db.db.Close() 66 | } 67 | 68 | func (db *boltEngine) FileSize() (int64, error) { 69 | return dirSize(db.path) 70 | } 71 | 72 | func (db *boltEngine) Cleanup() error { 73 | return os.Remove(db.path) 74 | } 75 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/bytesize.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // Code from http://golang.org/doc/effective_go.html 6 | type byteSize float64 7 | 8 | const ( 9 | _ = iota // ignore first value by assigning to blank identifier 10 | KB byteSize = 1 << (10 * iota) 11 | MB 12 | GB 13 | TB 14 | PB 15 | EB 16 | ZB 17 | YB 18 | ) 19 | 20 | func (b byteSize) String() string { 21 | switch { 22 | case b >= YB: 23 | return fmt.Sprintf("%.2fYB", b/YB) 24 | case b >= ZB: 25 | return fmt.Sprintf("%.2fZB", b/ZB) 26 | case b >= EB: 27 | return fmt.Sprintf("%.2fEB", b/EB) 28 | case b >= PB: 29 | return fmt.Sprintf("%.2fPB", b/PB) 30 | case b >= TB: 31 | return fmt.Sprintf("%.2fTB", b/TB) 32 | case b >= GB: 33 | return fmt.Sprintf("%.2fGB", b/GB) 34 | case b >= MB: 35 | return fmt.Sprintf("%.2fMB", b/MB) 36 | case b >= KB: 37 | return fmt.Sprintf("%.2fKB", b/KB) 38 | } 39 | return fmt.Sprintf("%.2fB", b) 40 | } 41 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/data/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xeoncross/go-embeddable-stores/02839977f509ddcebb89964ef056b24fbc8a0d89/cmd/pogreb-bench/data/.DS_Store -------------------------------------------------------------------------------- /cmd/pogreb-bench/data/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xeoncross/go-embeddable-stores/02839977f509ddcebb89964ef056b24fbc8a0d89/cmd/pogreb-bench/data/empty -------------------------------------------------------------------------------- /cmd/pogreb-bench/engine.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "os" 6 | "path/filepath" 7 | ) 8 | 9 | type kvEngine interface { 10 | Put(key []byte, value []byte) error 11 | Get(key []byte) ([]byte, error) 12 | Close() error 13 | FileSize() (int64, error) 14 | Cleanup() error 15 | } 16 | 17 | type engineCtr func(string) (kvEngine, error) 18 | 19 | var engines = map[string]engineCtr{ 20 | "pogreb": newPogreb, 21 | "goleveldb": newGolevelDB, 22 | "bolt": newBolt, 23 | "bbolt": newBBolt, 24 | // "badgerdb": newBadgerdb, 25 | "tiedot": newTiedot, 26 | } 27 | 28 | func getEngineCtr(name string) (engineCtr, error) { 29 | if ctr, ok := engines[name]; ok { 30 | return ctr, nil 31 | } 32 | return nil, errors.New("unknown engine") 33 | } 34 | 35 | func dirSize(path string) (int64, error) { 36 | var size int64 37 | err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error { 38 | if !info.IsDir() { 39 | size += info.Size() 40 | } 41 | return err 42 | }) 43 | return size, err 44 | } 45 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/engine_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math/rand" 5 | "path" 6 | "testing" 7 | ) 8 | 9 | // RandomBytes up to X length 10 | func randomBytes(min, max int) (b []byte) { 11 | b = make([]byte, min+rand.Intn(max-min)) 12 | _, err := rand.Read(b) 13 | if err != nil { 14 | panic(err) 15 | } 16 | return b 17 | } 18 | 19 | func BenchmarkEngines100(b *testing.B) { 20 | 21 | for engineName := range engines { 22 | ctr, err := getEngineCtr(engineName) 23 | if err != nil { 24 | b.Error(err) 25 | } 26 | 27 | b.Run(engineName, func(b2 *testing.B) { 28 | dbpath := path.Join("./data", "bench_"+engineName) 29 | db, err := ctr(dbpath) 30 | if err != nil { 31 | b.Error(err) 32 | } 33 | 34 | for n := 0; n < b2.N; n++ { 35 | db.Put(randomBytes(8, 64), randomBytes(8, 64)) 36 | } 37 | 38 | err = db.Close() 39 | if err != nil { 40 | b.Error(err) 41 | } 42 | 43 | err = db.Cleanup() 44 | if err != nil { 45 | b.Error(err) 46 | } 47 | }) 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/goleveldb.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/syndtr/goleveldb/leveldb" 7 | "github.com/syndtr/goleveldb/leveldb/opt" 8 | "github.com/syndtr/goleveldb/leveldb/util" 9 | ) 10 | 11 | type goleveldbEngine struct { 12 | db *leveldb.DB 13 | path string 14 | } 15 | 16 | func newGolevelDB(path string) (kvEngine, error) { 17 | opts := opt.Options{ 18 | Compression: opt.NoCompression, 19 | } 20 | db, err := leveldb.OpenFile(path, &opts) 21 | if err != nil { 22 | return nil, err 23 | } 24 | err = db.CompactRange(util.Range{}) 25 | return &goleveldbEngine{db: db, path: path}, err 26 | } 27 | 28 | func (db *goleveldbEngine) Put(key []byte, value []byte) error { 29 | return db.db.Put(key, value, nil) 30 | } 31 | 32 | func (db *goleveldbEngine) Get(key []byte) ([]byte, error) { 33 | return db.db.Get(key, nil) 34 | } 35 | 36 | func (db *goleveldbEngine) Close() error { 37 | return db.db.Close() 38 | } 39 | 40 | func (db *goleveldbEngine) FileSize() (int64, error) { 41 | return dirSize(db.path) 42 | } 43 | 44 | func (db *goleveldbEngine) Cleanup() error { 45 | return os.RemoveAll(db.path) 46 | } 47 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | _ "expvar" 5 | "flag" 6 | "fmt" 7 | "net/http" 8 | "os" 9 | "time" 10 | ) 11 | 12 | var ( 13 | engine = flag.String("e", "pogreb", "database engine name. pogreb, goleveldb, bolt or badgerdb") 14 | numKeys = flag.Int("n", 5000, "number of keys") 15 | minKeySize = flag.Int("mink", 32, "minimum key size") 16 | maxKeySize = flag.Int("maxk", 64, "maximum key size") 17 | minValueSize = flag.Int("minv", 128, "minimum value size") 18 | maxValueSize = flag.Int("maxv", 1024, "maximum value size") 19 | concurrency = flag.Int("c", 3, "number of concurrent goroutines") 20 | dir = flag.String("d", "data", "database directory") 21 | progress = flag.Bool("p", false, "show progress") 22 | ) 23 | 24 | func main() { 25 | //defer profile.Start(profile.MemProfile, profile.ProfilePath(".")).Stop() 26 | flag.Parse() 27 | if *dir == "" { 28 | flag.Usage() 29 | return 30 | } 31 | 32 | // Setup monitoring 33 | go http.ListenAndServe(":1234", http.DefaultServeMux) 34 | time.Sleep(time.Second) 35 | 36 | fmt.Printf("Number of keys: %d\n", *numKeys) 37 | fmt.Printf("Minimum key size: %d, maximum key size: %d\n", *minKeySize, *maxKeySize) 38 | fmt.Printf("Minimum value size: %d, maximum value size: %d\n", *minValueSize, *maxValueSize) 39 | fmt.Printf("Concurrency: %d\n", *concurrency) 40 | fmt.Println() 41 | 42 | for engine := range engines { 43 | if err := benchmark(engine, *dir, *numKeys, *minKeySize, *maxKeySize, *minValueSize, *maxValueSize, *concurrency, *progress); err != nil { 44 | fmt.Fprintln(os.Stderr, err) 45 | } 46 | 47 | fmt.Println() 48 | time.Sleep(time.Second * 3) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/pogreb.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "time" 6 | 7 | "github.com/akrylysov/pogreb" 8 | "github.com/akrylysov/pogreb/fs" 9 | ) 10 | 11 | func newPogreb(path string) (kvEngine, error) { 12 | opt := &pogreb.Options{FileSystem: fs.OS} 13 | opt.BackgroundSyncInterval = time.Second 14 | db, err := pogreb.Open(path, opt) 15 | return &pogrebEngine{db, path}, err 16 | } 17 | 18 | type pogrebEngine struct { 19 | *pogreb.DB 20 | path string 21 | } 22 | 23 | func (db *pogrebEngine) Cleanup() error { 24 | err := os.RemoveAll(db.path) 25 | if err == nil { 26 | err = os.Remove(db.path + ".index") 27 | } 28 | return err 29 | } 30 | -------------------------------------------------------------------------------- /cmd/pogreb-bench/tiedot.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/binary" 5 | "os" 6 | 7 | tiedot "github.com/HouzuoGuo/tiedot/db" 8 | ) 9 | 10 | /* 11 | * This test is super-wonky and only for very rough comparison as tiedot is a 12 | * document engine, not a key-value store. And we're not testing it correctly 13 | * anyway. 14 | */ 15 | 16 | var tiedotBucketName = "benchmark" 17 | 18 | func newTiedot(path string) (kvEngine, error) { 19 | db, err := tiedot.OpenDB(path) 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | // Second run this already exists 25 | _ = db.Create(tiedotBucketName) 26 | 27 | bucket := db.Use(tiedotBucketName) 28 | 29 | return &tiedotEngine{db: db, bucket: bucket, path: path}, err 30 | } 31 | 32 | type tiedotEngine struct { 33 | path string 34 | db *tiedot.DB 35 | bucket *tiedot.Col 36 | } 37 | 38 | // Not really fair to compare a document store to a key-value store 39 | func (db *tiedotEngine) Put(key []byte, value []byte) error { 40 | _, err := db.bucket.Insert(map[string]interface{}{ 41 | string(key): value, 42 | }) 43 | return err 44 | } 45 | 46 | func (db *tiedotEngine) Get(key []byte) ([]byte, error) { 47 | // Overflows for non-32 bit keys, but we don't care 48 | id := binary.BigEndian.Uint32(key) 49 | val, _ := db.bucket.Read(int(id)) 50 | 51 | // This will never work 52 | if val, ok := val["whytry"]; ok { 53 | return val.([]byte), nil 54 | } 55 | 56 | return []byte("lies, all lies"), nil 57 | } 58 | 59 | func (db *tiedotEngine) Close() error { 60 | return db.db.Close() 61 | } 62 | 63 | func (db *tiedotEngine) FileSize() (int64, error) { 64 | return dirSize(db.path) 65 | } 66 | 67 | func (db *tiedotEngine) Cleanup() error { 68 | return os.RemoveAll(db.path) 69 | } 70 | --------------------------------------------------------------------------------