1 # pq\Types AKA pg_type #
3 The ```pq\Types``` class provides an easy interface to access information stored in PostgreSQL's pg_type relation, f.e. type OIDs and names.
6 The first argument to the ```pq\Types``` constructor must be an ***instance*** of ```pq\Connection```.
7 An ***optional array of namespace names*** is expected as second argument, where 'public' and 'pg_catalog' are queried by default if no namespaces are specified.
12 $types = new pq\Types(new pq\Connection);
15 The types are standard objects indexed by OID and by name and accessible by array key/index:
19 $text = $types["text"];
22 printf("TEXT type (oid=%d, name=%s)\n", $text->oid, $text->typname);
26 > The pg_type relation fields have a ``typ`` prefix.
28 ## Usage when [executing queries](QueryExecution) ##
33 $connection = new pq\Connection;
34 $types = new pq\Types($connection);
35 $result = $connection->execParams("SELECT \$1 + \$2", array(10, 20),
36 array($types["int4"]->oid, $types["int4"]->oid));
39 You can pass a type OID for each parameter of a pepared statement. The PostgreSQL server will try to infer a type by context for any parameters for which no type OID was specified.
43 When ext-pq has been built with PostgreSQL server headers (*) present, then ```pq\Types``` has class constants for the standard types' oids already defined.
48 $connection = new pq\Connection;
49 $result = $connection->execParams("SELECT \$1 + \$2", array(10, 20),
50 array(pq\Types::INT4, pq\Types::INT4));
54 > You can test for static type support with ```pq\Types::DEFINED === true```
56 (*) ```include/postgresql/server/catalog/pg_type.h```
59 With static type support, date(time) values will automatically be converted to ```pq\Datetime``` objects.
65 $conn = new pq\Connection();
72 ")->fetchRow(pq\Result::FETCH_ARRAY);
74 foreach ($data as $datetime) {
75 printf("%-40s (%s)\n", $datetime, $datetime->format);
82 2013-09-20 14:34:38 (Y-m-d H:i:s)
83 2013-09-20 14:34:38.494886 (Y-m-d H:i:s.u)
84 2013-09-20 14:34:38.494886+0200 (Y-m-d H:i:s.uO)
87 ## Custom converters ##
89 ext-pq provides an interface called ```pq\Converter``` which one can implement to perform custom type conversions in a transparent manner. Consider the following naive example converting ```HSTORE``` columns on the fly:
95 class Hstore implements pq\Converter
99 function __construct(pq\Types $types) {
100 $this->oid = $types["hstore"]->oid;
103 function convertTypes() {
107 function convertFromString($string) {
108 return eval("return [$string];");
111 function convertToString($data) {
113 foreach ($data as $k => $v) {
114 $string .= "\"".addslashes($k)."\"=>";
116 $string .= "\"".addslashes($v)."\",";
125 $conn = new pq\Connection();
126 $type = new pq\Types($conn);
127 $conv = new Hstore($type);
128 $conn->setConverter($conv);
129 $conn->exec("SELECT '\"foo\"=>\"bar\"'::hstore hs")->fetchCol(0, $data);
135 Output would be the following: