valderman / selda

A type-safe, high-level SQL library for Haskell
https://selda.link
MIT License
478 stars 58 forks source link

How to use `tableFieldMod`? #185

Closed tankorsmash closed 1 year ago

tankorsmash commented 1 year ago

Thanks for the library, the docs are a big improvement over other ORMs!

The docs list autoFieldGen as a way to rename a field, but I don't see autoFieldGen in the source anywhere.

Maybe there's an updated solution, but I've got

data Person {
  personId: ID Person
}

and I'd like to use the database column name "id" instead of "personId". I thought this is what tableFieldMod would be, but I'm not sure.

tankorsmash commented 1 year ago

Ah I think the docs are just out of date. Commit 3061213 shows a snippet:

modPeople :: Table Person
modPeople = tableFieldMod "modpeople" [name :- primary] $ \name ->
  "mod_" <> name

and doing something like this for my case (remembering that name here is each of the columns, not just one) works!

valderman commented 1 year ago

Yeah, the docs are outdated here. That should be autoPrimary, not autoPrimaryGen, and the solution you found sounds like the correct one. A simple renaming function for your case might look like:

personColumnNames :: Text -> Text
personColumnNames "personId" = "id"
personColumnNames name = name

And then you'd do something like this to use it:

peopleTable :: Table Person
peopleTable = tableFieldMod "people" [#personId :- autoPrimary] personColumnNames

You'll also need to add a deriving Generic to your Person type (which requires the DeriveGeneric extension), an explicit instance SqlRow Person (the default instance for SqlRow should work as long as you derive Generic and don't use too exotic types for the fields of Person), and the OverloadedLabels extension for #personId.

EDIT: oh, and you also need OverloadedStrings in order to pattern match on Text.

tankorsmash commented 1 year ago

Thank you for breaking it down! That makes a lot of sense and lines up with the bits I was able to use on the official tutorial. Thanks!