你好,游客 登录 注册 搜索
背景:
阅读新闻

用第三方语言编写PostgreSQL 存储函数

[日期:2014-06-01] 来源:Linux社区  作者:四爷 [字体:大 中 小]

在PostgreSQL里,所有的存储函数需求都可以用PLPGSQL来实现。同时也支持用第三方语言来编写,这个就得看自己哪个方面熟练了。

不过要注意的一点是 PLPGSQL的效率怎么着都比其他第三方语言来的高效。

------------------------------------华丽丽的分割线------------------------------------

CentOS 6.3环境下yum安装PostgreSQL 9.3 http://www.linuxidc.com/Linux/2014-05/101787.htm

PostgreSQL缓存详述 http://www.linuxidc.com/Linux/2013-07/87778.htm

Windows平台编译 PostgreSQL http://www.linuxidc.com/Linux/2013-05/85114.htm

Ubuntu下LAPP(Linux+Apache+PostgreSQL+PHP)环境的配置与安装 http://www.linuxidc.com/Linux/2013-04/83564.htm

Ubuntu上的phppgAdmin安装及配置 http://www.linuxidc.com/Linux/2011-08/40520.htm

CentOS平台下安装PostgreSQL9.3 http://www.linuxidc.com/Linux/2014-05/101723.htm

PostgreSQL配置Streaming Replication集群 http://www.linuxidc.com/Linux/2014-05/101724.htm

------------------------------------华丽丽的分割线------------------------------------

比如,简单的插入表的存储函数:

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$;

现在来插入100W条记录,花费时间大概为27秒。

t_girl=# select insert_plpgsql(1000000);
 insert_plpgsql
----------------
 
(1 row)


Time: 27286.668 ms

我们改用python 来实现
在编写python 脚本前,确保系统已经载入了plpythonu扩展。

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$;

更多详情见请继续阅读下一页的精彩内容: http://www.linuxidc.com/Linux/2014-06/102568p2.htm

linux
相关资讯       PostgreSQL函数  PostgreSQL存储函数 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款