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.
11 $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);
27 The pg_type relation fields have a ``typ`` prefix.
29 ## Usage when [executing queries](pq/Connection/: Executing Queries)
34 $connection = new pq\Connection;
35 $types = new pq\Types($connection);
36 $result = $connection->execParams(
39 array($types["int4"]->oid, $types["int4"]->oid));
43 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.
47 pq\Types has class constants for the standard types' OIDs already defined.
50 $connection = new pq\Connection;
51 $result = $connection->execParams("SELECT \$1 + \$2",
53 array(pq\Types::INT4, pq\Types::INT4));
58 Date/time values will automatically be converted to pq\Datetime objects.
62 $conn = new pq\Connection();
69 ")->fetchRow(pq\Result::FETCH_ARRAY);
71 foreach ($data as $datetime) {
72 printf("%-40s (%s)\n", $datetime, $datetime->format);
80 2013-09-20 14:34:38 (Y-m-d H:i:s)
81 2013-09-20 14:34:38.494886 (Y-m-d H:i:s.u)
82 2013-09-20 14:34:38.494886+0200 (Y-m-d H:i:s.uO)
86 ext-pq provides the interface 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:
90 class Hstore implements pq\Converter
94 function __construct(pq\Types $types) {
95 $this->oid = $types["hstore"]->oid;
98 function convertTypes() {
102 function convertFromString($string, $type) {
103 return eval("return [$string];");
106 function convertToString($data, $type) {
108 foreach ($data as $k => $v) {
109 $string .= "\"".addslashes($k)."\"=>";
111 $string .= "\"".addslashes($v)."\",";
120 $conn = new pq\Connection();
121 $type = new pq\Types($conn);
122 $conv = new Hstore($type);
123 $conn->setConverter($conv);
124 $conn->exec("SELECT '\"foo\"=>\"bar\"'::hstore hs")->fetchCol(0, $data);
130 Output would be the following: