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

open enums #133

Merged
merged 1 commit into from
Aug 16, 2024
Merged

open enums #133

merged 1 commit into from
Aug 16, 2024

Conversation

oyvindberg
Copy link
Owner

Some people like to use tables and foreign keys to encode enums. It'll typically take this form:

create table title (code text primary key);
insert into title (code) values ('mr'), ('ms'), ('dr'), ('phd');

create table titledperson
(
    title       text       not null references title,
    name        text       not null
);

You can configure typo to generate so-called "open enums" for you.

val options = Options(
  // ...
  openEnums = Selector.relationNames("title")
)

And typo will output the Primary key type as something like this:

/** Type for the primary key of table `public.title`. It has some known values: 
  *  - dr
  *  - mr
  *  - ms
  *  - phd
  */
sealed abstract class TitleId(val value: String)

object TitleId {
  def apply(underlying: String): TitleId =
    ByName.getOrElse(underlying, Unknown(underlying))
  case object dr extends TitleId("dr")
  case object mr extends TitleId("mr")
  case object ms extends TitleId("ms")
  case object phd extends TitleId("phd")
  case class Unknown(override val value: String) extends TitleId(value)
  val All: List[TitleId] = List(dr, mr, ms, phd)
  val ByName: Map[String, TitleId] = All.map(x => (x.value, x)).toMap
  
  // type class instances
}

Supported data types

Currently, typo supports the following data types for open enums:

  • text
  • a domain which has text as its base type

@oyvindberg oyvindberg merged commit 35c1757 into main Aug 16, 2024
8 checks passed
@oyvindberg oyvindberg deleted the open-enums branch August 16, 2024 12:10
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.

1 participant