125 points · by EntICOnc · 4y ago · 102 comments
Listing columns first Then table Then join Then filter Then group bys Then limit
The order of operations are out of whack and makes pipeline ing a little hard.
I found this to be closer to LINQ way
I hope in near future databases will come with better query languages...
1. Sql is non-modular
2. Non-orthogonal
3. Its parroting of the (beautiful) relational data model is... opinionated at best.
The standard is unreadable and not really implementable, one always has to resort to implementation docs.
Realistically there are no alternatives, but... sql is no good.
What more natural could there be than to write this as (old 1992 correlated query style)
SELECT cityName FROM Cities C WHERE ((SELECT COUNT() FROM Inhabitants I WHERE I.cityName = C.cityName) > 4000)
Agreed ???
YOU CAN'T DO THIS IN SQL [standard version] !!! You must write
SELECT cityName FROM Cities C WHERE (4000 < (SELECT COUNT(
) FROM Inhabitants I WHERE I.cityName = C.cityName))This makes SQL about the only language in the world that allows you to write "a<b" in certain places but forbids you to write "b>a" in those very same places. Some professional piece of language design.
(Disclaimer : I don't know how matters are in SQL:2016 wrt to this issue, but it drove a former IBM employee who was at the time a member of the SQL standards committee to (a) start work on TTM and (b) leave IBM as soon as he could.)
Table Out1 has translated versions of fields AA..AZ from table In1.
Table Out2 has translated versions of fields BA..BZ from table In1.
table Out3 has translated versions of fields X..Z from table In2, and the translation depends on some of the AA..BZ fields, in both translated and untranslated forms.
We'd end up with views that depended on other views and after expanding had like a dozen self-joins to add more fields that weren't included in the base view. And views that were selecting a big list of columns unchanged, plus adding a couple.
But somehow despite being an absolute ^%#@!^&$! it still worked better than the pointy-clicky ETL tooling we'd been using previously. Mostly because of the run->debug->modify cycle time being faster, and only a little because of avoiding pointy-clicky stuff.
2. What SQL functions are you talking about? There are builtins, e.g. avg, sum, and then there are User Defined Functions, which have nothing to do with SQL, mostly just a random external language or one of the non-portable PL/SQL flavours.
Practically speaking, one cannot really write portable SQL outside of a very limited intersection of various dialects. And within this limit users just cannot build a reasonably portable code library.
There is a reason why analysts working with SQL just copy massive query templates again and again and again...
It makes it really hard to offer good autocompletions too.
https://docs.microsoft.com/en-us/azure/data-explorer/kusto/q...
Query q = db.from("foo").join("bar").using("id")
.select("id","foothing","barthing");
However, the moment you want any non-trivial SQL expression, such an API becomes unwieldy. And yet the need for non-trivial SQL expressions in queries can't be avoided, nor can it be left to the host language.Also, I'd really like a SQL mode where no literal constants are allowed, as a mechanism to force the use of query parameters and prevent SQL injection.
Plus (assume my .where() example was Java), the host language compiler is never going to find a way to cope with the declaration of the 'input' of the 'lambda', *precisely* because [the definitions of] those things are outside the scope of what the host language compiler knows about. So you need a way to do something like "import my-db-definition;" And then you need to put machinery in place to verify at runtime that the definitions as they are for the db, are still the same (or compatible) with the definitions that the program was compiled with. Etc. etc. etc.
Lambdas in the host language won't play well with remote RDBMSes -- you'd have to be able to serialize the lambda and make the serialized form reasonably efficient. I'm skeptical of lambdas for expressions in DB query APIs.
An expression like `foo + bar` has to become `.expr(plus("foo", "bar"))`, except, if you take this to its limit you'll want to use non-string objects to identify column names and other such things, and, again, it quickly becomes unwieldy.
You cover some of this in your comment, so I think we're in agreement:
> That "the API becomes unwieldy" is in fact inevitable.
And yet an API is kinda desirable.
Ultimately I think a query language with no constant literals, only query parameters, compiling to a standard AST that can also be constructed by APIs, may be the best way forward. One could then write in a QL to start with, compile to an AST, serialize into a host language if desired, modify and use that, or always use the QL, or even always use the API, unwieldy though it would be. Then lambdas could actually be in the QL and compiled on the fly as needed:
Query q = db.query();
q = q.from(...).join(...).using(...)
.select(...);
q = q.where(q.expr("foo + bar < baz"));
Ok, that snippet has a problem if we want `q` to be a unique pointer. Let's fix it up a bit: QueryScope qs;
Query q = db.query();
q = q.from(...).join(...).using(...)
.select(...);
/* Get a context of in-scope identifiers, types, ... */
qs = q.getWhereScope();
/* Now we can compile an expression string */
q = q.where(qc.expr("foo + bar < baz"));
And a hybrid QL + API might look like: QueryScope qs;
Query q = db.parse("SELECT ... FROM ... JOIN ... USING (...)");
/* Get a context of in-scope identifiers, types, ... */
qs = q.getWhereScope();
/* Now we can compile an expression string */
q = q.where(qc.expr("foo + bar < baz"));However, it's good to have options, I wonder if prql will get traction. It would be great if it did.
I think it helps you focus on the outcome required, and makes you more efficient deciding how to implement it.
I use the same approach for methods in normal code: first decide on the signature of the method, and potentially a unit test to test it, and then think about the implementation.
db.Table.where(x=> x.name == 'abc').skip(10).take(20).groupBy()
This is really hard in sql especially with temporary tables and nesting you need to do as soon as you need to do things a little out of order...
Etc
Moreover, your very examples illustrate how "thinking SQL" is *NOT* the path to finding proper solutions. .skip() and .take() clearly originate from the world of ranking problems and it drips off of every word that you were thinking of finding a "modern" way to specify [things like] "TOP 10", but those solutions are themselves a fundamentally crippled way to attack the problem.
I may have to write a second post now to include some from this one that I missed!
https://datastation.multiprocess.io/blog/2022-04-11-sql-pars...
That said, I've heard the duckdb folks have improved on the postgres parser a bit.
[1] https://github.com/m-novikov/tree-sitter-sql
Also, is it just me or does the text of this article have an almost SEO-spam-like "texture" to it? It reads very unnaturally.
[0] https://pganalyze.com/blog/parse-postgresql-queries-in-ruby
A month ago, I needed a parser to parse SQLite schemas. SQLite has some edge case and I needed a lossless parsing to detect these edge cases.
I finally wrote my own parser [1] to fullfill my needs and to have some fun. This is for a POC project.
A couple of times where I've needed to parse SQL I would typically write a module for sqlite3 and get it to do the parsing for me. But annoyingly I can't remember _why_ I did this or what I was trying to achieve.
[0] https://15799.courses.cs.cmu.edu/spring2022/project1.html
Being read-heavy the app was an ideal candidate for output caching. But - there were no hooks in the admin code to add cache invalidation. And I wasn't going to crawl through 10s of thousands of badly written lines and add cache invalidation calls manually, because I would miss some.
So I hooked into the database layer, parsed the SQL queries and extracted the table names. The read-heavy pages on the frontend were tagged in the cache with the names of the tables they read data from. In the backend, I'd collect the table names in all the write SQL queries and then clear the cache that was tagged with these table names.
Working at the table level rather than row level it cleared more data than was needed, but it was simple and effective.
It worked really well but never went into production - in the end we forced a rewrite of the app. One day I'd like to revisit the idea.
A few examples:
- Inlining scalar function calls (less impactful now with Sql Server 2019)
- Removing joins from a query when we know it won't impact the number of records
- Deepening where conditions against derived tables
- Killing "branches" of union queries when they can be determined to not matter statically
Yes, we could write the queries that way in the first place, but it would make them harder to compose, more verbose, and harder for the programmer to communicate intent. Not to mention, often the user can impact what the query will be, making it less feasible.
.
- Inlining scalar function calls (less impactful now with Sql Server 2019)
write them as table valued funcs and it'll inline them for you (ugly but it works and is easy)
.
- Removing joins from a query when we know it won't impact the number of records
That's just tree pruning. It does that
.
- Deepening where conditions against derived tables
If I understand you that's predicate pushdown. MSSQL does it well.
.
- Killing "branches" of union queries when they can be determined to not matter statically
Not sure what you mean. Can you give an example?
We tested all of these before taking the time to do the rewriting, and no, either they don't, or they way they did it isn't good enough. You can say I'm lying if you want, I'm not going to spend time arguing about it.
Could I ask what your process is for detecting whether a rewrite rule is still useful in subsequent versions of the DBMS? Do you read the release notes and test things out manually, or do you have an automated A/B test thing going on?
Additionally, have you ever had a rewrite rule change from being beneficial to being detrimental after upgrading versions? If so, how did you detect that?
Thanks!
Edit: Also, what considerations do you have for rewrite rule order? Do you find that it makes a significant difference in practice?
We've never had a rule change from being beneficial to detrimental. For most of them, I don't think that would be possible, because they just involve giving Sql less irrelevant things to chew on. For a few of them, like the manual scalar function inlining, I could see that being possible, so we will just need to keep checking.
For rewrite rule order, I guess we just do the ones that can enable other optimizations first. So far, that has been pretty simple to determine. For example, when we trim joins from inner queries, we first trim their selections (depending on what is actually used in the outer queries).
^1 specifically https://github.com/DerekStride/tree-sitter-sql , but there are a few others around too
Since some of the tables are multi-petabyte with thousand of downstream consumers, the savings have been in the millions of USD, because of CPU savings mostly, but also there is the benefit of improved wall time and data arriving much earlier to dashboards and reports.
We also created some other datasets that tell you how the tables are normally joined and another team created a ML model that now we use in an internal tool that automatically recommends the best join keys when you join 2 or more tables (since we have lots of historical info on that already stored).
We also had to create a very efficient table profiler to evaluate the candidates, because in some cases there are columns that are widely used in equi-where conditions, but their cardinality is very high, making them bad partition columns.
One guy created a parser that actually gets the most common values used to filter each column, I guess we could use that in the future to materialize some views; my original vision of the project was to continue with partial aggregations for common computations. The thing is there are several pieces of code that are pretty much copy/pasted and reused in many pipelines, so why not materialize those and rewrite the SQL of the subsequent pipelines to leverage the materialized version? huge savings there.
We are planning to present it in VLDB or a similar forum, there are some aspects of it that we need to 'clean' if we want to open source it.
Other parts of the system include the candidate evaluation and the module that computes the expected savings for the best candidate selected during evaluation; this system in particular has a lot of specific Presto and Spark logic that might need to get more general if we want to open source it.
- syntax highlighting
- algebraic manipulations
- optimization analysis of queries seen
- analysis of equivalence of queries
- query rewriting (for style, performance, etc.)
- RDBMS portability layer (implement a common
subset of SQL, port queries to different
engines; see previous item)
I can probably think of more.I briefly looked into Apache Calcite and DataFusion[2], but I am unsure if I am on the right track. If someone has any ideas about where to look, please let me know.
[1] https://stripe.com/en-gb/sigma [2] https://github.com/apache/arrow-datafusion
That looks like an entire DB engine, isn't it?
> map the public schema to the private schema
sounds like view.
It seems like a pretty major project as you describe it.
Events we receive e.g. from MySQL aren't fully self-descriptive, you need to know the schema they adhere to in order to interpret them. As table schemas can change over time and as -- due to the async nature of streaming the transaction log -- we may receive change events produced from before a table's schema was changed, we cannot simply query the current table schema. Parsing incoming DDL events is the only way for keeping the connector's view on the schema in sync.
You can also reverse engineer missing foreign key relationships by parsing all of an apps' stored procedures (for relationship diagrams, etc.). Or just what external entities are referenced from "other" databases to get an idea of minimal schemas needed for automated testing.
Can someone say how this works exactly? What does parsing offer that things like logs and other metrics don't in terms of monitoring?