autoload; cache; tests;
[m6w6/pq-gateway] / lib / pq / Gateway / Table / Relations.php
1 <?php
2
3 namespace pq\Gateway\Table;
4
5 use \pq\Gateway\Table;
6
7 const RELATION_SQL = <<<SQL
8 select
9 substring(att1.attname from '^.*(?=_'||att2.attname||'$)') as "id"
10 ,cl1.relname as "foreignTable"
11 ,att1.attname as "foreignColumn"
12 ,cl2.relname as "referencedTable"
13 ,att2.attname as "referencedColumn"
14 from
15 pg_constraint co
16 ,pg_class cl1
17 ,pg_class cl2
18 ,pg_attribute att1
19 ,pg_attribute att2
20 where
21 ( cl1.relname = \$1
22 or cl2.relname = \$1)
23 and co.confrelid != 0
24 and co.conrelid = cl1.oid
25 and co.conkey[1] = att1.attnum and cl1.oid = att1.attrelid
26 and co.confrelid = cl2.oid
27 and co.confkey[1] = att2.attnum and cl2.oid = att2.attrelid
28 order by
29 cl1.relname
30 ,att1.attnum
31 SQL;
32
33 class Relations
34 {
35 public $references;
36
37 function __construct(Table $table) {
38 $cache = $table->getMetadataCache();
39 if (!($this->references = $cache->get("$table:references"))) {
40 $this->references = $table->getConnection()
41 ->execParams(RELATION_SQL, array($table->getName()))
42 ->map(array(0,1), array(2,3,4), \pq\Result::FETCH_OBJECT);
43 $cache->set("$table:references", $this->references);
44 }
45 }
46
47 function __isset($r) {
48 return isset($this->references->$r);
49 }
50
51 function __get($r) {
52 return $this->references->$r;
53 }
54
55 function __set($r, $v) {
56 $this->references->$r = $v;
57 }
58
59 function __unset($r){
60 unset($this->references->$r);
61 }
62 }