Concatenate variable in Apex in salesforce? - apex

In salesforce batch class I am trying to do something like below, but its giving me error
global class PurgerefundcasesBatch implements Database.Batchable<sObject> {
private static final String refund = 'refund';
String query = String query = 'SELECT id, SubStatus__c FROM Case ' +
'WHERE SubStatus__c ='+ refund +' AND createdDate < LAST_N_DAYS:10';
global PurgerefundcasesBatch() {
}
.......
.........
}
Getting the below error..
Timestamp: Tue, 13 Feb 2018 21:59:17
Result: [OPERATION FAILED]: classes/PurgeDraftcasesBatch.cls: Missing ';' at 'query' (Line: 12, Column: 24)
classes/PurgeDraftcasesBatch.cls: Unexpected token '='. (Line: 12, Column: 30)
classes/PurgeDraftcasesBatch.cls: Unexpected token '='. (Line: 12, Column: 30)
classes/PurgeDraftcasesBatch.cls: Unexpected token '+'. (Line: 13, Column: 41)
classes/PurgeDraftcasesBatch.cls: Unexpected token '+'. (Line: 13, Column: 41)
classes/PurgeDraftcasesBatch.cls: Variable does not exist: String (Line: 12, Column: 17)
classes/PurgeDraftcasesBatch.cls: Invalid loop variable type expected SObject was Case (Line: 26, Column: 4)`

The major issiue is that you set your query variable in a wrong way. You can't define it like:
String query = String query =
String query = 'SELECT id, ELC_SubStatus__c FROM Case WHERE SubStatus__c ='+ refund +' AND createdDate < LAST_N_DAYS:10';

I was able to do this like below. Please refer to Dynamic SOQL for dynamic query considerations
private static final String refund = 'refund';
String query = 'SELECT id, SubStatus__c FROM Case ' +
'WHERE SubStatus__c = :refund AND createdDate < LAST_N_DAYS:10';

Related

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

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.

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.

i am getting error while using window functions in pyspark

i am trying to run the below code
employees = (spark.read.format('csv')
.option('sep', '\t')
.schema('''EMP_ID INT,F_NAME STRING,L_NAME STRING,
EMAIL STRING,PHONE_NR STRING,HIRE_DATE STRING,
JOB_ID STRING,SALARY FLOAT,
COMMISSION_PCT STRING,
MANAGER_ID STRING,DEP_ID STRING''')
.load('C:/data/hr_db/employees')
)
spec = Window.partitionBy('DEP_ID')
emp = (employees
.select('JOB_ID', 'DEP_ID', 'SALARY')
.withColumn('Total Salary', sum('SALARY').over(spec))
.orderBy('DEP_ID')
)
emp.show()
and getting the below error
File "C:\spark-2.4.4-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py", line 328, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o60.showString.java.lang.IllegalArgumentException: Unsupported class file major version 56
could you please anyone help me on this error?

ORA-06550: PLS-00103: Encountered the symbol "" with mybatis TypeHandler

I am using Typehandler to map a List<Dep> to oracle array of ... here is the setPArameter method in the handler :
public void setParameter(PreparedStatement ps, int i, List<Dep> parameter, JdbcType jdbcType)
throws SQLException {
Connection connection = ps.getConnection();
// StructDescriptor structDescriptor = StructDescriptor.createDescriptor("MEMS_ARR", connection);
Struct[] structs = null;
if(parameter != null && parameter.size() >0) {
structs = new Struct[parameter.size()];
for (int index = 0; index < parameter.size(); index++)
{
Dep dep = parameter.get(index);
Object[] params = new Object[7];
params[0] = dep.getOrder();
params[1] = dep.getIdTp;
params[2] = dep.getId();
params[3] = " ";
params[4] = " ";
params[5] = " ";
params[6] = " ";
// STRUCT struct = new STRUCT(structDescriptor, ps.getConnection(), params);
structs[index] = connection.createStruct("MEMS", params);
}
// ArrayDescriptor desc = ArrayDescriptor.createDescriptor("MEMS_ARR", ps.getConnection());
// ARRAY oracleArray = new ARRAY(desc, ps.getConnection(), structs);
}else {
parameter = new ArrayList<DependentDTO>();
structs= new Struct[0];
}
this.parameter = parameter;
Array oracleArray = ((OracleConnection) connection).createOracleArray("MEMS_ARR", structs);
ps.setArray(i, oracleArray);
}
and here is the MEMS type :
create or replace TYPE MEMS AS OBJECT
( MEM1 NUMBER(2,0),
MEM2 VARCHAR2(1),
MEM3 VARCHAR2(15),
MEM4 VARCHAR2(60),
MEM5 VARCHAR2(1),
MEM6 VARCHAR2(40),
MEM7 VARCHAR2(10)
);
and here is the portion of the xml mapping file that uses the Typehandler :
#{nat,javaType=String,jdbcType=VARCHAR,mode=IN}, --nat
**#{deps,javaType=List,jdbcType=ARRAY,mode=IN,jdbcTypeName=MEMS_ARR,typeHandler=com.my.package.MyHandler}, --mems**
#{res,javaType=String,jdbcType=VARCHAR,mode=OUT} --res
the error log is as follows :
Error querying database. Cause: java.sql.SQLException: ORA-06550: line 31, column 5: PLS-00103: Encountered the symbol "" when expecting one of the following: . ( ) , * # % & = - + < / > at in is mod remainder not rem => <an exponent (**)> <> or != or ~= >= <= <> and or like like2 like4 likec between || indicator multiset member submultiset The symbol "(" was substituted for "" to continue. ORA-06550: line 44, column 4: PLS-00103: Encountered the symbol ";" when expecting one of the following: . ( ) , * % & = - + < / > at in is mod remainder not rem => <an exponent (**)> <> or != or ~= >= <= <> and or like like2 like4 likec between || multiset ### The error may exist in file [E:\path\to\mapper\ADao.xml] ### The error may involve my.package.ADao.mthodToCall -Inline ### The error occurred while setting parameters ### SQL: {call MY_PROC( ... , --nat?, **--mems? --res**)}
As you can see in the logs, the mems is replaced by empty string or is merged with the next arg res ... the comma is not there
Also kindly note that I already debugged inside the mybatis code and realized that the mapping setParameter method is called and the input List is mapped correctly to the oracle array ... the issue happens at the time of real calling
The issue actually was that I simply missed one comma between two previous parameters ... but the error pointed to the wrong parameter to look at

tcpdf date error Message: Undefined offset: 2

i have a date (datepicker jquery) $fecha_constancia:
public function generarReporte(){
$data_b = array();
$container = $this->input->get_post('opc_report', TRUE);
$paciente = $this->input->get_post('paciente', TRUE);
$odontologo = $this->input->get_post('odontologo', TRUE);
$fecha_constancia = $this->input->get_post('fecha_constancia', TRUE);
$diagnostico = $this->input->get_post('diagnostico', TRUE);
$reposo= $this->input->get_post('reposo', TRUE);
$reposo = $reposo*7;
list($day,$mon,$year) = explode('/',$fecha_constancia);
$nueva_fecha = date('d/m/Y',mktime(0,0,0,$mon,$day+$reposo,$year));
$data_a = array(
'fecha_constancia' => $fecha_constancia,
'diagnostico' => $diagnostico,
'fecha_reposo' => $nueva_fecha,
'dias_reposo' => $reposo
but when I'm going to spend the time to the Make pdf throws me the following result:
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 2
Filename: controllers/constancia.php
Line Number: 38
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: controllers/constancia.php
Line Number: 38
is that the problem is in the date but not how to fix it
Check that the value of $fecha_constancia is an actual date in the format of Day/Month/Year.
This is line 38, correct?:
list($day,$mon,$year) = explode('/',$fecha_constancia);
Based on the error message, there's no slashes in $fecha_constancia. It can't assign anything to $mon and $year because explode is returning an array with a single element.