Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

java - Using Apache ANT to programmatically execute sql script with plpgsql function fails

I need to execute a SQL script programmatically. The script defines a function which upgrades the postgreSQL database depending on its version. It looks like this:

create or replace function update_auto_increment(version varchar(20)) returns integer
as $$
declare 
 v integer;
begin
 v := cast(version as int);
 if v < 590 then
 -- some upgrade code here
 v := 590;
 raise notice 'Updated base to version %', v;
 end if;
 return v;
end;
$$ language plpgsql;

select update_auto_increment(value) from info where name = 'version';

drop function update_auto_increment(varchar(20));

Then I prepare an ANT task and execute it:

SQLExec task = new SQLExec();
Project project = new Project();
project.init();
task.setProject(project);
task.setTaskType("sql");
task.setTaskName("sql");
task.setSrc(new File("updateScript.sql"));
task.setDriver(driver);
task.setPassword(password);
task.setUserid(username);
task.setUrl(connectionURL);
task.execute();

And the execution process fails when it encounters $$ :

org.postgresql.util.PSQLException: ERROR: syntax error (near: "$")
position: 91
at org.apache.tools.ant.taskdefs.SQLExec.execute(SQLExec.java:672)

(the error message was localized and I tried to translate it into English). So, the question is: how can I programmatically execute a SQL script with function definition in it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Most probably SQLExec is splitting the statement by ; which is the default statement termination character in SQL.

In your case, that splitting should not happen.

You might try to use something like this:

task.setDelimiterType(SQLExec.DelimiterType.ROW);
task.setDelimiter("/");

and then separate your SQL statements in the file with a / on a single line:

create or replace function update_auto_increment(version varchar(20)) returns integer
as $$
declare 
 v integer;
begin
 v := cast(version as int);
 if v < 590 then
 -- some upgrade code here
 v := 590;
 raise notice 'Updated base to version %', v;
 end if;
 return v;
end;
$$ language plpgsql;
/

select update_auto_increment(value) from info where name = 'version'
/

drop function update_auto_increment(varchar(20))
/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...