Creating a user with database access

@mattvardi i am trying to save users and roles with many to many relationship using GORM but it always throw duplicate key error my code is

admin_role := Role {ID: 1, Name: “Admin”, LoweredRoleName: “admin”}
db.Create(&admin_role)

db.Create(&User{ID:1, FirstName: “fname”, LastName: “lname”, Email:"email@abc.com", Roles: []Role{admin_role} })

above code through " pq: duplicate key value (id)=(1) violates unique constraint “primary”

Primary keys must be unique, in order to create this many to many relationship you should use a foreign key.

@mattvardi Normally i used to auto generate primary key with int datatype as identity which incremented by 1 with each new record in SQL server.

How can i implement same with cockroach i have checked and serial and unique_rowid() but it generate random (like 475763863047700481) int number but i want in sequence like 1,2 3, and so on

Also if i am going to use uuid for primary key then is there any default mechanism to generate uuid automatically on insertion with gorm or any recommended package ?

Thanks

Hey @muhammad.habib,

If you want a sequence to increment by +1 every time, i suggest you use CREATE SEQUENCE <seq_name>, the default setting should increment by one. The idea is to use nextval() in your create table.

See this for more information.

However, I reccomend using UUID’s for optimal performance. To use a UUID in gorm here is a medium article that should be helpful.

If you were to use the go pq driver you could use SQL syntax to specify your column type as UUID. For example: "CREATE TABLE IF NOT EXISTS test_table (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), value STRING NULL)")

Let me know if you have other questions.

Thanks,
Matt

Hi @mattvardi yet not received any information on this…

Hi @muhammad.habib,

What information are you referring to?

about pricing for Enterprise and managed.

Weird, our records show we reached out.

No worries, we will send you another email.

Thank you,
Matt