Skip to content

Instantly share code, notes, and snippets.

@michelp
Created October 3, 2017 16:24
Show Gist options
  • Select an option

  • Save michelp/2ccd682455664d0b91d759793fe23df2 to your computer and use it in GitHub Desktop.

Select an option

Save michelp/2ccd682455664d0b91d759793fe23df2 to your computer and use it in GitHub Desktop.
```
create table foo.stuff (
value integer,
date timestamp
)
insert into foo.stuff values (42, '2017-09-10');
insert into foo.stuff values (52, '2017-09-11');
insert into foo.stuff values (62, '2017-09-12');
create view api.sum_stuff as
select sum(value)
from foo.stuff;
```
I know in sql I can't say:
select * from api.sum_stuff where date >= '2017-09-11';
because date is not a selected column. so it's reasonable that in postgREST I
*also* can't say
http://localhost:3000/sum_stuff?date=gte.2017-09-11
which leads the question: how can aggregations be dynamically filtered in
postgrest?
It seems not possible except to write an "rpc function" and POST the arguments.
However this puts the onus on frontend developers to special case the POST into
their frameworks for a non-mutating operation, which is not very "restful". It
also defeats HTTP caching (as noted in the docs). There's also an abrupt
dichotomy of design: elegant views, including aggregates, that can be GET. But
then: all the dynamic filtering must be POSTed?
In many sql frameworks, parameters can be substituted into WHERE clauses of
application language strings that contain SQL and act as templates for the final
query that gets run. This is functionally not much different than an rcp
function (which is acting as the template in this case) but can be given a
unified and consistent restful interface.
It seems there has been some discussion about extending the RPC functionality to
support GETs, the documentation mentions this for the case of being "important
to caching". But there are serious caveats that URL parameters are already
reserved for output filtering and shaping.
So since I've answered my own question (it can't be done but with a function and
POST) I'd like to propose discussion for a postgREST feature: SQL templates. The
postgrest server could be run with an additional configuration parameter:
template-dir: './my_templates'
that contain mustache templates
(https://www.stackbuilders.com/tutorials/haskell/mustache-templates/) that,
by name, can override the default SQL generation that happens inside
postgrest. For example, if 'my_templates' contained the file 'sum_stuff.sql'
with the contents:
select sum(value) from foo.stuff where date >= {{date}}
the user can go to:
http://localhost:3000/sum_stuff?date=gte.2017-09-11
and get dynamically filtered aggregates.
Thoughts?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment