1

I have a query that makes repeated use of the same snippet of code, which I'll call foo(), as if the function existed:

SELECT
    foo(a),
    BUILTIN(foo(a))
FROM 
    foobar
GROUP BY
    foo(a)
HAVING
    BUILTIN(foo(a)) > bar()
ORDER BY
    foo(a)
;

Usually, I would have created this function foo long ago - what I actually see in my editor is the same messy nest of built-in functions several times.

However - I cannot CREATE my nice foo, as I only have USAGE permissions.

Does there exist a way for me to create some kind of 'alias', such that whenever I say foo, a longer function is executed; but this would of course not be available to any other DB user?

5
  • the whole point of functions is to encapsulate code in a nice simple syntax. since you can't define functions, you'll just have to repeat your function's code everywhere. Commented Feb 24, 2015 at 21:07
  • @MarcB I know that's the whole point. That's what I want to use one for! I wondered if there was a way for psql to 'know' locally that when I say foo I want bar to happen - but crucially foo is not created server-side, since I do not have permission to do so. Commented Feb 24, 2015 at 21:09
  • 1
    I believe you can create a function in the pg_temp schema and it will disappear after the connection closes, but I couldn't tell you if you have access to that or not. Commented Feb 24, 2015 at 21:14
  • nope. you need functions, there's no other workaround. it'd be a pretty silly DB security system that restricts function creation, but has a completely identical "this_is_not_a_function" syntax that is allowed. Commented Feb 24, 2015 at 21:14
  • @MarcB Well, the point would be at DB side it's exactly the same - noone else could see/use it, I wouldn't be creating anything there. I could go overkill and write a function to replace foo with whatever and then run the query in any scripting language - that's not a flaw of anyone's security. Commented Feb 24, 2015 at 21:39

1 Answer 1

2

In the case of the example you posted compute foo(a) in a subquery:

select foo_a, builtin(foo_a)
from (
    select foo(a) as foo_a
    from foobar
) s
group by 1
having builtin(foo_a) > bar()
order by 1
;
Sign up to request clarification or add additional context in comments.

1 Comment

I've accepted this answer because it's probably best in the general case, although I'd actually arrived at my code by trying to remove sub-queries. In my case, creating the function in pg_temp schema as BaconBits suggested worked a treat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.