#sql #sorting #last #id #convert #expression #order

sort_str_to_sql

Convert Sort Expression to SQL that can be used in 'ORDER BY' statement, e.g. '-aired,id' -> 'aird DESC NULLS LAST, id ASC NULLS LAST'.

6 releases (1 stable)

Uses old Rust 2015

1.0.0 Apr 12, 2015
0.0.5 Jan 17, 2015
0.0.3 Dec 20, 2014
0.0.2 Nov 22, 2014

#32 in #last

MIT license

4KB

Sort String To SQL

This is a rust crate to convert 'sort expressions' to SQL expressions that can be used in an 'ORDER BY'. E.g., -date,id will be converted to date DESC NULLS LAST, id ASC NULLS LAST.

It can be used to convert a HTTP query parameter to an expression that can be used in an SQL query. (I'm only using this with Postgres myself, so I can't promise you it will work with other databases.)

Build Status

Install

# Cargo.toml
[dependencies]
sort_str_to_sql = "1.0.0"

Input Format

Comma separated list of field names. Prepend a '-' for descending order or a '+' for ascending order (which is the default, so it's optional). Append a '-' if you want records with null values first (this sets NULLS FIRST).

You can find some examples in the inline #[test].

License

MIT


lib.rs:

Convert Sort Expression to SQL

Converts 'sort format' to 'SQL format'. E.g.:

  • -id -> id DESC NULLS LAST
  • id -> id ASC NULLS LAST
  • id- -> id ASC NULLS FIRST
  • -aired,id -> aired DESC NULLS LAST, id ASC NULLS LAST

Example

#![allow(unstable)]
assert!(
  sort_str_to_sql("-id") ==
  Some("id DESC NULLS LAST".to_owned())
);
assert!(
  sort_str_to_sql("-id,+aired-") ==
  Some("id DESC NULLS LAST, aired ASC NULLS FIRST".to_owned())
);

(See tests for more examples.)

Dependencies

~3.5MB
~75K SLoC