ntrrg / usersd
1
// Copyright 2019 Miguel Angel Rivera Notararigo. All rights reserved.
2
// This source code was released under the MIT license.
3

4
package sdb
5

6
import (
7
	"io/ioutil"
8
	"log"
9

10
	"github.com/blevesearch/bleve"
11
	"github.com/dgraph-io/badger/v2"
12
	"github.com/dgraph-io/badger/v2/options"
13
	ntbytes "nt.web.ve/go/ntgo/bytes"
14
)
15

16
// DB is a database object which provides database management methods, for data
17
// management see Tx.
18
type DB struct {
19
	opts Options
20

21
	db *badger.DB
22
	si bleve.Index
23

24
	buffers *ntbytes.BufferPool
25
	logger  *log.Logger
26
}
27

28
// Open initializes a database in the given directory.
29 1
func Open(dir string) (*DB, error) {
30 1
	var err error
31

32 1
	if dir == "" {
33 1
		dir, err = ioutil.TempDir("", "sdb")
34 1
		if err != nil {
35 1
			return nil, err
36
		}
37
	}
38

39 1
	opts := DefaultOptions(dir)
40

41 1
	return OpenWith(opts)
42
}
43

44
// OpenWith initializes a database with the given options.
45 1
func OpenWith(opts Options) (*DB, error) {
46 1
	var err error
47

48 1
	db := new(DB)
49

50 1
	db.buffers = ntbytes.NewBufferPool(
51 1
		opts.BufferPoolSize,
52 1
		opts.BufferPoolMaxBytes,
53 1
	)
54

55 1
	if opts.BufferPoolFill {
56 1
		db.buffers.Fill()
57
	}
58

59 1
	db.logger = opts.Logger
60

61 1
	if db.db, err = openDB(opts.Badger); err != nil {
62 1
		return nil, badgerError(err)
63
	}
64

65 1
	if db.si, err = openSearchIndex(opts.Bleve); err != nil {
66 1
		return nil, bleveError(err)
67
	}
68

69 1
	db.opts = opts
70

71 1
	return db, nil
72
}
73

74
// Close terminates the database.
75 1
func (db *DB) Close() error {
76 1
	if err := db.db.Close(); err != nil {
77 0
		return badgerError(err)
78
	}
79

80 1
	_, kvs, err := db.si.Advanced()
81 1
	if err != nil {
82 0
		return bleveError(err)
83
	}
84

85 1
	if err = kvs.Close(); err != nil {
86 0
		return bleveError(err)
87
	}
88

89 1
	return nil
90
}
91

92 1
func openDB(opts badger.Options) (*badger.DB, error) {
93 1
	opts.Logger = &bl{}
94 1
	opts.Compression = options.Snappy
95

96 1
	return badger.Open(opts)
97
}
98

99 1
func openSearchIndex(opts BleveOptions) (bleve.Index, error) {
100 1
	index, err := bleve.Open(opts.Dir)
101 1
	if err == bleve.Error(1) { // ErrorIndexPathDoesNotExist
102 1
		mapping := bleve.NewIndexMapping()
103 1
		mapping.TypeField = opts.DoctypeField
104

105 1
		for t, m := range opts.DocMappings {
106 1
			mapping.AddDocumentMapping(t, m)
107
		}
108

109 1
		return bleve.New(opts.Dir, mapping)
110
	}
111

112 1
	return index, err
113
}
114

115
type bl struct{}
116

117 0
func (l *bl) Errorf(f string, v ...interface{})   {}
118 0
func (l *bl) Warningf(f string, v ...interface{}) {}
119 1
func (l *bl) Infof(f string, v ...interface{})    {}
120 1
func (l *bl) Debugf(f string, v ...interface{})   {}

Read our documentation on viewing source code .

Loading