PL/Python PostgreSQL 存儲過程語言(花架子)

總有一天,我要把這樣的文章,刪掉,統統刪掉,I Hate PG!html

plpythonu安裝

安裝呢是在編譯的過程當中選擇python

./configure --with-python 

[root@laptop]# ./configure --help |grep python
  --with-python           build Python modules (PL/Python)
[root@]# 


具體能夠使用以下命令論證
./configure --help |grep python  

(Linux 環境中多使用 help, 真我的生都是昇華的,
很少說了,技術的梗,離開技術但願你也能活)

而後使用psql 吧,相似安裝模塊的語法,安裝語言sql

postgres=#   CREATE PROCEDURAL LANGUAGE plpythonu;
CREATE LANGUAGE
postgres=# \?
postgres=# \dL
                       List of languages
   Name    |  Owner   | Trusted |         Description          
-----------+----------+---------+------------------------------
 plpgsql   | postgres | t       | PL/pgSQL procedural language
 plpythonu | postgres | f       | 
(2 rows)

postgres=# \dL+
postgres=# CREATE OR REPLACE FUNCTION hello ()
postgres-#   RETURNS TEXT
postgres-# AS $$
postgres$# import os
postgres$# return '你好,我當前目錄爲:'+ os.getcwd()
postgres$# $$ LANGUAGE plpythonu;
CREATE FUNCTION
postgres=# SELECT hello();
               hello                
------------------------------------
 你好,我當前目錄爲:/dev/shm/hello
(1 row)

postgres=#

開篇一: 在greenplum(@pivotal) 中使用PL/Python

在下面的語句中加入了 try{} catch {} 是加入了異常處理post

CREATE TABLE test(id int, name varchar(20));

INSERT INTO test(id, name) VALUES(1, 'hire'),(2, 'me');

CREATE OR REPLACE FUNCTION query_test(a text) RETURNS text AS $$
try:
    query = "SELECT name FROM test"
    r = plpy.execute(query)
    return r[0]
except Exception, ex:
    plpy.notice(str(ex))
    return str(ex)
$$
LANGUAGE plpythonu ; 

SELECT query_test('nothing');

SELECT * FROM test;

定義查詢計劃 使用prepare

CREATE OR REPLACE FUNCTION query_test(a text) RETURNS text AS $$
try:
    query = "SELECT id FROM test where name = $1 "
    plan = plpy.prepare(query, ["text"])
    r = plpy.execute(plan , [a])
    return r[0]
except Exception, ex:
    plpy.notice(str(ex))
    return str(ex)
$$
LANGUAGE plpythonu ; 

SELECT query_test('me');

參考資料:ui

  1. 豬腦子
  2. 官方文檔 PL/Python
相關文章
相關標籤/搜索