What is the django ORM query for this sql query? - postgresql

Can this query be translated to Django ORM. This works in postgresql.
select * from user_feed_moderation
left join user_feed_moderator on mod_id=user_id
where
is_mod_available=false and
is_moderated = false order
by created_on
currently I am forced to run a raw sql query in django.
These are my models
class Moderator(models.Model):
is_mod_available = models.BooleanField(default=False)
user_id = models.BigIntegerField()
class Moderation(TimeStampedModel):
mod_id = models.BigIntegerField(null=True)
post_id = models.BigIntegerField()
content_type = models.CharField(max_length = 3, choices=ContentTypes.choices)
is_moderated = models.BooleanField(default=False)

Related

Retrieve data from MongoDB using Mongolite nested query

I am using mongolite package to retrieve data from MongoDB using R script. I need one framework data to be input to other. As below
connecting mongodb
library(mongolite)
mongoSample<-mongolite::mongo(collection = "Sample1", db = "Test", url =
"mongodb://User:123#Wyyuyu:13333/ty2_U",verbose = TRUE)
mongoSample2<-mongolite::mongo(collection = "Sample2", db = "Test", url =
"mongodb://User:123#Wyyuyu:13333/ty2_U",verbose = TRUE)
getting specific data from collection below query is working fine.
D$find(query = '{"_id": "xyz"}', fields = "{\"_id\":1, \"description\":1,\"name\":1}", sort = "{}", skip = 0, limit = 0, handler = NULL, pagesize = 1000)
But I want to filter passing values from another framework.
**As in SQL
SELECT * FROM Sample1 WHERE Id IN (SELECT Id FROM Sample2)
Any help on this will be much appreciated.

JPA use stored procedure in criteria query

I'm trying to define a criteria query with a function in select and in where statement.
The SQL query is:
select s.*, contr_topay(s.id) as rest
from spedizionestd s
where contr_topay(s.id) >0
... other conditions
... optional order by
contr_topay is the procedure in the database (Postgresql). I've defined a NamedStoredProcedure:
#NamedStoredProcedureQuery(
name = "MovimentoContrassegno.contr_topay",
procedureName = "contr_topay",
parameters = {
#StoredProcedureParameter(mode = ParameterMode.IN, queryParameter = "idsped", type = Long.class, optional = false),
#StoredProcedureParameter(mode = ParameterMode.OUT, queryParameter="importo", type=Double.class, optional = false),
}
)
and called it with success:
StoredProcedureQuery query = this.em.createNamedStoredProcedureQuery("MovimentoContrassegno.contr_dapagare");
query.setParameter("idsped", myid);
query.execute();
return (Double) query.getOutputParameterValue(2);
Now, how can I put the procedure in the select clause and in the where condition inside a criteria query?
NB: i need criteria query because I build dynamic query with additional where conditions and "order by" choised by the user at runtime
(I'm using eclipselink 2.6.0)

How to get List of Table Entity with only selected columns in Hibernate using native SQL?

I am trying to execute SQL query using session.createSQLQuery() method of Hibernate.
test table has 3 columns :
col1
col2
col3
Working
String sql = "SELECT * FROM test";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Test.class);
List<Test> testEntityList = query.list();
Not Working
String sql = "SELECT col1, col2 FROM test";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Test.class);
List<Test> testEntityList = query.list();
Error:
The column col3 was not found in this ResultSet.
I need to retrieve only a few specific columns from the table rather than the whole table.
How can I achieve this?
You can use hibernate projections, see this answer Hibernate Criteria Query to get specific columns or you can do this by changing the return type to
List<Object[]> and parsing it to List<Test>
List<Object[]> testEntityList = query.list();
List<Test> res = new ArrayList<Test>(testEntityList.size());
for (Object[] obj : testEntityList) {
Test test = new Test();
test.setCol1(obj[0]);
test.setCol2(obj[1]);
res.add(test);
}

jpa and native queries

I faced with a strange thing with native queries:
If I'm trying to use named native query like the following
#NamedNativeQuery(name = "native_count_avg_guest_quizzes", resultClass = java.math.BigDecimal.class, query = "select avg(c) as r from ((select count(*) as c from user_quiz uq join user u on (uq.user_id = u.id) where u.status = 'temporary' group by u.id) as res)")
The application cannot run and I have
org.hibernate.HibernateException: Errors in named queries: native_count_avg_guest_quizzes_
But the same query works fine if I do not use NamedNativeQuery and merely create a dynamic native query like the following:
entityManager.createNativeQuery(
"select avg(c) as r from ((select count(*) as c from user_quiz uq join user u on (uq.user_id = u.id) where u.status = 'temporary' group by u.id) as res)")
.getSingleResult()
Why? What I'm doing wrong with NamedNativeQuery? Thanks
Update:
Entity class is as following
#Entity
#Table(name = "user_quiz")
#NamedNativeQueries({
#NamedNativeQuery(name = "native_count_avg_guest_quizzes", resultClass = java.math.BigDecimal.class, query = "select avg(c) as r from ((select count(*) as c from user_quiz uq join user u on (uq.user_id = u.id) where u.status = 'temporary' group by u.id) as res)")
})
#NamedQueries({
#NamedQuery(name = "list_clients_quizzes", query = "select uq from UserQuiz uq where uq.quiz.client.id = :clientId"),
.......
})
public class UserQuiz extends Measurable {
.......
}
createNativeQuery is used for native SQL query language that mean DB can understand and execute that query (Eg, select * from some_table where id = '0001');
It may cause DB dependency. Now you are using JPQL language, that's why, use createQuery() or createNameQuery() with #NameQuery annotation sing.
Example :
#NameQuery
#NamedQuery(name = "findAllEmployee", query = "select e from Employee e")
#Entity
public class Employee {
#Id int id;
String name;
// ...
}
Query query = em.createNamedQuery("findAllEmployee");
query.getResultList()
Dynamic
Query query = em.createQuery("select e from Employee e");
query.getResultList()?
*Native
Query query = em.createNativeQuery("SELECT * FROM EMPLOYEE_TBL");
query.getResultList()?
Delete resultClass from #NamedNativeQuery.
See https://stackoverflow.com/a/9763489
For NamedNativeQueries you can only use resultClass when the result actually maps to an Entity.

Entity Framework - Select * from Entities where Id = (select max(Id) from Entities)

I have an entity set called Entities which has a field Name and a field Version. I wish to return the object having the highest version for the selected Name.
SQL wise I'd go
Select *
from table
where name = 'name' and version = (select max(version)
from table
where name = 'name')
Or something similar. Not sure how to achieve that with EF. I'm trying to use CreateQuery<> with a textual representation of the query if that helps.
Thanks
EDIT:
Here's a working version using two queries. Not what I want, seems very inefficient.
var container = new TheModelContainer();
var query = container.CreateQuery<SimpleEntity>(
"SELECT VALUE i FROM SimpleEntities AS i WHERE i.Name = 'Test' ORDER BY i.Version desc");
var entity = query.Execute(MergeOption.OverwriteChanges).FirstOrDefault();
query =
container.CreateQuery<SimpleEntity>(
"SELECT VALUE i FROM SimpleEntities AS i WHERE i.Name = 'Test' AND i.Version =" + entity.Version);
var entity2 = query.Execute(MergeOption.OverwriteChanges);
Console.WriteLine(entity2.GetType().ToString());
Can you try something like this?
using(var container = new TheModelContainer())
{
string maxEntityName = container.Entities.Max(e => e.Name);
Entity maxEntity = container.Entities
.Where(e => e.Name == maxEntityName)
.FirstOrDefault();
}
That would select the maximum value for Name from the Entities set first, and then grab the entity from the entity set that matches that name.
I think from a simplicity point of view, this should be same result but faster as does not require two round trips through EF to sql server, you always want to execute query as few times as possible for latency, as the Id field is primary key and indexed, should be performant
using(var db = new DataContext())
{
var maxEntity = db.Entities.OrderByDecending(x=>x.Id).FirstOrDefault()
}
Should be equivalent of sql query
SELECT TOP 1 * FROM Entities Order By id desc
so to include search term
string predicate = "name";
using(var db = new DataContext())
{
var maxEntity = db.Entities
.Where(x=>x.Name == predicate)
.OrderByDecending(x=>x.Id)
.FirstOrDefault()
}
I think something like this..?
var maxVersion = (from t in table
where t.name == "name"
orderby t.version descending
select t.version).FirstOrDefault();
var star = from t in table
where t.name == "name" &&
t.version == maxVersion
select t;
Or, as one statement:
var star = from t in table
let maxVersion = (
from v in table
where v.name == "name"
orderby v.version descending
select v.version).FirstOrDefault()
where t.name == "name" && t.version == maxVersion
select t;
this is the easiest way to get max
using (MyDBEntities db = new MyDBEntities())
{
var maxReservationID = _db .LD_Customer.Select(r => r.CustomerID).Max();
}