docs: Use code-block postgres consistently

This commit is contained in:
Wolfgang Walther
2024-02-19 21:54:15 +01:00
committed by Wolfgang Walther
parent 553ac79d9b
commit fcd29caecf
14 changed files with 55 additions and 55 deletions
@@ -54,7 +54,7 @@ Concerning the `pgjwt extension <https://github.com/michelp/pgjwt>`_, please cf.
In order to be able to work with postgres' SCRAM-SHA-256 password hashes, we also need the PBKDF2 key derivation function. Luckily there is `a PL/pgSQL implementation on stackoverflow <https://stackoverflow.com/a/72805848>`_:
.. code-block:: plpgsql
.. code-block:: postgres
CREATE FUNCTION basic_auth.pbkdf2(salt bytea, pw text, count integer, desired_length integer, algorithm text) RETURNS bytea
LANGUAGE plpgsql IMMUTABLE
@@ -120,7 +120,7 @@ In order to be able to work with postgres' SCRAM-SHA-256 password hashes, we als
Analogous to :ref:`sql_user_management` creates the function :code:`basic_auth.user_role`, we create a helper function to check the user's password, here with another name and signature (since we want the username, not an email address).
But contrary to :ref:`sql_user_management`, this function does not use a dedicated :code:`users` table with passwords, but instead utilizes the built-in table `pg_catalog.pg_authid <https://www.postgresql.org/docs/current/catalog-pg-authid.html>`_:
.. code-block:: plpgsql
.. code-block:: postgres
CREATE FUNCTION basic_auth.check_user_pass(username text, password text) RETURNS name
LANGUAGE sql
@@ -160,7 +160,7 @@ Logins
As described in :ref:`client_auth`, we'll create a JWT token inside our login function. Note that you'll need to adjust the secret key which is hard-coded in this example to a secure (at least thirty-two character) secret of your choosing.
.. code-block:: plpgsql
.. code-block:: postgres
CREATE TYPE basic_auth.jwt_token AS (
token text
+3 -3
View File
@@ -28,7 +28,7 @@ First we'll need a table to keep track of our users:
We would like the role to be a foreign key to actual database roles, however PostgreSQL does not support these constraints against the :code:`pg_roles` table. We'll use a trigger to manually enforce it.
.. code-block:: plpgsql
.. code-block:: postgres
create or replace function
basic_auth.check_role_exists() returns trigger as $$
@@ -50,7 +50,7 @@ We would like the role to be a foreign key to actual database roles, however Pos
Next we'll use the pgcrypto extension and a trigger to keep passwords safe in the :code:`users` table.
.. code-block:: plpgsql
.. code-block:: postgres
create extension if not exists pgcrypto;
@@ -72,7 +72,7 @@ Next we'll use the pgcrypto extension and a trigger to keep passwords safe in th
With the table in place we can make a helper to check a password against the encrypted column. It returns the database role for a user if the email and password are correct.
.. code-block:: plpgsql
.. code-block:: postgres
create or replace function
basic_auth.user_role(email text, pass text) returns name
+3 -3
View File
@@ -11,7 +11,7 @@ PostgREST automatically serves a full `OpenAPI <https://www.openapis.org/>`_ des
For extra customization, the OpenAPI output contains a "description" field for every `SQL comment <https://www.postgresql.org/docs/current/sql-comment.html>`_ on any database object. For instance,
.. code-block:: sql
.. code-block:: postgres
COMMENT ON SCHEMA mammals IS
'A warm-blooded vertebrate animal of a class that is distinguished by the secretion of milk by females for the nourishment of the young';
@@ -26,7 +26,7 @@ These unsavory comments will appear in the generated JSON as the fields, ``info.
Also if you wish to generate a ``summary`` field you can do it by having a multiple line comment, the ``summary`` will be the first line and the ``description`` the lines that follow it:
.. code-block:: plpgsql
.. code-block:: postgres
COMMENT ON TABLE entities IS
$$Entities summary
@@ -37,7 +37,7 @@ Also if you wish to generate a ``summary`` field you can do it by having a multi
Similarly, you can override the API title by commenting the schema.
.. code-block:: plpgsql
.. code-block:: postgres
COMMENT ON SCHEMA api IS
$$FooBar API
+1 -1
View File
@@ -236,7 +236,7 @@ Single JSON object as Function Parameter
:code:`Prefer: params=single-object` allows sending the JSON request body as the single argument of a :ref:`function <s_procs>`.
.. code-block:: plpgsql
.. code-block:: postgres
CREATE FUNCTION mult_them(param json) RETURNS int AS $$
SELECT (param->>'x')::int * (param->>'y')::int
+8 -8
View File
@@ -178,7 +178,7 @@ The join table determines many-to-many relationships. It must contain foreign ke
The join table is also detected if the composite key has additional columns.
.. code-block:: postgresql
.. code-block:: postgres
create table roles(
id int generated always as identity,
@@ -214,7 +214,7 @@ One-to-one relationships are detected in two ways.
- When the foreign key is a primary key as specified in the :ref:`sample film database <erd_film>`.
- When the foreign key has a unique constraint.
.. code-block:: postgresql
.. code-block:: postgres
create table technical_specs(
film_id int references films(id) unique,
@@ -246,7 +246,7 @@ You can manually define relationships by using functions. This is useful for dat
Assuming there's a foreign table ``premieres`` that we want to relate to ``films``.
.. code-block:: postgresql
.. code-block:: postgres
create foreign table premieres (
id integer,
@@ -478,7 +478,7 @@ Recursive One-To-One
To get either side of the Recursive One-To-One relationship, create the functions:
.. code-block:: postgresql
.. code-block:: postgres
create or replace function predecessor(presidents) returns setof presidents rows 1 as $$
select * from presidents where id = $1.predecessor_id
@@ -530,7 +530,7 @@ Recursive One-To-Many
To get the One-To-Many embedding, that is, the supervisors with their supervisees, create a function like this one:
.. code-block:: postgresql
.. code-block:: postgres
create or replace function supervisees(employees) returns setof employees as $$
select * from employees where supervisor_id = $1.id
@@ -562,7 +562,7 @@ Recursive Many-To-One
Let's take the same ``employees`` table from :ref:`recursive_o2m_embed`.
To get the Many-To-One relationship, that is, the employees with their respective supervisor, you need to create a function like this one:
.. code-block:: postgresql
.. code-block:: postgres
create or replace function supervisor(employees) returns setof employees rows 1 as $$
select * from employees where id = $1.supervisor_id
@@ -614,7 +614,7 @@ Recursive Many-To-Many
To get all the subscribers of a user as well as the ones they're following, define these functions:
.. code-block:: postgresql
.. code-block:: postgres
create or replace function subscribers(users) returns setof users as $$
select u.*
@@ -756,7 +756,7 @@ If you have a :ref:`Stored Procedure <s_procs>` that returns a table type, you c
Here's a sample function (notice the ``RETURNS SETOF films``).
.. code-block:: plpgsql
.. code-block:: postgres
CREATE FUNCTION getallfilms() RETURNS SETOF films AS $$
SELECT * FROM films;
+4 -4
View File
@@ -88,7 +88,7 @@ To add schemas dynamically, you can use :ref:`in_db_config` plus :ref:`config re
- If the schemas' names have a pattern, like a ``tenant_`` prefix, do:
.. code-block:: postgresql
.. code-block:: postgres
create or replace function postgrest.pre_config()
returns void as $$
@@ -100,7 +100,7 @@ To add schemas dynamically, you can use :ref:`in_db_config` plus :ref:`config re
- If there's no name pattern but they're created with a particular role (``CREATE SCHEMA mine AUTHORIZATION joe``), do:
.. code-block:: postgresql
.. code-block:: postgres
create or replace function postgrest.pre_config()
returns void as $$
@@ -112,7 +112,7 @@ To add schemas dynamically, you can use :ref:`in_db_config` plus :ref:`config re
- Otherwise, you might need to create a table that stores the allowed schemas.
.. code-block:: postgresql
.. code-block:: postgres
create table postgrest.config (schemas text);
@@ -125,7 +125,7 @@ To add schemas dynamically, you can use :ref:`in_db_config` plus :ref:`config re
Then each time you add an schema, do:
.. code-block:: postgresql
.. code-block:: postgres
NOTIFY pgrst, 'reload config';
NOTIFY pgrst, 'reload schema';
+4 -4
View File
@@ -23,7 +23,7 @@ To supply arguments in an API call, include a JSON object in the request payload
For instance, assume we have created this function in the database.
.. code-block:: plpgsql
.. code-block:: postgres
CREATE FUNCTION add_them(a integer, b integer)
RETURNS integer AS $$
@@ -73,7 +73,7 @@ Functions with a single unnamed JSON parameter
If you want the JSON request body to be sent as a single argument, you can create a function with a single unnamed ``json`` or ``jsonb`` parameter.
For this the ``Content-Type: application/json`` header must be included in the request.
.. code-block:: plpgsql
.. code-block:: postgres
CREATE FUNCTION mult_them(json) RETURNS int AS $$
SELECT ($1->>'x')::int * ($1->>'y')::int
@@ -108,7 +108,7 @@ To send raw XML, the parameter type must be ``xml`` and the header ``Content-Typ
To send raw binary, the parameter type must be ``bytea`` and the header ``Content-Type: application/octet-stream`` must be included in the request.
.. code-block:: plpgsql
.. code-block:: postgres
CREATE TABLE files(blob bytea);
@@ -252,7 +252,7 @@ Let's get its :ref:`explain_plan` when calling it with filters applied:
curl "http://localhost:3000/rpc/getallprojects?id=eq.1" \
-H "Accept: application/vnd.pgrst.plan"
.. code-block:: psql
.. code-block:: postgres
Aggregate (cost=8.18..8.20 rows=1 width=112)
-> Index Scan using projects_pkey on projects (cost=0.15..8.17 rows=1 width=40)
+1 -1
View File
@@ -88,7 +88,7 @@ any :code:`ANY` comparison matches any value in the list
For more complicated filters you will have to create a new view in the database, or use a stored procedure. For instance, here's a view to show "today's stories" including possibly older pinned stories:
.. code-block:: postgresql
.. code-block:: postgres
CREATE VIEW fresh_stories AS
SELECT *
+1 -1
View File
@@ -80,7 +80,7 @@ You can also configure the server with database settings by using a :ref:`pre-co
PGRST_DB_PRE_CONFIG = "postgrest.pre_config"
.. code-block:: postgresql
.. code-block:: postgres
-- create a dedicated schema, hidden from the API
create schema postgrest;
+4 -4
View File
@@ -339,7 +339,7 @@ RAISE errors with HTTP Status Codes
Custom status codes can be done by raising SQL exceptions inside :ref:`functions <s_procs>`. For instance, here's a saucy function that always responds with an error:
.. code-block:: postgresql
.. code-block:: postgres
CREATE OR REPLACE FUNCTION just_fail() RETURNS void
LANGUAGE plpgsql
@@ -366,7 +366,7 @@ One way to customize the HTTP status code is by raising particular exceptions ac
For even greater control of the HTTP status code, raise an exception of the ``PTxyz`` type. For instance to respond with HTTP 402, raise ``PT402``:
.. code-block:: sql
.. code-block:: postgres
RAISE sqlstate 'PT402' using
message = 'Payment Required',
@@ -394,7 +394,7 @@ Add HTTP Headers with RAISE
For full control over headers and status you can raise a ``PGRST`` SQLSTATE error. You can achieve this by adding the ``code``, ``message``, ``detail`` and ``hint`` in the PostgreSQL error message field as a JSON object. Here, the ``details`` and ``hint`` are optional. Similarly, the ``status`` and ``headers`` must be added to the SQL error detail field as a JSON object. For instance:
.. code-block:: sql
.. code-block:: postgres
RAISE sqlstate 'PGRST' USING
message = '{"code":"123","message":"Payment Required","details":"Quota exceeded","hint":"Upgrade your plan"}',
@@ -418,7 +418,7 @@ Returns:
For non standard HTTP status, you can optionally add ``status_text`` to describe the status code. For status code ``419`` the detail field may look like this:
.. code-block:: sql
.. code-block:: postgres
detail = '{"status":419,"status_text":"Page Expired","headers":{"X-Powered-By":"Nerd Rage"}}';
+3 -3
View File
@@ -96,7 +96,7 @@ When debugging a problem it's important to verify the running PostgREST version.
- Query ``application_name`` on `pg_stat_activity <https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-PG-STAT-ACTIVITY-VIEW>`_.
.. code-block:: psql
.. code-block:: postgres
select distinct application_name
from pg_stat_activity
@@ -177,7 +177,7 @@ This is enabled by :ref:`db-plan-enabled` (false by default).
curl "http://localhost:3000/users?select=name&order=id" \
-H "Accept: application/vnd.pgrst.plan"
.. code-block:: psql
.. code-block:: postgres
Aggregate (cost=73.65..73.68 rows=1 width=112)
-> Index Scan using users_pkey on users (cost=0.15..60.90 rows=850 width=36)
@@ -237,7 +237,7 @@ However, if you choose to use it in production you can add a :ref:`db-pre-reques
For example, to only allow requests from an IP address to get the execution plans:
.. code-block:: postgresql
.. code-block:: postgres
-- Assuming a proxy(Nginx, Cloudflare, etc) passes an "X-Forwarded-For" header(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)
create or replace function filter_plan_requests()
+4 -4
View File
@@ -68,7 +68,7 @@ Reloading with NOTIFY
PostgREST also allows you to reload its schema cache through PostgreSQL `NOTIFY <https://www.postgresql.org/docs/current/sql-notify.html>`_.
.. code-block:: postgresql
.. code-block:: postgres
NOTIFY pgrst, 'reload schema'
@@ -83,7 +83,7 @@ Automatic Schema Cache Reloading
You can do automatic schema cache reloading in a pure SQL way and forget about stale schema cache errors. For this use an `event trigger <https://www.postgresql.org/docs/current/event-trigger-definition.html>`_ and ``NOTIFY``.
.. code-block:: postgresql
.. code-block:: postgres
-- Create an event trigger function
CREATE OR REPLACE FUNCTION pgrst_watch() RETURNS event_trigger
@@ -103,7 +103,7 @@ Now, whenever the ``pgrst_watch`` trigger fires, PostgREST will auto-reload the
To disable auto reloading, drop the trigger.
.. code-block:: postgresql
.. code-block:: postgres
DROP EVENT TRIGGER pgrst_watch
@@ -113,7 +113,7 @@ Finer-Grained Event Trigger
You can refine the previous event trigger to only react to the events relevant to the schema cache. This also prevents unnecessary
reloading when creating temporary tables inside functions.
.. code-block:: postgresql
.. code-block:: postgres
-- watch CREATE and ALTER
CREATE OR REPLACE FUNCTION pgrst_ddl_watch() RETURNS event_trigger AS $$
+15 -15
View File
@@ -5,7 +5,7 @@ Transactions
After :ref:`user_impersonation`, every request to an :doc:`API resource <api>` runs inside a transaction. The sequence of the transaction is as follows:
.. code-block:: postgresql
.. code-block:: postgres
START TRANSACTION; -- <Access Mode> <Isolation Level>
-- <Transaction-scoped settings>
@@ -21,7 +21,7 @@ The access mode determines whether the transaction can modify the database or no
Modifying the database inside READ ONLY transactions is not possible. PostgREST uses this fact to enforce HTTP semantics in GET and HEAD requests. Consider the following:
.. code-block:: postgresql
.. code-block:: postgres
CREATE SEQUENCE callcounter_count START 1;
@@ -92,7 +92,7 @@ Isolation Level
Every transaction uses the PostgreSQL default isolation level: READ COMMITTED. Unless you modify `default_transaction_isolation <https://www.postgresql.org/docs/15/runtime-config-client.html#GUC-DEFAULT-TRANSACTION-ISOLATION>`_ for an impersonated role or function.
.. code-block:: postgresql
.. code-block:: postgres
ALTER ROLE webuser SET default_transaction_isolation TO 'repeatable read';
@@ -100,7 +100,7 @@ Every ``webuser`` gets its queries executed with ``default_transaction_isolation
Or to change the isolation level per function call.
.. code-block:: postgresql
.. code-block:: postgres
CREATE OR REPLACE FUNCTION myfunc()
RETURNS text as $$
@@ -118,7 +118,7 @@ PostgREST uses settings tied to the transaction lifetime. These can be used to g
You can get these with ``current_setting``
.. code-block:: postgresql
.. code-block:: postgres
-- request settings use the ``request.`` prefix.
SELECT
@@ -126,7 +126,7 @@ You can get these with ``current_setting``
And you can set them with ``set_config``
.. code-block:: postgresql
.. code-block:: postgres
-- response settings use the ``response.`` prefix.
SELECT
@@ -139,7 +139,7 @@ Request Headers, Cookies and JWT claims
PostgREST stores the headers, cookies and headers as JSON. To get them:
.. code-block:: postgresql
.. code-block:: postgres
-- To get all the headers sent in the request
SELECT current_setting('request.headers', true)::json;
@@ -162,7 +162,7 @@ PostgREST stores the headers, cookies and headers as JSON. To get them:
+ This is considered expected behavior by PostgreSQL. For more details, see `this discussion <https://www.postgresql.org/message-id/flat/CAB_pDVVa84w7hXhzvyuMTb8f5kKV3bee_p9QTZZ58Rg7zYM7sw%40mail.gmail.com>`_.
+ To avoid this inconsistency, you can create a wrapper function like:
.. code-block:: postgresql
.. code-block:: postgres
CREATE FUNCTION my_current_setting(text) RETURNS text
LANGUAGE SQL AS $$
@@ -176,7 +176,7 @@ Request Path and Method
The path and method are stored as ``text``.
.. code-block:: postgresql
.. code-block:: postgres
SELECT current_setting('request.path', true);
@@ -187,7 +187,7 @@ Request Role and Search Path
Because of :ref:`user_impersonation`, PostgREST sets the standard ``role``. You can get this in different ways:
.. code-block:: postgresql
.. code-block:: postgres
SELECT current_role;
@@ -204,7 +204,7 @@ Response Headers
You can set ``response.headers`` to add headers to the HTTP response. For instance, this statement would add caching headers to the response:
.. code-block:: sql
.. code-block:: postgres
-- tell client to cache response for two days
@@ -265,7 +265,7 @@ This allows finer-grained control over actions made by a role.
For example, consider `statement_timeout <https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-STATEMENT-TIMEOUT>`__. It allows you to abort any statement that takes more than a specified time. It is disabled by default.
.. code-block:: postgresql
.. code-block:: postgres
ALTER ROLE authenticator SET statement_timeout TO '10s';
ALTER ROLE anonymous SET statement_timeout TO '1s';
@@ -280,7 +280,7 @@ For more details see `Understanding Postgres Parameter Context <https://www.ente
However, starting from PostgreSQL 15, you can grant privileges for these settings with:
.. code-block:: postgresql
.. code-block:: postgres
GRANT SET ON PARAMETER <setting> TO <authenticator>;
@@ -290,7 +290,7 @@ Function Settings
In addition to :ref:`impersonated_settings`, PostgREST will also apply function settings as transaction-scoped settings. This allows functions settings to override
the impersonated and connection role settings.
.. code-block:: postgresql
.. code-block:: postgres
CREATE OR REPLACE FUNCTION myfunc()
RETURNS void as $$
@@ -340,7 +340,7 @@ Setting headers via pre-request
As an example, let's add some cache headers for all requests that come from an Internet Explorer(6 or 7) browser.
.. code-block:: postgresql
.. code-block:: postgres
create or replace function custom_headers()
returns void as $$
+1 -1
View File
@@ -206,7 +206,7 @@ PostgREST allows us to specify a stored procedure to run during attempted authen
First make a new schema and add the function:
.. code-block:: plpgsql
.. code-block:: postgres
create schema auth;
grant usage on schema auth to web_anon, todo_user;