Skip to content

Instantly share code, notes, and snippets.

@orther
Created July 23, 2014 02:19
Show Gist options
  • Save orther/e305aa4a69f551c390a2 to your computer and use it in GitHub Desktop.
Save orther/e305aa4a69f551c390a2 to your computer and use it in GitHub Desktop.
SQLAlchemy Argument and Example

This is from a facebood post Mehmet Ali 'mali' Akmanalp. These are two comments written by Mehmet Ali 'mali' Akmanalp:

Matt: so with SQLAlchemy the point is that the ORM is laid on top of this lower level SQL generator, so when the ORM is too specific and you need to fall back, you don't have to concatenate strings and you can generate syntactically correct and safe SQL through code. Check it: http://docs.sqlalchemy.org/en/rel_0_9/core/tutorial.html (scroll down for cooler examples).

Matt: let me give you an example from what I'm working on now. So let's say you have a generic query for fetching monthly aggregated import / export values between countries. Sometimes you want to filter by one country. Sometimes you want to filter by 10 countries. Sometimes you want to use the column containing the inflation-adjusted value instead of the regular column. Sometimes you want the average export instead of the total export.

With a low level abstraction layer, I can do stuff like already_complicated_query.filter(another_param==5). Or I can write a function that does get_world_trade_aggregate(country="USA", aggregate="average") and it'll generate the right query for me. But then that's not even all, if I have to modify or filter that query further in some other part of the code, in some unexpected way totally doable. It's less often that I have to write a whole new function or duplicate code.

So the point isn't the abstraction, it's the fact that it makes queries modifiable and composable, which is something you just can not have in raw sql. So given a query, I can decide to add something to it or change it without having to change the text based SQL. You know how it's good practice to split your 1000 line function into smaller, modular pieces? With this you can do that with your ginormous SQL query too. AND it's guaranteed to generate correct and safe SQL.

This also makes everything much more maintainable. E.g. If I change table names or migrate fields, often it's a non-issue and there is a single place I need to change that. But with raw SQL you have to go in and do a ctrl-f and hope you catch everything, but often you don't because someone decided that that field name should come from a variable or something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment