Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads
46.2. PL/Python Functions
Prev UpChapter 46. PL/Python - Python Procedural LanguageHome Next

46.2. PL/Python Functions

Functions in PL/Python are declared via the standardCREATE FUNCTION syntax:

CREATE FUNCTIONfuncname (argument-list)  RETURNSreturn-typeAS $$  # PL/Python function body$$ LANGUAGE plpythonu;

The body of a function is simply a Python script. When the function is called, its arguments are passed as elements of the listargs; named arguments are also passed as ordinary variables to the Python script. Use of named arguments is usually more readable. The result is returned from the Python code in the usual way, withreturn oryield (in case of a result-set statement). If you do not provide a return value, Python returns the defaultNone.PL/Python translates Python'sNone into the SQL null value. In a procedure, the result from the Python code must beNone (typically achieved by ending the procedure without areturn statement or by using areturn statement without argument); otherwise, an error will be raised.

For example, a function to return the greater of two integers can be defined as:

CREATE FUNCTION pymax (a integer, b integer)  RETURNS integerAS $$  if a > b:    return a  return b$$ LANGUAGE plpythonu;

The Python code that is given as the body of the function definition is transformed into a Python function. For example, the above results in:

def __plpython_procedure_pymax_23456():  if a > b:    return a  return b

assuming that 23456 is the OID assigned to the function byPostgreSQL.

The arguments are set as global variables. Because of the scoping rules of Python, this has the subtle consequence that an argument variable cannot be reassigned inside the function to the value of an expression that involves the variable name itself, unless the variable is redeclared as global in the block. For example, the following won't work:

CREATE FUNCTION pystrip(x text)  RETURNS textAS $$  x = x.strip()  # error  return x$$ LANGUAGE plpythonu;

because assigning tox makesx a local variable for the entire block, and so thex on the right-hand side of the assignment refers to a not-yet-assigned local variablex, not the PL/Python function parameter. Using theglobal statement, this can be made to work:

CREATE FUNCTION pystrip(x text)  RETURNS textAS $$  global x  x = x.strip()  # ok now  return x$$ LANGUAGE plpythonu;

But it is advisable not to rely on this implementation detail of PL/Python. It is better to treat the function parameters as read-only.


Prev Up Next
46.1. Python 2 vs. Python 3 Home 46.3. Data Values
epubpdf
Go to PostgreSQL 11
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp