Google数据存储中唯一的电子邮件 [英] Unique email in Google Datastore
问题描述
我有一个包含电子邮件
字段的用户
实体。 用户
实体ID是 ULID ,因为我想允许用户更改他们的电子邮件地址,但我想确保电子邮件地址在 CREATE
和 UPDATE
。
我正在使用数据存储事务。这是一段代码片段:
ctx:= context.Background()
k:= datastore.NameKey(User ,user.ID,nil)
_,err:= client.RunInTransaction(ctx,func(t * datastore.Transaction)错误{
//需要在事务中的其他东西
_,err = t.Put(k,user)
return err
})
return err
电子邮件
字段已建立索引。是否有任何方法可以搜索当前用户的电子邮件地址作为交易的一部分用户
实体?
* datastore.Transaction
没有 GetAll
方法,所以我不能运行这样的查询:
datastore.NewQuery(User)。Filter(Email =,user.Email)
恐怕使用
客户端。 GetAll(ctx,q,nil)
不保证事务内的隔离。 b $ b
解决方案简短答案是否定的,除非您查询特定的实体组,否则不能将查询用作事务的一部分。全局查询总是一致的。但是,将所有内容放入单个实体组中可能会限制写入吞吐量。
解决方法是您可以使用另一种类型的实体将电子邮件地址映射到用户。然后,您可以在交易中检查电子邮件实体,如果该电子邮件实体不存在或它指向不合适的位置,请将电子邮件实体和用户实体全部设置为单个交易。
I have a
User
entity containing anUser
entity id is a ULID, because I want to allow users to change their email addresses, but I want to ensure that the email address is unique on both aCREATE
and anUPDATE
.I am using Datastore transactions. This is a code fragment:
ctx := context.Background() k := datastore.NameKey("User", user.ID, nil) _, err := client.RunInTransaction(ctx, func(t *datastore.Transaction) error { // other stuff that needs to be in transaction _, err = t.Put(k, user) return err }) return err
The
User
entity for the current user's email address as part of the transaction?
*datastore.Transaction
does not have aGetAll
method, so I cannot run a query like this:datastore.NewQuery("User").Filter("Email =", user.Email)
I'm afraid that using
client.GetAll(ctx, q, nil)
will not guarantee isolation within the transaction.
解决方案The short answer is no, you cannot use a query as part of a transaction unless you are querying a specific entity group. Global queries are alway eventually consistent. However, to put everything in a single entity group would likely limit write throughput too much.
A workaround is you can have another Kind with entities that map email addresses to users. Then you can, in a transaction, check the email Entity and if it doesn't exist or it points to a bad location, set the email Entity and the user Entity all as a single transaction.
这篇关于Google数据存储中唯一的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!