Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

impl prefetched #18

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions peewee.py
Original file line number Diff line number Diff line change
Expand Up @@ -5175,6 +5175,18 @@ def save(self, force_insert=False, only=None):
def is_dirty(self):
return bool(self._dirty)

def prefetched(self, fk):
'''
Accepts a ForeignKeyField.
Returns true/false representing if accessing this attribute will trigger a database query.
'''
if isinstance(self, fk.model_class):
if getattr(self, fk.db_column) is None: return True
return fk.name in self._obj_cache
if isinstance(self, fk.rel_model):
return isinstance(getattr(self, fk._get_related_name()), list)
raise AttributeError('ForeignKeyField %s is not related to this model.' % fk)

@property
def dirty_fields(self):
return [f for f in self._meta.sorted_fields if f.name in self._dirty]
Expand Down
45 changes: 45 additions & 0 deletions playhouse/tests/test_query_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,51 @@ def test_aliasing_values(self):
self.assertEqual(results, [('u1', 'u1'), ('u2', 'u2')])


class TestPrefetchDetection(ModelTestCase):
requires = [Parent, Child, Orphan]

def setUp(self):
super(TestPrefetchDetection, self).setUp()
u1 = Parent.create(data='u1')
u2 = Child.create(parent=u1, data='u2')
u3 = Orphan.create(data='u3')

def test_prefetched(self):
u2 = (Child
.select(Child, Parent)
.join(Parent)
.first())
self.assertTrue(u2.prefetched(Child.parent))

def test_not_prefetched(self):
u2 = Child.select().first()
self.assertFalse(u2.prefetched(Child.parent))

def test_prefetched_null(self):
u3 = (Orphan
.select(Orphan, Parent)
.join(Parent, JOIN.LEFT_OUTER)
.first())
self.assertTrue(u3.prefetched(Orphan.parent))

def test_not_prefetched_null(self):
u3 = Orphan.select().first()
# even though it's not joined, we know the model
# is null because the FK value is null.
self.assertTrue(u3.prefetched(Orphan.parent))

def test_prefetched_nonsense(self):
u2 = Child.select().first()
def f():
u2.prefetched(Orphan.parent)
self.assertRaises(AttributeError, f)

def test_prefetched_set(self):
u2 = Parent.ALL.plus(Child.parent).first()
self.assertTrue(u2.prefetched(Child.parent))



class TestJoinedInstanceConstruction(ModelTestCase):
requires = [Blog, User, Relationship]

Expand Down