by simondotau · 5mo ago · 0 comments
Hmm – I should model the data according to the domain, not according to the shape my application objects happen to want.
Hmm – maybe “related objects” are not things to auto-fetch, but relationships the database engine is already built to handle.
Hmm – now that my schema matches my domain, complex problems can be solved with a few lines of SQL, saving me hundreds of lines of application code.
Hmm – in fact, now I realise that many important operations can be performed without round-tripping the data through application code at all, saving me thousands of lines of application code.
Similarly, designing your schema to match the domain does not necessarily grant you the productivity boons of an ORM.
Having (ab)used Postgres with and without ORM, I've never had a situation where the latter imposed any kind of design decisions on the schema. They're orthogonal concerns. Itself, the choice of using an ORM tends to be motivated by experience with certain requirements in the business logic. I love SQL, but when having to deal with API resources and their various representations, marshaling, validation, options, etc, it's difficult -- and to say the least, impractical -- to stay principled to the "no-ORM" and "raw-SQL" mottos.
TLDR: Tooling pressure is a design pressure.
Obsessively cramming tabular data into objects is often unnecessary, and it bloats the code downstream of the database query. It then encourages the bad habit of performing data manipulation in code rather than directly in the database.
"Fetch related objects" is a code smell. If any related data was needed, your original query should have already fetched it.
But in data management applications, the job is to derive specific information from stored facts. For that, SQL is not an implementation detail behind objects; it is the main abstraction. The whole point is to ask for the shape of data your application actually needs, not to arbitrarily hydrate objects and reinvent a bespoke querying engine on the client side. I can barely even remember the number of times that I've ripped an ORM out of a system because the code to interact with hydrated objects had devolved into a single-purpose database engine, a sprawling mess of code, seemingly well organised into objects, but ultimately wasteful.
Often, de-duplicating in code is a perfectly fine solution, and significantly more performant than multiple round-trips. A join that repeats parent columns is not a flaw in SQL. It is only a problem if the application insists on rebuilding a nested object graph instead of asking for the shape of data it actually needs.
If the data returned by the query does not match what you are presenting, the answer should not be to fetch a pile of related objects and interrogate them in memory. It is to use more SQL to further digest the data so that the result set more closely matches what you intend to present to the user.