Devops 已上線項目數(shù)據(jù)庫修改流程

增加一個不可以為Null的字段

  • Step 1: Add the Column as Nullable (First PR & Deployment)
    Modify the database schema to add the new column as nullable.
    Update the application code to handle null values and assign a default before inserting data.

SQL Migration

ALTER TABLE MyTable ADD NewColumn INT NULL;

C# Code (Handling Nulls)

public class MyEntity
{
    public int? NewColumn { get; set; } // Nullable field
}

// Ensure default value before inserting

int? newColumnValue = GetValueFromSource();
int finalValue = newColumnValue ?? 0; // Default to 0 if null

Deployment Considerations
? Deploy schema changes first
? Ensure application logic prevents NULL values from being inserted
? Monitor logs for unexpected behavior

  • Step 2: Populate Existing Data (Second PR & Deployment)
    Update existing records to ensure all rows have valid values before enforcing NOT NULL.
    SQL Migration
UPDATE MyTable SET NewColumn = 0 WHERE NewColumn IS NULL;

Deployment Considerations
? Run data migration scripts in a controlled environment
? Validate that all rows have non-null values
? Monitor database performance

  • Step 3: Enforce NOT NULL Constraint (Third PR & Deployment)
    Once all records have valid values, alter the column to NOT NULL.

SQL Migration

ALTER TABLE MyTable ALTER COLUMN NewColumn INT NOT NULL;

Deployment Considerations
? Ensure all inserts provide a valid value
? Test thoroughly in staging before deploying
? Monitor for unexpected errors

  • Step 4: Remove Null Handling Code (Fourth PR & Deployment)
    Since the database now guarantees that the column will always have a value, remove unnecessary null checks.

C# Code (Before Removal)

int? newColumnValue = GetValueFromSource();
int finalValue = newColumnValue ?? 0; // Default to 0 if null

C# Code (After Removal)

int finalValue = GetValueFromSource(); // No need for null handling

Deployment Considerations
? Ensure all inserts provide a valid value
? Remove unnecessary default assignments
? Validate application behavior after deployment

  • Best Practices
    ?? Use Feature Flags – Control rollout via feature flags if applicable
    ?? Monitor Logs & Errors – Track database changes and application behavior
    ?? Perform Incremental Rollouts – Deploy changes in small batches
    ?? Test in Staging First – Validate changes before production deployment
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容