1) Relational databases are the best abstraction we've found for storing data. Despite years of attempts (OODB, XML databases, various nosql stores, etc.), we have not been able to improve on it. postgresql, by adding native JSON support, became a better mongo than mongo virtually overnight.
2) Most people never learn databases, and most people who do are idiots working on enterprise three-tier architectures, so mostly it's misused. There is an attempt to hide them.
3) ORMs generally make easy stuff easy, and hard stuff painful.
What I generally want is:
1) Something translating SQL syntax into my native language, but maintaining SQL full semantics and expressiveness.
2) This should allow me to be database-agnostic.
3) This should prevent things like injection attacks.
4) It should not map onto objects. It should maintain 100% of the capability of SQL. The only differences should be syntactic (e.g. instead of writing WHERE, I might write .where() or similar).
5) This may and ideally should have added functionality, for example, around managing and organizing database migrations.
Stored procedures and virtual tables are also very important (but poorly implemented in most databases). These:
1) Allow proper abstraction at the SQL level.
2) Improve performance.
What most programmers fail to understand -- since universities don't teach -- is how powerful and elegant the underlying theory of databases is.
The huge win was that I could use the Clojure REPL to run my SQL-generating functions and see that the SQL actually matched what I was aiming for. Caching the query-building was as simple as memoizing the query building functions as queries are parameterised in any case, so can be reused.
There is something really nice about having the full power of SQL at your fingertips. The only drawback compared to ORMs of course is that it outputs the resulting query result in a flat structure. So any aggregation you'd need to handle in code or use something like Postgres JSON aggregation.
I think ORMs however, became a thing more so due to fear of having to write (correct) SQL. It was meant to reduce complexity for developers but of course that's not really how it panned out in reality.
It lets you build SQL queries using code and just returns the built SQL query as a string, the list of variables to pass into the query, and an error if your query was invalid.
Actually executing the query and doing stuff with the result is explicitly outside their scope. I typically use it with sqlx with a struct per query, just to avoid writing tedious row iterators.
Makes it super easy to eg define a function that adds paging to a query and returns the paged query. You can even write a function that takes an HTTP request, reads out standard paging parameters and adds them to a query.
? To me, this is the main use of an ORM: don't let it do query building for you (unless it's fairly simple LINQ stuff), but just have something map the rows returned to typesafe objects for you.
1) Has the correct native type
2) Can be accessed by name
Many normal database APIs do that themselves. I guess there's a little bit more for writes.
The point of ORMs is that they generally map objects onto tables. You create a class, and the ORM will create the database table for you based on what you have in the class. For example, for Django, you write:
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __str__(self):
return self.name
(source: https://docs.djangoproject.com/en/5.0/topics/db/queries/)And it will make the table for you. If you change the class, it will make the migration for you. That's clean, simple, and easy if you're not doing anything complex. It saves a ton of work.
However, this is a Very Bad Idea for complex systems, since exactly as you point out, there shouldn't be a 1:1 mapping between tables and classes. There may very well be a 1:1 or many:1 mapping between queries and classes. More sophisticated ORMs can do a bit of that, but at some point, you run into the equivalent of Greenspun's Tenth Rule, where the ORM turns into a more complex, buggy version of SQL.
Note that although advertised as for Java, it really supports any language that can run on the JVM which is many of them these days.
Tell me how you really feel :)
My biggest problem with ORM's is that it causes people to sprinkle the ORM code throughout their codebase but they'd never do that with SQL, they'd want to try and sequester it to a system whose responsibility is the retrieving and updating of data.
It puts people into a poor mindset around their data.
For most applications, "Retrieving and updating data" is the entire point, or at least a deeply fundamental part of how they work. It shouldn't scare you that such a core function -- the entire reason your application exists -- is "sprinkled around" your codebase. It should scare you if it isn't! I think the reason it scares you is because you imagine the performance nightmare of every random function possibly hitting the database N times. That's using an ORM terribly. Good ORMs let you plan database actions, and compose those plans.
Guys, you really, genuinely, don't have to choose between (a) writing SQL strings in code, and (b) using an ORM badly. You can truly do better!
SQLx comes close to this btw.
The basic data model was invented a half-century ago. Expressiveness of basic SQL is not different depending on the engine. Relational algebra is the same however it's implemented.
Some databases have extensions, and those are okay to include. You should be able to either (1) choose to not use those or (2) lock yourself into a subset of databases which support the extension you need.
It's good if those extension were namespaced. For example:
* If I want to use a postgres JSON type, it should live under postgres.json (or if it cuts across multiple databases, perhaps extensions.json or similar)
* Likewise, database built-in functions, except for common ones like min/max/mean, should be available under the namespace of those databases.
* It's okay if some of those are abstracted out into a namespace like extensions.math, so I can use extensions.math.sin no matter whether the underlying datastore decided to call it SINE, SIN, SINE_RADIANS, SIN(x/180*PI), and if it doesn't have sine, an exception gets raised.
The basic relational data model provides the best expressiveness for representing data and queries created to date, and doesn't differ. It's a good theoretical model, and it works well in practice. There's good reason it's survived this long, despite no lack of competition. The places expressiveness differs are relatively surface things like data types and functions.
It's also okay to have compound types, where I am explicit about what the type is in different databases. e.g.: string_type = {mysql: 'TEXT', postgresql: ...
> 1) Something translating SQL syntax into my native language, but maintaining SQL full semantics and expressiveness.
You have just described a good ORM used well.
> 2) This should allow me to be database-agnostic.
Meh, you sacrifice some powerful features if you demand total database agnosticism, and how often do you actually switch databases? Being database-agnostic is a side benefit of writing your logic simply against a good abstraction. The biggest benefit is composability. You can write (and optimize) one query against abstractions, and re-use that query in lots of different ways.
> 3) This should prevent things like injection attacks.
As all ORMs automatically already do.
> 4) It should not map onto objects. It should maintain 100% of the capability of SQL.
If it's not mapping onto objects, what is it doing? The problem is that your mental model of what "objects" means includes awful design decisions like deep inheritance trees, mutability, and lots of reference cycles (this.parent.child[0] == this, etc.) If your object model is already clean and following relational principles, then mapping into that model is exactly what you want.
It should not strive to maintain the capability of some bastardized pseudo-language which is despised by the progenitors of relational logic. It should strive to support the relational model. That's not the same thing.
> 5) This may and ideally should have added functionality, for example, around managing and organizing database migrations.
No, because your code versions and your database schemas advance together. To reliably run a database migration in code, you'd need to run it with the code version that exactly matches each step in the schema. That means for each step in the migration, you'd need to checkout the correct commit in git, compile, and run the ORM code in that version. Either that, or you're maintaining a code model that is compatible with every historical database schema, which is way worse.
But what ORMs should be able to do (and I haven't found one that does this well) is generate SQL migration scripts for you, which you store. Those would be frozen relative to the database schema version, so all the above problems go away.
> What most programmers fail to understand -- since universities don't teach -- is how powerful and elegant the underlying theory of databases is.
The underlying relational model is powerful and elegant. SQL itself is not. SQL is disliked by the founders of the relational model. Good ORMs let you incorporate the relational model into your code.
No. I did not. ORM is an "object–relational mapping." It maps data relations onto objects.
https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapp...
> how often do you actually switch databases?
Very often. Virtually all of the systems I write have at least two back-ends to maintain that flexibility. At the very least, I'd like my systems to run well locally for development but also to scale. The easiest way to do that is to e.g. support both SQLite and Postgres, but there are other ways which make sense.
In proprietary settings, I like having a BATNA. The architectural flexibility means I get better prices on hosted services and aren't liable to turning into a cash cow through lock-in. That's savings even if I'm not switching.
> If your object model is already clean and following relational principles, then mapping into that model is exactly what you want.
This is where your thinking broke. A good object model is NOT a relational model, and a good relational model is NOT an object model.
Learn the theory of both. They're both good theories, but they're different.
An ORM makes sense if you want to use an object model, but want the backing store to be an RDBMS.
> But what ORMs should be able to do (and I haven't found one that does this well) is generate SQL migration scripts for you, which you store. Those would be frozen relative to the database schema version, so all the above problems go away.
I believe that's one instantiation of what I wrote: "This may and ideally should have added functionality, for example, around managing and organizing database migrations." It's actually exactly what I was thinking.
Some ORMs do this not badly, actually. Don't let the perfect be the enemy of the good. A simple system which does 90% of the work of generating a migration (with manual verification and tweaks) is often better than a complex one which tries to do 100% of the work.
> The underlying relational model is powerful and elegant. SQL itself is not. SQL is disliked by the founders of the relational model.
Citation required.
In either case, ORMs aren't translating just syntax, but also semantics. That's where the problem lies. If you're not doing that, you're not an ORM.
> Good ORMs let you incorporate the relational model into your code.
You're confused about what an ORM is. ORMs essentially map an RDBMS onto an object model (which an OODBMS does natively). The two models are fundamentally different. It's a translation layer.
Any good database library will let me "incorporate the relational model into my code." That's not an ORM.
https://github.com/permazen/permazen/
It starts by asking what the most natural way is to integrate persistence with a programming language (Java in this case, but the concepts are generic), and then goes ahead and implements the features of an RDBMS as an in-process library that can be given different storage backends as long as they implement a sorted K/V store. So it can sit on top of a simple in-process file based K/V store, RocksDB, FoundationDB, or any SQL database like PostgreSQL, SQLite, Spanner, etc (it just uses the RDBMS to store sorted key/value pairs in that case).
Essentially it's a way to map object graphs to key/value pairs but with the usual features you'd want like indexing, validation, transactions, and so on. The design is really nice and can scale from tiny tasks you'd normally use JSON or object serialization for, all the way up to large distributed clusters.
Because the native object model is mapped directly to storage there's no object/relational mismatch.
Reads and writes on those objects are then mapped to K/V operations.
Stored procedures for business logic can be great for performance when they replace queries/mutations called thousands+ times.
I don't mind them for simple systems, but for more complex systems which need SQL, don't use an ORM. Mixing ORMs with raw SQL generally mixes and breaks layers of abstraction. This leads to a situation where the overall system is more complex than having a sane relational abstraction. For example, ORMs do a lot implicitly. A code change at the language level, with something like the Django ORM, can and will break your SQL code. Your data logic is also split across two places.
The only time I've seen this work is for SQL for one-off analytics done at a command line, where the SQL code is never intended to be reused.
EITHER:
- Use an ORM, if you are building something simple like a todo list or a basic eCommerce web site; or
- Use full SQL if you are doing something more complex (e.g. if you ever expect to do analytics); or
- If your programmers don't understand SQL, consider whether you want an ORM, a nosql, or to find programmers better matched to the problem domain.
(Footnote: Many good programmers don't understand SQL; that's okay. They just shouldn't be designing databases, any more than e.g. database experts should be designing machine learning algorithms, or machine learning experts should be designing front-end user interfaces. They're different skill domains, and they're all equally important. The key thing is people should know their skills. Otherwise, you'll get an unusable UX, a regression as our ML model, and a broken schema. This is especially true for something which looks simple on the surface but has deep theory behind it. ORMs make it look easy.)
Also, it’s pretty reductionist to say that it is only good for simple systems, when in fact, huge services are running it at almost all companies.
https://blog.codinghorror.com/object-relational-mapping-is-t...
They are really useful for like 90% of the work
The rest can be made with raw sql
Combine strengths of those two powerful tools, dont be religious
Way too much ORM hate here.
Everytime I use ORMs I feel frustrated by the capabilities compared to raw sql.
I feel handicapped in being able to have the data in a way I want.
I feel most of the criticism of ORMs come from people who don’t actually know how to properly use one. They were never meant for OLAP, they are for OLTP.
Now I only use ORM really only for some basic CRUD queries, if that.
If you use a query language that knows that we want objects linked to other objects, you can still have an ORM, but it doesn't have to do as much heavy lifting. The query can already specify the objects and properties you want explicitly, so you don't need to worry about, "which properties of which objects do I flesh? Am I over-fetching?"
That's why I've become a booster of EdgeDB: https://www.edgedb.com/ It's a sort of "midpoint" between regular SQL and an ORM. And it's language-agnostic, unlike an ORM.
(Some databases allow writing stored procedures in other languages, true, but that means a nonstandard interface, tightly coupled deployment model, and testing is still awful)
1) Databases had a consistent language for storage procedures
2) It was sane
The problem is that stored procedures work differently in every database, and most have come up with crazy / stupid ways to do them. That's a fixable problem, but it has not been fixed.
Painful to maintain, test, debug, etc.
stored procs also tie you to that database engine, which could be bad if, for example, you're paying a fat stack of cash to oracle and they come back asking for more.
i think a business logic api in a programming language that leverages raw SQL is the best middle-ground IMO.
i personally avoid them, but i don't often write complex SQL
This might be good time to plug my Postgres/TypeScript non-ORM: https://jawj.github.io/zapatos/.
I should say I also like what I've seen of https://kysely.dev/ and https://pgtyped.dev/.
1. Hot reloading code. As a Java developer, this is important for prototyping as I can iterate quicker.
2. Clarity. I can read exactly what's going on and I know exactly what query is being executed.
_strongly_ disagree and I bet anyone who has this opinion can't articulate a good, concrete, reason for it. The best they're going to come up with is FUD about changing table names, which is one of those theoretical things that very rarely manifests itself in reality.
But...
The actual main problem of ORM is not just ORM but a multi-layered translation of target language query code
- to internal target language database schema modeled from/to a db schema
- then to SQL syntax
- then to wire request to db
- then to SQL validator in db
- then to internal database query planner targeting relevant schema elements
- then to raw index/hash/scan executors
You see the picture?
If the database schema wire protocol could only be converted to the target language objects without SQL translation sitting in the middle, query would run optimally and with up-to-date statistics to query planner.Think of WASM-like protocol (as opposed to JS) to which queries are compiled in the client and passed to the db.
It has been done before on a basic key-value wire protocols and to an extent on graph databases with json requests. Structured relational data is making this hard to do as one would need to have up-to-date db stats in the client along with all index details to run an optimal query.
On the other hand, compiling this:
db.Posts.Get(p => (p.Authors.Includes(a => a.IsBoss))
? { Date: p.Date, Bosses: p.Authors = p.Authors.Filter(a => a.IsBoss), Groups: p.Groups.OrderBy(x => x.Name).Top(5) }
: { Date: p.ModifyDate, Bosses: null, Groups: p.EmployeeGroups.First() }
)
Into SQL would be close to impossible in an optimal way.
Alternatively, with schema access in the client it, one could write internal db "assembly language" procedure for looking up using indexes, conditional querying and spitting out binary result for minimal effort hydration.Just an idea, I am not aware of similar client query planner solutions available.
SQL is the abstraction. It's a high-level DSL which saves you from the low-level details of an ORM.
Unfortunately it came out 20 years before the first ORMs, so people default to thinking that ORMS must be an improvement over SQL.
SQL is an abstraction in the same way any programming language is an abstraction, but that's beside the point. Within the programming language itself, some support abstraction better than others (and lots of different varieties; it's not well-ordered). SQL basically just doesn't.
> It's a high-level DSL
I agree, but tell that to the people who write the core logic of their entire application in Procedures: that's not very specific. They're using the wrong tool for the job.
> which saves you from the low-level details of an ORM.
This doesn't make sense. The abstraction that SQL is over is the low-level details of how the database query engine works, not an ORM. And an ORM is not "lower level" than SQL. An ORM is just a different abstraction, one that tries to fit more readily into your application language than building SQL strings does. Building SQL strings directly is awful. Get yourself an ORM that allows composition of queries using the abstraction tools available in your language.
It's wild to me that this idea is so controversial that I literally get downvoted for suggesting it, when it's very obviously way better if you try it (or even seriously think about it). It's just an example of how deeply religious database developers are. I don't think any other software engineering sub-discipline is as intolerant of disagreement as database developers.
> people default to thinking that ORMS must be an improvement over SQL
It's not a default judgement. It's 15 years of experience, and tasting the fruit of an ORM done really well. It's also the opinion of the original progenitors of the relational model: EF Codd, Chris Date, etc. (At least, that there vastly better relational abstractions than SQL.) To all you overly religious database developers: guys, your prophets didn't even like SQL!