0f946fa1154feca0dc0ac84be3a65b9f1caa3a73
[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 cl2
17 ,pg_class cl1
18 ,pg_attribute att2
19 ,pg_attribute att1
20 where
21 ( cl1.relname = \$1
22 or cl2.relname = \$1)
23 and co.confrelid != 0
24 and co.confrelid = cl2.oid
25 and co.conrelid = cl1.oid
26 and co.confkey[1] = att2.attnum and cl2.oid = att2.attrelid
27 and co.conkey[1] = att1.attnum and cl1.oid = att1.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 // FIXME cache
39 $this->references = $table->getConnection()
40 ->execParams(RELATION_SQL, array($table->getName()))
41 ->map(array(0,1), array(2,3,4), \pq\Result::FETCH_OBJECT);
42 }
43
44 function __isset($r) {
45 return isset($this->references->$r);
46 }
47
48 function __get($r) {
49 return $this->references->$r;
50 }
51
52 function __set($r, $v) {
53 $this->references->$r = $v;
54 }
55
56 function __unset($r){
57 unset($this->references->$r);
58 }
59 }