Hacker News new | ask | show | jobs
by wruza 651 days ago
I never use orms and don’t find them appealing, but one thing I do with my sqls may interest you.

I always wrap .query(…) or simply pass its result to a set of quantifiers: .all(), .one(), .opt(), run(), count(). These assert there’s 0+, 1, 0-1, 0, 0 rows.

This is useful to control singletons (and nonetons), otherwise you end up check-throwing every other sql line. One/opt de-array results automatically from T[] to T and T | undefined. Count returns a number.

Sometimes I add many() which means 1+, but that’s rare in practice, cause sqls that return 1+ are semantically non-singleton related but business logic related, so explicit check is better.

I also thought about .{run,count}([max,[min]]) sometimes to limit destructiveness of unbounded updates and deletes, but never implemented that in real projects.

Maybe there’s a better way but I’m fine with this one.

Edit: messed up paragraphs on my phone, now it’s ok

1 comments

Interesting, it throws an error if result rows don't match expected quantity?
Yes, and together with .in_transaction(cb) wrapper it also rolls everything back. Sadly SQL itself doesn't have something like ASSERT ROWCOUNT <expr>, cause it's such an obvious check, especially in destructive ops. LIMIT exists, but it is silent and quirky with non-SELECTs.