duplicateKeyName function

String? duplicateKeyName(
  1. String message
)

Parses the index or constraint name out of a 2601/2627 message.

2601: with unique index 'IX_Customers_Code' 2627: Violation of UNIQUE KEY constraint 'UQ_…' or PRIMARY KEY constraint 'PK_…'

Returning null means the message did not name a key, so the caller must not treat the failure as the expected unique key already existing.

Implementation

String? duplicateKeyName(String message) {
  final match = RegExp(
    r"unique index '([^']+)'"
    r"|UNIQUE KEY constraint '([^']+)'"
    r"|PRIMARY KEY constraint '([^']+)'",
    caseSensitive: false,
  ).firstMatch(message);
  if (match == null) return null;
  return match.group(1) ?? match.group(2) ?? match.group(3);
}