📜 ⬆️ ⬇️

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

DB_Pgsql_Type is a framework for converting complex PostgreSQL 8.3+ types to their PHP counterparts and vice versa. With it, you can work with fields of a complex type (for example, a two-dimensional array of composite types) as easy as with familiar PHP arrays.

The following data types and any of their nested combinations are supported:
PostgreSQL is famous for its support for complex data types. For example, you can define a column of a table as a two-dimensional array of strings:

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

However, in a PHP script, when trying to get a value from such a column:
')
 $ 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:

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

DB_Pgsql_Type allows you to convert expressions of the form {{one, two}, {"three \" 3 "", four}} into a two-dimensional PHP array (taking into account the features of quoting of special sequences: quotes, apostrophes, empty strings, NULL and etc.) Or vice versa, if you need to write a two-dimensional array in the database.

Library sources and documentation can be found here:
dklab.ru/lib/DB_Pgsql_Type

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

 // Create a 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 ()
   )
 );
 // Returns array (array ("one", "two"), array ('three "3"', "four"))
 $ array = $ parser-> input ('$ Blk {' one, two}, {"three \" 3 \ "", four '}');

You can build back a string on a PHP array to insert into the database:

 echo $ parser-> output ($ array);

Download the library and see other examples : working with arrays, composite types and ROWTYPE, hstore, etc.

Source: https://habr.com/ru/post/56499/


All Articles