Custom fromSqlKey

Skip to first unread message

Nov 11, 2021, 11:52:38 AM11/11/21
to Yesod Web Framework
Guys, how do I make a custom version of the 'fromSqlKey' function?

I'm using a 'uuid' as a key in the table and I wanted to convert an entity into the model. For this I did this function:

  fromEntity e = let value = entityVal e
                 in  CadastrosModel { id = fromSqlKey (entityKey  e)
                                 , email = cadastrosEmail value
                                 , cnpjCpf = cadastrosCnpjCpf value
                                 , password = cadastrosPassword value

But fromSqlKey returns Int64. Is there any way to make uuid return?

The complete context is this:

Nov 12, 2021, 6:29:04 AM11/12/21
to Yesod Web Framework
Why do you need the fromSqlKey at all? I use it almost only for debugging purpose.

Can you just write a new function?
fromSqlKey' :: Entity YourModel -> UUID

Nov 12, 2021, 5:29:01 PM11/12/21
to Yesod Web Framework
But that's where I got stuck. I have:

fromEntity e = ...

therefore 'e' is a Entity  record.

From the documentation I saw these two gets:
entityVal works. My record is a Cadastro according to the model:

Cadastros json
    Id UUID  sqltype=uuid   default=uuid_generate_v4()
    email Text
    cnpjCpf Text
    password Text
    deriving Typeable

There is still the question of how to get the value of the Key record

For those who are not key, I only have a record and then I can use, for example, cadastrosPassword. But what about the key?

Nov 13, 2021, 4:26:17 AM11/13/21
to Yesod Web Framework
I read a few times but still don't really understand.

One important thing though: To my knowledge,
CadastrosId is an auto-generated alias for  Key Cadastros.
The id field is normally not in the model definition! It's auto-generated and it's always Int64 in Persistent.

So, to avoid name collissions, I strongly recommend to rename your custom Id field to e.g. id2.

You can add to your model definition:

  id2 UUID sqltype=uuid …
  UniqueId2 id2

The second line makes a unique index. Then you can use
getBy (UniqueId2 yourId)

To get your Id from an Entity, use this:

(cadastrosId2 . entityVal)

To get the real Int64 Persist Key, use entityKey

OK, the docs for Key rec say:

> By default, a backend will automatically generate the key Instead you can specify a Primary key made up of unique values.

So this behavior might can be changed, but I'd stick to the default and can only recommend this article:

Nov 14, 2021, 1:18:44 PM11/14/21
to Yesod Web Framework
I think I understand your question better now. I just stumbled upon the documentation "Custom ID column" at

fromSqlKey doesn't work because it returns Int64...

Don't you use the QuasiQuoter model definition for your Persist setup? In that case, have you used an upper-case i in the custom ID column definition?
Reply all
Reply to author
0 new messages