diff --git a/examples/official-site/README.md b/examples/official-site/README.md index 331bbf199..11238241a 100644 --- a/examples/official-site/README.md +++ b/examples/official-site/README.md @@ -26,6 +26,14 @@ Add `theme=light` or `theme=dark` to a component reference URL to preview its live examples using SQLPage's stock theme. For example, visit `/component.sql?component=form&theme=light`. +## Function reference + +Edit each function in [`sqlpage/content/functions/`](sqlpage/content/functions/). +The filename matches the function name and determines its reference URL. +Use YAML front matter for the catalog summary, return type, and ordered +`parameters` list. Set `required: true` on required arguments. +Write the overview and examples in Markdown below the front matter. + ## Component reference Document Handlebars component parameters in the first comment of `sqlpage/templates/.handlebars`. Start with a short summary paragraph, then give the complete overview, followed by `## Top-level parameters` and `## Row-level parameters`. Omit empty sections. For the nine components implemented in Rust, put the overview and parameter list in that component's `README.md` under `reference/components/` using the same structure. diff --git a/examples/official-site/sqlpage/content/functions/basic_auth_password.md b/examples/official-site/sqlpage/content/functions/basic_auth_password.md new file mode 100644 index 000000000..21143cd73 --- /dev/null +++ b/examples/official-site/sqlpage/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 absent, SQLPage sends an HTTP Basic challenge. Browsers normally respond by prompting for 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/sqlpage/content/functions/basic_auth_username.md b/examples/official-site/sqlpage/content/functions/basic_auth_username.md new file mode 100644 index 000000000..d6252e841 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/migrations/57_client_ip.sql b/examples/official-site/sqlpage/content/functions/client_ip.md similarity index 63% rename from examples/official-site/sqlpage/migrations/57_client_ip.sql rename to examples/official-site/sqlpage/content/functions/client_ip.md index 168451f40..ef5afe844 100644 --- a/examples/official-site/sqlpage/migrations/57_client_ip.sql +++ b/examples/official-site/sqlpage/content/functions/client_ip.md @@ -1,16 +1,11 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'client_ip', - '0.33.0', - 'network', - 'Returns the IP address of the client making the HTTP request. +--- +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 @@ -28,19 +23,17 @@ The function returns: 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'')` +- 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.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. -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/content/functions/configuration_directory.md b/examples/official-site/sqlpage/content/functions/configuration_directory.md new file mode 100644 index 000000000..ee7c260e4 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/cookie.md b/examples/official-site/sqlpage/content/functions/cookie.md new file mode 100644 index 000000000..5f92673c1 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/current_working_directory.md b/examples/official-site/sqlpage/content/functions/current_working_directory.md new file mode 100644 index 000000000..07c9ba069 --- /dev/null +++ b/examples/official-site/sqlpage/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. +Setting [`web_root`](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) changes where SQLPage serves files. It does not change the process working directory. Use [`sqlpage.web_root()`](?function=web_root) to get the directory actually being served. diff --git a/examples/official-site/sqlpage/content/functions/environment_variable.md b/examples/official-site/sqlpage/content/functions/environment_variable.md new file mode 100644 index 000000000..b46b60549 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/exec.md b/examples/official-site/sqlpage/content/functions/exec.md new file mode 100644 index 000000000..97c847a20 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/migrations/40_fetch.sql b/examples/official-site/sqlpage/content/functions/fetch.md similarity index 67% rename from examples/official-site/sqlpage/migrations/40_fetch.sql rename to examples/official-site/sqlpage/content/functions/fetch.md index 6995054c7..b2015792a 100644 --- a/examples/official-site/sqlpage/migrations/40_fetch.sql +++ b/examples/official-site/sqlpage/content/functions/fetch.md @@ -1,14 +1,17 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'fetch', - '0.20.3', - 'transfer-vertical', - 'Sends an HTTP request and returns the results as a string. +--- +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 @@ -21,13 +24,13 @@ We use the simplest form of the fetch function, that takes the URL to fetch as a ```sql -set url = ''https://nominatim.openstreetmap.org/search?format=json&q='' || sqlpage.url_encode($user_search); +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 '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; + CAST($api_results->>0->>'lat' AS FLOAT) as latitude, + CAST($api_results->>0->>'lon' AS FLOAT) as longitude; ``` ### POST query with a body @@ -35,41 +38,41 @@ select $user_search as title, 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. +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'') + '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'' + 'body', json_object( + 'Hello', 'world' ) ); set api_results = sqlpage.fetch($request); -select ''code'' as component; +select 'code' as component; select - ''API call results'' as title, - ''json'' as language, + '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): +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'' + 'url', 'https://api.example.com/data', + 'username', 'my_username', + 'password', 'my_password' ); set api_results = sqlpage.fetch($request); ``` @@ -100,7 +103,7 @@ Use it to skip the request when the value is already cached: ```sql set current_field_value = (select field from my_table where id = 1); -set target_url = case when $current_field_value is null then ''https://example.com/api/field/1'' end; +set target_url = case when $current_field_value is null then 'https://example.com/api/field/1' end; set api_value = sqlpage.fetch($target_url); update my_table set field = $api_value where id = 1 and field is null and $api_value is not null; ``` @@ -123,19 +126,3 @@ If the query returns more than one row or more than one column, SQLPage returns If you need to handle errors or inspect the response headers or the status code, use [`sqlpage.fetch_with_meta`](?function=fetch_with_meta). -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'fetch', - 1, - 'url', - '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.', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/content/functions/fetch_with_meta.md b/examples/official-site/sqlpage/content/functions/fetch_with_meta.md new file mode 100644 index 000000000..cf33e2e7c --- /dev/null +++ b/examples/official-site/sqlpage/content/functions/fetch_with_meta.md @@ -0,0 +1,83 @@ +--- +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 link +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; +``` + +### 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/sqlpage/content/functions/hash_password.md b/examples/official-site/sqlpage/content/functions/hash_password.md new file mode 100644 index 000000000..b81c05c91 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/header.md b/examples/official-site/sqlpage/content/functions/header.md new file mode 100644 index 000000000..7ee40e529 --- /dev/null +++ b/examples/official-site/sqlpage/content/functions/header.md @@ -0,0 +1,23 @@ +--- +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 one [HTTP request header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers). Names are case-insensitive: `sqlpage.header('User-Agent')` and `sqlpage.header('user-agent')` read the same value. An absent header returns SQL `NULL`. + +### 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/sqlpage/migrations/56_headers.sql b/examples/official-site/sqlpage/content/functions/headers.md similarity index 56% rename from examples/official-site/sqlpage/migrations/56_headers.sql rename to examples/official-site/sqlpage/content/functions/headers.md index b88aaf4e2..dc75859b4 100644 --- a/examples/official-site/sqlpage/migrations/56_headers.sql +++ b/examples/official-site/sqlpage/content/functions/headers.md @@ -1,28 +1,25 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'headers', - '0.33.0', - 'circle-dotted-letter-h', - 'Returns all HTTP request headers as a JSON object. +--- +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. +using SQLite's `json_each()` function. ```sql -select ''list'' as component; +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). +If not on SQLite, use your [database's JSON function](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). ### Details @@ -36,4 +33,3 @@ This is useful when you need to: - Access multiple headers at once If you only need access to a single known header, use [`sqlpage.header(name)`](?function=header) instead. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/content/functions/hmac.md b/examples/official-site/sqlpage/content/functions/hmac.md new file mode 100644 index 000000000..08514b6ed --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/link.md b/examples/official-site/sqlpage/content/functions/link.md new file mode 100644 index 000000000..9d4d37354 --- /dev/null +++ b/examples/official-site/sqlpage/content/functions/link.md @@ -0,0 +1,53 @@ +--- +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. + +To link directly to a section, pass its `id` as the third argument, without the `#`: + +```sql +select sqlpage.link('product.sql', json_object('product_name', name), 'product_description') as link +from products; +``` diff --git a/examples/official-site/sqlpage/content/functions/oidc_logout_url.md b/examples/official-site/sqlpage/content/functions/oidc_logout_url.md new file mode 100644 index 000000000..dcc8ae54e --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/migrations/21_path.sql b/examples/official-site/sqlpage/content/functions/path.md similarity index 53% rename from examples/official-site/sqlpage/migrations/21_path.sql rename to examples/official-site/sqlpage/content/functions/path.md index 5fc1afaa4..2e3101e37 100644 --- a/examples/official-site/sqlpage/migrations/21_path.sql +++ b/examples/official-site/sqlpage/content/functions/path.md @@ -1,14 +1,11 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'path', - '0.15.0', - 'slashes', - 'Returns the request path of the current page. +--- +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 @@ -17,10 +14,9 @@ If we have a page in a file named `my page.sql` at the root of your SQLPage inst then the following SQL query: ```sql -select ''text'' as component, sqlpage.path() as contents; +select 'text' as component, sqlpage.path() as contents; ``` will return `/my%20page.sql`. > Note that the path is URL-encoded. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/content/functions/persist_uploaded_file.md b/examples/official-site/sqlpage/content/functions/persist_uploaded_file.md new file mode 100644 index 000000000..c1060588d --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/persist_uploaded_files.md b/examples/official-site/sqlpage/content/functions/persist_uploaded_files.md new file mode 100644 index 000000000..34d6cca49 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/protocol.md b/examples/official-site/sqlpage/content/functions/protocol.md new file mode 100644 index 000000000..3578c54ff --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/random_string.md b/examples/official-site/sqlpage/content/functions/random_string.md new file mode 100644 index 000000000..c90b48688 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/migrations/24_read_file_as_data_url.sql b/examples/official-site/sqlpage/content/functions/read_file_as_data_url.md similarity index 62% rename from examples/official-site/sqlpage/migrations/24_read_file_as_data_url.sql rename to examples/official-site/sqlpage/content/functions/read_file_as_data_url.md index eba68adc3..e5bdb522e 100644 --- a/examples/official-site/sqlpage/migrations/24_read_file_as_data_url.sql +++ b/examples/official-site/sqlpage/content/functions/read_file_as_data_url.md @@ -1,15 +1,16 @@ --- Insert the 'variables' function into sqlpage_functions table -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" -) -VALUES ( - 'read_file_as_data_url', - '0.17.0', - 'file-dollar', - 'Returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) +--- +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. @@ -18,7 +19,7 @@ with the `web_root` [configuration option](https://github.com/sqlpage/SQLPage/bl If the given argument is null, the function will return null. -As with other functions, if an error occurs during execution +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. @@ -37,30 +38,12 @@ Otherwise, the MIME type will be guessed from the file extension, without lookin ## 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; +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. -'); - --- Insert the parameters for the 'variables' function into sqlpage_function_parameters table --- Parameter 1: 'method' parameter -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" -) -VALUES ( - 'read_file_as_data_url', - 1, - 'name', - 'Path to the file to read.', - 'TEXT' -); diff --git a/examples/official-site/sqlpage/content/functions/read_file_as_text.md b/examples/official-site/sqlpage/content/functions/read_file_as_text.md new file mode 100644 index 000000000..b7b78a2fc --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/migrations/74_regex_match.sql b/examples/official-site/sqlpage/content/functions/regex_match.md similarity index 61% rename from examples/official-site/sqlpage/migrations/74_regex_match.sql rename to examples/official-site/sqlpage/content/functions/regex_match.md index 8e0540458..f8e9e6699 100644 --- a/examples/official-site/sqlpage/migrations/74_regex_match.sql +++ b/examples/official-site/sqlpage/content/functions/regex_match.md @@ -1,16 +1,21 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'regex_match', - '0.43.0', - 'regex', - 'Matches a text value against a regular expression and returns the capture groups as a JSON object. +--- +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 @@ -31,16 +36,16 @@ You can put a `categories/404.sql` file in your project and extract the dynamic #### `categories/404.sql` ```sql set route = sqlpage.regex_match( - ''/categories/(?\w+)/post/(?\d+)'', + '/categories/(?\w+)/post/(?\d+)', sqlpage.path() ); -select ''redirect'' as component, ''/404'' as link +select 'redirect' as component, '/404' as link where $route is null; -select ''text'' as component; +select 'text' as component; select - ''Category: '' || ($route->>''category'') || '' | Post id: '' || ($route->>''id'') as contents; + 'Category: ' || ($route->>'category') || ' | Post id: ' || ($route->>'id') as contents; ``` If the current path is `/categories/sql/post/42`, `sqlpage.regex_match()` returns: @@ -54,8 +59,8 @@ 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); +where category = $route->>'category' + and id = cast($route->>'id' as integer); ``` ### Details @@ -67,37 +72,11 @@ where category = $route->>''category'' - 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'')` +- 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. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'regex_match', - 1, - 'pattern', - 'The regular expression pattern to match against the input text. Named capture groups such as `(?...)` are supported.', - 'TEXT' - ), - ( - 'regex_match', - 2, - 'text', - 'The text to match against the regular expression. Returns `NULL` when this argument is `NULL`.', - 'TEXT' - ); +The returned JSON can then be processed with your database's JSON functions. diff --git a/examples/official-site/sqlpage/content/functions/request_body.md b/examples/official-site/sqlpage/content/functions/request_body.md new file mode 100644 index 000000000..724a327c4 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/request_body_base64.md b/examples/official-site/sqlpage/content/functions/request_body_base64.md new file mode 100644 index 000000000..47cac0860 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/migrations/43_request_method.sql b/examples/official-site/sqlpage/content/functions/request_method.md similarity index 58% rename from examples/official-site/sqlpage/migrations/43_request_method.sql rename to examples/official-site/sqlpage/content/functions/request_method.md index b4beb545d..01577e059 100644 --- a/examples/official-site/sqlpage/migrations/43_request_method.sql +++ b/examples/official-site/sqlpage/content/functions/request_method.md @@ -1,22 +1,17 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'request_method', - '0.21.0', - 'http-get', - 'Returns the HTTP request method (GET, POST, etc.) used to access the page. +--- +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. SQLPage''s [form component](/component.sql?component=form) defaults to POST; a plain HTML form defaults to GET. + - **POST**: submit data to be processed by the server. SQLPage's [form component](/component.sql?component=form) defaults to POST; a plain HTML form defaults to GET. - **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. @@ -24,11 +19,9 @@ HTTP request methods (also known as verbs) are used to indicate the desired acti ## Require a PUT request ```sql -select ''redirect'' as component, - ''/error?msg=expected+a+PUT+request'' as link -where sqlpage.request_method() != ''PUT''; +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); ``` -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/38_run_sql.sql b/examples/official-site/sqlpage/content/functions/run_sql.md similarity index 67% rename from examples/official-site/sqlpage/migrations/38_run_sql.sql rename to examples/official-site/sqlpage/content/functions/run_sql.md index 314755f2e..9a077cc29 100644 --- a/examples/official-site/sqlpage/migrations/38_run_sql.sql +++ b/examples/official-site/sqlpage/content/functions/run_sql.md @@ -1,14 +1,23 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'run_sql', - '0.20.0', - 'login', - 'Executes another SQL file and returns its result as a JSON array. +--- +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 @@ -21,7 +30,7 @@ and use the [`dynamic`](documentation.sql?component=dynamic#component) component to include it in all your pages. ```sql -select ''dynamic'' as component, sqlpage.run_sql(''common_header.sql'') as properties; +select 'dynamic' as component, sqlpage.run_sql('common_header.sql') as properties; ``` #### Factorize logic between pages @@ -38,7 +47,7 @@ select some_field from some_table; ```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''; +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) @@ -65,31 +74,8 @@ You can pass parameters to the included file, as if it had been with a URL param For instance, you can use: ```sql -sqlpage.run_sql(''included_file.sql'', json_object(''param1'', ''value1'', ''param2'', ''value2'')) +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). -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'run_sql', - 1, - 'file', - '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.', - 'TEXT' - ),( - 'run_sql', - 2, - 'parameters', - '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.', - 'JSON' - ); diff --git a/examples/official-site/sqlpage/migrations/75_send_mail.sql b/examples/official-site/sqlpage/content/functions/send_mail.md similarity index 80% rename from examples/official-site/sqlpage/migrations/75_send_mail.sql rename to examples/official-site/sqlpage/content/functions/send_mail.md index 01d6281c0..4bbadd98c 100644 --- a/examples/official-site/sqlpage/migrations/75_send_mail.sql +++ b/examples/official-site/sqlpage/content/functions/send_mail.md @@ -1,16 +1,25 @@ -INSERT INTO sqlpage_functions ( - "name", - "return_type", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'send_mail', - 'JSON', - '0.45.0', - 'mail', - 'Sends a plain-text email using the outgoing mail server configured in SQLPage. +--- +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 @@ -35,9 +44,9 @@ 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!'' + 'to', 'alice@example.com', + 'subject', 'Hello from SQLPage', + 'body', 'Your first email is working!' )); ``` @@ -50,16 +59,16 @@ The sender comes from `smtp_from`. The result is a JSON object: 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"} +{"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; +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 @@ -137,13 +146,13 @@ Each attachment has a file name and a [data URL](https://developer.mozilla.org/e ```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'') + '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') )) )); ``` @@ -158,10 +167,10 @@ Set `body_html` to send an HTML version of the message alongside the plain-text ```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.

'' + 'to', 'alice@example.com', + 'subject', 'Welcome', + 'body', 'Welcome to our service.', + 'body_html', '

Welcome to our service.

' )); ``` @@ -173,9 +182,9 @@ Set `body_md` to send a [Markdown](https://daringfireball.net/projects/markdown/ ```sql set result = sqlpage.send_mail(json_object( - ''to'', ''alice@example.com'', - ''subject'', ''Welcome'', - ''body_md'', ''# Welcome\n\nWelcome to **our service**.'' + 'to', 'alice@example.com', + 'subject', 'Welcome', + 'body_md', '# Welcome\n\nWelcome to **our service**.' )); ``` @@ -186,25 +195,25 @@ SQLPage renders Markdown using the same [GFM](https://github.github.com/gfm/) op ### 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; +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 + '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 +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; ``` @@ -279,20 +288,3 @@ SQLPage does not currently support: | `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. | -' - ); - -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'send_mail', - 1, - 'message', - '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.', - 'JSON' - ); diff --git a/examples/official-site/sqlpage/content/functions/set_variable.md b/examples/official-site/sqlpage/content/functions/set_variable.md new file mode 100644 index 000000000..1b1692e49 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/uploaded_file_mime_type.md b/examples/official-site/sqlpage/content/functions/uploaded_file_mime_type.md new file mode 100644 index 000000000..7114f3a9a --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/uploaded_file_name.md b/examples/official-site/sqlpage/content/functions/uploaded_file_name.md new file mode 100644 index 000000000..82f0fc169 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/uploaded_file_path.md b/examples/official-site/sqlpage/content/functions/uploaded_file_path.md new file mode 100644 index 000000000..4f12188ce --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/url_encode.md b/examples/official-site/sqlpage/content/functions/url_encode.md new file mode 100644 index 000000000..f9adb2818 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/user_info.md b/examples/official-site/sqlpage/content/functions/user_info.md new file mode 100644 index 000000000..d63d9b24c --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/user_info_token.md b/examples/official-site/sqlpage/content/functions/user_info_token.md new file mode 100644 index 000000000..5d6ecc7d6 --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/migrations/20_variables_function.sql b/examples/official-site/sqlpage/content/functions/variables.md similarity index 58% rename from examples/official-site/sqlpage/migrations/20_variables_function.sql rename to examples/official-site/sqlpage/content/functions/variables.md index a0379d774..8e00fc70f 100644 --- a/examples/official-site/sqlpage/migrations/20_variables_function.sql +++ b/examples/official-site/sqlpage/content/functions/variables.md @@ -1,17 +1,19 @@ --- Insert the 'variables' function into sqlpage_functions table -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" -) -VALUES ( - 'variables', - '0.15.0', - 'variable', - '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. +--- +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: >- + Filter by source: `get` for URL parameters, `post` for form fields, or `set` for page variables. + With no argument, the result combines all three. +--- + +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 @@ -26,12 +28,12 @@ For more information about SQLPage variables, see the [*SQL in SQLPage* guide](/ ## 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` +- `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` For example, after `SET page = NULL` on a request to `?page=2`, -`sqlpage.variables(''get'')` still contains `"page":"2"`. +`sqlpage.variables('get')` still contains `"page":"2"`. The combined `sqlpage.variables()` contains `"page":null`. ## Example: a form with a variable number of fields @@ -41,13 +43,13 @@ The combined `sqlpage.variables()` contains `"page":null`. 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 '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 +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. @@ -56,7 +58,7 @@ 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'')) +select "key", "value" from json_each(sqlpage.variables('post')) ``` #### In Postgres @@ -66,7 +68,7 @@ Postgres has [`json_each_text`](https://www.postgresql.org/docs/9.3/functions-js ```sql INSERT INTO survey_answers (question_id, answer) SELECT key AS question_id, value AS answer -FROM json_each_text(sqlpage.variables(''post'')::json); +FROM json_each_text(sqlpage.variables('post')::json); ``` @@ -75,7 +77,7 @@ FROM json_each_text(sqlpage.variables(''post'')::json); ```sql INSERT INTO survey_answers SELECT [key] AS question_id, [value] AS answer -FROM OPENJSON(sqlpage.variables(''post'')); +FROM OPENJSON(sqlpage.variables('post')); ``` #### In MySQL @@ -90,32 +92,12 @@ SELECT question_id, json_unquote( json_extract( - sqlpage.variables(''post''), - concat(''$."'', question_id, ''"'') + sqlpage.variables('post'), + concat('$."', question_id, '"') ) ) FROM json_table( - json_keys(sqlpage.variables(''post'')), - ''$[*]'' columns (question_id int path ''$'') + json_keys(sqlpage.variables('post')), + '$[*]' columns (question_id int path '$') ) as question_ids ``` - -' -); - --- Insert the parameters for the 'variables' function into sqlpage_function_parameters table --- Parameter 1: 'method' parameter -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" -) -VALUES ( - 'variables', - 1, - 'method', - 'Filter by source: `get` for URL parameters, `post` for form fields, or `set` for page variables. With no argument, the result combines all three.', - 'TEXT' -); diff --git a/examples/official-site/sqlpage/content/functions/version.md b/examples/official-site/sqlpage/content/functions/version.md new file mode 100644 index 000000000..4a5327aaa --- /dev/null +++ b/examples/official-site/sqlpage/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/sqlpage/content/functions/web_root.md b/examples/official-site/sqlpage/content/functions/web_root.md new file mode 100644 index 000000000..e56340181 --- /dev/null +++ b/examples/official-site/sqlpage/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](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) 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/examples/official-site/sqlpage/migrations/08_functions.sql b/examples/official-site/sqlpage/migrations/08_functions.sql index 335729e56..90502d472 100644 --- a/examples/official-site/sqlpage/migrations/08_functions.sql +++ b/examples/official-site/sqlpage/migrations/08_functions.sql @@ -12,472 +12,3 @@ CREATE TABLE IF NOT EXISTS sqlpage_function_parameters ( "description_md" TEXT, "type" TEXT ); -INSERT INTO sqlpage_functions ( - "name", - "return_type", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'cookie', - 'TEXT', - '0.7.1', - 'cookie', - '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; -``` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'cookie', - 1, - 'name', - 'The name of the cookie to read.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'header', - '0.7.2', - 'heading', - 'Reads one [HTTP request header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers). Names are case-insensitive: `sqlpage.header(''User-Agent'')` and `sqlpage.header(''user-agent'')` read the same value. An absent header returns SQL `NULL`. - -### 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. - ' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'header', - 1, - 'name', - 'The name of the HTTP header to read.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "return_type", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'basic_auth_username', - 'TEXT', - '0.7.2', - 'user', - '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; -``` - -' - ), - ( - 'basic_auth_password', - 'TEXT', - '0.7.2', - 'key', - 'Returns the password from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. -If the header is absent, SQLPage sends an HTTP Basic challenge. Browsers normally respond by prompting for 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; -``` -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'hash_password', - '0.7.2', - 'spy', - ' -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). - ' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'hash_password', - 1, - 'password', - 'The password to hash.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'random_string', - '0.7.2', - 'arrows-shuffle', - '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; -``` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'random_string', - 1, - 'length', - 'The length of the string to generate.', - 'INTEGER' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'current_working_directory', - '0.11.0', - 'folder-question', - '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. -Setting [`web_root`](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) changes where SQLPage serves files. It does not change the process working directory. Use [`sqlpage.web_root()`](?function=web_root) to get the directory actually being served. -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'web_root', - '0.42.0', - 'folder-code', - '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](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) 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. -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'configuration_directory', - '0.42.0', - 'folder-cog', - '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. -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'environment_variable', - '0.11.0', - 'variable', - '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; -```' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'environment_variable', - 1, - 'name', - 'The name of the environment variable to read. Must be a literal string.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'version', - '0.11.0', - 'git-commit', - 'Returns the current version of SQLPage as a string.' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'exec', - '0.12.0', - 'terminal-2', - '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. -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'exec', - 1, - 'program', - 'The name of the program to execute. Must be a literal string.', - 'TEXT' - ), - ( - 'exec', - 2, - 'arguments...', - 'The arguments to pass to the program.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'url_encode', - '0.12.0', - 'percentage', - '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` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'url_encode', - 1, - 'string', - 'The string to encode.', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql b/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql deleted file mode 100644 index f97ce0ea0..000000000 --- a/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql +++ /dev/null @@ -1,186 +0,0 @@ --- Insert the 'variables' function into sqlpage_functions table -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" -) -VALUES ( - 'uploaded_file_path', - '0.17.0', - 'upload', - '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); -``` -' -), -( - 'uploaded_file_mime_type', - '0.18.0', - 'file-settings', - '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); -``` -' -), -( - 'uploaded_file_name', - '0.23.0', - 'file-description', - '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. -' -); - -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" -) -VALUES ( - 'uploaded_file_path', - 1, - 'name', - 'Name of the file input field in the form.', - 'TEXT' -), -( - 'uploaded_file_mime_type', - 1, - 'name', - 'Name of the file input field in the form.', - 'TEXT' -), -( - 'uploaded_file_name', - 1, - 'name', - 'Name of the file input field in the form.', - 'TEXT' -) -; diff --git a/examples/official-site/sqlpage/migrations/25_read_file_as_text.sql b/examples/official-site/sqlpage/migrations/25_read_file_as_text.sql deleted file mode 100644 index 9cdae13cf..000000000 --- a/examples/official-site/sqlpage/migrations/25_read_file_as_text.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Insert the 'variables' function into sqlpage_functions table -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" -) -VALUES ( - 'read_file_as_text', - '0.17.0', - 'file-invoice', - '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; -``` -'); - --- Insert the parameters for the 'variables' function into sqlpage_function_parameters table --- Parameter 1: 'method' parameter -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" -) -VALUES ( - 'read_file_as_text', - 1, - 'name', - 'Path to the file to read.', - 'TEXT' -); diff --git a/examples/official-site/sqlpage/migrations/27_protocol.sql b/examples/official-site/sqlpage/migrations/27_protocol.sql deleted file mode 100644 index 1b0e155c1..000000000 --- a/examples/official-site/sqlpage/migrations/27_protocol.sql +++ /dev/null @@ -1,30 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'protocol', - '0.17.1', - 'network', - '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 -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/39_persist_uploaded_file.sql b/examples/official-site/sqlpage/migrations/39_persist_uploaded_file.sql deleted file mode 100644 index 76619a2db..000000000 --- a/examples/official-site/sqlpage/migrations/39_persist_uploaded_file.sql +++ /dev/null @@ -1,77 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'persist_uploaded_file', - '0.20.1', - 'device-floppy', - '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'') -); -``` - -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'persist_uploaded_file', - 1, - 'file', - '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.', - 'TEXT' - ), - ( - 'persist_uploaded_file', - 2, - 'destination_folder', - '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.', - 'TEXT' - ), - ( - 'persist_uploaded_file', - 3, - 'allowed_extensions', - '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.', - 'TEXT' - ), - ( - 'persist_uploaded_file', - 4, - 'mode', - '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).', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/47_link.sql b/examples/official-site/sqlpage/migrations/47_link.sql deleted file mode 100644 index 0d2949983..000000000 --- a/examples/official-site/sqlpage/migrations/47_link.sql +++ /dev/null @@ -1,79 +0,0 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'link', - '0.25.0', - 'link', - '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. - -To link directly to a section, pass its `id` as the third argument, without the `#`: - -```sql -select sqlpage.link(''product.sql'', json_object(''product_name'', name), ''product_description'') as link -from products; -``` -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'link', - 1, - 'file', - 'The path of the SQLPage file to link to, relative to the current file.', - 'TEXT' - ), - ( - 'link', - 2, - 'parameters', - 'A JSON object with the parameters to pass to the linked file.', - 'JSON' - ), - ( - 'link', - 3, - 'fragment', - 'An optional fragment (hash) to append to the URL to link to a specific section of the target page.', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/55_request_body.sql b/examples/official-site/sqlpage/migrations/55_request_body.sql deleted file mode 100644 index 423ef6a27..000000000 --- a/examples/official-site/sqlpage/migrations/55_request_body.sql +++ /dev/null @@ -1,135 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'request_body', - '0.33.0', - 'http-post', - '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. -' - ); - -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'request_body_base64', - '0.33.0', - 'photo-up', - '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) -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/58_fetch_with_meta.sql b/examples/official-site/sqlpage/migrations/58_fetch_with_meta.sql deleted file mode 100644 index e89196e7a..000000000 --- a/examples/official-site/sqlpage/migrations/58_fetch_with_meta.sql +++ /dev/null @@ -1,96 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'fetch_with_meta', - '0.34.0', - 'transfer-vertical', - '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 link -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; -``` - -### 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).' - ); - -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'fetch_with_meta', - 1, - 'url', - '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.', - 'TEXT' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/61_oidc_functions.sql b/examples/official-site/sqlpage/migrations/61_oidc_functions.sql deleted file mode 100644 index 197e68a9c..000000000 --- a/examples/official-site/sqlpage/migrations/61_oidc_functions.sql +++ /dev/null @@ -1,288 +0,0 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'user_info_token', - '0.35.0', - 'key', - '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. -' - ); - -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'user_info', - '0.34.0', - 'user', - '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. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'user_info', - 1, - 'claim', - '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.', - 'TEXT' - ); - -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'oidc_logout_url', - '0.41.0', - 'logout', - '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. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'oidc_logout_url', - 1, - 'redirect_uri', - 'The relative URL path where the user should be redirected after logout. Must start with `/`. Defaults to `/` if not provided.', - 'TEXT' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/67_hmac_function.sql b/examples/official-site/sqlpage/migrations/67_hmac_function.sql deleted file mode 100644 index 86ebda476..000000000 --- a/examples/official-site/sqlpage/migrations/67_hmac_function.sql +++ /dev/null @@ -1,137 +0,0 @@ --- HMAC function documentation and examples -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'hmac', - '0.38.0', - 'shield-lock', - '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. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'hmac', - 1, - 'data', - 'The input data to compute the HMAC for. Can be any text string. Cannot be NULL.', - 'TEXT' - ), - ( - 'hmac', - 2, - 'key', - 'The secret key used to compute the HMAC. Should be kept confidential. Cannot be NULL.', - 'TEXT' - ), - ( - 'hmac', - 3, - 'algorithm', - 'The hash algorithm and output format. Optional, defaults to `sha256` (hex output). Supported values: `sha256`, `sha256-base64`, `sha512`, `sha512-base64`. Defaults to `sha256`.', - 'TEXT' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/72_set_variable.sql b/examples/official-site/sqlpage/migrations/72_set_variable.sql deleted file mode 100644 index 94ae7aad1..000000000 --- a/examples/official-site/sqlpage/migrations/72_set_variable.sql +++ /dev/null @@ -1,64 +0,0 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'set_variable', - '0.40.0', - 'variable', - '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. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'set_variable', - 1, - 'name', - 'The name of the variable to set.', - 'TEXT' - ), - ( - 'set_variable', - 2, - 'value', - 'The value to set the variable to.', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/79_persist_uploaded_files.sql b/examples/official-site/sqlpage/migrations/79_persist_uploaded_files.sql deleted file mode 100644 index 46b83efc9..000000000 --- a/examples/official-site/sqlpage/migrations/79_persist_uploaded_files.sql +++ /dev/null @@ -1,88 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'persist_uploaded_files', - '0.49.0', - 'files', - '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; -``` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'persist_uploaded_files', - 1, - 'files', - 'Name of the form field containing the uploaded files. A field named `photos[]` in the form can be referenced as `photos`.', - 'TEXT' - ), - ( - 'persist_uploaded_files', - 2, - 'destination_folder', - '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).', - 'TEXT' - ), - ( - 'persist_uploaded_files', - 3, - 'allowed_extensions', - '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.', - 'TEXT' - ), - ( - 'persist_uploaded_files', - 4, - 'mode', - 'Optional. Unix permissions to set on the files, in octal notation. By default, "600" (read/write for the owner only).', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql b/examples/official-site/sqlpage/migrations/82_reference_catalog.sql index 81689e61c..b20373b1f 100644 --- a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql +++ b/examples/official-site/sqlpage/migrations/82_reference_catalog.sql @@ -16,18 +16,6 @@ ALTER TABLE sqlpage_functions ADD COLUMN catalog_category TEXT REFERENCES refere ALTER TABLE sqlpage_functions ADD COLUMN catalog_summary TEXT; ALTER TABLE sqlpage_function_parameters ADD COLUMN optional BOOLEAN NOT NULL DEFAULT FALSE; -UPDATE sqlpage_function_parameters SET optional = TRUE WHERE ("function", name) IN ( - ('exec', 'arguments...'), - ('hmac', 'algorithm'), - ('link', 'parameters'), ('link', 'fragment'), - ('oidc_logout_url', 'redirect_uri'), - ('persist_uploaded_file', 'destination_folder'), ('persist_uploaded_file', 'allowed_extensions'), ('persist_uploaded_file', 'mode'), - ('persist_uploaded_files', 'destination_folder'), ('persist_uploaded_files', 'allowed_extensions'), ('persist_uploaded_files', 'mode'), - ('run_sql', 'parameters'), - ('set_variable', 'value'), - ('variables', 'method') -); - INSERT INTO component (name, icon, introduced_in_version, catalog_category) VALUES ('alert', 'alert-triangle', NULL, 'forms-and-feedback'), ('authentication', 'lock', '0.7.2', 'server-logic'), @@ -74,55 +62,6 @@ INSERT INTO component (name, icon, introduced_in_version, catalog_category) VALU ('toast', 'notification', '0.46.0', 'forms-and-feedback'), ('tracking', 'timeline-event-text', '0.18.0', 'display-data'); -WITH copy(name, category, summary) AS (VALUES - ('client_ip', 'request-data', 'Get the IP address of the client making the request.'), - ('cookie', 'request-data', 'Read a named cookie from the incoming request.'), - ('header', 'request-data', 'Read the value of one HTTP request header.'), - ('headers', 'request-data', 'Read all HTTP request headers as a JSON object.'), - ('path', 'request-data', 'Get the URL path of the current request.'), - ('protocol', 'request-data', 'Identify whether the request used HTTP or HTTPS.'), - ('request_body', 'request-data', 'Read the raw request body as text.'), - ('request_body_base64', 'request-data', 'Read a binary request body as a Base64 string.'), - ('request_method', 'request-data', 'Get the HTTP method, such as GET or POST.'), - ('variables', 'request-data', 'Read request or page variables as a JSON object.'), - - ('link', 'links-and-routing', 'Build a page URL with optional query parameters and a fragment.'), - ('regex_match', 'links-and-routing', 'Match text against a regular expression and extract capture groups.'), - ('set_variable', 'links-and-routing', 'Build a link to this page with a query parameter changed or removed.'), - ('url_encode', 'links-and-routing', 'Encode text for use in a URL.'), - - ('persist_uploaded_file', 'files-and-uploads', 'Save an uploaded file and return its path.'), - ('persist_uploaded_files', 'files-and-uploads', 'Save multiple uploads from one field and return their file details.'), - ('read_file_as_data_url', 'files-and-uploads', 'Read a file as a data URL for embedding in a page.'), - ('read_file_as_text', 'files-and-uploads', 'Read the text of a UTF-8 file from the web root.'), - ('uploaded_file_mime_type', 'files-and-uploads', 'Read the media type supplied by the browser for an uploaded file.'), - ('uploaded_file_name', 'files-and-uploads', 'Read the original filename supplied by the browser.'), - ('uploaded_file_path', 'files-and-uploads', 'Get the temporary path of an uploaded file.'), - - ('basic_auth_password', 'identity-and-security', 'Read the password sent with HTTP Basic authentication.'), - ('basic_auth_username', 'identity-and-security', 'Read the username sent with HTTP Basic authentication.'), - ('hash_password', 'identity-and-security', 'Hash a password with Argon2id for storage.'), - ('hmac', 'identity-and-security', 'Sign data with a shared secret using HMAC.'), - ('oidc_logout_url', 'identity-and-security', 'Build a sign-out URL for an OpenID Connect session.'), - ('random_string', 'identity-and-security', 'Generate a cryptographically secure random string.'), - ('user_info', 'identity-and-security', 'Read a named claim for the signed-in user.'), - ('user_info_token', 'identity-and-security', 'Read all claims from the user''s OpenID Connect ID token.'), - - ('fetch', 'external-services', 'Send an HTTP request and read the response body.'), - ('fetch_with_meta', 'external-services', 'Send an HTTP request and read its status, headers, and body.'), - ('send_mail', 'external-services', 'Send email with optional attachments through an SMTP server.'), - - ('configuration_directory', 'server-and-runtime', 'Locate the directory for SQLPage configuration and templates.'), - ('current_working_directory', 'server-and-runtime', 'Get the working directory of the SQLPage server process.'), - ('environment_variable', 'server-and-runtime', 'Read a named environment variable from the server.'), - ('exec', 'server-and-runtime', 'Run a program on the server and capture its output.'), - ('run_sql', 'server-and-runtime', 'Run another SQLPage file and return its rows as JSON.'), - ('version', 'server-and-runtime', 'Read the version of SQLPage serving the page.'), - ('web_root', 'server-and-runtime', 'Locate the directory that holds the site''s public files.') -) -UPDATE sqlpage_functions SET (catalog_category, catalog_summary) = (copy.category, copy.summary) -FROM copy WHERE sqlpage_functions.name = copy.name; - -- The catalog, topic navigation, and reference pages use the same entries and links. CREATE VIEW reference_entry AS WITH entries AS ( diff --git a/scripts/official-site/content.rs b/scripts/official-site/content.rs new file mode 100644 index 000000000..04bb75381 --- /dev/null +++ b/scripts/official-site/content.rs @@ -0,0 +1,43 @@ +use anyhow::{Context, Result, ensure}; +use config::{Config, File, FileFormat}; +use serde::de::DeserializeOwned; +use std::path::{Path, PathBuf}; +use walkdir::WalkDir; + +pub(super) fn markdown_pages( + directory: &Path, +) -> Result> { + let mut pages = Vec::new(); + for entry in WalkDir::new(directory) + .min_depth(1) + .max_depth(1) + .sort_by_file_name() + { + let entry = entry?; + let path = entry.into_path(); + if path.extension().and_then(std::ffi::OsStr::to_str) != Some("md") { + continue; + } + let (metadata, body) = read_page(&path).with_context(|| path.display().to_string())?; + pages.push((path, metadata, body)); + } + ensure!( + !pages.is_empty(), + "No Markdown pages in {}", + directory.display() + ); + Ok(pages) +} + +fn read_page(path: &Path) -> Result<(T, String)> { + let text = super::read(path)?; + let (metadata, body) = text + .strip_prefix("---\n") + .and_then(|text| text.split_once("\n---\n")) + .context("Expected YAML front matter delimited by ---")?; + let metadata = Config::builder() + .add_source(File::from_str(metadata, FileFormat::Yaml)) + .build()? + .try_deserialize()?; + Ok((metadata, body.trim().to_owned())) +} diff --git a/scripts/official-site/functions.rs b/scripts/official-site/functions.rs new file mode 100644 index 000000000..25cd47c94 --- /dev/null +++ b/scripts/official-site/functions.rs @@ -0,0 +1,70 @@ +use super::content::markdown_pages; +use anyhow::{Context, Result, ensure}; +use serde::Deserialize; +use sqlx::{query::query, sqlite::SqliteConnection}; +use std::path::Path; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Function { + icon: Option, + since: Option, + category: String, + summary: String, + return_type: Option, + #[serde(default)] + parameters: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Parameter { + name: String, + r#type: String, + description: String, + #[serde(default)] + required: bool, +} + +pub(super) async fn insert(db: &mut SqliteConnection, site: &Path) -> Result<()> { + for (path, function, body) in + markdown_pages::(&site.join("sqlpage/content/functions"))? + { + let name = path + .file_stem() + .and_then(std::ffi::OsStr::to_str) + .with_context(|| format!("Expected a function name in {}", path.display()))?; + ensure!(!body.is_empty(), "Missing documentation for {name}"); + query( + "INSERT INTO sqlpage_functions (name, icon, description_md, return_type, + introduced_in_version, catalog_category, catalog_summary) VALUES (?, ?, ?, ?, ?, ?, ?)", + ) + .bind(name) + .bind(function.icon) + .bind(body) + .bind(function.return_type) + .bind(function.since) + .bind(function.category) + .bind(function.summary) + .execute(&mut *db) + .await + .with_context(|| format!("Storing function {name}"))?; + for (position, parameter) in (1_i64..).zip(function.parameters) { + query( + "INSERT INTO sqlpage_function_parameters + (\"function\", \"index\", name, description_md, type, optional) + VALUES (?, ?, ?, ?, ?, ?)", + ) + .bind(name) + .bind(position) + .bind(¶meter.name) + .bind(parameter.description.trim()) + .bind(parameter.r#type) + .bind(!parameter.required) + .execute(&mut *db) + .await + .with_context(|| format!("Storing argument {} for {name}", parameter.name))?; + } + } + Ok(()) +} diff --git a/scripts/official-site/main.rs b/scripts/official-site/main.rs index 8069eebc5..0834b13fa 100644 --- a/scripts/official-site/main.rs +++ b/scripts/official-site/main.rs @@ -14,6 +14,8 @@ use std::fs; use std::path::Path; use walkdir::WalkDir; +mod content; + const COMPONENTS: &str = "reference/components"; #[tokio::main(flavor = "current_thread")] @@ -54,6 +56,7 @@ async fn main() -> Result<()> { .with_context(|| path.display().to_string())?; } } + functions::insert(&mut tx, &site).await?; let example_count = stage_site(&site, &output, &mut tx).await?; // Publish the exact sample schema and rows used by the copyable reference queries. let migrations = site.join("sqlpage/migrations"); @@ -152,6 +155,8 @@ async fn stage_site(source: &Path, output: &Path, db: &mut SqliteConnection) -> Ok(example_count) } +mod functions; + async fn verify_examples(db: &mut SqliteConnection, output: &Path, expected: usize) -> Result<()> { let indexed: Vec<(Option, Option)> = query_as( "SELECT e.path, e.source FROM example e JOIN documentation_fts f