Create-operations overwrite existing items if hashkey is already in use. How do I prevent that?
Which Category is your question related to? @auth
Amplify CLI Version 4.46.1
Setup Assume there is a model 'Asset' with some Hash- and Sortkey. There are @auth rules on it that only allow create and read operations and forbid delete and update operations. When creating a new Asset with a unique hash- and sortkey combination, everything works as expected.
Question When creating a new asset with a hash- and sortkey combination that is already in use, the old asset gets overwritten and replaced by the new one. I would've expected AppSync to fail my create request instead because updating should be forbidden, but it seems I misunderstood the operations. What can I do to get this behaviour?
@pafflu Can you share the relevant parts of your GraphQL schema?
@edwardfoyle to reproduce that behavior, I created the following model:
type Test
@model(subscriptions: null)
@key(fields:["companyId", "sortKey"])
@auth(rules: [
{allow: groups, groupsField: "companyId", groupClaim: "companyId", operations: [create, read]},
{allow: private, provider: iam, operations: [create, read, update, delete]}
])
{
companyId: ID!
sortKey: Int!
content: String!
}
I can create a new item with the same hash- and sortkey combination as an existing item, which will then overwrite the existing item with the new one.
+1 As it stated here, any PutItem operation in DynamoDB replaces item, if the same primary key has been specified. To prevent this behaviour one should use conditional expression. As one can see in autogenerated Mutation type, every mutation contains condition parameter and, as I guess, the aim is to prevent overwriting of existing Item based on some attributes. But if we inspect resolver templates, we can see this
#set( $condition = {
"expression": "attribute_not_exists(#id)",
"expressionNames": {
"#id": "id"
}
} )
As a result, if Item exists, we can't overwrite it in any case, and there is no sense in specifying additional conditions.
But if we specify compound key by ourselves like so for ex @key(fields: ["serialId", "type"]), we, from one hand, can't specify conditions for our key (because autogenerated conditionInput not includes these fields), and, from other hand, we still get same mentioned above autogenerated condition for id, though we don't use it.
To be more particular, lets consider my case. I have next in my amplify/backend/api/myapi/schema.graphql :
type Device @model
@auth(rules:[
{allow: owner}
])
@key(fields: ["serialId", "type"])
{
serialId: String!
type: String!
owner: String!
data: [Data] @connection(keyName: "byType", fields: ["serialId"])
}
type Data @model
@auth (rules:[{allow: owner}])
@key (name: "byType", fields:["serialId","type","createdAt"])
{
id: ID!
serialId: String!
type: String!
owner: String!
temperature: Float!
createdAt: AWSDateTime!
}
After amplify update api I get next in my amplify/backend/api/myapi/build/schema.graphql (I don' t show all, only relevant) :
type Mutation {
createDevice(input: CreateDeviceInput!, condition: ModelDeviceConditionInput): Device @aws_iam @aws_cognito_user_pools
updateDevice(input: UpdateDeviceInput!, condition: ModelDeviceConditionInput): Device @aws_iam @aws_cognito_user_pools
deleteDevice(input: DeleteDeviceInput!, condition: ModelDeviceConditionInput): Device @aws_iam @aws_cognito_user_pools
createData(input: CreateDataInput!, condition: ModelDataConditionInput): Data @aws_iam @aws_cognito_user_pools
updateData(input: UpdateDataInput!, condition: ModelDataConditionInput): Data @aws_iam @aws_cognito_user_pools
deleteData(input: DeleteDataInput!, condition: ModelDataConditionInput): Data @aws_iam @aws_cognito_user_pools
}
input ModelDeviceConditionInput {
and: [ModelDeviceConditionInput]
or: [ModelDeviceConditionInput]
not: ModelDeviceConditionInput
}
input ModelDataConditionInput {
serialId: ModelStringInput
type: ModelStringInput
temperature: ModelFloatInput
createdAt: ModelStringInput
and: [ModelDataConditionInput]
or: [ModelDataConditionInput]
not: ModelDataConditionInput
}
also I have this in my amplify/backend/api/myapi/build/resolvers/Mutation.createDevice.req.vtl:
## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("__typename", "Device"))
#set( $condition = {
"expression": "attribute_not_exists(#id)",
"expressionNames": {
"#id": "id"
}
} )
and this in my amplify/backend/api/myapi/build/resolvers/Mutation.createData.req.vtl:
## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("__typename", "Data"))
#set( $condition = {
"expression": "attribute_not_exists(#id)",
"expressionNames": {
"#id": "id"
}
} )
Let's consider Mutations
mutation CreateData($owner: String!, $serialId: String!, $type: String!, $temperature:Float!) {
createData(input: {owner: $owner, serialId: $serialId, temperature: $temperature, type: $type}){
id,
type,
owner
}
}
mutation CreateDataWithId($owner: String!, $serialId: String!, $type: String!, $temperature:Float!, $id: ID) {
createData(input: {owner: $owner, serialId: $serialId, temperature: $temperature, type: $type, id: $id}){
id,
type,
owner
}
}
mutation CreateDevice($owner: String!, $serialId: String!, $type: String!) {
createDevice(input: {owner: $owner, serialId: $serialId, type: $type}){
serialId,
type,
owner
}
}
If I issue mutation CreateData, then take id from response and then issue mutation CreateDataWithId - AppSync complains. But if I issue mutation CreateDevice, then change owner(sic!), and then issue it again - AppSync not complains.
Apologies for the late follow up, are you still experiencing issues with this? I tried to create a record with the same hash and sort key and it gave me an error. For defining your own custom primary key the CLI does generate the following snippet.
#foreach( $entry in $modelObjectKey.entrySet() )
#if( $velocityCount == 1 )
$util.qr($condition.put("expression", "attribute_not_exists(#keyCondition$velocityCount)"))
#else
$util.qr($condition.put("expression", "$condition.expression AND attribute_not_exists(#keyCondition$velocityCount)"))
#end
$util.qr($condition.expressionNames.put("#keyCondition$velocityCount", "$entry.key"))
#end
Closing based on last response and no further communication or related issues tied to this. Please let us know if you're still stuck on this issue.
This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.
Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels for those types of questions.