github.com/ledgerwatch/erigon-lib@v1.0.0/kv/mdbx/util.go (about)

     1  /*
     2     Copyright 2021 Erigon contributors
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package mdbx
    18  
    19  import (
    20  	mdbxbind "github.com/erigontech/mdbx-go/mdbx"
    21  	"github.com/ledgerwatch/erigon-lib/kv"
    22  	"github.com/ledgerwatch/log/v3"
    23  )
    24  
    25  func MustOpen(path string) kv.RwDB {
    26  	db, err := Open(path, log.New(), false)
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  	return db
    31  }
    32  
    33  func MustOpenRo(path string) kv.RoDB {
    34  	db, err := Open(path, log.New(), true)
    35  	if err != nil {
    36  		panic(err)
    37  	}
    38  	return db
    39  }
    40  
    41  // Open - main method to open database.
    42  func Open(path string, logger log.Logger, readOnly bool) (kv.RwDB, error) {
    43  	var db kv.RwDB
    44  	var err error
    45  	opts := NewMDBX(logger).Path(path)
    46  	if readOnly {
    47  		opts = opts.Flags(func(flags uint) uint { return flags | mdbxbind.Readonly })
    48  	}
    49  	db, err = opts.Open()
    50  
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  	return db, nil
    55  }