From 2ac2159a0a5b31f28e7c24e596f288c483451f41 Mon Sep 17 00:00:00 2001
From: Renaud Le Gac <renaud.legac@free.fr>
Date: Thu, 31 Mar 2011 18:46:41 +0000
Subject: [PATCH] Add a method to build the query to resolve foreign key.

---
 modules/plugin_dbui/foreignfield.py | 37 +++++++++++++++++++++++++----
 1 file changed, 32 insertions(+), 5 deletions(-)

diff --git a/modules/plugin_dbui/foreignfield.py b/modules/plugin_dbui/foreignfield.py
index 58d9b72e..91b604cd 100644
--- a/modules/plugin_dbui/foreignfield.py
+++ b/modules/plugin_dbui/foreignfield.py
@@ -14,11 +14,13 @@ K_KEY = "k_key"
 class ForeignField(dict):
     
     def __init__(self, db):
-        """ Scan the database model to identify foreign key,
-        Store the pointing table and field.
+        """Scan the database model to identify foreign key,
+        and to store the parent table, field and key.
         
         """
 
+        self._db = db
+        
         for table in db.tables:
             fields = [db[table][el] for el in db[table].fields]
             
@@ -50,7 +52,7 @@ class ForeignField(dict):
                             
     
     def is_foreign_field(self, table, field):
-        """ Return true is the table.field is a foreign key.
+        """Return true is the table.field is a foreign key.
         
         """
         if table in self:
@@ -65,8 +67,8 @@ class ForeignField(dict):
     
      
     def get_foreign_data(self, table, field):
-        """ Return a tuple containing the pointing table, the pointing field 
-        and key for the join:
+        """Return a tuple containing the parent table, the parent field 
+        and primary key of the parent table for the join:
         
             table.field --> k_table.k_field
             table.field == k_table.k_key
@@ -80,3 +82,28 @@ class ForeignField(dict):
         
         else:
             return None
+
+
+    def get_where_query(self, table):
+        """Return the query in order to handle foreign table. 
+        Return None is there is no foreign keys.
+        
+        """
+        if not self.is_table_with_foreign_fields(table):
+            return None
+
+        db, query = self._db, None
+
+        for field in self[table]:
+            
+            k_table = self[table][field][K_TABLE]
+            k_key = self[table][field][K_KEY]
+            
+            condition = db[table][field] == db[k_table][k_key]
+            
+            if query:
+                query = ((query) & (condition)) 
+            else:
+                query = condition
+                
+        return query
\ No newline at end of file
-- 
GitLab