MCPcopy Index your code
hub / github.com/nutsdb/nutsdb / multipleOperationsExample

Function multipleOperationsExample

examples/watcher/main.go:107–185  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

105}
106
107func multipleOperationsExample() {
108 fmt.Println("--- Example 2: Watch Multiple Operations ---")
109 key := []byte("multi_op_key")
110 done := make(chan struct{})
111 ctx, cancel := context.WithCancel(context.Background())
112 mu := sync.Mutex{}
113
114 messageCount := 0
115 watcher, err := db.Watch(ctx, bucket, key, func(msg *nutsdb.Message) error {
116 mu.Lock()
117 defer mu.Unlock()
118
119 messageCount++
120 fmt.Printf("[Watch] Operation #%d: ", messageCount)
121
122 switch msg.Flag {
123 case nutsdb.DataSetFlag:
124 fmt.Printf("SET - Value: %s\n", string(msg.Value))
125 case nutsdb.DataDeleteFlag:
126 fmt.Printf("DELETE - Key: %s\n", msg.Key)
127 }
128
129 if messageCount >= 3 {
130 cancel()
131 close(done)
132 }
133 return nil
134 })
135
136 if err != nil {
137 log.Fatal(err)
138 }
139
140 go func() {
141 if err := watcher.Run(); err != nil {
142 log.Fatal(err)
143 }
144 }()
145
146 if err := watcher.WaitReady(10 * time.Second); err != nil {
147 log.Fatal(err)
148 }
149
150 // Perform multiple operations
151 operations := []struct {
152 action string
153 value string
154 }{
155 {"put", "First value"},
156 {"put", "Updated value"},
157 {"delete", ""},
158 }
159
160 for _, op := range operations {
161 switch op.action {
162 case "put":
163 if err := db.Update(func(tx *nutsdb.Tx) error {
164 return tx.Put(bucket, key, []byte(op.value), nutsdb.Persistent)

Callers 1

mainFunction · 0.85

Calls 7

WatchMethod · 0.80
RunMethod · 0.80
WaitReadyMethod · 0.80
UpdateMethod · 0.80
PrintfMethod · 0.65
DeleteMethod · 0.65
PutMethod · 0.45

Tested by

no test coverage detected