PostgreSQL函数返回带有两个元素的文本数组

时间:2017-10-31 17:29:21

标签: python postgresql psycopg2

我试图使用postgresql函数返回带有两个元素的文本数组。但输出似乎产生了一个元素。

这是来自pgAdmin查询的结果:在这里,它看起来像是带有两个元素的结果数组

select "address_pts".usp_etl_gis_get_cname_bd_ext(3)
ALLEGHANY,POLYGON((1308185.61436242 959436.119048506,1308185.61436242 1036363.17188701,1441421.26094835 1036363.17188701,1441421.26094835 959436.119048506,1308185.61436242 959436.119048506))

但是在我调用函数的Python中,我看到输出数组的长度只有1。

(partial python code)
pg_cur.execute("SELECT \"VA\".address_pts.usp_etl_gis_get_cname_bd_ext(3)")
for rec in pg_cur:
   print(len(rec))
-- output = 1

for rec in pg_cur:
   print(rec[0])
-- ouput: ['ALLEGHANY', 'POLYGON((1308185.61436242 959436.119048506,1308185.61436242 1036363.17188701,1441421.26094835 1036363.17188701,1441421.26094835 959436.119048506,1308185.61436242 959436.119048506))']

 it generates an error for below code:
 for rec in pg_cur:
   print(rec[1]) 

-- Here is the function --  
-- postgresql 9.6

CREATE OR REPLACE FUNCTION address_pts.usp_etl_gis_get_cname_bd_ext(
_cid integer
  )
RETURNS TEXT[]
LANGUAGE 'plpgsql'
COST 100.0
VOLATILE NOT LEAKPROOF 
AS $function$


DECLARE cname TEXT;
DECLARE cbd_ext TEXT;
DECLARE outarr TEXT[];

BEGIN    
IF (_cid NOT BETWEEN 1 and 100) THEN
    RAISE EXCEPTION '%s IS NOT A VALID COUNTY ID. ENTER A COUNTY BETWEEN 1..100', _cid;
END IF;


select upper(rtrim(ltrim(replace(name10,' ','_'))))
into cname
from "jurisdictions"."CB_TIGER_2010"
WHERE county_id = _cid;

/* 
#Returns the float4 minimum bounding box for the supplied geometry, 
#as a geometry. The polygon is defined by the corner points of the 
#bounding box ((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY)). 
#(PostGIS will add a ZMIN/ZMAX coordinate as well).
*/

SELECT ST_AsText(ST_Envelope(geom))
INTO cbd_ext
from "jurisdictions"."CB_TIGER_2010"
where county_id = _cid;

outarr[0] := cname::text;
outarr[1] := cbd_ext::text;

RETURN outarr;

END;

$function$;

的问题:

  1. postgresql函数是否产生长度为1或2的数组?

  2. 如果len为1,如何分割结果?例如: [' ALLEGHANY',' POLYGON((1308185.614362,...))']

  3. 谢谢

1 个答案:

答案 0 :(得分:0)

如果您在使用Python时很乐意拆分字符串,可以尝试使用regex和模块re

# Python3
import re
p = re.compile(r"\['(.*)','(.*)']")
res = p.search("['ALLEGHANY','POLYGON((1308185.614362,...))']")

print(res.group(1)) # 'ALLEGHANY'
print(res.group(2)) # 'POLYGON((1308185.614362,...))'