Then simply open the file and use it as a source for relations:
Output:
If you want to understand exactly what this query does, just try removing one line at a time from the bottom (starting with summarize) and re-run the script!
Understanding SQL Compilation
In the example above, we can’t run to_sql on the second relation (total_weights_in_paris) because the extend uses a native Ruby function, which prevents both extend and summarize to be translated to SQL.
To better understand why the query works (JSON.pretty_generate returns the expected result), let’s debug the query tree (.debug can always be chained, it returns the relation itself):
As you can see, extend and summarize enclose the SQL query and will be executed by Bmg itself, after the SQL part has been executed and a result obtained from the database. This does not prevent chaining further, Bmg will even optimize subsequent chained operations and push everything it can to the SQL engine.
In the example below, observe how the restriction on “Smith” yields a WHERE clause in SQL, although the restrict operation is chained after extend and summarize: