sanitize id computation
[m6w6/pq-gateway] / lib / pq / Gateway / Table / Relations.php
index 128dca7ebb53aae950c8059bce4add4a1cd73859..3e4d7fbd8280a622d352ff1e9e607c3b3fe74fc9 100644 (file)
@@ -6,11 +6,15 @@ use \pq\Gateway\Table;
 
 const RELATION_SQL = <<<SQL
 select
-        substring(att1.attname from '^.*(?=_'||att2.attname||'$)') as "id"
-       ,cl1.relname                                                as "foreignTable"
-    ,att1.attname                                               as "foreignColumn"
-       ,cl2.relname                                                as "referencedTable"
-    ,att2.attname                                               as "referencedColumn"
+        case att1.attname
+        when att2.attname
+               then att1.attname
+               else substring(att1.attname from '^.*(?=_'||att2.attname||'$)')
+        end          as "id"
+       ,cl1.relname  as "foreignTable"
+       ,att1.attname as "foreignColumn"
+       ,cl2.relname  as "referencedTable"
+       ,att2.attname as "referencedColumn"
 from
      pg_constraint co
     ,pg_class      cl1
@@ -30,17 +34,26 @@ order by
        ,att1.attnum
 SQL;
 
+/**
+ * A foreighn key implementation
+ */
 class Relations
 {
-       public $references;
+       /**
+        * @var array
+        */
+       protected $references;
        
        function __construct(Table $table) {
                $cache = $table->getMetadataCache();
-               if (!($this->references = $cache->get("$table:references"))) {
-                       $this->references = $table->getConnection()
-                               ->execParams(RELATION_SQL, array($table->getName()))
-                               ->map(array(0,1), array(2,3,4), \pq\Result::FETCH_OBJECT);
-                       $cache->set("$table:references", $this->references);
+               if (!($this->references = $cache->get("$table#relations"))) {
+                       $table->getQueryExecutor()->execute(
+                               new \pq\Query\Writer(RELATION_SQL, array($table->getName())),
+                               function($result) use($table, $cache) {
+                                       $this->references = $result->map(array(0,1), array(1,2,3,4), \pq\Result::FETCH_OBJECT);
+                                       $cache->set("$table#relations", $this->references);
+                               }
+                       );
                }
        }