From d58313b7d3b84dc01e8056623e7b83bf6090f917 Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Sun, 22 Nov 2026 23:32:36 +0000 Subject: [PATCH] Keep each SQLPage function reference in its own Markdown page --- .../content/functions/basic_auth_password.md | 18 ++ .../content/functions/basic_auth_username.md | 18 ++ .../content/functions/client_ip.md | 39 +++ .../functions/configuration_directory.md | 33 ++ .../official-site/content/functions/cookie.md | 39 +++ .../functions/current_working_directory.md | 26 ++ .../content/functions/environment_variable.md | 21 ++ .../official-site/content/functions/exec.md | 42 +++ .../official-site/content/functions/fetch.md | 129 ++++++++ .../content/functions/fetch_with_meta.md | 84 +++++ .../content/functions/hash_password.md | 31 ++ .../official-site/content/functions/header.md | 24 ++ .../content/functions/headers.md | 35 +++ .../official-site/content/functions/hmac.md | 111 +++++++ .../official-site/content/functions/link.md | 51 +++ .../content/functions/oidc_logout_url.md | 100 ++++++ .../official-site/content/functions/path.md | 22 ++ .../functions/persist_uploaded_file.md | 54 ++++ .../functions/persist_uploaded_files.md | 66 ++++ .../content/functions/protocol.md | 26 ++ .../content/functions/random_string.md | 28 ++ .../functions/read_file_as_data_url.md | 49 +++ .../content/functions/read_file_as_text.md | 37 +++ .../content/functions/regex_match.md | 82 +++++ .../content/functions/request_body.md | 72 +++++ .../content/functions/request_body_base64.md | 52 ++++ .../content/functions/request_method.md | 27 ++ .../content/functions/run_sql.md | 81 +++++ .../content/functions/send_mail.md | 290 ++++++++++++++++++ .../content/functions/set_variable.md | 41 +++ .../functions/uploaded_file_mime_type.md | 41 +++ .../content/functions/uploaded_file_name.md | 54 ++++ .../content/functions/uploaded_file_path.md | 72 +++++ .../content/functions/url_encode.md | 24 ++ .../content/functions/user_info.md | 104 +++++++ .../content/functions/user_info_token.md | 39 +++ .../content/functions/variables.md | 101 ++++++ .../content/functions/version.md | 8 + .../content/functions/web_root.md | 30 ++ .../database/sqlpage_functions/functions.rs | 30 +- 40 files changed, 2214 insertions(+), 17 deletions(-) create mode 100644 examples/official-site/content/functions/basic_auth_password.md create mode 100644 examples/official-site/content/functions/basic_auth_username.md create mode 100644 examples/official-site/content/functions/client_ip.md create mode 100644 examples/official-site/content/functions/configuration_directory.md create mode 100644 examples/official-site/content/functions/cookie.md create mode 100644 examples/official-site/content/functions/current_working_directory.md create mode 100644 examples/official-site/content/functions/environment_variable.md create mode 100644 examples/official-site/content/functions/exec.md create mode 100644 examples/official-site/content/functions/fetch.md create mode 100644 examples/official-site/content/functions/fetch_with_meta.md create mode 100644 examples/official-site/content/functions/hash_password.md create mode 100644 examples/official-site/content/functions/header.md create mode 100644 examples/official-site/content/functions/headers.md create mode 100644 examples/official-site/content/functions/hmac.md create mode 100644 examples/official-site/content/functions/link.md create mode 100644 examples/official-site/content/functions/oidc_logout_url.md create mode 100644 examples/official-site/content/functions/path.md create mode 100644 examples/official-site/content/functions/persist_uploaded_file.md create mode 100644 examples/official-site/content/functions/persist_uploaded_files.md create mode 100644 examples/official-site/content/functions/protocol.md create mode 100644 examples/official-site/content/functions/random_string.md create mode 100644 examples/official-site/content/functions/read_file_as_data_url.md create mode 100644 examples/official-site/content/functions/read_file_as_text.md create mode 100644 examples/official-site/content/functions/regex_match.md create mode 100644 examples/official-site/content/functions/request_body.md create mode 100644 examples/official-site/content/functions/request_body_base64.md create mode 100644 examples/official-site/content/functions/request_method.md create mode 100644 examples/official-site/content/functions/run_sql.md create mode 100644 examples/official-site/content/functions/send_mail.md create mode 100644 examples/official-site/content/functions/set_variable.md create mode 100644 examples/official-site/content/functions/uploaded_file_mime_type.md create mode 100644 examples/official-site/content/functions/uploaded_file_name.md create mode 100644 examples/official-site/content/functions/uploaded_file_path.md create mode 100644 examples/official-site/content/functions/url_encode.md create mode 100644 examples/official-site/content/functions/user_info.md create mode 100644 examples/official-site/content/functions/user_info_token.md create mode 100644 examples/official-site/content/functions/variables.md create mode 100644 examples/official-site/content/functions/version.md create mode 100644 examples/official-site/content/functions/web_root.md diff --git a/examples/official-site/content/functions/basic_auth_password.md b/examples/official-site/content/functions/basic_auth_password.md new file mode 100644 index 000000000..67162811a --- /dev/null +++ b/examples/official-site/content/functions/basic_auth_password.md @@ -0,0 +1,18 @@ +--- +icon: key +since: 0.7.2 +category: identity-and-security +summary: Read the password sent with HTTP Basic authentication. +return_type: TEXT +--- + +Returns the password from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. + If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials. + +### Example + +```sql +SELECT 'authentication' AS component, + (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, + sqlpage.basic_auth_password() AS password; +``` diff --git a/examples/official-site/content/functions/basic_auth_username.md b/examples/official-site/content/functions/basic_auth_username.md new file mode 100644 index 000000000..d6252e841 --- /dev/null +++ b/examples/official-site/content/functions/basic_auth_username.md @@ -0,0 +1,18 @@ +--- +icon: user +since: 0.7.2 +category: identity-and-security +summary: Read the username sent with HTTP Basic authentication. +return_type: TEXT +--- + +Returns the username from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. + If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials. + +### Example + +```sql +SELECT 'authentication' AS component, + (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, + sqlpage.basic_auth_password() AS password; +``` diff --git a/examples/official-site/content/functions/client_ip.md b/examples/official-site/content/functions/client_ip.md new file mode 100644 index 000000000..ef5afe844 --- /dev/null +++ b/examples/official-site/content/functions/client_ip.md @@ -0,0 +1,39 @@ +--- +icon: network +since: 0.33.0 +category: request-data +summary: Get the IP address of the client making the request. +--- + +Returns the IP address of the client making the HTTP request. + +### Example + +```sql +insert into connection_log (client_ip) values (sqlpage.client_ip()); +``` + +### Details + +The function returns: +- The IP address of the client as a string +- `null` if the client IP cannot be determined (e.g., when serving through a Unix socket) + +### ⚠️ Important Notes for Production Use + +When [running behind a reverse proxy](/your-first-sql-website/nginx.sql) (e.g., Nginx, Apache, Cloudflare): +- This function will return the IP address of the reverse proxy, not the actual client +- To get the real client IP, use [`sqlpage.header`](?function=header): `sqlpage.header('x-forwarded-for')` or `sqlpage.header('x-real-ip')` + - The exact header name depends on your reverse proxy configuration + +Example with reverse proxy: +```sql +-- Choose the appropriate header based on your setup +select coalesce( + sqlpage.header('x-forwarded-for'), + sqlpage.header('x-real-ip'), + sqlpage.client_ip() +) as real_client_ip; +``` + +For security-critical applications, ensure your reverse proxy is properly configured to set and validate these headers. diff --git a/examples/official-site/content/functions/configuration_directory.md b/examples/official-site/content/functions/configuration_directory.md new file mode 100644 index 000000000..ee7c260e4 --- /dev/null +++ b/examples/official-site/content/functions/configuration_directory.md @@ -0,0 +1,33 @@ +--- +icon: folder-cog +since: 0.42.0 +category: server-and-runtime +summary: Locate the directory for SQLPage configuration and templates. +--- + +Returns the configuration directory where SQLPage looks for `sqlpage.json`, templates, and migrations. + +### Example + +```sql +SELECT 'text' AS component; +SELECT 'Configuration files are in ' AS contents; +SELECT sqlpage.configuration_directory() as contents, true as code; +``` + +#### Result + +Configuration files are in `/home/user/my_sqlpage_website/sqlpage` + +#### Notes + +The configuration directory is where SQLPage looks for: + - `sqlpage.json` (the configuration file) + - `templates/` (custom component templates) + - `migrations/` (database migration files) + +By default, it is `./sqlpage` relative to the current working directory, but it can be changed using: + - the `--config-dir` command line argument + - the `SQLPAGE_CONFIGURATION_DIRECTORY` or `CONFIGURATION_DIRECTORY` environment variable + +This function is useful when you need to reference configuration-related files in your SQL code. diff --git a/examples/official-site/content/functions/cookie.md b/examples/official-site/content/functions/cookie.md new file mode 100644 index 000000000..5f92673c1 --- /dev/null +++ b/examples/official-site/content/functions/cookie.md @@ -0,0 +1,39 @@ +--- +icon: cookie +since: 0.7.1 +category: request-data +summary: Read a named cookie from the incoming request. +return_type: TEXT +parameters: + - name: name + type: TEXT + required: true + description: The name of the cookie to read. +--- + +Reads a [cookie](https://en.wikipedia.org/wiki/HTTP_cookie) with the given name from the request. +Returns the value of the cookie as text, or NULL if the cookie is not present. + +Cookies can be set using the [cookie component](documentation.sql?component=cookie#component). + +### Example + +#### Set a cookie + +Set a cookie called `username` to greet the user by name every time they visit the page: + +```sql +select 'cookie' as component, 'username' as name, :username as value; + +SELECT 'form' as component; +SELECT 'username' as name, 'text' as type; +``` + +#### Read a cookie + +Read a cookie called `username` and greet the user by name: + +```sql +SELECT 'text' as component, + 'Hello, ' || sqlpage.cookie('username') || '!' as contents; +``` diff --git a/examples/official-site/content/functions/current_working_directory.md b/examples/official-site/content/functions/current_working_directory.md new file mode 100644 index 000000000..729bab4f1 --- /dev/null +++ b/examples/official-site/content/functions/current_working_directory.md @@ -0,0 +1,26 @@ +--- +icon: folder-question +since: 0.11.0 +category: server-and-runtime +summary: Get the working directory of the SQLPage server process. +--- + +Returns the [current working directory](https://en.wikipedia.org/wiki/Working_directory) of the SQLPage server process. + +### Example + +```sql +SELECT 'text' AS component; +SELECT 'Currently running from ' AS contents; +SELECT sqlpage.current_working_directory() as contents, true as code; +``` + +#### Result + +Currently running from `/home/user/my_sqlpage_website` + +#### Notes + +The current working directory is the directory from which the SQLPage server process was started. +By default, this is also the directory from which `.sql` files are loaded and served. +However, this can be changed by setting the `web_root` [configuration option](/configuration#web_root). diff --git a/examples/official-site/content/functions/environment_variable.md b/examples/official-site/content/functions/environment_variable.md new file mode 100644 index 000000000..b46b60549 --- /dev/null +++ b/examples/official-site/content/functions/environment_variable.md @@ -0,0 +1,21 @@ +--- +icon: variable +since: 0.11.0 +category: server-and-runtime +summary: Read a named environment variable from the server. +parameters: + - name: name + type: TEXT + required: true + description: The name of the environment variable to read. Must be a literal string. +--- + +Returns the value of the given [environment variable](https://en.wikipedia.org/wiki/Environment_variable). + +### Example + +```sql +SELECT 'text' AS component; +SELECT 'The value of the HOME environment variable is ' AS contents; +SELECT sqlpage.environment_variable('HOME') as contents, true as code; +``` diff --git a/examples/official-site/content/functions/exec.md b/examples/official-site/content/functions/exec.md new file mode 100644 index 000000000..97c847a20 --- /dev/null +++ b/examples/official-site/content/functions/exec.md @@ -0,0 +1,42 @@ +--- +icon: terminal-2 +since: 0.12.0 +category: server-and-runtime +summary: Run a program on the server and capture its output. +parameters: + - name: program + type: TEXT + required: true + description: The name of the program to execute. Must be a literal string. + - name: arguments... + type: TEXT + description: The arguments to pass to the program. +--- + +Executes a shell command and returns its output as text. + +### Example + +#### Fetch data from a remote API using curl + +```sql +select 'card' as component; +select value->>'name' as title, value->>'email' as description +from json_each(sqlpage.exec('curl', 'https://jsonplaceholder.typicode.com/users')); +``` + +#### Notes + + - This function is disabled by default for security reasons. You can enable it by setting `"allow_exec" : true` in `sqlpage/sqlpage.json`. Enable it only if you trust all the users that can access your SQLPage server files (both locally and on the database). + - Be careful when using this function, as it can be used to execute arbitrary shell commands on your server. Do not use it with untrusted input. + - The command is executed in the current working directory of the SQLPage server process. + - The command is executed with the same user as the SQLPage server process. + - The environment variables of the SQLPage server process are passed to the command, including potentially sensitive variables such as `DATABASE_URL`. + - The command is executed asynchronously, but the SQLPage server has to wait for it to finish before sending the result to the client. + This means that the SQLPage server will not be blocked while the command is running, it will be able to serve other requests, but it will not be able to serve the current request until the command has finished. + You should generally avoid long running commands. + - If the program name is NULL, the result will be NULL. + - If any argument is NULL, it will be passed to the command as an empty string. + - If the command exits with a non-zero exit code, the function will raise an error. + - Arbitrary SQL operations are not allowed as sqlpage function arguments. Use `SET` to assign the result of a SQL query to a variable, and then use that variable as an argument to `sqlpage.exec`. + - When `sqlpage.exec(...)` is a standalone selected column, the command runs once per returned row. Use `SET command_result = sqlpage.exec(...)` first if the command should run only once for the page. diff --git a/examples/official-site/content/functions/fetch.md b/examples/official-site/content/functions/fetch.md new file mode 100644 index 000000000..972b3a434 --- /dev/null +++ b/examples/official-site/content/functions/fetch.md @@ -0,0 +1,129 @@ +--- +icon: transfer-vertical +since: 0.20.3 +category: external-services +summary: Send an HTTP request and read the response body. +parameters: + - name: url + type: TEXT + required: true + description: Either a string containing an URL to request, or a json object in the standard format of the + request interface of the web fetch API. +--- + +Sends an HTTP request and returns the results as a string. + +## HTTP request examples + +### Simple GET query + +In this example, we use an API call to find the latitude and longitude of a place +the user searched for, and we display it on a map. + +We use the simplest form of the fetch function, that takes the URL to fetch as a string. + + +```sql +set url = 'https://nominatim.openstreetmap.org/search?format=json&q=' || sqlpage.url_encode($user_search) +set api_results = sqlpage.fetch($url); + +select 'map' as component; +select $user_search as title, + CAST($api_results->>0->>'lat' AS FLOAT) as latitude, + CAST($api_results->>0->>'lon' AS FLOAT) as longitude; +``` + +### POST query with a body + +In this example, we use the complex form of the function to make an +authenticated POST request, with custom request headers and a custom request body. + +We use SQLite's json functions to build the request body. +See [the list of SQL databases and their JSON functions](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) for +more information on how to build JSON objects in your database. + +```sql +set request = json_object( + 'method', 'POST', + 'url', 'https://postman-echo.com/post', + 'headers', json_object( + 'Content-Type', 'application/json', + 'Authorization', 'Bearer ' || sqlpage.environment_variable('MY_API_TOKEN') + ), + 'body', json_object( + 'Hello', 'world' + ) +); +set api_results = sqlpage.fetch($request); + +select 'code' as component; +select + 'API call results' as title, + 'json' as language, + $api_results as contents; +``` + + +### Authenticated request using Basic Auth + +Here's how to make a request to an API that requires [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication): + +```sql +set request = json_object( + 'url', 'https://api.example.com/data', + 'username', 'my_username', + 'password', 'my_password' +); +set api_results = sqlpage.fetch($request); +``` + +> This will add the `Authorization: Basic bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQK` header to the request, +> where `bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQK` is the base64 encoding of the string `my_username:my_password`. + +## JSON parameter format + +The fetch function accepts either a URL string, or a JSON object with the following parameters: + - `url`: The URL to fetch. Required. + - `method`: The HTTP method to use. Defaults to `GET`. + - `headers`: A JSON object with the headers to send. Defaults to sending a User-Agent header containing the SQLPage version. + - `body`: The body of the request. If it is a JSON object, it will be sent as JSON. If it is a string, it will be sent as is. When omitted, no request body is sent. + - `timeout_ms`: The maximum time to wait for the request, in milliseconds. Defaults to 5000. + - `username`: Optional username for HTTP Basic Authentication. Introduced in version 0.33.0. + - `password`: Optional password for HTTP Basic Authentication. Only used if username is provided. Introduced in version 0.33.0. + - `response_encoding`: Optional charset to use for decoding the response body. Defaults to `utf8`, or `base64` if the response contains binary data. All [standard web encodings](https://encoding.spec.whatwg.org/#concept-encoding-get) are supported, plus `hex`, `base64`, and `base64url`. Introduced in version 0.37.0. + +## Error handling and reading response headers + +If the request fails, this function throws an error, that will be displayed to the user. +The response headers are not available for inspection. + +## Conditional data fetching + +Since v0.40, `sqlpage.fetch(null)` returns null instead of throwing an error. +This makes it easier to conditionnally query an API: + +```sql +set current_field_value = (select field from my_table where id = 1); +set target_url = nullif('http://example.com/api/field/1', null); -- null if the field is currently null in the db +set api_value = sqlpage.fetch($target_url); -- no http request made if the field is not null in the db +update my_table set field = $api_value where id = 1 and $api_value is not null; -- update the field only if it was not present before +``` + +You can also make the HTTP request depend on whether a database query returns a row. +When `fetch` is a standalone selected column, SQLPage runs it only for rows returned by the database: + +```sql +set api_value = ( + select sqlpage.fetch(url) + from cache_misses + where key = $key +); +``` + +If `cache_misses` has no matching row, no HTTP request is made and `$api_value` is set to `NULL`. +If the query returns more than one row or more than one column, SQLPage returns a clear scalar `SET` error. + +## Advanced usage + +If you need to handle errors or inspect the response headers or the status code, +use [`sqlpage.fetch_with_meta`](?function=fetch_with_meta). diff --git a/examples/official-site/content/functions/fetch_with_meta.md b/examples/official-site/content/functions/fetch_with_meta.md new file mode 100644 index 000000000..c266356f0 --- /dev/null +++ b/examples/official-site/content/functions/fetch_with_meta.md @@ -0,0 +1,84 @@ +--- +icon: transfer-vertical +since: 0.34.0 +category: external-services +summary: Send an HTTP request and read its status, headers, and body. +parameters: + - name: url + type: TEXT + required: true + description: Either a string containing an URL to request, or a json object in the standard format of the + request interface of the web fetch API. +--- + +Sends an HTTP request and returns detailed metadata about the response, including status code, headers, and body. + +This function is similar to [`fetch`](?function=fetch), but returns a JSON object containing detailed information about the response. +When the response declares a `content-type` of `application/json`, the parsed body is returned under `json_body`: +```json +{ + "status": 200, + "headers": { + "content-type": "application/json", + "content-length": "1234" + }, + "json_body": { "name": "ditto" } +} +``` + +For every other content type, the body is returned as a string under `body`: +```json +{ + "status": 200, + "headers": { + "content-type": "text/html", + "content-length": "1234" + }, + "body": "..." +} +``` + +If the request fails or encounters an error (e.g., network issues, invalid UTF-8 response), instead of throwing an error, +the function returns a JSON object with an "error" field containing the error message. + +### Example: Basic Usage + +```sql +-- Make a request and get detailed response information +set response = sqlpage.fetch_with_meta('https://pokeapi.co/api/v2/pokemon/ditto'); + +-- redirect the user to an error page if the request failed +select 'redirect' as component, 'error.sql' as url +where + json_extract($response, '$.error') is not null + or json_extract($response, '$.status') != 200; + +-- Extract data from the response json body +select 'card' as component; +select + json_extract($response, '$.json_body.name') as title, + json_extract($response, '$.json_body.abilities[0].ability.name') as description +from $response; +``` + +### Example: Advanced Request with Authentication + +```sql +set request = json_object( + 'method', 'POST', + 'url', 'https://sqlpage.free.beeceptor.com', + 'headers', json_object( + 'Content-Type', 'application/json', + 'Authorization', 'Bearer ' || sqlpage.environment_variable('API_TOKEN') + ), + 'body', json_object( + 'key', 'value' + ) +); +set response = sqlpage.fetch_with_meta($request); + +-- Check response content type +select 'debug' as component, $response as response; +``` + +The function accepts the same parameters as the [`fetch` function](?function=fetch). diff --git a/examples/official-site/content/functions/hash_password.md b/examples/official-site/content/functions/hash_password.md new file mode 100644 index 000000000..b81c05c91 --- /dev/null +++ b/examples/official-site/content/functions/hash_password.md @@ -0,0 +1,31 @@ +--- +icon: spy +since: 0.7.2 +category: identity-and-security +summary: Hash a password with Argon2id for storage. +parameters: + - name: password + type: TEXT + required: true + description: The password to hash. +--- + +Hashes a password with the Argon2id variant and outputs it in the [PHC string format](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md), ready to store in your users table. + +Every call generates a brand new cryptographic salt so that two people choosing the same password still end up with different hashes, which defeats rainbow-table attacks and lets you safely reveal only the hash. + +Use this function only when creating or resetting a password (for example while inserting a brand new user): it writes the stored value. Later, at login time, the [authentication component](documentation.sql?component=authentication#component) reads the stored hash, hashes the visitor's password with the embedded salt and parameters, and grants access only if they match. + +### Example + +```sql +SELECT 'form' AS component; +SELECT 'username' AS name; +SELECT 'password' AS name, 'password' AS type; + +INSERT INTO users (name, password_hash) VALUES (:username, sqlpage.hash_password(:password)); +``` + +### Try online + +You can try the password hashing function [on this page](/examples/hash_password.sql). diff --git a/examples/official-site/content/functions/header.md b/examples/official-site/content/functions/header.md new file mode 100644 index 000000000..e31561b06 --- /dev/null +++ b/examples/official-site/content/functions/header.md @@ -0,0 +1,24 @@ +--- +icon: heading +since: 0.7.2 +category: request-data +summary: Read the value of one HTTP request header. +parameters: + - name: name + type: TEXT + required: true + description: The name of the HTTP header to read. +--- + +Reads a [header](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) with the given name from the request. + Returns the value of the header as text, or NULL if the header is not present. + +### Example + +Log the [`User-Agent`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) of the browser making the request in the database: + +```sql +INSERT INTO user_agent_log (user_agent) VALUES (sqlpage.header('user-agent')); +``` + +If you need access to all headers at once, use [`sqlpage.headers()`](?function=headers) instead. diff --git a/examples/official-site/content/functions/headers.md b/examples/official-site/content/functions/headers.md new file mode 100644 index 000000000..dc75859b4 --- /dev/null +++ b/examples/official-site/content/functions/headers.md @@ -0,0 +1,35 @@ +--- +icon: circle-dotted-letter-h +since: 0.33.0 +category: request-data +summary: Read all HTTP request headers as a JSON object. +--- + +Returns all HTTP request headers as a JSON object. + +### Example + +The following displays all HTTP request headers in a list, +using SQLite's `json_each()` function. + +```sql +select 'list' as component; + +select key as title, value as description +from json_each(sqlpage.headers()); -- json_each() is SQLite only +``` + +If not on SQLite, use your [database's JSON function](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). + +### Details + +The function returns a JSON object where: +- Keys are lowercase header names +- Values are the corresponding header values +- If no headers are present, returns an empty JSON object `{}` + +This is useful when you need to: +- Debug HTTP requests +- Access multiple headers at once + +If you only need access to a single known header, use [`sqlpage.header(name)`](?function=header) instead. diff --git a/examples/official-site/content/functions/hmac.md b/examples/official-site/content/functions/hmac.md new file mode 100644 index 000000000..08514b6ed --- /dev/null +++ b/examples/official-site/content/functions/hmac.md @@ -0,0 +1,111 @@ +--- +icon: shield-lock +since: 0.38.0 +category: identity-and-security +summary: Sign data with a shared secret using HMAC. +parameters: + - name: data + type: TEXT + required: true + description: The input data to compute the HMAC for. Can be any text string. Cannot be NULL. + - name: key + type: TEXT + required: true + description: The secret key used to compute the HMAC. Should be kept confidential. Cannot be NULL. + - name: algorithm + type: TEXT + description: 'The hash algorithm and output format. Optional, defaults to `sha256` (hex output). Supported + values: `sha256`, `sha256-base64`, `sha512`, `sha512-base64`. Defaults to `sha256`.' +--- + +Creates a unique "signature" for some data using a secret key. +This signature proves that the data hasn't been tampered with and comes from someone who knows the secret. + +## HMAC use cases + +[**HMAC**](https://en.wikipedia.org/wiki/HMAC) (Hash-based Message Authentication Code) is commonly used to: + - **Verify webhooks**: Use HMAC to ensure only a given external service can call a given endpoint in your application. +The service signs their request with a secret key, and you verify the signature before processing the data they sent you. +Used for instance by [Stripe](https://docs.stripe.com/webhooks?verify=verify-manually), and [Shopify](https://shopify.dev/docs/apps/build/webhooks/subscribe/https#step-2-validate-the-origin-of-your-webhook-to-ensure-its-coming-from-shopify). + - **Secure API requests**: Prove that an API request comes from an authorized source + - **Generate secure tokens**: Create temporary access codes for downloads or password resets + - **Protect data**: Ensure data hasn't been modified during transmission + +## Signing data + +The `sqlpage.hmac` function takes three inputs: +1. **Your data** - The text you want to sign (like a message or request body) +2. **Your secret key** - A password only you know (keep this safe!) +3. **Algorithm** (optional) - The hash algorithm and output format: + - `sha256` (default) - SHA-256 with hexadecimal output + - `sha256-base64` - SHA-256 with base64 output + - `sha512` - SHA-512 with hexadecimal output + - `sha512-base64` - SHA-512 with base64 output + +It returns a signature string. If someone changes even one letter in your data, the signature will be completely different. + +### Example: Verify a Webhooks signature + +When Shopify sends you a webhook (like when someone places an order), it includes a signature. Here's how to verify it's really from Shopify. +This supposes you store the secret key in an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) named `WEBHOOK_SECRET`. + +```sql +SET body = sqlpage.request_body(); +SET secret = sqlpage.environment_variable('WEBHOOK_SECRET'); +SET expected_signature = sqlpage.hmac($body, $secret, 'sha256'); +SET actual_signature = sqlpage.header('X-Webhook-Signature'); + +-- redirect to an error page and stop execution if the signature does not match +SELECT + 'redirect' as component, + '/error.sql?err=bad_webhook_signature' as link +WHERE $actual_signature != $expected_signature OR $actual_signature IS NULL; + +-- If we reach here, the signature is valid - process the order +INSERT INTO orders (order_data) VALUES ($body); + +SELECT 'json' as component, 'jsonlines' as type; +SELECT 'success' as status; +``` + +### Example: Time-limited links + +You can create links that will be valid only for a limited time by including a signature in them. +Let's say we have a `download.sql` page we want to link to, +but we don't want it to be accessible to anyone who can find the link. +Sign `file_id|expires_at` with a secret. Accept only if not expired and the signature matches. + +#### Generate a signed link + +```sql +SET expires_at = datetime('now', '+1 hour'); +SET token = sqlpage.hmac( + $file_id || '|' || $expires_at, + sqlpage.environment_variable('DOWNLOAD_SECRET'), + 'sha256' +); +SELECT '/download.sql?file_id=' || $file_id || '&expires_at=' || $expires_at || '&token=' || $token AS link; +``` + +#### Verify the signed link + +```sql +SET expected = sqlpage.hmac( + $file_id || '|' || $expires_at, + sqlpage.environment_variable('DOWNLOAD_SECRET'), + 'sha256' +); +SELECT 'redirect' AS component, '/error.sql?err=expired' AS link +WHERE $expected != $token OR $token IS NULL OR $expires_at < datetime('now'); + +-- serve the file +``` + +### Important Security Notes + + - **Keep your secret key safe**: If your secret leaks, anyone can forge signatures and access protected pages + - **The signature is case-sensitive**: Even a single wrong letter means the signature won't match + - **NULL handling**: Always use `IS DISTINCT FROM`, not `=` to check for hmac matches. + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) != $signature` will not redirect if `$signature` is NULL (the signature is absent). + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) IS DISTINCT FROM $signature` checks for both NULL and non-NULL values (but is not available in all SQL dialects). + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) != $signature OR $signature IS NULL` is the most portable solution. diff --git a/examples/official-site/content/functions/link.md b/examples/official-site/content/functions/link.md new file mode 100644 index 000000000..3c9bdbe89 --- /dev/null +++ b/examples/official-site/content/functions/link.md @@ -0,0 +1,51 @@ +--- +icon: link +since: 0.25.0 +category: links-and-routing +summary: Build a page URL with optional query parameters and a fragment. +parameters: + - name: file + type: TEXT + required: true + description: The path of the SQLPage file to link to, relative to the current file. + - name: parameters + type: JSON + description: A JSON object with the parameters to pass to the linked file. + - name: fragment + type: TEXT + description: An optional fragment (hash) to append to the URL to link to a specific section of the target + page. +--- + +Returns the URL of a SQLPage file with the given parameters. + +### Example + +Let's say you have a database of products, and you want the main page (`index.sql`) to link to the page of each product (`product.sql`) with the product name as a parameter. + +In `index.sql`, you can use the `link` function to generate the URL of the product page for each product. + +```sql +select 'list' as component; +select + name as title, + sqlpage.link('product', json_object('product_name', name)) as link +from products; +``` + +In `product.sql`, you can then use `$product_name` to get the name of the product from the URL parameter: + +```sql +select 'hero' as component, $product_name as title, product_info as description +from products +where name = $product_name; +``` + +> You could also have manually constructed the URL with `CONCAT('product?product_name=', name)`, +> but using `sqlpage.link` is better because it ensures that the URL is properly encoded. +> `sqlpage.link` will work even if the product name contains special characters like `&`, while `CONCAT(...)` would break the URL. + +### Parameters + - `file` (TEXT): The name of the SQLPage file to link to. + - `parameters` (JSON): The parameters to pass to the linked file. + - `fragment` (TEXT): An optional fragment (hash) to append to the URL. This is useful for linking to a specific section of a page. For instance if `product.sql` contains `select 'text' as component, 'product_description' as id;`, you can link to the product description section with `sqlpage.link('product.sql', json_object('product_name', name), 'product_description')`. diff --git a/examples/official-site/content/functions/oidc_logout_url.md b/examples/official-site/content/functions/oidc_logout_url.md new file mode 100644 index 000000000..dcc8ae54e --- /dev/null +++ b/examples/official-site/content/functions/oidc_logout_url.md @@ -0,0 +1,100 @@ +--- +icon: logout +since: 0.41.0 +category: identity-and-security +summary: Build a sign-out URL for an OpenID Connect session. +parameters: + - name: redirect_uri + type: TEXT + description: The relative URL path where the user should be redirected after logout. Must start with `/`. + Defaults to `/` if not provided. +--- + +The `sqlpage.oidc_logout_url` function generates a secure logout URL for users authenticated via [OIDC Single Sign-On](/sso). + +When a user visits this URL, SQLPage will: +1. Remove the authentication cookie +2. Redirect the user to the OIDC provider's logout endpoint (if available) +3. Finally redirect back to the specified `redirect_uri` + +## Security Features + +This function provides protection against **Cross-Site Request Forgery (CSRF)** attacks: +- The generated URL contains a cryptographically signed token +- The token includes a timestamp and expires after 10 minutes +- The token is signed using your OIDC client secret +- Only relative URLs (starting with `/`) are allowed as redirect targets + +This means that malicious websites cannot trick your users into logging out by simply including an image or link to your logout URL. + +## Add a logout button + +```sql +select 'button' as component; +select + 'Logout' as title, + sqlpage.oidc_logout_url('/') as link, + 'logout' as icon, + 'red' as outline; +``` + +This creates a logout button that, when clicked: +1. Logs the user out of your SQLPage application +2. Logs the user out of the OIDC provider (if the provider supports [RP-Initiated Logout](https://openid.net/specs/openid-connect-rpinitiated-1_0.html)) +3. Redirects the user back to your homepage (`/`) + +## Examples + +### Logout Button in Navigation + +```sql +select 'shell' as component, + 'My App' as title, + json_array( + json_object( + 'title', 'Logout', + 'link', sqlpage.oidc_logout_url('/'), + 'icon', 'logout' + ) + ) as menu_item; +``` + +### Logout with Return to Current Page + +```sql +select 'button' as component; +select + 'Sign Out' as title, + sqlpage.oidc_logout_url(sqlpage.path()) as link; +``` + +### Conditional Logout Link + +```sql +select 'button' as component +where sqlpage.user_info('sub') is not null; +select + 'Logout ' || sqlpage.user_info('name') as title, + sqlpage.oidc_logout_url('/') as link +where sqlpage.user_info('sub') is not null; +``` + +## Requirements + +- OIDC must be [configured](/sso) in your `sqlpage.json` +- If OIDC is not configured, this function returns NULL +- The `redirect_uri` must be a relative path starting with `/` + +## Provider Support + +The logout behavior depends on your OIDC provider: + +| Provider | Full Logout Support | +|----------|-------------------| +| Keycloak | ✅ Yes | +| Auth0 | ✅ Yes | +| Google | ❌ No (local logout only) | +| Azure AD | ✅ Yes | +| Okta | ✅ Yes | + +When the provider doesn't support RP-Initiated Logout, SQLPage will still remove the local authentication cookie and redirect to your specified URI. diff --git a/examples/official-site/content/functions/path.md b/examples/official-site/content/functions/path.md new file mode 100644 index 000000000..2e3101e37 --- /dev/null +++ b/examples/official-site/content/functions/path.md @@ -0,0 +1,22 @@ +--- +icon: slashes +since: 0.15.0 +category: request-data +summary: Get the URL path of the current request. +--- + +Returns the request path of the current page. +This is useful to generate links to the current page, and when you have a proxy in front of your SQLPage server that rewrites the URL. + +### Example + +If we have a page in a file named `my page.sql` at the root of your SQLPage installation +then the following SQL query: + +```sql +select 'text' as component, sqlpage.path() as contents; +``` + +will return `/my%20page.sql`. + +> Note that the path is URL-encoded. diff --git a/examples/official-site/content/functions/persist_uploaded_file.md b/examples/official-site/content/functions/persist_uploaded_file.md new file mode 100644 index 000000000..c1060588d --- /dev/null +++ b/examples/official-site/content/functions/persist_uploaded_file.md @@ -0,0 +1,54 @@ +--- +icon: device-floppy +since: 0.20.1 +category: files-and-uploads +summary: Save an uploaded file and return its path. +parameters: + - name: file + type: TEXT + required: true + description: Name of the form field containing the uploaded file. The current page must be referenced in + the `action` property of a `form` component that contains a file input field. + - name: destination_folder + type: TEXT + description: |- + Optional. Path to the folder where the file will be saved, relative to the web root (the root folder of your website files). By default, the file will be saved in the `uploads` folder. + + **Security note**: this value must be a folder name you choose yourself in your SQL code (a trusted constant). Never build it from untrusted input such as a form field, a query parameter, a request header, or anything else the visitor controls. The folder is joined directly to the web root, so a value containing `..` or an absolute path would cause the uploaded file to be written *outside* the web root, anywhere the SQLPage process can write. Keeping `destination_folder` a fixed value chosen by the application author avoids this. + - name: allowed_extensions + type: TEXT + description: |- + Optional. Comma-separated list of allowed file extensions. By default: jpg,jpeg,png,gif,bmp,webp,pdf,txt,doc,docx,xls,xlsx,csv,mp3,mp4,wav,avi,mov. + Changing this may be dangerous ! If you add "sql", "svg" or "html" to the list, an attacker could execute arbitrary SQL queries on your database, or impersonate other users. + - name: mode + type: TEXT + description: |- + Optional. Unix permissions to set on the file, in octal notation. By default, the file will be saved with "600" (read/write for the owner only). + Octal notation works by using three digits from 0 to 7: the first for the owner, the second for the group, and the third for others. + For example, "644" means read/write for the owner, and read-only for others. + [Learn more about numeric notation for file-system permissions on Wikipedia](https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation). +--- + +Persists an uploaded file to the local filesystem, and returns its path. +If the file input field is empty, the function returns NULL. + +### Example + +#### User profile picture + +##### `upload_form.sql` + +```sql +select 'form' as component, 'persist_uploaded_file.sql' as action; +select 'file' as type, 'profile_picture' as name, 'Upload your profile picture' as label; +``` + +##### `persist_uploaded_file.sql` + +```sql +update user +set profile_picture = sqlpage.persist_uploaded_file('profile_picture', 'profile_pictures', 'jpg,jpeg,png,gif,webp') +where id = ( + select user_id from session where session_id = sqlpage.cookie('session_id') +); +``` diff --git a/examples/official-site/content/functions/persist_uploaded_files.md b/examples/official-site/content/functions/persist_uploaded_files.md new file mode 100644 index 000000000..34d6cca49 --- /dev/null +++ b/examples/official-site/content/functions/persist_uploaded_files.md @@ -0,0 +1,66 @@ +--- +icon: files +since: 0.49.0 +category: files-and-uploads +summary: Save multiple uploads from one field and return their file details. +parameters: + - name: files + type: TEXT + required: true + description: Name of the form field containing the uploaded files. A field named `photos[]` in the form + can be referenced as `photos`. + - name: destination_folder + type: TEXT + description: |- + Optional. Path to the folder where the files will be saved, relative to the web root. By default, the files will be saved in the `uploads` folder. + + **Security note**: this value must be a folder name you choose yourself in your SQL code (a trusted constant). Never build it from untrusted input: see [`persist_uploaded_file`](?function=persist_uploaded_file). + - name: allowed_extensions + type: TEXT + description: |- + Optional. Comma-separated list of allowed file extensions, checked for every file. By default: jpg,jpeg,png,gif,bmp,webp,pdf,txt,doc,docx,xls,xlsx,csv,mp3,mp4,wav,avi,mov. + Changing this may be dangerous ! If you add "sql", "svg" or "html" to the list, an attacker could execute arbitrary SQL queries on your database, or impersonate other users. + - name: mode + type: TEXT + description: Optional. Unix permissions to set on the files, in octal notation. By default, "600" (read/write + for the owner only). +--- + +Persists all the files uploaded in a single form field, and returns a JSON array with one object per file: + + - `path`: where the file was saved, relative to the web root (like the return value of [`persist_uploaded_file`](?function=persist_uploaded_file)), + - `name`: the original name of the file on the user's device, + - `mime_type`: the type of the file, as sent by the browser, + - `size`: the size of the file, in bytes. + +If no file was uploaded in the field, the function returns NULL. + +Use it with a file input that has the `multiple` attribute, so that users can select several files at once. +It works like [`persist_uploaded_file`](?function=persist_uploaded_file), +which only persists one file (the last one, when several were sent). + +If one of the files has an extension that is not allowed, or cannot be saved, the function fails and no file is persisted. + +### Example + +#### Photo gallery + +##### `upload_form.sql` + +```sql +select 'form' as component, 'save_photos.sql' as action; +select 'file' as type, 'photos[]' as name, 'Photos' as label, true as multiple, 'image/*' as accept; +``` + +##### `save_photos.sql` + +```sql +set files = sqlpage.persist_uploaded_files('photos', 'photos', 'jpg,jpeg,png,webp'); + +-- SQLite (PostgreSQL: json_array_elements($files::json), SQL Server: OPENJSON($files)) +insert into photo (local_path, name, mime_type, size) +select value ->> 'path', value ->> 'name', value ->> 'mime_type', value ->> 'size' +from json_each($files); + +select 'redirect' as component, 'gallery.sql' as link; +``` diff --git a/examples/official-site/content/functions/protocol.md b/examples/official-site/content/functions/protocol.md new file mode 100644 index 000000000..3578c54ff --- /dev/null +++ b/examples/official-site/content/functions/protocol.md @@ -0,0 +1,26 @@ +--- +icon: network +since: 0.17.1 +category: request-data +summary: Identify whether the request used HTTP or HTTPS. +--- + +Returns the protocol that was used to access the current page. + +This can be either `http` or `https`. + +This is useful to generate links to the current page. + +### Example + +```sql +select 'text' as component, + sqlpage.protocol() || '://' || sqlpage.header('host') || sqlpage.path() as contents; +``` + +will return `https://example.com/example.sql`. + +> Note that the path is URL-encoded. The protocol is resolved in this order: +> - `Forwarded` header +> - `X-Forwarded-Proto` header +> request target / URI diff --git a/examples/official-site/content/functions/random_string.md b/examples/official-site/content/functions/random_string.md new file mode 100644 index 000000000..c90b48688 --- /dev/null +++ b/examples/official-site/content/functions/random_string.md @@ -0,0 +1,28 @@ +--- +icon: arrows-shuffle +since: 0.7.2 +category: identity-and-security +summary: Generate a cryptographically secure random string. +parameters: + - name: length + type: INTEGER + required: true + description: The length of the string to generate. +--- + +Returns a cryptographically secure random string of the given length. + +When used as a standalone selected column in a query that returns several rows, `random_string` runs once per returned row. +Use `SET token = sqlpage.random_string(32)` first if you want one token reused later in the page. + +### Example + +Generate a random string of 32 characters and use it as a session ID stored in a cookie: + +```sql +INSERT INTO login_session (session_token, username) VALUES (sqlpage.random_string(32), :username) +RETURNING + 'cookie' AS component, + 'session_id' AS name, + session_token AS value; +``` diff --git a/examples/official-site/content/functions/read_file_as_data_url.md b/examples/official-site/content/functions/read_file_as_data_url.md new file mode 100644 index 000000000..304e8e9ed --- /dev/null +++ b/examples/official-site/content/functions/read_file_as_data_url.md @@ -0,0 +1,49 @@ +--- +icon: file-dollar +since: 0.17.0 +category: files-and-uploads +summary: Read a file as a data URL for embedding in a page. +parameters: + - name: name + type: TEXT + required: true + description: Path to the file to read. +--- + +Returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) +containing the contents of the given file. + +The file path is relative to the `web root` directory, which is the directory from which your website is served. +By default, this is the directory SQLPage is launched from, but you can change it +with the `web_root` [configuration option](/configuration#web_root). + +If the given argument is null, the function will return null. + +As with other functions, if an error occurs during execution +(because the file does not exist, for instance), +the function will display an error message and the +database query will not be executed. + +If you are using a `sqlpage_files` table to store files directly in the database (serverless mode), +the function will attempt to read the file from the database filesystem if it is not found on the local disk, +using the same logic as for serving files in response to HTTP requests. + +## MIME type + +Data URLs contain the [MIME type](https://en.wikipedia.org/wiki/Media_type) of the file they represent. +If the first argument to this function is the result of a call to the `sqlpage.uploaded_file_path` function, +the declared MIME type of the uploaded file transmitted by the browser will be used. + +Otherwise, the MIME type will be guessed from the file extension, without looking at the file contents. + + +## Example: inlining a picture + +```sql +select 'card' as component; +select 'Picture' as title, sqlpage.read_file_as_data_url('/path/to/picture.jpg') as top_image; +``` + +> **Note:** Data URLs are larger than the original file they represent, so they should only be used for small files +> (under a few hundred kilobytes). +> Otherwise, the page will take a long time to load. diff --git a/examples/official-site/content/functions/read_file_as_text.md b/examples/official-site/content/functions/read_file_as_text.md new file mode 100644 index 000000000..b7b78a2fc --- /dev/null +++ b/examples/official-site/content/functions/read_file_as_text.md @@ -0,0 +1,37 @@ +--- +icon: file-invoice +since: 0.17.0 +category: files-and-uploads +summary: Read the text of a UTF-8 file from the web root. +parameters: + - name: name + type: TEXT + required: true + description: Path to the file to read. +--- + +Returns a string containing the contents of the given file. + +The file must be a raw text file using UTF-8 encoding. + +The file path is relative to the `web root` directory, which is the directory from which your website is served +(not necessarily the directory SQLPage is launched from). + +If the given argument is null, the function will return null. + +As with other functions, if an error occurs during execution +(because the file does not exist, for instance), +the function will display an error message and the +database query will not be executed. + +If you are using a `sqlpage_files` table to store files directly in the database (serverless mode), +the function will attempt to read the file from the database filesystem if it is not found on the local disk, +using the same logic as for serving files in response to HTTP requests. + +## Example + +### Rendering a markdown file + +```sql +select 'text' as component, sqlpage.read_file_as_text('/path/to/file.md') as contents_md; +``` diff --git a/examples/official-site/content/functions/regex_match.md b/examples/official-site/content/functions/regex_match.md new file mode 100644 index 000000000..f8e9e6699 --- /dev/null +++ b/examples/official-site/content/functions/regex_match.md @@ -0,0 +1,82 @@ +--- +icon: regex +since: 0.43.0 +category: links-and-routing +summary: Match text against a regular expression and extract capture groups. +parameters: + - name: pattern + type: TEXT + required: true + description: The regular expression pattern to match against the input text. Named capture groups such + as `(?...)` are supported. + - name: text + type: TEXT + required: true + description: The text to match against the regular expression. Returns `NULL` when this argument is `NULL`. +--- + +Matches a text value against a regular expression and returns the capture groups as a JSON object. + +If the text matches the pattern, the result contains one entry for each capture group that matched: +- key `0` contains the full match +- named groups like `(?...)` use their name as the JSON key +- unnamed groups like `( ... )` use their numeric index as a string + +If the text does not match, this function returns `NULL`. + +### Example: custom routing from `404.sql` + +This function is especially useful in a custom [`404.sql` page](/your-first-sql-website/custom_urls.sql), +where you want to turn a dynamic URL into variables your SQL can use. + +For example, suppose you want `/categories/{category}/post/{id}` URLs such as `/categories/sql/post/42`, +but there is no physical `categories/sql/post/42.sql` file on disk. +You can put a `categories/404.sql` file in your project and extract the dynamic parts from the URL: + +#### `categories/404.sql` +```sql +set route = sqlpage.regex_match( + '/categories/(?\w+)/post/(?\d+)', + sqlpage.path() +); + +select 'redirect' as component, '/404' as link +where $route is null; + +select 'text' as component; +select + 'Category: ' || ($route->>'category') || ' | Post id: ' || ($route->>'id') as contents; +``` + +If the current path is `/categories/sql/post/42`, `sqlpage.regex_match()` returns: + +```json +{"0":"/categories/sql/post/42","category":"sql","id":"42"} +``` + +You can then use those extracted values to query your database: + +```sql +select title, body +from posts +where category = $route->>'category' + and id = cast($route->>'id' as integer); +``` + +### Details + +- Quick regex reminder: + - `\w+` matches one or more "word" characters + - `\d+` matches one or more digits + - `(?...)` creates a named capture group +- Some databases, such as MySQL and MariaDB, treat backslashes specially inside SQL strings. + In those databases, you may need to write `\\w` and `\\d`, or use portable character classes such as `[A-Za-z0-9_]` and `[0-9]` instead. +- In SQLite, PostgreSQL, and some other databases, you can read fields from the returned JSON with `->` and `->>` +- On databases that do not support that syntax, use their JSON extraction function instead, such as `json_extract($route, '$.category')` +- For the full regular expression syntax supported by SQLPage, see the Rust `regex` crate documentation: + [regex syntax reference](https://docs.rs/regex/latest/regex/#syntax) +- If the input text is `NULL`, the function returns `NULL` +- If an optional capture group does not match, that key is omitted from the JSON object +- If the regular expression is invalid, SQLPage returns an error + +The returned JSON can then be processed with your database's JSON functions. diff --git a/examples/official-site/content/functions/request_body.md b/examples/official-site/content/functions/request_body.md new file mode 100644 index 000000000..724a327c4 --- /dev/null +++ b/examples/official-site/content/functions/request_body.md @@ -0,0 +1,72 @@ +--- +icon: http-post +since: 0.33.0 +category: request-data +summary: Read the raw request body as text. +--- + +Returns the raw request body as a string. + +A client (like a web browser, mobile app, or another server) can send information to your server in the request body. +This function allows you to read that information in your SQL code, +in order to create or update a resource in your database for instance. + +The request body is commonly used when building **REST APIs** (machines-to-machines interfaces) +that receive data from the client. + +This is especially useful in: +- `POST` and `PUT` requests for creating or updating resources in your database +- Any API endpoint that needs to receive complex data + +### Example: Building a REST API + +Here's an example of building an API endpoint that receives a json object, +and inserts it into a database. + +#### `api/create_user.sql` +```sql +-- Get the raw JSON body +set user_data = sqlpage.request_body(); + +-- Insert the user into database +with parsed_data as ( + select + json_extract($user_data, '$.name') as name, + json_extract($user_data, '$.email') as email +) +insert into users (name, email) +select name, email from parsed_data; + +-- Return success response +select 'json' as component, + json_object( + 'status', 'success', + 'message', 'User created successfully' + ) as contents; +``` + +### Testing the API + +You can test this API using curl: +```bash +curl -X POST http://localhost:8080/api/create_user \ + -H "Content-Type: application/json" \ + -d '{"name": "John", "email": "john@example.com"}' +``` + +## Special cases + +### NULL + +This function returns NULL if: + - There is no request body + - The request content type is `application/x-www-form-urlencoded` or `multipart/form-data` + (in these cases, use [`sqlpage.variables('post')`](?function=variables) instead) + +### Binary data + +If the request body is not valid text encoded in UTF-8, +invalid characters are replaced with the Unicode replacement character `�` (U+FFFD). + +If you need to handle binary data, +use [`sqlpage.request_body_base64()`](?function=request_body_base64) instead. diff --git a/examples/official-site/content/functions/request_body_base64.md b/examples/official-site/content/functions/request_body_base64.md new file mode 100644 index 000000000..47cac0860 --- /dev/null +++ b/examples/official-site/content/functions/request_body_base64.md @@ -0,0 +1,52 @@ +--- +icon: photo-up +since: 0.33.0 +category: request-data +summary: Read a binary request body as a Base64 string. +--- + +Returns the raw request body encoded in base64. This is useful when receiving binary data or when you need to handle non-text content in your API endpoints. + +## Base64 encoding + +Base64 is a way to encode binary data (like images or files) into text that can be safely stored and transmitted. This function automatically converts the incoming request body into this format. + +## Receiving binary data in an API + +This example shows how to receive and process an image uploaded directly in the request body: + +```sql +-- Assuming this is api/upload_image.sql +-- Client would send a POST request with the raw image data + +-- Get the base64-encoded image data +set image_data = sqlpage.request_body_base64(); + +-- Store the image data in the database +insert into images (data, uploaded_at) +values ($image_data, current_timestamp); + +-- Return success response +select 'json' as component, + json_object( + 'status', 'success', + 'message', 'Image uploaded successfully' + ) as contents; +``` + +You can test this API using curl: +```bash +curl -X POST http://localhost:8080/api/upload_image.sql \ + -H "Content-Type: application/octet-stream" \ + --data-binary "@/path/to/image.jpg" +``` + +This is particularly useful when: +- Working with binary data (images, files, etc.) +- The request body contains non-UTF8 characters +- You need to pass the raw body to another system that expects base64 + +> Note: Like [`sqlpage.request_body()`](?function=request_body), this function returns NULL if: +> - There is no request body +> - The request content type is `application/x-www-form-urlencoded` or `multipart/form-data` +> (in these cases, use [`sqlpage.variables('post')`](?function=variables) instead) diff --git a/examples/official-site/content/functions/request_method.md b/examples/official-site/content/functions/request_method.md new file mode 100644 index 000000000..2c415d4bf --- /dev/null +++ b/examples/official-site/content/functions/request_method.md @@ -0,0 +1,27 @@ +--- +icon: http-get +since: 0.21.0 +category: request-data +summary: Get the HTTP method, such as GET or POST. +--- + +Returns the HTTP request method (GET, POST, etc.) used to access the page. + +## HTTP request methods + +HTTP request methods (also known as verbs) are used to indicate the desired action to be performed on the identified resource. The most common methods are: + - **GET**: retrieve information from the server. This is the default method used by browsers when you click on a link. + - **POST**: submit data to be processed by the server. This is the default method used by browsers when you submit a form. + - **PUT**: replace the current representation of the target resource with the request payload. Most commonly used in REST APIs. + - **DELETE**: remove the target resource. + - **PATCH**, **HEAD**, **OPTIONS**, **CONNECT**, **TRACE**: less common methods that are used in specific situations. + +## Require a PUT request + +```sql +select 'redirect' as component, + '/error?msg=expected+a+PUT+request' as link +where sqlpage.request_method() != 'PUT'; + +insert into my_table (column1, column2) values (:value1, :value2); +``` diff --git a/examples/official-site/content/functions/run_sql.md b/examples/official-site/content/functions/run_sql.md new file mode 100644 index 000000000..9a077cc29 --- /dev/null +++ b/examples/official-site/content/functions/run_sql.md @@ -0,0 +1,81 @@ +--- +icon: login +since: 0.20.0 +category: server-and-runtime +summary: Run another SQLPage file and return its rows as JSON. +parameters: + - name: file + type: TEXT + required: true + description: |- + Path to the SQL file to execute, can be absolute, or relative to the web root (the root folder of your website sql files). + In-database files, from the sqlpage_files(path, contents, last_modified) table are supported. + - name: parameters + type: JSON + description: Optional JSON object to pass as parameters to the included SQL file. The keys of the object + will be available as variables in the included file. By default, the included file will have access to + the same variables as the calling file. +--- + +Executes another SQL file and returns its result as a JSON array. + +### Example + +#### Include a common header in all your pages + +It is common to want to run the same SQL queries at the beginning of all your pages, +to check if an user is logged in, render a header, etc. +You can create a file called `common_header.sql`, +and use the [`dynamic`](documentation.sql?component=dynamic#component) component with the `run_sql` function +to include it in all your pages. + +```sql +select 'dynamic' as component, sqlpage.run_sql('common_header.sql') as properties; +``` + +#### Factorize logic between pages + +Reuse a sqlpage query in multiple pages without duplicating code by storing the results of `run_sql` to variables: + +##### `reusable.sql` + +```sql +select some_field from some_table; +``` + +##### `index.sql` + +```sql +-- save the value of some_field from the first result row of reusable.sql into $my_var +set my_var = sqlpage.run_sql('reusable.sql')->>0->>'some_field'; +``` + +See [json in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) +for help with manipulating the json array returned by `run_sql`. + +#### Notes + + - **recursion**: you can use `run_sql` to include a file that itself includes another file, and so on. However, be careful to avoid infinite loops. SQLPage will throw an error if the inclusion depth is superior to `max_recursion_depth` (10 by default). + - **security**: be careful when using `run_sql` to include files. + - Never use `run_sql` with a user-provided parameter. + - Never run a file uploaded by a user, or a file that is not under your control. + - Remember that users can also run the files you include with `sqlpage.run_sql(...)` directly just by loading the file in the browser. + - Make sure this does not allow users to bypass security measures you put in place such as [access control](/component.sql?component=authentication). + - If you need to include a file, but make it inaccessible to users, you can use hidden files and folders (starting with a `.`), or put files in the special `sqlpage/` folder that is not accessible to users. + - **variables**: the included file will have access to the same variables (URL parameters, POST variables, etc.) + as the calling file. + If the included file changes the value of a variable or creates a new variable, the change will not be visible in the calling file. + - **per-row execution**: when `sqlpage.run_sql(...)` is a standalone selected column in a query that returns several rows, the included file runs once per returned row. + Use `SET included = sqlpage.run_sql(...)` first if the included file should run only once for the page. + +### Parameters + +You can pass parameters to the included file, as if it had been with a URL parameter. +For instance, you can use: + +```sql +sqlpage.run_sql('included_file.sql', json_object('param1', 'value1', 'param2', 'value2')) +``` + +Which will make `$param1` and `$param2` available in the included file. +[More information about building JSON objects in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). diff --git a/examples/official-site/content/functions/send_mail.md b/examples/official-site/content/functions/send_mail.md new file mode 100644 index 000000000..b9a6ae456 --- /dev/null +++ b/examples/official-site/content/functions/send_mail.md @@ -0,0 +1,290 @@ +--- +icon: mail +since: 0.45.0 +category: external-services +summary: Send email with optional attachments through an SMTP server. +return_type: JSON +parameters: + - name: message + type: JSON + required: true + description: 'A JSON object containing the email to send. Required properties are `to` (an address or non-empty + address array), `subject`, and either `body` or `body_md`. Optional properties are `from` (required unless + `smtp_from` or `SMTP_FROM` is configured), `reply_to`, `cc` (an address or non-empty address array), + `body` (the plain-text body; required unless `body_md` is provided), `body_html` (an HTML alternative + body sent as `multipart/alternative` alongside `body`), `body_md` (a Markdown body rendered to HTML and + sent as `multipart/alternative` with the raw Markdown as the plain-text alternative; cannot be combined + with `body_html`), and `attachments` (an array of `{ "filename": "...", "data_url": "data:..." }` objects). + Invalid JSON and invalid or unknown properties return `{ "status": "error", "error_code": "...", "error": + "..." }`. SQL `NULL` returns SQL `NULL` without sending.' +--- + +Sends a plain-text email using the outgoing mail server configured in SQLPage. + +### Quick start + +You need an [SMTP server](https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol), which is the outgoing mail server provided by an email account or email delivery service. + +Add its connection details to `sqlpage/sqlpage.json`: + +```json +{ + "smtp_host": "smtp.example.com", + "smtp_username": "your-smtp-user", + "smtp_password": "your-smtp-password", + "smtp_from": "My application " +} +``` + +The default connection uses STARTTLS on port 587, which is the most common setup. Restart SQLPage after changing its configuration. + +**Important:** SQLPage can sign in with an SMTP username and password, but it does not support OAuth. If the provider instructions only offer OAuth or "Modern Auth", use a different SMTP relay. + +You can now send an email from any SQL file: + +```sql +set result = sqlpage.send_mail(json_object( + 'to', 'alice@example.com', + 'subject', 'Hello from SQLPage', + 'body', 'Your first email is working!' +)); +``` + +The sender comes from `smtp_from`. The result is a JSON object: + +```json +{"status":"accepted"} +``` + +If the message cannot be sent, the function returns the reason instead of stopping the request: + +```json +{"status":"error","error_code":"INVALID_EMAIL_TO","error":"'xxx' is not a valid to email address"} +``` + +For every non-`NULL` call, `status` is either `accepted` or `error`. Always check it before showing a success message or continuing work that depends on the email: + +```sql +select 'alert' as component, + case when json_extract($result, '$.status') = 'accepted' then 'success' else 'danger' end as color, + case when json_extract($result, '$.status') = 'accepted' then 'Email sent' else 'Email could not be sent' end as title, + json_extract($result, '$.error') as description; +``` + +### SMTP provider settings + +Search the help pages or administration panel of the service that sends email for you. Look for **SMTP**, **outgoing mail server**, **SMTP submission**, **SMTP relay**, or **send from an app or device**. + +Provider documentation may use different names for the same settings: + +| Provider documentation | SQLPage setting | +| --- | --- | +| SMTP server, outgoing server, relay, or smart host | `smtp_host` | +| Port | `smtp_port` | +| STARTTLS, SSL/TLS, or connection security | `smtp_tls_mode` | +| SMTP username | `smtp_username` | +| SMTP password, app password, token, or API key | `smtp_password` | +| Sender or From address | `smtp_from` | + +The SMTP password is often a separate app password, token, or SMTP credential rather than the password used to open webmail. Use exactly what the provider instructions specify. + +For an existing mailbox, these official guides explain the available options: + +- [Personal Google Account app passwords](https://support.google.com/accounts/answer/185833), for eligible accounts +- [Google Workspace: send email from a printer, scanner, or app](https://knowledge.workspace.google.com/admin/gmail/send-email-from-a-printer-scanner-or-app) +- [Microsoft 365: send email from a device or application](https://learn.microsoft.com/en-us/exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-microsoft-365-or-office-365) + +Personal Outlook.com SMTP requires OAuth and is therefore not currently compatible. Microsoft 365 administrators can use the relay options described in the linked organization guide. + +Dedicated email delivery services also provide SMTP settings. Here are examples in alphabetical order: + +- [Amazon SES SMTP credentials](https://docs.aws.amazon.com/ses/latest/dg/smtp-credentials.html) +- [Mailgun SMTP](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/send-smtp) +- [Postmark SMTP](https://postmarkapp.com/developer/user-guide/send-email-with-smtp) +- [Resend SMTP](https://resend.com/docs/send-with-smtp) +- [Twilio SendGrid SMTP](https://www.twilio.com/docs/sendgrid/for-developers/sending-email/integrating-with-the-smtp-api) + +These links are examples, not endorsements. SQLPage is not affiliated with any of these services. Compare their requirements, limits, and pricing for your own use case. + +For local development, [Mailpit](https://mailpit.axllent.org/) accepts messages and displays them in a browser without delivering them to real recipients. The [SQLPage email example](https://github.com/sqlpage/SQLPage/tree/main/examples/sending%20emails) includes a ready-to-run Mailpit setup. + +All SMTP options can also be set with uppercase environment variables such as `SMTP_HOST` and `SMTP_PASSWORD`. See the complete [SQLPage configuration reference](/configuration). Do not commit SMTP credentials to source control. + +### Message fields + +The function takes one JSON object. Every message requires `to`, `subject`, and message content. Message content can be supplied in one of these ways: + +- `body`: the plain-text email body. This is required unless `body_md` is provided. +- `body_html`: an optional HTML alternative to `body`. It can be combined with `body`, but not with `body_md`. +- `body_md`: a Markdown body rendered to HTML automatically. It can be used on its own or combined with `body`; when `body` is omitted, the raw Markdown is used as the plain-text alternative. It cannot be combined with `body_html`. + +The supported content combinations are: + +| Fields | Result | +| --- | --- | +| `body` | Plain-text email | +| `body`, `body_html` | Plain-text and HTML alternatives | +| `body_md` | Raw Markdown and rendered HTML alternatives | +| `body`, `body_md` | `body` as the plain-text alternative and rendered Markdown as HTML | + +At least one of `body` or `body_md` is required. `body_html` by itself is not enough because every HTML email must also have a plain-text alternative. + +It also accepts: + +- `from`: overrides `smtp_from` for this message; +- `reply_to`: the address that receives replies; +- `cc`: a recipient who receives a visible copy; +- `attachments`: files to include with the message. + +`to` and `cc` can each be either one address or an array of addresses. Addresses can include a display name, for example `"Jane Doe "`. + +Most SMTP servers only allow approved sender addresses. Prefer a fixed `smtp_from`. Override `from` only when the SMTP provider allows the address. + +### Multiple recipients and attachments + +Each attachment has a file name and a [data URL](https://developer.mozilla.org/en-US/docs/Web/URI/Schemes/data) containing its data. This example attaches a file from the SQLPage server: + +```sql +set result = sqlpage.send_mail(json_object( + 'to', json_array('alice@example.com', 'bob@example.com'), + 'cc', 'team@example.com', + 'subject', 'Monthly report', + 'body', 'The report is attached.', + 'attachments', json_array(json_object( + 'filename', 'report.pdf', + 'data_url', sqlpage.read_file_as_data_url('report.pdf') + )) +)); +``` + +[`sqlpage.read_file_as_data_url`](/functions.sql?function=read_file_as_data_url) is one way to create attachment data. Data URLs can also come from an uploaded file, a database value, an HTTP response, or SQL. + +The combined decoded size of all attachments is limited by `max_email_attachment_size`, which defaults to 10 MiB. This is separate from `max_uploaded_file_size` because attachments do not have to come from form uploads. + +### HTML email + +Set `body_html` to send an HTML version of the message alongside the plain-text `body`. The message is sent as a `multipart/alternative`: mail clients that prefer HTML show the HTML body, and clients that prefer text show the plain-text body. + +```sql +set result = sqlpage.send_mail(json_object( + 'to', 'alice@example.com', + 'subject', 'Welcome', + 'body', 'Welcome to our service.', + 'body_html', '

Welcome to our service.

' +)); +``` + +Include a meaningful plain-text alternative for deliverability and accessibility. SQLPage does not sanitize `body_html`: the SQL author is responsible for the HTML content. Email clients ignore scripts, and styles are often stripped or sandboxed. + +### Markdown email + +Set `body_md` to send a [Markdown](https://daringfireball.net/projects/markdown/) version of the body. SQLPage renders the Markdown to HTML and sends the message as a `multipart/alternative` with two parts: the raw Markdown as the plain-text body, and the rendered HTML as the HTML body. When `body_md` is provided, `body` becomes optional. + +```sql +set result = sqlpage.send_mail(json_object( + 'to', 'alice@example.com', + 'subject', 'Welcome', + 'body_md', '# Welcome\n\nWelcome to **our service**.' +)); +``` + +When both `body` and `body_md` are provided, `body` is used as the plain-text alternative and the rendered `body_md` is used as the HTML alternative. `body_md` cannot be combined with `body_html`; use one or the other. + +SQLPage renders Markdown using the same [GFM](https://github.github.com/gfm/) options as the `markdown` template helper, honoring the `markdown_allow_dangerous_html` and `markdown_allow_dangerous_protocol` configuration options. + +### Contact form + +```sql +select 'form' as component, 'post' as method; +select 'email' as name, 'email' as type, true as required; +select 'message' as name, 'textarea' as type, true as required; + +set mail = json_object( + 'to', 'admin@example.com', + 'reply_to', :email, + 'subject', 'Website contact form', + 'body', :message +); +set result = ( + select sqlpage.send_mail($mail) + where :message is not null +); + +select 'alert' as component, + case when json_extract($result, '$.status') = 'accepted' then 'success' else 'danger' end as color, + case when json_extract($result, '$.status') = 'accepted' then 'Message sent' else 'Message could not be sent' end as title, + json_extract($result, '$.error') as description +where :message is not null; +``` + +On the initial page load, `:message` is `NULL`, so the query returns no row and no email is sent. After submission, `:email` and `:message` contain the form fields. + +For a public form, keep `to` fixed in SQL so visitors cannot use your server to email arbitrary recipients. Validate inputs and add suitable rate limiting and anti-abuse controls. + +### Before using this in production + +- A `status` of `accepted` is not proof of delivery. A message can still bounce or be filtered later. Check the provider logs or delivery webhooks when delivery status matters. +- The provider may require sender or domain verification and DNS records such as SPF, DKIM, or DMARC. Configure these with the provider and DNS host. +- The function waits for the SMTP server during the web request. It opens a new connection for each call and does not retry automatically or save failed messages in a queue. +- SMTP commands use a fixed 60-second timeout. SQLPage does not currently provide a setting to change it. +- A selected call runs once for every row returned by its query. If the query returns no rows, it sends no email. Avoid using it over many rows; use a background queue or provider bulk API for bulk sending. + +### Connection options + +`smtp_host` must contain only a host name or IP address. Do not include `smtp://`, `https://`, a path, or a port. + +Choose `smtp_tls_mode` according to the provider instructions: + +- `starttls` (default) requires a STARTTLS upgrade before authentication or message submission. Its default port is 587. SQLPage fails rather than continuing without encryption when STARTTLS is unavailable. +- `tls` encrypts the connection from the beginning. Its default port is 465. Providers may call this implicit TLS, SSL/TLS, or SMTPS. +- `none` sends the message without encryption. Its default port is 25. It cannot be used with a username and password and is intended only for a trusted local server such as Mailpit. + +Set `smtp_port` when the provider specifies another port, such as 2525. `smtp_username` and `smtp_password` must either both be configured or both be omitted. + +SQLPage normally validates TLS certificates using public web PKI roots. Enable `system_root_ca_certificates`, or set `SSL_CERT_FILE` or `SSL_CERT_DIR`, to use roots installed by the system administrator, including private roots. + +### Supported and unsupported features + +SQLPage supports unauthenticated SMTP servers and username/password authentication using the SMTP `PLAIN` and `LOGIN` mechanisms. Credentials are allowed only over an encrypted connection. + +SQLPage does not currently support: + +- OAuth or XOAUTH2 authentication. If a provider only allows OAuth, it is not compatible with this function; +- CRAM-MD5, DIGEST-MD5, client-certificate authentication, or a per-server custom CA file; +- opportunistic STARTTLS, direct delivery to recipient mail servers, or receiving email; +- BCC, multiple reply-to addresses, or custom email headers; +- provider-specific headers for templates, tags, tracking, scheduling, idempotency, or metadata; +- DKIM signing inside SQLPage, S/MIME, or end-to-end encryption. The SMTP provider may add DKIM signatures; +- connection pooling, automatic retries, a persistent queue, scheduled sending, or a bulk-send API; +- a configurable SMTP command timeout or EHLO client identity; +- delivery receipts, bounce processing, suppression lists, open or click tracking, or webhooks. + +### `NULL`, empty values, and invalid input + +- SQL `NULL` is passed through: `sqlpage.send_mail(NULL)` returns SQL `NULL`, sends nothing, and does not log a warning. +- A JSON value other than an object and unknown or invalid message fields produce a JSON result with `status`, `error_code`, and `error` fields. +- `to` and `subject` are required and cannot be JSON `null`. At least one of `body` or `body_md` must be provided. +- `from`, `reply_to`, `cc`, `body`, `body_html`, and `body_md` treat JSON `null` like an omitted field. If `from` is omitted, `smtp_from` must be configured. If `body` and `body_md` are both omitted, the message is rejected for missing content. When `body_html` and `body_md` are both omitted, the message is plain text only. +- `body_md` cannot be combined with `body_html`. +- `attachments` can be omitted or an empty array. JSON `null` is not accepted for `attachments`. +- Empty recipient arrays, JSON `null` inside recipient arrays, invalid addresses, an empty attachment file name, invalid data URLs, and unknown attachment fields produce an error result with `status`, `error_code`, and `error`. +- Empty strings are allowed for `subject` and `body`, although an SMTP server may reject them. + +### Error codes + +`error_code` is a stable, machine-readable value. `error` is the corresponding human-readable detail. + +| `error_code` | Meaning | +| --- | --- | +| `INVALID_MESSAGE` | The argument is not a valid message object, a required field is missing, or the message cannot be constructed. | +| `SMTP_NOT_CONFIGURED` | `smtp_host` is not configured. | +| `MISSING_EMAIL_FROM` | Neither the message nor `smtp_from` provides a sender. | +| `INVALID_EMAIL_FROM` | `from` is not a valid email address. | +| `INVALID_EMAIL_TO` | `to` is empty or contains an invalid email address. | +| `INVALID_EMAIL_CC` | `cc` is empty or contains an invalid email address. | +| `INVALID_EMAIL_REPLY_TO` | `reply_to` is not a valid email address. | +| `INVALID_ATTACHMENT` | An attachment has an invalid name, data URL, media type, or exceeds the configured size limit. | +| `SMTP_TLS_FAILED` | TLS certificates could not be configured or the encrypted connection failed. | +| `SMTP_TIMEOUT` | The SMTP operation timed out. | +| `SMTP_REJECTED` | The SMTP server returned a temporary or permanent rejection, including authentication failures. | +| `SMTP_CONNECTION_FAILED` | SQLPage could not connect to or communicate with the SMTP server. | diff --git a/examples/official-site/content/functions/set_variable.md b/examples/official-site/content/functions/set_variable.md new file mode 100644 index 000000000..1b1692e49 --- /dev/null +++ b/examples/official-site/content/functions/set_variable.md @@ -0,0 +1,41 @@ +--- +icon: variable +since: 0.40.0 +category: links-and-routing +summary: Build a link to this page with a query parameter changed or removed. +parameters: + - name: name + type: TEXT + required: true + description: The name of the variable to set. + - name: value + type: TEXT + description: The value to set the variable to. +--- + +Returns a URL that is the same as the current page's URL, but with a variable set to a new value. + +This function is useful when you want to create a link that changes a parameter on the current page, while preserving other parameters. + +It is equivalent to `sqlpage.link(sqlpage.path(), json_patch(sqlpage.variables('get'), json_object(name, value)))`. + +### Example + +Let's say you have a list of products, and you want to filter them by category. You can use `sqlpage.set_variable` to create links that change the category filter, without losing other potential filters (like a search query or a sort order). + +```sql +select 'button' as component, 'sm' as size, 'center' as justify; +select + category as title, + sqlpage.set_variable('category', category) as link, + case when $category = category then 'primary' else 'secondary' end as color +from categories; +``` + +When `sqlpage.set_variable(...)` is used as a standalone selected column in a query that returns several rows, it runs once per returned row. +This is useful for generating one link per row, as in the example above. +If you need a single link reused later in the page, store it with `SET` first. + +### Parameters + - `name` (TEXT): The name of the variable to set. + - `value` (TEXT): The value to set the variable to. If `NULL` is passed, the variable is removed from the URL. diff --git a/examples/official-site/content/functions/uploaded_file_mime_type.md b/examples/official-site/content/functions/uploaded_file_mime_type.md new file mode 100644 index 000000000..7114f3a9a --- /dev/null +++ b/examples/official-site/content/functions/uploaded_file_mime_type.md @@ -0,0 +1,41 @@ +--- +icon: file-settings +since: 0.18.0 +category: files-and-uploads +summary: Read the media type supplied by the browser for an uploaded file. +parameters: + - name: name + type: TEXT + required: true + description: Name of the file input field in the form. +--- + +Returns the MIME type of an uploaded file. + +## Example: handling a picture upload + +When letting the user upload a picture, you may want to check that the uploaded file is indeed an image. + +```sql +select 'redirect' as component, + 'invalid_file.sql' as link +where sqlpage.uploaded_file_mime_type('myfile') not like 'image/%'; +``` + +In `invalid_file.sql`, you can display an error message to the user: + +```sql +select 'alert' as component, 'Error' as title, + 'Invalid file type' as description, + 'alert-circle' as icon, 'red' as color; +``` + +## Example: white-listing file types + +You could have a database table containing the allowed MIME types, and check that the uploaded file is of one of those types: + +```sql +select 'redirect' as component, + 'invalid_file.sql' as link +where sqlpage.uploaded_file_mime_type('myfile') not in (select mime_type from allowed_mime_types); +``` diff --git a/examples/official-site/content/functions/uploaded_file_name.md b/examples/official-site/content/functions/uploaded_file_name.md new file mode 100644 index 000000000..82f0fc169 --- /dev/null +++ b/examples/official-site/content/functions/uploaded_file_name.md @@ -0,0 +1,54 @@ +--- +icon: file-description +since: 0.23.0 +category: files-and-uploads +summary: Read the original filename supplied by the browser. +parameters: + - name: name + type: TEXT + required: true + description: Name of the file input field in the form. +--- + +Returns the `filename` value in the `content-disposition` header. + +## Example: saving uploaded file metadata for later download + +### Making a form + +```sql +select 'form' as component, 'handle_file_upload.sql' as action; +select 'myfile' as name, 'file' as type, 'File' as label; +``` + +### Handling the form response + +### Inserting an arbitrary file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database + +In `handle_file_upload.sql`, one can process the form results like this: + +```sql +insert into uploaded_files (fname, content, uploaded) values ( + sqlpage.uploaded_file_name('myfile'), + sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('myfile')), + CURRENT_TIMESTAMP +); +``` + +> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files. + +### Downloading the uploaded files + +The file can be downloaded by clicking a link like this: +```sql +select 'button' as component; +select name as title, content as link from uploaded_files where name = $file_name limit 1; +``` + +> *Note*: because the file is ecoded as a data uri, the file is transferred to the client whether or not the link is clicked + +### Large files + +See the [`sqlpage.uploaded_file_path`](?function=uploaded_file_path#function) function. + +See the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function. diff --git a/examples/official-site/content/functions/uploaded_file_path.md b/examples/official-site/content/functions/uploaded_file_path.md new file mode 100644 index 000000000..4f12188ce --- /dev/null +++ b/examples/official-site/content/functions/uploaded_file_path.md @@ -0,0 +1,72 @@ +--- +icon: upload +since: 0.17.0 +category: files-and-uploads +summary: Get the temporary path of an uploaded file. +parameters: + - name: name + type: TEXT + required: true + description: Name of the file input field in the form. +--- + +Returns the path to a temporary file containing the contents of an uploaded file. + +## Example: handling a picture upload + +### Making a form + +```sql +select 'form' as component, 'handle_picture_upload.sql' as action; +select 'myfile' as name, 'file' as type, 'Picture' as label; +select 'title' as name, 'text' as type, 'Title' as label; +``` + +### Handling the form response + +### Inserting an image file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database + +In `handle_picture_upload.sql`, one can process the form results like this: + +```sql +insert into pictures (title, path) values (:title, sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('myfile'))); +``` + +> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files. + +### Inserting file contents as text into the database + +When the uploaded file is a simple raw text file (e.g. a `.txt` file), +one can use the [`sqlpage.read_file_as_text`](?function=read_file_as_text#function) +function to insert the contents of the file into the database like this: + +```sql +insert into text_documents (title, path) values (:title, sqlpage.read_file_as_text(sqlpage.uploaded_file_path('my_text_file'))); +``` + +### Saving the uploaded file to a permanent location + +When the uploaded file is larger than a few megabytes, it is not recommended to store it in the database. +Instead, one can save the file to a permanent location on the server, and store the path to the file in the database. + +You can move the file to a permanent location using the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function. +### Advanced file handling + +For more advanced file handling, such as uploading files to a cloud storage service, +you can write a small script in your favorite programming language, +and call it using the [`sqlpage.exec`](?function=exec#function) function. + +For instance, one could save the following small bash script to `/usr/local/bin/upload_to_s3`: + +```bash +#!/bin/bash +aws s3 cp "$1" s3://your-s3-bucket-name/ +echo "https://your-s3-bucket-url/$(basename "$1")" +``` + +Then, you can call it from SQL like this: + +```sql +set url = sqlpage.exec('upload_to_s3', sqlpage.uploaded_file_path('myfile')); +insert into uploaded_files (title, path) values (:title, $url); +``` diff --git a/examples/official-site/content/functions/url_encode.md b/examples/official-site/content/functions/url_encode.md new file mode 100644 index 000000000..f9adb2818 --- /dev/null +++ b/examples/official-site/content/functions/url_encode.md @@ -0,0 +1,24 @@ +--- +icon: percentage +since: 0.12.0 +category: links-and-routing +summary: Encode text for use in a URL. +parameters: + - name: string + type: TEXT + required: true + description: The string to encode. +--- + +Returns the given string, with all characters that are not allowed in a URL encoded. + +### Example + +```sql +select 'text' as component; +select 'https://example.com/?q=' || sqlpage.url_encode($user_search) as contents; +``` + +#### Result + +`https://example.com/?q=hello%20world` diff --git a/examples/official-site/content/functions/user_info.md b/examples/official-site/content/functions/user_info.md new file mode 100644 index 000000000..d63d9b24c --- /dev/null +++ b/examples/official-site/content/functions/user_info.md @@ -0,0 +1,104 @@ +--- +icon: user +since: 0.34.0 +category: identity-and-security +summary: Read a named claim for the signed-in user. +parameters: + - name: claim + type: TEXT + required: true + description: The name of the user information to retrieve. Common values include 'name', 'email', 'picture', + 'sub', 'preferred_username', 'given_name', and 'family_name'. The exact values available depend on your + OIDC provider and configuration. +--- + +The `sqlpage.user_info` function is a convenient way to access specific pieces of information about the currently logged-in user. +When you [configure Single Sign-On](/sso), your OIDC provider will issue an [ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) for the user, +which contains *claims*, with information about the user. + +Calling `sqlpage.user_info(claim_name)` lets you access these claims directly from SQL. + +## Read a claim + +The function takes one parameter: the name of the *claim* (the piece of information you want to retrieve). + +For example, to display a personalized welcome message, with the user's name, you can use: + +```sql +select 'text' as component; +select 'Welcome, ' || sqlpage.user_info('name') || '!' as title; +``` + +## Available Information + +The exact information available depends on your identity provider (the service you chose to authenticate with), +its configuration, and the scopes you requested. +Use [`sqlpage.user_info_token()`](?function=user_info_token) to see all the information available in the ID token of the current user. + +Here are some commonly available fields: + +### Basic Information +- `name`: The user's full name (usually first and last name separated by a space) +- `email`: The user's email address (*warning*: there is no guarantee that the user currently controls this email address. Use the `sub` claim for database references instead.) +- `picture`: URL to the user's profile picture + +### User Identifiers +- `sub`: A unique identifier for the user (use this to uniquely identify the user in your database) +- `preferred_username`: The username the user prefers to use + +### Name Components +- `given_name`: The user's first name +- `family_name`: The user's last name + +## Examples + +### Personalized Welcome Message +```sql +select 'text' as component, + 'Welcome back, **' || sqlpage.user_info('given_name') || '**!' as contents_md; +``` + +### User Profile Card +```sql +select 'card' as component; +select + sqlpage.user_info('name') as title, + sqlpage.user_info('email') as description, + sqlpage.user_info('picture') as image; +``` + +### Conditional Content Based on custom claims + +Some identity providers let you add custom claims to the ID token. +This lets you customize the behavior of your application based on arbitrary user attributes, +such as the user's role. + +```sql +-- show everything to admins, only public items to others +select 'list' as component; +select title from my_items + where is_public or sqlpage.user_info('role') = 'admin' +``` + +## Security Best Practices + +> ⚠️ **Important**: Always use the `sub` claim to identify users in your database, not their email address. +> The `sub` claim is guaranteed to be unique and stable for each user, while email addresses can change. +> In most providers, receiving an id token with a given email does not guarantee that the user currently controls that email. + +```sql +-- Store the user's ID in your database +insert into user_preferences (user_id, theme) +values (sqlpage.user_info('sub'), 'dark'); +``` + +## Troubleshooting + +If you're not getting the information you expect: + +1. Check that OIDC is properly configured in your `sqlpage.json` +2. Verify that you requested the right scopes in your OIDC configuration +3. Try using `sqlpage.user_info_token()` to see all available information +4. Check your OIDC provider's documentation for the exact claim names they use + +Remember: If the user is not logged in or the requested information is not available, this function returns NULL. diff --git a/examples/official-site/content/functions/user_info_token.md b/examples/official-site/content/functions/user_info_token.md new file mode 100644 index 000000000..5d6ecc7d6 --- /dev/null +++ b/examples/official-site/content/functions/user_info_token.md @@ -0,0 +1,39 @@ +--- +icon: key +since: 0.35.0 +category: identity-and-security +summary: Read all claims from the user's OpenID Connect ID token. +--- + +This function can be used only when you have [configured Single Sign-On with an OIDC provider](/sso). + +## The ID Token + +When a user logs in through OIDC, your application receives an [identity token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) from the identity provider. +This token contains information about the user, such as their name and email address. +The `sqlpage.user_info_token()` function lets you access the entire contents of the ID token, as a JSON object. +You can then use [your database's JSON functions](/blog.sql?post=JSON+in+SQL%3A+A+Comprehensive+Guide) to process that JSON. + +If you need to access a specific claim, it is easier and more performant to use the +[`sqlpage.user_info()`](?function=user_info) function instead. + +## Displaying user claims + +```sql +select 'list' as component; +select key as title, value as description +from json_each(sqlpage.user_info_token()); +``` + +This sqlite-specific example will show all the information available about the current user, such as: +- `sub`: A unique identifier for the user +- `name`: The user's full name +- `email`: The user's email address +- `picture`: A URL to the user's profile picture + +## Security notes + +- The ID token is automatically verified by SQLPage to ensure it hasn't been tampered with. +- The token is only available to authenticated users: if no user is logged in or sso is not configured, this function returns NULL +- If some information is not available in the token, you have to configure it on your OIDC provider, SQLPage can't do anything about it. +- The token is stored in a signed http-only cookie named `sqlpage_auth`. You can use [the cookie component](/component.sql?component=cookie) to delete it, and the user will be redirected to the login page on the next page load. diff --git a/examples/official-site/content/functions/variables.md b/examples/official-site/content/functions/variables.md new file mode 100644 index 000000000..a7c48f161 --- /dev/null +++ b/examples/official-site/content/functions/variables.md @@ -0,0 +1,101 @@ +--- +icon: variable +since: 0.15.0 +category: request-data +summary: Read request or page variables as a JSON object. +parameters: + - name: method + type: TEXT + description: 'Optional. Filter variables by source: ''get'' (URL parameters), ''post'' (form data), or + ''set'' (user-defined variables). When not provided, all variables are returned with SET variables taking + precedence over request parameters.' +--- + +Returns a JSON string containing variables from the HTTP request and user-defined variables. + +The [database's json handling functions](/blog?post=JSON+in+SQL%3A+A+Comprehensive+Guide) can then be used to process the data. + +## Variable Types + +SQLPage distinguishes between three types of variables: + +- **GET variables**: URL parameters from the [query string](https://en.wikipedia.org/wiki/Query_string) (immutable) +- **POST variables**: Values from form fields [submitted](https://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms) by the user (immutable) +- **SET variables**: User-defined variables created with the `SET` command (mutable) + +For more information about SQLPage variables, see the [*SQL in SQLPage* guide](/extensions-to-sql). + +## Usage + +- `sqlpage.variables()` - returns all variables (GET, POST, and SET combined). When multiple variables of the same name are present, the order of precedence is: set > post > get. +- `sqlpage.variables('get')` - returns only URL parameters +- `sqlpage.variables('post')` - returns only POST form data +- `sqlpage.variables('set')` - returns only user-defined variables created with `SET` + +When a SET variable has the same name as a GET or POST variable, the SET variable takes precedence in the combined result. + +## Example: a form with a variable number of fields + +### Making a form based on questions in a database table + +We can create a form which has a field for each value in a given table like this: + +```sql +select 'form' as component, 'handle_survey_answer.sql' as action; +select question_id as name, question_text as label from survey_questions; +``` + +### Handling form responses using `sqlpage.variables` + +In `handle_survey_answer.sql`, one can process the form results even if we don't know in advance +how many fields it contains. +The function to parse JSON data varies depending on the database engine you use. + +#### In SQLite +In SQLite, one can use [`json_each`](https://www.sqlite.org/json1.html#jeach) : + +```sql +insert into survey_answers(question_id, answer) +select "key", "value" from json_each(sqlpage.variables('post')) +``` + +#### In Postgres + +Postgres has [`json_each_text`](https://www.postgresql.org/docs/9.3/functions-json.html) : + +```sql +INSERT INTO survey_answers (question_id, answer) +SELECT key AS question_id, value AS answer +FROM json_each_text(sqlpage.variables('post')::json); +``` + + +#### In Microsoft SQL Server + +```sql +INSERT INTO survey_answers +SELECT [key] AS question_id, [value] AS answer +FROM OPENJSON(sqlpage.variables('post')); +``` + +#### In MySQL + +MySQL has [`JSON_TABLE`](https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html), +and [`JSON_KEYS`](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-keys) +which are a little bit less straightforward to use: + +```sql +INSERT INTO survey_answers (question_id, answer) +SELECT + question_id, + json_unquote( + json_extract( + sqlpage.variables('post'), + concat('$."', question_id, '"') + ) + ) +FROM json_table( + json_keys(sqlpage.variables('post')), + '$[*]' columns (question_id int path '$') +) as question_ids +``` diff --git a/examples/official-site/content/functions/version.md b/examples/official-site/content/functions/version.md new file mode 100644 index 000000000..4a5327aaa --- /dev/null +++ b/examples/official-site/content/functions/version.md @@ -0,0 +1,8 @@ +--- +icon: git-commit +since: 0.11.0 +category: server-and-runtime +summary: Read the version of SQLPage serving the page. +--- + +Returns the current version of SQLPage as a string. diff --git a/examples/official-site/content/functions/web_root.md b/examples/official-site/content/functions/web_root.md new file mode 100644 index 000000000..1acd5f840 --- /dev/null +++ b/examples/official-site/content/functions/web_root.md @@ -0,0 +1,30 @@ +--- +icon: folder-code +since: 0.42.0 +category: server-and-runtime +summary: Locate the directory that holds the site's public files. +--- + +Returns the web root directory where SQLPage serves `.sql` files from. + +### Example + +```sql +SELECT 'text' AS component; +SELECT 'SQL files are served from ' AS contents; +SELECT sqlpage.web_root() as contents, true as code; +``` + +#### Result + +SQL files are served from `/home/user/my_sqlpage_website` + +#### Notes + +The web root is the directory from which `.sql` files are loaded and served. +By default, it is the current working directory, but it can be changed using: + - the `--web-root` command line argument + - the `web_root` [configuration option](/configuration#web_root) in `sqlpage.json` + - the `WEB_ROOT` environment variable + +This is more reliable than `sqlpage.current_working_directory()` when you need to reference the location of your SQL files. diff --git a/src/webserver/database/sqlpage_functions/functions.rs b/src/webserver/database/sqlpage_functions/functions.rs index d92d7735c..d6d02e8ef 100644 --- a/src/webserver/database/sqlpage_functions/functions.rs +++ b/src/webserver/database/sqlpage_functions/functions.rs @@ -129,26 +129,22 @@ mod tests { use std::collections::BTreeSet; #[test] - fn functions_directory_matches_registered_functions() { - let directory = concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/webserver/database/sqlpage_functions/functions" - ); - let files: BTreeSet = std::fs::read_dir(directory) - .expect("functions directory") - .map(|entry| entry.expect("directory entry").path()) - .filter(|path| path.extension().is_some_and(|extension| extension == "rs")) - .map(|path| { - path.file_stem() - .expect("file stem") - .to_string_lossy() - .into_owned() - }) - .collect(); + fn registered_functions_have_a_module_and_documentation() { let registered: BTreeSet = SqlPageFunctionName::ALL .iter() .map(|function| function.name().to_owned()) .collect(); - assert_eq!(files, registered); + for (directory, extension) in [ + ("src/webserver/database/sqlpage_functions/functions", "rs"), + ("examples/official-site/content/functions", "md"), + ] { + let files: BTreeSet<_> = std::fs::read_dir(directory) + .unwrap_or_else(|error| panic!("{directory}: {error}")) + .map(|entry| entry.expect("directory entry").path()) + .filter(|path| path.extension().is_some_and(|ext| ext == extension)) + .map(|path| path.file_stem().unwrap().to_string_lossy().into_owned()) + .collect(); + assert_eq!(files, registered, "{directory}"); + } } }