@@ -242,8 +242,43 @@ class EntityMeta(type):
242242
243243 def __init__ (cls , clsname , superclasses , attributedict ):
244244 super ().__init__ (clsname , superclasses , attributedict )
245+ cls .validate_cached_relationships ()
245246 if clsname != "Entity" :
246247 setattr (Entity , clsname , cls )
248+ if not hasattr (Entity , 'entities' ):
249+ setattr (Entity , 'entities' , [])
250+ Entity .entities .append (cls )
251+
252+ def validate_cached_relationships (cls ):
253+ """
254+ Graphql doesn't allow for infinite nesting in queries.
255+ This function checks that cached relationships result in valid queries.
256+ - A cached object and not have its own cached relationships.
257+ """
258+
259+ cached_rels = [r for r in cls .relationships () if r .cache ]
260+ print (cached_rels )
261+ # Check if any cached classes have their own cached fields
262+ for rel in cached_rels :
263+ child_name = utils .title_case (rel .name )
264+ if hasattr (Entity , child_name ):
265+ for sub_rel in getattr (Entity , child_name ).relationships ():
266+ if sub_rel .cache :
267+ raise TypeError (
268+ "Cannot cache a relationship to an Entity with its own cached relationship(s). "
269+ f"`{ utils .snake_case (cls .__name__ )} ` caches `{ rel .name } ` which caches `{ sub_rel } `"
270+ )
271+
272+ # If this cls has cached fields check if any existing object caches this cls.
273+ if cached_rels :
274+ for entity in Entity .entities :
275+ attr = {rel .name : rel for rel in entity .relationships ()
276+ }.get (utils .snake_case (cls .__name__ ))
277+ if attr and attr .cache :
278+ raise TypeError (
279+ "Cannot cache a relationship to an Entity with its own cached relationship(s). "
280+ f"`{ utils .snake_case (entity .__name__ )} ` caches `{ utils .snake_case (cls .__name__ )} ` which caches `{ cached_rels } `"
281+ )
247282
248283
249284class Entity (metaclass = EntityMeta ):
0 commit comments