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

How to build multiple dynamic set fields #392

Open
elielr01 opened this issue Sep 28, 2023 · 0 comments
Open

How to build multiple dynamic set fields #392

elielr01 opened this issue Sep 28, 2023 · 0 comments

Comments

@elielr01
Copy link

This might be more a question rather than a bug or feature request.

I have an scenario where I have a struct with 3 pointers like:

type MyStruct struct {
 A *string `json:"a"`
 B *string `json:"b"`
 C *string `json:"c"`
}

And I wanted to update a table adding dynamic sets based on whether if such pointers have value or not (without setting them to null).

I tried:

// decoded a MyStruct into "ms"

query := goqu.Update("table").Set(
  goqu.Record{
    "a": ms.A,
    "b": ms.B,
    "c": ms.C
  }
)

In case A has a value, but B and C are nil, this will populate column "table.a", but will also populate with NULL the columns "table.b" and "table.c" which is not what I want. In this case I would expect only A to be updated.

I also tried:

// decoded a MyStruct into "ms"
query := goqu.Update("table")

if ms.A != nil {
  query = query.Set(goqu.Record{ "a": ms.A })
}
if ms.B != nil {
  query = query.Set(goqu.Record{ "b": ms.B })
}
if ms.C != nil {
  query = query.Set(goqu.Record{ "c": ms.C })
}

But in case B and C have values, only C gets updated (the latest Set overrides previous Set statements, instead of being aggregated).

Ultimately the question is how to write an update query, having a struct, so that only the non-nil pointers are set? Or am I going for the wrong approach? 🙃

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

No branches or pull requests

1 participant