DB_Pgsql_Type: transparent conversion of complex PostgreSQL types to PHP and back

DB_Pgsql_Type is a framework to convert complex types PostgreSQL 8.3+ in their PHP equivalents and back. With its help, you can work with fields of complex type (for example, a two-dimensional array of a composite type) as simple as in usual PHP arrays.

Following data types are supported and any sub-combination:
the

    Arrays of elements of any type (including multidimensional).

    Composite type ROWTYPE (in particular, themselves contain composite fields or fields arrays).

    * PostgreSQL hstore (including those containing complex elements). the

  • other types: TIMESTAMP (converted to Unix time), DATE, TIME, BOOLEAN, etc.
PostgreSQL is known for its support for complex data types. For example, you can define a column as a two-dimensional array of strings:

the
CREATE TABLE something(
id INTEGER,
matrix TEXT[][]
);
INSERT INTO something(id, matrix) VALUES(
1, ARRAY[ARRAY['one','two'], ARRAY['three "3"','four']]
);

However, in PHP when you try to get value from such a column:

the
$rs = $pdo->query("SELECT matrix FROM something WHERE id=1");
echo $rs->fetchColumn();

you will see only a string representation of this data, something like:

the
{{one,two},{"three \"3\"",four}}

DB_Pgsql_Type allows to convert expressions of the form {{one,two},{"three \"3\"",four}} in two-dimensional PHP array (with the features of quoting special sequences: quotation marks, apostrophes, empty strings, NULL, etc.) Or Vice versa, if you need to record a two-dimensional array in the database.

The source code for the libraries and documentation can be found here:
dklab.ru/lib/DB_Pgsql_Type

Here as a simple example, here is code to parse two-dimensional array of strings from the above listing:

the
// Create the parser for the type "array of arrays of strings".
$parser = new DB_Pgsql_Type_Array(
new DB_Pgsql_Type_Array(
new DB_Pgsql_Type_String()
)
);
// Will return array(array("one", "two"), array('three "3"', "four"))
$array = $parser->input('$Blk{'one,two},{"three \"3\"",four'}');

Can back to build a string in PHP array to insert into DB:

the
echo $parser->output($array);

Download the library and view more examples: arrays, composite types and ROWTYPE, * PostgreSQL hstore, etc.
Article based on information from habrahabr.ru

Комментарии

Популярные сообщения из этого блога

When the basin is small, or it's time to choose VPS server

Performance comparison of hierarchical models, Django and PostgreSQL

From Tomsk to Silicon Valley and Back