sql query in Rails where value IS BLANK (0 or nil) - sql

In Rails there is the method item.property.blank? which is true for property being "0" or nil or whitespace.
How can I make an sql query to check if a value is blank?
I now have:
Item.where("name = 'Testname' AND property <> '1'")
which shows me all items with name = 'Testname' and property = '0', but not those with property = nil (not defined).
How should my sql query be to be equivalent to
Item.where("name = 'Testname' AND property IS BLANK")
so that all items with property = '0' and property = nil are included to the search results?

Item.where("property IN ('0','') OR property IS NULL")
or more exactly...
Item.where("name = 'Testname' AND (property IN ('0','') OR property IS NULL)")

Without using SQL strings, you can do this:
Item.where(name: 'Testname', property: [nil, '0', ''])
It will produce the SQL query
SELECT `items`.* FROM `items`
WHERE `items`.`name` = 'Testname'
AND (`items`.`property` IN ('0', '') OR `items`.`property` IS NULL)

Related

How to change key part of query string dynamically in karate

I have the below requirement where I need to dynamically change the key-value pair of the query string, but I am able to dynamically change the value of the query parameter but not the key part. It is taking the text value like 'paramName' in the request.
string reqBody = version == 'v2' ? 'ABC' : 'DEF'
string paramName = version == 'v2' ? 'json_body' : 'proto_body'
param paramName = reqBody
GET https://test.apis.com/sample?paramName=ABC
or
GET https://test.apis.com/sample?paramName=DEF
If you need dynamic param names, use params: https://github.com/karatelabs/karate#params
* def temp = version == 'v2' ? { json_body: 'ABC' } : { proto_body: 'DEF' }
* params temp
If you still have questions, read this: https://stackoverflow.com/a/50350442/143475

PostgreSQL verify an empty array on json

I have the following row on select
jsonData
[]
[{"descricao":"falha na porta"}, {"descricao":"falha no ip"}]
[]
I have to Identify empty jsons, then manually add a value to it (eg row 1 and 3 ), I tried the following :
case when jsonData is null then cast('[{"descricao":"no error"}]' AS json) else jsonData end as opts
But the "is null" verification fails for this type of data (array of json), how to identify '[]' values in this case?
Note: I only have select permission on this db
You can use json_array_length()
when json_array_length(jsondata) = 0 then ...
Casting the json to text before comparison worked for this case :
" case when jsondata::text = '[]' "
Try this condition:
jsondata = JSON '[]'

laravel sql update isnull with parameters variables

$variable = array("apple" , "orange" , null, "apple2");
DB::statement("UPDATE table1
SET
field1= IsNull($variable[0],field1),
field2= IsNull($variable[2],field2),
where = someconditional")
I want if field is null in data array do not update but only that field. other fields (if not null) do it update
How can I write this code in laravel ?
Try this
$variable = array("apple" , "orange");
DB::table('table1')->where('some_field', $condition)->update(['field1' => $variable[0], 'field2' => $variable[1]]);

Grails: "where" query with optional associations

I'm trying to run a "where" query to find a domain model object that has no association with another domain model object or if it does, that domain model object has a specific property value. Here's my code:
query = Model.where({
other == null || other.something == value
})
def list = query.list()
However, the resulting list only contains objects that match the second part of the OR statement. It contains no results that match the "other == null" part. My guess is that since it's checking a value in the associated object its forcing it to only check entries that actually have this associated object. If that is the case, how do I go about creating this query and actually having it work correctly?
You have to use a LEFT JOIN in order to look for null associations. By default Grails uses inner join which will not be joined for null results. Using withCriteria as below you should get the expected results:
import org.hibernate.criterion.CriteriaSpecification
def results = Model.withCriteria {
other(CriteriaSpecification.LEFT_JOIN){
or{
isNull 'id'
eq 'something', value
}
}
}
UPDATE
I know aliasing is not possible in DetachedCritieria where one would try to specify the join as in createCriteria/withCriteria. There is an existing defect regarding adding the functionality to DetachedCriteria. Just adding the work around for where query as mentioned in defect.
Model.where {
other {
id == null || something == value
}
}.withPopulatedQuery(null, null){ query ->
query.#criteria.subcriteriaList[0].joinType = CriteriaSpecification.LEFT_JOIN
query.list()
}
I would rather use withCriteria instead of the above hack.
this might work:
query = Model.where({
isNull( other ) || other.something == value
})
If that wouldn't work, try something like:
other.id == null || other.something == value
UPDATE:
or with good'ol criteria query:
list = Pack.withCriteria{
or{
isNull 'other'
other{ eq 'something', value }
}
}

Active Record Query - Search Multiple Columns for Multiple Strings and Return Only if They Are All Included

I need help designing a query via Active Record & Postgresql.
• The query must search across all of the following columns...
The Model looks like this:
Collection
item_id1: String
item_id2: String
item_id3: String
item_id4: String
item_id5: String
item_id6: String
• The query needs to pass in an array of strings that need to be searched across all of the item_id fields.
• The query must also only return results of Records containing all of the strings within the array.
Note: I also have the Textacular Full Text Search gem installed. However, I tested a search that I believe is supposed to search and return matches only if the records include all of the passed in strings, and the search came up with nothing, despite records with those strings existing in my database. Like this: Collection.advanced_search('B0066AJ5TK&B0041KJSL2')
Just to clarify: You want records where each of the strings in the array are found somewhere within the six item_id fields?
There's probably a more elegant way to do this, but here's what I've got off the top of my head:
terms = ['foo', 'bar', 'baz']
conditions = []
values = {}
terms.each_with_index do |t,i|
arg_id = "term#{i}".to_sym
conditions << "(item_id1 = :#{arg_id} OR item_id2 = :#{arg_id} OR item_id3 = :#{arg_id} OR item_id4 = :#{arg_id} OR item_id5 = :#{arg_id} OR item_id6 = :#{arg_id})"
values[arg_id] = t
end
Collection.where(conditions.join(' AND '), values)
This should produce a query like this:
SELECT "collections".* FROM "collections" WHERE ((item_id1 = 'foo' OR item_id2 = 'foo' OR item_id3 = 'foo' OR item_id4 = 'foo' OR item_id5 = 'foo' OR item_id6 = 'foo') AND (item_id1 = 'bar' OR item_id2 = 'bar' OR item_id3 = 'bar' OR item_id4 = 'bar' OR item_id5 = 'bar' OR item_id6 = 'bar') AND (item_id1 = 'baz' OR item_id2 = 'baz' OR item_id3 = 'baz' OR item_id4 = 'baz' OR item_id5 = 'baz' OR item_id6 = 'baz'))
Which is long and ugly, but should get the results you want.
If you meant that the fields might contain the strings to be searched for, rather than be equal to them, you could instead use
item_id1 LIKE #{arg_id}
and
values[arg_id] = "%#{t}%"