Andreas Fuchs' Journal

submited by
Style Pass
2024-04-16 13:30:09

I’ve been writing a little web app in rust lately, and in it I decided to try to do it without an ORM. Instead, I modeled data access in a way that resembles the Data Access Layer pattern: You make a set of abstractions that maps the “business logic” to how the data is stored in the data store. Here are some types that I found useful in this journey so far.

The first item is a very subtle little thing that I wasn’t sure would work. But it does, and it’s really pleasing! Introducing IdType, a trait that marks a type used for database identifiers. Say you have a struct Bookmark in sqlite that is has a u64 as a primary key. What prevents you from passing accidentally just about any u64 (say, a user ID) into a struct and reading any bookmark in the database? Right, that’s why we make newtypes.

Sweet, but how do you create a new bookmark? Your database is what assigns these IDs, so do you make a second struct BookmarkForInsertion and sync struct fields? Or do you extract the ID fields and make a struct two layers deep? Pass all bookmark fields to an add function? All of these seemed unpleasant to me. Here’s what I do instead:

Leave a Comment