create a function via nativeQuery - java

I'm trying to insert a function on database via native query, like this
EntityManagerImpl entityManagerFunctionConta = (EntityManagerImpl) GermantechEntityManager.getEntityManager();
EntityTransaction transactionFunctionConta = entityManagerFunctionConta.getTransaction();
String functionConta = "CREATE OR REPLACE FUNCTION saldo_anterior_conta(dt_inicial date, id_conta bigint, id_empresa bigint) " +
"RETURNS numeric AS " +
"$BODY$ " +
"declare " +
"saldo_anterior numeric(14,2);" +
"begin " +
"select coalesce(sum(valor), 0) into saldo_anterior " +
"from saldoinicialconta " +
"where data < dt_inicial and empresa_id = id_empresa and conta_id = id_conta; " +
"return saldo_anterior;" +
"end;" +
"$BODY$ " +
"LANGUAGE plpgsql VOLATILE COST 100;" +
"ALTER FUNCTION saldo_anterior_movimentacao(date, bigint, bigint) OWNER TO postgres;";
transactionFunctionConta.begin();
entityManagerFunctionConta.createNativeQuery(functionConta).executeUpdate();
transactionFunctionConta.commit();
but the following exception is thrown
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.BatchUpdateException: Entrada em lote 1 <unknown> foi abortada. Chame getNextException para ver a causa.
Error Code: 0
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeJDK12BatchStatement(DatabaseAccessor.java:882)
at org.eclipse.persistence.internal.databaseaccess.DynamicSQLBatchWritingMechanism.executeBatchedStatements(DynamicSQLBatchWritingMechanism.java:144)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.writesCompleted(DatabaseAccessor.java:1714)
is there something wrong with the function? can we run a command like this via nativeQuery?

Related

WITH Recursive query is not working when run using entityManager native query

I'm running this PostgreSQL query on Java and it is throwing an error "ERROR: syntax error at or near ":".
But the query is working on Postgresql when I run directly.
I'm thinking Array[]::integer[] is causing the issue. Can someone has any idea?
String query = "WITH RECURSIVE tree AS ( SELECT id, ARRAY[]::integer[] AS ancestors \n" +
" FROM regions \n" +
" WHERE parent_id IS NULL\n" +
" UNION ALL \n" +
" SELECT soato.id, tree.ancestors || regions.parent_id \n" +
" FROM regions, tree \n" +
" WHERE regions.parent_id = tree.id \n" +
") \n" +
" SELECT d.id FROM department d \n" +
" WHERE d.region_id IN (select id from tree where 1703 = ANY(tree.ancestors))";
Query q = entityManager.createNativeQuery(query);
q.getResultList();
Use an explicit cast to avoid the implicit PostgreSQL option :: for casting.
ARRAY[CAST(NULL AS INTEGER)] AS ancestors

How write to s3 table sink in flink without update and delete changes error?

Consider a code:
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
class Scratch {
public static void main(String[] args) {
StreamTableEnvironment tableEnv = /*some init code here*/;
tableEnv.executeSql("CREATE TABLE my_table (\n" +
" id STRING,\n" +
" createdDate DATE,\n" +
" `date` STRING " +
" ) PARTITIONED BY (`date`) \n" +
" WITH (\n" +
" 'connector' = 'filesystem',\n" +
" 'path' = 's3://my-bucket/',\n" +
" 'format' = 'json'\n" +
" )");
tableEnv.executeSql("CREATE TABLE output_table (\n" +
" id STRING,\n" +
" created_date DATE,\n" +
" count_value BIGINT,\n" +
" PRIMARY KEY (id, created_date) NOT ENFORCED\n" +
") WITH (\n" +
" 'connector' = 'filesystem', \n" +
" 'path' = 's3://some-bucket/output-table/',\n" +
" 'format' = 'json'\n" +
" )");
Table temp = tableEnv.sqlQuery(
" SELECT id as id, " +
" max(createdDate) as created_date, " +
" COUNT(DISTINCT(id)) as count_value " +
" from my_table\n" +
" GROUP BY createdDate, id"
);
temp.executeInsert("output_table");
}
}
This will give me error:
org.apache.flink.client.program.ProgramInvocationException: The main method caused an error: Table sink 'default_catalog.default_database.output_table' doesn't support consuming update changes which is produced by node GroupAggregate(select=[MIN($f0) AS id, MAX(createdDate) AS created_date, COUNT(DISTINCT $f2) AS count_value ])
Is there a way to write aggregation to s3 via flink? (a flink is run in batch mode)
As it is you are running the query in streaming mode, which requires a sink that can handle the updates and deletes coming from the aggregation.
This will work if you either
produce the results in a CDC (changelog) format, such as debezium,
or run the job in batch mode
To run in batch mode, you can do this:
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableEnvironment;
EnvironmentSettings settings = EnvironmentSettings
.newInstance()
.inBatchMode()
.build();
TableEnvironment tEnv = TableEnvironment.create(settings);
If you need to use the Table API in batch execution mode while also having access to the DataStream API, this is only possible since Flink 1.14.

java postgresql using trigger

SQL = "create view CSaccept as select sID, cName from Apply where major = 'CS' and decision = 'Y' ";
stmt.executeUpdate(SQL);
SQL = "create or replace function test1() returns trigger as $$\n" +
"begin\n" +
" update Apply set cName = New.cName where (sID = Old.sID and cName = Old.cName and Apply.major = 'CS' and Apply.decision = 'Y');\n" +
" return Old;\n" +
"end;\n" +
"$$\n" +
"language 'plpgsql';\n" +
"create trigger CSacceptUpdate\n" +
"instead of update of cName on CSaccept\n" +
"for each row\n" +
"execute procedure test1();";
stmt.executeUpdate(SQL);
Hi I am writing a program in java using postgresql, and the error like below keeps popping up in the above SQL statement. What is the problem?
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: INSTEAD OF triggers cannot have column lists
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:473)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:393)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:322)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:308)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:284)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:258)
at SqlTest2.main(SqlTest2.java:270)
SQL = "create or replace function test2() returns trigger as $$\n" +
"begin\n" +
" delete from Apply where sID = old.sID and cName = old.cName and major = 'CS' and decision = 'Y';\n" +
" return Old;\n" +
"end;\n" +
"$$\n" +
"language 'plpgsql';\n" +
"create trigger CSacceptDelete\n" +
"instead of delete on CSaccept\n" +
"for each row\n" +
"execute procedure test2();";
above one works well. I don't know why First one is not working.

Spring Boot Mybatis Dynamic query

Hello im pretty new to mybatis and is the first time im trying to use with annotations in spring boot.
My code is something like this :
#Select("<script>"
+ "SELECT t.something, s.somewhat, "
+ "FROM t.table1 t "
+ "LEFT JOIN table2 s ON t.id = s.id "
+ "WHERE s.delete_date IS NULL "
+ "<if test=\"isnew\"> "
+ "AND t.insert_date = t.update_date "
+ "AND (t.score >= s.min_score AND t.score <= s.max_score) "
+ "</if>"
+ "union "
+ "ANOTHER SIMILAR QUERY WITH ANOTHER <IF> + "</script>")
List<Map<String, Object>> methodName(#Param("isnew") Boolean isNew);
This is the error.
Caused by: java.lang.IllegalArgumentException: org.apache.ibatis.builder.BuilderException: Could not find value method on SQL annotation. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 822;
Im almost sure there is an error of syntax very predictable but I cant find it.
Here are some examples of what I tried, none of them works:
"<if test="isnew = true">"
"<if test="isnew == true">"
"<if test="isnew != false">"
"<if test="isnew"> "
"<if test=#{isnew}"> "
"<if #{isnew} = true> "
Thanks in advance
For those who may have the same problem this is the solution:
You have to escape the character < , because mybatis takes it as an unopened tag, &lt will work :
+ "SELECT t.something, s.somewhat, "
+ "FROM t.table1 t "
+ "LEFT JOIN table2 s ON t.id = s.id "
+ "WHERE s.delete_date IS NULL "
+ "<if test=\"isnew\"> "
+ "AND t.insert_date = t.update_date "
+ "AND (t.score >= s.min_score AND t.score lt;= s.max_score) "
+ "</if>"
+ "union "
+ "ANOTHER SIMILAR QUERY WITH ANOTHER <IF> + "</script>")
List<Map<String, Object>> methodName(#Param("isnew") Boolean isNew);```

ORA-00933 SQL command not properly ended but good in SQL Developer

I am hoping someone can find what is the issue with my query because I am unable to see fault in it and Oracle SQL Developer seems to run the same query as the code in my Java Swing Application just fine.
My query in SQL Developer:
SELECT
ad.ID,ad.Script_Name,ad.Current_Status,
ad.Issues_found_during_run,ad.Testers,
ad.Run_Date,ad.Tools,u.fTag,u.role,
dbms_lob.substr(u.avatar)
FROM
allData ad
INNER JOIN
users u
ON
u.fTag = ad.lastUserWhoUpdated
GROUP BY
ad.ID,ad.Script_Name,ad.Current_Status,
ad.Issues_found_during_run,ad.Testers,
ad.Run_Date,ad.Tools,u.fTag,u.role,
dbms_lob.substr(u.avatar)
ORDER BY
ad.ID ASC;
Which run perfectly and returns the needed records I would be expecting it to.
However, that same query in my Java Swing App does not seem to like it as it gives me the error of:
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended.
My Java Swing App code:
connectToDB();
String query =
"SELECT " +
"ad.ID," +
"ad.Script_Name," +
"ad.Current_Status," +
"ad.Issues_found_during_run," +
"ad.Testers," +
"ad.Run_Date," +
"ad.Tools," +
"u.fTag," +
"u.role," +
"dbms_lob.substr(u.avatar) " +
"FROM " +
"allData ad " +
"INNER JOIN " +
"users u " +
"ON " +
"u.fTag = ad.lastUserWhoUpdated " +
"GROUP BY " +
"ad.ID," +
"ad.Script_Name," +
"ad.Current_Status," +
"ad.Issues_found_during_run," +
"ad.Testers," +
"ad.Run_Date," +
"ad.Tools," +
"u.fTag," +
"u.role," +
"dbms_lob.substr(u.avatar) " +
"ORDER BY " +
"ad.ID;";
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
etc..etc..
My structure for those 2 tables is:
SCRIPT_NAME VARCHAR2(100 BYTE)
CURRENT_STATUS VARCHAR2(50 BYTE)
ISSUES_FOUND_DURING_RUN VARCHAR2(150 BYTE)
TESTERS VARCHAR2(30 BYTE)
RUN_DATE DATE
TOOLS VARCHAR2(20 BYTE)
T_SUITE NUMBER(38,0)
NOE2 VARCHAR2(5 BYTE)
NOE3 VARCHAR2(5 BYTE)
ID NUMBER(38,0)
LASTUSERWHOUPDATED NUMBER
DATELASTMOD DATE
FTAG NUMBER(38,0)
ROLE VARCHAR2(15 BYTE)
AVATAR CLOB
So, what could I be missing?
Remove semicolon after the ad.ID like below. You don't need it
"ORDER BY " +
"ad.ID";

Categories

Resources