Can not call procedure by JPA - could not determine data type of parameter - postgresql

When trying to call procedure with timestamp parameters by the code:
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource)
.withSchemaName("time_series")
.withProcedureName("refresh_continuous_aggregate")
.declareParameters(new SqlParameter("continuous_aggregate", Types.VARCHAR),
new SqlParameter("window_start", Types.TIMESTAMP),
new SqlParameter("window_end", Types.TIMESTAMP));
MapSqlParameterSource inParams = new MapSqlParameterSource()
.addValue("continuous_aggregate", "time_series.current_data_hourly", Types.VARCHAR)
.addValue("window_start", "2020-11-12 01:02:03.123456789", Types.TIMESTAMP)
.addValue("window_end", "2021-02-12 01:02:03.123456789", Types.TIMESTAMP);
Map<String, Object> execute = simpleJdbcCall.execute(inParams);
I'm getting error:
ERROR o.s.i.handler.LoggingHandler ->
org.springframework.jdbc.BadSqlGrammarException:
CallableStatementCallback; bad SQL grammar [{call
time_series.refresh_continuous_aggregate(?, ?, ?)}]; nested exception
is org.postgresql.util.PSQLException: ERROR: could not determine data
type of parameter $2
The similar error I'm getting when I try to use native query with dynamic parameters:
String queryStr = "CALL time_series.refresh_continuous_aggregate(?1, ?2, ?3)";
Query query = entityManager.createNativeQuery(queryStr)
.setParameter(1, continuousAggregate)
.setParameter(2, windowStart, TemporalType.TIMESTAMP)
.setParameter(3, windowEnd, TemporalType.TIMESTAMP);
Object singleResult = query.getSingleResult();
ERROR o.h.e.jdbc.spi.SqlExceptionHelper -> ERROR: syntax error at or
near "$2"
And by using StoredProcedureQuery:
StoredProcedureQuery query = entityManager.createStoredProcedureQuery("time_series.refresh_continuous_aggregate")
.registerStoredProcedureParameter("continuous_aggregate", String.class, ParameterMode.IN)
.registerStoredProcedureParameter("window_start", Date.class, ParameterMode.IN)
.registerStoredProcedureParameter("window_end", Date.class, ParameterMode.IN)
.setParameter("continuous_aggregate", "time_series.current_data_hourly")
.setParameter("window_start", new Date(), TemporalType.TIMESTAMP)
.setParameter("window_end", new Date(), TemporalType.TIMESTAMP);
query.execute();
WARN o.h.e.jdbc.spi.SqlExceptionHelper -> SQL Error: 0, SQLState:
42P18 ERROR o.h.e.jdbc.spi.SqlExceptionHelper -> ERROR: could not
determine data type of parameter $2
It looks like JDBC drivers issue.

Related

postgres-rust error 42601 (Common Syntax Error): Issuing variable table names properly?

Cargo.toml:
[dependencies]
rocket = "0.4.4"
rocket_cors = "0.5.2"
postgres = "0.15.2"
r2d2_postgres = "0.14.0"
r2d2 = "0.8.0"
rocket_contrib = "0.4.4"
serde_json = "1.0.53"
I'm attempting to issue variable table names in rust-postgres by using the format! macro so that rust can handle the concatenation itself. state.val.get().unwrap().execute() is equivalent to connection.execute() in a regular usecase when equal to postgres::PostgresConnectionManager::new(). Here's the snippet:
let data_u8: &[u8] = data.peek();
let data_str: &str = str::from_utf8(&data_u8).unwrap();
let data_json: serde_json::Value = serde_json::from_str(&data_str).unwrap();
let table_name = data_json["broadcast_category"].to_string().replace(&['\"'][..], "");
let table_create = format!("CREATE TABLE IF NOT EXISTS category_{} (
message VARCHAR NOT NULL,
name VARCHAR NOT NULL,
)", table_name);
let table_create_ref: &str = &table_create[..];
println!("Table Create fn: {}", table_create);
state.val.get().unwrap().execute(table_create_ref, &[]).unwrap();
I only recieve the following error on compile-time: (data_json["broadcast_category"] is part of a serde_json::Value wrapper recieved on a POST request from the user.
Error:
thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: Error(Db(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState("42601"), message: "syntax error at or near \"$1\"", detail: None, hint: None, position: Some(Normal(59)), where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("scan.l"), line: Some(1133), routine: Some("scanner_yyerror") }))', src\main.rs:60:9
** src\main.rs:60:9 = state.val.get().unwrap().execute(table_create_ref, &[]).unwrap();
As always, your kind efforts and support is appreciated, and we thank you for your involvement in the community.

Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00936: missing expression

While executing insert and update command in oracle 11g I'm getting below error.
val stmt = con.createStatement()
//Insert
val query1 = "insert into audit values('D','abc','T','01-NOV-18','Inprogress')"
stmt.executeUpdate(query1)
//Update
val query2 = "Update audit Set status='test' where where product= = 'D'"
stmt.executeUpdate(query2)
I'm getting below error
//Error while updating record
Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00936: missing expression
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:195)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:1036)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
at oracle.jdbc.driver.OracleStatement.executeUpdateInternal(OracleStatement.java:1845)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1810)
at oracle.jdbc.driver.OracleStatementWrapper.executeUpdate(OracleStatementWrapper.java:294)
at com.oracle.OracleConnection$.main(OracleConnection.scala:21)
at com.oracle.OracleConnection.main(OracleConnection.scala)
Process finished with exit code 1
Any help will be appreciated. Thanks in advance
You have two where and two = in your update query.
val query2 = "Update audit Set status='test' where product='D'"

org.postgresql.util.PSQLException: No results returned by the query

hey everyone am trying to insert data in a table using #Query annotation in my spring boot app am getting a postgres Exception :
org.postgresql.util.PSQLException: No results returned by the query
this is my code :
this is the repository
#Query(value="INSERT INTO \"FCT_BY_DEV\"(\"IdDev\", \"IdFonction\") VALUES (?, ?) ",nativeQuery=true)
public String isertfonctionstodev(int dev,int fonction);
this is the controller :
#RequestMapping(value="/function/insert", method = RequestMethod.POST)
public String insererfonctions (int dev,int fonction){
System.out.println("dev="+dev+"fonction="+fonction);
fonctionRepository.isertfonctionstodev(dev, fonction);
System.out.println("********");
return "aaa";
}
am using this service by $http in angularJs
$http.post("/function/insert?dev="+$scope.id+"&fonction="+$scope.idf);
and finaly this is the server log
dev=16006fonction=14
Hibernate: INSERT INTO "FCT_BY_DEV"("IdDev", "IdFonction") VALUES (?, ?)
2016-04-27 16:52:03.204 WARN 7036 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 02000
2016-04-27 16:52:03.204 ERROR 7036 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Aucun résultat retourné par la requête.
the data is correct and i tried the same query with the same value and it worked why posgres is generating this exception and how can i fixed , thanks to any help
I think modifying queries must be annotared with an extra
#Modifying
This should solve your issue:
#Transactional
#Modifying(clearAutomatically = true)
#Query(value="update policy.tbl_policy set ac_status = 'INACTIVE' where pol_id = :policyId and version_no = :version_no and ac_status = 'ACTIVE'", nativeQuery=true)
public void updateExistingRowbyId(#Param("policyId") Long pol_id, #Param("version_no") Long version_no);
Without #Transactional annotation, following errors may occur:
javax.persistence.TransactionRequiredException: Executing an update/delete query

Error running update query in Postgres NPGSQL - ERROR: 42601: syntax error at or near "="

I am running the following update command:
NpgsqlCommand command = new NpgsqlCommand("UPDATE \"FPConfig_simulationresult\" SET key_name = :keyName WHERE id = :resultID", conn);
command.Parameters.Add(new NpgsqlParameter("keyName", DbType.String));
command.Parameters.Add(new NpgsqlParameter("resultID", DbType.Int32));
command.Parameters[0].Value = keyName;
command.Parameters[1].Value = resultID;
int rowsAffected = command.ExecuteNonQuery();
and get the error:
ERROR: 42601: syntax error at or near "="
I have checked everything in the update SQL statement, the table name and field names are correct.

Using a string as a RID with SQL Commands

Using the Java api on an Orient-DB 2.0 rc1. Is it possible to use a string as a RID?
Documentation : https://github.com/orientechnologies/orientdb/wiki/SQL-Update#example-3-add-a-value-into-a-collection
more specifiaclly the section SQL Commands
JSON received:
{
userRID:"#100:100",
group:"someCode"
}
JAVA CODE (xtend script):
def addUserInGroup(Message<JsonObject> message){
val params = new JsonObject() => [
putString("userId", message.body().getString("userRID"));
putString("code", message.body().getString("group"));
]
var queryCommand= "update Table add users=:userId where code=:code";
Map<String, Object> paramsFormatted = params.toMap();
database.command( new OCommandSQL(queryCommand) ).execute(paramsFormatted);
}
Table structure :
users : linklist (user object)
code : string
When I run the following commands in the studio they all work :
update Table add users=(Select #rid from User where #rid=#100:100) where code='someCode'
update Table add users=#100:100 where code='someCode'
But none of these command work in the API. I'm guessing there is something wrong in way I'm using the RID.
SEVERE: Exception in Java verticle
com.orientechnologies.orient.core.sql.OCommandSQLParsingException: Error on parsing command at position #29: Found unexpected keyword '=:USERID' while it was expected '[=]'. Use UPDATE <class>|cluster:<cluster>> [SET|ADD|PUT|REMOVE|INCREMENT|CONTENT {<JSON>}|MERGE {<JSON>}] [[,] <field-name> = <expression>|<sub-command>]* [LOCK <NONE|RECORD>] [UPSERT] [RETURN <COUNT|BEFORE|AFTER>] [WHERE <conditions>]
Command: update SecureAccess add users=:userId where code=:code
-------------------------------------^
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLAbstract.throwSyntaxErrorException(OCommandExecutorSQLAbstract.java:89)
at com.orientechnologies.common.parser.OBaseParser.parserRequiredKeyword(OBaseParser.java:317)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLUpdate.parseAddFields(OCommandExecutorSQLUpdate.java:605)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLUpdate.parse(OCommandExecutorSQLUpdate.java:129)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLUpdate.parse(OCommandExecutorSQLUpdate.java:59)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:56)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:37)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.command(OAbstractPaginatedStorage.java:1150)
at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:63)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.command(ONetworkProtocolBinary.java:1179)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:385)
at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:216)
at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:65)
janv. 07, 2015 8:45:17 AM org.vertx.java.core.logging.impl.JULLogDelegate error
SEVERE: Exception in Java verticle
com.orientechnologies.orient.core.sql.OCommandSQLParsingException: Error on parsing command at position #29: Found unexpected keyword '=:USERID' while it was expected '[=]'. Use UPDATE <class>|cluster:<cluster>> [SET|ADD|PUT|REMOVE|INCREMENT|CONTENT {<JSON>}|MERGE {<JSON>}] [[,] <field-name> = <expression>|<sub-command>]* [LOCK <NONE|RECORD>] [UPSERT] [RETURN <COUNT|BEFORE|AFTER>] [WHERE <conditions>]
Command: update SecureAccess add users=:userId where code=:code
-------------------------------------^
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLAbstract.throwSyntaxErrorException(OCommandExecutorSQLAbstract.java:89)
at com.orientechnologies.common.parser.OBaseParser.parserRequiredKeyword(OBaseParser.java:317)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLUpdate.parseAddFields(OCommandExecutorSQLUpdate.java:605)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLUpdate.parse(OCommandExecutorSQLUpdate.java:129)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLUpdate.parse(OCommandExecutorSQLUpdate.java:59)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:56)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:37)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.command(OAbstractPaginatedStorage.java:1150)
at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:63)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.command(ONetworkProtocolBinary.java:1179)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:385)
at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:216)
at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:65)
I think You should try something like :
putString("userId", new ORecordId(message.body().getString("userRID")));