douwen5681 2016-10-15 22:15
浏览 174
已采纳

如何确保NoSQL记录中的属性的唯一性(Golang + tiedot)

I'm working on a simple application written in golang, using tiedot as NoSQL database engine. I need to store some users in the database.

type User struct {
    Login        string
    PasswordHash string
    Salt         string
}

Of course two users cannot have the same login, and - as this engine does not provide any transaction mechanism - I'm wondering how to ensure that there's no duplicated login in the database when writing.

I first thought that I could just search for user by login before inserting, but as the database will be used concurently, it is not reliable.

Maybe I could wait for a random time and if there is another user with the same login in the collection, delete it, but that does not sound reliable either.

Is this even possible, or should I switch to a database engine that support transactions ?

  • 写回答

2条回答 默认 最新

  • dongluoheng3324 2016-10-16 16:17
    关注

    I first thought that I could just search for user by login before inserting, but as the database will be used concurently, it is not reliable.

    Right, it creates a race condition. The only way to resolve this is:

    1. Lock the table
    2. Search for the login
    3. Insert if the login is not found
    4. Unlock the table

    Table-locks are not a scalable solution, because it creates an expensive bottleneck in your application. It's why non-transactional storage engines like MySQL's MyISAM are being phased out. It's why MongoDB has to use clusters to scale up.

    It can work if you have a small dataset size and a light amount of concurrency, so perhaps it's adequate for login creation on a lightly-used website. New logins probably aren't created so frequently that they need to scale up so much.

    But users logging in, or password changes, or other changes to account attributes, do happen more frequently.

    The solution for this is to make this operation atomic, to avoid race conditions. For example, attempt the insert and have the database engine verify uniqueness and reject the insert if it violates that constraint.

    Unfortunately, I don't see any documentation in tiedot that shows that it supports a unique constraint or a uniqueness enforcement on indexes.

    Tiedot is 98% written by a single developer, in a period of about 2 years (May 2013 - April 2015). Very little activity since then (see https://www.openhub.net/p/tiedot). I would consider tiedot to be an experimental project, unlikely to expand in feature set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试