Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions examples/official-site/content/functions/basic_auth_password.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
icon: key
since: 0.7.2
category: identity-and-security
summary: Read the password sent with HTTP Basic authentication.
return_type: TEXT
---

Returns the password from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request.
If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials.

### Example

```sql
SELECT 'authentication' AS component,
(SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash,
sqlpage.basic_auth_password() AS password;
```
18 changes: 18 additions & 0 deletions examples/official-site/content/functions/basic_auth_username.md
Original file line number Diff line number Diff line change
@@ -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;
```
39 changes: 39 additions & 0 deletions examples/official-site/content/functions/client_ip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
icon: network
since: 0.33.0
category: request-data
summary: Get the IP address of the client making the request.
---

Returns the IP address of the client making the HTTP request.

### Example

```sql
insert into connection_log (client_ip) values (sqlpage.client_ip());
```

### Details

The function returns:
- The IP address of the client as a string
- `null` if the client IP cannot be determined (e.g., when serving through a Unix socket)

### ⚠️ Important Notes for Production Use

When [running behind a reverse proxy](/your-first-sql-website/nginx.sql) (e.g., Nginx, Apache, Cloudflare):
- This function will return the IP address of the reverse proxy, not the actual client
- To get the real client IP, use [`sqlpage.header`](?function=header): `sqlpage.header('x-forwarded-for')` or `sqlpage.header('x-real-ip')`
- The exact header name depends on your reverse proxy configuration

Example with reverse proxy:
```sql
-- Choose the appropriate header based on your setup
select coalesce(
sqlpage.header('x-forwarded-for'),
sqlpage.header('x-real-ip'),
sqlpage.client_ip()
) as real_client_ip;
```

For security-critical applications, ensure your reverse proxy is properly configured to set and validate these headers.
Original file line number Diff line number Diff line change
@@ -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.
39 changes: 39 additions & 0 deletions examples/official-site/content/functions/cookie.md
Original file line number Diff line number Diff line change
@@ -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;
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
icon: folder-question
since: 0.11.0
category: server-and-runtime
summary: Get the working directory of the SQLPage server process.
---

Returns the [current working directory](https://en.wikipedia.org/wiki/Working_directory) of the SQLPage server process.

### Example

```sql
SELECT 'text' AS component;
SELECT 'Currently running from ' AS contents;
SELECT sqlpage.current_working_directory() as contents, true as code;
```

#### Result

Currently running from `/home/user/my_sqlpage_website`

#### Notes

The current working directory is the directory from which the SQLPage server process was started.
By default, this is also the directory from which `.sql` files are loaded and served.
However, this can be changed by setting the `web_root` [configuration option](/configuration#web_root).
21 changes: 21 additions & 0 deletions examples/official-site/content/functions/environment_variable.md
Original file line number Diff line number Diff line change
@@ -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;
```
42 changes: 42 additions & 0 deletions examples/official-site/content/functions/exec.md
Original file line number Diff line number Diff line change
@@ -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.
129 changes: 129 additions & 0 deletions examples/official-site/content/functions/fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
---
icon: transfer-vertical
since: 0.20.3
category: external-services
summary: Send an HTTP request and read the response body.
parameters:
- name: url
type: TEXT
required: true
description: Either a string containing an URL to request, or a json object in the standard format of the
request interface of the web fetch API.
---

Sends an HTTP request and returns the results as a string.

## HTTP request examples

### Simple GET query

In this example, we use an API call to find the latitude and longitude of a place
the user searched for, and we display it on a map.

We use the simplest form of the fetch function, that takes the URL to fetch as a string.


```sql
set url = 'https://nominatim.openstreetmap.org/search?format=json&q=' || sqlpage.url_encode($user_search)
set api_results = sqlpage.fetch($url);

select 'map' as component;
select $user_search as title,
CAST($api_results->>0->>'lat' AS FLOAT) as latitude,
CAST($api_results->>0->>'lon' AS FLOAT) as longitude;
```

### POST query with a body

In this example, we use the complex form of the function to make an
authenticated POST request, with custom request headers and a custom request body.

We use SQLite's json functions to build the request body.
See [the list of SQL databases and their JSON functions](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) for
more information on how to build JSON objects in your database.

```sql
set request = json_object(
'method', 'POST',
'url', 'https://postman-echo.com/post',
'headers', json_object(
'Content-Type', 'application/json',
'Authorization', 'Bearer ' || sqlpage.environment_variable('MY_API_TOKEN')
),
'body', json_object(
'Hello', 'world'
)
);
set api_results = sqlpage.fetch($request);

select 'code' as component;
select
'API call results' as title,
'json' as language,
$api_results as contents;
```


### Authenticated request using Basic Auth

Here's how to make a request to an API that requires [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication):

```sql
set request = json_object(
'url', 'https://api.example.com/data',
'username', 'my_username',
'password', 'my_password'
);
set api_results = sqlpage.fetch($request);
```

> This will add the `Authorization: Basic bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQK` header to the request,
> where `bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQK` is the base64 encoding of the string `my_username:my_password`.

## JSON parameter format

The fetch function accepts either a URL string, or a JSON object with the following parameters:
- `url`: The URL to fetch. Required.
- `method`: The HTTP method to use. Defaults to `GET`.
- `headers`: A JSON object with the headers to send. Defaults to sending a User-Agent header containing the SQLPage version.
- `body`: The body of the request. If it is a JSON object, it will be sent as JSON. If it is a string, it will be sent as is. When omitted, no request body is sent.
- `timeout_ms`: The maximum time to wait for the request, in milliseconds. Defaults to 5000.
- `username`: Optional username for HTTP Basic Authentication. Introduced in version 0.33.0.
- `password`: Optional password for HTTP Basic Authentication. Only used if username is provided. Introduced in version 0.33.0.
- `response_encoding`: Optional charset to use for decoding the response body. Defaults to `utf8`, or `base64` if the response contains binary data. All [standard web encodings](https://encoding.spec.whatwg.org/#concept-encoding-get) are supported, plus `hex`, `base64`, and `base64url`. Introduced in version 0.37.0.

## Error handling and reading response headers

If the request fails, this function throws an error, that will be displayed to the user.
The response headers are not available for inspection.

## Conditional data fetching

Since v0.40, `sqlpage.fetch(null)` returns null instead of throwing an error.
This makes it easier to conditionnally query an API:

```sql
set current_field_value = (select field from my_table where id = 1);
set target_url = nullif('http://example.com/api/field/1', null); -- null if the field is currently null in the db
set api_value = sqlpage.fetch($target_url); -- no http request made if the field is not null in the db
update my_table set field = $api_value where id = 1 and $api_value is not null; -- update the field only if it was not present before
```

You can also make the HTTP request depend on whether a database query returns a row.
When `fetch` is a standalone selected column, SQLPage runs it only for rows returned by the database:

```sql
set api_value = (
select sqlpage.fetch(url)
from cache_misses
where key = $key
);
```

If `cache_misses` has no matching row, no HTTP request is made and `$api_value` is set to `NULL`.
If the query returns more than one row or more than one column, SQLPage returns a clear scalar `SET` error.

## Advanced usage

If you need to handle errors or inspect the response headers or the status code,
use [`sqlpage.fetch_with_meta`](?function=fetch_with_meta).
Loading
Loading