700f3fcad524829daf7b009632ac6f669ea8a75a
3 namespace pq\Gateway\Table
;
8 * case when att1.attname like '%\_'||att2.attname then
9 substring(att1.attname from '^.*(?=_'||att2.attname||'$)')
14 const RELATION_SQL
= <<<SQL
16 regexp_replace(att1.attname, '_'||att2.attname||'$', '')
18 ,cl1.relname as "foreignTable"
19 ,att1.attname as "foreignColumn"
20 ,cl2.relname as "referencedTable"
21 ,att2.attname as "referencedColumn"
31 and co.conrelid = cl1.oid
32 and co.conkey[1] = att1.attnum and cl1.oid = att1.attrelid
33 and co.confrelid = cl2.oid
34 and co.confkey[1] = att2.attnum and cl2.oid = att2.attrelid
42 class Relations
implements \Countable
, \IteratorAggregate
47 protected $references;
50 * @param \pq\Gateway\Table $table
52 function __construct(Table
$table) {
53 $cache = $table->getMetadataCache();
54 if (!($this->references
= $cache->get("$table:relations"))) {
55 $table->getQueryExecutor()->execute(
56 new \pq\Query\
Writer(RELATION_SQL
, array($table->getName())),
57 function($result) use($table, $cache) {
58 $rel = $result->map([3,0], null, \pq\Result
::FETCH_ASSOC
);
59 foreach ($rel as $table => $reference) {
60 foreach ($reference as $name => $ref) {
61 $this->references
[$table][$name] = new Reference($ref);
64 $cache->set("$table:relations", $this->references
);
70 function __isset($r) {
71 return isset($this->references
[$r]);
75 return $this->references
[$r];
78 function __set($r, $v) {
79 $this->references
[$r] = $v;
83 unset($this->references
[$r]);
87 * Get a reference to a table
88 * @param string $table
90 * @return \pq\Gateway\Table\Reference
92 function getReference($table, $ref = null) {
93 if (isset($this->references
[$table])) {
95 return current($this->references
[$table]);
97 if (isset($this->references
[$table][$ref])) {
98 return $this->references
[$table][$ref];
104 * Implements \Countable
108 return array_sum(array_map("count", $this->references
));
112 * Implements \IteratorAggregate
113 * @return \RecursiveArrayIterator
115 function getIterator() {
116 return new \
RecursiveArrayIterator($this->references
);