Skip to content

Commit

Permalink
feat(KeyTypes): Add a RowID key type
Browse files Browse the repository at this point in the history
Handles setting the primary key by fetching the newly created
entity from the database by the returned ROWID.
  • Loading branch information
elpete committed Aug 29, 2022
1 parent 9b3f3f7 commit 8b45d6d
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions models/KeyTypes/RowIDKeyType.cfc
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Handles the key being set by the database but not returned in the response.
* It queries the database based on the ROWID returned to get the actual primary key.
*/
component implements="KeyType" {

/**
* Does nothing as the key will be set by the database.
*
* @entity The entity that is being inserted.
*
* @return void
*/
public void function preInsert( required any entity ) {
if ( arguments.entity.keyNames().len() > 1 ) {
throw(
type = "InvalidKeyLength",
message = "RowIDKeyType cannot be used with composite primary keys."
);
}
return;
}

/**
* Sets the primary key after fetching the record by the ROWID
*
* @entity The entity that was inserted.
* @result The result of the queryExecute call.
*
* @return void
*/
public void function postInsert( required any entity, required struct result ) {
var keyName = arguments.entity.keyNames()[ 1 ];
var rowID = arguments.result.result.keyExists( keyName ) ? arguments.result.result[ keyName ] : arguments.result.result.keyExists(
"generated_key"
) ? arguments.result.result[ "generated_key" ] : arguments.result.result[ "generatedKey" ];
var generatedKey = arguments.entity.newQuery().retrieveQuery().where( "ROWID", rowID ).value( keyName );
arguments.entity.assignAttribute( keyName, generatedKey );
}

}

0 comments on commit 8b45d6d

Please sign in to comment.