safeql icon indicating copy to clipboard operation
safeql copied to clipboard

Opt-in for branded types (TableId rather than - number).

Open Newbie012 opened this issue 3 years ago • 3 comments

Newbie012 avatar Sep 10 '22 18:09 Newbie012

I guess this is also already possible now without any new SafeQL feature if using something like A.Type<> in ts-toolbelt or similar?

import {A} from 'ts-toolbelt'

type EUR = A.Type<number, 'eur'>
type USD = A.Type<number, 'usd'>

let eurWallet = 10 as EUR
let usdWallet = 15 as USD

eurWallet = usdWallet // error

karlhorky avatar Oct 06 '22 16:10 karlhorky

Not exactly:

function getById(userId: UserId) {
  return sql`select name from posts where id = ${userId}
}

How do you tell Postgres that UserId is a reference of users (id) and not posts (id)? by modifying the database (should be only possible in shadow database).

  1. Drop all constraints
  2. Drop all default values
  3. CREATE TYPE for each key.
  4. Map the created types to the TS types.

As a result, when auto-fix will be invoked, you'll receive id: UserId rather than id: number. It's a bit complicated, and I don't think there would be much adoption from the community, so I'm putting this as a low priority. But I will definitely get back to it!

Newbie012 avatar Oct 06 '22 19:10 Newbie012

Oh I see what you mean now, you're talking about the PostgreSQL data types created by CREATE TYPE, right ok.

So these in combination with TypeScript types - and maybe the TS types are also branded / opaque types - got it.

karlhorky avatar Oct 07 '22 09:10 karlhorky