In an effort to increase the code quality of contributions to ERPNext and other frappe apps, I’ll start to post some examples of code I found and how it could be done better.
My code is of course not perfect. You’re welcome to comment suggestions on how it could be improved.
Great contribution and have to agree! People should be aware Frappe has put tons of hours to built a framework so we don’t have to write manual SQL just like you don’t go building all the Js code for a view, you shouldn’t go writing SQL queries on a whim.
This is nice content to have in the documentation!
Hi all,
May be not the right place but how to use or can be done:
Frappe.db.sql(“select name from tabSales Invoice where created = (select max(created) from Sales invoice)”)
With the max(), you are leveraging the power if sql.
In this case, you’ll need more some python code with a frappe.get_all()
And yes, then frappe.db.sql() with embedded sql functions becomes more efficient.
Just my 2cts, definitely not an expert on the subject.
@rmeyer, good one!! I didn’t think of it that way. It does work
Similarly, how would you find an average or a sum using the frappe.get_list() or frappe.get_all() commands. It seems it can be done with frappe.db.sql() command using the AVG, SUM, COUNT.
I am bringing this up as I am trying to generate some reports that bring up vizualisations on average.
@rmeyer , thank you so much !!!
Working in education, fields I was really looking forward to these xtra sql commands.
Where did you find documentation for these?
Btw: lived in Leipzig for 2 years in 2003-2005, and absolutely loved my time there.
but have no idea how to cater for the UNIQUE constraint. Since frappe.db.sql is not defined client-side, I’m currently returning the entire dataset and then remove duplicates in JS. It’ll be lovely to remove duplicates with the API call.
@EugeneP my examples were in Python, your code seems to be JavaScript. SQL queries shouldn’t be possible from the client side (in JavaScript) in the first place.
Also there’s no “SELECT UNIQUE” in MariaDB, so this wouldn’t work as well.
But you can try the parameter distinct=1 for frappe.get_list: