postgresqldatabase-partitioning

How partition reminder is calculated in postgres for PARTITION BY HASH


I want to manually calculate reminder in order to use upsert in partitioned table. I tried following code:

create table test_partitioning
(
    test bigint not null
) partition by hash (test);

DO $$
    declare
        _remainder integer ;
    begin
        FOR _remainder IN (select generate_series(1, 10)) LOOP
                EXECUTE 'CREATE TABLE  IF NOT EXISTS  test_partitioning_' || _remainder ||
                        ' PARTITION OF test_partitioning FOR VALUES WITH (modulus 10, remainder ' || (_remainder - 1) || ')';
            END LOOP;
    END $$;

do
$$
    declare
        value bigint ;
        calculated_reminder int;
    begin
        FOR value IN (select generate_series(1, 10)) LOOP
                calculated_reminder = (((hashint8extended(value, 8816678312871386365)::numeric + 5305509591434766563) % 10)::int + 10) % 10;

                if not satisfies_hash_partition('test_partitioning'::regclass, 10, calculated_reminder, value) THEN
                    RAISE 'check failed, value=%, reminder=%', value, calculated_reminder;
                end if;
            end LOOP ;

    end
$$;

it's failed on values 2 and 3. What is wrong in my calculations?


Solution

  • Here is solution:

    CREATE OR REPLACE FUNCTION unsigned2signed(signed bigint)
    RETURNS numeric AS $$
    SELECT CASE
               WHEN signed >= 0 THEN signed::numeric
               ELSE 18446744073709551616 + signed
               END
    $$ LANGUAGE SQL;
    
    calculated_reminder = ((unsigned2signed(hashint8extended(value, 8816678312871386365)) + 5305509591434766563) % 18446744073709551616) % 10;
    

    btw original solution worked in tests too for number of partitions = 2^x (2, 4, 8 , 16, ...)