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

Get remote db model based on local model #49

Closed warflash closed 1 year ago

warflash commented 1 year ago

Feature request

I'm not sure this is already possible (easily) and there's no discussions tab for this repo sadly so I figured I'd open an issue.

Basically I'm looking for a way to get the Model that's stored in postgres based on a model that already exists (read from local json or whatever). There's PrimaryKey annotations which I thought would be used for this sort of usecase but can't figure out how.

Describe the solution you'd like

MyModel localModel = ; // read from somewhere

MyModel remoteModel = client.Table<MyModel>.GetByPkey(localModel);

something along those lines would be nice

acupofjose commented 1 year ago

You mean something like this?

var supabotMessages = await client.Table<Message>().Filter("id", Postgrest.Constants.Operator.Equals, id).Get();
warflash commented 1 year ago

Well sort of yeah. Just without the verbosity of "id", Postgrest.Constants.Operator.Equals, id. The primary keys are already annotated so I was hoping there would be a way to skip the verbose filter statements. For multi col keys in particular it's quite the hassle to create dicts and stuff.

 [Table("my_model")]
    public class MyModel: BaseModel
    {
        [PrimaryKey("id_2")]
        public string Id1 { get; set; }

        [PrimaryKey("id_2")]
        public string Id2{ get; set; }

        [PrimaryKey("id_3")]
        public string Id3 { get; set; }

        [Column("my_col")]
        public short MyCol{ get; set; }
       //....
   }

would result in a query like:

var filters = new Dictionary<string, string>()
           {
                {"id_1", localModel.Id1 },
                {"id_2", localModel.Id2 },
                {"id_3", localModel.Id3 },
            };
var dbModel = postgrestClient.Table<MyModel>().Match(filters).Get();

where to me it feels like the dict creation part should be able to be created automatically based on the [PrimaryKey(xx)] annotations.

Hope that makes sense :D

acupofjose commented 1 year ago

Oh yes! Very nice.

I've added the following on the master branch.

var moviePerson = new MoviePerson { Id = 1, MovieId = 1, PersonId = 1 };
var findMoviePerson = await client.Table<MoviePerson>().Match(moviePerson).Single();

Is that better? (This tangentially required better supporting composite primary keys, which is appreciated!)

acupofjose commented 1 year ago

If that works I’ll push it into the next version for you!

warflash commented 1 year ago

Awesome, yeah the syntax looks very nice, thank you👌

acupofjose commented 1 year ago

Available in v2.1.0!