Kamirus / purescript-selda

A type-safe, high-level SQL library for PureScript
MIT License
90 stars 3 forks source link

Better type inference for insert #47

Open Kamirus opened 3 years ago

Kamirus commented 3 years ago

insert (as well as insert_) has a meaningless type for a user, thus it is hard to start using it. motivation: #40 has more background on this issue.

insert_ ∷
  ∀ m t r.
  GenericInsert BackendPGClass m t r ⇒
  MonadSeldaPG m ⇒
  Table t → Array { | r } → m Unit

Say we have the following table definition:

employees ∷
  Table
    ( id ∷ Auto Int
    , name ∷ String
    , salary ∷ Default Int
    )
employees = Table { name: "employees" }

We should be able to apply insert_ to employees and let type inference figure out the rest. But this is not currently the case as salary is a default column, thus we can assign two different types to insert_ employees

insertEmployees1
  ∷ ∀ m
  . MonadSeldaPG m
  ⇒ Array
      { name ∷ String   -- required
      , salary ∷ Int    -- optional
      -- , id ∷ Int     -- illegal to insert
      }
  → m Unit
insertEmployees1 = insert_ employees

insertEmployees2
  ∷ ∀ m
  . MonadSeldaPG m
  ⇒ Array
      { name ∷ String
      }
  → m Unit
insertEmployees2 = insert_ employees

Potential Solution

Change (or provide an alternative) insert to allow only one type once a table is provided (type parameter t should uniquely determine r from the type of insert_). Types of optional columns should get wrapped with Maybe.

Then definition

insertEmployees = insert_ employees

Should be inferred to

insertEmployees
  ∷ ∀ m
  . MonadSeldaPG m
  ⇒ Array
      { name ∷ String
      , salary ∷ Maybe Int -- wrapped with additional Maybe
      }
  → m Unit