Conditionally filter on SQL query based on the field value - apex

I want to conditionally filter a SQL query based on the field value of a picklist. How do I do this? If the picklist field value is 'Any Type' then I want to NOT filter the query.
if (picklistValue == 'Any Type') //dont filter
SELECT Object__c.Name
FROM Object__c
WHERE Object__c.Type__c = :picklistValue

In these scenario's you need to build SOQL dynamically based on your conditions. In your case dynamic SOQL could be something like this:
List<Object__c > objList = new List<Object__c>();
String query = 'SELECT Object__c.Name FROM Object__c ';
if(picklistValue == 'Any Type') {// don't filter
// your code..
} else {
// apply filter
query = query + ' WHERE Object__c.Type__c = \'' + picklistValue + '\';
}
objList = Database.query(query);
You can refer dynamic SOQL documentation for more details.

Related

FORMIO: I am trying to create custom field logic, and I want to select value of every field for eg.(data.firstName will select value of Firstname)

let disableBool;
if(data.firstName === "disable"){
disableBool = true;
return disableBool;
}
result = disableBool;
This is an example of how I selected "Firstname" field and selected its value to perform some logic on it. Is there any way to select the value of every field so that for example if I type "disable" in any field then "disableBool = true".

Combining two search/filter functions to render template in flask pymongo

I have a text search based on a text index of my mongodb collection 'locations' so a user can search for results based on town/city.
and I also have a dropdown select where user can select a 'type'.
both functions return the desired result, but they both work independently. I don't know enough to understand how to combine them and render the results. Any help much appreciated.
#app.route("/search")
query = request.form.get("query")
search = mongo.db.properties.find({"$text": {"$search": query}})
Dropdown Filter:
#app.route("/search", methods=["GET", "POST"])
def search():
# query the database for all property types
featured = mongo.db.properties.find()
types = mongo.db.type.find()
query = request.form.get("query")
filtered_result = []
# gets property type input from dropdown select and renders results
if request.method == "POST":
property_types = request.form.get("propertytype")
filtered_result = list(mongo.db.properties.find({'property_type' : property_types}))
return render_template("properties.html", types=types, properties=filtered_result, featured=featured)

Conditions in prepared statements in postgres

I need to add a condition inside prepared statement in postgres.
Pseudocode (doesn't works, fires an error "argument of WHERE must be type boolean, not type text"):
if (nameFilter) {
whereParam = `name LIKE %${nameFilter}%`
} else {
whereParam = "true"
}
let query = prepare("SELECT * FROM users WHERE $1", whereParam);
Pseudocode (works but looks ugly):
if (nameFilter) {
likeParam = `%${nameFilter}%`
} else {
likeParam = "%"
}
let query = prepare("SELECT * FROM users WHERE name LIKE $1", likeParam);
For some reasons(query is really complex with a bunch of AND) manipulations with a string is not an option, so this will not help
if (nameFilter) {
q = `SELECT * FROM users WHERE name LIKE $1`
} else {
q = "SELECT * FROM users"
}
let query = prepare(q, nameFilter);
Desirable to have statement similar to SELECT * FROM users WHERE $1 AND $2 AND $3 ...
Any suggestions?
This query will work for you.
select * from users where
case
when coalesce($1, '') = '' then true
else (name ~ $1)
end;
The only thing you can pass as a parameter is a constant; you cannot pass part of an SQL query like name LIKE '%pattern%'.
So if your query is really different every time, you have to construct the SQL string in your code, just like you say you cannot do "for some reasons".
It may be annoying, but there is no other way.
When you construct an SQL statement, make sure you never concatenate strings like this:
sql = "SELECT * FROM users WHERE username ='" + username + "'"
because that would be vulnerable to SQL injection.

Error when using "ALL" operator when execute query

I need to execute following query using phalcon framework:
"SELECT id FROM table GROUP BY id HAVING '31' = ALL(array_agg(status))"
How can I execute this query using phalcon?
When I do following:
Model::query()
->columns(['id'])
->groupBy('id')
->having('31 = ALL(array_agg(status))')
->execute();
I get this error message:
Syntax error, unexpected token ALL, near to '(array_agg(status)) ', when parsing: SELECT id FROM [SomeNameSpace\Model] GROUP BY [id] HAVING 31 = ALL(array_agg(status)) (137)
I'm not 100% sure which Postgres functions are supported, but you can try like this:
Model::query()
->columns([
'id',
'ALL(array_agg(status)) AS statusCounter'
])
->groupBy('id')
->having('31 = statusCounter')
->execute();
Notice that I moved the aggregation functions in the select, rather in having clause.
UPDATE: here is an example of very custom query. Most functions used are not supported and it's sometimes cleaner just to write a simple SQL query and bind the desired Model to it:
public static function findNearest($params = null)
{
// A raw SQL statement
$sql = '
SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS(:lat))
* COS(RADIANS(X(coords)))
* COS(RADIANS(Y(coords)) - RADIANS(:lng))
+ SIN(RADIANS(:lat))
* SIN(RADIANS(X(coords)))))
AS distance_in_km
FROM object_locations
ORDER BY distance_in_km ASC
LIMIT 0,5;
';
// Base model
$model = new ObjectLocations();
// Execute the query
return new \Phalcon\Mvc\Model\Resultset\Simple(
null,
$model,
$model->getReadConnection()->query($sql, $params)
);
}
// How to use:
\Models\ObjectLocations::findNearest([
'lat' => 42.4961756,
'lng' => 27.471543300000008
])
You need to add ALL as dialect extension. Check this topic for example https://forum.phalconphp.com/discussion/16363/where-yearcurrenttimestamp-how-to-do-this

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)