Re: multiple CREATE FUNCTION AS items for PLs

From: Hannu Krosing <hannu(at)krosing(dot)net>
To: Peter Eisentraut <peter_e(at)gmx(dot)net>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: multiple CREATE FUNCTION AS items for PLs
Date: 2012-12-16 18:13:26
Message-ID: 50CE0F46.1000301@krosing.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 12/16/2012 07:37 AM, Peter Eisentraut wrote:
> I'm going to use PL/Python as an example, but I would also like to know
> if this could be applicable to other languages.
>
> When you do
>
> CREATE FUNCTION foo(...) ... LANGUAGE plpythonu
> AS $$
> source code here
> $$;
>
> it internally creates a "source file" that contains
>
> ---
> def __plpython_procedure_foo_12345():
> source code here
> ---
>
> It would be useful to be able to do something like this instead:
>
> ---
> some code here
>
> def __plpython_procedure_foo_12345():
> some more code here
> ---
>
> This would especially be useful for placing imports into the first part.
> While you can have them in the function definition, that means they are
> executed every time the function is called, which makes it much slower.
> Also, future imports are not possible this way.
>
> CREATE FUNCTION already supports multiple AS items. Currently, multiple
> AS items are rejected for all languages but C. I'd imagine lifting that
> restriction and leaving it up to the validator to check it. Then any
> language can accept two AS items if it wants and paste them together in
> whichever way it needs. (The probin/prosrc naming will then become more
> obsolete, but it's perhaps not worth changing anything about that.)
>
> So in practice this might look like this:
>
> CREATE FUNCTION foo(...) ... LANGUAGE plpythonu
> AS $$
> import x
> import y
> $$,
> $$
> real code here
> $$;
>
> Comments?
As an idea seems quite good, but maybe the "run once" part could use its
own keyword in the future, something like PREPARE or REQUIRE?

Or maye WITH to reuse a keyword

CREATE FUNCTION foo(...) ... LANGUAGE plpythonu
WITH -- this part is evaluated only once, in PLy_procedure_create
$$
import x
import y
$$
AS -- this is compiled in the same namespace as above
$$
<function body here>
$$;

WHile at it, why not also fix the functions to be real function
_with_ _real_ _arguments_ , not arguments-passed-in-as-globals

and at least we could call this function with its real name inside its own module
(stored global namespace) so we could easily do recursion

CREATE FUNCTION factorial(n bigint) returns bigint LANGUAGE plpythonu
AS $$
if n==0: return 1
return factorial(n-1) * n
$$;

----------------------
Hannu

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2012-12-16 18:20:53 Re: small pg_basebackup display bug
Previous Message Tom Lane 2012-12-16 18:03:08 Re: multiple CREATE FUNCTION AS items for PLs