Меню

Integer out of range ошибка

Admin 07.06.2020, обновлено: 09.08.2020 Python Errors

Ошибка вида psycopg2.errors.NumericValueOutOfRange: integer out of range.

Ошибка означает, что в таблице колонка в которую пытались сохраниться данные выходит за допустимые границы числа. Надо изменить эту колонку с INT на BIGINT.

Метки:psycopg2

Читайте также

  • PyCharm Python не видится модуль psycopg2PyCharm Python не видится модуль psycopg2
  • Ошибка в SQLAlchemy - sqlalchemy.orm.exc.StaleDataErrorОшибка в SQLAlchemy — sqlalchemy.orm.exc.StaleDataError
  • PostgreSQL - как сбросить очередьPostgreSQL — как сбросить очередь
  • Error on line 35 at column 206: EntityRef: expecting ';'Error on line 35 at column 206: EntityRef: expecting ‘;’

У сайта нет цели самоокупаться, поэтому на сайте нет рекламы. Но если вам пригодилась информация, можете лайкнуть страницу, оставить комментарий или отправить мне подарок на чашечку кофе.

Добавить комментарий

Напишите свой комментарий, если вам есть что добавить/поправить/спросить по теме текущей статьи:
«Что означает psycopg2.errors.NumericValueOutOfRange: integer out of range«

attach_file Добавить файл

Имя *

Email *

Получать новые комментарии по электронной почте. Вы можете подписаться без комментирования.

Approved: ASR Pro

  • 1. Download ASR Pro and install it on your computer
  • 2. Launch the program and click «Scan»
  • 3. Click «Repair» to fix any issues that are found
  • Speed up your computer’s performance now with this simple download.

    Sometimes your computer may display a message stating that a Postgres error integer is out of range. There can be many reasons for this problem. You tried to insert an integer value into a counter for INSERT that exceeds the range of the underlying integer data type in the specified scope. The simplest example is when you literally put too much valuable content into the database. In such cases, it could be an error in the write stream or the wrong data mode in the database.

      CREATE TABLE raw (    SERIAL ID,    regtime is NOT NULL,    NOT ZERO minute flow rate,    Varchar's resource (15),    ALL source port,    Varchar station (15),    exclude INTEGER,    logical filling); ... + table of indices and exchanges 

    I have been successfully using this bank for some time now, and with a sudden rate the next deposit no longer works ..

      INSERT INTO raw (   Time, Regtime, Blocked, Destination, Source Port, Source, Destination) VALUES (    1403184512.2283964, 1403184662.118, false, 2, 3, '192.168.0.1', '192.168.0.2'); 

    I don’t know where to start debugging. Instead of thisth I ran out of space and the error is pretty subtle.

    Requested

    Visited 15000 times

    I have two questions. I’m looking for two that insert the same value: 429496729600 , but some don’t work with the error:

      db => mount order_detail set amount = 400 * 1024 * 1024 * 1024 where I had = 11;ERROR: integer out of rangedb => update the amount defined for order_detail = 429496729600 only if id = 11;UPDATE 1 

    UPD
    If you forgot to enter the type amount , it will be bigint and

      400 * 1024 * 1024 * 1024 == 429496729600 

    31.8k

    asked May 2018 at 22:39

    16.5k

    Not The Answer You Are Looking For? Check Out Other Questions Tagged Sql Postgresql Type-conversion Or Ask Your Suspect.

    To force multiplication to return bigint instead of int, you can convert 1 to bigint and multiply

    postgres error integer out of range

      select cast (1 bigint every time) * 400 * 1024 * 1024 * 1024;   ?Pillar?-------------- 429496729600 

    answered Sep 8 ’18 at 19:50

    11.7k

    int boA larger value of 2 31 -1, the first update value greater than this, raises a new error.

    INT -2147483648 to +2147483647

    postgres error integer out of range

    BIGINT -9223372036854775808 to 9223372036854775807

      ALTER TABLE order_detail COLUMN Fine tuning of the amount TYPE BIGINT; 

    postgresql forces 429496729600 to try to be BIGINT because the value is greater than the int range.

      SELECT pg_typeof (429496729600);| pg_typeof --------- || || bigint | 

    If your website is multiplying by numbers, this will be interpreted as int .

      SELECT pg_typeof (1 * 15 * 1);| pg_typeof || --------- || whole | 
      SELECT 400 * 1024 * 1024 * 1024 :: BIGINT;| ?Pillar? || ------------ || 429496729600 | 

    answered Sep 8, 2018 at 7:45 pm

    Approved: ASR Pro

    ASR Pro is the world’s most popular and effective PC repair tool. It is trusted by millions of people to keep their systems running fast, smooth, and error-free. With its simple user interface and powerful scanning engine, ASR Pro quickly finds and fixes a broad range of Windows problems — from system instability and security issues to memory management and performance bottlenecks.

  • 1. Download ASR Pro and install it on your computer
  • 2. Launch the program and click «Scan»
  • 3. Click «Repair» to fix any issues that are found
  • 31.8k

    Speed up your computer’s performance now with this simple download.

    New issue

    Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

    By clicking “Sign up for GitHub”, you agree to our terms of service and
    privacy statement. We’ll occasionally send you account related emails.

    Already on GitHub?
    Sign in
    to your account

    Comments

    @igorbernstein

    I think I found a regression related to: #97

    When using deltas & rails fixtures with postgresql I get the error: «ERROR: index ‘catalog_edition_core’: sql_range_query: ERROR: integer out of range»

    I tracked the problem down to my sphinx.conf:
    sql_query = SELECT «catalog_editions».»id» * 4 + 0 AS «id»…..

    updating the sql_query to
    sql_query = SELECT «catalog_editions».»id»::bigint * 4 + 0 AS «id»…..

    fixes the issue. My temporary workaround is to monkey patch thinking sphinx:

    ThinkingSphinx::ActiveRecord::SQLBuilder.class_eval do
      def document_id
        quoted_alias = quote_column source.primary_key
        "#{quoted_primary_key}::bigint * #{config.indices.count} + #{source.offset} AS #{quoted_alias}"
      end
    end

    which obviously breaks mysql.

    @pat

    Are you finding this change still works for you? I’ve just created a test table which uses bigints for the primary key, and added a record with a very large id. Sphinx is happy indexing up to a point… but if the indices count or offset puts it over the 64 bit limit, then I get the error you mention, and your fix doesn’t stop the error. My understanding is that the calculated value is too big for PostgreSQL, let alone Sphinx.

    @igorbernstein

    @pat

    Thanks for the response Igor. Could you share the fixture definition? And how in your test you’re loading the fixture data?

    @lunaru

    Just to +1 this, this is definitely a regression from #97.

    It can reproduced running rake ts:index on any project using postgres and foxy fixtures.

    In 2.1.0:

    sql_query = SELECT «articles».»id» * 4::INT8 + 0 AS «id» …

    In 3.1.0:

    sql_query = SELECT «articles».»id» * 8 + 0 AS «id» …

    With an ID like «980190962», which is within the 32 bit integer range, multiplying it causes it to extend outside the bounds of the «integer» type.

    pat

    added a commit
    that referenced
    this issue

    May 4, 2014

    @pat

    Set big_document_ids to true either via set_property in specific index definitions, or within config/thinking_sphinx.yml to impact all indices. See #610.

    @pat

    Just pushed a fix for this to the develop branch. Either in a specific index:

    set_property :big_document_ids => true

    Or in config/thinking_sphinx.yml to impact all indices:

    development:
      big_document_ids: true

    To use the latest in develop:

    gem 'thinking-sphinx', '~> 3.1.1',
      :git    => 'git://github.com/pat/thinking-sphinx.git',
      :branch => 'develop',
      :ref    => '119ee4e1a7'

    @lunaru

    Awesome. Can’t wait for this to hit release

    @Envek

    I’ve seen such an error today when someone inserted 20014-12-25 in indexed date field 💣

    @pat

    @Envek you may want to set 64bit_timestamps to true for each environment in config/thinking_sphinx.yml — and/or have some validation on dates to avoid those massive values 😉

    Вопрос:

    Я пытаюсь вставить некоторые целые числа в таблицу Postgres со следующим несколько простым кодом.

    #include <libpq-fe.h>
    #include <stdio.h>
    #include <stdint.h>
    
    int main() {
    int64_t i = 0;
    PGconn * connection = PQconnectdb( "dbname='babyfood'" );
    if( !connection || PQstatus( connection ) != CONNECTION_OK )
    return 1;
    printf( "Number: " );
    scanf( "%d", &i );
    
    char * params[1];
    int param_lengths[1];
    int param_formats[1];
    param_lengths[0] = sizeof( i );
    param_formats[0] = 1;
    params[0] = (char*)&i;
    PGresult * res =  PQexecParams( connection,
    "INSERT INTO intlist VALUES ( $1::int8 )",
    1,
    NULL,
    params,
    param_lengths,
    param_formats,
    0 );
    printf( "%sn", PQresultErrorMessage( res ) );
    PQclear( res );
    PQfinish( connection );
    return 0;
    }
    

    Получаю следующие результаты:

    Number: 55
    ERROR:  integer out of range
    
    Number: 1
    ERROR:  integer out of range
    

    Я уверен, что int64_t всегда будет содержать 8-байтовое целое на любой разумной платформе. Что я делаю неправильно?

    Лучший ответ:

    Вместо:

    params[0] = (char*)&i;
    

    вы должны использовать:

    #include <endian.h>
    /* ... */
    int64_t const i_big_endian = htobe64(i);
    params[0] = (char*)&i_big_endian;
    

    Функция

    A htobe64 переключит сущность на малознаковом языке и ничего не сделает на big-endian.

    Отключите функцию flip_endian, так как это сделает вашу программу несовместимой с компьютерами большого и среднего уровней, такими как PowerPC, Alpha, Motorola, SPARC, IA64 и т.д. Даже если ваша программа не ожидает запуска их это плохой стиль, медленный и подверженный ошибкам.

    Ответ №1

    Хорошо, похоже, что это проблема конца, которая до сих пор не совсем объясняет это, поскольку малознаковое (то есть x86) 64-разрядное целое число со знаком должно вписываться в 64-битное целочисленное целое число и наоборот, они “просто испорчен. Однако замена конечного элемента на целое число дает правильное значение. Перестановка выполняется со следующей функцией:

    int64_t flip_endian( int64_t endi ) {
    char* bytearray;
    char swap;
    int64_t orig = endi;
    int i;
    
    bytearray = (char*)&orig;
    
    for( i = 0; i < sizeof( orig )/2; ++i ) {
    swap = bytearray[i];
    bytearray[i] = bytearray[ sizeof( orig ) - i - 1 ];
    bytearray[ sizeof( orig ) - i - 1 ] = swap;
    }
    
    return orig;
    
    }
    

    Ответ №2

    Я думаю, что он передается как 32-битный int, а затем получает отличное от 64-битного, потому что вы не говорите libpq, какой формат.

    Попробуйте указать массив для paramTypes, с oid для int8 (что равно 20) для параметра.

    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии

    А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Integer int64 biginteger real ошибка
  • Integer division or modulo by zero python ошибка