Faunadb conditional statement can't run false condition expression - next.js

I tried to build fulltext search API using nextjs and faunadb.
I referenced the article "How to Get a Full-Text Search with FaunaDB"
My index setting is as below.
This API will receive two values artist and term(short for search term)
If there is two, it will combined by and statement.
Or it will run there own statement or each value.
Implemented code is as below.
const queryCase = req.body.artist && req.body.term ? 1 : req.body.term != undefined ? 2 : 3
const tokens = await serverClient.query(
Filter(
Paginate(Match(Index("all_token_by_artist_and_description"), true)),
Lambda(
[
"artist",
"description",
"image",
"seller",
"creator",
"category",
"refId"
],
If(
Equals(queryCase, 1),
And(
Or(
ContainsStr(
LowerCase(Var("artist")),
req.body.term
),
ContainsStr(
LowerCase(Var("description")),
req.body.term
)
),
Equals(
LowerCase(Var('artist')),
LowerCase(req.body.artist)
)
),
If(
Equals(queryCase, 2),
Or(
ContainsStr(
LowerCase(Var("artist")),
req.body.term
),
ContainsStr(
LowerCase(Var("description")),
req.body.term
)
),
Equals(
LowerCase(Var('artist')),
LowerCase(req.body.artist)
)
)
)
)
)
)
res.status(200).json(tokens.data)
It couldn't run false condition expression. The false expression works fine
when I switched truth expression and false expression.
I get it fixed by make 3 separate query.
if(queryCase == 1){
tokens = await serverClient.query(
.....
)
}else if(queryCase == 2){
tokens = await serverClient.query(
.....
)
}else{
tokens = await serverClient.query(
.....
)
}
But I really have no idea what's wrong with the original query.
Can anyone tell me the problem with the query?

It caused by missing value. So I assigned random string to the missing value after the case is determined.
eg) If I only get "artist" value from request, assign random string to the "term".

Related

Filler word for SQLite statement to return any and all rows using WHERE [duplicate]

I am doing my crm project with SQLITE+FLASK. And I need a feature is let user to input the condition to filer the result.
I hope that my SQL statement can ignore the WHERE condition if the parameter is space or null.
For example, My input is "NAME", "AGE", "GENDER"
so my statement will be
SELECT *
FROM CUSTOMER
WHERE NAME = 'James' AND AGE = '25' AND GENDER = 'M'
But I hope that if user did not enter "NAME" my SQL statement can be something like the code below
SELECT *
FROM CUSTOMER
WHERE AGE = '25' AND GENDER = 'M'
I know maybe I can do this with string concat, but I hope I can do this by SQL statement.
You can do it with the OR operator for each of the columns, by checking also if the parameter value that you pass is NULL or a string with spaces:
SELECT *
FROM CUSTOMER
WHERE (NAME = :name OR TRIM(COALESCE(:name, '')) = '')
AND (AGE = :age OR TRIM(COALESCE(:age, '')) = '')
AND (GENDER = :gender OR TRIM(COALESCE(:gender, '')) = '')
You can use null condition as follows:
SELECT *
FROM CUSTOMER
WHERE (NAME = :name_input or :name_input is null)
AND (AGE = :age_input or :age_input is null)
AND (GENDER = :gender_input or :gender_input is null)

We are getting some exception, Exception message: "The LINQ expression 'DbSet<FactInspection>()

While update the .netcore 2.2 to 3.1, I am facing the issue.
.Where(f => f.Media_Id == __filter_MediaId_0 && f.Targeted_Date != null && f.Targeted_Date.Value.Date >= __filter_StartDate_Value_Date_1 && f.Targeted_Date.Value.Date <= __filter_EndDate_Value_Date_2)
.GroupBy(
keySelector: f => new {
Targeted_Year = f.Targeted_Year,
Targeted_Quarter = f.Targeted_Quarter,
Targeted_Quater_Range = f.Targeted_Quater_Range,
Phase = f.Phase == \"Completed\" ? \"Completed\" : \"Not >Completed\"
},
elementSelector: f => f)
.Select(e => new TargetDashboardResponse{
Targeted_Year = (Nullable<int>)e.Key.Targeted_Year.Value,
Quarter = e.Key.Targeted_Quarter,
Name = string.Format(
format: \"{0} ({1})\",
arg0: e.Key.Targeted_Quater_Range,
arg1: (object)e.Key.Targeted_Year),
Phase = e.Key.Phase,
Count = e
.Count()
}
)
.OrderBy(e0 => e0.Targeted_Year)'
could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.", Inner exception: "" , Stacktrace: " at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.g__CheckTranslated|15_0(ShapedQueryExpression translated, <>c__DisplayClass15_0& )
Exception message clearly says to add a call to one of these methods: ' AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync' at the end of your query.
For example: await (your query).ToListAsync()

Symfony2/Doctrine QueryBuilder multiple andwhere() fail

Bonjour,
I am having a problem with a simple request with QueryBuilder :
$query->where('ec.codeModePrelevement IN (:cbMode)')
->setParameter('cbMode', $modes)
->andWhere('ec.idStatusPaiement = :status')
->setParameter('status', EcheancesStatut::__EN_ATTENTE_PAIEMENT__)
->andWhere($query->expr()->eq('ec.idProduit',1))
->andWhere('ec.idProduit = :idProduit')
->setParameter('idProduit', 1 )
;
This return me no result as if in the database no user is corresponding to this : user with status = 1 codeproduit = 1 and modePaiement = VM or VMMANO.
Ihave verified all possible mistakes of typo. And users corresponding in database do exist.
I have tried to remove id produit filter it "works" i have some result:
$modes = array('VM','VMMANO');
$query->where('ec.codeModePrelevement IN (:cbMode)')
->setParameter('cbMode', $modes)
->andWhere('ec.idStatusPaiement = :status')
->setParameter('status', EcheancesStatut::__EN_ATTENTE_PAIEMENT__)
/*->andWhere('ec.idProduit = :idProduit')
->setParameter('idProduit', 1 )*/
;
This "works" to (removing modePaiement filter):
$query/*->where('ec.codeModePrelevement IN (:cbMode)')
->setParameter('cbMode', $modes)*/
->where('ec.idStatusPaiement = :status')
->setParameter('status', EcheancesStatut::__EN_ATTENTE_PAIEMENT__)
->andWhere('ec.idProduit = :idProduit')
->setParameter('idProduit', 1 )
;
but this returns me no result to (removing status payment filter) :
$query->where('ec.codeModePrelevement IN (:cbMode)')
->setParameter('cbMode', $modes)
/*->where('ec.idStatusPaiement = :status')
->setParameter('status', EcheancesStatut::__EN_ATTENTE_PAIEMENT__)*/
->andWhere('ec.idProduit = :idProduit')
->setParameter('idProduit', 1 )
;
Can you help me if you see something that i don't? Thank you.

Modify cell in a R DT::datatable based on previous row

I have a shiny app where I would like to modify the data displayed and/or the attributes of a cell based on the value of the same cell in the previous row.
In my code I have formatted whole rows based on the value of data[0] in rowCallback.
output$result <- DT::renderDataTable(tabledata(),
class = c('compact'),
rownames = FALSE,
server = FALSE,
escape = TRUE,
extensions = options = list(
rowCallback=JS("
function (row, data, index) {
var string=data[1], substring = 'sub total';
if (data[0]=='Grand Total') {
$(row).css('background-color', '#DEDEDE'), $(row).css('font-weight', 'bold') ;
}
else if (data[0].includes('sub total')) {
$(row).css('font-weight', 'bold');
}
}"
)
)
)
Can I achieve a modification of the data[0] cell based on the value of the same cell in the previous row using one of the callback functions?
So I changed tack and used the following drawCallback call
drawCallback=JS(" function ( settings ) {
var api = this.api();
var mydata = api.rows( {page:'current'} ).data();
var last=null;
api.column(0,{page:'current'}).data().each( function ( value, index ) {
if ( value == last) {
mydata[index][0] = ''
api.rows({ page: 'current' }).invalidate();
}
last=value;
});
}"
)

How to print a sqlite table content with genie programming language

Based on previous questions here I managed to create the dataset, print all recipes listed and now I am trying to pick one of the recipes from that list and show its Title, Instructions and Ingredients. The instructions are mapped to the Recipes via the pkID column and the ingredients are mapped to the Recipes through a recipeID column. When I open the database on Sqlite Database Browser I can access this information inside the Tables dropdown list, so I suppose the proper name for them are tables within the database.
I am not being able to "filter" by pkID and by recipeID, so that after picking one recipe, only the appropriate content is shown.
This is the code in Python of what I am trying to do in Genie:
def PrintSingleRecipe(self,which):
sql = 'SELECT * FROM Recipes WHERE pkID = %s' % str(which)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
for x in cursor.execute(sql):
recipeid =x[0]
print "Title: " + x[1]
print "Serves: " + x[2]
print "Source: " + x[3]
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
sql = 'SELECT * FROM Ingredients WHERE RecipeID = %s' % recipeid
print 'Ingredient List:'
for x in cursor.execute(sql):
print x[1]
print ''
print 'Instructions:'
sql = 'SELECT * FROM Instructions WHERE RecipeID = %s' % recipeid
for x in cursor.execute(sql):
print x[1]
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
resp = raw_input('Press A Key -> ')
I have not been able to improve much of my code, it seems that using the approach I used before of iterating in a step statement cannot be used here. This is how far I got in Genie:
def PrintSingleRecipe(db:Database)
stmt:Statement = PreparedStatements.select_all( db )
res:int = UserInterface.raw_input("Select a recipe -> ").to_int()
cols:int = stmt.column_count ()
var row = new dict of string, string
item:int = 1
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
while res == ROW
for i:int = 0 to (cols - 1)
row[ stmt.column_name( i ) ] = stmt.column_text( i )
stdout.printf( "%-5s", item.to_string( "%03i" ))
stdout.printf( "%-30s", row[ "Title" ])
stdout.printf( "%-20s", row[ "Serves" ])
stdout.printf( "%-30s\n", row[ "Source" ])
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print "Ingredient list"
print " "
stdout.printf("%-5s", item.to_string( "%03i" ))
I have found a solution to the problem, maybe it can be optimized. For now it is enough.
Answers from another question helped immensely. The solution I used was to use the exec function and point the callback to the PrintSingleRecipe().
Some adjustments had to be done for it to work as a callback, but I got what I needed.
Here is the code where the function gets called:
while true
response:string = UserInterface.get_input_from_menu()
if response == "1" // Show All Recipes
PrintAllRecipes(db)
else if response is "2" // Search for a recipe
pass
else if response is "3" //Show a Recipe
res:string = UserInterface.raw_input("Select a recipe -> ")
sql:string = "SELECT * FROM Recipes WHERE pkID = " + res
db.exec(sql, PrintSingleRecipe, null)
else if response is "4"//Delete a recipe
pass
else if response is "5" //Add a recipe
pass
else if response is "6" //Print a recipe
pass
else if response is "0" //Exit
print "Goodbye"
break
else
print "Unrecognized command. Try again."
Here is how the PrintSingleRecipe looks like:
def PrintSingleRecipe(n_columns:int, values:array of string, column_names:array of string):int
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
for i:int = 0 to n_columns
stdout.printf ("%s = %s\n", column_names[i], values[i])
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print "Ingredient list"
print " "
return 0

Resources