by bigpeopleareold · 11y ago · 0 comments
I can never, ever remember the intricacies of the Sequel API or any one of these query builder APIs. I am always looking up something that is rather trivial because I am thinking in SQL, the language, and always have to convert back to Ruby or whatever language I am working in.
CTEs and SQL functions in PostgreSQL strike a good balance in the composibility department for me, while still being able to write SQL.
How exactly are you going to just write SQL if the actual query statement needs to change based on the user input? Are you going to hardcode every possible permutation, or are you going to use a query builder? Or are there some advanced Postgres features that I'm not aware of that would allow all these combinations in some kind of prepared statement?
edit: The question I'm asking is pointed towards the people who are implying that you can "just use SQL" as static statements that are not dynamically assembled. Like a static function or prepared statement that takes some parameters, and at runtime you only pass in those parameters - not rejigger the actual SQL statement fragments. Your ad-hoc query builder implementations with SQL injection vulnerabilities are not relevant to what I'm asking.
How about something like this:
s = Select.new
s.add "WHERE title LIKE #{title}" if title
s.add "WHERE price <= #{price_range}" if price_range
s.add "LIMIT #{limit}" if limit
s.add "OFFSET #{offset}" if offset
s.add "id, blah, boo FROM products"
s.execute
Note how I deliberately shuffled the order and didn't bother with escaping.Also note how anyone who knows SQL could immediately work with this, learning curve: 5 seconds.
Why is there no ORM that works like this?
query = session.query(Products)
if limit:
query = query.limit(limit_val)
if offset:
query = query.offset(offset_val)
Sort is a bit tricky, but as I'm a noob at SQL Alchemy, I had some not-so-pretty boilerplate code implemented for decorating queries with custom sorts. But essentially it boiled down to: if sort_type == SORT_REVERSE_CONST:
sort_obj = sort_obj.desc()
else:
sort_obj = sort_obj.asc()
query = query.order_by(sort_obj)
And if you want to search through dynamic tables, change the initial query instantiation to something along these lines: query = session.query(retrieve_db_object(table_name))
And to execute: return query.all()All ORMs work "a bit like this". I don't want "a bit like this". I want exactly like this.
Because with my proposed interface I could be productive immediately and permanently. I would never have to refer to any documentation. Not once.
With every other ORM this is a pipe dream. Their "fancy" chainable wrapper-APIs are nothing but a ball on a chain.
Edit [responding to moe, below]: that's a matter of taste. I prefer to have my SQL _outside_ my code. If I have to write a little XML to make it happen, so be it. Additionally, unlike your example, a strict separation of SQL and data ensures SQL injection is not possible. That's also a worthy goal.
Does MyBatis have an API similar to what I outlined above?
Because the page that you link to shows a horror that I can't even begin to describe:
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
SQL mixed with proprietary XML soup?
Talk about combining the worst from all worlds...Because no one wants to write a SQL fragment parser. You would have write a parser that:
a) Could be started at an arbitrary place in a query and figure out what it needed to do.
b) Would be SQL-dialect aware. (Maybe -- it might be possible to skip this.)
Were it not for (a), I'd imagine you could quickly build this by using some kind of debug feature of the database -- sending it a query to parse and getting back a parse tree.
Knex is a very convenient, Promise-oriented query abstraction, and it has "raw" methods when only SQL snippets will do. http://knexjs.org/
select id, blah, boo
from products
where 1
and (title like :title} or if(:title = '', false, true))
and (price <= :price_range or if(:price_range = -1, false, true)
limit :limit
offset :offset
Its a trade off, bit of extra complexity in the query for simpler code logic. Really, I avoid using sql for these types of "search" / find methods, they're probably going to be slow as hell as soon as you get a sizable data set.I really despise orm's its essentially taking a black box (sql/database) and throwing it inside a much less tested, less optimized, less documented black box.
For what reason, I have no idea, nobody has ever been able to convince me there is a problem that needs solving. Almost every argument i've heard amounts to problems sql already solved a decade ago. I can only speculate but I'll hazard a guess it comes down to lack of enthusiasm to really learn sql properly (even though the person uses it / debugs it daily)
I'll try to write an example like that when I get home.
Of course, they're not "just SQL", and I do understand where the above comments come from.
And yes, sometimes I have to go look up how to do things I'd do trivially on SQL.
Because you're only showing a query builder, the "relational" not the "object mapper".
From an OOD point of view, if the end result of that query will be Product instances, why am I using a Select object to create them and why is it having to do some sort of string parsing to determine the objects I'm loading?
Because we can just infer the type to be returned via the FROM-clause of the query.
and why is it having to do some sort of string parsing to determine the objects I'm loading?
Because, to cite the immortal Larry Wall:
The computer should be doing the hard work.
That's what it's paid to do, after all.
-- Larry Wall
It has to do the string parsing, escaping and intelligent validation so I, the human, can write s.add "count(*) / sum(count(*)) * 100 as percentage"
instead of .select_append { ((count(star) / sum(count(star)).over) * 100.0).as(:percentage) }
The difference is that most people can read and write the former without thinking.The latter version may not look much more complicated at a glance. But as we all know these seemingly trivial fragments, more often than not, take ungodly amounts of very frustrating trial & error before they play along.
For example, here is :
{ type: 'select', columns: [{ expression: 'orgJobs.org_job_code', alias: 'job_code' }], joins: [{ table: 'org_jobs', alias: 'orgJobs' }], limit: 100, offset: 0 }
which yields:
select orgJobs.org_job_code as job_code from org_jobs as orgJobs limit 100 offset 0
and so its easy to do things like:
query.limit = 100;
and of course:
query.columns.push(additionalColumn);
and use something like lodash/underscore (or equivalent for your language) to add collection/array/object helper methods so you never have to write for-loops for things like mapping and property plucking.
http://www.ivc.com/blog/better-sql-strings-in-io-js-nodejs-p...
You don’t need another DSL to access relational databases SQL is already the best DSL for accessing relational databases. We don’t need to invent something new. Moreover the SQL syntax and features can differ from one database vendor to another.
I think the irony is that much of the problems of sql are related to a lack of tooling.
The lack of tooling is result of large numbers of devs being distracted by ORM which moves that particular problem into the language ide/editor.
Essentially we lack great *.sql editing, ide, macro, refactoring because of the lack of focus on sql itself.
edit: as an aside, string concatenation in the language of choice is its own road to hell.
Except that my other tools are just an editor like emacs and makefiles. So now to be productive I have to have and ide for sql, learn sql, learn macros.
Interesting that SQL came first. If it was so easy and obvious to use it we would not have seen any ORMs by now. But every other project that uses SQL databases ends up with some kind of ORM.
One of the reason is probably because there is an impedance mismatch. Code is already written dealing with objects, functions, pointers, data. But when it talks to the database it has to talk via a command line string interface so to speak.
There is another type of impedance mismatch and that is learning a new language. One can argue SQL is there to keep & manipulate the most precious things you have -- data, so one should spend time learning it well. But the other point is, SQL is there to keep & manipulate the most precious things you -- data, so don't mess with it if you don't know SQL very well. Let someone else learn it (the author of the ORM).
I am not arguing for one point or the other, just kind saying how it is interesting how we have been going in a circle the last 15 years or so.
I find LINQ + Entity Framework to be a blessing in C. Though I use the monad/function syntax not the LINQ query sugar when I use it.
sql-mode for some databases(mysql and oracle iirc) reads the DDL of the tables you are typing about, why is this not better and more general?
Sql is so well established and general as a solution that not learning it is a poor choice.
Notice that its only a yearish old I think?
Pgtap is on my list of things to poke around with.
edit: thanks btw
WHERE (_title IS NULL OR title LIKE _title)
AND (_minPrice IS NULL OR price > _minPrice)
AND (_maxPrice IS NULL OR price < _maxPrice)And I don't know what it would look like if the requirements changed to allow ordering by multiple columns with different possible sort directions... that might get back into dynamic SQL using a RETURN QUERY EXECUTE type of thing, which is basically using a query builder in your query language.
select c1, c2, c3, ... order by 2;
would order by "c2"
I can't speak specifically to Postgres, but, in my experience, there is nearly always a way to do what you want with bound parameters. No advanced features are required. It often results in poor performance and redundant code that is hard on the eyes. You will get what you deserve, but sometimes you don't have a choice.
Here is an example of the horror:
WHERE (:1 IS NULL OR :1 = item_id)
AND item_num BETWEEN NVL(:2,0) AND NVL(:2,9999999999)
AND item_date BETWEEN NVL(:3,'01-jan-1900') AND NVL(:3,'31-dec-4712')
AND item_name LIKE NVL(:4,'%')
ORDER BY
CASE :5 WHEN 'NUM' THEN item_num WHEN 'DATE' THEN item_date ELSE item_name END,
CASE :6 WHEN 'NUM' THEN item_num WHEN 'DATE' THEN item_date ELSE item_name END
Edit: I suppose you could also parameterize the ascending vs. descending sort, although I have never tried. My first thought is to duplicate each line in the ORDER BY clause: one bind parameter for ASC and another for DESC. Have each CASE return a constant if the bound value is NULL, and then bind NULL for the direction you do not want. Yuck.I am not advocating any of this but am pointing out that bind parameters can be abused in surprising ways if you are backed into a corner.
sql = 'SELECT * FROM products'
args = []
if title:
sql += ' WHERE title LIKE %?%'
args.append(title)
if upc:
if args:
sql += ' AND'
else:
sql += ' WHERE'
sql += ' upc LIKE %?%'
args.append(upc)
if price_min:
if args:
sql += ' AND'
else:
sql += ' WHERE'
sql += ' price >= ?'
args.append(price_min)
if price_max:
if args:
sql += ' AND'
else:
sql += ' WHERE'
sql += ' price <= ?'
args.append(price_max)
if order_by_name:
sql += ' ORDER BY name'
elif order_by_price_low:
sql += ' ORDER BY price'
elif order_by_price_high:
sql += ' ORDER BY price DESC'
conn.query(sql, args)The question I'm asking is pointed towards the people who are implying that you can "just use SQL" as static statements that are not dynamically assembled. Like a static function or prepared statement that takes some parameters, and at runtime you only pass in those parameters - not rejigger the actual SQL statement fragments.
Seriously, how is this different from "just use SQL". SQL was never really intended to be used by itself (except for manually typing queries into a console). Yes, what I wrote is code that writes code, but it's far different from a larger ORM or querying framework.
sql = "SELECT * FROM products WHERE TRUE"
....
if upc:
sql += ' AND upc LIKE %?%'
....
This saves having to worry about "AND" and "WHERE", and the extra "WHERE TRUE" results in the same execution plan (thus the same performance). SELECT
users.id,
users.email,
1
FROM
users
I can just use "--" to comment out any line without having to manage the last comma. Especially useful when building aggregations.I understand the impulse to "Just write SQL." But in practice, with all the string concatenation needed to generate actual queries, you can't really see what the SQL will be without running all the code in your head anyway.
I have written TSQL that changes the entire query (which was on the order of 80 joins) dynamically based on about ~20 different parameters, only a few actually passed into the stored procedure, the rest based on settings and configuration. It took a few hours to grok how everything came together at first, but a few tricks that the optimizer will remove means you can add arbitrary conditionals in whatever order you please.
The example you give is VERY trivial for dynamic SQL. postgres - http://www.postgresql.org/docs/9.1/static/ecpg-dynamic.html mssql - https://msdn.microsoft.com/en-us/library/ms188001.aspx
query = sprintf("select count(*) from data where %s = ?", column)
results = sql.execute(query, filter_value);
So long as you leave the "value" portion of the query as a '?' (or %s, or whatever your connector requires) and don't use direct user input for the column names, you're still safe from SQL injection.http://www.postgresql.org/docs/9.4/static/functions-string.h...
select(from('tab'), where(and(like('name','Mo%'),not(is('id',NULL)))However, the point is that I'd rather use SQL, it's simple as that.