Error function crosstab unknown does not exist

On 07/03/2012 06:48 AM, Stefan Schwarzer wrote: > Hi there, > > I am using 9.1.3. I inserted the tablefunc …

On 07/03/2012 06:48 AM, Stefan Schwarzer wrote:
> Hi there,
>
> I am using 9.1.3. I inserted the tablefunc extension, into a SCHEMA called tablefunc, in order to separate it from my tables. I had to create it as postgres user, but changed than the Owner of both schema and functions to my user XXX.
>
> Now, when I launch a query which includes «crosstab()» as a postgres user, everything works fine. However, if I launch it as user XXX, it complaints:
>
> ERROR: function crosstab(unknown, unknown) does not exist
> LINE 1: …ROM countries_view AS c LEFT JOIN ( SELECT * FROM crosstab( … ^
> HINT: No function matches the given name and argument types. You might need to add explicit type casts.
>
> ********** Error **********
> ERROR: function crosstab(unknown, unknown) does not exist
> SQL state: 42883
> Hint: No function matches the given name and argument types. You might need to add explicit type casts.
> Character: 84
>
>
> I looked for the other tables which are included in the query, if they belong to postgres, but they belong all to user XXX.
>
> So, what could that be?
>
> Thanks for any hints!

Are you schema qualifying the function name when you use it?

If not, does user XXX have schema tablefunc in their search_path?

>


Adrian Klaver
adrian(dot)klaver(at)gmail(dot)com

PostgreSQL statement uses the function
crosstab to pivot the table records, pivot means I want to convert the rows to
the column of particular column’s value and want to the others column value
respectively of converted rows.

PostgreSQL- CROSSTAB example

Suppose we have the following table

CREATE TABLE product

(

  id
serial not null,

  brand
text,

  category
text,

  qty
integer

);

— Insert some records

INSERT INTO product(brand,category,qty)

  VALUES(‘Arrow’,‘Cloths’,3000);

INSERT INTO product(brand,category,qty)

  VALUES(‘Samsung’,‘Mobile’,4500);

INSERT INTO product(brand,category,qty)

  VALUES(‘iPad’,‘Tablet’,2000);

INSERT INTO product(brand,category,qty)

  VALUES(‘Prestige’,‘Kitchen’,200);

Now,
select query

SELECT * FROM product;

Result:

id

brand

category

qty

1

«Arrow»

«Cloths»

3000

2

«Samsung»

«Mobile»

4500

3

«iPad»

«Tablet»

2000

4

«Prestige»

«Kitchen»

200

But expected
result as below

Result:

brand

Cloths

mobile

Tablet

kitchen

«Arrow»

3000

«iPad»

2000

«Prestige»

200

«Samsung»

4500

Using
CROSSTAB we can achieve the pivot goal, se the following query

SELECT *

FROM  
crosstab(

   ‘SELECT brand, category, qty

    FROM   product

    ORDER  BY 1,2′,

                $$VALUES (‘Cloths’::text), (‘Mobile’),(‘Tablet’),(‘Kitchen’)$$

   ) AS ct (brand text, Cloths int, Mobile int, Tablet int, Kitchen int);

 Result:

brand

Cloths

Mobile

Tablet

kitchen

«Arrow»

3000

«iPad»

2000

«Prestige»

200

«Samsung»

4500

Note: If you are getting
the following error:

ERROR:  function
crosstab(unknown, unknown) does not exist

LINE 2: FROM   crosstab(

               ^

HINT:  No function matches the given name and
argument types. You might need to add explicit type casts.

SQL state: 42883

Character: 17

The above error will remove executing the
following PostgreSQL statement

CREATE EXTENSION IF NOT EXISTS tablefunc;

View previous topic :: View next topic  
Author Message
jeffk
l33t
l33t

Joined: 13 Sep 2003
Posts: 671

PostPosted: Mon Oct 31, 2011 10:30 pm    Post subject: [SOLVED] postgresql-9.1 extensions tablefunc can’t load Reply with quote

I’m using postgresql-9.1 on ~amd64, and need to access the tablefuncs contrib library. I am having difficulty loading this library, perhaps due to my ignorance about changes that might be required re: 9.1 and PGXN style extensions vs. existing documentation referring to contrib-style sql:

Code:
foo=# select * FROM crosstab(‘select measurement, name, attr from attr order by 1,2’) as ct (measurement numeric, …

ERROR:  function crosstab(unknown) does not exist

LINE 1: select * FROM crosstab(‘select measurement, name, power_refer…



Code:
$ ls -al /usr/share/postgresql-9.1/extension/*tablefunc*

-rw-r—r— 1 root root 2013 Sep 27 07:31 /usr/share/postgresql-9.1/extension/tablefunc—1.0.sql

-rw-r—r— 1 root root  174 Sep 27 07:31 /usr/share/postgresql-9.1/extension/tablefunc.control

-rw-r—r— 1 root root 1004 Sep 27 07:31 /usr/share/postgresql-9.1/extension/tablefunc—unpackaged—1.0.sql



Code:
/usr/share/postgresql-9.1/extension $ sudo -u postgres psql -d foo -f tablefunc—1.0.sql

psql:tablefunc—1.0.sql:6: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:12: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:20: ERROR:  type «tablefunc_crosstab_2» already exists

psql:tablefunc—1.0.sql:28: ERROR:  type «tablefunc_crosstab_3» already exists

psql:tablefunc—1.0.sql:37: ERROR:  type «tablefunc_crosstab_4» already exists

psql:tablefunc—1.0.sql:42: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:47: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:52: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:58: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:63: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:68: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:73: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:80: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory

psql:tablefunc—1.0.sql:85: ERROR:  could not access file «MODULE_PATHNAME»: No such file or directory



Code:
/usr/share/postgresql-9.1/extension $ sudo -u postgres psql -d foo -f tablefunc—unpackaged—1.0.sql

psql:tablefunc—unpackaged—1.0.sql:3: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:4: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:5: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:6: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:7: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:8: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:9: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:10: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:11: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:12: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:13: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:14: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:15: ERROR:  extension «tablefunc» does not exist

psql:tablefunc—unpackaged—1.0.sql:16: ERROR:  extension «tablefunc» does not exist



Code:
$ sudo emerge postgresql-base postgresql-server -pv                                                       

[ebuild   R    ] dev-db/postgresql-base-9.1.1  USE=»nls pam readline ssl zlib -doc -kerberos -ldap -pg_legacytimestamp -threads» LINGUAS=»en -af -cs -de -es -fa -fr -hr -hu -it -ko -nb -pl -pt_BR -ro -ru -sk -sl -sv -tr -zh_CN -zh_TW» 0 kB

[ebuild   R    ] dev-db/postgresql-server-9.1.1  USE=»nls pam perl python xml -doc -pg_legacytimestamp (-selinux) -tcl -uuid» LINGUAS=»en -af -cs -de -es -fa -fr -hr -hu -it -ko -nb -pl -pt_BR -ro -ru -sk -sl -sv -tr -zh_CN -zh_TW» 0 kB



Any suggestions on the correct install procedure?

EDIT: I have the understanding now that the new create extension commands are called for. I still have some lurking error with a tablefunc_crosstab_2 possibly from an earlier version postgresql. Do I (should I) remove types that conflict until the extension installs successfully?

Code:
foo=# create extension tablefunc;                                                                                                                         

ERROR:  type «tablefunc_crosstab_2» already exists



Code:
foo=# create extension tablefunc from unpackaged;                                                                                                         

ERROR:  function normal_rand(integer, double precision, double precision) does not exist



Code:
foo=# select * from pg_available_extensions order by name;

        name        | default_version | installed_version |                               comment                               

———————+——————+——————-+———————————————————————-

 adminpack          | 1.0             |                   | administrative functions for PostgreSQL

 autoinc            | 1.0             |                   | functions for autoincrementing fields

 btree_gin          | 1.0             |                   | support for indexing common datatypes in GIN

 btree_gist         | 1.0             | 1.0               | support for indexing common datatypes in GiST

 chkpass            | 1.0             |                   | data type for auto-encrypted passwords

 citext             | 1.0             |                   | data type for case-insensitive character strings

 cube               | 1.0             |                   | data type for multidimensional cubes

 dblink             | 1.0             |                   | connect to other PostgreSQL databases from within a database

 dict_int           | 1.0             |                   | text search dictionary template for integers

 dict_xsyn          | 1.0             |                   | text search dictionary template for extended synonym processing

 earthdistance      | 1.0             |                   | calculate great-circle distances on the surface of the Earth

 file_fdw           | 1.0             |                   | foreign-data wrapper for flat file access

 fuzzystrmatch      | 1.0             |                   | determine similarities and distance between strings

 hstore             | 1.0             |                   | data type for storing sets of (key, value) pairs

 insert_username    | 1.0             |                   | functions for tracking who changed a table

 intagg             | 1.0             |                   | integer aggregator and enumerator (obsolete)

 intarray           | 1.0             |                   | functions, operators, and index support for 1-D arrays of integers

 isn                | 1.0             |                   | data types for international product numbering standards

 lo                 | 1.0             |                   | Large Object maintenance

 ltree              | 1.0             |                   | data type for hierarchical tree-like structures

 moddatetime        | 1.0             |                   | functions for tracking last modification time

 pageinspect        | 1.0             |                   | inspect the contents of database pages at a low level

 pg_buffercache     | 1.0             |                   | examine the shared buffer cache

 pg_freespacemap    | 1.0             |                   | examine the free space map (FSM)

 pg_stat_statements | 1.0             |                   | track execution statistics of all SQL statements executed

 pg_trgm            | 1.0             |                   | text similarity measurement and index searching based on trigrams

 pgcrypto           | 1.0             |                   | cryptographic functions

 pgrowlocks         | 1.0             |                   | show row-level locking information

 pgstattuple        | 1.0             |                   | show tuple-level statistics

 plperl             | 1.0             |                   | PL/Perl procedural language

 plperlu            | 1.0             |                   | PL/PerlU untrusted procedural language

 plpgsql            | 1.0             | 1.0               | PL/pgSQL procedural language

 plpython2u         | 1.0             |                   | PL/Python2U untrusted procedural language

 plpython3u         | 1.0             |                   | PL/Python3U untrusted procedural language

 plpythonu          | 1.0             |                   | PL/PythonU untrusted procedural language

 refint             | 1.0             |                   | functions for implementing referential integrity (obsolete)

 seg                | 1.0             |                   | data type for representing line segments or floating-point intervals

 sslinfo            | 1.0             |                   | information about SSL certificates

 tablefunc          | 1.0             |                   | functions that manipulate whole tables, including crosstab

 temporal           | 0.7.1           | 0.7.1             | temporal data type and functions

 test_parser        | 1.0             |                   | example of a custom parser for full-text search

 timetravel         | 1.0             |                   | functions for implementing time travel

 tsearch2           | 1.0             |                   | compatibility package for pre-8.3 text search functions

 unaccent           | 1.0             |                   | text search dictionary that removes accents

 xml2               | 1.0             |                   | XPath querying and XSLT

(45 rows)



Code:
foo=# select * from pg_extension order by extname;

  extname   | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition

————+———-+—————+—————-+————+————+—————

 btree_gist |       10 |         2200 | t              | 1.0        |           |

 plpgsql    |       10 |           11 | f              | 1.0        |           |

 temporal   |       10 |        16599 | t              | 0.7.1      |           |

(3 rows)

EDIT2: SOLVED.

The database had an old set of tablefunc types, presumably from prior experiments with tablefunc as contrib before 9.1. Identifying, deleting those types allowed create extension to run to completion:

Create a fresh database to test hypothesis:

Code:
$ sudo -u postgres createdb foo2

$ sudo -u postgres psql -d foo2

psql (9.1.1)

Type «help» for help.

foo2=# create extension tablefunc;

CREATE EXTENSION

foo2=#

foo2=# select typname,typlen from pg_type where typname like ‘%tablefunc%’ order by typname;

        typname        | typlen

————————+———

 _tablefunc_crosstab_2 |     -1

 _tablefunc_crosstab_3 |     -1

 _tablefunc_crosstab_4 |     -1

 tablefunc_crosstab_2  |     -1

 tablefunc_crosstab_3  |     -1

 tablefunc_crosstab_4  |     -1

(6 rows)



Works. Return to the real database, clear the bad old types:

Code:
$ sudo -u postgres psql -d foo                                                                       

psql (9.1.1)

Type «help» for help.

foo=# select typname,typlen from pg_type where typname like ‘%tablefunc%’ order by typname;

        typname        | typlen

————————+———

 _tablefunc_crosstab_2 |     -1

 _tablefunc_crosstab_3 |     -1

 _tablefunc_crosstab_4 |     -1

 tablefunc_crosstab_2  |     -1

 tablefunc_crosstab_3  |     -1

 tablefunc_crosstab_4  |     -1

(6 rows)

foo=# drop type tablefunc_crosstab_2;

DROP TYPE

foo=# drop type tablefunc_crosstab_3;

DROP TYPE

foo=# drop type tablefunc_crosstab_4;

DROP TYPE

foo=# drop type _tablefunc_crosstab_2;

ERROR:  type «_tablefunc_crosstab_2» does not exist

foo=# select typname,typlen from pg_type where typname like ‘%tablefunc%’ order by typname;                                                               

 typname | typlen

———+———

(0 rows)



Code:
foo=# create extension tablefunc;

CREATE EXTENSION

Thanks.

Back to top

View user's profile Send private message

Display posts from previous:   

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

Postgres 9.2.1 на OSX 10.9.2.

Если я запускаю следующий пример перекрестного запроса:

CREATE EXTENSION tablefunc; 

CREATE TABLE ct(id SERIAL, rowid TEXT, attribute TEXT, value TEXT);
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att1','val1');

SELECT *
FROM crosstab(
  'select rowid, attribute, value
   from ct
   where attribute = ''att2'' or attribute = ''att3''
   order by 1,2')
AS ct(row_name text, category_1 text, category_2 text, category_3 text);

Я получаю: ERROR: extension "tablefunc" already exists

Но если я закомментирую CREATE EXTENSION

Я получаю: ERROR: function crosstab(unknown) does not exist

Как мне выбраться из этого порочного круга? Это известная проблема?

3 ответа

Вы можете изменить первую строку на:

CREATE EXTENSION IF NOT EXISTS tablefunc;


11

akbarbin
5 Дек 2017 в 10:24

Проблема в моем случае заключалась в том, что расширение tablefunc было определено для одной конкретной схемы в моей БД и недоступно для всех схем в ней.

[изменить: как объяснялось выше, «недоступен для всех схем» следует читать «не может быть загружен во всех схемах»]

Я узнал, что:

  1. расширение можно загрузить только в одну схему, поэтому загрузите его в «общедоступную»
  2. вам нужно вручную удалить расширение из одной схемы, прежде чем вы сможете загрузить его в другую
  3. вы можете перечислить загруженные расширения для каждой схемы в pqsl, используя команду: df *.crosstab

[править: 4. вы можете получить доступ к расширению либо по search_path, либо загрузив его в общедоступную схему, либо явно указав схему]


7

Black
16 Апр 2014 в 03:30

В вашем ответе есть неверное представление:

и не доступен для всех схем в нем.

Все схемы в одной и той же базе данных доступны для всех сеансов в этой же базе данных (при наличии соответствующих прав). Это вопрос установки search_path. Схемы работают так же, как каталоги/папки в файловой системе.

Кроме того, вы можете квалифицировать функцию (и даже операторы) по схеме для доступа к ней независимо от search_path:

SELECT *
FROM my_extension_schema.crosstab(
    $$select rowid, attribute, "value"
      from   ct
      where  attribute IN ('att2', 'att3')
      order  by 1,2$$
   ,$$VALUES ('att2'), ('att3')$$
   ) AS ct(row_name text, category_2 text, category_3 text);

Недавний связанный ответ с дополнительной информацией:
Как использовать оператор% из расширения pg_trgm?

Сомнительный crosstab()

Ваш запрос возвратил атрибуты 'att2' и 'att3', но в списке определений столбцов есть три категории (category_1, category_2, category_3), которые не соответствуют запросу.
Я удалил category_1 и добавил в crosstab() второй параметр — «безопасную» версию. Подробнее здесь:
Запрос перекрестной таблицы PostgreSQL

В стороне: не используйте value в качестве имени столбца. Даже если Postgres это терпит. Это зарезервированное слово в стандартном SQL.


4

Community
20 Июн 2020 в 12:12

Понравилась статья? Поделить с друзьями:
  • Error func no 8 hifi image
  • Error func no 11 recovery image error no 2 load failed
  • Error full join is only supported with merge joinable or hash joinable join conditions
  • Error ftp login failed
  • Error ftdiun2k ini not found press finish to exit