Covert SQL query to TYPO3 query builder? - typo3

How to convert SQL query to TYPO3 query builder.
SELECT * FROM tableName ORDER BY (CASE WHEN DATE(dateColumn) < DATE(GETDATE()) THEN 1 ELSE 0
END) DESC, dateColumn ASC
enter link description here
Same functionality i need in typo3 query builder.

To get the sql query you posted, you can do it like following:
// little helper function to debug querybuilder,
// queries with parameter placeholders
function debugQuery(QueryBuilder $builder)
{
$preparedStatement = $builder->getSQL();
$parameters = $builder->getParameters();
$stringParams = [];
foreach ($parameters as $key => $parameter) {
$stringParams[':' . $key] = $parameter;
}
return strtr($preparedStatement, $stringParams);
}
// get querybuilder
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionByName('Default')
->createQueryBuilder();
// build query
$queryBuilder
->select('*')
->from('table')
->getConcreteQueryBuilder()->orderBy(
'(CASE WHEN DATE('
.$queryBuilder->quoteIdentifier('dateColumn')
.') < DATE(GETDATE()) THEN 1 ELSE 0 END)',
'DESC'
)
;
$queryBuilder->addOrderBy('dateColumn', 'ASC');
// build query
$sql = debugQuery($queryBuilder);
The generates following sql query:
SELECT
FROM `table`
ORDER BY
(CASE WHEN DATE(`dateColumn`) < DATE(GETDATE()) THEN 1 ELSE 0 END) DESC,
`dateColumn` ASC
Some note beside:
To my knowlage GETDATE() is not a valid mysql method, more MSSQL. Eventually you want CURRENT_DATE() instead.
edit #1
Not tested/run .. just created the sql string to match what you provided. So don't blame me if provided sql query is wrong itself.

Related

criteria api sub-select with sub-select and custom fields

I'd like to rewrite following sql query to criteria api:
select * from demands d
where exists (
select * from (
select a.demandid,
min(coalesce(a.securitylevel, a.securitylevel, -1)) themin,
max(coalesce(a.securitylevel, -1)) themax
from allocations a
group by demandid)
where demandid = d.id
and (themin = -1 and themax = -1
or themax >= 5)
);
The problem is that I'm not able to figure out how to write select clause for sub-queries, my current implementation produces CompoundSelection however subQyer.select accepts only Expression (DemandSecLevel is custom POJO/DTO).
public static Specification<Demand> bySecurityLevel(
final Integer securityLevel) {
return (root, query, cb) -> {
final Subquery<DemandSecLevel> subQuery = query.subquery(DemandSecLevel.class);
final Root<AllocationEntry> allocationEntryRoot = subQuery.from(AllocationEntry.class);
subQuery.select(cb.construct(
DemandSecLevel.class,
allocationEntryRoot.get(AllocationEntry_.incidentDemandId),
cb.min(cb.coalesce(allocationEntryRoot.get(AllocationEntry_.securityLevel), -1))
.alias("minSecLevel"),
cb.max(cb.coalesce(allocationEntryRoot.get(AllocationEntry_.securityLevel), -1))
.alias("maxSecLevel")
));

JPA Criteria orderBy: unexpected AST node

I have the following criteria query, which retrieves some fields from Anfrage and Sparte entities and also the translated string for the sparte.i18nKey.
This works as expected if I dont use orderBy.
Now I have the requirement to sort by the translated string for sparte.i18nKey and using the orderBy as shown below, results in QuerySyntaxException: unexpected AST node
So the problem must be the subselect in the orderBy clause!
select distinct new
my.domain.model.dto.AnfrageDTO(
anfrage0.id,
anfrage0.name,
anfrage0.sparte.id,
anfrage0.sparte.i18nKey,
-- retrieve translated string for sparte.i18nKey
(select rb0.value from at.luxbau.mis2.domain.model.ResourceBundleEntity as rb0
where (anfrage0.sparte.i18nKey = rb0.key) and (rb0.language = 'de'))
)
from my.domain.model.impl.Anfrage as anfrage0
left join anfrage0.sparte as sparte
order by (
-- sort by translated string for sparte.i18nKey
select rb1.value
from my.domain.model.ResourceBundleEntity as rb1
where (anfrage0.sparte.i18nKey = rb1.key) and (rb1.language = 'de')
) asc
My Java code looks like this:
private List<AnfrageDTO> getAnfragen() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<AnfrageDTO> query = cb.createQuery(AnfrageDTO.class);
Root<Anfrage> anfrage = query.from(Anfrage.class);
anfrage.join(Anfrage_.sparte, JoinType.LEFT);
query.select(cb.construct(AnfrageDTO.class,
anfrage.get(Anfrage_.id),
anfrage.get(Anfrage_.name),
anfrage.get(Anfrage_.sparte).get(Sparte_.id),
anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey),
// create subquery for translated sparte.i18nKey
createResourceBundleSubQuery(cb, query, anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey)).getSelection()));
TypedQuery<AnfrageDTO> tq = entityManager
.createQuery(query)
// use subquery to sort by translated sparte.i18nKey
.orderBy(cb.asc(createResourceBundleSubQuery(cb, query, anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey))));
tq.setMaxResults(10);
List<AnfrageDTO> anfragen = tq.getResultList();
return anfragen;
}
public Subquery<String> createResourceBundleSubQuery(CriteriaBuilder cb, CriteriaQuery<?> query, <String> expr) {
Subquery<String> subquery = query.subquery(String.class);
Root<ResourceBundleEntity> rb = subquery.from(ResourceBundleEntity.class);
subquery
.select(rb.get(ResourceBundleEntity_.value))
.where(cb.and(
cb.equal(expr, rb.get(ResourceBundleEntity_.key)),
cb.equal(rb.get(ResourceBundleEntity_.language), "de")));
return subquery;
}
Using a native SQL query with subselect in orderBy works also as expected.
select distinct
anfrage0_.id,
anfrage0_.name,
anfrage0_.sparte_id,
sparte4_.i18n_key,
(select rb3.i18n_value from resource_bundle rb3 where rb3.language_code = 'de' and rb3.i18n_key = sparte4_.i18n_key) as sparte_i18n_value
from
mis2.anfrage anfrage0_
left outer join mis2.sparte sparte4_ on anfrage0_.sparte_id = sparte4_.id
order by (
select rb.i18n_value
from mis2.resource_bundle rb
where sparte4_.i18n_key = rb.i18n_key and rb.language_code = 'de'
) asc
Also using an alias in the native SQL query works also as expected.
select distinct
anfrage0_.id,
anfrage0_.name,
anfrage0_.sparte_id,
sparte4_.i18n_key,
(select rb3.i18n_value from resource_bundle rb3 where rb3.language_code = 'de' and rb3.i18n_key = sparte4_.i18n_key) as sparte_i18n_value
from
mis2.anfrage anfrage0_
left outer join mis2.sparte sparte4_ on anfrage0_.sparte_id = sparte4_.id
order by sparte_i18n_value
asc
It would be great if JPA Criteria API would support using an alias in orderBy clause!
Any hints welcome - Thank you!
My environment is WildFly 11 and PostgreSQL 9.6.
JPA doesn't support passing parameter in order by clause, your problem has been asked before: Hibernate Named Query Order By parameter

How to execute union query in zf2 where i m using tablegateway?

How to execute the following query
select * from table1 union select * from table2
in zend-framework2 where i am using tablegateway? In the documentation of zf2,they didn't give any details about union query.
Try -
$select1 = new Select('table1');
[.... rest of the code ....]
$select2 = new Select('table2');
[.... rest of the code ....]
$select1->combine($select2); //This will create the required SQL union statement.
To get count of the two tables you have to use a bit of SQL rather then tableGateway -
$sql = new Sql($this->tableGateway->adapter);
$select_string = $sql->getSqlStringForSqlObject($select1);
$sql_string = 'SELECT * FROM (' . $select_string . ') AS select_union';
$statement = $this->tableGateway->adapter->createStatement($sql_string);
$resultSet = $statement->execute();
$total_records = count($resultSet);
$resultSet gives data.
$total_records gives total no. of records.

how to convert count(*) and group by queries to yii and fetch data from it

I want to convert this query in yii
SELECT count(*) AS cnt, date(dt) FROM tbl_log where status=2 GROUP BY date(dt)
and fetch data from that. I try this command (dt is datetime field):
$criteria = new CDbCriteria();
$criteria->select = 'count(*) as cnt, date(dt)';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
but no data will fetch!
wath can I do to get data?
Probably you see no data because you need assign data to model attributes which doesn't exist.
$criteria = new CDbCriteria();
$criteria->select = 'count(*) AS cnt, date(dt) AS dateVar';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
This means that your model must have attributes cnt and dateVar in order to show your data. If you need custom query then check Hearaman's answer.
Try this below code
$logs = Yii::app()->db->createCommand()
->select('COUNT(*) as cnt')
->from('tbl_log') //Your Table name
->group('date')
->where('status=2') // Write your where condition here
->queryAll(); //Will get the all selected rows from table
Number of visitor are:
echo count($logs);
Apart from using cDbCriteria, to do the same check this link http://www.yiiframework.com/forum/index.php/topic/10662-count-on-a-findall-query/
If you use Yii2 and have a model based on table tbl_log, you can do it in model style like that:
$status = 2;
$result = Model::find()
->select('count(*) as cnt, date(dt)')
->groupBy('date(dt)')
->where('status = :status')
->params([':status' => $status ])
->all();

FQL WHERE IN with Null feedback in the array

I'm trying the command below:
SELECT * FROM mytable WHERE field IN(1,2,3, NULL, 5)
and the result is {r1,r2,r3}
I want {r1,r2,r3,NULL,r4}, how can I do that?
Thank you!
You can't. Facebook automatically filters out NULL results from the rows. There is also no guarantee that the results will be in the same order as the arguments you passed in your IN criteria.
You also can't SELECT * in FQL. You have to individually select fields to return.
You'll need to do something like this:
THINGS_TO_FIND = array (1,2,3,NULL,5)
RESULT = FQL_URL + urlencode('SELECT field1, field2 FROM table WHERE field1 IN ' + THINGS_TO_FIND')
foreach (THING in THINGS_TO_FIND) {
foreach (ITEM in RESULT) {
if THING == ITEM->field1 then OUTPUT->field1 = ITEM->field2
}
}