1. 为什么要使用pl/lua
可以大大提升存储过程的性能,特别是循环的性能。 在PostgreSQL中数组或一些json对象都是不可变的,如往数组或json对象中添加元素时,需要把拷贝源对象而生成一个新对象,导致很大的开销。而使用lua语言的list和table对象就没有这个问题了。 lua语言的语法更灵活。
2. 我们先看看性能
2.1 查看循环的效率
create or replace function f_pl01(cnt int) returns int language plpgsql as $$declarei int;begini:=0;LOOPi = i + 1;EXIT WHEN i >= cnt;END LOOP;return i;end;$$;
create function f_lua01(cnt int) returns int language pllua as $$local i=0while( i < cnt ) doi = i+1endreturn i$$;
postgres=# \timingTiming is on.postgres=# select f_pl01(10000000);f_pl01----------10000000(1 row)Time: 6482.846 ms (00:06.483)postgres=# select f_lua01(10000000);f_lua01----------10000000(1 row)Time: 556.831 ms
create or replace function f_py01(cnt int) returns int language plpython3u as $$i = 0while i < cnt:i = i + 1return i$$;
postgres=# select f_py01(10000000);f_py01----------10000000(1 row)Time: 1008.750 ms (00:01.009)
2.2 数组中添加元素中的效率
create or replace function f_pl02(cnt int) returns int language plpgsql as $$declarei int;myarr text[];s1 text;begini:=0;s1 := lpad('', 2048, 'helloosdba');LOOPmyarr := array_append(myarr, s1);i = i + 1;EXIT WHEN i >= cnt;END LOOP;return array_length(myarr, 1);end;$$;
create or replace function f_lua02(cnt int) returns int language pllua as $$local i=0local myarr = {}local s1 = string.rep('helloosdba', 2048)while( i < cnt ) doi = i+1myarr[i] = s1endreturn #myarr$$;
postgres=# select f_pl02(100000);f_pl02--------100000(1 row)Time: 756.772 mspostgres=# select f_lua02(100000);f_lua02---------100000(1 row)Time: 10.731 ms
create or replace function f_py02(cnt int) returns int language plpython3u as $$i = 0myarr = []s1 = 'helloosdba'*2048while i < cnt:i = i+1myarr.append(s1)return len(myarr)$$;
postgres=# select f_py02(100000);f_py02--------100000(1 row)Time: 23.459 ms
3. 安装方法
cd usr/srccurl -R -O http://www.lua.org/ftp/lua-5.3.5.tar.gztar xvf lua-5.3.5.tar.gz
/usr/bin/ld: usr/local/lib/liblua.a(loadlib.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC/usr/bin/ld: final link failed: Nonrepresentable section on outputcollect2: error: ld returned 1 exit status
-fPIC:
CFLAGS= -fPIC -O2 -Wall -Wextra -DLUA_COMPAT_5_2 $(SYSCFLAGS) $(MYCFLAGS)
make install
cd usr/srcgit clone https://github.com/pllua/pllua-ng.gitcd pllua-ngmake PG_CONFIG=/usr/pgsql-11/bin/pg_configmake PG_CONFIG=/usr/pgsql-11/bin/pg_config install
create extension pllua;
4. pl/lua的一些资料
使用文档: https://pllua.github.io/pllua-ng/ 源代码:https://github.com/pllua/pllua-ng

扫描钉钉直播群二维码 关注我们免费看直播
文章转载自PostgreSQL中文社区,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




