PL/Python3U allows writing PostgreSQL functions in Python 3. It is an untrusted language with full access to the Python ecosystem. Only superusers can create functions.
CREATEEXTENSIONplpython3u;-- Simple function
CREATEFUNCTIONpy_hello(nametext)RETURNStextLANGUAGEplpython3uAS$$returnf"Hello, {name}!"$$;SELECTpy_hello('world');-- Using Python standard library
CREATEFUNCTIONpy_sha256(datatext)RETURNStextLANGUAGEplpython3uAS$$importhashlibreturnhashlib.sha256(data.encode()).hexdigest()$$;-- Returning a composite type
CREATETYPEaddressAS(streettext,citytext,ziptext);CREATEFUNCTIONparse_address(rawtext)RETURNSaddressLANGUAGEplpython3uAS$$importrem=re.match(r'(.+),\s*(.+)\s+(\d{5})',raw)ifm:return(m.group(1),m.group(2),m.group(3))returnNone$$;-- Set-returning function
CREATEFUNCTIONpy_generate_dates(starttext,daysint)RETURNSSETOFdateLANGUAGEplpython3uAS$$fromdatetimeimportdatetime,timedeltad=datetime.strptime(start,'%Y-%m-%d')foriinrange(days):yield(d+timedelta(days=i)).strftime('%Y-%m-%d')$$;-- Database access via plpy
CREATEFUNCTIONpy_row_count(table_nametext)RETURNSbigintLANGUAGEplpython3uAS$$result=plpy.execute(f"SELECT count(*) AS cnt FROM {table_name}")returnresult[0]['cnt']$$;-- Using external packages (must be installed on the server)
CREATEFUNCTIONpy_parse_json(urltext)RETURNSjsonbLANGUAGEplpython3uAS$$importjson,urllib.requestresponse=urllib.request.urlopen(url)data=json.loads(response.read())returnjson.dumps(data)$$;