Ref #347. Ported propelorm/propel#616.

After several hours of fighting with the code it's finally done. 
![code-35](https://f.cloud.github.com/assets/450980/505122/8dcbc698-bd0f-11e2-8098-4f2471d861ac.gif)