I know why activerecord does this: it's way easier to do the join in memory, so that one row is obtained per object and not an enormous row representing many, but not providing any utility for raw queries seems a big missing feature.
Edit: to be clear, by query I refer to read operations (select) that are not trivial (find one by id would be trivial)
But Ent is modeling data as a graph, and the DB behind the scenes is more of an implementation detail. The production version of Ent used at Meta stores data in TAO (https://engineering.fb.com/2013/06/25/core-data/tao-the-powe... my impression is that product engineers do not write any SQL when working with Ent at Meta.
That would be acceptable from my point of view. The problem is using SQL as a graph produces very inefficient queries once hitting a certain scale, but if the DB is already a graph, the problem should be limited.
Pushing graph queues down to a single SQL query so that the SQL DB spends massive CPU time on joins can be an issue. Instead these systems can avoid talking to the SQL DB at all for example if they’re on the happy path just chasing graph edges.
Ugh... what a bummer then.
Example of a query builder with built-in mapping capabilities (it’s mine):
https://github.com/bokwoon95/sq
I feel some exasperation when I see query builders that throw a query string back to the user and ask them to map the results themselves. That’s easily the most tedious and mistake-prone part of using SQL queries. In the case of my library, projection and mapping are handled by the same callback function so in order to SELECT a field you basically map it and it’s automatically added to the SELECT clause.
When you join 3 tables (assuming has many and "has many through" relationships), what you get back is enormous rows and multiple rows, all of this in tabular form, but in the software is usually represented as a graph. I'd love a library that helps building back these massive rows into relationships.
Please forgive me if your library does this, while I saw the "mapping function", I didn't see anything to help me build back graphs. I can map rows "easily", but I cannot recreate associations easily, it requires a bunch of work.
Hmm you've certainly given me something to think about. Thanks.
BTW joins are not challenging, but you made me realize I didn't show any joins in my basic examples. Here is an UPDATE with JOIN in the meantime: https://bokwoon.neocities.org/sq.html#postgres-update-with-j....
sql = "select blog.name, post.content, author.display_name from blog join post on blog.id = post.blog_id join author on post.author_id = author.id"
Assuming the relationship: many blogs have many posts and posts have one author, I'd expect something along the lines of (sudo code): schemaOnTheFly = Blogs{}.HasMany(Posts{}.HasOne(Author{}) // Sorry the syntax for this doesn't really exist
blogs := query.Exec(sql, params, schemaOnTheFly)
fmt.Printf("%+v\n", blogs[0].Posts[0].Author)
That's what I'd expect. Do notice that the schema is per-query, I'll let the developer handle the sharing portion of the schema (might be shared by a few queries)This is how SQLAlchemy does it. Lower level query tier you can use directly, and a higher level ORM tier that uses the query tier.
I disagree here. And I also don't like your framing.
Yes, type-level logic is harder to learn than understanding code you already read everyday.
It's also easier to count and calculate with your fingers and use concrete examples rather than learning abstract math. But we still do it, because in the end you learn it once and have a powerful tool that makes you more productive for the rest of your life and allow you do to things that you otherwise would never have been able to.
The same is true for code-generation in my opinion. And I believe it will change for Go as well. Go is not getting generics for no reason. It is because the push is strong - Go has more inexperierenced developers using it compared to other languages. But over time, they will turn into experienced developers. They learn more concept and want to become more productive. So they will gradually ask for more and more features until Go is nothing like it was before.
> 2. A good ORM solution should really build in permissions and composing mutations at a deep level. The previous generation of ORMs like ActiveRecord left this stuff to user space to everyone’s detriment.
Totally disagree. You can never solve those problems in a generic way for any domain. Just make it easy for the user to do it themselves.
> 3. Embedded DSL as query language is a blessing and a curse. It’s better than forcing engineers to learn a weird alternative to SQL strings, but more frustrating to experts. Use these tradeoffs with caution!
That's because SQL as a language has very very limited capabilities for abstraction. So every language will create a DSL to deal with it, even languages that can parse all the SQL and validate it at compile-time. Same reasons that I gave in 1.)
If I move the same type magic into codegen, the compiler is much happier; plus stack traces lead directly to a simple method implementation instead of jumping into difficult-to-follow proxy machinery. The downside is that the codegen logic that consumes the Typescript compiler API to understand the schema types is more complex than the mapped types before, but it does make it feasible to have my cake (derive an ORM/model API from a schema) and eat it too (not make the compiler so unstable and touchy).
I think codegen is OK as long as
- its designed in a way where it doesn't cause users to want or need to modify the generated code (this is the biggest downside of codegen)
- its against "relatively stable" API thing (protobuf / swagger descriptions, DB schema etc).
How do you handle the generated code? Do you check it into source control? If so, how do you ensure people do not touch it. Manually modified code generated code is one of the worst places to be in for maintenance. You mentioned you wanted language server support this means the generated code must not be ephemeral and continually visible to the rest of the project. When will this generated code need to be regenerated? On a schema change? How do you ensure the generated code always matches the schema?
Like I said all of these question can be answered, but it's quite a burden. In fact if I were you I would have looked into fixing the typescript compiler since the problems your ran into probably weren't fundamental. -
This ensures that generated code is consistent with its inputs (including the generator logic) for every merge to main. It prevents people from editing the generated code, since their edits will cause a diff in CI and fail the build, but no one ever actually loses their work since the codegen does not run automatically/continuously during local development.
Checking in the files also makes it very easy to review changes to the generator since you can always tell how the output is changing.
The total burden for the above system is:
- a 30 line command called `Notion assert-clean`
- A 30 line CircleCI job that loops over the list of code generator commands, calls the command, then calls assert-clean.
We’ve used that tactic for years for simpler stuff like “make sure the SQL dump is consistent with the SQL migrations” and “put all the file names in this directory tree into a typescript file so we can tab complete them”.
The only necessary bit is that your code generator shouldn’t be spitting out enormous mountains of unreadable code.
I have more than once implemented production code where 80% of the code is generated. With only the biz logic hand coded. Including a complex 50+ screen Typescript application developed from scratch in just 3 months.
However, as with any other tool, you have to use Codegen intelligently to get the benefits. I have more than once seen Codegen being used really badly. Making the people using it think that Codegen is always a bad idea. Codegen is a complex tool and there are many ways to use it incorrectly.
This is rather final. Honestly curious if this was shown to be the case or just the result of failed earlier attempts.
Often in Java/Kotlin projects people end up writing compiler plugins / annotation processors which is like moving the codegen to build time and making it harder to inspect/understand, while simultaneously spending more developer time on it since those systems may need to run for every compiler invocation. The same goes for Rust; rust’s various macro systems target the problem I have, but Rust users report long compile times due to macro magic. More esoteric languages like Scala and Haskell might have the expressive power I want, but don’t seem practical to implement for other reasons.
Of course there’s always the runtime only approach in Ruby/ActiveRecord but that runs into correctness problems at practical scales.
Codegen is usually brittle and is often ugly, but is guaranteed to have more metaprogramming power than in-language typelevel features. Ultimately any such system can be complex, I just hope to build one where the leverage I payed for with complexity is well worth it.
Well, if you can't use languages that make it possible/feasible, then code generation might indeed be the best option. It's just that your claim sounded quite general, so I had to jump in. :)
TypeScript can do this. It was done already halfway-well 6 years ago with way fewer features in TypeScript (https://github.com/brianc/node-sql/blob/master/lib/types.d.t...) - today we can do much better.
Its technically codegen but only from the schema; queries are fully typed on-the-fly.
You will also need to use a tuntime dsl to describe the schema, and then derive both the model classes and the model types from it (just because runtime parts cannot be derived from types)
Other than that, the rest is very possible.
This is kind of the whole ballgame right? How would you do any of this with types if the schema isn't defined until runtime?
The popular choice here is to use classes plus decorators, but its not the only choice
https://typegraphql.com/docs/introduction.html#what
The convenient bit here is that classes already have both a type and a runtime representation, and decorators are also available to attach any extra metadata necessary to that runtime representation
Interesting reading along the same lines is Language Oriented Programming (1994) http://www.gkc.org.uk/martin/papers/middle-out-t.pdf
Your own words are apt: I disagree here. And I also don't like your framing.
> Go has more inexperierenced developers using it compared to other languages. But over time, they will turn into experienced developers. They learn more concept and want to become more productive. So they will gradually ask for more and more features until Go is nothing like it was before.
Ignoring the rest of your comment, as well as the possibly snide remark regarding the experience of engineers who use Go, I believe this neither reflects reality nor the reality I wish to participate in.
Go eschews complexity, and is particularly paranoid of complexity sneaking in under the guise of convenience. Productivity is rarely hindered by having to hand-write a for-loop or some boilerplate to handle errors.
Go is designed to be easy to read and easy to write, to be comprehensible by both green and sage developers, and most importantly maintainable. This means preferring explicit behavior over implicit magic. The toolchain prioritizes fast compilation times over aggressive optimization.
I don't write Go to be productive (but I am very productive). I write Go so everyone can be productive. I don't want anyone spending time unraveling your life's work masterpiece. I don't want anyone to ever have to understand Scala or Haskell.
It's cool that you feel it necessary to reach for more powerful, expressive language constructs to be productive. I do not.
I would like to build something like Ent that is ergonomic and usable on both the client and the server in Typescript, and facilitates easily moving business logic between the two. The context at Notion is that we have a very smart client using something ORM-like and a somewhat dumb server using plain row record values, so while we do share some code between the two, it’s difficult to port larger features from the client to the server. It’s kind of the reverse situation that most people have, which is a smart server pushing GraphQL to a relatively dumb client.
There are a lot of people looking into client-focused or end-to-end database abstractions right now, so the space exciting. What the upstarts should learn from Ent is:
1. Codegen is powerful, and often easier to understand than a mountain of typelevel magic.
2. A good ORM solution should really build in permissions and composing mutations at a deep level. The previous generation of ORMs like ActiveRecord left this stuff to user space to everyone’s detriment.
3. Embedded DSL as query language is a blessing and a curse. It’s better than forcing engineers to learn a weird alternative to SQL strings, but more frustrating to experts. Use these tradeoffs with caution!