How to write Prisma queryRaw Mysql iLike correctly? - prisma

I’m using Prisma at nextJs. So, I have this working query:
export async function findMembersByNameRaw(name: string) {
const namesearch = '%name.toLowerCase()%'
const memberName = await prisma.$queryRaw `SELECT
zm.pe_id, pe.uid, pe.name, pe.gender, pe.year, zm.za_id,
z.za, se.sek
FROM
zm,
z,
se,
pe
WHERE
pe.name like '%plato%'
AND zm.people_id = pe.id
AND zm.zawiyah_id = z.id
AND z.sektor_id = se.id
ORDER BY
pe.id ASC
`
return memberName;
}
But I need to pass variable name to that queryRaw. How should I wrote that correctly?
Refer to PrismaDocs there is only for Postgres sample but not working in mySQL ($1 not recognize variable).

Based on this answer, I can write it correctly but change to this:
export async function findMembersByNameRaw(name: string) {
const namesearch = '%${name}%'
const memberName = await prisma.$queryRaw `SELECT
zm.pe_id, pe.uid, pe.name, pe.gender, pe.year, zm.za_id,
z.za, se.sek
FROM
zm,
z,
se,
pe
WHERE
pe.name like '${namesearch}’
AND zm.people_id = pe.id
AND zm.zawiyah_id = z.id
AND z.sektor_id = se.id
ORDER BY
pe.id ASC
`
return memberName;
}

Related

Distinct with joins

How do I get distinct rows based on the Last_Name field when my format is as follows:
public ActionResult Index()
{
ResumeDbEntities srd = new ResumeDbEntities();
List<M_Employees> First_Name = srd.M_Employees.ToList();
List<M_Employees> Last_Name = srd.M_Employees.ToList();
List<M_Employees> CurrentLaborCategory = srd.M_Employees.ToList();
List<M_Offices> Location_Number = srd.M_Offices.ToList();
List<M_Offices> City = srd.M_Offices.ToList();
List<M_Offices> State = srd.M_Offices.ToList();
List<S_Emp_Resume> Resume_Name = srd.S_Emp_Resume.ToList();
var multipleTbl = (from p in Resume_Name
join t in Last_Name on p.Employee_Rec_Key equals t.Employee_Rec_Key
join o in Location_Number on t.Office_Rec_Key equals o.Office_Rec_Key
where t.Employee_Rec_Key == 3633
select new MultipleClassRes { M_Employeesdetails = t, S_Emp_Resumedetails = p, M_Officesdetails = o});
return View(multipleTbl);
}
Newly working with MVC but included the auto number from one of the joins.

How to improve query with two contexts - MVC5, LINQ n EF

I have two contexts. In one of them i have two views of which i get cods related to an entity from the another context. This query is taking too long time. How to improve it?
var negociacoes = _db.Negociacoes.Include(o=> o.User).ToArray();
var produtos = _oriDb.Vw_Produtos.ToArray();
var clientesVendedor = _oriDb.Vw_ClientesVendedores.ToArray();
var query = from n in negociacoes
join p in produtos on n.ProdutoId equals p.ProdutoId
join c in clientesVendedor on n.ClienteId equals c.codigo_entidade
select new NegociacaoView
{
NegociacaoId = n.NegociacaoId,
ProdutoId = n.ProdutoId,
Produto = p.descricao,
ClienteId = n.ClienteId,
Cliente = c.razao_social,
Rca = n.Rca,
Quantidade = n.Quantidade,
Preco = n.Preco,
Situacao = n.Situacao,
UserId = n.User.UserName,
Atendente = n.Atendente,
CondicaoId = n.CondicaoId,
DataCriacao = n.DataCriacao,
DataLiberacao = n.DataLiberacao,
Observacao = n.Observacao,
User = n.User
};
return query.ToList();
There are a couple of ways to speed this up:
It helps to run the smallest most efficient query first, then use those results to constrain the following queries.
Defining a select list so the database doesn't have to materialize every column will speed things up and use less memory.
Unfortunately, no matter how you do it in LINQ, you will end up with sql that uses large IN statements. A sproc would give you access to temp tables and joins that would be even better.
var negociacoes = _db.Negociacoes.Include(o=> o.User).ToArray();
//Use results of first query to constrain the second two. You could maybe combine the second two into one query.
var clientIds = negociacoes.Select(x => x.ClienteId);
var productIds = negociacoes.Select(x => x.ProdutoId);
var produtos = _oriDb.Vw_Produtos
.Where(x => productIds.Contains(x.ProdutoId))
//add a select. You're only using two columns from this table.
//.Select(x => new { })
.ToArray();
var clientesVendedor = _oriDb.Vw_ClientesVendedores
.Where(x => clientIds.Contains(x.codigo_entidade))
//add a select. You're only using two columns from this table.
//.Select(x => new { })
.ToArray();
var query = from n in negociacoes
join p in produtos on n.ProdutoId equals p.ProdutoId
join c in clientesVendedor on n.ClienteId equals c.codigo_entidade
select new NegociacaoView
{
NegociacaoId = n.NegociacaoId,
ProdutoId = n.ProdutoId,
Produto = p.descricao,
ClienteId = n.ClienteId,
Cliente = c.razao_social,
Rca = n.Rca,
Quantidade = n.Quantidade,
Preco = n.Preco,
Situacao = n.Situacao,
UserId = n.User.UserName,
Atendente = n.Atendente,
CondicaoId = n.CondicaoId,
DataCriacao = n.DataCriacao,
DataLiberacao = n.DataLiberacao,
Observacao = n.Observacao,
User = n.User
};
return query.ToList();

EF Append to an IQueryable a Where that generates an OR

I'm trying to achieve dynamic filtering on a table. My UI has filters that can be enabled or disabled on demand, and as you can imagine, my query should be able to know when to add filters to the query.
What I have so far is that I check if the filter object has a value, and if it does it adds a where clause to it. Example:
var q1 = DBContext.Table1
if (!string.IsNullOrEmpty(filterModel.SubjectContains))
q1 = q1.Where(i => i.Subject.Contains(filterModel.SubjectContains));
if (filterModel.EnvironmentId != null)
q1 = q1.Where(i => i.EnvironmentId == filterModel.EnvironmentId);
if (filterModel.CreatedBy != null)
q1 = q1.Where(i => i.CreatedByUserId == filterModel.CreatedBy);
var final = q1.Select(i => new
{
IssuesId = i.IssuesId,
Subject = i.Subject,
EnvironmentId = i.EnvironmentId,
CreatedBy = i.CreatedByUser.FullName,
});
return final.ToList();
The code above generates T-SQL that contains a WHERE clause for each field that uses AND to combine the conditions. This is fine, and will work for most cases.
Something like:
Select
IssueId, Subject, EnvironmentId, CreatedById
From
Table1
Where
(Subject like '%stackoverflow%')
and (EnvironmentId = 1)
and (CreatedById = 123)
But then I have a filter that explicitly needs an IssueId. I'm trying to figure out how the EF Where clause can generate an OR for me. I'm looking something that should generate a Tsql that looks like this:
Select
IssueId, Subject, EnvironmentId, CreatedById
From
Table1
Where
(Subject like '%stackoverflow%')
and (EnvironmentId = 1)
and (CreatedById = 123)
or (IssueId = 10001)
Found a solution for this that doesn't have to do multiple database call and works for me.
//filterModel.StaticIssueIds is of type List<Int32>
if (filterModel.StaticIssueIds != null)
{
//Get all ids declared in filterModel.StaticIssueIds
var qStaticIssues = DBContext.Table1.Where(i => filterModel.StaticIssueIds.Contains(i.IssuesId));
//Let's get all Issues that isn't declared in filterModel.StaticIssueIds from the original IQueryable
//we have to do this to ensure that there isn't any duplicate records.
q1 = q1.Where(i => !filterModel.StaticIssueIds.Contains(i.IssuesId));
//We then concatenate q1 and the qStaticIssues.
q1 = q1.Concat(qStaticIssues);
}
var final = q1.Select(i => new
{
IssuesId = i.IssuesId,
Subject = i.Subject,
EnvironmentId = i.EnvironmentId,
CreatedBy = i.CreatedByUser.FullName,
});
return final.ToList();

JPA criteria: count from multiselect query

I want to implement a table component with pagination. The result in the table is retrieved by a multiselect-query like this:
SELECT DISTINCT t0.userId,
t0.userName,
t1.rolleName
FROM userTable t0
LEFT OUTER JOIN roleTable t1 ON t0.userId = t1.fkUser
WHERE(t0.userType = 'normalUser' AND t1.roleType = 'loginRole')
This result I can get via a multiselect-query.
Now for the pagination I have to retrieve the total rowcount at first.
Is there anybody who can define a criteriaquery for one of this sql? I failed because a subquery does not support multiselects and I do not know how to get this distinct into a count statement.
SELECT COUNT(*) FROM
(
SELECT DISTINCT t0.userId,
t0.userName,
t1.rolleName
FROM userTable t0
LEFT OUTER JOIN roleTable t1 ON t0.userId = t1.fkUser
WHERE(t0.userType = 'normalUser' AND t1.roleType = 'loginRole')
)
or
SELECT COUNT(DISTINCT t0.userId || t0.userName || t1.rolleName)
FROM userTable t0
LEFT OUTER JOIN roleTable t1 ON t0.userId = t1.fkUser
WHERE(t0.userType = 'normalUser' AND t1.roleType = 'loginRole')
Thanks in advance!
Btw. I am using OpenJpa on a WebSphere AppServer
The following is not tested but should work:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> query = builder.createQuery(Long.class);
Root<User> t0 = query.from(User.class);
Join<User, Role> t1 = t0.join("roles", JoinType.LEFT);
query.select(builder.concat(t0.get(User_.userId), builder.concat(t0.get(User_.userName), t1.get(Role_.rolleName))).distinct(true);
query.where(cb.equal(t0.get("userType"), "normalUser"), cb.equal(t1.get("roleType"), "loginRole"));
TypedQuery<Long> tq = em.createQuery(query);
Due to known issue https://jira.spring.io/browse/DATAJPA-1532 Multiselect does not work with repo.findall method. I handled this by autowiring entity manager to service class.
#Autowired
EntityManager entityManager;
public List<?> getResults() throws ParseException
{
//ModelSpecification modelSpecification = new ModelSpecification();
CriteriaQuery<DAO> query = modelSpecification.getSpecQuery();
TypedQuery<DAO> typedQuery = entityManager.createQuery(query);
List<?> resultList = typedQuery.getResultList();
//List<DAO> allData = entityManager.createQuery(query).getResultList();
return resultList;
}
You can find working code here https://github.com/bsridharpatnaik/CriteriaMultiselectGroupBy

How do i convert this multiple where cause SQL to eSQL?

T-SQL
USE [AdventureWorks];
SELECT p.* FROM Production.ProductCategory cat ,[Production].[ProductSubcategory] sub, [Production].[Product] p
WHERE cat.ProductCategoryID=1 AND sub.ProductCategoryID = cat.ProductCategoryID and p.ProductSubcategoryID = sub.ProductSubcategoryID
And i want to convert to eSQL for EntityDatasource
<asp:EntityDataSource ID="ProductDataSource" runat="server" ConnectionString="name=AdventureWorksEntities"
DefaultContainerName="AdventureWorksEntities" EntitySetName="Product"
Where="EXISTS(SELECT VALUE cat FROM ProductCategory AS cat WHERE cat.ProductCategoryID=1)
AND EXISTS(SELECT VALUE sub FROM ProductSubcategory AS sub WHERE sub.ProductCategoryID = cat.ProductCategoryID)
AND it.ProductSubcategoryID = sub.ProductSubcategoryID) "
>
</asp:EntityDataSource>
But it is error.
Update :
Thanks devart hints,
I modify the query to
SELECT VALUE p FROM AdventureWorksEntities.ProductCategory AS cat, AdventureWorksEntities.ProductSubcategory AS sub, AdventureWorksEntities.Product AS p WHERE cat.ProductCategoryID=1 AND sub.ProductCategoryID = cat.ProductCategoryID and p.ProductSubcategoryID = sub.ProductSubcategoryID
It work now.
You can use the following code for the Selecting EntityDataSource event handler, for example:
string query = #"SELECT VALUE p FROM EntityContainer.ProductCategory as cat, EntityContainer.ProductSubcategory as sub, EntityContainer.Product as p WHERE cat.ProductCategoryID=1 AND sub.ProductCategoryID = cat.ProductCategoryID and p.ProductSubcategoryID = sub.ProductSubcategoryID";
EntityDataSource source = null;
source = Page.FindControl("ProductDataSource") as EntityDataSource;
if(source != null) {
source.EntitySetName = null;
source.CommandText = query;
}
This code provides a strongly-typed result and uses the Where clause.