add support for one-dimensional arrays; type input parameters
[m6w6/pq-gateway] / lib / pq / Gateway / Table / Attributes.php
1 <?php
2
3 namespace pq\Gateway\Table;
4
5 use \pq\Gateway\Table;
6
7 const ATTRIBUTES_SQL = <<<SQL
8 select
9 attnum as index
10 ,attname as name
11 ,atttypid as type
12 ,atthasdef as hasdefault
13 ,not attnotnull as nullable
14 from
15 pg_attribute
16 where attrelid = \$1::regclass
17 and attnum > 0
18 SQL;
19
20 class Attributes
21 {
22 /**
23 * @var array
24 */
25 protected $columns = array();
26
27 /**
28 * @param \pq\Gateway\Table $table
29 */
30 function __construct(Table $table) {
31 $cache = $table->getMetadataCache();
32 if (!($this->columns = $cache->get("$table#attributes"))) {
33 $table->getQueryExecutor()->execute(
34 new \pq\Query\Writer(ATTRIBUTES_SQL, array($table->getName())),
35 function($result) use($table, $cache) {
36 foreach ($result->fetchAll(\pq\Result::FETCH_OBJECT) as $c) {
37 $this->columns[$c->index] = $this->columns[$c->name] = $c;
38 }
39 $cache->set("$table#attributes", $this->columns);
40 }
41 );
42 }
43 }
44
45 /**
46 * @implements \Countable
47 * @return int
48 */
49 function count() {
50 return count($this->columns);
51 }
52
53 /**
54 * Get all columns
55 * @return array
56 */
57 function getColumns() {
58 return $this->columns;
59 }
60
61 /**
62 * Get a single column
63 * @param string $c
64 * @return object
65 */
66 function getColumn($c) {
67 if (!isset($this->columns[$c])) {
68 throw new \OutOfBoundsException("Unknown column $c");
69 }
70 return $this->columns[$c];
71 }
72 }