# SQL Objects Injection

EF Core does NOT generate DDL for TVF, views, and stored procedures.
SQL source scripts are in `Persistence/SqlObjects/` (Embedded Resources).
After a migration/squash/rebase, they must be re-injected into the consolidated migration.

## Injection Process

```bash
# Check if SqlObjects folder exists with .sql files
SQL_OBJECTS_DIR="$INFRA_PROJECT_DIR/Persistence/SqlObjects"
SQL_FILES=$(find "$SQL_OBJECTS_DIR" -name "*.sql" 2>/dev/null | wc -l)

if [ "$SQL_FILES" -gt 0 ]; then
  echo ""
  echo "Found $SQL_FILES SQL object(s) in SqlObjects/"
  echo "Injecting SqlObjectHelper.ApplyAll(migrationBuilder) into migration..."

  # Validate migration file path before sed operations
  if [ ! -f "$MIGRATION_FILE" ]; then
    echo "ERROR: Migration file not found: $MIGRATION_FILE"
    exit 1
  fi
  if ! echo "$MIGRATION_FILE" | grep -qE '\.cs$'; then
    echo "ERROR: Invalid migration file path (not .cs): $MIGRATION_FILE"
    exit 1
  fi

  # Add using directive if not present
  if ! grep -q "using SmartStack.Infrastructure.Persistence.SqlObjects;" "$MIGRATION_FILE"; then
    sed -i '1s/^/using SmartStack.Infrastructure.Persistence.SqlObjects;\n/' "$MIGRATION_FILE"
  fi

  # Add SqlObjectHelper.ApplyAll at the end of Up() method
  sed -i '/protected override void Up/,/^        }/ {
    /^        }/ i\
\            // Apply SQL objects (TVF, Views, SP) from embedded resources\
\            SqlObjectHelper.ApplyAll(migrationBuilder);
  }' "$MIGRATION_FILE"

  # Verify injection succeeded (fallback to manual step if sed pattern didn't match)
  if ! grep -q "SqlObjectHelper.ApplyAll" "$MIGRATION_FILE"; then
    echo "WARNING: Automatic injection failed (indentation pattern may differ)"
    echo ""
    echo "MANUAL STEP REQUIRED: Add these lines inside the Up() method before the closing brace:"
    echo '    using SmartStack.Infrastructure.Persistence.SqlObjects;'
    echo '    ...'
    echo '    SqlObjectHelper.ApplyAll(migrationBuilder);'
    echo ""
    echo "File: $MIGRATION_FILE"
  else
    echo "  SqlObjectHelper.ApplyAll(migrationBuilder) injected"
  fi
  find "$SQL_OBJECTS_DIR" -name "*.sql" -exec basename {} \; | while read f; do
    echo "  - $f"
  done
else
  echo ""
  echo "No SQL objects found in SqlObjects/ - skipping injection"
fi
```
