Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(expression): support case-when expression #7276

Conversation

minhtri1396
Copy link

@minhtri1396 minhtri1396 commented Nov 12, 2024

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

Implement case-when expression to use case-when in SQL query.

User Case Description

We can use this expression to update batches instead of single update.

userIDs := make([]string, len(inputUsers))
userNameCases := make([]*clause.ExprCaseCondition, len(inputUsers))
for idx, user := range inputUsers {
    userIDs[idx] = user.ID
    userNameCases[idx] = &clause.ExprCaseCondition{
        When: "user_id=?",
        Then: "?",
        Vars: []any{
            user.ID,
            user.Name,
        },
    }
}

db.
    Table("users").
    Where("user_id IN (?)", userIDs).
    UpdateColumns(map[string]any{
        "user_name": clause.ExprCase{
            Cases: userNameCases,
            Else: &clause.ExprCaseElse{
            Then: "user_name",
                Vars: nil,
            },
        },
    })

The generated SQL will be:

UPDATE `users`
SET `user_name`=CASE
    WHEN user_id="user-001" THEN "user-name-001"
    WHEN user_id="user-002" THEN "user-name-002"
    ELSE user_name
END
WHERE user_id IN ("user-001","user-002")

@jinzhu
Copy link
Member

jinzhu commented Nov 14, 2024

Could we design the API to look something like this and place it in the datatypes package?

casewhen := datatypes.When("name = ?", "123").Then("hello").
            When("name = ?", "234").Then("hello2").
            Else("hello3")

db.Model(&user).Where("id = ?", 1).Update(map[string]any{"name": casewhen})

@jinzhu
Copy link
Member

jinzhu commented Nov 29, 2024

Closing this PR for now. Let me know once it’s published to go-gorm/datatypes!

@jinzhu jinzhu closed this Nov 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants