head	2.89;
access;
symbols
	REL9_0_0:2.86.2.3
	REL9_1_ALPHA1:2.88
	REL9_0_RC1:2.86.2.2
	REL9_0_BETA4:2.86.2.1
	REL9_0_STABLE:2.86.0.2
	REL9_0_BETA3:2.86
	REL9_0_BETA2:2.84
	REL7_4_29:2.20.2.1
	REL8_0_25:2.37.4.1
	REL8_1_21:2.49.2.2
	REL8_2_17:2.59.2.3
	REL8_3_11:2.67.2.1
	REL8_4_4:2.69.2.2
	REL9_0_BETA1:2.83
	REL9_0_ALPHA5_BRANCH:2.82.0.2
	REL9_0_ALPHA5:2.82
	REL7_4_28:2.20
	REL8_0_24:2.37
	REL8_1_20:2.49.2.1
	REL8_2_16:2.59.2.2
	REL8_3_10:2.67
	REL8_4_3:2.69.2.1
	REL9_0_ALPHA4:2.80
	REL9_0_ALPHA4_BRANCH:2.80.0.2
	REL8_5_ALPHA3:2.71
	REL8_5_ALPHA3_BRANCH:2.71.0.2
	REL7_4_27:2.20
	REL8_0_23:2.37
	REL8_1_19:2.49.2.1
	REL8_2_15:2.59.2.2
	REL8_3_9:2.67
	REL8_4_2:2.69
	REL8_5_ALPHA2:2.70
	REL8_5_ALPHA2_BRANCH:2.70.0.4
	REL7_4_26:2.20
	REL8_0_22:2.37
	REL8_1_18:2.49.2.1
	REL8_2_14:2.59.2.2
	REL8_3_8:2.67
	REL8_4_1:2.69
	REL8_5_ALPHA1:2.70
	REL8_5_ALPHA1_BRANCH:2.70.0.2
	REL8_4_STABLE:2.69.0.2
	REL8_4_0:2.69
	REL8_4_RC2:2.69
	REL8_4_RC1:2.69
	REL8_4_BETA2:2.69
	REL8_4_BETA1:2.69
	REL7_4_25:2.20
	REL8_0_21:2.37
	REL8_1_17:2.49.2.1
	REL8_2_13:2.59.2.2
	REL8_3_7:2.67
	REL7_4_24:2.20
	REL8_0_20:2.37
	REL8_1_16:2.49.2.1
	REL8_2_12:2.59.2.2
	REL8_3_6:2.67
	REL7_4_23:2.20
	REL8_0_19:2.37
	REL8_1_15:2.49.2.1
	REL8_2_11:2.59.2.2
	REL8_3_5:2.67
	REL7_4_22:2.20
	REL8_0_18:2.37
	REL8_1_14:2.49.2.1
	REL8_2_10:2.59.2.2
	REL8_3_4:2.67
	REL7_4_21:2.20
	REL8_0_17:2.37
	REL8_1_13:2.49.2.1
	REL8_2_9:2.59.2.2
	REL8_3_3:2.67
	REL7_4_20:2.20
	REL8_0_16:2.37
	REL8_1_12:2.49.2.1
	REL8_2_8:2.59.2.2
	REL8_3_2:2.67
	REL8_2_7:2.59.2.2
	REL8_3_1:2.67
	REL8_3_STABLE:2.67.0.2
	REL8_3_0:2.67
	REL8_3_RC2:2.66
	REL7_3_21:2.18
	REL7_4_19:2.20
	REL8_0_15:2.37
	REL8_1_11:2.49.2.1
	REL8_2_6:2.59.2.2
	REL8_3_RC1:2.66
	REL8_3_BETA4:2.66
	REL8_3_BETA3:2.66
	REL8_3_BETA2:2.66
	REL8_3_BETA1:2.66
	REL7_3_20:2.18
	REL7_4_18:2.20
	REL8_0_14:2.37
	REL8_1_10:2.49.2.1
	REL8_2_5:2.59.2.2
	REL7_3_19:2.18
	REL7_4_17:2.20
	REL8_0_13:2.37
	REL8_1_9:2.49.2.1
	REL8_2_4:2.59.2.1
	REL8_0_12:2.37
	REL8_1_8:2.49.2.1
	REL8_2_3:2.59.2.1
	REL7_3_18:2.18
	REL7_4_16:2.20
	REL8_0_11:2.37
	REL8_1_7:2.49.2.1
	REL8_2_2:2.59.2.1
	REL8_0_10:2.37
	REL8_1_6:2.49.2.1
	REL8_2_1:2.59
	REL7_4_15:2.20
	REL7_3_17:2.18
	REL8_2_STABLE:2.59.0.2
	REL8_2_0:2.59
	REL8_2_RC1:2.59
	REL8_2_BETA3:2.58
	REL8_2_BETA2:2.58
	REL8_1_5:2.49.2.1
	REL8_0_9:2.37
	REL7_4_14:2.20
	REL7_3_16:2.18
	REL8_2_BETA1:2.57
	REL7_3_15:2.18
	REL7_4_13:2.20
	REL8_0_8:2.37
	REL8_1_4:2.49
	REL7_3_14:2.18
	REL7_4_12:2.20
	REL8_0_7:2.37
	REL8_1_3:2.49
	REL7_3_13:2.18
	REL7_4_11:2.20
	REL8_0_6:2.37
	REL8_1_2:2.49
	REL7_3_12:2.18
	REL7_4_10:2.20
	REL8_0_5:2.37
	REL8_1_1:2.49
	REL8_1_STABLE:2.49.0.2
	REL8_1_0:2.49
	REL8_1_0RC1:2.48
	REL8_1_0BETA4:2.47
	REL8_1_0BETA3:2.45
	REL7_3_11:2.18
	REL7_4_9:2.20
	REL8_0_4:2.37
	REL8_1_0BETA2:2.45
	REL8_1_0BETA1:2.45
	REL7_2_8:2.15
	REL7_3_10:2.18
	REL7_4_8:2.20
	REL8_0_3:2.37
	REL8_0_2:2.37
	REL7_2_7:2.15
	REL7_3_9:2.18
	REL7_4_7:2.20
	REL8_0_1:2.37
	REL8_0_STABLE:2.37.0.4
	REL8_0_0:2.37.0.2
	REL8_0_0RC5:2.35
	REL8_0_0RC4:2.35
	REL8_0_0RC3:2.35
	REL8_0_0RC2:2.34
	REL8_0_0RC1:2.32
	REL8_0_0BETA5:2.32
	REL8_0_0BETA4:2.29
	REL7_4_6:2.20
	REL7_3_8:2.18
	REL7_2_6:2.15
	REL8_0_0BETA3:2.28
	REL8_0_0BETA2:2.27
	REL7_2_5:2.15
	REL7_4_5:2.20
	REL7_3_7:2.18
	REL7_4_4:2.20
	REL8_0_0BETA1:2.26
	REL7_4_3:2.20
	REL7_4_2:2.20
	REL7_3_6:2.18
	REL7_4_1:2.20
	REL7_3_5:2.18
	REL7_4:2.20
	REL7_4_RC2:2.20
	REL7_4_STABLE:2.20.0.2
	REL7_4_RC1:2.20
	REL7_4_BETA5:2.20
	REL7_4_BETA4:2.20
	REL7_4_BETA3:2.20
	REL7_4_BETA2:2.19
	WIN32_DEV:2.19.0.2
	REL7_4_BETA1:2.19
	REL7_3_4:2.18
	REL7_3_2:2.18
	REL7_2_4:2.15
	REL7_3_STABLE:2.18.0.2
	REL7_2_3:2.15
	REL7_2_STABLE:2.15.0.2
	REL7_2:2.15
	REL7_2_RC2:2.14
	REL7_2_RC1:2.14
	REL7_2_BETA5:2.14
	REL7_2_BETA4:2.11
	REL7_2_BETA3:2.10
	REL7_2_BETA2:2.10
	REL7_2_BETA1:2.10
	REL7_1_2:2.7
	REL7_1_STABLE:2.7.0.2
	REL7_1_BETA:2.5
	REL7_1_BETA3:2.7
	REL7_1_BETA2:2.7
	REL7_1:2.7
	REL7_0_PATCHES:2.4.0.2
	REL7_0:2.3;
locks; strict;
comment	@# @;


2.89
date	2010.09.09.00.48.22;	author momjian;	state Exp;
branches;
next	2.88;

2.88
date	2010.08.17.04.37.21;	author petere;	state Exp;
branches;
next	2.87;

2.87
date	2010.07.29.19.34.40;	author petere;	state Exp;
branches;
next	2.86;

2.86
date	2010.07.08.21.35.33;	author petere;	state Exp;
branches
	2.86.2.1;
next	2.85;

2.85
date	2010.06.14.18.47.05;	author momjian;	state Exp;
branches;
next	2.84;

2.84
date	2010.05.13.16.39.43;	author adunstan;	state Exp;
branches;
next	2.83;

2.83
date	2010.04.03.07.22.55;	author petere;	state Exp;
branches;
next	2.82;

2.82
date	2010.02.25.10.02.30;	author mha;	state Exp;
branches;
next	2.81;

2.81
date	2010.02.25.03.08.07;	author tgl;	state Exp;
branches;
next	2.80;

2.80
date	2010.02.12.19.35.25;	author adunstan;	state Exp;
branches;
next	2.79;

2.79
date	2010.02.05.18.11.46;	author momjian;	state Exp;
branches;
next	2.78;

2.78
date	2010.02.01.15.48.35;	author momjian;	state Exp;
branches;
next	2.77;

2.77
date	2010.01.30.01.46.57;	author adunstan;	state Exp;
branches;
next	2.76;

2.76
date	2010.01.27.02.55.04;	author adunstan;	state Exp;
branches;
next	2.75;

2.75
date	2010.01.26.23.11.56;	author adunstan;	state Exp;
branches;
next	2.74;

2.74
date	2010.01.20.03.37.10;	author rhaas;	state Exp;
branches;
next	2.73;

2.73
date	2010.01.20.01.08.21;	author adunstan;	state Exp;
branches;
next	2.72;

2.72
date	2010.01.09.02.40.50;	author adunstan;	state Exp;
branches;
next	2.71;

2.71
date	2009.11.29.03.02.27;	author tgl;	state Exp;
branches;
next	2.70;

2.70
date	2009.08.15.00.33.12;	author petere;	state Exp;
branches;
next	2.69;

2.69
date	2008.04.10.15.16.46;	author alvherre;	state Exp;
branches
	2.69.2.1;
next	2.68;

2.68
date	2008.03.28.00.21.55;	author tgl;	state Exp;
branches;
next	2.67;

2.67
date	2008.01.25.15.28.35;	author adunstan;	state Exp;
branches
	2.67.2.1;
next	2.66;

2.66
date	2007.05.04.14.55.32;	author adunstan;	state Exp;
branches;
next	2.65;

2.65
date	2007.05.03.15.05.56;	author neilc;	state Exp;
branches;
next	2.64;

2.64
date	2007.02.16.03.50.29;	author momjian;	state Exp;
branches;
next	2.63;

2.63
date	2007.02.01.19.10.24;	author momjian;	state Exp;
branches;
next	2.62;

2.62
date	2007.02.01.00.28.17;	author momjian;	state Exp;
branches;
next	2.61;

2.61
date	2007.01.31.20.56.18;	author momjian;	state Exp;
branches;
next	2.60;

2.60
date	2007.01.30.22.29.23;	author momjian;	state Exp;
branches;
next	2.59;

2.59
date	2006.11.13.17.13.56;	author adunstan;	state Exp;
branches
	2.59.2.1;
next	2.58;

2.58
date	2006.10.23.18.10.31;	author petere;	state Exp;
branches;
next	2.57;

2.57
date	2006.09.16.00.30.14;	author momjian;	state Exp;
branches;
next	2.56;

2.56
date	2006.08.12.20.05.54;	author tgl;	state Exp;
branches;
next	2.55;

2.55
date	2006.05.30.11.40.21;	author momjian;	state Exp;
branches;
next	2.54;

2.54
date	2006.05.29.13.51.23;	author adunstan;	state Exp;
branches;
next	2.53;

2.53
date	2006.05.26.17.34.16;	author adunstan;	state Exp;
branches;
next	2.52;

2.52
date	2006.03.10.19.10.48;	author momjian;	state Exp;
branches;
next	2.51;

2.51
date	2006.03.05.16.40.51;	author adunstan;	state Exp;
branches;
next	2.50;

2.50
date	2006.03.01.06.30.32;	author neilc;	state Exp;
branches;
next	2.49;

2.49
date	2005.11.04.23.14.00;	author petere;	state Exp;
branches
	2.49.2.1;
next	2.48;

2.48
date	2005.10.24.15.39.50;	author adunstan;	state Exp;
branches;
next	2.47;

2.47
date	2005.10.18.22.53.54;	author adunstan;	state Exp;
branches;
next	2.46;

2.46
date	2005.10.12.14.28.33;	author momjian;	state Exp;
branches;
next	2.45;

2.45
date	2005.08.24.19.16.49;	author tgl;	state Exp;
branches;
next	2.44;

2.44
date	2005.08.24.18.56.07;	author tgl;	state Exp;
branches;
next	2.43;

2.43
date	2005.08.12.21.42.53;	author momjian;	state Exp;
branches;
next	2.42;

2.42
date	2005.07.13.02.10.42;	author neilc;	state Exp;
branches;
next	2.41;

2.41
date	2005.06.05.03.16.29;	author momjian;	state Exp;
branches;
next	2.40;

2.40
date	2005.05.20.01.52.24;	author neilc;	state Exp;
branches;
next	2.39;

2.39
date	2005.04.09.03.52.43;	author momjian;	state Exp;
branches;
next	2.38;

2.38
date	2005.03.31.03.54.38;	author momjian;	state Exp;
branches;
next	2.37;

2.37
date	2005.01.17.17.29.49;	author momjian;	state Exp;
branches
	2.37.4.1;
next	2.36;

2.36
date	2005.01.17.03.04.17;	author momjian;	state Exp;
branches;
next	2.35;

2.35
date	2004.12.30.21.45.36;	author tgl;	state Exp;
branches;
next	2.34;

2.34
date	2004.12.13.18.05.08;	author petere;	state Exp;
branches;
next	2.33;

2.33
date	2004.12.11.20.03.37;	author petere;	state Exp;
branches;
next	2.32;

2.32
date	2004.11.21.21.17.01;	author tgl;	state Exp;
branches;
next	2.31;

2.31
date	2004.11.19.23.22.54;	author tgl;	state Exp;
branches;
next	2.30;

2.30
date	2004.11.06.14.32.10;	author petere;	state Exp;
branches;
next	2.29;

2.29
date	2004.10.15.16.51.48;	author momjian;	state Exp;
branches;
next	2.28;

2.28
date	2004.09.20.22.48.25;	author tgl;	state Exp;
branches;
next	2.27;

2.27
date	2004.08.18.03.37.56;	author momjian;	state Exp;
branches;
next	2.26;

2.26
date	2004.07.21.20.44.52;	author momjian;	state Exp;
branches;
next	2.25;

2.25
date	2004.07.21.20.34.43;	author momjian;	state Exp;
branches;
next	2.24;

2.24
date	2004.07.21.20.22.57;	author momjian;	state Exp;
branches;
next	2.23;

2.23
date	2004.05.16.23.22.06;	author neilc;	state Exp;
branches;
next	2.22;

2.22
date	2003.12.14.00.10.32;	author neilc;	state Exp;
branches;
next	2.21;

2.21
date	2003.11.29.19.51.37;	author pgsql;	state Exp;
branches;
next	2.20;

2.20
date	2003.08.31.17.32.19;	author petere;	state Exp;
branches
	2.20.2.1;
next	2.19;

2.19
date	2003.04.07.01.29.25;	author petere;	state Exp;
branches
	2.19.2.1;
next	2.18;

2.18
date	2002.09.21.18.32.53;	author petere;	state Exp;
branches;
next	2.17;

2.17
date	2002.09.18.20.09.32;	author petere;	state Exp;
branches;
next	2.16;

2.16
date	2002.03.06.19.05.57;	author momjian;	state Exp;
branches;
next	2.15;

2.15
date	2002.01.25.19.13.15;	author tgl;	state Exp;
branches;
next	2.14;

2.14
date	2002.01.08.16.13.41;	author petere;	state Exp;
branches;
next	2.13;

2.13
date	2002.01.08.05.39.26;	author momjian;	state Exp;
branches;
next	2.12;

2.12
date	2002.01.07.02.29.13;	author petere;	state Exp;
branches;
next	2.11;

2.11
date	2001.11.21.05.53.41;	author thomas;	state Exp;
branches;
next	2.10;

2.10
date	2001.09.10.21.58.47;	author petere;	state Exp;
branches;
next	2.9;

2.9
date	2001.06.22.21.37.14;	author momjian;	state Exp;
branches;
next	2.8;

2.8
date	2001.05.12.22.51.35;	author petere;	state Exp;
branches;
next	2.7;

2.7
date	2000.12.22.18.57.50;	author petere;	state Exp;
branches;
next	2.6;

2.6
date	2000.12.19.18.16.25;	author petere;	state Exp;
branches;
next	2.5;

2.5
date	2000.09.29.20.21.34;	author petere;	state Exp;
branches;
next	2.4;

2.4
date	2000.05.09.18.30.43;	author momjian;	state Exp;
branches;
next	2.3;

2.3
date	2000.03.31.06.17.21;	author thomas;	state Exp;
branches;
next	2.2;

2.2
date	2000.03.31.03.27.41;	author thomas;	state Exp;
branches;
next	2.1;

2.1
date	2000.03.30.22.13.30;	author thomas;	state Exp;
branches;
next	;

2.19.2.1
date	2003.09.07.04.36.42;	author momjian;	state Exp;
branches;
next	;

2.20.2.1
date	2010.05.13.16.44.35;	author adunstan;	state Exp;
branches;
next	;

2.37.4.1
date	2010.05.13.16.44.03;	author adunstan;	state Exp;
branches;
next	;

2.49.2.1
date	2006.05.30.12.32.37;	author momjian;	state Exp;
branches;
next	2.49.2.2;

2.49.2.2
date	2010.05.13.16.43.40;	author adunstan;	state Exp;
branches;
next	;

2.59.2.1
date	2007.01.30.22.29.40;	author momjian;	state Exp;
branches;
next	2.59.2.2;

2.59.2.2
date	2007.05.03.15.06.13;	author neilc;	state Exp;
branches;
next	2.59.2.3;

2.59.2.3
date	2010.05.13.16.43.14;	author adunstan;	state Exp;
branches;
next	;

2.67.2.1
date	2010.05.13.16.42.51;	author adunstan;	state Exp;
branches;
next	;

2.69.2.1
date	2010.03.11.21.53.53;	author alvherre;	state Exp;
branches;
next	2.69.2.2;

2.69.2.2
date	2010.05.13.16.40.36;	author adunstan;	state Exp;
branches;
next	;

2.86.2.1
date	2010.07.29.19.34.37;	author petere;	state Exp;
branches;
next	2.86.2.2;

2.86.2.2
date	2010.08.17.04.37.17;	author petere;	state Exp;
branches;
next	2.86.2.3;

2.86.2.3
date	2010.09.09.00.48.29;	author momjian;	state Exp;
branches;
next	;


desc
@@


2.89
log
@Doc fixes:

- remove excessive table cells
- moving function parameters into function tags rather than having
  them being considered separate
- add return type column on XML2 contrib module functions list and
  removing return types from function
- add table header to XML2 contrib parameter table

Thom Brown

Backpatch to 9.0.X.
@
text
@<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.88 2010/08/17 04:37:21 petere Exp $ -->

 <chapter id="plperl">
  <title>PL/Perl - Perl Procedural Language</title>

  <indexterm zone="plperl">
   <primary>PL/Perl</primary>
  </indexterm>

  <indexterm zone="plperl">
   <primary>Perl</primary>
  </indexterm>

  <para>
   PL/Perl is a loadable procedural language that enables you to write
   <productname>PostgreSQL</productname> functions in the
   <ulink url="http://www.perl.org">Perl programming language</ulink>.
  </para>

  <para>
   The main advantage to using PL/Perl is that this allows use,
   within stored functions, of the manyfold <quote>string
   munging</quote> operators and functions available for Perl.  Parsing
   complex strings might be easier using Perl than it is with the
   string functions and control structures provided in PL/pgSQL.
  </para>

  <para>
   To install PL/Perl in a particular database, use
   <literal>createlang plperl <replaceable>dbname</></literal>.
  </para>

  <tip>
   <para>
    If a language is installed into <literal>template1</>, all subsequently
    created databases will have the language installed automatically.
   </para>
  </tip>

  <note>
   <para>
    Users of source packages must specially enable the build of
    PL/Perl during the installation process.  (Refer to <xref
    linkend="install-short"> for more information.)  Users of
    binary packages might find PL/Perl in a separate subpackage.
   </para>
  </note>

 <sect1 id="plperl-funcs">
  <title>PL/Perl Functions and Arguments</title>

  <para>
   To create a function in the PL/Perl language, use the standard
   <xref linkend="sql-createfunction">
   syntax:

<programlisting>
CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS $$
    # PL/Perl function body
$$ LANGUAGE plperl;
</programlisting>

   The body of the function is ordinary Perl code. In fact, the PL/Perl
   glue code wraps it inside a Perl subroutine.  A PL/Perl function is
   called in a scalar context, so it can't return a list.  You can return
   non-scalar values (arrays, records, and sets) by returning a reference,
   as discussed below.
  </para>

  <para>
   PL/Perl also supports anonymous code blocks called with the
   <xref linkend="sql-do"> statement:

<programlisting>
DO $$
    # PL/Perl code
$$ LANGUAGE plperl;
</programlisting>

   An anonymous code block receives no arguments, and whatever value it
   might return is discarded.  Otherwise it behaves just like a function.
  </para>

  <note>
   <para>
    The use of named nested subroutines is dangerous in Perl, especially if
    they refer to lexical variables in the enclosing scope. Because a PL/Perl
    function is wrapped in a subroutine, any named subroutine you place inside
    one will be nested. In general, it is far safer to create anonymous
    subroutines which you call via a coderef. For more information, see the
    entries for <literal>Variable "%s" will not stay shared</literal> and
    <literal>Variable "%s" is not available</literal> in the
    <citerefentry><refentrytitle>perldiag</></citerefentry> man page, or
    search the Internet for <quote>perl nested named subroutine</>.
   </para>
  </note>

  <para>
   The syntax of the <command>CREATE FUNCTION</command> command requires
   the function body to be written as a string constant.  It is usually
   most convenient to use dollar quoting (see <xref
   linkend="sql-syntax-dollar-quoting">) for the string constant.
   If you choose to use escape string syntax <literal>E''</>,
   you must double the single quote marks (<literal>'</>) and backslashes
   (<literal>\</>) used in the body of the function
   (see <xref linkend="sql-syntax-strings">).
  </para>

  <para>
   Arguments and results are handled as in any other Perl subroutine:
   arguments are passed in <varname>@@_</varname>, and a result value
   is returned with <literal>return</> or as the last expression
   evaluated in the function.
  </para>

  <para>
   For example, a function returning the greater of two integer values
   could be defined as:

<programlisting>
CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
    if ($_[0] &gt; $_[1]) { return $_[0]; }
    return $_[1];
$$ LANGUAGE plperl;
</programlisting>
  </para>

  <para>
   If an SQL null value<indexterm><primary>null value</><secondary
   sortas="PL/Perl">in PL/Perl</></indexterm> is passed to a function,
   the argument value will appear as <quote>undefined</> in Perl.  The
   above function definition will not behave very nicely with null
   inputs (in fact, it will act as though they are zeroes).  We could
   add <literal>STRICT</> to the function definition to make
   <productname>PostgreSQL</productname> do something more reasonable:
   if a null value is passed, the function will not be called at all,
   but will just return a null result automatically.  Alternatively,
   we could check for undefined inputs in the function body.  For
   example, suppose that we wanted <function>perl_max</function> with
   one null and one nonnull argument to return the nonnull argument,
   rather than a null value:

<programlisting>
CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
    my ($x, $y) = @@_;
    if (not defined $x) {
        return undef if not defined $y;
        return $y;
    }
    return $x if not defined $y;
    return $x if $x &gt; $y;
    return $y;
$$ LANGUAGE plperl;
</programlisting>
   As shown above, to return an SQL null value from a PL/Perl
   function, return an undefined value.  This can be done whether the
   function is strict or not.
  </para>

  <para>
   Anything in a function argument that is not a reference is
   a string, which is in the standard <productname>PostgreSQL</productname>
   external text representation for the relevant data type. In the case of
   ordinary numeric or text types, Perl will just do the right thing and
   the programmer will normally not have to worry about it. However, in
   other cases the argument will need to be converted into a form that is
   more usable in Perl. For example, the <function>decode_bytea</function>
   function can be used to convert an argument of
   type <type>bytea</> into unescaped binary.
  </para>

  <para>
   Similarly, values passed back to <productname>PostgreSQL</productname>
   must be in the external text representation format. For example, the
   <function>encode_bytea</function> function can be used to
   escape binary data for a return value of type <type>bytea</>.
  </para>

  <para>
   Perl can return <productname>PostgreSQL</productname> arrays as
   references to Perl arrays.  Here is an example:

<programlisting>
CREATE OR REPLACE function returns_array()
RETURNS text[][] AS $$
    return [['a&quot;b','c,d'],['e\\f','g']];
$$ LANGUAGE plperl;

select returns_array();
</programlisting>
  </para>

  <para>
   Composite-type arguments are passed to the function as references
   to hashes.  The keys of the hash are the attribute names of the
   composite type.  Here is an example:

<programlisting>
CREATE TABLE employee (
    name text,
    basesalary integer,
    bonus integer
);

CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
    my ($emp) = @@_;
    return $emp-&gt;{basesalary} + $emp-&gt;{bonus};
$$ LANGUAGE plperl;

SELECT name, empcomp(employee.*) FROM employee;
</programlisting>
  </para>

  <para>
   A PL/Perl function can return a composite-type result using the same
   approach: return a reference to a hash that has the required attributes.
   For example:

<programlisting>
CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);

CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
    return {f2 =&gt; 'hello', f1 =&gt; 1, f3 =&gt; 'world'};
$$ LANGUAGE plperl;

SELECT * FROM perl_row();
</programlisting>

   Any columns in the declared result data type that are not present in the
   hash will be returned as null values.
  </para>

  <para>
    PL/Perl functions can also return sets of either scalar or
    composite types.  Usually you'll want to return rows one at a
    time, both to speed up startup time and to keep from queueing up
    the entire result set in memory.  You can do this with
    <function>return_next</function> as illustrated below.  Note that
    after the last <function>return_next</function>, you must put
    either <literal>return</literal> or (better) <literal>return
    undef</literal>.

<programlisting>
CREATE OR REPLACE FUNCTION perl_set_int(int)
RETURNS SETOF INTEGER AS $$
    foreach (0..$_[0]) {
        return_next($_);
    }
    return undef;
$$ LANGUAGE plperl;

SELECT * FROM perl_set_int(5);

CREATE OR REPLACE FUNCTION perl_set()
RETURNS SETOF testrowperl AS $$
    return_next({ f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' });
    return_next({ f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' });
    return_next({ f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' });
    return undef;
$$ LANGUAGE plperl;
</programlisting>

    For small result sets, you can return a reference to an array that
    contains either scalars, references to arrays, or references to
    hashes for simple types, array types, and composite types,
    respectively.  Here are some simple examples of returning the entire
    result set as an array reference:

<programlisting>
CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
    return [0..$_[0]];
$$ LANGUAGE plperl;

SELECT * FROM perl_set_int(5);

CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
    return [
        { f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' },
        { f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' },
        { f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' }
    ];
$$ LANGUAGE plperl;

SELECT * FROM perl_set();
</programlisting>
  </para>

  <para>
   If you wish to use the <literal>strict</> pragma with your code you 
   have a few options. For temporary global use you can <command>SET</> 
   <literal>plperl.use_strict</literal> to true.
   This will affect subsequent compilations of <application>PL/Perl</>
   functions, but not functions already compiled in the current session.
   For permanent global use you can set <literal>plperl.use_strict</literal>
   to true in the <filename>postgresql.conf</filename> file.
  </para>

  <para>
   For permanent use in specific functions you can simply put:
<programlisting>
use strict;
</programlisting>
   at the top of the function body.
  </para>

  <para>
  The <literal>feature</> pragma is also available to <function>use</> if your Perl is version 5.10.0 or higher.
  </para>

 </sect1>

 <sect1 id="plperl-data">
  <title>Data Values in PL/Perl</title>

  <para>
   The argument values supplied to a PL/Perl function's code are
   simply the input arguments converted to text form (just as if they
   had been displayed by a <command>SELECT</command> statement).
   Conversely, the <function>return</function> and <function>return_next</function>
   commands will accept any string that is acceptable input format
   for the function's declared return type.
  </para>
 </sect1>

 <sect1 id="plperl-builtins">
  <title>Built-in Functions</title>

 <sect2 id="plperl-database">
  <title>Database Access from PL/Perl</title>

  <para>
   Access to the database itself from your Perl function can be done
   via the following functions:
  </para>

   <variablelist>
    <varlistentry>
     <indexterm>
      <primary>spi_exec_query</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_query</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_fetchrow</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_prepare</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_exec_prepared</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_query_prepared</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_cursor_close</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_freeplan</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>spi_exec_query</>(<replaceable>query</replaceable> [, <replaceable>max-rows</replaceable>])</literal></term>
     <listitem>
      <para>
       <literal>spi_exec_query</literal> executes an SQL command and
returns the entire row set as a reference to an array of hash
references.  <emphasis>You should only use this command when you know
that the result set will be relatively small.</emphasis>  Here is an
example of a query (<command>SELECT</command> command) with the
optional maximum number of rows:

<programlisting>
$rv = spi_exec_query('SELECT * FROM my_table', 5);
</programlisting>
        This returns up to 5 rows from the table
        <literal>my_table</literal>.  If <literal>my_table</literal>
        has a column <literal>my_column</literal>, you can get that
        value from row <literal>$i</literal> of the result like this:
<programlisting>
$foo = $rv-&gt;{rows}[$i]-&gt;{my_column};
</programlisting>
       The total number of rows returned from a <command>SELECT</command>
       query can be accessed like this:
<programlisting>
$nrows = $rv-&gt;{processed}
</programlisting>
      </para>

      <para>
       Here is an example using a different command type:
<programlisting>
$query = "INSERT INTO my_table VALUES (1, 'test')";
$rv = spi_exec_query($query);
</programlisting>
       You can then access the command status (e.g.,
       <literal>SPI_OK_INSERT</literal>) like this:
<programlisting>
$res = $rv-&gt;{status};
</programlisting>
       To get the number of rows affected, do:
<programlisting>
$nrows = $rv-&gt;{processed};
</programlisting>
      </para>

      <para>
       Here is a complete example:
<programlisting>
CREATE TABLE test (
    i int,
    v varchar
);

INSERT INTO test (i, v) VALUES (1, 'first line');
INSERT INTO test (i, v) VALUES (2, 'second line');
INSERT INTO test (i, v) VALUES (3, 'third line');
INSERT INTO test (i, v) VALUES (4, 'immortal');

CREATE OR REPLACE FUNCTION test_munge() RETURNS SETOF test AS $$
    my $rv = spi_exec_query('select i, v from test;');
    my $status = $rv-&gt;{status};
    my $nrows = $rv-&gt;{processed};
    foreach my $rn (0 .. $nrows - 1) {
        my $row = $rv-&gt;{rows}[$rn];
        $row-&gt;{i} += 200 if defined($row-&gt;{i});
        $row-&gt;{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row-&gt;{v}));
        return_next($row);
    }
    return undef;
$$ LANGUAGE plperl;

SELECT * FROM test_munge();
</programlisting>
    </para>
    </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal><function>spi_query(<replaceable>command</replaceable>)</function></literal></term>
     <term><literal><function>spi_fetchrow(<replaceable>cursor</replaceable>)</function></literal></term>
     <term><literal><function>spi_cursor_close(<replaceable>cursor</replaceable>)</function></literal></term>

    <listitem>
    <para>
    <literal>spi_query</literal> and <literal>spi_fetchrow</literal>
    work together as a pair for row sets which might be large, or for cases
    where you wish to return rows as they arrive.
    <literal>spi_fetchrow</literal> works <emphasis>only</emphasis> with
    <literal>spi_query</literal>. The following example illustrates how
    you use them together:

<programlisting>
CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT);

CREATE OR REPLACE FUNCTION lotsa_md5 (INTEGER) RETURNS SETOF foo_type AS $$
    use Digest::MD5 qw(md5_hex);
    my $file = '/usr/share/dict/words';
    my $t = localtime;
    elog(NOTICE, "opening file $file at $t" );
    open my $fh, '&lt;', $file # ooh, it's a file access!
        or elog(ERROR, "cannot open $file for reading: $!");
    my @@words = &lt;$fh&gt;;
    close $fh;
    $t = localtime;
    elog(NOTICE, "closed file $file at $t");
    chomp(@@words);
    my $row;
    my $sth = spi_query("SELECT * FROM generate_series(1,$_[0]) AS b(a)");
    while (defined ($row = spi_fetchrow($sth))) {
        return_next({
            the_num =&gt; $row-&gt;{a},
            the_text =&gt; md5_hex($words[rand @@words])
        });
    }
    return;
$$ LANGUAGE plperlu;

SELECT * from lotsa_md5(500);
</programlisting>
    </para>

    <para>
     Normally, <function>spi_fetchrow</> should be repeated until it
     returns <literal>undef</literal>, indicating that there are no more
     rows to read.  The cursor returned by <literal>spi_query</literal>
     is automatically freed when
     <function>spi_fetchrow</> returns <literal>undef</literal>.
     If you do not wish to read all the rows, instead call
     <function>spi_cursor_close</> to free the cursor.
     Failure to do so will result in memory leaks.
    </para>

    </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal><function>spi_prepare(<replaceable>command</replaceable>, <replaceable>argument types</replaceable>)</function></literal></term>
     <term><literal><function>spi_query_prepared(<replaceable>plan</replaceable>, <replaceable>arguments</replaceable>)</function></literal></term>
     <term><literal><function>spi_exec_prepared(<replaceable>plan</replaceable> [, <replaceable>attributes</replaceable>], <replaceable>arguments</replaceable>)</function></literal></term>
     <term><literal><function>spi_freeplan(<replaceable>plan</replaceable>)</function></literal></term>

    <listitem>
    <para>
    <literal>spi_prepare</literal>, <literal>spi_query_prepared</literal>, <literal>spi_exec_prepared</literal>,
    and <literal>spi_freeplan</literal> implement the same functionality but for prepared queries.
    <literal>spi_prepare</literal> accepts a query string with numbered argument placeholders ($1, $2, etc)
    and a string list of argument types:
<programlisting>
$plan = spi_prepare('SELECT * FROM test WHERE id &gt; $1 AND name = $2',
                                                     'INTEGER', 'TEXT');
</programlisting>
    Once a query plan is prepared by a call to <literal>spi_prepare</literal>, the plan can be used instead
    of the string query, either in <literal>spi_exec_prepared</literal>, where the result is the same as returned
    by <literal>spi_exec_query</literal>, or in <literal>spi_query_prepared</literal> which returns a cursor
    exactly as <literal>spi_query</literal> does, which can be later passed to <literal>spi_fetchrow</literal>.
    The optional second parameter to <literal>spi_exec_prepared</literal> is a hash reference of attributes;
    the only attribute currently supported is <literal>limit</literal>, which sets the maximum number of rows returned by a query. 
    </para>

    <para>
    The advantage of prepared queries is that is it possible to use one prepared plan for more
    than one query execution. After the plan is not needed anymore, it can be freed with
    <literal>spi_freeplan</literal>:
<programlisting>
CREATE OR REPLACE FUNCTION init() RETURNS VOID AS $$
        $_SHARED{my_plan} = spi_prepare('SELECT (now() + $1)::date AS now',
                                        'INTERVAL');
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION add_time( INTERVAL ) RETURNS TEXT AS $$
        return spi_exec_prepared(
                $_SHARED{my_plan},
                $_[0]
        )->{rows}->[0]->{now};
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION done() RETURNS VOID AS $$
        spi_freeplan( $_SHARED{my_plan});
        undef $_SHARED{my_plan};
$$ LANGUAGE plperl;

SELECT init();
SELECT add_time('1 day'), add_time('2 days'), add_time('3 days');
SELECT done();

  add_time  |  add_time  |  add_time
------------+------------+------------
 2005-12-10 | 2005-12-11 | 2005-12-12
</programlisting>
    Note that the parameter subscript in <literal>spi_prepare</literal> is defined via
    $1, $2, $3, etc, so avoid declaring query strings in double quotes that might easily
    lead to hard-to-catch bugs.
    </para>

    <para>
    Another example illustrates usage of an optional parameter in <literal>spi_exec_prepared</literal>:
<programlisting>
CREATE TABLE hosts AS SELECT id, ('192.168.1.'||id)::inet AS address
                      FROM generate_series(1,3) AS id;

CREATE OR REPLACE FUNCTION init_hosts_query() RETURNS VOID AS $$
        $_SHARED{plan} = spi_prepare('SELECT * FROM hosts
                                      WHERE address &lt;&lt; $1', 'inet');
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION query_hosts(inet) RETURNS SETOF hosts AS $$
        return spi_exec_prepared(
                $_SHARED{plan},
                {limit =&gt; 2},
                $_[0]
        )->{rows};
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION release_hosts_query() RETURNS VOID AS $$
        spi_freeplan($_SHARED{plan});
        undef $_SHARED{plan};
$$ LANGUAGE plperl;

SELECT init_hosts_query();
SELECT query_hosts('192.168.1.0/30');
SELECT release_hosts_query();

    query_hosts    
-----------------
 (1,192.168.1.1)
 (2,192.168.1.2)
(2 rows)
</programlisting>
    </para>
    </listitem>
    </varlistentry>
   </variablelist>
 </sect2>

 <sect2 id="plperl-utility-functions">
  <title>Utility functions in PL/Perl</title>

   <variablelist>
    <varlistentry>
     <indexterm>
      <primary>elog</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>elog(<replaceable>level</replaceable>, <replaceable>msg</replaceable>)</function></literal></term>
     <listitem>
      <para>
       Emit a log or error message. Possible levels are
       <literal>DEBUG</>, <literal>LOG</>, <literal>INFO</>,
       <literal>NOTICE</>, <literal>WARNING</>, and <literal>ERROR</>.
       <literal>ERROR</>
        raises an error condition; if this is not trapped by the surrounding
        Perl code, the error propagates out to the calling query, causing
        the current transaction or subtransaction to be aborted.  This
        is effectively the same as the Perl <literal>die</> command.
        The other levels only generate messages of different
        priority levels.
        Whether messages of a particular priority are reported to the client,
        written to the server log, or both is controlled by the
        <xref linkend="guc-log-min-messages"> and
        <xref linkend="guc-client-min-messages"> configuration
        variables. See <xref linkend="runtime-config"> for more
        information.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <indexterm>
      <primary>quote_literal</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>quote_literal(<replaceable>string</replaceable>)</function></literal></term>
     <listitem>
      <para>
        Return the given string suitably quoted to be used as a string literal in an SQL
        statement string. Embedded single-quotes and backslashes are properly doubled.
        Note that <function>quote_literal</> returns undef on undef input; if the argument
        might be undef, <function>quote_nullable</> is often more suitable.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <indexterm>
      <primary>quote_nullable</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>quote_nullable(<replaceable>string</replaceable>)</function></literal></term>
     <listitem>
      <para>
        Return the given string suitably quoted to be used as a string literal in an SQL
        statement string; or, if the argument is undef, return the unquoted string "NULL".
        Embedded single-quotes and backslashes are properly doubled.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <indexterm>
      <primary>quote_ident</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>quote_ident(<replaceable>string</replaceable>)</function></literal></term>
     <listitem>
      <para>
        Return the given string suitably quoted to be used as an identifier in
        an SQL statement string. Quotes are added only if necessary (i.e., if
        the string contains non-identifier characters or would be case-folded).
        Embedded quotes are properly doubled.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <indexterm>
      <primary>decode_bytea</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>decode_bytea(<replaceable>string</replaceable>)</function></literal></term>
     <listitem>
      <para>
        Return the unescaped binary data represented by the contents of the given string,
        which should be <type>bytea</type> encoded.
        </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <indexterm>
      <primary>encode_bytea</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>encode_bytea(<replaceable>string</replaceable>)</function></literal></term>
     <listitem>
      <para>
        Return the <type>bytea</type> encoded form of the binary data contents of the given string.
        </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <indexterm>
      <primary>encode_array_literal</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>encode_array_literal(<replaceable>array</replaceable>)</function></literal></term>
     <term><literal><function>encode_array_literal(<replaceable>array</replaceable>, <replaceable>delimiter</replaceable>)</function></literal></term>
     <listitem>
      <para>
        Returns the contents of the referenced array as a string in array literal format
        (see <xref linkend="arrays-input">).
        Returns the argument value unaltered if it's not a reference to an array.
        The delimiter used between elements of the array literal defaults to "<literal>, </literal>"
        if a delimiter is not specified or is undef.
        </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <indexterm>
      <primary>encode_array_constructor</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>encode_array_constructor(<replaceable>array</replaceable>)</function></literal></term>
     <listitem>
      <para>
        Returns the contents of the referenced array as a string in array constructor format
        (see <xref linkend="sql-syntax-array-constructors">).
        Individual values are quoted using <function>quote_nullable</function>.
        Returns the argument value, quoted using <function>quote_nullable</function>,
        if it's not a reference to an array.
        </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <indexterm>
      <primary>looks_like_number</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>

     <term><literal><function>looks_like_number(<replaceable>string</replaceable>)</function></literal></term>
     <listitem>
      <para>
        Returns a true value if the content of the given string looks like a
        number, according to Perl, returns false otherwise.
        Returns undef if the argument is undef.  Leading and trailing space is
        ignored. <literal>Inf</> and <literal>Infinity</> are regarded as numbers.
        </para>
     </listitem>
    </varlistentry>

   </variablelist>
 </sect2>
 </sect1>

 <sect1 id="plperl-global">
  <title>Global Values in PL/Perl</title>

  <para>
    You can use the global hash <varname>%_SHARED</varname> to store
    data, including code references, between function calls for the
    lifetime of the current session.
  </para>

  <para>
    Here is a simple example for shared data:
<programlisting>
CREATE OR REPLACE FUNCTION set_var(name text, val text) RETURNS text AS $$
    if ($_SHARED{$_[0]} = $_[1]) {
        return 'ok';
    } else {
        return "cannot set shared variable $_[0] to $_[1]";
    }
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION get_var(name text) RETURNS text AS $$
    return $_SHARED{$_[0]};
$$ LANGUAGE plperl;

SELECT set_var('sample', 'Hello, PL/Perl!  How''s tricks?');
SELECT get_var('sample');
</programlisting>
  </para>

  <para>
   Here is a slightly more complicated example using a code reference:

<programlisting>
CREATE OR REPLACE FUNCTION myfuncs() RETURNS void AS $$
    $_SHARED{myquote} = sub {
        my $arg = shift;
        $arg =~ s/(['\\])/\\$1/g;
        return "'$arg'";
    };
$$ LANGUAGE plperl;

SELECT myfuncs(); /* initializes the function */

/* Set up a function that uses the quote function */

CREATE OR REPLACE FUNCTION use_quote(TEXT) RETURNS text AS $$
    my $text_to_quote = shift;
    my $qfunc = $_SHARED{myquote};
    return &amp;$qfunc($text_to_quote);
$$ LANGUAGE plperl;
</programlisting>

   (You could have replaced the above with the one-liner
   <literal>return $_SHARED{myquote}-&gt;($_[0]);</literal>
   at the expense of readability.)
  </para>

  <para>
    The <varname>%_SHARED</varname> variable and other global state within
    the language are public data, available to all PL/Perl functions within a
    session. Use with care, especially in situations that involve use of 
    multiple roles or <literal>SECURITY DEFINER</> functions.
  </para>
 </sect1>

 <sect1 id="plperl-trusted">
  <title>Trusted and Untrusted PL/Perl</title>

  <indexterm zone="plperl-trusted">
   <primary>trusted</primary>
   <secondary>PL/Perl</secondary>
  </indexterm>

  <para>
   Normally, PL/Perl is installed as a <quote>trusted</> programming
   language named <literal>plperl</>.  In this setup, certain Perl
   operations are disabled to preserve security.  In general, the
   operations that are restricted are those that interact with the
   environment. This includes file handle operations,
   <literal>require</literal>, and <literal>use</literal> (for
   external modules).  There is no way to access internals of the
   database server process or to gain OS-level access with the
   permissions of the server process,
   as a C function can do.  Thus, any unprivileged database user can
   be permitted to use this language.
  </para>

  <para>
   Here is an example of a function that will not work because file
   system operations are not allowed for security reasons:
<programlisting>
CREATE FUNCTION badfunc() RETURNS integer AS $$
    my $tmpfile = "/tmp/badfile";
    open my $fh, '&gt;', $tmpfile
        or elog(ERROR, qq{could not open the file "$tmpfile": $!});
    print $fh "Testing writing to a file\n";
    close $fh or elog(ERROR, qq{could not close the file "$tmpfile": $!});
    return 1;
$$ LANGUAGE plperl;
</programlisting>
    The creation of this function will fail as its use of a forbidden
    operation will be caught by the validator.
  </para>

  <para>
   Sometimes it is desirable to write Perl functions that are not
   restricted.  For example, one might want a Perl function that sends
   mail.  To handle these cases, PL/Perl can also be installed as an
   <quote>untrusted</> language (usually called
   <application>PL/PerlU</application><indexterm><primary>PL/PerlU</></indexterm>).
   In this case the full Perl language is available.  If the
   <command>createlang</command> program is used to install the
   language, the language name <literal>plperlu</literal> will select
   the untrusted PL/Perl variant.
  </para>

  <para>
   The writer of a <application>PL/PerlU</> function must take care that the function
   cannot be used to do anything unwanted, since it will be able to do
   anything that could be done by a user logged in as the database
   administrator.  Note that the database system allows only database
   superusers to create functions in untrusted languages.
  </para>

  <para>
   If the above function was created by a superuser using the language
   <literal>plperlu</>, execution would succeed.
  </para>

  <para>
   In the same way, anonymous code blocks written in Perl can use
   restricted operations if the language is specified as
   <literal>plperlu</> rather than <literal>plperl</>, but the caller
   must be a superuser.
  </para>

  <note>
    <para>
      For security reasons, to stop a leak of privileged operations from
      <application>PL/PerlU</> to <application>PL/Perl</>, these two languages
      have to run in separate instances of the Perl interpreter. If your
      Perl installation has been appropriately compiled, this is not a problem.
      However, not all installations are compiled with the requisite flags.
      If <productname>PostgreSQL</> detects that this is the case then it will
      not start a second interpreter, but instead create an error. In
      consequence, in such an installation, you cannot use both
      <application>PL/PerlU</> and <application>PL/Perl</> in the same backend
      process. The remedy for this is to obtain a Perl installation configured
      with the appropriate flags, namely either <literal>usemultiplicity</>
      or <literal>useithreads</>. <literal>usemultiplicity</> is preferred
      unless you actually need to use threads. For more details, see the
      <citerefentry><refentrytitle>perlembed</></citerefentry> man page.
    </para>
  </note>

 </sect1>

 <sect1 id="plperl-triggers">
  <title>PL/Perl Triggers</title>

  <para>
   PL/Perl can be used to write trigger functions.  In a trigger function,
   the hash reference <varname>$_TD</varname> contains information about the
   current trigger event. <varname>$_TD</> is a global variable,
   which gets a separate local value for each invocation of the trigger.
   The fields of the <varname>$_TD</varname> hash reference are:

   <variablelist>
    <varlistentry>
     <term><literal>$_TD-&gt;{new}{foo}</literal></term>
     <listitem>
      <para>
       <literal>NEW</literal> value of column <literal>foo</literal>
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{old}{foo}</literal></term>
     <listitem>
      <para>
       <literal>OLD</literal> value of column <literal>foo</literal>
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{name}</literal></term>
     <listitem>
      <para>
       Name of the trigger being called
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{event}</literal></term>
     <listitem>
      <para>
       Trigger event: <literal>INSERT</>, <literal>UPDATE</>,
       <literal>DELETE</>, <literal>TRUNCATE</>, or <literal>UNKNOWN</>
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{when}</literal></term>
     <listitem>
      <para>
       When the trigger was called: <literal>BEFORE</literal>, <literal>AFTER</literal>, or <literal>UNKNOWN</literal>
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{level}</literal></term>
     <listitem>
      <para>
       The trigger level: <literal>ROW</literal>, <literal>STATEMENT</literal>, or <literal>UNKNOWN</literal>
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{relid}</literal></term>
     <listitem>
      <para>
       OID of the table on which the trigger fired
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{table_name}</literal></term>
     <listitem>
      <para>
       Name of the table on which the trigger fired
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{relname}</literal></term>
     <listitem>
      <para>
       Name of the table on which the trigger fired. This has been deprecated,
       and could be removed in a future release.
       Please use $_TD-&gt;{table_name} instead.
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{table_schema}</literal></term>
     <listitem>
      <para>
       Name of the schema in which the table on which the trigger fired, is
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>$_TD-&gt;{argc}</literal></term>
     <listitem>
      <para>
       Number of arguments of the trigger function
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>@@{$_TD-&gt;{args}}</literal></term>
     <listitem>
      <para>
       Arguments of the trigger function.  Does not exist if <literal>$_TD-&gt;{argc}</literal> is 0.
      </para>
     </listitem>
    </varlistentry>

   </variablelist>
  </para>

  <para>
   Row-level triggers can return one of the following:

   <variablelist>
    <varlistentry>
     <term><literal>return;</literal></term>
     <listitem>
      <para>
       Execute the operation
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>"SKIP"</literal></term>
     <listitem>
      <para>
       Don't execute the operation
      </para>
     </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal>"MODIFY"</literal></term>
     <listitem>
      <para>
       Indicates that the <literal>NEW</literal> row was modified by
       the trigger function
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>

  <para>
   Here is an example of a trigger function, illustrating some of the
   above:
<programlisting>
CREATE TABLE test (
    i int,
    v varchar
);

CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS $$
    if (($_TD-&gt;{new}{i} &gt;= 100) || ($_TD-&gt;{new}{i} &lt;= 0)) {
        return "SKIP";    # skip INSERT/UPDATE command
    } elsif ($_TD-&gt;{new}{v} ne "immortal") {
        $_TD-&gt;{new}{v} .= "(modified by trigger)";
        return "MODIFY";  # modify row and execute INSERT/UPDATE command
    } else {
        return;           # execute INSERT/UPDATE command
    }
$$ LANGUAGE plperl;

CREATE TRIGGER test_valid_id_trig
    BEFORE INSERT OR UPDATE ON test
    FOR EACH ROW EXECUTE PROCEDURE valid_id();
</programlisting>
  </para>
 </sect1>

 <sect1 id="plperl-under-the-hood">
  <title>PL/Perl Under the Hood</title>

 <sect2 id="plperl-config">
  <title>Configuration</title>

  <para>
  This section lists configuration parameters that affect <application>PL/Perl</>.
  To set any of these parameters before <application>PL/Perl</> has been loaded,
  it is necessary to have added <quote><literal>plperl</></> to the
  <xref linkend="guc-custom-variable-classes"> list in
  <filename>postgresql.conf</filename>.
  </para>

  <variablelist>

     <varlistentry id="guc-plperl-on-init" xreflabel="plperl.on_init">
      <term><varname>plperl.on_init</varname> (<type>string</type>)</term>
      <indexterm>
       <primary><varname>plperl.on_init</> configuration parameter</primary>
      </indexterm>
      <listitem>
       <para>
       Specifies Perl code to be executed when a Perl interpreter is first initialized
       and before it is specialized for use by <literal>plperl</> or <literal>plperlu</>.
       The SPI functions are not available when this code is executed.
       If the code fails with an error it will abort the initialization of the interpreter
       and propagate out to the calling query, causing the current transaction
       or subtransaction to be aborted.
       </para>
       <para>
       The Perl code is limited to a single string. Longer code can be placed
       into a module and loaded by the <literal>on_init</> string.
       Examples:
<programlisting>
plperl.on_init = 'require "plperlinit.pl"'
plperl.on_init = 'use lib "/my/app"; use MyApp::PgInit;'
</programlisting>
       </para>
       <para>
       Any modules loaded by <literal>plperl.on_init</>, either directly or
       indirectly, will be available for use by <literal>plperl</>.  This may
       create a security risk. To see what modules have been loaded you can use:
<programlisting>
DO 'elog(WARNING, join ", ", sort keys %INC)' language plperl;
</programlisting>
       </para>
       <para>
       Initialization will happen in the postmaster if the plperl library is included
       in <literal>shared_preload_libraries</> (see <xref linkend="guc-shared-preload-libraries">),
       in which case extra consideration should be given to the risk of destabilizing the postmaster.
       </para>
       <para>
       This parameter can only be set in the postgresql.conf file or on the server command line.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry id="guc-plperl-on-plperl-init" xreflabel="plperl.on_plperl_init">
      <term><varname>plperl.on_plperl_init</varname> (<type>string</type>)</term>
      <term><varname>plperl.on_plperlu_init</varname> (<type>string</type>)</term>
      <indexterm>
       <primary><varname>plperl.on_plperl_init</> configuration parameter</primary>
      </indexterm>
      <indexterm>
       <primary><varname>plperl.on_plperlu_init</> configuration parameter</primary>
      </indexterm>
      <listitem>
       <para>
       These parameters specify Perl code to be executed when the
       <literal>plperl</>, or <literal>plperlu</> language is first used in a
       session.  Changes to these parameters after the corresponding language
       has been used will have no effect.
       The SPI functions are not available when this code is executed.
       Only superusers can change these settings.
       The Perl code in <literal>plperl.on_plperl_init</> can only perform trusted operations.
       </para>
       <para>
       The effect of setting these parameters is very similar to executing a
       <literal>DO</> command with the Perl code before any other use of the
       language.  The parameters are useful when you want to execute the Perl
       code automatically on every connection, or when a connection is not
       interactive. The parameters can be used by non-superusers by having a
       superuser execute an <literal>ALTER USER ... SET ...</> command.
       For example:
<programlisting>
ALTER USER joe SET plperl.on_plperl_init = '$_SHARED{debug} = 1';
</programlisting>
       </para>
       <para>
       If the code fails with an error it will abort the initialization and
       propagate out to the calling query, causing the current transaction or
       subtransaction to be aborted. Any changes within Perl won't be undone.
       If the language is used again the initialization will be repeated.
       </para>
       <para>
       The difference between these two settings and the 
       <literal>plperl.on_init</> setting is that these can be used for
       settings specific to the trusted or untrusted language variant, such
       as setting values in the <varname>%_SHARED</> variable. By contrast,
       <literal>plperl.on_init</> is more useful for doing things like
       setting the library search path for <productname>Perl</> or 
       loading Perl modules that don't interact directly with 
       <productname>PostgreSQL</>.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry id="guc-plperl-use-strict" xreflabel="plperl.use_strict">
      <term><varname>plperl.use_strict</varname> (<type>boolean</type>)</term>
      <indexterm>
       <primary><varname>plperl.use_strict</> configuration parameter</primary>
      </indexterm>
      <listitem>
       <para>
       When set true subsequent compilations of PL/Perl functions have the <literal>strict</> pragma enabled.
       This parameter does not affect functions already compiled in the current session.
       </para>
      </listitem>
     </varlistentry>

  </variablelist>
</sect2>

 <sect2 id="plperl-missing">
  <title>Limitations and Missing Features</title>

  <para>
   The following features are currently missing from PL/Perl, but they
   would make welcome contributions.

   <itemizedlist>
    <listitem>
     <para>
      PL/Perl functions cannot call each other directly.
     </para>
    </listitem>

    <listitem>
     <para>
      SPI is not yet fully implemented.
     </para>
    </listitem>

    <listitem>
     <para>
      If you are fetching very large data sets using
      <literal>spi_exec_query</literal>, you should be aware that
      these will all go into memory.  You can avoid this by using
      <literal>spi_query</literal>/<literal>spi_fetchrow</literal> as
      illustrated earlier.
     </para>
     <para>
        A similar problem occurs if a set-returning function passes a
        large set of rows back to PostgreSQL via <literal>return</literal>. You
        can avoid this problem too by instead using
        <literal>return_next</literal> for each row returned, as shown
        previously.
     </para>
    </listitem>

     <listitem>
      <para>
        When a session ends normally, not due to a fatal error, any
        <literal>END</> blocks that have been defined are executed.
        Currently no other actions are performed. Specifically, 
        file handles are not automatically flushed and objects are 
        not automatically destroyed.
      </para>
     </listitem>
   </itemizedlist>
  </para>
 </sect2>

 </sect1>

</chapter>
@


2.88
log
@Spell and markup checking
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.87 2010/07/29 19:34:40 petere Exp $ -->
d448 3
a450 3
     <term><literal><function>spi_query</>(<replaceable>command</replaceable>)</literal></term>
     <term><literal><function>spi_fetchrow</>(<replaceable>cursor</replaceable>)</literal></term>
     <term><literal><function>spi_cursor_close</>(<replaceable>cursor</replaceable>)</literal></term>
d506 4
a509 4
     <term><literal><function>spi_prepare</>(<replaceable>command</replaceable>, <replaceable>argument types</replaceable>)</literal></term>
     <term><literal><function>spi_query_prepared</>(<replaceable>plan</replaceable>, <replaceable>arguments</replaceable>)</literal></term>
     <term><literal><function>spi_exec_prepared</>(<replaceable>plan</replaceable> [, <replaceable>attributes</replaceable>], <replaceable>arguments</replaceable>)</literal></term>
     <term><literal><function>spi_freeplan</>(<replaceable>plan</replaceable>)</literal></term>
d614 1
a614 1
     <term><literal><function>elog</>(<replaceable>level</replaceable>, <replaceable>msg</replaceable>)</literal></term>
d643 1
a643 1
     <term><literal><function>quote_literal</>(<replaceable>string</replaceable>)</literal></term>
d660 1
a660 1
     <term><literal><function>quote_nullable</>(<replaceable>string</replaceable>)</literal></term>
d676 1
a676 1
     <term><literal><function>quote_ident</>(<replaceable>string</replaceable>)</literal></term>
d693 1
a693 1
     <term><literal><function>decode_bytea</>(<replaceable>string</replaceable>)</literal></term>
d708 1
a708 1
     <term><literal><function>encode_bytea</>(<replaceable>string</replaceable>)</literal></term>
d722 2
a723 2
     <term><literal><function>encode_array_literal</>(<replaceable>array</replaceable>)</literal></term>
     <term><literal><function>encode_array_literal</>(<replaceable>array</replaceable>, <replaceable>delimiter</replaceable>)</literal></term>
d741 1
a741 1
     <term><literal><function>encode_array_constructor</>(<replaceable>array</replaceable>)</literal></term>
d759 1
a759 1
     <term><literal><function>looks_like_number</>(<replaceable>string</replaceable>)</literal></term>
@


2.87
log
@Fix indentation of verbatim block elements

Block elements with verbatim formatting (literallayout, programlisting,
screen, synopsis) should be aligned at column 0 independent of the surrounding
SGML, because whitespace is significant, and indenting them creates erratic
whitespace in the output.  The CSS stylesheets already take care of indenting
the output.

Assorted markup improvements to go along with it.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.86 2010/07/08 21:35:33 petere Exp $ -->
d697 1
a697 1
        which should be bytea encoded.
d711 1
a711 1
        Return the bytea encoded form of the binary data contents of the given string.
@


2.86
log
@Some small changes for plperl.sgml:
   - wrapped long code-lines, for pdf
   - typo

Erik Rijkers
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.85 2010/06/14 18:47:05 momjian Exp $ -->
d533 1
a533 4
    </para>

    <para>
    <programlisting>
d558 1
a558 4
    </programlisting>
    </para>

    <para>
d566 1
a566 4
    </para>

    <para>
    <programlisting>
d571 1
a571 1
        $_SHARED{plan} = spi_prepare('SELECT * FROM hosts 
d597 1
a597 1
    </programlisting>
@


2.86.2.1
log
@Fix indentation of verbatim block elements

Block elements with verbatim formatting (literallayout, programlisting,
screen, synopsis) should be aligned at column 0 independent of the surrounding
SGML, because whitespace is significant, and indenting them creates erratic
whitespace in the output.  The CSS stylesheets already take care of indenting
the output.

Assorted markup improvements to go along with it.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.86 2010/07/08 21:35:33 petere Exp $ -->
d533 4
a536 1
<programlisting>
d561 4
a564 1
</programlisting>
d572 4
a575 1
<programlisting>
d580 1
a580 1
        $_SHARED{plan} = spi_prepare('SELECT * FROM hosts
d606 1
a606 1
</programlisting>
@


2.86.2.2
log
@Spell and markup checking
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.86.2.1 2010/07/29 19:34:37 petere Exp $ -->
d697 1
a697 1
        which should be <type>bytea</type> encoded.
d711 1
a711 1
        Return the <type>bytea</type> encoded form of the binary data contents of the given string.
@


2.86.2.3
log
@Doc fixes:

- remove excessive table cells
- moving function parameters into function tags rather than having
  them being considered separate
- add return type column on XML2 contrib module functions list and
  removing return types from function
- add table header to XML2 contrib parameter table

Thom Brown

Backpatch to 9.0.X.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.86.2.2 2010/08/17 04:37:17 petere Exp $ -->
d448 3
a450 3
     <term><literal><function>spi_query(<replaceable>command</replaceable>)</function></literal></term>
     <term><literal><function>spi_fetchrow(<replaceable>cursor</replaceable>)</function></literal></term>
     <term><literal><function>spi_cursor_close(<replaceable>cursor</replaceable>)</function></literal></term>
d506 4
a509 4
     <term><literal><function>spi_prepare(<replaceable>command</replaceable>, <replaceable>argument types</replaceable>)</function></literal></term>
     <term><literal><function>spi_query_prepared(<replaceable>plan</replaceable>, <replaceable>arguments</replaceable>)</function></literal></term>
     <term><literal><function>spi_exec_prepared(<replaceable>plan</replaceable> [, <replaceable>attributes</replaceable>], <replaceable>arguments</replaceable>)</function></literal></term>
     <term><literal><function>spi_freeplan(<replaceable>plan</replaceable>)</function></literal></term>
d614 1
a614 1
     <term><literal><function>elog(<replaceable>level</replaceable>, <replaceable>msg</replaceable>)</function></literal></term>
d643 1
a643 1
     <term><literal><function>quote_literal(<replaceable>string</replaceable>)</function></literal></term>
d660 1
a660 1
     <term><literal><function>quote_nullable(<replaceable>string</replaceable>)</function></literal></term>
d676 1
a676 1
     <term><literal><function>quote_ident(<replaceable>string</replaceable>)</function></literal></term>
d693 1
a693 1
     <term><literal><function>decode_bytea(<replaceable>string</replaceable>)</function></literal></term>
d708 1
a708 1
     <term><literal><function>encode_bytea(<replaceable>string</replaceable>)</function></literal></term>
d722 2
a723 2
     <term><literal><function>encode_array_literal(<replaceable>array</replaceable>)</function></literal></term>
     <term><literal><function>encode_array_literal(<replaceable>array</replaceable>, <replaceable>delimiter</replaceable>)</function></literal></term>
d741 1
a741 1
     <term><literal><function>encode_array_constructor(<replaceable>array</replaceable>)</function></literal></term>
d759 1
a759 1
     <term><literal><function>looks_like_number(<replaceable>string</replaceable>)</function></literal></term>
@


2.85
log
@Fix doc plperl doc with is -> are change.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.84 2010/05/13 16:39:43 adunstan Exp $ -->
d176 1
a176 1
   to escape binary data for a return value of type <type>bytea</>.
d518 2
a519 1
$plan = spi_prepare('SELECT * FROM test WHERE id &gt; $1 AND name = $2', 'INTEGER', 'TEXT');
d538 2
a539 1
        $_SHARED{my_plan} = spi_prepare( 'SELECT (now() + $1)::date AS now', 'INTERVAL');
d576 2
a577 1
CREATE TABLE hosts AS SELECT id, ('192.168.1.'||id)::inet AS address FROM generate_series(1,3) AS id;
d580 2
a581 1
        $_SHARED{plan} = spi_prepare('SELECT * FROM hosts WHERE address &lt;&lt; $1', 'inet');
@


2.84
log
@Abandon the use of Perl's Safe.pm to enforce restrictions in plperl, as it is
fundamentally insecure. Instead apply an opmask to the whole interpreter that
imposes restrictions on unsafe operations. These restrictions are much harder
to subvert than is Safe.pm, since there is no container to be broken out of.
Backported to release 7.4.

In releases 7.4, 8.0 and 8.1 this also includes the necessary backporting of
the two interpreters model for plperl and plperlu adopted in release 8.2.

In versions 8.0 and up, the use of Perl's POSIX module to undo its locale
mangling on Windows has become insecure with these changes, so it is
replaced by our own routine, which is also faster.

Nice side effects of the changes include that it is now possible to use perl's
"strict" pragma in a natural way in plperl, and that perl's $a and
$b variables now work as expected in sort routines, and that function
compilation is significantly faster.

Tim Bunce and Andrew Dunstan, with reviews from Alex Hunsaker and
Alexey Klyukin.

Security: CVE-2010-1169
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.83 2010/04/03 07:22:55 petere Exp $ -->
d838 1
a838 1
    the language is public data, available to all PL/Perl functions within a
@


2.83
log
@Remove unnecessary xref endterm attributes and title ids

The endterm attribute is mainly useful when the toolchain does not support
automatic link target text generation for a particular situation.  In  the
past, this was required by the man page tools for all reference page links,
but that is no longer the case, and it now actually gets in the way of
proper automatic link text generation.  The only remaining use cases are
currently xrefs to refsects.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.82 2010/02/25 10:02:30 mha Exp $ -->
d1157 1
a1157 1
plperl.on_init = '$ENV{NYTPROF}="start=no"; require Devel::NYTProf::PgPLPerl'
d1162 8
@


2.82
log
@Fix typos, per Richard Huxton
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.81 2010/02/25 03:08:07 tgl Exp $ -->
d54 1
a54 1
   <xref linkend="sql-createfunction" endterm="sql-createfunction-title">
d72 1
a72 1
   <xref linkend="sql-do" endterm="sql-do-title"> statement:
@


2.81
log
@Improve warning about creating nested named subroutines in plperl.
Per discussion.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.80 2010/02/12 19:35:25 adunstan Exp $ -->
d1157 2
a1158 2
plplerl.on_init = '$ENV{NYTPROF}="start=no"; require Devel::NYTProf::PgPLPerl'
plplerl.on_init = 'use lib "/my/app"; use MyApp::PgInit;'
d1200 1
a1200 1
ALTER USER joe SET plplerl.on_plperl_init = '$_SHARED{debug} = 1';
@


2.80
log
@Add plperl.on_plperl_init and plperl.on_plperlu_init settings for language-specific startup. Rename recently added plperl.on_perl_init to plperl.on_init. Also, code cleanup for utf8 hack. Patch from Tim Bunce, reviewed by Alex Hunsaker.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.79 2010/02/05 18:11:46 momjian Exp $ -->
d88 7
a94 6
    function is wrapped in a subroutine, any named subroutine you create will
    be nested. In general, it is far safer to create anonymous subroutines
    which you call via a coderef. See <literal>Variable "%s" will not stay shared</literal>
    and <literal>Variable "%s" is not available</literal> in the
    <citerefentry><refentrytitle>perldiag</></citerefentry> man page for more
    details.
@


2.79
log
@Improve PL/Perl documentation of database access functions.

Alexey Klyukin
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.78 2010/02/01 15:48:35 momjian Exp $ -->
d834 7
d1137 2
a1138 2
     <varlistentry id="guc-plperl-on-perl-init" xreflabel="plperl.on_perl_init">
      <term><varname>plperl.on_perl_init</varname> (<type>string</type>)</term>
d1140 1
a1140 1
       <primary><varname>plperl.on_perl_init</> configuration parameter</primary>
d1144 2
a1145 1
       Specifies perl code to be executed when a perl interpreter is first initialized.
d1152 2
a1153 2
       The perl code is limited to a single string. Longer code can be placed
       into a module and loaded by the <literal>on_perl_init</> string.
d1156 2
a1157 2
plplerl.on_perl_init = '$ENV{NYTPROF}="start=no"; require Devel::NYTProf::PgPLPerl'
plplerl.on_perl_init = 'use lib "/my/app"; use MyApp::PgInit;'
d1171 50
@


2.78
log
@Remove tabs in sgml.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.77 2010/01/30 01:46:57 adunstan Exp $ -->
d341 28
a370 8
     <term><literal><function>spi_query</>(<replaceable>command</replaceable>)</literal></term>
     <term><literal><function>spi_fetchrow</>(<replaceable>cursor</replaceable>)</literal></term>
     <term><literal><function>spi_prepare</>(<replaceable>command</replaceable>, <replaceable>argument types</replaceable>)</literal></term>
     <term><literal><function>spi_exec_prepared</>(<replaceable>plan</replaceable>, <replaceable>arguments</replaceable>)</literal></term>
     <term><literal><function>spi_query_prepared</>(<replaceable>plan</replaceable> [, <replaceable>attributes</replaceable>], <replaceable>arguments</replaceable>)</literal></term>
     <term><literal><function>spi_cursor_close</>(<replaceable>cursor</replaceable>)</literal></term>
     <term><literal><function>spi_freeplan</>(<replaceable>plan</replaceable>)</literal></term>

d443 2
d446 6
d491 21
d513 7
a519 2
    and <literal>spi_freeplan</literal> implement the same functionality but for prepared queries. Once
    a query plan is prepared by a call to <literal>spi_prepare</literal>, the plan can be used instead
d523 2
d535 1
a535 1
CREATE OR REPLACE FUNCTION init() RETURNS INTEGER AS $$
d542 1
a542 1
                $_[0],
d546 1
a546 1
CREATE OR REPLACE FUNCTION done() RETURNS INTEGER AS $$
d568 34
a601 7
     Normally, <function>spi_fetchrow</> should be repeated until it
     returns <literal>undef</literal>, indicating that there are no more
     rows to read.  The cursor is automatically freed when
     <function>spi_fetchrow</> returns <literal>undef</literal>.
     If you do not wish to read all the rows, instead call
     <function>spi_cursor_close</> to free the cursor.
     Failure to do so will result in memory leaks.
d603 1
a603 1
     </listitem>
@


2.77
log
@Add plperl.on_perl_init setting to provide for initializing the perl library on load. Also, handle END blocks in plperl.
Database access is disallowed during both these operations, although it might be allowed in END blocks in future.

Patch from Tim Bunce.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.76 2010/01/27 02:55:04 adunstan Exp $ -->
d1061 3
a1063 3
	   The perl code is limited to a single string. Longer code can be placed
	   into a module and loaded by the <literal>on_perl_init</> string.
	   Examples:
@


2.76
log
@Fix plperl.sgml errors from recent commit.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.75 2010/01/26 23:11:56 adunstan Exp $ -->
d1031 66
a1096 1
 <sect1 id="plperl-missing">
d1131 1
d1133 9
a1141 1
    </listitem>
d1144 2
@


2.75
log
@Various small improvements and cleanups for PL/Perl.

- Allow (ineffective) use of 'require' in plperl
    If the required module is not already loaded then it dies.
    So "use strict;" now works in plperl.

- Pre-load the feature module if perl >= 5.10.
    So "use feature :5.10;" now works in plperl.

- Stored procedure subs are now given names.
    The names are not visible in ordinary use, but they make
    tools like Devel::NYTProf and Devel::Cover much more useful.

- Simplified and generalized the subroutine creation code.
    Now one code path for generating sub source code, not four.
    Can generate multiple 'use' statements with specific imports
    (which handles plperl.use_strict currently and can easily
    be extended to handle a plperl.use_feature=':5.12' in future).

- Disallows use of Safe version 2.20 which is broken for PL/Perl.
    http://rt.perl.org/rt3/Ticket/Display.html?id=72068

- Assorted minor optimizations by pre-growing data structures.

Patch from Tim Bunce, reviewed by Alex Hunsaker.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.74 2010/01/20 03:37:10 rhaas Exp $ -->
d288 3
a290 3
   If you wish to use the <literal>strict</> pragma with your code you have a few options.
   For temporary global use you can <command>SET</> <literal>plperl.use_strict</literal>
   to true (see <xref linkend="plperl.use_strict">).
a694 2
 </sect1>

a1069 2
 </sect2>

@


2.74
log
@Fix doc build, which was broken by PL/perl utility functions patch.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.73 2010/01/20 01:08:21 adunstan Exp $ -->
d288 7
a294 9
   If you wish to use the <literal>strict</> pragma with your code,
   the easiest way to do so is to <command>SET</>
   <literal>plperl.use_strict</literal> to true.  This parameter affects
   subsequent compilations of <application>PL/Perl</> functions, but not
   functions already compiled in the current session.  To set the
   parameter before <application>PL/Perl</> has been loaded, it is
   necessary to have added <quote><literal>plperl</></> to the <xref
   linkend="guc-custom-variable-classes"> list in
   <filename>postgresql.conf</filename>.
d298 1
a298 1
   Another way to use the <literal>strict</> pragma is to put:
d302 19
a320 7
   in the function body.  But this only works in <application>PL/PerlU</>
   functions, since the <literal>use</> triggers a <literal>require</>
   which is not a trusted operation.  In
   <application>PL/Perl</> functions you can instead do:
<programlisting>
BEGIN { strict->import(); }
</programlisting>
a694 12
 <sect1 id="plperl-data">
  <title>Data Values in PL/Perl</title>

  <para>
   The argument values supplied to a PL/Perl function's code are
   simply the input arguments converted to text form (just as if they
   had been displayed by a <command>SELECT</command> statement).
   Conversely, the <literal>return</> command will accept any string
   that is acceptable input format for the function's declared return
   type.  So, within the PL/Perl function,
   all values are just text strings.
  </para>
d1043 1
a1043 2
      PL/Perl functions cannot call each other directly (because they
      are anonymous subroutines inside Perl).
d1072 2
@


2.73
log
@Add utility functions to PLPerl:
    quote_literal, quote_nullable, quote_ident,
    encode_bytea, decode_bytea, looks_like_number,
    encode_array_literal, encode_array_constructor.
Split SPI.xs into two - SPI.xs now contains only SPI functions. Remainder
are in new Util.xs.
Some more code and documentation cleanup along the way, as well as
adding some CVS markers to files missing them.

Original patch from Tim Bunce, with a little editing from me.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.72 2010/01/09 02:40:50 adunstan Exp $ -->
d323 1
a681 1
  </para>
@


2.72
log
@Tidy up and refactor plperl.c.

- Changed MULTIPLICITY check from runtime to compiletime.
    No loads the large Config module.
- Changed plperl_init_interp() to return new interp
    and not alter the global interp_state
- Moved plperl_safe_init() call into check_interp().
- Removed plperl_safe_init_done state variable
    as interp_state now covers that role.
- Changed plperl_create_sub() to take a plperl_proc_desc argument.
- Simplified return value handling in plperl_create_sub.
- Changed perl.com link in the docs to perl.org and tweaked
    wording to clarify that require, not use, is what's blocked.
- Moved perl code in large multi-line C string literal macros
    out to plc_*.pl files.
- Added a test2macro.pl utility to convert the plc_*.pl files to
    macros in a perlchunks.h file which is #included
- Simplifed plperl_safe_init() slightly
- Optimized pg_verifymbstr calls to avoid unneeded strlen()s.

Patch from Tim Bunce, with minor editing from me.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.71 2009/11/29 03:02:27 tgl Exp $ -->
d16 1
a16 1
   <productname>PostgreSQL</productname> functions in the 
d104 1
a104 1
   (<literal>\</>) used in the body of the function 
d144 3
a146 3
    my ($x,$y) = @@_;
    if (! defined $x) {
        if (! defined $y) { return undef; }
d149 2
a150 2
    if (! defined $y) { return $x; }
    if ($x &gt; $y) { return $x; }
d161 1
a161 1
   a string, which is in the standard <productname>PostgreSQL</productname> 
d165 4
a168 10
   other cases the argument will need to be converted into a form that is 
   more usable in Perl. For example, here is how to convert an argument of 
   type <type>bytea</> into unescaped binary 
   data:

<programlisting>
    my $arg = shift;
    $arg =~ s!\\(?:\\|(\d{3}))!$1 ? chr(oct($1)) : "\\"!ge;
</programlisting>

d172 4
a175 9
   Similarly, values passed back to <productname>PostgreSQL</productname> 
   must be in the external text representation format. For example, here 
   is how to escape binary data for a return value of type <type>bytea</>:

<programlisting>
    $retval =~ s!(\\|[^ -~])!sprintf("\\%03o",ord($1))!ge;
    return $retval;
</programlisting>

d314 4
a317 1
 <sect1 id="plperl-database">
d335 1
a335 1
     <term><literal><function>spi_exec_prepared</>(<replaceable>plan</replaceable>)</literal></term>
d450 1
a450 1
      
d452 1
a452 1
    <literal>spi_prepare</literal>, <literal>spi_query_prepared</literal>, <literal>spi_exec_prepared</literal>, 
d459 1
a459 1
    
d462 1
a462 1
    than one query execution. After the plan is not needed anymore, it can be freed with 
d473 1
a473 1
        return spi_exec_prepared( 
d488 1
a488 1
  add_time  |  add_time  |  add_time  
d511 5
d517 1
d546 134
d682 1
d723 1
a723 1
SELECT set_var('sample', 'Hello, PL/Perl!  How's tricks?');
d837 1
a837 1
      consequence, in such an installation, you cannot use both 
d839 5
a843 4
      process. The remedy for this is to obtain a Perl installation created
      with the appropriate flags, namely either <literal>usemultiplicity</> or
      both <literal>usethreads</> and <literal>useithreads</>. 
      For more details,see the <literal>perlembed</> manual page.
d846 1
a846 1
  
d855 2
a856 2
   current trigger event. <varname>$_TD</> is a global variable, 
   which gets a separate local value for each invocation of the trigger. 
d938 1
a938 1
       and could be removed in a future release. 
@


2.71
log
@Add support for anonymous code blocks (DO blocks) to PL/Perl.

Joshua Tolley, reviewed by Brendan Jurd and Tim Bunce
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.70 2009/08/15 00:33:12 petere Exp $ -->
d17 1
a17 1
   <ulink url="http://www.perl.com">Perl programming language</ulink>.
d316 2
a317 1
   functions, since <literal>use</> is not a trusted operation.  In
@


2.70
log
@Clarify the documentation about PL/Perl nested subroutines, per Josh
Berkus.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.69 2008/04/10 15:16:46 alvherre Exp $ -->
d62 1
d64 18
a81 4
   glue code wraps it inside a Perl subroutine. A PL/Perl function must
   always return a scalar value.  You can return more complex structures
   (arrays, records, and sets) by returning a reference, as discussed below.
   Never return a list.
d687 7
@


2.69
log
@Remove mention of DBD::PgSPI, which is unmaintained and generally unnecessary.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.68 2008/03/28 00:21:55 tgl Exp $ -->
d75 4
a78 2
    which you call via a coderef. See the <literal>perldiag</literal>
    man page for more details.
@


2.69.2.1
log
@Improve PL/Perl documentation of database access functions.  (Backpatch to 8.4
of a patch previously applied by Bruce Momjian to CVS HEAD)

Alexey Klyukin
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.69 2008-04-10 15:16:46 alvherre Exp $ -->
a312 1
  </para>
a319 28
     <indexterm>
      <primary>spi_query</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_fetchrow</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_prepare</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_exec_prepared</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_query_prepared</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_cursor_close</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
      <primary>spi_freeplan</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
d322 8
a401 2
    </listitem>
    </varlistentry>
a402 6
    <varlistentry>
     <term><literal><function>spi_query</>(<replaceable>command</replaceable>)</literal></term>
     <term><literal><function>spi_fetchrow</>(<replaceable>cursor</replaceable>)</literal></term>
     <term><literal><function>spi_cursor_close</>(<replaceable>cursor</replaceable>)</literal></term>

    <listitem>
d440 1
a440 1

d442 3
a444 29
     Normally, <function>spi_fetchrow</> should be repeated until it
     returns <literal>undef</literal>, indicating that there are no more
     rows to read.  The cursor returned by <literal>spi_query</literal>
     is automatically freed when
     <function>spi_fetchrow</> returns <literal>undef</literal>.
     If you do not wish to read all the rows, instead call
     <function>spi_cursor_close</> to free the cursor.
     Failure to do so will result in memory leaks.
    </para>

    </listitem>
    </varlistentry>

    <varlistentry>
     <term><literal><function>spi_prepare</>(<replaceable>command</replaceable>, <replaceable>argument types</replaceable>)</literal></term>
     <term><literal><function>spi_query_prepared</>(<replaceable>plan</replaceable>, <replaceable>arguments</replaceable>)</literal></term>
     <term><literal><function>spi_exec_prepared</>(<replaceable>plan</replaceable> [, <replaceable>attributes</replaceable>], <replaceable>arguments</replaceable>)</literal></term>
     <term><literal><function>spi_freeplan</>(<replaceable>plan</replaceable>)</literal></term>

    <listitem>
    <para>
    <literal>spi_prepare</literal>, <literal>spi_query_prepared</literal>, <literal>spi_exec_prepared</literal>,
    and <literal>spi_freeplan</literal> implement the same functionality but for prepared queries.
    <literal>spi_prepare</literal> accepts a query string with numbered argument placeholders ($1, $2, etc)
    and a string list of argument types:
<programlisting>
$plan = spi_prepare('SELECT * FROM test WHERE id &gt; $1 AND name = $2', 'INTEGER', 'TEXT');
</programlisting>
    Once a query plan is prepared by a call to <literal>spi_prepare</literal>, the plan can be used instead
a447 2
    The optional second parameter to <literal>spi_exec_prepared</literal> is a hash reference of attributes;
    the only attribute currently supported is <literal>limit</literal>, which sets the maximum number of rows returned by a query. 
d449 1
a449 1

d452 1
a452 1
    than one query execution. After the plan is not needed anymore, it can be freed with
d458 1
a458 1
CREATE OR REPLACE FUNCTION init() RETURNS VOID AS $$
d463 1
a463 1
        return spi_exec_prepared(
d465 1
a465 1
                $_[0]
d469 1
a469 1
CREATE OR REPLACE FUNCTION done() RETURNS VOID AS $$
d478 1
a478 1
  add_time  |  add_time  |  add_time
d491 7
a497 1
    Another example illustrates usage of an optional parameter in <literal>spi_exec_prepared</literal>:
d499 1
a499 34

    <para>
    <programlisting>
CREATE TABLE hosts AS SELECT id, ('192.168.1.'||id)::inet AS address FROM generate_series(1,3) AS id;

CREATE OR REPLACE FUNCTION init_hosts_query() RETURNS VOID AS $$
        $_SHARED{plan} = spi_prepare('SELECT * FROM hosts WHERE address &lt;&lt; $1', 'inet');
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION query_hosts(inet) RETURNS SETOF hosts AS $$
        return spi_exec_prepared(
                $_SHARED{plan},
                {limit =&gt; 2},
                $_[0]
        )->{rows};
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION release_hosts_query() RETURNS VOID AS $$
        spi_freeplan($_SHARED{plan});
        undef $_SHARED{plan};
$$ LANGUAGE plperl;

SELECT init_hosts_query();
SELECT query_hosts('192.168.1.0/30');
SELECT release_hosts_query();

    query_hosts    
-----------------
 (1,192.168.1.1)
 (2,192.168.1.2)
(2 rows)
    </programlisting>
    </para>
    </listitem>
d531 1
@


2.69.2.2
log
@Abandon the use of Perl's Safe.pm to enforce restrictions in plperl, as it is
fundamentally insecure. Instead apply an opmask to the whole interpreter that
imposes restrictions on unsafe operations. These restrictions are much harder
to subvert than is Safe.pm, since there is no container to be broken out of.
Backported to release 7.4.

In releases 7.4, 8.0 and 8.1 this also includes the necessary backporting of
the two interpreters model for plperl and plperlu adopted in release 8.2.

In versions 8.0 and up, the use of Perl's POSIX module to undo its locale
mangling on Windows has become insecure with these changes, so it is
replaced by our own routine, which is also faster.

Nice side effects of the changes include that it is now possible to use perl's
"strict" pragma in a natural way in plperl, and that perl's $a and
$b variables now work as expected in sort routines, and that function
compilation is significantly faster.

Tim Bunce and Andrew Dunstan, with reviews from Alex Hunsaker and
Alexey Klyukin.

Security: CVE-2010-1169
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.69.2.1 2010/03/11 21:53:53 alvherre Exp $ -->
d298 6
a303 1
   in the function body.
@


2.68
log
@Support statement-level ON TRUNCATE triggers.  Simon Riggs
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.67 2008/01/25 15:28:35 adunstan Exp $ -->
d312 1
a312 14
   via the function <function>spi_exec_query</function> described
   below, or via an experimental module 
   <ulink url="http://www.cpan.org/modules/by-module/DBD/APILOS/">
   <literal>DBD::PgSPI</literal></ulink>
   (also available at <ulink url="http://www.cpan.org/SITES.html">
   <acronym>CPAN mirror sites</></ulink>).  This module makes available a
   <acronym>DBI</>-compliant database-handle named
   <varname>$pg_dbh</varname> that can be used to perform queries with
   normal <acronym>DBI</>
   syntax.<indexterm><primary>DBI</></indexterm>
  </para>

  <para>
   PL/Perl provides additional Perl commands:
d402 1
@


2.67
log
@Fix example of de-escaping bytea argument, per Florian Weimer. Also fix example
of escaping bytea return value. Both cases did not handle backslash values properly.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.66 2007/05/04 14:55:32 adunstan Exp $ -->
d20 2
a21 1
  <para> The usual advantage to using PL/Perl is that this allows use,
d23 1
a23 1
    munging</quote> operators and functions available for Perl.  Parsing
d25 3
a27 2
   string functions and control structures provided in PL/pgSQL.</para>
  
d744 2
a745 1
       Trigger event: <literal>INSERT</>, <literal>UPDATE</>, <literal>DELETE</>, or <literal>UNKNOWN</>
d828 1
a828 1
   Triggers can return one of the following:
d835 1
a835 1
       Execute the statement
d844 1
a844 1
       Don't execute the statement
@


2.67.2.1
log
@Abandon the use of Perl's Safe.pm to enforce restrictions in plperl, as it is
fundamentally insecure. Instead apply an opmask to the whole interpreter that
imposes restrictions on unsafe operations. These restrictions are much harder
to subvert than is Safe.pm, since there is no container to be broken out of.
Backported to release 7.4.

In releases 7.4, 8.0 and 8.1 this also includes the necessary backporting of
the two interpreters model for plperl and plperlu adopted in release 8.2.

In versions 8.0 and up, the use of Perl's POSIX module to undo its locale
mangling on Windows has become insecure with these changes, so it is
replaced by our own routine, which is also faster.

Nice side effects of the changes include that it is now possible to use perl's
"strict" pragma in a natural way in plperl, and that perl's $a and
$b variables now work as expected in sort routines, and that function
compilation is significantly faster.

Tim Bunce and Andrew Dunstan, with reviews from Alex Hunsaker and
Alexey Klyukin.

Security: CVE-2010-1169
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.67 2008/01/25 15:28:35 adunstan Exp $ -->
d296 6
a301 1
   in the function body.
@


2.66
log
@Make clearer how arguments and return values in pl/perl are escaped. This is to clarify the situation that Theo Schlossnagle recently reported on -bugs.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.65 2007/05/03 15:05:56 neilc Exp $ -->
d153 1
a153 1
    $arg =~ s!\\(\d{3})!chr(oct($1))!ge;
d164 1
a164 1
    $retval =~ s!([^ -~])!sprintf("\\%03o",ord($1))!ge;
@


2.65
log
@Fix some typos in the documentation. Patch from Brian Gough. Backport
the relevant fixes to 8.2 as well.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.64 2007/02/16 03:50:29 momjian Exp $ -->
d141 30
d177 1
a177 1
    return [['a"b','c,d'],['e\\f','g']];
@


2.64
log
@Remove tabs from SGML files to help tag alingment and improve
detection of tabs are added in the future.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.63 2007/02/01 19:10:24 momjian Exp $ -->
d23 1
a23 1
   complex strings might be be easier using Perl than it is with the
d622 1
a622 1
    operation will be be caught by the validator.
@


2.63
log
@Wording cleanup for error messages.  Also change can't -> cannot.

Standard English uses "may", "can", and "might" in different ways:

        may - permission, "You may borrow my rake."

        can - ability, "I can lift that log."

        might - possibility, "It might rain today."

Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice.  Similarly, "It may crash" is better stated, "It might crash".
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.62 2007/02/01 00:28:17 momjian Exp $ -->
d652 1
a652 1
	  For security reasons, to stop a leak of privileged operations from
d654 11
a664 11
	  have to run in separate instances of the Perl interpreter. If your
	  Perl installation has been appropriately compiled, this is not a problem.
	  However, not all installations are compiled with the requisite flags.
	  If <productname>PostgreSQL</> detects that this is the case then it will
	  not start a second interpreter, but instead create an error. In
	  consequence, in such an installation, you cannot use both 
	  <application>PL/PerlU</> and <application>PL/Perl</> in the same backend
	  process. The remedy for this is to obtain a Perl installation created
	  with the appropriate flags, namely either <literal>usemultiplicity</> or
	  both <literal>usethreads</> and <literal>useithreads</>. 
	  For more details,see the <literal>perlembed</> manual page.
@


2.62
log
@Consistenly use colons before '<programlisting>' blocks, where
appropriate.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.61 2007/01/31 20:56:18 momjian Exp $ -->
d400 1
a400 1
        or elog(ERROR, "can't open $file for reading: $!");
d544 1
a544 1
        return "can't set shared variable $_[0] to $_[1]";
@


2.61
log
@Update documentation on may/can/might:

Standard English uses "may", "can", and "might" in different ways:

        may - permission, "You may borrow my rake."

        can - ability, "I can lift that log."

        might - possibility, "It might rain today."

Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice.  Similarly, "It may crash" is better stated, "It might crash".

Also update two error messages mentioned in the documenation to match.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.60 2007/01/30 22:29:23 momjian Exp $ -->
d178 1
a178 1
   For example,
d262 1
a262 1
   Another way to use the <literal>strict</> pragma is to put
d268 1
a268 1
   <application>PL/Perl</> functions you can instead do
@


2.60
log
@Update documentation for backslashes to mention escape string syntax
more, and standard_conforming_strings less, because in the future non-E
strings will not treat backslashes specially.

Also use E'' strings where backslashes are used in examples. (The
existing examples would have drawn warnings.)

Backpatch to 8.2.X.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.59 2006/11/13 17:13:56 adunstan Exp $ -->
d23 1
a23 1
   complex strings may be be easier using Perl than it is with the
d385 1
a385 1
    work together as a pair for row sets which may be large, or for cases
d432 1
a432 1
    than one query execution. After the plan is not needed anymore, it may be freed with 
d604 1
a604 1
   as a C function can do.  Thus, any unprivileged database user may
@


2.59
log
@Force plperl and plperlu to run in separate interpreters. Create an error
on an attempt to create the second interpreter if this is not supported by
the perl installation. Per recent -hackers discussion.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.58 2006/10/23 18:10:31 petere Exp $ -->
d83 4
a86 4
   If you choose to use regular single-quoted string constant syntax,
   you must escape single quote marks (<literal>'</>) and backslashes
   (<literal>\</>) used in the body of the function, typically by
   doubling them (see <xref linkend="sql-syntax-strings">).
@


2.59.2.1
log
@Update documentation for backslashes to mention escape string syntax
more, and standard_conforming_strings less, because in the future non-E
strings will not treat backslashes specially.

Also use E'' strings where backslashes are used in examples. (The
existing examples would have drawn warnings.)

Backpatch to 8.2.X.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.59 2006/11/13 17:13:56 adunstan Exp $ -->
d83 4
a86 4
   If you choose to use escape string syntax <literal>E''</>,
   you must double the single quote marks (<literal>'</>) and backslashes
   (<literal>\</>) used in the body of the function 
   (see <xref linkend="sql-syntax-strings">).
@


2.59.2.2
log
@Fix some typos in the documentation. Patch from Brian Gough. Backport
the relevant fixes to 8.2 as well.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.59.2.1 2007/01/30 22:29:40 momjian Exp $ -->
d23 1
a23 1
   complex strings may be easier using Perl than it is with the
d622 1
a622 1
    operation will be caught by the validator.
@


2.59.2.3
log
@Abandon the use of Perl's Safe.pm to enforce restrictions in plperl, as it is
fundamentally insecure. Instead apply an opmask to the whole interpreter that
imposes restrictions on unsafe operations. These restrictions are much harder
to subvert than is Safe.pm, since there is no container to be broken out of.
Backported to release 7.4.

In releases 7.4, 8.0 and 8.1 this also includes the necessary backporting of
the two interpreters model for plperl and plperlu adopted in release 8.2.

In versions 8.0 and up, the use of Perl's POSIX module to undo its locale
mangling on Windows has become insecure with these changes, so it is
replaced by our own routine, which is also faster.

Nice side effects of the changes include that it is now possible to use perl's
"strict" pragma in a natural way in plperl, and that perl's $a and
$b variables now work as expected in sort routines, and that function
compilation is significantly faster.

Tim Bunce and Andrew Dunstan, with reviews from Alex Hunsaker and
Alexey Klyukin.

Security: CVE-2010-1169
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.59.2.2 2007/05/03 15:06:13 neilc Exp $ -->
d266 6
a271 1
   in the function body.
@


2.58
log
@Spellchecking and such
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.57 2006/09/16 00:30:14 momjian Exp $ -->
d649 19
@


2.57
log
@Remove emacs info from footer of SGML files.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.56 2006/08/12 20:05:54 tgl Exp $ -->
d24 1
a24 1
   string functions and control structures provided in PL/pgsql.</para>
d191 1
a191 1
   hash will be returned as NULLs.
@


2.56
log
@Tweak SPI_cursor_open to allow INSERT/UPDATE/DELETE RETURNING; this was
merely a matter of fixing the error check, since the underlying Portal
infrastructure already handles it.  This in turn allows these statements
to be used in some existing plpgsql and plperl contexts, such as a
plpgsql FOR loop.  Also, do some marginal code cleanup in places that
were being sloppy about distinguishing SELECT from SELECT INTO.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.55 2006/05/30 11:40:21 momjian Exp $ -->
a878 17

<!-- Keep this comment at the end of the file
Local variables:
mode:sgml
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:("/usr/lib/sgml/catalog")
sgml-local-ecat-files:nil
End:
-->
@


2.55
log
@Update PL documentation:

An article at WebProNews quoted from the PG docs as to the merits of
stored procedures.  I have added a bit more material on their merits,
as well as making a few changes to improve the introductions to
PL/Perl and PL/Tcl.

Chris Browne
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.54 2006/05/29 13:51:23 adunstan Exp $ -->
a246 1

a248 9
    <para>
     <application>PL/Perl</> does not currently have full support for
     domain types: it treats a domain the same as the underlying scalar
     type.  This means that constraints associated with the domain will
     not be enforced.  This is not an issue for function arguments, but
     it is a hazard if you declare a <application>PL/Perl</> function
     as returning a domain type.
    </para>

d432 1
a432 1
    than one query execution. After the plan is not needed anymore, it must be freed with 
d439 1
a439 1
	$_SHARED{my_plan} = spi_prepare( 'SELECT (now() + $1)::date AS now', 'INTERVAL');
d443 4
a446 4
	return spi_exec_prepared( 
		$_SHARED{my_plan},
		$_[0],
	)->{rows}->[0]->{now};
d450 2
a451 2
	spi_freeplan( $_SHARED{my_plan});
	undef $_SHARED{my_plan};
d471 7
a477 7
    <literal>spi_cursor_close</literal> can be used to abort sequence of
    <literal>spi_fetchrow</literal> calls. Normally, the call to
    <literal>spi_fetchrow</literal> that returns <literal>undef</literal> is
    the signal that there are no more rows to read. Also
    that call automatically frees the cursor associated with the query. If it is desired not
    to read all retuned rows, <literal>spi_cursor_close</literal> must be
    called to avoid memory leaks.  
a478 2


d621 2
a622 2
	The creation of this function will fail as its use of a forbidden
	operation will be be caught by the validator.
d739 2
a740 2
	   and could be removed in a future release. 
	   Please use $_TD-&gt;{table_name} instead.
@


2.54
log
@
Make plperl's $_TD trigger data a global rather than a lexical variable,
with a fresh local value for each invocation, to avoid unexpected sharing
violations. Per recent -hackers discussion.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.53 2006/05/26 17:34:16 adunstan Exp $ -->
d20 6
@


2.53
log
@
Add table_name and table_schema to plperl trigger data. relname is
kept but now deprecated. Patch from Adam Sjøgren. Add regression test to
show plperl trigger data (Andrew).
TBD: apply similar changes to plpgsql, plpython and pltcl.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.52 2006/03/10 19:10:48 momjian Exp $ -->
d663 3
a665 2
   current trigger event.  The fields of the <varname>$_TD</varname> hash
   reference are:
@


2.52
log
@Make $PostgreSQL CVS tags consistent for SGML files.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/advanced.sgml,v 1.49 2005/04/09 03:52:43 momjian Exp $ -->
d731 9
d743 12
a754 1
       Name of the table on which the trigger fired
@


2.51
log
@
Prepared queries for PLPerl, plus fixing a small plperl memory leak. Patch
and docs from Dmitry Karasik, slightly editorialised.
@
text
@d1 1
a1 3
<!--
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.50 2006/03/01 06:30:32 neilc Exp $
-->
@


2.50
log
@This patch makes the error message strings throughout the backend
more compliant with the error message style guide. In particular,
errdetail should begin with a capital letter and end with a period,
whereas errmsg should not. I also fixed a few related issues in
passing, such as fixing the repeated misspelling of "lexeme" in
contrib/tsearch2 (per Tom's suggestion).
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.49 2005/11/04 23:14:00 petere Exp $
d299 1
a299 1
   PL/Perl provides three additional Perl commands:
a308 1
     <term><literal><function>spi_exec_query</>(<replaceable>command</replaceable>)</literal></term>
d310 6
a315 1
     <term><literal><function>spi_fetchrow</>(<replaceable>command</replaceable>)</literal></term>
d426 60
@


2.49
log
@Spellchecking run, final cleanups
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.48 2005/10/24 15:39:50 adunstan Exp $
d402 1
a402 1
        or elog(ERROR, "Can't open $file for reading: $!");
d559 1
a559 1
        or elog(ERROR, qq{Could not open the file "$tmpfile": $!});
d561 1
a561 1
    close $fh or elog(ERROR, qq{Could not close the file "$tmpfile": $!});
@


2.49.2.1
log
@Backpatch documentation additions for PL language choice and
regex_replace() to 8.1.X.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.49 2005/11/04 23:14:00 petere Exp $
a21 6
  <para> The usual advantage to using PL/Perl is that this allows use,
   within stored functions, of the manyfold <quote>string
    munging</quote> operators and functions available for Perl.  Parsing
   complex strings may be be easier using Perl than it is with the
   string functions and control structures provided in PL/pgsql.</para>
  
@


2.49.2.2
log
@Abandon the use of Perl's Safe.pm to enforce restrictions in plperl, as it is
fundamentally insecure. Instead apply an opmask to the whole interpreter that
imposes restrictions on unsafe operations. These restrictions are much harder
to subvert than is Safe.pm, since there is no container to be broken out of.
Backported to release 7.4.

In releases 7.4, 8.0 and 8.1 this also includes the necessary backporting of
the two interpreters model for plperl and plperlu adopted in release 8.2.

In versions 8.0 and up, the use of Perl's POSIX module to undo its locale
mangling on Windows has become insecure with these changes, so it is
replaced by our own routine, which is also faster.

Nice side effects of the changes include that it is now possible to use perl's
"strict" pragma in a natural way in plperl, and that perl's $a and
$b variables now work as expected in sort routines, and that function
compilation is significantly faster.

Tim Bunce and Andrew Dunstan, with reviews from Alex Hunsaker and
Alexey Klyukin.

Security: CVE-2010-1169
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.49.2.1 2006/05/30 12:32:37 momjian Exp $
d278 6
a283 1
   in the function body.
a598 19

  <note>
    <para>
          For security reasons, to stop a leak of privileged operations from
      <application>PL/PerlU</> to <application>PL/Perl</>, these two languages
          have to run in separate instances of the Perl interpreter. If your
          Perl installation has been appropriately compiled, this is not a problem.
          However, not all installations are compiled with the requisite flags.
          If <productname>PostgreSQL</> detects that this is the case then it will
          not start a second interpreter, but instead create an error. In
          consequence, in such an installation, you cannot use both 
          <application>PL/PerlU</> and <application>PL/Perl</> in the same backend
          process. The remedy for this is to obtain a Perl installation created
          with the appropriate flags, namely either <literal>usemultiplicity</> or
          both <literal>usethreads</> and <literal>useithreads</>. 
          For more details,see the <literal>perlembed</> manual page.
    </para>
  </note>
  
@


2.48
log
@
Fix incorrect wording about function failure time on unsafe ops - these
are now caught by the validator. And a small visit from the perl style police:
check the return value from open().
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.47 2005/10/18 22:53:54 adunstan Exp $
d316 1
a316 1
returns the entire rowset as a reference to an array of hash
d387 1
a387 1
    work together as a pair for rowsets which may be large, or for cases
d690 1
a690 1
       Arguments of the trigger function.  Does not exist if $_TD-&gt;{argc} is 0.
d790 1
a790 1
        large set of rows back to postgres via <literal>return</literal>. You
@


2.47
log
@
replace use of predefined perl vars $a and $b with $x and $y - per Greg Sabino Mullane
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.46 2005/10/12 14:28:33 momjian Exp $
d557 5
a561 2
    open(TEMP, "&gt;/tmp/badfile");
    print TEMP "Gotcha!\n";
d565 2
a566 1
   The creation of the function will succeed, but executing it will not.
@


2.46
log
@Add warning about plperl nested named subroutines

Andrew Dunstan
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.45 2005/08/24 19:16:49 tgl Exp $
d121 4
a124 4
    my ($a,$b) = @@_;
    if (! defined $a) {
        if (! defined $b) { return undef; }
        return $b;
d126 3
a128 3
    if (! defined $b) { return $a; }
    if ($a &gt; $b) { return $a; }
    return $b;
@


2.45
log
@Mention BEGIN { strict->import(); } as a substitute for 'use strict'
in plperl functions.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.44 2005/08/24 18:56:07 tgl Exp $
d56 2
a57 1
   The body of the function is ordinary Perl code. A PL/Perl function must
d63 1
d65 6
a70 8
    The syntax of the <command>CREATE FUNCTION</command> command requires
    the function body to be written as a string constant.  It is usually
    most convenient to use dollar quoting (see <xref
    linkend="sql-syntax-dollar-quoting">) for the string constant.
    If you choose to use regular single-quoted string constant syntax,
    you must escape single quote marks (<literal>'</>) and backslashes
    (<literal>\</>) used in the body of the function, typically by
    doubling them (see <xref linkend="sql-syntax-strings">).
d72 12
@


2.44
log
@Adjust description of use_strict parameter.  Some other minor editorial
cleanup.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.43 2005/08/12 21:42:53 momjian Exp $
d256 1
a256 1
   Another way to use the <literal>strict</> pragma is to just put
d260 6
a265 2
   in the function body.  But this only works for <application>PL/PerlU</>
   functions, since <literal>use</> is not a trusted operation.
@


2.43
log
@Improve documention on loading large data sets into plperl.

David Fetter
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.42 2005/07/13 02:10:42 neilc Exp $
d49 1
a49 5
   syntax.  A PL/Perl function must always return a scalar value.  You
   can return more complex structures (arrays, records, and sets) 
   in the appropriate context by returning a reference.
   Never return a list.  Here follows an example of a PL/Perl
   function.
d56 4
a59 1
   The body of the function is ordinary Perl code.
a60 27
    <para>
    As with ordinary Perl code, you should use the strict pragma,
    which you can do in one of two ways:

    <itemizedlist>
     <listitem>
      <para>
       Globally, by adding <quote>plperl</quote> to the list of <xref
        linkend="guc-custom-variable-classes"> and setting
       <literal>plperl.use_strict</literal> to true in
       <filename>postgresql.conf</filename>
      </para>
    </listitem>
     <listitem>
      <para>
       One function at a time, by using PL/PerlU (you must be database
       superuser to do this) and including

<programlisting>
use strict;
</programlisting>

        in the function body.
        </para>
    </listitem>
    </itemizedlist>
    </para>
d180 2
a181 2
    composite types.  In general, you'll want to return rows one at a
    time both to speed up startup time and to keep from queueing up
d185 2
a186 2
    either <literal>return;</literal> or (better) <literal>return
    undef;</literal>
d212 1
a212 1
    result set as a reference:
d242 21
@


2.42
log
@Documentation for some new PL/Perl features. Patch from David Fetter,
various editorialization from Neil Conway.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.41 2005/06/05 03:16:29 momjian Exp $
d49 6
a54 1
   syntax:
d290 1
a290 1
   PL/Perl provides two additional Perl commands:
d301 3
d306 7
a312 3
       Executes an SQL command.  Here is an example of a query
       (<command>SELECT</command> command) with the optional maximum
       number of rows:
d360 1
a360 1
CREATE FUNCTION test_munge() RETURNS SETOF test AS $$
d375 39
a413 1
      </para>
d769 5
a773 3
      In the current implementation, if you are fetching or returning
      very large data sets, you should be aware that these will all go
      into memory.
d775 8
@


2.41
log
@Here's a patch to do the following:

1. Rename spi_return_next to return_next.
2. Add a new test for return_next.
3. Update the expected output.
4. Update the documentation.

Abhijit Menon-Sen
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.40 2005/05/20 01:52:24 neilc Exp $
d57 27
d148 14
d202 34
a235 4
   PL/Perl functions can also return sets of either scalar or composite
   types.  To do this, return a reference to an array that contains
   either scalars or references to hashes, respectively.  Here are
   some simple examples:
d239 1
a239 1
return [0..$_[0]];
a243 1

d250 1
a250 1
$$  LANGUAGE plperl;
a254 5
   When you do this, Perl will have to build the entire array in memory;
   therefore the technique does not scale to very large result sets. You
   can instead call <function>return_next</function> for each element of
   the result set, passing it either a scalar or a reference to a hash,
   as appropriate to your function's return type.
d285 1
a285 1
   PL/Perl itself presently provides two additional Perl commands:
a348 1
    my $res = [];
d356 1
a356 1
        push @@$res, $row;
d358 1
a358 1
    return $res;
@


2.40
log
@Add some links to the CREATE FUNCTION reference page when describing
function definition for particular PLs. Original patch from David
Fetter, editorializing by Neil Conway.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.39 2005/04/09 03:52:43 momjian Exp $
d185 5
a189 2
   Note that when you do this, Perl will have to build the entire array in
   memory; therefore the technique does not scale to very large result sets.
@


2.39
log
@We don't put URL's in ulink's because the URL is always generated, but
we can put words in ulink and the URL will still be printed.

per Peter
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.38 2005/03/31 03:54:38 momjian Exp $
d47 3
a49 1
   To create a function in the PL/Perl language, use the standard syntax:
@


2.38
log
@Adjust SGML ulink tags to the URL is always displayed in our printed docs.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.37 2005/01/17 17:29:49 momjian Exp $
d18 2
a19 2
   <productname>PostgreSQL</productname> functions in the Perl programming language,
   <ulink url="http://www.perl.com"></ulink>.
d203 5
a207 4
   below, or via an experimental module <literal>DBD::PgSPI</literal>, 
   <ulink url="http://www.cpan.org/modules/by-module/DBD/APILOS/"></ulink>,
   (also available at <acronym>CPAN mirror sites</>, <ulink
   url="http://www.cpan.org/SITES.html"></ulink>).  This module makes available a
@


2.37
log
@Please find enclosed another patch that now (I hope) really is
correct.  It's in addition to the previous patch.

David Fetter
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.36 2005/01/17 03:04:17 momjian Exp $
d18 2
a19 2
   <productname>PostgreSQL</productname> functions in the <ulink
   url="http://www.perl.com">Perl</ulink> programming language.
d203 4
a206 5
   below, or via an experimental module <ulink
   url="http://www.cpan.org/modules/by-module/DBD/APILOS/"><literal>DBD::PgSPI</literal></ulink>
   (also available at <ulink
   url="http://www.cpan.org/SITES.html"><acronym>CPAN</> mirror
   sites</ulink>).  This module makes available a
@


2.37.4.1
log
@Abandon the use of Perl's Safe.pm to enforce restrictions in plperl, as it is
fundamentally insecure. Instead apply an opmask to the whole interpreter that
imposes restrictions on unsafe operations. These restrictions are much harder
to subvert than is Safe.pm, since there is no container to be broken out of.
Backported to release 7.4.

In releases 7.4, 8.0 and 8.1 this also includes the necessary backporting of
the two interpreters model for plperl and plperlu adopted in release 8.2.

In versions 8.0 and up, the use of Perl's POSIX module to undo its locale
mangling on Windows has become insecure with these changes, so it is
replaced by our own routine, which is also faster.

Nice side effects of the changes include that it is now possible to use perl's
"strict" pragma in a natural way in plperl, and that perl's $a and
$b variables now work as expected in sort routines, and that function
compilation is significantly faster.

Tim Bunce and Andrew Dunstan, with reviews from Alex Hunsaker and
Alexey Klyukin.

Security: CVE-2010-1169
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.37 2005/01/17 17:29:49 momjian Exp $
d461 1
a461 20

  <note>
    <para>
          For security reasons, to stop a leak of privileged operations from
      <application>PL/PerlU</> to <application>PL/Perl</>, these two languages
          have to run in separate instances of the Perl interpreter. If your
          Perl installation has been appropriately compiled, this is not a problem.
          However, not all installations are compiled with the requisite flags.
          If <productname>PostgreSQL</> detects that this is the case then it will
          not start a second interpreter, but instead create an error. In
          consequence, in such an installation, you cannot use both 
          <application>PL/PerlU</> and <application>PL/Perl</> in the same backend
          process. The remedy for this is to obtain a Perl installation created
          with the appropriate flags, namely either <literal>usemultiplicity</> or
          both <literal>usethreads</> and <literal>useithreads</>. 
          For more details,see the <literal>perlembed</> manual page.
    </para>
  </note>
  
</sect1>
@


2.36
log
@Please find enclosed a patch to the pl/perl documents that correctly
tells what arguments go to pl/perl triggers.

David Fetter
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.35 2004/12/30 21:45:36 tgl Exp $
d546 1
a546 1
     <term><literal>@@{$_TD-&gt;{argv}}</literal></term>
d549 1
a549 1
       Arguments of the trigger function
d555 1
a555 1
     <term><literal>$_TD-&gt;{argc}</literal></term>
d558 1
a558 1
       Number of arguments of the trigger function
d562 1
@


2.35
log
@More minor updates and copy-editing.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.34 2004/12/13 18:05:08 petere Exp $
d492 1
a492 1
     <term><literal>$_TD{name}</literal></term>
d501 1
a501 1
     <term><literal>$_TD{event}</literal></term>
d510 1
a510 1
     <term><literal>$_TD{when}</literal></term>
d519 1
a519 1
     <term><literal>$_TD{level}</literal></term>
d528 1
a528 1
     <term><literal>$_TD{relid}</literal></term>
d537 1
a537 1
     <term><literal>$_TD{relname}</literal></term>
d546 1
a546 1
     <term><literal>@@{$_TD{argv}}</literal></term>
d555 1
a555 1
     <term><literal>$_TD{argc}</literal></term>
@


2.34
log
@Spell checker run
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.33 2004/12/11 20:03:37 petere Exp $
d135 1
a135 1
SELECT name, empcomp(employee) FROM employee;
d138 57
d264 31
d315 8
a322 2
        The other levels simply report the message to the system log
        and/or client.
d339 2
a340 66
   type.  So, the PL/Perl programmer can manipulate data values as if
   they were just text.
  </para>

  <para>
   PL/Perl can also return row sets and composite types, and row sets
   of composite types.  Here is an example of a PL/Perl function
   returning a row set of a row type.  Note that a composite type is
   always represented as a hash reference.
<programlisting>
CREATE TABLE test (
    i int,
    v varchar
);

INSERT INTO test (i, v) VALUES (1, 'first line');
INSERT INTO test (i, v) VALUES (2, 'second line');
INSERT INTO test (i, v) VALUES (3, 'third line');
INSERT INTO test (i, v) VALUES (4, 'immortal');

CREATE FUNCTION test_munge() RETURNS SETOF test AS $$
    my $res = [];
    my $rv = spi_exec_query('select i, v from test;');
    my $status = $rv-&gt;{status};
    my $nrows = $rv-&gt;{processed};
    foreach my $rn (0 .. $nrows - 1) {
        my $row = $rv-&gt;{rows}[$rn];
        $row-&gt;{i} += 200 if defined($row-&gt;{i});
        $row-&gt;{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row-&gt;{v}));
        push @@$res, $row;
    }
    return $res;
$$ LANGUAGE plperl;

SELECT * FROM test_munge();
</programlisting>
  </para>

  <para>
   Here is an example of a PL/Perl function returning a composite
   type:
<programlisting>
CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);

CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
    return {f2 =&gt; 'hello', f1 =&gt; 1, f3 =&gt; 'world'};
$$ LANGUAGE plperl;
</programlisting>
  </para>

  <para>
   Here is an example of a PL/Perl function returning a row set of a
   composite type.  Since a row set is always a reference to an array
   and a composite type is always a reference to a hash, a row set of a
   composite type is a reference to an array of hash references.
<programlisting>
CREATE TYPE testsetperl AS (f1 integer, f2 text, f3 text);

CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testsetperl AS $$
    return [
        { f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt;  'World' },
        { f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt;  'PostgreSQL' },
        { f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt;  'PL/Perl' }
    ];
$$  LANGUAGE plperl;
</programlisting>
d350 1
a350 2
    lifetime of the current session, which is bounded from below by
    the lifetime of the current transaction.
d392 1
a392 1
    return &$qfunc($text_to_quote);
d397 1
a397 1
   <literal>return $_SHARED{myquote}->($_[0]);</literal>
d651 1
a651 3
      into memory.  Future features will help with this.  In the
      meantime, we suggest that you not use PL/Perl if you will fetch
      or return very large result sets.
@


2.33
log
@Patch to the pl/perl documents that clarifies the scope of global data and
gives an example of storing a code reference

by David Fetter
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.32 2004/11/21 21:17:01 tgl Exp $
d298 1
a298 1
   and a composite type is always a reference to a hash, a rowset of a
@


2.32
log
@Fix plperl and pltcl error handling per my previous proposal.  SPI
operations are now run as subtransactions, so that errors in them
can be reported as ordinary Perl or Tcl errors and caught by the
normal error handling convention of those languages.  Also do some
minor code cleanup in pltcl.c: extract a large chunk of duplicated
code in pltcl_SPI_execute and pltcl_SPI_execute_plan into a shared
subroutine.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.31 2004/11/19 23:22:54 tgl Exp $
d318 8
a325 2
   You can use the global hash <varname>%_SHARED</varname> to store
   data between function calls.  For example:
d343 28
@


2.31
log
@Fix incorrect documentation of plperl's method for accessing the number
of rows processed by a SPI query (David Fetter); also some other minor
editorial cleanup (Tom Lane).
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.30 2004/11/06 14:32:10 petere Exp $
d222 7
a228 3
       <literal>ERROR</> raises an error condition: further execution
       of the function is abandoned, and the current transaction is
       aborted.
@


2.30
log
@Reduce formatting entropy
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.29 2004/10/15 16:51:48 momjian Exp $
d69 1
a69 1
   Arguments are passed in <varname>@@_</varname>, and a result value
d80 1
a80 1
    if ($_[0] > $_[1]) { return $_[0]; }
d109 1
a109 1
    if ($a > $b) { return $a; }
d132 1
a132 1
    return $emp->{basesalary} + $emp->{bonus};
d177 4
a180 4
       This returns up to 5 rows from the table
       <literal>my_table</literal>.  If <literal>my_table</literal>
       has a column <literal>my_column</literal>, it could be accessed
       like this:
d182 1
a182 1
$foo = $rv->{rows}[$i]->{my_column};
d184 2
a185 1
       The total number of rows returned can be accessed like this:
d187 1
a187 1
$nrows = @@{$rv->{rows}};
d200 1
a200 1
$res = $rv->{status};
d204 1
a204 1
$nrows = $rv->{rows};
d264 6
a269 7
    my $status = $rv->{status};
    my $rows = @@{$rv->{rows}};
    my $processed = $rv->{processed};
    foreach my $rn (0 .. $rows - 1) {
        my $row = $rv->{rows}[$rn];
        $row->{i} += 200 if defined($row->{i});
        $row->{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row->{v}));
d286 1
a286 1
    return {f2 => 'hello', f1 => 1, f3 => 'world'};
d301 3
a303 3
        { f1 => 1, f2 => 'Hello', f3 =>  'World' },
        { f1 => 2, f2 => 'Hello', f3 =>  'PostgreSQL' },
        { f1 => 3, f2 => 'Hello', f3 =>  'PL/Perl' }
d306 1
a306 1
  </programlisting>
d362 1
a362 1
    open(TEMP, ">/tmp/badfile");
d400 3
a402 3
   PL/Perl can be used to write trigger functions.  The global hash
   reference <varname>$_TD</varname> contains information about the
   current trigger event.  The parts of <varname>$_TD</varname> hash
d407 1
a407 1
     <term><literal>$_TD->{new}{foo}</literal></term>
d416 1
a416 1
     <term><literal>$_TD->{old}{foo}</literal></term>
d491 1
a491 1
       Number of arguments of the trigger functions
d524 1
a524 1
       Indicates that the <literal>NEW</literal> rows was modified by
d542 1
a542 1
    if (($_TD->{new}{i} &gt;= 100) || ($_TD->{new}{i} &lt;= 0)) {
d544 2
a545 2
    } elsif ($_TD->{new}{v} ne "immortal") {
        $_TD->{new}{v} .= "(modified by trigger)";
@


2.29
log
@This patch clarifies the usage of references in PL/Perl :)

David Fetter
@
text
@d2 1
a2 1
$PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.28 2004/09/20 22:48:25 tgl Exp $
a39 1

d87 13
a99 16
   If an SQL <literal>NULL</literal> value<indexterm><primary>null
    value</><secondary sortas="PL/Perl">in PL/Perl</></indexterm> is
    passed to a function, the argument value will appear as
    <quote>undefined</> in Perl.  The above function definition will not
    behave very nicely with <literal>NULL</literal> inputs (in fact, it
    will act as though they are zeroes).  We could add <literal>STRICT</>
    to the function definition to make
    <productname>PostgreSQL</productname> do something more reasonable: if
    a <literal>NULL</literal> value is passed, the function will not be
    called at all, but will just return a <literal>NULL</literal> result
    automatically.  Alternatively, we could check for undefined inputs in
    the function body.  For example, suppose that we wanted
    <function>perl_max</function> with one <literal>NULL</literal> and one
    non-<literal>NULL</literal> argument to return the
    non-<literal>NULL</literal> argument, rather than a
    <literal>NULL</literal> value:
d113 3
a115 6
  </para>

  <para>
    As shown above, to return an SQL <literal>NULL</literal> value from
    a PL/Perl function, return an undefined value.  This can be done
    whether the function is strict or not.
a137 5

  <para>
   There is now support for returning a composite-type result value.
  </para>

d144 3
a146 2
   Access to the database itself from your Perl function can be done via
   spi_exec_query, or via an experimental module <ulink
d148 3
a150 2
   (also available at <ulink url="http://www.cpan.org/SITES.html"><acronym>CPAN</>
   mirror sites</ulink>).  This module makes available a
d152 3
a154 3
   <varname>$pg_dbh</varname> that can be used to perform queries
   with normal <acronym>DBI</> syntax.<indexterm><primary>DBI</></indexterm>

a165 4
     <indexterm>
      <primary>elog</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
d167 2
a168 1
     <term><function>spi_exec_query(</> [ <replaceable>SELECT query</replaceable> [, <replaceable>max_rows</replaceable>]] | [<replaceable>non-SELECT query</replaceable>] ) </term>
d170 11
a180 11
       <para>
        Here is an example of a SELECT query with the optional maximum
number of rows.
<programlisting>
$rv = spi_exec_query('SELECT * from my_table', 5);
</programlisting>

This returns up to 5 rows from my_table.
       </para>
       <para>
If my_table has a column my_column, it would be accessed as
d184 1
a184 3
       </para>
       <para>
The number of rows actually returned would be:
d188 4
a191 3
       </para>
       <para>
Here is an example using a non-SELECT statement.
d196 2
a197 2

You can then access status (SPI_OK_INSERT, e.g.) like this.
d201 1
a201 4

       </para>
       <para>
To get the rows affected, do:
d205 1
a205 2
       </para>

d207 1
a208 1
    </varlistentry>
d210 6
a215 1
     <term><function>elog</> <replaceable>level</replaceable>, <replaceable>msg</replaceable></term>
d245 4
a248 8
   PL/Perl can now return rowsets and composite types, and rowsets of
composite types.
  </para>

  <para>
   Here is an example of a PL/Perl function returning a rowset of a
   row type.  Note that a composite type is always represented as a
   hash reference.
d251 2
a252 2
       i int,
       v varchar
d255 4
a258 4
INSERT INTO test (i, v) VALUES (1,'first line');
INSERT INTO test (i, v) VALUES (2,'second line');
INSERT INTO test (i, v) VALUES (3,'third line');
INSERT INTO test (i, v) VALUES (4,'immortal');
d260 1
a260 1
create function test_munge() returns setof test language plperl as $$
d262 1
a262 1
    my $rv = spi_exec_query('select i,v from test;');
d266 1
a266 1
    foreach my $rn (0..$rows-1) {
d270 1
a270 1
        push @@$res,$row;
d273 1
a273 1
$$;
d275 1
a275 1
select * from test_munge();
d280 3
a282 2
   Here is an example of a PL/Perl function returning a composite type:
  <programlisting>
d286 1
a286 3

 return {f2 => 'hello', f1 => 1, f3 => 'world'};

d288 1
a288 1
  </programlisting>
d292 5
a296 5
  Here is an example of a PL/Perl function returning a rowset of a
composite type.  As a rowset is always a reference to an array
and a composite type is always a reference to a hash, a rowset of a
composite type is a reference to an array of hash references.
  <programlisting>
d300 5
a304 5
 return[
        {f1 => 1, f2 => 'hello', f3 =>  'world'},
        {f1 => 2, f2 => 'hello', f3 =>  'postgres'},
        {f1 => 3, f2 => 'hello', f3 =>  'plperl'}
       ];
d309 1
d312 1
d314 2
a315 4
  You can use the %_SHARED to store data between function calls.
  </para>
  <para>
For example:
d317 1
a317 1
CREATE OR REPLACE FUNCTION set_var(name TEXT, val TEXT) RETURNS TEXT AS $$
d321 1
a321 1
        return "Can't set shared variable $_[0] to $_[1]";
d325 1
a325 1
CREATE OR REPLACE FUNCTION get_var(name TEXT) RETURNS text AS $$
d329 1
a329 1
SELECT set_var('sample', $q$Hello, PL/Perl!  How's tricks?$q$);
a331 1

a332 2
   

d395 1
d400 68
a467 3
   PL/Perl can now be used to write trigger functions using the
<varname>$_TD</varname> hash reference.
  </para>
d469 8
a476 2
  <para>
   Some useful parts of the $_TD hash reference are:
d478 8
a485 12
<programlisting>
$_TD->{new}{foo} # NEW value of column foo
$_TD->{old}{bar} # OLD value of column bar
$_TD{name}       # Name of the trigger being called
$_TD{event}      # INSERT, UPDATE, DELETE or UNKNOWN
$_TD{when}       # BEFORE, AFTER or UNKNOWN
$_TD{level}      # ROW, STATEMENT or UNKNOWN
$_TD{relid}      # Relation ID of the table on which the trigger occurred.
$_TD{relname}    # Name of the table on which the trigger occurred.
@@{$_TD{argv}}    # Array of arguments to the trigger function.  May be empty.
$_TD{argc}       # Number of arguments to the trigger.  Why is this here?
</programlisting>
d487 9
d500 30
a529 5
<programlisting>
return;   -- Executes the statement
SKIP;     -- Doesn't execute the statement
MODIFY; -- Says it modified a NEW row
</programlisting>
d533 2
a534 2
Here is an example of a trigger function, illustrating some of the
above.
d537 2
a538 2
        i int,
        v varchar
d542 2
a543 2
    if (($_TD->{new}{i}>=100) || ($_TD->{new}{i}<=0)) {
        return "SKIP";   # Skip INSERT/UPDATE command
d546 1
a546 1
        return "MODIFY"; # Modify tuple and proceed INSERT/UPDATE command
d548 1
a548 1
        return;      # Proceed INSERT/UPDATE command
d552 3
a554 2
CREATE TRIGGER "test_valid_id_trig" BEFORE INSERT OR UPDATE ON test
FOR EACH ROW EXECUTE PROCEDURE "valid_id"();
d576 1
a576 1
      <application>Full SPI</application> is not yet implemented.
d579 1
d581 7
a587 7
      <para>
        In the current implementation, if you are fetching or
        returning very large datasets, you should be aware that these
        will all go into memory.  Future features will help with this.
        In the meantime, we suggest that you not use pl/perl if you
        will fetch or return very large result sets.
      </para>
a588 1

@


2.28
log
@Some editorializing on the docs for the dollar-quoting feature: fix
grammar, don't drop discussions into the middle of unrelated discussions,
etc.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/plperl.sgml,v 2.27 2004/08/18 03:37:56 momjian Exp $
d263 3
a265 1
   Here is an example of a PL/Perl function returning a rowset of a row type:
d310 4
a313 1
  Here is an example of a PL/Perl function returning a rowset of a composite type.
@


2.27
log
@The enclose patch clarifies and makes a more useful example for the
Global Values in PL/Perl section of the documents.

David Fetter
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/plperl.sgml,v 2.26 2004/07/21 20:44:52 momjian Exp $
d50 1
a50 2
CREATE FUNCTION <replaceable>funcname</replaceable>
(<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS $$
d54 1
a54 6
   The body of the function is ordinary Perl code. Since the body of
   the function is treated as a string by
   <productname>PostgreSQL</productname>, it can be specified using
   dollar quoting (as shown above), or via the legacy single quote
   syntax (see <xref linkend="sql-syntax-strings"> for more
   information).
d57 11
@


2.26
log
@Please find enclosed a patch that matches the PL/Perl documentation
(fairly closely, I hope) to the current PL/Perl implementation.

David Fetter
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/plperl.sgml,v 2.25 2004/07/21 20:34:43 momjian Exp $
d320 1
a320 2
  You can use the %_SHARED to store data between function calls.  WHY
IS THIS A HASH, AND NOT A HASH REF?
d325 6
a330 3
CREATE OR REPLACE FUNCTION set_var(TEXT) RETURNS TEXT AS $$
    $_SHARED{first} = 'Hello, PL/Perl!';
    return 'ok';
d333 2
a334 2
CREATE OR REPLACE FUNCTION get_var() RETURNS text AS $$
    return $_SHARED{first};
d337 2
a338 2
SELECT set_var('hello plperl');
SELECT get_var();
@


2.25
log
@Back out pg_autovacuum commit after cvs clean failure causes commit.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/plperl.sgml,v 2.23 2004/05/16 23:22:06 neilc Exp $
d37 4
a40 3
    PL/Perl during the installation process.  (Refer to the installation
    instructions for more information.)  Users of binary packages
    might find PL/Perl in a separate subpackage.
d58 1
a58 1
   dollar quoting (as shown above), or via the usual single quote
d83 16
a98 13
   If an SQL null value<indexterm><primary>null value</><secondary
   sortas="PL/Perl">in PL/Perl</></indexterm> is passed to a function,
   the argument value will appear as <quote>undefined</> in Perl.  The
   above function definition will not behave very nicely with null
   inputs (in fact, it will act as though they are zeroes).  We could
   add <literal>STRICT</> to the function definition to make
   <productname>PostgreSQL</productname> do something more reasonable:
   if a null value is passed, the function will not be called at all,
   but will just return a null result automatically.  Alternatively,
   we could check for undefined inputs in the function body.  For
   example, suppose that we wanted <function>perl_max</function> with
   one null and one non-null argument to return the non-null argument,
   rather than a null value:
d115 3
a117 3
   As shown above, to return an SQL null value from a PL/Perl
   function, return an undefined value.  This can be done whether the
   function is strict or not.
d134 1
a134 1
    return $emp->{'basesalary'} + $emp->{'bonus'};
d142 1
a142 2
   There is currently no support for returning a composite-type result
   value.
a144 25
  <tip>
   <para>
    Because the function body is passed as an SQL string literal to
    <command>CREATE FUNCTION</command>, you have to use dollar quoting
    or escape single quotes and backslashes within your Perl source,
    typically by doubling them.  Another possible approach is to avoid
    writing single quotes by using Perl's extended quoting operators
    (<literal>q[]</literal>, <literal>qq[]</literal>,
    <literal>qw[]</literal>).
   </para>
  </tip>
 </sect1>

 <sect1 id="plperl-data">
  <title>Data Values in PL/Perl</title>

  <para>
   The argument values supplied to a PL/Perl function's code are
   simply the input arguments converted to text form (just as if they
   had been displayed by a <command>SELECT</command> statement).
   Conversely, the <literal>return</> command will accept any string
   that is acceptable input format for the function's declared return
   type.  So, the PL/Perl programmer can manipulate data values as if
   they were just text.
  </para>
d152 1
a152 1
   an experimental module <ulink
d155 1
a155 1
   mirror sites</ulink>). This module makes available a
d159 1
d163 1
a163 1
   PL/Perl itself presently provides only one additional Perl command:
d168 4
d176 47
d239 105
d404 60
d466 1
a466 1
  <title>Missing Features</title>
d476 1
a476 2
      are anonymous subroutines inside Perl).  There's presently no
      way for them to share global variables, either.
d482 1
a482 3
      PL/Perl cannot be used to write trigger
      functions.<indexterm><primary>trigger</><secondary>in
      PL/Perl</></indexterm>
a484 1

d486 7
a492 5
     <para>
      <application>DBD::PgSPI</applicatioN> or similar capability
      should be integrated into the standard
      <productname>PostgreSQL</productname> distribution.
     </para>
d494 1
@


2.24
log
@lease find enclosed a patch that matches the PL/Perl documentation
(fairly closely, I hope) to the current PL/Perl implementation.

David Fetter
@
text
@d37 3
a39 4
    PL/Perl during the installation process.  (Refer to <xref
    linkend="install-short"> for more information.)  Users of
    binary packages might find PL/Perl in a separate subpackage.

d57 1
a57 1
   dollar quoting (as shown above), or via the legacy single quote
d82 13
a94 16
   If an SQL <literal>NULL</literal> value<indexterm><primary>null
    value</><secondary sortas="PL/Perl">in PL/Perl</></indexterm> is
    passed to a function, the argument value will appear as
    <quote>undefined</> in Perl.  The above function definition will not
    behave very nicely with <literal>NULL</literal> inputs (in fact, it
    will act as though they are zeroes).  We could add <literal>STRICT</>
    to the function definition to make
    <productname>PostgreSQL</productname> do something more reasonable: if
    a <literal>NULL</literal> value is passed, the function will not be
    called at all, but will just return a <literal>NULL</literal> result
    automatically.  Alternatively, we could check for undefined inputs in
    the function body.  For example, suppose that we wanted
    <function>perl_max</function> with one <literal>NULL</literal> and one
    non-<literal>NULL</literal> argument to return the
    non-<literal>NULL</literal> argument, rather than a
    <literal>NULL</literal> value:
d111 3
a113 3
    As shown above, to return an SQL <literal>NULL</literal> value from
    a PL/Perl function, return an undefined value.  This can be done
    whether the function is strict or not.
d130 1
a130 1
    return $emp->{basesalary} + $emp->{bonus};
d138 2
a139 1
   There is now support for returning a composite-type result value.
d142 25
d174 1
a174 1
   spi_exec_query, or via an experimental module <ulink
d177 1
a177 1
   mirror sites</ulink>).  This module makes available a
a180 1

d184 1
a184 1
   PL/Perl itself presently provides two additional Perl commands:
a188 4
      <primary>spi_exec_query</primary>
      <secondary>in PL/Perl</secondary>
     </indexterm>
     <indexterm>
a192 47
     <term><function>spi_exec_query(</> [ <replaceable>SELECT query</replaceable> [, <replaceable>max_rows</replaceable>]] | [<replaceable>non-SELECT query</replaceable>] ) </term>
     <listitem>
       <para>
        Here is an example of a SELECT query with the optional maximum
number of rows.
<programlisting>
$rv = spi_exec_query('SELECT * from my_table', 5);
</programlisting>

This returns up to 5 rows from my_table.
       </para>
       <para>
If my_table has a column my_column, it would be accessed as
<programlisting>
$foo = $rv->{rows}[$i]->{my_column};
</programlisting>
       </para>
       <para>
The number of rows actually returned would be:
<programlisting>
$nrows = @@{$rv->{rows}};
</programlisting>
       </para>
       <para>
Here is an example using a non-SELECT statement.
<programlisting>
$query = "INSERT INTO my_table VALUES (1, 'test')";
$rv = spi_exec_query($query);
</programlisting>

You can then access status (SPI_OK_INSERT, e.g.) like this.
<programlisting>
$res = $rv->{status};
</programlisting>

       </para>
       <para>
To get the rows affected, do:
<programlisting>
$nrows = $rv->{rows};
</programlisting>
       </para>

     </listitem>

    </varlistentry>
    <varlistentry>
a208 105
 <sect1 id="plperl-data">
  <title>Data Values in PL/Perl</title>

  <para>
   The argument values supplied to a PL/Perl function's code are
   simply the input arguments converted to text form (just as if they
   had been displayed by a <command>SELECT</command> statement).
   Conversely, the <literal>return</> command will accept any string
   that is acceptable input format for the function's declared return
   type.  So, the PL/Perl programmer can manipulate data values as if
   they were just text.
  </para>

  <para>
   PL/Perl can now return rowsets and composite types, and rowsets of
composite types.
  </para>

  <para>
   Here is an example of a PL/Perl function returning a rowset of a row type:
<programlisting>
CREATE TABLE test (
       i int,
       v varchar
);

INSERT INTO test (i, v) VALUES (1,'first line');
INSERT INTO test (i, v) VALUES (2,'second line');
INSERT INTO test (i, v) VALUES (3,'third line');
INSERT INTO test (i, v) VALUES (4,'immortal');

create function test_munge() returns setof test language plperl as $$
    my $res = [];
    my $rv = spi_exec_query('select i,v from test;');
    my $status = $rv->{status};
    my $rows = @@{$rv->{rows}};
    my $processed = $rv->{processed};
    foreach my $rn (0..$rows-1) {
        my $row = $rv->{rows}[$rn];
        $row->{i} += 200 if defined($row->{i});
        $row->{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row->{v}));
        push @@$res,$row;
    }
    return $res;
$$;

select * from test_munge();
</programlisting>
  </para>

  <para>
   Here is an example of a PL/Perl function returning a composite type:
  <programlisting>
CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);

CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$

 return {f2 => 'hello', f1 => 1, f3 => 'world'};

$$ LANGUAGE plperl;
  </programlisting>
  </para>

  <para>
  Here is an example of a PL/Perl function returning a rowset of a composite type.
  <programlisting>
CREATE TYPE testsetperl AS (f1 integer, f2 text, f3 text);

CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testsetperl AS $$
 return[
        {f1 => 1, f2 => 'hello', f3 =>  'world'},
        {f1 => 2, f2 => 'hello', f3 =>  'postgres'},
        {f1 => 3, f2 => 'hello', f3 =>  'plperl'}
       ];
$$  LANGUAGE plperl;
  </programlisting>
  </para>
 </sect1>
 <sect1 id="plperl-global">
  <title>Global Values in PL/Perl</title>
  <para>
  You can use the %_SHARED to store data between function calls.  WHY
IS THIS A HASH, AND NOT A HASH REF?
  </para>
  <para>
For example:
<programlisting>
CREATE OR REPLACE FUNCTION set_var(TEXT) RETURNS TEXT AS $$
    $_SHARED{first} = 'Hello, PL/Perl!';
    return 'ok';
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION get_var() RETURNS text AS $$
    return $_SHARED{first};
$$ LANGUAGE plperl;

SELECT set_var('hello plperl');
SELECT get_var();
</programlisting>

  </para>
   

 </sect1>

a268 60
 <sect1 id="plperl-triggers">
  <title>PL/Perl Triggers</title>

  <para>
   PL/Perl can now be used to write trigger functions using the
<varname>$_TD</varname> hash reference.
  </para>

  <para>
   Some useful parts of the $_TD hash reference are:

<programlisting>
$_TD->{new}{foo} # NEW value of column foo
$_TD->{old}{bar} # OLD value of column bar
$_TD{name}       # Name of the trigger being called
$_TD{event}      # INSERT, UPDATE, DELETE or UNKNOWN
$_TD{when}       # BEFORE, AFTER or UNKNOWN
$_TD{level}      # ROW, STATEMENT or UNKNOWN
$_TD{relid}      # Relation ID of the table on which the trigger occurred.
$_TD{relname}    # Name of the table on which the trigger occurred.
@@{$_TD{argv}}    # Array of arguments to the trigger function.  May be empty.
$_TD{argc}       # Number of arguments to the trigger.  Why is this here?
</programlisting>

  </para>

  <para>
   Triggers can return one of the following:
<programlisting>
return;   -- Executes the statement
SKIP;     -- Doesn't execute the statement
MODIFY; -- Says it modified a NEW row
</programlisting>
  </para>

  <para>
Here is an example of a trigger function, illustrating some of the
above.
<programlisting>
CREATE TABLE test (
        i int,
        v varchar
);

CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS $$
    if (($_TD->{new}{i}>=100) || ($_TD->{new}{i}<=0)) {
        return "SKIP";   # Skip INSERT/UPDATE command
    } elsif ($_TD->{new}{v} ne "immortal") {
        $_TD->{new}{v} .= "(modified by trigger)";
        return "MODIFY"; # Modify tuple and proceed INSERT/UPDATE command
    } else {
        return;      # Proceed INSERT/UPDATE command
    }
$$ LANGUAGE plperl;

CREATE TRIGGER "test_valid_id_trig" BEFORE INSERT OR UPDATE ON test
FOR EACH ROW EXECUTE PROCEDURE "valid_id"();
</programlisting>
  </para>
 </sect1>
d271 1
a271 1
  <title>Limitations and Missing Features</title>
d281 2
a282 1
      are anonymous subroutines inside Perl).
d288 3
a290 1
      <application>Full SPI</application> is not yet implemented.
d293 1
d295 5
a299 7
      <para>
        In the current implementation, if you are fetching or
        returning very large datasets, you should be aware that these
        will all go into memory.  Future features will help with this.
        In the meantime, we suggest that you not use pl/perl if you
        will fetch or return very large result sets.
      </para>
a300 1

@


2.23
log
@Add documentation for the new "dollar quoting" feature, and update existing
examples to use dollar quoting when appropriate. Original patch from David
Fetter, additional work and editorializing by Neil Conway.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/plperl.sgml,v 2.22 2003/12/14 00:10:32 neilc Exp $
d37 4
a40 3
    PL/Perl during the installation process.  (Refer to the installation
    instructions for more information.)  Users of binary packages
    might find PL/Perl in a separate subpackage.
d58 1
a58 1
   dollar quoting (as shown above), or via the usual single quote
d83 16
a98 13
   If an SQL null value<indexterm><primary>null value</><secondary
   sortas="PL/Perl">in PL/Perl</></indexterm> is passed to a function,
   the argument value will appear as <quote>undefined</> in Perl.  The
   above function definition will not behave very nicely with null
   inputs (in fact, it will act as though they are zeroes).  We could
   add <literal>STRICT</> to the function definition to make
   <productname>PostgreSQL</productname> do something more reasonable:
   if a null value is passed, the function will not be called at all,
   but will just return a null result automatically.  Alternatively,
   we could check for undefined inputs in the function body.  For
   example, suppose that we wanted <function>perl_max</function> with
   one null and one non-null argument to return the non-null argument,
   rather than a null value:
d115 3
a117 3
   As shown above, to return an SQL null value from a PL/Perl
   function, return an undefined value.  This can be done whether the
   function is strict or not.
d134 1
a134 1
    return $emp->{'basesalary'} + $emp->{'bonus'};
d142 1
a142 2
   There is currently no support for returning a composite-type result
   value.
a144 25
  <tip>
   <para>
    Because the function body is passed as an SQL string literal to
    <command>CREATE FUNCTION</command>, you have to use dollar quoting
    or escape single quotes and backslashes within your Perl source,
    typically by doubling them.  Another possible approach is to avoid
    writing single quotes by using Perl's extended quoting operators
    (<literal>q[]</literal>, <literal>qq[]</literal>,
    <literal>qw[]</literal>).
   </para>
  </tip>
 </sect1>

 <sect1 id="plperl-data">
  <title>Data Values in PL/Perl</title>

  <para>
   The argument values supplied to a PL/Perl function's code are
   simply the input arguments converted to text form (just as if they
   had been displayed by a <command>SELECT</command> statement).
   Conversely, the <literal>return</> command will accept any string
   that is acceptable input format for the function's declared return
   type.  So, the PL/Perl programmer can manipulate data values as if
   they were just text.
  </para>
d152 1
a152 1
   an experimental module <ulink
d155 1
a155 1
   mirror sites</ulink>). This module makes available a
d159 1
d163 1
a163 1
   PL/Perl itself presently provides only one additional Perl command:
d168 4
d176 47
d239 105
d404 60
d466 1
a466 1
  <title>Missing Features</title>
d476 1
a476 2
      are anonymous subroutines inside Perl).  There's presently no
      way for them to share global variables, either.
d482 1
a482 3
      PL/Perl cannot be used to write trigger
      functions.<indexterm><primary>trigger</><secondary>in
      PL/Perl</></indexterm>
a484 1

d486 7
a492 5
     <para>
      <application>DBD::PgSPI</applicatioN> or similar capability
      should be integrated into the standard
      <productname>PostgreSQL</productname> distribution.
     </para>
d494 1
@


2.22
log
@This patch makes some improvements and adds some additional detail
to the documentation on routine database maintainence activities.
I also corrected a bunch of SGML markup.
@
text
@d2 1
a2 1
$PostgreSQL: pgsql-server/doc/src/sgml/plperl.sgml,v 2.21 2003/11/29 19:51:37 pgsql Exp $
d49 2
a50 1
CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS '
d52 1
a52 1
' LANGUAGE plperl;
d54 6
a59 1
   The body of the function is ordinary Perl code.
d74 1
a74 1
CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS '
d77 1
a77 1
' LANGUAGE plperl;
d97 1
a97 1
CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS '
d106 1
a106 1
' LANGUAGE plperl;
d128 1
a128 1
CREATE FUNCTION empcomp(employee) RETURNS integer AS '
d130 2
a131 2
    return $emp->{''basesalary''} + $emp->{''bonus''};
' LANGUAGE plperl;
d145 6
a150 6
    <command>CREATE FUNCTION</command>, you have to escape single
    quotes and backslashes within your Perl source, typically by
    doubling them as shown in the above example.  Another possible
    approach is to avoid writing single quotes by using Perl's
    extended quoting operators (<literal>q[]</literal>,
    <literal>qq[]</literal>, <literal>qw[]</literal>).
d235 1
a235 1
CREATE FUNCTION badfunc() RETURNS integer AS '
d239 1
a239 1
' LANGUAGE plperl;
@


2.21
log
@
$Header: -> $PostgreSQL Changes ...
@
text
@d2 1
a2 1
$PostgreSQL: /cvsroot/pgsql-server/doc/src/sgml/plperl.sgml,v 2.20 2003/08/31 17:32:19 petere Exp $
d155 1
a155 1
   had been displayed by a <literal>SELECT</literal> statement).
@


2.20
log
@Add/edit index entries.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/plperl.sgml,v 2.19 2003/04/07 01:29:25 petere Exp $
@


2.20.2.1
log
@Abandon the use of Perl's Safe.pm to enforce restrictions in plperl, as it is
fundamentally insecure. Instead apply an opmask to the whole interpreter that
imposes restrictions on unsafe operations. These restrictions are much harder
to subvert than is Safe.pm, since there is no container to be broken out of.
Backported to release 7.4.

In releases 7.4, 8.0 and 8.1 this also includes the necessary backporting of
the two interpreters model for plperl and plperlu adopted in release 8.2.

In versions 8.0 and up, the use of Perl's POSIX module to undo its locale
mangling on Windows has become insecure with these changes, so it is
replaced by our own routine, which is also faster.

Nice side effects of the changes include that it is now possible to use perl's
"strict" pragma in a natural way in plperl, and that perl's $a and
$b variables now work as expected in sort routines, and that function
compilation is significantly faster.

Tim Bunce and Andrew Dunstan, with reviews from Alex Hunsaker and
Alexey Klyukin.

Security: CVE-2010-1169
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.20 2003/08/31 17:32:19 petere Exp $
d262 1
a262 20

  <note>
    <para>
          For security reasons, to stop a leak of privileged operations from
      <application>PL/PerlU</> to <application>PL/Perl</>, these two languages
          have to run in separate instances of the Perl interpreter. If your
          Perl installation has been appropriately compiled, this is not a problem.
          However, not all installations are compiled with the requisite flags.
          If <productname>PostgreSQL</> detects that this is the case then it will
          not start a second interpreter, but instead create an error. In
          consequence, in such an installation, you cannot use both 
          <application>PL/PerlU</> and <application>PL/Perl</> in the same backend
          process. The remedy for this is to obtain a Perl installation created
          with the appropriate flags, namely either <literal>usemultiplicity</> or
          both <literal>usethreads</> and <literal>useithreads</>. 
          For more details,see the <literal>perlembed</> manual page.
    </para>
  </note>
  
</sect1>
@


2.19
log
@General editing
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/plperl.sgml,v 2.18 2002/09/21 18:32:53 petere Exp $
d76 6
a81 5
   If an SQL null value is passed to a function, the argument value
   will appear as <quote>undefined</> in Perl.  The above function
   definition will not behave very nicely with null inputs (in fact,
   it will act as though they are zeroes).  We could add
   <literal>STRICT</> to the function definition to make
d174 1
a174 1
   with normal <acronym>DBI</> syntax.
d184 1
a184 1
      <secondary>PL/Perl</secondary>
d206 5
d240 8
a247 7
   restricted.  For example, one might want a Perl function that
   sends mail.  To handle these cases, PL/Perl can also be installed
   as an <quote>untrusted</> language (usually called
   <application>PL/PerlU</application>).  In this case the full Perl language is
   available.  If the <command>createlang</command> program is used to
   install the language, the language name <literal>plperlu</literal>
   will select the untrusted PL/Perl variant.
d282 3
a284 1
      PL/Perl cannot be used to write trigger functions.
@


2.19.2.1
log
@Update this branch to match CVS head, includes WIN32 improvements.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/plperl.sgml,v 2.20 2003/08/31 17:32:19 petere Exp $
d76 5
a80 6
   If an SQL null value<indexterm><primary>null value</><secondary
   sortas="PL/Perl">in PL/Perl</></indexterm> is passed to a function,
   the argument value will appear as <quote>undefined</> in Perl.  The
   above function definition will not behave very nicely with null
   inputs (in fact, it will act as though they are zeroes).  We could
   add <literal>STRICT</> to the function definition to make
d173 1
a173 1
   with normal <acronym>DBI</> syntax.<indexterm><primary>DBI</></indexterm>
d183 1
a183 1
      <secondary>in PL/Perl</secondary>
a204 5
  <indexterm zone="plperl-trusted">
   <primary>trusted</primary>
   <secondary>PL/Perl</secondary>
  </indexterm>

d234 7
a240 8
   restricted.  For example, one might want a Perl function that sends
   mail.  To handle these cases, PL/Perl can also be installed as an
   <quote>untrusted</> language (usually called
   <application>PL/PerlU</application><indexterm><primary>PL/PerlU</></indexterm>).
   In this case the full Perl language is available.  If the
   <command>createlang</command> program is used to install the
   language, the language name <literal>plperlu</literal> will select
   the untrusted PL/Perl variant.
d275 1
a275 3
      PL/Perl cannot be used to write trigger
      functions.<indexterm><primary>trigger</><secondary>in
      PL/Perl</></indexterm>
@


2.18
log
@Add more appropriate markup.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/plperl.sgml,v 2.17 2002/09/18 20:09:32 petere Exp $
d37 2
a38 2
    PL/Perl during the installation process (refer to the installation
    instructions for more information).  Users of binary packages
d60 6
a65 2
   evaluated in the function.  For example, a function returning the
   greater of two integer values could be defined as:
d152 1
a152 1
   The argument values supplied to a PL/Perl function's script are
d213 2
a214 2
   database backend process or to gain OS-level access with the
   permissions of the <productname>PostgreSQL</productname> user ID,
d234 1
a234 1
   restricted --- for example, one might want a Perl function that
d262 1
a262 1
   would make welcome contributions:
@


2.17
log
@Update installation instructions and put mostly everything in one place.
Also, some editing in PL/Perl and PL/Python chapters.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql-server/doc/src/sgml/plperl.sgml,v 2.16 2002/03/06 19:05:57 momjian Exp $
d165 1
a165 1
   (also available at <ulink url="http://www.cpan.org/SITES.html">CPAN
d233 1
a233 1
   <quote>PL/PerlU</quote>).  In this case the full Perl language is
d240 1
a240 1
   The writer of a PL/PerlU function must take care that the function
@


2.16
log
@Update docs for new stored procedure error levels.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.15 2002/01/25 19:13:15 tgl Exp $
d17 3
a19 48
   PL/Perl is a loadable procedural language
   that enables the <ulink url="http://www.perl.com">Perl</ulink> programming
   language to be used to write 
   <productname>PostgreSQL</productname> functions.
  </para>

  <!-- **** PL/Perl overview **** -->

  <sect1 id="plperl-overview">
   <title>Overview</title>

   <para>
    Normally, PL/Perl is installed as a <quote>trusted</> programming
    language named <literal>plperl</>.  In this setup, certain Perl
    operations are disabled to preserve security.  In general, the operations
    that are restricted are those that interact with the environment. This
    includes file handle operations, <literal>require</literal>, and
    <literal>use</literal> (for external modules).
    There is no way to access internals of the
    database backend or to gain OS-level access under the permissions of the
    <productname>PostgreSQL</productname> user ID, as a C function can do.
    Thus, any unprivileged database user may be
    permitted to use this language.
   </para>
   <para>
    Sometimes it is desirable to write Perl functions that are not restricted
    --- for example, one might want a Perl function that sends
    mail.  To handle these cases, PL/Perl can also be installed as an
    <quote>untrusted</> language (usually named <literal>plperlu</>).
    In this case the full Perl language is available.  The writer of a PL/PerlU
    function must take care that the function cannot be used to do anything
    unwanted, since it will be able to do anything that could be done by
    a user logged in as the database administrator.  Note that the database
    system allows only database superusers to create functions in untrusted
    languages.
   </para>
 </sect1>

 <sect1 id="plperl-install">
  <title>Building and Installing PL/Perl</title>

  <para>
   If the <option>--with-perl</option> option was supplied to the
   <indexterm><primary><filename>configure</filename></primary></indexterm>
   <filename>configure</filename> script,
   the <productname>PostgreSQL</productname> build process will attempt to
   build the PL/Perl shared library and install it in the 
   <productname>PostgreSQL</productname> library directory.
d23 2
a24 18
   On most platforms, since PL/Perl is a shared library, the
   <indexterm><primary>libperl</primary></indexterm>
   <filename>libperl</filename> library must be a shared library also.
   At the time of this writing, this is almost never the case in prebuilt
   Perl packages.  If this difficulty arises in your situation, a
   message like this will appear during the build to point out this
   fact:
<screen>
<computeroutput>
*** Cannot build PL/Perl because libperl is not a shared library.
*** You might have to rebuild your Perl installation.  Refer to
*** the documentation for details.
</computeroutput>
</screen>
   If you see this, you will have to re-build and install
   <productname>Perl</productname> manually to be able to build
   PL/Perl.  During the configuration process for
   <productname>Perl</productname>, request a shared library.
a26 20
  <para>
   After having reinstalled Perl, change to the directory
   <filename>src/pl/plperl</filename> in the
   <productname>PostgreSQL</productname> source tree and issue the commands
<programlisting>
gmake clean
gmake all
gmake install
</programlisting>
   to complete the build and installation of the PL/Perl shared library.
  </para>

   <para>
    To install
    PL/Perl and/or PL/PerlU in a particular database, use the
    <filename>createlang</filename> script, for example
    <literal>createlang plperl <replaceable>dbname</></literal> or
    <literal>createlang plperlu <replaceable>dbname</></literal>.
   </para>

a32 1
  </sect1>
d34 8
a41 1
  <!-- **** PL/Perl description **** -->
d43 2
a44 2
  <sect1 id="plperl-description">
   <title>Description</title>
d46 3
a48 7
   <sect2>
    <title>PL/Perl Functions and Arguments</title>

    <para>
     To create a function in the PL/Perl language, use the standard syntax

     <programlisting>
d52 3
a54 1
     </programlisting>
d56 6
a61 11
     PL/PerlU is the same, except that the language should be specified as
     <literal>plperlu</>.
    </para>

    <para>
     The body of the function is ordinary Perl code.  Arguments and
     results are handled as in any other Perl subroutine: arguments
     are passed in <varname>@@_</varname>, and a result value is returned
     with <literal>return</> or as the last expression evaluated in the
     function.  For example, a function
     returning the greater of two integer values could be defined as:
d63 1
a63 1
     <programlisting>
d68 2
a69 1
     </programlisting>
d71 13
a83 11
     If a NULL is passed to a function, the argument value will appear
     as <quote>undefined</> in Perl.  The above function definition will
     not behave very nicely with NULL inputs (in fact, it will act as
     though they are zeroes).  We could add <literal>WITH (isStrict)</>
     to the function definition to make <productname>PostgreSQL</productname>
     do something more reasonable: if a NULL is passed, the
     function will not be called at all, but will just return a NULL
     result automatically.  Alternatively, we could check for undefined
     inputs in the function body.  For example, suppose that we wanted perl_max
     with one null and one non-null argument to return the non-null
     argument, rather than NULL:
d85 1
a85 1
     <programlisting>
d96 2
a97 2
     </programlisting>
    </para>
d99 10
a108 10
    <para>
     As shown above,
     to return a NULL from a PL/Perl function, return an undefined
     value.  This can be done whether the function is strict or not.
    </para>

    <para>
     Composite-type arguments are passed to the function as references to
     hashes.  The keys of the hash are the attribute names of the composite
     type.  Here is an example:
d110 1
a110 1
     <programlisting>
d123 2
a124 2
     </programlisting>
    </para>
d126 4
a129 4
    <para>
     There is not currently any support for returning a composite-type
     result value.
    </para>
d135 5
a139 5
    quotes and backslashes within your Perl source, typically by doubling them
    as shown in the above example.  Another possible approach is to
    avoid writing single quotes by using Perl's extended quoting functions
    (<literal>q[]</literal>, <literal>qq[]</literal>,
    <literal>qw[]</literal>).
d142 72
d227 1
d229 8
a236 2
   Note that if the same function was created by a superuser using language 
   <literal>plperlu</>, execution would succeed.
d239 7
a245 1
   </sect2>
d247 5
a251 2
   <sect2>
    <title>Data Values in PL/Perl</title>
d253 2
a254 8
    <para>
     The argument values supplied to a PL/Perl function's script are simply
     the input arguments converted to text form (just as if they had been
     displayed by a SELECT statement).  Conversely, the <literal>return</>
     command will accept any string that is acceptable input format for
     the function's declared return type.  So, the PL/Perl programmer can
     manipulate data values as if they were just text.
    </para>
d256 3
a258 4
   </sect2>

   <sect2>
    <title>Database Access from PL/Perl</title>
d260 23
a282 9
  <para>
   Access to the database itself from your Perl function can be done via
   an experimental module <ulink
   url="http://www.cpan.org/modules/by-module/DBD/APILOS/"><literal>DBD::PgSPI</literal></ulink>
   (also available at <ulink url="http://www.cpan.org/SITES.html">CPAN
   mirror sites</ulink>). This module makes available a
   <acronym>DBI</>-compliant database-handle named
   <varname>$pg_dbh</varname> that can be used to perform queries
   with normal <acronym>DBI</> syntax.
d284 1
d286 1
a286 48
    <para>
     PL/Perl itself presently provides only one additional Perl command:
    </para>

    <variablelist>
     <varlistentry>
      <indexterm>
       <primary>elog</primary>
      </indexterm>
      <term><function>elog</> <replaceable>level</replaceable>, <replaceable>msg</replaceable></term>
      <listitem>
       <para>
	Emit a log or error message. Possible levels are
	<literal>DEBUG</>, <literal>LOG</>, <literal>INFO</>,
	<literal>NOTICE</>, <literal>WARNING</>, and <literal>ERROR</>.
	<literal>ERROR</> raises an error condition: further execution
	of the function is abandoned, and the current transaction is
	aborted.
       </para>
      </listitem>
     </varlistentry>

    </variablelist>

   </sect2>

   <sect2>
    <title>Missing Features</title>

    <para>
     PL/Perl functions cannot call each other directly (because they
     are anonymous subroutines inside Perl).  There's presently
     no way for them to share global variables, either.
    </para>

    <para>
     PL/Perl cannot currently be used to write trigger functions.
    </para>

    <para>
     DBD::PgSPI or similar capability should be integrated
     into the standard <productname>PostgreSQL</productname> distribution.
    </para>

   </sect2>

  </sect1>
 </chapter>
@


2.15
log
@Overhaul plperl documentation.
@
text
@d2 1
a2 1
$Header$
d281 6
a286 7
	Emit a log or error message. Possible levels are <literal>DEBUG</>,
	<literal>NOTICE</>, and <literal>ERROR</>.
	<literal>DEBUG</> and <literal>NOTICE</> simply emit the given message
	into the postmaster log (and send it to the client too, in the case of
	<literal>NOTICE</>).  <literal>ERROR</> raises an error condition:
	further execution of the function is abandoned, and the current
	transaction is aborted.
@


2.14
log
@Point to main CPAN site, and reword a little.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.13 2002/01/08 05:39:26 momjian Exp $
d5 2
a6 2
<chapter id="plperl">
 <title>PL/Perl - Perl Procedural Language</title>
d8 45
a52 34
 <indexterm zone="plperl">
  <primary>PL/Perl</primary>
 </indexterm>

 <indexterm zone="plperl">
  <primary>Perl</primary>
 </indexterm>

 <sect1 id="intro">
  <title>Introduction</title>

 <para>
  PL/Perl allows you to write functions in the <ulink
  url="http://www.perl.com">Perl</ulink> programming language that may
  be used in SQL queries as if they were built into
  <productname>PostgreSQL</productname>.
 </para>

 <para>
  The PL/Perl interpreter (when installed as trusted interpreter with 
  default name <literal>plperl</>) is a full Perl interpreter. However, certain
  operations have been disabled in order to maintain the security of
  the system.  In general, the operations that are restricted are
  those that interact with the environment. This includes file handle
  operations, <literal>require</literal>, and <literal>use</literal>
  (for external modules).  It should be noted that this security is
  not absolute. Indeed, several Denial-of-Service attacks are still
  possible - memory exhaustion and endless loops are two examples.

 </para>
 <para>
  When PL/Perl is installed as <quote>untrusted</> interpreter (with name <literal>plperlu</literal>),
  everything is permitted, and any Perl code can be loaded (by a superuser only).
 </para>
d56 1
a56 1
  <title>Building and Installing</title>
d59 1
a59 3
   In order to build and install PL/Perl if you are installing
   <productname>PostgreSQL</productname> from source then the
   <option>--with-perl</option> must be supplied to the
d61 8
a68 2
   <filename>configure</filename> script.  PL/Perl requires that, when
   <productname>Perl</productname> was installed, the
d70 3
a72 3
   <filename>libperl</filename> library was build as a shared object.
   At the time of this writing, this is almost never the case in the
   Perl packages that are distributed with the operating systems.  A
d82 1
a82 1
   Therefore it is likely that you will have to re-build and install
d84 2
a85 1
   PL/Perl.
d89 1
a89 2
   When you want to retry to build PL/Perl after having reinstalled
   Perl, then change to the directory
d97 1
d100 77
a176 15
  <para>
   The <command>createlang</command> command is used to install the
   language into a database.
<screen>
<prompt>$</prompt> <userinput>createlang plperl template1</userinput>
</screen>
   Alternatively, to create untrusted interpreter (where functions can only
be created by a superuser, but the functions are not restricted), use:
<screen>
<prompt>$</prompt> <userinput>createlang plperlu template1</userinput>
</screen>
   If it is installed into template1, all future databases will have
   the language installed automatically.
  </para>
 </sect1>
d178 10
a187 2
 <sect1 id="plperl-use">
  <title>Using PL/Perl</title>
d189 1
a189 3
  <para>
   Assume you have the following table:
<programlisting>
a194 13
</programlisting>

   In order to get the total compensation (base + bonus) we could
   define a function as follows:
<programlisting>
CREATE FUNCTION totalcomp(integer, integer) RETURNS integer
    AS 'return $_[0] + $_[1]'
    LANGUAGE plperl;
</programlisting>

   Notice that the arguments to the function are passed in
   <varname>@@_</varname> as might be expected.
  </para>
a195 10
  <para>
   We can now use our function like so:
<programlisting>
SELECT name, totalcomp(basesalary, bonus) FROM employee;
</programlisting>
  </para>

  <para>
   But, we can also pass entire tuples to our functions:
<programlisting>
d197 1
a197 1
    my $emp = shift;
d200 9
a208 5
</programlisting>
   A tuple is passed as a reference to a hash. The keys are the names
   of the fields in the tuples. The hash values are values of the
   corresponding fields in the tuple.
  </para>
d213 4
a216 3
    <command>CREATE FUNCTION</command> you have to escape single
    quotes within your Perl source, either by doubling them as shown
    above, or by using the extended quoting functions
d218 1
a218 2
    <literal>qw[]</literal>).  Backslashes must be escaped by doubling
    them.
a222 7
   The new function <function>empcomp</function> can be used like:
<programlisting>
SELECT name, empcomp(employee) FROM employee;
</programlisting>
  </para>

  <para>
d235 1
a235 1
   Note that if same function was created by superuser using language 
d238 20
d269 49
a317 2
 </sect1>
</chapter>
@


2.13
log
@Update bad URL's with good ones.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.12 2002/01/07 02:29:13 petere Exp $
d181 1
a181 1
   Access to database itself from your Perl function can be done via
d183 6
a188 5
   url="http://cpan.digisle.net/authors/id/A/AP/APILOS/"><literal>DBD::PgSPI</literal></ulink>
   (also on <ulink url="http://www.cpan.org">CPAN</ulink>). This
   module makes available a <acronym>DBI</>-compliant database-handle
   named <varname>$pg_dbh</varname>, and you can use that to perform
   queries with normal <acronym>DBI</> syntax.
@


2.12
log
@Editorial review
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.11 2001/11/21 05:53:41 thomas Exp $
d183 1
a183 1
   url="http://www.formenos.org/PgSPI/"><literal>DBD::PgSPI</literal></ulink>
@


2.11
log
@Deprecate 'current' for date/time input.
Fix up references to "PostgreSQL" rather than "Postgres". Was roughly
 evenly split between the two before. ref/ files not yet done.
@
text
@d2 1
a2 1
$Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.10 2001/09/10 21:58:47 petere Exp $
d16 3
d20 3
a22 2
  PL/Perl allows you to write functions in the Perl programming
  language that may be used in SQL queries as if they were built into
d28 1
a28 1
  default name <literal>plperl</>) interpreter is a full Perl interpreter. However, certain
d40 1
a40 1
  everything is permitted, and any Perl code can be loaded (by superuser only).
d42 1
d62 3
a64 4
*****
* Cannot build PL/Perl because libperl is not a shared library.
* Skipped.
*****
d91 1
a91 1
be created by superuser, but the functions are not restricted), use:
d106 1
a106 1
CREATE TABLE EMPLOYEE (
d118 1
a118 1
    LANGUAGE 'plperl';
d138 1
a138 1
' LANGUAGE 'plperl';
d158 1
a158 1
   The new function <function>empcomp</function> can used like:
d172 1
a172 1
' LANGUAGE 'plperl';
d175 2
a176 1

d181 7
a187 4
   Access to database itself from your Perl function can be done via 
   an experimental module <ulink url="http://www.formenos.org/PgSPI/"><literal>DBD::PgSPI</literal></ulink>. This module makes available a <acronym>DBI</>-compliant
   database-handle named <varname>$pg_dbh</varname>, and you can use that to make queries with
   normal <acronym>DBI</> syntax.
@


2.10
log
@Markup and spell-check run over Programmer's Guide (rather incomplete still).
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.9 2001/06/22 21:37:14 momjian Exp $
d19 1
a19 1
  <productname>Postgres</productname>.
d44 1
a44 1
   <productname>Postgres</productname> from source then the
d72 1
a72 1
   <productname>Postgres</productname> source tree and issue the commands
@


2.9
log
@Attached is documentation describing plperlu differences from plperl.

Alex Pilosov
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.8 2001/05/12 22:51:35 petere Exp $
d24 1
a24 1
  default name 'plperl') intepreter is a full Perl interpreter. However, certain
d27 1
a27 1
  those that interact with the environment. This includes filehandle
d35 2
a36 2
  When PL/Perl is installed as 'untrusted' interpreter (with name 'plperlu'),
  everything is permitted, and any perl code can be loaded (by superuser only).
d173 1
a173 1
   'plperlu', execution would succeed.
d176 4
a179 4
   Access to database itself from your perl function can be done via 
   an experimental module DBD::PgSPI, available at <ulink url="http://www.formenos.org/PgSPI/">this site</ulink>. This module makes available a DBI-compliant
   database-handle named $pg_dbh, and you can use that to make queries with
   normal DBI syntax.
@


2.8
log
@Add index.  Only some parts of the manual set have index entries so far...
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.7 2000/12/22 18:57:50 petere Exp $
d23 2
a24 1
  The PL/Perl intepreter is a full Perl interpreter. However, certain
d32 5
d86 5
d171 9
@


2.7
log
@Replace incorrect uses of 'which' with 'that'.  (so-called "wicked which")
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.6 2000/12/19 18:16:25 petere Exp $
d8 8
d40 1
d43 1
@


2.6
log
@Polish PL/Perl documentation.  The README file got shrunk to being a
pointer into the real documentation.
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.5 2000/09/29 20:21:34 petere Exp $
d10 1
a10 1
  language which may be used in SQL queries as if they were built into
d140 1
a140 1
   Here is an example of a function which will not work because file
@


2.5
log
@Add `id' attributes to all `chapter' and `sect1' tags, to generate useful
names for the HTML files (e.g., not x4856.htm).
@
text
@d2 1
a2 1
$Header: /home/projects/pgsql/cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.4 2000/05/09 18:30:43 momjian Exp $
d5 46
a50 2
 <chapter id="pl-perl">
  <title>PL/perl - Perl Procedural Language</title>
d53 9
a61 2
   This chapter describes how to compile, install and
   use PL/Perl.
a62 24
  <sect1 id="plperl-overview">
   <title>Overview</title>
   <para>
    PL/Perl allows you to write functions in the Perl scripting
    language which may be used in SQL queries as if they were 
    built into <productname>Postgres</productname>. 
   </para>
   <para>
    The PL/Perl intepreter is a full Perl interpreter. However,
    certain operations have been disabled in order to increase
    the security level of the system.
   </para>
   <para>
    In general, the operations that are restricted are those that
    interact with the environment. This includes filehandle operations,
    <literal>require</literal>, and <literal>use</literal> (for external
    modules).
   </para>
   <para>
    It should be noted that this security is not absolute. Indeed, several
    Denial-of-Service attacks are still possible - memory exhaustion and
    endless loops are two.
   </para>
  </sect1>
d64 10
a73 15
  <sect1 id="plperl-install">
   <title>Building and Installing</title>
   <para>
    Assuming that the <productname>Postgres</productname>
    source tree is rooted at $PGSRC, then the Pl/perl source
    code is located in $PGSRC/src/pl/plperl.
   </para>
   <para>
    To build, simply do the following:
    <programlisting>
cd $PGSRC/src/pl/plperl
perl Makefile.PL
make
    </programlisting>
   </para>
d75 2
a76 14
   <para>
    This will create a shared library file. On a Linux system, it will be
    named plperl.so. The extension may differ on other systems.
   </para>
   <para>
    The shared library should then be copied into the lib subdirectory of the
    postgres installation.
   </para>
   <para>
    The createlang command is used to install the language into a database.
    If it is installed into template1, all future databases will have the
    language installed automatically.
   </para>
  </sect1>
d78 3
a80 5
  <sect1 id="plperl-use">
   <title>Using PL/Perl</title>
   <para>
    Assume you have the following table:
    <programlisting>
d83 9
a91 8
    basesalary int4,
    bonus int4 );
    </programlisting>

    In order to get the total compensation (base + bonus) we could
    define a function as follows:
    <programlisting>
CREATE FUNCTION totalcomp(int4, int4) RETURNS int4
d94 25
a118 1
    </programlisting>
d120 1
a120 6
    Note that the arguments are passed to the function in
    <literal>@@_</literal> as might be expected. Also, because
    of the quoting rules for the SQL creating the function, you
    may find yourself using the extended quoting functions (qq[],
    q[], qw[]) more often that you are used to.
   </para>
d122 7
a128 4
    We may now use our function like so:
    <programlisting>
SELECT name, totalcomp(basesalary, bonus) from employee
    </programlisting>
d130 24
a153 20
   <para>
    But, we can also pass entire tuples to our function:
    <programlisting>
CREATE FUNCTION empcomp(employee) returns int4
    AS 'my $emp = shift;
        return $emp->{''basesalary''} + $emp->{''bonus''};'
    LANGUAGE 'plperl';
    </programlisting>
    A tuple is passed as a reference to hash. The keys are the names of
    fields in the tuples. The values are values of the corresponding
    field in the tuple.
   </para>
   <para>
    The new function <literal>empcomp</literal> can used like:
    <programlisting>
SELECT name, empcomp(employee) from employee;
    </programlisting>
   </para>
  </sect1>
 </chapter>
@


2.4
log
@More single-quote fixes.
@
text
@d2 1
a2 1
$Header: /usr/local/cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.3 2000/03/31 06:17:21 thomas Exp $
d12 1
a12 1
  <sect1>
d37 1
a37 1
  <sect1>
d68 1
a68 1
  <sect1>
@


2.3
log
@Use a uniform chapter title for all of the procedural languages.
@
text
@d2 1
a2 1
$Header: /usr/local/cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.2 2000/03/31 03:27:41 thomas Exp $
d104 1
a104 1
        return $emp->{'basesalary'} + $emp->{'bonus'};'
@


2.2
log
@Minor markup changes. Refer to (".../catalog") in the emacs hints.
@
text
@d2 1
a2 1
$Header$
d6 1
a6 1
  <title>Perl Procedural Language</title>
@


2.1
log
@Split off language-specific docs to their own chapters.
Add PL/perl docs from Mark Hollomon.
Put language-specific docs into the User's Guide, and move the rest
 to the Programmer's Guide.
@
text
@d1 4
d132 1
a132 1
sgml-local-catalogs:("/usr/lib/sgml/CATALOG")
@
