github.com/cayleygraph/cayley@v0.7.7/graph/kv/bolt/bolt.go (about)

     1  // Copyright 2016 The Cayley Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package bolt
    16  
    17  import (
    18  	"os"
    19  	"path/filepath"
    20  
    21  	"github.com/cayleygraph/cayley/clog"
    22  	"github.com/cayleygraph/cayley/graph"
    23  	"github.com/cayleygraph/cayley/graph/kv"
    24  	hkv "github.com/hidal-go/hidalgo/kv"
    25  	"github.com/hidal-go/hidalgo/kv/bolt"
    26  )
    27  
    28  func init() {
    29  	// override implementation; hidalgo expects a path to a database file,
    30  	// while cayley was using path/index.bolt file previously
    31  	kv.Register(Type, kv.Registration{
    32  		NewFunc:      Open,
    33  		InitFunc:     Create,
    34  		IsPersistent: true,
    35  	})
    36  }
    37  
    38  const (
    39  	Type = bolt.Name
    40  )
    41  
    42  func getBoltFile(cfgpath string) string {
    43  	return filepath.Join(cfgpath, "indexes.bolt")
    44  }
    45  
    46  func Create(path string, _ graph.Options) (hkv.KV, error) {
    47  	err := os.MkdirAll(path, 0700)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	db, err := bolt.Open(getBoltFile(path), nil)
    52  	if err != nil {
    53  		clog.Errorf("Error: couldn't create Bolt database: %v", err)
    54  		return nil, err
    55  	}
    56  	return db, nil
    57  }
    58  
    59  func Open(path string, opt graph.Options) (hkv.KV, error) {
    60  	db, err := bolt.Open(getBoltFile(path), nil)
    61  	if err != nil {
    62  		clog.Errorf("Error, couldn't open! %v", err)
    63  		return nil, err
    64  	}
    65  	bdb := db.DB()
    66  	// BoolKey returns false on non-existence. IE, Sync by default.
    67  	bdb.NoSync, err = opt.BoolKey("nosync", false)
    68  	if err != nil {
    69  		db.Close()
    70  		return nil, err
    71  	}
    72  	bdb.NoGrowSync = bdb.NoSync
    73  	if bdb.NoSync {
    74  		clog.Infof("Running in nosync mode")
    75  	}
    76  	return db, nil
    77  }