Follow

if nulls were a billion dollar mistake, having database IDs be represented as just integers is a half billion dollar mistake

we're still using pointers that can silently corrupt data and return invalid results, and we actually got worse by removing all type information about what they point to

at least C pointers segfault (sometimes) if you mess them up

@5225225 If you have FOREIGN KEY constraints set up properly, I don't see what's so bad about it.

How would you preserve type information in an ID?

Or is this more "I can't tell if ID 1000 is page 1000 or forum post 1000"

@aismallard

Foreign key constraints are like runtime type checks as opposed to a compile time check, they're needed but it's best to be told about it early.

I'd use a wrapper type Id<T> that means 'an id for T'. So Id<User> is a user id, and Id<Post> is a post id. So anywhere in the code where you'd use a bare int, use that wrapper type. Get the database library you're using to recognise it.
(cont...)

This is more useful if you're using an ORM since you could make it so you're never dealing with a raw int id, but even without that it greatly reduces the risk of mixing up an id of User vs an id of Post.

Say you want to edit a post with a particular user id. The signature (Id<User>, Id<Post>, string) makes a whole lot more sense than (int, int, string).

And if you're using random binary strings (like UUIDs) as IDs, you could embed the type in the id itself, to let you reject a bad id earlier.

@5225225 Oh I see, I thought you meant exclusively within the database schema.

I definitely agree types should be opaque and compile-time-verifiable: no more having pid_t or whatever that's just an int, since it allows arbitrary assignment and invalid operations (like multiplication).

@5225225 Rust is definitely nice for this since you can make an opaque struct that is produced by the database or object manager, so you know it's always valid, but is no heavier than the underlying integer.

Sign in to participate in the conversation
☠️ librepunk ☠️

A friendly mastodon instance primarily for shitposting, gays, and the glory of the free and open source software movement.