sql - Sort by parameter to backend database -


how sorting logic specified in rest api handled backend database?

supposing rest api request

https://<<some api>>/?sortby=-id,name 

is there easier way of converting above rest api sortby parameter without having regex seperate string commas, , check if first character contains dash form below sql request?

select * students order id asc, name desc 

comma delimited strings don't have split regex.. following c# it, example:

string sort = request["sortby"]; if(sort != null){   foreach(string s in sort.split(',')){     string direction = "desc";     if(s[0] == '-')       direction = "asc";     if(permittedcolumnslist.contains(s.replace("-", ""))       sql = sql + s.replace("-", "") + " " + direction + ","; } sql = sql.remove(sql.length - 1); // drop last comma 

this still parsing , looking first dash though, seem not want.

if prepared store permissible sort ops in dictionary gets simpler looking:

//column dictionary mapping acceptable parameters sql //implements them coldict["-id"]="id asc,"; coldict["id"]="id desc,"; coldict["-name"]="name asc,"; coldict["name"]="name desc,";  string sort = request["sortby"]; if(sort != null){   foreach(string s in sort.split(',')){     if(coldict.containskey(s))       sql = sql + coldict[s]; } sql = sql.remove(sql.length - 1); // drop last comma 

i think there's far should go in looking simplify things. wouldn't wise blindly take user typed url, , shove in sql suffixed asc if put - (i keep expecting - desc) because that's security risk. building dictionary of permitted values isolate risk. dictionary can built programmatically doesn't need altering manually every time query schema changes


Comments