### Build and install pg_net with make Source: https://github.com/supabase/pg_net/blob/master/README.md Clone the repository and run make to build and install the extension. Requires a PostgreSQL development environment. ```bash make && make install ``` -------------------------------- ### Example of net._urlencode_string() Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md Example call to net._urlencode_string() showing the percent-encoded output for the input 'foo1=bar1 & !<>'. ```sql SELECT net._urlencode_string('foo1=bar1 & !<>'); -- => 'foo1%3Dbar1%20%26%20%21%3C%3E' ``` -------------------------------- ### net.wait_until_running usage example Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md Example showing how to use net.wait_until_running after a crash or restart to wait for the worker to come back before firing requests. ```sql -- After a crash or restart, wait for the worker to come back before firing requests SELECT net.worker_restart(); SELECT net.wait_until_running(); SELECT net.http_get('https://example.com'); ``` -------------------------------- ### Example: migrate to net._http_collect_response Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-response-collection.md Example showing the recommended migration path: call net._http_collect_response directly instead of the deprecated net.http_collect_response. The comment explicitly warns not to use the deprecated function. ```sql -- Do NOT use; migrate to the private function: SELECT * FROM net._http_collect_response(1, async := false); ``` -------------------------------- ### net.wake usage example Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md Example showing a direct queue insert followed by a manual net.wake() call, because the insert itself never wakes the worker. ```sql -- Direct queue insert, then manual wake (the insert itself never wakes the worker) INSERT INTO net.http_request_queue(method, url, timeout_milliseconds) VALUES ('GET', 'https://example.com', 5000); SELECT net.wake(); ``` -------------------------------- ### Basic net.http_post examples Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Shows basic usage of net.http_post: posting a raw JSON payload and posting a table row as JSON. The second example uses a CTE to select one row and passes it via to_jsonb, with a custom header. ```sql -- Basic use: POST a raw JSON payload SELECT net.http_post( 'https://postman-echo.com/post', '{"key": "value", "n": 5}'::jsonb ) AS request_id; -- Post one row of a table as the payload; each selected row posts a request WITH selected_row AS ( SELECT * FROM target_table LIMIT 1 ) SELECT net.http_post( 'https://postman-echo.com/post', to_jsonb(selected_row.*), headers := '{"API-KEY-HEADER": ""}'::jsonb ) AS request_id FROM selected_row; ``` -------------------------------- ### Example: blocking wait with net._await_response Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-response-collection.md Shows a blocking wait loop using net._await_response when the response id is not known in advance. The example posts a request, waits for the response row, then selects it. ```sql -- Blocking wait loop, useful when the response id is not known in advance SELECT net.http_post('https://example.com/webhook', '{"event": "x"}'::jsonb) \gset PERFORM net._await_response(:request_id); -- returns true once the row appears SELECT * FROM net._http_response WHERE id = :request_id; ``` -------------------------------- ### Basic net.http_delete examples Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Shows basic usage of net.http_delete: a simple DELETE by id and a per-row DELETE using a path parameter from a table. The second example uses a CTE to select an id and concatenates it to the URL. ```sql -- Basic delete by id SELECT net.http_delete('https://dummy.restapiexample.com/api/v1/delete/2') AS request_id; -- Delete the row id as a path parameter, per row of a table WITH selected_id AS ( SELECT id FROM target_table LIMIT 1 ) SELECT net.http_delete('https://dummy.restapiexample.com/api/v1/delete/' || id) FROM selected_id; ``` -------------------------------- ### Enable pg_net via shared_preload_libraries Source: https://github.com/supabase/pg_net/blob/master/README.md Add pg_net to shared_preload_libraries in postgresql.conf to load the extension at server start. ```sql shared_preload_libraries = 'pg_net' ``` -------------------------------- ### Call net._encode_url_with_params_array with example parameters Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md Shows how to call net._encode_url_with_params_array with a base URL and an array of pre-encoded key=value strings. The output is the full URL with the query string appended, as shown in the comment. ```sql -- Same operation the request functions perform internally SELECT net._encode_url_with_params_array( 'https://example.com/endpoint', ARRAY['foo1=bar1', 'encoded=%21'] ); -- => https://example.com/endpoint?foo1=bar1&encoded=%21 ``` -------------------------------- ### net.http_post Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Documentation for the net.http_post function, including signature, parameters, return type, errors, and examples. ```APIDOC ## net.http_post ### Description Enqueues an asynchronous HTTP POST request with a JSON body. ### Signature ```sql create or replace function net.http_post( -- url for the request url text, -- body of the POST request body jsonb default '{}'::jsonb, -- key/value pairs to be url encoded and appended to the `url` params jsonb default '{}'::jsonb, -- key/values to be included in request headers headers jsonb default '{"Content-Type": "application/json"}'::jsonb, -- the maximum number of milliseconds the request may take before being cancelled timeout_milliseconds int DEFAULT 5000 ) -- request_id reference returns bigint language plpgsql ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `url` | `text` | yes | — | URL for the request (`http`/`https` only, see `net.http_get`). | | `body` | `jsonb` | no | `'{}'::jsonb` | JSON body. Serialized as `body::text` and stored UTF-8 encoded in `net.http_request_queue.body` (bytea) via `convert_to(body::text, 'UTF8')`; sent with `CURLOPT_POSTFIELDS`. | | `params` | `jsonb` | no | `'{}'::jsonb` | Query-string key/value pairs appended to `url` (same handling as `net.http_get`). | | `headers` | `jsonb` | no | `'{"Content-Type": "application/json"}'::jsonb` | Key/value header pairs. Special content-type rules: if the supplied headers contain no `content-type` key (case-insensitive match on the key), `{"Content-Type": "application/json"}` is merged in automatically even when `headers` is `NULL`; if a content-type key is present with any value other than exactly `application/json`, the function raises an exception (see below). | | `timeout_milliseconds` | `int` | no | `5000` | See `net.http_get`. | ### Return Type `bigint` — the request id (queue row id), same contract as `net.http_get`. ### Throws (synchronous) | Error | Condition | |---|---| | `Content-Type header must be "application/json"` | the `headers` jsonb contains a `content-type` key whose value differs from `application/json` (case-insensitive key lookup, exact value comparison; `sql/pg_net.sql` line 192) | | `null value in column "url"` | `url IS NULL` | | `invalid URL "": ` / `failed to encode URL "": ` | URL parsing/encoding failure in `net._encode_url_with_params_array` | ### Examples ```sql -- Basic use: POST a raw JSON payload SELECT net.http_post( 'https://postman-echo.com/post', '{"key": "value", "n": 5}'::jsonb ) AS request_id; -- Post one row of a table as the payload; each selected row posts a request WITH selected_row AS ( SELECT * FROM target_table LIMIT 1 ) SELECT net.http_post( 'https://postman-echo.com/post', to_jsonb(selected_row.*), headers := '{"API-KEY-HEADER": ""}'::jsonb ) AS request_id FROM selected_row; ``` ```sql -- Error handling: the content-type guard is a synchronous exception DO $$ BEGIN BEGIN PERFORM net.http_post( 'https://example.com', '{"a": 1}'::jsonb, headers := '{"Content-Type": "text/plain"}'::jsonb ); EXCEPTION WHEN raise_exception THEN RAISE NOTICE 'caught: % (SQLSTATE %)', SQLERRM, SQLSTATE; END; END $$; -- -> caught: Content-Type header must be "application/json" (SQLSTATE P0001) ``` ``` -------------------------------- ### Run all tests in a file Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Set PYTEST_ARGS to the test file path to run all tests in that file. Note the double equals sign in the example. ```bash $ nix develop $ PYTEST_ARGS="PYTEST_ARGS="test/test_user_db.py" xpg test ``` -------------------------------- ### Debug with GDB wrapper Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Enter the nix shell and run the net-with-gdb script to debug the background worker. The script automatically obtains the pid of the latest started worker. ```bash $ nix-shell $ sudo net-with-gdb ``` -------------------------------- ### Calling an API with net.http_get Source: https://github.com/supabase/pg_net/blob/master/README.md Calls the Postman Echo API with a GET request using net.http_get. The response can be viewed with a query on net._http_response. ```sql SELECT net.http_get ( 'https://postman-echo.com/get?foo1=bar1&foo2=bar2' ) AS request_id; ``` -------------------------------- ### net.http_delete Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Documentation for the net.http_delete function, including signature, parameters, return type, errors, and examples. ```APIDOC ## net.http_delete ### Description Enqueues an asynchronous HTTP DELETE request. Optionally carries a body (stored and sent when non-NULL). ### Signature ```sql create or replace function net.http_delete( -- url for the request url text, -- key/value pairs to be url encoded and appended to the `url` params jsonb default '{}'::jsonb, -- key/values to be included in request headers headers jsonb default '{}'::jsonb, -- the maximum number of milliseconds the request may take before being cancelled timeout_milliseconds int default 5000, -- optional body of the request body jsonb default NULL ) -- request_id reference returns bigint language plpgsql as $$ declare request_id bigint; params_array text[]; begin select coalesce(array_agg(net._urlencode_string(key) || '=' || net._urlencode_string(value)), '{}') into params_array from jsonb_each_text(params); -- Add to the request queue insert into net.http_request_queue(method, url, headers, body, timeout_milliseconds) values ( 'DELETE', net._encode_url_with_params_array(url, params_array), headers, convert_to(body::text, 'UTF8'), timeout_milliseconds ) returning id into request_id; perform net.wake(); return request_id; end $$; ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `url` | `text` | yes | — | URL for the request (`http`/`https` only). | | `params` | `jsonb` | no | `'{}'::jsonb` | Query-string key/value pairs appended to `url`. | | `headers` | `jsonb` | no | `'{}'::jsonb` | Key/value header pairs. No content-type enforcement (unlike `net.http_post`). | | `timeout_milliseconds` | `int` | no | `5000` | See `net.http_get`. | | `body` | `jsonb` | no | `NULL` | Optional JSON body. When non-`NULL`, serialized as `body::text`, UTF-8 encoded via `convert_to`, and sent as POSTFIELDS together with `CURLOPT_CUSTOMREQUEST = "DELETE"` (`src/core.c` `init_curl_handle`). When `NULL`, sent with no body. | ### Return type `bigint` — the request id, same contract as `net.http_get`. ### Throws (synchronous) | Error | Condition | |---|---| | `null value in column "url"` | `url IS NULL` | | `invalid URL "": ` / `failed to encode URL "": ` | URL parsing/encoding failure | Note: when `params`, `headers`, or `body` is `NULL`, the queue row stores `NULL` and `init_curl_handle` treats the row as headerless/bodyless — no exception is raised (headers NULL skips the `array(select ...)` subquery path; see `test/test_http_errors.py` `test_bad_utils` for the helper functions, and `src/core.c` for NULL `headersBin`/`bodyBin` handling). ### Examples ```sql -- Basic delete by id SELECT net.http_delete('https://dummy.restapiexample.com/api/v1/delete/2') AS request_id; -- Delete the row id as a path parameter, per row of a table WITH selected_id AS ( SELECT id FROM target_table LIMIT 1 ) SELECT net.http_delete('https://dummy.restapiexample.com/api/v1/delete/' || id) FROM selected_id; ``` ```sql -- Delete with the id as a query param plus a JSON body (triggers in the README -- show the trigger-Typesense pattern; body usage mirrors http_post) WITH selected_id AS ( SELECT id FROM target_table LIMIT 1 ) SELECT net.http_delete( 'https://dummy.restapiexample.com/api/v1/delete/', format('{"id": "%s"}', id)::jsonb, body := '{"reason": "user requested removal"}'::jsonb ) AS request_id FROM selected_id; ``` ``` -------------------------------- ### Unpack net.http_response_result from net._http_collect_response Source: https://github.com/supabase/pg_net/blob/master/_autodocs/types.md Example query that unpacks the nested net.http_response_result composite returned by net._http_collect_response, accessing status, message, and response fields. ```sql -- Unpack the nested composite SELECT (res).status, (res).message, (res).response.status_code, (res).response.headers, (res).response.body FROM net._http_collect_response(42, async := false) AS res; ``` -------------------------------- ### Apply config changes and restart worker Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md Example SQL commands to apply ttl/batch_size configuration changes and bounce the worker in one call. It sets the pg_net.ttl GUC, reloads configuration, restarts the worker, and waits until it is running. ```sql -- Apply ttl/batch_size config changes and bounce the worker in one call ALTER SYSTEM SET pg_net.ttl TO '1 hour'; SELECT pg_reload_conf(); SELECT net.worker_restart(); SELECT net.wait_until_running(); ``` -------------------------------- ### net.http_get Source: https://github.com/supabase/pg_net/blob/master/_autodocs/index.md Sends an asynchronous HTTP GET request. ```APIDOC ## net.http_get ### Description Sends an asynchronous HTTP GET request. ### Method GET ### Endpoint net.http_get ### Parameters #### Function Parameters - **url** (text) - Required - The URL to send the request to. - **params** (jsonb) - Optional - Query parameters to include in the request. - **headers** (jsonb) - Optional - HTTP headers to include in the request. - **timeout_milliseconds** (integer) - Optional - Timeout in milliseconds for the request. ### Request Example ```sql SELECT net.http_get( url := 'https://example.com/api', params := '{"key":"value"}'::jsonb, headers := '{"Authorization":"Bearer token"}'::jsonb, timeout_milliseconds := 5000 ); ``` ### Response #### Success Response (200) - **id** (bigint) - The ID of the queued request. #### Response Example ```json { "id": 1 } ``` ``` -------------------------------- ### Run a single test with PYTEST_ARGS Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Set PYTEST_ARGS to filter which tests run. This example runs only the test_connect test. PYTEST_ARGS is passed directly to pytest. ```bash $ nix develop $ PYTEST_ARGS="-k test_connect" xpg test ``` -------------------------------- ### Create request wrapper function Source: https://github.com/supabase/pg_net/blob/master/README.md Creates a function that wraps PG_NET request functions to record request details in the request_tracker table. It supports DELETE, POST, and GET methods, and raises an exception for other methods. ```sql CREATE OR REPLACE FUNCTION request_wrapper( method TEXT, url TEXT, params JSONB DEFAULT '{}'::JSONB, body JSONB DEFAULT '{}'::JSONB, headers JSONB DEFAULT '{}'::JSONB ) RETURNS BIGINT AS $$ DECLARE request_id BIGINT; BEGIN IF method = 'DELETE' THEN SELECT net.http_delete( url:=url, params:=params, headers:=headers ) INTO request_id; ELSIF method = 'POST' THEN SELECT net.http_post( url:=url, body:=body, params:=params, headers:=headers ) INTO request_id; ELSIF method = 'GET' THEN SELECT net.http_get( url:=url, params:=params, headers:=headers ) INTO request_id; ELSE RAISE EXCEPTION 'Method must be DELETE, POST, or GET'; END IF; INSERT INTO request_tracker (method, url, params, body, headers, request_id) VALUES (method, url, params, body, headers, request_id); RETURN request_id; END; $$ LANGUAGE plpgsql; ``` -------------------------------- ### Guard application path with net.check_worker_is_up() Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md Example usage of net.check_worker_is_up() to guard an application path. It calls the function before making an HTTP request and catches the raise_exception error to log a warning. ```sql -- Guard an application path that depends on the worker BEGIN SELECT net.check_worker_is_up(); SELECT net.http_get('https://example.com'); EXCEPTION WHEN raise_exception THEN RAISE WARNING 'pg_net worker is down: %', SQLERRM; END; ``` -------------------------------- ### Use the nxpg binary cache Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Configure the nxpg binary cache to download pre-built packages instead of building them. This is for repo members to save time. ```sh nix run nixpkgs#cachix use nxpg ``` -------------------------------- ### View pg_net configuration variables Source: https://github.com/supabase/pg_net/blob/master/README.md Use SHOW commands to display the current values of pg_net configuration variables. ```sql show pg_net.batch_size; show pg_net.ttl; show pg_net.database_name; show pg_net.username; show pg_net.max_timeout_ms; ``` -------------------------------- ### Open development shell and run tests Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Enter the development shell and run the test suite. The xpg command runs tests against the latest PostgreSQL version by default. ```bash # Open a development shell with all deps and tools present $ nix develop # test on latest pg $ xpg test # test on pg 14 $ xpg -v 14 test # test on pg 15 $ xpg -v 15 test ``` -------------------------------- ### Create pg_net extension Source: https://github.com/supabase/pg_net/blob/master/README.md Run the create extension command to activate pg_net. This creates the net schema to avoid naming conflicts. ```psql create extension pg_net; ``` -------------------------------- ### Run load test with net-loadtest Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Run the load test with 1000 requests and a batch size of 200. The command takes the number of requests and the pg_net.batch_size as parameters. ```bash $ net-loadtest 1000 200 ``` -------------------------------- ### Test net.http_get with debug output Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Run a SQL query to test net.http_get and observe the debug output. The output shows curl traces including connection attempts and HTTP response details. ```sql select net.http_get('http://localhost:3000/projects'); -- * Trying ::1:3000... -- * connect to ::1 port 3000 failed: Connection refused -- * Trying 127.0.0.1:3000... -- * Connected to localhost (127.0.0.1) port 3000 (#0) -- > GET /projects HTTP/1.1 -- Host: localhost:3000 -- Accept: */* -- User-Agent: pg_net/0.2 -- -- * Mark bundle as not supporting multiuse -- < HTTP/1.1 200 OK -- < Transfer-Encoding: chunked -- < Date: Fri, 27 Aug 2021 00:14:37 GMT -- < Server: postgrest/7.0.0 (UNKNOWN) -- < Content-Type: application/json; charset=utf-8 -- < Content-Range: 0-58/* -- < Content-Location: /projects -- < -- * Connection #0 to host localhost left intact ``` -------------------------------- ### Basic net.http_get calls Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Shows two basic calls to net.http_get. The first passes a full URL with query parameters; the second uses named parameters to add URL-encoded params and a custom header. Both return a request_id immediately. ```sql -- Basic call: returns a request_id immediately SELECT net.http_get('https://postman-echo.com/get?foo1=bar1&foo2=bar2') AS request_id; -- With url-encoded params and a custom header SELECT net.http_get( 'https://postman-echo.com/get', params := '{"foo1": "bar1", "encoded": "!"}'::jsonb, -- "!" is encoded to %21 headers := '{"API-KEY-HEADER": ""}'::jsonb ) AS request_id; ``` -------------------------------- ### Create net.http_method domain Source: https://github.com/supabase/pg_net/blob/master/_autodocs/types.md Defines the net.http_method domain over text, restricting values to 'get', 'post', or 'delete' (case-insensitive). Used as the column type for net.http_request_queue.method. ```sql create domain net.http_method as text check ( value ilike 'get' or value ilike 'post' or value ilike 'delete' ); ``` -------------------------------- ### Sending a delete request to an API Source: https://github.com/supabase/pg_net/blob/master/README.md Sends a DELETE request to the specified URL using net.http_delete. The example uses the Dummy Rest API endpoint and returns the request_id. ```sql SELECT net.http_delete( 'https://dummy.restapiexample.com/api/v1/delete/2' ) AS request_id; ``` -------------------------------- ### net.http_get Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Enqueues an asynchronous HTTP GET request and returns a request ID. The request is processed in the background; transport-level failures are captured in the response table, not thrown synchronously. ```APIDOC ## net.http_get ### Description Enqueues an asynchronous HTTP GET request. Returns a request ID that can be used to correlate the response. ### Signature sql create or replace function net.http_get( url text, params jsonb default '{}'::jsonb, headers jsonb default '{}'::jsonb, timeout_milliseconds int default 5000 ) returns bigint ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `url` | `text` | yes | — | URL for the request. Must include a scheme; only `http` and `https` are allowed. A relative URL raises `invalid URL ""` synchronously. | | `params` | `jsonb` | no | `'{}'::jsonb` | Key/value pairs URL-encoded and appended to `url` as a query string. | | `headers` | `jsonb` | no | `'{}'::jsonb` | Key/value header pairs. Each pair becomes one header line `Key: value`. A header containing a CR or LF is never sent; the request gets an ERROR response. | | `timeout_milliseconds` | `int` | no | `5000` | Maximum milliseconds before libcurl cancels the request. Must be `1..pg_net.max_timeout_ms` (default 600000); values outside the bound are not sent and get an ERROR response. | ### Return Type `bigint` — the `id` of the inserted row in `net.http_request_queue`. It is the identifier used to correlate the response row in `net._http_response` and to pass to `net._http_collect_response`. ### Throws (synchronous, to the calling session) | Error | Condition | |---|---| | `null value in column "url"` | `url IS NULL` (NOT NULL violation at insert) | | `invalid URL "": ` | URL rejected by libcurl's `curl_url()`/`curl_url_set(CURLUPART_URL, ...)` in `net._encode_url_with_params_array`, e.g. a relative URL without a scheme | | `failed to encode URL "": ` | `curl_url_get(CURLUPART_URL, ...)` fails in `net._encode_url_with_params_array` | Transport-level failures (DNS failure, connection refused, protocol not allowed, HTTP 4xx/5xx) are **not** thrown — they appear in `net._http_response.error_msg` / `status_code`. ### Examples sql -- Basic call: returns a request_id immediately SELECT net.http_get('https://postman-echo.com/get?foo1=bar1&foo2=bar2') AS request_id; -- With url-encoded params and a custom header SELECT net.http_get( 'https://postman-echo.com/get', params := '{"foo1": "bar1", "encoded": "!"}'::jsonb, -- "!" is encoded to %21 headers := '{"API-KEY-HEADER": ""}'::jsonb ) AS request_id; sql -- Error handling in application code: catch synchronous validation errors, -- then poll the response async-style DO $$ DECLARE req_id bigint; res net.http_response_result; BEGIN BEGIN req_id := net.http_get('/relative-url-is-rejected'); EXCEPTION WHEN others THEN RAISE NOTICE 'request rejected synchronously: %', SQLERRM; END; -- Out-of-bounds timeouts are NOT thrown; they produce an ERROR response row req_id := net.http_get( 'https://example.com', timeout_milliseconds := 0 -- rejected by the worker, response.status = 'ERROR' ); res := net._http_collect_response(req_id, async := false); IF res.status = 'ERROR' THEN RAISE NOTICE 'request failed: %', res.message; END IF; END $$; ``` -------------------------------- ### RegisterBackgroundWorker call for pg_net worker Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/background-worker.md Registers the background worker with flags for shared memory access and database connection, starting after recovery, with a restart time of 1 second. ```c RegisterBackgroundWorker(&(BackgroundWorker){ .bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION, .bgw_start_time = BgWorkerStart_RecoveryFinished, .bgw_library_name = "pg_net", .bgw_function_name = "pg_net_worker", .bgw_name = "pg_net " EXTVERSION " worker", .bgw_restart_time = net_worker_restart_time_sec, // 1 second }); ``` -------------------------------- ### Create request tracker table Source: https://github.com/supabase/pg_net/blob/master/README.md Creates a table to track request details for retrying failed requests. The table stores method, URL, params, body, headers, and request_id for each request. ```sql CREATE TABLE request_tracker( method TEXT, url TEXT, params JSONB, body JSONB, headers JSONB, request_id BIGINT ) ``` -------------------------------- ### Define the five GUCs for pg_net Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/background-worker.md Registers the configuration parameters `pg_net.ttl`, `pg_net.batch_size`, `pg_net.max_timeout_ms`, `pg_net.database_name`, and `pg_net.username` with their defaults and access levels. ```c DefineCustomStringVariable("pg_net.ttl", ..., &guc_ttl, "6 hours", PGC_SIGHUP, 0, check_ttl, NULL, NULL); DefineCustomIntVariable("pg_net.batch_size", ..., &guc_batch_size, 200, 0, PG_INT16_MAX, PGC_SIGHUP, 0, NULL, NULL, NULL); DefineCustomIntVariable("pg_net.max_timeout_ms", ..., &guc_max_timeout_ms, DEFAULT_MAX_TIMEOUT_MS /* 600000 */, 1, PG_INT32_MAX, PGC_SUSET, 0, NULL, NULL, NULL); DefineCustomStringVariable("pg_net.database_name", ..., &guc_database_name, "postgres", PGC_SU_BACKEND, 0, NULL, NULL, NULL); DefineCustomStringVariable("pg_net.username", ..., &guc_username, NULL, PGC_SU_BACKEND, 0, NULL, NULL, NULL); ``` -------------------------------- ### Change pg_net.database_name and restart worker Source: https://github.com/supabase/pg_net/blob/master/_autodocs/configuration.md Changes pg_net.database_name and restarts the worker with net.worker_restart(), then blocks until it is running with net.wait_until_running(). Changing database_name requires a worker restart because it is read only at worker start. ```sql -- Point the worker at another database (restart required) ALTER SYSTEM SET pg_net.database_name TO 'analytics'; SELECT net.worker_restart(); SELECT net.wait_until_running(); ``` -------------------------------- ### net.http_post function definition (sql/pg_net.sql) Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Full PL/pgSQL implementation of net.http_post. It extracts the content-type header (case-insensitive), merges in the default application/json header if missing, raises an exception if the content-type is not exactly application/json, URL-encodes params, inserts into net.http_request_queue, and calls net.wake(). ```sql create or replace function net.http_post( -- url for the request url text, -- body of the POST request body jsonb default '{}'::jsonb, -- key/value pairs to be url encoded and appended to the `url` params jsonb default '{}'::jsonb, -- key/values to be included in request headers headers jsonb default '{"Content-Type": "application/json"}'::jsonb, -- the maximum number of milliseconds the request may take before being cancelled timeout_milliseconds int DEFAULT 5000 ) -- request_id reference returns bigint language plpgsql as $$ declare request_id bigint; params_array text[]; content_type text; begin -- Exctract the content_type from headers select header_value into content_type from jsonb_each_text(coalesce(headers, '{}'::jsonb)) r(header_name, header_value) where lower(header_name) = 'content-type' limit 1; -- If the user provided new headers and omitted the content type -- add it back in automatically if content_type is null then select headers || '{"Content-Type": "application/json"}'::jsonb into headers; end if; -- Confirm that the content-type is set as "application/json" if content_type <> 'application/json' then raise exception 'Content-Type header must be "application/json"'; end if; select coalesce(array_agg(net._urlencode_string(key) || '=' || net._urlencode_string(value)), '{}') into params_array from jsonb_each_text(params); -- Add to the request queue insert into net.http_request_queue(method, url, headers, body, timeout_milliseconds) values ( 'POST', net._encode_url_with_params_array(url, params_array), headers, convert_to(body::text, 'UTF8'), timeout_milliseconds ) returning id into request_id; perform net.wake(); return request_id; end $$; ``` -------------------------------- ### net.wake Source: https://github.com/supabase/pg_net/blob/master/_autodocs/index.md Wakes up the background worker. ```APIDOC ## net.wake ### Description Wakes up the background worker. ### Method POST ### Endpoint net.wake ### Parameters #### Function Parameters - **worker_id** (integer) - Optional - The ID of the worker to wake. If not specified, all workers are woken. ### Request Example ```sql SELECT net.wake(); ``` ### Response #### Success Response (200) - **status** (text) - The status of the operation. #### Response Example ```json { "status": "OK" } ``` ``` -------------------------------- ### Set pg_net.database_name in postgresql.conf Source: https://github.com/supabase/pg_net/blob/master/README.md Configure the database where pg_net is applied by setting pg_net.database_name. Replace with the actual database name. ```sql pg_net.database_name = ''; ``` -------------------------------- ### net.http_get function definition Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Defines the net.http_get function that enqueues an asynchronous HTTP GET request. It URL-encodes the provided params, inserts a row into net.http_request_queue, wakes the worker, and returns the request_id. The function signature includes defaults for params, headers, and timeout_milliseconds. ```sql create or replace function net.http_get( -- url for the request url text, -- key/value pairs to be url encoded and appended to the `url` params jsonb default '{}'::jsonb, -- key/values to be included in request headers headers jsonb default '{}'::jsonb, -- the maximum number of milliseconds the request may take before being cancelled timeout_milliseconds int default 5000 ) -- request_id reference returns bigint language plpgsql as $$ declare request_id bigint; params_array text[]; begin select coalesce(array_agg(net._urlencode_string(key) || '=' || net._urlencode_string(value)), '{}') into params_array from jsonb_each_text(params); -- Add to the request queue insert into net.http_request_queue(method, url, headers, timeout_milliseconds) values ( 'GET', net._encode_url_with_params_array(url, params_array), headers, timeout_milliseconds ) returning id into request_id; perform net.wake(); return request_id; end $$; ``` -------------------------------- ### Change pg_net settings with ALTER SYSTEM Source: https://github.com/supabase/pg_net/blob/master/README.md Use ALTER SYSTEM to change pg_net settings. Note that ALTER SYSTEM requires SUPERUSER privileges. ```sql alter system set pg_net.ttl to '1 hour' alter system set pg_net.batch_size to 500; ``` -------------------------------- ### net.wake Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md Wakes the background worker so it processes the queue. The wake fires at commit time, so a transaction calling `net.wake()` (or the request functions, which call it internally) needs to be committed before the worker starts processing. Multiple concurrent `net.wake()` calls coalesce into one latch per transaction. ```APIDOC ## net.wake ### Description Wakes the background worker so it processes the queue. The wake fires at commit time, so a transaction calling `net.wake()` (or the request functions, which call it internally) needs to be committed before the worker starts processing. Multiple concurrent `net.wake()` calls coalesce into one latch per transaction. ### Method FUNCTION ### Endpoint net.wake() ### Parameters None. ### Return Type `void` ### Behavioral Notes - The wake fires **at commit time**, so a transaction calling `net.wake()` (or the request functions, which call it internally) needs to be committed before the worker starts processing. - Multiple concurrent `net.wake()` calls coalesce into one latch per transaction. - `PREPARE TRANSACTION` / `COMMIT PREPARED` do **not** wake the worker automatically; a manual `net.wake()` is required in that case. - Rows inserted directly into `net.http_request_queue` do not wake the worker; they are only picked up the next time the worker runs (e.g. after another request or `net.wake()`). ### Example ```sql -- Direct queue insert, then manual wake (the insert itself never wakes the worker) INSERT INTO net.http_request_queue(method, url, timeout_milliseconds) VALUES ('GET', 'https://example.com', 5000); SELECT net.wake(); ``` ``` -------------------------------- ### Schedule serverless function call every minute with PG_CRON Source: https://github.com/supabase/pg_net/blob/master/README.md Uses the PG_CRON extension to schedule a cron job that calls net.http_get every minute to invoke a serverless function. The job sends a GET request to the specified Edge function URL with a JSONB header containing content type and authorization token. ```sql SELECT cron.schedule( 'cron-job-name', '* * * * *', -- Executes every minute (cron syntax) $$ -- SQL query SELECT net.http_get( -- URL of Edge function url:='https://.functions.supabase.co/example', headers:='{ "Content-Type": "application/json", "Authorization": "Bearer " }'::JSONB ) as request_id; $$ ); ``` -------------------------------- ### net.worker_restart Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md Documentation for the net.worker_restart function, which reloads configuration and restarts the background worker. ```APIDOC ## net.worker_restart ### Description Reloads configuration and asks the background worker to restart. Implementation is C (`PG_FUNCTION_INFO_V1(worker_restart)` in `src/worker.c`): it calls `pg_reload_conf()`, atomically sets the shared-memory `got_restart` flag, latches the worker, and returns the result of `pg_reload_conf`. ### Function Signature ```sql create or replace function net.worker_restart() returns bool language 'c' as 'MODULE_PATHNAME'; ``` ### Parameters None. ### Return Type `bool` — the result of `pg_reload_conf()` (true if a reload signal was sent). This keeps backward compatibility; see the `TODO` comment in `src/worker.c`. ### Effects - Reloads the config file (`SIGHUP` semantics) immediately. - Sets `got_restart` in shared memory and wakes the worker; the worker picks this up in `wait_while_processing_interrupts` and exits, whereupon the postmaster restarts it after 1 second (`bgw_restart_time = net_worker_restart_time_sec`, `src/worker.c`). - Restart is required for changes to `pg_net.database_name` and `pg_net.username` to take effect (`PGC_SU_BACKEND` GUCs are otherwise read once at worker start). - The worker signals completion by publishing `WS_EXITED`, after which the restarting worker publishes `WS_RUNNING`; `net.wait_until_running` blocks until then. ### Example ```sql -- Apply ttl/batch_size config changes and bounce the worker in one call ALTER SYSTEM SET pg_net.ttl TO '1 hour'; SELECT pg_reload_conf(); SELECT net.worker_restart(); SELECT net.wait_until_running(); ``` ``` -------------------------------- ### Show pg_net runtime GUC values Source: https://github.com/supabase/pg_net/blob/master/_autodocs/configuration.md Displays the current values of all five runtime GUCs for pg_net. ```sql SHOW pg_net.batch_size; SHOW pg_net.ttl; SHOW pg_net.database_name; SHOW pg_net.username; SHOW pg_net.max_timeout_ms; ``` -------------------------------- ### Async response collection with net._http_collect_response Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-response-collection.md Shows async usage: fire a request with net.http_get, then call net._http_collect_response with async := true to check immediately. If the request is still in flight, the function returns ('ERROR','request matching request_id not found',NULL). ```sql -- Async: fire the request, check later without blocking SELECT net.http_get('https://postman-echo.com/get') AS request_id \gset SELECT * FROM net._http_collect_response(1, async := true); -- -> ('ERROR','request matching request_id not found',NULL) if still in flight ``` -------------------------------- ### net.http_get / net.http_post / net.http_delete Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Documentation for the three public request functions in pg_net: net.http_get, net.http_post, and net.http_delete. Each function enqueues a request and returns a bigint request id immediately. ```APIDOC ## net.http_get ### Description Enqueues an HTTP GET request into `net.http_request_queue` and returns a `bigint` request id immediately. The request executes asynchronously in the background worker. ### Method GET ### Endpoint `net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds int)` ### Parameters - **url** (text) - Required - The URL to send the GET request to. Passing `NULL` raises a `NOT NULL` constraint violation on `net.http_request_queue.url`. - **params** (jsonb) - Optional - Query parameters to append to the URL. - **headers** (jsonb) - Optional - HTTP headers to include in the request. - **timeout_milliseconds** (int) - Optional - Timeout for the request in milliseconds. ### Returns - **bigint** - The request id assigned to the enqueued request. ### Notes - The function is `VOLATILE` and parallel-unsafe. - The function is not `STRICT`; `NULL` values for parameters are not rejected by the function itself. ## net.http_post ### Description Enqueues an HTTP POST request into `net.http_request_queue` and returns a `bigint` request id immediately. The request executes asynchronously in the background worker. ### Method POST ### Endpoint `net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds int)` ### Parameters - **url** (text) - Required - The URL to send the POST request to. Passing `NULL` raises a `NOT NULL` constraint violation on `net.http_request_queue.url`. - **body** (jsonb) - Optional - The request body to send. - **params** (jsonb) - Optional - Query parameters to append to the URL. - **headers** (jsonb) - Optional - HTTP headers to include in the request. - **timeout_milliseconds** (int) - Optional - Timeout for the request in milliseconds. ### Returns - **bigint** - The request id assigned to the enqueued request. ### Notes - The function is `VOLATILE` and parallel-unsafe. - The function is not `STRICT`; `NULL` values for parameters are not rejected by the function itself. ## net.http_delete ### Description Enqueues an HTTP DELETE request into `net.http_request_queue` and returns a `bigint` request id immediately. The request executes asynchronously in the background worker. ### Method DELETE ### Endpoint `net.http_delete(url text, params jsonb, headers jsonb, timeout_milliseconds int)` ### Parameters - **url** (text) - Required - The URL to send the DELETE request to. Passing `NULL` raises a `NOT NULL` constraint violation on `net.http_request_queue.url`. - **params** (jsonb) - Optional - Query parameters to append to the URL. - **headers** (jsonb) - Optional - HTTP headers to include in the request. - **timeout_milliseconds** (int) - Optional - Timeout for the request in milliseconds. ### Returns - **bigint** - The request id assigned to the enqueued request. ### Notes - The function is `VOLATILE` and parallel-unsafe. - The function is not `STRICT`; `NULL` values for parameters are not rejected by the function itself. ``` -------------------------------- ### Enable Nix flakes in nix.conf Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Add this line to /etc/nix/nix.conf to enable Nix flakes support. After editing, restart the Nix daemon (on macOS: sudo launchctl kickstart -k system/org.nixos.nix-daemon). ```nix.conf experimental-features = nix-command flakes ``` -------------------------------- ### Error handling with net.http_get Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-http-request-functions.md Demonstrates error handling in application code. It catches synchronous validation errors (e.g., a relative URL) and then shows that an out-of-bounds timeout is not thrown but results in an ERROR response row, which is collected via net._http_collect_response. ```sql -- Error handling in application code: catch synchronous validation errors, -- then poll the response async-style DO $$ DECLARE req_id bigint; res net.http_response_result; BEGIN BEGIN req_id := net.http_get('/relative-url-is-rejected'); EXCEPTION WHEN others THEN RAISE NOTICE 'request rejected synchronously: %', SQLERRM; END; -- Out-of-bounds timeouts are NOT thrown; they produce an ERROR response row req_id := net.http_get( 'https://example.com', timeout_milliseconds := 0 -- rejected by the worker, response.status = 'ERROR' ); res := net._http_collect_response(req_id, async := false); IF res.status = 'ERROR' THEN RAISE NOTICE 'request failed: %', res.message; END IF; END $$; ``` -------------------------------- ### net.wait_until_running function definition Source: https://github.com/supabase/pg_net/blob/master/_autodocs/api-reference/net-worker-management.md SQL definition for the net.wait_until_running function. It is a C-language function that returns void and has no parameters. The comment describes its purpose. ```sql create or replace function net.wait_until_running() returns void language 'c' as 'MODULE_PATHNAME'; comment on function net.wait_until_running() is 'waits until the worker is running'; ``` -------------------------------- ### Restart Nix daemon on macOS Source: https://github.com/supabase/pg_net/blob/master/CONTRIBUTING.md Run this command to restart the Nix daemon after enabling flakes. This is required for the configuration change to take effect. ```bash sudo launchctl kickstart -k system/org.nixos.nix-daemon ```