add identity and lock
[m6w6/pq-gateway] / lib / pq / Gateway / Table / Identity.php
1 <?php
2
3 namespace pq\Gateway\Table;
4
5 use \pq\Gateway\Table;
6
7 const IDENTITY_SQL = <<<SQL
8 select
9 a.attname as column
10 from pg_class c
11 join pg_index i on c.oid = i.indrelid
12 join pg_attribute a on c.oid = a.attrelid
13 where
14 c.relname = \$1
15 and a.attnum = any(i.indkey)
16 and i.indisprimary
17 order by
18 a.attnum
19 SQL;
20
21 /**
22 * A primary key implementation
23 */
24 class Identity implements \Countable, \IteratorAggregate
25 {
26 /**
27 * @var array
28 */
29 protected $columns = array();
30
31 /**
32 * @param \pq\Gateway\Table $table
33 */
34 function __construct(Table $table) {
35 $cache = $table->getMetadataCache();
36 if (!($this->columns = $cache->get("$table#identity"))) {
37 $table->getQueryExecutor()->execute(
38 new \pq\Query\Writer(IDENTITY_SQL, array($table->getName())),
39 function($result) use($table, $cache) {
40 $this->columns = array_map("current", $result->fetchAll(\pq\Result::FETCH_ARRAY));
41 $cache->set("$table#identity", $this->columns);
42 }
43 );
44 }
45 }
46
47 /**
48 * @implements \Countable
49 * @return int
50 */
51 function count() {
52 return count($this->columns);
53 }
54
55 /**
56 * @implements \IteratorAggregate
57 * @return \ArrayIterator
58 */
59 function getIterator() {
60 return new \ArrayIterator($this->columns);
61 }
62
63 /**
64 * Get the column names which the primary key contains
65 * @return array
66 */
67 function getColumns() {
68 return $this->columns;
69 }
70 }