b96ae661a8b12bd1a256d4775535163c0a25dfed
3 namespace pq\Gateway\Table
;
7 const RELATION_SQL
= <<<SQL
9 cl1.relname as "foreignTable"
14 generate_subscripts(conkey,1) index
17 and attnum = any(conkey)
18 and conkey[index] = attnum
22 ,cl2.relname as "referencedTable"
27 generate_subscripts(confkey,1) index
30 and attnum = any(confkey)
31 and confkey[index] = attnum
34 ) as "referencedColumns"
36 join pg_class cl1 on cl1.oid = co.conrelid
37 join pg_class cl2 on cl2.oid = co.confrelid
47 class Relations
implements \Countable
, \IteratorAggregate
52 protected $references;
55 * @param \pq\Gateway\Table $table
57 function __construct(Table
$table) {
58 $cache = $table->getMetadataCache();
59 if (!($this->references
= $cache->get("$table:relations"))) {
60 $table->getQueryExecutor()->execute(
61 new \pq\Query\
Writer(RELATION_SQL
, array($table->getName())),
62 function($result) use($table, $cache) {
63 $rel = $result->map([1,2], null, \pq\Result
::FETCH_ASSOC
);
64 foreach ($rel as $ref) {
65 foreach ($ref as $table => $key) {
66 $reference = new Reference($key);
67 $this->references
[$table][$reference->name
] = $reference;
70 $cache->set("$table:relations", $this->references
);
76 function __isset($r) {
77 return isset($this->references
[$r]);
81 return $this->references
[$r];
84 function __set($r, $v) {
85 $this->references
[$r] = $v;
89 unset($this->references
[$r]);
93 * Get a reference to a table
94 * @param string $table
96 * @return \pq\Gateway\Table\Reference
98 function getReference($table, $ref = null) {
99 if (isset($this->references
[$table])) {
101 return current($this->references
[$table]);
103 if (isset($this->references
[$table][$ref])) {
104 return $this->references
[$table][$ref];
110 * Implements \Countable
114 return array_sum(array_map("count", $this->references
));
118 * Implements \IteratorAggregate
119 * @return \ArrayIterator
121 function getIterator() {
122 return new \
ArrayIterator($this->references
);