AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 307768
Accepted
x-yuri
x-yuri
Asked: 2022-02-22 02:49:02 +0800 CST2022-02-22 02:49:02 +0800 CST 2022-02-22 02:49:02 +0800 CST

atributo 51 do tipo users tem o tipo errado

  • 772

Estou tentando importar dados para uma tabela pg de um arquivo csv. O erro que recebo é:

$ psql -U postgres -c "COPY users (first_name) FROM '/users.csv' (FORMAT csv)"
ERROR:  attribute 51 of type users has wrong type
DETAIL:  Table has type integer, but query expects character varying.
CONTEXT:  COPY users, line 1

Como saber de qual atributo se trata? Por esse motivo, um INSERT também falha:

$ psql -U postgres -c "INSERT INTO users (first_name) VALUES ('first_name')"
ERROR:  attribute 51 of type record has wrong type
DETAIL:  Table has type integer, but query expects character varying.

Tentei contar de acordo com a \d userssaída e com o attnumvalor:

SELECT a.*
FROM pg_attribute a
    JOIN pg_class c on a.attrelid = c.oid
    JOIN pg_namespace n on c.relnamespace = n.oid
WHERE n.nspname = 'public'
    AND c.relname = 'users'
    AND attnum >= 1
ORDER BY attnum

Estou executando o PostgreSQL 12.7.

postgresql insert
  • 1 1 respostas
  • 48 Views

1 respostas

  • Voted
  1. Best Answer
    x-yuri
    2022-02-22T04:49:19+08:002022-02-22T04:49:19+08:00

    O número corresponde ao pg_attribute.attnumvalor. Eu segui o seguinte conselho para reordenar as colunas. Parece que os índices se referem a colunas usando attnumvalores. Ou seja, após reordenar as colunas, elas passaram a se referir a outras colunas, o que gerou o erro.

    Para reproduzir o problema ( script ), crie uma tabela:

    > CREATE TABLE t1 (f1 varchar, f2 varchar, f3 integer)
    CREATE TABLE
    
    > CREATE INDEX ON t1 (f2) WHERE f2 IS NOT NULL
    CREATE INDEX
    
    > \d t1
                          Table "public.t1"
     Column |       Type        | Collation | Nullable | Default 
    --------+-------------------+-----------+----------+---------
     f1     | character varying |           |          | 
     f2     | character varying |           |          | 
     f3     | integer           |           |          | 
    Indexes:
        "t1_f2_idx" btree (f2) WHERE f2 IS NOT NULL
    

    Reordenar colunas:

    > UPDATE pg_attribute SET attnum = 30001 WHERE attname = 'f2' AND attrelid = 16384
    UPDATE 1
    
    > UPDATE pg_attribute SET attnum = 30002 WHERE attname = 'f3' AND attrelid = 16384
    UPDATE 1
    
    > UPDATE pg_attribute SET attnum = 3 WHERE attname = 'f2' AND attrelid = 16384
    UPDATE 1
    
    > UPDATE pg_attribute SET attnum = 2 WHERE attname = 'f3' AND attrelid = 16384
    UPDATE 1
    
    > \d t1
                          Table "public.t1"
     Column |       Type        | Collation | Nullable | Default 
    --------+-------------------+-----------+----------+---------
     f1     | character varying |           |          | 
     f3     | integer           |           |          | 
     f2     | character varying |           |          | 
    Indexes:
        "t1_f2_idx" btree (f3 COLLATE "default" text_ops) WHERE f3 IS NOT NULL
    

    Tente inserir uma linha:

    > INSERT INTO t1 (f1) VALUES ('f1')
    ERROR:  attribute 2 of type record has wrong type
    DETAIL:  Table has type integer, but query expects character varying.
    
    > SELECT a.attname, a.attnum
    FROM pg_attribute a
        JOIN pg_class c on a.attrelid = c.oid
        JOIN pg_namespace n on c.relnamespace = n.oid
    WHERE n.nspname = 'public'
        AND c.relname = 't1'
        AND attnum >= 1
    ORDER BY attnum
     attname | attnum 
    ---------+--------
     f1      |      1
     f3      |      2
     f2      |      3
    (3 rows)
    

    Como você pode ver t1_f2_idxagora se refere f3(na tabela é um inteiro, no índice uma string).

    Pelo menos neste caso é reversível:

    > UPDATE pg_attribute SET attnum = 30001 WHERE attname = 'f2' AND attrelid = 16384
    UPDATE 1
    
    > UPDATE pg_attribute SET attnum = 30002 WHERE attname = 'f3' AND attrelid = 16384
    UPDATE 1
    
    > UPDATE pg_attribute SET attnum = 2 WHERE attname = 'f2' AND attrelid = 16384
    UPDATE 1
    
    > UPDATE pg_attribute SET attnum = 3 WHERE attname = 'f3' AND attrelid = 16384
    UPDATE 1
    
    > INSERT INTO t1 (f1) VALUES ('f1')
    INSERT 0 1
    
    • 0

relate perguntas

  • Posso ativar o PITR depois que o banco de dados foi usado

  • Práticas recomendadas para executar a replicação atrasada do deslocamento de tempo

  • Os procedimentos armazenados impedem a injeção de SQL?

  • Sequências Biológicas do UniProt no PostgreSQL

  • Qual é a diferença entre a replicação do PostgreSQL 9.0 e o Slony-I?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve