top | item 44048348

(no title)

fixprix | 9 months ago

C# can turn lambdas into expression trees at runtime allowing libraries like EF to transform code like `db.Products.Where(p => p.Price < 100).Select(p => p.Name);` right to SQL by iterating the structure of that code. JavaScript ORMs would be revolutionized if they had this ability.

discuss

order

whstl|9 months ago

Good answer. To elaborate on it and provide examples.

In languages that don't have expression inspection capabilities you have to replace the `(p) => p.Price < 100` part with something that is possible for the language to inspect.

Normally it's strings or something using a builder pattern.

For example, in TypeORM:

    queryBuilder.where("product.price < :price", { price: 100 })
And in Mongoose:

    Product.find({ price: { $lt: 100 } });
The LINQ-ish version would be:

    Product.find((p) => p.price < 100);
--

Similarly, for Ruby on Rails:

    Product.where("price < ?", 100)
Ruby's Sequel overloads operators to have a more natural syntax:

    DB[:products].where { price < 100 }
But the "lambda" syntax would be:

    Product.where { |p| p.price < 100 }

pjmlp|9 months ago

Sadly expression trees got out of love in modern .NET and it remains to be seen how much they will ever improve them.

https://github.com/dotnet/csharplang/discussions/158

contextfree|9 months ago

The last comment thread by agocke is interesting. I've thought before that it's unfortunate that LINQ and expression trees were implemented before the move to Roslyn, because if they'd been implemented afterwards they could maybe have just directly used the same object model that the compiler itself uses, which could make it more sustainable to keep them in sync with language changes.

shellac|9 months ago

Java has two somewhat related projects in this space, and it does add a substantial cost to language changes (assuming you commit to keep expression trees up to date). https://openjdk.org/projects/babylon/ is the most interesting to me, as a linq+++ potentially.

zigzag312|9 months ago

An interesting thing about expression trees is that with JIT they can be compiled at runtime, but with AOT they are interpreted at runtime.

vosper|9 months ago

> JavaScript ORMs would be revolutionized if they had this ability.

Is this possible in JavaScript?

paavohtl|9 months ago

Not easily. There's no built-in way to access the abstract syntax tree (or equivalent) of a function at run time. The best thing you can do is to obtain the source code of a function using `.toString()` and then use a separate JS parser to process it, but that's not a very realistic option.

Arnavion|9 months ago

There is a limited form of such "expression rewriting" using tagged template strings introduced in ES2015. But it wouldn't be particularly useful for the ORM case.