I am attempting to insert two users with the database.insert method. One user that should work, and another that is missing required fields.
// Create two users, one of which is missing a required field
User[] users = new List<User>{
new User(FirstName='Test',
LastName = 'User',
Email = '[email protected],
Username = 'some_unique_username',
Alias = 'tuser',
TimeZoneSidKey = 'America/New_York',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'ISO-8859-1',
ProfileId = '00e3h000001YUCZAA4',
LanguageLocaleKey = 'en_US'
),
new User ()};
Database.SaveResult[] srList = Database.insert(users, false);
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully inserted account. User ID: ' + sr.getId());
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('User fields that affected this error: ' + err.getFields());
}
}
}
As expected, when the code is executed, I receive on Successful message with the User Id, for the first user, and one error message, for the second user. Strangely, when I attempt to query for the first User or find them in the database they do not exist. Even more strangely, when I do not attempt to insert the user that produces the error, then the first user is successfully inserted and DOES exist in the database. My understanding is that Database.insert(users, false) should not rollback insertions when there is an error, but in this case it seems to be doing just that. How is this possible?