fetching values from an aggregate function - JPQL - jpql

I am trying to use a named query but it does not work:
#NamedQuery(name = "Uscensuspopulationdata.fetchmostpopstate", query = "SELECT MAX(u.pop2010) FROM Uscensuspopulationdata where u.pop2010 <> 0")
Uscensuspopulationdata is an entity. what mistake am i doing? this is the error:
FailedPredicateException(arithmeticPrimary,{ aggregatesAllowed() }?)

The exception isn't very descriptive, but it doesn't seem you've defined what 'u' is in the query you've shown. Try "..Uscensuspopulationdata u where.." or a different JPA provider to see if you can get an exception that might provide more detail to help point you in the right direction.

Related

Python Simple Salesforce Select AS Not Working

I'm trying the standard SELECT ... AS call to rename a column in query output with the Python Salesforce API and it's throwing following error:
... unexpected token: 'AS'", 'errorCode': 'MALFORMED_QUERY'}
So far most native language calls from SOQL have been working in the API and it seems, from here, that SELECT ... AS is valid SOQL.
Query outline:
from simple_salesforce import Salesforce
sf = Salesforce(username=myusername, password=mypassword, security_token=mytoken)
query = "select closedate as Date from opportunity"
query_list = sf.query_all(query)['records']
edit
error remains even after putting the new column name within quotes as advised in above link:
query = "select closedate as \"Date\" from Opportunity"
Thanks
As Terminus mentioned, SOQL field aliasing is not possible in SOQL in most contexts, including yours. The only case in which I have seen aliasing working in SOQL is in aggregate queries. For example, in apex you could write:
AggregateResult myResult = [SELECT count(Id) SpecialName FROM Contact];
system.debug(myResult);
and receive the result:
DEBUG|AggregateResult:{SpecialName=1630}
In python via simple-salesforce it would look like this:
sf.query_all('SELECT count(Id) SpecialName FROM Contact')
with the result:
OrderedDict([('totalSize', 1),
('done', True),
('records',
[OrderedDict([('attributes',
OrderedDict([('type', 'AggregateResult')])),
('SpecialName', 6587)])])])
Please mark as answered if this answer your question.
The syntax seems to be incorrect.
Try query = "select closedate <insert alias> from Opportunity" according to the alias notation documented here : https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_alias.htm

How to add a condition in "ON" cause of "LEFT JOIN" in PonyORM

I want to run the following query in PonyORM.
SELECT af.AppFormID, af.AppFormTitle, ra.CreateGrant, ra.ReadGrant, ra.UpdateGrant, ra.DeleteGrant, ra.PrintGrant
FROM public.appforms as af left join public.roleaccesses as ra
on af.appformid = ra.appformid and ra.roleid = 2
if you see the last part of the code, I added a condition in "ON" cause.
I tried to write the following code in python.
query= orm.left_join((af.AppFormID, af.AppFormTitle, ra.CreateGrant, ra.ReadGrant, ra.UpdateGrant, ra.DeleteGrant, ra.PrintGrant) for af in AppForms for ra in af.RoleAccess if ra.RoleID.RoleID == id)
But, "if" is known as "WHERE" cause. How can I solve this problem?
Thank for any help.
Current version of PonyORM (0.7.6) does not support additional conditions in LEFT JOIN clause. But I agree that this is a useful feature.
Please add a new issue here: https://github.com/ponyorm/pony/issues
I do not guarantee that it will be implemented quickly, but eventually we will add it.
Until this, you need to write a raw SQL query:
role_id = 2
rows = db.select("""
SELECT af.AppFormID, af.AppFormTitle,
ra.CreateGrant, ra.ReadGrant,
ra.UpdateGrant, ra.DeleteGrant, ra.PrintGrant
FROM public.appforms as af
LEFT JOIN public.roleaccesses as ra
ON af.appformid = ra.appformid and ra.roleid = $role_id
""")

Automapper Project().To Error A query body must end with a select

I'm trying to prevent that a query to an entity bring more columns than necessary. Should only bring those columns specified in the target model.
Below is my code built following some examples to achieve my goal but I get syntax error "A query body must end with a select clause or a group clause linq”
int the query line.
var studentEventsModel = from c in DbContext.StudentEvent.Project().To<StudentEventViewModel>();
Please let me know what I’m doing wrong.
public IEnumerable<StudentEventViewModel> GetStudentEventsListViewModel()
{
Mapper.CreateMap<StudentEvent, StudentEventViewModel>();
var studentEventsModel = from c in DbContext.StudentEvent.Project().To<StudentEventViewModel>();
return studentEventsModel;
}
As #hometoast mentioned you may add select at the end of your query like this:
var studentEventsModel =
from c in DbContext.StudentEvent.Project().To<StudentEventViewModel>() select c;
or alerternatively you may use the lambda expression like this:
var studentEventsModel = DbContext.StudentEvent.Project().To<StudentEventViewModel>();
And as to the question on why you are seeing that error, it is due to the fact that a query syntax must end with select or group, mentioned here in the documentation.
A query expression must begin with a from clause and must end with a
select or group clause. Between the first from clause and the last
select or group clause, it can contain one or more of these optional
clauses: where, orderby, join, let and even additional from clauses.
You can also use the into keyword to enable the result of a join or
group clause to serve as the source for additional query clauses in
the same query expression.

Astyanax parepared statement withvalues() not working properly

today I migrated to Astyanax 1.56.42 and discovered, that withValues() on prepared statements doesn't seem to work properly with SQL SELECT...WHERE...IN ().
ArrayList<ByteBuffer> uids = new ArrayList<ByteBuffer>(fileUids.size());
for (int i = 0; i < fileUids.size(); i++) {
uids.add(ByteBuffer.wrap(UUIDtoByteArray(fileUids.get(i)), 0, 16));
}
result = KEYSPACE.prepareQuery(CF_FILESYSTEM)
.withCql("SELECT * from files where file_uid in (?);")
.asPreparedStatement()
.withValues(uids)
.execute();
If my ArrayList contains more than one entry, this results in error
SEVERE: com.netflix.astyanax.connectionpool.exceptions.BadRequestException: BadRequestException: [host=hostname(hostname):9160, latency=5(5), attempts=1]InvalidRequestException(why:there were 1 markers(?) in CQL but 2 bound variables)
What am I doing wrong? Is there any other way to handle a SQL SELECT...WHERE...IN () - statement or did I find a bug?
Best regards
Chris
As you mentioned because you are supplying a collection (ArrayList) to a single ? Astyanax throws an exception. I think you need to add a ? for each element you want to have inside the IN clause.
Say you want to have 2 ints stored in an ArrayList called arrayListObj the where clause, your statement looks like this:
SELECT & FROM users WHERE somevalue IN (arrayListObj);
Because you are suppling a collection, this cant work, so you will need multiple ?'s. I.e. you want :
SELECT name, occupation FROM users WHERE userid IN (arrayListObj.get(0), arrayListObj.get(1));
I couldn't find anything on the Astyanax wiki about using the IN clause with prepared statements.

Nhibernate linq where clause with boolean value

If I try to add a where clause, containing a lambda filter on a boolean field, to a nhibernate linq query, the filter seems to be ignored:
var result = Session.Linq().Where(x=> x.Approved);
Session is an iSession and Newspaper is a simple object with the fields NewspaperId int, Name - varchar(50) and Approved - bit.
When I run this the following sql is generated:
SELECT this_.NewspaperId as Newspape1_33_0_, this_.Name as Name33_0_, this_.Approved as Approved33_0_, FROM Newspapers this_
it seems to ignore the lambda if it is for a boolean field.
It works fine for the name field, ie:
var result = Session.Linq().Where(x=> x.Name == "The Times");
results in:
exec sp_executesql N'SELECT this_.NewspaperId as Newspape1_33_0_, this_.Name as Name33_0_, this_.Approved as Approved33_0_ FROM Newspapers this_ WHERE this_.Name = #p0',N'#p0 nvarchar(9)',#p0=N'The Times'
Anybody know why I can't query on a boolean value?
Any help is greatly appreciated
I am using NHibernate 2.1 with linq
It's been a while so you've probably got your answer somewhere else a long time ago. But to answer your question: I can't see a reason why this wouldn't work. Actually I've tried it out in both NH2.1.2 and NH3.0.0. It works in both (verified by looking at the query with SQL Profiler). So it would be interesting to see the mapping you used, perhapse there's something wrong there.

Resources