From a165f861270994da0435e42e568f8e4327bd8251 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Fri, 24 Feb 2012 00:33:28 +0000 Subject: [PATCH] Added docs about how to create a generic array typecaster --- doc/src/extensions.rst | 14 ++++++++++++++ doc/src/faq.rst | 7 +++++++ doc/src/usage.rst | 10 +++++++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/doc/src/extensions.rst b/doc/src/extensions.rst index 1ad88eda..820468dd 100644 --- a/doc/src/extensions.rst +++ b/doc/src/extensions.rst @@ -325,6 +325,20 @@ details. .. versionadded:: 2.4.3 + .. _cast-array-unknown: + + .. note:: + + The function can be used to create a generic array typecaster, + returning a list of strings: just use the `~psycopg2.STRING` as base + typecaster. For instance, if you want to receive from the database an + array of :sql:`macaddr`, each address represented by string, you can + use:: + + psycopg2.extensions.register_type( + psycopg2.extensions.new_array_type( + (1040,), 'MACADDR[]', psycopg2.STRING)) + .. function:: register_type(obj [, scope]) diff --git a/doc/src/faq.rst b/doc/src/faq.rst index 3296cd84..8afc478f 100644 --- a/doc/src/faq.rst +++ b/doc/src/faq.rst @@ -109,6 +109,13 @@ Transferring binary data from PostgreSQL 9.0 doesn't work. .. __: http://www.postgresql.org/docs/9.0/static/datatype-binary.html .. __: http://www.postgresql.org/docs/9.0/static/runtime-config-client.html#GUC-BYTEA-OUTPUT +Arrays of *TYPE* are not casted to list. + Arrays are only casted to list when their oid is known, and an array + typecaster is registered for them. If there is no typecaster, the array is + returned unparsed from PostgreSQL (e.g. ``{a,b,c}``). It is easy to create + a generic arrays typecaster, returning a list of array: an example is + provided in the `~psycopg2.extensions.new_array_type()` documentation. + Best practices -------------- diff --git a/doc/src/usage.rst b/doc/src/usage.rst index d480adef..a1b51de7 100644 --- a/doc/src/usage.rst +++ b/doc/src/usage.rst @@ -294,7 +294,7 @@ the SQL string that would be sent to the database. `bytea_output`__ configuration parameter to ``escape``, either in the server configuration file or in the client session (using a query such as ``SET bytea_output TO escape;``) before receiving binary data. - + .. __: http://www.postgresql.org/docs/9.0/static/datatype-binary.html .. __: http://www.postgresql.org/docs/9.0/static/runtime-config-client.html#GUC-BYTEA-OUTPUT @@ -334,6 +334,14 @@ the SQL string that would be sent to the database. >>> cur.mogrify("SELECT %s;", ([10, 20, 30], )) 'SELECT ARRAY[10, 20, 30];' + .. note:: + + Reading back from PostgreSQL, arrays are converted to list of Python + objects as expected, but only if the types are known one. Arrays of + unknown types are returned as represented by the database (e.g. + ``{a,b,c}``). You can easily create a typecaster for :ref:`array of + unknown types `. + .. _adapt-tuple: .. index::