diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ca527789..c71095307 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## unreleased +- A table row action without a link leaves its cell empty. ([#1709](https://github.com/sqlpage/SQLPage/pull/1709)) - SQLPage reports syntax errors before running any statements in the affected SQL file. ([#1706](https://github.com/sqlpage/SQLPage/discussions/1706)) - OIDC logs focus on configuration and failures. SQLPage omits tokens, cookie values, user claims, and callback and logout query strings from OIDC diagnostics. - Standard alert descriptions have higher text contrast. diff --git a/examples/official-site/README.md b/examples/official-site/README.md index 0393a97a0..331bbf199 100644 --- a/examples/official-site/README.md +++ b/examples/official-site/README.md @@ -56,7 +56,7 @@ Name each example with a zero-padded number and a short, hyphenated title. Keep - **[`code/01-display-html-source.sql`](reference/components/code/01-display-html-source.sql)** runs inline. Start with a block comment containing a title and optional Markdown. The SQL after the comment supplies the copyable source, preview, and direct URL. - **[`shell/01-dark-shell-with-navigation-menus.standalone.sql`](reference/components/shell/01-dark-shell-with-navigation-menus.standalone.sql)** runs only when its direct URL is opened. Use this form when the example controls the page shell or HTTP response. -- **[`cookie/01-set-and-read-a-cookie.md`](reference/components/cookie/01-set-and-read-a-cookie.md)** displays a walkthrough. Start with a `# Title` and use fenced code blocks for SQL that needs an application database, changes state, or spans multiple files. +- **[`form/01-separate-submission-handler.md`](reference/components/form/01-separate-submission-handler.md)** displays a walkthrough. Start with a `# Title` and use fenced code blocks for SQL that needs an application database, changes state, or spans multiple files. ```sql /* diff --git a/examples/official-site/component.sql b/examples/official-site/component.sql index c6f22ed3b..9be9d138c 100644 --- a/examples/official-site/component.sql +++ b/examples/official-site/component.sql @@ -3,7 +3,8 @@ select 'redirect' as component, where not exists (select 1 from component where name = $component); select 'http_header' as component, - 'public, max-age=600, stale-while-revalidate=3600, stale-if-error=86400' as "Cache-Control", + case when $component in ('list', 'table') or sqlpage.request_method() <> 'GET' then 'private, no-store' + else 'public, max-age=600, stale-while-revalidate=3600, stale-if-error=86400' end as "Cache-Control", printf('<%s>; rel="canonical"', sqlpage.link('component', json_object('component', $component))) as "Link"; select 'dynamic' as component, sqlpage.run_sql('sqlpage/docs-reference.sql', json_object( @@ -13,11 +14,18 @@ select 'dynamic' as component, sqlpage.run_sql('sqlpage/docs-reference.sql', jso select 'title' as component, 2 as level, 'Examples' as contents, 'examples' as id where exists (select 1 from example where component = $component); +select 'text' as component, + 'For examples that use sample tables, download the [SQLite sample data](/examples/reference/sample-data.sql.txt). In a fresh SQLPage app, run `sqlite3 sqlpage/sqlpage.db < sample-data.sql.txt` from the app directory. Save the example as a SQL page and point any links to that file.' as contents_md +where exists ( + select 1 from example where component = $component + and (source glob '*demo_*' or source glob '*from customers*' or source glob '*from customer_feedback*' or source glob '*from tickets*') +); + select 'dynamic' as component, json_array( json_object( 'component', 'docs-example', 'number', number, 'title', title, 'description_md', description, 'source', source, - 'preview', preview + 'preview', preview, 'standalone_url', case when not preview then '/' || path end ), coalesce(sqlpage.run_sql(case when preview then path end), '[]'), case when preview then json_object('component', 'docs-example', 'end_result', true) diff --git a/examples/official-site/examples/authentication/create_session_token.sql b/examples/official-site/examples/authentication/create_session_token.sql index 8ea8cd192..3df649e4f 100644 --- a/examples/official-site/examples/authentication/create_session_token.sql +++ b/examples/official-site/examples/authentication/create_session_token.sql @@ -1,16 +1,17 @@ -- delete expired sessions delete from user_sessions where created_at < datetime('now', '-1 day'); --- check that the +-- Verify the password before creating a session. SELECT 'authentication' AS component, - 'login.sql?failed' AS link, -- redirect to the login page on error - (SELECT password_hash FROM users WHERE username = :username) AS password_hash, -- this is a hash of the password 'admin' - :password AS password; -- this is the password that the user sent through our form in 'index.sql' + '/examples/authentication/login.sql?failed' AS link, -- redirect to the login page on error + (SELECT password_hash FROM users WHERE username = :username) AS password_hash, + :password AS password; --- if we haven't been redirected, then the password is correct --- create a new session -insert into user_sessions (session_token, username) values (sqlpage.random_string(32), :username) -returning 'cookie' as component, 'session_token' as name, session_token as value; +-- Remembered sessions keep their browser cookie for up to one day. +set token = sqlpage.random_string(32); +insert into user_sessions (session_token, username) values ($token, :username); +select 'cookie' as component, 'session_token' as name, $token as value where :remember is null; +select 'cookie' as component, 'session_token' as name, $token as value, 86400 as max_age where :remember is not null; -- redirect to the authentication example home page -select 'redirect' as component, '/examples/authentication' as link; \ No newline at end of file +select 'redirect' as component, '/examples/authentication' as link; diff --git a/examples/official-site/examples/authentication/index.sql b/examples/official-site/examples/authentication/index.sql index 6ef3a297a..28a5e50f8 100644 --- a/examples/official-site/examples/authentication/index.sql +++ b/examples/official-site/examples/authentication/index.sql @@ -1,6 +1,6 @@ -- redirect the user to the login page if they are not logged in -- this query should be present at the top of every page that requires authentication -set user_role = (select role from users natural join user_sessions where session_token = sqlpage.cookie('session_token')); +set user_role = (select role from users natural join user_sessions where session_token = sqlpage.cookie('session_token') and created_at >= datetime('now', '-1 day')); select 'redirect' as component, 'login.sql' as link where $user_role is null; select 'dynamic' as component, diff --git a/examples/official-site/examples/reference/entries.sql b/examples/official-site/examples/reference/entries.sql new file mode 100644 index 000000000..b4ef204f8 --- /dev/null +++ b/examples/official-site/examples/reference/entries.sql @@ -0,0 +1,6 @@ +set token = sqlpage.cookie('docs_entry'); +select 'form' as component, 'Your sample entry' as title, '/examples/reference/save-entry.sql' as action, 'Save entry' as validate; +select 'name' as name, 'Sample name' as label, true as required, 60 as maxlength, + (select name from demo_entries where token = $token) as value; +select 'list' as component, 'Your saved entry' as title, 'No saved entry yet' as empty_title; +select name as title from demo_entries where token = $token; diff --git a/examples/official-site/examples/reference/events.js b/examples/official-site/examples/reference/events.js new file mode 100644 index 000000000..5ebe4e6c9 --- /dev/null +++ b/examples/official-site/examples/reference/events.js @@ -0,0 +1,17 @@ +const events = new EventSource( + "/reference/components/json/04-stream-server-sent-events.standalone.sql", +); +const customers = document.querySelector("#customers"); +events.onmessage = (event) => { + const row = JSON.parse(event.data); + const item = document.createElement("li"); + item.textContent = row.name; + customers.append(item); +}; +events.onerror = () => { + events.close(); + document.querySelector("#stream-status").textContent = customers.children + .length + ? "Stream closed." + : "No customers received."; +}; diff --git a/examples/official-site/examples/reference/events.sql b/examples/official-site/examples/reference/events.sql new file mode 100644 index 000000000..52d005b1d --- /dev/null +++ b/examples/official-site/examples/reference/events.sql @@ -0,0 +1,4 @@ +select 'shell' as component, 'Stream of customers' as title, + '/examples/reference/events.js' as javascript_module; +select 'text' as component, 'Customers received from the stream' as title; +select 'html' as component, '
Connecting…
' as html; diff --git a/examples/official-site/examples/reference/poem.sql b/examples/official-site/examples/reference/poem.sql new file mode 100644 index 000000000..ca2fc40f7 --- /dev/null +++ b/examples/official-site/examples/reference/poem.sql @@ -0,0 +1,9 @@ +set poem = case when $action = 'saved' then sqlpage.cookie('docs_poem') else :poem end; +select 'cookie' as component, 'docs_poem' as name, :poem as value, false as secure +where $action = 'save' and :poem is not null and length(:poem) between 1 and 200; +select 'text' as component, case when $action in ('save', 'saved') then 'Saved poem' else 'Poem preview' end as title, + coalesce($poem, 'No poem saved yet.') as contents +where length(coalesce($poem, '')) between 1 and 200 or $action = 'saved'; +select 'text' as component, 'Enter a poem of 1 to 200 characters.' as contents +where $action in ('save', 'preview') and length(coalesce($poem, '')) not between 1 and 200; +select 'text' as component, '[Read the saved poem](/examples/reference/poem.sql?action=saved) | [Write another poem](/component.sql?component=button#example-7)' as contents_md; diff --git a/examples/official-site/examples/reference/record.sql b/examples/official-site/examples/reference/record.sql new file mode 100644 index 000000000..aa65e3c16 --- /dev/null +++ b/examples/official-site/examples/reference/record.sql @@ -0,0 +1,21 @@ +set states = case when json_valid(sqlpage.cookie('docs_projects')) then sqlpage.cookie('docs_projects') else '{}' end; +set record_id = (select id from demo_projects where id = cast($id as integer)); +set key = '$."' || $record_id || '"'; +set state = coalesce(json_extract($states, $key), (select initial_status from demo_projects where id = $record_id)); +set next_state = case when :operation = 'delete' then 'Removed' when :operation = 'use' then 'In use' + when :operation = 'restore' then 'Available' end; +select 'cookie' as component, 'docs_projects' as name, json_set($states, $key, $next_state) as value, false as secure +where $record_id is not null and $next_state is not null; +select 'redirect' as component, '/examples/reference/record.sql?id=' || $record_id as link +where $next_state is not null and $record_id is not null; + +select 'text' as component, name as title, 'Status: ' || $state as contents from demo_projects where id = $record_id; +select 'form' as component, 'Apply to this project' as validate +where $record_id is not null; +select 'operation' as name, 'Action' as label, 'select' as type, + json_array(json_object('label', 'Start using', 'value', 'use'), + json_object('label', 'Remove', 'value', 'delete'), + json_object('label', 'Restore', 'value', 'restore')) as options, + case $action when 'delete' then 'delete' when 'restore' then 'restore' else 'use' end as value; +select 'text' as component, + '[Back to the list](/component.sql?component=list#example-4) | [Back to the table](/component.sql?component=table#example-11)' as contents_md; diff --git a/examples/official-site/examples/reference/save-entry.sql b/examples/official-site/examples/reference/save-entry.sql new file mode 100644 index 000000000..bc1071e88 --- /dev/null +++ b/examples/official-site/examples/reference/save-entry.sql @@ -0,0 +1,9 @@ +select 'redirect' as component, '/examples/reference/entries.sql' as link +where sqlpage.request_method() <> 'POST' or length(trim(coalesce(:name, ''))) not between 1 and 60; +set token = coalesce((select token from demo_entries where token = sqlpage.cookie('docs_entry')), sqlpage.random_string(32)); +delete from demo_entries where updated_at < datetime('now', '-1 day'); +insert into demo_entries(token, name) values ($token, trim(:name)) +on conflict(token) do update set name = excluded.name, updated_at = current_timestamp; +select 'cookie' as component, 'docs_entry' as name, $token as value, 86400 as max_age, + false as secure; +select 'redirect' as component, '/examples/reference/entries.sql' as link; diff --git a/examples/official-site/examples/reference/second-page.sql b/examples/official-site/examples/reference/second-page.sql new file mode 100644 index 000000000..287b743f2 --- /dev/null +++ b/examples/official-site/examples/reference/second-page.sql @@ -0,0 +1,4 @@ +select 'dynamic' as component, + sqlpage.run_sql('examples/reference/shared-shell.sql', json_object('title', 'Second page')) as properties; +select 'text' as component, 'Two pages, one menu' as title, + '[Open the other page](/reference/components/dynamic/03-include-another-sql-file.standalone.sql) to see the same menu with a different page title.' as contents_md; diff --git a/examples/official-site/examples/reference/shared-shell.json b/examples/official-site/examples/reference/shared-shell.json new file mode 100644 index 000000000..6800b9cb0 --- /dev/null +++ b/examples/official-site/examples/reference/shared-shell.json @@ -0,0 +1,8 @@ +{ + "component": "shell", + "title": "Shared JSON navigation", + "menu_item": [ + { "title": "Component catalog", "link": "/components.sql" }, + { "title": "SQL functions", "link": "/functions.sql" } + ] +} diff --git a/examples/official-site/examples/reference/shared-shell.sql b/examples/official-site/examples/reference/shared-shell.sql new file mode 100644 index 000000000..12931679e --- /dev/null +++ b/examples/official-site/examples/reference/shared-shell.sql @@ -0,0 +1,3 @@ +select 'shell' as component, coalesce($title, 'Catalog') as title, + json_group_array(json_object('title', name, 'link', '/component.sql?component=' || name) order by name) as menu_item +from component where name in ('card', 'chart', 'map'); diff --git a/examples/official-site/reference/components/authentication/01-basic-auth-and-sessions.md b/examples/official-site/reference/components/authentication/01-basic-auth-and-sessions.md index 9f58d30c4..a82a969c0 100644 --- a/examples/official-site/reference/components/authentication/01-basic-auth-and-sessions.md +++ b/examples/official-site/reference/components/authentication/01-basic-auth-and-sessions.md @@ -1,5 +1,7 @@ # HTTP basic authentication and sessions +[Try signing in and out with the sample accounts](/examples/authentication/). + ### Usage with HTTP basic authentication The most basic usage of the authentication component is with the diff --git a/examples/official-site/reference/components/big_number/01-changes-and-progress-bars.sql b/examples/official-site/reference/components/big_number/01-changes-and-progress-bars.sql index 923fcac43..da30dba35 100644 --- a/examples/official-site/reference/components/big_number/01-changes-and-progress-bars.sql +++ b/examples/official-site/reference/components/big_number/01-changes-and-progress-bars.sql @@ -3,22 +3,15 @@ Big numbers with change indicators and progress bars */ select 'big_number' as "component"; -select - 'Sales' as "title", - 75 as "value", - '%' as "unit", - '#sales_dashboard' as "title_link", - TRUE as "title_link_new_tab", - '#sales_details' as "value_link", - FALSE as "value_link_new_tab", - 'Conversion rate' as "description", - 9 as "change_percent", - 75 as "progress_percent", - 'blue' as "progress_color"; +select 'Resolved tickets' as title, count(*) as value, 'Goal: 50 tickets' as description, + round(100.0 * count(*) / 50) as progress_percent, 'blue' as progress_color +from tickets; -select - 'Revenue' as "title", - '4,300' as "value", - '$' as "unit", - 'Year on year' as "description", - -8 as "change_percent"; +with daily as ( + select date(resolved_at) as day, count(*) as total from tickets group by day +), changes as ( + select day, total, lag(total) over (order by day) as previous from daily +) +select 'Latest daily resolutions' as title, total as value, day as description, + round(100.0 * (total - previous) / nullif(previous, 0)) as change_percent +from changes order by day desc limit 1; diff --git a/examples/official-site/reference/components/big_number/02-dropdowns-and-layout.sql b/examples/official-site/reference/components/big_number/02-dropdowns-and-layout.sql index 3bf3bc45d..ff27c06cc 100644 --- a/examples/official-site/reference/components/big_number/02-dropdowns-and-layout.sql +++ b/examples/official-site/reference/components/big_number/02-dropdowns-and-layout.sql @@ -1,33 +1,26 @@ /* -Big numbers with dropdowns and customized layout -*/ -select - 'big_number' as "component", - 3 as "columns", - 'colorfull_dashboard' as "id"; - -select - 'Users' as "title", - '1,234' as "value", - 'red' as "color", - '#users' as "title_link", - FALSE as "title_link_new_tab", - '#users_details' as "value_link", - TRUE as "value_link_new_tab"; +Choose a revenue period -select - 'Orders' as "title", - 56 as "value", - 'green' as "color", - '#orders' as "title_link", - TRUE as "title_link_new_tab"; - -select - 'Revenue' as "title", - '9,876' as "value", - '€' as "unit", - 'blue' as "color", - -7 as "change_percent", - JSON('{"label":"This week","link":"?days=7&component=big_number#colorfull_dashboard"}') as "dropdown_item", - JSON('{"label":"This month","link":"?days=30&component=big_number#colorfull_dashboard"}') as "dropdown_item", - JSON('{"label":"This quarter","link":"?days=90&component=big_number#colorfull_dashboard"}') as "dropdown_item"; +The period ends on the most recent sample order. Choose a week, month or quarter to recalculate revenue and compare it with the preceding period of the same length. +*/ +set days = case cast($days as integer) when 30 then 30 when 90 then 90 else 7 end; +select 'big_number' as component, 3 as columns; +select 'Customers' as title, count(*) as value from customers; +select 'Orders' as title, count(*) as value from demo_orders; +set latest = (select max(ordered_on) from demo_orders); +set period_start = date($latest, '-' || $days || ' days'); +with choices(days, label) as (values (7, 'This week'), (30, 'This month'), (90, 'This quarter')), +revenue as ( + select sum(case when ordered_on > $period_start then amount end) as current_total, + sum(case when ordered_on <= $period_start then amount end) as previous_total + from demo_orders where ordered_on > date($period_start, '-' || $days || ' days') +) +select 'Revenue' as title, current_total as value, + round(100.0 * (current_total - previous_total) / nullif(previous_total, 0)) as change_percent, '$' as unit, + 'Last ' || $days || ' days of sample orders' as description, + json((select json_group_array(json_object( + 'label', label, + 'link', '/reference/components/big_number/02-dropdowns-and-layout.sql?days=' || days, + 'active', json(iif(days = cast($days as integer), 'true', 'false')) + ) order by days = cast($days as integer) desc, days) from choices)) as dropdown_item +from revenue; diff --git a/examples/official-site/reference/components/breadcrumb/02-link-description-and-current-page.sql b/examples/official-site/reference/components/breadcrumb/02-link-description-and-current-page.sql index 7d6fd254e..5bce025f2 100644 --- a/examples/official-site/reference/components/breadcrumb/02-link-description-and-current-page.sql +++ b/examples/official-site/reference/components/breadcrumb/02-link-description-and-current-page.sql @@ -1,19 +1,18 @@ /* Description of a link and selection of the current page -*/ -select 'breadcrumb' as "component"; - -select - 'Home' as "title", - '/' as "link", - TRUE as "active"; -select - 'Articles' as "title", - '/blog.sql' as "link", - 'Stay informed with the latest news' as "description"; +Follow a link to move through the library. The row whose position matches the selected section sets `active` to true and marks the current page. +*/ +set current = min(3, max(1, coalesce(cast($section as integer), 3))); +select 'breadcrumb' as component; +with pages(position, name) as (values (1, 'Library'), (2, 'Articles'), (3, 'JSON in SQL')) +select name as title, position = cast($current as integer) as active, + 'Open ' || name as description, + '/reference/components/breadcrumb/02-link-description-and-current-page.sql?section=' || position as link +from pages where position <= cast($current as integer) order by position; -select - 'JSON in SQL' as "title", - '/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide' as "link", - 'Learn advanced json functions for MySQL, SQLite, PostgreSQL, and SQL Server' as "description"; +select 'text' as component, 'Current section: ' || case cast($current as integer) + when 1 then 'Library' + when 2 then 'Articles' + when 3 then 'JSON in SQL' end as contents; +select 'Go deeper in the library' as contents, '/reference/components/breadcrumb/02-link-description-and-current-page.sql?section=' || ($current + 1) as link where cast($current as integer) < 3; diff --git a/examples/official-site/reference/components/button/07-multiple-form-actions.sql b/examples/official-site/reference/components/button/07-multiple-form-actions.sql index 83183e6d2..335ceb33c 100644 --- a/examples/official-site/reference/components/button/07-multiple-form-actions.sql +++ b/examples/official-site/reference/components/button/07-multiple-form-actions.sql @@ -6,7 +6,7 @@ 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. +Preview displays the submitted poem. Save stores it in this browser, where the saved-poem link can read it on the next visit. */ select 'form' as "component", @@ -15,19 +15,21 @@ select select 'textarea' as "type", - 'Poem' as "name", + 'poem' as "name", + true as required, + 200 as maxlength, 'Write a poem' as "placeholder"; select 'button' as "component"; select - '/examples/show_variables.sql?action=save' as "link", + '/examples/reference/poem.sql?action=save' as "link", 'poem' as "form", 'primary' as "color", 'Save' as "title"; select - '/examples/show_variables.sql?action=preview' as "link", + '/examples/reference/poem.sql?action=preview' as "link", 'poem' as "form", 'yellow' as "outline", 'Preview' as "title"; diff --git a/examples/official-site/reference/components/button/08-download-button.sql b/examples/official-site/reference/components/button/08-download-button.sql index fbe75160a..698a583b4 100644 --- a/examples/official-site/reference/components/button/08-download-button.sql +++ b/examples/official-site/reference/components/button/08-download-button.sql @@ -9,5 +9,5 @@ select '/sqlpage_introduction_video.mp4' as "link", 'Download Video' as "title", 'download' as "icon", - 'Introduction Video.webm' as "download", + 'Introduction Video.mp4' as "download", 'nofollow' as "rel"; diff --git a/examples/official-site/reference/components/card/02-dashboard-with-markdown.sql b/examples/official-site/reference/components/card/02-dashboard-with-markdown.sql index f5fb24efd..c513df74a 100644 --- a/examples/official-site/reference/components/card/02-dashboard-with-markdown.sql +++ b/examples/official-site/reference/components/card/02-dashboard-with-markdown.sql @@ -3,28 +3,8 @@ A dashboard with Markdown descriptions 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. */ -select - 'card' as "component", - 4 as "columns"; - -select - '**152** sales today' as "description_md", - TRUE as "active", - 'currency-euro' as "icon"; - -select - '**13** new users' as "description_md", - 'user-plus' as "icon", - 'green' as "color"; - -select - '**2** complaints' as "description_md", - 'alert-circle' as "icon", - 'danger' as "color", - '/examples/show_variables.sql?action=view_complaints' as "link", - 'red-lt' as "background_color"; - -select - '**1** pending support request' as "description_md", - 'mail-question' as "icon", - 'warning' as "color"; +select 'card' as component, 3 as columns; +select '**' || count(*) || '** active customers' as description_md, 'users' as icon, + true as active from customers where status = 'Active'; +select '**' || sum(seats) || '** seats' as description_md, 'armchair' as icon from customers; +select '**' || count(*) || '** resolved tickets' as description_md, 'check' as icon from tickets; diff --git a/examples/official-site/reference/components/carousel/01-animal-image-carousel.sql b/examples/official-site/reference/components/carousel/01-animal-image-carousel.sql index a83d9c842..0cb1a6072 100644 --- a/examples/official-site/reference/components/carousel/01-animal-image-carousel.sql +++ b/examples/official-site/reference/components/carousel/01-animal-image-carousel.sql @@ -3,6 +3,7 @@ A basic example of carousel */ select 'carousel' as "component", + true as controls, 'cats1' as "name", 'Famous Database Animals' as "title"; diff --git a/examples/official-site/reference/components/chart/10-timeline-with-links.sql b/examples/official-site/reference/components/chart/10-timeline-with-links.sql index 72862a1cc..1a0f0dcd5 100644 --- a/examples/official-site/reference/components/chart/10-timeline-with-links.sql +++ b/examples/official-site/reference/components/chart/10-timeline-with-links.sql @@ -19,7 +19,7 @@ select 'Operations' as "label", '2021-12-29' as "value", '2022-01-02' as "value", - '/examples/chart.sql?phase=1' as "link"; + '/reference/components/chart/10-timeline-with-links.sql?phase=1' as "link"; select 'Phase 2' as "series", @@ -32,3 +32,6 @@ select 'Maintenance' as "label", '2022-01-01' as "value", '2022-01-03' as "value"; + +select 'text' as component, 'Phase 1: Operations' as title, + 'Prepare the release and verify the backup before Phase 2 starts.' as contents where $phase = '1'; diff --git a/examples/official-site/reference/components/chart/11-color-individual-values.sql b/examples/official-site/reference/components/chart/11-color-individual-values.sql index f392faa0d..88562e46d 100644 --- a/examples/official-site/reference/components/chart/11-color-individual-values.sql +++ b/examples/official-site/reference/components/chart/11-color-individual-values.sql @@ -27,6 +27,8 @@ select TRUE as "labels", FALSE as "show_legend"; -select '30 days' as "label", 100 as "value", 'red' as "color" -union all select '60 days', 200, 'orange' -union all select '90 days', 300, 'green'; +with accounts(days_remaining) as (values (7), (15), (22), (45), (88)), +windows as (select ((days_remaining + 29) / 30) * 30 as days from accounts) +select days || ' days' as label, count(*) as value, + case days when 30 then 'red' when 60 then 'orange' else 'green' end as color +from windows group by days order by days; diff --git a/examples/official-site/reference/components/chart/13-y-axis-reference-lines.sql b/examples/official-site/reference/components/chart/13-y-axis-reference-lines.sql index d0a3919d1..fea53cd0c 100644 --- a/examples/official-site/reference/components/chart/13-y-axis-reference-lines.sql +++ b/examples/official-site/reference/components/chart/13-y-axis-reference-lines.sql @@ -31,21 +31,6 @@ select 'azure' as "color", 4 as "marker"; -select - 70 as "yline", - 'target' as "label", - 'green' as "color"; - -select - 90 as "yline", - 100 as "yline_end", - 'throttling' as "label", - 'red' as "color"; - -select '2024-05-01T08:00:00Z' as "x", 52 as "y" -union all select '2024-05-01T09:00:00Z', 58 -union all select '2024-05-01T10:00:00Z', 71 -union all select '2024-05-01T11:00:00Z', 83 -union all select '2024-05-01T12:00:00Z', 94 -union all select '2024-05-01T13:00:00Z', 76 -union all select '2024-05-01T14:00:00Z', 63; +with thresholds(name, low, high, color) as (values ('target', 70, null, 'green'), ('throttling', 90, 100, 'red')) +select low as yline, high as yline_end, name as label, color from thresholds; +select measured_at as x, temperature as y from demo_readings order by measured_at; diff --git a/examples/official-site/reference/components/chart/14-x-axis-event-markers.sql b/examples/official-site/reference/components/chart/14-x-axis-event-markers.sql index 9b3b2083e..620d84f83 100644 --- a/examples/official-site/reference/components/chart/14-x-axis-event-markers.sql +++ b/examples/official-site/reference/components/chart/14-x-axis-event-markers.sql @@ -4,7 +4,7 @@ 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: +maintenance window. [Show events since noon](/reference/components/chart/14-x-axis-event-markers.sql?since=2024-05-01T12%3A00%3A00Z) to see the earlier annotations disappear. A single query can draw a whole log of events: ```sql select started_at as xline, ended_at as xline_end, summary as label, @@ -24,22 +24,10 @@ select 'blue-lt' as "color", 3 as "marker"; -select - '2024-05-01T10:00:00Z' as "xline", - 'deploy' as "label", - 'green' as "color"; - -select - '2024-05-01T11:30:00Z' as "xline", - '2024-05-01T13:00:00Z' as "xline_end", - 'incident' as "label", - 'red' as "color"; - -select '2024-05-01T08:00:00Z' as "x", 120 as "y" -union all select '2024-05-01T09:00:00Z', 134 -union all select '2024-05-01T10:00:00Z', 128 -union all select '2024-05-01T11:00:00Z', 141 -union all select '2024-05-01T12:00:00Z', 512 -union all select '2024-05-01T13:00:00Z', 470 -union all select '2024-05-01T14:00:00Z', 156 -union all select '2024-05-01T15:00:00Z', 133; +with events(started, ended, summary, severity) as (values + ('2024-05-01T10:00:00Z', null, 'deploy', 'info'), + ('2024-05-01T11:30:00Z', '2024-05-01T13:00:00Z', 'incident', 'outage')) +select started as xline, ended as xline_end, summary as label, + case severity when 'outage' then 'red' else 'green' end as color +from events where started >= coalesce($since, '2024-05-01') order by started; +select measured_at as x, latency_ms as y from demo_readings order by measured_at; diff --git a/examples/official-site/reference/components/chart/15-reference-lines-on-horizontal-bars.sql b/examples/official-site/reference/components/chart/15-reference-lines-on-horizontal-bars.sql index dca222f0a..52b23dfe0 100644 --- a/examples/official-site/reference/components/chart/15-reference-lines-on-horizontal-bars.sql +++ b/examples/official-site/reference/components/chart/15-reference-lines-on-horizontal-bars.sql @@ -26,17 +26,8 @@ select 'azure' as "color", TRUE as "labels"; -select - 90 as "yline", - 'full' as "label", - 'red' as "color"; - -select - 'db-1' as "xline", - 'watched' as "label", - 'purple' as "color"; - -select 'backup-1' as "x", 41 as "y" -union all select 'web-2', 63 -union all select 'db-1', 88 -union all select 'web-1', 96; +select 90 as yline, 'full' as label, 'red' as color; +select 'db-1' as xline, 'watched' as label, 'purple' as color; +with disks(host, used_gb, capacity_gb) as (values ('backup-1', 82, 200), ('web-2', 63, 100), + ('db-1', 440, 500), ('web-1', 48, 50)) +select host as x, round(100.0 * used_gb / capacity_gb) as y from disks order by y; diff --git a/examples/official-site/reference/components/columns/02-tech-company-kpis.sql b/examples/official-site/reference/components/columns/02-tech-company-kpis.sql index f7bd46bdd..b7d478fc3 100644 --- a/examples/official-site/reference/components/columns/02-tech-company-kpis.sql +++ b/examples/official-site/reference/components/columns/02-tech-company-kpis.sql @@ -1,38 +1,10 @@ /* Tech Company KPIs Display */ -select - 'columns' as "component"; - -select - 'Monthly Active Users' as "title", - '10k' as "value", - 'blue' as "value_color", - 4 as "size", - 'Total active users this month, showcasing user engagement.' as "description", - JSON('[{"icon":"target","description":"Target: 12,000"}]') as "item", - '#' as "link", - 'User Activity Overview' as "button_text", - 'info' as "button_color"; - -select - 'Revenue' as "title", - '$49k' as "value", - 'blue' as "value_color", - 4 as "size", - 'Total revenue generated this month, indicating financial performance.' as "description", - JSON('[{"icon":"trending-down","color":"red","description":"down from $51k last month"}]') as "item", - '#' as "link", - 'Financial Dashboard' as "button_text", - 'info' as "button_color"; - -select - 'Customer Satisfaction' as "title", - '94%' as "value", - 'blue' as "value_color", - 4 as "size", - 'Percentage of satisfied customers, reflecting service quality.' as "description", - JSON('[{"icon":"trending-up","color":"green","description":"+ 2% this month"}]') as "item", - '#' as "link", - 'Open Google Ratings' as "button_text", - 'info' as "button_color"; +select 'columns' as component; +select 'Active customers' as title, count(*) as value, 4 as size, + 'Customers on an active plan' as description from customers where status = 'Active'; +select 'Revenue' as title, '$' || sum(amount) as value, 4 as size, + 'Total sample order revenue' as description from demo_orders; +select 'Customer satisfaction' as title, round(100.0 * avg(satisfied)) || '%' as value, 4 as size, + 'Share of positive responses' as description from customer_feedback; diff --git a/examples/official-site/reference/components/cookie/01-set-and-read-a-cookie.md b/examples/official-site/reference/components/cookie/01-set-and-read-a-cookie.md deleted file mode 100644 index e10b2e360..000000000 --- a/examples/official-site/reference/components/cookie/01-set-and-read-a-cookie.md +++ /dev/null @@ -1,17 +0,0 @@ -# Set a cookie and read it on the next request - -Set the cookie before producing any page content: - -```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. -``` - -On a later request, read the value the browser sent with [`sqlpage.cookie`](/functions.sql?function=cookie). Setting a response cookie does not change the current request. - -```sql -SELECT 'text' as component, - 'Your name is ' || COALESCE(sqlpage.cookie('username'), 'not known to us') as contents; -``` diff --git a/examples/official-site/reference/components/cookie/01-set-and-read-a-cookie.standalone.sql b/examples/official-site/reference/components/cookie/01-set-and-read-a-cookie.standalone.sql new file mode 100644 index 000000000..1476229a8 --- /dev/null +++ b/examples/official-site/reference/components/cookie/01-set-and-read-a-cookie.standalone.sql @@ -0,0 +1,14 @@ +/* +Set a cookie and read it on the next request + +Choose a color and submit. The first response sets the cookie and redirects. The next request reads the value your browser sends. +*/ +select 'cookie' as component, 'docs_color' as name, :color as value, false as secure +where :color in ('green', 'blue'); +select 'redirect' as component, '/reference/components/cookie/01-set-and-read-a-cookie.standalone.sql' as link +where :color in ('green', 'blue'); +select 'text' as component, 'Color received from your browser: ' || + coalesce(sqlpage.cookie('docs_color'), '(no cookie yet)') as contents; +select 'form' as component, 'Set cookie and reload' as validate; +select 'select' as type, 'color' as name, 'Favorite color' as label, json_array(json_object('label', 'Green', 'value', 'green'), + json_object('label', 'Blue', 'value', 'blue')) as options; diff --git a/examples/official-site/reference/components/csv/01-csv-download-url.sql b/examples/official-site/reference/components/csv/01-csv-download-url.sql index 861de2b5c..31603f41b 100644 --- a/examples/official-site/reference/components/csv/01-csv-download-url.sql +++ b/examples/official-site/reference/components/csv/01-csv-download-url.sql @@ -9,9 +9,11 @@ This makes it possible to download even very large files without overloading the ```sql select 'csv' as component, 'example.csv' as filename; -SELECT * FROM my_large_table; +SELECT * FROM component; ``` +This endpoint exports the documentation site’s component catalog. Replace `component` with the table or query you want to export. + Link to `csv_download.sql` from a separate page with the button below. Opening the link starts the download without embedding the CSV data in the page that contains the button. */ select 'button' as "component"; diff --git a/examples/official-site/reference/components/csv/02-csv-download-button.sql b/examples/official-site/reference/components/csv/02-csv-download-button.sql index 0a9deaad2..1a291eb1c 100644 --- a/examples/official-site/reference/components/csv/02-csv-download-button.sql +++ b/examples/official-site/reference/components/csv/02-csv-download-button.sql @@ -9,11 +9,10 @@ For smaller files, this is easier and faster to use than creating a separate SQL select 'csv' as "component", 'Download my data' as "title", - 'people' as "filename", + 'customers' as "filename", 'file-download' as "icon", 'green' as "color", ';' as "separator", TRUE as "bom"; -select 'Ophir' as "Forename", 'Lojkine' as "Surname", 'lovasoa' as "Pseudonym" -union all select 'Linus', 'Torvalds', 'torvalds'; +select name as Customer, plan as Plan, seats as Seats from customers order by name; diff --git a/examples/official-site/reference/components/debug/02-inspect-function-result.md b/examples/official-site/reference/components/debug/02-inspect-function-result.md deleted file mode 100644 index ed5106899..000000000 --- a/examples/official-site/reference/components/debug/02-inspect-function-result.md +++ /dev/null @@ -1,7 +0,0 @@ -# Inspect the result of a SQLPage function - -Show the result of a SQLPage function: - -```sql -select 'debug' as component, sqlpage.environment_variable('HOME'); -``` diff --git a/examples/official-site/reference/components/debug/02-inspect-function-result.standalone.sql b/examples/official-site/reference/components/debug/02-inspect-function-result.standalone.sql new file mode 100644 index 000000000..5d618bbce --- /dev/null +++ b/examples/official-site/reference/components/debug/02-inspect-function-result.standalone.sql @@ -0,0 +1,7 @@ +/* +Inspect the result of a SQLPage function + +Open the example to inspect its request path and HTTP method. +*/ +select 'debug' as component, sqlpage.path() as requested_path, + sqlpage.request_method() as method; diff --git a/examples/official-site/reference/components/download/02-pdf-from-server.md b/examples/official-site/reference/components/download/02-pdf-from-server.md deleted file mode 100644 index 1c9ce1fa3..000000000 --- a/examples/official-site/reference/components/download/02-pdf-from-server.md +++ /dev/null @@ -1,11 +0,0 @@ -# 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; -``` diff --git a/examples/official-site/reference/components/download/02-pdf-from-server.standalone.sql b/examples/official-site/reference/components/download/02-pdf-from-server.standalone.sql new file mode 100644 index 000000000..c3011b809 --- /dev/null +++ b/examples/official-site/reference/components/download/02-pdf-from-server.standalone.sql @@ -0,0 +1,7 @@ +/* +Download a PDF file from the server + +Open the demo to download the SQLPage conference slides. Replace the sample path with a file served by your application. +*/ +select 'download' as component, 'SQLPage-talk.pdf' as filename, + sqlpage.read_file_as_data_url('pgconf/2024-sqlpage-badass.pdf') as data_url; diff --git a/examples/official-site/reference/components/download/03-image-from-a-blob.md b/examples/official-site/reference/components/download/03-image-from-a-blob.standalone.sql similarity index 56% rename from examples/official-site/reference/components/download/03-image-from-a-blob.md rename to examples/official-site/reference/components/download/03-image-from-a-blob.standalone.sql index 1670ae3ad..73982b7e4 100644 --- a/examples/official-site/reference/components/download/03-image-from-a-blob.md +++ b/examples/official-site/reference/components/download/03-image-from-a-blob.standalone.sql @@ -1,19 +1,7 @@ -# Serve an image stored as a BLOB in the database +/* +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; -``` +Open the demo to download a one-pixel GIF stored as a BLOB in SQLite. [Try a missing image](/reference/components/download/03-image-from-a-blob.standalone.sql?id=2) to get HTTP 404. ### Customize the mime type @@ -30,3 +18,8 @@ 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. +*/ +set id = coalesce(cast($id as integer), 1); +select 'status_code' as component, 404 as status where not exists (select 1 from demo_images where id = $id); +select 'download' as component, filename, content as data_url from demo_images where id = $id; +select 'text' as component, 'Image not found' as contents where not exists (select 1 from demo_images where id = $id); diff --git a/examples/official-site/reference/components/dynamic/02-read-static-json-file.md b/examples/official-site/reference/components/dynamic/02-read-static-json-file.md deleted file mode 100644 index ece37ba42..000000000 --- a/examples/official-site/reference/components/dynamic/02-read-static-json-file.md +++ /dev/null @@ -1,32 +0,0 @@ -# Static component data 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.sql?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"} - ]} - ] -} -``` diff --git a/examples/official-site/reference/components/dynamic/02-read-static-json-file.standalone.sql b/examples/official-site/reference/components/dynamic/02-read-static-json-file.standalone.sql new file mode 100644 index 000000000..5d82381d3 --- /dev/null +++ b/examples/official-site/reference/components/dynamic/02-read-static-json-file.standalone.sql @@ -0,0 +1,7 @@ +/* +Static component data in JSON files + +Open the demo to load the navigation from [the shared JSON file](/examples/reference/shared-shell.json). Each page can load that same file. +*/ +select 'dynamic' as component, sqlpage.read_file_as_text('examples/reference/shared-shell.json') as properties; +select 'text' as component, 'Follow a menu item to its component reference.' as contents; diff --git a/examples/official-site/reference/components/dynamic/03-include-another-sql-file.md b/examples/official-site/reference/components/dynamic/03-include-another-sql-file.md deleted file mode 100644 index c0c74d0f2..000000000 --- a/examples/official-site/reference/components/dynamic/03-include-another-sql-file.md +++ /dev/null @@ -1,22 +0,0 @@ -# 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; -``` diff --git a/examples/official-site/reference/components/dynamic/03-include-another-sql-file.standalone.sql b/examples/official-site/reference/components/dynamic/03-include-another-sql-file.standalone.sql new file mode 100644 index 000000000..28eb09f7c --- /dev/null +++ b/examples/official-site/reference/components/dynamic/03-include-another-sql-file.standalone.sql @@ -0,0 +1,15 @@ +/* +Including another SQL file + +The parent passes a title to a shared SQL file. The child uses the title and reads component names for its menu. [Visit a second page that includes the same file](/examples/reference/second-page.sql). + +The shared SQL file returns a shell and its menu. Its input title is accessible as `$title`. + +```sql +select 'shell' as component, coalesce($title, 'Catalog') as title, + json_group_array(json_object('title', name, 'link', '/component.sql?component=' || name) order by name) as menu_item +from component where name in ('card', 'chart', 'map'); +``` +*/ +select 'dynamic' as component, sqlpage.run_sql('examples/reference/shared-shell.sql', json_object('title', 'SQL component catalog')) as properties; +select 'text' as component, 'Follow a menu item to its component reference.' as contents; diff --git a/examples/official-site/reference/components/dynamic/04-dynamic-shell.md b/examples/official-site/reference/components/dynamic/04-dynamic-shell.md deleted file mode 100644 index 39632eca6..000000000 --- a/examples/official-site/reference/components/dynamic/04-dynamic-shell.md +++ /dev/null @@ -1,29 +0,0 @@ -# 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.sql?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). diff --git a/examples/official-site/reference/components/dynamic/04-dynamic-shell.standalone.sql b/examples/official-site/reference/components/dynamic/04-dynamic-shell.standalone.sql new file mode 100644 index 000000000..ca3b6e1bf --- /dev/null +++ b/examples/official-site/reference/components/dynamic/04-dynamic-shell.standalone.sql @@ -0,0 +1,9 @@ +/* +Dynamic shell + +The query turns navigation components in the catalog into a menu. Follow any menu item to its reference. +*/ +select 'dynamic' as component, json_object('component', 'shell', 'title', 'Catalog menu', + 'menu_item', json_group_array(json_object('title', name, 'link', '/component.sql?component=' || name) order by name)) as properties +from component where catalog_category = 'navigation'; +select 'text' as component, 'Follow a menu item to its component reference.' as contents; diff --git a/examples/official-site/reference/components/dynamic/05-dynamic-table-columns.md b/examples/official-site/reference/components/dynamic/05-dynamic-table-columns.md deleted file mode 100644 index b31bc5f59..000000000 --- a/examples/official-site/reference/components/dynamic/05-dynamic-table-columns.md +++ /dev/null @@ -1,18 +0,0 @@ -# Dynamic tables - -The `dynamic` component can be used to generate [tables](/component.sql?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; -``` diff --git a/examples/official-site/reference/components/dynamic/05-dynamic-table-columns.sql b/examples/official-site/reference/components/dynamic/05-dynamic-table-columns.sql new file mode 100644 index 000000000..0c239ae51 --- /dev/null +++ b/examples/official-site/reference/components/dynamic/05-dynamic-table-columns.sql @@ -0,0 +1,14 @@ +/* +Dynamic tables + +Choose All columns or Hide Admin. The query groups roles by person and turns them into JSON keys. Those keys become the table headers. +*/ +select 'button' as component; +select 'All columns' as title, '/reference/components/dynamic/05-dynamic-table-columns.sql' as link; +select 'Hide Admin' as title, '/reference/components/dynamic/05-dynamic-table-columns.sql?hide=Admin' as link; + +select 'table' as component; +with facts(person, role, quantity) as (values ('Alice', 'Editor', 1), ('Alice', 'Admin', 0), ('Ben', 'Editor', 0), ('Ben', 'Admin', 1)) +select 'dynamic' as component, json_patch(json_object('Member', person), + json_group_object(role, quantity order by role)) as properties +from facts where $hide is null or role <> $hide group by person order by person; diff --git a/examples/official-site/reference/components/empty_state/01-not-found-message.sql b/examples/official-site/reference/components/empty_state/01-not-found-message.sql index 316897519..a9a470f1d 100644 --- a/examples/official-site/reference/components/empty_state/01-not-found-message.sql +++ b/examples/official-site/reference/components/empty_state/01-not-found-message.sql @@ -1,17 +1,16 @@ /* -Show a not-found message +Search the component catalog -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. +Try “chart” for a match or “spaceship” for an empty result. */ -select - 'empty_state' as "component", - 'No results found' as "title", - '404' as "header", - 'Try adjusting your search or filter to find what you''re looking for.' as "description", - 'Search again' as "link_text", - 'search' as "link_icon", - '#not-found' as "link", - 'not-found' as "id"; +set search = coalesce($search, 'spaceship'); + +select 'form' as component, 'GET' as method, '/reference/components/empty_state/01-not-found-message.sql' as action, 'Search' as validate; +select 'search' as name, 'Component name' as label, $search as value; + +select 'empty_state' as component, 'No results found' as title, + 'Try searching for chart or form.' as description, 'Search again' as link_text, + '/reference/components/empty_state/01-not-found-message.sql?search=' as link, 'search' as link_icon +where not exists (select 1 from component where instr(name, lower($search)) > 0); +select 'list' as component, 'Matching components' as title where exists (select 1 from component where instr(name, lower($search)) > 0); +select name as title, '/component.sql?component=' || name as link from component where instr(name, lower($search)) > 0 order by name; diff --git a/examples/official-site/reference/components/empty_state/02-error-with-illustration.sql b/examples/official-site/reference/components/empty_state/02-error-with-illustration.sql index 698f075cb..498b64896 100644 --- a/examples/official-site/reference/components/empty_state/02-error-with-illustration.sql +++ b/examples/official-site/reference/components/empty_state/02-error-with-illustration.sql @@ -10,6 +10,6 @@ select 'SQLPage can do a lot of things, but this is not one of them. Please restart your browser and **cross your fingers**.' as "description_md", - 'Close and restart' as "link_text", + 'Back to components' as "link_text", 'rotate-clockwise' as "link_icon", - '#' as "link"; + '/components.sql' as "link"; diff --git a/examples/official-site/reference/components/facet/01-category-selector-with-all-link.sql b/examples/official-site/reference/components/facet/01-category-selector-with-all-link.sql index 988cb6c6a..665d5f7bd 100644 --- a/examples/official-site/reference/components/facet/01-category-selector-with-all-link.sql +++ b/examples/official-site/reference/components/facet/01-category-selector-with-all-link.sql @@ -1,26 +1,14 @@ /* -A category selector with an All link +Choose a ship class -A category selector with an All link. In an application, use the selected `class` URL parameter to filter the displayed data. +Select Galaxy to see only Galaxy-class ships. All ships clears the filter. */ -select 'table' as "component"; +select 'facet' as component, 'Ship class' as description, + '/reference/components/facet/01-category-selector-with-all-link.sql' as all_link, 'All ships' as all_title, $class is null as all_active; -select 'USS Enterprise (NCC-1701)' as "name", 'Constitution' as "class" -union all select 'USS Exeter (NCC-1672)', 'Galaxy' -union all select 'USS Exeter (NCC-1672)', 'Constitution'; +select class as title, sqlpage.link('/reference/components/facet/01-category-selector-with-all-link.sql', json_object('class', class)) as link, + class = $class as active +from (select distinct class from demo_ships) as classes order by class; -select - 'facet' as "component", - 'Classes' as "description", - '/component.sql?component=facet' as "all_link", - 'All' as "all_title", - FALSE as "all_active"; - -select - 'Constitution' as "title", - '/component.sql?component=facet&class=Constitution' as "link", - TRUE as "active"; - -select - 'Galaxy' as "title", - '/component.sql?component=facet&class=Galaxy' as "link"; +select 'table' as component; +select name, class from demo_ships where $class is null or class = $class order by name; diff --git a/examples/official-site/reference/components/facet/02-compact-facet-dropdown.sql b/examples/official-site/reference/components/facet/02-compact-facet-dropdown.sql index 4909fc554..9a8864eeb 100644 --- a/examples/official-site/reference/components/facet/02-compact-facet-dropdown.sql +++ b/examples/official-site/reference/components/facet/02-compact-facet-dropdown.sql @@ -1,29 +1,15 @@ /* -A compact facet selector +Choose a ship class from a dropdown -Compact mode displays the facet choices in a dropdown. +Select Galaxy to see only Galaxy-class ships. All ships clears the filter. */ -select 'table' as "component"; +select 'facet' as component, 'Ship class' as description, + '/reference/components/facet/02-compact-facet-dropdown.sql' as all_link, 'All ships' as all_title, $class is null as all_active, + true as compact, 'Ship class' as dropdown_title, coalesce($class, 'All ships') as selected_facet; -select 'USS Enterprise (NCC-1701)' as "name", 'Constitution' as "class" -union all select 'USS Defiant (NCC-1764)', 'Constitution' -union all select 'USS Exeter (NCC-1672)', 'Constitution'; +select class as title, sqlpage.link('/reference/components/facet/02-compact-facet-dropdown.sql', json_object('class', class)) as link, + class = $class as active +from (select distinct class from demo_ships) as classes order by class; -select - 'facet' as "component", - 'Classes' as "description", - '/component.sql?component=facet' as "all_link", - 'All' as "all_title", - FALSE as "all_active", - TRUE as "compact", - 'Select a spaceship class' as "dropdown_title", - 'Constitution' as "selected_facet"; - -select - 'Constitution' as "title", - '/component.sql?component=facet&class=Constitution' as "link", - TRUE as "active"; - -select - 'Galaxy' as "title", - '/component.sql?component=facet&class=Galaxy' as "link"; +select 'table' as component; +select name, class from demo_ships where $class is null or class = $class order by name; diff --git a/examples/official-site/reference/components/form/01-separate-submission-handler.md b/examples/official-site/reference/components/form/01-separate-submission-handler.md index ac4623e03..73074c490 100644 --- a/examples/official-site/reference/components/form/01-separate-submission-handler.md +++ b/examples/official-site/reference/components/form/01-separate-submission-handler.md @@ -1,5 +1,7 @@ # Handle a form submission in a separate file +[Try the form and see your saved entry](/examples/reference/entries.sql). The live demo keeps one entry per browser. The two-file example below shows how to apply the same submit-and-redirect pattern to a users table. + 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, diff --git a/examples/official-site/reference/components/form/06-single-select-field.sql b/examples/official-site/reference/components/form/06-single-select-field.sql index 42dc0feee..2dd3b2aef 100644 --- a/examples/official-site/reference/components/form/06-single-select-field.sql +++ b/examples/official-site/reference/components/form/06-single-select-field.sql @@ -1,27 +1,7 @@ /* A single-select field -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 -``` +The query builds the option labels and values from the fruit table. Submit to inspect the selected ID. */ select 'form' as "component", @@ -31,4 +11,5 @@ select 'Fruit' as "name", 'select' as "type", 'Select a fruit...' as "empty_option", - '[{"label": "Orange", "value": 0}, {"label": "Apple", "value": 1}, {"label": "Banana", "value": 3}]' as "options"; + json_group_array(json_object('label', name, 'value', id) order by name) as options +from demo_fruits; diff --git a/examples/official-site/reference/components/form/08-radio-buttons.sql b/examples/official-site/reference/components/form/08-radio-buttons.sql index 42e48d157..90743f9ab 100644 --- a/examples/official-site/reference/components/form/08-radio-buttons.sql +++ b/examples/official-site/reference/components/form/08-radio-buttons.sql @@ -1,49 +1,13 @@ /* Radio buttons -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; -``` - -Submitting the form opens the reference for the component selected in `$component`. +The catalog supplies the radio options. Each radio has the same field name and a different value. Submit to open the selected component reference. */ select 'form' as "component", '/component.sql' as "action", 'GET' as "method"; -select - 'component' as "name", - 'radio' as "type", - 'form' as "value", - 'Read user input in SQL' as "description", - 'Form' as "label"; - -select - 'component' as "name", - 'radio' as "type", - 'map' as "value", - TRUE as "checked", - 'Display a map based on database data' as "description", - 'Map' as "label"; - -select - 'component' as "name", - 'radio' as "type", - 'chart' as "value", - 'Interactive plots of SQL query results' as "description", - 'Chart' as "label"; +select 'component' as name, 'radio' as type, name as value, name as label, + catalog_summary as description, name = 'map' as checked +from component where name in ('form', 'map', 'chart') order by name; diff --git a/examples/official-site/reference/components/form/10-hidden-field.sql b/examples/official-site/reference/components/form/10-hidden-field.sql index 44c6d3259..cf887df3e 100644 --- a/examples/official-site/reference/components/form/10-hidden-field.sql +++ b/examples/official-site/reference/components/form/10-hidden-field.sql @@ -1,27 +1,12 @@ /* -A hidden field +Submit a hidden record ID -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. +The form sends the project ID along with the visible confirmation. The handler uses that ID to read the project name. */ -select - 'form' as "component", - 'Delete' as "validate", - 'red' as "validate_color"; - -select - 'hidden' as "type", - 'resource_id' as "name", - '1234' as "value"; - -select - 'confirm' as "name", - 'Please type "sensitive resource" here to confirm the deletion' as "label", - TRUE as "required"; +select 'form' as component, '/reference/components/form/10-hidden-field.sql' as action, 'Confirm selection' as validate; +select 'hidden' as type, 'project_id' as name, id as value from demo_projects order by id limit 1; +select 'text' as type, 'confirmation' as name, 'Type confirm to select the project' as label, true as required; +select 'alert' as component, 'Selected project: ' || name as title from demo_projects +where id = cast(:project_id as integer) and :confirmation = 'confirm'; +select 'alert' as component, 'Type confirm and submit again.' as title +where :confirmation is not null and :confirmation <> 'confirm'; diff --git a/examples/official-site/reference/components/http_header/02-redirect-with-location.md b/examples/official-site/reference/components/http_header/02-redirect-with-location.md deleted file mode 100644 index ee1269c83..000000000 --- a/examples/official-site/reference/components/http_header/02-redirect-with-location.md +++ /dev/null @@ -1,10 +0,0 @@ -# Redirect with a Location 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. - -```sql -select - 'http_header' as "component", - '/another-page.sql' as "Location"; -``` diff --git a/examples/official-site/reference/components/http_header/02-redirect-with-location.standalone.sql b/examples/official-site/reference/components/http_header/02-redirect-with-location.standalone.sql new file mode 100644 index 000000000..40cacde50 --- /dev/null +++ b/examples/official-site/reference/components/http_header/02-redirect-with-location.standalone.sql @@ -0,0 +1,6 @@ +/* +Redirect with a Location header + +Opening the demo sends a Location header. The browser follows it to the component catalog. Inspect the first response in your browser’s Network panel. +*/ +select 'http_header' as component, '/components.sql' as "Location"; diff --git a/examples/official-site/reference/components/json/01-query-results-as-json-array.md b/examples/official-site/reference/components/json/01-query-results-as-json-array.md deleted file mode 100644 index 738b081aa..000000000 --- a/examples/official-site/reference/components/json/01-query-results-as-json-array.md +++ /dev/null @@ -1,30 +0,0 @@ -# Send query results as a single JSON array - -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 -``` diff --git a/examples/official-site/reference/components/json/01-query-results-as-json-array.standalone.sql b/examples/official-site/reference/components/json/01-query-results-as-json-array.standalone.sql new file mode 100644 index 000000000..9a92e53b6 --- /dev/null +++ b/examples/official-site/reference/components/json/01-query-results-as-json-array.standalone.sql @@ -0,0 +1,13 @@ +/* +Send query results as a single JSON array + +Open the demo to get a JSON array containing one object per customer. Select only the columns you want clients to receive. + +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 +``` +*/ +select 'json' as component; +select id, name, plan from customers order by id; diff --git a/examples/official-site/reference/components/json/02-one-json-object-per-row.md b/examples/official-site/reference/components/json/02-one-json-object-per-row.md deleted file mode 100644 index e2aecb5d9..000000000 --- a/examples/official-site/reference/components/json/02-one-json-object-per-row.md +++ /dev/null @@ -1,30 +0,0 @@ -# Send one JSON object per row - -In `jsonlines` mode, each query result is rendered as a JSON object in a separate line, -without a top-level array. - -If there are no rows, the response body is empty. If there is a single row, the response is a 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 } -``` diff --git a/examples/official-site/reference/components/json/02-one-json-object-per-row.standalone.sql b/examples/official-site/reference/components/json/02-one-json-object-per-row.standalone.sql new file mode 100644 index 000000000..4d05f41aa --- /dev/null +++ b/examples/official-site/reference/components/json/02-one-json-object-per-row.standalone.sql @@ -0,0 +1,8 @@ +/* +Send one JSON object per row + +Open the demo for all customers, or [request customer 2](/reference/components/json/02-one-json-object-per-row.standalone.sql?id=2). Each matching row becomes one line. An unknown ID produces an empty body. +*/ +select 'json' as component, 'jsonlines' as type; +select id, name, plan from customers +where $id is null or id = cast($id as integer) order by id; diff --git a/examples/official-site/reference/components/json/03-nested-api-response.md b/examples/official-site/reference/components/json/03-nested-api-response.md deleted file mode 100644 index aa186b67a..000000000 --- a/examples/official-site/reference/components/json/03-nested-api-response.md +++ /dev/null @@ -1,42 +0,0 @@ -# Create a complex API endpoint - -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. diff --git a/examples/official-site/reference/components/json/03-nested-api-response.standalone.sql b/examples/official-site/reference/components/json/03-nested-api-response.standalone.sql new file mode 100644 index 000000000..4acb3305c --- /dev/null +++ b/examples/official-site/reference/components/json/03-nested-api-response.standalone.sql @@ -0,0 +1,10 @@ +/* +Create a complex API endpoint + +Open the demo to see a single object with a `customers` array. The database builds the nested JSON value. + +Use `json_group_array` on SQLite, `json_agg` on PostgreSQL, `JSON_ARRAYAGG` on MySQL or `FOR JSON PATH` on SQL Server to aggregate rows. +*/ +select 'json' as component, json_object('customers', + json_group_array(json_object('id', id, 'name', name, 'plan', plan) order by id)) as contents +from customers; diff --git a/examples/official-site/reference/components/json/04-stream-server-sent-events.md b/examples/official-site/reference/components/json/04-stream-server-sent-events.md deleted file mode 100644 index ee766afd5..000000000 --- a/examples/official-site/reference/components/json/04-stream-server-sent-events.md +++ /dev/null @@ -1,25 +0,0 @@ -# Stream query results with server-sent events - -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/reference/components/json/04-stream-server-sent-events.standalone.sql b/examples/official-site/reference/components/json/04-stream-server-sent-events.standalone.sql new file mode 100644 index 000000000..b91c7a2d6 --- /dev/null +++ b/examples/official-site/reference/components/json/04-stream-server-sent-events.standalone.sql @@ -0,0 +1,15 @@ +/* +Stream query results with server-sent events + +[Watch the customer names arrive in a browser](/examples/reference/events.sql), or open the demo to inspect the raw stream. Each customer produces one event. The browser demo closes the EventSource when the response ends. + +In a browser, handle each row as a message. Close the connection when the finite query ends to prevent automatic reconnection. + +```javascript +const stream = new EventSource('/reference/components/json/04-stream-server-sent-events.standalone.sql'); +stream.onmessage = event => console.log(JSON.parse(event.data).name); +stream.onerror = () => stream.close(); +``` +*/ +select 'json' as component, 'sse' as type; +select id, name from customers order by id; diff --git a/examples/official-site/reference/components/list/02-clickable-empty-state.sql b/examples/official-site/reference/components/list/02-clickable-empty-state.sql index 42d20e9ce..c9c06e4c6 100644 --- a/examples/official-site/reference/components/list/02-clickable-empty-state.sql +++ b/examples/official-site/reference/components/list/02-clickable-empty-state.sql @@ -3,8 +3,6 @@ A clickable empty state The empty state appears when the query after `select 'list' as component` returns no rows. `empty_link` makes that state clickable. */ -select - 'list' as "component", - 'No items yet' as "empty_title", - 'This list is empty. Click here to create a new item !' as "empty_description", - '/documentation.sql' as "empty_link"; +select 'list' as component, 'Your sample entry' as title, 'No entry yet' as empty_title, + 'Click to create your first entry.' as empty_description, '/examples/reference/entries.sql' as empty_link; +select name as title, '/examples/reference/entries.sql' as link from demo_entries where token = sqlpage.cookie('docs_entry'); diff --git a/examples/official-site/reference/components/list/04-actions-icons-and-colors.sql b/examples/official-site/reference/components/list/04-actions-icons-and-colors.sql index 3d5552067..d474edf1c 100644 --- a/examples/official-site/reference/components/list/04-actions-icons-and-colors.sql +++ b/examples/official-site/reference/components/list/04-actions-icons-and-colors.sql @@ -1,34 +1,12 @@ /* -A list with action links, icons, and colors -*/ -select - 'list' as "component", - 'Top SQLPage features' as "title", - TRUE as "compact"; - -select - 'Authentication' as "title", - '/component.sql?component=authentication' as "link", - 'Authenticate users with a login form or HTTP basic authentication' as "description", - 'red' as "color", - 'lock' as "icon", - TRUE as "active", - '/component.sql?component=authentication#component' as "view_link"; +A list with project actions -select - 'Editing data' as "title", - '/component.sql?component=form' as "link", - 'SQLPage makes it easy to UPDATE, INSERT and DELETE data in your database tables' as "description", - 'blue' as "color", - 'database' as "icon", - '/examples/show_variables.sql?action=edit&feature=form' as "edit_link", - '/examples/show_variables.sql?action=delete&feature=form' as "delete_link"; - -select - 'API' as "title", - '/component.sql?component=json' as "link", - 'Generate a REST API from a single SQL query to connect with other applications and services' as "description", - 'green' as "color", - 'plug-connected' as "icon", - '/examples/show_variables.sql?action=edit&feature=json' as "edit_link", - '/examples/show_variables.sql?action=delete&feature=json' as "delete_link"; +View a project or follow an action and confirm it. Changes belong to this browser. +*/ +set states = case when json_valid(sqlpage.cookie('docs_projects')) then sqlpage.cookie('docs_projects') else '{}' end; +select 'list' as component, 'Sample projects' as title, true as compact; +select name as title, coalesce(json_extract($states, '$."' || id || '"'), initial_status) as description, + '/examples/reference/record.sql?id=' || id as view_link, + '/examples/reference/record.sql?action=edit&id=' || id as edit_link, + '/examples/reference/record.sql?action=delete&id=' || id as delete_link, 'folder' as icon +from demo_projects order by id; diff --git a/examples/official-site/reference/components/log/01-write-to-server-log.md b/examples/official-site/reference/components/log/01-write-to-server-log.md deleted file mode 100644 index cb93fafac..000000000 --- a/examples/official-site/reference/components/log/01-write-to-server-log.md +++ /dev/null @@ -1,41 +0,0 @@ -# Write to the server 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/reference/components/log/01-write-to-server-log.standalone.sql b/examples/official-site/reference/components/log/01-write-to-server-log.standalone.sql new file mode 100644 index 000000000..f559ac002 --- /dev/null +++ b/examples/official-site/reference/components/log/01-write-to-server-log.standalone.sql @@ -0,0 +1,8 @@ +/* +Write to the server log + +Open the demo to write one message. The page shows its exact text. If you run SQLPage locally, find the matching entry in your terminal. +*/ +set message = 'Documentation demo ' || sqlpage.random_string(8) || ' at ' || current_timestamp; +select 'log' as component, 'info' as level, $message as message; +select 'text' as component, 'Message sent to the server log' as title, $message as contents; diff --git a/examples/official-site/reference/components/login/01-login-form-with-remember-me.sql b/examples/official-site/reference/components/login/01-login-form-with-remember-me.sql index 8ad411895..6d0d538a6 100644 --- a/examples/official-site/reference/components/login/01-login-form-with-remember-me.sql +++ b/examples/official-site/reference/components/login/01-login-form-with-remember-me.sql @@ -1,15 +1,11 @@ /* -Using the main options of the login component +Sign in and remember the session -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 +Sign in with the sample username `user` and password `user`. The protected page shows the account role and a sign-out link. */ select 'login' as "component", - '/examples/show_variables.sql' as "action", + '/examples/authentication/create_session_token.sql' as "action", '/assets/icon.webp' as "image", 'Please login to your account' as "title", 'Username' as "username", @@ -17,8 +13,5 @@ select FALSE as "autofocus", 'user' as "username_icon", 'lock' as "password_icon", - 'Forgot your password?' as "forgot_password_text", - '/examples/show_variables.sql?action=reset_password' as "forgot_password_link", - 'Remember me' as "remember_me_text", - 'Don''t have an account? [Register here](/examples/show_variables.sql?action=register)' as "footer_md", - 'Sign in' as "validate"; + 'Remember me for one day' as remember_me_text, + 'Try **user** / **user** or **admin** / **admin**.' as footer_md, 'Sign in' as validate; diff --git a/examples/official-site/reference/components/login/02-basic-login-form.sql b/examples/official-site/reference/components/login/02-basic-login-form.sql index d372ccb01..ae184e5f4 100644 --- a/examples/official-site/reference/components/login/02-basic-login-form.sql +++ b/examples/official-site/reference/components/login/02-basic-login-form.sql @@ -1,8 +1,12 @@ /* Basic login form + +Sign in with the sample username `user` and password `user`. The protected page shows the account role and a sign-out link. */ select 'login' as "component", + '/examples/authentication/create_session_token.sql' as action, + 'Try user / user' as title, 'Username' as "username", 'Password' as "password", FALSE as "autofocus"; diff --git a/examples/official-site/reference/components/map/02-geojson-and-custom-tiles.sql b/examples/official-site/reference/components/map/02-geojson-and-custom-tiles.sql index ccb9d9e3f..475b9d375 100644 --- a/examples/official-site/reference/components/map/02-geojson-and-custom-tiles.sql +++ b/examples/official-site/reference/components/map/02-geojson-and-custom-tiles.sql @@ -20,11 +20,13 @@ select 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png' as "tile_source", '' as "attribution"; +with places(place, longitude, latitude) as (values ('Mvezo, Birth Place of Nelson Mandela', 28.49, -31.96)) select 'peace' as "icon", 20 as "size", 'https://en.wikipedia.org/wiki/Nelson_Mandela' as "link", - '{"type":"Feature", "properties": { "title":"Mvezo, Birth Place of Nelson Mandela" }, "geometry": { "type":"Point", "coordinates": [28.49, -31.96] }}' as "geojson"; + json_object('type', 'Feature', 'properties', json_object('title', place), + 'geometry', json_object('type', 'Point', 'coordinates', json_array(longitude, latitude))) as "geojson" from places; select 'text' as "component", diff --git a/examples/official-site/reference/components/map/03-links-and-rich-descriptions.sql b/examples/official-site/reference/components/map/03-links-and-rich-descriptions.sql index a4470112c..3c1b44f96 100644 --- a/examples/official-site/reference/components/map/03-links-and-rich-descriptions.sql +++ b/examples/official-site/reference/components/map/03-links-and-rich-descriptions.sql @@ -3,17 +3,13 @@ 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/). */ select 'map' as "component", 'Paris' as "title", 13 as "zoom", 48.85 as "latitude", - 2.34 as "longitude", - 'https://api.maptiler.com/maps/streets-v2/{z}/{x}/{y}.png?key=RwoF6Y3gcKx4OBMbvqOY' as "tile_source"; + 2.34 as "longitude"; select 'Notre Dame' as "title", diff --git a/examples/official-site/reference/components/map/04-geometric-shapes-without-tiles.sql b/examples/official-site/reference/components/map/04-geometric-shapes-without-tiles.sql index b012af14c..39256ce60 100644 --- a/examples/official-site/reference/components/map/04-geometric-shapes-without-tiles.sql +++ b/examples/official-site/reference/components/map/04-geometric-shapes-without-tiles.sql @@ -15,8 +15,10 @@ select 'This literal red square is defined as a GeoJSON polygon. Each (x,y) coordinate is a JSON array.' as "description", JSON('{"type":"Polygon","coordinates":[[[0,0],[0,4],[4,4],[4,0],[0,0]]]}') as "geojson"; +with vertices(position, x, y) as (values (1, 5, 0), (2, 9, 0), (3, 7, 4), (4, 5, 0)) select 'SQLite' as "title", 'blue' as "color", 'This 2D shape was generated by a SQL query.' as "description", - JSON('{"type":"Polygon","coordinates":[[[5,0],[9,0],[7,4],[5,0]]]}') as "geojson"; + json_object('type', 'Polygon', 'coordinates', + json_array(json_group_array(json_array(x, y) order by position))) as geojson from vertices; diff --git a/examples/official-site/reference/components/modal/03-open-embedded-chart-from-datagrid.sql b/examples/official-site/reference/components/modal/03-open-embedded-chart-from-datagrid.sql index 2615cbeb2..332e9b23a 100644 --- a/examples/official-site/reference/components/modal/03-open-embedded-chart-from-datagrid.sql +++ b/examples/official-site/reference/components/modal/03-open-embedded-chart-from-datagrid.sql @@ -6,7 +6,7 @@ A popup modal that contains a chart generated by a separate SQL file. The modal select 'modal' as "component", 'my_embed_chart_modal' as "id", - 'Embeded chart content' as "title", + 'Embedded chart content' as "title", 'Close' as "close", '/examples/chart.sql?_sqlpage_embed' as "embed"; diff --git a/examples/official-site/reference/components/modal/04-embed-a-video.sql b/examples/official-site/reference/components/modal/04-embed-a-video.sql index abcbd2797..b8904552d 100644 --- a/examples/official-site/reference/components/modal/04-embed-a-video.sql +++ b/examples/official-site/reference/components/modal/04-embed-a-video.sql @@ -4,7 +4,7 @@ Example of modal video content select 'modal' as "component", 'my_embed_video_modal' as "id", - 'Embeded video content' as "title", + 'Embedded video content' as "title", 'Close' as "close", 'https://www.youtube.com/embed/mXdgmSdaXkg' as "embed", 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share' as "allow", diff --git a/examples/official-site/reference/components/pagination/01-page-numbers.sql b/examples/official-site/reference/components/pagination/01-page-numbers.sql index 135edf49a..94169cdb7 100644 --- a/examples/official-site/reference/components/pagination/01-page-numbers.sql +++ b/examples/official-site/reference/components/pagination/01-page-numbers.sql @@ -1,14 +1,20 @@ /* Basic page numbers -This is an extremely simple example of a pagination component that displays only the page numbers, with the first page being the current page. +Choose a page to see its component names. The query orders the catalog by name before taking a page. */ -select 'pagination' as "component"; +set example_url = '/reference/components/pagination/01-page-numbers.sql'; +set page_size = 15; +set last_page = (select (count(*) + $page_size - 1) / $page_size from component); +set page = min(cast($last_page as integer), max(1, coalesce(cast($page as integer), 1))); -select - 1 as "contents", - '/component.sql?component=pagination&page=1' as "link", - TRUE as "active"; +select 'pagination' as component; +with recursive pages(n) as ( + select 1 union all select n + 1 from pages where n < cast($last_page as integer) +) +select n as contents, $example_url || '?page=' || n as link, n = cast($page as integer) as active +from pages order by n; -select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" -union all select 3, '/component.sql?component=pagination&page=3'; +select 'table' as component; +select name as Component from component order by name +limit cast($page_size as integer) offset (($page - 1) * $page_size); diff --git a/examples/official-site/reference/components/pagination/02-outlined-links.sql b/examples/official-site/reference/components/pagination/02-outlined-links.sql index 110a61462..57178e0ed 100644 --- a/examples/official-site/reference/components/pagination/02-outlined-links.sql +++ b/examples/official-site/reference/components/pagination/02-outlined-links.sql @@ -1,16 +1,20 @@ /* Outlined pagination links -The outline style adds a rectangular border to each navigation link. +Choose a page to see its component names. The query orders the catalog by name before taking a page. */ -select - 'pagination' as "component", - TRUE as "outline"; +set example_url = '/reference/components/pagination/02-outlined-links.sql'; +set page_size = 15; +set last_page = (select (count(*) + $page_size - 1) / $page_size from component); +set page = min(cast($last_page as integer), max(1, coalesce(cast($page as integer), 1))); -select - 1 as "contents", - '/component.sql?component=pagination&page=1' as "link", - TRUE as "active"; +select 'pagination' as component, true as outline; +with recursive pages(n) as ( + select 1 union all select n + 1 from pages where n < cast($last_page as integer) +) +select n as contents, $example_url || '?page=' || n as link, n = cast($page as integer) as active +from pages order by n; -select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" -union all select 3, '/component.sql?component=pagination&page=3'; +select 'table' as component; +select name as Component from component order by name +limit cast($page_size as integer) offset (($page - 1) * $page_size); diff --git a/examples/official-site/reference/components/pagination/03-circular-links.sql b/examples/official-site/reference/components/pagination/03-circular-links.sql index 116ab6162..78cb3716f 100644 --- a/examples/official-site/reference/components/pagination/03-circular-links.sql +++ b/examples/official-site/reference/components/pagination/03-circular-links.sql @@ -1,16 +1,20 @@ /* Circular pagination links -The circle style adds a circular border to each navigation link. +Choose a page to see its component names. The query orders the catalog by name before taking a page. */ -select - 'pagination' as "component", - TRUE as "circle"; +set example_url = '/reference/components/pagination/03-circular-links.sql'; +set page_size = 15; +set last_page = (select (count(*) + $page_size - 1) / $page_size from component); +set page = min(cast($last_page as integer), max(1, coalesce(cast($page as integer), 1))); -select - 1 as "contents", - '/component.sql?component=pagination&page=1' as "link", - TRUE as "active"; +select 'pagination' as component, true as circle; +with recursive pages(n) as ( + select 1 union all select n + 1 from pages where n < cast($last_page as integer) +) +select n as contents, $example_url || '?page=' || n as link, n = cast($page as integer) as active +from pages order by n; -select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" -union all select 3, '/component.sql?component=pagination&page=3'; +select 'table' as component; +select name as Component from component order by name +limit cast($page_size as integer) offset (($page - 1) * $page_size); diff --git a/examples/official-site/reference/components/pagination/04-disabled-navigation-links.sql b/examples/official-site/reference/components/pagination/04-disabled-navigation-links.sql index 98be67f49..cafed3f51 100644 --- a/examples/official-site/reference/components/pagination/04-disabled-navigation-links.sql +++ b/examples/official-site/reference/components/pagination/04-disabled-navigation-links.sql @@ -1,21 +1,24 @@ /* Disabled navigation links -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. +Choose a page to see its component names. The query orders the catalog by name before taking a page. */ -select - 'pagination' as "component", - '/component.sql?component=pagination' as "first_link", - TRUE as "first_disabled", - '/component.sql?component=pagination' as "previous_link", - TRUE as "previous_disabled", - '/component.sql?component=pagination&page=2#example-4' as "next_link", - '/component.sql?component=pagination&page=3#example-4' as "last_link"; +set example_url = '/reference/components/pagination/04-disabled-navigation-links.sql'; +set page_size = 15; +set last_page = (select (count(*) + $page_size - 1) / $page_size from component); +set page = min(cast($last_page as integer), max(1, coalesce(cast($page as integer), 1))); -select - 1 as "contents", - '/component.sql?component=pagination&page=1' as "link", - TRUE as "active"; +select 'pagination' as component, + $example_url || '?page=1' as first_link, cast($page as integer) = 1 as first_disabled, + $example_url || '?page=' || max(1, $page - 1) as previous_link, cast($page as integer) = 1 as previous_disabled, + $example_url || '?page=' || min(cast($last_page as integer), $page + 1) as next_link, $page = $last_page as next_disabled, + $example_url || '?page=' || $last_page as last_link, $page = $last_page as last_disabled; +with recursive pages(n) as ( + select 1 union all select n + 1 from pages where n < cast($last_page as integer) +) +select n as contents, $example_url || '?page=' || n as link, n = cast($page as integer) as active +from pages order by n; -select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" -union all select 3, '/component.sql?component=pagination&page=3'; +select 'table' as component; +select name as Component from component order by name +limit cast($page_size as integer) offset (($page - 1) * $page_size); diff --git a/examples/official-site/reference/components/pagination/05-text-navigation-labels.sql b/examples/official-site/reference/components/pagination/05-text-navigation-labels.sql index 82b8287ca..f6a559d81 100644 --- a/examples/official-site/reference/components/pagination/05-text-navigation-labels.sql +++ b/examples/official-site/reference/components/pagination/05-text-navigation-labels.sql @@ -1,25 +1,24 @@ /* Navigation links with text labels -Instead of using icons, you can apply text to the navigation links. +Choose a page to see its component names. The query orders the catalog by name before taking a page. */ -select - 'pagination' as "component", - 'First' as "first_title", - 'Last' as "last_title", - 'Previous' as "previous_title", - 'Next' as "next_title", - '/component.sql?component=pagination' as "first_link", - TRUE as "first_disabled", - '/component.sql?component=pagination' as "previous_link", - TRUE as "previous_disabled", - '/component.sql?component=pagination&page=2#example-5' as "next_link", - '/component.sql?component=pagination&page=3#example-5' as "last_link"; +set example_url = '/reference/components/pagination/05-text-navigation-labels.sql'; +set page_size = 15; +set last_page = (select (count(*) + $page_size - 1) / $page_size from component); +set page = min(cast($last_page as integer), max(1, coalesce(cast($page as integer), 1))); -select - 1 as "contents", - '/component.sql?component=pagination&page=1' as "link", - TRUE as "active"; +select 'pagination' as component, 'First' as first_title, 'Previous' as previous_title, 'Next' as next_title, 'Last' as last_title, + $example_url || '?page=1' as first_link, cast($page as integer) = 1 as first_disabled, + $example_url || '?page=' || max(1, $page - 1) as previous_link, cast($page as integer) = 1 as previous_disabled, + $example_url || '?page=' || min(cast($last_page as integer), $page + 1) as next_link, $page = $last_page as next_disabled, + $example_url || '?page=' || $last_page as last_link, $page = $last_page as last_disabled; +with recursive pages(n) as ( + select 1 union all select n + 1 from pages where n < cast($last_page as integer) +) +select n as contents, $example_url || '?page=' || n as link, n = cast($page as integer) as active +from pages order by n; -select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" -union all select 3, '/component.sql?component=pagination&page=3'; +select 'table' as component; +select name as Component from component order by name +limit cast($page_size as integer) offset (($page - 1) * $page_size); diff --git a/examples/official-site/reference/components/pagination/06-pagination-with-offset.sql b/examples/official-site/reference/components/pagination/06-pagination-with-offset.sql index 846352cf4..7c883e979 100644 --- a/examples/official-site/reference/components/pagination/06-pagination-with-offset.sql +++ b/examples/official-site/reference/components/pagination/06-pagination-with-offset.sql @@ -1,29 +1,26 @@ /* Pagination with an offset -If you have a large number of pages to display, you can use an offset to represent a group of pages. +Choose a page to see its component names. The query orders the catalog by name before taking a page. */ -select - 'pagination' as "component", - '/component.sql?component=pagination&page=1#example-6' as "first_link", - '/component.sql?component=pagination&page=3#example-6' as "previous_link", - '/component.sql?component=pagination&page=5#example-6' as "next_link", - '/component.sql?component=pagination&page=99#example-6' as "last_link"; +set example_url = '/reference/components/pagination/06-pagination-with-offset.sql'; +set page_size = 1; +set last_page = (select (count(*) + $page_size - 1) / $page_size from component); +set page = min(cast($last_page as integer), max(1, coalesce(cast($page as integer), 1))); -select 1 as "contents", '/component.sql?component=pagination&page=1' as "link" -union all select 2, '/component.sql?component=pagination&page=2' -union all select 3, '/component.sql?component=pagination&page=3'; +select 'pagination' as component, + $example_url || '?page=1' as first_link, cast($page as integer) = 1 as first_disabled, + $example_url || '?page=' || max(1, $page - 1) as previous_link, cast($page as integer) = 1 as previous_disabled, + $example_url || '?page=' || min(cast($last_page as integer), $page + 1) as next_link, $page = $last_page as next_disabled, + $example_url || '?page=' || $last_page as last_link, $page = $last_page as last_disabled; +with recursive pages(n) as ( + select 1 union all select n + 1 from pages where n < cast($last_page as integer) +) +select n as contents, $example_url || '?page=' || n as link, n = cast($page as integer) as active, + n > 1 and n < cast($last_page as integer) and abs(n - $page) = 2 as offset +from pages +where n in (1, cast($last_page as integer)) or abs(n - $page) <= 2 order by n; -select - 4 as "contents", - '/component.sql?component=pagination&page=4' as "link", - TRUE as "active"; - -select 5 as "contents", '/component.sql?component=pagination&page=5' as "link" -union all select 6, '/component.sql?component=pagination&page=6'; - -select TRUE as "offset"; - -select - 99 as "contents", - '/component.sql?component=pagination&page=99' as "link"; +select 'table' as component; +select name as Component from component order by name +limit cast($page_size as integer) offset (($page - 1) * $page_size); diff --git a/examples/official-site/reference/components/redirect/01-redirect-to-login.md b/examples/official-site/reference/components/redirect/01-redirect-to-login.md deleted file mode 100644 index 3a0b2fb91..000000000 --- a/examples/official-site/reference/components/redirect/01-redirect-to-login.md +++ /dev/null @@ -1,8 +0,0 @@ -# Redirect a user to the login page - -Redirect a user to the login page if they are not logged in: - -```sql -SELECT 'redirect' AS component, 'login.sql' AS link -WHERE NOT EXISTS (SELECT 1 FROM login_session WHERE id = sqlpage.cookie('session_id')); -``` diff --git a/examples/official-site/reference/components/redirect/01-redirect-to-login.standalone.sql b/examples/official-site/reference/components/redirect/01-redirect-to-login.standalone.sql new file mode 100644 index 000000000..ef1366be7 --- /dev/null +++ b/examples/official-site/reference/components/redirect/01-redirect-to-login.standalone.sql @@ -0,0 +1,10 @@ +/* +Redirect a user to the login page + +Open the page before and after signing in with demo credentials `user` / `user`. +*/ +select 'redirect' as component, '/examples/authentication/login.sql' as link +where not exists (select 1 from user_sessions where session_token = sqlpage.cookie('session_token') + and created_at >= datetime('now', '-1 day')); +select 'text' as component, 'You have a current session.' as contents; +select 'Sign out' as contents, '/examples/authentication/logout.sql' as link; diff --git a/examples/official-site/reference/components/rss/01-sqlpage-news-feed.standalone.sql b/examples/official-site/reference/components/rss/01-sqlpage-news-feed.standalone.sql index 4458f33cf..111fc3328 100644 --- a/examples/official-site/reference/components/rss/01-sqlpage-news-feed.standalone.sql +++ b/examples/official-site/reference/components/rss/01-sqlpage-news-feed.standalone.sql @@ -1,30 +1,27 @@ /* An RSS channel for SQLPage news -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/)... +Open the feed to see recent blog posts, newest first. Each query row supplies one RSS item. A feed reader can subscribe to this example’s URL. */ -select 'http_header' as component, 'application/rss+xml' as "Content-Type"; +select 'http_header' as component, + 'application/rss+xml; charset=utf-8' 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, - 'https://sql-page.com/sqlpage_introduction_video.mp4' as enclosure_url, - 123456789 as enclosure_length, - 'video/mp4' as enclosure_type, - '2023-12-04' as date; +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, + 'https://sql-page.com/rss.sql' as self_link, + 'Technology' as category, + 'https://github.com/sponsors/lovasoa' as funding_url, + '2de3f968-9928-5ec6-9653-6fc6fe382cfd' as guid; +SELECT title, + description, + CASE + WHEN external_url IS NOT NULL THEN external_url + ELSE 'https://sql-page.com/blog.sql?post=' || title + END AS link, + created_at AS date, + false AS explicit +FROM blog_posts +ORDER BY created_at DESC; diff --git a/examples/official-site/reference/components/shell/02-highlight-active-menu-item.standalone.sql b/examples/official-site/reference/components/shell/02-highlight-active-menu-item.standalone.sql index 2d649e637..d7dcbaed7 100644 --- a/examples/official-site/reference/components/shell/02-highlight-active-menu-item.standalone.sql +++ b/examples/official-site/reference/components/shell/02-highlight-active-menu-item.standalone.sql @@ -1,14 +1,12 @@ /* -Highlight an active menu item +Highlight the current menu item -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. +Choose About or Home to move the highlight. */ -select - 'shell' as "component", - 'SQLPage: SQL websites' as "title", - 'database' as "icon", - '/' as "link", - JSON('{"title":"Home","active":true}') as "menu_item", - JSON('{"title":"About"}') as "menu_item"; +set page = case when $page = 'About' then 'About' else 'Home' end; +select 'shell' as component, 'Navigation example' as title, + json_object('title', 'Home', 'link', '/reference/components/shell/02-highlight-active-menu-item.standalone.sql?page=Home', + 'active', json(iif($page = 'Home', 'true', 'false'))) as menu_item, + json_object('title', 'About', 'link', '/reference/components/shell/02-highlight-active-menu-item.standalone.sql?page=About', + 'active', json(iif($page = 'About', 'true', 'false'))) as menu_item; +select 'title' as component, $page as contents; diff --git a/examples/official-site/reference/components/shell/03-share-shell-across-pages.md b/examples/official-site/reference/components/shell/03-share-shell-across-pages.md index 0a6f49c0e..6abd13886 100644 --- a/examples/official-site/reference/components/shell/03-share-shell-across-pages.md +++ b/examples/official-site/reference/components/shell/03-share-shell-across-pages.md @@ -1,5 +1,7 @@ # Sharing the shell between multiple pages +[Open a page that shares its navigation with the SQL include example](/examples/reference/second-page.sql). + It is common to want to share the same shell between multiple pages. #### Static menu diff --git a/examples/official-site/reference/components/status_bar/01-query-workspace-status-bar.sql b/examples/official-site/reference/components/status_bar/01-query-workspace-status-bar.sql index 837e2f934..38dd0514c 100644 --- a/examples/official-site/reference/components/status_bar/01-query-workspace-status-bar.sql +++ b/examples/official-site/reference/components/status_bar/01-query-workspace-status-bar.sql @@ -3,20 +3,9 @@ A query workspace 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. */ -select - 'status_bar' as "component", - 'Query status' as "label", - FALSE as "fixed"; - -select - 'Connected' as "title", - 'database' as "icon", - 'green' as "color", - 'Connected to the reporting database' as "tooltip"; - -select '24 rows' as "title"; - -select - 'SQL functions' as "title", - 'book' as "icon", - '/functions.sql' as "link"; +select 'table' as component; +select name, plan from customers order by name; +select 'status_bar' as component, false as fixed, 'Query status' as label; +select 'Connected' as title, 'database' as icon, 'green' as color; +select count(*) || ' rows' as title from customers; +select 'SQL functions' as title, 'book' as icon, '/functions.sql' as link; diff --git a/examples/official-site/reference/components/status_code/01-return-http-404.md b/examples/official-site/reference/components/status_code/01-return-http-404.md deleted file mode 100644 index 4c018db94..000000000 --- a/examples/official-site/reference/components/status_code/01-return-http-404.md +++ /dev/null @@ -1,8 +0,0 @@ -# Return an HTTP 404 status - -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/reference/components/status_code/01-return-http-404.standalone.sql b/examples/official-site/reference/components/status_code/01-return-http-404.standalone.sql new file mode 100644 index 000000000..7bdd256af --- /dev/null +++ b/examples/official-site/reference/components/status_code/01-return-http-404.standalone.sql @@ -0,0 +1,8 @@ +/* +Return an HTTP 404 status + +Open the demo and check the response status in the Network panel. It returns 404 and a readable page. +*/ +select 'status_code' as component, 404 as status; +select 'text' as component, 'Sample record not found' as title, + 'The HTTP status of this response is 404. You can inspect it in the Network panel.' as contents; diff --git a/examples/official-site/reference/components/steps/01-online-checkout-steps.sql b/examples/official-site/reference/components/steps/01-online-checkout-steps.sql index eb504319f..0bd906c95 100644 --- a/examples/official-site/reference/components/steps/01-online-checkout-steps.sql +++ b/examples/official-site/reference/components/steps/01-online-checkout-steps.sql @@ -1,13 +1,11 @@ /* Online store checkout steps -*/ -select 'steps' as "component"; - -select 'Shopping' as "title" -union all select 'Store pickup'; -select - 'Payment' as "title", - TRUE as "active"; - -select 'Review & Order' as "title"; +Follow a link to see how the current location changes. +*/ +set current = min(4, max(1, coalesce(cast($step as integer), 3))); +select 'steps' as component; +with pages(position, name) as (values (1, 'Shopping'), (2, 'Store pickup'), (3, 'Payment'), (4, 'Review order')) +select name as title, position = cast($current as integer) as active, + '/reference/components/steps/01-online-checkout-steps.sql?step=' || position as link +from pages order by position; diff --git a/examples/official-site/reference/components/steps/02-numbered-progress-with-icons.sql b/examples/official-site/reference/components/steps/02-numbered-progress-with-icons.sql index f206e53f2..31c32add9 100644 --- a/examples/official-site/reference/components/steps/02-numbered-progress-with-icons.sql +++ b/examples/official-site/reference/components/steps/02-numbered-progress-with-icons.sql @@ -1,36 +1,11 @@ /* A progress indicator with custom color, auto-generated step numbers, icons, and description tooltips -*/ -select - 'steps' as "component", - TRUE as "counter", - 'purple' as "color"; - -select - 'Registration form' as "title", - 'forms' as "icon", - 'https://github.com/sqlpage/SQLPage' as "link", - 'Initial account data creation.' as "description"; - -select - 'Email confirmation' as "title", - 'mail' as "icon", - 'https://sql-page.com' as "link", - 'Confirm your email by clicking on a link in a validation email.' as "description"; -select - 'ID verification' as "title", - 'Checking personal information' as "description", - 'user' as "icon", - '#' as "link"; - -select - 'Final account approval' as "title", - 'ophir.dev' as "description", - 'https://ophir.dev/' as "link", - 'eye-check' as "icon", - TRUE as "active"; - -select - 'Account creation' as "title", - 'check' as "icon"; +Follow a link to see how the current location changes. +*/ +set current = min(5, max(1, coalesce(cast($step as integer), 4))); +select 'steps' as component, true as counter, 'purple' as color; +with pages(position, name) as (values (1, 'Registration'), (2, 'Confirm email'), (3, 'Verify ID'), (4, 'Approval'), (5, 'Create account')) +select name as title, position = cast($current as integer) as active, + '/reference/components/steps/02-numbered-progress-with-icons.sql?step=' || position as link, case position when 1 then 'forms' when 2 then 'mail' when 3 then 'user' when 4 then 'eye-check' else 'check' end as icon, 'Go to ' || name as description +from pages order by position; diff --git a/examples/official-site/reference/components/tab/01-tabs-for-page-navigation.sql b/examples/official-site/reference/components/tab/01-tabs-for-page-navigation.sql index a0d93655e..7e2ac1c7b 100644 --- a/examples/official-site/reference/components/tab/01-tabs-for-page-navigation.sql +++ b/examples/official-site/reference/components/tab/01-tabs-for-page-navigation.sql @@ -1,33 +1,16 @@ /* -Basic tabs for page navigation +Switch between projects and tasks -The live example shows three tabs with the first marked as active. To switch content based on the selected 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: +Choose a tab. Its URL selects both the active tab and the query that supplies the table. +*/ +set tab = case when $tab = 'Tasks' then 'Tasks' else 'Projects' end; -```sql -set tab = coalesce($tab, 'Projects'); select 'tab' as component; -select 'Projects' as title, $tab = 'Projects' as active; -select 'Tasks' as title, $tab = 'Tasks' as active; +with tabs(name) as (values ('Projects'), ('Tasks')) +select name as title, name = $tab as active, + sqlpage.link('/reference/components/tab/01-tabs-for-page-navigation.sql', json_object('tab', name)) as link +from tabs; select 'table' as component; - -select * from my_projects where $tab = 'Projects'; -select * from my_tasks where $tab = 'Tasks'; -``` - -The query defaults to Projects on the first visit. The links then select either `?tab=Projects` or `?tab=Tasks`. -*/ -select 'tab' as "component"; - -select - 'This tab does not exist' as "title", - TRUE as "active", - '/component.sql?component=tab&tab=tab_1' as "link"; - -select 'I am not a true tab' as "title", '/component.sql?component=tab&tab=tab_2' as "link" -union all select 'Do not click here', '/component.sql?component=tab&tab=tab_3'; +select name as Project from demo_projects where $tab = 'Projects' order by id; +select task as Task from demo_tasks where $tab = 'Tasks' order by id; diff --git a/examples/official-site/reference/components/tab/02-centered-tabs-with-icons.sql b/examples/official-site/reference/components/tab/02-centered-tabs-with-icons.sql index 7667a4409..69a081896 100644 --- a/examples/official-site/reference/components/tab/02-centered-tabs-with-icons.sql +++ b/examples/official-site/reference/components/tab/02-centered-tabs-with-icons.sql @@ -1,23 +1,16 @@ /* -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 -*/ -select - 'tab' as "component", - TRUE as "center"; +Centered navigation tabs with icons -select - 'Hero' as "title", - '/component.sql?component=hero#component' as "link", - 'home' as "icon", - 'The hero component is a full-width banner with a title and an image.' as "description"; +Choose a tab. Its URL selects both the active tab and the query that supplies the table. +*/ +set tab = case when $tab = 'Tasks' then 'Tasks' else 'Projects' end; -select - 'Tab' as "title", - '/component.sql?component=tab#component' as "link", - 'user' as "icon", - 'purple' as "color"; +select 'tab' as component, true as center; +with tabs(name, icon, description) as (values ('Projects', 'folder', 'Projects in the sample workspace'), ('Tasks', 'checklist', 'Tasks in the sample workspace')) +select name as title, name = $tab as active, + sqlpage.link('/reference/components/tab/02-centered-tabs-with-icons.sql', json_object('tab', name)) as link, icon, description, case when name = $tab then 'body' end as color +from tabs; -select - 'Card' as "title", - '/component.sql?component=card#component' as "link", - 'credit-card' as "icon"; +select 'table' as component; +select name as Project from demo_projects where $tab = 'Projects' order by id; +select task as Task from demo_tasks where $tab = 'Tasks' order by id; diff --git a/examples/official-site/reference/components/table/05-sortable-table-with-average-footer.sql b/examples/official-site/reference/components/table/05-sortable-table-with-average-footer.sql index 4d2b37a5a..eeae651d1 100644 --- a/examples/official-site/reference/components/table/05-sortable-table-with-average-footer.sql +++ b/examples/official-site/reference/components/table/05-sortable-table-with-average-footer.sql @@ -1,16 +1,8 @@ /* A sortable table with a colored footer showing the average value of its entries */ -select - 'table' as "component", - TRUE as "sort"; - -select 'Rudolph Lingens' as "Person", 190 as "Height" -union all select 'Jane Doe', 150 -union all select 'John Doe', 200; - -select - TRUE as "_sqlpage_footer", - 'green' as "_sqlpage_color", - 'Average' as "Person", - 180 as "Height"; +select 'table' as component, true as sort; +with people(name, height) as (values ('Rudolph Lingens', 190), ('Jane Doe', 150), ('John Doe', 200)) +select name as Person, height as Height, false as _sqlpage_footer, null as _sqlpage_color from people +union all +select 'Average', avg(height), true, 'green' from people; diff --git a/examples/official-site/reference/components/table/06-sort-table-columns.sql b/examples/official-site/reference/components/table/06-sort-table-columns.sql index ea0248a36..5ed453e49 100644 --- a/examples/official-site/reference/components/table/06-sort-table-columns.sql +++ b/examples/official-site/reference/components/table/06-sort-table-columns.sql @@ -1,5 +1,5 @@ /* -Sort table columns +Sort numbers, stock quantities and currency A table with column sorting. Sorting sorts numbers in numeric order, and strings in alphabetical order. diff --git a/examples/official-site/reference/components/table/07-striped-rows-and-initial-search.sql b/examples/official-site/reference/components/table/07-striped-rows-and-initial-search.sql index af698a629..161ad014f 100644 --- a/examples/official-site/reference/components/table/07-striped-rows-and-initial-search.sql +++ b/examples/official-site/reference/components/table/07-striped-rows-and-initial-search.sql @@ -1,5 +1,7 @@ /* A table with some presentation options + +The initial search for NCC- hides USS Defiant, whose registry starts with IX-. Clear the search to see all six ships. */ select 'table' as "component", diff --git a/examples/official-site/reference/components/table/08-friendly-empty-message.sql b/examples/official-site/reference/components/table/08-friendly-empty-message.sql index cef80ab09..e962c818f 100644 --- a/examples/official-site/reference/components/table/08-friendly-empty-message.sql +++ b/examples/official-site/reference/components/table/08-friendly-empty-message.sql @@ -1,6 +1,11 @@ /* -An empty table with a friendly message +Search the component catalog + +Try “chart” for a match or “spaceship” for an empty result. */ -select - 'table' as "component", - 'Nothing to see here at the moment.' as "empty_description"; +set search = coalesce($search, 'spaceship'); + +select 'form' as component, 'GET' as method, '/reference/components/table/08-friendly-empty-message.sql' as action, 'Search' as validate; +select 'search' as name, 'Component name' as label, $search as value; +select 'table' as component, 'No components match your search. Try chart.' as empty_description; +select name as Component from component where instr(name, lower($search)) > 0 order by name; diff --git a/examples/official-site/reference/components/table/10-dynamic-column-names.md b/examples/official-site/reference/components/table/10-dynamic-column-names.md deleted file mode 100644 index 5580b38ae..000000000 --- a/examples/official-site/reference/components/table/10-dynamic-column-names.md +++ /dev/null @@ -1,47 +0,0 @@ -# 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. diff --git a/examples/official-site/reference/components/table/10-dynamic-column-names.sql b/examples/official-site/reference/components/table/10-dynamic-column-names.sql new file mode 100644 index 000000000..bfe3e8ee2 --- /dev/null +++ b/examples/official-site/reference/components/table/10-dynamic-column-names.sql @@ -0,0 +1,23 @@ +/* +Dynamic column names in a table + +Choose which products to display. The query groups sales by store and uses the product names as JSON keys. Those keys become the table headers. + +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. +*/ +select 'button' as component; +select 'All columns' as title, '/reference/components/table/10-dynamic-column-names.sql' as link; +select 'Hide Tea' as title, '/reference/components/table/10-dynamic-column-names.sql?hide=Tea' as link; + +select 'table' as component; +with facts(store, item, quantity) as (values ('Madrid', 'Coffee', 12), ('Madrid', 'Tea', 7), ('Paris', 'Coffee', 5), ('Paris', 'Tea', 14)) +select 'dynamic' as component, json_patch(json_object('Store', store), + json_group_object(item, quantity order by item)) as properties +from facts where $hide is null or item <> $hide group by store order by store; diff --git a/examples/official-site/reference/components/table/11-row-action-buttons.sql b/examples/official-site/reference/components/table/11-row-action-buttons.sql index e833d5567..3395824e9 100644 --- a/examples/official-site/reference/components/table/11-row-action-buttons.sql +++ b/examples/official-site/reference/components/table/11-row-action-buttons.sql @@ -31,41 +31,22 @@ Each button is defined by the following properties: ### Example using all of the above */ -select - 'table' as "component", - '/examples/show_variables.sql?action=edit&update_id={id}' as "edit_url", - '/examples/show_variables.sql?action=delete&delete_id={id}' as "delete_url", - JSON('{"name":"history","tooltip":"View Standard History","link":"/examples/show_variables.sql?action=history&standard_id={id}","icon":"history"}') as "custom_actions"; - -select - 'CalStd' as "name", - 'PharmaCo' as "vendor", - 'P1234' as "Product", - 'T23523' as "lot number", - 'Available' as "status", - '2026-10-13' as "expires on", - 32 as "_sqlpage_id", - JSON('{"name":"View PDF","tooltip":"View Presentation","link":"https://sql-page.com/pgconf/2024-sqlpage-badass.pdf","icon":"file-type-pdf"}') as "_sqlpage_actions", - JSON('{"name":"Action","tooltip":"Set In Use","link":"/examples/show_variables.sql?action=set_in_use&standard_id=32","icon":"caret-right"}') as "_sqlpage_actions"; - -select - 'CalStd' as "name", - 'PharmaCo' as "vendor", - 'P1234' as "Product", - 'T2352' as "lot number", - 'In Use' as "status", - '2026-10-14' as "expires on", - 33 as "_sqlpage_id", - JSON('{"name":"View PDF","tooltip":"View Presentation","link":"https://sql-page.com/pgconf/2024-sqlpage-badass.pdf","icon":"file-type-pdf"}') as "_sqlpage_actions", - JSON('{"name":"Action","tooltip":"Retire Standard","link":"/examples/show_variables.sql?action=retire&standard_id=33","icon":"test-pipe-off"}') as "_sqlpage_actions"; - -select - 'CalStd' as "name", - 'PharmaCo' as "vendor", - 'P1234' as "Product", - 'A123' as "lot number", - 'Discarded' as "status", - '2026-09-30' as "expires on", - 31 as "_sqlpage_id", - JSON('{"name":"View PDF","tooltip":"View Presentation","link":"https://sql-page.com/pgconf/2024-sqlpage-badass.pdf","icon":"file-type-pdf"}') as "_sqlpage_actions", - JSON('{"name":"Action"}') as "_sqlpage_actions"; +set states = case when json_valid(sqlpage.cookie('docs_projects')) then sqlpage.cookie('docs_projects') else '{}' end; +select 'table' as component, + '/examples/reference/record.sql?action=edit&id={id}' as edit_url, + '/examples/reference/record.sql?action=delete&id={id}' as delete_url, + json_object('name', 'Details', 'icon', 'info-circle', 'link', '/examples/reference/record.sql?id={id}') as custom_actions; +with projects as ( + select id, name, coalesce(json_extract($states, '$."' || id || '"'), initial_status) as status from demo_projects +) +select id as _sqlpage_id, name, status, + json_object('name', 'Reference', 'tooltip', 'View presentation', 'icon', 'file-type-pdf', + 'link', '/pgconf/2024-sqlpage-badass.pdf') as _sqlpage_actions, + case status when 'Removed' then json_object('name', 'Action') + else json_object('name', 'Action', + 'tooltip', case status when 'Available' then 'Start using' else 'Retire' end, + 'icon', case status when 'Available' then 'player-play' else 'archive' end, + 'link', '/examples/reference/record.sql?id=' || id || + case status when 'Available' then '&action=use' else '&action=delete' end) + end as _sqlpage_actions +from projects order by id; diff --git a/examples/official-site/reference/components/tracking/02-server-status-with-downtime.sql b/examples/official-site/reference/components/tracking/02-server-status-with-downtime.sql index 55d17a026..ab77fba89 100644 --- a/examples/official-site/reference/components/tracking/02-server-status-with-downtime.sql +++ b/examples/official-site/reference/components/tracking/02-server-status-with-downtime.sql @@ -1,21 +1,11 @@ /* -An example of servers tracking component -*/ -select - 'tracking' as "component", - 'Servers status' as "title", - '60% are running' as "information", - 'Status of all **currently running servers**' as "description_md", - 'top' as "placement", - 4 as "width"; - -select 'success' as "color", 'operational' as "title" -union all select 'success', 'operational' -union all select 'success', 'operational' -union all select 'danger', 'Downtime'; +Track server latency against a target -select 'No data' as "title"; - -select 'success' as "color", 'operational' as "title" -union all select 'warning', 'Big load' -union all select 'success', 'operational'; +Each segment represents a measurement. Hover over it to see the timestamp and response time. The percentage uses the same 200 ms threshold as the colors. +*/ +select 'tracking' as component, 'Server status' as title, + round(100.0 * avg(latency_ms < 200)) || '% within latency target' as information, + 'Sample checks with a 200 ms target' as description_md from demo_readings; +select measured_at || ': ' || latency_ms || ' ms' as title, + case when latency_ms < 200 then 'success' else 'danger' end as color +from demo_readings order by measured_at; diff --git a/examples/official-site/sqlpage/migrations/84_component_examples.sql b/examples/official-site/sqlpage/migrations/84_component_examples.sql new file mode 100644 index 000000000..0c997f7de --- /dev/null +++ b/examples/official-site/sqlpage/migrations/84_component_examples.sql @@ -0,0 +1,38 @@ +-- Small datasets shared by the runnable reference examples. +CREATE TABLE demo_ships (name TEXT PRIMARY KEY, class TEXT NOT NULL); +INSERT INTO demo_ships VALUES + ('Enterprise NCC-1701', 'Constitution'), ('Exeter NCC-1672', 'Constitution'), + ('Enterprise NCC-1701-D', 'Galaxy'), ('Odyssey NCC-71832', 'Galaxy'); + +CREATE TABLE demo_fruits (id INTEGER PRIMARY KEY, name TEXT NOT NULL); +INSERT INTO demo_fruits VALUES (1, 'Orange'), (2, 'Apple'), (3, 'Banana'); + +CREATE TABLE demo_projects (id INTEGER PRIMARY KEY, name TEXT NOT NULL, initial_status TEXT NOT NULL); +INSERT INTO demo_projects VALUES (1, 'Website', 'Available'), (2, 'Mobile app', 'In use'), (3, 'Archive', 'Removed'); +CREATE TABLE demo_tasks (id INTEGER PRIMARY KEY, project_id INTEGER REFERENCES demo_projects, task TEXT NOT NULL); +INSERT INTO demo_tasks VALUES (1, 1, 'Design navigation'), (2, 1, 'Publish documentation'), (3, 2, 'Test notifications'); + +-- One checkout per date, with an amount in whole dollars. +CREATE TABLE demo_orders (ordered_on TEXT PRIMARY KEY, amount INTEGER NOT NULL); +INSERT INTO demo_orders VALUES + ('2025-01-02', 20), ('2025-02-01', 35), ('2025-02-28', 10), + ('2025-03-20', 80), ('2025-03-27', 45), ('2025-03-31', 60); + +CREATE TABLE demo_readings (measured_at TEXT PRIMARY KEY, temperature INTEGER, latency_ms INTEGER); +INSERT INTO demo_readings VALUES + ('2024-05-01T08:00:00Z', 52, 120), ('2024-05-01T09:00:00Z', 58, 134), + ('2024-05-01T10:00:00Z', 71, 128), ('2024-05-01T11:00:00Z', 83, 141), + ('2024-05-01T12:00:00Z', 94, 512), ('2024-05-01T13:00:00Z', 76, 470), + ('2024-05-01T14:00:00Z', 63, 156); + +-- Each browser can keep one sample entry. The form handler expires old entries. +CREATE TABLE demo_entries ( + token TEXT PRIMARY KEY, + name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 60), + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX demo_entries_updated_at ON demo_entries(updated_at); + +-- A one-pixel GIF, stored as binary rather than as an encoded data URL. +CREATE TABLE demo_images (id INTEGER PRIMARY KEY, filename TEXT NOT NULL, content BLOB NOT NULL); +INSERT INTO demo_images VALUES (1, 'sample.gif', X'47494638396101000100800000000000FFFFFF21F90401000000002C00000000010001000002024401003B'); diff --git a/examples/official-site/sqlpage/templates/docs-example.handlebars b/examples/official-site/sqlpage/templates/docs-example.handlebars index 1d6428117..483cbc82b 100644 --- a/examples/official-site/sqlpage/templates/docs-example.handlebars +++ b/examples/official-site/sqlpage/templates/docs-example.handlebars @@ -8,6 +8,7 @@