7ad5326a84931c84f7fe1c8e40bcc747ad48c913
[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 /**
34 * A foreighn key implementation
35 */
36 class Relations
37 {
38 /**
39 * @var array
40 */
41 protected $references;
42
43 function __construct(Table $table) {
44 $cache = $table->getMetadataCache();
45 if (!($this->references = $cache->get("$table#relations"))) {
46 $table->getQueryExecutor()->execute(
47 new \pq\Query\Writer(RELATION_SQL, array($table->getName())),
48 function($result) use($table, $cache) {
49 $this->references = $result->map(array(0,1), array(1,2,3,4), \pq\Result::FETCH_OBJECT);
50 $cache->set("$table#relations", $this->references);
51 }
52 );
53 }
54 }
55
56 function __isset($r) {
57 return isset($this->references->$r);
58 }
59
60 function __get($r) {
61 return $this->references->$r;
62 }
63
64 function __set($r, $v) {
65 $this->references->$r = $v;
66 }
67
68 function __unset($r){
69 unset($this->references->$r);
70 }
71 }