2017-06-19 9 views
0

UNIQUE列のデフォルトgen_random_bytesのは、我々は次の表があるとしましょう:のPostgreSQL:

CREATE TABLE foo (
    column_1 bigint, 
    column_2 bytea DEFAULT gen_random_bytes(2), 
    PRIMARY KEY (column_1, column_2) 
); 

注:私たちはcolumn_2が&暗号的に強いランダムになりたいです。

主キーの競合を起こさずに行を挿入するにはどうすればよいですか?

私はgen_random_bytes(2)がユニークな結果を返すまでループする必要があると思いますか?その場合、純粋なSQL、おそらくplpgsqlではなく再帰的なCTEでこのループを実行できますか?

答えて

0
insert into t (col1, col2) 
select 1, ('\x' || right('000' || to_hex(i), 4))::bytea 
from (
    select generate_series(0, 65535) i 
    except 
    select get_byte(col2, 0) * 256 + get_byte(col2, 1) 
    from t 
    where col1 = 1 
) s 
order by random() 
limit 1 
+0

ご迷惑をおかけして申し訳ございません。 1つの行だけを挿入したいだけです。 – ma11hew28

+0

@mattdipasquale:新しい回答 –