github.com/zooyer/miskit@v1.0.71/imdb/driver/buntdb/buntdb.go (about)

     1  package buntdb
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/tidwall/buntdb"
     8  	"github.com/zooyer/miskit/imdb"
     9  )
    10  
    11  type buntConn struct {
    12  	db *buntdb.DB
    13  }
    14  
    15  type buntDriver int
    16  
    17  func (b buntDriver) Open(args string) (_ imdb.Conn, err error) {
    18  	var c buntConn
    19  
    20  	if c.db, err = buntdb.Open(args); err != nil {
    21  		return
    22  	}
    23  
    24  	return &c, nil
    25  }
    26  
    27  func (c buntConn) Get(ctx context.Context, key string) (value string, err error) {
    28  	if err = c.db.View(func(tx *buntdb.Tx) error {
    29  		if value, err = tx.Get(key); err != nil && err != buntdb.ErrNotFound {
    30  			return err
    31  		}
    32  		return nil
    33  	}); err != nil {
    34  		return
    35  	}
    36  
    37  	return
    38  }
    39  
    40  func (c buntConn) Set(ctx context.Context, key, value string) (err error) {
    41  	if err = c.db.Update(func(tx *buntdb.Tx) error {
    42  		if _, _, err = tx.Set(key, value, nil); err != nil {
    43  			return err
    44  		}
    45  		return nil
    46  	}); err != nil {
    47  		return
    48  	}
    49  
    50  	return
    51  }
    52  
    53  func (c buntConn) SetEx(ctx context.Context, key, value string, seconds int64) (err error) {
    54  	if err = c.db.Update(func(tx *buntdb.Tx) error {
    55  		var options = buntdb.SetOptions{
    56  			Expires: seconds > 0,
    57  			TTL:     time.Second * time.Duration(seconds),
    58  		}
    59  		if _, _, err = tx.Set(key, value, &options); err != nil {
    60  			return err
    61  		}
    62  		return nil
    63  	}); err != nil {
    64  		return
    65  	}
    66  
    67  	return
    68  }
    69  
    70  func (c buntConn) Del(ctx context.Context, key string) (err error) {
    71  	if err = c.db.Update(func(tx *buntdb.Tx) error {
    72  		if _, err = tx.Delete(key); err != nil && err != buntdb.ErrNotFound {
    73  			return err
    74  		}
    75  		return nil
    76  	}); err != nil {
    77  		return
    78  	}
    79  
    80  	return
    81  }
    82  
    83  func (c buntConn) TTL(ctx context.Context, key string) (seconds int64, err error) {
    84  	if err = c.db.Update(func(tx *buntdb.Tx) error {
    85  		var ttl time.Duration
    86  		if ttl, err = tx.TTL(key); err != nil {
    87  			if err == buntdb.ErrNotFound {
    88  				seconds = -2
    89  				return nil
    90  			}
    91  			return err
    92  		}
    93  
    94  		seconds = int64(ttl.Seconds())
    95  
    96  		return nil
    97  	}); err != nil {
    98  		return
    99  	}
   100  
   101  	return
   102  }
   103  
   104  func init() {
   105  	imdb.Register("buntdb", new(buntDriver))
   106  }