登录
首页 >  Golang >  Go问答

Golang BoltDB 删除键似乎无效

来源:stackoverflow

时间:2024-02-13 08:54:23 443浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《Golang BoltDB 删除键似乎无效》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

centos 7,github boltdb/bolt 版本 1.3.1,go 版本 go1.17.7 linux/amd64

这个问题可能是对 boltdb 工作原理的误解,或者可能是我有一个错误,或者可能是存在问题。我以前使用过boltdb,并且取得了很好的效果。不过,我并没有明确寻找这个问题。我看到的是,我尝试从存储桶中删除一个键,并且该键及其值在活动 db.update 中被删除,但在 db.update 结束后它仍然存在。寻找可能发生的事情的任何解释。看来这个功能不可能被破坏。

我正在使用 boltdb 存储桶来存储与电子邮件地址关联的临时令牌,以创建新帐户。想要立即整洁并清理旧数据(过期的令牌、滥用的令牌等)。相当标准的东西。临时token的结构为(key为临时token,10位随机字符串):

(临时token就是bucket key)

type temptokenstruct struct {

emailaddress        string   `json:"emailaddress"`        // email address to be changed 

tokenexpirytime     int64    `json:"tokenexpirytime"`     // expiry time for token in epoch time

}

用户在网络表单中输入电子邮件地址并点击“提交”。这将创建对 rest 服务的调用,该服务会在临时令牌表中创建一个条目,例如:

“bplnfgdsc2”=> [电子邮件受保护],1645650084

该服务通过电子邮件发送一个嵌入临时令牌的 url,该链接将用户带到一个表单,允许他们输入电子邮件地址(再次验证)和新密码(两次)。点击“提交”后,会在 web 处理程序中调用以下代码:

func checktokenvalid(emailaddress string, temptoken string) error {
var temptokendata temptokenstruct
var temptokenbytes []byte

temptokenbytes = []byte(temptoken)

db, err := bolt.open(user_db_name, 0644, nil)

if err != nil {
    return err
}

defer db.close()

err = db.update(func(tx *bolt.tx) error {
    temptokenbucket := tx.bucket([]byte("temptokens"))

    // the bucket hasn't been created, so there are no stored tokens
    if temptokenbucket == nil {
        return errors.new("not authorized (1): please request a new password new/change email from the login page.")
    }

    // there is no matching token stored in the bucket, so this is an invalid request
    temptokenjson := temptokenbucket.get(temptokenbytes)

    //[i've put a printf here: a]

    if temptokenjson == nil {
        return errors.new("not authorized (2): please request a new password new/change email from the login page.")
    }

    jsonconverterr := json.unmarshal(temptokenjson, &temptokendata)

    if jsonconverterr != nil {
        temptokenbucket.delete(temptokenbytes)
        return errors.new("not authorized (3): please request a new password new/change email from the login page.")
    }

    // check to see if the time is expired, if so, remove the key and indicate error
    if temptokendata.tokenexpirytime < time.now().unix() {
        temptokenbucket.delete(temptokenbytes)

        //[i've put a printf here: b]

        return errors.new("not authorized (4): please request a new password new/change email from the login page.")
    }

    // check to see if the email addresses match
    if emailaddress != temptokendata.emailaddress {
        temptokenbucket.delete(temptokenbytes)
        return errors.new("not authorized (5): please request a new password new/change email from the login page.")
    }

    temptokenbucket.delete(temptokenbytes)
    return nil
})

// this is test code to see if the key was in fact deleted
db.update(func(tx *bolt.tx) error {
    temptokenbucket := tx.bucket([]byte("temptokens"))
    temptokenjson := temptokenbucket.get(temptokenbytes)

    // [i've put a printf here: c]

    return nil
})

return err
}

我正在使用超时令牌 (4) 进行测试,因此当它遇到超时令牌时,它希望从存储桶中删除这个现在无效的令牌。

在 a 位置,它打印: 首先获取调用令牌 bplnfgdsc2 为 {"emailaddress":"[email protected]","tokenexpirytime":1645650084}

在 b 位置,我放入了执行 .get 的代码,它打印出来(看起来已被删除): db关闭前(4),删除后,token bplnfgdsc2为

在c位置,它打印(看起来又回来了): db 关闭后,令牌 bplnfgdsc2 为 {"emailaddress":"[email protected]","tokenexpirytime":1645650084}

没有任何错误返回。我已经重复了很多次,将 fmt.printfs 放在各处以查看发生了什么。结果是一样的,密钥似乎没有被删除。之后,我“vi -b”数据库文件,键值仍然存在。它坐下后运行,它仍然看到那里的键值。我很困惑,任何指示将不胜感激。

更新:put/get/delete/get 的基本 bolt 功能按照此测试代码工作(应该是显而易见的):

package main

import "fmt"
import "encoding/json"
import "github.com/boltdb/bolt"

type tempTokenStruct struct {
EmailAddress        string   `json:"emailaddress"`        // Email Address to be changed (Temporary Token is the DB key)
TokenExpiryTime     int64    `json:"tokenexpirytime"`     // Expiry Time for token in Epoch time
}


func main() {
    var tempToken tempTokenStruct

    tempToken.EmailAddress = "[email protected]"
    tempToken.TokenExpiryTime = 1234567890

    tempTokenDataJSON, jsonMarshalError := json.Marshal(tempToken)

    if jsonMarshalError != nil {
            fmt.Printf("JSON Marshal Error: %s\n", jsonMarshalError.Error())
            return
    }

    tempTokenKey := []byte("foo")

db, err := bolt.Open("test.db", 0644, nil)

if err != nil {
            fmt.Printf("Error opening Database\n")
    return
}

defer db.Close()

// Put a key in the table
err = db.Update(func(tx *bolt.Tx) error {
    tempTokenBucket, err := tx.CreateBucketIfNotExists([]byte("temptokens"))

    if err != nil {
        return err
    }

    dbPutError := tempTokenBucket.Put(tempTokenKey, []byte(tempTokenDataJSON))

    return dbPutError
})

    if err != nil {
            fmt.Printf("Error putting key value pair into table: %s\n", err.Error())
    }

    // Check if the key/value is there after putting it in
err = db.Update(func(tx *bolt.Tx) error {
    tempTokenBucket, err := tx.CreateBucketIfNotExists([]byte("temptokens"))

    if err != nil {
        return err
    }

    valueGet := tempTokenBucket.Get(tempTokenKey)

            fmt.Printf("Value for Token: \"%s\" is \"%s\" just after putting it in there\n", tempTokenKey, valueGet)

    return nil
})

    // Delete that key from the table
err = db.Update(func(tx *bolt.Tx) error {
    tempTokenBucket, err := tx.CreateBucketIfNotExists([]byte("temptokens"))

    if err != nil {
        return err
    }

    dbDeleteError := tempTokenBucket.Delete(tempTokenKey)

    return dbDeleteError
})

    if err != nil {
            fmt.Printf("Error Deleting key from bucket: %s\n", err.Error())
    }

    // Check if the key/value is there after deleting it
err = db.Update(func(tx *bolt.Tx) error {
    tempTokenBucket, err := tx.CreateBucketIfNotExists([]byte("temptokens"))

    if err != nil {
        return err
    }

    valueGet := tempTokenBucket.Get(tempTokenKey)

            fmt.Printf("Value for Token: \"%s\" is \"%s\" after the delete\n", tempTokenKey, valueGet)

    return nil
})

    if err != nil {
            fmt.Printf("Error getting key from table: %s\n", err.Error())
    }
}

打印输出:

令牌的值:“foo”放入其中后为“{”emailaddress”:“[email protected]”,“tokenexpirytime”:1234567890}”

令牌的值:删除后“foo”为“”

所以,不确定为什么其他代码不起作用。几乎就像删除使用不同的密钥一样,但该密钥在其他代码中是相同的。


正确答案


我相信 db.update 具有非零返回值的行为是这里的混乱。根据the docs

在闭包内,您可以看到一致的数据库视图。您通过在最后返回 nil 来提交交易。您还可以随时通过返回错误来回滚事务。

您返回的错误为:

return errors.new("not authorized (4): please request a new password new/change email from the login page.")

这意味着 db.update( 中的所有操作都将回滚。这可以在您的简单示例中进行少量更改来复制 (return fmt.errorf("returning error here")):

package main

import "fmt"
import "encoding/json"
import "github.com/boltdb/bolt"

type temptokenstruct struct {
    emailaddress    string `json:"emailaddress"`    // email address to be changed (temporary token is the db key)
    tokenexpirytime int64  `json:"tokenexpirytime"` // expiry time for token in epoch time
}

func main() {
    var temptoken temptokenstruct
    temptoken.emailaddress = "[email protected]"
    temptoken.tokenexpirytime = 1234567890

    temptokendatajson, jsonmarshalerror := json.marshal(temptoken)
    if jsonmarshalerror != nil {
        fmt.printf("json marshal error: %s\n", jsonmarshalerror.error())
        return
    }
    temptokenkey := []byte("foo")
    db, err := bolt.open("test.db", 0644, nil)
    if err != nil {
        fmt.printf("error opening database\n")
        return
    }
    defer db.close()

    // put a key in the table
    err = db.update(func(tx *bolt.tx) error {
        temptokenbucket, err := tx.createbucketifnotexists([]byte("temptokens"))

        if err != nil {
            return err
        }

        dbputerror := temptokenbucket.put(temptokenkey, []byte(temptokendatajson))

        return dbputerror
    })

    if err != nil {
        fmt.printf("error putting key value pair into table: %s\n", err.error())
    }

    // check if the key/value is there after putting it in
    err = db.update(func(tx *bolt.tx) error {
        temptokenbucket, err := tx.createbucketifnotexists([]byte("temptokens"))

        if err != nil {
            return err
        }

        valueget := temptokenbucket.get(temptokenkey)

        fmt.printf("value for token: \"%s\" is \"%s\" just after putting it in there\n", temptokenkey, valueget)

        return nil
    })

    // delete that key from the table
    err = db.update(func(tx *bolt.tx) error {
        temptokenbucket, err := tx.createbucketifnotexists([]byte("temptokens"))

        if err != nil {
            return err
        }
        temptokenbucket.delete(temptokenkey)
        return fmt.errorf("returning error here")  // changed here
    })

    if err != nil {
        fmt.printf("error deleting key from bucket: %s\n", err.error())
    }

    // check if the key/value is there after deleting it
    err = db.update(func(tx *bolt.tx) error {
        temptokenbucket, err := tx.createbucketifnotexists([]byte("temptokens"))
        if err != nil {
            return err
        }
        valueget := temptokenbucket.get(temptokenkey)
        fmt.printf("value for token: \"%s\" is \"%s\" after the delete\n", temptokenkey, valueget)
        return nil
    })

    if err != nil {
        fmt.printf("error getting key from table: %s\n", err.error())
    }
}

现在的输出是:

Value for Token: "foo" is "{"emailaddress":"[email protected]","tokenexpirytime":1234567890}" just after putting it in there
Error Deleting key from bucket: RETURNING ERROR HERE
Value for Token: "foo" is "{"emailaddress":"[email protected]","tokenexpirytime":1234567890}" after the delete

这似乎与您在主代码中看到的内容相符。修复相对简单 - 如果您希望提交更改,请不要返回错误。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>