标签:postgresql plpgsql function python
在PostgreSQL里,所有的存储函数需求都可以用PLPGSQL来实现。同时也支持用第三方语言来编写,这个就得看自己哪个方面熟练了。CREATE OR REPLACE FUNCTION ytt.insert_plpgsql(f_num integer) RETURNS void LANGUAGE plpgsql AS $ytt$ declare i int := 0; v_rank int := 0; v_log_time timestamp; begin while i < f_num loop v_rank = ceil(random()*100); v_log_time = now() - ‘1 day‘::interval*ceil(random()*50); insert into t1 (rank,log_time) values (v_rank,v_log_time); i = i + 1; end loop; end; $ytt$;
t_girl=# select insert_plpgsql(1000000); insert_plpgsql ---------------- (1 row) Time: 27286.668 ms
t_girl=# \dx plpythonu List of installed extensions Name | Version | Schema | Description -----------+---------+------------+------------------------------------------ plpythonu | 1.0 | pg_catalog | PL/PythonU untrusted procedural language (1 row)
CREATE OR REPLACE FUNCTION ytt.insert_py(f_num integer) RETURNS void LANGUAGE plpythonu AS $ytt$ import datetime import random i = 0 while i < f_num: v_rank = random.randrange(0,100) v_log_time = datetime.datetime.now() - datetime.timedelta(days=random.randrange(0,50)) query0 = "insert into ytt.t1 (rank,log_time) values (" + str(v_rank) + ",‘" + str(v_log_time)+ "‘)" plpy.execute(query0) i += 1 $ytt$;
t_girl=# select insert_py(1000000); insert_py ----------- (1 row) Time: 86061.558 ms
CREATE OR REPLACE FUNCTION ytt.insert_multi_py(f_num integer, f_values integer) RETURNS text LANGUAGE plpythonu AS $ytt$ import datetime import random i = 0 j = 0 query0 = "insert into ytt.t1(rank,log_time) values " data0 = ‘‘ if (f_num/f_values)*f_values < f_num: return ‘Parameters should be times relation.(f_num:1000,f_values:10)‘ else: while i < int(f_num/f_values): j = 0 while j < f_values: v_rank = random.randrange(0,100) v_log_time = datetime.datetime.now() - datetime.timedelta(days=random.randrange(0,50)) data0 = data0 + ",(" + str(v_rank) + ",‘" + str(v_log_time)+ "‘)" j += 1 result0 = query0 + data0[1:len(data0)] plpy.execute(result0) data0 = ‘‘ i += 1 return ‘Inserting ‘ + str(f_num) + ‘ rows‘ $ytt$;
t_girl=# select insert_multi_py(1000000,20); insert_multi_py ------------------------ Inserting 1000000 rows (1 row) Time: 27587.715 ms t_girl=#
用第三方语言编写PostgreSQL 存储函数,布布扣,bubuko.com
标签:postgresql plpgsql function python
原文地址:http://blog.csdn.net/yueliangdao0608/article/details/25642771