64 points · by valenterry · 2y ago · 145 comments
Not to mention this practically invites dumb string interpolation in SQL preparation, undoing decades of work to rid the world of this terrible habit. (Edit: This problem is solvable.)
Don’t try to be clever, use a structured format (JSON, protobuf, etc.) with a well documented schema.
Note that I’m only talking about APIs. It’s an entirely different matter if your product allows users to type in and send complex queries interactively.
* Forget about nascent LLM-interpreted natural language as programming language.
"and": [ { "property": "material", "operator": "equals", "value": "carbon" },
Would be;
["and", ["=", "material", "carbon"], ...]
https://developers.google.com/google-ads/api/docs/query/over... https://developer.intuit.com/app/developer/qbo/docs/learn/ex... https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.... https://carto.com/developers/sql-api/
From an end user standpoint, I preferred working with such API than with the ones creating nested json filters structures to model the filtering logic. It also provides a convenient way to select fields in the response, better in my opinion than "field mask" alternative that you can find on other APIs.
I don't see an issue in failing to optimize queries. The database does query planning on the fly. You do have to be a bit careful that you don't generate queries that can DoS your DB, but all solvable and not drastically different than a developer adding a new query to the product. What we do does create a prepare statement on the fly. We process the input query and generate SQL and collect each value the user as input into arrays for the types the correspond to and then index those arrays. So, for example, the query "pr:123 and (user:foo or user:bar)" would turn to SQL like: "pull_request = ($1)[1] and (user = ($2)[1] or user = ($2)[2])" (this allows us to statically type our queries).
In short, if your requirements that users should be able to generate complex queries, I think this is significantly better than JSON. And you can process an input language into JSON and the problem is effectively the same from that point.
Databases do query planning, but some of them cache query plans based on the SQL text before substituting arguments, and may optimise reoccurring queries more aggressively.
Even if there are three applications, this blog post isn't saying every single problem has to be solved this way, so if you're one of the people solving one of those three problems, this could be a great solution for you.
> Databases do query planning, but some of them cache query plans based on the SQL text before substituting arguments, and may optimise reoccurring queries more aggressively.
Ok, and? Even if we go with your JSON solution, you still need to query the database at the end of the day, and your JSON query is not going to translate into the exact same SQL every time (unless you're doing very limited set of operations). I'm not sure what the real advice or information is here. Are you saying we should just never do some query language that translates to SQL at all? All SQL queries should just be dynamic on the input parameters? Even if your statement on query plan optimization is true, how do we know it matters for the product? Maybe slightly longer queries are totally fine in this context?
I used it for this exact usecase, we had some data in postgress and front-end had limited api, and readonly postgrest was simpler than adding the api I needed to the frontend.
This means, extending the API by allowing more and more parts of SQL is easy and still backwards compatible.
It's much harder to come up with a custom language / structure from the get-go that doesn't cause backwards-compatibility issues down the road. I guess I should have emphasized this point in the article a bit more, thank you for the comment.
Okay, so now you find some way to bundle many queries, with allowances for connecting the result of one query to another, into a single request with all the results in a single response. Congratulations, you just recreated GraphQL.
I'm not saying that I suggest to do that, but for the specific point that you mention, I don't see any theoretical advantage of GraphQL in terms of performance.
I've been playing around with this idea of using this language as a colloquial standard for writing things like a DB poxy/cache or a "standard" interface for something like a ECS based OLAP-esque on columnar stores. Nothing to report at the time but I love to hear from people who have worked on a similar thing.
I'm expecting raw SQL to replace the API for a whole class of apps.
Throw in an event sourcing architecture for server side processing and you have a single SQL based API for all operations.
In the normal usage we have special tag prefixes with meaning, and now each query entry point has the same query language and you just need to know what the tag prefixes mean for that context.
I haven't done it yet, but next step is to add a complexity limit, that way people just can't send us queries that will DoS the database.
- it's insecure (update anything, anywhere! just need to get by check constraints)
- it's slow (table scans, when I meant to use index)
- it's bad for horizontal scaling (things like sharding fundamentally relies on shrinking the domain of access patterns).
Solve that by introducing some sort of capability system into the query language (think foreign keys, forward or backward), and we can make major strides on all fronts.
It's entirely possible to add permissions and access control on any modern dbms.
> - it's slow (table scans, when I meant to use index)
Maybe you are using an OLTP when you meant to use an OLAP dbms?
> - it's bad for horizontal scaling (things like sharding fundamentally relies on shrinking the domain of access patterns).
See above.
SQL is more adequate as a "language" or "standard" because that's what it is. What matters is that the underlying dbms that offers this functionality is appropriate.
My understanding is this is all mandatory access control which is cumbersome as usual.
> Maybe you are using an OLTP when you meant to use an OLAP dbms?
"It's slow" was too pithy. When it's fast it great, but it's too easy to write things that are slow my mistake. I want things to be rejected if it they don't use an index in many cases, not fall back on a slow table scan.
The most key part is that I posit that the "when are table scans allowed?" policy is very similar to the security policy.
SQL is more than adequate as a "language" or a "standard".
... WHERE (either A or B or C) (either beginswith OR endswith) (either X or Y or Z)
i.e. expressing the condition in a way closely mirroring the English syntax, instead of having to fully write out all 18 (=3x2x3) clauses. (Natural rules for short-circuiting would apply, so if 'A beginswith X' evaluates to true, no further conditions need be check)This isn't just limited to query languages. In many programming languages, it strikes me as odd that I can't write something like `if A is (either X or Z)`, which mirrors how I would naturally express the condition in English, but need to reformulate it as `if A is X or A is Z`, or (worse IMO from the readability standpoint) something like `if [X,Z].includes(A)`.
Don't be too quick to assign rationality where its absence will do. If SQL has been despised it's quite possible the reasons have never been any good.
See https://vincent.bernat.ch/en/blog/2023-sql-like-language-fil....
We have been seeing this trend (or pendulum swing) of pushing SQL and simplicity. I am not saying this solution is simple (will leave that for discussion).
Tangential, if this kinda stuff is interesting, folks might be interested in what Omnigres (disclaimer: my employer) is doing with the python integration in Postgres
INSERT requests would create forms, SELECT would create a table.
The idea was that you could create something simple like an BBS with only a few lines of code:
CREATE TABLE posts (title TEXT, content TEXT)
INSERT INTO posts (title, content) VALUES (request.title, request.content)
SELECT title, content FROM posts
It actually works! Here's the code on GH: https://github.com/seisvelas/Sea-QuillSadly, I stopped working on it after only 1 or 2 weekends because I switched professions to cybersecurity and had too much to learn - every weekend thereafter was CTFs or bug bounties.
Oh well! Someday I'd like to write a more intuitive, "conventional" style language for Urbit, maybe called HoonScript or something. So my affection for Racket's language oriented programming will (maybe, one day) not be in vain!
So just use postgrest.
But, even if they did reinvent half of postgrest, there are plenty of reasons this might be the right choice given more contextual information, tech decisions aren't made in a vacuum, it just might not be possible to use postgrest.
It worked nice, but apart from querying logs, I don’t see a use case where one would do this rather than just creating api endpoints.
ODATA [1] is probably the main one, and it’s adopted by e.g. Microsoft’s Azure APIs. JSON:API [2] is another, although I’ve never seen it used anywhere personally.
They’re both pretty heavy specifications so I’ve never bothered implementing anything that 100% follows them. But I have picked bits and pieces from time to time—in particular ODATA’s idea for filtering is nice and comprehensive imo, and there are a number of libraries in various languages which handle parsing its filter strings into structured data.
My main issue is that joins will be processed locally, so all the foreign data will be fetched before the join happens. But otherwise basic CRUD is easy.
https://wiki.postgresql.org/wiki/Foreign_data_wrappers
Specifically, https://google.aip.dev/assets/misc/ebnf-filtering.txt which is a modification of their common expression language https://github.com/google/cel-spec
Edit: totally forgot to add the actual link. Here goes: https://security.stackexchange.com/questions/229954/why-cant...
The key advantage here being the ability to package this into a library, instead of everyone and their mother rolling their own.
[0] Skip the API, Ship Your Database - https://fly.io/blog/skip-the-api/
psql --host=crt.sh --port=5432 --username=guest certwatchJust create a sql user with the correct access rights. Don't reinvent the wheel.
QoS could be a problem, indeed. If QoS it is an issue in the case one is working on, exposing your data as SQL might not be best choice, and neither is exposing any type of api that causes the server to have to do hard work.
For small applications with a hundred to a few hundred users using the databases own user management is quite handy. You can be very sure that you don't leek information and you can be quite certain that potential bugs in your application code won't lead to many of the common security vulnerability's that exist.
It seems to me that there is a large gap between "inject SQL from the user directly into the database" and "provide a limited query language that can be translated to SQL". There are plenty of situations where the latter is totally fine. Is that reinventing the wheel? I don't think so.
But faster than you can imagine, the next requirement comes in: OR filters!
bicycles that are (made of steel AND weigh from 10 to 20kg) OR
(made of carbon AND weigh from 5 to 10kg)
Hmm.. I don't know if this is a good example. I have been in the product search space for almost 10 years now and that feature request never came up. And I cataloged thousands of feature requests users had about product search interfaces.In the rare case users do something like this, they usually use two tabs. One, where they compare steel bikes and one where they compare carbon bikes.
It makes sense, when you think about the frontend implications. Users are very used to checkboxes and range sliders. The user would check "steel" and set the range slider to "10-20". Now how do they expect to duplicate the sliders and the checkboxes to construct the alternative configuration? They open the page in a new tab and use the alternative settings in that tab.
However, it's not only about the users as in the visitors of the shop. It can also be a feature such as "show similar bicycles" that will require more complicated queries. And while it's of course possible to maybe run multiple queries and combine the results by code, it can be nice to just do it in one query that is easy to understand and debug/optimize because it's pretty much just SQL.
Additionally, tons of products do support "OR". Take the Amazon search. It has sections that are "OR" inside of them and "AND" across the sections.
We don't? Why not?
- Exposing an API that accepts SQL is crazy.
- It's a terrible idea.
- Especially if the API is exposed on the internet.
That isn't reasoning. We don't encounter actual reasoning until:
- Doing that is insecure
- itwill lead to SQL injection attacks
- it is a nightmare to maintain
- it will lock the backend implementation into a specific technology
Even these are highly debatable, so I ask again, why not just expose a SQL API, even over the Internet?
No. I don’t agree at all. Creating a custom query language based on json or lisp or whatever is easy enough, flexible enough, prone to evolution, and helps building an abstraction between the front and the back. With this in mind, the day you decide to query an ElasticSearch instead of the RDBMS, the frontal API doesn’t need to change, there’s juste to update the translation layer to generate an ES query instead of SQL.
Exposing SQL to the API is an awful idea.
1. Access control.
Table and column-level access control. Row-level restrictions by expressions.
Out-of-band table filters that the user cannot override in the query.
2. Query complexity restrictions.
Allow queries only using the index. Restrict the maximum number of records to scan. Limit the max query runtime or maximum memory consumption.
Out-of-band limiting on the result size.
3. Rate limiting.
Limit the number of rows or bytes scanned over a period of time for a user, for an IP address or IP subnet.
4. Interfaces and formats.
CORS headers. HTTP compression. TLS. Proxy protocols.
JSON with metadata, Protobuf, etc.
TLDR. It works with ClickHouse; it is doubtful with other DBMS.
For example, you might have a table "users" but while "admins" can see all users, "moderators" might only be allowed to see the users of their moderated areas.
As soon as this kind of flexibility is needed, solutions like Postgrest stop working - they are just not made for that level of customization.
It's kind of weird designers of GraphQL spent so much effort on cherry picking results but left query part static.
It should be called PickResultLang (PickRL) instead.