3e4d7fbd8280a622d352ff1e9e607c3b3fe74fc9
[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 case att1.attname
10 when att2.attname
11 then att1.attname
12 else substring(att1.attname from '^.*(?=_'||att2.attname||'$)')
13 end as "id"
14 ,cl1.relname as "foreignTable"
15 ,att1.attname as "foreignColumn"
16 ,cl2.relname as "referencedTable"
17 ,att2.attname as "referencedColumn"
18 from
19 pg_constraint co
20 ,pg_class cl1
21 ,pg_class cl2
22 ,pg_attribute att1
23 ,pg_attribute att2
24 where
25 ( cl1.relname = \$1
26 or cl2.relname = \$1)
27 and co.confrelid != 0
28 and co.conrelid = cl1.oid
29 and co.conkey[1] = att1.attnum and cl1.oid = att1.attrelid
30 and co.confrelid = cl2.oid
31 and co.confkey[1] = att2.attnum and cl2.oid = att2.attrelid
32 order by
33 cl1.relname
34 ,att1.attnum
35 SQL;
36
37 /**
38 * A foreighn key implementation
39 */
40 class Relations
41 {
42 /**
43 * @var array
44 */
45 protected $references;
46
47 function __construct(Table $table) {
48 $cache = $table->getMetadataCache();
49 if (!($this->references = $cache->get("$table#relations"))) {
50 $table->getQueryExecutor()->execute(
51 new \pq\Query\Writer(RELATION_SQL, array($table->getName())),
52 function($result) use($table, $cache) {
53 $this->references = $result->map(array(0,1), array(1,2,3,4), \pq\Result::FETCH_OBJECT);
54 $cache->set("$table#relations", $this->references);
55 }
56 );
57 }
58 }
59
60 function __isset($r) {
61 return isset($this->references->$r);
62 }
63
64 function __get($r) {
65 return $this->references->$r;
66 }
67
68 function __set($r, $v) {
69 $this->references->$r = $v;
70 }
71
72 function __unset($r){
73 unset($this->references->$r);
74 }
75 }