Skip to content

Commit bf5b3a0

Browse files
committed
Give request context functions their own reference files
1 parent 172022e commit bf5b3a0

14 files changed

Lines changed: 203 additions & 195 deletions

File tree

‎examples/build_site/content.rs‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,30 @@
1-
use anyhow::{Context, Result};
2-
use serde::de::DeserializeOwned;
1+
use anyhow::{Context, Result, ensure};
2+
use serde::{Deserialize, de::DeserializeOwned};
33
use std::{fs, path::Path};
44

5+
#[derive(Deserialize)]
6+
#[serde(deny_unknown_fields)]
7+
pub(super) struct Parameter {
8+
pub(super) name: String,
9+
pub(super) r#type: String,
10+
pub(super) description: String,
11+
#[serde(default)]
12+
pub(super) required: bool,
13+
}
14+
15+
impl Parameter {
16+
pub(super) fn validate(&self) -> Result<()> {
17+
for (name, value) in [
18+
("name", &self.name),
19+
("type", &self.r#type),
20+
("description", &self.description),
21+
] {
22+
ensure!(!value.trim().is_empty(), "Expected text in {name}");
23+
}
24+
Ok(())
25+
}
26+
}
27+
528
pub(super) fn collection<T: DeserializeOwned>(
629
dir: &Path,
730
file: &str,

‎examples/build_site/functions.rs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use super::{
2+
Seed,
3+
content::{Parameter, pages},
4+
};
5+
use anyhow::Result;
6+
use serde::Deserialize;
7+
use std::path::Path;
8+
9+
#[derive(Default, Deserialize)]
10+
#[serde(deny_unknown_fields)]
11+
struct Function {
12+
icon: Option<String>,
13+
since: Option<String>,
14+
category: Option<String>,
15+
summary: Option<String>,
16+
return_type: Option<String>,
17+
#[serde(default)]
18+
parameters: Vec<Parameter>,
19+
}
20+
21+
pub(super) fn insert(seed: &mut Seed, dir: &Path) -> Result<()> {
22+
pages(dir, |name, f: Function, body| {
23+
seed.row(
24+
"INSERT INTO sqlpage_functions (name, icon, description_md, return_type,
25+
introduced_in_version, catalog_category, catalog_summary) VALUES (?, ?, ?, ?, ?, ?, ?)",
26+
&[&name, &f.icon, &body, &f.return_type, &f.since, &f.category, &f.summary],
27+
)?;
28+
for (index, p) in (1_i64..).zip(f.parameters) {
29+
p.validate()?;
30+
seed.row(
31+
"INSERT INTO sqlpage_function_parameters (\"function\", \"index\", name, description_md, type, optional)
32+
VALUES (?, ?, ?, ?, ?, ?)",
33+
&[&name, &index, &p.name, &p.description, &p.r#type, &!p.required],
34+
)?;
35+
}
36+
Ok(())
37+
})
38+
}

‎examples/build_site/main.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ mod blog;
22
mod configuration;
33
mod content;
44
mod directories;
5+
mod functions;
56
mod seed;
67

78
use anyhow::{Context, Result, bail, ensure};
@@ -94,5 +95,6 @@ async fn documentation_seed(site: &Path) -> Result<String> {
9495
blog::insert(&mut seed, &site.join("content/blog"))?;
9596
configuration::insert(&mut seed)?;
9697
directories::insert(&mut seed, &site.join("content"))?;
98+
functions::insert(&mut seed, &site.join("content/functions"))?;
9799
Ok(seed.finish())
98100
}

‎examples/official-site/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ Edit `content/guides.yaml` for the guides list and `content/projects.yaml` for t
4040
example project cards. A project's `folder` must match its folder under
4141
[`examples/`](../).
4242

43+
## Function reference
44+
45+
Function pages in `content/functions/` use their filename as the public function
46+
name. Keep the argument list in signature order and mark mandatory arguments with
47+
`required: true`. The Markdown body can include SQL examples without escaping.
48+
Older entries still live in the SQL migrations.
49+
4350
## Landing page
4451

4552
The home page is rendered by `index.sql` and the `landing-page` custom template.

examples/official-site/sqlpage/migrations/57_client_ip.sql renamed to examples/official-site/content/functions/client_ip.md

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,11 @@
1-
INSERT INTO
2-
sqlpage_functions (
3-
"name",
4-
"introduced_in_version",
5-
"icon",
6-
"description_md"
7-
)
8-
VALUES
9-
(
10-
'client_ip',
11-
'0.33.0',
12-
'network',
13-
'Returns the IP address of the client making the HTTP request.
1+
---
2+
icon: network
3+
since: 0.33.0
4+
category: request-data
5+
summary: Get the IP address of the client making the request.
6+
---
7+
8+
Returns the IP address of the client making the HTTP request.
149

1510
### Example
1611

@@ -28,19 +23,17 @@ The function returns:
2823

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

3429
Example with reverse proxy:
3530
```sql
3631
-- Choose the appropriate header based on your setup
3732
select coalesce(
38-
sqlpage.header(''x-forwarded-for''),
39-
sqlpage.header(''x-real-ip''),
33+
sqlpage.header('x-forwarded-for'),
34+
sqlpage.header('x-real-ip'),
4035
sqlpage.client_ip()
4136
) as real_client_ip;
4237
```
4338

4439
For security-critical applications, ensure your reverse proxy is properly configured to set and validate these headers.
45-
'
46-
);
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
icon: cookie
3+
since: 0.7.1
4+
category: request-data
5+
summary: Read a named cookie from the incoming request.
6+
return_type: TEXT
7+
parameters:
8+
- name: name
9+
type: TEXT
10+
required: true
11+
description: The name of the cookie to read.
12+
---
13+
14+
Reads a [cookie](https://en.wikipedia.org/wiki/HTTP_cookie) with the given name from the request.
15+
Returns the value of the cookie as text, or NULL if the cookie is not present.
16+
17+
Cookies can be set using the [cookie component](documentation.sql?component=cookie#component).
18+
19+
### Example
20+
21+
#### Set a cookie
22+
23+
Set a cookie called `username` to greet the user by name every time they visit the page:
24+
25+
```sql
26+
select 'cookie' as component, 'username' as name, :username as value;
27+
28+
SELECT 'form' as component;
29+
SELECT 'username' as name, 'text' as type;
30+
```
31+
32+
#### Read a cookie
33+
34+
Read a cookie called `username` and greet the user by name:
35+
36+
```sql
37+
SELECT 'text' as component,
38+
'Hello, ' || sqlpage.cookie('username') || '!' as contents;
39+
```
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
icon: heading
3+
since: 0.7.2
4+
category: request-data
5+
summary: Read the value of one HTTP request header.
6+
parameters:
7+
- name: name
8+
type: TEXT
9+
required: true
10+
description: The name of the HTTP header to read.
11+
---
12+
13+
Reads a [header](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) with the given name from the request.
14+
Returns the value of the header as text, or NULL if the header is not present.
15+
16+
### Example
17+
18+
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:
19+
20+
```sql
21+
INSERT INTO user_agent_log (user_agent) VALUES (sqlpage.header('user-agent'));
22+
```
23+
24+
If you need access to all headers at once, use [`sqlpage.headers()`](?function=headers) instead.

examples/official-site/sqlpage/migrations/56_headers.sql renamed to examples/official-site/content/functions/headers.md

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,25 @@
1-
INSERT INTO sqlpage_functions (
2-
"name",
3-
"introduced_in_version",
4-
"icon",
5-
"description_md"
6-
)
7-
VALUES (
8-
'headers',
9-
'0.33.0',
10-
'circle-dotted-letter-h',
11-
'Returns all HTTP request headers as a JSON object.
1+
---
2+
icon: circle-dotted-letter-h
3+
since: 0.33.0
4+
category: request-data
5+
summary: Read all HTTP request headers as a JSON object.
6+
---
7+
8+
Returns all HTTP request headers as a JSON object.
129

1310
### Example
1411

1512
The following displays all HTTP request headers in a list,
16-
using SQLite''s `json_each()` function.
13+
using SQLite's `json_each()` function.
1714

1815
```sql
19-
select ''list'' as component;
16+
select 'list' as component;
2017

2118
select key as title, value as description
2219
from json_each(sqlpage.headers()); -- json_each() is SQLite only
2320
```
2421

25-
If not on SQLite, use your [database''s JSON function](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide).
22+
If not on SQLite, use your [database's JSON function](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide).
2623

2724
### Details
2825

@@ -36,4 +33,3 @@ This is useful when you need to:
3633
- Access multiple headers at once
3734

3835
If you only need access to a single known header, use [`sqlpage.header(name)`](?function=header) instead.
39-
');
Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
INSERT INTO sqlpage_functions (
2-
"name",
3-
"introduced_in_version",
4-
"icon",
5-
"description_md"
6-
)
7-
VALUES (
8-
'path',
9-
'0.15.0',
10-
'slashes',
11-
'Returns the request path of the current page.
1+
---
2+
icon: slashes
3+
since: 0.15.0
4+
category: request-data
5+
summary: Get the URL path of the current request.
6+
---
7+
8+
Returns the request path of the current page.
129
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.
1310

1411
### Example
@@ -17,10 +14,9 @@ If we have a page in a file named `my page.sql` at the root of your SQLPage inst
1714
then the following SQL query:
1815

1916
```sql
20-
select ''text'' as component, sqlpage.path() as contents;
17+
select 'text' as component, sqlpage.path() as contents;
2118
```
2219

2320
will return `/my%20page.sql`.
2421

2522
> Note that the path is URL-encoded.
26-
');
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
icon: network
3+
since: 0.17.1
4+
category: request-data
5+
summary: Identify whether the request used HTTP or HTTPS.
6+
---
7+
8+
Returns the protocol that was used to access the current page.
9+
10+
This can be either `http` or `https`.
11+
12+
This is useful to generate links to the current page.
13+
14+
### Example
15+
16+
```sql
17+
select 'text' as component,
18+
sqlpage.protocol() || '://' || sqlpage.header('host') || sqlpage.path() as contents;
19+
```
20+
21+
will return `https://example.com/example.sql`.
22+
23+
> Note that the path is URL-encoded. The protocol is resolved in this order:
24+
> - `Forwarded` header
25+
> - `X-Forwarded-Proto` header
26+
> request target / URI

0 commit comments

Comments
 (0)