fortunes.sql 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. CREATE TYPE fortune_t AS (id int, message text);
  2. create or replace function fortune_template(f fortune_t) returns text as $$
  3. SELECT format('<tr><td>%s</td><td>%s</td></tr>', $1.id, regexp_replace($1.message, '<', '&lt;','g'));
  4. $$ language sql volatile;
  5. create or replace function fortunes_template(fortunes fortune_t[]) returns text as $$
  6. WITH header AS (
  7. SELECT 0 as id,'<!DOCTYPE html>
  8. <html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>' as html
  9. ), footer AS (
  10. SELECT 2,'</table></body></html>' as html
  11. ), fortunes AS (
  12. SELECT unnest as fortune from unnest($1)
  13. ), additional AS (
  14. SELECT (-1, 'Additional fortune added at request time.')::fortune_t as f
  15. ), all_fortunes AS (
  16. SELECT * from (SELECT * FROM fortunes UNION ALL SELECT * from additional) p ORDER BY (fortune).message
  17. ), fortunes_html AS (
  18. SELECT 1,string_agg(fortune_template(fortune), '') from all_fortunes
  19. ), html AS (
  20. SELECT * FROM header UNION SELECT * FROM fortunes_html UNION SELECT * from footer ORDER BY id
  21. )
  22. SELECT string_agg(html,'') from html;
  23. $$ language sql volatile;
  24. create or replace function "fortunes.html"() returns bytea as $$
  25. DECLARE
  26. fortunes fortune_t[];
  27. BEGIN
  28. SET LOCAL "response.headers" = '[{"Content-Type": "text/html"}]';
  29. SELECT array_agg(CAST((id,message) AS fortune_t)) FROM "Fortunes" INTO fortunes;
  30. RETURN convert_to(fortunes_template(fortunes), 'UTF8');
  31. END
  32. $$ language plpgsql volatile;