Why are String Formatted Queries Considered So Magical?

Duncan Booth duncan.booth at invalid.invalid
Tue Jun 29 06:32:49 EDT 2010


Owen Jacobson <angrybaldguy at gmail.com> wrote:

> However, not every programming language has 
> the kind of structural flexibility to do that well: a library similar 
> to SQLalchemy would be incredibly clunky (if it worked at all) in, 
say, 
> Java or C#, and it'd be nearly impossible to pull off in C.

I guess you've never used LINQ in C# then?

Microsoft did a pretty impressive job with LINQ: they provided a set of 
methods that may be used to query SQL databases and the same methods 
also work on any other sequence-like types. They also produced a DSL 
that compiles into the LINQ method calls which means that those who 
prefer SQL syntax can use it to process non-SQL data.

A LINQ expression produces a generator that allows you to iterate over 
the result set (and you can re-use the generator so that if it depends 
on the values of other variables or attributes each time you iterate you 
get a different set of results).

When you use LINQ on a SQL database internally it generates the correct 
SQL to produce the result set on the SQL server, when you use it on an 
array or other such sequence it uses generic functions compiled for the 
appropriate data types. In order to be able to do this they changed the 
language to allow expressions to compile either to executable code or to 
a parse tree. For example:

var participants =
    Competition.GetParticipants()
    .Where(participant=> participant.Score > 80)
    .OrderByDescending(participant => participant.Score)
    .Select(participant => new { participant.Id,
                                 Name=participant.Name });

If this is operating on a database table the Where method is overloaded 
to accept a parse tree as its argument and it can then use that to 
generate SQL, but for .Net objects the Where method simply uses the 
lambda expression as a callable delegate.

(example cribbed from 
http://geekswithblogs.net/shahed/archive/2008/01/28/118992.aspx)

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list