supabase-community / postgrest-csharp

A C# Client library for Postgrest
https://supabase-community.github.io/postgrest-csharp/api/Postgrest.html
MIT License
114 stars 22 forks source link

Ignoring `null` in a JSONB column using `record` #71

Closed TranquilMarmot closed 11 months ago

TranquilMarmot commented 11 months ago

Feature request

Is your feature request related to a problem? Please describe.

I have a JSONB column that I'm writing to, defined like this:

[Table("games")]
public class Game : BaseModel
{
    [PrimaryKey]
    public string? id { get; set; }

    [Column]
    public GameState? state { get; set; }
}

public record GameState(Boolean? some_value)

// ... elsewhere ...

var data = new GameState(null)l;

await client
    .From<Game>()
    .Where(game => game.id == gameId)
    .Set(game => game.state!, data)
    .Update();

This will write the following JSON to the JSONB column:

{ "some_value": null }

Describe the solution you'd like

This is mostly fine, but it would be nice to be able to ignore null values when serializing to JSONB.

Describe alternatives you've considered

I tried to define the column like so:

    [Column("state", NullValueHandling = NullValueHandling.Ignore)]
    public GameState? state { get; set; }

But that doesn't have an effect. I assume because it applies to the entire column, and not the individual fields in the serialized JSON value.

acupofjose commented 11 months ago

Sure! You ought to be able to just use the underlying Newtonsoft attribute for it (this is what ColumnAttribute is doing behind the scenes anyway). Just specify the property on the object that you want to be ignored.

Something like:

public record GameState
{
  [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  public string? ExampleProperty { get; set; }
}
TranquilMarmot commented 11 months ago

Works perfectly! Thank you!