r/programming • u/gajus0 • Feb 12 '19
Using SQL query builder is an anti-pattern
https://medium.com/@gajus/stop-using-knex-js-and-earn-30-bf410349856c17
u/definitelynotbeardo Feb 12 '19
Articles based on the premise that x has issues so you should never use x are an anti-pattern.
3
u/darchangel Feb 12 '19
"x has issues so you should never use x are an anti-pattern" articles are and anti-pattern :)
6
u/bro-away- Feb 12 '19
You only chose the most obtuse example for showing queries aren’t “easy” (and then also ban functionality in the library for your challenge)
Aka you’re too scared to face the fact that knex can be useful for a majority of queries but want to use an extreme example to try to make it look bad.
Also composability for your library sucks. Why would I want to go from a fluent api to a Russian nesting doll api that needs interpolation and an extra variable to work.
1
u/Darfer Feb 12 '19
I have spent a sizable chunk of my career wasting time trying (when forced) to write DB queries with Sql builders/ORMs. To use such tools you need to have a complete understanding of both SQL and the SQL builder. Anything even remotely complex usually exposes severe limitations with the tool and you spend orders of magnitude more time trying to find a workaround, than you would have with straight SQL. Back when I did Magento, I remember spending days trying to get their ORM to do even moderately complex queries, when I could have done the whole thing in ten minutes if could just write a query string. Literally days vs minutes. And for no reasonable gain.
Currently I use SQL Alchemy on a Python project I am heading up. The rule is to use Alchemy only for the most basic of queries. No Joins ever. After that, be conscious of SQL injection, and just write a damn query string. This saves oceans of time.
1
u/Caraes_Naur Feb 12 '19
Totally agreed. ORMs are for query prototyping, and even then only useful for trivial to simple queries.
Just learn SQL and how to write queries securely.
-1
u/gajus0 Feb 12 '19
Note: Part of the article was removed. It was challenging reader to implement this query (and earlier a query with WITH block) using Knex.js without using Knex.js raw methods in return for USD 30 reward. While it is possible to write the latter query using Knex.js, it is admittedly not the best use case for Knex.js.
2
u/Darfer Feb 12 '19
Nah. Put it back. That query was the perfect example of why shouldn't use an ORM/Sql Builder. That level of complexity in a SQL query is not at all uncommon. At least half of my queries end up looking like that. And there is no way, reason, or excuse for doing that in a builder.
15
u/tonefart Feb 12 '19
By that logic, ORMs are anti-pattern... because they build queries...