Liferay DynamicQuery - xPath and Array comparison - sql

My final goal is I want to get plid and portletId that can be display my article(or entry with any type if it is possible).
I have sql query that return me any portlet availble for display my article.
But when I have to use dynamicQuery to get the same results, I get problem with xPath and array comparison, please help!
SELECT * FROM portletpreferences pr
WHERE pr.preferences != '<portlet-preferences />' AND pr.ownerid = 0 AND pr.portletid ilike '%_INSTANCE_%' AND pr.plid IN(
SELECT layout.plid FROM layout
WHERE layout.type_ = 'portlet' AND layout.groupid = 19 AND layout.hidden_ is false)
AND pr.portletpreferencesid IN (
SELECT pr.portletpreferencesid FROM portletpreferences pr
WHERE 'true' = ANY(xpath('//preference[name="anyAssetType"]/value/text()', XMLPARSE(DOCUMENT pr.preferences))::text[])
OR (SELECT (array(SELECT id_ FROM journalstructure))::text[]) && xpath('//preference[name="classTypeIds"]/value/text()', XMLPARSE(DOCUMENT pr.preferences))::text[] )

If you are bent upon using this same query, then use this query directly with Custom-SQL in liferay by creating custom-finders instead of using DynamicQuery. That would give you a lot of flexibility in using any type of SQL query directly.
I don't think this query can be converted to DynamicQuery, but if you do manage to convert it then please do post it here :-)

DynamicQuery is very powerful, see e.g. my answer how to find layouts with specific JournalArticles. I think your requirement is similar to this one:
Liferay: How to find all Layouts with the specific JournalArticle in AssetPublisher portlets?

Related

Can't join FREETEXTTABLE with typeORM functions

I'm working on a graphQL backend with TypeORM
I found FREETEXT, CONTAiNS, FREETEXTTABLE and CONTAINSTABLE options for fulltext searching in my SQL database.
As FREETEXTTABLE has a "RANK column, it is more useful and I’m using this option.
I added required settings to the database and by below query it’s working correctly when applying the query directly into the database:
SELECT * FROM content
INNER JOIN freetexttable( content , *, 'test text') newtable ON newtable.[KEY] = "id"
ORDER BY newtable.RANK desc
OFFSET 0 ROWS FETCH NEXT 12 ROWS ONLY
But when I try to use it with TypeORM like below I have some errors.
import { getRepository } from "typeorm";
let repo = getRepository(Content)
return repo.createQueryBuilder("qb")
.innerJoin(FREETEXTTABLE( qb , *, 'light'), newtable,newtable.[KEY] = qb.id)
.skip(0)
.take(12)
.getManyAndCount();
And it returns this error:
"Error: Invalid object name 'FREETEXTTABLE( qb , *, 'light')'."
Could you please let me know if there is a problem with my code or maybe you know a better option for fulltext search in SQL database
I was searching for the same issue. I was unable to find a solution to use FREETEXTTABLE with typeorm, so I had to implement it using raw SQL. using below code
repo.query(" RAW SQL ")

Syntax error on WITH clause

I am working on a web app and there are some long winded stored procedures and just trying to figure something out, I have extracted this part of the stored proc, but cant get it to work. The guy who did this is creating alias after alias.. and I just want to get a section to work it out. Its complaining about the ending but all the curly brackets seem to match. Thanks in advance..
FInputs is another stored procedure.. the whole thing is referred to as BASE.. the result of this was being put in a temp table where its all referred to as U. I am trying to break it down into separate sections.
;WITH Base AS
(
SELECT
*
FROM F_Inputs(1,1,100021)
),
U AS
(
SELECT
ISNULL(q.CoverPK,r.CoverPK) AS CoverPK,
OneLine,
InputPK,
ISNULL(q.InputName,r.InputName) AS InputName,
InputOrdinal,
InputType,
ParentPK,
InputTriggerFK,
ISNULL(q.InputString,r.InputString) AS InputString,
PageNo,
r.RatePK,
RateName,
Rate,
Threshold,
ISNULL(q.Excess,r.Excess) AS Excess,
RateLabel,
RateTip,
Refer,
DivBy,
RateOrdinal,
RateBW,
ngRequired,
ISNULL(q.RateValue,r.RateValue) AS RateValue,
ngClass,
ngPattern,
UnitType,
TableChildren,
TableFirstColumn,
parentRatePK,
listRatePK,
NewParentBW,
NewChildBW,
ISNULL(q.SumInsured,0) AS SumInsured,
ISNULL(q.NoItems,0) AS NoItems,
DisplayBW,
ReturnBW,
StringBW,
r.lblSumInsured,
lblNumber,
SubRateHeading,
TrigSubHeadings,
ISNULL(q.RateTypeFK,r.RateTypeFK) AS RateTypeFK,
0 AS ListNo,
0 AS ListOrdinal,
InputSelectedPK,
InputVis,
CASE
WHEN ISNULL(NewChildBW,0) = 0
THEN 1
WHEN q.RatePK is NOT null
THEN 1
ELSE RateVis
END AS RateVis,
RateStatus,
DiscountFirstRate,
DiscountSubsequentRate,
CoverCalcFK,
TradeFilter,
ngDisabled,
RateGroup,
SectionNo
FROM BASE R
LEFT JOIN QuoteInputs Q
ON q.RatePK = r.RatePK
AND q.ListNo = 0
AND q.QuoteId = 100021 )
Well, I explained the issue in the comments section already. I'm doing it here again, so future readers find the answer more easily.
A WITH clause is part of a query. It creates a view on-the-fly, e.g.:
with toys as (select * from products where type = 'toys') select * from toys;
Without the query at the end, the statement is invalid (and would not make much sense anyhow; if one wanted a permanent view for later use, one would use CREATE VIEW instead).

looking for db2 text function or method I can do a text contain rather than like

I'm looking for a db2 function that does a text contain search. At present I am running the following query against the data below....
SELECT distinct
s.search_id,
s.search_heading,
s.search_url
FROM repman.search s, repman.search_tags st
WHERE s.search_id = st.search_id
AND ( UPPER(s.search_heading) LIKE (cast('%REPORT%' AS VARGRAPHIC(32)))
OR (UPPER(st.search_tag) LIKE cast('%REPORT%' AS VARGRAPHIC(32)))
)
ORDER BY s.search_heading;
Which returns...
But if I change the search text to %REPORTS% rather than %REPORT% (which I need to do) the like search does not work and I get zero results.
I read a link that used a function named CONTAINS like below but when trying to use the function I get an error.
SELECT distinct
s.search_id,
s.search_heading,
s.search_url
FROM repman.search s, repman.search_tags st
WHERE s.search_id = st.search_id
AND CONTAINS(s.search_heading, 'REPORTS') = 1
Has anynoe got any suggestions? I'm on db2 version DB2/LINUXPPC 9.1.6.
Thanks
In order to look for a pattern in a string, you can use Regular Expressions. They are built-in DB2 with xQuery since DB2 v9. There are also other ways to do that. I wrote an article in my blog (in Spanish that you can translate) about Regular Expressions in DB2.
xmlcast(xmlquery('fn:matches(\$TEXT,''^[A-Za-z 0-9]*$'')')

Django select only rows with duplicate field values

suppose we have a model in django defined as follows:
class Literal:
name = models.CharField(...)
...
Name field is not unique, and thus can have duplicate values. I need to accomplish the following task:
Select all rows from the model that have at least one duplicate value of the name field.
I know how to do it using plain SQL (may be not the best solution):
select * from literal where name IN (
select name from literal group by name having count((name)) > 1
);
So, is it possible to select this using django ORM? Or better SQL solution?
Try:
from django.db.models import Count
Literal.objects.values('name')
.annotate(Count('id'))
.order_by()
.filter(id__count__gt=1)
This is as close as you can get with Django. The problem is that this will return a ValuesQuerySet with only name and count. However, you can then use this to construct a regular QuerySet by feeding it back into another query:
dupes = Literal.objects.values('name')
.annotate(Count('id'))
.order_by()
.filter(id__count__gt=1)
Literal.objects.filter(name__in=[item['name'] for item in dupes])
This was rejected as an edit. So here it is as a better answer
dups = (
Literal.objects.values('name')
.annotate(count=Count('id'))
.values('name')
.order_by()
.filter(count__gt=1)
)
This will return a ValuesQuerySet with all of the duplicate names. However, you can then use this to construct a regular QuerySet by feeding it back into another query. The django ORM is smart enough to combine these into a single query:
Literal.objects.filter(name__in=dups)
The extra call to .values('name') after the annotate call looks a little strange. Without this, the subquery fails. The extra values tricks the ORM into only selecting the name column for the subquery.
try using aggregation
Literal.objects.values('name').annotate(name_count=Count('name')).exclude(name_count=1)
In case you use PostgreSQL, you can do something like this:
from django.contrib.postgres.aggregates import ArrayAgg
from django.db.models import Func, Value
duplicate_ids = (Literal.objects.values('name')
.annotate(ids=ArrayAgg('id'))
.annotate(c=Func('ids', Value(1), function='array_length'))
.filter(c__gt=1)
.annotate(ids=Func('ids', function='unnest'))
.values_list('ids', flat=True))
It results in this rather simple SQL query:
SELECT unnest(ARRAY_AGG("app_literal"."id")) AS "ids"
FROM "app_literal"
GROUP BY "app_literal"."name"
HAVING array_length(ARRAY_AGG("app_literal"."id"), 1) > 1
Ok, so for some reason none of the above worked for, it always returned <MultilingualQuerySet []>. I use the following, much easier to understand but not so elegant solution:
dupes = []
uniques = []
dupes_query = MyModel.objects.values_list('field', flat=True)
for dupe in set(dupes_query):
if not dupe in uniques:
uniques.append(dupe)
else:
dupes.append(dupe)
print(set(dupes))
If you want to result only names list but not objects, you can use the following query
repeated_names = Literal.objects.values('name').annotate(Count('id')).order_by().filter(id__count__gt=1).values_list('name', flat='true')

DISTINCT is not working

SQL query in Ms-Access
INSERT INTO tblTmpEventLog( TrackingNumber, PartNumber, PartNumberChgLvl,
EnteredBy, EventTypeSelected, EventDate )
SELECT DISTINCT tblRevRelLog_Detail.RevRelTrackingNumber,
tblRevRelLog_Detail.PartNumber, tblRevRelLog_Detail.ChangeLevel,
[Forms]![frmEventLog_Input]![EnteredBy] AS EnteredBy,
[Forms]![frmEventLog_Input]![EventTypeSelected] AS EventTypeSelected,
CDate([Forms]![frmEventLog_Input]![EventDate]) AS EventDate
FROM tblRevRelLog_Detail LEFT JOIN tblEventLog
ON (tblEventLog.PartNumber = tblRevRelLog_Detail.PartNumber)
AND (tblEventLog.PartNumberChgLvl = tblRevRelLog_Detail.ChangeLevel)
WHERE ((([tblRevRelLog_Detail]![RevRelTrackingNumber]) =
[Forms]![frmEventLog_Input]![TrackingNumber]))
AND ((tblEventLog.PartNumber) NOT IN
(SELECT tblEventLog.PartNumber FROM tblEventLog
WHERE tblEventLog.EventTypeSelected = 'pn REMOVED From Wrapper'
AND tblEventLog.TrackingNumber =
tblRevRelLog_Detail.RevRelTrackingNumber
AND tblEventLog.PartNumber = tblRevRelLog_Detail.PartNumber
AND tblEventLog.PartNumberChgLvl =
tblRevRelLog_Detail.ChangeLevel
));
DISTINCT keyword for EnteredBy, EventTypeSelected is not working..I mean, data for these columns is not displaying when I use DISTINCT keyword.
EVENTDATE is working fine, but I do not understand why is it not displaying for EneteredBy and EventTypeSelected columns.
Can anyone tell me how to handle this?
It may be that the query can't interpret properly from the form directly as the final data type. However in your date field, you are wrapping it in a function CDATE( ... ). So, the SQL engine knows the result type. I would suggest doing the same for the other fields. Ex: doing a CAST ( ...your form control... as DateTime ) as OtherColumn, etc... I THINK Access allows casting, but not positive. Otherwise, pre-pull the form value into a declared data type variable and use THAT variable in the query AS OtherColumn as you are doing.
Additionally to what #Jack mentioned, you can always go back to your account, look at your historical question, and click on whatever answers actually helped / solve your problems. Some questions never do get answers and that's ok, just give credit to those that DO help.
I have found in the past (I don't remember which old version of Access this was) that if you set the value of a form control in VBA, and then use that control in a query, the query will not see the value you set in VBA. If the user edits the control normally, the query sees the expected value. Perhaps that's what happened here.
To work around that, you can declare a VBA function that returns the desired value. For example, instead of this:
SELECT ..., Forms!MainForm!TextEntry AS TextEntry, ... FROM ...
use this:
SELECT ..., GetTextEntry() AS TextEntry, ... FROM ...
along with this:
Public Function TextEntry() As Variant
TextEntry = Forms!MainForm!TextEntry
End Function