Put sets the value for a key in the bucket. If the key exist then its previous value will be overwritten. Supplied value must remain valid for the life of the transaction. Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the
(key []byte, value []byte)
| 450 | // Supplied value must remain valid for the life of the transaction. |
| 451 | // Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large. |
| 452 | func (b *Bucket) Put(key []byte, value []byte) (err error) { |
| 453 | if lg := b.tx.db.Logger(); lg != discardLogger { |
| 454 | lg.Debugf("Putting key %q", key) |
| 455 | defer func() { |
| 456 | if err != nil { |
| 457 | lg.Errorf("Putting key %q failed: %v", key, err) |
| 458 | } else { |
| 459 | lg.Debugf("Putting key %q successfully", key) |
| 460 | } |
| 461 | }() |
| 462 | } |
| 463 | if b.tx.db == nil { |
| 464 | return errors.ErrTxClosed |
| 465 | } else if !b.Writable() { |
| 466 | return errors.ErrTxNotWritable |
| 467 | } else if len(key) == 0 { |
| 468 | return errors.ErrKeyRequired |
| 469 | } else if len(key) > MaxKeySize { |
| 470 | return errors.ErrKeyTooLarge |
| 471 | } else if int64(len(value)) > MaxValueSize { |
| 472 | return errors.ErrValueTooLarge |
| 473 | } |
| 474 | |
| 475 | // Insert into node. |
| 476 | // Tip: Use a new variable `newKey` instead of reusing the existing `key` to prevent |
| 477 | // it from being marked as leaking, and accordingly cannot be allocated on stack. |
| 478 | newKey := cloneBytes(key) |
| 479 | |
| 480 | // Move cursor to correct position. |
| 481 | c := b.Cursor() |
| 482 | k, _, flags := c.seek(newKey) |
| 483 | |
| 484 | // Return an error if there is an existing key with a bucket value. |
| 485 | if bytes.Equal(newKey, k) && (flags&common.BucketLeafFlag) != 0 { |
| 486 | return errors.ErrIncompatibleValue |
| 487 | } |
| 488 | |
| 489 | // gofail: var beforeBucketPut struct{} |
| 490 | |
| 491 | c.node().put(newKey, newKey, value, 0, 0) |
| 492 | |
| 493 | return nil |
| 494 | } |
| 495 | |
| 496 | // Delete removes a key from the bucket. |
| 497 | // If the key does not exist then nothing is done and a nil error is returned. |