温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PostgreSQL DBA(99) - Develop(generate random string)

发布时间:2020-08-13 11:37:34 来源:ITPUB博客 阅读:122 作者:husthxd 栏目:关系型数据库

为了验证TOAST的相关功能,通过lpad、rpad等方式由于重复率太高看不出效果,因此需要生成随机字符串来填充数据。

生成随机字符串的样例函数

CREATE OR REPLACE FUNCTION sf_generate_randomstring(length int4)
RETURNS text
AS $$
declare 
  chars text[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}';
  ret text := '';
  i integer := 0;
  lenofarray int := array_length(chars, 1);
begin
  if length < 0 then
    raise exception '输入参数不合法,请重新输入!';
  end if;
  for i in 1..length loop
    ret := ret || chars[1+random()*(lenofarray-1)];
  end loop;
  return ret;
end;
$$ 
LANGUAGE 'plpgsql'
;

该函数会随机生成由a-zA-Z0-9字符组成的字符串,长度由输入参数length确定,当然也可以在数组chars中添加其他字符,如中文字符等。
效果如下:

[local]:5432 pg12@testdb=# select sf_generate_randomstring(100);
                                       sf_generate_randomstring                             
--------------------------------------------------------------------------------------------
 hmski6FmSCcRPcfmSkC3aaX7Ay3QlmTz0497pitHNjLcU8KdKVtO7ysmoqRnwM2Dc9VuPnOxGfUgTX6lIdplRciYETic4GrdRqD1
(1 row)
Time: 2.022 ms
[local]:5432 pg12@testdb=# select length(sf_generate_randomstring(40000));
 length 
--------
  40000
(1 row)
Time: 174.529 ms
[local]:5432 pg12@testdb=#

参考资料
PostgreSQL 如何快速构建 海量 逼真 测试数据

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI