Ошибка неверный синтаксис для типа bigint

I’m trying to import a CSV file via pgadmin dn it keeps throwing an error on the first line

ERROR:  invalid input syntax for type bigint: "8668394"

I recognize the «» say it is is trying to import the integer as a string but I can’t understand why this is the case. When I open the CSV in notepad++ it doesn’t show any quote marks or formating that might be causing this. This is what I see in notepad++

8668394,Damoujia,China,Asia/Shanghai,36.54356,119.81326 CR LF
9123882,Shanwang,China,Asia/Shanghai,36.5454,118.711 CR LF
11969451,Katang Ailieke,China,Asia/Urumqi,38.15279,85.51784 CR LF
12110889,Wulong,China,Asia/Shanghai,29.32431,107.76056 CR LF
12324243,Yingqiu,China,Asia/Shanghai,36.52663,118.99285 CR LF

Does anyone have any idea what is going wrong here?

I am a newbie to PostgreSQL. I have created below PostgreSQL function and getting an error as below:

ERROR:  invalid input syntax for type bigint: "expenseid"
CREATE OR REPLACE FUNCTION insertorupdateinvoice(invoice jsonb)
     RETURNS void
LANGUAGE plpgsql
AS $BODY$
Declare _invoiceid bigint;
begin
  --Consider all columns in specialist table as character varying and code column as integer.
  insert into invoicemaster (expenseid, invoiceno, transactiondate, totalinvoiceamount, invoicedoc, createdby, createdon)
  select j.invoice->>'expenseid'::bigint, 
         j.invoice->>'invoiceno', 
         (j.invoice->>'transactiondate')::date, 
         j.invoice->>'totalinvoiceamount'::double precision, 
         j.invoice->>'invoicedoc', 
         j.invoice->>'createdby'::bigint, 
         (j.invoice->>'createdon')::timestamp without time zone
  from jsonb_array_elements(invoice) as j(invoice)
  returning invoiceid into _invoiceid;
  
  insert into lineitemmaster (invoiceid, transactiondate, merchantname, amount, departmentid, policyid, itemdescription, 
                              itemcategory, itemtype, status, isrejected, createdby, createdon)
  select _invoiceid::bigint, 
        x.invoice->>'transactiondate'::date, 
        x.invoice->>'merchantname', 
        x.invoice->>'amount'::double precision, 
        x.invoice->>'departmentid'::integer, 
        x.invoice->>'policyid'::integer, 
        x.invoice->>'itemdescription', 
        x.invoice->>'itemcategory'::integer, 
        x.invoice->>'itemtype'::integer, 
        x.invoice->>'status'::boolean, 
        x.invoice->>'isrejected'::boolean, 
        x.invoice->>'createdby'::bigint, 
        (x.invoice->>'createdon')::timestamp without time zone
  from jsonb_array_elements(invoice ->'lineitems') as x;
end;
$BODY$;

I am executing function as below:

select * from insertorupdateinvoice('{"expenseid":1,
    "invoiceno":"04012022",
    "transactiondate":"2022-01-04",
    "totalinvoiceamount":1000.00,
    "invoicedoc":"invoicedoc",
    "createdby":"1",
    "list":[
      {"transactiondate":"2022-01-01", "merchantname":"Apple", "amount":"100.50", "departmentid":"1","policyid":"1", "itemdescription":"iphone 14 pro max", "itemcategory":"55", "itemtype":"499", "status":"true", "isrejected":"false", "createdby":"1"},
      {"transactiondate":"2022-01-02", "merchantname":"Samsung", "amount":"1050.35", "departmentid":"2","policyid":"2", "itemdescription":"samsung galaxy tab", "itemcategory":"40", "itemtype":"50", "status":"true", "isrejected":"false", "createdby":"1"},
      {"transactiondate":"2022-01-03", "merchantname":"Big bazar", "amount":"555.75", "departmentid":"3","policyid":"3", "itemdescription":"grocerry", "itemcategory":"5", "itemtype":"90", "status":"false", "isrejected":"false", "createdby":"1"}
    ]}');

error I am getting as below:

ERROR:  invalid input syntax for type bigint: "expenseid"
LINE 2:   select j.invoice->>'expenseid'::bigint, 
                             ^
QUERY:  insert into invoicemaster (expenseid, invoiceno, transactiondate, totalinvoiceamount, invoicedoc, createdby, createdon)
  select j.invoice->>'expenseid'::bigint, 
         j.invoice->>'invoiceno', 
         (j.invoice->>'transactiondate')::date, 
         j.invoice->>'totalinvoiceamount'::double precision, 
         j.invoice->>'invoicedoc', 
         j.invoice->>'createdby'::bigint, 
         (j.invoice->>'createdon')::timestamp without time zone
  from jsonb_array_elements(invoice) as j(invoice)
  returning invoiceid
CONTEXT:  PL/pgSQL function insertorupdateinvoice(jsonb) line 5 at SQL statement
SQL state: 22P02

BigInt-это объект-обертка примитива,используемый для представления и манипулирования примитивными значениями bigint-которые слишком велики,чтобы быть представленными примитивом числа.

Исключение JavaScript «x не может быть преобразовано в BigInt, поскольку оно не является целым числом» возникает, когда функция BigInt() используется для числа, которое не является целым числом.

В ES2020 появился новый встроенный объект BigInt,который позволяет представлять целые числа,большие 253-1.Bigint является примитивным типом,как число,строка,символ,булево undefined и null.

Мы можем работать с большими числами в JavaScript,используя тип данных BigInt.Преимущества:Он может хранить числа большого размера.Он выполняет арифметические операции.

Прототип.toString()Метод toString()возвращает строку,представляющую указанное значение BigInt.

SyntaxError:неверный синтаксис BigInt

Исключение JavaScript «недопустимый синтаксис BigInt» возникает, когда строковое значение приводится к BigInt , но не может быть проанализировано как целое число.

Message

SyntaxError: Cannot convert x to a BigInt (V8-based)
SyntaxError: invalid BigInt syntax (Firefox)
SyntaxError: Failed to parse String to BigInt (Safari)

Error type

Что пошло не так?

При использовании функции BigInt() для преобразования строки в BigInt строка будет анализироваться так же, как и исходный код, и результирующее значение должно быть целым числом.

Examples

Invalid cases

const a = BigInt("1.5");
const b = BigInt("1n");
const c = BigInt.asIntN(4, "8n");

Valid cases

const a = BigInt("1");
const b = BigInt("  1   ");
const c = BigInt.asIntN(4, "8");

See also

  • BigInt


JavaScript

RangeError:неправильная длина массива
Исключение JavaScript «Недопустимая длина массива» возникает при указании отрицательного числа с плавающей запятой или превышает максимальное значение, поддерживаемое платформой.
SyntaxError:недопустимое присвоение левой стороны
Исключение JavaScript «недопустимое назначение слева» возникает, когда где-то произошло неожиданное.
TypeError: неверное присвоение константе «x»
Исключение JavaScript «недопустимое присвоение константе» возникает при попытке изменить постоянное значение.
RangeError:недействительная дата
Исключение JavaScript «недопустимая дата» возникает, когда была предоставлена ​​строка, ведущая к Date.parse().

Issue Description

We have a definition for a createdAt column as BIGINT in postgres. We’ve had the defaultValue in sequelize defined and working as:

createdAt: {
    type: DataTypes.INTEGER,
    defaultValue: Sequelize.literal('current_millis()'),
  }

This has been working consistently without issue until approximately June 1st, 11am PST.

Now when performing inserts we receive the error message:

 Unexpected error: invalid input syntax for type bigint: "[object Object]"
SequelizeDatabaseError: invalid input syntax for type bigint: "[object Object]"

What are you doing?

Nothing has changed on our end, so I’m not sure how to provide reproduction to the issue..

What do you expect to happen?

We expect the inserts to interpolate the defaultValue correctly and pass our literal current_millis() function to postgres.

What is actually happening?

We see the error.

Additional context

Inspecting the values being passed it seems that the literal function is not being run and instead a javascript string representation of the sequelize.literal is being set. Inspecting the createdAt definition returns:

{
  type: [Function: INTEGER] {
    types: {
      postgres: [Array],
      mysql: [Array],
      mariadb: [Array],
      sqlite: [Array],
      mssql: [Array]
    },
    key: 'INTEGER'
  },
  defaultValue: Literal { val: 'current_millis()' }
}

Looking into the code base it seems that there are some places that explicitly call out when to run the value as a function, e.g. https://github.com/sequelize/sequelize/blob/master/lib/sequelize.js#L1206-L1214

I’m not sure that exact location is where our issue stems from, but hopefully it helps tracking down what is going wrong.

Environment

  • Sequelize version: 5.21.5
  • Node.js version: v13.8.0
  • Operating System: mac

Issue Template Checklist

How does this problem relate to dialects?

  • [ x] I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s):
  • I don’t know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don’t know how to start, I would need guidance.
  • No, I don’t have the time, although I believe I could do it if I had the time…
  • [x ] No, I don’t have the time and I wouldn’t even know how to start.

Я пытаюсь импортировать файл CSV через pgadmin dn, он продолжает выдавать ошибку в первой строке.

ERROR:  invalid input syntax for type bigint: "8668394"

Я узнаю, что «» говорит, что он пытается импортировать целое число в виде строки, но я не могу понять, почему это так. Когда я открываю CSV в блокноте ++, он не показывает никаких кавычек или форматирования, которые могут быть причиной этого. Вот что я вижу в блокноте++

8668394,Damoujia,China,Asia/Shanghai,36.54356,119.81326 CR LF
9123882,Shanwang,China,Asia/Shanghai,36.5454,118.711 CR LF
11969451,Katang Ailieke,China,Asia/Urumqi,38.15279,85.51784 CR LF
12110889,Wulong,China,Asia/Shanghai,29.32431,107.76056 CR LF
12324243,Yingqiu,China,Asia/Shanghai,36.52663,118.99285 CR LF

Кто-нибудь знает, что здесь не так?

1 ответ

Лучший ответ

Для всех, кто сталкивается с подобной проблемой. Моя проблема заключалась в том, что файл был закодирован с использованием UTF8-BOM, в блокноте ++ выберите «Кодировка»> «UTF-8» и повторно сохраните файл. Это удалит скрытую метку порядка байтов (BOM) в начале файла и позволит импорту работать правильно.


0

Aaron Harker
10 Мар 2022 в 02:38

hello everyone,

I am trying to run the proc below but get an error : invalid input
syntax for type bigint: «2004-10-26» Can anyone suggest what I am
doing wrong here?

Rx

— Function: public.getdateallocated(date, date)

DROP FUNCTION public.getdateallocated(date, date);

CREATE OR REPLACE FUNCTION public.getdateallocated(date, date)
RETURNS text AS
‘Declare

workflow_t ix_workflow_task%ROWTYPE;

BEGIN

SELECT ix_workflow_task.»DATE_COMPLETED»,
ix_workflow_task.»WORKFLOW_ACTIVITY_XPDL_ID», ix_workflow_task.»TYPE»
INTO workflow_t from ix_workflow_task
INNER JOIN ix_workflow_instance ON
ix_workflow_task.»WORKFLOW_INSTANCE_KEY» =
ix_workflow_instance.»WORKFLOW_INSTANCE_KEY»
INNER JOIN ix_workflow_instance_to_domain ON
ix_workflow_instance_to_domain.»WORKFLOW_INSTANCE_KEY» =
ix_workflow_instance.»WORKFLOW_INSTANCE_KEY»
INNER JOIN ix_core_case ON
ix_workflow_instance_to_domain.»DOMAIN_KEY» =
ix_core_case.»CORECASEKEY»
where to_char(ix_workflow_task.»DATE_COMPLETED», ‘DD-MM-YYYY’) <> »
AND ix_core_case.»DELETED» = 0
AND («CORECASEKEY» in (select * FROM getStatusSwitch($1,$2,
‘Assessment’, ‘Prosecution’))
OR «CORECASEKEY» in (select * from
getStatusSwitch($1,$2, ‘Assessment’, ‘Investigation’))
OR «CORECASEKEY» in (select * from
getStatusSwitch($1,$2, ‘Assessment’, ‘Other’)))
group by ix_workflow_task.»DATE_COMPLETED»,
ix_workflow_task.»WORKFLOW_ACTIVITY_XPDL_ID», ix_workflow_task.»TYPE»
having (lower(ix_workflow_task.»WORKFLOW_ACTIVITY_XPDL_ID») LIKE
‘organise surveillance — 9b’ AND ix_workflow_task.»TYPE» = ‘Human’
or lower(ix_workflow_task.»WORKFLOW_ACTIVITY_XPDL_ID»)
LIKE ‘start case mix workflow — 9’ AND ix_workflow_task.»TYPE» =
‘System’
or lower(ix_workflow_task.»WORKFLOW_ACTIVITY_XPDL_ID») LIKE
‘finalise case — 13’ AND ix_workflow_task.»TYPE» = ‘Human’
or lower(ix_workflow_task.»WORKFLOW_ACTIVITY_XPDL_ID») LIKE
‘complete final priority smart form — 39’ AND
ix_workflow_task.»TYPE» = ‘Human’
or lower(ix_workflow_task.»WORKFLOW_ACTIVITY_XPDL_ID») LIKE
‘check for case mix type — 17’ AND ix_workflow_task.»TYPE» =
‘System’)
and (ix_workflow_task.»DATE_COMPLETED» >= $1 and
ix_workflow_task.»DATE_COMPLETED» <= $2);

return workflow_t.»WORKFLOW_ACTIVITY_XPDL_ID» ||
to_char(workflow_t.»DATE_COMPLETED», ‘DD-MM-YYYY’);

END;


LANGUAGE ‘plpgsql’ VOLATILE;

select getdateallocated(’10/10/04′,’12/12/04′);

SyntaxError:неверный синтаксис BigInt

Исключение JavaScript «недопустимый синтаксис BigInt» возникает, когда строковое значение приводится к BigInt , но не может быть проанализировано как целое число.

Message

SyntaxError: Cannot convert x to a BigInt (V8-based)
SyntaxError: invalid BigInt syntax (Firefox)
SyntaxError: Failed to parse String to BigInt (Safari)

Error type

Что пошло не так?

При использовании функции BigInt() для преобразования строки в BigInt строка будет анализироваться так же, как и исходный код, и результирующее значение должно быть целым числом.

Examples

Invalid cases

const a = BigInt("1.5");
const b = BigInt("1n");
const c = BigInt.asIntN(4, "8n");

Valid cases

const a = BigInt("1");
const b = BigInt("  1   ");
const c = BigInt.asIntN(4, "8");

See also

  • BigInt

JavaScript

  • RangeError:неправильная длина массива

    Исключение JavaScript «Недопустимая длина массива» возникает при указании отрицательного числа с плавающей запятой или превышает максимальное значение, поддерживаемое платформой.

  • SyntaxError:недопустимое присвоение левой стороны

    Исключение JavaScript «недопустимое назначение слева» возникает, когда где-то произошло неожиданное.

  • TypeError: неверное присвоение константе «x»

    Исключение JavaScript «недопустимое присвоение константе» возникает при попытке изменить постоянное значение.

  • RangeError:недействительная дата

    Исключение JavaScript «недопустимая дата» возникает, когда была предоставлена ​​строка, ведущая к Date.parse().

Issue Description

We have a definition for a createdAt column as BIGINT in postgres. We’ve had the defaultValue in sequelize defined and working as:

createdAt: {
    type: DataTypes.INTEGER,
    defaultValue: Sequelize.literal('current_millis()'),
  }

This has been working consistently without issue until approximately June 1st, 11am PST.

Now when performing inserts we receive the error message:

 Unexpected error: invalid input syntax for type bigint: "[object Object]"
SequelizeDatabaseError: invalid input syntax for type bigint: "[object Object]"

What are you doing?

Nothing has changed on our end, so I’m not sure how to provide reproduction to the issue..

What do you expect to happen?

We expect the inserts to interpolate the defaultValue correctly and pass our literal current_millis() function to postgres.

What is actually happening?

We see the error.

Additional context

Inspecting the values being passed it seems that the literal function is not being run and instead a javascript string representation of the sequelize.literal is being set. Inspecting the createdAt definition returns:

{
  type: [Function: INTEGER] {
    types: {
      postgres: [Array],
      mysql: [Array],
      mariadb: [Array],
      sqlite: [Array],
      mssql: [Array]
    },
    key: 'INTEGER'
  },
  defaultValue: Literal { val: 'current_millis()' }
}

Looking into the code base it seems that there are some places that explicitly call out when to run the value as a function, e.g. https://github.com/sequelize/sequelize/blob/master/lib/sequelize.js#L1206-L1214

I’m not sure that exact location is where our issue stems from, but hopefully it helps tracking down what is going wrong.

Environment

  • Sequelize version: 5.21.5
  • Node.js version: v13.8.0
  • Operating System: mac

Issue Template Checklist

How does this problem relate to dialects?

  • [ x] I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s):
  • I don’t know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don’t know how to start, I would need guidance.
  • No, I don’t have the time, although I believe I could do it if I had the time…
  • [x ] No, I don’t have the time and I wouldn’t even know how to start.

Я новичок в PostgreSQL. Я создал ниже функцию PostgreSQL и получил ошибку, как показано ниже:

ERROR:  invalid input syntax for type bigint: "expenseid"
CREATE OR REPLACE FUNCTION insertorupdateinvoice(invoice jsonb)
     RETURNS void
LANGUAGE plpgsql
AS $BODY$
Declare _invoiceid bigint;
begin
  --Consider all columns in specialist table as character varying and code column as integer.
  insert into invoicemaster (expenseid, invoiceno, transactiondate, totalinvoiceamount, invoicedoc, createdby, createdon)
  select j.invoice->>'expenseid'::bigint, 
         j.invoice->>'invoiceno', 
         (j.invoice->>'transactiondate')::date, 
         j.invoice->>'totalinvoiceamount'::double precision, 
         j.invoice->>'invoicedoc', 
         j.invoice->>'createdby'::bigint, 
         (j.invoice->>'createdon')::timestamp without time zone
  from jsonb_array_elements(invoice) as j(invoice)
  returning invoiceid into _invoiceid;
  
  insert into lineitemmaster (invoiceid, transactiondate, merchantname, amount, departmentid, policyid, itemdescription, 
                              itemcategory, itemtype, status, isrejected, createdby, createdon)
  select _invoiceid::bigint, 
        x.invoice->>'transactiondate'::date, 
        x.invoice->>'merchantname', 
        x.invoice->>'amount'::double precision, 
        x.invoice->>'departmentid'::integer, 
        x.invoice->>'policyid'::integer, 
        x.invoice->>'itemdescription', 
        x.invoice->>'itemcategory'::integer, 
        x.invoice->>'itemtype'::integer, 
        x.invoice->>'status'::boolean, 
        x.invoice->>'isrejected'::boolean, 
        x.invoice->>'createdby'::bigint, 
        (x.invoice->>'createdon')::timestamp without time zone
  from jsonb_array_elements(invoice ->'lineitems') as x;
end;
$BODY$;

Я выполняю функцию, как показано ниже:

select * from insertorupdateinvoice('{"expenseid":1,
    "invoiceno":"04012022",
    "transactiondate":"2022-01-04",
    "totalinvoiceamount":1000.00,
    "invoicedoc":"invoicedoc",
    "createdby":"1",
    "list":[
      {"transactiondate":"2022-01-01", "merchantname":"Apple", "amount":"100.50", "departmentid":"1","policyid":"1", "itemdescription":"iphone 14 pro max", "itemcategory":"55", "itemtype":"499", "status":"true", "isrejected":"false", "createdby":"1"},
      {"transactiondate":"2022-01-02", "merchantname":"Samsung", "amount":"1050.35", "departmentid":"2","policyid":"2", "itemdescription":"samsung galaxy tab", "itemcategory":"40", "itemtype":"50", "status":"true", "isrejected":"false", "createdby":"1"},
      {"transactiondate":"2022-01-03", "merchantname":"Big bazar", "amount":"555.75", "departmentid":"3","policyid":"3", "itemdescription":"grocerry", "itemcategory":"5", "itemtype":"90", "status":"false", "isrejected":"false", "createdby":"1"}
    ]}');

Ошибка, которую я получаю, как показано ниже:

ERROR:  invalid input syntax for type bigint: "expenseid"
LINE 2:   select j.invoice->>'expenseid'::bigint, 
                             ^
QUERY:  insert into invoicemaster (expenseid, invoiceno, transactiondate, totalinvoiceamount, invoicedoc, createdby, createdon)
  select j.invoice->>'expenseid'::bigint, 
         j.invoice->>'invoiceno', 
         (j.invoice->>'transactiondate')::date, 
         j.invoice->>'totalinvoiceamount'::double precision, 
         j.invoice->>'invoicedoc', 
         j.invoice->>'createdby'::bigint, 
         (j.invoice->>'createdon')::timestamp without time zone
  from jsonb_array_elements(invoice) as j(invoice)
  returning invoiceid
CONTEXT:  PL/pgSQL function insertorupdateinvoice(jsonb) line 5 at SQL statement
SQL state: 22P02

Итак, я получил решение для этого, как показано ниже, поскольку не используйте имя jsonb при извлечении значений.

    CREATE OR REPLACE FUNCTION public.insertorupdateinvoice(
        invoice jsonb)
        RETURNS void
        LANGUAGE 'plpgsql'
        COST 100
        VOLATILE PARALLEL UNSAFE
    AS $BODY$
    Declare _invoiceid bigint;
    begin
      insert into invoicemaster (expenseid, invoiceno, transactiondate, totalinvoiceamount, invoicedoc, createdby, createdon)
      values ( (invoice->>'expenseid') :: bigint, 
               (invoice->>'invoiceno') :: character, 
               (invoice->>'transactiondate') :: date, 
               (invoice->>'totalinvoiceamount') :: double precision, 
               (invoice->>'invoicedoc') :: character, 
               (invoice->>'createdby') :: bigint,
               NOW()
             )
      returning invoiceid into _invoiceid;

      insert into lineitemmaster (invoiceid, transactiondate, merchantname, amount, departmentid, policyid, itemdescription, 
                                  itemcategory, itemtype, status, isrejected, createdby, createdon)
      select _invoiceid::bigint, 
            (x->>'transactiondate')::date, 
            x->>'merchantname', 
            (x->>'amount')::double precision, 
            (x->>'departmentid')::integer, 
            (x->>'policyid')::integer, 
            x->>'itemdescription', 
            (x->>'itemcategory')::integer, 
            (x->>'itemtype')::integer, 
            (x->>'status')::boolean, 
            (x->>'isrejected')::boolean, 
            (x->>'createdby')::bigint,
            NOW()
      from jsonb_array_elements(invoice ->'lineitems') as x;
    end;
    $BODY$;


0

Krunal
9 Янв 2023 в 11:22

У меня в модели было поле с

book_classes = (("","Select Form"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4'),("All Forms","All Forms"))
b_classes = models.CharField('Form',max_length=9,choices=book_classes,default="n/a")

А затем изменил его на

b_class =models.ForeignKey(ClassBooks,on_delete=models.CASCADE)

Где

class ClassBooks(models.Model):
    name = models.CharField(max_length=10,help_text='The class the book belongs to')

Теперь я застрял, потому что когда я пытаюсь мигрировать, я получаю ошибку.

Invalid input syntax for type bigint:"All Forms"

Что мне нужно сделать?

Если вы не хотите потерять db.sqlite3, попробуйте сначала удалить миграции

Шаг 1: Удалите файл db.sqlite3.

Шаг 2 : $ python manage.py migrate

Шаг 3 : $ python manage.py makemigrations

Шаг 4: Создайте суперпользователя с помощью $ python manage.py createsuperuser

новый db.sqlite3 будет сгенерирован автоматически

См. Поле чужого ключа. По умолчанию поле FK будет использовать первичный ключ ссылающейся таблицы (модели), в данном случае поле id из ClassBooks. Поле id является целым числом, поэтому вы получите ошибку при попытке использовать строковое поле. Чтобы заставить это работать, из ссылки на документацию :

ForeignKey.to_field

Поле связанного объекта, к которому относится отношение. По умолчанию Django использует первичный ключ связанного объекта. Если вы ссылаетесь на другое поле, то это поле должно иметь unique=True.

Что в вашем случае становится:

b_class =models.ForeignKey(ClassBooks,to_field='name',on_delete=models.CASCADE)

Это предполагает, что поле name имеет ограничение Unique.

Хотя я не уверен, как "", "1", "2" ... сопоставить с ClassBooks.name.

Вернуться на верх

под управлением COPY результаты ERROR: invalid input syntax for integer: "" сообщение об ошибке для меня. Что я упускаю?

мой :

"age","first_name","last_name"
"23","Ivan","Poupkine"
"","Eugene","Pirogov"

мой :

CREATE TABLE people (
  age        integer,
  first_name varchar(20),
  last_name  varchar(20)
);

COPY people
FROM '/tmp/people.csv'
WITH (
  FORMAT CSV,
  HEADER true,
  NULL ''
);

DROP TABLE people;

выход:

$ psql postgres -f /tmp/sql_test.sql
CREATE TABLE
psql:sql_test.sql:13: ERROR:  invalid input syntax for integer: ""
CONTEXT:  COPY people, line 3, column age: ""
DROP TABLE

Общая информация:

  • PostgreSQL 9.2.4

7 ответов


ошибка: неверный входной синтаксис для integer: «»

"" не является допустимым числом. В PostgreSQL можно без кавычек пустые поля как null по умолчанию в CSV, но "" было бы похоже на написание:

SELECT ''::integer;

и не по той же причине.

если вы хотите иметь дело с CSV, который имеет такие вещи, как цитируемые пустые строки для целых чисел null, вам нужно будет передать его PostgreSQL через предпроцессор, который может немного его подправить. CSV-вход PostgreSQL не понимает всех странных и замечательных возможных злоупотреблений CSV.

варианты:

  • загрузка его в электронную таблицу и экспорт вменяемого CSV;
  • использование Python csv модуль для Perl Text::CSV и т. д. Для предварительной обработки;
  • использование Perl / Python / whatever для загрузки CSV и вставки его непосредственно в DB
  • используя инструмент ETL, как CloverETL, Talend Studio, или Pentaho чайник

Я думаю, что лучше изменить csv-файл, например:

"age","first_name","last_name"
23,Ivan,Poupkine
,Eugene,Pirogov

также можно определить вашу таблицу как

CREATE TABLE people (
  age        varchar(20),
  first_name varchar(20),
  last_name  varchar(20)
);

и после копирования, вы можете обменять пустые строки:

select nullif(age, '')::int as age, first_name, last_name
from people

у меня была такая же ошибка на postgres с COPY утверждение, но мой файл tab-разделены вместо запятую и в кавычках.

моя ошибка заключалась в том, что я охотно копировал/вставлял содержимое файла из github, но в этом процессе все вкладки были преобразованы в пробелы, следовательно, ошибка. Мне пришлось загрузить и сохранить raw-файл, чтобы получить хорошую копию.


в конечном итоге это делается с помощью csvfix:

csvfix map -fv '' -tv '0' /tmp/people.csv > /tmp/people_fixed.csv

в случае, если вы точно знаете, какие столбцы должны быть integer или float, вы можете указать только их:

csvfix map -f 1 -fv '' -tv '0' /tmp/people.csv > /tmp/people_fixed.csv

без указания точных столбцов может возникнуть очевидный побочный эффект, когда пустая строка будет превращена в строку с 0 символ.


это должно работать без изменения исходного csv-файла:

alter table people alter column age type text;
copy people from '/tmp/people.csv' with csv;

Я получил эту ошибку при загрузке » / «разделенного CSV-файла, хотя в моем входном файле не было символов»». Оказалось, что я забыл указать формат:

копировать … ОТ… С (ФОРМАТ CSV, разделитель ‘|’).

1

автор: Slobodan Savkovic



Problem/Motivation

Drupal 9.2.7
Unexpected error after enabling webform_group, using PostgreSQL.

DrupalCoreDatabaseDatabaseExceptionWrapper: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: «my_test_form» LINE 5: WHERE «group_content_field_data».»entity_id» = ‘my_test_for… ^: SELECT «base_table».»id» AS «id», «base_table».»id» AS «base_table_id» FROM «group_content» «base_table» INNER JOIN «group_content_field_data» «group_content_field_data» ON «group_content_field_data».»id» = «base_table».»id» WHERE «group_content_field_data».»entity_id» = :db_condition_placeholder_0; Array ( [:db_condition_placeholder_0] => my_test_form ) in DrupalCoreEntityQuerySqlQuery->result() (line 271 of core/lib/Drupal/Core/Entity/Query/Sql/Query.php).
DrupalCoreDatabaseStatementWrapper->execute() (Line: 874)
DrupalCoreDatabaseConnection->query() (Line: 195)
DrupalCoreDatabaseDriverpgsqlConnection->query() (Line: 512)
DrupalCoreDatabaseQuerySelect->execute() (Line: 145)
DrupalCoreDatabaseDriverpgsqlSelect->execute() (Line: 271)
DrupalCoreEntityQuerySqlQuery->result() (Line: 83)
DrupalCoreEntityQuerySqlQuery->execute() (Line: 166)
Drupalwebform_groupWebformGroupManager->getCurrentGroupContent() (Line: 140)
Drupalwebform_groupWebformGroupManager->getCurrentUserGroupRoles() (Line: 309)
webform_group_webform_access()
call_user_func_array() (Line: 403)
DrupalCoreExtensionModuleHandler->invokeAll() (Line: 97)
DrupalCoreEntityEntityAccessControlHandler->access() (Line: 314)
DrupalCoreEntityEntityBase->access() (Line: 65)
DrupalCoreEntityEntityAccessCheck->access()
call_user_func_array() (Line: 159)
DrupalCoreAccessAccessManager->performCheck() (Line: 135)
DrupalCoreAccessAccessManager->check() (Line: 112)
DrupalCoreAccessAccessManager->checkRequest() (Line: 109)
DrupalCoreRoutingAccessAwareRouter->checkAccess() (Line: 94)
DrupalCoreRoutingAccessAwareRouter->matchRequest() (Line: 112)
SymfonyComponentHttpKernelEventListenerRouterListener->onKernelRequest()
call_user_func() (Line: 142)
DrupalComponentEventDispatcherContainerAwareEventDispatcher->dispatch() (Line: 134)
SymfonyComponentHttpKernelHttpKernel->handleRaw() (Line: 80)
SymfonyComponentHttpKernelHttpKernel->handle() (Line: 57)
DrupalCoreStackMiddlewareSession->handle() (Line: 47)
DrupalCoreStackMiddlewareKernelPreHandle->handle() (Line: 106)
Drupalpage_cacheStackMiddlewarePageCache->pass() (Line: 85)
Drupalpage_cacheStackMiddlewarePageCache->handle() (Line: 47)
DrupalCoreStackMiddlewareReverseProxyMiddleware->handle() (Line: 52)
DrupalCoreStackMiddlewareNegotiationMiddleware->handle() (Line: 23)
StackStackedHttpKernel->handle() (Line: 717)
DrupalCoreDrupalKernel->handle() (Line: 19)

Steps to reproduce

Enable webform_group
And try to build the my_test_form webform

Proposed resolution

Cast entity id as (int).

Remaining tasks

To be patched

User interface changes

no

API changes

no

Data model changes

no

Tag1 supports the Drupal Project.Tag1 logo

Issue Description

We have a definition for a createdAt column as BIGINT in postgres. We’ve had the defaultValue in sequelize defined and working as:

createdAt: {
    type: DataTypes.INTEGER,
    defaultValue: Sequelize.literal('current_millis()'),
  }

This has been working consistently without issue until approximately June 1st, 11am PST.

Now when performing inserts we receive the error message:

 Unexpected error: invalid input syntax for type bigint: "[object Object]"
SequelizeDatabaseError: invalid input syntax for type bigint: "[object Object]"

What are you doing?

Nothing has changed on our end, so I’m not sure how to provide reproduction to the issue..

What do you expect to happen?

We expect the inserts to interpolate the defaultValue correctly and pass our literal current_millis() function to postgres.

What is actually happening?

We see the error.

Additional context

Inspecting the values being passed it seems that the literal function is not being run and instead a javascript string representation of the sequelize.literal is being set. Inspecting the createdAt definition returns:

{
  type: [Function: INTEGER] {
    types: {
      postgres: [Array],
      mysql: [Array],
      mariadb: [Array],
      sqlite: [Array],
      mssql: [Array]
    },
    key: 'INTEGER'
  },
  defaultValue: Literal { val: 'current_millis()' }
}

Looking into the code base it seems that there are some places that explicitly call out when to run the value as a function, e.g. https://github.com/sequelize/sequelize/blob/master/lib/sequelize.js#L1206-L1214

I’m not sure that exact location is where our issue stems from, but hopefully it helps tracking down what is going wrong.

Environment

  • Sequelize version: 5.21.5
  • Node.js version: v13.8.0
  • Operating System: mac

Issue Template Checklist

How does this problem relate to dialects?

  • [ x] I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s):
  • I don’t know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don’t know how to start, I would need guidance.
  • No, I don’t have the time, although I believe I could do it if I had the time…
  • [x ] No, I don’t have the time and I wouldn’t even know how to start.

  • Ошибка невозможно загрузить av базу
  • Ошибка неверный сигнал апс
  • Ошибка невозможно вызвать invoke или begininvoke
  • Ошибка неверный сертификат ssl дбд
  • Ошибка невозвратных затрат это