validateIdNullability static method

String? validateIdNullability(
  1. ElementAnnotation idAnnotation,
  2. bool isNullable
)

Validate ID field nullability ID fields must be nullable UNLESS autoIncrement is explicitly false AND strategy is not UUID Returns error message if invalid, null if valid

Implementation

static String? validateIdNullability(
  ElementAnnotation idAnnotation,
  bool isNullable,
) {
  try {
    final source = idAnnotation.toSource();

    // Extract autoIncrement value
    bool autoIncrement = true; // default
    final autoIncrementMatch = RegExp(
      r'autoIncrement\s*:\s*(true|false)',
    ).firstMatch(source);
    if (autoIncrementMatch != null) {
      autoIncrement = autoIncrementMatch.group(1) == 'true';
    }

    // Extract strategy
    final strategy = extractIdStrategy(idAnnotation);

    // ID field must be nullable UNLESS:
    // 1. autoIncrement is explicitly false AND
    // 2. strategy is not UUID
    if (!isNullable) {
      // Non-nullable ID is only allowed if autoIncrement is false and strategy is not UUID
      if (autoIncrement || strategy == IDStrategy.uuid) {
        return 'ID field must be nullable unless autoIncrement is explicitly set to false and strategy is not UUID. '
            'Use "int?" or "String?" instead of "int" or "String".';
      }
    }
  } catch (e) {
    // Silently fail and allow
  }

  return null;
}