Cannot retrieve inserted row when using UUID as primary key #340
-
DescriptionI'm encountering an issue when trying to create a record with a UUID primary key using Bob ORM. While the system works fine with auto-increment columns, it fails when using UUID as the primary key. Environment
Database Schemacreate table api_keys
(
id binary(16) default (uuid_to_bin(uuid(), 1)) not null
primary key,
`key` varchar(64) not null,
secret varchar(255) null,
constraint api_keys_key_uniq
unique (`key`)
)
row_format = DYNAMIC; Code Examplef := factory.New()
createdAPIKey, err := f.NewAPIKey().Create(ctx, writerBob)
require.NoError(t, err) Error Message
Looking at the source code in dialect/mysql/table.go, it appears that the issue occurs because: The system checks for autoIncrementColumn first, which is empty in this case if t.autoIncrementColumn != "" {
lastID, err := results[i].LastInsertId()
if err != nil {
return nil, err
}
autoIncrArgs = append(autoIncrArgs, Arg(lastID))
} else {
uIdx, uArgs := t.uniqueSet(w, val)
if uIdx == -1 || len(uArgs) == 0 {
return nil, orm.ErrCannotRetrieveRow
}
idArgs[uIdx] = append(idArgs[uIdx], ArgGroup(internal.ToAnySlice(uArgs)...))
} Questions
Additional ContextThe system works fine with auto-increment primary keys, but fails specifically with UUID primary keys. This seems to be related to how the ORM handles record retrieval after insertion when using non-auto-increment unique identifiers. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
So............................. this is a limitation of MySQL. MySQL does not support the IF a table has an auto increment field, we can use If not, Bob tries to see if you have set any unique rows while inserting. For example, if However, in this case, you are not manually setting any unique rows (the UUID is set by default), so there is no way for Bob to retrieve what row was inserted. If using the factory, you can for example add a mod to generate the UUID in code. Since Bob will then know the UUID before insertion, it will be able to retrieve it after. |
Beta Was this translation helpful? Give feedback.
So............................. this is a limitation of MySQL.
MySQL does not support the
RETURNING
clause, so it is tricky to retrieve a row that was just inserted.IF a table has an auto increment field, we can use
LastInsertID()
to retrieve this.If not, Bob tries to see if you have set any unique rows while inserting. For example, if
email
is a unique field and you insert a row with the email [email protected], then Bob can try to retrieve the row with that email and guarantee that it was the row that was just inserted.However, in this case, you are not manually setting any unique rows (the UUID is set by default), so there is no way for Bob to retrieve what row was inserted.
If us…