...)` 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/content/functions/request_body.md b/examples/official-site/content/functions/request_body.md
new file mode 100644
index 000000000..724a327c4
--- /dev/null
+++ b/examples/official-site/content/functions/request_body.md
@@ -0,0 +1,72 @@
+---
+icon: http-post
+since: 0.33.0
+category: request-data
+summary: Read the raw request body as text.
+---
+
+Returns the raw request body as a string.
+
+A client (like a web browser, mobile app, or another server) can send information to your server in the request body.
+This function allows you to read that information in your SQL code,
+in order to create or update a resource in your database for instance.
+
+The request body is commonly used when building **REST APIs** (machines-to-machines interfaces)
+that receive data from the client.
+
+This is especially useful in:
+- `POST` and `PUT` requests for creating or updating resources in your database
+- Any API endpoint that needs to receive complex data
+
+### Example: Building a REST API
+
+Here's an example of building an API endpoint that receives a json object,
+and inserts it into a database.
+
+#### `api/create_user.sql`
+```sql
+-- Get the raw JSON body
+set user_data = sqlpage.request_body();
+
+-- Insert the user into database
+with parsed_data as (
+ select
+ json_extract($user_data, '$.name') as name,
+ json_extract($user_data, '$.email') as email
+)
+insert into users (name, email)
+select name, email from parsed_data;
+
+-- Return success response
+select 'json' as component,
+ json_object(
+ 'status', 'success',
+ 'message', 'User created successfully'
+ ) as contents;
+```
+
+### Testing the API
+
+You can test this API using curl:
+```bash
+curl -X POST http://localhost:8080/api/create_user \
+ -H "Content-Type: application/json" \
+ -d '{"name": "John", "email": "john@example.com"}'
+```
+
+## Special cases
+
+### NULL
+
+This function returns NULL if:
+ - There is no request body
+ - The request content type is `application/x-www-form-urlencoded` or `multipart/form-data`
+ (in these cases, use [`sqlpage.variables('post')`](?function=variables) instead)
+
+### Binary data
+
+If the request body is not valid text encoded in UTF-8,
+invalid characters are replaced with the Unicode replacement character `�` (U+FFFD).
+
+If you need to handle binary data,
+use [`sqlpage.request_body_base64()`](?function=request_body_base64) instead.
diff --git a/examples/official-site/content/functions/request_body_base64.md b/examples/official-site/content/functions/request_body_base64.md
new file mode 100644
index 000000000..47cac0860
--- /dev/null
+++ b/examples/official-site/content/functions/request_body_base64.md
@@ -0,0 +1,52 @@
+---
+icon: photo-up
+since: 0.33.0
+category: request-data
+summary: Read a binary request body as a Base64 string.
+---
+
+Returns the raw request body encoded in base64. This is useful when receiving binary data or when you need to handle non-text content in your API endpoints.
+
+## Base64 encoding
+
+Base64 is a way to encode binary data (like images or files) into text that can be safely stored and transmitted. This function automatically converts the incoming request body into this format.
+
+## Receiving binary data in an API
+
+This example shows how to receive and process an image uploaded directly in the request body:
+
+```sql
+-- Assuming this is api/upload_image.sql
+-- Client would send a POST request with the raw image data
+
+-- Get the base64-encoded image data
+set image_data = sqlpage.request_body_base64();
+
+-- Store the image data in the database
+insert into images (data, uploaded_at)
+values ($image_data, current_timestamp);
+
+-- Return success response
+select 'json' as component,
+ json_object(
+ 'status', 'success',
+ 'message', 'Image uploaded successfully'
+ ) as contents;
+```
+
+You can test this API using curl:
+```bash
+curl -X POST http://localhost:8080/api/upload_image.sql \
+ -H "Content-Type: application/octet-stream" \
+ --data-binary "@/path/to/image.jpg"
+```
+
+This is particularly useful when:
+- Working with binary data (images, files, etc.)
+- The request body contains non-UTF8 characters
+- You need to pass the raw body to another system that expects base64
+
+> Note: Like [`sqlpage.request_body()`](?function=request_body), this function returns NULL if:
+> - There is no request body
+> - The request content type is `application/x-www-form-urlencoded` or `multipart/form-data`
+> (in these cases, use [`sqlpage.variables('post')`](?function=variables) instead)
diff --git a/examples/official-site/sqlpage/migrations/43_request_method.sql b/examples/official-site/content/functions/request_method.md
similarity index 65%
rename from examples/official-site/sqlpage/migrations/43_request_method.sql
rename to examples/official-site/content/functions/request_method.md
index e5868b6d8..2c415d4bf 100644
--- a/examples/official-site/sqlpage/migrations/43_request_method.sql
+++ b/examples/official-site/content/functions/request_method.md
@@ -1,16 +1,11 @@
-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
@@ -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/content/functions/run_sql.md
similarity index 67%
rename from examples/official-site/sqlpage/migrations/38_run_sql.sql
rename to examples/official-site/content/functions/run_sql.md
index 314755f2e..9a077cc29 100644
--- a/examples/official-site/sqlpage/migrations/38_run_sql.sql
+++ b/examples/official-site/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/content/functions/send_mail.md
similarity index 80%
rename from examples/official-site/sqlpage/migrations/75_send_mail.sql
rename to examples/official-site/content/functions/send_mail.md
index 01d6281c0..4bbadd98c 100644
--- a/examples/official-site/sqlpage/migrations/75_send_mail.sql
+++ b/examples/official-site/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/content/functions/set_variable.md b/examples/official-site/content/functions/set_variable.md
new file mode 100644
index 000000000..1b1692e49
--- /dev/null
+++ b/examples/official-site/content/functions/set_variable.md
@@ -0,0 +1,41 @@
+---
+icon: variable
+since: 0.40.0
+category: links-and-routing
+summary: Build a link to this page with a query parameter changed or removed.
+parameters:
+ - name: name
+ type: TEXT
+ required: true
+ description: The name of the variable to set.
+ - name: value
+ type: TEXT
+ description: The value to set the variable to.
+---
+
+Returns a URL that is the same as the current page's URL, but with a variable set to a new value.
+
+This function is useful when you want to create a link that changes a parameter on the current page, while preserving other parameters.
+
+It is equivalent to `sqlpage.link(sqlpage.path(), json_patch(sqlpage.variables('get'), json_object(name, value)))`.
+
+### Example
+
+Let's say you have a list of products, and you want to filter them by category. You can use `sqlpage.set_variable` to create links that change the category filter, without losing other potential filters (like a search query or a sort order).
+
+```sql
+select 'button' as component, 'sm' as size, 'center' as justify;
+select
+ category as title,
+ sqlpage.set_variable('category', category) as link,
+ case when $category = category then 'primary' else 'secondary' end as color
+from categories;
+```
+
+When `sqlpage.set_variable(...)` is used as a standalone selected column in a query that returns several rows, it runs once per returned row.
+This is useful for generating one link per row, as in the example above.
+If you need a single link reused later in the page, store it with `SET` first.
+
+### Parameters
+ - `name` (TEXT): The name of the variable to set.
+ - `value` (TEXT): The value to set the variable to. If `NULL` is passed, the variable is removed from the URL.
diff --git a/examples/official-site/content/functions/uploaded_file_mime_type.md b/examples/official-site/content/functions/uploaded_file_mime_type.md
new file mode 100644
index 000000000..7114f3a9a
--- /dev/null
+++ b/examples/official-site/content/functions/uploaded_file_mime_type.md
@@ -0,0 +1,41 @@
+---
+icon: file-settings
+since: 0.18.0
+category: files-and-uploads
+summary: Read the media type supplied by the browser for an uploaded file.
+parameters:
+ - name: name
+ type: TEXT
+ required: true
+ description: Name of the file input field in the form.
+---
+
+Returns the MIME type of an uploaded file.
+
+## Example: handling a picture upload
+
+When letting the user upload a picture, you may want to check that the uploaded file is indeed an image.
+
+```sql
+select 'redirect' as component,
+ 'invalid_file.sql' as link
+where sqlpage.uploaded_file_mime_type('myfile') not like 'image/%';
+```
+
+In `invalid_file.sql`, you can display an error message to the user:
+
+```sql
+select 'alert' as component, 'Error' as title,
+ 'Invalid file type' as description,
+ 'alert-circle' as icon, 'red' as color;
+```
+
+## Example: white-listing file types
+
+You could have a database table containing the allowed MIME types, and check that the uploaded file is of one of those types:
+
+```sql
+select 'redirect' as component,
+ 'invalid_file.sql' as link
+where sqlpage.uploaded_file_mime_type('myfile') not in (select mime_type from allowed_mime_types);
+```
diff --git a/examples/official-site/content/functions/uploaded_file_name.md b/examples/official-site/content/functions/uploaded_file_name.md
new file mode 100644
index 000000000..82f0fc169
--- /dev/null
+++ b/examples/official-site/content/functions/uploaded_file_name.md
@@ -0,0 +1,54 @@
+---
+icon: file-description
+since: 0.23.0
+category: files-and-uploads
+summary: Read the original filename supplied by the browser.
+parameters:
+ - name: name
+ type: TEXT
+ required: true
+ description: Name of the file input field in the form.
+---
+
+Returns the `filename` value in the `content-disposition` header.
+
+## Example: saving uploaded file metadata for later download
+
+### Making a form
+
+```sql
+select 'form' as component, 'handle_file_upload.sql' as action;
+select 'myfile' as name, 'file' as type, 'File' as label;
+```
+
+### Handling the form response
+
+### Inserting an arbitrary file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database
+
+In `handle_file_upload.sql`, one can process the form results like this:
+
+```sql
+insert into uploaded_files (fname, content, uploaded) values (
+ sqlpage.uploaded_file_name('myfile'),
+ sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('myfile')),
+ CURRENT_TIMESTAMP
+);
+```
+
+> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files.
+
+### Downloading the uploaded files
+
+The file can be downloaded by clicking a link like this:
+```sql
+select 'button' as component;
+select name as title, content as link from uploaded_files where name = $file_name limit 1;
+```
+
+> *Note*: because the file is ecoded as a data uri, the file is transferred to the client whether or not the link is clicked
+
+### Large files
+
+See the [`sqlpage.uploaded_file_path`](?function=uploaded_file_path#function) function.
+
+See the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function.
diff --git a/examples/official-site/content/functions/uploaded_file_path.md b/examples/official-site/content/functions/uploaded_file_path.md
new file mode 100644
index 000000000..4f12188ce
--- /dev/null
+++ b/examples/official-site/content/functions/uploaded_file_path.md
@@ -0,0 +1,72 @@
+---
+icon: upload
+since: 0.17.0
+category: files-and-uploads
+summary: Get the temporary path of an uploaded file.
+parameters:
+ - name: name
+ type: TEXT
+ required: true
+ description: Name of the file input field in the form.
+---
+
+Returns the path to a temporary file containing the contents of an uploaded file.
+
+## Example: handling a picture upload
+
+### Making a form
+
+```sql
+select 'form' as component, 'handle_picture_upload.sql' as action;
+select 'myfile' as name, 'file' as type, 'Picture' as label;
+select 'title' as name, 'text' as type, 'Title' as label;
+```
+
+### Handling the form response
+
+### Inserting an image file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database
+
+In `handle_picture_upload.sql`, one can process the form results like this:
+
+```sql
+insert into pictures (title, path) values (:title, sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('myfile')));
+```
+
+> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files.
+
+### Inserting file contents as text into the database
+
+When the uploaded file is a simple raw text file (e.g. a `.txt` file),
+one can use the [`sqlpage.read_file_as_text`](?function=read_file_as_text#function)
+function to insert the contents of the file into the database like this:
+
+```sql
+insert into text_documents (title, path) values (:title, sqlpage.read_file_as_text(sqlpage.uploaded_file_path('my_text_file')));
+```
+
+### Saving the uploaded file to a permanent location
+
+When the uploaded file is larger than a few megabytes, it is not recommended to store it in the database.
+Instead, one can save the file to a permanent location on the server, and store the path to the file in the database.
+
+You can move the file to a permanent location using the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function.
+### Advanced file handling
+
+For more advanced file handling, such as uploading files to a cloud storage service,
+you can write a small script in your favorite programming language,
+and call it using the [`sqlpage.exec`](?function=exec#function) function.
+
+For instance, one could save the following small bash script to `/usr/local/bin/upload_to_s3`:
+
+```bash
+#!/bin/bash
+aws s3 cp "$1" s3://your-s3-bucket-name/
+echo "https://your-s3-bucket-url/$(basename "$1")"
+```
+
+Then, you can call it from SQL like this:
+
+```sql
+set url = sqlpage.exec('upload_to_s3', sqlpage.uploaded_file_path('myfile'));
+insert into uploaded_files (title, path) values (:title, $url);
+```
diff --git a/examples/official-site/content/functions/url_encode.md b/examples/official-site/content/functions/url_encode.md
new file mode 100644
index 000000000..f9adb2818
--- /dev/null
+++ b/examples/official-site/content/functions/url_encode.md
@@ -0,0 +1,24 @@
+---
+icon: percentage
+since: 0.12.0
+category: links-and-routing
+summary: Encode text for use in a URL.
+parameters:
+ - name: string
+ type: TEXT
+ required: true
+ description: The string to encode.
+---
+
+Returns the given string, with all characters that are not allowed in a URL encoded.
+
+### Example
+
+```sql
+select 'text' as component;
+select 'https://example.com/?q=' || sqlpage.url_encode($user_search) as contents;
+```
+
+#### Result
+
+`https://example.com/?q=hello%20world`
diff --git a/examples/official-site/content/functions/user_info.md b/examples/official-site/content/functions/user_info.md
new file mode 100644
index 000000000..d63d9b24c
--- /dev/null
+++ b/examples/official-site/content/functions/user_info.md
@@ -0,0 +1,104 @@
+---
+icon: user
+since: 0.34.0
+category: identity-and-security
+summary: Read a named claim for the signed-in user.
+parameters:
+ - name: claim
+ type: TEXT
+ required: true
+ description: The name of the user information to retrieve. Common values include 'name', 'email', 'picture',
+ 'sub', 'preferred_username', 'given_name', and 'family_name'. The exact values available depend on your
+ OIDC provider and configuration.
+---
+
+The `sqlpage.user_info` function is a convenient way to access specific pieces of information about the currently logged-in user.
+When you [configure Single Sign-On](/sso), your OIDC provider will issue an [ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) for the user,
+which contains *claims*, with information about the user.
+
+Calling `sqlpage.user_info(claim_name)` lets you access these claims directly from SQL.
+
+## Read a claim
+
+The function takes one parameter: the name of the *claim* (the piece of information you want to retrieve).
+
+For example, to display a personalized welcome message, with the user's name, you can use:
+
+```sql
+select 'text' as component;
+select 'Welcome, ' || sqlpage.user_info('name') || '!' as title;
+```
+
+## Available Information
+
+The exact information available depends on your identity provider (the service you chose to authenticate with),
+its configuration, and the scopes you requested.
+Use [`sqlpage.user_info_token()`](?function=user_info_token) to see all the information available in the ID token of the current user.
+
+Here are some commonly available fields:
+
+### Basic Information
+- `name`: The user's full name (usually first and last name separated by a space)
+- `email`: The user's email address (*warning*: there is no guarantee that the user currently controls this email address. Use the `sub` claim for database references instead.)
+- `picture`: URL to the user's profile picture
+
+### User Identifiers
+- `sub`: A unique identifier for the user (use this to uniquely identify the user in your database)
+- `preferred_username`: The username the user prefers to use
+
+### Name Components
+- `given_name`: The user's first name
+- `family_name`: The user's last name
+
+## Examples
+
+### Personalized Welcome Message
+```sql
+select 'text' as component,
+ 'Welcome back, **' || sqlpage.user_info('given_name') || '**!' as contents_md;
+```
+
+### User Profile Card
+```sql
+select 'card' as component;
+select
+ sqlpage.user_info('name') as title,
+ sqlpage.user_info('email') as description,
+ sqlpage.user_info('picture') as image;
+```
+
+### Conditional Content Based on custom claims
+
+Some identity providers let you add custom claims to the ID token.
+This lets you customize the behavior of your application based on arbitrary user attributes,
+such as the user's role.
+
+```sql
+-- show everything to admins, only public items to others
+select 'list' as component;
+select title from my_items
+ where is_public or sqlpage.user_info('role') = 'admin'
+```
+
+## Security Best Practices
+
+> ⚠️ **Important**: Always use the `sub` claim to identify users in your database, not their email address.
+> The `sub` claim is guaranteed to be unique and stable for each user, while email addresses can change.
+> In most providers, receiving an id token with a given email does not guarantee that the user currently controls that email.
+
+```sql
+-- Store the user's ID in your database
+insert into user_preferences (user_id, theme)
+values (sqlpage.user_info('sub'), 'dark');
+```
+
+## Troubleshooting
+
+If you're not getting the information you expect:
+
+1. Check that OIDC is properly configured in your `sqlpage.json`
+2. Verify that you requested the right scopes in your OIDC configuration
+3. Try using `sqlpage.user_info_token()` to see all available information
+4. Check your OIDC provider's documentation for the exact claim names they use
+
+Remember: If the user is not logged in or the requested information is not available, this function returns NULL.
diff --git a/examples/official-site/content/functions/user_info_token.md b/examples/official-site/content/functions/user_info_token.md
new file mode 100644
index 000000000..5d6ecc7d6
--- /dev/null
+++ b/examples/official-site/content/functions/user_info_token.md
@@ -0,0 +1,39 @@
+---
+icon: key
+since: 0.35.0
+category: identity-and-security
+summary: Read all claims from the user's OpenID Connect ID token.
+---
+
+This function can be used only when you have [configured Single Sign-On with an OIDC provider](/sso).
+
+## The ID Token
+
+When a user logs in through OIDC, your application receives an [identity token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) from the identity provider.
+This token contains information about the user, such as their name and email address.
+The `sqlpage.user_info_token()` function lets you access the entire contents of the ID token, as a JSON object.
+You can then use [your database's JSON functions](/blog.sql?post=JSON+in+SQL%3A+A+Comprehensive+Guide) to process that JSON.
+
+If you need to access a specific claim, it is easier and more performant to use the
+[`sqlpage.user_info()`](?function=user_info) function instead.
+
+## Displaying user claims
+
+```sql
+select 'list' as component;
+select key as title, value as description
+from json_each(sqlpage.user_info_token());
+```
+
+This sqlite-specific example will show all the information available about the current user, such as:
+- `sub`: A unique identifier for the user
+- `name`: The user's full name
+- `email`: The user's email address
+- `picture`: A URL to the user's profile picture
+
+## Security notes
+
+- The ID token is automatically verified by SQLPage to ensure it hasn't been tampered with.
+- The token is only available to authenticated users: if no user is logged in or sso is not configured, this function returns NULL
+- If some information is not available in the token, you have to configure it on your OIDC provider, SQLPage can't do anything about it.
+- The token is stored in a signed http-only cookie named `sqlpage_auth`. You can use [the cookie component](/component.sql?component=cookie) to delete it, and the user will be redirected to the login page on the next page load.
diff --git a/examples/official-site/sqlpage/migrations/20_variables_function.sql b/examples/official-site/content/functions/variables.md
similarity index 57%
rename from examples/official-site/sqlpage/migrations/20_variables_function.sql
rename to examples/official-site/content/functions/variables.md
index 792285695..a7c48f161 100644
--- a/examples/official-site/sqlpage/migrations/20_variables_function.sql
+++ b/examples/official-site/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: 'Optional. Filter variables by source: ''get'' (URL parameters), ''post'' (form data), or
+ ''set'' (user-defined variables). When not provided, all variables are returned with SET variables taking
+ precedence over request parameters.'
+---
+
+Returns a JSON string containing variables from the HTTP request and user-defined variables.
+
+The [database's json handling functions](/blog?post=JSON+in+SQL%3A+A+Comprehensive+Guide) can then be used to process the data.
## Variable Types
@@ -26,9 +28,9 @@ 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`
When a SET variable has the same name as a GET or POST variable, the SET variable takes precedence in the combined result.
@@ -39,13 +41,13 @@ When a SET variable has the same name as a GET or POST variable, the SET variabl
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.
@@ -54,7 +56,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
@@ -64,7 +66,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);
```
@@ -73,7 +75,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
@@ -88,32 +90,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',
- 'Optional. Filter variables by source: ''get'' (URL parameters), ''post'' (form data), or ''set'' (user-defined variables). When not provided, all variables are returned with SET variables taking precedence over request parameters.',
- 'TEXT'
-);
diff --git a/examples/official-site/content/functions/version.md b/examples/official-site/content/functions/version.md
new file mode 100644
index 000000000..4a5327aaa
--- /dev/null
+++ b/examples/official-site/content/functions/version.md
@@ -0,0 +1,8 @@
+---
+icon: git-commit
+since: 0.11.0
+category: server-and-runtime
+summary: Read the version of SQLPage serving the page.
+---
+
+Returns the current version of SQLPage as a string.
diff --git a/examples/official-site/content/functions/web_root.md b/examples/official-site/content/functions/web_root.md
new file mode 100644
index 000000000..e56340181
--- /dev/null
+++ b/examples/official-site/content/functions/web_root.md
@@ -0,0 +1,30 @@
+---
+icon: folder-code
+since: 0.42.0
+category: server-and-runtime
+summary: Locate the directory that holds the site's public files.
+---
+
+Returns the web root directory where SQLPage serves `.sql` files from.
+
+### Example
+
+```sql
+SELECT 'text' AS component;
+SELECT 'SQL files are served from ' AS contents;
+SELECT sqlpage.web_root() as contents, true as code;
+```
+
+#### Result
+
+SQL files are served from `/home/user/my_sqlpage_website`
+
+#### Notes
+
+The web root is the directory from which `.sql` files are loaded and served.
+By default, it is the current working directory, but it can be changed using:
+ - the `--web-root` command line argument
+ - the `web_root` [configuration option](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/content/guides.yaml b/examples/official-site/content/guides.yaml
new file mode 100644
index 000000000..025aef47f
--- /dev/null
+++ b/examples/official-site/content/guides.yaml
@@ -0,0 +1,28 @@
+- sort_order: 1
+ title: Your first website
+ link: /your-first-sql-website/
+ description: Install SQLPage and build a website from a SQL file.
+- sort_order: 2
+ title: SQL and variables
+ link: /extensions-to-sql.sql
+ description: Read request parameters, set variables, and call SQLPage functions.
+- sort_order: 3
+ title: Custom components
+ link: /custom_components.sql
+ description: Render your own HTML with Handlebars templates.
+- sort_order: 4
+ title: Database migrations
+ link: /your-first-sql-website/migrations.sql
+ description: Create and update your database schema with versioned SQL files.
+- sort_order: 5
+ title: Custom URLs
+ link: /your-first-sql-website/custom_urls.sql
+ description: Give your pages readable URLs and route requests to SQL files.
+- sort_order: 6
+ title: Reverse proxy
+ link: /your-first-sql-website/nginx.sql
+ description: Serve your site with Nginx and HTTPS.
+- sort_order: 7
+ title: Managed hosting
+ link: /your-first-sql-website/hosted.sql
+ description: Try SQLPage online or publish your website with DataPage.
diff --git a/examples/official-site/content/projects.yaml b/examples/official-site/content/projects.yaml
new file mode 100644
index 000000000..2dcd2f96a
--- /dev/null
+++ b/examples/official-site/content/projects.yaml
@@ -0,0 +1,68 @@
+- title: Advanced Authentication
+ folder: user-authentication
+ db_engine: postgres
+ description: Build a secure user authentication system with login, signup, and in-database session management.
+- title: Authenticated CRUD
+ folder: CRUD - Authentication
+ db_engine: sqlite
+ description: Complete Create-Read-Update-Delete operations with user authentication.
+- title: Image Gallery
+ folder: image gallery with user uploads
+ db_engine: sqlite
+ description: Create an image gallery with user uploads and session management.
+- title: Developer UI
+ folder: SQLPage developer user interface
+ db_engine: postgres
+ description: A web-based interface for managing SQLPage files and database tables.
+- title: Corporate Game
+ folder: corporate-conundrum
+ db_engine: sqlite
+ description: An interactive multiplayer board game with real-time updates.
+- title: Roundest Pokemon
+ folder: roundest_pokemon_rating
+ db_engine: sqlite
+ description: Demo app with a distinct non-default design, using custom HTML templates for everything.
+- title: Todo Application
+ folder: todo application (PostgreSQL)
+ db_engine: postgres
+ description: A full-featured todo list application with PostgreSQL backend.
+- title: MySQL & JSON
+ folder: mysql json handling
+ db_engine: mysql
+ description: Learn advanced JSON manipulation in MySQL to build advanced SQLPage applications.
+- title: Apache Web Server
+ folder: web servers - apache
+ db_engine: mysql
+ description: Use an existing Apache httpd Web Server to expose your SQLPage application.
+- title: Sending Emails
+ folder: sending emails
+ db_engine: sqlite
+ description: Use the fetch function to send emails (or interact with any other HTTP API).
+- title: Simple Website
+ folder: simple-website-example
+ db_engine: sqlite
+ description: Basic website example with navigation and data management.
+- title: Geographic App
+ folder: PostGIS - using sqlpage with geographic data
+ db_engine: postgres
+ description: Use SQLPage to create and manage geodata.
+- title: Multi-step form
+ folder: forms-with-multiple-steps
+ db_engine: sqlite
+ description: Guide to the implementation of forms that spread over multiple pages.
+- title: Custom HTML & JS
+ folder: custom form component
+ db_engine: mysql
+ description: Building a custom form component with a dynamic widget using HTML and javascript.
+- title: Splitwise Clone
+ folder: splitwise
+ db_engine: sqlite
+ description: An expense tracker app to split expenses with your friends, with nice debt charts.
+- title: Advanced Forms with MS SQL Server
+ folder: microsoft sql server advanced forms
+ db_engine: sql server
+ description: Forms with multi-value dropdowns, using SQL Server and its JSON functions.
+- title: Rich Text Editor
+ folder: rich-text-editor
+ db_engine: sqlite
+ description: A rich text editor with bold, italic, lists, images, and more. It posts its contents as Markdown.
diff --git a/examples/official-site/content/shared-parameters.yaml b/examples/official-site/content/shared-parameters.yaml
new file mode 100644
index 000000000..573207c8c
--- /dev/null
+++ b/examples/official-site/content/shared-parameters.yaml
@@ -0,0 +1,10 @@
+id:
+ name: id
+ type: TEXT
+ description: id attribute added to the container in HTML. It can be used to target this item through css
+ or for scrolling to this item through links (use "#id" in link url).
+class:
+ name: class
+ type: TEXT
+ description: class attribute added to the container in HTML. It can be used to apply custom styling to this
+ item through css. Added in v0.18.0.
diff --git a/examples/official-site/documentation.sql b/examples/official-site/documentation.sql
index 58a8074a4..92017596d 100644
--- a/examples/official-site/documentation.sql
+++ b/examples/official-site/documentation.sql
@@ -29,6 +29,8 @@ select case kind when 'component' then 'Components' else 'Functions' end as titl
(kind = 'function' and name in ('fetch', 'link', 'run_sql', 'variables'))
) as links
from reference_entry group by kind order by kind;
+select 'Configuration' as title, 'settings' as icon, '/configuration' as link,
+ 'Look up server settings, accepted values, and defaults.' as description;
select 'title' as component, 'Anatomy of a SQL page' as contents, 2 as level, 'how-it-works' as id;
select 'text' as component, 'Each SQL file is a page. Its first SELECT names a component and sets its top-level parameters. The rows returned by the next SELECT supply the row-level parameters. This list uses both.' as contents;
diff --git a/examples/official-site/llms.txt.sql b/examples/official-site/llms.txt.sql
index 106080336..a88439718 100644
--- a/examples/official-site/llms.txt.sql
+++ b/examples/official-site/llms.txt.sql
@@ -51,7 +51,7 @@ Key features:
- [Components reference](/components.sql): List of all ' || (select count(*) from component) || ' built-in UI components with parameters and examples
- [Functions reference](/functions.sql): SQLPage built-in functions for handling requests, encoding data, and more
-- [Configuration guide](https://github.com/sqlpage/SQLPage/blob/main/configuration.md): Complete list of configuration options in sqlpage.json
+- [Configuration reference](/configuration): Accepted values and defaults for SQLPage server settings
## Components
diff --git a/examples/official-site/safety.sql b/examples/official-site/safety.sql
index 2ba06a7fc..8522ed1cb 100644
--- a/examples/official-site/safety.sql
+++ b/examples/official-site/safety.sql
@@ -144,7 +144,7 @@ For more information, see the [this discussion](https://github.com/sqlpage/SQLPa
## Database connections
SQLPage uses a fixed pool of database connections, and will never open more connections than the ones you
-[configured](https://github.com/sqlpage/SQLPage/blob/main/configuration.md). So even under heavy load, your database
+[configured](/configuration#max_database_pool_connections). So even under heavy load, your database
connection limit will never be saturated by SQLPage.
And SQLPage will accept any restriction you put on the database user you use to connect to your database, so you can
diff --git a/examples/official-site/search.sql b/examples/official-site/search.sql
index eede7173a..a367e5891 100644
--- a/examples/official-site/search.sql
+++ b/examples/official-site/search.sql
@@ -7,6 +7,9 @@ where name = lower($search) or (kind = 'function' and lower($search) in (
))
order by kind limit 1;
+select 'redirect' as component, '/configuration#' || name as link
+from config_option where name = lower($search);
+
select 'shell-docs' as component, 'Search' as section,
coalesce($search || ' | ', '') || 'SQLPage documentation search' as title;
@@ -17,7 +20,10 @@ set escaped_search = '"' || replace(coalesce($search, ''), '"', '""') || '"';
with matches as (
select title, trim(description, char(13) || char(10) || ' ') as summary, page, parameters, fragment, rank,
- row_number() over (partition by page, parameters order by rank, rowid) as position
+ row_number() over (
+ partition by page, parameters, case when page = '/configuration' then fragment end
+ order by rank, rowid
+ ) as position
from documentation_fts
where documentation_fts match $escaped_search
)
diff --git a/examples/official-site/sqlpage/migrations/01_documentation.sql b/examples/official-site/sqlpage/migrations/01_documentation.sql
deleted file mode 100644
index 98b72ab0e..000000000
--- a/examples/official-site/sqlpage/migrations/01_documentation.sql
+++ /dev/null
@@ -1,1771 +0,0 @@
-CREATE TABLE component(
- name TEXT PRIMARY KEY,
- description TEXT NOT NULL,
- icon TEXT, -- icon name from tabler icon
- introduced_in_version TEXT
-);
-
-CREATE TABLE parameter_type(
- name TEXT PRIMARY KEY
-);
-INSERT INTO parameter_type(name) VALUES
- ('BOOLEAN'), ('COLOR'), ('HTML'), ('ICON'), ('INTEGER'), ('JSON'), ('REAL'), ('TEXT'), ('TIMESTAMP'), ('URL');
-
-CREATE TABLE parameter(
- top_level BOOLEAN DEFAULT FALSE,
- name TEXT,
- component TEXT REFERENCES component(name) ON DELETE CASCADE,
- description TEXT,
- description_md TEXT,
- type TEXT REFERENCES parameter_type(name) ON DELETE CASCADE,
- optional BOOLEAN DEFAULT FALSE,
- PRIMARY KEY (component, top_level, name)
-);
-
-CREATE TABLE example(
- component TEXT REFERENCES component(name) ON DELETE CASCADE,
- description TEXT,
- properties JSON,
- FOREIGN KEY (component) REFERENCES component(name) ON DELETE CASCADE
-);
-
--- The reference shows the SQL and renders the same stored component rows.
--- Arrays with several items become repeated column aliases, as in handwritten SQLPage files.
-CREATE VIEW example_with_source AS
-SELECT example.rowid AS example_id,
- row_number() OVER (PARTITION BY component ORDER BY example.rowid) AS example_number,
- example.*,
- (SELECT group_concat('select' || char(10) || (
- WITH fields AS (
- SELECT field.key AS name, coalesce(item.type, field.type) AS type,
- CASE WHEN item.key IS NULL THEN field.value ELSE item.value END AS value
- FROM json_each(statement.value) AS field
- LEFT JOIN json_each(
- CASE WHEN field.type = 'array' AND json_array_length(field.value) > 1 THEN field.value END
- ) AS item ON true
- )
- SELECT group_concat(' ' || CASE type
- WHEN 'true' THEN 'TRUE'
- WHEN 'false' THEN 'FALSE'
- WHEN 'array' THEN 'JSON(' || quote(value) || ')'
- WHEN 'object' THEN 'JSON(' || quote(value) || ')'
- ELSE quote(value)
- END || format(' as "%w"', name), ',' || char(10))
- FROM fields
- ) || ';', char(10) || char(10)) FROM json_each(example.properties) AS statement) AS source
-FROM example;
-
-INSERT INTO component(name, icon, description) VALUES
- ('list', 'list', 'A vertical list of items. Each item can be clickable and link to another page.');
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'list', * FROM (VALUES
- -- top level
- ('title', 'Text header at the top of the list.', 'TEXT', TRUE, TRUE),
- ('empty_title', 'Title text to display if the list is empty.', 'TEXT', TRUE, TRUE),
- ('empty_description', 'Description to display if the list is empty.', 'TEXT', TRUE, TRUE),
- ('empty_description_md', 'Description to display if the list is empty, in Markdown format.', 'TEXT', TRUE, TRUE),
- ('empty_link', 'URL to which the user should be taken if they click on the empty list.', 'URL', TRUE, TRUE),
- ('compact', 'Whether to display the list in a more compact format, allowing more items to be displayed on the screen.', 'BOOLEAN', TRUE, TRUE),
- ('wrap', 'Wrap list items onto multiple lines if they are too long', 'BOOLEAN', TRUE, TRUE),
- -- item level
- ('title', 'Name of the list item, displayed prominently.', 'TEXT', FALSE, FALSE),
- ('description', 'A description of the list item, displayed as greyed-out text.', 'TEXT', FALSE, TRUE),
- ('description_md', 'A description of the list item, displayed as greyed-out text, in Markdown format, allowing you to use rich text formatting, including `**bold**` and `*italic*` text.', 'TEXT', FALSE, TRUE),
- ('link', 'An URL to which the user should be taken when they click on the list item.', 'URL', FALSE, TRUE),
- ('icon', 'Name of an icon to display on the left side of the item.', 'ICON', FALSE, TRUE),
- ('image_url', 'The URL of a small image to display on the left side of the item.', 'URL', FALSE, TRUE),
- ('color', 'The name of a color, to be displayed as a dot near the list item contents.', 'COLOR', FALSE, TRUE),
- ('active', 'Whether this item in the list is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE),
- ('view_link', 'A URL to which the user should be taken when they click on the "view" icon. Does not show the icon when omitted.', 'URL', FALSE, TRUE),
- ('edit_link', 'A URL to which the user should be taken when they click on the "edit" icon. Does not show the icon when omitted.', 'URL', FALSE, TRUE),
- ('delete_link', 'A page that will be loaded when the user clicks on the delete button for this specific item. The link will be submitted as a POST request.', 'URL', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('list', 'A basic compact list', json('[{"component":"list", "compact": true, "title": "SQLPage lists are..."},{"title":"Beautiful"},{"title":"Useful"},{"title":"Versatile"}]')),
- ('list', 'An empty list with a link to add an item', json('[{"component":"list", "empty_title": "No items yet", "empty_description": "This list is empty. Click here to create a new item !", "empty_link": "documentation.sql"}]')),
- ('list', '
-### A list with rich text descriptions
-
-This example illustrates creating a nice list where each item has a title, a description, an image, and a link to another page.
-
-> Be careful, nested links are not supported. If you use the list''s `link` property, then your markdown `description_md` should not contain any link.
-', json('[{"component":"list", "wrap": true},
- {"title":"SQL Websites", "image_url": "/favicon.ico", "description_md":"Write SQL, get a website. SQLPage is a **SQL**-based **site** generator for **PostgreSQL**, **MySQL**, **SQLite** and **SQL Server**.", "link": "/"},
- {"title":"SQL Forms", "image_url": "https://upload.wikimedia.org/wikipedia/commons/b/b6/FileStack_retouched.jpg", "description_md":"Easily collect data **from users to your database** using the *form* component. Handle the data in SQL with `INSERT` or `UPDATE` queries.", "link": "?component=form"},
- {"title":"SQL Maps", "image_url": "https://upload.wikimedia.org/wikipedia/commons/1/15/Vatican_City_map_EN.png", "description_md":"Show database contents on a map using the *map* component. Works well with *PostGIS* and *SpatiaLite*.", "link": "?component=map"},
- {"title":"Advanced features", "icon": "settings", "description_md":"[Authenticate users](?component=authentication), [edit data](?component=form), [generate an API](?component=json), [maintain your database schema](/your-first-sql-website/migrations.sql), and more."}
- ]')),
- ('list', 'A beautiful list with bells and whistles.',
- json('[{"component":"list", "title":"Top SQLPage features", "compact": true },
- {"title":"Authentication", "link":"?component=authentication", "description": "Authenticate users with a login form or HTTP basic authentication", "color": "red", "icon":"lock", "active": true, "view_link": "?component=authentication#view" },
- {"title":"Editing data", "link":"?component=form", "description": "SQLPage makes it easy to UPDATE, INSERT and DELETE data in your database tables", "color": "blue", "icon":"database", "edit_link": "?component=form#edit", "delete_link": "?component=form#delete" },
- {"title":"API", "link":"?component=json", "description": "Generate a REST API from a single SQL query to connect with other applications and services", "color": "green", "icon":"plug-connected", "edit_link": "?component=json#edit", "delete_link": "?component=json#delete" }
- ]'));
-
-INSERT INTO component(name, icon, description) VALUES
- ('datagrid', 'grid-dots', 'Display small pieces of information in a clear and readable way. Each item has a name and is associated with a value.');
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'datagrid', * FROM (VALUES
- -- top level
- ('title', 'Text header at the top of the data grid.', 'TEXT', TRUE, TRUE),
- ('description', 'A short paragraph displayed below the title.', 'TEXT', TRUE, TRUE),
- ('description_md', 'A short paragraph displayed below the title - formatted using markdown.', 'TEXT', TRUE, TRUE),
- ('icon', 'Name of an icon to display on the left side of the title.', 'ICON', TRUE, TRUE),
- ('image_url', 'URL of an image to display on the left side of the title.', 'URL', TRUE, TRUE),
- -- item level
- ('title', 'Name of the piece of information.', 'TEXT', FALSE, FALSE),
- ('description', 'Value to display below the name.', 'TEXT', FALSE, TRUE),
- ('footer', 'Muted text to display below the value.', 'TEXT', FALSE, TRUE),
- ('image_url', 'URL of a small image (such as an avatar) to display on the left side of the value.', 'URL', FALSE, TRUE),
- ('link', 'A target URL to which the user should be taken when they click on the value.', 'URL', FALSE, TRUE),
- ('icon', 'An icon name (from tabler-icons.io) to display on the left side of the value.', 'ICON', FALSE, TRUE),
- ('color', 'If set to a color name, the value will be displayed in a pill of that color.', 'COLOR', FALSE, TRUE),
- ('active', 'Whether this item in the grid is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE),
- ('tooltip', 'A tooltip to display when the user passes their mouse over the value.', 'TEXT', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('datagrid', 'Just some sections of information.', json('[{"component":"datagrid"},{"title":"Language","description":"SQL"},{"title":"Creation date","description":"1974"}, {"title":"Language family","description":"Query language"}]')),
- ('datagrid', 'A beautiful data grid with nice colors and icons.',
- json('[{"component":"datagrid", "title": "Ophir Lojkine", "image_url": "https://avatars.githubusercontent.com/u/552629", "description_md": "Member since **2021**"},
- {"title": "Pseudo", "description": "lovasoa", "image_url": "https://avatars.githubusercontent.com/u/552629" },
- {"title": "Status", "description": "Active", "color": "green"},
- {"title": "Email Status", "description": "Validated", "icon": "check", "active": true, "tooltip": "Email address has been validated."},
- {"title": "Personal page", "description": "ophir.dev", "link": "https://ophir.dev/", "tooltip": "About me"}
- ]')),
- ('datagrid', 'Using a picture in the data grid card header.', json('[
- {"component":"datagrid", "title": "Website Ideas", "icon": "bulb"},
- {"title": "Search engine", "link":"https://google.com", "description": "Google", "color": "red", "icon":"brand-google", "footer": "Owned by Alphabet Inc."},
- {"title": "Encyclopedia", "link":"https://wikipedia.org", "description": "Wikipedia", "color": "blue", "icon":"world", "footer": "Owned by the Wikimedia Foundation"}
- ]'));
-
-
-INSERT INTO component(name, icon, description) VALUES
- ('steps', 'dots-circle-horizontal', 'Guide users through multi-stage processes, displaying a clear list of previous and future steps.');
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'steps', * FROM (VALUES
- -- top level
- ('color', 'Color of the bars displayed between steps.', 'COLOR', TRUE, TRUE),
- ('counter', 'Display the number of the step on top of its name.', 'TEXT', TRUE, TRUE),
- ('title', 'Title of the section.', 'TEXT', TRUE, TRUE),
- ('description', 'Description of the section.', 'TEXT', TRUE, TRUE),
- -- item level
- ('title', 'Name of the step.', 'TEXT', FALSE, TRUE),
- ('description', 'Tooltip to display when the user passes their mouse over the step''s name.', 'TEXT', FALSE, TRUE),
- ('link', 'A target URL to which the user should be taken when they click on the step.', 'URL', FALSE, TRUE),
- ('icon', 'An icon name (from tabler-icons.io) to display on the left side of the step name.', 'ICON', FALSE, TRUE),
- ('active', 'Whether this item in the grid is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('steps', 'Online store checkout steps.', json('[{"component":"steps"},{"title":"Shopping"},{"title":"Store pickup"}, {"title":"Payment","active":true},{"title":"Review & Order"}]')),
- ('steps', 'A progress indicator with custom color, auto-generated step numbers, icons, and description tooltips.',
- json('[{"component":"steps", "counter": true, "color":"purple"}, '||
- '{"title": "Registration form", "icon":"forms", "link": "https://github.com/sqlpage/SQLPage", "description": "Initial account data creation."},' ||
- '{"title": "Email confirmation", "icon": "mail", "link": "https://sql-page.com", "description": "Confirm your email by clicking on a link in a validation email."},' ||
- '{"title": "ID verification", "description": "Checking personal information", "icon": "user", "link": "#"},' ||
- '{"title": "Final account approval", "description": "ophir.dev", "link": "https://ophir.dev/", "icon":"eye-check", "active": true},' ||
- '{"title":"Account creation", "icon":"check"}]'));
-
-INSERT INTO component(name, icon, description) VALUES
- ('text', 'align-left', 'A paragraph of text. The entire component will render as a single paragraph, with each item being rendered as a span of text inside it, the styling of which can be customized using parameters.');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'text', * FROM (VALUES
- -- top level
- ('title', 'Text header before the paragraph.', 'TEXT', TRUE, TRUE),
- ('center', 'Whether to center the title.', 'BOOLEAN', TRUE, TRUE),
- ('html', 'Raw html code to include on the page. Don''t use that if you are not sure what you are doing, it may have security implications.', 'TEXT', TRUE, TRUE),
- ('contents', 'A top-level paragraph of text to display, without any formatting, without having to make additional queries.', 'TEXT', TRUE, TRUE),
- ('contents_md', 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.', 'TEXT', TRUE, TRUE),
- ('article', 'Makes long texts more readable by increasing the line height, adding margins, using a serif font, and decorating the initial letter.', 'BOOLEAN', TRUE, TRUE),
- -- item level
- ('contents', 'A span of text to display', 'TEXT', FALSE, FALSE),
- ('contents_md', 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.', 'TEXT', FALSE, TRUE),
- ('link', 'An URL to which the user should be taken when they click on this span of text.', 'URL', FALSE, TRUE),
- ('color', 'The name of a color for this span of text.', 'COLOR', FALSE, TRUE),
- ('underline', 'Whether the span of text should be underlined.', 'BOOLEAN', FALSE, TRUE),
- ('bold', 'Whether the span of text should be displayed as bold.', 'BOOLEAN', FALSE, TRUE),
- ('code', 'Use a monospace font. Useful to display the text as code.', 'BOOLEAN', FALSE, TRUE),
- ('italics', 'Whether the span of text should be displayed as italics.', 'BOOLEAN', FALSE, TRUE),
- ('break', 'Indicates that the current span of text starts a new paragraph.', 'BOOLEAN', FALSE, TRUE),
- ('size', 'A number between 1 and 6 indicating the font size.', 'INTEGER', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('text', 'Rendering a simple text paragraph.', json('[{"component":"text", "contents":"Hello, world ! <3"}]')),
- ('text', 'Rendering rich text using markdown', json('[{"component":"text", "article": true, "contents_md":"\n'||
- '# Markdown in SQLPage\n\n' ||
- '## Simple formatting\n\n' ||
- 'SQLPage supports only plain text as column values, but markdown allows easily adding **bold**, *italics*, [external links](https://github.com/sqlpage/SQLPage), [links to other pages](/index.sql) and [intra-page links](#my-paragraph). \n\n' ||
- '## Lists\n' ||
- '### Unordered lists\n' ||
- '* SQLPage is easy\n' ||
- '* SQLPage is fun\n' ||
- '* SQLPage is free\n\n' ||
- '### Ordered lists\n' ||
- '1. SQLPage is fast\n' ||
- '2. SQLPage is safe\n' ||
- '3. SQLPage is open-source\n\n' ||
- '## Code\n' ||
- '```sql\n' ||
- 'SELECT ''list'' AS component;\n' ||
- 'SELECT name as title FROM users;\n' ||
- '```\n\n' ||
- '## Tables\n\n' ||
- '| SQLPage component | Description | Documentation link |\n' ||
- '| --- | --- | --- |\n' ||
- '| text | A paragraph of text. | [Documentation](https://sql-page.com/documentation.sql?component=text) |\n' ||
- '| list | A list of items. | [Documentation](https://sql-page.com/documentation.sql?component=list) |\n' ||
- '| steps | A progress indicator. | [Documentation](https://sql-page.com/documentation.sql?component=steps) |\n' ||
- '| form | A series of input fields. | [Documentation](https://sql-page.com/documentation.sql?component=form) |\n\n' ||
- '## Quotes\n' ||
- '> Fantastic.\n>\n' ||
- '> — [HackerNews User](https://news.ycombinator.com/item?id=36194473#36209061) about SQLPage\n\n' ||
- '## Images\n' ||
- '\n\n' ||
- '## Horizontal rules\n' ||
- '---\n\n' ||
- '"}]')),
- ('text', 'Rendering a paragraph with links and styling.',
- json('[{"component":"text", "title":"About SQL"}, '||
- '{"contents":"SQL", "bold":true, "italics": true}, '||
- '{"contents":" is a domain-specific language used in programming and designed for managing data held in a "},'||
- '{"contents": "relational database management system", "link": "https://en.wikipedia.org/wiki/Relational_database"},'||
- '{"contents": ". It is particularly useful in handling structured data."}]')
- ),
- (
- 'text',
- 'An intra-page link to a section of the page.',
- json('[
- {"component":"text", "contents_md":"This is a link to the [next paragraph](#my-paragraph). You can open this link in a new tab and the page will scroll to the paragraph on load."},
- {"component":"text", "id": "my-paragraph", "contents_md": "This **is** the next paragraph."}
- ]')
- )
-;
-
-INSERT INTO component(name, icon, description) VALUES
- ('form', 'cursor-text', '
-## Building forms in SQL
-
-The form component will display a series of input fields of various types, that can be filled in by the user.
-When the user submits the form, the data is posted to an SQL file specified in the `action` property.
-
-### Handling submitted values
-
-The receiving SQL page will be able to handle the data,
-and insert it into the database, use it to perform a search, format it, update existing data, etc.
-
-A value in a field named "x" will be available as `:x` in the SQL query of the target page.
-
-### Form projects
-
- - [A multi-step form](https://github.com/sqlpage/SQLPage/tree/main/examples/forms-with-multiple-steps), guiding the user through a process without overwhelming them with a large form.
- - [File upload form](https://github.com/sqlpage/SQLPage/tree/main/examples/image%20gallery%20with%20user%20uploads), letting users upload images to a gallery.
- - [Rich text editor](https://github.com/sqlpage/SQLPage/tree/main/examples/rich-text-editor), letting users write text with bold, italics, links, images, etc.
- - [Master-detail form](https://github.com/sqlpage/SQLPage/tree/main/examples/master-detail-forms), to edit a list of structured items.
- - [Form with a variable number of fields](https://github.com/sqlpage/SQLPage/tree/main/examples/forms%20with%20a%20variable%20number%20of%20fields), when the fields are not known in advance.
- - [Demo of all input types](/examples/form), showing all the input types supported by SQLPage.
-');
-INSERT INTO parameter(component, name, description_md, type, top_level, optional) SELECT 'form', * FROM (VALUES
- -- top level
- ('enctype', '
-When ``method="post"``, this specifies how the form-data should be encoded
-when submitting it to the server.
-', 'TEXT', TRUE, TRUE),
- -- item level
- ('formenctype', '
-When ``type`` is ``submit`` or ``image``, this specifies how the form-data
-should be encoded when submitting it to the server.
-
-Takes precedence over any ``enctype`` set on the ``form`` element.
-
-NOTE: when a ``file`` type input is present, then ``formenctype="multipart/form-data"``
-is automatically applied to the default validate button.
-', 'TEXT', FALSE, TRUE)
-);
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'form', * FROM (VALUES
- -- top level
- ('method', 'Set this to ''GET'' to pass the form contents directly as URL parameters. If the user enters a value v in a field named x, submitting the form will load target.sql?x=v. If target.sql contains SELECT $x, it will display the value v.', 'TEXT', TRUE, TRUE),
- ('action', 'An optional link to a target page that will handle the results of the form. By default the target page is the current page with the id of the form (if passed) used as hash - this will bring us back to the location of the form after submission. Setting it to the name of a different sql file will load that file when the user submits the form.', 'TEXT', TRUE, TRUE),
- ('title', 'A name to display at the top of the form. It will be displayed in a larger font size at the top of the form.', 'TEXT', TRUE, TRUE),
- ('validate', 'The text to display in the button at the bottom of the form that submits the values. Omit this property to let the browser display the default form validation text, or set it to the empty string to remove the button completely.', 'TEXT', TRUE, TRUE),
- ('validate_color', 'The color of the button at the bottom of the form that submits the values. Omit this property to use the default color.', 'COLOR', TRUE, TRUE),
- ('validate_outline', 'A color to outline the validation button.', 'COLOR', TRUE, TRUE),
- ('validate_shape', 'The shape of the validation button (e.g., pill, square).', 'TEXT', TRUE, TRUE),
- ('validate_size', 'The size of the validation button (e.g., sm, lg).', 'TEXT', TRUE, TRUE),
- ('reset', 'The text to display in the button at the bottom of the form that resets the form to its original state. Omit this property not to show a reset button at all.', 'TEXT', TRUE, TRUE),
- ('id', 'A unique identifier for the form, which can then be used to validate the form from a button outside of the form.', 'TEXT', TRUE, TRUE),
- ('auto_submit', 'Automatically submit the form when the user changes any of its fields, and remove the validation button.', 'BOOLEAN', TRUE, TRUE),
- ('validate_icon', 'Name of an icon to be displayed on the left side of the submit button.', 'ICON', TRUE, TRUE),
- ('reset_icon', 'Name of an icon to be displayed on the left side of the reset button.', 'ICON', TRUE, TRUE),
- ('reset_color', 'The color of the button at the bottom of the form that resets the form to its original state. Omit this property to use the default color.', 'COLOR', TRUE, TRUE),
- ('reset_outline', 'A color to outline the reset button.', 'COLOR', TRUE, TRUE),
- ('reset_shape', 'The shape of the reset button (e.g., pill, square).', 'TEXT', TRUE, TRUE),
- ('reset_size', 'The size of the reset button (e.g., sm, lg).', 'TEXT', TRUE, TRUE),
- ('narrow', 'Whether to trim the horizontal padding between the icon and the label of the validation and reset buttons.', 'BOOLEAN', TRUE, TRUE),
- -- item level
- ('type', 'Declares input control behavior and expected format. All HTML input types are supported (text, number, date, file, checkbox, radio, hidden, ...). SQLPage adds some custom types: textarea, switch, header. text by default. See https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#input_types', 'TEXT', FALSE, TRUE),
- ('name', 'The name of the input field, that you can use in the target page to get the value the user entered for the field.', 'TEXT', FALSE, FALSE),
- ('label', 'A friendly name for the text field to show to the user.', 'TEXT', FALSE, TRUE),
- ('placeholder', 'A placeholder text that will be shown in the field when is is empty.', 'TEXT', FALSE, TRUE),
- ('value', 'A default value that will already be present in the field when the user loads the page.', 'TEXT', FALSE, TRUE),
- ('options', 'A json array of objects containing the label and value of initial options of a select field. Used only when type=select. JSON objects in the array can contain the properties "label", "value" and "selected".', 'JSON', FALSE, TRUE),
- ('options_source', 'Only for inputs of type `select`. URL of a SQL file that returns JSON search results for the dropdown. The SQL file receives the search text as `$search` and must return an array of objects with exactly `label` and `value`. Use `options` for options that should be available before the user searches.', 'URL', FALSE, TRUE),
- ('required', 'Set this to true to prevent the form contents from being sent if this field is left empty by the user.', 'BOOLEAN', FALSE, TRUE),
- ('min', 'The minimum value to accept for an input of type number', 'REAL', FALSE, TRUE),
- ('max', 'The maximum value to accept for an input of type number', 'REAL', FALSE, TRUE),
- ('checked', 'Used only for checkboxes and radio buttons. Indicates whether the checkbox should appear as already checked.', 'BOOLEAN', FALSE, TRUE),
- ('multiple', 'For select elements, indicates that multiple elements can be selected simultaneously. When using multiple, you should add square brackets after the variable name: ''my_variable[]'' as name. For file inputs, lets the user select several files at once: save them all with [sqlpage.persist_uploaded_files](functions.sql?function=persist_uploaded_files).', 'BOOLEAN', FALSE, TRUE),
- ('empty_option', 'Only for inputs of type `select`. Adds an empty option with the given label before the ones defined in `options`. Useful when generating other options from a database table.', 'TEXT', FALSE, TRUE),
- ('searchable', 'For select and multiple-select elements, displays them with a nice dropdown that allows searching for options.', 'BOOLEAN', FALSE, TRUE),
- ('dropdown', 'An alias for "searchable".', 'BOOLEAN', FALSE, TRUE),
- ('create_new', 'In a select with a dropdown (`searchable`, `dropdown` or `options_source`), this option allows the user to enter new values, that are not in the list of options. Works for single selects and for multiselects.', 'BOOLEAN', FALSE, TRUE),
- ('step', 'The increment of values in an input of type number. Set to 1 to allow only integers.', 'REAL', FALSE, TRUE),
- ('description', 'A helper text to display near the input field.', 'TEXT', FALSE, TRUE),
- ('description_md', 'A helper text to display near the input field - formatted using markdown.', 'TEXT', FALSE, TRUE),
- ('pattern', 'A regular expression that the value must match. For instance, [0-9]{3} will only accept 3 digits.', 'TEXT', FALSE, TRUE),
- ('autofocus', 'Automatically focus the field when the page is loaded', 'BOOLEAN', FALSE, TRUE),
- ('width', 'Width of the form field, between 1 and 12.', 'INTEGER', FALSE, TRUE),
- ('autocomplete', 'Whether the browser should suggest previously entered values for this field.', 'BOOLEAN', FALSE, TRUE),
- ('minlength', 'Minimum length of text allowed in the field.', 'INTEGER', FALSE, TRUE),
- ('maxlength', 'Maximum length of text allowed in the field.', 'INTEGER', FALSE, TRUE),
- ('formaction', 'When type is "submit", this specifies the URL of the file that will handle the form submission. Useful when you need multiple submit buttons.', 'TEXT', FALSE, TRUE),
- ('formmethod', 'When type is "submit", the HTTP method to submit the form with. Takes precedence over the form''s own "method".', 'TEXT', FALSE, TRUE),
- ('formnovalidate', 'When type is "submit", skips the browser''s validation of the other fields when this button submits the form.', 'BOOLEAN', FALSE, TRUE),
- ('formtarget', 'When type is "submit", where to display the response. Takes the same values as a link target: "_blank" to open a new tab, "_self" to stay in the same one.', 'TEXT', FALSE, TRUE),
- ('accept', 'Used only for inputs of type "file". A comma-separated list of the file types the user can pick, given as extensions (".pdf,.png") or as MIME types ("image/*").', 'TEXT', FALSE, TRUE),
- ('list', 'The id of a datalist element holding the suggestions to show for this field. The datalist itself has to be rendered by the "html" component.', 'TEXT', FALSE, TRUE),
- ('class', 'A CSS class to apply to the form element.', 'TEXT', FALSE, TRUE),
- ('prefix_icon','Icon to display on the left side of the input field, on the same line.','ICON',FALSE,TRUE),
- ('prefix','Text to display on the left side of the input field, on the same line.','TEXT',FALSE,TRUE),
- ('suffix','Short text to display after th input, on the same line. Useful to add units or a currency symbol to an input.','TEXT',FALSE,TRUE),
- ('readonly','Set to true to prevent the user from modifying the value of the input field.','BOOLEAN',FALSE,TRUE),
- ('rows','Number of rows to display for a textarea. Defaults to 3.','INTEGER',FALSE,TRUE),
- ('disabled','Makes the field non-editable, non-focusable, and not submitted with the form. Use readonly instead for simple non-editable fields.','BOOLEAN',FALSE,TRUE),
- ('id','A unique identifier for the input, which can then be used to select and manage the field with Javascript code. Usefull for advanced using as setting client side event listeners, interactive control of input field (disabled, visibility, read only, e.g.) and AJAX requests.','TEXT',FALSE,TRUE)
-) x;
-INSERT INTO example(component, description, properties) VALUES
- (
- 'form',
- '
-
-The best way to manage forms in SQLPage is to create at least two separate files:
-
- - one that will contain the form itself, and will be loaded when the user visits the page,
- - one that will handle the form submission, and will redirect to whatever page you want to display after the form has been submitted.
-
-For instance, if you were creating a form to manage a list of users, you could create:
-
- - a file named `users.sql` that would contain a list of users and a form to create a new user,
- - a file named `create_user.sql` that would insert the new user in the database, and then redirect to `users.sql`.
-
-`create_user.sql` could contain the following sql statement to [safely](safety.sql) insert the new user in the database:
-
-```sql
-INSERT INTO users(name) VALUES(:username)
-RETURNING ''redirect'' AS component, ''users.sql'' AS link
-```
-
-When loading the page, the value for `:username` will be `NULL` if no value has been submitted.
-',
- json('[{"component":"form", "action": "create_user.sql"}, {"name": "username"}]')),
- ('form', 'A user registration form, illustrating the use of required fields, and different input types.',
- json('[{"component":"form", "title": "User", "validate": "Create new user"}, '||
- '{"name": "First name", "placeholder": "John"}, '||
- '{"name": "Last name", "required": true, "description": "We need your last name for legal purposes."},'||
- '{"name": "Resume", "type": "textarea"},'||
- '{"name": "Birth date", "type": "date", "max": "2010-01-01", "value": "1994-04-16"},'||
- '{"name": "Password", "type": "password", "pattern": "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$", "required": true, "description_md": "**Password Requirements:** Minimum **8 characters**, at least **one letter** & **one number**. *Tip:* Use a passphrase for better security!"},'||
- '{"label": "I accept the terms and conditions", "name": "terms", "type": "checkbox", "required": true}'||
- ']')),
- ('form','Create prepended and appended inputs to make your forms easier to use.',
- json('[{"component":"form"}, '||
- '{"name": "Your account", "prefix_icon": "mail", "prefix": "Email:", "suffix": "@mydomain.com"}, ' ||
- ']')),
-
- ('form','With the header type, you can group your input fields based on a theme. For example, you can categorize fields according to a person''s identity and their contact information.',
- json('[{"component":"form","title":"Information about the person"}, '||
- '{"type": "header", "label": "Identity"},' ||
- '{"name": "Name"},' ||
- '{"name": "Surname"},' ||
- '{"type": "header","label": "Contact"},' ||
- '{"name": "phone", "label": "Phone number"},' ||
- '{"name": "Email"},' ||
- ']')),
-
- ('form','A toggle switch in an HTML form is a user interface element that allows users to switch between two states, typically "on" and "off." It visually resembles a physical switch and is often used for settings or options that can be enabled or disabled.',
- json('[{"component":"form"},
- {"type": "switch", "label": "Dark theme", "name": "dark", "description": "Enable dark theme"},
- {"type": "switch", "label": "A required toggle switch", "name": "my_checkbox", "required": true,"checked": true},
- {"type": "switch", "label": "A disabled toggle switch", "name": "my_field", "disabled": true}
- ]')),
-
- ('form', 'This example illustrates the use of the `select` type.
-In this select input, the various options are hardcoded, but they could also be loaded from a database table,
-[using a function to convert the rows into a json array](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) like
- - `json_group_array()` in SQLite,
- - `json_agg()` in Postgres,
- - `JSON_ARRAYAGG()` in MySQL, or
- - `FOR JSON PATH` in Microsoft SQL Server.
-
-
-In SQLite, the query would look like
-```sql
-SELECT
- ''select'' as type,
- ''Select a fruit...'' as empty_option,
- ''cherry'' as prefix_icon,
- json_group_array(json_object(
- ''label'', name,
- ''value'', id
- )) as options
-FROM fruits
-```
-', json('[{"component":"form", "action":"examples/show_variables.sql"},
- {"name": "Fruit", "type": "select",
- "empty_option": "Select a fruit...",
- "options":
- "[{\"label\": \"Orange\", \"value\": 0}, {\"label\": \"Apple\", \"value\": 1}, {\"label\": \"Banana\", \"value\": 3}]"}
- ]')),
- ('form', '### Multi-select
-You can authorize the user to select multiple options by setting the `multiple` property to `true`.
-This creates a more compact (but arguably less user-friendly) alternative to a series of checkboxes.
-In this case, you should add square brackets to the name of the field (e.g. `''my_field[]'' as name`).
-The target page will then receive the value as a JSON array of strings, which you can iterate over using
- - the `json_each` function [in SQLite](https://www.sqlite.org/json1.html) and [Postgres](https://www.postgresql.org/docs/9.3/functions-json.html),
- - the [`OPENJSON`](https://learn.microsoft.com/fr-fr/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16) function in Microsoft SQL Server.
- - in MySQL, json manipulation is less straightforward: see [the SQLPage MySQL json example](https://github.com/sqlpage/SQLPage/tree/main/examples/mysql%20json%20handling)
-
-[More information on how to handle JSON in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide).
-
-The target page could then look like this:
-
-```sql
-insert into best_fruits(id) -- INSERT INTO ... SELECT ... runs the SELECT query and inserts the results into the table
-select CAST(value AS integer) as id -- all values are transmitted by the browser as strings
-from json_each($my_field); -- in SQLite, json_each returns a table with a "value" column for each element in the JSON array
-```
-
-### Example multiselect generated from a database table
-
-If you have a table of all possible options (`my_options(id int, label text)`),
-and want to generate a multi-select field from it, you have two options:
-- if the number of options is not too large, you can use the `options` parameter to return them all as a JSON array in the SQL query
-- if the number of options is large (e.g. more than 1000), you can use `options_source` to load options dynamically from a different SQL query as the user types
-
-#### Embedding all options in the SQL query
-
-Let''s say you have a table that contains the selected options per user (`my_user_options(user_id int, option_id int)`).
-You can use a query like this to generate the multi-select field:
-
-```sql
-select ''select'' as type, true as multiple, json_group_array(json_object(
- ''label'', my_options.label,
- ''value'', my_options.id,
- ''selected'', my_user_options.option_id is not null
-)) as options
-from my_options
-left join my_user_options
- on my_options.id = my_user_options.option_id
- and my_user_options.user_id = $user_id
-```
-
-This will generate a json array of objects, each containing the label, value and selected status of each option.
-
-#### Loading options dynamically from a different SQL query with `options_source`
-
-If the `my_options` table has a large number of rows, you can use the `options_source` parameter to load options dynamically from a different SQL query as the user types.
-
-We''ll write a second SQL file, `options_source.sql`, that will receive the user''s search string as a parameter named `$search`,
- and return a json array of objects, each containing the label and value of each option.
-
-When both `options` and `options_source` are set, the local `options` are loaded first. Search results from `options_source` are loaded into the same option list; a result with the same `value` updates the existing option. This is useful to set a default preselected value with `options_source`.
-
-`options_source` may already contain query parameters. SQLPage preserves them and adds or replaces the `search` parameter when loading options.
-
-##### `options_source.sql`
-
-```sql
-select ''json'' as component;
-
-select id as value, label as label
-from my_options
-where label like $search || ''%'';
-```
-
-##### `form`
-
-', json('[{"component":"form", "action":"examples/show_variables.sql", "reset": "Reset"},
- {"name": "component", "type": "select",
- "value": "form",
- "options": [{"label": "Form", "value": "form"}],
- "options_source": "examples/from_component_options_source.sql?category=component",
- "description": "Start typing the name of a component like ''map'' or ''form''..."
- }]')),
- ('form', 'This example illustrates the use of the `radio` type.
-The `name` parameter is used to group the radio buttons together.
-The `value` parameter is used to set the value that will be submitted when the user selects the radio button.
-The `label` parameter is used to display a friendly name for the radio button.
-The `description` parameter is used to display a helper text near the radio button.
-
-We could also save all the options in a database table, and then run a simple query like
-
-```sql
-SELECT ''form'' AS component;
-SELECT
- ''radio'' as type,
- ''db'' as name,
- option_name as label,
- option_id as value
-FROM my_options;
-```
-
-In this example, depending on what the user clicks, the page will be reloaded with a the variable `$component` set to the string "form", "map", or "chart".
-
- ', json('[{"component":"form", "method": "GET"},
- {"name": "component", "type": "radio", "value": "form", "description": "Read user input in SQL", "label": "Form"},
- {"name": "component", "type": "radio", "value": "map", "checked": true, "description": "Display a map based on database data", "label": "Map"},
- {"name": "component", "type": "radio", "value": "chart", "description": "Interactive plots of SQL query results", "label": "Chart"}
- ]')),
- ('form', '
-### Dynamically refresh the page when the user changes the form
-
-The form will be automatically submitted when the user changes any of its fields, and the page will be reloaded with the new value.
-The validation button is removed.
-', json('[{"component":"form", "auto_submit": true},
- {"name": "component", "type": "select", "autocomplete": false, "options": [
- {"label": "Form", "value": "form", "selected": true},
- {"label": "Map", "value": "map"},
- {"label": "Chart", "value": "chart"}
- ], "description": "Choose a component to view its documentation. No need to click a button, the page will be reloaded automatically.", "label": "Component"}
- ]')),
- ('form', 'When you want to include some information in the form data, but not display it to the user, you can use a hidden field.
-
-This can be used to track simple data such as the current user''s id,
-or to implement more complex flows, such as a multi-step form,
-where the user is redirected to a different page after each step.
-
-This can also be used to implement [CSRF protection](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern),
-if your website has authenticated users that can perform sensitive actions through simple links.
-But note that SQLPage cookies already have the `SameSite=strict` attribute by default, which protects you against CSRF attacks by default in most cases.
-
-', json('[{"component":"form", "validate": "Delete", "validate_color": "red"},
- {"type": "hidden", "name": "resource_id", "value": "1234"},
- {"name": "confirm", "label": "Please type \"sensitive resource\" here to confirm the deletion", "required": true}
- ]')),
- ('form', 'This example illustrates the use of custom validation buttons and half-width fields.',
- json('[{"component":"form", "title": "User", "validate": "Create new user", "validate_color": "green", "reset": "Clear"},
- {"name": "first_name", "label": "First name", "placeholder": "John", "width": 4},
- {"name": "middle_name", "label": "Middle name", "placeholder": "Fitzgerald", "width": 4},
- {"name": "last_name", "label": "Last name", "placeholder": "Doe", "width": 4},
- {"name": "email", "label": "Email", "placeholder": "john.doe@gmail.com", "width": 12},
- {"name": "password", "label": "Password", "type": "password", "width": 6},
- {"name": "password_confirmation", "label": "Password confirmation", "type": "password", "width": 6},
- {"name": "terms", "label": "I accept the terms and conditions", "type": "checkbox", "required": true}
- ]')),
- ('form', '
-## File upload
-
-You can use the `file` type to allow the user to upload a file.
-
-The file will be uploaded to the server, and you will be able to access it using the
-[`sqlpage.uploaded_file_path`](functions.sql?function=uploaded_file_path#function) function.
-
-Here is how you could save the uploaded file to a table in the database:
-
-```sql
-INSERT INTO uploaded_file(name, data)
-VALUES (
- :filename,
- sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''my_file''))
-)
-```
-',
- json('[{"component":"form", "enctype": "multipart/form-data", "title": "Upload a picture", "validate": "Upload", "action": "examples/handle_picture_upload.sql"},
- {"name": "my_file", "type": "file", "accept": "image/png, image/jpeg", "label": "Picture", "description": "Upload a small picture", "required": true}
- ]')),
- ('form', '
-## Form Encoding
-
-You can specify the way form data should be encoded by setting the `enctype`
-top-level property on the form.
-
-You may also specify `formenctype` on `submit` and `image` type inputs.
-This will take precedence over the `enctype` specified on the form and is
-useful in the case there are multiple `submit` buttons on the form.
-For example, an external site may have specific requirements on encoding type.
-
-As a rule of thumb, ``multipart/form-data`` is best when fields may contain
-copious non-ascii characters or for binary data such as an image or a file.
-However, ``application/x-www-form-urlencoded`` creates less overhead when
-many short ascii text values are submitted.
-',
- json('[
- {
- "component": "form",
- "method": "post",
- "enctype": "multipart/form-data",
- "title": "Submit with different encoding types",
- "validate": "Submit with form encoding type",
- "action": "examples/handle_enctype.sql"
- },
- {"name": "data", "type": "text", "label": "Data", "required": true},
- {
- "name": "percent_encoded",
- "type": "submit",
- "label": "Submit as",
- "width": 4,
- "formaction": "examples/handle_enctype.sql",
- "formenctype": "application/x-www-form-urlencoded",
- "value": "application/x-www-form-urlencoded"
- },
- {
- "name": "multipart_form_data",
- "type": "submit",
- "label": "Submit as",
- "width": 4,
- "formaction": "examples/handle_enctype.sql",
- "formenctype": "multipart/form-data",
- "value": "multipart/form-data"
- }
-]')),
- ('form', '
-## Bulk data insertion
-
-You can use the `file` type to allow the user to upload a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values)
-file containing data to insert in a table.
-
-SQLPage can load data from a CSV file and insert it into a database table.
-SQLPage re-uses PostgreSQL''s [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html)
-to specify the format of the CSV file, but makes it work with all supported databases.
-
-> When connected to a PostgreSQL database, SQLPage will use the native `COPY` statement,
-> for super fast and efficient on-database CSV parsing.
-> But it will also work transparently with other databases, by
-> parsing the CSV locally and emulating the same behavior with simple `INSERT` statements.
-
-Here is how you could easily copy data from a CSV to a table in the database:
-
-```sql
-copy product(name, description) from ''product_data_input''
-with (header true, delimiter '','', quote ''"'');
-```
-
-If you want to pre-process the data before inserting it into the final table,
-you can use a temporary table to store the data, and then insert it into the final table:
-
-```sql
--- temporarily store the data in a table with text columns
-create temporary table if not exists product_tmp(name text, description text, price text);
-delete from product_tmp;
-
--- copy the data from the CSV file into the temporary table
-copy product_tmp(name, description, price) from ''product_data_input'';
-
--- insert the data into the final table, converting the price column to an integer
-insert into product(name, description, price)
-select name, description, CAST(price AS integer) from product_tmp
-where price is not null and description is not null and length(description) > 10;
-```
-
-This will load the processed CSV into the product table, provided it has the following structure:
-
-```csv
-name,description,price
-"SQLPage","A tool to create websites using SQL",0
-"PostgreSQL","A powerful open-source relational database",0
-"SQLite","A lightweight relational database",0
-"MySQL","A popular open-source relational database",0
-```
-',
- json('[{"component":"form", "title": "CSV import", "validate": "Load data", "action": "examples/handle_csv_upload.sql"},
- {"name": "product_data_input", "type": "file", "accept": "text/csv", "label": "Products", "description": "Upload a CSV with a name, description, and price columns", "required": true}
- ]'))
-;
-
-INSERT INTO component(name, icon, description) VALUES
- ('chart', 'timeline', 'A component that plots data. Line, area, bar, and pie charts are all supported. Each item in the component is a data point in the graph.');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'chart', * FROM (VALUES
- -- top level
- ('title', 'The name of the chart.', 'TEXT', TRUE, TRUE),
- ('type', 'The type of chart. One of: "line", "area", "bar", "column", "pie", "scatter", "bubble", "heatmap", "rangeBar". "column" is a synonym of "bar".', 'TEXT', TRUE, FALSE),
- ('time', 'Whether the x-axis represents time. If set to true, the x values will be parsed and formatted as dates for the user.', 'BOOLEAN', TRUE, TRUE),
- ('xmin', 'The minimal value for the x-axis. When time is true, this can be a date or timestamp.', 'TEXT', TRUE, TRUE),
- ('xmax', 'The maximum value for the x-axis. When time is true, this can be a date or timestamp.', 'TEXT', TRUE, TRUE),
- ('ymin', 'The minimal value for the y-axis.', 'REAL', TRUE, TRUE),
- ('ymax', 'The maximum value for the y-axis.', 'REAL', TRUE, TRUE),
- ('xtitle', 'Title of the x axis, displayed below it.', 'TEXT', TRUE, TRUE),
- ('ytitle', 'Title of the y axis, displayed to its left.', 'TEXT', TRUE, TRUE),
- ('ztitle', 'Title of the z axis, displayed in tooltips.', 'TEXT', TRUE, TRUE),
- ('xticks', 'Number of intervals used to generate a numeric x-axis, normally producing one more tick position. On category and time axes, this is a target for label density, so the visible label count may differ.', 'INTEGER', TRUE, TRUE),
- ('yticks', 'Number of ticks on the y axis.', 'INTEGER', TRUE, TRUE),
- ('ystep', 'Step between ticks on the y axis.', 'REAL', TRUE, TRUE),
- ('marker', 'Marker size', 'REAL', TRUE, TRUE),
- ('labels', 'Whether to show the data labels on the chart or not.', 'BOOLEAN', TRUE, TRUE),
- ('color', 'The name of a color in which to display the chart. If there are multiple series in the chart, this parameter can be repeated multiple times.', 'COLOR', TRUE, TRUE),
- ('stacked', 'Whether to cumulate values from different series. Supported by the "line", "area" and "bar" chart types, and ignored by the others. Series are aligned on their x values, and a series that has no value for a given x counts as zero there.', 'BOOLEAN', TRUE, TRUE),
- ('toolbar', 'Whether to display a toolbar at the top right of the chart, that offers downloading the data as CSV.', 'BOOLEAN', TRUE, TRUE),
- ('show_legend', 'Whether to display the legend listing all chart series. Defaults to true.', 'BOOLEAN', TRUE, TRUE),
- ('logarithmic', 'Display the y-axis in logarithmic scale.', 'BOOLEAN', TRUE, TRUE),
- ('horizontal', 'Displays a bar chart with horizontal bars instead of vertical ones.', 'BOOLEAN', TRUE, TRUE),
- ('height', 'Height of the chart, in pixels. By default: 250', 'INTEGER', TRUE, TRUE),
- -- item level
- ('x', 'The value of the point on the horizontal axis. Numeric values use continuous, proportionate positioning; text values are evenly spaced categories. Set the top-level time property for dates and timestamps.', 'REAL', FALSE, FALSE),
- ('y', 'The value of the point on the vertical axis', 'REAL', FALSE, FALSE),
- ('z', 'A third value carried by the point. Used as the bubble radius in a bubble chart, and shown in the tooltip under the name given by the top-level "ztitle".', 'REAL', FALSE, TRUE),
- ('link', 'A URL to open when the data point is clicked. The tooltip value also links to the point, as does a text x value when shown as the tooltip title.', 'URL', FALSE, TRUE),
- ('label', 'An alias for parameter "x". On a row that draws a reference line, the text to display next to the line. Labels are plain text; HTML markup is displayed literally.', 'TEXT', FALSE, TRUE),
- ('value', 'An alias for parameter "y"', 'REAL', FALSE, TRUE),
- ('series', 'If multiple series are represented and share the same y-axis, this parameter can be used to distinguish between them. Series names are plain text; HTML markup is displayed literally.', 'TEXT', FALSE, TRUE),
- ('yline', 'Draws a reference line across the chart at this value of the y axis instead of plotting a point, to show a limit such as a quota or an alarm threshold. Not drawn if it falls outside of the axis, so set ymax when the limit is above the data.', 'REAL', FALSE, TRUE),
- ('yline_end', 'Makes the yline a band instead of a line, reaching to this value.', 'REAL', FALSE, TRUE),
- ('xline', 'Draws a reference line across the chart at this position of the x axis instead of plotting a point, to mark an event such as a deployment. A date or a timestamp when time is set, otherwise one of the x values.', 'TEXT', FALSE, TRUE),
- ('xline_end', 'Makes the xline a band instead of a line, reaching to this value.', 'TEXT', FALSE, TRUE),
- ('color', 'The name of a color for what this row draws: the bar, slice or point it plots, or the reference line it draws. Defaults to the color of the series for a data point, and to grey for a reference line.', 'COLOR', FALSE, TRUE)
-) x;
-INSERT INTO example(component, description, properties) VALUES
- ('chart', 'An area chart representing a time series, using the top-level property `time`.
- Ticks on the x axis are adjusted automatically, and ISO datetimes are parsed and displayed in a readable format.', json('[
- {
- "component": "chart",
- "title": "Quarterly Revenue",
- "type": "area",
- "color": "blue-lt",
- "marker": 5,
- "time": true
- },
- {"x":"2022-01-01T00:00:00Z","y":15},
- {"x":"2022-04-01T00:00:00Z","y":46},
- {"x":"2022-07-01T00:00:00Z","y":23},
- {"x":"2022-10-01T00:00:00Z","y":70},
- {"x":"2023-01-01T00:00:00Z","y":35},
- {"x":"2023-04-01T00:00:00Z","y":106},
- {"x":"2023-07-01T00:00:00Z","y":53}
- ]')),
- ('chart', 'A pie chart.', json('[{"component":"chart", "title": "Answers", "type": "pie", "labels": true},
- {"label": "Yes", "value": 65},
- {"label": "No", "value": 35}]')),
- ('chart', 'A basic bar chart', json('[
- {"component":"chart", "type": "bar", "title": "Quarterly Results", "horizontal": true, "labels": true},
- {"label": "Tom", "value": 35}, {"label": "Olive", "value": 15}]')),
- ('chart', 'A TreeMap Chart allows you to display hierarchical data in a nested layout. This is useful for visualizing the proportion of each part to the whole.',
- json('[
- {"component":"chart", "type": "treemap", "title": "Quarterly Results By Region (in k$)", "labels": true },
- {"series": "North America", "label": "United States", "value": 35},
- {"series": "North America", "label": "Canada", "value": 15},
- {"series": "Europe", "label": "France", "value": 30},
- {"series": "Europe", "label": "Germany", "value": 55},
- {"series": "Asia", "label": "China", "value": 20},
- {"series": "Asia", "label": "Japan", "value": 10}
- ]')),
- ('chart', 'A bar chart with multiple series.', json('[{"component":"chart", "title": "Expenses", "type": "bar", "stacked": true, "toolbar": true, "show_legend": false, "ystep": 10}, '||
- '{"series": "Marketing", "x": 2021, "value": 35}, '||
- '{"series": "Marketing", "x": 2022, "value": 15}, '||
- '{"series": "Human resources", "x": 2021, "value": 30}, '||
- '{"series": "Human resources", "x": 2022, "value": 55}]')),
- ('chart', 'A stacked area chart, showing how each series contributes to a total.
-The `stacked` property also works with the `line` and `bar` chart types.
-
-Series are aligned on their `x` values, and a series that has no value for a given `x` counts as zero there:
-below, the graphics card draws no power outside of the render.
-If a missing value does not mean zero in your data, make all the series share the same `x` values,
-for instance by rounding timestamps to a common interval.',
- json('[{"component":"chart", "title": "Power draw", "type": "area", "stacked": true, "time": true, "ytitle": "watts", "color": ["blue", "teal"], "marker": 4}, '||
- '{"series": "CPU", "x": "2024-03-01T10:00:00Z", "value": 45}, '||
- '{"series": "CPU", "x": "2024-03-01T10:15:00Z", "value": 52}, '||
- '{"series": "CPU", "x": "2024-03-01T10:30:00Z", "value": 48}, '||
- '{"series": "CPU", "x": "2024-03-01T10:45:00Z", "value": 44}, '||
- '{"series": "GPU", "x": "2024-03-01T10:15:00Z", "value": 120}, '||
- '{"series": "GPU", "x": "2024-03-01T10:30:00Z", "value": 140}]')),
- ('chart', 'A line chart with multiple series. One of the most common types of charts, often used to show trends over time.
-Also demonstrates the use of the `toolbar` attribute to allow the user to download the graph as an image or the data as a CSV file.',
- json('[{"component":"chart", "title": "Revenue", "ymin": 0, "toolbar": true},
- {"series": "Chicago Store", "x": 2021, "value": 35},
- {"series": "Chicago Store", "x": 2022, "value": 15},
- {"series": "Chicago Store", "x": 2023, "value": 45},
- {"series": "New York Store", "x": 2021, "value": 30},
- {"series": "New York Store", "x": 2022, "value": 55},
- {"series": "New York Store", "x": 2023, "value": 19}
- ]')),
- ('chart', 'A scatter plot with multiple custom options.',
- json('[
- {"component":"chart", "title": "Gross domestic product and its growth", "type": "scatter",
- "xtitle": "Growth Rate", "ytitle": "GDP (Trillions USD)", "height": 500, "marker": 8,
- "xmin": 0, "xmax": 10, "ymin": 0, "ymax": 25, "yticks": 5},
-
- {"series": "Brazil", "x": 2.5, "y": 2},
- {"series": "China", "x": 6.5, "y": 14},
- {"series": "United States", "x": 2.3, "y": 21},
- {"series": "France", "x": 1.5, "y": 3},
- {"series": "South Africa", "x": 0.9, "y": 0.3}
- ]')),
- ('chart', '
-## Heatmaps
-
-You can build heatmaps using the `heatmap` top-level property.
-
-The data format follows the [apexcharts heatmap format](https://apexcharts.com/angular-chart-demos/heatmap-charts/basic/),
-where each series is represented as a line in the chart:
- - The `x` property of each item will be used as the x-axis value.
- - The `series` property of each item will be used as the y-axis value.
- - The `y` property of each item will be used as the value to display in the heatmap
-
-The `color` property sets the color of each series separately, in order.
-',json('[
- {"component":"chart", "title": "Survey Results", "type": "heatmap",
- "ytitle": "Database managemet system", "xtitle": "Year", "color": ["purple","purple","purple"]},
- { "series": "PostgreSQL", "x": "2000", "y": 48},{ "series": "SQLite", "x": "2000", "y": 44},{ "series": "MySQL", "x": "2000", "y": 78},
- { "series": "PostgreSQL", "x": "2010", "y": 65},{ "series": "SQLite", "x": "2010", "y": 62},{ "series": "MySQL", "x": "2010", "y": 83},
- { "series": "PostgreSQL", "x": "2020", "y": 73},{ "series": "SQLite", "x": "2020", "y": 38},{ "series": "MySQL", "x": "2020", "y": 87}
- ]')),
- ('chart', 'A timeline displaying events with a start and an end date. A data row can include a `link` to open when its bar or tooltip title is clicked.',
- json('[
- {"component":"chart", "title": "Project Timeline", "type": "rangeBar", "time": true, "color": ["teal", "cyan"], "labels": true, "xmin": "2021-12-28", "xmax": "2022-01-04" },
- {"series": "Phase 1", "label": "Operations", "value": ["2021-12-29", "2022-01-02"], "link": "/examples/chart.sql?phase=1"},
- {"series": "Phase 2", "label": "Operations", "value": ["2022-01-03", "2022-01-04"]},
- {"series": "Yearly maintenance", "label": "Maintenance", "value": ["2022-01-01", "2022-01-03"]}
- ]')),
- ('chart', '
-## Coloring a single value
-
-A data row can carry its own `color`, to paint the one bar, slice or point it
-plots. Use it when the color says something the axes do not: a threshold
-crossed, a status, the one category the reader should look at first.
-
-```sql
-select ''chart'' as component, ''bar'' as type, true as horizontal,
- true as labels, false as show_legend;
-select
- window_label as label,
- accounts as value,
- case when days <= 30 then ''red'' when days <= 60 then ''orange'' else ''green'' end as color
-from expiring_accounts order by days;
-```
-
-A row color takes precedence over the color of its series. On a `line` or an
-`area` chart it paints the marker of the point, so set `marker` for it to show.
-A `heatmap` shades its cells from their own value and ignores it.
-', json('[
- {"component":"chart", "title": "Accounts expiring soon", "type": "bar",
- "horizontal": true, "labels": true, "show_legend": false},
- {"label": "30 days", "value": 100, "color": "red"},
- {"label": "60 days", "value": 200, "color": "orange"},
- {"label": "90 days", "value": 300, "color": "green"}
- ]')),
- ('chart', 'A pie chart whose rows choose their own slice colors.', json('[
- {"component":"chart", "title": "Support tickets", "type": "pie", "labels": true},
- {"label": "Resolved", "value": 72, "color": "green"},
- {"label": "In progress", "value": 21, "color": "yellow"},
- {"label": "Overdue", "value": 7, "color": "red"}
- ]')),
- ('chart', '
-## Reference lines
-
-A row with a `yline` is not plotted as a data point, but drawn as a line across
-the whole chart, at that value of the y axis. Use it for the limit that the data
-should be read against: a disk quota, an alarm threshold, a service level
-objective. Add `yline_end` to make it a band instead of a line.
-
-Reference lines are rows, so they come from a query like everything else,
-and a chart can have as many of them as the query returns:
-
-```sql
-select ''chart'' as component, ''CPU temperature'' as title, true as time, 100 as ymax;
-select celsius as yline, name as label, color as color from thresholds;
-select measured_at as x, celsius as y from readings order by measured_at;
-```
-
-They are drawn as annotations rather than as an extra series, so they are not
-added to the total of a `stacked` chart, and are not filled in an `area` chart.
-
-A line outside of the y axis is not drawn, and does not stretch the axis to fit,
-so set `ymax` when the limit is above the data.
-', json('[
- {"component":"chart", "title": "CPU temperature", "type": "line", "time": true,
- "ytitle": "°C", "ymax": 100, "color": "azure", "marker": 4},
- {"yline": 70, "label": "target", "color": "green"},
- {"yline": 90, "yline_end": 100, "label": "throttling", "color": "red"},
- {"x": "2024-05-01T08:00:00Z", "y": 52},
- {"x": "2024-05-01T09:00:00Z", "y": 58},
- {"x": "2024-05-01T10:00:00Z", "y": 71},
- {"x": "2024-05-01T11:00:00Z", "y": 83},
- {"x": "2024-05-01T12:00:00Z", "y": 94},
- {"x": "2024-05-01T13:00:00Z", "y": 76},
- {"x": "2024-05-01T14:00:00Z", "y": 63}
- ]')),
- ('chart', '
-## Marking events
-
-`xline` is the counterpart of `yline`: it marks a position on the x axis instead
-of a value on the y axis. On its own it marks a moment, like a deployment.
-With `xline_end`, it covers everything in between, like an incident or a
-maintenance window. A single query can draw a whole log of them:
-
-```sql
-select started_at as xline, ended_at as xline_end, summary as label,
- case severity when ''outage'' then ''red'' else ''orange'' end as color
-from incidents where started_at > $since;
-```
-
-When `time` is set, an `xline` is a date or a timestamp, written like the `x` of
-a data point. On a chart with text labels on the x axis, it is one of those labels.
-', json('[
- {"component":"chart", "title": "Request latency", "type": "area", "time": true,
- "ytitle": "ms", "color": "blue-lt", "marker": 3},
- {"xline": "2024-05-01T10:00:00Z", "label": "deploy", "color": "green"},
- {"xline": "2024-05-01T11:30:00Z", "xline_end": "2024-05-01T13:00:00Z",
- "label": "incident", "color": "red"},
- {"x": "2024-05-01T08:00:00Z", "y": 120},
- {"x": "2024-05-01T09:00:00Z", "y": 134},
- {"x": "2024-05-01T10:00:00Z", "y": 128},
- {"x": "2024-05-01T11:00:00Z", "y": 141},
- {"x": "2024-05-01T12:00:00Z", "y": 512},
- {"x": "2024-05-01T13:00:00Z", "y": 470},
- {"x": "2024-05-01T14:00:00Z", "y": 156},
- {"x": "2024-05-01T15:00:00Z", "y": 133}
- ]')),
- ('chart', '
-## Reference lines follow their axis
-
-A reference belongs to the column it is written in, not to a direction on the
-screen. `yline` always marks a value of `y`, and `xline` a position on `x`,
-whichever way round the chart is drawn. A `horizontal` bar chart runs its y axis
-from left to right, so a `yline` is drawn down the chart and an `xline` picks out
-one of the bars.
-
-```sql
-select ''chart'' as component, ''bar'' as type, true as horizontal, 100 as ymax;
-select 90 as yline, ''full'' as label, ''red'' as color;
-select ''db-1'' as xline, ''watched'' as label, ''purple'' as color;
-select host as x, percent_used as y from disks order by percent_used;
-```
-
-A `pie` has no axes and ignores reference lines, and on a `heatmap`, whose y axis
-holds the names of the series, only `xline` has a meaning.
-', json('[
- {"component":"chart", "title": "Disk usage", "type": "bar", "horizontal": true,
- "ymax": 100, "color": "azure", "labels": true},
- {"yline": 90, "label": "full", "color": "red"},
- {"xline": "db-1", "label": "watched", "color": "purple"},
- {"x": "backup-1", "y": 41},
- {"x": "web-2", "y": 63},
- {"x": "db-1", "y": 88},
- {"x": "web-1", "y": 96}
- ]')),
- ('chart', '
-## Multiple charts on the same line
-
-You can create information-dense dashboards by using the [card component](?component=card#component)
-to put multiple charts on the same line.
-
-For this, create one sql file per visualization you want to show,
-and set the `embed` attribute of the [card](?component=card#component) component
-to the path of the file you want to include, followed by `?_sqlpage_embed`.
-',
- json('[
- {"component":"card", "title":"A dashboard with multiple graphs on the same line", "columns": 2},
- {"embed": "/examples/chart.sql?color=green&n=42&_sqlpage_embed"},
- {"embed": "/examples/chart.sql?_sqlpage_embed" }
- ]'));
-
-INSERT INTO component(name, icon, description) VALUES
- ('table', 'table', 'A table with optional filtering and sorting.
-Unlike most others, this component does not have a fixed set of item properties, any property that is used will be rendered directly as a column in the table.
-Tables can contain rich text, including images, links, and icons. Table rows can be styled with a background color, and the table can be made striped, hoverable, and bordered.
-
-Advanced users can apply custom styles to table columns using a CSS class with the same name as the column, and to table rows using the `_sqlpage_css_class` property.
-');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'table', * FROM (VALUES
- -- top level
- ('title', 'A title displayed above the table.', 'TEXT', TRUE, TRUE),
- ('sort', 'Make the columns clickable to let the user sort by the value contained in the column.', 'BOOLEAN', TRUE, TRUE),
- ('search', 'Add a search bar at the top of the table, letting users easily filter table rows by value.', 'BOOLEAN', TRUE, TRUE),
- ('initial_search_value', 'Pre-fills the search bar used to filter the table. The user will still be able to edit the value to display table rows that will initially be filtered out.', 'TEXT', TRUE, TRUE),
- ('search_placeholder', 'Customizes the placeholder text shown in the search input field. Replaces the default "Search..." with text that better describes what users should search for.', 'TEXT', TRUE, TRUE),
- ('markdown', 'Set this to the name of a column whose content should be interpreted as markdown . Used to display rich text with links in the table. This argument can be repeated multiple times to intepret multiple columns as markdown.', 'TEXT', TRUE, TRUE),
- ('icon', 'Set this to the name of a column whose content should be interpreted as a tabler icon name. Used to display icons in the table. This argument can be repeated multiple times to intepret multiple columns as icons. Introduced in v0.8.0.', 'TEXT', TRUE, TRUE),
- ('align_right', 'Name of a column the contents of which should be right-aligned. This argument can be repeated multiple times to align multiple columns to the right. Introduced in v0.15.0.', 'TEXT', TRUE, TRUE),
- ('align_center', 'Name of a column the contents of which should be center-aligned. This argument can be repeated multiple times to align multiple columns to the center.', 'TEXT', TRUE, TRUE),
- ('monospace', 'Name of a column the contents of which should be displayed in monospace. This argument can be repeated multiple times to display multiple columns in monospace. Introduced in v0.32.1.', 'TEXT', TRUE, TRUE),
- ('striped_rows', 'Whether to add zebra-striping to any table row.', 'BOOLEAN', TRUE, TRUE),
- ('striped_columns', 'Whether to add zebra-striping to any table column.', 'BOOLEAN', TRUE, TRUE),
- ('hover', 'Whether to enable a hover state on table rows.', 'BOOLEAN', TRUE, TRUE),
- ('border', 'Whether to draw borders on all sides of the table and cells.', 'BOOLEAN', TRUE, TRUE),
- ('overflow', 'Whether to to let "wide" tables overflow across the right border and enable browser-based horizontal scrolling.', 'BOOLEAN', TRUE, TRUE),
- ('small', 'Whether to use compact table.', 'BOOLEAN', TRUE, TRUE),
- ('description','Description of the table contents. Helps users with screen readers to find a table and understand what it’s about.','TEXT',TRUE,TRUE),
- ('empty_description', 'Text to display if the table does not contain any row. Defaults to "no data".', 'TEXT', TRUE, TRUE),
- ('freeze_columns', 'Whether to freeze the leftmost column of the table.', 'BOOLEAN', TRUE, TRUE),
- ('freeze_headers', 'Whether to freeze the top row of the table.', 'BOOLEAN', TRUE, TRUE),
- ('freeze_footers', 'Whether to freeze the footer (bottom row) of the table, only works if that row has the `_sqlpage_footer` property applied to it.', 'BOOLEAN', TRUE, TRUE),
- ('raw_numbers', 'Name of a column whose values are numeric, but should be displayed as raw numbers without any formatting (no thousands separators, decimal separator is always a dot). This argument can be repeated multiple times.', 'TEXT', TRUE, TRUE),
- ('money', 'Name of a numeric column whose values should be displayed as currency amounts, in the currency defined by the `currency` property. This argument can be repeated multiple times.', 'TEXT', TRUE, TRUE),
- ('currency', 'The ISO 4217 currency code (e.g., USD, EUR, GBP, etc.) to use when formatting monetary values.', 'TEXT', TRUE, TRUE),
- ('number_format_digits', 'Maximum number of decimal digits to display for numeric values.', 'INTEGER', TRUE, TRUE),
- ('number_format_locale', 'A BCP 47 language tag (e.g. "de-DE", "en-IN") deciding how numbers and monetary values are formatted. Defaults to the locale of the visitor''s browser.', 'TEXT', TRUE, TRUE),
- ('edit_url', 'If set, an edit button will be added to each row. The value of this property should be a URL, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. Clicking the edit button will take the user to that URL. Added in v0.39.0', 'TEXT', TRUE, TRUE),
- ('delete_url', 'If set, a delete button will be added to each row. The value of this property should be a URL, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. Clicking the delete button will take the user to that URL. Added in v0.39.0', 'TEXT', TRUE, TRUE),
- ('custom_actions', 'If set, a column of custom action buttons will be added to each row. The value of this property should be a JSON array of objects, each object defining a button with the following properties: `name` (the text to display on the button), `icon` (the tabler icon name or image link to display on the button), `link` (the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row), and `tooltip` (optional text to display when hovering over the button). Added in v0.39.0', 'JSON', TRUE, TRUE),
- -- row level
- ('_sqlpage_css_class', 'For advanced users. Sets a css class on the table row. Added in v0.8.0.', 'TEXT', FALSE, TRUE),
- ('_sqlpage_color', 'Sets the background color of the row. Added in v0.8.0.', 'COLOR', FALSE, TRUE),
- ('_sqlpage_footer', 'Sets this row as the table footer. It is recommended that this parameter is applied to the last row. Added in v0.34.0.', 'BOOLEAN', FALSE, TRUE),
- ('_sqlpage_id', 'Sets the id of the html tabler row element. Allows you to make links targeting a specific row in a table.', 'TEXT', FALSE, TRUE),
- ('_sqlpage_actions', 'Sets custom action buttons for this specific row in addition to any defined at the table level, The value of this property should be a JSON array of objects, each object defining a button with the following properties: `name` (the text to display on the button), `icon` (the tabler icon name or image link to display on the button), `link` (the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row), and `tooltip` (optional text to display when hovering over the button). Added in v0.39.0', 'JSON', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('table', 'The most basic table.',
- json('[{"component":"table"}, {"a": 1, "b": 2}, {"a": 3, "b": 4}]')),
- ('table', 'A table of users with filtering and sorting.',
- json('[
- {"component":"table", "sort":true, "search":true, "search_placeholder": "Filter by name"},
- {"First Name": "Ophir", "Last Name": "Lojkine", "Pseudonym": "lovasoa"},
- {"First Name": "Linus", "Last Name": "Torvalds", "Pseudonym": "torvalds"}
- ]')),
- ('table', 'A table that uses markdown to display links',
- json('[{"component":"table", "markdown": "Name", "icon": "icon", "search": true}, '||
- '{"icon": "table", "name": "[Table](?component=table)", "description": "Displays SQL results as a searchable table.", "_sqlpage_color": "red"},
- {"icon": "timeline", "name": "[Chart](?component=chart)", "description": "Show graphs based on numeric data."}
- ]')),
- ('table', 'A sortable table with a colored footer showing the average value of its entries.',
- json('[{"component":"table", "sort":true}, '||
- '{"Person": "Rudolph Lingens", "Height": 190},' ||
- '{"Person": "Jane Doe", "Height": 150},' ||
- '{"Person": "John Doe", "Height": 200},' ||
- '{"_sqlpage_footer":true, "_sqlpage_color": "green", "Person": "Average", "Height": 180}]')),
- (
- 'table',
- 'A table with column sorting. Sorting sorts numbers in numeric order, and strings in alphabetical order.
-
-Numbers can be displayed
- - as raw digits without formatting using the `raw_numbers` property,
- - as currency using the `money` property to define columns that contain monetary values and `currency` to define the currency,
- - as numbers with a fixed maximum number of decimal digits using the `number_format_digits` property.
-',
- json(
- '[{"component":"table", "sort": true, "align_right": ["Price", "Amount in stock"], "align_center": ["part_no"], "raw_numbers": ["id"], "currency": "USD", "money": ["Price"] },
- {"id": 31456, "part_no": "SQL-TABLE-856-G", "Price": 12, "Amount in stock": 5},
- {"id": 996, "part_no": "SQL-FORMS-86-M", "Price": 1, "Amount in stock": 1234},
- {"id": 131456, "part_no": "SQL-CARDS-56-K", "Price": 127, "Amount in stock": 98}
- ]'
- )),
- (
- 'table',
- 'A table with some presentation options',
- json(
- '[{"component":"table",
- "hover": true, "striped_rows": true,
- "description": "Some Star Trek Starfleet starships",
- "small": true, "initial_search_value": "NCC-"
- },
- {"name": "USS Enterprise", "registry": "NCC-1701-C", "class":"Ambassador"},
- {"name": "USS Archer", "registry": "NCC-44278", "class":"Archer"},
- {"name": "USS Endeavour", "registry": "NCC-06", "class":"Columbia"},
- {"name": "USS Constellation", "registry": "NCC-1974", "class":"Constellation"},
- {"name": "USS Dakota", "registry": "NCC-63892", "class":"Akira"},
- {"name": "USS Defiant", "registry": "IX-74205", "class":"Defiant"}
- ]'
- )),
- (
- 'table',
- 'An empty table with a friendly message',
- json('[{"component":"table", "empty_description": "Nothing to see here at the moment."}]')
- ),
- (
- 'table',
- 'A large table with many rows and columns, with frozen columns on the left and headers on top. This allows users to browse large datasets without loosing track of their position.',
- json('[
- {"component": "table", "freeze_columns": true, "freeze_headers": true},
- {
- "feature": "SQL Execution",
- "description": "Fully compatible with existing databases SQL dialects, executes any SQL query.",
- "benefits": "Short learning curve, easy to use, interoperable with existing tools."
- },
- {
- "feature": "Data Visualization",
- "description": "Automatic visualizations of query results: graphs, plots, pie charts, heatmaps, etc.",
- "benefits": "Quickly analyze data trends, attractive and easy to understand, no external visualization tools or languages to learn."
- },
- {
- "feature": "User Authentication",
- "description": "Supports user sessions, from basic auth to single sign-on.",
- "benefits": "Secure, enforces access control policies, and provides a customizable security layer."
- },
- {
- "feature": "APIs",
- "description": "Allows building JSON REST APIs and integrating with external APIs.",
- "benefits": "Enables automation and integration with other platforms, facilitates data exchange."
- },
- {
- "feature": "Files",
- "description": "File uploads, downloads and processing. Supports local filesystem and database storage.",
- "benefits": "Convenient file management, secure data handling, flexible storage options, integrates with existing systems."
- },
- {
- "feature": "Maps",
- "description": "Supports GeoJSON and is compatible with GIS data for map visualization.",
- "benefits": "Geospatial data representation, integrates with geographic information systems."
- },
- {
- "feature": "Custom Components",
- "description": "Build advanced features using HTML, JavaScript, and CSS.",
- "benefits": "Tailor-made user experiences, easy to implement custom UI requirements."
- },
- {
- "feature": "Forms",
- "description": "Insert and update data in databases based on user input.",
- "benefits": "Simplified data input and management, efficient user interactions with databases."
- },
- {
- "feature": "DB Compatibility",
- "description": "Works with MySQL, PostgreSQL, SQLite, Microsoft SQL Server and compatible databases.",
- "benefits": "Broad compatibility with popular database systems, ensures seamless integration."
- },
- {
- "feature": "Security",
- "description": "Built-in protection against common web vulnerabilities: no SQL injection, no XSS.",
- "benefits": "Passes audits and security reviews, reduces the risk of data breaches."
- },
- {
- "feature": "Performance",
- "description": "Designed for performance, with a focus on efficient data processing and minimal overhead.",
- "benefits": "Quickly processes large datasets, handles high volumes of requests, and minimizes server load."
- },
- {
- "_sqlpage_footer": true,
- "feature": "Summary",
- "description": "Summarizes the features of the product.",
- "benefits": "Provides a quick overview of the product''s features and benefits."
- }
-]')
- ),
- (
- 'table',
- '#### Dynamic column names in a table
-
-In all the previous examples, the column names were hardcoded in the SQL query.
-This makes it very easy to quickly visualize the results of a query as a table,
-but it can be limiting if you want to include columns that are not known in advance.
-In situations when the number and names of the columns depend on the data, or on variables,
-you can use the `dynamic` component to generate the table columns dynamically.
-
-For that, you will need to return JSON objects from your SQL query, where the keys are the column names,
-and the values are the cell contents.
-
-Databases [offer utilities to generate JSON objects from query results](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide)
- - In PostgreSQL, you can use the [`json_build_object`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING)
-function for a fixed number of columns, or [`json_object_agg`](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE) for a dynamic number of columns.
- - In SQLite, you can use the [`json_object`](https://www.sqlite.org/json1.html) function for a fixed number of columns,
-or the `json_group_object` function for a dynamic number of columns.
- - In MySQL, you can use the [`JSON_OBJECT`](https://dev.mysql.com/doc/refman/8.0/en/json-creation-functions.html#function_json-object) function for a fixed number of columns,
-or the [`JSON_OBJECTAGG`](https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html#function_json-objectagg) function for a dynamic number of columns.
- - In Microsoft SQL Server, you can use the [`FOR JSON PATH`](https://docs.microsoft.com/en-us/sql/relational-databases/json/format-query-results-as-json-with-for-json-sql-server?view=sql-server-ver15) clause.
-
-For instance, let''s say we have a table with three columns: store, item, and quantity_sold.
-We want to create a pivot table where each row is a store, and each column is an item.
-We will return a set of json objects that look like this: `{"store":"Madrid", "Item1": 42, "Item2": 7, "Item3": 0}`
-
-```sql
-SELECT ''table'' AS component;
-with filled_data as (
- select
- stores.store, items.item,
- (select coalesce(sum(quantity_sold), 0) from store_sales where store=stores.store and item=items.item) as quantity
- from (select distinct store from store_sales) as stores
- cross join (select distinct item from store_sales) as items
- order by stores.store, items.item
-)
-SELECT
- ''dynamic'' AS component,
- JSON_PATCH( -- SQLite-specific, refer to your database documentation for the equivalent JSON functions
- JSON_OBJECT(''store'', store),
- JSON_GROUP_OBJECT(item, quantity)
- ) AS properties
-FROM
- filled_data
-GROUP BY
- store;
-```
-
-This will generate a table with the stores in the first column, and the items in the following columns, with the quantity sold in each store for each item.
-
-', NULL
- ),
- (
- 'table',
-'## Using Action Buttons in a table.
-
-### Preset Actions: `edit_url` & `delete_url`
-Since edit and delete are common actions, the `table` component has dedicated `edit_url` and `delete_url` properties to add buttons for these actions.
-The value of these properties should be a URL, containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row.
-
-### Column with fixed action buttons
-
-You may want to add custom action buttons to your table rows, for instance to view details, download a file, or perform a custom operation.
-For this, the `table` component has a `custom_actions` top-level property that lets you define a column of buttons, each button defined by a name, an icon, a link, and an optional tooltip.
-
-### Column with variable action buttons
-
-The `table` component also supports the row level `_sqlpage_actions` column in your data table.
-This is helpful if you want a more complex logic, for instance to disable a button on some rows, or to change the link or icon based on the row data.
-
-> WARNING!
-> If the number of array items in `_sqlpage_actions` is not consistent across all rows, the table may not render correctly.
-> You can leave blank spaces by including an object with only the `name` property.
-
-The table has a column of buttons, each button defined by the `custom_actions` column at the table level, and by the `_sqlpage_actions` property at the row level.
-
-### `custom_actions` & `_sqlpage_actions` JSON properties.
-
-Each button is defined by the following properties:
-* `name`: sets the column header and the tooltip if no tooltip is provided,
-* `tooltip`: text to display when hovering over the button,
-* `link`: the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row,
-* `icon`: the tabler icon name or image link to display on the button
-
-### Example using all of the above
-'
- ,
- json('[
- {
- "component": "table",
- "edit_url": "/examples/show_variables.sql?action=edit&update_id={id}",
- "delete_url": "/examples/show_variables.sql?action=delete&delete_id={id}",
- "custom_actions": {
- "name": "history",
- "tooltip": "View Standard History",
- "link": "/examples/show_variables.sql?action=history&standard_id={id}",
- "icon": "history"
- }
- },
- {
- "name": "CalStd",
- "vendor": "PharmaCo",
- "Product": "P1234",
- "lot number": "T23523",
- "status": "Available",
- "expires on": "2026-10-13",
- "_sqlpage_id": 32,
- "_sqlpage_actions": [
- {
- "name": "View PDF",
- "tooltip": "View Presentation",
- "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf",
- "icon": "file-type-pdf"
- },
- {
- "name": "Action",
- "tooltip": "Set In Use",
- "link": "/examples/show_variables.sql?action=set_in_use&standard_id=32",
- "icon": "caret-right"
- }
- ]
- },
- {
- "name": "CalStd",
- "vendor": "PharmaCo",
- "Product": "P1234",
- "lot number": "T2352",
- "status": "In Use",
- "expires on": "2026-10-14",
- "_sqlpage_id": 33,
- "_sqlpage_actions": [
- {
- "name": "View PDF",
- "tooltip": "View Presentation",
- "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf",
- "icon": "file-type-pdf"
- },
- {
- "name": "Action",
- "tooltip": "Retire Standard",
- "link": "/examples/show_variables.sql?action=retire&standard_id=33",
- "icon": "test-pipe-off"
- }
- ]
- },
- {
- "name": "CalStd",
- "vendor": "PharmaCo",
- "Product": "P1234",
- "lot number": "A123",
- "status": "Discarded",
- "expires on": "2026-09-30",
- "_sqlpage_id": 31,
- "_sqlpage_actions": [
- {
- "name": "View PDF",
- "tooltip": "View Presentation",
- "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf",
- "icon": "file-type-pdf"
- },
- {
- "name": "Action"
- }
- ]
- }
-]'
-)
-);
-
-
-
-INSERT INTO component(name, icon, description) VALUES
- ('csv', 'download', 'Lets the user download data as a CSV file.
-Each column from the items in the component will map to a column in the resulting CSV.
-
-When `csv` is used as a **header component** (without a [shell](?component=shell)), it will trigger a download of the CSV file directly on page load.
-If the csv file to download is large, we recommend using this approach.
-
-When used inside a page (after calling the shell component), this will add a button to the page that lets the user download the CSV file.
-The button will need to load the entire contents of the CSV file in memory, inside the browser, even if the user does not click on it.
-If the csv file to download is large, we recommend using this component without a shell component in order to efficiently stream the data to the browser.
-');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'csv', * FROM (VALUES
- -- top level
- ('separator', 'How individual values should be separated in the CSV. "," by default, set it to "\t" for tab-separated values.', 'TEXT', TRUE, TRUE),
- ('title', 'The text displayed on the download button.', 'TEXT', TRUE, FALSE),
- ('filename', 'The name of the file that should be downloaded (without the extension).', 'TEXT', TRUE, TRUE),
- ('icon', 'Name of the icon (from tabler-icons.io) to display in the button. Ignored when used as a header component.', 'ICON', TRUE, TRUE),
- ('color', 'Color of the button. Ignored when used as a header component.', 'COLOR', TRUE, TRUE),
- ('size', 'The size of the button (e.g., sm, lg). Ignored when used as a header component.', 'TEXT', TRUE, TRUE),
- ('bom', 'Whether to include a Byte Order Mark (a special character indicating the character encoding) at the beginning of the file. This is useful for Excel compatibility.', 'BOOLEAN', TRUE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('csv', '
-### Header component: creating a CSV download URL
-
-You can create a page that will trigger a download of the CSV file when the user visits it.
-The contents will be streamed efficiently from the database to the browser, without being fully loaded in memory.
-This makes it possible to download even very large files without overloading the database server, the web server, or the client''s browser.
-
-#### `csv_download.sql`
-
-```sql
-select ''csv'' as component, ''example.csv'' as filename;
-SELECT * FROM my_large_table;
-```
-
-#### `index.sql`
-',
- json('[{"component":"button"}, {"title": "Download my data", "link": "/examples/csv_download.sql"}]')),
- ('csv', '
-### CSV download button
-
-This will generate a button to download the CSV file.
-The button element itself will embed the entire contents of the CSV file, so it should not be used for large files.
-The file will be entirely loaded in memory on the user''s browser, even if the user does not click on the button.
-For smaller files, this is easier and faster to use than creating a separate SQL file to generate the CSV.
-',
- json('[{"component":"csv", "title": "Download my data", "filename": "people", "icon": "file-download", "color": "green", "separator": ";", "bom": true}, '||
- '{"Forename": "Ophir", "Surname": "Lojkine", "Pseudonym": "lovasoa"},' ||
- '{"Forename": "Linus", "Surname": "Torvalds", "Pseudonym": "torvalds"}]'));
-
-
-INSERT INTO component(name, icon, description) VALUES
- ('dynamic', 'repeat', 'Renders other components, given their properties as JSON.
-If you are looking for a way to run FOR loops, to share similar code between pages of your site,
-or to render multiple components for every line returned by your SQL query, then this is the component to use');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'dynamic', * FROM (VALUES
- -- top level
- ('properties', 'A json object or array that contains the names and properties of other components.', 'JSON', TRUE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('dynamic', 'The dynamic component has a single top-level property named `properties`, but it can render any number of other components.
-Let''s start with something simple to illustrate the logic. We''ll render a `text` component with two row-level properties: `contents` and `italics`.
-', json('[{"component":"dynamic", "properties": "[{\"component\":\"text\"}, {\"contents\":\"Hello, I am a dynamic component !\", \"italics\":true}]"}]')),
- ('dynamic', '
-## Static component data stored in `.json` files
-
-You can also store the data for a component in a `.json` file, and load it using the `dynamic` component.
-
-This is particularly useful to create a single [shell](?component=shell#component) defining the site''s overall appearance and menus,
-and displaying it on all pages without duplicating its code.
-
-The following will load the data for a `shell` component from a file named `shell.json`,
-using the [`sqlpage.read_file_as_text`](/functions.sql?function=read_file_as_text) function.
-
-```sql
-SELECT ''dynamic'' AS component, sqlpage.read_file_as_text(''shell.json'') AS properties;
-```
-
-and `shell.json` would be placed at the website''s root and contain the following:
-
-```json
-{
- "component": "shell",
- "title": "SQLPage documentation",
- "link": "/",
- "menu_item": [
- {"link": "index.sql", "title": "Home"},
- {"title": "Community", "submenu": [
- {"link": "blog.sql", "title": "Blog"},
- {"link": "https//github.com/sqlpage/SQLPage/issues", "title": "Issues"},
- {"link": "https//github.com/sqlpage/SQLPage/discussions", "title": "Discussions"},
- {"link": "https//github.com/sqlpage/SQLPage", "title": "Github"}
- ]}
- ]
-}
-```
-', NULL),
-('dynamic', '
-## Including another SQL file
-
-To avoid repeating the same code on multiple pages, you can include another SQL file using the `dynamic` component
-together with the [`sqlpage.run_sql`](/functions.sql?function=run_sql) function.
-
-For instance, the following will include the file `shell.sql` at the top of the page,
-and pass it a `$title` variable to display the page title.
-
-```sql
-SELECT ''dynamic'' AS component,
- sqlpage.run_sql(''shell.sql'', json_object(''title'', ''SQLPage documentation'')) AS properties;
-```
-
-And `shell.sql` could contain the following:
-
-```sql
-SELECT ''shell'' AS component,
- COALESCE($title, ''Default title'') AS title,
- ''/my_icon.png'' AS icon,
- ''products'' AS menu_item,
- ''about'' AS menu_item;
-```
-
-', NULL),
- ('dynamic', '
-## Dynamic shell
-
-On databases without a native JSON type (such as the default SQLite database),
-you can use the `dynamic` component to generate
-json data to pass to components that expect it.
-
-This example generates a menu similar to the [shell example](?component=shell#component), but without using a native JSON type.
-
-```sql
-SELECT ''dynamic'' AS component, ''
-{
- "component": "shell",
- "title": "SQLPage documentation",
- "link": "/",
- "menu_item": [
- {"link": "index.sql", "title": "Home"},
- {"title": "Community", "submenu": [
- {"link": "blog.sql", "title": "Blog"},
- {"link": "https//github.com/sqlpage/SQLPage/issues", "title": "Issues"},
- {"link": "https//github.com/sqlpage/SQLPage/discussions", "title": "Discussions"},
- {"link": "https//github.com/sqlpage/SQLPage", "title": "Github"}
- ]}
- ]
-}
-'' AS properties
-```
-
-[View the result of this query, as well as an example of how to generate a dynamic menu
-based on the database contents](./examples/dynamic_shell.sql).
-', NULL),
- ('dynamic', '
-## Dynamic tables
-
-The `dynamic` component can be used to generate [tables](?component=table#component) with dynamic columns,
-using [your database''s JSON functions](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide).
-
-For instance, let''s say we have a table with three columns: user_id, name, and role.
-We want to create a table where each row is a user, and each column is a role.
-We will return a set of json objects that look like this: `{"name": "Alice", "admin": true, "editor": false, "viewer": true}`
-```sql
-SELECT ''table'' AS component;
-SELECT ''dynamic'' AS component,
- json_patch(
- json_object(''name'', name),
- json_object_agg(role, is_admin)
- ) AS properties
-FROM users
-GROUP BY name;
-```
-', NULL);
-
-INSERT INTO component(name, icon, description) VALUES
- ('shell', 'layout-navbar', '
-Customize the overall layout, header and footer of the page.
-
-This is a special component that provides the page structure wrapping all other components on your page.
-
-It generates the complete HTML document including the `` section with metadata, title, and stylesheets,
-as well as the navigation bar, main content area, and footer.
-
-If you don''t explicitly call the shell component at the top of your SQL file, SQLPage will automatically
-add a default shell component before your first try to display data on the page.
-
-Use the shell component to customize page-wide settings like the page title, navigation menu, theme, fonts,
-and to include custom visual styles (with CSS) or interactive behavior (with JavaScript) that should be loaded on the page.
-');
-
-INSERT INTO parameter(component, name, description_md, type, top_level, optional) SELECT 'shell', * FROM (VALUES
- ('favicon', 'The URL of the icon the web browser should display in bookmarks and tabs. This property is particularly useful if multiple sites are hosted on the same domain with different [``site_prefix``](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage).', 'URL', TRUE, TRUE),
- ('manifest', 'The location of the [manifest.json](https://developer.mozilla.org/en-US/docs/Web/Manifest) if the site is a [PWA](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps). Among other features, serving a manifest enables your site to be "installed" as an app on most mobile devices.', 'URL', TRUE, TRUE)
-) x;
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'shell', * FROM (VALUES
- -- top level
- ('title', 'The title of your page. Will be shown in a top bar above the page contents. Also usually displayed by web browsers as the name of the web page''s tab.', 'TEXT', TRUE, TRUE),
- ('layout', 'The general page layout. Can be "boxed" (the default), "horizontal" (for a full-width menu), "vertical"(vertical menu), "fluid" (removes side margins).', 'TEXT', TRUE, TRUE),
- ('description', 'A description of the page. It can be displayed by search engines when your page appears in their results.', 'TEXT', TRUE, TRUE),
- ('link', 'The target of the link in the top navigation bar.', 'URL', TRUE, TRUE),
- ('css', 'The URL of a CSS file to load and apply to the page.', 'URL', TRUE, TRUE),
- ('javascript', 'The URL of a Javascript file to load and execute on the page.', 'URL', TRUE, TRUE),
- ('javascript_module', 'The URL of a javascript module in the ESM format (see javascript.info/modules)', 'URL', TRUE, TRUE),
- ('rss', 'The URL of an RSS feed to display in the top navigation bar. You can use the rss component to generate the field.', 'URL', TRUE, TRUE),
- ('image', 'The URL of an image to display next to the page title.', 'URL', TRUE, TRUE),
- ('social_image', 'The URL of the preview image that will appear in the Open Graph metadata when the page is shared on social media.', 'URL', TRUE, TRUE),
- ('icon', 'Name of an icon (from tabler-icons.io) to display next to the title in the navigation bar.', 'ICON', TRUE, TRUE),
- ('menu_item', 'Adds a menu item in the navigation bar at the top of the page. The menu item will have the specified name, and will link to as .sql file of the same name. A dropdown can be generated by passing a json object with a `title` and `submenu` properties.', 'TEXT', TRUE, TRUE),
- ('fixed_top_menu', 'Fixes the top bar with menu at the top (the top bar remains visible when scrolling long pages).', 'BOOLEAN', TRUE, TRUE),
- ('search_target', 'When this is set, a search field will appear in the top navigation bar, and load the specified sql file with an URL parameter named "search" when the user searches something.', 'TEXT', TRUE, TRUE),
- ('search_value', 'This value will be placed in the search field when "search_target" is set. Using the "$search" query parameter value will mirror the value that the user has searched for.', 'TEXT', TRUE, TRUE),
- ('search_placeholder', 'Customizes the placeholder text shown in the search input field. Replaces the default "Search" with text that better describes what users should search for. It is also used as the accessible name of the search field, which screen readers announce.', 'TEXT', TRUE, TRUE),
- ('search_button', 'Customizes the text displayed on the search button. Replaces the default "Search" label with custom text that may better match your applications terminology or language.', 'TEXT', TRUE, TRUE),
- ('norobot', 'Forbids robots to save this page in their database and follow the links on this page. This will prevent this page to appear in Google search results for any query, for instance.', 'BOOLEAN', TRUE, TRUE),
- ('font', 'Specifies the font to be used for displaying text, which can be a valid font name from fonts.google.com or the path to a local WOFF2 font file starting with a slash (e.g., "/fonts/MyLocalFont.woff2").', 'TEXT', TRUE, TRUE),
- ('font_size', 'Font size on the page, in pixels. Set to 18 by default.', 'INTEGER', TRUE, TRUE),
- ('language', 'The language of the page. This can be used by search engines and screen readers to determine in which language the page is written.', 'TEXT', TRUE, TRUE),
- ('rtl', 'Whether the page should be displayed in right-to-left mode. Used to display Arabic, Hebrew, Persian, etc.', 'BOOLEAN', TRUE, TRUE),
- ('refresh', 'Number of seconds after which the page should refresh. This can be useful to display dynamic content that updates automatically.', 'INTEGER', TRUE, TRUE),
- ('sidebar', 'Whether the menu defined by menu_item should be displayed on the left side of the page instead of the top. Introduced in v0.27.', 'BOOLEAN', TRUE, TRUE),
- ('sidebar_theme', 'Used with sidebar property, It can be set to "dark" to exclusively set the sidebar into dark theme.', 'TEXT', TRUE, TRUE),
- ('theme', 'Set to "dark" to use a dark theme.', 'TEXT', TRUE, TRUE),
- ('footer', 'Muted text to display in the footer of the page. This can be used to display a link to the terms and conditions of your application, for instance. By default, shows "Built with SQLPage". Supports links with markdown.', 'TEXT', TRUE, TRUE),
- ('preview_image', 'The URL of an image to display as a link preview when the page is shared on social media', 'URL', TRUE, TRUE),
- ('navbar_title', 'The title shown in the navigation bar or sidebar. Defaults to the page title. Set an empty string to show just the logo.', 'TEXT', TRUE, TRUE),
- ('target', 'Where the menu items should open: "_blank" for a new tab, "_self" for the same tab, "_parent" for the parent frame, or "_top" for the full body of the window. Set it inside a "menu_item" json object; it has no effect when set directly on the shell.', 'TEXT', TRUE, TRUE),
- ('class', 'class attribute added to the page''s html element. It can be used to apply custom styling to the whole page through css.', 'TEXT', TRUE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('shell', '
-This example configures a dark shell with menus linking to pages on this site.
-
-Each `menu_item` object defines a link or a dropdown. The "Community" menu links to the blog, issue tracker, discussions, and source code.
-
-The object form can be used directly only on database engines that have a native JSON type.
-On other engines (such as SQLite), you can use the [`dynamic`](?component=dynamic#component) component to generate the same result.
-
-
-You see the [page layouts demo](./examples/layouts.sql) for a live example of the different layouts.
-',
- json('[{
- "component": "shell",
- "title": "SQLPage: SQL websites",
- "navbar_title": "SQLPage",
- "link": "/",
- "menu_item": [
- {"title": "About", "submenu": [
- {"link": "/safety.sql", "title": "Security", "icon": "lock"},
- {"link": "/performance.sql", "title": "Performance", "icon": "bolt"},
- {"link": "//github.com/sqlpage/SQLPage/blob/main/LICENSE.txt", "title": "License", "icon": "file-text"},
- {"link": "/blog.sql", "title": "Articles", "icon": "book"}
- ]},
- {"title": "Examples", "submenu": [
- {"link": "/examples/tabs/", "title": "Tabs", "icon": "layout-navbar"},
- {"link": "/examples/layouts.sql", "title": "Layouts", "icon": "layout"},
- {"link": "/examples/multistep-form", "title": "Forms", "icon": "edit"},
- {"link": "/examples/handle_picture_upload.sql", "title": "File uploads", "icon": "upload"},
- {"link": "/examples/authentication/", "title": "Password protection", "icon": "password-user"},
- {"link": "//github.com/sqlpage/SQLPage/blob/main/examples/", "title": "All examples & demos", "icon": "code"}
- ]},
- {"title": "Community", "submenu": [
- {"link": "/blog.sql", "title": "Blog", "icon": "book"},
- {"link": "//github.com/sqlpage/SQLPage/issues", "title": "Report a bug", "icon": "bug"},
- {"link": "//github.com/sqlpage/SQLPage/discussions", "title": "Discussions", "icon": "message"},
- {"link": "//github.com/sqlpage/SQLPage", "title": "Github", "icon": "brand-github"}
- ]},
- {"title": "Documentation", "submenu": [
- {"link": "/your-first-sql-website", "title": "Getting started", "icon": "book"},
- {"link": "/components.sql", "title": "All Components", "icon": "list-details"},
- {"link": "/functions.sql", "title": "SQLPage Functions", "icon": "math-function"},
- {"link": "/extensions-to-sql", "title": "Extensions to SQL", "icon": "cube-plus"},
- {"link": "/custom_components.sql", "title": "Custom Components", "icon": "puzzle"},
- {"link": "//github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage", "title": "Configuration", "icon": "settings"}
- ]},
- {"title": "Search", "link": "/search"}
- ],
- "layout": "boxed",
- "language": "en-US",
- "description": "Go from SQL queries to web applications in an instant.",
- "preview_image": "https://sql-page.com/sqlpage_social_preview.webp",
- "theme": "dark",
- "font_size": 19,
- "image": "/assets/icon.webp",
- "favicon": "/favicon.ico",
- "javascript_module": "/assets/highlightjs-launch.js",
- "css": "/assets/highlightjs-and-tabler-theme.css",
- "footer": "[Built with SQLPage](https://github.com/sqlpage/SQLPage/tree/main/examples/official-site)"
- }]')),
- ('shell', '
-This example shows how to set menu items as active in the navigation, so that they are highlighted in the nav bar.
-
-In this example you can see that two menu items are created, "Home" and "About" and the "Home" tab is marked as active.
-',
- json('[{
- "component": "shell",
- "title": "SQLPage: SQL websites",
- "icon": "database",
- "link": "/",
- "menu_item": [
- {"title": "Home", "active": true},
- {"title": "About"}
- ]
- }]')),
-
- ('shell', '
-### Sharing the shell between multiple pages
-
-It is common to want to share the same shell between multiple pages.
-
-#### Static menu
-
-If your menu is completely static (it does not depend on the database content),
-you can use the [`dynamic`](?component=dynamic#component) component together with the
-[`sqlpage.read_file_as_text`](functions.sql?function=read_file_as_text#function) function to load the shell from
-a json file.
-
-```sql
-SELECT ''dynamic'' AS component, sqlpage.read_file_as_text(''shell.json'') AS properties;
-```
-
-and in `shell.json`:
-
-```json
-{
- "component": "shell",
- "title": "SQL + JSON = <3",
- "link": "/",
- "menu_item": [
- {"link": "index.sql", "title": "Home"},
- {"title": "Community", "submenu": [
- {"link": "/blog.sql", "title": "Blog"},
- {"link": "//github.com/sqlpage/SQLPage", "title": "Github"}
- ]}
- ]
-}
-```
-
-#### Dynamic menu
-
-If your menu depends on the database content, or on special `sqlpage` functions,
-you can use the `dynamic` component,
-but this time with the [`sqlpage.run_sql`](functions.sql?function=run_sql#function)
-function to generate the menu from the database.
-
-```sql
-SELECT ''dynamic'' AS component, sqlpage.run_sql(''shell.sql'') AS properties;
-```
-
-and in `shell.sql`:
-
-```sql
-SELECT ''shell'' AS component, ''run_sql is cool'' as title,
- json_group_array(json_object(
- ''link'', link,
- ''title'', title
- )) as menu_item
-FROM my_menu_items
-```
-
-(check your database documentation for the exact syntax of the `json_group_array` function).
-
-Another case when dynamic menus are useful is when you want to show some
-menu items only in certain conditions.
-
-For instance, you could show an "Admin panel" menu item only to users with the "admin" role,
-a "Profile" menu item only to authenticated users,
-and a "Login" menu item only to unauthenticated users:
-
-```sql
-set role = (
- SELECT role FROM users
- INNER JOIN sessions ON users.id = sessions.user_id
- WHERE sessions.session_id = sqlpage.cookie(''session_id'')
-); -- Read more about how to handle user sessions in the "authentication" component documentation
-
-SELECT
- ''shell'' AS component,
- ''My authenticated website'' AS title,
-
- -- Add an admin panel link if the user is an admin
- CASE WHEN $role = ''admin'' THEN ''{"link": "admin.sql", "title": "Admin panel"}'' END AS menu_item,
-
- -- Add a profile page if the user is authenticated
- CASE WHEN $role IS NOT NULL THEN ''{"link": "profile.sql", "title": "My profile"}'' END AS menu_item,
-
- -- Add a login link if the user is not authenticated
- CASE WHEN $role IS NULL THEN ''login'' END AS menu_item
-;
-```
-
-More about how to handle user sessions in the [authentication component documentation](?component=authentication#component).
-
-### Menu with icons
-
-The "icon" attribute may be specified for items in the top menu and submenus to display an icon
-before the title (or instead). Similarly, the "image" attribute defines a file-based icon. For
-image-based icons, the "size" attribute may be specified at the top level of menu_item only to
-reduce the size of image-based icons. The following snippet provides an example, which is also
-available [here](examples/menu_icon.sql).
-
-```sql
-SELECT
- ''shell'' AS component,
- ''SQLPage'' AS title,
- ''database'' AS icon,
- ''/'' AS link,
- TRUE AS fixed_top_menu,
- ''{"title":"About","icon": "settings","submenu":[{"link":"/safety.sql","title":"Security","icon": "logout"},{"link":"/performance.sql","title":"Performance"}]}'' AS menu_item,
- ''{"title":"Examples","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg","submenu":[{"link":"/examples/tabs/","title":"Tabs","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg"},{"link":"/examples/layouts.sql","title":"Layouts"}]}'' AS menu_item,
- ''{"title":"Examples","size":"sm","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg","submenu":[{"link":"/examples/tabs/","title":"Tabs","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg"},{"link":"/examples/layouts.sql","title":"Layouts"}]}'' AS menu_item,
- ''Official [SQLPage](https://sql-page.com) documentation'' as footer;
-```
-', NULL),
- ('shell', '
-### Returning custom HTML, XML, plain text, or other formats
-
-Use `shell-empty` to opt out of SQLPage''s component system and return raw data directly.
-
-By default, SQLPage wraps all your content in a complete HTML page with navigation and styling.
-The `shell-empty` component tells SQLPage to skip this HTML wrapper and return only the raw content you specify.
-
-Use it to create endpoints that return things like
- - XML (for JSON, use the [json](?component=json) component)
- - plain text or markdown content (for instance for consumption by LLMs)
- - a custom data format you need
-
-When using `shell-empty`, you should use the [http_header](component.sql?component=http%5Fheader) component first
-to set the correct [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) (like `application/json` or `application/xml`).
-',
- json('[
- {
- "component":"http_header",
- "Content-Type":"application/xml"
- },
- {
- "component":"shell-empty",
- "contents": "\n \n 42 \n john.doe \n "
- }
- ]')
- ),
- ('shell','
-### Generate your own HTML
-If you generate your own HTML from a SQL query, you can also use the `shell-empty` component to include it in a page.
-This is useful when you want to generate a snippet of HTML that can be dynamically included in a larger page.
-Make sure you know what you are doing, and be careful to escape the HTML properly,
-as you are stepping out of the safe SQLPage framework and into the wild world of HTML.
-
-In this scenario, you can use the `html` property, which serves as an alias for the `contents` property.
-This property improves code readability by clearly indicating that you are generating HTML.
-Since SQLPage returns HTML by default, there is no need to specify the content type in the HTTP header.
-',
- json('[{"component":"shell-empty", "html": "\n\n\n My page \n\n\n My page \n\n"}]'));
diff --git a/examples/official-site/sqlpage/migrations/02_hero_component.sql b/examples/official-site/sqlpage/migrations/02_hero_component.sql
deleted file mode 100644
index bee6a8d90..000000000
--- a/examples/official-site/sqlpage/migrations/02_hero_component.sql
+++ /dev/null
@@ -1,184 +0,0 @@
--- Hero
-INSERT INTO
- component(name, icon, description)
-VALUES
- (
- 'hero',
- 'home',
- 'Display a large title and description for your page, with an optional large illustrative image. Useful in your home page, for instance.'
- );
-
-INSERT INTO
- parameter(
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-SELECT
- 'hero',
- *
-FROM
- (
- VALUES
- -- top level
- (
- 'title',
- 'The title of your page. Will be shown in very large characters at the top.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'description',
- 'A description of the page. Displayed below the title, in smaller characters and slightly greyed out.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'description_md',
- 'A description of the page. Displayed below the title, in smaller characters and slightly greyed out - formatted using markdown.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'image',
- 'The URL of an image to display next to the page title.',
- 'URL',
- TRUE,
- TRUE
- ),
- (
- 'video',
- 'The URL of a video to display next to the page title.',
- 'URL',
- TRUE,
- TRUE
- ),
- (
- 'link',
- 'Creates a large "call to action" button below the description, linking to the specified URL.',
- 'URL',
- TRUE,
- TRUE
- ),
- (
- 'link_text',
- 'The text to display in the call to action button. Defaults to "Go".',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'poster',
- 'URL of the image to be displayed before the video starts. Ignored if no video is present.',
- 'URL',
- TRUE,
- TRUE
- ),
- (
- 'nocontrols',
- 'Hide the video controls (play, pause, volume, etc.), and autoplay the video.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- ('muted', 'Mute the video', 'BOOLEAN', TRUE, TRUE),
- ('autoplay', 'Automatically start playing the video', 'BOOLEAN', TRUE, TRUE),
- ('loop', 'Loop the video', 'BOOLEAN', TRUE, TRUE),
- (
- 'reverse',
- 'Reverse the order of the image and text: the image will be on the left, and the text on the right. On small screens, the image will be above the text.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- -- item level
- (
- 'title',
- 'The name of a single feature section highlighted by this hero.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'description',
- 'Description of the feature section.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'description_md',
- 'Description of the feature section - formatted using markdown.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'icon',
- 'Icon of the feature section.',
- 'ICON',
- FALSE,
- TRUE
- ),
- (
- 'color',
- 'Color of the badge behind the feature section''s icon. Defaults to "success".',
- 'COLOR',
- FALSE,
- TRUE
- ),
- (
- 'link',
- 'An URL to which the user should be taken when they click on the section title.',
- 'TEXT',
- FALSE,
- TRUE
- )
- ) x;
-
-INSERT INTO
- example(component, description, properties)
-VALUES
- (
- 'hero',
- 'The simplest possible hero section',
- json(
- '[{
- "component":"hero",
- "title": "Welcome",
- "description": "This is a very simple site built with SQLPage."
- }]'
- )
- ),
- (
- 'hero',
- 'A hero with a background image.',
- json(
- '[{
- "component":"hero",
- "title": "SQLPage",
- "description_md": "Documentation for the *SQLPage* low-code web application framework.",
- "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Lac_de_Zoug.jpg/1280px-Lac_de_Zoug.jpg",
- "link": "/documentation.sql",
- "link_text": "Read Documentation !"},' || '{"title": "Fast", "description": "Pages load instantly, even on slow mobile networks.", "icon": "car", "color": "red", "link": "/"},' || '{"title": "Beautiful", "description": "Uses pre-defined components that look professional.", "icon": "eye", "color": "green", "link": "/"},' || '{"title": "Easy", "description_md": "You can teach yourself enough SQL to use [**SQLPage**](https://sql-page.com) in a weekend.", "icon": "sofa", "color": "blue", "link": "/"}' || ']'
- )
- ),
- (
- 'hero',
- 'A hero with a video',
- json(
- '[{
- "component":"hero",
- "title": "Databases",
- "reverse": true,
- "description_md": "# “The goal is to turn data into information, and information into insight.”",
- "poster": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Lac_de_Zoug.jpg/1280px-Lac_de_Zoug.jpg",
- "video": "/sqlpage_introduction_video.mp4"
- }]')
- );
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/03_alert_component.sql b/examples/official-site/sqlpage/migrations/03_alert_component.sql
deleted file mode 100644
index 92e672c29..000000000
--- a/examples/official-site/sqlpage/migrations/03_alert_component.sql
+++ /dev/null
@@ -1,188 +0,0 @@
--- Alert component
-INSERT INTO component(name, icon, description)
-VALUES (
- 'alert',
- 'alert-triangle',
- 'A visually distinctive message or notification.'
- );
-INSERT INTO parameter(
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES (
- 'alert',
- 'title',
- 'Title of the alert message.',
- 'TEXT',
- TRUE,
- FALSE
- ),
- (
- 'alert',
- 'icon',
- 'Icon name (from tabler-icons.io) to display next to the alert message.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'alert',
- 'color',
- 'The color theme for the alert message.',
- 'COLOR',
- TRUE,
- TRUE
- ),
- (
- 'alert',
- 'description',
- 'Detailed description or content of the alert message.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'alert',
- 'description_md',
- 'Detailed description or content of the alert message, in Markdown format, allowing you to use rich text formatting, including `**bold**` and `*italic*` text.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'alert',
- 'dismissible',
- 'Whether the user can close the alert message.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'alert',
- 'important',
- 'Set this to TRUE to make the alert message more prominent.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'alert',
- 'link',
- 'A URL to link to from the alert message.',
- 'URL',
- TRUE,
- TRUE
- ),
- (
- 'alert',
- 'link_text',
- 'Customize the text of the link in the alert message. The default is "Ok".',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'alert',
- 'link',
- 'A URL to link to from the alert message.',
- 'URL',
- FALSE,
- TRUE
- ),
- (
- 'alert',
- 'title',
- 'Customize the text of the link in the alert message. The default is "Ok".',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'alert',
- 'color',
- 'Customize the color of the link.',
- 'COLOR',
- FALSE,
- TRUE
- );
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties)
-VALUES (
- 'alert',
- 'A basic alert message',
- JSON(
- '[{"component":"alert", "title":"Attention", "description":"This is an important message."}]'
- )
- ),
- (
- 'alert',
- 'A list of notifications',
- JSON(
- '[
- {"component" :"alert", "title":"Success","description":"Item successfully added to your cart.", "icon":"check", "color": "green"},
- {"component":"alert", "title":"Warning","description":"Your cart is almost full.", "icon":"alert-triangle", "color": "yellow"},
- {"component":"alert", "title":"Error","description":"Your cart is full.", "icon":"alert-circle", "color": "red"}
- ]'
- )
- ),
- (
- 'alert',
- 'A full-featured notification message with multiple links',
- JSON(
- '[
- {
- "component" :"alert",
- "title": "Your dashboard is ready!",
- "icon":"analyze",
- "color":"teal",
- "dismissible": true,
- "description":"Your public web dashboard was successfully created."
- },
- {
- "link":"dashboard.sql",
- "title": "View your dashboard"
- },
- {
- "link" :"index.sql",
- "title": "Back to home",
- "color": "secondary"
- }
- ]'
- )
- ),
- (
- 'alert',
- 'An important danger alert message with an icon and color',
- JSON(
- '[
- {
- "component":"alert",
- "title":"Alert",
- "icon":"alert-circle",
- "color":"red",
- "important": true,
- "dismissible": true,
- "description":"SQLPage is entirely free and open source.",
- "link":"https://github.com/sqlpage/SQLPage",
- "link_text":"See source code"
- }]'
- )
- ),
- (
- 'alert',
- 'An alert message with a Markdown-formatted description',
- JSON(
- '[
- {
- "component":"alert",
- "title":"Free and open source",
- "icon": "free-rights",
- "color": "info",
- "description_md":"*SQLPage* is entirely free and open source. You can **contribute** to it on [GitHub](https://github.com/sqlpage/SQLPage)."
- }]'
- )
- );
diff --git a/examples/official-site/sqlpage/migrations/04_http_header.sql b/examples/official-site/sqlpage/migrations/04_http_header.sql
deleted file mode 100644
index 1667e4260..000000000
--- a/examples/official-site/sqlpage/migrations/04_http_header.sql
+++ /dev/null
@@ -1,116 +0,0 @@
--- Insert the http_header component into the component table
-INSERT INTO component (name, description, icon)
-VALUES (
- 'http_header',
- '
-An advanced component to set arbitrary HTTP headers: can be used to set a custom caching policy to your pages, or implement custom redirections, for example.
-If you are a beginner, you probably don''t need this component.
-
-When used, this component has to be the first component in the page, because once the page is sent to the browser, it is too late to change the headers.
-
-HTTP headers are additional pieces of information sent with responses to web requests that provide instructions
-or metadata about the data being sent — for example,
-setting cache control directives to control caching behavior
-or specifying the content type of a response.
-
-Any valid HTTP header name can be used as a top-level parameter for this component.
-The examples shown here are just that, examples; and you can create any custom header
-if needed simply by declaring it.
-
-If your header''s name contains a dash or any other special character,
-you will have to use your database''s quoting mechanism to declare it.
-In standard SQL, you can use double quotes to quote identifiers (like "X-My-Header"),
-in Microsoft SQL Server, you can use square brackets (like [X-My-Header]).
- ',
- 'world-www'
- );
--- Insert the parameters for the http_header component into the parameter table
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES (
- 'http_header',
- 'Cache-Control',
- 'Directives for how long the page should be cached by the browser. Set this to max-age=N to keep the page in cache for N seconds.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'http_header',
- 'Content-Disposition',
- 'Provides instructions on how the response content should be displayed or handled by the client, such as inline or as an attachment.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'http_header',
- 'Location',
- 'Specifies the URL to redirect the client to, usually used in 3xx redirection responses.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'http_header',
- 'Set-Cookie',
- 'Sets a cookie in the client browser, used for session management and storing user-related information.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'http_header',
- 'Access-Control-Allow-Origin',
- 'Specifies which origins are allowed to access the resource in a cross-origin request, used for implementing Cross-Origin Resource Sharing (CORS).',
- 'TEXT',
- TRUE,
- TRUE
- );
-
--- Insert an example usage of the http_header component into the example table
-INSERT INTO example (component, description, properties)
-VALUES (
- 'http_header',
- 'Set cache control directives for caching behavior. In this example, the response can be cached by the browser
- and served from the cache for up to 600 seconds (10 minutes) after it is first requested.
- During that time, even if the cached response becomes stale (outdated), the browser can still use it (stale-while-revalidate)
- for up to 3600 seconds (1 hour) while it retrieves a fresh copy from the server in the background.
- If there is an error while trying to retrieve a fresh copy from the server,
- the browser can continue to serve the stale response for up to 86400 seconds (24 hours) (stale-if-error) instead of showing an error page.
- This caching behavior helps improve the performance and responsiveness of the website by reducing the number of requests made to the server
- and allowing the browser to serve content from its cache when appropriate.',
- JSON(
- '[{
- "component": "http_header",
- "Cache-Control": "public, max-age=600, stale-while-revalidate=3600, stale-if-error=86400"
- }]'
- )
- ),
- (
- 'http_header',
- 'Redirect the user to another page. In this example, the user is redirected to a file named another-page.sql at the root of the website. The current page will not be displayed at all.
- This is useful in particular for content creation pages that contain only INSERT statements, because you can redirect the user to the page that lists the content after it has been created.',
- JSON(
- '[{
- "component": "http_header",
- "Location": "/another-page.sql"
- }]'
- )
- ),
- (
- 'http_header',
- 'Set a custom non-standard header for the response. In this example, the response will include a custom header named X-My-Header with the value "my value".',
- JSON(
- '[{
- "component": "http_header",
- "X-My-Header": "my value"
- }]'
- )
- );
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/05_cookie.sql b/examples/official-site/sqlpage/migrations/05_cookie.sql
deleted file mode 100644
index 3b3816546..000000000
--- a/examples/official-site/sqlpage/migrations/05_cookie.sql
+++ /dev/null
@@ -1,125 +0,0 @@
--- Insert the http_header component into the component table
-INSERT INTO component (name, description, icon)
-VALUES (
- 'cookie',
- '
-Sets a cookie in the client browser, used for session management and storing user-related information.
-
-This component creates a single cookie. Since cookies need to be set before the response body is sent to the client,
-this component should be **placed at the top of the page**, before any other components that generate output.
-
-After being set, a cookie can be accessed anywhere in your SQL code using the `sqlpage.cookie(''cookie_name'')` pseudo-function.
-
-Note that if your site is accessed over HTTP (and not HTTPS), you have to set `false as secure` to force browsers to accept your cookies.',
- 'cookie'
- );
--- Insert the parameters for the http_header component into the parameter table
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES (
- 'cookie',
- 'name',
- 'The name of the cookie to set.',
- 'TEXT',
- TRUE,
- FALSE
- ),
- (
- 'cookie',
- 'value',
- 'The value of the cookie to set.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'cookie',
- 'path',
- 'The path for which the cookie will be sent. If not specified, the cookie will be sent for all paths.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'cookie',
- 'domain',
- 'The domain for which the cookie will be sent. If not specified, the cookie will be sent for all domains.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'cookie',
- 'secure',
- 'Whether the cookie should only be sent over a secure (HTTPS) connection. Defaults to TRUE.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'cookie',
- 'http_only',
- 'Whether the cookie should only be accessible via HTTP and not via client-side scripts. If explicitly set to false, the cookie will be accessible via both HTTP and client-side scripts.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'cookie',
- 'remove',
- 'Set to TRUE to remove the cookie from the client browser. When specified, other parameters are ignored.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'cookie',
- 'max_age',
- 'The maximum age of the cookie in seconds. number of seconds until the cookie expires. If both Expires and Max-Age are set, Max-Age has precedence.',
- 'INTEGER',
- TRUE,
- TRUE
- ),
- (
- 'cookie',
- 'expires',
- 'The date at which the cookie expires (either a timestamp or a date object). If not specified, the cookie will expire when the browser is closed.',
- 'TIMESTAMP',
- TRUE,
- TRUE
- ),
- (
- 'cookie',
- 'same_site',
- 'Whether the cookie should only be sent for requests originating from the same site. See owasp.org/www-community/SameSite. `strict` is the recommended and default value, but you may want to set it to `lax` if you want your users to keep their session when they click on a link to your site from an external site.',
- 'TEXT',
- TRUE,
- TRUE
- );
--- Insert an example usage of the http_header component into the example table
-INSERT INTO example (component, description)
-VALUES (
- 'cookie',
- 'Create a cookie named `username` with the value `John Doe`...
-
-```sql
-SELECT ''cookie'' as component,
- ''username'' as name,
- ''John Doe'' as value
- FALSE AS secure; -- You can remove this if the site is served over HTTPS.
-```
-
-and then display the value of the cookie using the [`sqlpage.cookie`](functions.sql?function=cookie) function:
-
-```sql
-SELECT ''text'' as component,
- ''Your name is '' || COALESCE(sqlpage.cookie(''username''), ''not known to us'');
-```
- '
- );
diff --git a/examples/official-site/sqlpage/migrations/06_debug.sql b/examples/official-site/sqlpage/migrations/06_debug.sql
deleted file mode 100644
index 7df4263b5..000000000
--- a/examples/official-site/sqlpage/migrations/06_debug.sql
+++ /dev/null
@@ -1,25 +0,0 @@
--- Insert the http_header component into the component table
-INSERT INTO component (name, description, icon)
-VALUES (
- 'debug',
- 'Visualize any set of values as JSON.
-Can be used to display all the parameters passed to the component.
-Useful for debugging: just replace the name of the component you want to debug with ''debug'', and see all the top-level and row-level parameters that are passed to it, and their types.',
- 'bug'
- );
--- Insert an example usage of the http_header component into the example table
-INSERT INTO example (component, description, properties)
-VALUES (
- 'debug',
- 'At any time, if you are confused about what data you are passing to a component, just replace the component name with ''debug'' to see all the parameters that are passed to it.',
- JSON('[{"component": "debug", "my_top_level_property": true}, {"x": "y", "z": 42}, {"a": "b", "c": null}]')
- ),
- (
- 'debug',
- 'Show the result of a SQLPage function:
-
-```sql
-select ''debug'' as component, sqlpage.environment_variable(''HOME'');
-```',
- NULL
- );
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/07_authentication.sql b/examples/official-site/sqlpage/migrations/07_authentication.sql
deleted file mode 100644
index ca44e9c48..000000000
--- a/examples/official-site/sqlpage/migrations/07_authentication.sql
+++ /dev/null
@@ -1,189 +0,0 @@
--- Insert the http_header component into the component table
-INSERT INTO component (name, description, icon, introduced_in_version)
-VALUES (
- 'authentication',
- '
-Create pages with password-restricted access.
-
-
-When you want to add user authentication to your SQLPage application,
-you have two main options:
-
-1. The `authentication` component:
- - lets you manage usernames and passwords yourself
- - does not require any external service
- - gives you fine-grained control over
- - which pages and actions are protected
- - the look of the [login form](?component=login)
- - the duration of the session
- - the permissions of each user
-2. [**Single sign-on**](/sso)
- - lets users log in with their existing accounts (like Google, Microsoft, or your organization''s own identity provider)
- - requires setting up an external service (Google, Microsoft, etc.)
- - frees you from implementing a lot of features like password reset, account creation, user management, etc.
-
-This page describes the first option.
-
-When used, this component has to be at the top of your page,
-because once the page has begun being sent to the browser,
-it is too late to restrict access to it.
-
-The authentication component checks if the user has sent the correct password,
-and if not, redirects them to the URL specified in the link parameter.
-
-If you don''t want to re-check the password on every page (which is an expensive operation),
-you can check the password only once and store a session token in your database
-(see the session example below).
-
-You can use the [cookie component](?component=cookie) to set the session token cookie in the client browser,
-and then check whether the token matches what you stored in subsequent pages.',
- 'lock',
- '0.7.2'
- );
--- Insert the parameters for the http_header component into the parameter table
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES (
- 'authentication',
- 'link',
- 'The URL to redirect the user to if they are not logged in. If this parameter is not specified, the user will stay on the current page, but be asked to log in using a popup in their browser (HTTP basic authentication).',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'authentication',
- 'password',
- 'The password that was sent by the user. You can set this to :password if you have a login form leading to your page.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'authentication',
- 'password_hash',
- 'The hash of the password that you stored for the user that is currently trying to log in. These hashes can be generated ahead of time using a tool like https://argon2.online/.',
- 'TEXT',
- TRUE,
- TRUE
- );
-
--- Insert an example usage of the http_header component into the example table
-INSERT INTO example (component, description)
-VALUES (
- 'authentication',
- '
-
-### Usage with HTTP basic authentication
-
-The most basic usage of the authentication component is with the
-[`sqlpage.basic_auth_username()`](functions.sql?function=basic_auth_username#function) and
-[`sqlpage.basic_auth_password()`](functions.sql?function=basic_auth_password#function) functions.
-The component will check if the provided password matches the stored [password hash](/examples/hash_password.sql),
-and if not, it will prompt the user to enter a password in a browser popup:
-
-```sql
-SELECT ''authentication'' AS component,
- ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w'' AS password_hash, -- this is a hash of the password ''password''
- sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup
-```
-
-You can [generate a password hash using the `hash_password` function](/examples/hash_password.sql).
-
-If you want to have multiple users with different passwords,
-you could store them with their password hashes in the database,
-or just hardcode them use a `CASE` statement:
-
-```sql
-SELECT ''authentication'' AS component,
- case sqlpage.basic_auth_username()
- when ''admin''
- then ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w'' -- the password is ''password''
- when ''user''
- then ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$qsrWdjgl96ooYw'' -- the password is ''user''
- end AS password_hash, -- this is a hash of the password ''password''
- sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup
-```
-
-Try this example online: [SQL Basic Auth](/examples/authentication/basic_auth.sql).
-
-### Advanced user session management
-
-*Basic auth* is the simplest way to password-protect a page,
-but it is not very flexible nor user-friendly,
-because the browser will show an unstyled popup asking for the username and password.
-
-For more advanced authentication, you can store user information and user sessions in your database.
-You can then use the [`form`](/component.sql?component=form#component) component to create a custom login form.
-When the user submits the form, you check if the password is correct using the `authentication` component.
-You then store a unique string of numbers and letters (a session token) both in the user''s browser
-using the [`cookie`](/component.sql?component=cookie#component) component and in your database.
-Then, in all the pages that require authentication, you check if the cookie is present and matches the session token in your database.
-
-You can check if the user has sent the correct password in a form, and if not, redirect them to a login page.
-
-Create a login form in a file called `login.sql` that uses the [login component](?component=login):
-
-```sql
-select ''login'' as component;
-```
-
-And then, in `create_session_token.sql` :
-
-```sql
-SELECT ''authentication'' AS component,
- ''login.sql'' AS link,
- ''$argon2id$v=19$m=16,t=2,p=1$TERTd0lIcUpraWFTcmRQYw$+bjtag7Xjb6p1dsuYOkngw'' AS password_hash, -- generated using sqlpage.hash_password
- :password AS password; -- this is the password that the user sent through our form
-
--- The code after this point is only executed if the user has sent the correct password
-
-```
-
-and in `login.sql` :
-
-```sql
-SELECT ''form'' AS component, ''Login'' AS title, ''my_protected_page.sql'' AS action;
-SELECT ''password'' AS type, ''password'' AS name, ''Password'' AS label;
-```
-
-### Advanced: usage with a session token
-
-Calling the `authentication` component is expensive.
-The password hashing algorithm is designed to be slow, so that it is difficult to brute-force the password,
-even if an attacker gets access to the database.
-
-If you want to avoid calling the `authentication` component on every page, you can use a session token.
-A session token is a random string that is generated when the user logs in, and stored in the database.
-It has a limited lifetime, and is stored in a cookie in the user''s browser.
-When the user visits a page, the session token is sent to the server, and the server checks if it is valid.
-
-```sql
-SELECT ''authentication'' AS component,
- ''login.sql'' AS link,
- (SELECT password_hash FROM user WHERE username = :username) AS password_hash,
- :password AS password;
-
--- The code after this point is only executed if the user has sent the correct password
-
--- Generate a random session token
-INSERT INTO session (id, username)
-VALUES (sqlpage.random_string(32), :username)
-RETURNING
- ''cookie'' AS component,
- ''session_token'' AS name,
- id AS value;
-```
-
-### Single sign-on with OIDC (OpenID Connect)
-
-If you don''t want to manage your own user database,
-you can [use OpenID Connect and OAuth2](/sso) to authenticate users.
-This allows users to log in with their Google, Microsoft, or internal company account.
-');
diff --git a/examples/official-site/sqlpage/migrations/08_functions.sql b/examples/official-site/sqlpage/migrations/08_functions.sql
deleted file mode 100644
index 30a8a7835..000000000
--- a/examples/official-site/sqlpage/migrations/08_functions.sql
+++ /dev/null
@@ -1,484 +0,0 @@
-CREATE TABLE IF NOT EXISTS sqlpage_functions (
- "name" TEXT PRIMARY KEY,
- "icon" TEXT,
- "description_md" TEXT,
- "return_type" TEXT,
- "introduced_in_version" TEXT
-);
-CREATE TABLE IF NOT EXISTS sqlpage_function_parameters (
- "function" TEXT REFERENCES sqlpage_functions("name"),
- "index" INTEGER,
- "name" TEXT,
- "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 a [header](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) with the given name from the request.
- Returns the value of the header as text, or NULL if the header is not present.
-
-### Example
-
-Log the [`User-Agent`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) of the browser making the request in the database:
-
-```sql
-INSERT INTO user_agent_log (user_agent) VALUES (sqlpage.header(''user-agent''));
-```
-
-If you need access to all headers at once, use [`sqlpage.headers()`](?function=headers) instead.
- '
- );
-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 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;
-```
-'
- );
-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.
-However, this can be changed by setting the `web_root` [configuration option](https://github.com/sqlpage/SQLPage/blob/main/configuration.md).
-'
- );
-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/10_map.sql b/examples/official-site/sqlpage/migrations/10_map.sql
deleted file mode 100644
index 8ef4693b0..000000000
--- a/examples/official-site/sqlpage/migrations/10_map.sql
+++ /dev/null
@@ -1,265 +0,0 @@
-INSERT INTO
- component (name, description, icon, introduced_in_version)
-VALUES
- (
- 'map',
- '
-
-## Visualize SQL data on a map.
-
-The map component displays a custom interactive map with markers on it.
-
-In its simplest form, the component displays points on a map from a table of latitudes and longitudes.
-But it can also be used by cartographers in combination with PostgreSQL''s PostGIS or SQLite''s spatialite,
-to create custom visualizations of geospatial data.
-Use the `geojson` property to generate rich maps from a GIS database.
-
-### Example Use Cases
-
-1. **Store Locator**: Build an interactive map to find the nearest store information using SQL-stored geospatial data.
-2. **Delivery Route Optimization**: Visualize the results of delivery route optimization algorithms.
-3. **Sales Heatmap**: Identify high-performing regions by mapping sales data stored in SQL.
-4. **Real-Time Tracking**: Create dynamic dashboards that track vehicles, assets, or users live using PostGIS or MS SQL Server geospatial time series data. Use the [shell](?component=shell) component to auto-refresh the map.
-5. **Demographic Insights**: Map customer demographics or trends geographically to uncover opportunities for growth or better decision-making.
-',
- 'map',
- '0.8.0'
- );
-
--- Insert the parameters for the http_header component into the parameter table
-INSERT INTO
- parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES
- (
- 'map',
- 'title',
- 'A text header displayed above the map.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'map',
- 'latitude',
- 'Latitude of the center of the map. If omitted, the map will be centered on its markers.',
- 'REAL',
- TRUE,
- TRUE
- ),
- (
- 'map',
- 'longitude',
- 'Longitude of the center of the map.',
- 'REAL',
- TRUE,
- TRUE
- ),
- (
- 'map',
- 'zoom',
- 'Zoom Level to apply to the map. Defaults to 5.',
- 'REAL',
- TRUE,
- TRUE
- ),
- (
- 'map',
- 'max_zoom',
- 'How far the map can be zoomed in. Defaults to 18. Added in v0.15.2.',
- 'INTEGER',
- TRUE,
- TRUE
- ),
- (
- 'map',
- 'tile_source',
- 'Custom map tile images to use, as a URL. Defaults to "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png". Added in v0.15.2.',
- 'URL',
- TRUE,
- TRUE
- ),
- (
- 'map',
- 'attribution',
- 'Text to display at the bottom right of the map. Defaults to "© OpenStreetMap".',
- 'HTML',
- TRUE,
- TRUE
- ),
- (
- 'map',
- 'height',
- 'Height of the map, in pixels. Default to 350px',
- 'INTEGER',
- TRUE,
- TRUE
- ),
- (
- 'map',
- 'latitude',
- 'Latitude of the marker. Required only if geojson is not set.',
- 'REAL',
- FALSE,
- FALSE
- ),
- (
- 'map',
- 'longitude',
- 'Longitude of the marker. Required only if geojson is not set.',
- 'REAL',
- FALSE,
- FALSE
- ),
- (
- 'map',
- 'title',
- 'Title of the marker, displayed on hover and in the tooltip when the marker is clicked.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'map',
- 'link',
- 'A link to associate to the marker''s title. If set, the marker tooltip''s title will be clickable and will open the link.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'map',
- 'description',
- 'Plain text description of the marker, to be displayed in a tooltip when the marker is clicked.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'map',
- 'description_md',
- 'Description of the marker, in markdown, rendered in a tooltip when the marker is clicked.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'map',
- 'icon',
- 'Name of the icon to use for the marker',
- 'ICON',
- FALSE,
- TRUE
- ),
- (
- 'map',
- 'color',
- 'Background color of the marker on the map. Requires "icon" to be set.',
- 'COLOR',
- FALSE,
- TRUE
- ),
- (
- 'map',
- 'geojson',
- 'A GeoJSON geometry (line, polygon, ...) to display on the map. Can be styled using geojson properties using the name of leaflet path options. Introduced in 0.15.1. Accepts raw strings in addition to JSON objects since 0.15.2.',
- 'JSON',
- FALSE,
- TRUE
- ),
- (
- 'map',
- 'size',
- 'Size of the marker icon. Requires "icon" to be set. Introduced in 0.15.2.',
- 'INTEGER',
- FALSE,
- TRUE
- );
-
--- Insert an example usage of the map component into the example table
-INSERT INTO
- example (component, description, properties)
-VALUES
- (
- 'map',
- '
-### Adding a marker to a map
-
-Showing how to place a marker on a map. Useful for basic location displays like showing a single office location, event venue, or point of interest. The marker shows basic hover and click interactions.
-',
- JSON (
- '[{ "component": "map" }, { "title": "New Delhi", "latitude": 28.6139, "longitude": 77.2090 }]'
- )
- ),
- (
- 'map',
- '
-### Advanced map customization using GeoJSON and custom map tiles
-
-This example demonstrates using topographic map tiles, custom marker styling,
-and clickable markers that link to external content - perfect for educational or tourism applications.
-
-It uses [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) to display polygons and lines.
-
- - You can generate GeoJSON data from PostGIS geometries using the [`ST_AsGeoJSON`](https://postgis.net/docs/ST_AsGeoJSON.html) function.
- - In spatialite, you can use the [`AsGeoJSON`](https://www.gaia-gis.it/gaia-sins/spatialite-sql-5.1.0.html#p3misc) function.
- - In MySQL, you can use the [`ST_AsGeoJSON()`](https://dev.mysql.com/doc/refman/8.0/en/spatial-geojson-functions.html#function_st-asgeojson) function.
-',
- JSON (
- '[{ "component": "map", "zoom": 5, "max_zoom": 8, "height": 600, "latitude": -25, "longitude": 28, "tile_source": "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", "attribution": "" },
- { "icon": "peace",
- "size": 20,
- "link": "https://en.wikipedia.org/wiki/Nelson_Mandela",
- "geojson": "{\"type\":\"Feature\", \"properties\": { \"title\":\"Mvezo, Birth Place of Nelson Mandela\" }, \"geometry\": { \"type\":\"Point\", \"coordinates\": [28.49, -31.96] }}"}]'
- )
- ),
- (
- 'map',
- '
-### Maps with links and rich descriptions
-
-Demonstrates how to create an engaging map with custom icons, colors, rich descriptions with markdown support, and connecting points with lines.
-Perfect for visualizing multi-dimensional relationships between points on a map, like routes between locations.
-
-Note that the map tile source is set to a MapTiler map. The API key included in the URL in this demo will not work on your own website.
-You should get your own API key at [MapTiler](https://www.maptiler.com/cloud/).
-',
- JSON (
- '[
- { "component": "map", "title": "Paris", "zoom": 13, "latitude": 48.85, "longitude": 2.34, "tile_source": "https://api.maptiler.com/maps/streets-v2/{z}/{x}/{y}.png?key=RwoF6Y3gcKx4OBMbvqOY" },
- { "title": "Notre Dame", "icon": "building-castle", "color": "indigo", "latitude": 48.8530, "longitude": 2.3498, "description_md": "A beautiful cathedral.", "link": "https://en.wikipedia.org/wiki/Notre-Dame_de_Paris" },
- { "title": "Eiffel Tower", "icon": "tower", "color": "red", "latitude": 48.8584, "longitude": 2.2945, "description_md": "A tall tower. [Wikipedia](https://en.wikipedia.org/wiki/Eiffel_Tower)" },
- { "title": "Tower to Cathedral", "geojson": {"type": "LineString", "coordinates": [[2.2945, 48.8584], [2.3498, 48.8530]]}, "color": "teal", "description": "A nice 45 minutes walk." }
- ]'
- )
- ),
- (
- 'map',
- '
-### Abstract geometric visualizations
-
-Example showing how to create abstract geometric visualizations without a base map.
-Useful for displaying spatial data that doesn''t need geographic context, like floor plans, seating charts,
-or abstract 2D data visualizations.
-',
- JSON (
- '[
- { "component": "map", "tile_source": false },
- { "title": "MySQL",
- "color": "red", "description": "This literal red square is defined as a GeoJSON polygon. Each (x,y) coordinate is a JSON array.",
- "geojson": {"type": "Polygon", "coordinates": [[[0, 0], [0, 4], [4, 4], [4, 0], [0, 0]]]}
- },
- {
- "title": "SQLite",
- "color": "blue", "description": "This 2D shape was generated by a SQL query.",
- "geojson": {"type": "Polygon", "coordinates": [[[5, 0], [9, 0], [7, 4], [5, 0]]]}
- }
- ]'
- )
- );
diff --git a/examples/official-site/sqlpage/migrations/11_json.sql b/examples/official-site/sqlpage/migrations/11_json.sql
deleted file mode 100644
index 8384ab58c..000000000
--- a/examples/official-site/sqlpage/migrations/11_json.sql
+++ /dev/null
@@ -1,211 +0,0 @@
-INSERT INTO
- component (name, description, icon, introduced_in_version)
-VALUES
- (
- 'json',
- 'Converts SQL query results into the JSON machine-readable data format. Ideal to quickly build APIs for interfacing with external systems.
-
-**JSON** is a widely used data format for programmatic data exchange.
-For example, you can use it to integrate with web services written in different languages,
-with mobile or desktop apps, or with [custom client-side components](/custom_components.sql) inside your SQLPage app.
-
-Use it when your application needs to expose data to external systems.
-If you only need to render standard web pages,
-and do not need other software to access your data,
-you can ignore this component.
-
-This component **must appear at the top of your SQL file**, before any other data has been sent to the browser.
-An HTTP response can have only a single datatype, and it must be declared in the headers.
-So if you have already called the `shell` component, or another traditional HTML component,
-you cannot use this component in the same file.
-
-SQLPage can also return JSON or JSON Lines when the incoming request says it prefers them with an HTTP `Accept` header, so the same `/users.sql` page can show a table in a browser but return raw data to `curl -H "Accept: application/json" http://localhost:8080/users.sql`.
-
-Use this component when you want to control the payload or force JSON output even for requests that would normally get HTML.
-',
- 'code',
- '0.9.0'
- );
-
--- Insert the parameters for the http_header component into the parameter table
-INSERT INTO
- parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES
- (
- 'json',
- 'contents',
- 'A single JSON payload to send. You can use your database''s built-in json functions to build the value to enter here. If not provided, the contents will be taken from the next SQL statements and rendered as a JSON array.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'json',
- 'type',
- 'The type of the JSON payload to send: "array", "jsonlines", or "sse".
-In "array" mode, each query result is rendered as a JSON object in a single top-level array.
-In "jsonlines" mode, results are rendered as JSON objects in separate lines, without a top-level array.
-In "sse" mode, results are rendered as JSON objects in separate lines, prefixed by "data: ", which allows you to read the results as server-sent events in real-time from javascript.',
- 'TEXT',
- TRUE,
- TRUE
- );
-
--- Insert an example usage of the http_header component into the example table
-INSERT INTO
- example (component, description)
-VALUES
- (
- 'json',
- '
-## Send query results as a single JSON array: `''array'' as type`
-
-The default `array` mode sends the query results as a single JSON array.
-
-If a query returns an error, the array will contain an object with an `error` property.
-
-If multiple queries are executed, all query results will be concatenated into a single array
-of heterogeneous objects.
-
-### SQL
-
-```sql
-select ''json'' AS component;
-select * from users;
-```
-
-### Result
-
-```json
-[
- {"username":"James","userid":1},
- {"username":"John","userid":2}
-]
-```
-
-Clients can also receive JSON or JSON Lines automatically by requesting the same SQL file with an HTTP `Accept` header such as `application/json` or `application/x-ndjson` when the component is omitted, for example:
-
-```
-curl -H "Accept: application/json" http://localhost:8080/users.sql
-```
- '
- ),
- (
- 'json',
- '
-## Send a single JSON object: `''jsonlines'' as type`
-
-In `jsonlines` mode, each query result is rendered as a JSON object in a separate line,
-without a top-level array.
-
-If there is a single query result, the response will be a valid JSON object.
-If there are multiple query results, you will need to parse each line of the response as a separate JSON object.
-
-If a query returns an error, the response will be a JSON object with an `error` property.
-
-### SQL
-
-The following SQL creates an API endpoint that takes a `user_id` URL parameter
-and returns a single JSON object containing the user''s details, with one json object key per column in the `users` table.
-
-```sql
-select ''json'' AS component, ''jsonlines'' AS type;
-select * from users where id = $user_id LIMIT 1;
-```
-
-> Note the `LIMIT 1` clause. The `jsonlines` type will send one JSON object per result row,
-> separated only by a single newline character (\n).
-> So if your query returns multiple rows, the result will not be a single valid JSON object,
-> like most JSON parsers expect.
-
-### Result
-
-```json
-{ "username":"James", "userid":1 }
-```
-'
- ),
- (
- 'json',
- '
-## Create a complex API endpoint: the `''contents''` property
-
-You can create an API endpoint that will return a JSON value in any format you want,
-to implement a complex API.
-
-You should use [the json functions provided by your database](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) to form the value you pass to the `contents` property.
-To build a json array out of rows from the database, you can use:
- - `json_group_array()` in SQLite,
- - `json_agg()` in Postgres, or
- - `JSON_ARRAYAGG()` in MySQL.
- - `FOR JSON PATH` in SQL Server.
-
-
-```sql
-SELECT ''json'' AS component,
- JSON_OBJECT(
- ''users'', (
- SELECT JSON_GROUP_ARRAY(
- JSON_OBJECT(
- ''username'', username,
- ''userid'', id
- )
- ) FROM users
- )
- ) AS contents;
-```
-
-This will return a JSON response that looks like this:
-
-```json
-{
- "users" : [
- { "username":"James", "userid":1 }
- ]
-}
-```
-
-If you want to handle custom API routes, like `POST /api/users/:id`,
-you can use
- - the [`404.sql` file](/your-first-sql-website/custom_urls.sql) to handle the request despite the URL not matching any file,
- - the [`request_method` function](/functions.sql?function=request_method#function) to differentiate between GET and POST requests,
- - and the [`path` function](/functions.sql?function=path#function) to extract the `:id` parameter from the URL.
-'
- ),
- (
- 'json',
- '
-## Access query results in real-time with server-sent events: `''sse'' as type`
-
-Using server-sent events, you can stream large query results to the client in real-time,
-row by row.
-
-This allows building sophisticated dynamic web applications that will start processing and displaying
-the first rows of data in the browser while the database server is still processing the end of the query.
-
-### SQL
-
-```sql
-select ''json'' AS component, ''sse'' AS type;
-select * from users;
-```
-
-### JavaScript
-
-```javascript
-const eventSource = new EventSource("users.sql");
-eventSource.onmessage = function (event) {
- const user = JSON.parse(event.data);
- console.log(user.username);
-}
-eventSource.onerror = () => eventSource.close(); // do not reconnect after reading all the data
-```
-'
- );
diff --git a/examples/official-site/sqlpage/migrations/12_blog.sql b/examples/official-site/sqlpage/migrations/12_blog.sql
deleted file mode 100644
index 773e29ecb..000000000
--- a/examples/official-site/sqlpage/migrations/12_blog.sql
+++ /dev/null
@@ -1,185 +0,0 @@
-CREATE TABLE blog_posts (
- title TEXT PRIMARY KEY,
- description TEXT NOT NULL,
- icon TEXT NOT NULL,
- external_url TEXT,
- content TEXT,
- created_at TIMESTAMP NOT NULL
-);
-
-INSERT INTO blog_posts (title, description, icon, created_at, content)
-VALUES
- (
- 'SQLPage versus No-Code tools',
- 'What are the advantages and disadvantages of SQLPage compared to No-Code tools?',
- 'code-minus',
- '2023-08-03',
- '
-# Choosing Your Path: No-Code, Low-Code, or SQL-Based Development
-
-The platform you select shapes the entire trajectory of your application.
-Each approach offers distinct advantages, yet demands different compromises - a choice that warrants careful consideration.
-
-## No-Code Platforms: Speed with Limitations
-
-No-Code platforms present a visual canvas for building applications without traditional programming. Whilst brilliant for rapid prototypes and straightforward departmental tools, they falter when confronted with complexity and scale.
-
-**Best suited to**: Quick internal tools and simple workflows
-
-### **Notable examples**
-
- - [NocoBase](https://www.nocobase.com/)
- - [NocoDB](https://www.nocodb.com/)
- - [Saltcorn](https://github.com/saltcorn/saltcorn)
-
-
-## Low-Code Platforms: The Flexible Middle Ground
-
-These platforms artfully combine visual development with traditional coding. They maintain the power of custom code whilst accelerating development through carefully designed components.
-
-**Best suited to**: Complex applications requiring both speed and customisation
-
-### **Notable examples**
-
- - [Budibase](https://budibase.com/)
- - [Directus](https://github.com/directus/directus)
- - [Rowy](https://github.com/rowyio/rowy)
-
-## SQL-Based Development: Elegant Simplicity
-
-SQLPage offers a refreshingly direct approach: pure SQL-driven web applications.
-
-For those versed in SQL, it enables sophisticated data-driven applications without the overhead of additional frameworks.
-
-**Best suited to**: Data-centric applications and dashboards
-
-**Details**: [SQLPage on GitHub](https://github.com/sqlpage/SQLPage)
-
-## The AI Revolution in Development
-
-The emergence of Large Language Models (LLMs) has fundamentally shifted the landscape of application development. Tools that once demanded extensive coding expertise have become remarkably more accessible. AI assistants like ChatGPT excel particularly at generating SQL queries and database operations, making SQL-based platforms surprisingly approachable even for those with limited database experience. These AI companions serve as expert pair programmers, offering suggestions, debugging assistance, and ready-to-use code snippets.
-
-This transformation especially benefits platforms like SQLPage, where the AI''s prowess in SQL generation can bridge the traditional expertise gap. Even complex queries and database operations can be created through natural language conversations with AI assistants, democratising access to sophisticated data manipulation capabilities.
-
-## Making an Informed Choice
-
-Selecting the right development approach requires weighing multiple factors against your project''s specific needs.
-
-Consider these key decision points to guide your platform selection:
-
-### **Time Constraints**
- - Immediate delivery required → No-Code
- - Several days available → SQLPage or Low-Code
-
-### **Data Complexity**
- - Structured data manipulation → SQLPage
- - Complex workflows → Low-Code
-
-### **Team Expertise**
- - SQL skills → SQLPage
- - Limited technical expertise → No-Code
- - Varied technical capabilities → Low-Code
-
-### **Control Requirements**
- - Precise data layer control → SQLPage
- - Visual design flexibility → Low-Code
- - Speed over customisation → No-Code
-
-## Further Investigation
-
-For a thorough demonstration of SQLPage''s capabilities: [Building a Full Web Application with SQLPage](https://www.youtube.com/watch?v=mXdgmSdaXkg)
-');
-
-INSERT INTO blog_posts (title, description, icon, created_at, external_url)
-VALUES (
- 'Repeating yourself thrice won''t make you a 3X developer',
- 'A dive into the traditional 3-tier architecture and the DRY principle, and how tools like SQLPage helps you avoid repeating yourself.',
- 'box-multiple-3',
- '2023-08-01',
- 'https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0'
-);
-
-INSERT INTO blog_posts (title, description, icon, created_at, content)
-VALUES (
- '3 solutions to the 3 layer problem',
- 'What is the 3 layer problem, and how SQLPage solves it?',
- 'adjustments-question',
- '2023-08-10',
- '
-# 3 solutions to the 3 layer problem
-
-> Some interesting questions emerged from the article [Repeating yourself thrice doesn''t turn you into a 3X developer](https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0).
-> This short follow-up article aims to answer them and clarify some points.
-
-Hello all,
-
-I am Ophir Lojkine, the main contributor of the open-source application server **SQLPage**.
-
-The previous article focused on the conventional model of splitting applications into three distinct tiers:
-
-1. a graphical interface (_front-end_),
-2. an application server (_back-end_),
-3. and a database.
-
-In many projects, this results in three distinct implementations of the application’s data model:
-
-1. First, in SQL, in the form of tables, views, and relationships in the database,
-2. Then, in _server side_ languages such as Java, Python, or PHP, to create an API managing access to the data, and to implement the business logic of the application,
-3. Finally, in JavaScript or TypeScript to implement data manipulation in the user interface.
-
-
-
----
-
-The topic of interest here is the duplication of the data model between the different layers,
-and the communication overhead between them.
-We are not talking about how the code is structured within each layer.
-It can follow a Model-View-Controller pattern or not, it doesn''t matter.
-
-This three-layer model has several advantages:
-specialization of the programmers,
-parallelization of work,
-scalability,
-separation of concerns,
-and an optimal exploitation of the capacities of the infrastructure on which each layer is deployed:
-web browser, server application and database.
-
-Nevertheless, in large-scale projects,
-there is often a certain redundancy of the code between the different layers,
-as well as a non-negligible share of code dedicated to communication between them.
-For small teams and solo developers, this becomes a major drawback.
-
-## 3 solutions
-
-Fortunately, there are several approaches to solving this problem:
-
-1. For **UI-centric applications** without complicated data processing needs,
-you can almost completely abandon server-side development and **directly expose the data to the frontend**.
-Open-source tools available in this space include Supabase, PocketBase or Hasura.
-2. For **applications with a predominant business logic**, traditional _web frameworks_
-solve this problem by centralizing frontend and database control in the backend code.
-A common solution involves using an ORM and templating system instead of a dedicated javascript application.
-Popular solutions include Django, Ruby on Rails, or Symphony.
-3. For simpler applications, it is possible to **avoid both backend and frontend development**
-by adopting a _database-first_ approach.
-This alternative, although less widespread, allows taking advantage of under-exploited modern capacities of relational databases.
-The purpose of the original article was to introduce this lesser known approach.
- * **SQLPage** is representative of this last category,
- which allows designing a complete web application _in SQL_.
- This leads to a loss of control over the precise visual appearance of the application,
- which will get a “standardized” look and feel.
- On the other hand, this translates into significant gains in terms of development speed,
- simplicity and performance.
- This solution is not intended to compete with traditional _frameworks_,
- but rather integrate earlier in the life cycle of a project.
- It thus makes it possible to quickly develop a data structure adapted to the application,
- and to iterate over it while benefiting from continuous visual feedback on the final result.
- Then, when the application grows, it’s easy to add a classic frontend and backend on top of the existing database,
- without having to start from scratch.
-
-Whichever approach is chosen in the end,
-a solid understanding of the conventional three-tier architecture,
-as well as a clear perspective on the challenges it creates and the possible solutions,
-facilitates decision-making and the evolution of the project with the best suited technologies.
- '
- );
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/13_tab.sql b/examples/official-site/sqlpage/migrations/13_tab.sql
deleted file mode 100644
index 162386f15..000000000
--- a/examples/official-site/sqlpage/migrations/13_tab.sql
+++ /dev/null
@@ -1,129 +0,0 @@
-INSERT INTO component (name, description, icon, introduced_in_version)
-VALUES (
- 'tab',
- 'Build a tabbed interface, with each tab being a link to a page. Each tab can be in two states: active or inactive.',
- 'row-insert-bottom',
- '0.9.5'
- );
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES (
- 'tab',
- 'title',
- 'Text to display on the tab. If link is not set, the link will be the current page with a ''$tab'' parameter set to the tab''s title. If ''id'' is set, the page will be scrolled to the tab.',
- 'TEXT',
- FALSE,
- FALSE
- ),
- (
- 'tab',
- 'link',
- 'Link to the page to display when the tab is clicked. By default, the link refers to the current page, with a ''tab'' parameter set to the tab''s title and hash set to the id (if passed) - this brings us back to the location of the tab after submission.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'tab',
- 'active',
- 'Whether the tab is active or not. Defaults to false.',
- 'BOOLEAN',
- FALSE,
- TRUE
- ),
- (
- 'tab',
- 'icon',
- 'Name of the icon to display on the tab. See tabler-icons.io for a list of available icons.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'tab',
- 'color',
- 'Color of the tab''s text, and of its underline when it is active. See preview.tabler.io/colors.html for a list of available colors.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'tab',
- 'description',
- 'Description of the tab. This is displayed when the user hovers over the tab.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'tab',
- 'center',
- 'Whether the tabs should be centered or not. Defaults to false.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'tab',
- 'center',
- 'Whether this individual tab''s label should be centered inside the tab. Defaults to false.',
- 'BOOLEAN',
- FALSE,
- TRUE
- )
- ;
-
-INSERT INTO example (component, description, properties)
-VALUES (
- 'tab',
- 'This example shows a very basic set of three tabs. The first tab is active. You could use this at the top of a page for easy navigation.
-
-To implement contents that change based on the active tab, use the `tab` parameter in the page query string.
-For example, if the page is `/my-page.sql`, then the first tab will have a link of `/my-page.sql?tab=My+First+tab`.
-
-You could then for instance display contents coming from the database based on the value of the `tab` parameter.
-For instance: `SELECT ''text'' AS component, contents_md FROM my_page_contents WHERE tab = $tab`.
-Or you could write different queries for different tabs and use the `$tab` parameter with a static value in a where clause to switch between tabs:
-
-```sql
-select ''tab'' as component;
-select ''Projects'' as title, $tab = ''Projects'' as active;
-select ''Tasks'' as title, $tab = ''Tasks'' as active;
-
-select ''table'' as component;
-
-select * from my_projects where $tab = ''Projects'';
-select * from my_tasks where $tab = ''Tasks'';
-```
-
-Note that the example below is completely static, and does not use the `tab` parameter to actually switch between tabs.
-View the [dynamic tabs example](/examples/tabs/).
-',
- JSON(
- '[
- { "component": "tab" },
- { "title": "This tab does not exist", "active": true, "link": "?component=tab&tab=tab_1" },
- { "title": "I am not a true tab", "link": "?component=tab&tab=tab_2" },
- { "title": "Do not click here", "link": "?component=tab&tab=tab_3" }
- ]'
- )
- ),
- (
- 'tab',
- 'This example shows a more sophisticated set of tabs. The tabs are centered, the active tab has a different color, and all the tabs have a custom link and icon.',
- JSON(
- '[
- { "component": "tab", "center": true },
- { "title": "Hero", "link": "?component=hero#component", "icon": "home", "description": "The hero component is a full-width banner with a title and an image." },
- { "title": "Tab", "link": "?component=tab#component", "icon": "user", "color": "purple" },
- { "title": "Card", "link": "?component=card#component", "icon": "credit-card" }
- ]'
- )
- )
- ;
diff --git a/examples/official-site/sqlpage/migrations/16_timeline.sql b/examples/official-site/sqlpage/migrations/16_timeline.sql
deleted file mode 100644
index 78f19ba5f..000000000
--- a/examples/official-site/sqlpage/migrations/16_timeline.sql
+++ /dev/null
@@ -1,103 +0,0 @@
-INSERT INTO component (name, description, icon, introduced_in_version)
-VALUES (
- 'timeline',
- 'A list of events with a vertical line connecting them.',
- 'git-commit',
- '0.13.0'
- );
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES (
- 'timeline',
- 'simple',
- 'If set to true, the timeline will be displayed in a condensed format without icons.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'timeline',
- 'title',
- 'Name of the event.',
- 'TEXT',
- FALSE,
- FALSE
- ),
- (
- 'timeline',
- 'date',
- 'Date of the event.',
- 'TEXT',
- FALSE,
- FALSE
- ),
- (
- 'timeline',
- 'icon',
- 'Name of the icon to display next to the event. See tabler-icons.io for a list of available icons.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'timeline',
- 'color',
- 'Color of the icon. See preview.tabler.io/colors.html for a list of available colors.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'timeline',
- 'description',
- 'Textual description of the event.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'timeline',
- 'description_md',
- 'Description of the event in Markdown.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'timeline',
- 'link',
- 'Link to a page with more information about the event.',
- 'TEXT',
- FALSE,
- TRUE
- );
-INSERT INTO example (component, description, properties)
-VALUES (
- 'timeline',
- 'A basic timeline with just names and dates.',
- JSON(
- '[
- { "component": "timeline", "simple": true },
- { "title": "New message from Elon Musk", "date": "13:00" },
- { "title": "Jeff Bezos assigned task \"work more\" to you.", "date": "yesterday, 16:35" }
- ]'
- )
- ),
- (
- 'timeline',
- 'A full-fledged timeline with icons, colors, and rich text descriptions.',
- JSON(
- '[
- { "component": "timeline" },
- { "title": "v0.13.0 was just released !", "link": "https://github.com/sqlpage/SQLPage/releases/", "date": "2023-10-16", "icon": "brand-github", "color": "green", "description_md": "This version introduces the `timeline` component." },
- { "title": "They are talking about us...", "description_md": "[This article](https://www.postgresql.org/about/news/announcing-sqlpage-build-dynamic-web-applications-in-sql-2672/) on the official PostgreSQL website mentions SQLPage.", "date": "2023-07-12", "icon": "database", "color": "blue" }
- ]'
- )
- )
- ;
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/18_button.sql b/examples/official-site/sqlpage/migrations/18_button.sql
deleted file mode 100644
index 4cfd80e88..000000000
--- a/examples/official-site/sqlpage/migrations/18_button.sql
+++ /dev/null
@@ -1,122 +0,0 @@
--- Button Component Documentation
-
--- Component Definition
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('button', 'hand-click', 'Displays one or more buttons that follow links, download files, or submit a form.', '0.14.0');
-
--- Inserting parameter information for the button component
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'button', * FROM (VALUES
- -- Top-level parameters (for the whole button list)
- ('justify', 'The horizontal alignment of the button list (e.g., start, end, center, between).', 'TEXT', TRUE, TRUE),
- ('size', 'The size of the buttons (e.g., sm, lg).', 'TEXT', TRUE, TRUE),
- ('shape', 'Shape of the buttons (e.g., pill, square)', 'TEXT', TRUE, TRUE),
- -- Item-level parameters (for each button)
- ('link', 'The URL to which the button should navigate when clicked. If the form attribute is specified, then this overrides the page to which the form is submitted.', 'URL', FALSE, TRUE),
- ('color', 'The color of the button (e.g., red, green, blue, but also primary, warning, danger, etc.). Only base color names are supported, not variations like "blue-lt" or "gray-300". Use a custom CSS stylesheet to further customize the colors.', 'COLOR', FALSE, TRUE),
- ('title', 'The text displayed on the button.', 'TEXT', FALSE, TRUE),
- ('tooltip', 'Text displayed when the user hovers over the button.', 'TEXT', FALSE, TRUE),
- ('disabled', 'Whether the button is disabled or not.', 'BOOLEAN', FALSE, TRUE),
- ('outline', 'Outline color of the button (e.g. red, purple, ...)', 'COLOR', FALSE, TRUE),
- ('space_after', 'Whether there should be extra space to the right of the button. In a line of buttons, this will put the buttons before this one on the left, and the ones after on the right.', 'BOOLEAN', FALSE, TRUE),
- ('icon_after', 'Name of an icon to display after the text in the button', 'ICON', FALSE, TRUE),
- ('icon', 'Name of an icon to be displayed on the left side of the button.', 'ICON', FALSE, TRUE),
- ('image', 'Path to image file (relative. relative to web root or URL) to be displayed on the button.', 'TEXT', FALSE, TRUE),
- ('narrow', 'Whether to trim horizontal padding.', 'BOOLEAN', FALSE, TRUE),
- ('form', 'Identifier (id) of the form to which the button should submit.', 'TEXT', FALSE, TRUE),
- ('rel', '"nofollow" when the contents of the target link are not endorsed, "noopener" when the target is not trusted, and "noreferrer" to hide where the user came from when they open the link.', 'TEXT', FALSE, TRUE),
- ('target', '"_blank" to open the link in a new tab, "_self" to open it in the same tab, "_parent" to open it in the parent frame, or "_top" to open it in the full body of the window.', 'TEXT', FALSE, TRUE),
- ('download', 'If defined, the link will download the target instead of navigating to it. Set the value to the desired name of the downloaded file.', 'TEXT', FALSE, TRUE),
- ('id', 'HTML Identifier to add to the button element.', 'TEXT', FALSE, TRUE)
-) x;
-
--- Inserting example information for the button component
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'A basic button with a link',
- json('[{"component":"button"}, {"link":"/documentation.sql", "title":"Enabled"}, {"link":"#", "title":"Disabled", "disabled":true}]'))
-;
-
-
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'A button with a custom shape, size, and outline color',
- json('[{"component":"button", "size":"sm", "shape":"pill" },
- {"title":"Purple", "outline":"purple" },
- {"title":"Orange", "outline":"orange" },
- {"title":"Red", "outline":"red" }]')
- );
-
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'A list of buttons aligned in the center',
- json('[{"component":"button", "justify":"center"},
- {"link":"#", "color":"light", "title":"Light"},
- {"link":"#", "color":"success", "title":"Success"},
- {"link":"#", "color":"info", "title":"Info"},
- {"link":"#", "color":"dark", "title":"Dark"},
- {"link":"#", "color":"warning", "title":"Warning"},
- {"link":"#", "color":"danger", "title":"Narrow"}]')
- );
-
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'Icon buttons using the narrow property',
- json('[{"component":"button"},
- {"link":"#", "narrow":true, "icon":"edit", "color":"primary", "tooltip":"Edit" },
- {"link":"#", "narrow":true, "icon":"trash", "color":"danger", "tooltip":"Delete" },
- {"link":"#", "narrow":true, "icon":"corner-down-right", "color":"info", "tooltip":"Preview" },
- {"link":"#", "narrow":true, "icon":"download", "color":"success", "tooltip":"Download" },
- {"link":"#", "narrow":true, "icon":"upload", "color":"warning", "tooltip":"Upload" },
- {"link":"#", "narrow":true, "icon":"info-circle", "color":"cyan", "tooltip":"Info" },
- {"link":"#", "narrow":true, "icon":"help-circle", "color":"purple", "tooltip":"Help" },
- {"link":"#", "narrow":true, "icon":"settings", "color":"indigo", "tooltip":"Settings" }]')
- );
-
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'Buttons with icons and different sizes',
- json('[{"component":"button", "size":"lg" },
- {"link":"#", "outline":"azure", "title":"Edit", "icon":"edit"},
- {"link":"#", "outline":"danger", "title":"Delete", "icon":"trash"}]')
- );
-
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'A row of square buttons with spacing in between',
- json('[{"component":"button", "shape":"square"},
- {"link":"#", "color":"green", "title":"Save", "icon": "device-floppy" },
- {"link":"#", "title":"Cancel", "space_after":true, "tooltip": "This will delete your draft"},
- {"link":"#", "outline":"indigo", "title":"Preview", "icon_after": "corner-down-right", "tooltip": "View temporary draft" }]')
- );
-
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'Multiple buttons sending the same form to different pages.
-
-We use `'''' AS validate` to remove the submit button from inside the form itself,
-and instead use the button component to submit the form to pages with different GET variables.
-
-In the target page, we could then use the GET variable `$action` to determine what to do with the form data.
- ',
- json('[{"component":"form", "id": "poem", "validate": ""},
- {"type": "textarea", "name": "Poem", "placeholder": "Write a poem"},
- {"component":"button"},
- {"link":"?action=save", "form":"poem", "color":"primary", "title":"Save" },
- {"link":"?action=preview", "form":"poem", "outline":"yellow", "title":"Preview" }]')
- );
-
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'A button that downloads a file when clicked, and prevents search engines from following the link.',
- json('[{"component":"button"},
- {"link":"/sqlpage_introduction_video.mp4",
- "title":"Download Video",
- "icon":"download",
- "download":"Introduction Video.webm",
- "rel":"nofollow"
- }]')
- );
-
-INSERT INTO example(component, description, properties) VALUES
- ('button', 'A button with an image-based icon.',
- json('[{"component":"button"},
- {"link":"https://en.wikipedia.org/wiki/File:Globe.svg",
- "title":"Open an article",
- "image":"https://upload.wikimedia.org/wikipedia/commons/f/fa/Globe.svg"
- }]')
- );
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES
- ('button', 'image_alt', 'Alternative text for an informative button image. Leave empty if decorative or repeated by the button title.', 'TEXT', FALSE, TRUE);
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/28_tracking_component.sql b/examples/official-site/sqlpage/migrations/28_tracking_component.sql
deleted file mode 100644
index e873f5bf0..000000000
--- a/examples/official-site/sqlpage/migrations/28_tracking_component.sql
+++ /dev/null
@@ -1,136 +0,0 @@
-INSERT INTO component (name, description, icon, introduced_in_version)
-VALUES (
- 'tracking',
- 'Component for visualising activity logs or other monitoring-related data.',
- 'timeline-event-text',
- '0.18.0'
- );
-
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES (
- 'tracking',
- 'title',
- 'Title of the tracking component.',
- 'TEXT',
- TRUE,
- FALSE
- ),
- (
- 'tracking',
- 'information',
- 'A short text displayed below the title.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'tracking',
- 'description',
- 'A short paragraph.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'tracking',
- 'description_md',
- 'A short paragraph formatted using markdown.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'tracking',
- 'width',
- 'Width of the component, between 1 and 12.',
- 'INTEGER',
- TRUE,
- TRUE
- ),
- (
- 'tracking',
- 'placement',
- 'Position of the tooltip (e.g. top, bottom, right, left)',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'tracking',
- 'color',
- 'Color of the tracked item (e.g. success, warning, danger)',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'tracking',
- 'title',
- 'Description of the state.',
- 'TEXT',
- FALSE,
- FALSE
- ),
- (
- 'tracking',
- 'link',
- 'A URL to open when the user clicks on the tracked item.',
- 'URL',
- FALSE,
- TRUE
- ),
- (
- 'tracking',
- 'center',
- 'Whether to center the component.',
- 'BOOLEAN',
- TRUE,
- TRUE
- );
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties)
-VALUES
- (
- 'tracking',
- 'A basic example of servers tracking component',
- JSON(
- '[
- {"component":"tracking","title":"Servers status"},
- {"title":"No data"},
- {"title":"No data"},
- {"title":"No data"},
- {"title":"No data"},
- {"title":"No data"},
- {"title":"No data"},
- {"title":"No data"},
- {"title":"No data"}
- ]'
- )
- ),
- (
- 'tracking',
- 'An example of servers tracking component',
- JSON(
- '[
- {"component":"tracking","title":"Servers status","information":"60% are running","description_md":"Status of all **currently running servers**","placement":"top","width":4},
- {"color":"success","title":"operational"},
- {"color":"success","title":"operational"},
- {"color":"success","title":"operational"},
- {"color":"danger","title":"Downtime"},
- {"title":"No data"},
- {"color":"success","title":"operational"},
- {"color":"warning","title":"Big load"},
- {"color":"success","title":"operational"}
- ]'
- )
- );
-
-
diff --git a/examples/official-site/sqlpage/migrations/29_divider_component.sql b/examples/official-site/sqlpage/migrations/29_divider_component.sql
deleted file mode 100644
index 3acaa4e4b..000000000
--- a/examples/official-site/sqlpage/migrations/29_divider_component.sql
+++ /dev/null
@@ -1,152 +0,0 @@
-INSERT INTO component (name, description, icon, introduced_in_version)
-VALUES (
- 'divider',
- 'Dividers help organize content and make the interface layout clear and uncluttered.',
- 'separator',
- '0.18.0'
- );
-
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES (
- 'divider',
- 'contents',
- 'A text in the divider.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'divider',
- 'position',
- 'Position of the text (e.g. left, right).',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'divider',
- 'color',
- 'The name of a color for this span of text.',
- 'COLOR',
- TRUE,
- TRUE
- ),
- (
- 'divider',
- 'size',
- 'The size of the divider text, from 1 to 6.',
- 'INTEGER',
- TRUE,
- TRUE
- ),
- (
- 'divider',
- 'bold',
- 'Whether the text is bold.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'divider',
- 'italics',
- 'Whether the text is italicized.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'divider',
- 'underline',
- 'Whether the text is underlined.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'divider',
- 'link',
- 'URL of the link for the divider text. Available only when contents is present.',
- 'URL',
- TRUE,
- TRUE
- );
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties)
-VALUES
- (
- 'divider',
- 'An empty divider',
- JSON(
- '[
- {
- "component":"divider"
- }
- ]'
- )
- ),
- (
- 'divider',
- 'A divider with centered text',
- JSON(
- '[
- {
- "component":"divider",
- "contents":"Hello"
- }
- ]'
- )
- ),
- (
- 'divider',
- 'A divider with text at left',
- JSON(
- '[
- {
- "component":"divider",
- "contents":"Hello",
- "position":"left"
- }
- ]'
- )
- ),
- (
- 'divider',
- 'A divider with blue text and a link',
- JSON(
- '[
- {
- "component":"divider",
- "contents":"SQLPage components",
- "link":"/documentation.sql",
- "color":"blue"
- }
- ]'
- )
- ),
- (
- 'divider',
- 'A divider with bold, italic, and underlined text',
- JSON(
- '[
- {
- "component":"divider",
- "contents":"Important notice",
- "position":"left",
- "color":"red",
- "size":5,
- "bold":true,
- "italics":true,
- "underline":true
- }
- ]'
- )
- );
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql b/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql
deleted file mode 100644
index 6ec48379a..000000000
--- a/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql
+++ /dev/null
@@ -1,76 +0,0 @@
-INSERT INTO component (name, description, icon, introduced_in_version)
-VALUES (
- 'breadcrumb',
- 'A secondary navigation aid that helps users understand their location on a website or mobile application.',
- 'dots',
- '0.18.0'
- );
-
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
- VALUES (
- 'breadcrumb',
- 'title',
- 'Hyperlink text to display.',
- 'TEXT',
- FALSE,
- FALSE
- ),
- (
- 'breadcrumb',
- 'link',
- 'Link to the page to display when the link is clicked. By default, the link refers to the current page, with a ''link'' parameter set to the link''s title.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'breadcrumb',
- 'active',
- 'Whether the link is active or not. Defaults to false.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'breadcrumb',
- 'description',
- 'Description of the link. This is displayed when the user hovers over the link.',
- 'TEXT',
- FALSE,
- TRUE
- );
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties)
-VALUES
- (
- 'breadcrumb',
- 'Basic usage of the breadcrumb component',
- JSON(
- '[
- {"component":"breadcrumb"},
- {"title":"Home","link":"/"},
- {"title":"Components", "link":"/documentation.sql"},
- {"title":"Breadcrumb", "link":"?component=breadcrumb"}
- ]'
- )
- ),
- (
- 'breadcrumb',
- 'Description of a link and selection of the current page.',
- JSON(
- '[
- {"component":"breadcrumb"},
- {"title":"Home","link":"/","active": true},
- {"title":"Articles","link":"/blog.sql","description":"Stay informed with the latest news"},
- {"title":"JSON in SQL","link":"/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide", "description": "Learn advanced json functions for MySQL, SQLite, PostgreSQL, and SQL Server" }
- ]'
- )
- );
diff --git a/examples/official-site/sqlpage/migrations/31_card_docs_update.sql b/examples/official-site/sqlpage/migrations/31_card_docs_update.sql
deleted file mode 100644
index 25e79b5f2..000000000
--- a/examples/official-site/sqlpage/migrations/31_card_docs_update.sql
+++ /dev/null
@@ -1,93 +0,0 @@
-DELETE FROM component WHERE name = 'card';
-
-INSERT INTO component(name, icon, description) VALUES
- ('card', 'credit-card', 'A grid where each element is a small card that displays a piece of data.');
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'card', * FROM (VALUES
- -- top level
- ('title', 'Text header at the top of the list of cards.', 'TEXT', TRUE, TRUE),
- ('description', 'A short paragraph displayed below the title.', 'TEXT', TRUE, TRUE),
- ('description_md', 'A short paragraph displayed below the title - formatted using markdown.', 'TEXT', TRUE, TRUE),
- ('columns', 'The number of columns in the grid of cards. This is just a hint, the grid will adjust dynamically to the user''s screen size, rendering fewer columns if needed to fit the contents. To control the size of cards individually, use the `width` row-level property instead.', 'INTEGER', TRUE, TRUE),
- -- item level
- ('title', 'Name of the card, displayed at the top.', 'TEXT', FALSE, FALSE),
- ('description', 'The body of the card, where you put the main text contents of the card.
- This does not support rich text formatting, only plain text.
- If you want to use rich text formatting, use the `description_md` property instead.', 'TEXT', FALSE, TRUE),
- ('description_md', '
- The body of the card, in Markdown format.
- This is useful if you want to display a lot of text in the card, with many options for formatting, such as
- line breaks, **bold**, *italics*, lists, #titles, [links](target.sql), , etc.', 'TEXT', FALSE, TRUE),
- ('top_image', 'The URL (absolute or relative) of an image to display at the top of the card.', 'URL', FALSE, TRUE),
- ('top_image_lazy', 'Whether the top image must be lazily loaded. Defaults to false, meaning eagerly loaded.', 'BOOLEAN', FALSE, TRUE),
- ('top_image_width', 'Specify the top image width, in pixels. Helps prevent layout shifts.', 'INTEGER', FALSE, TRUE),
- ('top_image_height', 'Specify the top image height, in pixels. Helps prevent layout shifts.', 'INTEGER', FALSE, TRUE),
- ('footer', 'Muted text to display at the bottom of the card.', 'TEXT', FALSE, TRUE),
- ('footer_md', 'Muted text to display at the bottom of the card, with rich text formatting in Markdown format.', 'TEXT', FALSE, TRUE),
- ('link', 'An URL to which the user should be taken when they click on the card.', 'URL', FALSE, TRUE),
- ('target', 'Where the card''s link opens: "_blank" for a new tab, "_self" for the same tab, "_parent" for the parent frame, or "_top" for the full body of the window.', 'TEXT', FALSE, TRUE),
- ('footer_link', 'An URL to which the user should be taken when they click on the footer.', 'URL', FALSE, TRUE),
- ('style', 'Inline style property to your iframe embed code. For example "background-color: #FFFFFF"', 'TEXT', FALSE, TRUE),
- ('height', 'Height of the iframe embed code, in pixels. Used only when embed_mode is ''iframe''.', 'INTEGER', FALSE, TRUE),
- ('allow', 'The permissions policy of the iframe embed code, for instance "fullscreen; clipboard-write". Used only when embed_mode is ''iframe''.', 'TEXT', FALSE, TRUE),
- ('sandbox', 'The restrictions to apply to the iframe embed code, for instance "allow-scripts allow-same-origin". Used only when embed_mode is ''iframe''.', 'TEXT', FALSE, TRUE),
- ('icon', 'Name of an icon to display on the right side of the card.', 'ICON', FALSE, TRUE),
- ('color', 'The name of a color, to be displayed on the left of the card to highlight it. If the embed parameter is enabled and you don''t have a title or description, this parameter won''t apply.', 'COLOR', FALSE, TRUE),
- ('background_color', 'The background color of the card.', 'COLOR', FALSE, TRUE),
- ('active', 'Whether this item in the grid is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE),
- ('width', 'The width of the card, between 1 (smallest) and 12 (full-width). The default width is 3, resulting in 4 cards per line. When embed_mode is ''iframe'', this is used as the width of the iframe instead, and defaults to 100%.', 'INTEGER', FALSE, TRUE)
-) x;
-INSERT INTO parameter(component, name, description_md, type, top_level, optional) SELECT 'card', * FROM (VALUES
- ('embed', 'A url whose contents will be fetched and injected into the body of this card.
- This can be used to inject arbitrary html content, but is especially useful for injecting
- the output of other sql files rendered by SQLPage. For the latter case you can pass the
- `?_sqlpage_embed` query parameter, which will skip the shell layout.
- Components inside the fetched content initialize automatically. Custom scripts that insert
- SQLPage fragments should dispatch a bubbling `fragment-loaded` event on the element containing
- the new content. Initialization includes that element and its descendants; dispatching the
- event on `document` initializes pending components throughout the page. Repeated events
- preserve existing form and widget handlers', 'TEXT', FALSE, TRUE),
- ('embed_mode', 'Set to ''iframe'' to embed the target (specified through embed property) in an iframe.
- Unless this is explicitly set, the embed target is fetched and injected within the parent page. If embed_mode is set to iframe,
- You can also set height and width parameters to configure the appearance and the sandbox and allow parameters to configure
- security aspects of the iframe. Refer to the [MDN page](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)
- for an explanation of these parameters.', 'TEXT', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('card', 'A beautiful card grid with bells and whistles, showing examples of SQLPage features.',
- json('[{"component":"card", "title":"Popular SQLPage features", "columns": 2},
- {"title": "Download as spreadsheet", "link": "?component=csv#component", "description": "Using the CSV component, you can download your data as a spreadsheet.", "icon":"file-plus", "color": "green", "footer_md": "SQLPage can both [read](?component=form#component) and [write](?component=csv#component) **CSV** files."},
- {"title": "Custom components", "link": "/custom_components.sql", "description": "If you know some HTML, you can create your own components for your application.", "icon":"code", "color": "orange", "footer_md": "You can look at the [source of the official components](https://github.com/sqlpage/SQLPage/tree/main/sqlpage/templates) for inspiration."}
- ]')),
- ('card', 'You can use cards to display a dashboard with quick access to important information. Use [markdown](https://www.markdownguide.org/basic-syntax) to format the text.',
- json('[
- {"component": "card", "columns": 4},
- {"description_md": "**152** sales today", "active": true, "icon": "currency-euro"},
- {"description_md": "**13** new users", "icon": "user-plus", "color": "green"},
- {"description_md": "**2** complaints", "icon": "alert-circle", "color": "danger", "link": "?view_complaints", "background_color": "red-lt"},
- {"description_md": "**1** pending support request", "icon": "mail-question", "color": "warning"}
- ]')),
- ('card', 'A gallery of images.',
- json('[
- {"component":"card", "title":"My favorite animals in pictures", "columns": 3},
- {"title": "Lynx", "description_md": "The **lynx** is a medium-sized **wild cat** native to Northern, Central and Eastern Europe to Central Asia and Siberia, the Tibetan Plateau and the Himalayas.", "top_image_alt": "A Eurasian lynx", "top_image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Lynx_lynx_-_05.jpg/330px-Lynx_lynx_-_05.jpg", "top_image_width": 330, "top_image_height": 495, "top_image_lazy": true, "icon":"star" },
- {"title": "Squirrel", "description_md": "The **chipmunk** is a small, striped rodent of the family Sciuridae. Chipmunks are found in North America, with the exception of the Siberian chipmunk which is found primarily in Asia.", "top_image_alt": "A squirrel eating a nut", "top_image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/American_squirrel_eating_nut%2C_13_Jun_2013.JPG/330px-American_squirrel_eating_nut%2C_13_Jun_2013.JPG", "top_image_width": 330, "top_image_height": 495, "top_image_lazy": true },
- {"title": "Spider", "description_md": "The **jumping spider family** (_Salticidae_) contains more than 600 described genera and about *6000 described species*, making it the largest family of spiders with about 13% of all species.", "top_image_alt": "An orb weaver spinning a web", "top_image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Australian_orb_weaver_spinning_web.jpg/330px-Australian_orb_weaver_spinning_web.jpg", "top_image_width": 330, "top_image_height": 495, "top_image_lazy": true }
- ]')),
- ('card', 'Beautifully colored cards with variable width. The blue card (width 6) takes half the screen, whereas of the red and green cards have the default width of 3',
- json('[
- {"component":"card", "title":"Beautifully colored cards" },
- {"title": "Red card", "color": "red", "background_color": "red-lt", "description": "Penalty! You are out!", "icon":"play-football" },
- {"title": "Blue card", "color": "blue", "width": 6, "background_color": "blue-lt", "description": "The Blue Card facilitates migration of foreigners to Europe.", "icon":"currency-euro" },
- {"title": "Green card", "color": "green", "background_color": "green-lt", "description": "Welcome to the United States of America !", "icon":"user-dollar" }
- ]')),
- ('card', 'Cards with remote content',
- json('[
- {"component":"card", "title":"Card with embedded remote content", "columns": 2},
- {"title": "Embedded Chart", "embed": "/examples/chart.sql?_sqlpage_embed" },
- {"title": "Embedded Video", "embed": "https://www.youtube.com/embed/mXdgmSdaXkg", "allow": "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share", "embed_mode": "iframe", "height": "350" }
- ]'));
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES
- ('card', 'top_image_alt', 'Alternative text for an informative card image. Leave empty if decorative.', 'TEXT', FALSE, TRUE),
- ('card', 'embed_title', 'Accessible name of the iframe. Defaults to the card title, or Embedded content if no title is set.', 'TEXT', FALSE, TRUE);
diff --git a/examples/official-site/sqlpage/migrations/34_carousel.sql b/examples/official-site/sqlpage/migrations/34_carousel.sql
deleted file mode 100644
index 70f74b53b..000000000
--- a/examples/official-site/sqlpage/migrations/34_carousel.sql
+++ /dev/null
@@ -1,163 +0,0 @@
-INSERT INTO component (name, description, icon, introduced_in_version)
-VALUES (
- 'carousel',
- 'A carousel is used to display images. When used with multiple images, it will cycle through them automatically or with controls, creating a slideshow.',
- 'carousel-horizontal',
- '0.18.3'
- );
-INSERT INTO parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES
- (
- 'carousel',
- 'title',
- 'A name to display at the top of the carousel.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'indicators',
- 'Style of image indicators (square or dot).',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'vertical',
- 'Whether to use the vertical image indicators.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'controls',
- 'Whether to show the control links to go previous or next item.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'width',
- 'Width of the component, between 1 and 12. Default is 12.',
- 'INTEGER',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'auto',
- 'Whether to automatically cycle through the carousel items. Default is false.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'center',
- 'Whether to center the carousel.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'fade',
- 'Whether to apply the fading effect.',
- 'BOOLEAN',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'delay',
- 'Specify the delay, in milliseconds, between two images.',
- 'INTEGER',
- TRUE,
- TRUE
- ),
- (
- 'carousel',
- 'image',
- 'The URL (absolute or relative) of an image to display in the carousel.',
- 'URL',
- FALSE,
- FALSE
- ),
- (
- 'carousel',
- 'title',
- 'Add caption to the slide.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'carousel',
- 'description',
- 'A short paragraph.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'carousel',
- 'description_md',
- 'A short paragraph formatted using markdown.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'carousel',
- 'width',
- 'The width of the image, in pixels.',
- 'INTEGER',
- FALSE,
- TRUE
- ),
- (
- 'carousel',
- 'height',
- 'The height of the image, in pixels.',
- 'INTEGER',
- FALSE,
- TRUE
- );
-INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES
- ('carousel', 'image_alt', 'Alternative text describing the slide image. Leave empty if the image is decorative or its caption already describes it.', 'TEXT', FALSE, TRUE);
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties)
-VALUES (
- 'carousel',
- 'A basic example of carousel',
- JSON(
- '[
- {"component":"carousel","name":"cats1","title":"Famous Database Animals"},
- {"image_alt":"African elephants at a watering hole","image":"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Elefantes_africanos_de_sabana_%28Loxodonta_africana%29%2C_Elephant_Sands%2C_Botsuana%2C_2018-07-28%2C_DD_114-117_PAN.jpg/1280px-Elefantes_africanos_de_sabana_%28Loxodonta_africana%29%2C_Elephant_Sands%2C_Botsuana%2C_2018-07-28%2C_DD_114-117_PAN.jpg"},
- {"image_alt":"A panoramic view of Penguin Island","image":"https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Penguin_Island_panorama_with_ferry_and_dolphins_in_foreground%2C_March_2023_06.jpg/1280px-Penguin_Island_panorama_with_ferry_and_dolphins_in_foreground%2C_March_2023_06.jpg"}
- ]'
- )
- ),
- (
- 'carousel',
- 'An advanced example of carousel with controls',
- JSON(
- '[
- {"component":"carousel","title":"SQL web apps","width":10, "center":true,"controls":true,"auto":true},
- {"image":"/sqlpage_cover_image.webp","title":"SQLPage is modern","description":"Built by engineers who have built so many web applications the old way, they decided they just wouldn''t anymore.", "height": 512},
- {"image":"/sqlpage_illustration_alien.webp","title":"SQLPage is easy", "description":"SQLPage connects to your database, then it turns your SQL queries into nice websites.", "height": 512}
- ]'
- )
- );
diff --git a/examples/official-site/sqlpage/migrations/35_code_title.sql b/examples/official-site/sqlpage/migrations/35_code_title.sql
deleted file mode 100644
index cf2960332..000000000
--- a/examples/official-site/sqlpage/migrations/35_code_title.sql
+++ /dev/null
@@ -1,115 +0,0 @@
--- Documentation for the title component
-INSERT INTO component (name, description, icon, introduced_in_version) VALUES (
- 'title',
- 'Defines HTML headings. The level 1 is used for the maximal size and the level 6 is used for the minimal size.',
- 'letter-case-upper',
- '0.19.0'
-);
-
-INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES (
- 'title',
- 'center',
- 'Whether to center the title.',
- 'BOOLEAN',
- TRUE,
- TRUE
-),(
- 'title',
- 'contents',
- 'A text to display.',
- 'TEXT',
- TRUE,
- FALSE
-),(
- 'title',
- 'level',
- 'Set the heading level (default level is 1)',
- 'INTEGER',
- TRUE,
- TRUE
-);
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties) VALUES (
- 'title',
- 'Displays several titles with different levels.',
- JSON(
- '[
- {"component":"title","contents":"Level 1"},
- {"component":"title","contents":"Level 2","level": 2},
- {"component":"title","contents":"Level 3","level": 3}
- ]'
- )
-);
-
-INSERT INTO example(component, description, properties) VALUES (
- 'title',
- 'Displays a centered title.',
- JSON(
- '[
- {"component":"title","contents":"Level 1","center": true}
- ]'
- )
-);
-
--- Documentation for the code component
-INSERT INTO component (name, description, icon, introduced_in_version) VALUES (
- 'code',
- 'Displays one or many blocks of code from a programming language or formated text as XML or JSON.',
- 'code',
- '0.19.0'
-);
-
-INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES (
- 'code',
- 'title',
- 'Set the heading level (default level is 1)',
- 'TEXT',
- FALSE,
- TRUE
-),(
- 'code',
- 'contents',
- 'A block of code.',
- 'TEXT',
- FALSE,
- FALSE
-),(
- 'code',
- 'description',
- 'Description of the snipet of code.',
- 'TEXT',
- FALSE,
- TRUE
-),(
- 'code',
- 'description_md',
- 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.',
- 'TEXT',
- FALSE,
- TRUE
-),(
- 'code',
- 'language',
- 'Set the programming language name.',
- 'TEXT',
- FALSE,
- TRUE
-);
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties) VALUES (
- 'code',
- 'Displays a block of HTML code.',
- JSON(
- '[
- {"component":"code"},
- {
- "title":"A HTML5 example",
- "language":"html",
- "description":"Here’s the very minimum that an HTML document should contain, assuming it has CSS and JavaScript linked to it.",
- "contents":"\n\n\t\n\t\t \n\t\ttitle \n\t\t \n\t\t\n\t\n\t\n\t\t\n\t\n"
- }
- ]'
- )
-);
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/37_rss.sql b/examples/official-site/sqlpage/migrations/37_rss.sql
deleted file mode 100644
index 0a3e70bb8..000000000
--- a/examples/official-site/sqlpage/migrations/37_rss.sql
+++ /dev/null
@@ -1,287 +0,0 @@
--- Documentation for the RSS component
-INSERT INTO component (name, description, icon, introduced_in_version) VALUES (
- 'rss',
- 'Produces a data flow in the RSS format.
-Can be used to generate a podcast feed.
-To use this component, you must first return an HTTP header with the "application/rss+xml" content type (see http_header component). Next, you must use the shell-empty component to avoid that SQLPage generates HTML code.',
- 'rss',
- '0.20.0'
-);
-
-INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES (
- 'rss',
- 'title',
- 'Defines the title of the channel.',
- 'TEXT',
- TRUE,
- FALSE
-),(
- 'rss',
- 'link',
- 'Defines the hyperlink to the channel.',
- 'URL',
- TRUE,
- FALSE
-),(
- 'rss',
- 'description',
- 'Describes the channel.',
- 'TEXT',
- TRUE,
- FALSE
-),(
- 'rss',
- 'language',
- 'Defines the language of the channel, specified in the ISO 639 format. For example, "en" for English, "fr" for French.',
- 'TEXT',
- TRUE,
- TRUE
-),(
- 'rss',
- 'category',
- 'Defines the category of the channel. The value should be a string representing the category (e.g., "News", "Technology", etc.).',
- 'TEXT',
- TRUE,
- TRUE
-),(
- 'rss',
- 'sub_category',
- 'Defines a sub-category, nested inside the "category". Ignored unless "category" is also set.',
- 'TEXT',
- TRUE,
- TRUE
-),(
- 'rss',
- 'explicit',
- 'Indicates whether the channel contains explicit content. The value can be either TRUE or FALSE.',
- 'BOOLEAN',
- TRUE,
- TRUE
-),(
- 'rss',
- 'image_url',
- 'Provides a URL linking to the artwork for the channel.',
- 'URL',
- TRUE,
- TRUE
-),(
- 'rss',
- 'author',
- 'Defines the group, person, or people responsible for creating the channel.',
- 'TEXT',
- TRUE,
- TRUE
-),(
- 'rss',
- 'copyright',
- 'Provides the copyright details for the channel.',
- 'TEXT',
- TRUE,
- TRUE
-),(
- 'rss',
- 'self_link',
- 'URL of the RSS feed.',
- 'URL',
- TRUE,
- TRUE
-),(
- 'rss',
- 'funding_url',
- 'Specifies the donation/funding links for the channel. The content of the tag is the recommended string to be used with the link.',
- 'URL',
- TRUE,
- TRUE
-),(
- 'rss',
- 'funding_text',
- 'The text to display with the donation/funding link. Ignored unless "funding_url" is also set.',
- 'TEXT',
- TRUE,
- TRUE
-),(
- 'rss',
- 'type',
- 'Specifies the channel as either episodic or serial. The value can be either "episodic" or "serial".',
- 'TEXT',
- TRUE,
- TRUE
-),(
- 'rss',
- 'complete',
- 'Specifies that a channel is complete and will not post any more items in the future.',
- 'BOOLEAN',
- TRUE,
- TRUE
-),(
- 'rss',
- 'locked',
- 'Tells podcast hosting platforms whether they are allowed to import this feed.',
- 'BOOLEAN',
- TRUE,
- TRUE
-),(
- 'rss',
- 'guid',
- 'The globally unique identifier (GUID) for a channel. The value is a UUIDv5.',
- 'TEXT',
- TRUE,
- TRUE
-),(
- 'rss',
- 'title',
- 'Defines the title of the feed item (episode name, blog post title, etc.).',
- 'TEXT',
- FALSE,
- FALSE
-),(
- 'rss',
- 'link',
- 'Defines the hyperlink to the item (blog post URL, etc.).',
- 'URL',
- FALSE,
- FALSE
-),(
- 'rss',
- 'description',
- 'Describes the item',
- 'TEXT',
- FALSE,
- FALSE
-),(
- 'rss',
- 'date',
- 'Indicates when the item was published (RFC-822 date-time).',
- 'TEXT',
- FALSE,
- TRUE
-),(
- 'rss',
- 'enclosure_url',
- 'For podcast episodes, provides a URL linking to the audio/video episode content, in mp3, m4a, m4v, or mp4 format.',
- 'URL',
- FALSE,
- TRUE
-),(
- 'rss',
- 'enclosure_length',
- 'The length in bytes of the audio/video episode content.',
- 'INTEGER',
- FALSE,
- TRUE
-),(
- 'rss',
- 'enclosure_type',
- 'The MIME media type of the audio/video episode content (e.g., "audio/mpeg", "audio/m4a", "video/m4v", "video/mp4").',
- 'TEXT',
- FALSE,
- TRUE
-),(
- 'rss',
- 'guid',
- 'The globally unique identifier (GUID) for an item.',
- 'TEXT',
- FALSE,
- TRUE
-),(
- 'rss',
- 'episode',
- 'The chronological number that is associated with an item.',
- 'INTEGER',
- FALSE,
- TRUE
-),(
- 'rss',
- 'season',
- 'The chronological number associated with an item''s season.',
- 'INTEGER',
- FALSE,
- TRUE
-),(
- 'rss',
- 'episode_type',
- 'Defines the type of content for a specific item. The value can be either "full", "trailer", or "bonus".',
- 'TEXT',
- FALSE,
- TRUE
-),(
- 'rss',
- 'block',
- 'Prevents a specific item from appearing in podcast listening applications.',
- 'BOOLEAN',
- FALSE,
- TRUE
-),(
- 'rss',
- 'explicit',
- 'Indicates whether the item contains explicit content. The value can be either TRUE or FALSE.',
- 'BOOLEAN',
- FALSE,
- TRUE
-),(
- 'rss',
- 'image_url',
- 'Provides a URL linking to the artwork for the item.',
- 'URL',
- FALSE,
- TRUE
-),(
- 'rss',
- 'duration',
- 'The duration of an item in seconds.',
- 'INTEGER',
- FALSE,
- TRUE
-),(
- 'rss',
- 'transcript_url',
- 'A link to a transcript or closed captions file for the item.',
- 'URL',
- FALSE,
- TRUE
-),(
- 'rss',
- 'transcript_type',
- 'The type of the transcript or closed captions file for the item (e.g., "text/plain", "text/html", "text/vtt", "application/json", "application/x-subrip").',
- 'TEXT',
- FALSE,
- TRUE
-);
-
--- Insert example(s) for the component
-INSERT INTO example (component, description)
-VALUES (
- 'rss',
- '
-### An RSS channel about SQLPage latest news.
-
-```sql
-select ''http_header'' as component, ''application/rss+xml'' as content_type;
-select ''shell-empty'' as component;
-select
- ''rss'' as component,
- ''SQLPage blog'' as title,
- ''https://sql-page.com/blog.sql'' as link,
- ''latest news about SQLpage'' as description,
- ''en'' as language,
- ''Technology'' as category,
- FALSE as explicit,
- ''https://sql-page.com/favicon.ico'' as image_url,
- ''Ophir Lojkine'' as author,
- ''https://github.com/sponsors/lovasoa'' as funding_url,
- ''episodic'' as type;
-select
- ''Hello everyone !'' as title,
- ''https://sql-page.com/blog.sql?post=Come%20see%20me%20build%20twitter%20live%20on%20stage%20in%20Prague'' as link,
- ''If some of you european SQLPagers are around Prague this december, I will be giving a talk about SQLPage at pgconf.eu on December 14th.'' as description,
- ''http://127.0.0.1:8080/sqlpage_introduction_video.mp4'' as enclosure_url,
- 123456789 as enclosure_length,
- ''video/mp4'' as enclosure_type,
- ''2023-12-04'' as date;
-```
-
-Once you have your rss feed ready, you can submit it to podcast directories like
-[Apple Podcasts](https://podcastsconnect.apple.com/my-podcasts),
-[Spotify](https://podcasters.spotify.com/),
-[Google Podcasts](https://podcastsmanager.google.com/)...
-');
\ 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/46_html.sql b/examples/official-site/sqlpage/migrations/46_html.sql
deleted file mode 100644
index 58168c0d4..000000000
--- a/examples/official-site/sqlpage/migrations/46_html.sql
+++ /dev/null
@@ -1,97 +0,0 @@
--- Documentation for the RSS component
-INSERT INTO
- component (name, description, icon, introduced_in_version)
-VALUES
- (
- 'html',
- 'Include raw HTML in the output. For advanced users only. Use this component to create complex layouts or to include external content.
- Be very careful when using this component with user-generated content, as it can lead to security vulnerabilities.
- Use this component only if you are familiar with the security implications of including raw HTML, and understand the risks of cross-site scripting (XSS) attacks.',
- 'html',
- '0.25.0'
- );
-
-INSERT INTO
- parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES
- (
- 'html',
- 'html',
- 'Raw HTML content to include in the page. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.',
- 'TEXT',
- TRUE,
- TRUE
- ),
- (
- 'html',
- 'html',
- 'Raw HTML content to include in the page. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'html',
- 'text',
- 'Text content to include in the page. This will be sanitized and escaped. Use this property to include user-generated content that should not contain HTML tags.',
- 'TEXT',
- FALSE,
- TRUE
- ),
- (
- 'html',
- 'post_html',
- 'Raw HTML content to include after the text content. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.',
- 'TEXT',
- FALSE,
- TRUE
- );
-
--- Insert example(s) for the component
-INSERT INTO
- example (component, description, properties)
-VALUES
- (
- 'html',
- 'Include a simple HTML snippet. In this example, the HTML code is hardcoded in the SQL query, so it is safe. You should never include data that may be manipulated by a user in the HTML content.
- ',
- JSON (
- '[{
- "component": "html",
- "html": "This text is safe because it is hardcoded ! "
- }]'
- )
- ),
- (
- 'html',
- 'Include multiple html snippets as row-level parameters. Again, be careful what you include in the HTML content. If the data comes from a user, it can be manipulated to include malicious code.',
- JSON (
- '[{"component":"html", "html":""},
- {"html":"
"},
- {"html":"
"},
- {"html":"
"}
- ]'
- )
- ),
- (
- 'html',
- 'In order to include user-generated content that should be sanitized, use the `text` property instead of `html`. The `text` property will display the text as-is, without interpreting any HTML tags.',
- JSON (
- '
- [
- {"component": "html"},
- {
- "html": "The following will be sanitized: ",
- "text": "",
- "post_html": " . Phew! That was close!
"
- }
- ]'
- )
- );
\ No newline at end of file
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 267a728d2..000000000
--- a/examples/official-site/sqlpage/migrations/47_link.sql
+++ /dev/null
@@ -1,77 +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.
-
-### Parameters
- - `file` (TEXT): The name of the SQLPage file to link to.
- - `parameters` (JSON): The parameters to pass to the linked file.
- - `fragment` (TEXT): An optional fragment (hash) to append to the URL. This is useful for linking to a specific section of a page. For instance if `product.sql` contains `select ''text'' as component, ''product_description'' as id;`, you can link to the product description section with `sqlpage.link(''product.sql'', json_object(''product_name'', name), ''product_description'')`.
-'
- );
-
-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/48_status_code.sql b/examples/official-site/sqlpage/migrations/48_status_code.sql
deleted file mode 100644
index f80d4266a..000000000
--- a/examples/official-site/sqlpage/migrations/48_status_code.sql
+++ /dev/null
@@ -1,65 +0,0 @@
--- Insert the status_code component into the component table
-INSERT INTO
- component (name, description, icon)
-VALUES
- (
- 'status_code',
- 'Sets the HTTP response code for the current page.
-
-This is an advanced technical component.
-You typically need it when building internet-facing APIs and websites,
-but you may not need it for simple internal applications.
-
-- Indicating operation results when using [SQLPage as an API](?component=json)
- - `200`: *OK*, for successful operations
- - `201`: *Created*, for successful record insertion
- - `404`: *Not Found*, for missing resources
- - `500`: *Internal Server Error*, for failed operations
-- Handling data validation errors
- - `400`: *Bad Request*, for invalid data
-- Enforcing access controls
- - `403`: *Forbidden*, for unauthorized access
- - `401`: *Unauthorized*, for unauthenticated access
-- Tracking system health
- - `500`: *Internal Server Error*, for failed operations
-
-For search engine optimization:
-- Use `404` for deleted content to remove outdated URLs from search engines
-- For redirection from one page to another, use
- - `301` (moved permanently), or
- - `302` (moved temporarily)
-- Use `503` during maintenance',
- 'error-404'
- );
-
--- Insert the parameters for the status_code component into the parameter table
-INSERT INTO
- parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES
- (
- 'status_code',
- 'status',
- 'HTTP status code (e.g., 200 OK, 401 Unauthorized, 409 Conflict)',
- 'INTEGER',
- TRUE,
- FALSE
- );
-
-INSERT INTO example (component, description)
-VALUES (
- 'status_code',
- '
-Set the HTTP status code to 404, indicating that the requested resource was not found.
-Useful in combination with [`404.sql` files](/your-first-sql-website/custom_urls.sql):
-
-```sql
-SELECT ''status_code'' as component, 404 as status;
-```
-');
diff --git a/examples/official-site/sqlpage/migrations/49_big_number.sql b/examples/official-site/sqlpage/migrations/49_big_number.sql
deleted file mode 100644
index acdb2858d..000000000
--- a/examples/official-site/sqlpage/migrations/49_big_number.sql
+++ /dev/null
@@ -1,66 +0,0 @@
--- Big Number Component Documentation
-
--- Component Definition
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('big_number', 'chart-area', 'A component to display key metrics or statistics with optional description, change indicator, and progress bar. Useful in dashboards.', '0.28.0');
-
--- Inserting parameter information for the big_number component
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'big_number', * FROM (VALUES
- -- Top-level parameters (for the whole big_number list)
- ('columns', 'The number of columns to display the big numbers in (default is one column per item).', 'INTEGER', TRUE, TRUE),
- ('wrap', 'Wrap long titles and descriptions onto multiple lines. By default, they are truncated with an ellipsis.', 'BOOLEAN', TRUE, TRUE),
- -- id and class, at both levels, come from 99_shared_id_class_attributes.sql
- -- Item-level parameters (for each big number)
- ('title', 'The title or label for the big number.', 'TEXT', FALSE, TRUE),
- ('title_link', 'A link for the Big Number title. If set, the entire title becomes clickable.', 'TEXT', FALSE, TRUE),
- ('title_link_new_tab', 'If true, the title link will open in a new tab/window.', 'BOOLEAN', FALSE, TRUE),
- ('value_link', 'A link for the Big Number value. If set, the entire value becomes clickable.', 'TEXT', FALSE, TRUE),
- ('value_link_new_tab', 'If true, the value link will open in a new tab/window.', 'BOOLEAN', FALSE, TRUE),
- ('value', 'The main value to be displayed prominently.', 'TEXT', FALSE, FALSE),
- ('unit', 'The unit of measurement for the value.', 'TEXT', FALSE, TRUE),
- ('description', 'A description or additional context for the big number.', 'TEXT', FALSE, TRUE),
- ('change_percent', 'The percentage change in value (e.g., 7 for 7% increase, -8 for 8% decrease).', 'INTEGER', FALSE, TRUE),
- ('progress_percent', 'The value of the progress (0-100).', 'INTEGER', FALSE, TRUE),
- ('progress_color', 'The color of the progress bar (e.g., "primary", "success", "danger").', 'TEXT', FALSE, TRUE),
- ('dropdown_item', 'A list of JSON objects containing links. e.g. {"label":"This week", "link":"?days=7"}', 'JSON', FALSE, TRUE),
- ('color', 'The color of the card background and its main value.', 'COLOR', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('big_number', 'Big numbers with change indicators and progress bars',
- json('[
- {"component":"big_number"},
- {
- "title":"Sales",
- "value":75,
- "unit":"%",
- "title_link": "#sales_dashboard",
- "title_link_new_tab": true,
- "value_link": "#sales_details",
- "value_link_new_tab": false,
- "description":"Conversion rate",
- "change_percent": 9,
- "progress_percent": 75,
- "progress_color": "blue"
- },
- {
- "title":"Revenue",
- "value":"4,300",
- "unit":"$",
- "description":"Year on year",
- "change_percent": -8
- }
- ]'));
-
-INSERT INTO example(component, description, properties) VALUES
- ('big_number', 'Big numbers with dropdowns and customized layout',
- json('[
- {"component":"big_number", "columns":3, "id":"colorfull_dashboard"},
- {"title":"Users", "value":"1,234", "color": "red", "title_link": "#users", "title_link_new_tab": false, "value_link": "#users_details", "value_link_new_tab": true },
- {"title":"Orders", "value":56, "color": "green", "title_link": "#orders", "title_link_new_tab": true },
- {"title":"Revenue", "value":"9,876", "unit": "€", "color": "blue", "change_percent": -7, "dropdown_item": [
- {"label":"This week", "link":"?days=7&component=big_number#colorfull_dashboard"},
- {"label":"This month", "link":"?days=30&component=big_number#colorfull_dashboard"},
- {"label":"This quarter", "link":"?days=90&component=big_number#colorfull_dashboard"}
- ]}
- ]'));
diff --git a/examples/official-site/sqlpage/migrations/51_column.sql b/examples/official-site/sqlpage/migrations/51_column.sql
deleted file mode 100644
index 06674e936..000000000
--- a/examples/official-site/sqlpage/migrations/51_column.sql
+++ /dev/null
@@ -1,118 +0,0 @@
--- Column Component Documentation
-
--- Component Definition
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('columns', 'columns', 'A component to display various items in a card layout, allowing users to choose options. Useful for showcasing different features or services, or KPIs. See also the big_number component.', '0.29.0');
-
--- Inserting parameter information for the column component
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'columns', * FROM (VALUES
- ('title', 'The title or label for the item.', 'TEXT', FALSE, TRUE),
- ('value', 'The value associated with the item.', 'TEXT', FALSE, TRUE),
- ('description', 'A brief description of the item.', 'TEXT', FALSE, TRUE),
- ('description_md', 'A brief description of the item, formatted using markdown.', 'TEXT', FALSE, TRUE),
- ('item', 'A list of bullet points associated with the columns, represented either as text, or as a json object with "icon", "color", and "description" or "description_md" fields.', 'JSON', FALSE, TRUE),
- ('link', 'A link associated with the item.', 'TEXT', FALSE, TRUE),
- ('button_text', 'Text for the button.', 'TEXT', FALSE, TRUE),
- ('button_color', 'Optional color for the button.', 'TEXT', FALSE, TRUE),
- ('target', 'Optional target for the button. Set to "_blank" to open links in a new tab.', 'TEXT', FALSE, TRUE),
- ('value_color', 'Color for the value text.', 'TEXT', FALSE, TRUE),
- ('small_text', 'Optional small text to display after the value.', 'TEXT', FALSE, TRUE),
- ('icon', 'Optional icon to display in a ribbon.', 'ICON', FALSE, TRUE),
- ('icon_color', 'Color for the icon in the ribbon.', 'TEXT', FALSE, TRUE),
- ('size', 'Size of the column, affecting layout.', 'INTEGER', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('columns', 'Pricing Plans Display',
- json('[
- {"component":"columns"},
- {
- "title":"Start Plan",
- "value":"€18",
- "description":"Perfect for testing and small-scale projects",
- "item": [
- "128MB Database",
- "SQLPage hosting",
- "Community support"
- ],
- "link":"https://datapage.app",
- "button_text":"Start Free Trial",
- "small_text":"/month"
- },
- {
- "title":"Pro Plan",
- "value":"€40",
- "icon":"rocket",
- "description":"For growing projects needing enhanced features",
- "item": [
- {"icon":"database", "color": "blue", "description":"1GB Database"},
- {"icon":"headset", "color": "green", "description":"Priority Support"},
- {"icon":"world", "color": "purple", "description":"Custom Domain"}
- ],
- "link":"https://datapage.app",
- "button_text":"Start Free Trial",
- "button_color":"indigo",
- "value_color":"indigo",
- "small_text":"/month"
- },
- {
- "title":"Enterprise Plan",
- "value":"€600",
- "icon":"building-skyscraper",
- "description":"For large-scale operations with custom needs",
- "item": [
- {"icon":"database-plus", "description_md":"**Custom Database Scaling**"},
- {"icon":"shield-lock", "description_md":"**Enterprise Auth** with Single Sign-On"},
- {"icon":"headset", "description_md":"**Monthly** Expert Support time"},
- {"icon":"file-certificate", "description_md":"**SLA** with guaranteed uptime"}
- ],
- "link":"mailto:contact@datapage.app",
- "button_text":"Contact Us",
- "small_text":"/month",
- "target":"_blank"
- }
- ]')),
-
- ('columns', 'Tech Company KPIs Display',
- json('[
- {"component":"columns"},
- {
- "title":"Monthly Active Users",
- "value":"10k",
- "value_color":"blue",
- "size": 4,
- "description":"Total active users this month, showcasing user engagement.",
- "item": [
- {"icon": "target", "description":"Target: 12,000"}
- ],
- "link":"#",
- "button_text":"User Activity Overview",
- "button_color":"info"
- },
- {
- "title":"Revenue",
- "value":"$49k",
- "value_color":"blue",
- "size": 4,
- "description":"Total revenue generated this month, indicating financial performance.",
- "item": [
- {"icon":"trending-down", "color": "red", "description":"down from $51k last month" }
- ],
- "link":"#",
- "button_text":"Financial Dashboard",
- "button_color":"info"
- },
- {
- "title":"Customer Satisfaction",
- "value":"94%",
- "value_color":"blue",
- "size": 4,
- "description":"Percentage of satisfied customers, reflecting service quality.",
- "item": [
- {"icon":"trending-up", "color": "green", "description":"+ 2% this month" }
- ],
- "link":"#",
- "button_text": "Open Google Ratings",
- "button_color":"info"
- }
- ]'));
diff --git a/examples/official-site/sqlpage/migrations/52_foldable.sql b/examples/official-site/sqlpage/migrations/52_foldable.sql
deleted file mode 100644
index d70201dfe..000000000
--- a/examples/official-site/sqlpage/migrations/52_foldable.sql
+++ /dev/null
@@ -1,27 +0,0 @@
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('foldable', 'chevrons-down', 'A foldable list of elements which can be expanded individually.', '0.29.0');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'foldable', * FROM (VALUES
- ('id', 'ID attribute added to the container in HTML. Used for targeting through CSS or for scrolling via links. When set at the top level, applies to the entire foldable component.', 'TEXT', TRUE, TRUE),
- ('class', 'CSS class(es) to add to the foldable container. When set at the top level, applies to the entire foldable component.', 'TEXT', TRUE, TRUE),
- ('id', 'ID attribute added to individual foldable items. Used for targeting through CSS or for scrolling via links.', 'TEXT', FALSE, TRUE),
- ('class', 'CSS class(es) to add to individual foldable items.', 'TEXT', FALSE, TRUE),
- ('title', 'Title of the foldable item, displayed on the button.', 'TEXT', FALSE, TRUE),
- ('description', 'Plain text description of the item, displayed when expanded.', 'TEXT', FALSE, TRUE),
- ('description_md', 'Markdown description of the item, displayed when expanded.', 'TEXT', FALSE, TRUE),
- ('expanded', 'If set to TRUE, the foldable item starts in an expanded state. Defaults FALSE', 'BOOLEAN', FALSE, TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('foldable', 'A single foldable paragraph of text', json('[
- {"component":"foldable"},
- {"title":"The foldable component", "description": "This is a simple foldable component. It can be used to show and hide content. It is a list of items, each with a title and a description. The description is displayed when the item is expanded."},
- ]'));
-
-INSERT INTO example(component, description, properties) VALUES
- ('foldable', 'A SQLPage-themed foldable list with Markdown', json('[
- {"component":"foldable"},
- {"title":"Quick Prototyping", "description_md": "Build a functional web app prototype in minutes using just SQL queries:\n\n- Rapid development\n- Ideal for MVPs\n- Great for internal tools\n\nLearn more about [quick prototyping](/your-first-sql-website/).", "expanded": true},
- {"title":"Data Visualization", "description_md": "Quickly transform your database into useful insights:\n\n1. **Charts**: Line, bar, pie\n2. **KPIs**: Appealing visualizations of key metrics\n3. **Maps**: Geospatial data\n\nAs simple as:\n\n```sql\nSELECT ''chart'' as component;\nSELECT date as x, revenue as y FROM sales;\n```"},
- {"title":"Don''t stare, interact!", "description_md": "SQLPage is not just a passive *Business Intelligence* tool. With SQLPage, you can act upon user input:\n\n- *User input collection*: Building a form is just as easy as building a chart.\n- *Data validation*: Write your own validation rules in SQL.\n- *Database updates*: `INSERT` and `UPDATE` are first-class citizens.\n- *File uploads*: Upload `CSV` and other files, store and display them the way you want.\n\n> Let users interact with your data, not just look at it!"}
- ]'));
\ No newline at end of file
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 c406c3f7a..000000000
--- a/examples/official-site/sqlpage/migrations/58_fetch_with_meta.sql
+++ /dev/null
@@ -1,97 +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 url
-where
- json_extract($response, ''$.error'') is not null
- or json_extract($response, ''$.status'') != 200;
-
--- Extract data from the response json body
-select ''card'' as component;
-select
- json_extract($response, ''$.json_body.name'') as title,
- json_extract($response, ''$.json_body.abilities[0].ability.name'') as description
-from $response;
-```
-
-### Example: Advanced Request with Authentication
-
-```sql
-set request = json_object(
- ''method'', ''POST'',
- ''url'', ''https://sqlpage.free.beeceptor.com'',
- ''headers'', json_object(
- ''Content-Type'', ''application/json'',
- ''Authorization'', ''Bearer '' || sqlpage.environment_variable(''API_TOKEN'')
- ),
- ''body'', json_object(
- ''key'', ''value''
- )
-);
-set response = sqlpage.fetch_with_meta($request);
-
--- Check response content type
-select ''debug'' as component, $response as response;
-```
-
-The function accepts the same parameters as the [`fetch` function](?function=fetch).'
- );
-
-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/59_unsafe_contents_md.sql b/examples/official-site/sqlpage/migrations/59_unsafe_contents_md.sql
deleted file mode 100644
index 5f8f2c97a..000000000
--- a/examples/official-site/sqlpage/migrations/59_unsafe_contents_md.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'text', * FROM (VALUES
-('unsafe_contents_md','Markdown format with html blocks. Use this only with trusted content. See the html-blocks section of the Commonmark spec for additional info.', 'TEXT', TRUE, TRUE),
-('unsafe_contents_md','Markdown format with html blocks. Use this only with trusted content. See the html-blocks section of the Commonmark spec for additional info.', 'TEXT', FALSE, TRUE)
-);
diff --git a/examples/official-site/sqlpage/migrations/60_empty_state.sql b/examples/official-site/sqlpage/migrations/60_empty_state.sql
deleted file mode 100644
index 1f0b65518..000000000
--- a/examples/official-site/sqlpage/migrations/60_empty_state.sql
+++ /dev/null
@@ -1,52 +0,0 @@
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('empty_state', 'info-circle', 'Displays a large placeholder message to communicate a single information to the user and invite them to take action.
-
-Typically includes a title, an optional icon/image, descriptive text (rich text formatting and images supported via Markdown), and a call-to-action button.
-
-Ideal for first-use screens, empty data sets, "no results" pages, or error messages.', '0.35.0');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'empty_state', * FROM (VALUES
- ('title','Description of the empty state.','TEXT',TRUE,FALSE),
- ('header','Text displayed on the top of the empty state.','TEXT',TRUE,TRUE),
- ('icon','Name of an icon to be displayed on the top of the empty state.','ICON',TRUE,TRUE),
- ('image','The URL (absolute or relative) of an image to display at the top of the empty state.','URL',TRUE,TRUE),
- ('description','A short text displayed below the title.','TEXT',TRUE,TRUE),
- ('description_md','A short text displayed below the title, formatted using markdown.','TEXT',TRUE,TRUE),
- ('link_text','The text displayed on the button.','TEXT',TRUE,FALSE),
- ('link_icon','Name of an icon to be displayed on the left side of the button.','ICON',TRUE,FALSE),
- ('link','The URL to which the button should navigate when clicked.','URL',TRUE,FALSE)
- -- id and class come from 99_shared_id_class_attributes.sql
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('empty_state', '
-This example shows how to create a 404-style "Not Found" empty state with
- - a prominent header displaying "404",
- - a helpful description suggesting to adjust search parameters, and
- - a "Search again" button with a search icon that links back to the search page.
-',
- json('[{
- "component": "empty_state",
- "title": "No results found",
- "header": "404",
- "description": "Try adjusting your search or filter to find what you''re looking for.",
- "link_text": "Search again",
- "link_icon": "search",
- "link": "#not-found",
- "id": "not-found"
- }]')),
- ('empty_state', '
-It''s possible to use an icon or an image to illustrate the problem.
-',
- json('[{
- "component": "empty_state",
- "title": "A critical problem has occurred",
- "icon": "mood-wrrr",
- "description_md": "SQLPage can do a lot of things, but this is not one of them.
-
-Please restart your browser and **cross your fingers**.",
- "link_text": "Close and restart",
- "link_icon": "rotate-clockwise",
- "link": "#"
- }]'));
-
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/62_example_cards.sql b/examples/official-site/sqlpage/migrations/62_example_cards.sql
deleted file mode 100644
index 04a7c90d9..000000000
--- a/examples/official-site/sqlpage/migrations/62_example_cards.sql
+++ /dev/null
@@ -1,104 +0,0 @@
-create table
- example_cards as
-select
- 'Advanced Authentication' as title,
- 'user-authentication' as folder, -- Has to exactly match the folder name in the /examples/ directory
- 'postgres' as db_engine,
- 'Build a secure user authentication system with login, signup, and in-database session management.' as description
-union all
-select
- 'Authenticated CRUD',
- 'CRUD - Authentication',
- 'sqlite',
- 'Complete Create-Read-Update-Delete operations with user authentication.'
-union all
-select
- 'Image Gallery',
- 'image gallery with user uploads',
- 'sqlite',
- 'Create an image gallery with user uploads and session management.'
-union all
-select
- 'Developer UI',
- 'SQLPage developer user interface',
- 'postgres',
- 'A web-based interface for managing SQLPage files and database tables.'
-union all
-select
- 'Corporate Game',
- 'corporate-conundrum',
- 'sqlite',
- 'An interactive multiplayer board game with real-time updates.'
-union all
-select
- 'Roundest Pokemon',
- 'roundest_pokemon_rating',
- 'sqlite',
- 'Demo app with a distinct non-default design, using custom HTML templates for everything.'
-union all
-select
- 'Todo Application',
- 'todo application (PostgreSQL)',
- 'postgres',
- 'A full-featured todo list application with PostgreSQL backend.'
-union all
-select
- 'MySQL & JSON',
- 'mysql json handling',
- 'mysql',
- 'Learn advanced JSON manipulation in MySQL to build advanced SQLPage applications.'
-union all
-select
- 'Apache Web Server',
- 'web servers - apache',
- 'mysql',
- 'Use an existing Apache httpd Web Server to expose your SQLPage application.'
-union all
-select
- 'Sending Emails',
- 'sending emails',
- 'sqlite',
- 'Use the fetch function to send emails (or interact with any other HTTP API).'
-union all
-select
- 'Simple Website',
- 'simple-website-example',
- 'sqlite',
- 'Basic website example with navigation and data management.'
-union all
-select
- 'Geographic App',
- 'PostGIS - using sqlpage with geographic data',
- 'postgres',
- 'Use SQLPage to create and manage geodata.'
-union all
-select
- 'Multi-step form',
- 'forms-with-multiple-steps',
- 'sqlite',
- 'Guide to the implementation of forms that spread over multiple pages.'
-union all
-select
- 'Custom HTML & JS',
- 'custom form component',
- 'mysql',
- 'Building a custom form component with a dynamic widget using HTML and javascript.'
-union all
-select
- 'Splitwise Clone',
- 'splitwise',
- 'sqlite',
- 'An expense tracker app to split expenses with your friends, with nice debt charts.'
-union all
-select
- 'Advanced Forms with MS SQL Server',
- 'microsoft sql server advanced forms',
- 'sql server',
- 'Forms with multi-value dropdowns, using SQL Server and its JSON functions.'
-union all
-select
- 'Rich Text Editor',
- 'rich-text-editor',
- 'sqlite',
- 'A rich text editor with bold, italic, lists, images, and more. It posts its contents as Markdown.'
-;
diff --git a/examples/official-site/sqlpage/migrations/63_modal.sql b/examples/official-site/sqlpage/migrations/63_modal.sql
deleted file mode 100644
index 308e40e61..000000000
--- a/examples/official-site/sqlpage/migrations/63_modal.sql
+++ /dev/null
@@ -1,85 +0,0 @@
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('modal', 'app-window', '
-Defines the a temporary popup box displayed on top of a webpage’s content.
-Useful for displaying additional information, help, or collect data from users.
-
-Modals are closed by default, and can be opened by clicking on a button or link targeting their ID.', '0.36.0');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'modal', * FROM (VALUES
- ('title','Description of the modal box.','TEXT',TRUE,FALSE),
- ('close','The text to display in the Close button.','TEXT',TRUE,TRUE),
- ('close_label','The same as `close`. Use it on databases where `close` is a reserved word, such as SQL Server.','TEXT',TRUE,TRUE),
- ('contents','A paragraph of text to display, without any formatting, without having to make additional queries.','TEXT',FALSE,TRUE),
- ('contents_md','Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.','TEXT',FALSE,TRUE),
- ('scrollable','Create a scrollable modal that allows scroll the modal body.','BOOLEAN',TRUE,TRUE),
- ('class','Class attribute added to the container in HTML. It can be used to apply custom styling to this item through css.','TEXT',TRUE,TRUE),
- ('id','ID attribute added to the container in HTML. It can be used to target this item through css or for displaying this item.','TEXT',TRUE,FALSE),
- ('large','Indicates that the modal box has an increased width.','BOOLEAN',TRUE,TRUE),
- ('small','Indicates that the modal box has a reduced width.','BOOLEAN',TRUE,TRUE),
- ('embed','Embed remote content in an iframe.','TEXT',TRUE,TRUE),
- ('embed_mode','Use "iframe" to display embedded content within an iframe.','TEXT',TRUE,TRUE),
- ('height','Height of the modal content, in pixels. Overflow content scrolls.','INTEGER',TRUE,TRUE),
- ('allow','For embedded content, this attribute specifies the features or permissions that can be used.','TEXT',TRUE,TRUE),
- ('sandbox','For embedded content, this attribute specifies the security restrictions on the loaded content.','TEXT',TRUE,TRUE),
- ('style','Applies CSS styles to the embedded content.','TEXT',TRUE,TRUE)
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('modal',
- 'This example shows how to create a modal box that displays a paragraph of text. The modal window is opened with the help of a button.',
- json('[
- {"component": "modal","id": "my_modal","title": "A modal box","close": "Close"},
- {"contents":"I''m a modal window, and I allow you to display additional information or help for the user."},
- {"component": "button"},
- {"title":"Open a simple modal","link":"#my_modal"}
- ]')
- ),
- ('modal',
- 'Example of modal form content',
- json('[
- {
- "component":"modal",
- "id":"my_embed_form_modal",
- "title":"Embeded form content",
- "large":true,
- "embed":"/examples/form.sql?_sqlpage_embed"
- },
- {"component": "button"},
- {"title":"Open a modal with a form","link":"#my_embed_form_modal"}
- ]')
- ),
- ('modal',
- 'A popup modal that contains a chart generated by a separate SQL file. The modal is triggered by links inside a datagrid.',
- json('[
- {
- "component":"modal",
- "id":"my_embed_chart_modal",
- "title":"Embeded chart content",
- "close":"Close",
- "embed":"/examples/chart.sql?_sqlpage_embed"
- },
- {"component": "datagrid"},
- {"title":"Chart", "color":"blue", "description":"Revenue", "link":"#my_embed_chart_modal"},
- {"title":"Form", "color":"green", "description":"Fill info", "link":"#my_embed_form_modal"},
- ]')
- ),
- ('modal',
- 'Example of modal video content',
- json('[
- {
- "component":"modal",
- "id":"my_embed_video_modal",
- "title":"Embeded video content",
- "close":"Close",
- "embed":"https://www.youtube.com/embed/mXdgmSdaXkg",
- "allow":"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share",
- "embed_mode":"iframe",
- "height":"350"
- },
- {"component": "text", "contents_md": "Open a [modal with a video](#my_embed_video_modal)"}
- ]')
- );
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'button', * FROM (VALUES
- ('modal','Display the modal window corresponding to the specified ID.','TEXT',FALSE,TRUE)
-) x;
diff --git a/examples/official-site/sqlpage/migrations/65_download.sql b/examples/official-site/sqlpage/migrations/65_download.sql
deleted file mode 100644
index a05b49ab8..000000000
--- a/examples/official-site/sqlpage/migrations/65_download.sql
+++ /dev/null
@@ -1,140 +0,0 @@
--- Insert the download component into the component table
-INSERT INTO
- component (name, description, icon, introduced_in_version)
-VALUES
- (
- 'download',
- '
-The *download* component lets a page immediately return a file to the visitor.
-
-Instead of showing a web page, it sends the file''s bytes as the whole response,
-so it should be used **at the very top of your SQL page** (before the shell or any other page contents).
-It is an error to use this component after another component that would display content.
-
-## Sending a file
-
-- You provide the file content using a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs).
-A data URL is just a text string that contains both the file type and the actual data.
-- Optionally, you provide a "filename" so the browser shows a proper Save As name.
-If you do not provide a filename, many browsers will try to display the file inline (for example images or JSON), depending on the content type.
-- You link to the page that uses the download component from another page, using the [button](/component.sql?component=button) component for example.
-
-## Data URL format
-
-- It looks like this: `data:[content-type][;base64],DATA`
-- Examples:
- - Plain text (URL-encoded): `data:text/plain,Hello%20world`
- - JSON (URL-encoded): `data:application/json,%7B%22message%22%3A%22Hi%22%7D`
- - Binary data (Base64): `data:application/octet-stream;base64,SGVsbG8h`
-
-Tips:
-- Use URL encoding when you have textual data. You can use [`sqlpage.url_encode(source_text)`](/functions?function=url_encode) to encode the data.
-- Use Base64 when you have binary data (images, PDFs, or content that may include special characters).
-- Use [`sqlpage.read_file_as_data_url(file_path)`](/functions?function=read_file_as_data_url) to read a file from the server and return it as a data URL.
-
-> Keep in mind that large files are better served from disk or object storage. Data URLs are best for small to medium files.
-There is a big performance penalty for loading large files as data URLs, so it is not recommended.
-',
- 'download',
- '0.37.0'
- );
-
--- Insert the parameters for the download component into the parameter table
-INSERT INTO
- parameter (
- component,
- name,
- description,
- type,
- top_level,
- optional
- )
-VALUES
- (
- 'download',
- 'data_url',
- 'The file content to send, written as a data URL (for example: data:text/plain,Hello%20world or data:application/octet-stream;base64,SGVsbG8h). The part before the comma declares the content type and whether the data is base64-encoded. The part after the comma is the actual data.',
- 'TEXT',
- TRUE,
- FALSE
- ),
- (
- 'download',
- 'filename',
- 'The suggested name of the file to save (for example: report.csv). When set, the browser will download the file as an attachment with this name. When omitted, many browsers may try to display the file inline depending on its content type.',
- 'TEXT',
- TRUE,
- TRUE
- );
-
--- Insert usage examples of the download component into the example table
-INSERT INTO
- example (component, description)
-VALUES
- (
- 'download',
- '
-## Simple plain text file
-Download a small text file. The content is URL-encoded (spaces become %20).
-
-```sql
-select
- ''download'' as component,
- ''data:text/plain,Hello%20SQLPage%20world!'' as data_url,
- ''hello.txt'' as filename;
-```
-'
- ),
- (
- 'download',
- '
-## Download a PDF file from the server
-
-Download a PDF file with the proper content type so PDF readers recognize it.
-Uses [`sqlpage.read_file_as_data_url(file_path)`](/functions?function=read_file_as_data_url) to read the file from the server.
-
-```sql
-select
- ''download'' as component,
- ''report.pdf'' as filename,
- sqlpage.read_file_as_data_url(''report.pdf'') as data_url;
-```
-'
- ),
- (
- 'download',
- '
-## Serve an image stored as a BLOB in the database
-
-### Automatically detect the mime type
-
-If you have a table with a column `content` that contains a BLOB
-(depending on the database, the type may be named `BYTEA`, `BLOB`, `VARBINARY`, or `IMAGE`),
-you can just return its contents directly, and SQLPage will automatically detect the mime type,
-and convert it to a data URL.
-
-```sql
-select
- ''download'' as component,
- content as data_url
-from document
-where id = $doc_id;
-```
-
-### Customize the mime type
-
-In PostgreSQL, you can use the [encode(bytes, format)](https://www.postgresql.org/docs/current/functions-binarystring.html#FUNCTION-ENCODE) function to encode the file content as Base64,
-and manually create your own data URL.
-
-```sql
-select
- ''download'' as component,
- ''data:'' || doc.mime_type || '';base64,'' || encode(doc.content::bytea, ''base64'') as data_url
-from document as doc
-where doc.id = $doc_id;
-```
-
- - In Microsoft SQL Server, you can use the [BASE64_ENCODE(bytes)](https://learn.microsoft.com/en-us/sql/t-sql/functions/base64-encode-transact-sql) function to encode the file content as Base64.
- - In MySQL and MariaDB, you can use the [TO_BASE64(str)](https://mariadb.com/docs/server/reference/sql-functions/string-functions/to_base64) function.
-'
- );
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/66_log_component.sql b/examples/official-site/sqlpage/migrations/66_log_component.sql
deleted file mode 100644
index 3a2cb083b..000000000
--- a/examples/official-site/sqlpage/migrations/66_log_component.sql
+++ /dev/null
@@ -1,61 +0,0 @@
-INSERT INTO component(name, icon, introduced_in_version, description) VALUES
-('log', 'logs', '0.37.1', 'A component that writes messages to the server logs.
-When a page runs, it prints your message to the terminal/console (standard error).
-Use it to track what happens and troubleshoot issues.
-
-## Reading log messages
-
-- Running from a terminal (Linux, macOS, or Windows PowerShell/Command Prompt): they show up in the window.
-- Docker: run `docker logs `.
-- Linux service (systemd): run `journalctl -u sqlpage`.
-- This component''s output is written to [standard error (stderr)](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)). SQLPage request access logs are separate and are written to standard output (stdout).
-');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'log', * FROM (VALUES
- -- top level
- ('message', 'The text to write to the server logs. It is printed when the page runs.', 'TEXT', TRUE, FALSE),
- ('level', 'How important the message is. One of ''trace'', ''debug'', ''info'' (default), ''warn'', ''error''. Not case-sensitive. Controls the level shown in the logs.', 'TEXT', TRUE, TRUE)
-) x;
-
-INSERT INTO example(component, description) VALUES
-('log', '
-### Record a simple message
-
-This writes "Hello, World!" to the server logs.
-
-```sql
-SELECT ''log'' as component, ''Hello, World!'' as message;
-```
-
-Example output:
-
-```text
-[2025-09-13T22:30:14.722Z INFO sqlpage::log from "x.sql" statement 1] Hello, World!
-```
-
-### Set the importance (level)
-
-Choose how important the message is.
-
-```sql
-SELECT ''log'' as component, ''error'' as level, ''This is an error message'' as message;
-```
-
-Example output:
-
-```text
-[2025-09-13T22:30:14.722Z ERROR sqlpage::log from "x.sql" statement 2] This is an error message
-```
-
-### Log dynamic information
-
-Include variables like a username.
-
-```sql
-set username = ''user''
-
-select ''log'' as component,
- ''403 - failed for '' || coalesce($username, ''None'') as message,
- ''error'' as level;
-```
-')
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/68_login.sql b/examples/official-site/sqlpage/migrations/68_login.sql
deleted file mode 100644
index 11d29de18..000000000
--- a/examples/official-site/sqlpage/migrations/68_login.sql
+++ /dev/null
@@ -1,79 +0,0 @@
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('login', 'password-user', '
-The login component is an authentication form with numerous customization options.
-It offers the main functionalities for this type of form.
-The user can enter their username and password.
-There are many optional attributes such as the use of icons on input fields, the insertion of a link to a page to reset the password, an option for the application to maintain the user''s identity via a cookie.
-It is also possible to set the title of the form, display the company logo, or customize the appearance of the form submission button.
-
-This component should be used in conjunction with other components such as [authentication](component.sql?component=authentication) and [cookie](component.sql?component=cookie).
-It does not implement any logic and simply collects the username and password to pass them to the code responsible for authentication.
-
-A few things to know :
-- The form uses the POST method to transmit information to the destination page,
-- The user''s username and password are entered into fields with the names `username` and `password`,
-- To obtain the values of username and password, you must use the variables `:username` and `:password`,
-- When you set the `remember_me_text` property, the variable `:remember` becomes available after form submission to check if the user checked the "remember me" checkbox.
-', '0.39.0');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'login', * FROM (VALUES
- ('title','Title of the authentication form.','TEXT',TRUE,TRUE),
- ('enctype','Form data encoding.','TEXT',TRUE,TRUE),
- ('action','An optional link to a target page that will handle the results of the form. ','TEXT',TRUE,TRUE),
- ('error_message','An error message to display above the form, typically shown after a failed login attempt.','TEXT',TRUE,TRUE),
- ('error_message_md','A markdown error message to display above the form, typically shown after a failed login attempt.','TEXT',TRUE,TRUE),
- ('username','Label and placeholder for the user account identifier text field.','TEXT',TRUE,FALSE),
- ('password','Label and placeholder for the password field.','TEXT',TRUE,FALSE),
- ('autofocus','Focus the username field when the page opens. Defaults to true. Set to false when the form is one part of a larger page.','BOOLEAN',TRUE,TRUE),
- ('username_icon','Icon to display on the left side of the input field, on the same line.','ICON',TRUE,TRUE),
- ('password_icon','Icon to display on the left side of the input field, on the same line.','ICON',TRUE,TRUE),
- ('image','The URL of an centered image displayed before the title.','URL',TRUE,TRUE),
- ('forgot_password_text','A text for the link allowing the user to reset their password. If the text is empty, the link is not displayed.','TEXT',TRUE,TRUE),
- ('forgot_password_link','The link to the page allowing the user to reset their password.','TEXT',TRUE,TRUE),
- ('remember_me_text','A text for the option allowing the user to request the preservation of their identity. If the text is empty, the option is not displayed.','TEXT',TRUE,TRUE),
- ('footer','A text placed at the bottom of the authentication form. If both footer and footer_md are specified, footer takes precedence.','TEXT',TRUE,TRUE),
- ('footer_md','A markdown text placed at the bottom of the authentication form. Useful for creating links to other pages (creating a new account, contacting technical support, etc.).','TEXT',TRUE,TRUE),
- ('validate','The text to display in the button at the bottom of the form that submits the values.','TEXT',TRUE,TRUE),
- ('validate_color','The color of the button at the bottom of the form that submits the values. Omit this property to use the default color.','COLOR',TRUE,TRUE),
- ('validate_shape','The shape of the validation button.','TEXT',TRUE,TRUE),
- ('validate_outline','A color to outline the validation button.','COLOR',TRUE,TRUE),
- ('validate_size','The size of the validation button.','TEXT',TRUE,TRUE)
-) x;
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties)
-VALUES (
- 'login',
- 'Using the main options of the login component
-
-When the user clicks the "Sign in" button, the form is submitted to the `/examples/show_variables.sql` page.
-There, you will have access to the variables:
- - `:username`: the username entered by the user
- - `:password`: the password entered by the user
- - `:remember`: the string "on" if the checkbox was checked, or NULL if it was not checked
-',
- JSON(
- '[
- {
- "component": "login",
- "action": "/examples/show_variables",
- "image": "../assets/icon.webp",
- "title": "Please login to your account",
- "username": "Username",
- "password": "Password",
- "autofocus": false,
- "username_icon": "user",
- "password_icon": "lock",
- "forgot_password_text": "Forgot your password?",
- "forgot_password_link": "reset_password.sql",
- "remember_me_text": "Remember me",
- "footer_md": "Don''t have an account? [Register here](register.sql)",
- "validate": "Sign in"
- }
- ]'
- )
- ),
- ('login', 'Basic login form', JSON('[{"component": "login", "username": "Username", "password": "Password", "autofocus": false}]'));
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES
- ('login', 'image_alt', 'Alternative text for an informative login image. Leave empty if decorative.', 'TEXT', TRUE, TRUE);
diff --git a/examples/official-site/sqlpage/migrations/70_pagination.sql b/examples/official-site/sqlpage/migrations/70_pagination.sql
deleted file mode 100644
index 5bb50d01a..000000000
--- a/examples/official-site/sqlpage/migrations/70_pagination.sql
+++ /dev/null
@@ -1,252 +0,0 @@
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('pagination', 'sailboat-2', '
-Navigation links to go to the first, previous, next, or last page of a dataset.
-Useful when data is divided into pages, each containing a fixed number of rows.
-
-This component only handles the display of pagination.
-**Your sql queries are responsible for filtering data** based on the page number passed as a URL parameter.
-
-This component is typically used in conjunction with a [table](?component=table),
-[list](?component=list), or [card](?component=card) component.
-
-The pagination component displays navigation buttons (first, previous, next, last) customizable with text or icons.
-
-For large numbers of pages, an offset can limit the visible page links.
-
-A minimal example of a SQL query that uses the pagination would be:
-```sql
-select ''table'' as component;
-select * from my_table limit 100 offset $offset;
-
-select ''pagination'' as component;
-with recursive pages as (
- select 0 as offset
- union all
- select offset + 100 from pages
- where offset + 100 < (select count(*) from my_table)
-)
-select
- (offset/100+1) as contents,
- sqlpage.link(sqlpage.path(), json_object(''offset'', offset)) as link,
- offset = coalesce(cast($offset as integer), 0) as active
-from pages;
-```
-
-For more advanced usage, the [pagination guide](blog.sql?post=How+to+use+the+pagination+component) provides a complete tutorial.
-', '0.40.0');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'pagination', * FROM (VALUES
- -- Top-level parameters
- ('first_link','A target URL to which the user should be directed to get to the first page. If none, the link is not displayed.','URL',TRUE,TRUE),
- ('previous_link','A target URL to which the user should be directed to get to the previous page. If none, the link is not displayed.','URL',TRUE,TRUE),
- ('next_link','A target URL to which the user should be directed to get to the next page. If none, the link is not displayed.','URL',TRUE,TRUE),
- ('last_link','A target URL to which the user should be directed to get to the last page. If none, the link is not displayed.','URL',TRUE,TRUE),
- ('first_title','The text displayed on the button to go to the first page.','TEXT',TRUE,TRUE),
- ('previous_title','The text displayed on the button to go to the previous page.','TEXT',TRUE,TRUE),
- ('next_title','The text displayed on the button to go to the next page.','TEXT',TRUE,TRUE),
- ('last_title','The text displayed on the button to go to the last page.','TEXT',TRUE,TRUE),
- ('first_disabled','disables the button to go to the first page.','BOOLEAN',TRUE,TRUE),
- ('previous_disabled','disables the button to go to the previous page.','BOOLEAN',TRUE,TRUE),
- ('next_disabled','Disables the button to go to the next page.','BOOLEAN',TRUE,TRUE),
- ('last_disabled','disables the button to go to the last page.','BOOLEAN',TRUE,TRUE),
- ('outline','Whether to use outline version of the pagination.','BOOLEAN',TRUE,TRUE),
- ('circle','Whether to use circle version of the pagination.','BOOLEAN',TRUE,TRUE),
- -- Item-level parameters (for each page)
- ('contents','Page number.','INTEGER',FALSE,FALSE),
- ('link','A target URL to which the user should be redirected to view the requested page of data.','URL',FALSE,TRUE),
- ('offset','Whether to use offset to show only a few pages at a time. Usefull if the count of pages is too large. Defaults to false','BOOLEAN',FALSE,TRUE),
- ('active','Whether the link is active or not. Defaults to false.','BOOLEAN',FALSE,TRUE)
-) x;
-
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties)
-VALUES (
- 'pagination',
- 'This is an extremely simple example of a pagination component that displays only the page numbers, with the first page being the current page.',
- JSON(
- '[
- {
- "component": "pagination"
- },
- {
- "contents": 1,
- "link": "?component=pagination&page=1",
- "active": true
- },
- {
- "contents": 2,
- "link": "?component=pagination&page=2"
- },
- {
- "contents": 3,
- "link": "?component=pagination&page=3"
- }
- ]'
- )
- ),
- (
- 'pagination',
- 'The ouline style adds a rectangular border to each navigation link.',
- JSON(
- '[
- {
- "component": "pagination",
- "outline": true
- },
- {
- "contents": 1,
- "link": "?component=pagination&page=1",
- "active": true
- },
- {
- "contents": 2,
- "link": "?component=pagination&page=2"
- },
- {
- "contents": 3,
- "link": "?component=pagination&page=3"
- }
- ]'
- )
- ),
- (
- 'pagination',
- 'The circle style adds a circular border to each navigation link.',
- JSON(
- '[
- {
- "component": "pagination",
- "circle": true
- },
- {
- "contents": 1,
- "link": "?component=pagination&page=1",
- "active": true
- },
- {
- "contents": 2,
- "link": "?component=pagination&page=2"
- },
- {
- "contents": 3,
- "link": "?component=pagination&page=3"
- }
- ]'
- )
- ),
- (
- 'pagination',
- 'The following example implements navigation links that can be enabled or disabled as needed. Since a navigation link does not appear if no link is assigned to it, you must always assign a link to display it as disabled.',
- JSON(
- '[
- {
- "component": "pagination",
- "first_link": "?component=pagination",
- "first_disabled": true,
- "previous_link": "?component=pagination",
- "previous_disabled": true,
- "next_link": "#?page=2",
- "last_link": "#?page=3"
-
- },
- {
- "contents": 1,
- "link": "?component=pagination&page=1",
- "active": true
- },
- {
- "contents": 2,
- "link": "?component=pagination&page=2"
- },
- {
- "contents": 3,
- "link": "?component=pagination&page=3"
- }
- ]'
- )
- ),
- (
- 'pagination',
- 'Instead of using icons, you can apply text to the navigation links.',
- JSON(
- '[
- {
- "component": "pagination",
- "first_title": "First",
- "last_title": "Last",
- "previous_title": "Previous",
- "next_title": "Next",
- "first_link": "?component=pagination",
- "first_disabled": true,
- "previous_link": "?component=pagination",
- "previous_disabled": true,
- "next_link": "#?page=2",
- "last_link": "#?page=3"
-
- },
- {
- "contents": 1,
- "link": "?component=pagination&page=1",
- "active": true
- },
- {
- "contents": 2,
- "link": "?component=pagination&page=2"
- },
- {
- "contents": 3,
- "link": "?component=pagination&page=3"
- }
- ]'
- )
- ),
- (
- 'pagination',
- 'If you have a large number of pages to display, you can use an offset to represent a group of pages.',
- JSON(
- '[
- {
- "component": "pagination",
- "first_link": "#?page=1",
- "previous_link": "#?page=3",
- "next_link": "#?page=4",
- "last_link": "#?page=99"
-
- },
- {
- "contents": 1,
- "link": "?component=pagination&page=1"
- },
- {
- "contents": 2,
- "link": "?component=pagination&page=2"
- },
- {
- "contents": 3,
- "link": "?component=pagination&page=3"
- },
- {
- "contents": 4,
- "link": "?component=pagination&page=4",
- "active": true
- },
- {
- "contents": 5,
- "link": "?component=pagination&page=5"
- },
- {
- "contents": 6,
- "link": "?component=pagination&page=6"
- },
- {
- "offset": true
- },
- {
- "contents": 99,
- "link": "?component=pagination&page=99"
- },
- ]'
- )
- );
-
\ 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/76_toast.sql b/examples/official-site/sqlpage/migrations/76_toast.sql
deleted file mode 100644
index 4afc43fbd..000000000
--- a/examples/official-site/sqlpage/migrations/76_toast.sql
+++ /dev/null
@@ -1,48 +0,0 @@
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('toast', 'notification', '
-Displays a brief notification above the page. Each top-level `toast` row creates one notification, and consecutive toasts at the same position are queued in a shared stack.
-
-Ordinary notifications use `role="status"` and `aria-live="polite"`. Colored variants retain a readable contrasting foreground. Automatic dismissal and the manual close control are configured independently.', '0.46.0');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'toast', * FROM (VALUES
- ('title', 'Optional notification heading.', 'TEXT', TRUE, TRUE),
- ('description', 'Escaped plain-text body. This is used only when `description_md` is not supplied.', 'TEXT', TRUE, TRUE),
- ('description_md', 'Rich-text alternative to `description`, rendered as Markdown. When both properties are supplied, `description_md` takes precedence.', 'TEXT', TRUE, TRUE),
- ('icon', 'Optional [Tabler icon](https://tabler.io/icons) name.', 'ICON', TRUE, TRUE),
- ('color', 'Optional Tabler color. The default is the neutral toast appearance; colored variants use the matching contrasting foreground utility.', 'COLOR', TRUE, TRUE),
- ('dismissible', 'Whether to render an accessible manual close button. Defaults to true and is independent of automatic dismissal.', 'BOOLEAN', TRUE, TRUE),
- ('duration', 'Automatic dismissal delay in milliseconds. Defaults to 5000. Set to 0 to keep the toast visible until manually dismissed (when `dismissible` is true) or the page is left.', 'INTEGER', TRUE, TRUE),
- ('position', 'Screen placement: `top-start`, `top-center`, `top-end`, `bottom-start`, `bottom-center`, or `bottom-end`. Defaults to `top-end`; invalid values safely fall back to that default.', 'TEXT', TRUE, TRUE),
- ('trigger', 'Optional URL fragment that opens the toast without reloading the page, with or without the leading `#`. When set, the toast does not open on page load and can be opened repeatedly by a link or button whose target is that fragment. Multiple toasts can share a trigger to open as a stack.', 'TEXT', TRUE, TRUE)
- -- id and class come from 99_shared_id_class_attributes.sql
-) x;
-
-INSERT INTO example(component, description, properties) VALUES
- ('toast', 'A toast that opens when the page loads and disappears automatically after the default 5000 milliseconds.', json('[
- {"component":"toast","id":"toast-auto","title":"This is a SQLPage toast","description":"This toast will open automatically when the page loads.","icon":"check","color":"green"}
- ]')),
- ('toast', 'A persistent error notification that disables automatic dismissal and requires the user to activate its close button.', json('[
- {"component":"toast","id":"toast-dismissible","trigger":"persistent-error","title":"Could not save","description":"Review the highlighted fields and try again.","icon":"alert-triangle","color":"black","duration":0,"dismissible":true},
- {"component":"toast","id":"toast-nondismissible","trigger":"persistent-status","title":"Connection unavailable","description":"This persistent notification has no manual close control.","duration":0,"dismissible":false},
- {"component":"button"},
- {"title":"Show dismissible error","link":"#persistent-error","color":"red"},
- {"title":"Show non-dismissible status","link":"#persistent-status"}
- ]')),
- ('toast', 'A persistent rich Markdown notification. Markdown takes precedence over plain text and renders emphasis and a link as HTML, while plain-text content remains escaped.', json('[
- {"component":"toast","id":"toast-markdown","trigger":"rich-notifications","title":"Release available","description":"This fallback stays escaped ","description_md":"Version **2.0** is ready. [Read the notes](https://example.com/releases).","color":"blue","duration":0},
- {"component":"toast","id":"toast-plain","trigger":"rich-notifications","description":"Plain text stays escaped ","color":"white","duration":0},
- {"component":"button"},
- {"title":"Show rich notifications","link":"#rich-notifications"}
- ]')),
- ('toast', 'Several persistent queued notifications. Toasts with the same position share a container and stack instead of overlapping.', json('[
- {"component":"toast","id":"toast-stack-one","trigger":"queued notifications","title":"Import started","description":"Preparing records.","duration":0},
- {"component":"toast","id":"toast-stack-two","trigger":"queued notifications","title":"Import running","description":"Processing records.","duration":0},
- {"component":"toast","id":"toast-short","trigger":"queued notifications","title":"Temporary update","description":"This message closes shortly.","duration":2000},
- {"component":"button"},
- {"title":"Show queued notifications","link":"#queued notifications"}
- ]')),
- ('toast', 'A notification placed at the bottom center of the screen instead of the default top end.', json('[
- {"component":"toast","id":"toast-bottom-center","trigger":"bottom-notification","title":"Download ready","description":"Your export is ready.","position":"bottom-center","duration":0},
- {"component":"button"},
- {"title":"Show bottom notification","link":"#bottom-notification"}
- ]'));
diff --git a/examples/official-site/sqlpage/migrations/77_facet.sql b/examples/official-site/sqlpage/migrations/77_facet.sql
deleted file mode 100644
index c721d2ff4..000000000
--- a/examples/official-site/sqlpage/migrations/77_facet.sql
+++ /dev/null
@@ -1,130 +0,0 @@
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('facet', 'filter', '
-Navigation links for filtering a dataset by a category, status, owner, or other attribute.
-
-This component only renders the filter navigation. **Your SQL query is responsible for filtering the data** based on the URL parameter selected by the user.
-
-Use it alongside a [table](?component=table), [list](?component=list), or [card](?component=card). The links use GET parameters, so the selected filter can be bookmarked and shared.
-
-Set `compact` to display the facets in a dropdown, which is useful for a moderate number of choices or on narrow screens. Use `selected_facet` to show the active facet in the closed dropdown. `all_link` and `all_title` add a link that clears the filter.
-
-The following portable pattern filters a table by category. `sqlpage.link` preserves the current page path while safely generating the URL.
-
-```sql
-select ''table'' as component;
-select title, category
-from my_table
-where $category is null or category = $category;
-
-select ''facet'' as component,
- ''Category'' as description,
- sqlpage.link(sqlpage.path(), json_object(''category'', null)) as all_link,
- $category is null as all_active;
-select category as title,
- sqlpage.link(sqlpage.path(), json_object(''category'', category)) as link,
- category = $category as active
-from my_table
-group by category
-order by category;
-```
-', '0.46.0');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'facet', * FROM (VALUES
- -- Top-level parameters
- ('description','The facet category label.','TEXT',TRUE,TRUE),
- ('dropdown_title','Text shown on the compact-mode dropdown button when no facet is selected. Defaults to `Choose facet`.','TEXT',TRUE,TRUE),
- ('selected_facet','An alias for `dropdown_title`.','TEXT',TRUE,TRUE),
- ('compact','Displays the facets in a dropdown instead of links.','BOOLEAN',TRUE,TRUE),
- ('center','Whether to center the facet selector','BOOLEAN',TRUE,TRUE),
- ('all_link','URL that clears the filter. If omitted, no All link is displayed.','URL',TRUE,TRUE),
- ('all_title','Text for the link that clears the filter. Defaults to "ALL".','TEXT',TRUE,TRUE),
- ('all_active','Whether the link that clears the filter is active. Defaults to false.','BOOLEAN',TRUE,TRUE),
- -- Item-level parameters (for each facet)
- ('title','Facet title.','TEXT',FALSE,FALSE),
- ('link','URL for the facet.','URL',FALSE,FALSE),
- ('active','Whether the link is active or not. Defaults to false.','BOOLEAN',FALSE,TRUE)
-) x;
-
--- Insert example(s) for the component
-INSERT INTO example(component, description, properties)
-VALUES (
- 'facet',
- 'A category selector with an All link. In an application, the SQL pattern above uses the chosen URL parameter to filter the displayed data.',
- JSON(
- '[
- {
- "component": "table"
- },
- {
- "name": "USS Enterprise (NCC-1701)",
- "class": "Constitution"
- },
- {
- "name": "USS Exeter (NCC-1672)",
- "class": "Galaxy"
- },
- {
- "name": "USS Exeter (NCC-1672)",
- "class": "Constitution"
- },
- {
- "component": "facet",
- "description": "Classes",
- "all_link": "?component=facet",
- "all_title": "All",
- "all_active": false
- },
- {
- "title": "Constitution",
- "link": "?component=facet&class=Constitution",
- "active": true
- },
- {
- "title": "Galaxy",
- "link": "?component=facet&class=Galaxy"
- }
- ]'
- )
- ),
- (
- 'facet',
- 'Compact mode displays the facet choices in a dropdown.',
- JSON(
- '[
- {
- "component": "table"
- },
- {
- "name": "USS Enterprise (NCC-1701)",
- "class": "Constitution"
- },
- {
- "name": "USS Defiant (NCC-1764)",
- "class": "Constitution"
- },
- {
- "name": "USS Exeter (NCC-1672)",
- "class": "Constitution"
- },
- {
- "component": "facet",
- "description": "Classes",
- "all_link": "?component=facet",
- "all_title": "All",
- "all_active": false,
- "compact": true,
- "dropdown_title": "Select a spaceship class",
- "selected_facet": "Constitution"
- },
- {
- "title": "Constitution",
- "link": "?component=facet&class=Constitution",
- "active": true
- },
- {
- "title": "Galaxy",
- "link": "?component=facet&class=Galaxy"
- }
- ]'
- )
- );
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/80_status_bar.sql b/examples/official-site/sqlpage/migrations/80_status_bar.sql
deleted file mode 100644
index 9a4ce68d6..000000000
--- a/examples/official-site/sqlpage/migrations/80_status_bar.sql
+++ /dev/null
@@ -1,23 +0,0 @@
-INSERT INTO component(name, icon, description, introduced_in_version) VALUES
- ('status_bar', 'layout-bottombar',
- 'Display short status messages and links in a single horizontal bar. Each row adds one segment. When there are several segments, the last one aligns to the far edge. If the segments do not all fit, scroll the bar horizontally to see the rest.',
- '0.49.0');
-
-INSERT INTO parameter(component, name, description, type, top_level, optional)
-SELECT 'status_bar', * FROM (VALUES
- ('fixed', 'Keep the bar at the bottom of the screen while the page scrolls. Defaults to true. A fixed bar overlays page content, so leave space below your last item if needed. Set to false to place the bar in the page where the SQL appears.', 'BOOLEAN', TRUE, TRUE),
- ('label', 'Accessible name for the bar. Defaults to "Status bar".', 'TEXT', TRUE, TRUE),
- ('title', 'Text displayed in the segment.', 'TEXT', FALSE, TRUE),
- ('icon', 'Icon displayed before the text.', 'ICON', FALSE, TRUE),
- ('color', 'Color of the segment text and icon.', 'COLOR', FALSE, TRUE),
- ('tooltip', 'Text shown when hovering over the segment or focusing its link. For an icon without a title, supply a tooltip to give the segment an accessible name.', 'TEXT', FALSE, TRUE),
- ('link', 'URL to open when the segment is clicked.', 'URL', FALSE, TRUE)
-) p;
-
-INSERT INTO example(component, description, properties) VALUES
- ('status_bar', 'A query workspace shows the database connection, row count, and a link to the function reference. Omit `fixed` to pin this bar to the bottom of the screen.', json('[
- {"component":"status_bar","label":"Query status","fixed":false},
- {"title":"Connected","icon":"database","color":"green","tooltip":"Connected to the reporting database"},
- {"title":"24 rows"},
- {"title":"SQL functions","icon":"book","link":"/functions.sql"}
- ]'));
diff --git a/examples/official-site/sqlpage/migrations/81_guide_directory.sql b/examples/official-site/sqlpage/migrations/81_guide_directory.sql
deleted file mode 100644
index 0a8687df1..000000000
--- a/examples/official-site/sqlpage/migrations/81_guide_directory.sql
+++ /dev/null
@@ -1,15 +0,0 @@
-CREATE TABLE guide (
- sort_order INTEGER PRIMARY KEY,
- title TEXT NOT NULL,
- link TEXT NOT NULL UNIQUE,
- description TEXT NOT NULL
-);
-
-INSERT INTO guide (sort_order, title, link, description) VALUES
- (1, 'Your first website', '/your-first-sql-website/', 'Install SQLPage and build a website from a SQL file.'),
- (2, 'SQL and variables', '/extensions-to-sql.sql', 'Read request parameters, set variables, and call SQLPage functions.'),
- (3, 'Custom components', '/custom_components.sql', 'Render your own HTML with Handlebars templates.'),
- (4, 'Database migrations', '/your-first-sql-website/migrations.sql', 'Create and update your database schema with versioned SQL files.'),
- (5, 'Custom URLs', '/your-first-sql-website/custom_urls.sql', 'Give your pages readable URLs and route requests to SQL files.'),
- (6, 'Reverse proxy', '/your-first-sql-website/nginx.sql', 'Serve your site with Nginx and HTTPS.'),
- (7, 'Managed hosting', '/your-first-sql-website/hosted.sql', 'Try SQLPage online or publish your website with DataPage.');
diff --git a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql b/examples/official-site/sqlpage/migrations/82_reference_catalog.sql
deleted file mode 100644
index 3f5be829d..000000000
--- a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql
+++ /dev/null
@@ -1,184 +0,0 @@
--- Short catalog descriptions help readers choose a page before opening its full reference.
-CREATE TABLE reference_category (
- id TEXT PRIMARY KEY,
- title TEXT NOT NULL,
- sort_order INTEGER NOT NULL
-);
-
-INSERT INTO reference_category (id, title, sort_order) VALUES
- ('display-data', 'Display data', 1),
- ('forms-and-feedback', 'Forms and feedback', 2),
- ('navigation', 'Navigation', 3),
- ('page-layout', 'Page layout and content', 4),
- ('http-responses', 'HTTP responses', 5),
- ('server-logic', 'Server logic', 6),
- ('request-data', 'Request data', 1),
- ('links-and-routing', 'Links and routing', 2),
- ('files-and-uploads', 'Files and uploads', 3),
- ('identity-and-security', 'Identity and security', 4),
- ('external-services', 'External services', 5),
- ('server-and-runtime', 'Server and runtime', 6);
-
-ALTER TABLE component ADD COLUMN catalog_category TEXT REFERENCES reference_category(id);
-ALTER TABLE component ADD COLUMN catalog_summary TEXT;
-ALTER TABLE sqlpage_functions ADD COLUMN catalog_category TEXT REFERENCES reference_category(id);
-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')
-);
-
-WITH copy(name, category, summary) AS (VALUES
- ('big_number', 'display-data', 'Highlight a metric with a trend or progress indicator.'),
- ('card', 'display-data', 'Arrange records in cards with images, links, or embedded content.'),
- ('carousel', 'display-data', 'Show a slideshow of images with optional captions and controls.'),
- ('chart', 'display-data', 'Plot query results as line, area, bar, or pie charts.'),
- ('datagrid', 'display-data', 'Lay out labeled values in a compact grid.'),
- ('list', 'display-data', 'Present rows as a vertical list with optional links and icons.'),
- ('map', 'display-data', 'Plot locations and geographic shapes on an interactive map.'),
- ('table', 'display-data', 'Turn query results into a sortable, searchable table.'),
- ('timeline', 'display-data', 'Arrange events along a vertical timeline.'),
- ('tracking', 'display-data', 'Show a sequence of activity or status changes as colored segments.'),
-
- ('alert', 'forms-and-feedback', 'Draw attention to a message with a color and an icon.'),
- ('button', 'forms-and-feedback', 'Follow a link, download a file, or submit a form.'),
- ('empty_state', 'forms-and-feedback', 'Explain an empty view and offer the reader a next step.'),
- ('form', 'forms-and-feedback', 'Collect input with text fields, file uploads, and other controls.'),
- ('login', 'forms-and-feedback', 'Display a sign-in form for a username and password.'),
- ('modal', 'forms-and-feedback', 'Open a dialog over the page for details, forms, or media.'),
- ('toast', 'forms-and-feedback', 'Show a brief notification above the page.'),
-
- ('breadcrumb', 'navigation', 'Link the current page to its parent pages.'),
- ('facet', 'navigation', 'Let readers choose filters for a dataset.'),
- ('pagination', 'navigation', 'Link to other pages of a query result.'),
- ('status_bar', 'navigation', 'Show status messages and links in a horizontal bar.'),
- ('steps', 'navigation', 'Mark progress through the stages of a task.'),
- ('tab', 'navigation', 'Switch between related pages using labeled tabs.'),
-
- ('code', 'page-layout', 'Display source code with syntax highlighting.'),
- ('columns', 'page-layout', 'Compare plans, features, or options in side-by-side cards.'),
- ('divider', 'page-layout', 'Separate sections with a horizontal rule.'),
- ('foldable', 'page-layout', 'Let readers expand individual sections to see their contents.'),
- ('hero', 'page-layout', 'Introduce a page with a headline, media, and a call to action.'),
- ('html', 'page-layout', 'Insert your own HTML markup into the page.'),
- ('shell', 'page-layout', 'Set the page layout, navigation, branding, and footer.'),
- ('text', 'page-layout', 'Write paragraphs using plain text or Markdown.'),
- ('title', 'page-layout', 'Add a heading and choose its level.'),
-
- ('cookie', 'http-responses', 'Set a cookie in the visitor''s browser.'),
- ('csv', 'http-responses', 'Export query rows as a downloadable CSV file.'),
- ('download', 'http-responses', 'Send a file directly to the visitor.'),
- ('http_header', 'http-responses', 'Set response headers for caching, content types, and more.'),
- ('json', 'http-responses', 'Return query results as JSON for an API.'),
- ('redirect', 'http-responses', 'Send the visitor to another URL.'),
- ('rss', 'http-responses', 'Publish an RSS feed from query results.'),
- ('status_code', 'http-responses', 'Set the HTTP status code returned by a page.'),
-
- ('authentication', 'server-logic', 'Restrict access by checking a password against a stored hash.'),
- ('debug', 'server-logic', 'Inspect the values passed to a component as JSON.'),
- ('dynamic', 'server-logic', 'Render SQLPage components described by JSON data.'),
- ('log', 'server-logic', 'Write a message to the SQLPage server log.')
-)
-UPDATE component SET (catalog_category, catalog_summary) = (copy.category, copy.summary)
-FROM copy WHERE component.name = copy.name;
-
-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 (
- SELECT 'component' AS kind, name, icon, catalog_category, catalog_summary,
- description AS description_md, introduced_in_version, NULL AS return_type,
- '/component.sql?component=' || name AS link,
- (SELECT count(*) FROM example WHERE example.component = component.name) AS example_count,
- NULL AS arguments
- FROM component
- UNION ALL
- SELECT 'function', name, icon, catalog_category, catalog_summary,
- description_md, introduced_in_version, return_type, '/functions.sql?function=' || name, NULL,
- coalesce((SELECT group_concat(CASE WHEN optional THEN '[' || name || ']' ELSE name END, ', ' ORDER BY "index")
- FROM sqlpage_function_parameters WHERE "function" = f.name), '')
- FROM sqlpage_functions AS f
-)
-SELECT kind, name, icon, link, description_md, introduced_in_version, return_type, example_count, arguments,
- coalesce(category.id, 'other') AS category_id,
- coalesce(category.title, 'Other') AS category_title,
- coalesce(category.sort_order, 99) AS category_order,
- coalesce(catalog_summary, substr(trim(description_md, char(10) || ' #'), 1,
- instr(trim(description_md, char(10) || ' #') || char(10), char(10)) - 1)) AS summary
-FROM entries
-LEFT JOIN reference_category AS category ON category.id = entries.catalog_category;
-
--- The section is part of the anchor: a component can accept the same name at both levels.
-CREATE VIEW reference_parameter AS
-WITH fields AS (
- SELECT 'component' AS kind, component AS entry,
- CASE WHEN top_level THEN 'top-level-parameters' ELSE 'row-level-parameters' END AS section,
- name, type, optional, coalesce(description_md, description) AS description_md, optional AS position
- FROM parameter
- UNION ALL
- SELECT 'function', "function", 'parameters', name, type, optional, description_md, "index"
- FROM sqlpage_function_parameters
-), sections(section, title, introduction, section_order) AS (VALUES
- ('top-level-parameters', 'Top-level parameters', 'Set these in the SELECT that names the component.', 1),
- ('row-level-parameters', 'Row-level parameters', 'Return these columns in the rows that follow the component.', 2),
- ('parameters', 'Parameters', NULL, 1)
-)
-SELECT fields.*, title, introduction, section_order, section || '-' || name AS anchor
-FROM fields JOIN sections USING (section);
diff --git a/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql b/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql
deleted file mode 100644
index 712cb683f..000000000
--- a/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql
+++ /dev/null
@@ -1,87 +0,0 @@
--- Every component whose `id` and `class` properties behave in the ordinary way
--- is documented from the lists below, so that the wording stays identical
--- across components and so that the (component, top_level, name) primary key
--- of `parameter` is not violated.
---
--- A handful of components deliberately document `id` or `class` in their own
--- migration instead, because the generic wording would be wrong for them:
--- `modal` (`id` is required, and is what a button targets), `form` (`id` is
--- what an outside submit button references), `foldable` (top level and item
--- level mean different things) and `button` (`id` lands on each button, not on
--- the container). Do not duplicate those here.
-
-INSERT INTO parameter(component, top_level, name, description, type, optional)
-SELECT *, 'id', 'id attribute added to the container in HTML. It can be used to target this item through css or for scrolling to this item through links (use "#id" in link url).', 'TEXT', TRUE
-FROM (VALUES
- ('alert', TRUE),
- ('big_number', TRUE),
- ('big_number', FALSE),
- ('breadcrumb', TRUE),
- ('card', FALSE),
- ('chart', TRUE),
- ('code', TRUE),
- ('csv', TRUE),
- ('datagrid', TRUE),
- ('datagrid', FALSE),
- ('empty_state', TRUE),
- ('hero', TRUE),
- ('list', TRUE),
- ('list', FALSE),
- ('map', TRUE),
- ('status_bar', TRUE),
- ('tab', TRUE),
- ('tab', FALSE),
- ('table', TRUE),
- ('timeline', TRUE),
- ('timeline', FALSE),
- ('title', TRUE),
- ('toast', TRUE),
- ('tracking', TRUE),
- ('text', TRUE),
- ('carousel', TRUE),
- ('login', TRUE),
- ('pagination', TRUE),
- ('facet', TRUE)
-);
-
-INSERT INTO parameter(component, top_level, name, description, type, optional)
-SELECT *, 'id', 'id attribute injected as an anchor in HTML. It can be used for scrolling to this item through links (use "#id" in link url). Added in v0.18.0.', 'TEXT', TRUE
-FROM (VALUES
- ('steps', TRUE)
-);
-
-INSERT INTO parameter(component, top_level, name, description, type, optional)
-SELECT *, 'class', 'class attribute added to the container in HTML. It can be used to apply custom styling to this item through css. Added in v0.18.0.', 'TEXT', TRUE
-FROM (VALUES
- ('alert', TRUE),
- ('big_number', TRUE),
- ('big_number', FALSE),
- ('breadcrumb', TRUE),
- ('button', TRUE),
- ('card', TRUE),
- ('card', FALSE),
- ('chart', TRUE),
- ('code', TRUE),
- ('csv', TRUE),
- ('datagrid', TRUE),
- ('divider', TRUE),
- ('empty_state', TRUE),
- ('form', TRUE),
- ('list', TRUE),
- ('list', FALSE),
- ('map', TRUE),
- ('status_bar', TRUE),
- ('status_bar', FALSE),
- ('tab', TRUE),
- ('tab', FALSE),
- ('table', TRUE),
- ('timeline', TRUE),
- ('timeline', FALSE),
- ('title', TRUE),
- ('toast', TRUE),
- ('tracking', TRUE),
- ('carousel', TRUE),
- ('login', TRUE),
- ('pagination', TRUE),
- ('facet', TRUE)
-);
diff --git a/examples/official-site/sqlpage/templates/docs-parameters.handlebars b/examples/official-site/sqlpage/templates/docs-parameters.handlebars
index 4642c7f1f..bf5c9f0c2 100644
--- a/examples/official-site/sqlpage/templates/docs-parameters.handlebars
+++ b/examples/official-site/sqlpage/templates/docs-parameters.handlebars
@@ -14,7 +14,7 @@
{{#if required}}Required {{/if}}
- {{{markdown description_md}}}
+ {{{markdown description_md}}}{{#if default_md}}Default
{{{markdown default_md}}}{{/if}}
{{/each}}
diff --git a/examples/official-site/sqlpage/templates/shell-docs.handlebars b/examples/official-site/sqlpage/templates/shell-docs.handlebars
index a4687a922..d5c51f4d6 100644
--- a/examples/official-site/sqlpage/templates/shell-docs.handlebars
+++ b/examples/official-site/sqlpage/templates/shell-docs.handlebars
@@ -104,7 +104,7 @@
Blog
Performance
Security
- Configuration
+ Configuration
Community
{{icon_img "arrow-up" 16}} Back to top
diff --git a/examples/official-site/test.hurl b/examples/official-site/test.hurl
index 99061a770..c50a035e8 100644
--- a/examples/official-site/test.hurl
+++ b/examples/official-site/test.hurl
@@ -19,6 +19,19 @@ xpath "string(//main//a[normalize-space()='Components']/@href)" == "/components.
xpath "string(//main//a[normalize-space()='Functions']/@href)" == "/functions.sql"
body not contains "An error occurred"
+GET http://localhost:8080/configuration
+HTTP 200
+[Asserts]
+xpath "//*[@id='listen_on']//a[@href='#listen_on']" count == 1
+xpath "normalize-space(//*[@id='listen_on']/dd)" contains "443"
+xpath "//*[@id='database_connection_idle_timeout_seconds']" count == 1
+body not contains "An error occurred"
+
+GET http://localhost:8080/search.sql?search=LISTEN_ON
+HTTP 302
+[Asserts]
+header "Location" == "/configuration#listen_on"
+
GET http://localhost:8080/components.sql
HTTP 200
[Asserts]
diff --git a/examples/official-site/your-first-sql-website/nginx.md b/examples/official-site/your-first-sql-website/nginx.md
index 59235958b..1586f2cb4 100644
--- a/examples/official-site/your-first-sql-website/nginx.md
+++ b/examples/official-site/your-first-sql-website/nginx.md
@@ -78,7 +78,7 @@ but will increase the load on your SQLPage server, and reduce the amount of user
Refer to the official documentation for [proxy buffering](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering), [gzip](https://nginx.org/en/docs/http/ngx_http_gzip_module.html), and [chunked transfer](https://nginx.org/en/docs/http/ngx_http_core_module.html#chunked_transfer_encoding) when tuning these values.
-When SQLPage sits behind a reverse proxy, set `compress_responses` to `false` [in `sqlpage.json`](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) so that NGINX compresses once at the edge.
+When SQLPage sits behind a reverse proxy, set `compress_responses` to `false` [in `sqlpage.json`](/configuration#compress_responses) so that NGINX compresses once at the edge.
### URL Rewriting
diff --git a/examples/official-site/your-first-sql-website/tutorial.md b/examples/official-site/your-first-sql-website/tutorial.md
index 7ef99a11e..497ca7ea7 100644
--- a/examples/official-site/your-first-sql-website/tutorial.md
+++ b/examples/official-site/your-first-sql-website/tutorial.md
@@ -87,7 +87,7 @@ Later, when you want to deploy your website online, you can switch back to a per
> For instance, a SQL Server database named `db` running on `localhost` port `1433` with the username `funny:user` and the password `p@ssw0rd` would be represented as
> `mssql://funny%3Auser:p%40ssw0rd@localhost:1433/db`.
-For more information about the properties that can be set in sqlpage.json, see [SQLPage's configuration documentation](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage)
+For more information about the properties that can be set in sqlpage.json, see [SQLPage's configuration reference](/configuration).

@@ -180,7 +180,7 @@ If you prefer to host your website yourself, you can use a cloud provider or a V
- [Setup docker](https://github.com/sqlpage/SQLPage?tab=readme-ov-file#with-docker) or another process manager such as [systemd](https://github.com/sqlpage/SQLPage/blob/main/sqlpage.service) to start SQLPage automatically when your server boots and to keep it running
- Optionally, [setup a reverse proxy](nginx.sql) to avoid exposing SQLPage directly to the internet
- Optionally, setup a TLS certificate to enable HTTPS
-- Configure connection to a cloud database or a database running on your server in [`sqlpage.json`](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage)
+- Configure connection to a cloud database or a database running on your server in [`database_url`](/configuration#database_url)
## Go further
diff --git a/package.json b/package.json
index 62cae9e5d..e01545759 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,8 @@
"typecheck": "tsc && tsc -p tests/js && tsc -p tests/end-to-end",
"format": "biome format --write .",
"fix": "biome check --fix --unsafe .",
- "site:build": "node scripts/site-build.mjs",
+ "site:build": "cargo run --locked --features site-build --example build_site",
+ "site:test": "node --test tests/js/component_documentation.checks.ts",
"site": "npm run build && npm run site:build && cd target/official-site && cargo run --locked --manifest-path ../../Cargo.toml"
},
"repository": {
diff --git a/scripts/site-build.mjs b/scripts/site-build.mjs
deleted file mode 100644
index 96a3d5c90..000000000
--- a/scripts/site-build.mjs
+++ /dev/null
@@ -1,59 +0,0 @@
-import {
- copyFileSync,
- cpSync,
- existsSync,
- mkdirSync,
- mkdtempSync,
- renameSync,
- rmSync,
-} from "node:fs";
-import { dirname, join, relative, resolve } from "node:path";
-
-const repository = resolve(import.meta.dirname, "..");
-const siteDirectory = join(repository, "target", "official-site");
-const source = join(repository, "examples", "official-site");
-
-const excluded = new Set([
- "README.md",
- "docker-compose.yml",
- "test.hurl",
- join("sqlpage", "sqlpage.db"),
- join("sqlpage", "https"),
-]);
-
-function buildSite() {
- const parent = dirname(siteDirectory);
- mkdirSync(parent, { recursive: true });
- const temporary = mkdtempSync(join(parent, ".official-site-"));
- const next = join(temporary, "next");
- const previous = join(temporary, "previous");
- try {
- cpSync(source, next, {
- recursive: true,
- filter: (file) => !excluded.has(relative(source, file)),
- });
- copyFileSync(
- join(repository, "configuration.md"),
- join(next, "configuration.md"),
- );
- // Stage the complete site before exchanging the previous preview.
- try {
- renameSync(siteDirectory, previous);
- } catch (error) {
- if (error.code !== "ENOENT") throw error;
- }
- try {
- renameSync(next, siteDirectory);
- } catch (error) {
- if (!existsSync(siteDirectory) && existsSync(previous)) {
- renameSync(previous, siteDirectory);
- }
- throw error;
- }
- console.log(`Prepared ${siteDirectory}`);
- } finally {
- rmSync(temporary, { force: true, recursive: true });
- }
-}
-
-buildSite();
diff --git a/src/app_config.rs b/src/app_config.rs
index 6e9166457..e899139f2 100644
--- a/src/app_config.rs
+++ b/src/app_config.rs
@@ -14,9 +14,16 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
-#[cfg(not(feature = "lambda-web"))]
+#[cfg(any(not(feature = "lambda-web"), feature = "config-schema"))]
const DEFAULT_DATABASE_FILE: &str = "sqlpage.db";
+const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_mins(30);
+const DEFAULT_MAX_LIFETIME: Duration = Duration::from_hours(1);
+const CERTIFICATE_CACHE_DIRECTORY: &str = "sqlpage/https";
+
+#[cfg(feature = "config-schema")]
+mod schema;
+
impl AppConfig {
pub fn from_cli(cli: &Cli) -> anyhow::Result {
let mut config = if let Some(config_file) = &cli.config_file {
@@ -92,19 +99,11 @@ impl AppConfig {
let is_sqlite = self.database_url.starts_with("sqlite:");
self.database_connection_idle_timeout = resolve_timeout(
self.database_connection_idle_timeout,
- if is_sqlite {
- None
- } else {
- Some(Duration::from_mins(30))
- },
+ (!is_sqlite).then_some(DEFAULT_IDLE_TIMEOUT),
);
self.database_connection_max_lifetime = resolve_timeout(
self.database_connection_max_lifetime,
- if is_sqlite {
- None
- } else {
- Some(Duration::from_hours(1))
- },
+ (!is_sqlite).then_some(DEFAULT_MAX_LIFETIME),
);
}
@@ -207,210 +206,252 @@ pub fn load_from_env() -> anyhow::Result {
.with_context(|| format!("Unable to load configuration from {}", config_dir.display()))
}
+/// Settings accepted in a server configuration file.
#[derive(Debug, Deserialize, PartialEq, Clone)]
+#[cfg_attr(feature = "config-schema", derive(schemars::JsonSchema))]
+#[cfg_attr(feature = "config-schema", schemars(transform = schema::remove_unset_defaults))]
#[allow(clippy::struct_excessive_bools)]
pub struct AppConfig {
+ /// Database connection URL or ODBC connection string. Percent-encode special
+ /// characters in URL usernames and passwords. See [Database connection strings](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#database-connection-strings).
+ /// The server also recognizes an existing `sqlpage.db` in the working directory for compatibility.
#[serde(default = "default_database_url")]
+ #[cfg_attr(feature = "config-schema", schemars(default, extend("x-default-description" = format!(
+ "SQLite file `{DEFAULT_DATABASE_FILE}` in the configuration directory, or in-memory SQLite on Lambda or when the directory is unwritable."
+ ))))]
pub database_url: String,
- /// A separate field for the database password. If set, this will override any password specified in the `database_url`.
+
+ /// Overrides the password in `database_url`. This value does not require percent encoding.
#[serde(default)]
pub database_password: Option,
+
+ /// Maximum number of simultaneous database connections. Must be greater than zero.
+ #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = schema::pool_sizes())))]
pub max_database_pool_connections: Option,
+
+ /// Close a database connection after this many idle seconds. Set to zero to disable.
#[serde(
default,
deserialize_with = "deserialize_duration_seconds",
rename = "database_connection_idle_timeout_seconds"
)]
+ #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend(
+ "x-default-description" = schema::timeout(DEFAULT_IDLE_TIMEOUT)
+ )))]
pub database_connection_idle_timeout: Option,
+
+ /// Maximum age in seconds of a connection in the pool. Set to zero to disable.
#[serde(
default,
deserialize_with = "deserialize_duration_seconds",
rename = "database_connection_max_lifetime_seconds"
)]
+ #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend(
+ "x-default-description" = schema::timeout(DEFAULT_MAX_LIFETIME)
+ )))]
pub database_connection_max_lifetime: Option,
+ /// SQLite extensions to load, such as `mod_spatialite`. Use a space-separated list in environment variables.
#[serde(default)]
pub sqlite_extensions: Vec,
+ /// Host and port on which to listen, for example `127.0.0.1:8080` or `localhost:8080`.
#[serde(default, deserialize_with = "deserialize_socket_addr")]
+ #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend(
+ "x-default-description" = format!("`{}` with `https_domain`, otherwise `{}`.",
+ default_listen_on(true), default_listen_on(false)
+ )
+ )))]
pub listen_on: Option,
+
+ /// Overrides the port in `listen_on`. A Kubernetes service URI in this setting is ignored.
#[serde(default, deserialize_with = "deserialize_port")]
+ #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend("x-default-description" = "The port in `listen_on`.")))]
pub port: Option,
+
+ /// Unix socket path. On Unix this serves HTTP exclusively on the socket and overrides TCP listener settings.
pub unix_socket: Option,
- /// Number of times to retry connecting to the database after a failure when the server starts
- /// up. Retries will happen every 5 seconds. The default is 6 retries, which means the server
- /// will wait up to 30 seconds for the database to become available.
+ /// Number of times to retry a failed database connection at startup, with five seconds between attempts.
#[serde(default = "default_database_connection_retries")]
pub database_connection_retries: u32,
- /// Maximum number of seconds to wait before giving up when acquiring a database connection from the
- /// pool. The default is 10 seconds.
+ /// Maximum time in seconds to wait for a connection from the database pool. Must be positive.
#[serde(default = "default_database_connection_acquire_timeout_seconds")]
pub database_connection_acquire_timeout_seconds: f64,
- /// The directory where the .sql files are located. Defaults to the current directory.
+ /// Root directory for SQL pages and static files. Static serving follows symlinks.
+ /// A symlink under the web root exposes its target, including files outside the web root.
+ /// Keep links to private files and directories outside the web root. See the [security guide](https://github.com/sqlpage/SQLPage/blob/main/SECURITY.md).
#[serde(default = "default_web_root")]
+ #[cfg_attr(
+ feature = "config-schema",
+ schemars(default = "schema::working_directory")
+ )]
pub web_root: PathBuf,
- /// The directory where the sqlpage configuration file is located. Defaults to `./sqlpage`.
+ /// Directory containing the configuration file, templates, migrations, and connection management scripts.
+ /// Keep this directory private. To select it before the server looks for the configuration file,
+ /// pass `--config-dir` or set `CONFIGURATION_DIRECTORY` or `SQLPAGE_CONFIGURATION_DIRECTORY`.
#[serde(default = "configuration_directory")]
+ #[cfg_attr(
+ feature = "config-schema",
+ schemars(default = "default_configuration_directory")
+ )]
pub configuration_directory: PathBuf,
- /// Set to true to allow the `sqlpage.exec` function to be used in SQL queries.
- /// This should be enabled only if you trust the users writing SQL queries, since it gives
- /// them the ability to execute arbitrary shell commands on the server.
+ /// Allow `sqlpage.exec` to execute server-side commands. Enable only if everyone who can write SQL pages,
+ /// including through the `sqlpage_files` database table, is trusted to run arbitrary commands.
#[serde(default)]
pub allow_exec: bool,
- /// SMTP server host used by the `sqlpage.send_mail` function.
+ /// SMTP server hostname or IP address used by `sqlpage.send_mail`. Required when configuring a port, credentials, or sender.
pub smtp_host: Option,
- /// SMTP server port. Defaults to 25 for plaintext, 465 for implicit TLS, and 587 for STARTTLS.
+ /// Port used to connect to the SMTP server. Valid ports range from 1 to 65535.
+ #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = format!(
+ "{} for `none`, {} for `tls`, {} for `starttls`.",
+ SmtpTlsMode::None.default_port(), SmtpTlsMode::Tls.default_port(), SmtpTlsMode::Starttls.default_port()
+ ))))]
pub smtp_port: Option,
- /// Optional SMTP user name used by the `sqlpage.send_mail` function.
- /// If set, `SQLPage` authenticates to `SMTP_HOST` with this user name and `smtp_password`.
+ /// SMTP username. Set it together with `smtp_password` and use `starttls` or `tls`.
pub smtp_username: Option,
- /// Optional SMTP password used by the `sqlpage.send_mail` function when `smtp_username` is set.
+ /// SMTP password. Set it together with `smtp_username`.
pub smtp_password: Option,
- /// Default sender used by the `sqlpage.send_mail` function when the message has no `from` property.
+ /// Default sender address for `sqlpage.send_mail`, optionally including a display name.
+ /// The message's `from` property overrides this setting.
pub smtp_from: Option,
- /// Encryption mode used to connect to `SMTP_HOST`.
+ /// SMTP transport security. Use `starttls` to require a STARTTLS upgrade or `tls` to use TLS from connection start.
+ /// Use `none` only with a trusted relay that does not require credentials.
#[serde(default)]
pub smtp_tls_mode: SmtpTlsMode,
- /// Maximum combined decoded size of attachments in one email.
+ /// Maximum combined size in bytes of decoded attachments in one email, independent of the upload limit.
#[serde(default = "default_max_email_attachment_size")]
pub max_email_attachment_size: usize,
- /// Maximum size of uploaded files in bytes. The default is 5MiB (5 * 1024 * 1024 bytes)
+ /// Maximum size in bytes of submitted forms and uploaded files.
#[serde(default = "default_max_file_size")]
pub max_uploaded_file_size: usize,
- /// The base URL of the `OpenID` Connect provider.
- /// Required when enabling Single Sign-On through an OIDC provider.
+ /// Issuer URL of the [OpenID Connect provider](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#openid-connect-oidc-authentication). Required for single sign-on.
+ #[cfg_attr(feature = "config-schema", schemars(with = "Option", url))]
pub oidc_issuer_url: Option,
- /// The client ID assigned to `SQLPage` when registering with the OIDC provider.
- /// Defaults to `sqlpage`.
+
+ /// Client ID assigned by the OIDC provider.
#[serde(default = "default_oidc_client_id")]
pub oidc_client_id: String,
- /// The client secret for authenticating `SQLPage` to the OIDC provider.
- /// Required when enabling Single Sign-On through an OIDC provider.
+
+ /// Client secret required to authenticate with the OIDC provider. Keep this value private.
pub oidc_client_secret: Option,
- /// Space-separated list of [scopes](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims) to request during OIDC authentication.
- /// Defaults to "openid email profile"
+
+ /// Space-separated [scopes](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims) to request during login.
#[serde(default = "default_oidc_scopes")]
pub oidc_scopes: String,
- /// Defines a list of path prefixes that should be protected by OIDC authentication.
- /// By default, all paths are protected.
- /// If you specify a list of prefixes, only requests whose path starts with one of the prefixes will require authentication.
- /// For example, if you set this to `["/private"]`, then requests to `/private/some_page.sql` will require authentication,
- /// but requests to `/index.sql` will not.
- /// NOTE: `OIDC_PUBLIC_PATHS` takes precedence over `OIDC_PROTECTED_PATHS`.
- /// For example, if you have `["/private"]` on the `protected_paths` like before, but also `["/private/public"]` on the `public_paths`, then `/private` requires authentication, but `/private/public` requires not authentication.
- /// You cannot make a path inside a public path private again. So expanding the previous example, if you now add `/private/public/private_again`, then this path will still be accessible.
+ /// Path prefixes that require OIDC authentication, relative to `site_prefix`.
+ /// For example, use `["/admin", "/users/settings"]` to require login for both prefixes.
+ /// All prefixes must begin with `/`. The server normalizes decoded dot segments and repeated separators
+ /// and recognizes ASCII case aliases on case-insensitive storage. Public prefixes take precedence.
+ /// Use a space-separated list for environment variables.
#[serde(default = "default_oidc_protected_paths")]
pub oidc_protected_paths: Vec,
- /// Defines path prefixes to exclude from OIDC authentication.
- /// By default, no paths are excluded.
- /// Paths matching these prefixes will not require authentication.
- /// For example, if set to `["/public"]`, requests to `/public/some_page.sql` will not require authentication,
- /// but requests to `/index.sql` will still require it.
- /// To make `/protected/public.sql` public while protecting its containing directory,
- /// set `oidc_public_paths` to `["/protected/public.sql"]` and `oidc_protected_paths` to `["/protected"]`.
- /// Be aware that any path starting with `/protected/public.sql` (e.g., `/protected/public.sql.backup`) will also become public.
+ /// Path prefixes accessible without OIDC authentication, relative to `site_prefix`.
+ /// All prefixes must begin with `/`. They override protected prefixes, including nested protected prefixes. A trailing slash limits a directory match:
+ /// `/public/` matches its contents while `/public` also matches `/publicity`.
+ /// Use a space-separated list for environment variables.
#[serde(default)]
pub oidc_public_paths: Vec,
- /// Additional trusted audiences for OIDC JWT tokens, beyond the client ID.
- /// By default (when None), all additional audiences are trusted for compatibility
- /// with providers that include multiple audience values (like ZITADEL, Azure AD, etc.).
- /// Set to an empty list to only allow the client ID as audience.
- /// Set to a specific list to only allow those specific additional audiences.
+ /// JWT audiences accepted in addition to the client ID. Omitting the setting accepts all additional audiences.
+ /// Set `[]` to accept only the client ID, or list specific additional audiences.
+ /// Use a space-separated list for environment variables.
#[serde(default)]
pub oidc_additional_trusted_audiences: Option>,
- /// A domain name to use for the HTTPS server. If this is set, the server will perform all the necessary
- /// steps to set up an HTTPS server automatically. All you need to do is point your domain name to the
- /// server's IP address.
- ///
- /// It will listen on port 443 for HTTPS connections,
- /// and will automatically request a certificate from Let's Encrypt
- /// using the ACME protocol (requesting a TLS-ALPN-01 challenge).
+ /// Public domain for automatic Let's Encrypt certificates. Point its DNS record to this server.
+ /// HTTPS always listens on port 443. A different port in `listen_on` or `port` also serves plain HTTP.
pub https_domain: Option,
- /// The hostname where your application is publicly accessible (e.g., "myapp.example.com").
- /// This is used for OIDC redirect URLs. If not set, `https_domain` will be used instead.
+ /// Public hostname for OIDC redirect URLs, for example `myapp.example.com`.
+ /// Wildcard and loopback listeners use `localhost` and the listener port when deriving this value.
+ #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = "Uses `https_domain` or the listener address.")))]
pub host: Option,
- /// The email address to use when requesting a certificate from Let's Encrypt.
- /// Defaults to `contact@`.
+ /// Contact email for Let's Encrypt certificate requests.
+ #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = "`contact@`")))]
pub https_certificate_email: Option,
- /// The directory to store the Let's Encrypt certificate in. Defaults to `./sqlpage/https`.
+ /// Writable directory for caching HTTPS certificates. The relative default is resolved against the working directory.
#[serde(default = "default_https_certificate_cache_dir")]
+ #[cfg_attr(
+ feature = "config-schema",
+ schemars(default = "schema::certificate_cache_directory")
+ )]
pub https_certificate_cache_dir: PathBuf,
- /// URL to the ACME directory. Defaults to the Let's Encrypt production directory.
+ /// ACME directory URL used to request HTTPS certificates.
#[serde(default = "default_https_acme_directory_url")]
pub https_acme_directory_url: String,
- /// Whether we should run in development or production mode. Used to determine
- /// whether to show error messages to the user.
+ /// Development or production mode. Production hides detailed errors from users and caches files between requests.
#[serde(default)]
pub environment: DevOrProd,
- /// Serve the website from a sub path. For example, if you set this to `/sqlpage/`, the website will be
- /// served from `https://yourdomain.com/sqlpage/`. Defaults to `/`.
- /// This is useful if you want to serve the website on the same domain as other content, and
- /// you are using a reverse proxy to route requests to the correct server.
+ /// Base path for all URLs. Set `/sqlpage/` to serve the site at `https://example.com/sqlpage/`.
#[serde(
deserialize_with = "deserialize_site_prefix",
default = "default_site_prefix"
)]
pub site_prefix: String,
- /// Maximum number of messages that can be stored in memory before sending them to the client.
- /// This prevents a single request from using up all available memory.
+ /// Maximum number of rendered rows queued while waiting for a slow client. Must be greater than zero.
#[serde(default = "default_max_pending_rows")]
pub max_pending_rows: usize,
- /// Whether to compress the http response body when the client supports it.
- /// Enabling response compression hinders the ability of `SQLPage` to stream every single byte
- /// of data as soon as it is produced.
- /// As a rule of thub, enable response compression when your app is fast.
+ /// Compress HTTP responses when the client supports compression. This saves bandwidth but can buffer streamed output.
#[serde(default = "default_compress_responses")]
pub compress_responses: bool,
- /// Content-Security-Policy header to send to the client.
- /// If not set, a default policy allowing
- /// - scripts from the same origin,
- /// - script elements with the `nonce="{{@csp_nonce}}"` attribute,
+ /// Content-Security-Policy header for HTML responses. An empty string disables it.
+ /// A custom policy can use `'nonce-{NONCE}'` to include a fresh nonce for each request.
#[serde(default)]
+ #[cfg_attr(feature = "config-schema", schemars(with = "String", extend(
+ "default" = crate::webserver::content_security_policy::DEFAULT_CONTENT_SECURITY_POLICY
+ )))]
pub content_security_policy: ContentSecurityPolicyTemplate,
- /// Whether `sqlpage.fetch` should load trusted certificates from the operating system's certificate store
- /// By default, it loads Mozilla's root certificates that are embedded in the `SQLPage` binary, or the ones pointed to by the
- /// `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables.
+ /// Load trusted HTTPS certificates for `sqlpage.fetch` from the operating system's certificate store.
+ /// When the system store is enabled, `SSL_CERT_FILE` and `SSL_CERT_DIR` select certificate sources.
+ /// Disabling this setting uses the embedded Mozilla roots.
#[serde(default = "default_system_root_ca_certificates")]
+ #[cfg_attr(feature = "config-schema", schemars(default, extend(
+ "x-default-description" = "True when `SSL_CERT_FILE` or `SSL_CERT_DIR` is nonempty, otherwise false."
+ )))]
pub system_root_ca_certificates: bool,
- /// Maximum depth of recursion allowed in the `run_sql` function.
+ /// Maximum recursion depth for `sqlpage.run_sql`. Valid values range from 0 to 255.
#[serde(default = "default_max_recursion_depth")]
pub max_recursion_depth: u8,
+ /// Allow raw HTML in Markdown. Enable only when all Markdown content is trusted.
#[serde(default = "default_markdown_allow_dangerous_html")]
pub markdown_allow_dangerous_html: bool,
+ /// Allow dangerous protocols such as `javascript:` in Markdown links. Enable only when all Markdown content is trusted.
#[serde(default = "default_markdown_allow_dangerous_protocol")]
pub markdown_allow_dangerous_protocol: bool,
+ /// Time in milliseconds to cache a file before checking the filesystem for changes.
+ #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = format!(
+ "{} in production, {} in development.",
+ DevOrProd::Production.default_cache_stale_duration_ms(), DevOrProd::Development.default_cache_stale_duration_ms()
+ ))))]
pub cache_stale_duration_ms: Option,
}
@@ -418,18 +459,14 @@ impl AppConfig {
#[must_use]
pub fn cache_stale_duration_ms(&self) -> u64 {
self.cache_stale_duration_ms
- .unwrap_or_else(|| if self.environment.is_prod() { 1000 } else { 0 })
+ .unwrap_or_else(|| self.environment.default_cache_stale_duration_ms())
}
#[must_use]
pub fn listen_on(&self) -> SocketAddr {
- let mut addr = self.listen_on.unwrap_or_else(|| {
- if self.https_domain.is_some() {
- SocketAddr::from(([0, 0, 0, 0], 443))
- } else {
- SocketAddr::from(([0, 0, 0, 0], 8080))
- }
- });
+ let mut addr = self
+ .listen_on
+ .unwrap_or_else(|| default_listen_on(self.https_domain.is_some()));
if let Some(port) = self.port {
addr.set_port(port);
}
@@ -437,6 +474,10 @@ impl AppConfig {
}
}
+fn default_listen_on(https: bool) -> SocketAddr {
+ SocketAddr::from(([0, 0, 0, 0], if https { 443 } else { 8080 }))
+}
+
impl RoutingConfig for AppConfig {
fn prefix(&self) -> &str {
&self.site_prefix
@@ -457,6 +498,10 @@ fn configuration_directory() -> PathBuf {
}
}
}
+ default_configuration_directory()
+}
+
+fn default_configuration_directory() -> PathBuf {
PathBuf::from("./sqlpage")
}
@@ -506,17 +551,19 @@ fn env_config() -> config::Environment {
.with_list_parse_key("oidc_additional_trusted_audiences")
}
+#[derive(Deserialize)]
+#[cfg_attr(feature = "config-schema", derive(schemars::JsonSchema))]
+#[serde(untagged)]
+enum PortOrUrl {
+ Port(u16),
+ Url(String),
+}
+
fn deserialize_port<'de, D>(deserializer: D) -> Result, D::Error>
where
D: Deserializer<'de>,
{
// deserializes both 8080 and "tcp://1.1.1.1:9090"
- #[derive(Deserialize)]
- #[serde(untagged)]
- enum PortOrUrl {
- Port(u16),
- Url(String),
- }
let port_or_url: Option = Deserialize::deserialize(deserializer)?;
match port_or_url {
Some(PortOrUrl::Port(p)) => Ok(Some(p)),
@@ -712,7 +759,7 @@ fn default_max_email_attachment_size() -> usize {
}
fn default_https_certificate_cache_dir() -> PathBuf {
- default_web_root().join("sqlpage").join("https")
+ default_web_root().join(CERTIFICATE_CACHE_DIRECTORY)
}
fn default_https_acme_directory_url() -> String {
@@ -758,6 +805,7 @@ fn default_oidc_protected_paths() -> Vec {
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone, Copy, Eq, Default)]
+#[cfg_attr(feature = "config-schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum DevOrProd {
#[default]
@@ -766,6 +814,7 @@ pub enum DevOrProd {
}
#[derive(Debug, Deserialize, PartialEq, Clone, Copy, Eq, Default)]
+#[cfg_attr(feature = "config-schema", derive(Serialize, schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum SmtpTlsMode {
None,
@@ -783,6 +832,10 @@ impl SmtpTlsMode {
}
}
impl DevOrProd {
+ fn default_cache_stale_duration_ms(self) -> u64 {
+ if self.is_prod() { 1000 } else { 0 }
+ }
+
pub(crate) fn is_prod(self) -> bool {
self == DevOrProd::Production
}
diff --git a/src/app_config/schema.rs b/src/app_config/schema.rs
new file mode 100644
index 000000000..6fb55611b
--- /dev/null
+++ b/src/app_config/schema.rs
@@ -0,0 +1,47 @@
+use super::{CERTIFICATE_CACHE_DIRECTORY, Duration};
+use crate::webserver::database::default_max_connections;
+use schemars::Schema;
+use serde_json::Value;
+use sqlx::any::AnyKind;
+
+pub(super) fn working_directory() -> &'static str {
+ "."
+}
+
+pub(super) fn certificate_cache_directory() -> &'static str {
+ CERTIFICATE_CACHE_DIRECTORY
+}
+
+pub(super) fn timeout(duration: Duration) -> String {
+ format!(
+ "Disabled for SQLite, {} seconds for other databases.",
+ duration.as_secs()
+ )
+}
+
+pub(super) fn pool_sizes() -> String {
+ [
+ ("PostgreSQL", AnyKind::Postgres, false),
+ ("MySQL", AnyKind::MySql, false),
+ ("SQLite on disk", AnyKind::Sqlite, false),
+ ("SQLite in memory", AnyKind::Sqlite, true),
+ ("MSSQL", AnyKind::Mssql, false),
+ ("ODBC", AnyKind::Odbc, false),
+ ]
+ .map(|(label, kind, memory)| format!("{label} {}", default_max_connections(kind, memory)))
+ .join(", ")
+}
+
+/// JSON Schema defaults represent a single value supplied when the property is omitted.
+/// Conditional defaults have a human-readable description, and optional settings can be unset.
+pub(super) fn remove_unset_defaults(schema: &mut Schema) {
+ if let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) {
+ for field in properties.values_mut().filter_map(Value::as_object_mut) {
+ if field.contains_key("x-default-description")
+ || field.get("default") == Some(&Value::Null)
+ {
+ field.remove("default");
+ }
+ }
+ }
+}
diff --git a/src/webserver/database/connect.rs b/src/webserver/database/connect.rs
index 3c0e42030..ca9d5d3fa 100644
--- a/src/webserver/database/connect.rs
+++ b/src/webserver/database/connect.rs
@@ -104,20 +104,17 @@ where
}
fn max_connections(config: &AppConfig, kind: AnyKind) -> u32 {
- if let Some(max) = config.max_database_pool_connections {
- return max;
- }
- // Different databases have a different number of max concurrent connections allowed by default
+ config
+ .max_database_pool_connections
+ .unwrap_or_else(|| default_max_connections(kind, config.database_url.contains(":memory:")))
+}
+
+pub(crate) fn default_max_connections(kind: AnyKind, in_memory: bool) -> u32 {
match kind {
AnyKind::Postgres | AnyKind::Odbc => 50, // Default to PostgreSQL-like limits for Generic
AnyKind::MySql => 75,
- AnyKind::Sqlite => {
- if config.database_url.contains(":memory:") {
- 128
- } else {
- 16
- }
- }
+ AnyKind::Sqlite if in_memory => 128,
+ AnyKind::Sqlite => 16,
AnyKind::Mssql => 100,
}
}
diff --git a/src/webserver/database/mod.rs b/src/webserver/database/mod.rs
index b8c2d6153..23a1b0be3 100644
--- a/src/webserver/database/mod.rs
+++ b/src/webserver/database/mod.rs
@@ -10,6 +10,8 @@ mod sqlpage_functions;
mod error_highlighting;
mod sql_to_json;
+#[cfg(feature = "config-schema")]
+pub(crate) use connect::default_max_connections;
pub use sql::SqlFile;
use sqlx::any::AnyKind;
// SupportedDatabase is defined in this module
diff --git a/src/webserver/database/sqlpage_functions/README.md b/src/webserver/database/sqlpage_functions/README.md
index 00fde024c..7a5dc676e 100644
--- a/src/webserver/database/sqlpage_functions/README.md
+++ b/src/webserver/database/sqlpage_functions/README.md
@@ -27,6 +27,8 @@ sqlpage_functions! {
}
```
+Add the matching Markdown page to the [function reference](../../../../examples/official-site/content/functions/). The registry test checks that each public function has a page.
+
The [`sqlpage_functions!`](function_traits.rs) macro generates the
`SqlPageFunctionName` enum the SQL engine dispatches on. Per-function argument extraction, dispatch,
and return-value conversion are handled generically in [`function_traits.rs`](function_traits.rs) by
diff --git a/tests/configuration_docs/mod.rs b/tests/configuration_docs/mod.rs
index 244b07e6e..ff6c6187e 100644
--- a/tests/configuration_docs/mod.rs
+++ b/tests/configuration_docs/mod.rs
@@ -1,32 +1,71 @@
+#![cfg(feature = "config-schema")]
+
+use schemars::schema_for;
use serde::Deserialize;
use serde::de::value::Error as DeError;
use serde::de::{Deserializer, Visitor};
+use serde_json::json;
use sqlpage::app_config::AppConfig;
use std::collections::BTreeSet;
#[test]
-fn configuration_md_documents_every_option() {
- let documented = documented_option_names();
- let implemented = app_config_option_names();
-
- let undocumented: Vec<_> = implemented.difference(&documented).collect();
- let unimplemented: Vec<_> = documented.difference(&implemented).collect();
-
- assert!(
- undocumented.is_empty() && unimplemented.is_empty(),
- "configuration.md and AppConfig disagree.\n\
- Missing from configuration.md: {undocumented:?}\n\
- Documented but not in AppConfig: {unimplemented:?}"
+fn every_public_setting_has_a_description() {
+ let schema = schema_for!(AppConfig);
+ let properties = schema.get("properties").unwrap().as_object().unwrap();
+ assert_eq!(
+ properties.keys().cloned().collect::>(),
+ app_config_option_names()
);
+ for (name, property) in properties {
+ assert!(
+ property["description"]
+ .as_str()
+ .is_some_and(|text| !text.trim().is_empty()),
+ "{name} needs a Rust doc comment"
+ );
+ }
}
-fn documented_option_names() -> BTreeSet {
- let table = std::fs::read_to_string("configuration.md").unwrap();
- table
- .lines()
- .filter_map(|line| line.strip_prefix("| `")?.split('`').next())
- .map(str::to_owned)
- .collect()
+#[test]
+fn schema_documents_input_types_and_effective_defaults() {
+ let schema = schema_for!(AppConfig);
+ let properties = schema.get("properties").unwrap();
+ let timeout = &properties["database_connection_idle_timeout_seconds"];
+ assert_eq!(timeout["type"], json!(["number", "null"]));
+ assert!(
+ timeout["x-default-description"]
+ .as_str()
+ .unwrap()
+ .contains("SQLite")
+ );
+ assert!(timeout.get("default").is_none());
+ assert_eq!(properties["site_prefix"]["default"], "/");
+ assert_eq!(properties["smtp_tls_mode"]["default"], "starttls");
+ assert_eq!(properties["web_root"]["default"], ".");
+ assert_eq!(
+ properties["configuration_directory"]["default"],
+ "./sqlpage"
+ );
+ assert_eq!(properties["content_security_policy"]["type"], "string");
+ assert!(
+ properties["content_security_policy"]["default"]
+ .as_str()
+ .unwrap()
+ .contains("{NONCE}")
+ );
+ assert!(
+ properties["system_root_ca_certificates"]
+ .get("default")
+ .is_none()
+ );
+ assert!(properties["database_url"].get("default").is_none());
+ assert_eq!(properties["oidc_public_paths"]["default"], json!([]));
+ assert!(
+ properties["oidc_additional_trusted_audiences"]
+ .get("default")
+ .is_none()
+ );
+ assert!(schema.get("required").is_none());
}
fn app_config_option_names() -> BTreeSet {
diff --git a/tests/js/component_documentation.spec.ts b/tests/js/component_documentation.checks.ts
similarity index 81%
rename from tests/js/component_documentation.spec.ts
rename to tests/js/component_documentation.checks.ts
index c78a46838..f062a7a39 100644
--- a/tests/js/component_documentation.spec.ts
+++ b/tests/js/component_documentation.checks.ts
@@ -5,28 +5,14 @@ import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import test from "node:test";
-// Every built-in component is a Handlebars template in sqlpage/templates/, and
-// its properties are documented as rows of the `parameter` table of the
-// official site, built by the SQL migrations in examples/official-site/.
-// Nothing links the two, so they drift: properties get added to a template and
-// never documented, and documented properties outlive the code that read them.
-//
-// This test builds the official site's documentation database, reads the
-// property names out of the templates, and asserts that the two agree.
+// Check both directions: every property a template reads has documentation,
+// and each documented property is used at the advertised level.
const require = createRequire(import.meta.url);
const REPO_ROOT = path.resolve(
path.dirname(require.resolve("../../package.json")),
);
const TEMPLATES_DIR = path.join(REPO_ROOT, "sqlpage", "templates");
-const MIGRATIONS_DIR = path.join(
- REPO_ROOT,
- "examples",
- "official-site",
- "sqlpage",
- "migrations",
-);
-
/** Components rendered by src/render.rs rather than by a Handlebars template. */
const COMPONENTS_WITHOUT_A_TEMPLATE = new Set([
"authentication",
@@ -233,32 +219,30 @@ function read_templates(): Map {
}
function read_documentation(): Map {
- const migrations = fs
- .readdirSync(MIGRATIONS_DIR)
- .filter((file) => file.endsWith(".sql"))
- // SQLPage applies migrations in the order of their numeric prefix.
- .sort(
- (a, b) =>
- Number.parseInt(a, 10) - Number.parseInt(b, 10) || a.localeCompare(b),
- );
-
const db = new DatabaseSync(":memory:");
- for (const file of migrations) {
- db.exec(fs.readFileSync(path.join(MIGRATIONS_DIR, file), "utf8"));
- }
+ db.exec(
+ fs.readFileSync(
+ path.join(
+ REPO_ROOT,
+ "target/official-site/sqlpage/migrations/01_documentation.sql",
+ ),
+ "utf8",
+ ),
+ );
const documented = new Map();
+ for (const row of db.prepare("select name from component").all()) {
+ assert.ok(typeof row.name === "string");
+ documented.set(row.name, { top: new Set(), row: new Set() });
+ }
const rows = db
.prepare("select component, name, top_level from parameter")
.all();
for (const { component, name, top_level } of rows) {
assert.ok(typeof component === "string" && typeof name === "string");
assert.equal(typeof top_level, "number");
- let entry = documented.get(component);
- if (!entry) {
- entry = { top: new Set(), row: new Set() };
- documented.set(component, entry);
- }
+ const entry = documented.get(component);
+ assert.ok(entry, component);
(top_level ? entry.top : entry.row).add(name);
}
db.close();
@@ -268,18 +252,12 @@ function read_documentation(): Map {
const templates = read_templates();
const documented = read_documentation();
-test("every component documented by the official site has a template", () => {
- const missing = [...documented.keys()].filter(
- (component) =>
- !templates.has(component) &&
- !COMPONENTS_WITHOUT_A_TEMPLATE.has(component),
- );
- assert.deepEqual(
- missing,
- [],
- `These components are documented but have no sqlpage/templates/*.handlebars file. ` +
- `If they are rendered by src/render.rs, add them to COMPONENTS_WITHOUT_A_TEMPLATE.`,
- );
+test("the official site documents every public component", () => {
+ const publicComponents = [
+ ...templates.keys(),
+ ...COMPONENTS_WITHOUT_A_TEMPLATE,
+ ];
+ assert.deepEqual([...documented.keys()].sort(), publicComponents.sort());
});
test("every property read by a template is documented", () => {
@@ -299,8 +277,7 @@ test("every property read by a template is documented", () => {
assert.deepEqual(
undocumented.sort(),
[],
- `These properties are read by a template but not documented. Add a row to ` +
- `the component's migration in examples/official-site/sqlpage/migrations/.`,
+ "These properties are read by a template but not documented. Update the component page in examples/official-site/content/components/.",
);
});
@@ -326,7 +303,7 @@ test("every documented property is read by its template", () => {
assert.deepEqual(
unimplemented.sort(),
[],
- `Remove the documentation, or fix its top_level, in ` +
- `examples/official-site/sqlpage/migrations/.`,
+ `Remove the documentation, or correct its parameter group, in ` +
+ `examples/official-site/content/components/.`,
);
});
diff --git a/tests/js/tsconfig.json b/tests/js/tsconfig.json
index 752910d94..d20d4c79a 100644
--- a/tests/js/tsconfig.json
+++ b/tests/js/tsconfig.json
@@ -2,9 +2,10 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"lib": ["es2022"],
+ "allowJs": true,
"module": "nodenext",
"moduleResolution": "nodenext",
"types": ["node"]
},
- "include": ["*.spec.ts"]
+ "include": ["*.spec.ts", "*.checks.ts"]
}