将 ORDER BY 作为参数传递给 postgres 函数的最佳方法

时间:2021-02-11 01:36:48

标签: sql database postgresql rest

假设我有一个像这样的 postgres 函数(... 省略号是伪代码)

create or replace function get_people (order_by varchar(64)[])
returns table (id bigint, age smallint, height smallint, weight smallint)
as $$
begin
select
    *
from
    person
order by
    ....

假设我想允许我的用户通过 REST API 像这样调用这个函数(仅伪代码,暂时忽略 GET 与 POST)

$.ajax({type: 'POST',
    url: 'example.com/api/get_persons',
    data: JSON.stringify({order_by: ['weight ASC', 'height DESC', 'age ASC', 'id ASC']}),
...

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您必须为要排序的每个可能的列定义一个婴儿车

SELECT
    *
from
    person
order by
case when 'weight asc' = ANY(orderbyenum) then weight end asc,
case when Paramwheightdesc then height end desc,
....

如果你想把它放在一个数组中(例如枚举),我称之为 orderbyparam orderbytype[],你传递给你的 proc:

SELECT
    *
from
    person
order by
case when 'weight asc' = ANY(orderbyparam) then weight end asc,
case when 'height desc' = ANY(orderbyparam) then height end desc,
....