github.com/blong14/gache@v0.0.0-20240124023949-89416fd8bbfa/internal/proxy/table.go (about) 1 package proxy 2 3 import ( 4 "context" 5 "fmt" 6 gdb "github.com/blong14/gache/internal/db" 7 gerrors "github.com/blong14/gache/internal/errors" 8 ) 9 10 type Table struct { 11 impl gdb.Table 12 name []byte 13 } 14 15 func NewTable(opts *gdb.TableOpts) *Table { 16 return &Table{ 17 name: opts.TableName, 18 impl: gdb.New(opts), 19 } 20 } 21 22 func (va *Table) Execute(_ context.Context, query *gdb.Query) { 23 switch query.Header.Inst { 24 case gdb.GetValue: 25 var resp gdb.QueryResponse 26 if value, ok := va.impl.Get(query.Key); ok { 27 resp = gdb.QueryResponse{ 28 Key: query.Key, 29 Value: value, 30 RangeValues: [][][]byte{{query.Key, value}}, 31 Stats: gdb.QueryStats{ 32 Count: 1, 33 }, 34 Success: true, 35 } 36 } 37 query.Done(resp) 38 case gdb.Count: 39 count := va.impl.Count() 40 query.Done( 41 gdb.QueryResponse{ 42 RangeValues: [][][]byte{ 43 {[]byte("count"), []byte(fmt.Sprintf("%d", count))}, 44 }, 45 Stats: gdb.QueryStats{ 46 Count: uint(count), 47 }, 48 Success: true, 49 }, 50 ) 51 case gdb.GetRange: 52 var resp gdb.QueryResponse 53 values, ok := va.impl.ScanWithLimit( 54 query.KeyRange.Start, query.KeyRange.End, query.KeyRange.Limit) 55 if ok { 56 resp = gdb.QueryResponse{ 57 RangeValues: values, 58 Stats: gdb.QueryStats{ 59 Count: uint(len(values)), 60 }, 61 Success: true, 62 } 63 } 64 query.Done(resp) 65 case gdb.SetValue: 66 var resp gdb.QueryResponse 67 if err := va.impl.Set(query.Key, query.Value); err == nil { 68 resp = gdb.QueryResponse{ 69 Key: query.Key, 70 Value: query.Value, 71 Stats: gdb.QueryStats{ 72 Count: 1, 73 }, 74 Success: true, 75 } 76 } 77 query.Done(resp) 78 case gdb.BatchSetValue: 79 var errs *gerrors.Error 80 for _, kv := range query.Values { 81 if kv.Valid() { 82 errs = gerrors.Append(errs, va.impl.Set(kv.Key, kv.Value)) 83 } 84 } 85 var resp gdb.QueryResponse 86 if errs.ErrorOrNil() == nil { 87 resp = gdb.QueryResponse{ 88 Stats: gdb.QueryStats{ 89 Count: uint(len(query.Values)), 90 }, 91 Success: true, 92 } 93 } 94 query.Done(resp) 95 default: 96 } 97 } 98 99 func (va *Table) Stop() { 100 va.impl.Close() 101 }