Reputation: 2258
I find Pony to be a nice orm to use for small projects. However, when your project grows past a certain point placing @db_session in your functions becomes almost compulsory for every function that is written.
Following SOLID principles, I am trying to interface the PonyORM. However, it is turning out to not be as easy as I thought.
class CustomQuery(object):
def __init__(self, query):
self.obj = query
def __getattr__(self, attr):
return getattr(self.obj, attr)
@db_session
def count(self):
return self.obj.count()
@db_session
def first(self):
return self.obj.first()
@db_session
def without_distinct(self):
return self.obj.without_distinct()
def __iter__(self):
return self.obj.__iter__()
class DatabaseService:
@staticmethod
@db_session
def select(*args):
# This will be select() interface
return CustomQuery(select(*args))
This is an example of what Im trying to do. However I'm running into issues when I do some thing like:
# User has many PhoneNumbers
user = User.select().first()
assert isInstance(user, CustomQuery)
user.phone_numbers.count()
If I understand correctly, when doing user.phone_numbers.count()
a new pony.orm.core.Query
object is created.
I would like to instead return a CustomQuery
object instead which would allow for the db_session to persist.
Any thoughts to how this can be done? Or any other way others have dealt with a mess of @db_session
decorators?
Upvotes: 1
Views: 126
Reputation: 71
Firstly, it seems to me that you are trying to fight Pony design philosophy: the whole idea of the @db_session decorator is to relieve you from having to deal with database management (boilerplate code, open/close DB, SQL, rollback, etc.) and I understand that you want to do it yourself, hence rendering the ideas of @db_session moot
Secondly, by nature, unless a decorator has side effects at call time, it is just a wrapper that starts and ends with the call. So the idea to have it persist is also going in the opposite direction of its intended purpose.
All in all, if you want to do the work of the facilities pony offers you, you may better just quit using pony altogether.
Perhaps, you should ask yourself why you want pony and why you want to get rid of the decorators. Having made up your mind will help you take the right decision for you.
HTH
Upvotes: 1