r/javascript • u/zaiste • Dec 10 '19
Stop using Knex.js
https://medium.com/@gajus/stop-using-knex-js-and-earn-30-bf410349856c5
u/ryanpeden Dec 11 '19
I understand the point the author is trying to make. And I used to be pretty firmly opposed to ORMs and query builders.
I like SQL a lot - in one of the large applications I've worked on in my career, every database option from basic CRUD to very complex queries happened in stored procedures in the database. While it was a tad tedious sometimes, it was also really damn fast. And I wrote a heck of a lot of SQL.
But over time, I've come to appreciate the benefits of a full-featured ORM. I think ORMs can be great tools for developers who have lived and breathed SQL for a while and can reasonably infer what the ORM is going to do under the hood.
Recently, I worked on a new .NET Core project, and so I used Entity Framework Core. I could've written a SQL script to create all the tables for me, but instead, I created my data model in C#, and then let EF Core generate the migrations to create the tables for me.
And to be honest, I found that using C# as a notation for describing my tables and relationships between them nicer than using SQL to do it. But if I hadn't spent a decent amount of time learning how to create normalized relation data models using SQL, I probably would've done a crappy job of expressing my data model in C#. So I suppose that understanding the relational nature of relational databases is the key here - and using SQL sort of forces you to think relationally. And as a bonus, I ended up with a nice set of C# classes that I can use in my application.
On the query builder side of things, EF Core is pretty darn good - I can generally predict what SQL it's going to generate. And if it ever does go off the rails, EF Core offers a raw SQL escape hatch. You just give it the SQL query, tell it what class to map the query back to, and things generally just work. Sure, there are times where I could write better SQL than EF Core generates, but in most cases, the difference isn't big enough to matter. And when it does matter, the hand-crafted SQL usually tends to be a short-lived stop on the road to super-fast Redis caching, so the faster SQL doesn't end up mattering.
I suppose what I'm trying to say is....query builders and ORMs are tools that can be used badly or used poorly. It's easy to get into trouble if you use them as a crutch because you don't really understand how the relational data you're using works. But if you do have a solid grasp of relational fundamentals, you can use ORMs and query builders as force multipliers.
Damn, this ended up longer than I expected. Maybe I should turn this thing into a blog post. Sincere thanks to anyone who actually read the whole thing!
1
Mar 17 '24
Knex.js is a SQL Query Builder for Javascript. Different from sequelize which is an orm.
Knex offers basic functions and allows you to do advanced queries with sql or even a mixture of the two using knex.raw for example. I use it because I think it's lighter, simpler, it's the first time I've used it, but it's working well for my project in this moment.
2
u/Funwithloops Dec 10 '19
I'm not sold at all on the benefit of fragments over a query builder. In the case of a small simple query, there's virtually no benefit since the SQL generated by the query builder is going to be obvious. In the case of a complex query, it's going to turn into a probably buggy unreadable mess of string concatenation.
Also you can easily use tagged template literals with Knex by writing a simple wrapper around knex.raw:
async function sql(static, ...dynamic) {
const result = await knex.raw(static.join('?'), dynamic);
return result.rows;
}4
u/libertarianets Dec 10 '19 edited Dec 10 '19
Stop using ORMs.
EDIT: Unless you're often switching between relational databases, which is the perfect use case for an ORM.
EDIT EDIT: I guess the point I'm trying to make is that database query languages aren't scary. Learn them rather than and unlock their full power without constraints of a query builder or ORM.
8
u/Funwithloops Dec 10 '19
This is such an elitist attitude in software. Use ORMs where they make sense. Don't use ORMs where they don't. There are plenty of simple cases where an ORM works just as well or better than raw SQL.
And Knex isn't even an ORM. It's a query builder.
3
5
u/kelmore5 Dec 10 '19
What's wrong with ORMs?
7
u/libertarianets Dec 10 '19 edited Dec 10 '19
Oof. This debate has been beaten like a dead horse.
My two cents: Database query languages aren't harder than any other programming language. ORMs may speed up writing simple things at first, but once you get to the nitty gritty, you'll find yourself using the escape hatch into the base query language anyway. You'll do other developers a favor by exposing the lower level queries and removing the extra unnecessary layer of abstraction.
2
u/kelmore5 Dec 10 '19
Hm, I can see that. I guess I've always liked them since they're easier to read in the respective language, but maybe it's time to make a switch away from them.
Just another thing to add to my never-ending list to read about programming!
2
u/libertarianets Dec 10 '19
Honestly, if you're worried about having too much to learn, then I think you're doing yourself a disservice by learning an ORM. Yes it is in the same language that you're learning (say Javascript) but behind the scenes, javascript is transpiling how you used the ORM API to the query language. Why not just jump straight into the query language and unlock its full power?
The counter argument to this is that an ORM is supposed to abstract away the database details, so theoretically you could swap out your database with another one and you wouldn't need to change the code at all.
My experience in practice is that it never happens like this due to the vast differences in database structures. If you're switching from one relational database to another (MySQL to SQLite) or something like that, then okay, maybe. (What would be the benefit of doing this anyway?...)
But most of the time when you switch a database, you're looking to get some extra performance and cater to how your data is structured. So you're going from a relational database to a noSQL database, or to a graph database for example. In that case your ORM abstraction is gonna be completely useless and you're going to have to rewrite everything anyway.
I think that ORMs are the wrong abstraction.
My advice: If you can learn MySQL, you'll be able pick up on any other database query language that you need to just fine. If you get thrown into a codebase that uses an ORM, you'll be able to pick that up even quicker if necessary.
But yeah keep with it my friend!
2
u/kelmore5 Dec 10 '19
Well actually, I've been programming for about 9 years now, and I'm well versed in MySQL :) I'm more wondering about new hires, especially junior devs, I bring into a future company I'm in the midst of creating. I know when I was an intern, having everything laid out in an ORM was really beneficial to me. It meant I could understand everything from the get go without being bogged down by further training in MySQL.
Still, you definitely raise an interesting point. Maybe it's better to just train people in SQL? It is more versatile. I'm wondering if there's a balance between ease of use and "standards," but I guess that's more of a me issue haha.
Anyway!
If you're switching from one relational database to another (MySQL to SQLite) or something like that, then okay, maybe. (What would be the benefit of doing this anyway?
This is actually really interesting because I didn't even think of it. I do this all the time in my work! I create scripts for clients, and some clients want the script to be portable while others require web services. This means I'm constantly changing my boilerplates between using SQLite and MySQL, so maybe sticking with an ORM is important just for that use case! I'm glad you brought that up.
Thanks for taking the time for your response man. You have good points, appreciate it! I'm not sure if I'd say ORMs are "the wrong abstraction" for my uses, but switching my code base / boilerplates to queries is something I might consider down the road.
Edit: Also, if you are creating out the ORM, there's no way to do that without using SQL (in my experience). In my opinion, the practicality of an ORM is being immediately understandable for people who aren't creating it or just for yourself later on down the road.
2
u/libertarianets Dec 10 '19
Right on. Good luck with your business endeavor. Sorry I assumed you were a beginner, haha!
1
2
u/GolemancerVekk Dec 11 '19
If your data model is object-oriented and your database is relational then ORM (in the sense of Object-Relational Mapping) is not a choice. You're doing it, period. It's your choice whether you code your own homebrew mapping or use an established ORM solution, but don't kid yourself that you can "stop using ORM".
3
u/wherediditrun Dec 11 '19 edited Dec 11 '19
The main attribute which qualifies something being ORM or not is model hydration, in other words no matter what query I sent, I do not worry about business model mapping. Active Record pattern like in laravel of hibernate in Java are just added fluff to it. So for example https://diesel.rs/ is also an orm.
you're often switching between relational databases
Who does this? I mean, this is one of more silly claims being made about ORM usage. Yeah b la bla bla Uncle Bob database has to be a plugin into the application. ORM helps with this, but it's barely the reason why it's implemented.
EDIT EDIT: I guess the point I'm trying to make is that database query languages aren't scary. Learn them rather than and unlock their full power without constraints of a query builder or ORM.
Oh yeah, lets litter the project with freaking strings all over the place, because why? Becuase we can. Great. I'm sorry, that's so short sighted, f search for usages, who cares about refactoring. It's not enough that template literals are going freaking berserk in recent years, lets add more hard to maintain code. Because language natively can do this on its own.
It can do it, does not translate it should do it.
1
Mar 17 '24
Four years later, we are here. knex still has a good performance and a very good learning curve. The last update 3 months ago. seems to be being held with affection.
0
Dec 10 '19
[deleted]
3
u/spacejack2114 Dec 10 '19
You can write a lot of SQL with Knex without resorting to raw, and I think it has a pretty nice API. The downside is you have to know how to write the SQL, then you need to know how to write it in Knex.
9
u/kelmore5 Dec 10 '19 edited Dec 10 '19
I mean, as someone who came from a Python / Java & JPA background to using JS, Knex makes a lot of sense to me. I feel like it reads better as JS code then SQL queries do. There may be real advantage in using only queries for the sole purpose of showing DBAs, but why would a DBA be looking over JS anyway if that was the case?
Also, this seems like a plug for the author's alternative. Seems like a lot of people agree too: https://www.reddit.com/r/node/comments/apu4tn/stop_using_knexjs_and_get_30/