Bug with amplify generated composite keys
Hello, I created a composite sort key using the amplify cli. The composite key includes the a person's first and last name. Most of the time the composite key is generated correctly in Dynamo DB like: john#doe. However, sometimes it'll be saved as ${ctx.args.input.first}#${ctx.args.input.last}. Subsequently, when I try to run a query with this composite key, it skips over the records that have this faulty composite key. I have not messed with any of the code auto generated by amplify and have confirmed that the first and last name values due indeed exist in the data row. Also, the primary keys were also defined. If anyone can point me in the right direction that would be great!
Could you share the generated request and response templates. That could help in narrowing down if the issue is with the genrated code
Closing this due to lack of requested information. Please comment on this thread to re-open the issue if you're still stuck.
@yuth @kaustavghosh06 I meet the same problem.If I run a Mutation (update) with null values for those fields the sort key contains the pattern @MattWlodarski mentioned If i do not include those fields in the mutation the sort key is regenerated and contains the pattern @MattWlodarski mentioned (${ctx.args.input.first}#${ctx.args.input.last}.) According to me, if the mutation does not contains the sort fields, the sort key should not be regenerated.
Here is the part of the cli generated request template that regenerate it:
[Start] Validate update mutation for @key 'byRequestedCrecheByFirstNameAndLastName'. **
#set( $hasSeenSomeKeyArg = false ) #set( $keyFieldNames = ["firstName", "lastName"] ) #foreach( $keyFieldName in $keyFieldNames ) #if( $ctx.args.input.containsKey("$keyFieldName") ) #set( $hasSeenSomeKeyArg = true ) #end #end #foreach( $keyFieldName in $keyFieldNames ) #if( $hasSeenSomeKeyArg && !$ctx.args.input.containsKey("$keyFieldName") ) $util.error("When updating any part of the composite sort key for @key 'byRequestedCrecheByFirstNameAndLastName', you must provide all fields for the key. Missing key: '$keyFieldName'.") #end #end
[End] Validate update mutation for @key 'byRequestedCrecheByFirstNameAndLastName'. **
#if( $util.isNull($dynamodbNameOverrideMap) ) #set( $dynamodbNameOverrideMap = { "firstName#lastName": "firstNameLastName" } ) #else $util.qr($dynamodbNameOverrideMap.put("firstName#lastName", "firstNameLastName")) #end $util.qr($ctx.args.input.put("firstName#lastName","${ctx.args.input.firstName}#${ctx.args.input.lastName}"))
// To fix it, I think we could modify the last line to be: #if(hasSeenSomeKeyArg) $util.qr($ctx.args.input.put("firstName#lastName","${ctx.args.input.firstName}#${ctx.args.input.lastName}")) #end
What about it? thanks in advance.
Hi
Any news about it ? thanks
Well here is part of my schema I setup as mentioned before, I haven't touched anything else:
type OutcomesRecord @model
@key(name: "byDobLastFirst", fields: ["dob", "last", "first"], queryField: "outcomesRecordByDobLastFirst")
{
id: ID!
clinicId: ID
clinicianId: ID
groupId: ID
statusSummaryId: ID
first: String!
last: String!
dob: String!
}
As you can see, first, last, and dob are all required fields so if they don't exist the record can't even be created which is why this bug is confusing me.
Here is the generated code for the create mutation:
`#if( $util.isNull($dynamodbNameOverrideMap) ) #set( $dynamodbNameOverrideMap = { "last#first": "lastFirst" } ) #else $util.qr($dynamodbNameOverrideMap.put("last#first", "lastFirst")) #end $util.qr($ctx.args.input.put("last#first","${ctx.args.input.last}#${ctx.args.input.first}")) #if( $util.isNull($dynamodbNameOverrideMap) ) #set( $dynamodbNameOverrideMap = { "dob#last#first#caseId": "dobLastFirstCaseId" } ) #else $util.qr($dynamodbNameOverrideMap.put("dob#last#first#caseId", "dobLastFirstCaseId")) #end $util.qr($ctx.args.input.put("dob#last#first#caseId","${ctx.args.input.dob}#${ctx.args.input.last}#${ctx.args.input.first}#${ctx.args.input.caseId}"))
[Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $util.time.nowISO8601()))) $util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601()))) $util.qr($context.args.input.put("__typename", "OutcomesRecord")) { "version": "2017-02-28", "operation": "PutItem", "key": #if( $modelObjectKey ) $util.toJson($modelObjectKey) #else { "id": $util.dynamodb.toDynamoDBJson($util.defaultIfNullOrBlank($ctx.args.input.id, $util.autoId())) } #end, "attributeValues": $util.dynamodb.toMapValuesJson($context.args.input), "condition": { "expression": "attribute_not_exists(#id)", "expressionNames": { "#id": "id" } } }
[End] Prepare DynamoDB PutItem Request. **`
@yuth Just ran into same issue. This happens in my case if in a mutation to update the record, the fields that constitute the composite key are not included in the input. Manually changing like below solves the issue.
#set( $hasSeenSomeKeyArg = false )
#set( $hasSeenAllKeyArg = true )
#set( $keyFieldNames = ["status", "fromDate"] )
#foreach( $keyFieldName in $keyFieldNames )
#if( $ctx.args.input.containsKey("$keyFieldName") )
#set( $hasSeenSomeKeyArg = true )
#else
#set( $hasSeenAllKeyArg = false )
#end
#end
#foreach( $keyFieldName in $keyFieldNames )
#if( $hasSeenSomeKeyArg && !$ctx.args.input.containsKey("$keyFieldName") )
$util.error("When updating any part of the composite sort key for @key 'byCustomer', you must provide all fields for the key. Missing key: '$keyFieldName'.")
#end
#end
## [End] Validate update mutation for @key 'byCustomer'. **
#if( $hasSeenAllKeyArg )
#if( $util.isNull($dynamodbNameOverrideMap) )
#set( $dynamodbNameOverrideMap = {
"status#fromDate": "statusFromDate"
} )
#else
$util.qr($dynamodbNameOverrideMap.put("status#fromDate", "statusFromDate"))
#end
$util.qr($ctx.args.input.put("status#fromDate","${ctx.args.input.status}#${ctx.args.input.fromDate}"))
#end
That way composite key will be updated only of all fields available (not sure if this is actually a behaviour you want, or if it leads to logical issues)
Hey thanks @clahoud !! That makes sense. Those fields are required for a create mutation but not for an update mutation.
Reopening as the problem persist (I just run into this myself) and the suggested workaround is to wrap the expression check. My proposed solution would be wrap the whole override block altogether since that does not need to run if we don't have the key values specified.
The fix must take into account multiple @key directives on the type as well.
I have just run into this issue as well. Had no idea why my items weren't returning in my queries after they had been updated, then stumbled across the underlying problem when editing a different resolver and came to github to report it...
Seems like a pretty simple fix and I think it's a fairly common scenario...
In my example, we have an object with status and priority forming a composite key. The key is used to fetch all items with a status of "active" ordered by priority (these fields are updated infrequently). The object also has a notes field that is updated frequently. When the notes field is updated, the item will no longer be returned in our query as the status#priority field is set to ${ctx.args.input.status}#${ctx.args.input.priority}.
I've resolved our issue in the exact same way as @mdebo suggested.
There is another issue at play here, in addition to the fix @clahoud suggested.
I have created a composite key that combines the updatedAt, and createdAt timestamps. Whenever the record is created, or updated, the value of the key is always the same (i.e. not what is expected):
"updatedAt#createdAt": "${ctx.args.input.updatedAt}#${ctx.args.input.createdAt}"
This is because the validation is run before the defaults are set for updatedAt and created at. If I manually move these above the validation block in the resolver, the values are populated correctly.
This works:
## [Start] Prepare DynamoDB PutItem Request. **
#set( $createdAt = $util.time.nowISO8601() )
## Automatically set the createdAt timestamp. **
$util.qr($context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $createdAt)))
## Automatically set the updatedAt timestamp. **
$util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $createdAt)))
$util.qr($context.args.input.put("__typename", "Profile"))
## [Start] Validate create mutation for @key 'explore'. **
#set( $hasSeenSomeKeyArg = false )
#set( $keyFieldNames = ["updatedAt", "createdAt"] )
#foreach( $keyFieldName in $keyFieldNames )
#if( $ctx.args.input.containsKey("$keyFieldName") ) #set( $hasSeenSomeKeyArg = true ) #end
#end
#foreach( $keyFieldName in $keyFieldNames )
#if( $hasSeenSomeKeyArg && !$ctx.args.input.containsKey("$keyFieldName") )
$util.error("When creating any part of the composite sort key for @key 'explore', you must provide all fields for the key. Missing key: '$keyFieldName'.")
#end
#end
## [End] Validate create mutation for @key 'explore'. **
#if( $util.isNull($dynamodbNameOverrideMap) )
#set( $dynamodbNameOverrideMap = {
"updatedAt#createdAt": "updatedAtCreatedAt"
} )
#else
$util.qr($dynamodbNameOverrideMap.put("updatedAt#createdAt", "updatedAtCreatedAt"))
#end
$util.qr($ctx.args.input.put("updatedAt#createdAt","${ctx.args.input.updatedAt}#${ctx.args.input.createdAt}"))
This does not work
## [Start] Validate create mutation for @key 'explore'. **
#set( $hasSeenSomeKeyArg = false )
#set( $keyFieldNames = ["updatedAt", "createdAt"] )
#foreach( $keyFieldName in $keyFieldNames )
#if( $ctx.args.input.containsKey("$keyFieldName") ) #set( $hasSeenSomeKeyArg = true ) #end
#end
#foreach( $keyFieldName in $keyFieldNames )
#if( $hasSeenSomeKeyArg && !$ctx.args.input.containsKey("$keyFieldName") )
$util.error("When creating any part of the composite sort key for @key 'explore', you must provide all fields for the key. Missing key: '$keyFieldName'.")
#end
#end
## [End] Validate create mutation for @key 'explore'. **
#if( $util.isNull($dynamodbNameOverrideMap) )
#set( $dynamodbNameOverrideMap = {
"updatedAt#createdAt": "updatedAtCreatedAt"
} )
#else
$util.qr($dynamodbNameOverrideMap.put("updatedAt#createdAt", "updatedAtCreatedAt"))
#end
$util.qr($ctx.args.input.put("updatedAt#createdAt","${ctx.args.input.updatedAt}#${ctx.args.input.createdAt}"))
## [Start] Prepare DynamoDB PutItem Request. **
#set( $createdAt = $util.time.nowISO8601() )
## Automatically set the createdAt timestamp. **
$util.qr($context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $createdAt)))
## Automatically set the updatedAt timestamp. **
$util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $createdAt)))
$util.qr($context.args.input.put("__typename", "Profile"))
Hi @attilah, I have the same issue, I'm using v4.27.3
I have 3 @key in my model.
@key(name: "byDeletedByDate", fields: ["deleted", "createdAt"], queryField: "listShippingBills")
@key(name: "byStatusByDeletedByDate", fields: ["status", "deleted", "createdAt"], queryField: "listShippingBillsByStatus")
@key(name: "byBillNumberByDeletedByDate", fields: ["billNumber", "deleted", "createdAt"], queryField: "listShippingBillsByBillNumber")
Hi all. Experiencing the same problem here.
Amplify cli: v4.29.0
My key: @key(name: "byChallenge", fields: ["challengeId", "createdAt", "authorId"], queryField: "listChallengeVideosByChallenge")
Will try to use a workaround while there's no solid solution.
Any update on this? I am having the same issue
Same issue here
Same issue here
Same issue here Amplify cli: v4.41.2
any updates? still a bug after being identified over a year ago (v.4.49.0)
@attilah @kaustavghosh06 @SwaySway @yuth @ammarkarachi @edwardfoyle @litwicki this is such a critical bug it should be at the highest priority of any work for Amplify CLI. This essentially makes accessing DynamoDB data that uses a composite sort key completely unreliable and inconsistent because a record "disappears" (is not returned) if an update is performed that does not include the fields that make up the composite sort key. This can cause customers to think their data just disappeared... how can anything be more critical to fix than that? This has already been well diagnosed. Can the Amplify community please have an update when this will be fixed?
So far, I am unable to reproduce this issue with the latest version of the CLI. However, this bug sounds a lot like https://github.com/aws-amplify/amplify-cli/issues/6634, which was fixed in v4.44.2. Can you try the instructions in https://github.com/aws-amplify/amplify-cli/issues/6634#issuecomment-786956504 and see if that fixes your issue.
@cjihrig you are right looks like this was fixed somewhat recently in v4.44.2 and up. Not sure why this issue didn't get picked up originally instead of that other newer issue (https://github.com/aws-amplify/amplify-cli/issues/6634), but I think this issue can be closed now. I just have a lot of composite sort keys to go back and fix now that I know they won't return to the same bad state with the next update that is run.