Incorrect sort of DB query results in micronaut project - sorting

I am passing this to the repository function:
Pageable.from(offset, limit).order(Sort.Order(orderBy, direction, true))
It works just fine if orderBy is the name of a String property. If I try to sort by a number property it will return the results ordered as:
1,
11,
12,
...
19,
2,
20,
21
Any suggestions on how to fix for the number ordering?
Doing the sort on the method name (such as findAllOrderByNameAsc) is not an option because this is a parameter that comes from the API. We need to support ordering by any property.

remove the ignoreCase=true parameter or pass it as false
Sort.Order(orderBy, direction, true)
you should use ignoreCase only on String fields

Related

Postgresql natural sort with numbers first

In Postgres I need to sort text with natural order, but with one exception - if the string has only number, it should be placed at top.
So I need such order:
["98", "125", "134", "148", "265", "634", "1233", "5231", "1m1ds", "1m2", "1m3", "1n3", "1w3r", "2m3", "2n3ds", "9t6","12gh", "13jy","25hg", "123y", "des2", "nme", "wer5"]
I tried with this:
CREATE COLLATION IF NOT EXISTS numeric (provider = icu, locale = 'en#colNumeric=yes');
ALTER TABLE "baggage_belts" ALTER COLUMN "name" type TEXT COLLATE numeric;
and it is ok, but numbers are mixed into numbers+text:
[1m1ds, 1m2, 1m3, 1n3, 1w3r, 2m3, 2n3ds, 9t6, 12gh, 13jy, 25hg, 98, 123y, 125, 134, 148, 265, 634, 1233, 5231, des2, nme, wer5]
Anyone has knowledge is it possible make it works with "empty" numbers first?
Then you should add a second ORDER BY expression that checks for non-digits:
ORDER BY name ~ '[^[:digit:]]', name
This relies on FALSE < TRUE, and you can support it with a two-column index defined like the ORDER BY clause.
Finally, I resolved the problem by creating additional property into Entity with #Formula:
#Formula(value = "name ~ '[^[:digit:]]'")
public String nonDigitName;
and now I have
Sort.by(Sort.Direction.ASC, "nonDigitName", "name")
I have one more challenge. I would like to move this property to another class MySortClass and make my base entity class extends MySortClass. But when I moved the property, I have
Unable to locate Attribute with the the given name [nonDigitName] on this ManagedType [pl.ppl.szopl.app.baggagebelt.BaggageBeltEntity]
Is there any possibility to Sort by inherited fields?

Laravel / Eloquent - how to ORDER BY FIELD

I'm trying to sort my query results based on a series of slash-separated ids (from the URL, e.g. /10/25/1). I grab the URL segments and explode them to get an array with elements 10, 25, 1. Now, I want my SQL to be something like this:
ORDER BY FIELD(`products`.`id`, 10, 25, 1)
In Eloquent, I'm trying to do this:
->orderByRaw('FIELD(`products`.`id`, ?)', [implode(', ', $product_ids)])
But that outputs something like this:
ORDER BY FIELD(`products`.`id`, "10, 25, 1")
I could declare a variable, loop through my array, and build the string 10, 25, 1 and just use that variable in place of the ? -- however, I would not be getting the benefit of whatever Eloquent does to prevent SQL injection attacks.
Suggestions?
Each parameter needs to have its own placeholder.
You can implode placeholders and pass the array as a parameter:
$placeholders = implode(',', array_fill(0, count($product_ids), '?'));
->orderByRaw("FIELD(`products`.`id`, $placeholders)", $product_ids)

Ruby Array Item Extract Specific Values

I have an array that includes a list of items that look like the following:
#<InvTypes typeID: 235, typeName: "That's the right stuff">, #<InvTypes typeID: 5, typeName: "And-some-of This">
How would I be able to extract the typeID and typeName?
I'm assuming I'd array.each, but I'm unsure from there what I'd do.
I'm .to_a the result. Without that though, the code looks like the following: #<ActiveRecord::Relation [#<InvTypes typeID: 18, typeName: "Stuff">, #<InvTypes typeID 19, typeName: "More Stuff's">, ...]>
Pluck returns an Array of attribute values type-casted to match the
plucked column names, if they can be deduced. Plucking an SQL fragment
returns String values by default.
http://apidock.com/rails/ActiveRecord/Calculations/pluck
SOLUTION:
your_relation.pluck(:typeID, :typeName)

How to sort in grails list?

I just started with grails and would like to sort a list by descending date. I tried this:
<g:sortableColumn property="eventStartDate" defaultOrder="asc" title="${message(code: 'event.eventStartDate.label', default: 'Event Start Date')}" />
However this does not sort the list. The controller looks like this:
def list = {
params.max = Math.min(params.max ? params.int('max') : 10, 100)
[eventInstanceList: Event.list(params), eventInstanceTotal: Event.count()]
}
How can I sort by descending eventStartDate?
The reason it might not have worked is:
Event.list(params) retrieves everything.
You are sorting it in ascending order (asc) but you said you want to sort it in descending order (desc).
Solution:
Change the second line of your controller action to:
[eventInstanceList: Event.list(order: "desc"), eventInstanceTotal: Event.count()]
More info:
http://grails.github.io/grails-doc/2.2.1/ref/Domain%20Classes/list.html
Event.list(params) returns every thing in the domain object. It doesn't do any filtering. Use findAllBy* or findBy* or createCriteria instead.
Example:
Event.findAllByNameAndDate(params.get("name"), params.get("date"), [max: 10, order: "desc"])
More info:
grails domain class .list() method with params

Linq Query on int using string

I'm trying to query the unique reference number of a table using Linq to Entities. The ID is provided via a textbox and hence a string in my code. Obviously in the database table the field is an integer so I have tried using .ToString first and then .Contains in the same way you would with a varchar(). This doesn't seem to work, with the error coming from the .ToString method.
How do you do this? I have tried converting the textboxes content to an integer but this then means the user would have to enter the exact int instead of a partial number.
Many Thanks
I'm not sure why toString do not work for you. I've tried this to methods. Both returned answers:
List<int> ids = new List<int>() { 111, 211, 311, 422, 522, 622, 733, 833, 933 };
string query = "11";
var result = ids.Where(id => id.ToString().Contains(query));
var result2 = ids.ConvertAll<string>(i => i.ToString()).Where(id => id.Contains(query));
// Both return the first three items
int value;
if(int.TryParse(someTextString,out value))
{
//do work here using integer comparision with 'value'
}
Whatever do you mean by "partial" value? Whatever you are "adding" to the user supplied string, you can still do before you parse the value. Your explanation is not very clear.
If you are indeed trying to make a wildcard search, this will fail using Linq-to-entities against a DB int value. I doubt lte will make much sense of sometable.intvalue.ToString().Contains(). In this case, you might need to do some client side maths to figure out what ranges need retrieving, or to write a stored procedure that does the search at the SQL end..

Resources