I'm trying to dynamically run queries against my Postgres database, but can't fully wrap my head around it.
The solution I'm looking for is one where I can set the query dynamically, perhaps by appending parameters to the final query throughout the code, and then have only one instance of the query being executed.
As mentioned in the title I am using SQLBoiler to interface with Postgres.
Here's what I'm looking for in pseudo code:
final_query := QueryMod{
Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
}
if a == 1 {
final_query = append(final_query, And(" and mt_important = ?", bool(false)))
} else {
final_query = append(final_query, And(" and mt_ness = ?", bool(true)))
}
res_mt_count, err := models.MTs(
final_query,
).All(CTX, DB)
Thankful for any help along the way! :)
mkopriva solved my problems with the following solution:
type QueryModSlice []qm.QueryMod
func (s QueryModSlice) Apply(q *queries.Query) {
qm.Apply(q, s...)
}
func main() {
mods := QueryModSlice{
qm.Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
}
if a == 1 {
mods = append(mods, qm.And(" and mt_important = ?", bool(false)))
} else {
mods = append(mods, qm.And(" and mt_ness = ?", bool(true)))
}
res_mt, err := models.MTs(mods).All(CTX, DB)
}
Thanks a bunch! :)
Related
I made a method on the back-end side to handle the filter of my datatable.
On the other hand, this one does not manage the accents of the French language, so if I have "école" and I write "ecole" it cannot find it.
I found this method on another question on stackoverflow
public static String RemoveDiacritics(this String s)
{
String normalizedString = s.Normalize(NormalizationForm.FormD);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < normalizedString.Length; i++)
{
Char c = normalizedString[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
and it works, but only for part of my problem. It works on the letter or the word that is written in the search, but I am not able to apply it in my linq query, so with the .RemoveDiacritics() method my "école" becomes "ecole", but I don't am not able to apply it in the column of my table and it always looks for "école".
Here the code for the search:
if (search != null)
{
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.UsagerId == IdFilter || x.Niveau == IdFilter);
}
else if (search != "")
{
// this line work
textFilter = search.ToLower().RemoveDiacritics();
// This is the full line, but absolutely takes the accents out to get the right information out
// query = query.Where(x => x.Nom.ToLower().Contains(textFilter) || x.Prenom.ToLower().Contains(textFilter) || x.Username.ToLower().Contains(textFilter) || x.Email.ToLower().Contains(textFilter) || x.EtabNom.ToLower().Contains(textFilter) || x.ActifStatut.ToLower().Contains(textFilter));
// This is the line that will replace the line above, which I try and it doesn't work ( this part: x.Prenom.ToLower().RemoveDiacritics())
query = query.Where(x => x.Prenom.ToLower().RemoveDiacritics().Contains(textFilter));
}
}
This is the basic query:
IQueryable<ListeUsagers> query = (from u in db.USAGERs
join e in db.ETABLISSEMENTs on u.USAGER_INST equals e.ETAB_CODE
where u.USAGER_INST == instId && u.USAGER_NIVEAU > 3 && u.USAGER_NIVEAU < 5 //&& u.USAGER_ACTIF == 1
select new ListeUsagers()
{
UsagerId = u.USAGER_id,
Nom = u.USAGER_NOM,
Prenom = u.USAGER_PRENOM,
EtabCode = e.ETAB_CODE,
EtabNom = e.ETAB_NOM_COURT,
EtabType = e.ETAB_TYPE,
Niveau = u.USAGER_NIVEAU,
Username = u.USAGER_USERNAME,
UserPassword = u.USAGER_MP,
DateCreation = u.USAGER_DATE_INSC,
Sexe = u.USAGER_SEXE,
Lang = u.USAGER_LANGUE,
Telephone = u.USAGER_TELEPHONE,
Email = u.USAGER_EMAIL,
FonctionTravail = u.USAGER_FONCTION,
LieuTravail = u.USAGER_LIEUTRAVAIL,
Note = u.USAGER_NOTE,
Actif = u.USAGER_ACTIF,
ActifStatut = u.USAGER_ACTIF == 0 ? "Inactif" : "Actif"
});
This is the error:
LINQ to Entities does not recognize the method 'System.String RemoveDiacritics(System.String)' method, and this method cannot be translated into a store expression.
There's built-in functionality to do this in entityframework: https://learn.microsoft.com/en-us/ef/core/miscellaneous/collations-and-case-sensitivity if you're using EF 5+
You'll want an accent insensitive collation ("AI", not "AS" in the examples on that page.)
public static void updatecasefields(List<Case> lstcase) {
//List<Case> lstcase = new list<case>();
ID devRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CRM_CSR_Case').getRecordTypeId();
for (Case cs: lstcase) {
if(cs.ID != null && cs.RecordTypeId == devRecordTypeId) {
}
List<CRM_CasePick__c> Casp = [SELECT Id, CRM_Carrier_Name__c,CRM_LOB__c, CRM_SLA_Turnaround_Time__c,CRM_Category__c, CRM_Issue_Sub_Type__c,CRM_Issue_Type__c,CRM_Turnaround_Time_Days__c FROM CRM_CasePick__c WHERE CRM_Carrier_Name__c = :cs.GiDP_CarrierName__c AND CRM_Category__c = :cs.CRM_Category__c AND CRM_Issue_Type__c = :cs.CRM_Issue_Type__c AND CRM_Issue_Sub_Type__c = :cs.CRM_Issue_Sub_Type__c AND CRM_LOB__c = :cs.CRM_Line_of_Business__c];
for(CRM_CasePick__c CP: Casp) {
cs.CRM_Turnaround_Time_Days__c = cp.CRM_Turnaround_Time_Days__c;
cs.CRM_SLA_Turnaround_time__c = cp.CRM_SLA_Turnaround_Time__c;
}
}
}
Remove the SOQL query from the for loop - best practice is to never run a query within a loop.
Right now it is running that query for every value of the initial list. If the list is over 100 records, it will exceed the governor limit.
this is my code
using (var conn = new DataEntities())
{
var query = from c in conn.servers where c.Servername != null select c;
servers srv = query.FirstOrDefault();
if (srv != null)
{
Start.IPAddress = srv.ServerIP;
Start.ServerName = srv.Servername;
Start.GamePort = Convert.ToUInt16(srv.ServerPort);
}
Start.Servers.Add(Start.ServerName, Start.GamePort);
}
servers srv = query.FirstOrDefault(); // error here
An unhandled exception of
type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.dll
Additional information: An error occurred while executing the command definition. See the inner exception for details.
can write to usually better way ?
some suggestions i'm still beginner ^^
Thank you
solved
using (var conn = new DataEntities())
{
var query = from c in conn.servers
select new
{
c.Servername,
c.ServerPort,
c.ServerIP
};
foreach (var item in query)
{
Start.IPAddress = item.ServerIP;
Start.ServerName = item.Servername;
Start.GamePort = Convert.ToUInt16(item.ServerPort);
}
Start.Servers.Add(Start.ServerName, Start.GamePort);
}
I am using sails to build an API, one of my function needs to get columns from my PGSQL database. My SQL request is working when I test it in PGadmin, it looks like this :
SELECT "user".id, "user".picture, "user".first_name, "trophe".trophe FROM "user" INNER JOIN "trophe" ON "trophe".user = "user".id WHERE "trophe".foot = 1
When I transcript this request in my sails API, it looks like this :
getHommeAndChevre: function (req, res) {
console.log(req.param("id"));
Trophe.query("SELECT 'user'.id, 'user'.picture, 'user'.first_name, 'trophe'.trophe FROM 'user' INNER JOIN 'trophe' ON 'trophe'.user = 'user'.id WHERE 'trophe'.foot ="+req.param('id'), function(err,trophes){
if(!trophes) {return res.status(400).end();}
if(trophes){
_each(trophes, function(trophe){
if (trophe.trophe == 0) {var chevre = trophe};
if (trophe.trophe == 1) { var homme = trophe};
})
return res.status(200).json({chevre: chevre, homme: homme})
}
});
}
However whatever I do the Trophe.query always returned undefined. What could be wrong here ?
Your return is outside the callback , so you return the value before the end of the query.
_each(trophes, function(trophe, index){
if (trophe.trophe == 0) {var chevre = trophe};
if (trophe.trophe == 1) { var homme = trophe};
if (index == trophes.length - 1) //End of the loop
return res.status(200).json({chevre: chevre, homme: homme});
})
Use double quotes for identifiers
Trophe.query('SELECT "user".id, "user".picture, "user".first_name, ...
I have a Table User(ID, Name....), Projects(ID, Name, Timestamps, IsFavorite...), Projects_Favoite(UserID, ProjectID)
I try to check for each projekt if there is a row for the current user. If there is a row I want set the "IsFavorite" in my Project true, otherwise false.
I tied:
for(int i = 0; i <= erg.Count();i++)
{
if (erg.ElementAt(i).User11.Any(u => u.Guid == ID) == true)
erg.ElementAt(i).SetFavorite = true;
}
but there is no way to use ElementAt, because it can't translated to SQL.
So I tried:
for(int i = 0; i <= erg.Count();i++)
{
if (erg.Take(i).Last().User11.Any(u => u.Guid == ID) == true)
erg.Take(i).Last().SetFavorite = true;
}
same problem here, so I tried:
foreach (Project project in erg)
{
if (project.User11.Any(u => u.Guid == ID))
project.SetFavorite = true;
}
There is the same problem. Is there a way to realise a ElementAt?
You should be able to do:
foreach (Project project in erg.Where(p => p.User11.Any(u => u.Guid == ID))
.ToList())
project.SetFavorite = true;
}
Assuming that erg is an IQuerable than you cannot use ElementAt as it is not supported (http://msdn.microsoft.com/en-us/library/bb399342.aspx check the section Operators With no translation), you can use it on a list though, but of course you will lose the benefits of the deferred query.
Try to use Skip instead
var whatyouwant = erg.Skip(index).First();
By looking at the stacktrace (can't read german though) looks there's something wrong with the SetFavorite column. Try first to remove this bit first:
project.SetFavorite = true;
then check also that your model columns match with what you got on the db.