Home Download Docs Code Community
     1	/*
     2	Copyright 2013 The Perkeep Authors.
     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 kvutil contains helpers related to
    18	// modernc.org/kv.
    19	package kvutil // import "perkeep.org/pkg/kvutil"
    20	
    21	import (
    22		"fmt"
    23		"io"
    24		"os"
    25		"strconv"
    26	
    27		"go4.org/lock"
    28		"modernc.org/kv"
    29	)
    30	
    31	// Open opens the named kv DB file for reading/writing. It
    32	// creates the file if it does not exist yet.
    33	func Open(dbFile string, opts *kv.Options) (*kv.DB, error) {
    34		createOpen := kv.Open
    35		verb := "opening"
    36		if _, err := os.Stat(dbFile); os.IsNotExist(err) {
    37			createOpen = kv.Create
    38			verb = "creating"
    39		}
    40		if opts == nil {
    41			opts = &kv.Options{}
    42		}
    43		if opts.Locker == nil {
    44			opts.Locker = func(dbFile string) (io.Closer, error) {
    45				lkfile := dbFile + ".lock"
    46				cl, err := lock.Lock(lkfile)
    47				if err != nil {
    48					return nil, fmt.Errorf("failed to acquire lock on %s: %v", lkfile, err)
    49				}
    50				return cl, nil
    51			}
    52		}
    53		if v, _ := strconv.ParseBool(os.Getenv("CAMLI_KV_VERIFY")); v {
    54			opts.VerifyDbBeforeOpen = true
    55			opts.VerifyDbAfterOpen = true
    56			opts.VerifyDbBeforeClose = true
    57			opts.VerifyDbAfterClose = true
    58		}
    59		db, err := createOpen(dbFile, opts)
    60		if err != nil {
    61			return nil, fmt.Errorf("error %s %s: %v", verb, dbFile, err)
    62		}
    63		return db, nil
    64	}
Website layout inspired by memcached.
Content by the authors.