How do I create user-defined function in AWS Aurora RDS Postgres

*爱你&永不变心* 提交于 2020-05-14 05:48:32

问题


(Formatting questions for simplicity)

I am using AWS RDS Aurora Postgres 10.7 (this is the latest version available for my us-west-2 region). I am using this in a serverless mode and hence I get the Query Editor embedded inside AWS Console to run my queries. I have a requirement of writing user-defined function to perform certain complex database operations. I tried it on my local instance of Postgres and it works fine, however, on AWS I am not able to create a function.

The following results in an error: ERROR: syntax error at or near "END". Please note adding a semicolon after 'return 1' also results in to error.

CREATE OR REPLACE function some_function()
  RETURNS integer AS
$BODY$
Begin
    return 1
End
$BODY$
  LANGUAGE 'plpgsql';

whereas, the following lets me create the function but it is unusable as it has no body.

CREATE OR REPLACE function some_function()
  RETURNS integer AS
$BODY$
Begin
End
$BODY$
  LANGUAGE 'plpgsql';

My questions is: Has anyone used AWS RDS Query Editor to create user-defined functions in Aurora Postgres? Is yes, what part of syntax is wrong in the example above.

回答1:


We run into the same problem and got in touch with AWS, who confirmed it is indeed a problem with the Query Editor tool. They don't have an ETA on when the problem will be fixed.

Solution 1: Use psql

The good news is that this will work with psql. This is a snippet from their reply email:

$ psql -h database-2.cluster-xx.us-west-2.rds.amazonaws.com -d postgres -U postgres
postgres=> CREATE OR REPLACE FUNCTION trigger_set_updated_at() RETURNS TRIGGER AS $$
postgres$> BEGIN  NEW.updated_at = NOW();  
postgres$> RETURN NEW;END;$$ 
postgres-> LANGUAGE plpgsql;
CREATE FUNCTION

Documentation on how to set it up: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ConnectToPostgreSQLInstance.html

Solution 2: Use the Data API

We already use the Data API to communicate with our cluster, so for us the simplest solution is actually using the AWS CLI and the existing database secret.

You can put your function definition in a function.sql file:

CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
    BEGIN
        RETURN i + 1;
    END;
$$ LANGUAGE plpgsql;

Then execute it on the database with:

cat function.sql | xargs -0 aws rds-data execute-statement \
    --resource-arn arn:aws:rds:eu-west-1:xxx:cluster:cluster-name \
    --secret-arn arn:aws:secretsmanager:eu-west-1:xxx:secret:secret-name-xxx \
    --database "database_name" \
    --sql

Hopefully this is useful, good luck!



来源:https://stackoverflow.com/questions/57994804/how-do-i-create-user-defined-function-in-aws-aurora-rds-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!