diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e8a81395..4f4d21947 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,7 +65,7 @@ jobs: - run: cargo fmt --all -- --check - run: cargo clippy --all-targets --all-features -- -D warnings - name: Prepare and check official website - run: npm run site:test + run: npm run site:test -- --features odbc-static - name: Upload prepared website uses: actions/upload-artifact@v7 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index 69f3bc898..fd7c8f3c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ - SQLite query results preserve the full 64-bit range of `INTEGER` values. ([#1636](https://github.com/sqlpage/SQLPage/issues/1636)) - Big number title links have a larger target for touch and pointer users. - Carousel slide indicators and pagination arrows now have accessible names. Keyboard users can activate carousel arrows and enabled pagination links. Screen readers announce the current page. +- The carousel's `delay` parameter controls the interval between automatically changing slides. - Button, card, carousel, and login images accept alternative text. Embedded card frames use their own title or the card title. - Inline links are underlined so they stand out without relying on color. The documentation search button has a clear accessible name separate from its shortcut hint. - Disabled buttons expose their state to assistive technology and cannot be activated. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8c5861f8e..acd54c1ab 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -67,9 +67,8 @@ built executable. Component suites use `fixtures//{index.sql,test.ts}` an import the shared `fixture.ts` harness; root-level `*.spec.ts` files cover the official site. -For changes to component documentation, run `npm run site:test`. It rebuilds -the site and checks the prepared reference against public components and their -template properties. +Run `npm run site:test` after changing component documentation. It builds the +site, verifies its published examples and search index, and tests the parser. Run `npx playwright test --grep @accessibility` from `tests/end-to-end` to audit the official site's component documentation and its live examples in SQLPage's @@ -113,7 +112,7 @@ Architectural constraints and documentation maintenance rules are in [AGENTS.md](./AGENTS.md). Edit existing documentation in the [official site](./examples/official-site/) in place. -Deployment recreates the website's database from the site's SQL migrations. +Deployment uses the SQLite database prepared by the site build. Run `npm run site` to preview changes using the same site build as deployment. diff --git a/Cargo.lock b/Cargo.lock index 44baecad3..a63558a68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4707,6 +4707,7 @@ dependencies = [ "tracing-log", "tracing-opentelemetry", "tracing-subscriber", + "walkdir", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 69de70e34..1c4471428 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,10 @@ include = [ "/frontend/dist", ] +[[example]] +name = "build-site" +path = "scripts/official-site/main.rs" + [lints.rust] elided_lifetimes_in_paths = "deny" unreachable_pub = "deny" @@ -147,6 +151,7 @@ lambda-web = [ ] [dev-dependencies] +walkdir = "2" actix-http = "3" tempfile = "3" tokio = { version = "1", features = ["rt", "time", "test-util"] } diff --git a/examples/official-site/Dockerfile b/examples/official-site/Dockerfile index 849b2861d..de781b7d0 100644 --- a/examples/official-site/Dockerfile +++ b/examples/official-site/Dockerfile @@ -1,4 +1,4 @@ FROM lovasoa/sqlpage:main -COPY --chown=sqlpage:sqlpage ./sqlpage /etc/sqlpage +ENV SQLPAGE_CONFIGURATION_DIRECTORY=/var/www/sqlpage COPY --chown=sqlpage:sqlpage . /var/www diff --git a/examples/official-site/README.md b/examples/official-site/README.md index 201f458af..0393a97a0 100644 --- a/examples/official-site/README.md +++ b/examples/official-site/README.md @@ -4,7 +4,7 @@ The SQLPage website is of course built with SQLPage ! Things that you may be interested to look at: - The [custom component we use for our stylish home page](./sqlpage/templates/landing-page.handlebars) - - The [migrations](./sqlpage/migrations) that populate the database with the documentation for all components + - How to [document a component and add examples](#component-reference) - The [advanced multistep form example](./examples/multistep-form/) It is hosted as a simple Docker container on [sql-page.com](https://sql-page.com). @@ -20,12 +20,54 @@ After `npm run build`, run `npm run site:build` to prepare the site under `target/official-site/`. Run SQLPage from that directory, or run `docker compose -f examples/official-site/docker-compose.yml up --build` from -the repository root. +the repository root. Demo login sessions survive a server restart and reset when the site is rebuilt. Add `theme=light` or `theme=dark` to a component reference URL to preview its live examples using SQLPage's stock theme. For example, visit `/component.sql?component=form&theme=light`. +## Component reference + +Document Handlebars component parameters in the first comment of `sqlpage/templates/.handlebars`. Start with a short summary paragraph, then give the complete overview, followed by `## Top-level parameters` and `## Row-level parameters`. Omit empty sections. For the nine components implemented in Rust, put the overview and parameter list in that component's `README.md` under `reference/components/` using the same structure. + +```handlebars +{{!-- +Display source code with syntax highlighting. + +The code component renders text as escaped, highlighted source. + +## Top-level parameters + + - **id** (TEXT) + - **class** (TEXT) + +## Row-level parameters + + - **contents** (TEXT, required): A block of source code. + - **language** (TEXT): Language used for syntax highlighting. +--}} +``` + +Parameters are optional by default. Add `, required` after the type for a required parameter. The standard `id` and `class` parameters inherit their HTML descriptions. Give them a description when their behavior differs. + +Put each component's examples in its directory under `reference/components/`. Set its icon, category, and the version that introduced it in `sqlpage/migrations/82_reference_catalog.sql`. + +Name each example with a zero-padded number and a short, hyphenated title. Keep its number when editing so links such as `#example-2` remain stable. A runnable example's file path is also its direct URL. + +- **[`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. + +```sql +/* +Show HTML source +*/ +select 'code' as component; +select 'html' as language, '

Hello

' as contents; +``` + +Run `npm run site:test` to build the site, check its search index and published SQL, and run the documentation parser tests. Run `npm run site` to preview the site. + ## Landing page The home page is rendered by `index.sql` and the `landing-page` custom template. diff --git a/examples/official-site/colors.sql b/examples/official-site/colors.sql index 7ef53f37f..7cb614c49 100644 --- a/examples/official-site/colors.sql +++ b/examples/official-site/colors.sql @@ -1,11 +1,10 @@ set theme = coalesce($theme, 'custom'); -select 'dynamic' as component, json_patch(json_extract(properties, '$[0]'), json_object( +select 'dynamic' as component, json_patch(sqlpage.run_sql('reference/components/shell/01-dark-shell-with-navigation-menus.standalone.sql')->0, json_object( 'title', $theme || ' SQLPage Colors', 'css', case $theme when 'custom' then '/assets/highlightjs-and-tabler-theme.css' end, 'theme', case $theme when 'default' then 'light' else 'dark' end -)) as properties -FROM example WHERE component = 'shell' LIMIT 1; +)) as properties; select 'tab' as component; select 'Default theme' as title, '?theme=default' as link, 'Default theme' as description, case $theme when 'default' then 'primary' end as color, $theme = 'default' as disabled; diff --git a/examples/official-site/component.sql b/examples/official-site/component.sql index 747882aab..c6f22ed3b 100644 --- a/examples/official-site/component.sql +++ b/examples/official-site/component.sql @@ -13,25 +13,14 @@ 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); -with examples as ( - -- HTTP headers and shells can only run at the start of a response. - select *, - case when component not in ('shell', 'http_header') then properties end as result, - case when length(trim(description)) <= 120 - and glob('*[^a-zA-Z0-9 ,.''()-]*', trim(description)) = 0 - then trim(description) end as short_title - from example_with_source where component = $component -) select 'dynamic' as component, json_array( json_object( - 'component', 'docs-example', 'number', example_number, - 'title', short_title, 'description_md', case when short_title is null then description end, - 'source', source, - 'preview', result is not null + 'component', 'docs-example', 'number', number, 'title', title, + 'description_md', description, 'source', source, + 'preview', preview ), - json(coalesce(result, '[]')), - -- Keep every native component of the example inside the same result panel. - case when result is not null then json_object('component', 'docs-example', 'end_result', true) + coalesce(sqlpage.run_sql(case when preview then path end), '[]'), + case when preview then json_object('component', 'docs-example', 'end_result', true) else json_array() end ) as properties -from examples order by example_id; +from example where component = $component order by number; diff --git a/examples/official-site/examples/authentication/index.sql b/examples/official-site/examples/authentication/index.sql index 32d2b6dc3..6ef3a297a 100644 --- a/examples/official-site/examples/authentication/index.sql +++ b/examples/official-site/examples/authentication/index.sql @@ -4,8 +4,7 @@ set user_role = (select role from users natural join user_sessions where session select 'redirect' as component, 'login.sql' as link where $user_role is null; select 'dynamic' as component, - json_insert(properties, '$[0].menu_item[#]', 'logout') as properties -FROM example WHERE component = 'shell' LIMIT 1; + json_insert(sqlpage.run_sql('reference/components/shell/01-dark-shell-with-navigation-menus.standalone.sql'), '$[0].menu_item[#]', 'logout') as properties; select 'alert' as component, 'info' as color, CONCAT('You are logged in as ', $user_role) as title; diff --git a/examples/official-site/examples/layouts.sql b/examples/official-site/examples/layouts.sql index 45fac4e3b..fad868b57 100644 --- a/examples/official-site/examples/layouts.sql +++ b/examples/official-site/examples/layouts.sql @@ -4,14 +4,13 @@ set layout = coalesce($layout, 'boxed'); set sidebar = coalesce($sidebar, 0); select 'dynamic' as component, - json_patch(properties->0, + json_patch(sqlpage.run_sql('reference/components/shell/01-dark-shell-with-navigation-menus.standalone.sql')->0, json_object( 'title', 'Shell layouts | SQLPage', 'layout', $layout, 'sidebar', $sidebar = 1 ) - ) as properties -FROM example WHERE component = 'shell' LIMIT 1; + ) as properties; select 'text' as component, ' # Layouts diff --git a/examples/official-site/reference/components/alert/01-basic-alert.sql b/examples/official-site/reference/components/alert/01-basic-alert.sql new file mode 100644 index 000000000..048a59fff --- /dev/null +++ b/examples/official-site/reference/components/alert/01-basic-alert.sql @@ -0,0 +1,7 @@ +/* +A basic alert message +*/ +select + 'alert' as "component", + 'Attention' as "title", + 'This is an important message.' as "description"; diff --git a/examples/official-site/reference/components/alert/02-success-warning-error-alerts.sql b/examples/official-site/reference/components/alert/02-success-warning-error-alerts.sql new file mode 100644 index 000000000..b0a7afcf7 --- /dev/null +++ b/examples/official-site/reference/components/alert/02-success-warning-error-alerts.sql @@ -0,0 +1,23 @@ +/* +A list of notifications +*/ +select + 'alert' as "component", + 'Success' as "title", + 'Item successfully added to your cart.' as "description", + 'check' as "icon", + 'green' as "color"; + +select + 'alert' as "component", + 'Warning' as "title", + 'Your cart is almost full.' as "description", + 'alert-triangle' as "icon", + 'yellow' as "color"; + +select + 'alert' as "component", + 'Error' as "title", + 'Your cart is full.' as "description", + 'alert-circle' as "icon", + 'red' as "color"; diff --git a/examples/official-site/reference/components/alert/03-alert-with-links.sql b/examples/official-site/reference/components/alert/03-alert-with-links.sql new file mode 100644 index 000000000..481c4b6d1 --- /dev/null +++ b/examples/official-site/reference/components/alert/03-alert-with-links.sql @@ -0,0 +1,19 @@ +/* +A full-featured notification message with multiple links +*/ +select + 'alert' as "component", + 'Your dashboard is ready!' as "title", + 'analyze' as "icon", + 'teal' as "color", + TRUE as "dismissible", + 'Your public web dashboard was successfully created.' as "description"; + +select + '/examples/chart.sql' as "link", + 'View your dashboard' as "title"; + +select + '/' as "link", + 'Back to home' as "title", + 'secondary' as "color"; diff --git a/examples/official-site/reference/components/alert/04-dismissible-alert.sql b/examples/official-site/reference/components/alert/04-dismissible-alert.sql new file mode 100644 index 000000000..bcdbd0d53 --- /dev/null +++ b/examples/official-site/reference/components/alert/04-dismissible-alert.sql @@ -0,0 +1,16 @@ +/* +A dismissible alert + +`close_label` gives the close button an accessible name. +*/ +select + 'alert' as "component", + 'Alert' as "title", + 'alert-circle' as "icon", + 'red' as "color", + TRUE as "important", + TRUE as "dismissible", + 'Dismiss this alert' as "close_label", + 'SQLPage is entirely free and open source.' as "description", + 'https://github.com/sqlpage/SQLPage' as "link", + 'See source code' as "link_text"; diff --git a/examples/official-site/reference/components/alert/05-alert-with-markdown.sql b/examples/official-site/reference/components/alert/05-alert-with-markdown.sql new file mode 100644 index 000000000..46dcf08a2 --- /dev/null +++ b/examples/official-site/reference/components/alert/05-alert-with-markdown.sql @@ -0,0 +1,9 @@ +/* +An alert message with a Markdown-formatted description +*/ +select + 'alert' as "component", + 'Free and open source' as "title", + 'free-rights' as "icon", + 'info' as "color", + '*SQLPage* is entirely free and open source. You can **contribute** to it on [GitHub](https://github.com/sqlpage/SQLPage).' as "description_md"; 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 new file mode 100644 index 000000000..9f58d30c4 --- /dev/null +++ b/examples/official-site/reference/components/authentication/01-basic-auth-and-sessions.md @@ -0,0 +1,101 @@ +# HTTP basic authentication and sessions + +### Usage with HTTP basic authentication + +The most basic usage of the authentication component is with the +[`sqlpage.basic_auth_username()`](/functions.sql?function=basic_auth_username#function) and +[`sqlpage.basic_auth_password()`](/functions.sql?function=basic_auth_password#function) functions. +The component will check if the provided password matches the stored [password hash](/examples/hash_password.sql), +and if not, it will prompt the user to enter a password in a browser popup: + +```sql +SELECT 'authentication' AS component, + '$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w' AS password_hash, -- this is a hash of the password 'password' + sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup +``` + +You can [generate a password hash using the `hash_password` function](/examples/hash_password.sql). + +If you want to have multiple users with different passwords, +you could store them with their password hashes in the database, +or just hardcode them use a `CASE` statement: + +```sql +SELECT 'authentication' AS component, + case sqlpage.basic_auth_username() + when 'admin' + then '$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w' -- the password is 'password' + when 'user' + then '$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$qsrWdjgl96ooYw' -- the password is 'user' + end AS password_hash, -- this is a hash of the password 'password' + sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup +``` + +Try this example online: [SQL Basic Auth](/examples/authentication/basic_auth.sql). + +### Advanced user session management + +*Basic auth* is the simplest way to password-protect a page, +but it is not very flexible nor user-friendly, +because the browser will show an unstyled popup asking for the username and password. + +For more advanced authentication, you can store user information and user sessions in your database. +You can then use the [`form`](/component.sql?component=form#component) component to create a custom login form. +When the user submits the form, you check if the password is correct using the `authentication` component. +You then store a unique string of numbers and letters (a session token) both in the user's browser +using the [`cookie`](/component.sql?component=cookie#component) component and in your database. +Then, in all the pages that require authentication, you check if the cookie is present and matches the session token in your database. + +You can check if the user has sent the correct password in a form, and if not, redirect them to a login page. + +Create a login form in a file called `login.sql` that uses the [login component](/component.sql?component=login): + +```sql +select 'login' as component, 'create_session_token.sql' as action; +``` + +And then, in `create_session_token.sql` : + +```sql +SELECT 'authentication' AS component, + 'login.sql' AS link, + '$argon2id$v=19$m=16,t=2,p=1$TERTd0lIcUpraWFTcmRQYw$+bjtag7Xjb6p1dsuYOkngw' AS password_hash, -- generated using sqlpage.hash_password + :password AS password; -- this is the password that the user sent through our form + +-- The code after this point is only executed if the user has sent the correct password + +``` + +### Advanced: usage with a session token + +Calling the `authentication` component is expensive. +The password hashing algorithm is designed to be slow, so that it is difficult to brute-force the password, +even if an attacker gets access to the database. + +If you want to avoid calling the `authentication` component on every page, you can use a session token. +A session token is a random string that is generated when the user logs in, and stored in the database. +It has a limited lifetime, and is stored in a cookie in the user's browser. +When the user visits a page, the session token is sent to the server, and the server checks if it is valid. + +```sql +SELECT 'authentication' AS component, + 'login.sql' AS link, + (SELECT password_hash FROM user WHERE username = :username) AS password_hash, + :password AS password; + +-- The code after this point is only executed if the user has sent the correct password + +-- Generate a random session token +INSERT INTO session (id, username) +VALUES (sqlpage.random_string(32), :username) +RETURNING + 'cookie' AS component, + 'session_token' AS name, + id AS value; +``` + +### Single sign-on with OIDC (OpenID Connect) + +If you don't want to manage your own user database, +you can [use OpenID Connect and OAuth2](/sso) to authenticate users. +This allows users to log in with their Google, Microsoft, or internal company account. diff --git a/examples/official-site/reference/components/authentication/README.md b/examples/official-site/reference/components/authentication/README.md new file mode 100644 index 000000000..5616891a5 --- /dev/null +++ b/examples/official-site/reference/components/authentication/README.md @@ -0,0 +1,39 @@ +Restrict access by checking a password against a stored hash. + +When you want to add user authentication to your SQLPage application, +you have two main options: + +1. The `authentication` component: + - lets you manage usernames and passwords yourself + - does not require any external service + - gives you fine-grained control over + - which pages and actions are protected + - the look of the [login form](?component=login) + - the duration of the session + - the permissions of each user +2. [**Single sign-on**](/sso) + - lets users log in with their existing accounts (like Google, Microsoft, or your organization's own identity provider) + - requires setting up an external service (Google, Microsoft, etc.) + - frees you from implementing a lot of features like password reset, account creation, user management, etc. + +This page describes the first option. + +When used, this component has to be at the top of your page, +because once the page has begun being sent to the browser, +it is too late to restrict access to it. + +The authentication component checks if the user has sent the correct password, +and if not, redirects them to the URL specified in the link parameter. + +If you don't want to re-check the password on every page (which is an expensive operation), +you can check the password only once and store a session token in your database +(see the session example below). + +You can use the [cookie component](?component=cookie) to set the session token cookie in the client browser, +and then check whether the token matches what you stored in subsequent pages. + +## Top-level parameters + + - **link** (TEXT): The URL to redirect the user to if they are not logged in. If this parameter is not specified, the user will stay on the current page, but be asked to log in using a popup in their browser (HTTP basic authentication). + - **password** (TEXT): The password that was sent by the user. You can set this to :password if you have a login form leading to your page. + - **password_hash** (TEXT): The hash of the password that you stored for the user that is currently trying to log in. These hashes can be generated ahead of time using a tool like https://argon2.online/. 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 new file mode 100644 index 000000000..923fcac43 --- /dev/null +++ b/examples/official-site/reference/components/big_number/01-changes-and-progress-bars.sql @@ -0,0 +1,24 @@ +/* +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 + 'Revenue' as "title", + '4,300' as "value", + '$' as "unit", + 'Year on year' as "description", + -8 as "change_percent"; 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 new file mode 100644 index 000000000..3bf3bc45d --- /dev/null +++ b/examples/official-site/reference/components/big_number/02-dropdowns-and-layout.sql @@ -0,0 +1,33 @@ +/* +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"; + +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"; diff --git a/examples/official-site/reference/components/breadcrumb/01-breadcrumb-trail.sql b/examples/official-site/reference/components/breadcrumb/01-breadcrumb-trail.sql new file mode 100644 index 000000000..d244d4a63 --- /dev/null +++ b/examples/official-site/reference/components/breadcrumb/01-breadcrumb-trail.sql @@ -0,0 +1,8 @@ +/* +Basic usage of the breadcrumb component +*/ +select 'breadcrumb' as "component"; + +select 'Home' as "title", '/' as "link" +union all select 'Components', '/documentation.sql' +union all select 'Breadcrumb', '/component.sql?component=breadcrumb'; 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 new file mode 100644 index 000000000..7d6fd254e --- /dev/null +++ b/examples/official-site/reference/components/breadcrumb/02-link-description-and-current-page.sql @@ -0,0 +1,19 @@ +/* +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"; + +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"; diff --git a/examples/official-site/reference/components/button/01-button-with-link.sql b/examples/official-site/reference/components/button/01-button-with-link.sql new file mode 100644 index 000000000..122929a8c --- /dev/null +++ b/examples/official-site/reference/components/button/01-button-with-link.sql @@ -0,0 +1,13 @@ +/* +A basic button with a link +*/ +select 'button' as "component"; + +select + '/documentation.sql' as "link", + 'Enabled' as "title"; + +select + '#' as "link", + 'Disabled' as "title", + TRUE as "disabled"; diff --git a/examples/official-site/reference/components/button/02-custom-shape-size-and-outline.sql b/examples/official-site/reference/components/button/02-custom-shape-size-and-outline.sql new file mode 100644 index 000000000..d1f60d905 --- /dev/null +++ b/examples/official-site/reference/components/button/02-custom-shape-size-and-outline.sql @@ -0,0 +1,11 @@ +/* +A button with a custom shape, size, and outline color +*/ +select + 'button' as "component", + 'sm' as "size", + 'pill' as "shape"; + +select 'Purple' as "title", 'purple' as "outline" +union all select 'Orange', 'orange' +union all select 'Red', 'red'; diff --git a/examples/official-site/reference/components/button/03-centered-button-list.sql b/examples/official-site/reference/components/button/03-centered-button-list.sql new file mode 100644 index 000000000..00e3df5e7 --- /dev/null +++ b/examples/official-site/reference/components/button/03-centered-button-list.sql @@ -0,0 +1,13 @@ +/* +A list of buttons aligned in the center +*/ +select + 'button' as "component", + 'center' as "justify"; + +select '#' as "link", 'light' as "color", 'Light' as "title" +union all select '#', 'success', 'Success' +union all select '#', 'info', 'Info' +union all select '#', 'dark', 'Dark' +union all select '#', 'warning', 'Warning' +union all select '#', 'danger', 'Narrow'; diff --git a/examples/official-site/reference/components/button/04-narrow-icon-buttons.sql b/examples/official-site/reference/components/button/04-narrow-icon-buttons.sql new file mode 100644 index 000000000..dfd7c7501 --- /dev/null +++ b/examples/official-site/reference/components/button/04-narrow-icon-buttons.sql @@ -0,0 +1,13 @@ +/* +Icon buttons using the narrow property +*/ +select 'button' as "component"; + +select '#' as "link", TRUE as "narrow", 'edit' as "icon", 'primary' as "color", 'Edit' as "tooltip" +union all select '#', TRUE, 'trash', 'danger', 'Delete' +union all select '#', TRUE, 'corner-down-right', 'info', 'Preview' +union all select '#', TRUE, 'download', 'success', 'Download' +union all select '#', TRUE, 'upload', 'warning', 'Upload' +union all select '#', TRUE, 'info-circle', 'cyan', 'Info' +union all select '#', TRUE, 'help-circle', 'purple', 'Help' +union all select '#', TRUE, 'settings', 'indigo', 'Settings'; diff --git a/examples/official-site/reference/components/button/05-icons-and-sizes.sql b/examples/official-site/reference/components/button/05-icons-and-sizes.sql new file mode 100644 index 000000000..8b8148bec --- /dev/null +++ b/examples/official-site/reference/components/button/05-icons-and-sizes.sql @@ -0,0 +1,9 @@ +/* +Buttons with icons and different sizes +*/ +select + 'button' as "component", + 'lg' as "size"; + +select '#' as "link", 'azure' as "outline", 'Edit' as "title", 'edit' as "icon" +union all select '#', 'danger', 'Delete', 'trash'; diff --git a/examples/official-site/reference/components/button/06-spaced-square-buttons.sql b/examples/official-site/reference/components/button/06-spaced-square-buttons.sql new file mode 100644 index 000000000..99d1225f6 --- /dev/null +++ b/examples/official-site/reference/components/button/06-spaced-square-buttons.sql @@ -0,0 +1,25 @@ +/* +A row of square buttons with spacing in between +*/ +select + 'button' as "component", + 'square' as "shape"; + +select + '#' as "link", + 'green' as "color", + 'Save' as "title", + 'device-floppy' as "icon"; + +select + '#' as "link", + 'Cancel' as "title", + TRUE as "space_after", + 'This will delete your draft' as "tooltip"; + +select + '#' as "link", + 'indigo' as "outline", + 'Preview' as "title", + 'corner-down-right' as "icon_after", + 'View temporary draft' as "tooltip"; 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 new file mode 100644 index 000000000..83183e6d2 --- /dev/null +++ b/examples/official-site/reference/components/button/07-multiple-form-actions.sql @@ -0,0 +1,33 @@ +/* +Submit one form to different pages + +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. +*/ +select + 'form' as "component", + 'poem' as "id", + '' as "validate"; + +select + 'textarea' as "type", + 'Poem' as "name", + 'Write a poem' as "placeholder"; + +select 'button' as "component"; + +select + '/examples/show_variables.sql?action=save' as "link", + 'poem' as "form", + 'primary' as "color", + 'Save' as "title"; + +select + '/examples/show_variables.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 new file mode 100644 index 000000000..fbe75160a --- /dev/null +++ b/examples/official-site/reference/components/button/08-download-button.sql @@ -0,0 +1,13 @@ +/* +A button that downloads a file + +A button that downloads a file when clicked, and prevents search engines from following the link. +*/ +select 'button' as "component"; + +select + '/sqlpage_introduction_video.mp4' as "link", + 'Download Video' as "title", + 'download' as "icon", + 'Introduction Video.webm' as "download", + 'nofollow' as "rel"; diff --git a/examples/official-site/reference/components/button/09-image-icon.sql b/examples/official-site/reference/components/button/09-image-icon.sql new file mode 100644 index 000000000..cf606f9e9 --- /dev/null +++ b/examples/official-site/reference/components/button/09-image-icon.sql @@ -0,0 +1,9 @@ +/* +A button with an image-based icon +*/ +select 'button' as "component"; + +select + 'https://en.wikipedia.org/wiki/File:Globe.svg' as "link", + 'Open an article' as "title", + 'https://upload.wikimedia.org/wikipedia/commons/f/fa/Globe.svg' as "image"; diff --git a/examples/official-site/reference/components/card/01-feature-card-grid.sql b/examples/official-site/reference/components/card/01-feature-card-grid.sql new file mode 100644 index 000000000..2e74fc3fc --- /dev/null +++ b/examples/official-site/reference/components/card/01-feature-card-grid.sql @@ -0,0 +1,25 @@ +/* +A card grid of SQLPage features + +A beautiful card grid with bells and whistles, showing examples of SQLPage features. +*/ +select + 'card' as "component", + 'Popular SQLPage features' as "title", + 2 as "columns"; + +select + 'Download as spreadsheet' as "title", + '/component.sql?component=csv#component' as "link", + 'Using the CSV component, you can download your data as a spreadsheet.' as "description", + 'file-plus' as "icon", + 'green' as "color", + 'SQLPage can both [read](/component.sql?component=form#component) and [write](/component.sql?component=csv#component) **CSV** files.' as "footer_md"; + +select + 'Custom components' as "title", + '/custom_components.sql' as "link", + 'If you know some HTML, you can create your own components for your application.' as "description", + 'code' as "icon", + 'orange' as "color", + 'You can look at the [source of the official components](https://github.com/sqlpage/SQLPage/tree/main/sqlpage/templates) for inspiration.' as "footer_md"; 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 new file mode 100644 index 000000000..f5fb24efd --- /dev/null +++ b/examples/official-site/reference/components/card/02-dashboard-with-markdown.sql @@ -0,0 +1,30 @@ +/* +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"; diff --git a/examples/official-site/reference/components/card/03-image-gallery.sql b/examples/official-site/reference/components/card/03-image-gallery.sql new file mode 100644 index 000000000..26bce3c09 --- /dev/null +++ b/examples/official-site/reference/components/card/03-image-gallery.sql @@ -0,0 +1,35 @@ +/* +A gallery of images +*/ +select + 'card' as "component", + 'My favorite animals in pictures' as "title", + 3 as "columns"; + +select + 'Lynx' as "title", + 'The **lynx** is a medium-sized **wild cat** native to Northern, Central and Eastern Europe to Central Asia and Siberia, the Tibetan Plateau and the Himalayas.' as "description_md", + 'A Eurasian lynx' as "top_image_alt", + 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Lynx_lynx_-_05.jpg/330px-Lynx_lynx_-_05.jpg' as "top_image", + 330 as "top_image_width", + 495 as "top_image_height", + TRUE as "top_image_lazy", + 'star' as "icon"; + +select + 'Squirrel' as "title", + 'The **chipmunk** is a small, striped rodent of the family Sciuridae. Chipmunks are found in North America, with the exception of the Siberian chipmunk which is found primarily in Asia.' as "description_md", + 'A squirrel eating a nut' as "top_image_alt", + 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/American_squirrel_eating_nut%2C_13_Jun_2013.JPG/330px-American_squirrel_eating_nut%2C_13_Jun_2013.JPG' as "top_image", + 330 as "top_image_width", + 495 as "top_image_height", + TRUE as "top_image_lazy"; + +select + 'Spider' as "title", + 'The **jumping spider family** (_Salticidae_) contains more than 600 described genera and about *6000 described species*, making it the largest family of spiders with about 13% of all species.' as "description_md", + 'An orb weaver spinning a web' as "top_image_alt", + 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Australian_orb_weaver_spinning_web.jpg/330px-Australian_orb_weaver_spinning_web.jpg' as "top_image", + 330 as "top_image_width", + 495 as "top_image_height", + TRUE as "top_image_lazy"; diff --git a/examples/official-site/reference/components/card/04-mixed-width-cards.sql b/examples/official-site/reference/components/card/04-mixed-width-cards.sql new file mode 100644 index 000000000..35e82ff95 --- /dev/null +++ b/examples/official-site/reference/components/card/04-mixed-width-cards.sql @@ -0,0 +1,30 @@ +/* +Cards with different widths + +Beautifully colored cards with variable width. The blue card (width 6) takes half the screen, whereas of the red and green cards have the default width of 3 +*/ +select + 'card' as "component", + 'Beautifully colored cards' as "title"; + +select + 'Red card' as "title", + 'red' as "color", + 'red-lt' as "background_color", + 'Penalty! You are out!' as "description", + 'play-football' as "icon"; + +select + 'Blue card' as "title", + 'blue' as "color", + 6 as "width", + 'blue-lt' as "background_color", + 'The Blue Card facilitates migration of foreigners to Europe.' as "description", + 'currency-euro' as "icon"; + +select + 'Green card' as "title", + 'green' as "color", + 'green-lt' as "background_color", + 'Welcome to the United States of America !' as "description", + 'user-dollar' as "icon"; diff --git a/examples/official-site/reference/components/card/05-embedded-chart-and-video.sql b/examples/official-site/reference/components/card/05-embedded-chart-and-video.sql new file mode 100644 index 000000000..e8f8389f3 --- /dev/null +++ b/examples/official-site/reference/components/card/05-embedded-chart-and-video.sql @@ -0,0 +1,20 @@ +/* +Cards with embedded content + +The first card embeds a SQLPage chart as a page fragment. The second embeds a video player in an iframe with its own `height` and `allow` attributes. +*/ +select + 'card' as "component", + 'Card with embedded remote content' as "title", + 2 as "columns"; + +select + 'Embedded Chart' as "title", + '/examples/chart.sql' as "embed"; + +select + 'Embedded Video' as "title", + 'https://www.youtube.com/embed/mXdgmSdaXkg' as "embed", + 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share' as "allow", + 'iframe' as "embed_mode", + '350' as "height"; 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 new file mode 100644 index 000000000..a83d9c842 --- /dev/null +++ b/examples/official-site/reference/components/carousel/01-animal-image-carousel.sql @@ -0,0 +1,15 @@ +/* +A basic example of carousel +*/ +select + 'carousel' as "component", + 'cats1' as "name", + 'Famous Database Animals' as "title"; + +select + 'African elephants at a watering hole' as "image_alt", + 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Elefantes_africanos_de_sabana_%28Loxodonta_africana%29%2C_Elephant_Sands%2C_Botsuana%2C_2018-07-28%2C_DD_114-117_PAN.jpg/1280px-Elefantes_africanos_de_sabana_%28Loxodonta_africana%29%2C_Elephant_Sands%2C_Botsuana%2C_2018-07-28%2C_DD_114-117_PAN.jpg' as "image"; + +select + 'A panoramic view of Penguin Island' as "image_alt", + 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Penguin_Island_panorama_with_ferry_and_dolphins_in_foreground%2C_March_2023_06.jpg/1280px-Penguin_Island_panorama_with_ferry_and_dolphins_in_foreground%2C_March_2023_06.jpg' as "image"; diff --git a/examples/official-site/reference/components/carousel/02-autoplay-with-controls.sql b/examples/official-site/reference/components/carousel/02-autoplay-with-controls.sql new file mode 100644 index 000000000..c16ed2c8c --- /dev/null +++ b/examples/official-site/reference/components/carousel/02-autoplay-with-controls.sql @@ -0,0 +1,22 @@ +/* +An advanced example of carousel with controls +*/ +select + 'carousel' as "component", + 'SQL web apps' as "title", + 10 as "width", + TRUE as "center", + TRUE as "controls", + TRUE as "auto"; + +select + '/sqlpage_cover_image.webp' as "image", + 'SQLPage is modern' as "title", + 'Built by engineers who have built so many web applications the old way, they decided they just wouldn''t anymore.' as "description", + 512 as "height"; + +select + '/sqlpage_illustration_alien.webp' as "image", + 'SQLPage is easy' as "title", + 'SQLPage connects to your database, then it turns your SQL queries into nice websites.' as "description", + 512 as "height"; diff --git a/examples/official-site/reference/components/chart/01-time-series-area-chart.sql b/examples/official-site/reference/components/chart/01-time-series-area-chart.sql new file mode 100644 index 000000000..c00a54b6e --- /dev/null +++ b/examples/official-site/reference/components/chart/01-time-series-area-chart.sql @@ -0,0 +1,20 @@ +/* +An area chart with a time axis + +Set the top-level property `time` to plot timestamps. The chart formats ISO datetimes and adjusts the x-axis ticks automatically. +*/ +select + 'chart' as "component", + 'Quarterly Revenue' as "title", + 'area' as "type", + 'blue-lt' as "color", + 5 as "marker", + TRUE as "time"; + +select '2022-01-01T00:00:00Z' as "x", 15 as "y" +union all select '2022-04-01T00:00:00Z', 46 +union all select '2022-07-01T00:00:00Z', 23 +union all select '2022-10-01T00:00:00Z', 70 +union all select '2023-01-01T00:00:00Z', 35 +union all select '2023-04-01T00:00:00Z', 106 +union all select '2023-07-01T00:00:00Z', 53; diff --git a/examples/official-site/reference/components/chart/02-pie-chart.sql b/examples/official-site/reference/components/chart/02-pie-chart.sql new file mode 100644 index 000000000..4c9e72c55 --- /dev/null +++ b/examples/official-site/reference/components/chart/02-pie-chart.sql @@ -0,0 +1,11 @@ +/* +A pie chart +*/ +select + 'chart' as "component", + 'Answers' as "title", + 'pie' as "type", + TRUE as "labels"; + +select 'Yes' as "label", 65 as "value" +union all select 'No', 35; diff --git a/examples/official-site/reference/components/chart/03-bar-chart.sql b/examples/official-site/reference/components/chart/03-bar-chart.sql new file mode 100644 index 000000000..c2d682f74 --- /dev/null +++ b/examples/official-site/reference/components/chart/03-bar-chart.sql @@ -0,0 +1,12 @@ +/* +A basic bar chart +*/ +select + 'chart' as "component", + 'bar' as "type", + 'Quarterly Results' as "title", + TRUE as "horizontal", + TRUE as "labels"; + +select 'Tom' as "label", 35 as "value" +union all select 'Olive', 15; diff --git a/examples/official-site/reference/components/chart/04-treemap.sql b/examples/official-site/reference/components/chart/04-treemap.sql new file mode 100644 index 000000000..1e8b7ebdb --- /dev/null +++ b/examples/official-site/reference/components/chart/04-treemap.sql @@ -0,0 +1,17 @@ +/* +A treemap chart + +A TreeMap Chart allows you to display hierarchical data in a nested layout. This is useful for visualizing the proportion of each part to the whole. +*/ +select + 'chart' as "component", + 'treemap' as "type", + 'Quarterly Results By Region (in k$)' as "title", + TRUE as "labels"; + +select 'North America' as "series", 'United States' as "label", 35 as "value" +union all select 'North America', 'Canada', 15 +union all select 'Europe', 'France', 30 +union all select 'Europe', 'Germany', 55 +union all select 'Asia', 'China', 20 +union all select 'Asia', 'Japan', 10; diff --git a/examples/official-site/reference/components/chart/05-multi-series-bar-chart.sql b/examples/official-site/reference/components/chart/05-multi-series-bar-chart.sql new file mode 100644 index 000000000..e98d7583c --- /dev/null +++ b/examples/official-site/reference/components/chart/05-multi-series-bar-chart.sql @@ -0,0 +1,16 @@ +/* +A bar chart with multiple series +*/ +select + 'chart' as "component", + 'Expenses' as "title", + 'bar' as "type", + TRUE as "stacked", + TRUE as "toolbar", + FALSE as "show_legend", + 10 as "ystep"; + +select 'Marketing' as "series", 2021 as "x", 35 as "value" +union all select 'Marketing', 2022, 15 +union all select 'Human resources', 2021, 30 +union all select 'Human resources', 2022, 55; diff --git a/examples/official-site/reference/components/chart/06-stacked-area-chart.sql b/examples/official-site/reference/components/chart/06-stacked-area-chart.sql new file mode 100644 index 000000000..a64285d59 --- /dev/null +++ b/examples/official-site/reference/components/chart/06-stacked-area-chart.sql @@ -0,0 +1,28 @@ +/* +A stacked area chart + +A stacked area chart, showing how each series contributes to a total. +The `stacked` property also works with the `line` and `bar` chart types. + +Series are aligned on their `x` values, and a series that has no value for a given `x` counts as zero there: +below, the graphics card draws no power outside of the render. +If a missing value does not mean zero in your data, make all the series share the same `x` values, +for instance by rounding timestamps to a common interval. +*/ +select + 'chart' as "component", + 'Power draw' as "title", + 'area' as "type", + TRUE as "stacked", + TRUE as "time", + 'watts' as "ytitle", + 'blue' as "color", + 'teal' as "color", + 4 as "marker"; + +select 'CPU' as "series", '2024-03-01T10:00:00Z' as "x", 45 as "value" +union all select 'CPU', '2024-03-01T10:15:00Z', 52 +union all select 'CPU', '2024-03-01T10:30:00Z', 48 +union all select 'CPU', '2024-03-01T10:45:00Z', 44 +union all select 'GPU', '2024-03-01T10:15:00Z', 120 +union all select 'GPU', '2024-03-01T10:30:00Z', 140; diff --git a/examples/official-site/reference/components/chart/07-multi-series-line-chart.sql b/examples/official-site/reference/components/chart/07-multi-series-line-chart.sql new file mode 100644 index 000000000..f05b2d6c1 --- /dev/null +++ b/examples/official-site/reference/components/chart/07-multi-series-line-chart.sql @@ -0,0 +1,18 @@ +/* +A line chart with multiple series + +A line chart with multiple series. One of the most common types of charts, often used to show trends over time. +Also demonstrates the use of the `toolbar` attribute to allow the user to download the graph as an image or the data as a CSV file. +*/ +select + 'chart' as "component", + 'Revenue' as "title", + 0 as "ymin", + TRUE as "toolbar"; + +select 'Chicago Store' as "series", 2021 as "x", 35 as "value" +union all select 'Chicago Store', 2022, 15 +union all select 'Chicago Store', 2023, 45 +union all select 'New York Store', 2021, 30 +union all select 'New York Store', 2022, 55 +union all select 'New York Store', 2023, 19; diff --git a/examples/official-site/reference/components/chart/08-custom-scatter-plot.sql b/examples/official-site/reference/components/chart/08-custom-scatter-plot.sql new file mode 100644 index 000000000..7c63b6fd4 --- /dev/null +++ b/examples/official-site/reference/components/chart/08-custom-scatter-plot.sql @@ -0,0 +1,22 @@ +/* +A scatter plot with multiple custom options +*/ +select + 'chart' as "component", + 'Gross domestic product and its growth' as "title", + 'scatter' as "type", + 'Growth Rate' as "xtitle", + 'GDP (Trillions USD)' as "ytitle", + 500 as "height", + 8 as "marker", + 0 as "xmin", + 10 as "xmax", + 0 as "ymin", + 25 as "ymax", + 5 as "yticks"; + +select 'Brazil' as "series", 2.5 as "x", 2 as "y" +union all select 'China', 6.5, 14 +union all select 'United States', 2.3, 21 +union all select 'France', 1.5, 3 +union all select 'South Africa', 0.9, 0.3; diff --git a/examples/official-site/reference/components/chart/09-heatmap.sql b/examples/official-site/reference/components/chart/09-heatmap.sql new file mode 100644 index 000000000..ce82aff21 --- /dev/null +++ b/examples/official-site/reference/components/chart/09-heatmap.sql @@ -0,0 +1,32 @@ +/* +Heatmaps + +Set `type` to `heatmap` on the chart row. + +The data format follows the [apexcharts heatmap format](https://apexcharts.com/angular-chart-demos/heatmap-charts/basic/), +where each series is represented as a line in the chart: + - The `x` property of each item will be used as the x-axis value. + - The `series` property of each item will be used as the y-axis value. + - The `y` property of each item will be used as the value to display in the heatmap + +The `color` property sets the color of each series separately, in order. +*/ +select + 'chart' as "component", + 'Survey Results' as "title", + 'heatmap' as "type", + 'Database management system' as "ytitle", + 'Year' as "xtitle", + 'purple' as "color", + 'purple' as "color", + 'purple' as "color"; + +select 'PostgreSQL' as "series", '2000' as "x", 48 as "y" +union all select 'SQLite', '2000', 44 +union all select 'MySQL', '2000', 78 +union all select 'PostgreSQL', '2010', 65 +union all select 'SQLite', '2010', 62 +union all select 'MySQL', '2010', 83 +union all select 'PostgreSQL', '2020', 73 +union all select 'SQLite', '2020', 38 +union all select 'MySQL', '2020', 87; 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 new file mode 100644 index 000000000..72862a1cc --- /dev/null +++ b/examples/official-site/reference/components/chart/10-timeline-with-links.sql @@ -0,0 +1,34 @@ +/* +A timeline chart with links + +A timeline displaying events with a start and an end date. A data row can include a `link` to open when its bar or tooltip title is clicked. +*/ +select + 'chart' as "component", + 'Project Timeline' as "title", + 'rangeBar' as "type", + TRUE as "time", + 'teal' as "color", + 'cyan' as "color", + TRUE as "labels", + '2021-12-28' as "xmin", + '2022-01-04' as "xmax"; + +select + 'Phase 1' as "series", + 'Operations' as "label", + '2021-12-29' as "value", + '2022-01-02' as "value", + '/examples/chart.sql?phase=1' as "link"; + +select + 'Phase 2' as "series", + 'Operations' as "label", + '2022-01-03' as "value", + '2022-01-04' as "value"; + +select + 'Yearly maintenance' as "series", + 'Maintenance' as "label", + '2022-01-01' as "value", + '2022-01-03' as "value"; 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 new file mode 100644 index 000000000..f392faa0d --- /dev/null +++ b/examples/official-site/reference/components/chart/11-color-individual-values.sql @@ -0,0 +1,32 @@ +/* +Coloring a single value + +A data row can carry its own `color`, to paint the one bar, slice or point it +plots. Use it when the color says something the axes do not: a threshold +crossed, a status, the one category the reader should look at first. + +```sql +select 'chart' as component, 'bar' as type, true as horizontal, + true as labels, false as show_legend; +select + window_label as label, + accounts as value, + case when days <= 30 then 'red' when days <= 60 then 'orange' else 'green' end as color +from expiring_accounts order by days; +``` + +A row color takes precedence over the color of its series. On a `line` or an +`area` chart it paints the marker of the point, so set `marker` for it to show. +A `heatmap` shades its cells from their own value and ignores it. +*/ +select + 'chart' as "component", + 'Accounts expiring soon' as "title", + 'bar' as "type", + TRUE as "horizontal", + 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'; diff --git a/examples/official-site/reference/components/chart/12-pie-slice-colors.sql b/examples/official-site/reference/components/chart/12-pie-slice-colors.sql new file mode 100644 index 000000000..f982bc89a --- /dev/null +++ b/examples/official-site/reference/components/chart/12-pie-slice-colors.sql @@ -0,0 +1,12 @@ +/* +A pie chart whose rows choose their own slice colors +*/ +select + 'chart' as "component", + 'Support tickets' as "title", + 'pie' as "type", + TRUE as "labels"; + +select 'Resolved' as "label", 72 as "value", 'green' as "color" +union all select 'In progress', 21, 'yellow' +union all select 'Overdue', 7, 'red'; 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 new file mode 100644 index 000000000..d0a3919d1 --- /dev/null +++ b/examples/official-site/reference/components/chart/13-y-axis-reference-lines.sql @@ -0,0 +1,51 @@ +/* +Reference lines + +A row with a `yline` is not plotted as a data point, but drawn as a line across +the whole chart, at that value of the y axis. Use it for the limit that the data +should be read against: a disk quota, an alarm threshold, a service level +objective. Add `yline_end` to make it a band instead of a line. + +Reference lines are rows, so they come from a query like everything else, +and a chart can have as many of them as the query returns: + +```sql +select 'chart' as component, 'CPU temperature' as title, true as time, 100 as ymax; +select celsius as yline, name as label, color as color from thresholds; +select measured_at as x, celsius as y from readings order by measured_at; +``` + +They are drawn as annotations rather than as an extra series, so they are not +added to the total of a `stacked` chart, and are not filled in an `area` chart. + +A line outside of the y axis is not drawn, and does not stretch the axis to fit, +so set `ymax` when the limit is above the data. +*/ +select + 'chart' as "component", + 'CPU temperature' as "title", + 'line' as "type", + TRUE as "time", + '°C' as "ytitle", + 100 as "ymax", + '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; 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 new file mode 100644 index 000000000..9b3b2083e --- /dev/null +++ b/examples/official-site/reference/components/chart/14-x-axis-event-markers.sql @@ -0,0 +1,45 @@ +/* +Marking events + +`xline` is the counterpart of `yline`: it marks a position on the x axis instead +of a value on the y axis. On its own it marks a moment, like a deployment. +With `xline_end`, it covers everything in between, like an incident or a +maintenance window. A single query can draw a whole log of them: + +```sql +select started_at as xline, ended_at as xline_end, summary as label, + case severity when 'outage' then 'red' else 'orange' end as color +from incidents where started_at > $since; +``` + +When `time` is set, an `xline` is a date or a timestamp, written like the `x` of +a data point. On a chart with text labels on the x axis, it is one of those labels. +*/ +select + 'chart' as "component", + 'Request latency' as "title", + 'area' as "type", + TRUE as "time", + 'ms' as "ytitle", + '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; 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 new file mode 100644 index 000000000..dca222f0a --- /dev/null +++ b/examples/official-site/reference/components/chart/15-reference-lines-on-horizontal-bars.sql @@ -0,0 +1,42 @@ +/* +Reference lines follow their axis + +A reference belongs to the column it is written in, not to a direction on the +screen. `yline` always marks a value of `y`, and `xline` a position on `x`, +whichever way round the chart is drawn. A `horizontal` bar chart runs its y axis +from left to right, so a `yline` is drawn down the chart and an `xline` picks out +one of the bars. + +```sql +select 'chart' as component, 'bar' as type, true as horizontal, 100 as ymax; +select 90 as yline, 'full' as label, 'red' as color; +select 'db-1' as xline, 'watched' as label, 'purple' as color; +select host as x, percent_used as y from disks order by percent_used; +``` + +A `pie` has no axes and ignores reference lines, and on a `heatmap`, whose y axis +holds the names of the series, only `xline` has a meaning. +*/ +select + 'chart' as "component", + 'Disk usage' as "title", + 'bar' as "type", + TRUE as "horizontal", + 100 as "ymax", + '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; diff --git a/examples/official-site/reference/components/chart/16-side-by-side-charts.sql b/examples/official-site/reference/components/chart/16-side-by-side-charts.sql new file mode 100644 index 000000000..acca41b20 --- /dev/null +++ b/examples/official-site/reference/components/chart/16-side-by-side-charts.sql @@ -0,0 +1,17 @@ +/* +Multiple charts on the same line + +You can create information-dense dashboards by using the [card component](/component.sql?component=card#component) +to put multiple charts on the same line. + +For this, create one sql file per visualization you want to show, +and set the `embed` attribute of the [card](/component.sql?component=card#component) component +to the path of the file you want to include, followed by `?_sqlpage_embed`. +*/ +select + 'card' as "component", + 'A dashboard with multiple graphs on the same line' as "title", + 2 as "columns"; + +select '/examples/chart.sql?color=green&n=42&_sqlpage_embed' as "embed" +union all select '/examples/chart.sql?_sqlpage_embed'; diff --git a/examples/official-site/reference/components/code/01-display-html-source.sql b/examples/official-site/reference/components/code/01-display-html-source.sql new file mode 100644 index 000000000..37e6450e2 --- /dev/null +++ b/examples/official-site/reference/components/code/01-display-html-source.sql @@ -0,0 +1,24 @@ +/* +Display HTML source + +Displays a block of HTML code. +*/ +select + 'code' as "component"; + +select + 'A HTML5 example' as "title", + 'html' as "language", + 'Here’s the very minimum that an HTML document should contain, assuming it has CSS and JavaScript linked to it.' as "description", + ' + + + + title + + + + + + +' as "contents"; diff --git a/examples/official-site/reference/components/columns/01-pricing-plans.sql b/examples/official-site/reference/components/columns/01-pricing-plans.sql new file mode 100644 index 000000000..b69c59267 --- /dev/null +++ b/examples/official-site/reference/components/columns/01-pricing-plans.sql @@ -0,0 +1,44 @@ +/* +Pricing Plans Display +*/ +select + 'columns' as "component"; + +select + 'Start Plan' as "title", + '€18' as "value", + 'Perfect for testing and small-scale projects' as "description", + '128MB Database' as "item", + 'SQLPage hosting' as "item", + 'Community support' as "item", + 'https://datapage.app' as "link", + 'Start Free Trial' as "button_text", + '/month' as "small_text"; + +select + 'Pro Plan' as "title", + '€40' as "value", + 'rocket' as "icon", + 'For growing projects needing enhanced features' as "description", + JSON('{"icon":"database","color":"blue","description":"1GB Database"}') as "item", + JSON('{"icon":"headset","color":"green","description":"Priority Support"}') as "item", + JSON('{"icon":"world","color":"purple","description":"Custom Domain"}') as "item", + 'https://datapage.app' as "link", + 'Start Free Trial' as "button_text", + 'indigo' as "button_color", + 'indigo' as "value_color", + '/month' as "small_text"; + +select + 'Enterprise Plan' as "title", + '€600' as "value", + 'building-skyscraper' as "icon", + 'For large-scale operations with custom needs' as "description", + JSON('{"icon":"database-plus","description_md":"**Custom Database Scaling**"}') as "item", + JSON('{"icon":"shield-lock","description_md":"**Enterprise Auth** with Single Sign-On"}') as "item", + JSON('{"icon":"headset","description_md":"**Monthly** Expert Support time"}') as "item", + JSON('{"icon":"file-certificate","description_md":"**SLA** with guaranteed uptime"}') as "item", + 'mailto:contact@datapage.app' as "link", + 'Contact Us' as "button_text", + '/month' as "small_text", + '_blank' as "target"; 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 new file mode 100644 index 000000000..f7bd46bdd --- /dev/null +++ b/examples/official-site/reference/components/columns/02-tech-company-kpis.sql @@ -0,0 +1,38 @@ +/* +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"; 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 new file mode 100644 index 000000000..e10b2e360 --- /dev/null +++ b/examples/official-site/reference/components/cookie/01-set-and-read-a-cookie.md @@ -0,0 +1,17 @@ +# 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/README.md b/examples/official-site/reference/components/cookie/README.md new file mode 100644 index 000000000..c92f82720 --- /dev/null +++ b/examples/official-site/reference/components/cookie/README.md @@ -0,0 +1,21 @@ +Set a cookie in the visitor's browser. + +Each call sets one cookie for session management or other visitor-specific information. Since cookies need to be set before the response body is sent to the client, +this component should be **placed at the top of the page**, before any other components that generate output. + +After being set, a cookie can be accessed anywhere in your SQL code using the `sqlpage.cookie('cookie_name')` pseudo-function. + +Note that if your site is accessed over HTTP (and not HTTPS), you have to set `false as secure` to force browsers to accept your cookies. + +## Top-level parameters + + - **name** (TEXT, required): The name of the cookie to set. + - **domain** (TEXT): The domain for which the cookie will be sent. If not specified, the cookie will be sent for all domains. + - **expires** (TIMESTAMP): The date at which the cookie expires (either a timestamp or a date object). If not specified, the cookie will expire when the browser is closed. + - **http_only** (BOOLEAN): Whether the cookie should only be accessible via HTTP and not via client-side scripts. If explicitly set to false, the cookie will be accessible via both HTTP and client-side scripts. + - **max_age** (INTEGER): The maximum age of the cookie in seconds. number of seconds until the cookie expires. If both Expires and Max-Age are set, Max-Age has precedence. + - **path** (TEXT): The path for which the cookie will be sent. If not specified, the cookie will be sent for all paths. + - **remove** (BOOLEAN): Set to TRUE to remove the cookie from the client browser. When specified, other parameters are ignored. + - **same_site** (TEXT): Whether the cookie should only be sent for requests originating from the same site. See owasp.org/www-community/SameSite. `strict` is the recommended and default value, but you may want to set it to `lax` if you want your users to keep their session when they click on a link to your site from an external site. + - **secure** (BOOLEAN): Whether the cookie should only be sent over a secure (HTTPS) connection. Defaults to TRUE. + - **value** (TEXT): The value of the cookie to set. 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 new file mode 100644 index 000000000..861de2b5c --- /dev/null +++ b/examples/official-site/reference/components/csv/01-csv-download-url.sql @@ -0,0 +1,21 @@ +/* +Create a CSV download URL + +You can create a page that will trigger a download of the CSV file when the user visits it. +The contents will be streamed efficiently from the database to the browser, without being fully loaded in memory. +This makes it possible to download even very large files without overloading the database server, the web server, or the client's browser. + +#### `csv_download.sql` + +```sql +select 'csv' as component, 'example.csv' as filename; +SELECT * FROM my_large_table; +``` + +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"; + +select + 'Download my data' as "title", + '/examples/csv_download.sql' as "link"; 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 new file mode 100644 index 000000000..0a9deaad2 --- /dev/null +++ b/examples/official-site/reference/components/csv/02-csv-download-button.sql @@ -0,0 +1,19 @@ +/* +CSV download button + +This will generate a button to download the CSV file. +The button element itself will embed the entire contents of the CSV file, so it should not be used for large files. +The file will be entirely loaded in memory on the user's browser, even if the user does not click on the button. +For smaller files, this is easier and faster to use than creating a separate SQL file to generate the CSV. +*/ +select + 'csv' as "component", + 'Download my data' as "title", + 'people' 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'; diff --git a/examples/official-site/reference/components/datagrid/01-sql-language-facts.sql b/examples/official-site/reference/components/datagrid/01-sql-language-facts.sql new file mode 100644 index 000000000..d638674be --- /dev/null +++ b/examples/official-site/reference/components/datagrid/01-sql-language-facts.sql @@ -0,0 +1,8 @@ +/* +Just some sections of information +*/ +select 'datagrid' as "component"; + +select 'Language' as "title", 'SQL' as "description" +union all select 'Creation date', '1974' +union all select 'Language family', 'Query language'; diff --git a/examples/official-site/reference/components/datagrid/02-profile-with-colors-and-icons.sql b/examples/official-site/reference/components/datagrid/02-profile-with-colors-and-icons.sql new file mode 100644 index 000000000..672e3c017 --- /dev/null +++ b/examples/official-site/reference/components/datagrid/02-profile-with-colors-and-icons.sql @@ -0,0 +1,31 @@ +/* +A beautiful data grid with nice colors and icons +*/ +select + 'datagrid' as "component", + 'Ophir Lojkine' as "title", + 'https://avatars.githubusercontent.com/u/552629' as "image_url", + 'Member since **2021**' as "description_md"; + +select + 'Pseudo' as "title", + 'lovasoa' as "description", + 'https://avatars.githubusercontent.com/u/552629' as "image_url"; + +select + 'Status' as "title", + 'Active' as "description", + 'green' as "color"; + +select + 'Email Status' as "title", + 'Validated' as "description", + 'check' as "icon", + TRUE as "active", + 'Email address has been validated.' as "tooltip"; + +select + 'Personal page' as "title", + 'ophir.dev' as "description", + 'https://ophir.dev/' as "link", + 'About me' as "tooltip"; diff --git a/examples/official-site/reference/components/datagrid/03-website-ideas-with-links.sql b/examples/official-site/reference/components/datagrid/03-website-ideas-with-links.sql new file mode 100644 index 000000000..f0e064a65 --- /dev/null +++ b/examples/official-site/reference/components/datagrid/03-website-ideas-with-links.sql @@ -0,0 +1,23 @@ +/* +Website ideas with links +*/ +select + 'datagrid' as "component", + 'Website Ideas' as "title", + 'bulb' as "icon"; + +select + 'Search engine' as "title", + 'https://google.com' as "link", + 'Google' as "description", + 'red' as "color", + 'brand-google' as "icon", + 'Owned by Alphabet Inc.' as "footer"; + +select + 'Encyclopedia' as "title", + 'https://wikipedia.org' as "link", + 'Wikipedia' as "description", + 'blue' as "color", + 'world' as "icon", + 'Owned by the Wikimedia Foundation' as "footer"; diff --git a/examples/official-site/reference/components/debug/01-inspect-component-parameters.sql b/examples/official-site/reference/components/debug/01-inspect-component-parameters.sql new file mode 100644 index 000000000..75d9cea57 --- /dev/null +++ b/examples/official-site/reference/components/debug/01-inspect-component-parameters.sql @@ -0,0 +1,16 @@ +/* +Inspect the parameters passed to a component + +At any time, if you are confused about what data you are passing to a component, just replace the component name with 'debug' to see all the parameters that are passed to it. +*/ +select + 'debug' as "component", + TRUE as "my_top_level_property"; + +select + 'y' as "x", + 42 as "z"; + +select + 'b' as "a", + NULL as "c"; 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 new file mode 100644 index 000000000..ed5106899 --- /dev/null +++ b/examples/official-site/reference/components/debug/02-inspect-function-result.md @@ -0,0 +1,7 @@ +# 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/divider/01-empty-divider.sql b/examples/official-site/reference/components/divider/01-empty-divider.sql new file mode 100644 index 000000000..cede8b5c6 --- /dev/null +++ b/examples/official-site/reference/components/divider/01-empty-divider.sql @@ -0,0 +1,5 @@ +/* +An empty divider +*/ +select + 'divider' as "component"; diff --git a/examples/official-site/reference/components/divider/02-centered-text.sql b/examples/official-site/reference/components/divider/02-centered-text.sql new file mode 100644 index 000000000..a4aa74562 --- /dev/null +++ b/examples/official-site/reference/components/divider/02-centered-text.sql @@ -0,0 +1,6 @@ +/* +A divider with centered text +*/ +select + 'divider' as "component", + 'Hello' as "contents"; diff --git a/examples/official-site/reference/components/divider/03-left-aligned-text.sql b/examples/official-site/reference/components/divider/03-left-aligned-text.sql new file mode 100644 index 000000000..d2d59cd13 --- /dev/null +++ b/examples/official-site/reference/components/divider/03-left-aligned-text.sql @@ -0,0 +1,7 @@ +/* +A divider with text at left +*/ +select + 'divider' as "component", + 'Hello' as "contents", + 'left' as "position"; diff --git a/examples/official-site/reference/components/divider/04-blue-link.sql b/examples/official-site/reference/components/divider/04-blue-link.sql new file mode 100644 index 000000000..a291f235e --- /dev/null +++ b/examples/official-site/reference/components/divider/04-blue-link.sql @@ -0,0 +1,8 @@ +/* +A divider with blue text and a link +*/ +select + 'divider' as "component", + 'SQLPage components' as "contents", + '/documentation.sql' as "link", + 'blue' as "color"; diff --git a/examples/official-site/reference/components/divider/05-formatted-text.sql b/examples/official-site/reference/components/divider/05-formatted-text.sql new file mode 100644 index 000000000..f1bf445e2 --- /dev/null +++ b/examples/official-site/reference/components/divider/05-formatted-text.sql @@ -0,0 +1,12 @@ +/* +A divider with bold, italic, and underlined text +*/ +select + 'divider' as "component", + 'Important notice' as "contents", + 'left' as "position", + 'red' as "color", + 5 as "size", + TRUE as "bold", + TRUE as "italics", + TRUE as "underline"; diff --git a/examples/official-site/reference/components/download/01-plain-text-file.standalone.sql b/examples/official-site/reference/components/download/01-plain-text-file.standalone.sql new file mode 100644 index 000000000..4a2512764 --- /dev/null +++ b/examples/official-site/reference/components/download/01-plain-text-file.standalone.sql @@ -0,0 +1,9 @@ +/* +Download a plain text file + +Download a small text file. The content is URL-encoded (spaces become %20). +*/ +select + 'download' as component, + 'data:text/plain,Hello%20SQLPage%20world!' as data_url, + 'hello.txt' as filename; 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 new file mode 100644 index 000000000..1c9ce1fa3 --- /dev/null +++ b/examples/official-site/reference/components/download/02-pdf-from-server.md @@ -0,0 +1,11 @@ +# 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/03-image-from-a-blob.md b/examples/official-site/reference/components/download/03-image-from-a-blob.md new file mode 100644 index 000000000..1670ae3ad --- /dev/null +++ b/examples/official-site/reference/components/download/03-image-from-a-blob.md @@ -0,0 +1,32 @@ +# Serve an image stored as a BLOB in the database + +### Automatically detect the mime type + +If you have a table with a column `content` that contains a BLOB +(depending on the database, the type may be named `BYTEA`, `BLOB`, `VARBINARY`, or `IMAGE`), +you can just return its contents directly, and SQLPage will automatically detect the mime type, +and convert it to a data URL. + +```sql +select + 'download' as component, + content as data_url +from document +where id = $doc_id; +``` + +### Customize the mime type + +In PostgreSQL, you can use the [encode(bytes, format)](https://www.postgresql.org/docs/current/functions-binarystring.html#FUNCTION-ENCODE) function to encode the file content as Base64, +and manually create your own data URL. + +```sql +select + 'download' as component, + 'data:' || doc.mime_type || ';base64,' || encode(doc.content::bytea, 'base64') as data_url +from document as doc +where doc.id = $doc_id; +``` + + - In Microsoft SQL Server, you can use the [BASE64_ENCODE(bytes)](https://learn.microsoft.com/en-us/sql/t-sql/functions/base64-encode-transact-sql) function to encode the file content as Base64. + - In MySQL and MariaDB, you can use the [TO_BASE64(str)](https://mariadb.com/docs/server/reference/sql-functions/string-functions/to_base64) function. diff --git a/examples/official-site/reference/components/download/README.md b/examples/official-site/reference/components/download/README.md new file mode 100644 index 000000000..2104c6559 --- /dev/null +++ b/examples/official-site/reference/components/download/README.md @@ -0,0 +1,32 @@ +Send a file directly to the visitor. + +Put `download` **at the top of your SQL page**, before the shell or any other component that displays content. The file's bytes are the entire response. + +## Sending a file + +- You provide the file content using a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs). +A data URL is just a text string that contains both the file type and the actual data. +- Optionally, you provide a "filename" so the browser shows a proper Save As name. +If you do not provide a filename, many browsers will try to display the file inline (for example images or JSON), depending on the content type. +- You link to the page that uses the download component from another page, using the [button](/component.sql?component=button) component for example. + +## Data URL format + +- It looks like this: `data:[content-type][;base64],DATA` +- Examples: + - Plain text (URL-encoded): `data:text/plain,Hello%20world` + - JSON (URL-encoded): `data:application/json,%7B%22message%22%3A%22Hi%22%7D` + - Binary data (Base64): `data:application/octet-stream;base64,SGVsbG8h` + +Tips: +- Use URL encoding when you have textual data. You can use [`sqlpage.url_encode(source_text)`](/functions?function=url_encode) to encode the data. +- Use Base64 when you have binary data (images, PDFs, or content that may include special characters). +- Use [`sqlpage.read_file_as_data_url(file_path)`](/functions?function=read_file_as_data_url) to read a file from the server and return it as a data URL. + +> Keep in mind that large files are better served from disk or object storage. Data URLs are best for small to medium files. +There is a big performance penalty for loading large files as data URLs, so it is not recommended. + +## Top-level parameters + + - **data_url** (TEXT, required): The file content to send, written as a data URL (for example: data:text/plain,Hello%20world or data:application/octet-stream;base64,SGVsbG8h). The part before the comma declares the content type and whether the data is base64-encoded. The part after the comma is the actual data. + - **filename** (TEXT): The suggested name of the file to save (for example: report.csv). When set, the browser will download the file as an attachment with this name. When omitted, many browsers may try to display the file inline depending on its content type. diff --git a/examples/official-site/reference/components/dynamic/01-render-text-from-json.sql b/examples/official-site/reference/components/dynamic/01-render-text-from-json.sql new file mode 100644 index 000000000..ad31e249a --- /dev/null +++ b/examples/official-site/reference/components/dynamic/01-render-text-from-json.sql @@ -0,0 +1,9 @@ +/* +Render a text component from JSON + +The dynamic component has a single top-level property named `properties`, but it can render any number of other components. +Let's start with something simple to illustrate the logic. We'll render a `text` component with two row-level properties: `contents` and `italics`. +*/ +select + 'dynamic' as "component", + '[{"component":"text"}, {"contents":"Hello, I am a dynamic component !", "italics":true}]' as "properties"; 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 new file mode 100644 index 000000000..ece37ba42 --- /dev/null +++ b/examples/official-site/reference/components/dynamic/02-read-static-json-file.md @@ -0,0 +1,32 @@ +# 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/03-include-another-sql-file.md b/examples/official-site/reference/components/dynamic/03-include-another-sql-file.md new file mode 100644 index 000000000..c0c74d0f2 --- /dev/null +++ b/examples/official-site/reference/components/dynamic/03-include-another-sql-file.md @@ -0,0 +1,22 @@ +# 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/04-dynamic-shell.md b/examples/official-site/reference/components/dynamic/04-dynamic-shell.md new file mode 100644 index 000000000..39632eca6 --- /dev/null +++ b/examples/official-site/reference/components/dynamic/04-dynamic-shell.md @@ -0,0 +1,29 @@ +# 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/05-dynamic-table-columns.md b/examples/official-site/reference/components/dynamic/05-dynamic-table-columns.md new file mode 100644 index 000000000..b31bc5f59 --- /dev/null +++ b/examples/official-site/reference/components/dynamic/05-dynamic-table-columns.md @@ -0,0 +1,18 @@ +# 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/README.md b/examples/official-site/reference/components/dynamic/README.md new file mode 100644 index 000000000..0f305640a --- /dev/null +++ b/examples/official-site/reference/components/dynamic/README.md @@ -0,0 +1,7 @@ +Render SQLPage components described by JSON data. + +Use `dynamic` to share components across pages, repeat components for query results, or render multiple components from a single row. + +## Top-level parameters + + - **properties** (JSON): A json object or array that contains the names and properties of other components. 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 new file mode 100644 index 000000000..316897519 --- /dev/null +++ b/examples/official-site/reference/components/empty_state/01-not-found-message.sql @@ -0,0 +1,17 @@ +/* +Show a not-found message + +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. +*/ +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"; 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 new file mode 100644 index 000000000..698f075cb --- /dev/null +++ b/examples/official-site/reference/components/empty_state/02-error-with-illustration.sql @@ -0,0 +1,15 @@ +/* +Show an illustration + +It's possible to use an icon or an image to illustrate the problem. +*/ +select + 'empty_state' as "component", + 'A critical problem has occurred' as "title", + 'mood-wrrr' as "icon", + '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", + 'rotate-clockwise' as "link_icon", + '#' 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 new file mode 100644 index 000000000..988cb6c6a --- /dev/null +++ b/examples/official-site/reference/components/facet/01-category-selector-with-all-link.sql @@ -0,0 +1,26 @@ +/* +A category selector with an All link + +A category selector with an All link. In an application, use the selected `class` URL parameter to filter the displayed data. +*/ +select 'table' as "component"; + +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 + '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"; 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 new file mode 100644 index 000000000..4909fc554 --- /dev/null +++ b/examples/official-site/reference/components/facet/02-compact-facet-dropdown.sql @@ -0,0 +1,29 @@ +/* +A compact facet selector + +Compact mode displays the facet choices in a dropdown. +*/ +select 'table' as "component"; + +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 + '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"; diff --git a/examples/official-site/reference/components/foldable/01-foldable-paragraph.sql b/examples/official-site/reference/components/foldable/01-foldable-paragraph.sql new file mode 100644 index 000000000..6e4617e9e --- /dev/null +++ b/examples/official-site/reference/components/foldable/01-foldable-paragraph.sql @@ -0,0 +1,9 @@ +/* +A single foldable paragraph of text +*/ +select + 'foldable' as "component"; + +select + 'The foldable component' as "title", + 'This is a simple foldable component. It can be used to show and hide content. It is a list of items, each with a title and a description. The description is displayed when the item is expanded.' as "description"; diff --git a/examples/official-site/reference/components/foldable/02-foldable-markdown-list.sql b/examples/official-site/reference/components/foldable/02-foldable-markdown-list.sql new file mode 100644 index 000000000..df1cfc544 --- /dev/null +++ b/examples/official-site/reference/components/foldable/02-foldable-markdown-list.sql @@ -0,0 +1,42 @@ +/* +A SQLPage-themed foldable list with Markdown +*/ +select + 'foldable' as "component"; + +select + 'Quick Prototyping' as "title", + 'Build a functional web app prototype in minutes using just SQL queries: + +- Rapid development +- Ideal for MVPs +- Great for internal tools + +Learn more about [quick prototyping](/your-first-sql-website/).' as "description_md", + TRUE as "expanded"; + +select + 'Data Visualization' as "title", + 'Quickly transform your database into useful insights: + +1. **Charts**: Line, bar, pie +2. **KPIs**: Appealing visualizations of key metrics +3. **Maps**: Geospatial data + +As simple as: + +```sql +SELECT ''chart'' as component; +SELECT date as x, revenue as y FROM sales; +```' as "description_md"; + +select + 'Don''t stare, interact!' as "title", + 'SQLPage is not just a passive *Business Intelligence* tool. With SQLPage, you can act upon user input: + +- *User input collection*: Building a form is just as easy as building a chart. +- *Data validation*: Write your own validation rules in SQL. +- *Database updates*: `INSERT` and `UPDATE` are first-class citizens. +- *File uploads*: Upload `CSV` and other files, store and display them the way you want. + +> Let users interact with your data, not just look at it!' as "description_md"; 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 new file mode 100644 index 000000000..ac4623e03 --- /dev/null +++ b/examples/official-site/reference/components/form/01-separate-submission-handler.md @@ -0,0 +1,32 @@ +# Handle a form submission in a separate file + +The best way to manage forms in SQLPage is to create at least two separate files: + + - one that will contain the form itself, and will be loaded when the user visits the page, + - one that will handle the form submission, and will redirect to whatever page you want to display after the form has been submitted. + +For instance, if you were creating a form to manage a list of users, you could create: + + - a file named `users.sql` that would contain a list of users and a form to create a new user, + - a file named `create_user.sql` that would insert the new user in the database, and then redirect to `users.sql`. + +### `users.sql` + +```sql +select + 'form' as "component", + 'create_user.sql' as "action"; + +select 'username' as "name"; +``` + +### `create_user.sql` + +This statement can [safely](/safety.sql) insert the new user in the database: + +```sql +INSERT INTO users(name) VALUES(:username) +RETURNING 'redirect' AS component, 'users.sql' AS link; +``` + +When loading the page, the value for `:username` will be `NULL` if no value has been submitted. diff --git a/examples/official-site/reference/components/form/02-user-registration.sql b/examples/official-site/reference/components/form/02-user-registration.sql new file mode 100644 index 000000000..f9ba476a1 --- /dev/null +++ b/examples/official-site/reference/components/form/02-user-registration.sql @@ -0,0 +1,41 @@ +/* +A user registration form + +A user registration form, illustrating the use of required fields, and different input types. +*/ +select + 'form' as "component", + 'User' as "title", + 'Create new user' as "validate"; + +select + 'First name' as "name", + 'John' as "placeholder"; + +select + 'Last name' as "name", + TRUE as "required", + 'We need your last name for legal purposes.' as "description"; + +select + 'Resume' as "name", + 'textarea' as "type"; + +select + 'Birth date' as "name", + 'date' as "type", + '2010-01-01' as "max", + '1994-04-16' as "value"; + +select + 'Password' as "name", + 'password' as "type", + '^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$' as "pattern", + TRUE as "required", + '**Password Requirements:** Minimum **8 characters**, at least **one letter** & **one number**. *Tip:* Use a passphrase for better security!' as "description_md"; + +select + 'I accept the terms and conditions' as "label", + 'terms' as "name", + 'checkbox' as "type", + TRUE as "required"; diff --git a/examples/official-site/reference/components/form/03-input-prefix-and-suffix.sql b/examples/official-site/reference/components/form/03-input-prefix-and-suffix.sql new file mode 100644 index 000000000..4f06861d3 --- /dev/null +++ b/examples/official-site/reference/components/form/03-input-prefix-and-suffix.sql @@ -0,0 +1,12 @@ +/* +Inputs with a prefix or suffix + +Create prepended and appended inputs to make your forms easier to use. +*/ +select 'form' as "component"; + +select + 'Your account' as "name", + 'mail' as "prefix_icon", + 'Email:' as "prefix", + '@mydomain.com' as "suffix"; diff --git a/examples/official-site/reference/components/form/04-group-inputs-under-headers.sql b/examples/official-site/reference/components/form/04-group-inputs-under-headers.sql new file mode 100644 index 000000000..ab659b69d --- /dev/null +++ b/examples/official-site/reference/components/form/04-group-inputs-under-headers.sql @@ -0,0 +1,25 @@ +/* +Group inputs under headers + +With the header type, you can group your input fields based on a theme. For example, you can categorize fields according to a person's identity and their contact information. +*/ +select + 'form' as "component", + 'Information about the person' as "title"; + +select + 'header' as "type", + 'Identity' as "label"; + +select 'Name' as "name" +union all select 'Surname'; + +select + 'header' as "type", + 'Contact' as "label"; + +select + 'phone' as "name", + 'Phone number' as "label"; + +select 'Email' as "name"; diff --git a/examples/official-site/reference/components/form/05-toggle-switch.sql b/examples/official-site/reference/components/form/05-toggle-switch.sql new file mode 100644 index 000000000..40cf28164 --- /dev/null +++ b/examples/official-site/reference/components/form/05-toggle-switch.sql @@ -0,0 +1,25 @@ +/* +A toggle switch + +A toggle switch in an HTML form is a user interface element that allows users to switch between two states, typically "on" and "off." It visually resembles a physical switch and is often used for settings or options that can be enabled or disabled. +*/ +select 'form' as "component"; + +select + 'switch' as "type", + 'Dark theme' as "label", + 'dark' as "name", + 'Enable dark theme' as "description"; + +select + 'switch' as "type", + 'A required toggle switch' as "label", + 'my_checkbox' as "name", + TRUE as "required", + TRUE as "checked"; + +select + 'switch' as "type", + 'A disabled toggle switch' as "label", + 'my_field' as "name", + TRUE as "disabled"; 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 new file mode 100644 index 000000000..42dc0feee --- /dev/null +++ b/examples/official-site/reference/components/form/06-single-select-field.sql @@ -0,0 +1,34 @@ +/* +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 +``` +*/ +select + 'form' as "component", + '/examples/show_variables.sql' as "action"; + +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"; diff --git a/examples/official-site/reference/components/form/07-multi-select.sql b/examples/official-site/reference/components/form/07-multi-select.sql new file mode 100644 index 000000000..bbec498e9 --- /dev/null +++ b/examples/official-site/reference/components/form/07-multi-select.sql @@ -0,0 +1,83 @@ +/* +Multi-select + +You can authorize the user to select multiple options by setting the `multiple` property to `true`. +This creates a more compact (but arguably less user-friendly) alternative to a series of checkboxes. +In this case, you should add square brackets to the name of the field (e.g. `'my_field[]' as name`). +The target page will then receive the value as a JSON array of strings, which you can iterate over using + - [`json_each`](https://www.sqlite.org/json1.html) in SQLite, + - [`json_array_elements_text`](https://www.postgresql.org/docs/current/functions-json.html) in PostgreSQL, + - the [`OPENJSON`](https://learn.microsoft.com/fr-fr/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16) function in Microsoft SQL Server. + - in MySQL, json manipulation is less straightforward: see [the SQLPage MySQL json example](https://github.com/sqlpage/SQLPage/tree/main/examples/mysql%20json%20handling) + +[More information on how to handle JSON in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). + +The target page could then look like this: + +```sql +insert into best_fruits(id) -- INSERT INTO ... SELECT ... runs the SELECT query and inserts the results into the table +select CAST(value AS integer) as id -- all values are transmitted by the browser as strings +from json_each(:my_field); -- in SQLite, json_each returns a table with a "value" column for each element in the JSON array +``` + +### Example multiselect generated from a database table + +If you have a table of all possible options (`my_options(id int, label text)`), +and want to generate a multi-select field from it, you have two options: +- if the number of options is not too large, you can use the `options` parameter to return them all as a JSON array in the SQL query +- if the number of options is large (e.g. more than 1000), you can use `options_source` to load options dynamically from a different SQL query as the user types + +#### Embedding all options in the SQL query + +Let's say you have a table that contains the selected options per user (`my_user_options(user_id int, option_id int)`). +You can use a query like this to generate the multi-select field: + +```sql +select 'my_field[]' as name, 'select' as type, true as multiple, json_group_array(json_object( + 'label', my_options.label, + 'value', my_options.id, + 'selected', my_user_options.option_id is not null +)) as options +from my_options +left join my_user_options + on my_options.id = my_user_options.option_id + and my_user_options.user_id = $user_id +``` + +This will generate a json array of objects, each containing the label, value and selected status of each option. + +#### Loading options dynamically from a different SQL query with `options_source` + +If the `my_options` table has a large number of rows, you can use the `options_source` parameter to load options dynamically from a different SQL query as the user types. + +We'll write a second SQL file, `options_source.sql`, that will receive the user's search string as a parameter named `$search`, + and return a json array of objects, each containing the label and value of each option. + +When both `options` and `options_source` are set, the local `options` are loaded first. Search results from `options_source` are loaded into the same option list; a result with the same `value` updates the existing option. This is useful to set a default preselected value with `options_source`. + +`options_source` may already contain query parameters. SQLPage preserves them and adds or replaces the `search` parameter when loading options. + +##### `options_source.sql` + +```sql +select 'json' as component; + +select id as value, label as label +from my_options +where label like $search || '%'; +``` + +The live form loads options from SQLPage's component catalog. Try searching for a component and selecting it alongside the default. The [single-select example](#example-15) shows how to replace the current selection. +*/ +select + 'form' as "component", + '/examples/show_variables.sql' as "action", + 'Reset' as "reset"; + +select + 'component[]' as "name", + 'select' as "type", + TRUE as "multiple", + JSON('[{"label":"Form","value":"form","selected":true}]') as "options", + '/examples/from_component_options_source.sql?category=component' as "options_source", + 'Start typing the name of a component like ''map'' or ''form''...' as "description"; diff --git a/examples/official-site/reference/components/form/08-radio-buttons.sql b/examples/official-site/reference/components/form/08-radio-buttons.sql new file mode 100644 index 000000000..42e48d157 --- /dev/null +++ b/examples/official-site/reference/components/form/08-radio-buttons.sql @@ -0,0 +1,49 @@ +/* +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`. +*/ +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"; diff --git a/examples/official-site/reference/components/form/09-auto-submit-on-change.sql b/examples/official-site/reference/components/form/09-auto-submit-on-change.sql new file mode 100644 index 000000000..b15b5d4d6 --- /dev/null +++ b/examples/official-site/reference/components/form/09-auto-submit-on-change.sql @@ -0,0 +1,21 @@ +/* +Reload the page when a field changes + +The form will be automatically submitted when the user changes any of its fields, and the page will be reloaded with the new value. +The validation button is removed. +*/ +select + 'form' as "component", + 'GET' as "method", + '/component.sql' as "action", + TRUE as "auto_submit"; + +select + 'component' as "name", + 'select' as "type", + FALSE as "autocomplete", + JSON('{"label":"Form","value":"form","selected":true}') as "options", + JSON('{"label":"Map","value":"map"}') as "options", + JSON('{"label":"Chart","value":"chart"}') as "options", + 'Choose a component to view its documentation. No need to click a button, the page will be reloaded automatically.' as "description", + 'Component' as "label"; diff --git a/examples/official-site/reference/components/form/10-hidden-field.sql b/examples/official-site/reference/components/form/10-hidden-field.sql new file mode 100644 index 000000000..44c6d3259 --- /dev/null +++ b/examples/official-site/reference/components/form/10-hidden-field.sql @@ -0,0 +1,27 @@ +/* +A hidden field + +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. +*/ +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"; diff --git a/examples/official-site/reference/components/form/11-custom-buttons-and-field-widths.sql b/examples/official-site/reference/components/form/11-custom-buttons-and-field-widths.sql new file mode 100644 index 000000000..af9168514 --- /dev/null +++ b/examples/official-site/reference/components/form/11-custom-buttons-and-field-widths.sql @@ -0,0 +1,25 @@ +/* +Custom validation buttons and field widths + +This example illustrates the use of custom validation buttons and half-width fields. +*/ +select + 'form' as "component", + 'User' as "title", + 'Create new user' as "validate", + 'green' as "validate_color", + 'Clear' as "reset"; + +select 'first_name' as "name", 'First name' as "label", 'John' as "placeholder", 4 as "width" +union all select 'middle_name', 'Middle name', 'Fitzgerald', 4 +union all select 'last_name', 'Last name', 'Doe', 4 +union all select 'email', 'Email', 'john.doe@gmail.com', 12; + +select 'password' as "name", 'Password' as "label", 'password' as "type", 6 as "width" +union all select 'password_confirmation', 'Password confirmation', 'password', 6; + +select + 'terms' as "name", + 'I accept the terms and conditions' as "label", + 'checkbox' as "type", + TRUE as "required"; diff --git a/examples/official-site/reference/components/form/12-file-upload.sql b/examples/official-site/reference/components/form/12-file-upload.sql new file mode 100644 index 000000000..5c94c80ca --- /dev/null +++ b/examples/official-site/reference/components/form/12-file-upload.sql @@ -0,0 +1,32 @@ +/* +File upload + +You can use the `file` type to allow the user to upload a file. + +The file will be uploaded to the server, and you will be able to access it using the +[`sqlpage.uploaded_file_path`](/functions.sql?function=uploaded_file_path) function. + +Here is how you could save the uploaded file to a table in the database: + +```sql +INSERT INTO uploaded_file(name, data) +VALUES ( + sqlpage.uploaded_file_name('my_file'), + sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('my_file')) +); +``` +*/ +select + 'form' as "component", + 'multipart/form-data' as "enctype", + 'Upload a picture' as "title", + 'Upload' as "validate", + '/examples/handle_picture_upload.sql' as "action"; + +select + 'my_file' as "name", + 'file' as "type", + 'image/png, image/jpeg' as "accept", + 'Picture' as "label", + 'Upload a small picture' as "description", + TRUE as "required"; diff --git a/examples/official-site/reference/components/form/13-form-encoding.sql b/examples/official-site/reference/components/form/13-form-encoding.sql new file mode 100644 index 000000000..e9f39dc87 --- /dev/null +++ b/examples/official-site/reference/components/form/13-form-encoding.sql @@ -0,0 +1,47 @@ +/* +Form Encoding + +You can specify the way form data should be encoded by setting the `enctype` +top-level property on the form. + +You may also specify `formenctype` on `submit` and `image` type inputs. +This will take precedence over the `enctype` specified on the form and is +useful in the case there are multiple `submit` buttons on the form. +For example, an external site may have specific requirements on encoding type. + +As a rule of thumb, ``multipart/form-data`` is best when fields may contain +copious non-ascii characters or for binary data such as an image or a file. +However, ``application/x-www-form-urlencoded`` creates less overhead when +many short ascii text values are submitted. +*/ +select + 'form' as "component", + 'post' as "method", + 'multipart/form-data' as "enctype", + 'Submit with different encoding types' as "title", + 'Submit with form encoding type' as "validate", + '/examples/handle_enctype.sql' as "action"; + +select + 'data' as "name", + 'text' as "type", + 'Data' as "label", + TRUE as "required"; + +select + 'percent_encoded' as "name", + 'submit' as "type", + 'Submit as' as "label", + 4 as "width", + '/examples/handle_enctype.sql' as "formaction", + 'application/x-www-form-urlencoded' as "formenctype", + 'application/x-www-form-urlencoded' as "value"; + +select + 'multipart_form_data' as "name", + 'submit' as "type", + 'Submit as' as "label", + 4 as "width", + '/examples/handle_enctype.sql' as "formaction", + 'multipart/form-data' as "formenctype", + 'multipart/form-data' as "value"; diff --git a/examples/official-site/reference/components/form/14-bulk-csv-import.sql b/examples/official-site/reference/components/form/14-bulk-csv-import.sql new file mode 100644 index 000000000..9c36637af --- /dev/null +++ b/examples/official-site/reference/components/form/14-bulk-csv-import.sql @@ -0,0 +1,62 @@ +/* +Bulk data insertion + +You can use the `file` type to allow the user to upload a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) +file containing data to insert in a table. + +SQLPage can load data from a CSV file and insert it into a database table. +SQLPage re-uses PostgreSQL's [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html) +to specify the format of the CSV file, but makes it work with all supported databases. + +> When connected to a PostgreSQL database, SQLPage will use the native `COPY` statement, +> for super fast and efficient on-database CSV parsing. +> But it will also work transparently with other databases, by +> parsing the CSV locally and emulating the same behavior with simple `INSERT` statements. + +Here is how you could easily copy data from a CSV to a table in the database: + +```sql +copy product(name, description, price) from 'product_data_file' +with (header true, delimiter ',', quote '"'); +``` + +If you want to pre-process the data before inserting it into the final table, +you can use a temporary table to store the data, and then insert it into the final table: + +```sql +-- temporarily store the data in a table with text columns +create temporary table if not exists product_tmp(name text, description text, price text); +delete from product_tmp; + +-- copy the data from the CSV file into the temporary table +copy product_tmp(name, description, price) from 'product_data_file' with (header true); + +-- insert the data into the final table, converting the price column to an integer +insert into product(name, description, price) +select name, description, CAST(price AS integer) from product_tmp +where price is not null and description is not null and length(description) > 10; +``` + +This will load the processed CSV into the product table, provided it has the following structure: + +```csv +name,description,price +"SQLPage","A tool to create websites using SQL",0 +"PostgreSQL","A powerful open-source relational database",0 +"SQLite","A lightweight relational database",0 +"MySQL","A popular open-source relational database",0 +``` +*/ +select + 'form' as "component", + 'CSV import' as "title", + 'Load data' as "validate", + '/examples/handle_csv_upload.sql' as "action"; + +select + 'product_data_file' as "name", + 'file' as "type", + 'text/csv' as "accept", + 'Products' as "label", + 'Upload a CSV with a name, description, and price columns' as "description", + TRUE as "required"; diff --git a/examples/official-site/reference/components/form/15-single-select-with-remote-search.sql b/examples/official-site/reference/components/form/15-single-select-with-remote-search.sql new file mode 100644 index 000000000..cec2206e4 --- /dev/null +++ b/examples/official-site/reference/components/form/15-single-select-with-remote-search.sql @@ -0,0 +1,17 @@ +/* +Single select with remote search + +The form starts with Form selected using `value` and `options`. Search for a component and select it to replace that value. The form submits one string named `component`. +*/ +select + 'form' as "component", + '/examples/show_variables.sql' as "action", + 'Reset' as "reset"; + +select + 'component' as "name", + 'select' as "type", + 'form' as "value", + JSON('[{"label":"Form","value":"form"}]') as "options", + '/examples/from_component_options_source.sql?category=component' as "options_source", + 'Search for one component, such as map or form.' as "description"; diff --git a/examples/official-site/reference/components/hero/01-simple-hero.sql b/examples/official-site/reference/components/hero/01-simple-hero.sql new file mode 100644 index 000000000..c8d241cc1 --- /dev/null +++ b/examples/official-site/reference/components/hero/01-simple-hero.sql @@ -0,0 +1,7 @@ +/* +The simplest possible hero section +*/ +select + 'hero' as "component", + 'Welcome' as "title", + 'This is a very simple site built with SQLPage.' as "description"; diff --git a/examples/official-site/reference/components/hero/02-background-image.sql b/examples/official-site/reference/components/hero/02-background-image.sql new file mode 100644 index 000000000..1afce3eee --- /dev/null +++ b/examples/official-site/reference/components/hero/02-background-image.sql @@ -0,0 +1,31 @@ +/* +A hero with a background image +*/ +select + 'hero' as "component", + 'SQLPage' as "title", + 'Documentation for the *SQLPage* low-code web application framework.' as "description_md", + 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Lac_de_Zoug.jpg/1280px-Lac_de_Zoug.jpg' as "image", + '/documentation.sql' as "link", + 'Read Documentation !' as "link_text"; + +select + 'Fast' as "title", + 'Pages load instantly, even on slow mobile networks.' as "description", + 'car' as "icon", + 'red' as "color", + '/' as "link"; + +select + 'Beautiful' as "title", + 'Uses pre-defined components that look professional.' as "description", + 'eye' as "icon", + 'green' as "color", + '/' as "link"; + +select + 'Easy' as "title", + 'You can teach yourself enough SQL to use [**SQLPage**](https://sql-page.com) in a weekend.' as "description_md", + 'sofa' as "icon", + 'blue' as "color", + '/' as "link"; diff --git a/examples/official-site/reference/components/hero/03-hero-with-video.sql b/examples/official-site/reference/components/hero/03-hero-with-video.sql new file mode 100644 index 000000000..46f196fab --- /dev/null +++ b/examples/official-site/reference/components/hero/03-hero-with-video.sql @@ -0,0 +1,10 @@ +/* +A hero with a video +*/ +select + 'hero' as "component", + 'Databases' as "title", + TRUE as "reverse", + '# “The goal is to turn data into information, and information into insight.”' as "description_md", + 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Lac_de_Zoug.jpg/1280px-Lac_de_Zoug.jpg' as "poster", + '/sqlpage_introduction_video.mp4' as "video"; diff --git a/examples/official-site/reference/components/html/01-render-html-snippet.sql b/examples/official-site/reference/components/html/01-render-html-snippet.sql new file mode 100644 index 000000000..b493ad02f --- /dev/null +++ b/examples/official-site/reference/components/html/01-render-html-snippet.sql @@ -0,0 +1,8 @@ +/* +Render an HTML snippet + +Include a simple HTML snippet. In this example, the HTML code is hardcoded in the SQL query, so it is safe. You should never include data that may be manipulated by a user in the HTML content. +*/ +select + 'html' as "component", + '

This text is safe because it is hardcoded!

' as "html"; diff --git a/examples/official-site/reference/components/html/02-render-multiple-snippets.sql b/examples/official-site/reference/components/html/02-render-multiple-snippets.sql new file mode 100644 index 000000000..e963d54f1 --- /dev/null +++ b/examples/official-site/reference/components/html/02-render-multiple-snippets.sql @@ -0,0 +1,17 @@ +/* +Render multiple HTML snippets + +Include multiple html snippets as row-level parameters. Again, be careful what you include in the HTML content. If the data comes from a user, it can be manipulated to include malicious code. +*/ +select + 'html' as "component", + '
' as "html"; + +select + '
20%
' as "html"; + +select + '
80%
' as "html"; + +select + '
' as "html"; diff --git a/examples/official-site/reference/components/html/03-escape-text-in-html.sql b/examples/official-site/reference/components/html/03-escape-text-in-html.sql new file mode 100644 index 000000000..6435a10cb --- /dev/null +++ b/examples/official-site/reference/components/html/03-escape-text-in-html.sql @@ -0,0 +1,12 @@ +/* +Escape text in HTML + +Use the `text` property to display user-generated content literally, including any HTML tags it contains. +*/ +select + 'html' as "component"; + +select + '

The following is displayed as text: ' as "html", + '' as "text", + '. Phew! That was close!

' as "post_html"; diff --git a/examples/official-site/reference/components/http_header/01-cache-control-directives.standalone.sql b/examples/official-site/reference/components/http_header/01-cache-control-directives.standalone.sql new file mode 100644 index 000000000..8975d94bb --- /dev/null +++ b/examples/official-site/reference/components/http_header/01-cache-control-directives.standalone.sql @@ -0,0 +1,10 @@ +/* +Set cache control directives + +The browser can reuse the cached response for 10 minutes (`max-age`). +Once it expires, the browser can serve the stale response for up to one hour while refreshing it in the background (`stale-while-revalidate`). +If refreshing fails, the browser can use the stale response for up to 24 hours (`stale-if-error`). +*/ +select + 'http_header' as "component", + 'public, max-age=600, stale-while-revalidate=3600, stale-if-error=86400' as "Cache-Control"; 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 new file mode 100644 index 000000000..ee1269c83 --- /dev/null +++ b/examples/official-site/reference/components/http_header/02-redirect-with-location.md @@ -0,0 +1,10 @@ +# 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/03-custom-response-header.standalone.sql b/examples/official-site/reference/components/http_header/03-custom-response-header.standalone.sql new file mode 100644 index 000000000..bb7634df7 --- /dev/null +++ b/examples/official-site/reference/components/http_header/03-custom-response-header.standalone.sql @@ -0,0 +1,8 @@ +/* +Set a custom response header + +Set a custom non-standard header for the response. In this example, the response will include a custom header named X-My-Header with the value "my value". +*/ +select + 'http_header' as "component", + 'my value' as "X-My-Header"; diff --git a/examples/official-site/reference/components/http_header/README.md b/examples/official-site/reference/components/http_header/README.md new file mode 100644 index 000000000..09cbf5ad3 --- /dev/null +++ b/examples/official-site/reference/components/http_header/README.md @@ -0,0 +1,18 @@ +Set response headers for caching, content types, and more. + +Put this component at the beginning of the page, before any response content is sent. Set custom headers to control caching, specify the response media type, or redirect the visitor. + +Any valid HTTP header name can be used as a top-level parameter for this component. + +If your header's name contains a dash or any other special character, +you will have to use your database's quoting mechanism to declare it. +In standard SQL, you can use double quotes to quote identifiers (like "X-My-Header"), +in Microsoft SQL Server, you can use square brackets (like [X-My-Header]). + +## Top-level parameters + + - **Access-Control-Allow-Origin** (TEXT): Specifies which origins are allowed to access the resource in a cross-origin request, used for implementing Cross-Origin Resource Sharing (CORS). + - **Cache-Control** (TEXT): Directives for how long the page should be cached by the browser. Set this to max-age=N to keep the page in cache for N seconds. + - **Content-Disposition** (TEXT): Provides instructions on how the response content should be displayed or handled by the client, such as inline or as an attachment. + - **Location** (TEXT): Specifies the URL to redirect the client to, usually used in 3xx redirection responses. + - **Set-Cookie** (TEXT): Sets a cookie in the client browser, used for session management and storing user-related information. 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 new file mode 100644 index 000000000..738b081aa --- /dev/null +++ b/examples/official-site/reference/components/json/01-query-results-as-json-array.md @@ -0,0 +1,30 @@ +# 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/02-one-json-object-per-row.md b/examples/official-site/reference/components/json/02-one-json-object-per-row.md new file mode 100644 index 000000000..e2aecb5d9 --- /dev/null +++ b/examples/official-site/reference/components/json/02-one-json-object-per-row.md @@ -0,0 +1,30 @@ +# 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/03-nested-api-response.md b/examples/official-site/reference/components/json/03-nested-api-response.md new file mode 100644 index 000000000..aa186b67a --- /dev/null +++ b/examples/official-site/reference/components/json/03-nested-api-response.md @@ -0,0 +1,42 @@ +# 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/04-stream-server-sent-events.md b/examples/official-site/reference/components/json/04-stream-server-sent-events.md new file mode 100644 index 000000000..ee766afd5 --- /dev/null +++ b/examples/official-site/reference/components/json/04-stream-server-sent-events.md @@ -0,0 +1,25 @@ +# 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/README.md b/examples/official-site/reference/components/json/README.md new file mode 100644 index 000000000..17cffd575 --- /dev/null +++ b/examples/official-site/reference/components/json/README.md @@ -0,0 +1,27 @@ +Return query results as JSON for an API. + +**JSON** is a widely used data format for programmatic data exchange. +For example, you can use it to integrate with web services written in different languages, +with mobile or desktop apps, or with [custom client-side components](/custom_components.sql) inside your SQLPage app. + +Use it when your application needs to expose data to external systems. +If you only need to render standard web pages, +and do not need other software to access your data, +you can ignore this component. + +This component **must appear at the top of your SQL file**, before any other data has been sent to the browser. +An HTTP response can have only a single datatype, and it must be declared in the headers. +So if you have already called the `shell` component, or another traditional HTML component, +you cannot use this component in the same file. + +SQLPage can also return JSON or JSON Lines when the incoming request says it prefers them with an HTTP `Accept` header, so the same `/users.sql` page can show a table in a browser but return raw data to `curl -H "Accept: application/json" http://localhost:8080/users.sql`. + +Use this component when you want to control the payload or force JSON output even for requests that would normally get HTML. + +## Top-level parameters + + - **contents** (TEXT): A single JSON payload to send. You can use your database's built-in json functions to build the value to enter here. If not provided, the contents will be taken from the next SQL statements and rendered as a JSON array. + - **type** (TEXT): The type of the JSON payload to send: "array", "jsonlines", or "sse". + In "array" mode, each query result is rendered as a JSON object in a single top-level array. + In "jsonlines" mode, results are rendered as JSON objects in separate lines, without a top-level array. + In "sse" mode, results are rendered as JSON objects in separate lines, prefixed by "data: ", which allows you to read the results as server-sent events in real-time from javascript. diff --git a/examples/official-site/reference/components/list/01-compact-list.sql b/examples/official-site/reference/components/list/01-compact-list.sql new file mode 100644 index 000000000..6e399acc2 --- /dev/null +++ b/examples/official-site/reference/components/list/01-compact-list.sql @@ -0,0 +1,11 @@ +/* +A basic compact list +*/ +select + 'list' as "component", + TRUE as "compact", + 'SQLPage lists are...' as "title"; + +select 'Beautiful' as "title" +union all select 'Useful' +union all select 'Versatile'; 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 new file mode 100644 index 000000000..42d20e9ce --- /dev/null +++ b/examples/official-site/reference/components/list/02-clickable-empty-state.sql @@ -0,0 +1,10 @@ +/* +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"; diff --git a/examples/official-site/reference/components/list/03-rich-text-descriptions.sql b/examples/official-site/reference/components/list/03-rich-text-descriptions.sql new file mode 100644 index 000000000..406873311 --- /dev/null +++ b/examples/official-site/reference/components/list/03-rich-text-descriptions.sql @@ -0,0 +1,33 @@ +/* +A list with rich text descriptions + +This example illustrates creating a nice list where each item has a title, a description, an image, and a link to another page. + +> Be careful, nested links are not supported. If you use the list's `link` property, then your markdown `description_md` should not contain any link. +*/ +select + 'list' as "component", + TRUE as "wrap"; + +select + 'SQL Websites' as "title", + '/favicon.ico' as "image_url", + 'Write SQL, get a website. SQLPage is a **SQL**-based **site** generator for **PostgreSQL**, **MySQL**, **SQLite** and **SQL Server**.' as "description_md", + '/' as "link"; + +select + 'SQL Forms' as "title", + 'https://upload.wikimedia.org/wikipedia/commons/b/b6/FileStack_retouched.jpg' as "image_url", + 'Easily collect data **from users to your database** using the *form* component. Handle the data in SQL with `INSERT` or `UPDATE` queries.' as "description_md", + '/component.sql?component=form' as "link"; + +select + 'SQL Maps' as "title", + 'https://upload.wikimedia.org/wikipedia/commons/1/15/Vatican_City_map_EN.png' as "image_url", + 'Show database contents on a map using the *map* component. Works well with *PostGIS* and *SpatiaLite*.' as "description_md", + '/component.sql?component=map' as "link"; + +select + 'Advanced features' as "title", + 'settings' as "icon", + '[Authenticate users](/component.sql?component=authentication), [edit data](/component.sql?component=form), [generate an API](/component.sql?component=json), [maintain your database schema](/your-first-sql-website/migrations.sql), and more.' as "description_md"; 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 new file mode 100644 index 000000000..3d5552067 --- /dev/null +++ b/examples/official-site/reference/components/list/04-actions-icons-and-colors.sql @@ -0,0 +1,34 @@ +/* +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"; + +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"; 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 new file mode 100644 index 000000000..cb93fafac --- /dev/null +++ b/examples/official-site/reference/components/log/01-write-to-server-log.md @@ -0,0 +1,41 @@ +# 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/README.md b/examples/official-site/reference/components/log/README.md new file mode 100644 index 000000000..874d78f23 --- /dev/null +++ b/examples/official-site/reference/components/log/README.md @@ -0,0 +1,15 @@ +Write a message to the SQLPage server log. + +Use it to track what happens and troubleshoot issues. + +## Reading log messages + +- Running from a terminal (Linux, macOS, or Windows PowerShell/Command Prompt): they show up in the window. +- Docker: run `docker logs `. +- Linux service (systemd): run `journalctl -u sqlpage`. +- This component's output is written to [standard error (stderr)](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)). SQLPage request access logs are separate and are written to standard output (stdout). + +## Top-level parameters + + - **message** (TEXT, required): The text to write to the server logs. It is printed when the page runs. + - **level** (TEXT): How important the message is. One of 'trace', 'debug', 'info' (default), 'warn', 'error'. Not case-sensitive. Controls the level shown in the logs. 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 new file mode 100644 index 000000000..8ad411895 --- /dev/null +++ b/examples/official-site/reference/components/login/01-login-form-with-remember-me.sql @@ -0,0 +1,24 @@ +/* +Using the main options of the login component + +When the user clicks the "Sign in" button, the form is submitted to the `/examples/show_variables.sql` page. +There, you will have access to the variables: + - `:username`: the username entered by the user + - `:password`: the password entered by the user + - `:remember`: the string "on" if the checkbox was checked, or NULL if it was not checked +*/ +select + 'login' as "component", + '/examples/show_variables.sql' as "action", + '/assets/icon.webp' as "image", + 'Please login to your account' as "title", + 'Username' as "username", + 'Password' as "password", + 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"; 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 new file mode 100644 index 000000000..d372ccb01 --- /dev/null +++ b/examples/official-site/reference/components/login/02-basic-login-form.sql @@ -0,0 +1,8 @@ +/* +Basic login form +*/ +select + 'login' as "component", + 'Username' as "username", + 'Password' as "password", + FALSE as "autofocus"; diff --git a/examples/official-site/reference/components/map/01-place-a-marker.sql b/examples/official-site/reference/components/map/01-place-a-marker.sql new file mode 100644 index 000000000..a6a839c2e --- /dev/null +++ b/examples/official-site/reference/components/map/01-place-a-marker.sql @@ -0,0 +1,11 @@ +/* +Adding a marker to a map + +Showing how to place a marker on a map. Useful for basic location displays like showing a single office location, event venue, or point of interest. The marker shows basic hover and click interactions. +*/ +select 'map' as "component"; + +select + 'New Delhi' as "title", + 28.6139 as "latitude", + 77.209 as "longitude"; 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 new file mode 100644 index 000000000..ccb9d9e3f --- /dev/null +++ b/examples/official-site/reference/components/map/02-geojson-and-custom-tiles.sql @@ -0,0 +1,31 @@ +/* +Advanced map customization using GeoJSON and custom map tiles + +This example demonstrates using topographic map tiles, custom marker styling, +and clickable markers that link to external content - perfect for educational or tourism applications. + +The [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) feature here is a single point. Its coordinates are `[longitude, latitude]`; the top-level `latitude` and `longitude` set the map's initial center. + + - You can generate GeoJSON data from PostGIS geometries using the [`ST_AsGeoJSON`](https://postgis.net/docs/ST_AsGeoJSON.html) function. + - In spatialite, you can use the [`AsGeoJSON`](https://www.gaia-gis.it/gaia-sins/spatialite-sql-5.1.0.html#p3misc) function. + - In MySQL, you can use the [`ST_AsGeoJSON()`](https://dev.mysql.com/doc/refman/8.0/en/spatial-geojson-functions.html#function_st-asgeojson) function. +*/ +select + 'map' as "component", + 5 as "zoom", + 8 as "max_zoom", + 600 as "height", + -25 as "latitude", + 28 as "longitude", + 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png' as "tile_source", + '' as "attribution"; + +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"; + +select + 'text' as "component", + 'Map data: [© OpenStreetMap contributors](https://www.openstreetmap.org/copyright), SRTM. Map style: [© OpenTopoMap](https://opentopomap.org/) ([CC BY-SA](https://creativecommons.org/licenses/by-sa/3.0/)).' as "contents_md"; 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 new file mode 100644 index 000000000..a4470112c --- /dev/null +++ b/examples/official-site/reference/components/map/03-links-and-rich-descriptions.sql @@ -0,0 +1,39 @@ +/* +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"; + +select + 'Notre Dame' as "title", + 'building-castle' as "icon", + 'indigo' as "color", + 48.853 as "latitude", + 2.3498 as "longitude", + 'A beautiful cathedral.' as "description_md", + 'https://en.wikipedia.org/wiki/Notre-Dame_de_Paris' as "link"; + +select + 'Eiffel Tower' as "title", + 'tower' as "icon", + 'red' as "color", + 48.8584 as "latitude", + 2.2945 as "longitude", + 'A tall tower. [Wikipedia](https://en.wikipedia.org/wiki/Eiffel_Tower)' as "description_md"; + +select + 'Tower to Cathedral' as "title", + JSON('{"type":"LineString","coordinates":[[2.2945,48.8584],[2.3498,48.8530]]}') as "geojson", + 'teal' as "color", + 'A nice 45 minutes walk.' as "description"; 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 new file mode 100644 index 000000000..b012af14c --- /dev/null +++ b/examples/official-site/reference/components/map/04-geometric-shapes-without-tiles.sql @@ -0,0 +1,22 @@ +/* +Abstract geometric visualizations + +Example showing how to create abstract geometric visualizations without a base map. +Useful for displaying spatial data that doesn't need geographic context, like floor plans, seating charts, +or abstract 2D data visualizations. +*/ +select + 'map' as "component", + FALSE as "tile_source"; + +select + 'MySQL' as "title", + 'red' as "color", + '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"; + +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"; diff --git a/examples/official-site/reference/components/modal/01-open-text-modal-with-button.sql b/examples/official-site/reference/components/modal/01-open-text-modal-with-button.sql new file mode 100644 index 000000000..0c27b1039 --- /dev/null +++ b/examples/official-site/reference/components/modal/01-open-text-modal-with-button.sql @@ -0,0 +1,19 @@ +/* +Open a text modal with a button + +This example shows how to create a modal box that displays a paragraph of text. The modal window is opened with the help of a button. +*/ +select + 'modal' as "component", + 'my_modal' as "id", + 'A modal box' as "title", + 'Close' as "close"; + +select + 'I''m a modal window, and I allow you to display additional information or help for the user.' as "contents"; + +select 'button' as "component"; + +select + 'Open a simple modal' as "title", + '#my_modal' as "link"; diff --git a/examples/official-site/reference/components/modal/02-embed-a-form.sql b/examples/official-site/reference/components/modal/02-embed-a-form.sql new file mode 100644 index 000000000..232ab62ef --- /dev/null +++ b/examples/official-site/reference/components/modal/02-embed-a-form.sql @@ -0,0 +1,17 @@ +/* +Embed a form in a modal + +The button opens the dialog by its `id`. `embed` loads the form from another SQLPage file without its surrounding page shell. +*/ +select + 'modal' as "component", + 'my_embed_form_modal' as "id", + 'Embedded form' as "title", + TRUE as "large", + '/examples/form.sql' as "embed"; + +select 'button' as "component"; + +select + 'Open a modal with a form' as "title", + '#my_embed_form_modal' as "link"; 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 new file mode 100644 index 000000000..2615cbeb2 --- /dev/null +++ b/examples/official-site/reference/components/modal/03-open-embedded-chart-from-datagrid.sql @@ -0,0 +1,16 @@ +/* +Open a chart modal from a datagrid + +A popup modal that contains a chart generated by a separate SQL file. The modal is triggered by links inside a datagrid. +*/ +select + 'modal' as "component", + 'my_embed_chart_modal' as "id", + 'Embeded chart content' as "title", + 'Close' as "close", + '/examples/chart.sql?_sqlpage_embed' as "embed"; + +select 'datagrid' as "component"; + +select 'Chart' as "title", 'blue' as "color", 'Revenue' as "description", '#my_embed_chart_modal' as "link" +union all select 'Form', 'green', 'Fill info', '/component.sql?component=modal#my_embed_form_modal'; 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 new file mode 100644 index 000000000..abcbd2797 --- /dev/null +++ b/examples/official-site/reference/components/modal/04-embed-a-video.sql @@ -0,0 +1,16 @@ +/* +Example of modal video content +*/ +select + 'modal' as "component", + 'my_embed_video_modal' as "id", + 'Embeded 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", + 'iframe' as "embed_mode", + '350' as "height"; + +select + 'text' as "component", + 'Open a [modal with a video](#my_embed_video_modal)' as "contents_md"; diff --git a/examples/official-site/reference/components/pagination/01-page-numbers.sql b/examples/official-site/reference/components/pagination/01-page-numbers.sql new file mode 100644 index 000000000..135edf49a --- /dev/null +++ b/examples/official-site/reference/components/pagination/01-page-numbers.sql @@ -0,0 +1,14 @@ +/* +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. +*/ +select 'pagination' as "component"; + +select + 1 as "contents", + '/component.sql?component=pagination&page=1' as "link", + TRUE as "active"; + +select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" +union all select 3, '/component.sql?component=pagination&page=3'; diff --git a/examples/official-site/reference/components/pagination/02-outlined-links.sql b/examples/official-site/reference/components/pagination/02-outlined-links.sql new file mode 100644 index 000000000..110a61462 --- /dev/null +++ b/examples/official-site/reference/components/pagination/02-outlined-links.sql @@ -0,0 +1,16 @@ +/* +Outlined pagination links + +The outline style adds a rectangular border to each navigation link. +*/ +select + 'pagination' as "component", + TRUE as "outline"; + +select + 1 as "contents", + '/component.sql?component=pagination&page=1' as "link", + TRUE as "active"; + +select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" +union all select 3, '/component.sql?component=pagination&page=3'; diff --git a/examples/official-site/reference/components/pagination/03-circular-links.sql b/examples/official-site/reference/components/pagination/03-circular-links.sql new file mode 100644 index 000000000..116ab6162 --- /dev/null +++ b/examples/official-site/reference/components/pagination/03-circular-links.sql @@ -0,0 +1,16 @@ +/* +Circular pagination links + +The circle style adds a circular border to each navigation link. +*/ +select + 'pagination' as "component", + TRUE as "circle"; + +select + 1 as "contents", + '/component.sql?component=pagination&page=1' as "link", + TRUE as "active"; + +select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" +union all select 3, '/component.sql?component=pagination&page=3'; 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 new file mode 100644 index 000000000..98be67f49 --- /dev/null +++ b/examples/official-site/reference/components/pagination/04-disabled-navigation-links.sql @@ -0,0 +1,21 @@ +/* +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. +*/ +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"; + +select + 1 as "contents", + '/component.sql?component=pagination&page=1' as "link", + TRUE as "active"; + +select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" +union all select 3, '/component.sql?component=pagination&page=3'; 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 new file mode 100644 index 000000000..82b8287ca --- /dev/null +++ b/examples/official-site/reference/components/pagination/05-text-navigation-labels.sql @@ -0,0 +1,25 @@ +/* +Navigation links with text labels + +Instead of using icons, you can apply text to the navigation links. +*/ +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"; + +select + 1 as "contents", + '/component.sql?component=pagination&page=1' as "link", + TRUE as "active"; + +select 2 as "contents", '/component.sql?component=pagination&page=2' as "link" +union all select 3, '/component.sql?component=pagination&page=3'; 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 new file mode 100644 index 000000000..846352cf4 --- /dev/null +++ b/examples/official-site/reference/components/pagination/06-pagination-with-offset.sql @@ -0,0 +1,29 @@ +/* +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. +*/ +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"; + +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 + 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"; 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 new file mode 100644 index 000000000..3a0b2fb91 --- /dev/null +++ b/examples/official-site/reference/components/redirect/01-redirect-to-login.md @@ -0,0 +1,8 @@ +# 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/README.md b/examples/official-site/reference/components/redirect/README.md new file mode 100644 index 000000000..246a2bc11 --- /dev/null +++ b/examples/official-site/reference/components/redirect/README.md @@ -0,0 +1,29 @@ +Send the visitor to another URL. + +### Conditional logic + +To conditionally execute a component or a [SQLPage function](/functions.sql), you can use the `redirect` component. +A common use case is error handling. You may want to proceed with the rest of a page only when certain pre-conditions are met. + +```sql +SELECT + 'redirect' AS component, + 'error_page.sql' AS link +WHERE NOT your_condition; + +-- The rest of the page is only executed if the condition is true +``` +### Technical limitation + +You must use this component **at the beginning of your SQL file**, before any other components that might send content to the browser. +Since the component needs to tell the browser to go to a different page by sending an *HTTP header*, +it will fail if the HTTP headers have already been sent by the time it is executed. + +> **Important difference from [http_header](?component=http_header)** +> +> This component completely stops the page from running after it's called. +> This makes it a good choice for protecting sensitive information from unauthorized users. + +## Top-level parameters + + - **link** (TEXT, required): The URL to redirect the user to. 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 new file mode 100644 index 000000000..4458f33cf --- /dev/null +++ b/examples/official-site/reference/components/rss/01-sqlpage-news-feed.standalone.sql @@ -0,0 +1,30 @@ +/* +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/)... +*/ +select 'http_header' as component, 'application/rss+xml' as "Content-Type"; +select 'shell-empty' as component; +select + 'rss' as component, + 'SQLPage blog' as title, + 'https://sql-page.com/blog.sql' as link, + 'latest news about SQLpage' as description, + 'en' as language, + 'Technology' as category, + FALSE as explicit, + 'https://sql-page.com/favicon.ico' as image_url, + 'Ophir Lojkine' as author, + 'https://github.com/sponsors/lovasoa' as funding_url, + 'episodic' as type; +select + 'Hello everyone !' as title, + 'https://sql-page.com/blog.sql?post=Come%20see%20me%20build%20twitter%20live%20on%20stage%20in%20Prague' as link, + 'If some of you european SQLPagers are around Prague this december, I will be giving a talk about SQLPage at pgconf.eu on December 14th.' as description, + '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; diff --git a/examples/official-site/reference/components/shell/01-dark-shell-with-navigation-menus.standalone.sql b/examples/official-site/reference/components/shell/01-dark-shell-with-navigation-menus.standalone.sql new file mode 100644 index 000000000..94a086602 --- /dev/null +++ b/examples/official-site/reference/components/shell/01-dark-shell-with-navigation-menus.standalone.sql @@ -0,0 +1,54 @@ +/* +A dark shell with navigation menus + +This example configures a dark shell with menus linking to pages on this site. + +Each `menu_item` object defines a link or a dropdown. The "Community" menu links to the blog, issue tracker, discussions, and source code. SQLite's `json()` function marks the literal values as JSON. + +See the [page layouts demo](/examples/layouts.sql) for more layout options. +*/ +select + 'shell' as "component", + 'SQLPage: SQL websites' as "title", + 'SQLPage' as "navbar_title", + '/' as "link", + JSON('{"title": "About", "submenu": [ + {"link": "/safety.sql", "title": "Security", "icon": "lock"}, + {"link": "/performance.sql", "title": "Performance", "icon": "bolt"}, + {"link": "https://github.com/sqlpage/SQLPage/blob/main/LICENSE.txt", "title": "License", "icon": "file-text"}, + {"link": "/blog.sql", "title": "Articles", "icon": "book"} + ]}') as "menu_item", + JSON('{"title": "Examples", "submenu": [ + {"link": "/examples/tabs/", "title": "Tabs", "icon": "layout-navbar"}, + {"link": "/examples/layouts.sql", "title": "Layouts", "icon": "layout"}, + {"link": "/examples/multistep-form", "title": "Forms", "icon": "edit"}, + {"link": "/examples/handle_picture_upload.sql", "title": "File uploads", "icon": "upload"}, + {"link": "/examples/authentication/", "title": "Password protection", "icon": "password-user"}, + {"link": "https://github.com/sqlpage/SQLPage/blob/main/examples/", "title": "All examples & demos", "icon": "code"} + ]}') as "menu_item", + JSON('{"title": "Community", "submenu": [ + {"link": "/blog.sql", "title": "Blog", "icon": "book"}, + {"link": "https://github.com/sqlpage/SQLPage/issues", "title": "Report a bug", "icon": "bug"}, + {"link": "https://github.com/sqlpage/SQLPage/discussions", "title": "Discussions", "icon": "message"}, + {"link": "https://github.com/sqlpage/SQLPage", "title": "GitHub", "icon": "brand-github"} + ]}') as "menu_item", + JSON('{"title": "Documentation", "submenu": [ + {"link": "/your-first-sql-website", "title": "Getting started", "icon": "book"}, + {"link": "/components.sql", "title": "All Components", "icon": "list-details"}, + {"link": "/functions.sql", "title": "SQLPage Functions", "icon": "math-function"}, + {"link": "/extensions-to-sql", "title": "Extensions to SQL", "icon": "cube-plus"}, + {"link": "/custom_components.sql", "title": "Custom Components", "icon": "puzzle"}, + {"link": "https://github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage", "title": "Configuration", "icon": "settings"} + ]}') as "menu_item", + JSON('{"title": "Search", "link": "/search.sql"}') as "menu_item", + 'boxed' as "layout", + 'en-US' as "language", + 'Go from SQL queries to web applications in an instant.' as "description", + 'https://sql-page.com/sqlpage_social_preview.webp' as "preview_image", + 'dark' as "theme", + 19 as "font_size", + '/assets/icon.webp' as "image", + '/favicon.ico' as "favicon", + '/assets/highlightjs-launch.js' as "javascript_module", + '/assets/highlightjs-and-tabler-theme.css' as "css", + '[Built with SQLPage](https://github.com/sqlpage/SQLPage/tree/main/examples/official-site)' as "footer"; 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 new file mode 100644 index 000000000..2d649e637 --- /dev/null +++ b/examples/official-site/reference/components/shell/02-highlight-active-menu-item.standalone.sql @@ -0,0 +1,14 @@ +/* +Highlight an active 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. +*/ +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"; 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 new file mode 100644 index 000000000..0a6f49c0e --- /dev/null +++ b/examples/official-site/reference/components/shell/03-share-shell-across-pages.md @@ -0,0 +1,107 @@ +# Sharing the shell between multiple pages + +It is common to want to share the same shell between multiple pages. + +#### Static menu + +If your menu is completely static (it does not depend on the database content), +you can use the [`dynamic`](/component.sql?component=dynamic#component) component together with the +[`sqlpage.read_file_as_text`](/functions.sql?function=read_file_as_text#function) function to load the shell from +a json file. + +```sql +SELECT 'dynamic' AS component, sqlpage.read_file_as_text('shell.json') AS properties; +``` + +and in `shell.json`: + +```json +{ + "component": "shell", + "title": "SQL + JSON = <3", + "link": "/", + "menu_item": [ + {"link": "index.sql", "title": "Home"}, + {"title": "Community", "submenu": [ + {"link": "/blog.sql", "title": "Blog"}, + {"link": "//github.com/sqlpage/SQLPage", "title": "Github"} + ]} + ] +} +``` + +#### Dynamic menu + +If your menu depends on the database content, or on special `sqlpage` functions, +you can use the `dynamic` component, +but this time with the [`sqlpage.run_sql`](/functions.sql?function=run_sql#function) +function to generate the menu from the database. + +```sql +SELECT 'dynamic' AS component, sqlpage.run_sql('shell.sql') AS properties; +``` + +and in `shell.sql`: + +```sql +SELECT 'shell' AS component, 'run_sql is cool' as title, + json_group_array(json_object( + 'link', link, + 'title', title + )) as menu_item +FROM my_menu_items +``` + +(check your database documentation for the exact syntax of the `json_group_array` function). + +Another case when dynamic menus are useful is when you want to show some +menu items only in certain conditions. + +For instance, you could show an "Admin panel" menu item only to users with the "admin" role, +a "Profile" menu item only to authenticated users, +and a "Login" menu item only to unauthenticated users: + +```sql +set role = ( + SELECT role FROM users + INNER JOIN sessions ON users.id = sessions.user_id + WHERE sessions.session_id = sqlpage.cookie('session_id') +); -- Read more about how to handle user sessions in the "authentication" component documentation + +SELECT + 'shell' AS component, + 'My authenticated website' AS title, + + -- Add an admin panel link if the user is an admin + CASE WHEN $role = 'admin' THEN '{"link": "admin.sql", "title": "Admin panel"}' END AS menu_item, + + -- Add a profile page if the user is authenticated + CASE WHEN $role IS NOT NULL THEN '{"link": "profile.sql", "title": "My profile"}' END AS menu_item, + + -- Add a login link if the user is not authenticated + CASE WHEN $role IS NULL THEN 'login' END AS menu_item +; +``` + +More about how to handle user sessions in the [authentication component documentation](/component.sql?component=authentication#component). + +### Menu with icons + +The "icon" attribute may be specified for items in the top menu and submenus to display an icon +before the title (or instead). Similarly, the "image" attribute defines a file-based icon. For +image-based icons, the "size" attribute may be specified at the top level of menu_item only to +reduce the size of image-based icons. The following snippet provides an example, which is also +available [here](/examples/menu_icon.sql). + +```sql +SELECT + 'shell' AS component, + 'SQLPage' AS title, + 'database' AS icon, + '/' AS link, + TRUE AS fixed_top_menu, + '{"title":"About","icon": "settings","submenu":[{"link":"/safety.sql","title":"Security","icon": "logout"},{"link":"/performance.sql","title":"Performance"}]}' AS menu_item, + '{"title":"Examples","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg","submenu":[{"link":"/examples/tabs/","title":"Tabs","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg"},{"link":"/examples/layouts.sql","title":"Layouts"}]}' AS menu_item, + '{"title":"Examples","size":"sm","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg","submenu":[{"link":"/examples/tabs/","title":"Tabs","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg"},{"link":"/examples/layouts.sql","title":"Layouts"}]}' AS menu_item, + 'Official [SQLPage](https://sql-page.com) documentation' as footer; +``` diff --git a/examples/official-site/reference/components/shell/04-return-raw-xml.standalone.sql b/examples/official-site/reference/components/shell/04-return-raw-xml.standalone.sql new file mode 100644 index 000000000..1f85d4b88 --- /dev/null +++ b/examples/official-site/reference/components/shell/04-return-raw-xml.standalone.sql @@ -0,0 +1,27 @@ +/* +Returning custom HTML, XML, plain text, or other formats + +Use `shell-empty` to opt out of SQLPage's component system and return raw data directly. + +By default, SQLPage wraps all your content in a complete HTML page with navigation and styling. +The `shell-empty` component tells SQLPage to skip this HTML wrapper and return only the raw content you specify. + +Use it to create endpoints that return things like + - XML (for JSON, use the [json](/component.sql?component=json) component) + - plain text or markdown content (for instance for consumption by LLMs) + - a custom data format you need + +When using `shell-empty`, you should use the [http_header](/component.sql?component=http%5Fheader) component first +to set the correct [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) (like `application/json` or `application/xml`). +*/ +select + 'http_header' as "component", + 'application/xml' as "Content-Type"; + +select + 'shell-empty' as "component", + ' + + 42 + john.doe + ' as "contents"; diff --git a/examples/official-site/reference/components/shell/05-return-custom-html.standalone.sql b/examples/official-site/reference/components/shell/05-return-custom-html.standalone.sql new file mode 100644 index 000000000..5aca169eb --- /dev/null +++ b/examples/official-site/reference/components/shell/05-return-custom-html.standalone.sql @@ -0,0 +1,23 @@ +/* +Generate your own HTML + +If you generate your own HTML from a SQL query, you can also use the `shell-empty` component to include it in a page. +This is useful when you want to generate a snippet of HTML that can be dynamically included in a larger page. +Make sure you know what you are doing, and be careful to escape the HTML properly, +as you are stepping out of the safe SQLPage framework and into the wild world of HTML. + +In this scenario, you can use the `html` property, which serves as an alias for the `contents` property. +This property improves code readability by clearly indicating that you are generating HTML. +Since SQLPage returns HTML by default, there is no need to specify the content type in the HTTP header. +*/ +select + 'shell-empty' as "component", + ' + + + My page + + +

My page

+ +' as "html"; 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 new file mode 100644 index 000000000..837e2f934 --- /dev/null +++ b/examples/official-site/reference/components/status_bar/01-query-workspace-status-bar.sql @@ -0,0 +1,22 @@ +/* +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"; 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 new file mode 100644 index 000000000..4c018db94 --- /dev/null +++ b/examples/official-site/reference/components/status_code/01-return-http-404.md @@ -0,0 +1,8 @@ +# 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/README.md b/examples/official-site/reference/components/status_code/README.md new file mode 100644 index 000000000..e9a034da0 --- /dev/null +++ b/examples/official-site/reference/components/status_code/README.md @@ -0,0 +1,29 @@ +Set the HTTP status code returned by a page. + +This is an advanced technical component. +You typically need it when building internet-facing APIs and websites, +but you may not need it for simple internal applications. + +- Indicating operation results when using [SQLPage as an API](?component=json) + - `200`: *OK*, for successful operations + - `201`: *Created*, for successful record insertion + - `404`: *Not Found*, for missing resources + - `500`: *Internal Server Error*, for failed operations +- Handling data validation errors + - `400`: *Bad Request*, for invalid data +- Enforcing access controls + - `403`: *Forbidden*, for unauthorized access + - `401`: *Unauthorized*, for unauthenticated access +- Tracking system health + - `500`: *Internal Server Error*, for failed operations + +For search engine optimization: +- Use `404` for deleted content to remove outdated URLs from search engines +- For redirection from one page to another, use + - `301` (moved permanently), or + - `302` (moved temporarily) +- Use `503` during maintenance + +## Top-level parameters + + - **status** (INTEGER, required): HTTP status code (e.g., 200 OK, 401 Unauthorized, 409 Conflict) 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 new file mode 100644 index 000000000..eb504319f --- /dev/null +++ b/examples/official-site/reference/components/steps/01-online-checkout-steps.sql @@ -0,0 +1,13 @@ +/* +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"; 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 new file mode 100644 index 000000000..f206e53f2 --- /dev/null +++ b/examples/official-site/reference/components/steps/02-numbered-progress-with-icons.sql @@ -0,0 +1,36 @@ +/* +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"; 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 new file mode 100644 index 000000000..a0d93655e --- /dev/null +++ b/examples/official-site/reference/components/tab/01-tabs-for-page-navigation.sql @@ -0,0 +1,33 @@ +/* +Basic tabs for page navigation + +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: + +```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; + +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'; 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 new file mode 100644 index 000000000..7667a4409 --- /dev/null +++ b/examples/official-site/reference/components/tab/02-centered-tabs-with-icons.sql @@ -0,0 +1,23 @@ +/* +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"; + +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"; + +select + 'Tab' as "title", + '/component.sql?component=tab#component' as "link", + 'user' as "icon", + 'purple' as "color"; + +select + 'Card' as "title", + '/component.sql?component=card#component' as "link", + 'credit-card' as "icon"; diff --git a/examples/official-site/reference/components/table/01-simple-table.sql b/examples/official-site/reference/components/table/01-simple-table.sql new file mode 100644 index 000000000..2ce725212 --- /dev/null +++ b/examples/official-site/reference/components/table/01-simple-table.sql @@ -0,0 +1,7 @@ +/* +The most basic table +*/ +select 'table' as "component"; + +select 1 as "a", 2 as "b" +union all select 3, 4; diff --git a/examples/official-site/reference/components/table/02-filter-and-sort-users.sql b/examples/official-site/reference/components/table/02-filter-and-sort-users.sql new file mode 100644 index 000000000..b05446253 --- /dev/null +++ b/examples/official-site/reference/components/table/02-filter-and-sort-users.sql @@ -0,0 +1,11 @@ +/* +A table of users with filtering and sorting +*/ +select + 'table' as "component", + TRUE as "sort", + TRUE as "search", + 'Filter by name' as "search_placeholder"; + +select 'Ophir' as "First Name", 'Lojkine' as "Last Name", 'lovasoa' as "Pseudonym" +union all select 'Linus', 'Torvalds', 'torvalds'; diff --git a/examples/official-site/reference/components/table/03-markdown-links.sql b/examples/official-site/reference/components/table/03-markdown-links.sql new file mode 100644 index 000000000..a0519a1cd --- /dev/null +++ b/examples/official-site/reference/components/table/03-markdown-links.sql @@ -0,0 +1,19 @@ +/* +A table that uses markdown to display links +*/ +select + 'table' as "component", + 'Name' as "markdown", + 'icon' as "icon", + TRUE as "search"; + +select + 'table' as "icon", + '[Table](/component.sql?component=table)' as "name", + 'Displays SQL results as a searchable table.' as "description", + 'red' as "_sqlpage_color"; + +select + 'timeline' as "icon", + '[Chart](/component.sql?component=chart)' as "name", + 'Show graphs based on numeric data.' as "description"; diff --git a/examples/official-site/reference/components/table/04-embed-charts-in-cells.sql b/examples/official-site/reference/components/table/04-embed-charts-in-cells.sql new file mode 100644 index 000000000..c6edf5b5c --- /dev/null +++ b/examples/official-site/reference/components/table/04-embed-charts-in-cells.sql @@ -0,0 +1,11 @@ +/* +Embed charts in table cells + +`embed: Chart` names the column to render. Each row supplies its own chart URL in `Chart`; an empty value leaves that cell empty. The browser requests each populated cell separately. +*/ +select + 'table' as "component", + 'Chart' as "embed"; + +select 7 as "Starting number", '/examples/chart.sql?n=7&color=blue' as "Chart" +union all select 13, '/examples/chart.sql?n=13&color=green'; 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 new file mode 100644 index 000000000..4d2b37a5a --- /dev/null +++ b/examples/official-site/reference/components/table/05-sortable-table-with-average-footer.sql @@ -0,0 +1,16 @@ +/* +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"; 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 new file mode 100644 index 000000000..ea0248a36 --- /dev/null +++ b/examples/official-site/reference/components/table/06-sort-table-columns.sql @@ -0,0 +1,23 @@ +/* +Sort table columns + +A table with column sorting. Sorting sorts numbers in numeric order, and strings in alphabetical order. + +Numbers can be displayed + - as raw digits without formatting using the `raw_numbers` property, + - as currency using the `money` property to define columns that contain monetary values and `currency` to define the currency, + - as numbers with a fixed maximum number of decimal digits using the `number_format_digits` property. +*/ +select + 'table' as "component", + TRUE as "sort", + 'Price' as "align_right", + 'Amount in stock' as "align_right", + JSON('["part_no"]') as "align_center", + JSON('["id"]') as "raw_numbers", + 'USD' as "currency", + JSON('["Price"]') as "money"; + +select 31456 as "id", 'SQL-TABLE-856-G' as "part_no", 12 as "Price", 5 as "Amount in stock" +union all select 996, 'SQL-FORMS-86-M', 1, 1234 +union all select 131456, 'SQL-CARDS-56-K', 127, 98; 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 new file mode 100644 index 000000000..af698a629 --- /dev/null +++ b/examples/official-site/reference/components/table/07-striped-rows-and-initial-search.sql @@ -0,0 +1,17 @@ +/* +A table with some presentation options +*/ +select + 'table' as "component", + TRUE as "hover", + TRUE as "striped_rows", + 'Some Star Trek Starfleet starships' as "description", + TRUE as "small", + 'NCC-' as "initial_search_value"; + +select 'USS Enterprise' as "name", 'NCC-1701-C' as "registry", 'Ambassador' as "class" +union all select 'USS Archer', 'NCC-44278', 'Archer' +union all select 'USS Endeavour', 'NCC-06', 'Columbia' +union all select 'USS Constellation', 'NCC-1974', 'Constellation' +union all select 'USS Dakota', 'NCC-63892', 'Akira' +union all select 'USS Defiant', 'IX-74205', 'Defiant'; 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 new file mode 100644 index 000000000..cef80ab09 --- /dev/null +++ b/examples/official-site/reference/components/table/08-friendly-empty-message.sql @@ -0,0 +1,6 @@ +/* +An empty table with a friendly message +*/ +select + 'table' as "component", + 'Nothing to see here at the moment.' as "empty_description"; diff --git a/examples/official-site/reference/components/table/09-freeze-headers-and-columns.sql b/examples/official-site/reference/components/table/09-freeze-headers-and-columns.sql new file mode 100644 index 000000000..ad27454fc --- /dev/null +++ b/examples/official-site/reference/components/table/09-freeze-headers-and-columns.sql @@ -0,0 +1,70 @@ +/* +Freeze table headers and columns + +`freeze_columns` keeps the first column visible when scrolling sideways. `freeze_headers` keeps the column names visible when scrolling down. The footer in this example scrolls normally; set `freeze_footers` to pin it too. +*/ +select + 'table' as "component", + TRUE as "freeze_columns", + TRUE as "freeze_headers"; + +select + 'SQL Execution' as "feature", + 'Fully compatible with existing databases SQL dialects, executes any SQL query.' as "description", + 'Short learning curve, easy to use, interoperable with existing tools.' as "benefits"; + +select + 'Data Visualization' as "feature", + 'Automatic visualizations of query results: graphs, plots, pie charts, heatmaps, etc.' as "description", + 'Quickly analyze data trends, attractive and easy to understand, no external visualization tools or languages to learn.' as "benefits"; + +select + 'User Authentication' as "feature", + 'Supports user sessions, from basic auth to single sign-on.' as "description", + 'Secure, enforces access control policies, and provides a customizable security layer.' as "benefits"; + +select + 'APIs' as "feature", + 'Allows building JSON REST APIs and integrating with external APIs.' as "description", + 'Enables automation and integration with other platforms, facilitates data exchange.' as "benefits"; + +select + 'Files' as "feature", + 'File uploads, downloads and processing. Supports local filesystem and database storage.' as "description", + 'Convenient file management, secure data handling, flexible storage options, integrates with existing systems.' as "benefits"; + +select + 'Maps' as "feature", + 'Supports GeoJSON and is compatible with GIS data for map visualization.' as "description", + 'Geospatial data representation, integrates with geographic information systems.' as "benefits"; + +select + 'Custom Components' as "feature", + 'Build advanced features using HTML, JavaScript, and CSS.' as "description", + 'Tailor-made user experiences, easy to implement custom UI requirements.' as "benefits"; + +select + 'Forms' as "feature", + 'Insert and update data in databases based on user input.' as "description", + 'Simplified data input and management, efficient user interactions with databases.' as "benefits"; + +select + 'DB Compatibility' as "feature", + 'Works with MySQL, PostgreSQL, SQLite, Microsoft SQL Server and compatible databases.' as "description", + 'Broad compatibility with popular database systems, ensures seamless integration.' as "benefits"; + +select + 'Security' as "feature", + 'Built-in protection against common web vulnerabilities: no SQL injection, no XSS.' as "description", + 'Passes audits and security reviews, reduces the risk of data breaches.' as "benefits"; + +select + 'Performance' as "feature", + 'Designed for performance, with a focus on efficient data processing and minimal overhead.' as "description", + 'Quickly processes large datasets, handles high volumes of requests, and minimizes server load.' as "benefits"; + +select + TRUE as "_sqlpage_footer", + 'Summary' as "feature", + 'Summarizes the features of the product.' as "description", + 'Provides a quick overview of the product''s features and benefits.' as "benefits"; 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 new file mode 100644 index 000000000..5580b38ae --- /dev/null +++ b/examples/official-site/reference/components/table/10-dynamic-column-names.md @@ -0,0 +1,47 @@ +# 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/11-row-action-buttons.sql b/examples/official-site/reference/components/table/11-row-action-buttons.sql new file mode 100644 index 000000000..e833d5567 --- /dev/null +++ b/examples/official-site/reference/components/table/11-row-action-buttons.sql @@ -0,0 +1,71 @@ +/* +Using action buttons in a table + +### Preset Actions: `edit_url` & `delete_url` +Since edit and delete are common actions, the `table` component has dedicated `edit_url` and `delete_url` properties to add buttons for these actions. +The value of these properties should be a URL, containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. + +### Column with fixed action buttons + +You may want to add custom action buttons to your table rows, for instance to view details, download a file, or perform a custom operation. +For this, the `table` component has a `custom_actions` top-level property that lets you define a column of buttons, each button defined by a name, an icon, a link, and an optional tooltip. + +### Column with variable action buttons + +The `table` component also supports the row level `_sqlpage_actions` column in your data table. +This is helpful if you want a more complex logic, for instance to disable a button on some rows, or to change the link or icon based on the row data. + +> WARNING! +> If the number of array items in `_sqlpage_actions` is not consistent across all rows, the table may not render correctly. +> You can leave blank spaces by including an object with only the `name` property. + +The table has a column of buttons, each button defined by the `custom_actions` column at the table level, and by the `_sqlpage_actions` property at the row level. + +### `custom_actions` & `_sqlpage_actions` JSON properties. + +Each button is defined by the following properties: +* `name`: sets the column header and the tooltip if no tooltip is provided, +* `tooltip`: text to display when hovering over the button, +* `link`: the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row, +* `icon`: the tabler icon name or image link to display on the button + +### Example using all of the above +*/ +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"; diff --git a/examples/official-site/reference/components/text/01-simple-paragraph.sql b/examples/official-site/reference/components/text/01-simple-paragraph.sql new file mode 100644 index 000000000..8d7c1df5f --- /dev/null +++ b/examples/official-site/reference/components/text/01-simple-paragraph.sql @@ -0,0 +1,6 @@ +/* +Rendering a simple text paragraph +*/ +select + 'text' as "component", + 'Hello, world ! <3' as "contents"; diff --git a/examples/official-site/reference/components/text/02-render-rich-markdown.sql b/examples/official-site/reference/components/text/02-render-rich-markdown.sql new file mode 100644 index 000000000..dd80f98e4 --- /dev/null +++ b/examples/official-site/reference/components/text/02-render-rich-markdown.sql @@ -0,0 +1,52 @@ +/* +Rendering rich text using Markdown +*/ +select + 'text' as "component", + TRUE as "article", + 'markdown-example' as "id", + ' +# Markdown in SQLPage + +## Simple formatting + +Markdown supports **bold**, *italics*, [external links](https://github.com/sqlpage/SQLPage), [links to other pages](/index.sql), and [intra-page links](#markdown-example). + +## Lists +### Unordered lists +* SQLPage is easy +* SQLPage is fun +* SQLPage is free + +### Ordered lists +1. SQLPage is fast +2. SQLPage is safe +3. SQLPage is open-source + +## Code +```sql +SELECT ''list'' AS component; +SELECT name as title FROM users; +``` + +## Tables + +| SQLPage component | Description | Documentation link | +| --- | --- | --- | +| text | A paragraph of text. | [Documentation](/component.sql?component=text) | +| list | A list of items. | [Documentation](/component.sql?component=list) | +| steps | A progress indicator. | [Documentation](/component.sql?component=steps) | +| form | A series of input fields. | [Documentation](/component.sql?component=form) | + +## Quotes +> Fantastic. +> +> — [HackerNews User](https://news.ycombinator.com/item?id=36194473#36209061) about SQLPage + +## Images +![SQLPage logo](https://sql-page.com/favicon.ico) + +## Horizontal rules +--- + +' as "contents_md"; diff --git a/examples/official-site/reference/components/text/03-links-and-styling.sql b/examples/official-site/reference/components/text/03-links-and-styling.sql new file mode 100644 index 000000000..5ed4b7254 --- /dev/null +++ b/examples/official-site/reference/components/text/03-links-and-styling.sql @@ -0,0 +1,20 @@ +/* +Rendering a paragraph with links and styling +*/ +select + 'text' as "component", + 'About SQL' as "title"; + +select + 'SQL' as "contents", + TRUE as "bold", + TRUE as "italics"; + +select + ' is a domain-specific language used in programming and designed for managing data held in a ' as "contents"; + +select + 'relational database management system' as "contents", + 'https://en.wikipedia.org/wiki/Relational_database' as "link"; + +select '. It is particularly useful in handling structured data.' as "contents"; diff --git a/examples/official-site/reference/components/text/04-in-page-link.sql b/examples/official-site/reference/components/text/04-in-page-link.sql new file mode 100644 index 000000000..8b0096994 --- /dev/null +++ b/examples/official-site/reference/components/text/04-in-page-link.sql @@ -0,0 +1,11 @@ +/* +An intra-page link to a section of the page +*/ +select + 'text' as "component", + 'This is a link to the [next paragraph](#my-paragraph). You can open this link in a new tab and the page will scroll to the paragraph on load.' as "contents_md"; + +select + 'text' as "component", + 'my-paragraph' as "id", + 'This **is** the next paragraph.' as "contents_md"; diff --git a/examples/official-site/reference/components/timeline/01-names-and-dates.sql b/examples/official-site/reference/components/timeline/01-names-and-dates.sql new file mode 100644 index 000000000..07a724e9c --- /dev/null +++ b/examples/official-site/reference/components/timeline/01-names-and-dates.sql @@ -0,0 +1,9 @@ +/* +A basic timeline with just names and dates +*/ +select + 'timeline' as "component", + TRUE as "simple"; + +select 'New message from Elon Musk' as "title", '13:00' as "date" +union all select 'Jeff Bezos assigned task "work more" to you.', 'yesterday, 16:35'; diff --git a/examples/official-site/reference/components/timeline/02-icons-colors-and-rich-text.sql b/examples/official-site/reference/components/timeline/02-icons-colors-and-rich-text.sql new file mode 100644 index 000000000..7d888e854 --- /dev/null +++ b/examples/official-site/reference/components/timeline/02-icons-colors-and-rich-text.sql @@ -0,0 +1,19 @@ +/* +A full-fledged timeline with icons, colors, and rich text descriptions +*/ +select 'timeline' as "component"; + +select + 'v0.13.0 was just released !' as "title", + 'https://github.com/sqlpage/SQLPage/releases/' as "link", + '2023-10-16' as "date", + 'brand-github' as "icon", + 'green' as "color", + 'This version introduces the `timeline` component.' as "description_md"; + +select + 'They are talking about us...' as "title", + '[This article](https://www.postgresql.org/about/news/announcing-sqlpage-build-dynamic-web-applications-in-sql-2672/) on the official PostgreSQL website mentions SQLPage.' as "description_md", + '2023-07-12' as "date", + 'database' as "icon", + 'blue' as "color"; diff --git a/examples/official-site/reference/components/title/01-heading-levels.sql b/examples/official-site/reference/components/title/01-heading-levels.sql new file mode 100644 index 000000000..4a402d78c --- /dev/null +++ b/examples/official-site/reference/components/title/01-heading-levels.sql @@ -0,0 +1,16 @@ +/* +Displays several titles with different levels +*/ +select + 'title' as "component", + 'Level 1' as "contents"; + +select + 'title' as "component", + 'Level 2' as "contents", + 2 as "level"; + +select + 'title' as "component", + 'Level 3' as "contents", + 3 as "level"; diff --git a/examples/official-site/reference/components/title/02-centered-title.sql b/examples/official-site/reference/components/title/02-centered-title.sql new file mode 100644 index 000000000..d81416d2b --- /dev/null +++ b/examples/official-site/reference/components/title/02-centered-title.sql @@ -0,0 +1,7 @@ +/* +Displays a centered title +*/ +select + 'title' as "component", + 'Level 1' as "contents", + TRUE as "center"; diff --git a/examples/official-site/reference/components/toast/01-dismiss-automatically.sql b/examples/official-site/reference/components/toast/01-dismiss-automatically.sql new file mode 100644 index 000000000..9405df517 --- /dev/null +++ b/examples/official-site/reference/components/toast/01-dismiss-automatically.sql @@ -0,0 +1,12 @@ +/* +Dismiss automatically + +A toast that opens when the page loads and disappears automatically after the default 5000 milliseconds. +*/ +select + 'toast' as "component", + 'toast-auto' as "id", + 'This is a SQLPage toast' as "title", + 'This toast will open automatically when the page loads.' as "description", + 'check' as "icon", + 'green' as "color"; diff --git a/examples/official-site/reference/components/toast/02-dismiss-manually.sql b/examples/official-site/reference/components/toast/02-dismiss-manually.sql new file mode 100644 index 000000000..066405a71 --- /dev/null +++ b/examples/official-site/reference/components/toast/02-dismiss-manually.sql @@ -0,0 +1,36 @@ +/* +Dismiss manually + +A persistent error notification that disables automatic dismissal and requires the user to activate its close button. +*/ +select + 'toast' as "component", + 'toast-dismissible' as "id", + 'persistent-error' as "trigger", + 'Could not save' as "title", + 'Review the highlighted fields and try again.' as "description", + 'alert-triangle' as "icon", + 'black' as "color", + 0 as "duration", + TRUE as "dismissible"; + +select + 'toast' as "component", + 'toast-nondismissible' as "id", + 'persistent-status' as "trigger", + 'Connection unavailable' as "title", + 'This persistent notification has no manual close control.' as "description", + 0 as "duration", + FALSE as "dismissible"; + +select + 'button' as "component"; + +select + 'Show dismissible error' as "title", + '#persistent-error' as "link", + 'red' as "color"; + +select + 'Show non-dismissible status' as "title", + '#persistent-status' as "link"; diff --git a/examples/official-site/reference/components/toast/03-render-markdown.sql b/examples/official-site/reference/components/toast/03-render-markdown.sql new file mode 100644 index 000000000..3ae008454 --- /dev/null +++ b/examples/official-site/reference/components/toast/03-render-markdown.sql @@ -0,0 +1,29 @@ +/* +Render Markdown + +A persistent rich Markdown notification. Markdown takes precedence over plain text and renders emphasis and a link as HTML, while plain-text content remains escaped. +*/ +select + 'toast' as "component", + 'toast-markdown' as "id", + 'rich-notifications' as "trigger", + 'Release available' as "title", + 'This fallback stays escaped' as "description", + 'Version **2.0** is ready. [Read the notes](https://example.com/releases).' as "description_md", + 'blue' as "color", + 0 as "duration"; + +select + 'toast' as "component", + 'toast-plain' as "id", + 'rich-notifications' as "trigger", + 'Plain text stays escaped' as "description", + 'white' as "color", + 0 as "duration"; + +select + 'button' as "component"; + +select + 'Show rich notifications' as "title", + '#rich-notifications' as "link"; diff --git a/examples/official-site/reference/components/toast/04-queue-notifications.sql b/examples/official-site/reference/components/toast/04-queue-notifications.sql new file mode 100644 index 000000000..92ac9f60b --- /dev/null +++ b/examples/official-site/reference/components/toast/04-queue-notifications.sql @@ -0,0 +1,35 @@ +/* +Queue notifications + +Several persistent queued notifications. Toasts with the same position share a container and stack instead of overlapping. +*/ +select + 'toast' as "component", + 'toast-stack-one' as "id", + 'queued notifications' as "trigger", + 'Import started' as "title", + 'Preparing records.' as "description", + 0 as "duration"; + +select + 'toast' as "component", + 'toast-stack-two' as "id", + 'queued notifications' as "trigger", + 'Import running' as "title", + 'Processing records.' as "description", + 0 as "duration"; + +select + 'toast' as "component", + 'toast-short' as "id", + 'queued notifications' as "trigger", + 'Temporary update' as "title", + 'This message closes shortly.' as "description", + 2000 as "duration"; + +select + 'button' as "component"; + +select + 'Show queued notifications' as "title", + '#queued notifications' as "link"; diff --git a/examples/official-site/reference/components/toast/05-bottom-center-notification.sql b/examples/official-site/reference/components/toast/05-bottom-center-notification.sql new file mode 100644 index 000000000..2de942e2c --- /dev/null +++ b/examples/official-site/reference/components/toast/05-bottom-center-notification.sql @@ -0,0 +1,20 @@ +/* +Choose a notification position + +A notification placed at the bottom center of the screen instead of the default top end. +*/ +select + 'toast' as "component", + 'toast-bottom-center' as "id", + 'bottom-notification' as "trigger", + 'Download ready' as "title", + 'Your export is ready.' as "description", + 'bottom-center' as "position", + 0 as "duration"; + +select + 'button' as "component"; + +select + 'Show bottom notification' as "title", + '#bottom-notification' as "link"; diff --git a/examples/official-site/reference/components/tracking/01-unknown-server-status.sql b/examples/official-site/reference/components/tracking/01-unknown-server-status.sql new file mode 100644 index 000000000..69cf7f1fd --- /dev/null +++ b/examples/official-site/reference/components/tracking/01-unknown-server-status.sql @@ -0,0 +1,15 @@ +/* +A basic example of servers tracking component +*/ +select + 'tracking' as "component", + 'Servers status' as "title"; + +select 'No data' as "title" +union all select 'No data' +union all select 'No data' +union all select 'No data' +union all select 'No data' +union all select 'No data' +union all select 'No data' +union all select 'No data'; 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 new file mode 100644 index 000000000..55d17a026 --- /dev/null +++ b/examples/official-site/reference/components/tracking/02-server-status-with-downtime.sql @@ -0,0 +1,21 @@ +/* +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'; + +select 'No data' as "title"; + +select 'success' as "color", 'operational' as "title" +union all select 'warning', 'Big load' +union all select 'success', 'operational'; diff --git a/examples/official-site/sqlpage/migrations/999_fts_search_index.sql b/examples/official-site/reference/search-index.sql similarity index 88% rename from examples/official-site/sqlpage/migrations/999_fts_search_index.sql rename to examples/official-site/reference/search-index.sql index ee0ba09e8..1611378bf 100644 --- a/examples/official-site/sqlpage/migrations/999_fts_search_index.sql +++ b/examples/official-site/reference/search-index.sql @@ -17,8 +17,8 @@ FROM reference_parameter AS p JOIN reference_entry AS e ON e.kind = p.kind AND e.name = p.entry; INSERT INTO documentation_fts(title, description, example_source, page, fragment) -SELECT component || ' component example', description, properties, e.link, 'example-' || example_number -FROM example_with_source AS x +SELECT x.title, x.description, x.source, e.link, 'example-' || x.number +FROM example AS x JOIN reference_entry AS e ON e.kind = 'component' AND e.name = x.component; INSERT INTO documentation_fts(title, description, page, parameters) diff --git a/examples/official-site/sqlpage/migrations/01_documentation.sql b/examples/official-site/sqlpage/migrations/01_documentation.sql index 31cd392cd..416260d90 100644 --- a/examples/official-site/sqlpage/migrations/01_documentation.sql +++ b/examples/official-site/sqlpage/migrations/01_documentation.sql @@ -1,1780 +1,38 @@ -CREATE TABLE component( - name TEXT PRIMARY KEY, - description TEXT NOT NULL, - icon TEXT, -- icon name from tabler icon - introduced_in_version TEXT +CREATE TABLE reference_category ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL, + sort_order INTEGER NOT NULL ); -CREATE TABLE parameter_type( - name TEXT PRIMARY KEY +CREATE TABLE component ( + name TEXT PRIMARY KEY, + description TEXT NOT NULL DEFAULT '', + icon TEXT, + introduced_in_version TEXT, + catalog_category TEXT REFERENCES reference_category(id), + catalog_summary TEXT ); -INSERT INTO parameter_type(name) VALUES - ('BOOLEAN'), ('COLOR'), ('HTML'), ('ICON'), ('INTEGER'), ('JSON'), ('REAL'), ('TEXT'), ('TIMESTAMP'), ('URL'); -CREATE TABLE parameter( - top_level BOOLEAN DEFAULT FALSE, - name TEXT, - component TEXT REFERENCES component(name) ON DELETE CASCADE, - description TEXT, - description_md TEXT, - type TEXT REFERENCES parameter_type(name) ON DELETE CASCADE, - optional BOOLEAN DEFAULT FALSE, +CREATE TABLE parameter ( + component TEXT NOT NULL REFERENCES component(name) ON DELETE CASCADE, + top_level BOOLEAN NOT NULL, + name TEXT NOT NULL, + type TEXT NOT NULL CHECK (type IN ( + 'BOOLEAN', 'COLOR', 'HTML', 'ICON', 'INTEGER', 'JSON', 'REAL', 'TEXT', 'TIMESTAMP', 'URL' + )), + optional BOOLEAN NOT NULL, + description_md TEXT NOT NULL, PRIMARY KEY (component, top_level, name) ); -CREATE TABLE example( - component TEXT REFERENCES component(name) ON DELETE CASCADE, - description TEXT, - properties JSON, - FOREIGN KEY (component) REFERENCES component(name) ON DELETE CASCADE -); - --- The reference shows the SQL and renders the same stored component rows. --- Arrays with several items become repeated column aliases, as in handwritten SQLPage files. -CREATE VIEW example_with_source AS -SELECT example.rowid AS example_id, - row_number() OVER (PARTITION BY component ORDER BY example.rowid) AS example_number, - example.*, - (SELECT group_concat('select' || char(10) || ( - WITH fields AS ( - SELECT field.key AS name, coalesce(item.type, field.type) AS type, - CASE WHEN item.key IS NULL THEN field.value ELSE item.value END AS value - FROM json_each(statement.value) AS field - LEFT JOIN json_each( - CASE WHEN field.type = 'array' AND json_array_length(field.value) > 1 THEN field.value END - ) AS item ON true - ) - SELECT group_concat(' ' || CASE type - WHEN 'true' THEN 'TRUE' - WHEN 'false' THEN 'FALSE' - WHEN 'array' THEN 'JSON(' || quote(value) || ')' - WHEN 'object' THEN 'JSON(' || quote(value) || ')' - ELSE quote(value) - END || format(' as "%w"', name), ',' || char(10)) - FROM fields - ) || ';', char(10) || char(10)) FROM json_each(example.properties) AS statement) AS source -FROM example; - -INSERT INTO component(name, icon, description) VALUES - ('list', 'list', 'A vertical list of items. Each item can be clickable and link to another page.'); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'list', * FROM (VALUES - -- top level - ('title', 'Text header at the top of the list.', 'TEXT', TRUE, TRUE), - ('empty_title', 'Title text to display if the list is empty.', 'TEXT', TRUE, TRUE), - ('empty_description', 'Description to display if the list is empty.', 'TEXT', TRUE, TRUE), - ('empty_description_md', 'Description to display if the list is empty, in Markdown format.', 'TEXT', TRUE, TRUE), - ('empty_link', 'URL to which the user should be taken if they click on the empty list.', 'URL', TRUE, TRUE), - ('compact', 'Whether to display the list in a more compact format, allowing more items to be displayed on the screen.', 'BOOLEAN', TRUE, TRUE), - ('wrap', 'Wrap list items onto multiple lines if they are too long', 'BOOLEAN', TRUE, TRUE), - -- item level - ('title', 'Name of the list item, displayed prominently.', 'TEXT', FALSE, FALSE), - ('description', 'A description of the list item, displayed as greyed-out text.', 'TEXT', FALSE, TRUE), - ('description_md', 'A description of the list item, displayed as greyed-out text, in Markdown format, allowing you to use rich text formatting, including `**bold**` and `*italic*` text.', 'TEXT', FALSE, TRUE), - ('link', 'An URL to which the user should be taken when they click on the list item.', 'URL', FALSE, TRUE), - ('icon', 'Name of an icon to display on the left side of the item.', 'ICON', FALSE, TRUE), - ('image_url', 'The URL of a small image to display on the left side of the item.', 'URL', FALSE, TRUE), - ('color', 'The name of a color, to be displayed as a dot near the list item contents.', 'COLOR', FALSE, TRUE), - ('active', 'Whether this item in the list is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE), - ('view_link', 'A URL to which the user should be taken when they click on the "view" icon. Does not show the icon when omitted.', 'URL', FALSE, TRUE), - ('edit_link', 'A URL to which the user should be taken when they click on the "edit" icon. Does not show the icon when omitted.', 'URL', FALSE, TRUE), - ('delete_link', 'A page that will be loaded when the user clicks on the delete button for this specific item. The link will be submitted as a POST request.', 'URL', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('list', 'A basic compact list', json('[{"component":"list", "compact": true, "title": "SQLPage lists are..."},{"title":"Beautiful"},{"title":"Useful"},{"title":"Versatile"}]')), - ('list', 'The empty state appears when the query after `select ''list'' as component` returns no rows. `empty_link` makes that state clickable.', json('[{"component":"list", "empty_title": "No items yet", "empty_description": "This list is empty. Click here to create a new item !", "empty_link": "documentation.sql"}]')), - ('list', ' -### A list with rich text descriptions - -This example illustrates creating a nice list where each item has a title, a description, an image, and a link to another page. - -> Be careful, nested links are not supported. If you use the list''s `link` property, then your markdown `description_md` should not contain any link. -', json('[{"component":"list", "wrap": true}, - {"title":"SQL Websites", "image_url": "/favicon.ico", "description_md":"Write SQL, get a website. SQLPage is a **SQL**-based **site** generator for **PostgreSQL**, **MySQL**, **SQLite** and **SQL Server**.", "link": "/"}, - {"title":"SQL Forms", "image_url": "https://upload.wikimedia.org/wikipedia/commons/b/b6/FileStack_retouched.jpg", "description_md":"Easily collect data **from users to your database** using the *form* component. Handle the data in SQL with `INSERT` or `UPDATE` queries.", "link": "?component=form"}, - {"title":"SQL Maps", "image_url": "https://upload.wikimedia.org/wikipedia/commons/1/15/Vatican_City_map_EN.png", "description_md":"Show database contents on a map using the *map* component. Works well with *PostGIS* and *SpatiaLite*.", "link": "?component=map"}, - {"title":"Advanced features", "icon": "settings", "description_md":"[Authenticate users](?component=authentication), [edit data](?component=form), [generate an API](?component=json), [maintain your database schema](/your-first-sql-website/migrations.sql), and more."} - ]')), - ('list', 'A beautiful list with bells and whistles.', - json('[{"component":"list", "title":"Top SQLPage features", "compact": true }, - {"title":"Authentication", "link":"?component=authentication", "description": "Authenticate users with a login form or HTTP basic authentication", "color": "red", "icon":"lock", "active": true, "view_link": "?component=authentication#view" }, - {"title":"Editing data", "link":"?component=form", "description": "SQLPage makes it easy to UPDATE, INSERT and DELETE data in your database tables", "color": "blue", "icon":"database", "edit_link": "?component=form#edit", "delete_link": "?component=form#delete" }, - {"title":"API", "link":"?component=json", "description": "Generate a REST API from a single SQL query to connect with other applications and services", "color": "green", "icon":"plug-connected", "edit_link": "?component=json#edit", "delete_link": "?component=json#delete" } - ]')); - -INSERT INTO component(name, icon, description) VALUES - ('datagrid', 'grid-dots', 'Display small pieces of information in a clear and readable way. Each item has a name and is associated with a value.'); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'datagrid', * FROM (VALUES - -- top level - ('title', 'Text header at the top of the data grid.', 'TEXT', TRUE, TRUE), - ('description', 'A short paragraph displayed below the title.', 'TEXT', TRUE, TRUE), - ('description_md', 'A short paragraph displayed below the title - formatted using markdown.', 'TEXT', TRUE, TRUE), - ('icon', 'Name of an icon to display on the left side of the title.', 'ICON', TRUE, TRUE), - ('image_url', 'URL of an image to display on the left side of the title.', 'URL', TRUE, TRUE), - -- item level - ('title', 'Name of the piece of information.', 'TEXT', FALSE, FALSE), - ('description', 'Value to display below the name.', 'TEXT', FALSE, TRUE), - ('footer', 'Muted text to display below the value.', 'TEXT', FALSE, TRUE), - ('image_url', 'URL of a small image (such as an avatar) to display on the left side of the value.', 'URL', FALSE, TRUE), - ('link', 'A target URL to which the user should be taken when they click on the value.', 'URL', FALSE, TRUE), - ('icon', 'An icon name (from tabler-icons.io) to display on the left side of the value.', 'ICON', FALSE, TRUE), - ('color', 'If set to a color name, the value will be displayed in a pill of that color.', 'COLOR', FALSE, TRUE), - ('active', 'Whether this item in the grid is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE), - ('tooltip', 'A tooltip to display when the user passes their mouse over the value.', 'TEXT', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('datagrid', 'Just some sections of information.', json('[{"component":"datagrid"},{"title":"Language","description":"SQL"},{"title":"Creation date","description":"1974"}, {"title":"Language family","description":"Query language"}]')), - ('datagrid', 'A beautiful data grid with nice colors and icons.', - json('[{"component":"datagrid", "title": "Ophir Lojkine", "image_url": "https://avatars.githubusercontent.com/u/552629", "description_md": "Member since **2021**"}, - {"title": "Pseudo", "description": "lovasoa", "image_url": "https://avatars.githubusercontent.com/u/552629" }, - {"title": "Status", "description": "Active", "color": "green"}, - {"title": "Email Status", "description": "Validated", "icon": "check", "active": true, "tooltip": "Email address has been validated."}, - {"title": "Personal page", "description": "ophir.dev", "link": "https://ophir.dev/", "tooltip": "About me"} - ]')), - ('datagrid', 'Using a picture in the data grid card header.', json('[ - {"component":"datagrid", "title": "Website Ideas", "icon": "bulb"}, - {"title": "Search engine", "link":"https://google.com", "description": "Google", "color": "red", "icon":"brand-google", "footer": "Owned by Alphabet Inc."}, - {"title": "Encyclopedia", "link":"https://wikipedia.org", "description": "Wikipedia", "color": "blue", "icon":"world", "footer": "Owned by the Wikimedia Foundation"} - ]')); - - -INSERT INTO component(name, icon, description) VALUES - ('steps', 'dots-circle-horizontal', 'Guide users through multi-stage processes, displaying a clear list of previous and future steps.'); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'steps', * FROM (VALUES - -- top level - ('color', 'Color of the bars displayed between steps.', 'COLOR', TRUE, TRUE), - ('counter', 'Display the number of the step on top of its name.', 'TEXT', TRUE, TRUE), - ('title', 'Title of the section.', 'TEXT', TRUE, TRUE), - ('description', 'Description of the section.', 'TEXT', TRUE, TRUE), - -- item level - ('title', 'Name of the step.', 'TEXT', FALSE, TRUE), - ('description', 'Tooltip to display when the user passes their mouse over the step''s name.', 'TEXT', FALSE, TRUE), - ('link', 'A target URL to which the user should be taken when they click on the step.', 'URL', FALSE, TRUE), - ('icon', 'An icon name (from tabler-icons.io) to display on the left side of the step name.', 'ICON', FALSE, TRUE), - ('active', 'Whether this item in the grid is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('steps', 'Online store checkout steps.', json('[{"component":"steps"},{"title":"Shopping"},{"title":"Store pickup"}, {"title":"Payment","active":true},{"title":"Review & Order"}]')), - ('steps', 'A progress indicator with custom color, auto-generated step numbers, icons, and description tooltips.', - json('[{"component":"steps", "counter": true, "color":"purple"}, '|| - '{"title": "Registration form", "icon":"forms", "link": "https://github.com/sqlpage/SQLPage", "description": "Initial account data creation."},' || - '{"title": "Email confirmation", "icon": "mail", "link": "https://sql-page.com", "description": "Confirm your email by clicking on a link in a validation email."},' || - '{"title": "ID verification", "description": "Checking personal information", "icon": "user", "link": "#"},' || - '{"title": "Final account approval", "description": "ophir.dev", "link": "https://ophir.dev/", "icon":"eye-check", "active": true},' || - '{"title":"Account creation", "icon":"check"}]')); - -INSERT INTO component(name, icon, description) VALUES - ('text', 'align-left', 'A paragraph of text. The entire component will render as a single paragraph, with each item being rendered as a span of text inside it, the styling of which can be customized using parameters.'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'text', * FROM (VALUES - -- top level - ('title', 'Text header before the paragraph.', 'TEXT', TRUE, TRUE), - ('center', 'Whether to center the title.', 'BOOLEAN', TRUE, TRUE), - ('html', 'Raw html code to include on the page. Don''t use that if you are not sure what you are doing, it may have security implications.', 'TEXT', TRUE, TRUE), - ('contents', 'A top-level paragraph of text to display, without any formatting, without having to make additional queries.', 'TEXT', TRUE, TRUE), - ('contents_md', 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.', 'TEXT', TRUE, TRUE), - ('article', 'Makes long texts more readable by increasing the line height, adding margins, using a serif font, and decorating the initial letter.', 'BOOLEAN', TRUE, TRUE), - -- item level - ('contents', 'A span of text to display', 'TEXT', FALSE, FALSE), - ('contents_md', 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.', 'TEXT', FALSE, TRUE), - ('link', 'An URL to which the user should be taken when they click on this span of text.', 'URL', FALSE, TRUE), - ('color', 'The name of a color for this span of text.', 'COLOR', FALSE, TRUE), - ('underline', 'Whether the span of text should be underlined.', 'BOOLEAN', FALSE, TRUE), - ('bold', 'Whether the span of text should be displayed as bold.', 'BOOLEAN', FALSE, TRUE), - ('code', 'Use a monospace font. Useful to display the text as code.', 'BOOLEAN', FALSE, TRUE), - ('italics', 'Whether the span of text should be displayed as italics.', 'BOOLEAN', FALSE, TRUE), - ('break', 'Indicates that the current span of text starts a new paragraph.', 'BOOLEAN', FALSE, TRUE), - ('size', 'A number between 1 and 6 indicating the font size.', 'INTEGER', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('text', 'Rendering a simple text paragraph.', json('[{"component":"text", "contents":"Hello, world ! <3"}]')), - ('text', 'Rendering rich text using markdown', json('[{"component":"text", "article": true, "contents_md":"\n'|| - '# Markdown in SQLPage\n\n' || - '## Simple formatting\n\n' || - 'SQLPage supports only plain text as column values, but markdown allows easily adding **bold**, *italics*, [external links](https://github.com/sqlpage/SQLPage), [links to other pages](/index.sql) and [intra-page links](#my-paragraph). \n\n' || - '## Lists\n' || - '### Unordered lists\n' || - '* SQLPage is easy\n' || - '* SQLPage is fun\n' || - '* SQLPage is free\n\n' || - '### Ordered lists\n' || - '1. SQLPage is fast\n' || - '2. SQLPage is safe\n' || - '3. SQLPage is open-source\n\n' || - '## Code\n' || - '```sql\n' || - 'SELECT ''list'' AS component;\n' || - 'SELECT name as title FROM users;\n' || - '```\n\n' || - '## Tables\n\n' || - '| SQLPage component | Description | Documentation link |\n' || - '| --- | --- | --- |\n' || - '| text | A paragraph of text. | [Documentation](https://sql-page.com/documentation.sql?component=text) |\n' || - '| list | A list of items. | [Documentation](https://sql-page.com/documentation.sql?component=list) |\n' || - '| steps | A progress indicator. | [Documentation](https://sql-page.com/documentation.sql?component=steps) |\n' || - '| form | A series of input fields. | [Documentation](https://sql-page.com/documentation.sql?component=form) |\n\n' || - '## Quotes\n' || - '> Fantastic.\n>\n' || - '> — [HackerNews User](https://news.ycombinator.com/item?id=36194473#36209061) about SQLPage\n\n' || - '## Images\n' || - '![SQLPage logo](https://sql-page.com/favicon.ico)\n\n' || - '## Horizontal rules\n' || - '---\n\n' || - '"}]')), - ('text', 'Rendering a paragraph with links and styling.', - json('[{"component":"text", "title":"About SQL"}, '|| - '{"contents":"SQL", "bold":true, "italics": true}, '|| - '{"contents":" is a domain-specific language used in programming and designed for managing data held in a "},'|| - '{"contents": "relational database management system", "link": "https://en.wikipedia.org/wiki/Relational_database"},'|| - '{"contents": ". It is particularly useful in handling structured data."}]') - ), - ( - 'text', - 'An intra-page link to a section of the page.', - json('[ - {"component":"text", "contents_md":"This is a link to the [next paragraph](#my-paragraph). You can open this link in a new tab and the page will scroll to the paragraph on load."}, - {"component":"text", "id": "my-paragraph", "contents_md": "This **is** the next paragraph."} - ]') - ) -; - -INSERT INTO component(name, icon, description) VALUES - ('form', 'cursor-text', ' -## Building forms in SQL - -The form component will display a series of input fields of various types, that can be filled in by the user. -When the user submits the form, the data is posted to an SQL file specified in the `action` property. - -### Handling submitted values - -The receiving SQL page will be able to handle the data, -and insert it into the database, use it to perform a search, format it, update existing data, etc. - -A value in a field named "x" will be available as `:x` in the SQL query of the target page. - -### Form projects - - - [A multi-step form](https://github.com/sqlpage/SQLPage/tree/main/examples/forms-with-multiple-steps), guiding the user through a process without overwhelming them with a large form. - - [File upload form](https://github.com/sqlpage/SQLPage/tree/main/examples/image%20gallery%20with%20user%20uploads), letting users upload images to a gallery. - - [Rich text editor](https://github.com/sqlpage/SQLPage/tree/main/examples/rich-text-editor), letting users write text with bold, italics, links, images, etc. - - [Master-detail form](https://github.com/sqlpage/SQLPage/tree/main/examples/master-detail-forms), to edit a list of structured items. - - [Form with a variable number of fields](https://github.com/sqlpage/SQLPage/tree/main/examples/forms%20with%20a%20variable%20number%20of%20fields), when the fields are not known in advance. - - [Demo of all input types](/examples/form), showing all the input types supported by SQLPage. -'); -INSERT INTO parameter(component, name, description_md, type, top_level, optional) SELECT 'form', * FROM (VALUES - -- top level - ('enctype', ' -Encoding used for POST submissions. Use `multipart/form-data` for file uploads. -', 'TEXT', TRUE, TRUE), - -- item level - ('formenctype', ' -When ``type`` is ``submit`` or ``image``, this specifies how the form-data -should be encoded when submitting it to the server. - -Takes precedence over any ``enctype`` set on the ``form`` element. - -NOTE: when a ``file`` type input is present, then ``formenctype="multipart/form-data"`` -is automatically applied to the default validate button. -', 'TEXT', FALSE, TRUE) -); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'form', * FROM (VALUES - -- top level - ('method', 'The default is `POST`: read a field named `x` as `:x` on the target page. Use `GET` for bookmarkable searches and filters; the field appears in the URL as `?x=value` and can be read as `$x`.', 'TEXT', TRUE, TRUE), - ('action', 'An optional link to a target page that will handle the results of the form. By default the target page is the current page with the id of the form (if passed) used as hash - this will bring us back to the location of the form after submission. Setting it to the name of a different sql file will load that file when the user submits the form.', 'TEXT', TRUE, TRUE), - ('title', 'A name to display at the top of the form. It will be displayed in a larger font size at the top of the form.', 'TEXT', TRUE, TRUE), - ('validate', 'The text to display in the button at the bottom of the form that submits the values. Omit this property to let the browser display the default form validation text, or set it to the empty string to remove the button completely.', 'TEXT', TRUE, TRUE), - ('validate_color', 'The color of the button at the bottom of the form that submits the values. Omit this property to use the default color.', 'COLOR', TRUE, TRUE), - ('validate_outline', 'A color to outline the validation button.', 'COLOR', TRUE, TRUE), - ('validate_shape', 'The shape of the validation button (e.g., pill, square).', 'TEXT', TRUE, TRUE), - ('validate_size', 'The size of the validation button (e.g., sm, lg).', 'TEXT', TRUE, TRUE), - ('reset', 'The text to display in the button at the bottom of the form that resets the form to its original state. Omit this property not to show a reset button at all.', 'TEXT', TRUE, TRUE), - ('id', 'A unique identifier for the form, which can then be used to validate the form from a button outside of the form.', 'TEXT', TRUE, TRUE), - ('auto_submit', 'Automatically submit the form when the user changes any of its fields, and remove the validation button.', 'BOOLEAN', TRUE, TRUE), - ('validate_icon', 'Name of an icon to be displayed on the left side of the submit button.', 'ICON', TRUE, TRUE), - ('reset_icon', 'Name of an icon to be displayed on the left side of the reset button.', 'ICON', TRUE, TRUE), - ('reset_color', 'The color of the button at the bottom of the form that resets the form to its original state. Omit this property to use the default color.', 'COLOR', TRUE, TRUE), - ('reset_outline', 'A color to outline the reset button.', 'COLOR', TRUE, TRUE), - ('reset_shape', 'The shape of the reset button (e.g., pill, square).', 'TEXT', TRUE, TRUE), - ('reset_size', 'The size of the reset button (e.g., sm, lg).', 'TEXT', TRUE, TRUE), - ('narrow', 'Whether to trim the horizontal padding between the icon and the label of the validation and reset buttons.', 'BOOLEAN', TRUE, TRUE), - -- item level - ('type', 'Declares input control behavior and expected format. All HTML input types are supported (text, number, date, file, checkbox, radio, hidden, ...). SQLPage adds some custom types: textarea, switch, header. text by default. See https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#input_types', 'TEXT', FALSE, TRUE), - ('name', 'The name of the input field, that you can use in the target page to get the value the user entered for the field.', 'TEXT', FALSE, FALSE), - ('label', 'A friendly name for the text field to show to the user.', 'TEXT', FALSE, TRUE), - ('placeholder', 'A placeholder text that will be shown in the field when is is empty.', 'TEXT', FALSE, TRUE), - ('value', 'A default value that will already be present in the field when the user loads the page.', 'TEXT', FALSE, TRUE), - ('options', 'A json array of objects containing the label and value of initial options of a select field. Used only when type=select. JSON objects in the array can contain the properties "label", "value" and "selected".', 'JSON', FALSE, TRUE), - ('options_source', 'Only for inputs of type `select`. URL of a SQL file that returns JSON search results for the dropdown. The SQL file receives the search text as `$search` and must return an array of objects with exactly `label` and `value`. Use `options` for options that should be available before the user searches.', 'URL', FALSE, TRUE), - ('required', 'Set this to true to prevent the form contents from being sent if this field is left empty by the user.', 'BOOLEAN', FALSE, TRUE), - ('min', 'The minimum value to accept for an input of type number', 'REAL', FALSE, TRUE), - ('max', 'The maximum value to accept for an input of type number', 'REAL', FALSE, TRUE), - ('checked', 'Used only for checkboxes and radio buttons. Indicates whether the checkbox should appear as already checked.', 'BOOLEAN', FALSE, TRUE), - ('multiple', 'For select elements, indicates that multiple elements can be selected simultaneously. When using multiple, you should add square brackets after the variable name: ''my_variable[]'' as name. For file inputs, lets the user select several files at once: save them all with [sqlpage.persist_uploaded_files](functions.sql?function=persist_uploaded_files).', 'BOOLEAN', FALSE, TRUE), - ('empty_option', 'Only for inputs of type `select`. Adds an empty option with the given label before the ones defined in `options`. Useful when generating other options from a database table.', 'TEXT', FALSE, TRUE), - ('searchable', 'For select and multiple-select elements, displays them with a nice dropdown that allows searching for options.', 'BOOLEAN', FALSE, TRUE), - ('dropdown', 'An alias for "searchable".', 'BOOLEAN', FALSE, TRUE), - ('create_new', 'In a select with a dropdown (`searchable`, `dropdown` or `options_source`), this option allows the user to enter new values, that are not in the list of options. Works for single selects and for multiselects.', 'BOOLEAN', FALSE, TRUE), - ('create_new_text', 'Text shown before the typed value in the dropdown row that creates a new value, when `create_new` is set. Replaces the default "Add", for instance to translate it.', 'TEXT', FALSE, TRUE), - ('no_results_text', 'Text shown in a select with a dropdown when the search matches no option. Replaces the default "No results found", for instance to translate it.', 'TEXT', FALSE, TRUE), - ('step', 'The increment of values in an input of type number. Set to 1 to allow only integers.', 'REAL', FALSE, TRUE), - ('description', 'A helper text to display near the input field.', 'TEXT', FALSE, TRUE), - ('description_md', 'A helper text to display near the input field - formatted using markdown.', 'TEXT', FALSE, TRUE), - ('pattern', 'A regular expression that the value must match. For instance, [0-9]{3} will only accept 3 digits.', 'TEXT', FALSE, TRUE), - ('autofocus', 'Automatically focus the field when the page is loaded', 'BOOLEAN', FALSE, TRUE), - ('width', 'Width of the form field, between 1 and 12.', 'INTEGER', FALSE, TRUE), - ('autocomplete', 'Whether the browser should suggest previously entered values for this field.', 'BOOLEAN', FALSE, TRUE), - ('minlength', 'Minimum length of text allowed in the field.', 'INTEGER', FALSE, TRUE), - ('maxlength', 'Maximum length of text allowed in the field.', 'INTEGER', FALSE, TRUE), - ('formaction', 'When type is "submit", this specifies the URL of the file that will handle the form submission. Useful when you need multiple submit buttons.', 'TEXT', FALSE, TRUE), - ('formmethod', 'When type is "submit", the HTTP method to submit the form with. Takes precedence over the form''s own "method".', 'TEXT', FALSE, TRUE), - ('formnovalidate', 'When type is "submit", skips the browser''s validation of the other fields when this button submits the form.', 'BOOLEAN', FALSE, TRUE), - ('formtarget', 'When type is "submit", where to display the response. Takes the same values as a link target: "_blank" to open a new tab, "_self" to stay in the same one.', 'TEXT', FALSE, TRUE), - ('accept', 'Used only for inputs of type "file". A comma-separated list of the file types the user can pick, given as extensions (".pdf,.png") or as MIME types ("image/*").', 'TEXT', FALSE, TRUE), - ('list', 'The id of a datalist element holding the suggestions to show for this field. The datalist itself has to be rendered by the "html" component.', 'TEXT', FALSE, TRUE), - ('class', 'A CSS class to apply to the form element.', 'TEXT', FALSE, TRUE), - ('prefix_icon','Icon to display on the left side of the input field, on the same line.','ICON',FALSE,TRUE), - ('prefix','Text to display on the left side of the input field, on the same line.','TEXT',FALSE,TRUE), - ('suffix','Short text to display after th input, on the same line. Useful to add units or a currency symbol to an input.','TEXT',FALSE,TRUE), - ('readonly','Set to true to prevent the user from modifying the value of the input field.','BOOLEAN',FALSE,TRUE), - ('rows','Number of rows to display for a textarea. Defaults to 3.','INTEGER',FALSE,TRUE), - ('disabled','Makes the field non-editable, non-focusable, and not submitted with the form. Use readonly instead for simple non-editable fields.','BOOLEAN',FALSE,TRUE), - ('id','A unique identifier for the input, which can then be used to select and manage the field with Javascript code. Usefull for advanced using as setting client side event listeners, interactive control of input field (disabled, visibility, read only, e.g.) and AJAX requests.','TEXT',FALSE,TRUE) -) x; -INSERT INTO example(component, description, properties) VALUES - ( - 'form', - ' - -The best way to manage forms in SQLPage is to create at least two separate files: - - - one that will contain the form itself, and will be loaded when the user visits the page, - - one that will handle the form submission, and will redirect to whatever page you want to display after the form has been submitted. - -For instance, if you were creating a form to manage a list of users, you could create: - - - a file named `users.sql` that would contain a list of users and a form to create a new user, - - a file named `create_user.sql` that would insert the new user in the database, and then redirect to `users.sql`. - -`create_user.sql` could contain the following sql statement to [safely](safety.sql) insert the new user in the database: - -```sql -INSERT INTO users(name) VALUES(:username) -RETURNING ''redirect'' AS component, ''users.sql'' AS link -``` - -When loading the page, the value for `:username` will be `NULL` if no value has been submitted. -', - json('[{"component":"form", "action": "create_user.sql"}, {"name": "username"}]')), - ('form', 'A user registration form, illustrating the use of required fields, and different input types.', - json('[{"component":"form", "title": "User", "validate": "Create new user"}, '|| - '{"name": "First name", "placeholder": "John"}, '|| - '{"name": "Last name", "required": true, "description": "We need your last name for legal purposes."},'|| - '{"name": "Resume", "type": "textarea"},'|| - '{"name": "Birth date", "type": "date", "max": "2010-01-01", "value": "1994-04-16"},'|| - '{"name": "Password", "type": "password", "pattern": "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$", "required": true, "description_md": "**Password Requirements:** Minimum **8 characters**, at least **one letter** & **one number**. *Tip:* Use a passphrase for better security!"},'|| - '{"label": "I accept the terms and conditions", "name": "terms", "type": "checkbox", "required": true}'|| - ']')), - ('form','Create prepended and appended inputs to make your forms easier to use.', - json('[{"component":"form"}, '|| - '{"name": "Your account", "prefix_icon": "mail", "prefix": "Email:", "suffix": "@mydomain.com"}, ' || - ']')), - - ('form','With the header type, you can group your input fields based on a theme. For example, you can categorize fields according to a person''s identity and their contact information.', - json('[{"component":"form","title":"Information about the person"}, '|| - '{"type": "header", "label": "Identity"},' || - '{"name": "Name"},' || - '{"name": "Surname"},' || - '{"type": "header","label": "Contact"},' || - '{"name": "phone", "label": "Phone number"},' || - '{"name": "Email"},' || - ']')), - - ('form','A toggle switch in an HTML form is a user interface element that allows users to switch between two states, typically "on" and "off." It visually resembles a physical switch and is often used for settings or options that can be enabled or disabled.', - json('[{"component":"form"}, - {"type": "switch", "label": "Dark theme", "name": "dark", "description": "Enable dark theme"}, - {"type": "switch", "label": "A required toggle switch", "name": "my_checkbox", "required": true,"checked": true}, - {"type": "switch", "label": "A disabled toggle switch", "name": "my_field", "disabled": true} - ]')), - - ('form', 'This example illustrates the use of the `select` type. -In this select input, the various options are hardcoded, but they could also be loaded from a database table, -[using a function to convert the rows into a json array](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) like - - `json_group_array()` in SQLite, - - `json_agg()` in Postgres, - - `JSON_ARRAYAGG()` in MySQL, or - - `FOR JSON PATH` in Microsoft SQL Server. - - -In SQLite, the query would look like -```sql -SELECT - ''select'' as type, - ''Select a fruit...'' as empty_option, - ''cherry'' as prefix_icon, - json_group_array(json_object( - ''label'', name, - ''value'', id - )) as options -FROM fruits -``` -', json('[{"component":"form", "action":"examples/show_variables.sql"}, - {"name": "Fruit", "type": "select", - "empty_option": "Select a fruit...", - "options": - "[{\"label\": \"Orange\", \"value\": 0}, {\"label\": \"Apple\", \"value\": 1}, {\"label\": \"Banana\", \"value\": 3}]"} - ]')), - ('form', '### Multi-select -You can authorize the user to select multiple options by setting the `multiple` property to `true`. -This creates a more compact (but arguably less user-friendly) alternative to a series of checkboxes. -In this case, you should add square brackets to the name of the field (e.g. `''my_field[]'' as name`). -The target page will then receive the value as a JSON array of strings, which you can iterate over using - - the `json_each` function [in SQLite](https://www.sqlite.org/json1.html) and [Postgres](https://www.postgresql.org/docs/9.3/functions-json.html), - - the [`OPENJSON`](https://learn.microsoft.com/fr-fr/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16) function in Microsoft SQL Server. - - in MySQL, json manipulation is less straightforward: see [the SQLPage MySQL json example](https://github.com/sqlpage/SQLPage/tree/main/examples/mysql%20json%20handling) - -[More information on how to handle JSON in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). - -The target page could then look like this: - -```sql -insert into best_fruits(id) -- INSERT INTO ... SELECT ... runs the SELECT query and inserts the results into the table -select CAST(value AS integer) as id -- all values are transmitted by the browser as strings -from json_each($my_field); -- in SQLite, json_each returns a table with a "value" column for each element in the JSON array -``` - -### Example multiselect generated from a database table - -If you have a table of all possible options (`my_options(id int, label text)`), -and want to generate a multi-select field from it, you have two options: -- if the number of options is not too large, you can use the `options` parameter to return them all as a JSON array in the SQL query -- if the number of options is large (e.g. more than 1000), you can use `options_source` to load options dynamically from a different SQL query as the user types - -#### Embedding all options in the SQL query - -Let''s say you have a table that contains the selected options per user (`my_user_options(user_id int, option_id int)`). -You can use a query like this to generate the multi-select field: - -```sql -select ''select'' as type, true as multiple, json_group_array(json_object( - ''label'', my_options.label, - ''value'', my_options.id, - ''selected'', my_user_options.option_id is not null -)) as options -from my_options -left join my_user_options - on my_options.id = my_user_options.option_id - and my_user_options.user_id = $user_id -``` - -This will generate a json array of objects, each containing the label, value and selected status of each option. - -#### Loading options dynamically from a different SQL query with `options_source` - -If the `my_options` table has a large number of rows, you can use the `options_source` parameter to load options dynamically from a different SQL query as the user types. - -We''ll write a second SQL file, `options_source.sql`, that will receive the user''s search string as a parameter named `$search`, - and return a json array of objects, each containing the label and value of each option. - -When both `options` and `options_source` are set, the local `options` are loaded first. Search results from `options_source` are loaded into the same option list; a result with the same `value` updates the existing option. This is useful to set a default preselected value with `options_source`. - -`options_source` may already contain query parameters. SQLPage preserves them and adds or replaces the `search` parameter when loading options. - -##### `options_source.sql` - -```sql -select ''json'' as component; - -select id as value, label as label -from my_options -where label like $search || ''%''; -``` - -##### `form` - -', json('[{"component":"form", "action":"examples/show_variables.sql", "reset": "Reset"}, - {"name": "component", "type": "select", - "value": "form", - "options": [{"label": "Form", "value": "form"}], - "options_source": "examples/from_component_options_source.sql?category=component", - "description": "Start typing the name of a component like ''map'' or ''form''..." - }]')), - ('form', 'This example illustrates the use of the `radio` type. -The `name` parameter is used to group the radio buttons together. -The `value` parameter is used to set the value that will be submitted when the user selects the radio button. -The `label` parameter is used to display a friendly name for the radio button. -The `description` parameter is used to display a helper text near the radio button. - -We could also save all the options in a database table, and then run a simple query like - -```sql -SELECT ''form'' AS component; -SELECT - ''radio'' as type, - ''db'' as name, - option_name as label, - option_id as value -FROM my_options; -``` - -In this example, depending on what the user clicks, the page will be reloaded with a the variable `$component` set to the string "form", "map", or "chart". - - ', json('[{"component":"form", "method": "GET"}, - {"name": "component", "type": "radio", "value": "form", "description": "Read user input in SQL", "label": "Form"}, - {"name": "component", "type": "radio", "value": "map", "checked": true, "description": "Display a map based on database data", "label": "Map"}, - {"name": "component", "type": "radio", "value": "chart", "description": "Interactive plots of SQL query results", "label": "Chart"} - ]')), - ('form', ' -### Dynamically refresh the page when the user changes the form - -The form will be automatically submitted when the user changes any of its fields, and the page will be reloaded with the new value. -The validation button is removed. -', json('[{"component":"form", "auto_submit": true}, - {"name": "component", "type": "select", "autocomplete": false, "options": [ - {"label": "Form", "value": "form", "selected": true}, - {"label": "Map", "value": "map"}, - {"label": "Chart", "value": "chart"} - ], "description": "Choose a component to view its documentation. No need to click a button, the page will be reloaded automatically.", "label": "Component"} - ]')), - ('form', 'When you want to include some information in the form data, but not display it to the user, you can use a hidden field. - -This can be used to track simple data such as the current user''s id, -or to implement more complex flows, such as a multi-step form, -where the user is redirected to a different page after each step. - -This can also be used to implement [CSRF protection](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern), -if your website has authenticated users that can perform sensitive actions through simple links. -But note that SQLPage cookies already have the `SameSite=strict` attribute by default, which protects you against CSRF attacks by default in most cases. - -', json('[{"component":"form", "validate": "Delete", "validate_color": "red"}, - {"type": "hidden", "name": "resource_id", "value": "1234"}, - {"name": "confirm", "label": "Please type \"sensitive resource\" here to confirm the deletion", "required": true} - ]')), - ('form', 'This example illustrates the use of custom validation buttons and half-width fields.', - json('[{"component":"form", "title": "User", "validate": "Create new user", "validate_color": "green", "reset": "Clear"}, - {"name": "first_name", "label": "First name", "placeholder": "John", "width": 4}, - {"name": "middle_name", "label": "Middle name", "placeholder": "Fitzgerald", "width": 4}, - {"name": "last_name", "label": "Last name", "placeholder": "Doe", "width": 4}, - {"name": "email", "label": "Email", "placeholder": "john.doe@gmail.com", "width": 12}, - {"name": "password", "label": "Password", "type": "password", "width": 6}, - {"name": "password_confirmation", "label": "Password confirmation", "type": "password", "width": 6}, - {"name": "terms", "label": "I accept the terms and conditions", "type": "checkbox", "required": true} - ]')), - ('form', ' -## File upload - -You can use the `file` type to allow the user to upload a file. - -The file will be uploaded to the server, and you will be able to access it using the -[`sqlpage.uploaded_file_path`](functions.sql?function=uploaded_file_path) function. - -Here is how you could save the uploaded file to a table in the database: - -```sql -INSERT INTO uploaded_file(name, data) -VALUES ( - sqlpage.uploaded_file_name(''my_file''), - sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''my_file'')) -); -``` -', - json('[{"component":"form", "enctype": "multipart/form-data", "title": "Upload a picture", "validate": "Upload", "action": "examples/handle_picture_upload.sql"}, - {"name": "my_file", "type": "file", "accept": "image/png, image/jpeg", "label": "Picture", "description": "Upload a small picture", "required": true} - ]')), - ('form', ' -## Form Encoding - -You can specify the way form data should be encoded by setting the `enctype` -top-level property on the form. - -You may also specify `formenctype` on `submit` and `image` type inputs. -This will take precedence over the `enctype` specified on the form and is -useful in the case there are multiple `submit` buttons on the form. -For example, an external site may have specific requirements on encoding type. - -As a rule of thumb, ``multipart/form-data`` is best when fields may contain -copious non-ascii characters or for binary data such as an image or a file. -However, ``application/x-www-form-urlencoded`` creates less overhead when -many short ascii text values are submitted. -', - json('[ - { - "component": "form", - "method": "post", - "enctype": "multipart/form-data", - "title": "Submit with different encoding types", - "validate": "Submit with form encoding type", - "action": "examples/handle_enctype.sql" - }, - {"name": "data", "type": "text", "label": "Data", "required": true}, - { - "name": "percent_encoded", - "type": "submit", - "label": "Submit as", - "width": 4, - "formaction": "examples/handle_enctype.sql", - "formenctype": "application/x-www-form-urlencoded", - "value": "application/x-www-form-urlencoded" - }, - { - "name": "multipart_form_data", - "type": "submit", - "label": "Submit as", - "width": 4, - "formaction": "examples/handle_enctype.sql", - "formenctype": "multipart/form-data", - "value": "multipart/form-data" - } -]')), - ('form', ' -## Bulk data insertion - -You can use the `file` type to allow the user to upload a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) -file containing data to insert in a table. - -SQLPage can load data from a CSV file and insert it into a database table. -SQLPage re-uses PostgreSQL''s [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html) -to specify the format of the CSV file, but makes it work with all supported databases. - -> When connected to a PostgreSQL database, SQLPage will use the native `COPY` statement, -> for super fast and efficient on-database CSV parsing. -> But it will also work transparently with other databases, by -> parsing the CSV locally and emulating the same behavior with simple `INSERT` statements. - -Here is how you could easily copy data from a CSV to a table in the database: - -```sql -copy product(name, description, price) from ''product_data_input'' -with (header true, delimiter '','', quote ''"''); -``` - -If you want to pre-process the data before inserting it into the final table, -you can use a temporary table to store the data, and then insert it into the final table: - -```sql --- temporarily store the data in a table with text columns -create temporary table if not exists product_tmp(name text, description text, price text); -delete from product_tmp; - --- copy the data from the CSV file into the temporary table -copy product_tmp(name, description, price) from ''product_data_input'' with (header true); - --- insert the data into the final table, converting the price column to an integer -insert into product(name, description, price) -select name, description, CAST(price AS integer) from product_tmp -where price is not null and description is not null and length(description) > 10; -``` - -This will load the processed CSV into the product table, provided it has the following structure: - -```csv -name,description,price -"SQLPage","A tool to create websites using SQL",0 -"PostgreSQL","A powerful open-source relational database",0 -"SQLite","A lightweight relational database",0 -"MySQL","A popular open-source relational database",0 -``` -', - json('[{"component":"form", "title": "CSV import", "validate": "Load data", "action": "examples/handle_csv_upload.sql"}, - {"name": "product_data_input", "type": "file", "accept": "text/csv", "label": "Products", "description": "Upload a CSV with a name, description, and price columns", "required": true} - ]')) -; - -INSERT INTO component(name, icon, description) VALUES - ('chart', 'timeline', 'A component that plots data. Line, area, bar, and pie charts are all supported. Each item in the component is a data point in the graph.'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'chart', * FROM (VALUES - -- top level - ('title', 'The name of the chart.', 'TEXT', TRUE, TRUE), - ('type', 'The type of chart. One of: "line", "area", "bar", "column", "pie", "scatter", "bubble", "heatmap", "rangeBar", or "treemap". "column" is a synonym of "bar".', 'TEXT', TRUE, FALSE), - ('time', 'Whether the x-axis represents time. If set to true, the x values will be parsed and formatted as dates for the user.', 'BOOLEAN', TRUE, TRUE), - ('xmin', 'The minimal value for the x-axis. When time is true, this can be a date or timestamp.', 'TEXT', TRUE, TRUE), - ('xmax', 'The maximum value for the x-axis. When time is true, this can be a date or timestamp.', 'TEXT', TRUE, TRUE), - ('ymin', 'The minimal value for the y-axis.', 'REAL', TRUE, TRUE), - ('ymax', 'The maximum value for the y-axis.', 'REAL', TRUE, TRUE), - ('xtitle', 'Title of the x axis, displayed below it.', 'TEXT', TRUE, TRUE), - ('ytitle', 'Title of the y axis, displayed to its left.', 'TEXT', TRUE, TRUE), - ('ztitle', 'Title of the z axis, displayed in tooltips.', 'TEXT', TRUE, TRUE), - ('xticks', 'Number of intervals used to generate a numeric x-axis, normally producing one more tick position. On category and time axes, this is a target for label density, so the visible label count may differ.', 'INTEGER', TRUE, TRUE), - ('yticks', 'Number of ticks on the y axis.', 'INTEGER', TRUE, TRUE), - ('ystep', 'Step between ticks on the y axis.', 'REAL', TRUE, TRUE), - ('marker', 'Marker size', 'REAL', TRUE, TRUE), - ('labels', 'Whether to show the data labels on the chart or not.', 'BOOLEAN', TRUE, TRUE), - ('color', 'The name of a color in which to display the chart. If there are multiple series in the chart, this parameter can be repeated multiple times.', 'COLOR', TRUE, TRUE), - ('stacked', 'Whether to cumulate values from different series. Supported by the "line", "area" and "bar" chart types, and ignored by the others. Series are aligned on their x values, and a series that has no value for a given x counts as zero there.', 'BOOLEAN', TRUE, TRUE), - ('toolbar', 'Whether to display a toolbar at the top right of the chart, that offers downloading the data as CSV.', 'BOOLEAN', TRUE, TRUE), - ('show_legend', 'Whether to display the legend listing all chart series. Defaults to true.', 'BOOLEAN', TRUE, TRUE), - ('logarithmic', 'Display the y-axis in logarithmic scale.', 'BOOLEAN', TRUE, TRUE), - ('horizontal', 'Displays a bar chart with horizontal bars instead of vertical ones.', 'BOOLEAN', TRUE, TRUE), - ('height', 'Height of the chart, in pixels. By default: 250', 'INTEGER', TRUE, TRUE), - -- item level - ('x', 'The value of the point on the horizontal axis. Numeric values use continuous, proportionate positioning; text values are evenly spaced categories. Set the top-level time property for dates and timestamps.', 'REAL', FALSE, FALSE), - ('y', 'The value of the point on the vertical axis', 'REAL', FALSE, FALSE), - ('z', 'A third value carried by the point. Used as the bubble radius in a bubble chart, and shown in the tooltip under the name given by the top-level "ztitle".', 'REAL', FALSE, TRUE), - ('link', 'A URL to open when the data point is clicked. The tooltip value also links to the point, as does a text x value when shown as the tooltip title.', 'URL', FALSE, TRUE), - ('label', 'An alias for parameter "x". On a row that draws a reference line, the text to display next to the line. Labels are plain text; HTML markup is displayed literally.', 'TEXT', FALSE, TRUE), - ('value', 'An alias for parameter "y"', 'REAL', FALSE, TRUE), - ('series', 'If multiple series are represented and share the same y-axis, this parameter can be used to distinguish between them. Series names are plain text; HTML markup is displayed literally.', 'TEXT', FALSE, TRUE), - ('yline', 'Draws a reference line across the chart at this value of the y axis instead of plotting a point, to show a limit such as a quota or an alarm threshold. Not drawn if it falls outside of the axis, so set ymax when the limit is above the data.', 'REAL', FALSE, TRUE), - ('yline_end', 'Makes the yline a band instead of a line, reaching to this value.', 'REAL', FALSE, TRUE), - ('xline', 'Draws a reference line across the chart at this position of the x axis instead of plotting a point, to mark an event such as a deployment. A date or a timestamp when time is set, otherwise one of the x values.', 'TEXT', FALSE, TRUE), - ('xline_end', 'Makes the xline a band instead of a line, reaching to this value.', 'TEXT', FALSE, TRUE), - ('color', 'The name of a color for what this row draws: the bar, slice or point it plots, or the reference line it draws. Defaults to the color of the series for a data point, and to grey for a reference line.', 'COLOR', FALSE, TRUE) -) x; -INSERT INTO example(component, description, properties) VALUES - ('chart', 'An area chart representing a time series, using the top-level property `time`. - Ticks on the x axis are adjusted automatically, and ISO datetimes are parsed and displayed in a readable format.', json('[ - { - "component": "chart", - "title": "Quarterly Revenue", - "type": "area", - "color": "blue-lt", - "marker": 5, - "time": true - }, - {"x":"2022-01-01T00:00:00Z","y":15}, - {"x":"2022-04-01T00:00:00Z","y":46}, - {"x":"2022-07-01T00:00:00Z","y":23}, - {"x":"2022-10-01T00:00:00Z","y":70}, - {"x":"2023-01-01T00:00:00Z","y":35}, - {"x":"2023-04-01T00:00:00Z","y":106}, - {"x":"2023-07-01T00:00:00Z","y":53} - ]')), - ('chart', 'A pie chart.', json('[{"component":"chart", "title": "Answers", "type": "pie", "labels": true}, - {"label": "Yes", "value": 65}, - {"label": "No", "value": 35}]')), - ('chart', 'A basic bar chart', json('[ - {"component":"chart", "type": "bar", "title": "Quarterly Results", "horizontal": true, "labels": true}, - {"label": "Tom", "value": 35}, {"label": "Olive", "value": 15}]')), - ('chart', 'A TreeMap Chart allows you to display hierarchical data in a nested layout. This is useful for visualizing the proportion of each part to the whole.', - json('[ - {"component":"chart", "type": "treemap", "title": "Quarterly Results By Region (in k$)", "labels": true }, - {"series": "North America", "label": "United States", "value": 35}, - {"series": "North America", "label": "Canada", "value": 15}, - {"series": "Europe", "label": "France", "value": 30}, - {"series": "Europe", "label": "Germany", "value": 55}, - {"series": "Asia", "label": "China", "value": 20}, - {"series": "Asia", "label": "Japan", "value": 10} - ]')), - ('chart', 'A bar chart with multiple series.', json('[{"component":"chart", "title": "Expenses", "type": "bar", "stacked": true, "toolbar": true, "show_legend": false, "ystep": 10}, '|| - '{"series": "Marketing", "x": 2021, "value": 35}, '|| - '{"series": "Marketing", "x": 2022, "value": 15}, '|| - '{"series": "Human resources", "x": 2021, "value": 30}, '|| - '{"series": "Human resources", "x": 2022, "value": 55}]')), - ('chart', 'A stacked area chart, showing how each series contributes to a total. -The `stacked` property also works with the `line` and `bar` chart types. - -Series are aligned on their `x` values, and a series that has no value for a given `x` counts as zero there: -below, the graphics card draws no power outside of the render. -If a missing value does not mean zero in your data, make all the series share the same `x` values, -for instance by rounding timestamps to a common interval.', - json('[{"component":"chart", "title": "Power draw", "type": "area", "stacked": true, "time": true, "ytitle": "watts", "color": ["blue", "teal"], "marker": 4}, '|| - '{"series": "CPU", "x": "2024-03-01T10:00:00Z", "value": 45}, '|| - '{"series": "CPU", "x": "2024-03-01T10:15:00Z", "value": 52}, '|| - '{"series": "CPU", "x": "2024-03-01T10:30:00Z", "value": 48}, '|| - '{"series": "CPU", "x": "2024-03-01T10:45:00Z", "value": 44}, '|| - '{"series": "GPU", "x": "2024-03-01T10:15:00Z", "value": 120}, '|| - '{"series": "GPU", "x": "2024-03-01T10:30:00Z", "value": 140}]')), - ('chart', 'A line chart with multiple series. One of the most common types of charts, often used to show trends over time. -Also demonstrates the use of the `toolbar` attribute to allow the user to download the graph as an image or the data as a CSV file.', - json('[{"component":"chart", "title": "Revenue", "ymin": 0, "toolbar": true}, - {"series": "Chicago Store", "x": 2021, "value": 35}, - {"series": "Chicago Store", "x": 2022, "value": 15}, - {"series": "Chicago Store", "x": 2023, "value": 45}, - {"series": "New York Store", "x": 2021, "value": 30}, - {"series": "New York Store", "x": 2022, "value": 55}, - {"series": "New York Store", "x": 2023, "value": 19} - ]')), - ('chart', 'A scatter plot with multiple custom options.', - json('[ - {"component":"chart", "title": "Gross domestic product and its growth", "type": "scatter", - "xtitle": "Growth Rate", "ytitle": "GDP (Trillions USD)", "height": 500, "marker": 8, - "xmin": 0, "xmax": 10, "ymin": 0, "ymax": 25, "yticks": 5}, - - {"series": "Brazil", "x": 2.5, "y": 2}, - {"series": "China", "x": 6.5, "y": 14}, - {"series": "United States", "x": 2.3, "y": 21}, - {"series": "France", "x": 1.5, "y": 3}, - {"series": "South Africa", "x": 0.9, "y": 0.3} - ]')), - ('chart', ' -## Heatmaps - -Set `type` to `heatmap` on the chart row. - -The data format follows the [apexcharts heatmap format](https://apexcharts.com/angular-chart-demos/heatmap-charts/basic/), -where each series is represented as a line in the chart: - - The `x` property of each item will be used as the x-axis value. - - The `series` property of each item will be used as the y-axis value. - - The `y` property of each item will be used as the value to display in the heatmap - -The `color` property sets the color of each series separately, in order. -',json('[ - {"component":"chart", "title": "Survey Results", "type": "heatmap", - "ytitle": "Database management system", "xtitle": "Year", "color": ["purple","purple","purple"]}, - { "series": "PostgreSQL", "x": "2000", "y": 48},{ "series": "SQLite", "x": "2000", "y": 44},{ "series": "MySQL", "x": "2000", "y": 78}, - { "series": "PostgreSQL", "x": "2010", "y": 65},{ "series": "SQLite", "x": "2010", "y": 62},{ "series": "MySQL", "x": "2010", "y": 83}, - { "series": "PostgreSQL", "x": "2020", "y": 73},{ "series": "SQLite", "x": "2020", "y": 38},{ "series": "MySQL", "x": "2020", "y": 87} - ]')), - ('chart', 'A timeline displaying events with a start and an end date. A data row can include a `link` to open when its bar or tooltip title is clicked.', - json('[ - {"component":"chart", "title": "Project Timeline", "type": "rangeBar", "time": true, "color": ["teal", "cyan"], "labels": true, "xmin": "2021-12-28", "xmax": "2022-01-04" }, - {"series": "Phase 1", "label": "Operations", "value": ["2021-12-29", "2022-01-02"], "link": "/examples/chart.sql?phase=1"}, - {"series": "Phase 2", "label": "Operations", "value": ["2022-01-03", "2022-01-04"]}, - {"series": "Yearly maintenance", "label": "Maintenance", "value": ["2022-01-01", "2022-01-03"]} - ]')), - ('chart', ' -## Coloring a single value - -A data row can carry its own `color`, to paint the one bar, slice or point it -plots. Use it when the color says something the axes do not: a threshold -crossed, a status, the one category the reader should look at first. - -```sql -select ''chart'' as component, ''bar'' as type, true as horizontal, - true as labels, false as show_legend; -select - window_label as label, - accounts as value, - case when days <= 30 then ''red'' when days <= 60 then ''orange'' else ''green'' end as color -from expiring_accounts order by days; -``` - -A row color takes precedence over the color of its series. On a `line` or an -`area` chart it paints the marker of the point, so set `marker` for it to show. -A `heatmap` shades its cells from their own value and ignores it. -', json('[ - {"component":"chart", "title": "Accounts expiring soon", "type": "bar", - "horizontal": true, "labels": true, "show_legend": false}, - {"label": "30 days", "value": 100, "color": "red"}, - {"label": "60 days", "value": 200, "color": "orange"}, - {"label": "90 days", "value": 300, "color": "green"} - ]')), - ('chart', 'A pie chart whose rows choose their own slice colors.', json('[ - {"component":"chart", "title": "Support tickets", "type": "pie", "labels": true}, - {"label": "Resolved", "value": 72, "color": "green"}, - {"label": "In progress", "value": 21, "color": "yellow"}, - {"label": "Overdue", "value": 7, "color": "red"} - ]')), - ('chart', ' -## Reference lines - -A row with a `yline` is not plotted as a data point, but drawn as a line across -the whole chart, at that value of the y axis. Use it for the limit that the data -should be read against: a disk quota, an alarm threshold, a service level -objective. Add `yline_end` to make it a band instead of a line. - -Reference lines are rows, so they come from a query like everything else, -and a chart can have as many of them as the query returns: - -```sql -select ''chart'' as component, ''CPU temperature'' as title, true as time, 100 as ymax; -select celsius as yline, name as label, color as color from thresholds; -select measured_at as x, celsius as y from readings order by measured_at; -``` - -They are drawn as annotations rather than as an extra series, so they are not -added to the total of a `stacked` chart, and are not filled in an `area` chart. - -A line outside of the y axis is not drawn, and does not stretch the axis to fit, -so set `ymax` when the limit is above the data. -', json('[ - {"component":"chart", "title": "CPU temperature", "type": "line", "time": true, - "ytitle": "°C", "ymax": 100, "color": "azure", "marker": 4}, - {"yline": 70, "label": "target", "color": "green"}, - {"yline": 90, "yline_end": 100, "label": "throttling", "color": "red"}, - {"x": "2024-05-01T08:00:00Z", "y": 52}, - {"x": "2024-05-01T09:00:00Z", "y": 58}, - {"x": "2024-05-01T10:00:00Z", "y": 71}, - {"x": "2024-05-01T11:00:00Z", "y": 83}, - {"x": "2024-05-01T12:00:00Z", "y": 94}, - {"x": "2024-05-01T13:00:00Z", "y": 76}, - {"x": "2024-05-01T14:00:00Z", "y": 63} - ]')), - ('chart', ' -## Marking events - -`xline` is the counterpart of `yline`: it marks a position on the x axis instead -of a value on the y axis. On its own it marks a moment, like a deployment. -With `xline_end`, it covers everything in between, like an incident or a -maintenance window. A single query can draw a whole log of them: - -```sql -select started_at as xline, ended_at as xline_end, summary as label, - case severity when ''outage'' then ''red'' else ''orange'' end as color -from incidents where started_at > $since; -``` - -When `time` is set, an `xline` is a date or a timestamp, written like the `x` of -a data point. On a chart with text labels on the x axis, it is one of those labels. -', json('[ - {"component":"chart", "title": "Request latency", "type": "area", "time": true, - "ytitle": "ms", "color": "blue-lt", "marker": 3}, - {"xline": "2024-05-01T10:00:00Z", "label": "deploy", "color": "green"}, - {"xline": "2024-05-01T11:30:00Z", "xline_end": "2024-05-01T13:00:00Z", - "label": "incident", "color": "red"}, - {"x": "2024-05-01T08:00:00Z", "y": 120}, - {"x": "2024-05-01T09:00:00Z", "y": 134}, - {"x": "2024-05-01T10:00:00Z", "y": 128}, - {"x": "2024-05-01T11:00:00Z", "y": 141}, - {"x": "2024-05-01T12:00:00Z", "y": 512}, - {"x": "2024-05-01T13:00:00Z", "y": 470}, - {"x": "2024-05-01T14:00:00Z", "y": 156}, - {"x": "2024-05-01T15:00:00Z", "y": 133} - ]')), - ('chart', ' -## Reference lines follow their axis - -A reference belongs to the column it is written in, not to a direction on the -screen. `yline` always marks a value of `y`, and `xline` a position on `x`, -whichever way round the chart is drawn. A `horizontal` bar chart runs its y axis -from left to right, so a `yline` is drawn down the chart and an `xline` picks out -one of the bars. - -```sql -select ''chart'' as component, ''bar'' as type, true as horizontal, 100 as ymax; -select 90 as yline, ''full'' as label, ''red'' as color; -select ''db-1'' as xline, ''watched'' as label, ''purple'' as color; -select host as x, percent_used as y from disks order by percent_used; -``` - -A `pie` has no axes and ignores reference lines, and on a `heatmap`, whose y axis -holds the names of the series, only `xline` has a meaning. -', json('[ - {"component":"chart", "title": "Disk usage", "type": "bar", "horizontal": true, - "ymax": 100, "color": "azure", "labels": true}, - {"yline": 90, "label": "full", "color": "red"}, - {"xline": "db-1", "label": "watched", "color": "purple"}, - {"x": "backup-1", "y": 41}, - {"x": "web-2", "y": 63}, - {"x": "db-1", "y": 88}, - {"x": "web-1", "y": 96} - ]')), - ('chart', ' -## Multiple charts on the same line - -You can create information-dense dashboards by using the [card component](?component=card#component) -to put multiple charts on the same line. - -For this, create one sql file per visualization you want to show, -and set the `embed` attribute of the [card](?component=card#component) component -to the path of the file you want to include, followed by `?_sqlpage_embed`. -', - json('[ - {"component":"card", "title":"A dashboard with multiple graphs on the same line", "columns": 2}, - {"embed": "/examples/chart.sql?color=green&n=42&_sqlpage_embed"}, - {"embed": "/examples/chart.sql?_sqlpage_embed" } - ]')); - -INSERT INTO component(name, icon, description) VALUES - ('table', 'table', 'A table with optional filtering and sorting. -Unlike most others, this component does not have a fixed set of item properties, any property that is used will be rendered directly as a column in the table. -Tables can contain rich text, including images, links, and icons. Table rows can be styled with a background color, and the table can be made striped, hoverable, and bordered. - -Advanced users can apply custom styles to table columns using a CSS class with the same name as the column, and to table rows using the `_sqlpage_css_class` property. -'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'table', * FROM (VALUES - -- top level - ('title', 'A title displayed above the table.', 'TEXT', TRUE, TRUE), - ('sort', 'Make the columns clickable to let the user sort by the value contained in the column.', 'BOOLEAN', TRUE, TRUE), - ('search', 'Add a search bar at the top of the table, letting users easily filter table rows by value.', 'BOOLEAN', TRUE, TRUE), - ('initial_search_value', 'Pre-fills the search bar used to filter the table. The user will still be able to edit the value to display table rows that will initially be filtered out.', 'TEXT', TRUE, TRUE), - ('search_placeholder', 'Customizes the placeholder text shown in the search input field. Replaces the default "Search..." with text that better describes what users should search for.', 'TEXT', TRUE, TRUE), - ('markdown', 'Set this to the name of a column whose content should be interpreted as markdown . Used to display rich text with links in the table. This argument can be repeated multiple times to intepret multiple columns as markdown.', 'TEXT', TRUE, TRUE), - ('icon', 'Set this to the name of a column whose content should be interpreted as a tabler icon name. Used to display icons in the table. This argument can be repeated multiple times to intepret multiple columns as icons. Introduced in v0.8.0.', 'TEXT', TRUE, TRUE), - ('embed', 'Name of a column whose values are URLs to HTML fragments, such as other SQLPage pages. Repeat this property to select multiple columns. The browser fetches each nonempty URL with `_sqlpage_embed=1`, which skips the SQLPage shell, and initializes any components inside the cell. Use only URLs whose HTML you trust. There is one request per populated cell. Sorting uses the original URL, and search skips embedded cells.', 'TEXT', TRUE, TRUE), - ('align_right', 'Name of a column the contents of which should be right-aligned. This argument can be repeated multiple times to align multiple columns to the right. Introduced in v0.15.0.', 'TEXT', TRUE, TRUE), - ('align_center', 'Name of a column the contents of which should be center-aligned. This argument can be repeated multiple times to align multiple columns to the center.', 'TEXT', TRUE, TRUE), - ('monospace', 'Name of a column the contents of which should be displayed in monospace. This argument can be repeated multiple times to display multiple columns in monospace. Introduced in v0.32.1.', 'TEXT', TRUE, TRUE), - ('striped_rows', 'Whether to add zebra-striping to any table row.', 'BOOLEAN', TRUE, TRUE), - ('striped_columns', 'Whether to add zebra-striping to any table column.', 'BOOLEAN', TRUE, TRUE), - ('hover', 'Whether to enable a hover state on table rows.', 'BOOLEAN', TRUE, TRUE), - ('border', 'Whether to draw borders on all sides of the table and cells.', 'BOOLEAN', TRUE, TRUE), - ('overflow', 'Whether to to let "wide" tables overflow across the right border and enable browser-based horizontal scrolling.', 'BOOLEAN', TRUE, TRUE), - ('small', 'Whether to use compact table.', 'BOOLEAN', TRUE, TRUE), - ('description','Description of the table contents. Helps users with screen readers to find a table and understand what it’s about.','TEXT',TRUE,TRUE), - ('empty_description', 'Text to display if the table does not contain any row. Defaults to "no data".', 'TEXT', TRUE, TRUE), - ('freeze_columns', 'Whether to freeze the leftmost column of the table.', 'BOOLEAN', TRUE, TRUE), - ('freeze_headers', 'Whether to freeze the top row of the table.', 'BOOLEAN', TRUE, TRUE), - ('freeze_footers', 'Whether to freeze the footer (bottom row) of the table, only works if that row has the `_sqlpage_footer` property applied to it.', 'BOOLEAN', TRUE, TRUE), - ('raw_numbers', 'Name of a column whose values are numeric, but should be displayed as raw numbers without any formatting (no thousands separators, decimal separator is always a dot). This argument can be repeated multiple times.', 'TEXT', TRUE, TRUE), - ('money', 'Name of a numeric column whose values should be displayed as currency amounts, in the currency defined by the `currency` property. This argument can be repeated multiple times.', 'TEXT', TRUE, TRUE), - ('currency', 'The ISO 4217 currency code (e.g., USD, EUR, GBP, etc.) to use when formatting monetary values.', 'TEXT', TRUE, TRUE), - ('number_format_digits', 'Maximum number of decimal digits to display for numeric values.', 'INTEGER', TRUE, TRUE), - ('number_format_locale', 'A BCP 47 language tag (e.g. "de-DE", "en-IN") deciding how numbers and monetary values are formatted. Defaults to the locale of the visitor''s browser.', 'TEXT', TRUE, TRUE), - ('edit_url', 'If set, an edit button will be added to each row. The value of this property should be a URL, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. Clicking the edit button will take the user to that URL. Added in v0.39.0', 'TEXT', TRUE, TRUE), - ('delete_url', 'If set, a delete button will be added to each row. The value of this property should be a URL, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. Clicking the delete button will take the user to that URL. Added in v0.39.0', 'TEXT', TRUE, TRUE), - ('custom_actions', 'If set, a column of custom action buttons will be added to each row. The value of this property should be a JSON array of objects, each object defining a button with the following properties: `name` (the text to display on the button), `icon` (the tabler icon name or image link to display on the button), `link` (the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row), and `tooltip` (optional text to display when hovering over the button). Added in v0.39.0', 'JSON', TRUE, TRUE), - -- row level - ('_sqlpage_css_class', 'For advanced users. Sets a css class on the table row. Added in v0.8.0.', 'TEXT', FALSE, TRUE), - ('_sqlpage_color', 'Sets the background color of the row. Added in v0.8.0.', 'COLOR', FALSE, TRUE), - ('_sqlpage_footer', 'Sets this row as the table footer. It is recommended that this parameter is applied to the last row. Added in v0.34.0.', 'BOOLEAN', FALSE, TRUE), - ('_sqlpage_id', 'Sets the id of the html tabler row element. Allows you to make links targeting a specific row in a table.', 'TEXT', FALSE, TRUE), - ('_sqlpage_actions', 'Sets custom action buttons for this specific row in addition to any defined at the table level, The value of this property should be a JSON array of objects, each object defining a button with the following properties: `name` (the text to display on the button), `icon` (the tabler icon name or image link to display on the button), `link` (the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row), and `tooltip` (optional text to display when hovering over the button). Added in v0.39.0', 'JSON', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('table', 'The most basic table.', - json('[{"component":"table"}, {"a": 1, "b": 2}, {"a": 3, "b": 4}]')), - ('table', 'A table of users with filtering and sorting.', - json('[ - {"component":"table", "sort":true, "search":true, "search_placeholder": "Filter by name"}, - {"First Name": "Ophir", "Last Name": "Lojkine", "Pseudonym": "lovasoa"}, - {"First Name": "Linus", "Last Name": "Torvalds", "Pseudonym": "torvalds"} - ]')), - ('table', 'A table that uses markdown to display links', - json('[{"component":"table", "markdown": "Name", "icon": "icon", "search": true}, '|| - '{"icon": "table", "name": "[Table](?component=table)", "description": "Displays SQL results as a searchable table.", "_sqlpage_color": "red"}, - {"icon": "timeline", "name": "[Chart](?component=chart)", "description": "Show graphs based on numeric data."} - ]')), - ('table', '`embed: Chart` names the column to render. Each row supplies its own chart URL in `Chart`; an empty value leaves that cell empty. The browser requests each populated cell separately.', - json('[ - {"component": "table", "embed": "Chart"}, - {"Starting number": 7, "Chart": "/examples/chart.sql?n=7&color=blue"}, - {"Starting number": 13, "Chart": "/examples/chart.sql?n=13&color=green"} - ]')), - ('table', 'A sortable table with a colored footer showing the average value of its entries.', - json('[{"component":"table", "sort":true}, '|| - '{"Person": "Rudolph Lingens", "Height": 190},' || - '{"Person": "Jane Doe", "Height": 150},' || - '{"Person": "John Doe", "Height": 200},' || - '{"_sqlpage_footer":true, "_sqlpage_color": "green", "Person": "Average", "Height": 180}]')), - ( - 'table', - 'A table with column sorting. Sorting sorts numbers in numeric order, and strings in alphabetical order. - -Numbers can be displayed - - as raw digits without formatting using the `raw_numbers` property, - - as currency using the `money` property to define columns that contain monetary values and `currency` to define the currency, - - as numbers with a fixed maximum number of decimal digits using the `number_format_digits` property. -', - json( - '[{"component":"table", "sort": true, "align_right": ["Price", "Amount in stock"], "align_center": ["part_no"], "raw_numbers": ["id"], "currency": "USD", "money": ["Price"] }, - {"id": 31456, "part_no": "SQL-TABLE-856-G", "Price": 12, "Amount in stock": 5}, - {"id": 996, "part_no": "SQL-FORMS-86-M", "Price": 1, "Amount in stock": 1234}, - {"id": 131456, "part_no": "SQL-CARDS-56-K", "Price": 127, "Amount in stock": 98} - ]' - )), - ( - 'table', - 'A table with some presentation options', - json( - '[{"component":"table", - "hover": true, "striped_rows": true, - "description": "Some Star Trek Starfleet starships", - "small": true, "initial_search_value": "NCC-" - }, - {"name": "USS Enterprise", "registry": "NCC-1701-C", "class":"Ambassador"}, - {"name": "USS Archer", "registry": "NCC-44278", "class":"Archer"}, - {"name": "USS Endeavour", "registry": "NCC-06", "class":"Columbia"}, - {"name": "USS Constellation", "registry": "NCC-1974", "class":"Constellation"}, - {"name": "USS Dakota", "registry": "NCC-63892", "class":"Akira"}, - {"name": "USS Defiant", "registry": "IX-74205", "class":"Defiant"} - ]' - )), - ( - 'table', - 'An empty table with a friendly message', - json('[{"component":"table", "empty_description": "Nothing to see here at the moment."}]') - ), - ( - 'table', - '`freeze_columns` keeps the first column visible when scrolling sideways. `freeze_headers` keeps the column names visible when scrolling down. The footer in this example scrolls normally; set `freeze_footers` to pin it too.', - json('[ - {"component": "table", "freeze_columns": true, "freeze_headers": true}, - { - "feature": "SQL Execution", - "description": "Fully compatible with existing databases SQL dialects, executes any SQL query.", - "benefits": "Short learning curve, easy to use, interoperable with existing tools." - }, - { - "feature": "Data Visualization", - "description": "Automatic visualizations of query results: graphs, plots, pie charts, heatmaps, etc.", - "benefits": "Quickly analyze data trends, attractive and easy to understand, no external visualization tools or languages to learn." - }, - { - "feature": "User Authentication", - "description": "Supports user sessions, from basic auth to single sign-on.", - "benefits": "Secure, enforces access control policies, and provides a customizable security layer." - }, - { - "feature": "APIs", - "description": "Allows building JSON REST APIs and integrating with external APIs.", - "benefits": "Enables automation and integration with other platforms, facilitates data exchange." - }, - { - "feature": "Files", - "description": "File uploads, downloads and processing. Supports local filesystem and database storage.", - "benefits": "Convenient file management, secure data handling, flexible storage options, integrates with existing systems." - }, - { - "feature": "Maps", - "description": "Supports GeoJSON and is compatible with GIS data for map visualization.", - "benefits": "Geospatial data representation, integrates with geographic information systems." - }, - { - "feature": "Custom Components", - "description": "Build advanced features using HTML, JavaScript, and CSS.", - "benefits": "Tailor-made user experiences, easy to implement custom UI requirements." - }, - { - "feature": "Forms", - "description": "Insert and update data in databases based on user input.", - "benefits": "Simplified data input and management, efficient user interactions with databases." - }, - { - "feature": "DB Compatibility", - "description": "Works with MySQL, PostgreSQL, SQLite, Microsoft SQL Server and compatible databases.", - "benefits": "Broad compatibility with popular database systems, ensures seamless integration." - }, - { - "feature": "Security", - "description": "Built-in protection against common web vulnerabilities: no SQL injection, no XSS.", - "benefits": "Passes audits and security reviews, reduces the risk of data breaches." - }, - { - "feature": "Performance", - "description": "Designed for performance, with a focus on efficient data processing and minimal overhead.", - "benefits": "Quickly processes large datasets, handles high volumes of requests, and minimizes server load." - }, - { - "_sqlpage_footer": true, - "feature": "Summary", - "description": "Summarizes the features of the product.", - "benefits": "Provides a quick overview of the product''s features and benefits." - } -]') - ), - ( - 'table', - '#### Dynamic column names in a table - -In all the previous examples, the column names were hardcoded in the SQL query. -This makes it very easy to quickly visualize the results of a query as a table, -but it can be limiting if you want to include columns that are not known in advance. -In situations when the number and names of the columns depend on the data, or on variables, -you can use the `dynamic` component to generate the table columns dynamically. - -For that, you will need to return JSON objects from your SQL query, where the keys are the column names, -and the values are the cell contents. - -Databases [offer utilities to generate JSON objects from query results](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) - - In PostgreSQL, you can use the [`json_build_object`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING) -function for a fixed number of columns, or [`json_object_agg`](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE) for a dynamic number of columns. - - In SQLite, you can use the [`json_object`](https://www.sqlite.org/json1.html) function for a fixed number of columns, -or the `json_group_object` function for a dynamic number of columns. - - In MySQL, you can use the [`JSON_OBJECT`](https://dev.mysql.com/doc/refman/8.0/en/json-creation-functions.html#function_json-object) function for a fixed number of columns, -or the [`JSON_OBJECTAGG`](https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html#function_json-objectagg) function for a dynamic number of columns. - - In Microsoft SQL Server, you can use the [`FOR JSON PATH`](https://docs.microsoft.com/en-us/sql/relational-databases/json/format-query-results-as-json-with-for-json-sql-server?view=sql-server-ver15) clause. - -For instance, let''s say we have a table with three columns: store, item, and quantity_sold. -We want to create a pivot table where each row is a store, and each column is an item. -We will return a set of json objects that look like this: `{"store":"Madrid", "Item1": 42, "Item2": 7, "Item3": 0}` - -```sql -SELECT ''table'' AS component; -with filled_data as ( - select - stores.store, items.item, - (select coalesce(sum(quantity_sold), 0) from store_sales where store=stores.store and item=items.item) as quantity - from (select distinct store from store_sales) as stores - cross join (select distinct item from store_sales) as items - order by stores.store, items.item -) -SELECT - ''dynamic'' AS component, - JSON_PATCH( -- SQLite-specific, refer to your database documentation for the equivalent JSON functions - JSON_OBJECT(''store'', store), - JSON_GROUP_OBJECT(item, quantity) - ) AS properties -FROM - filled_data -GROUP BY - store; -``` - -This will generate a table with the stores in the first column, and the items in the following columns, with the quantity sold in each store for each item. - -', NULL - ), - ( - 'table', -'## Using Action Buttons in a table. - -### Preset Actions: `edit_url` & `delete_url` -Since edit and delete are common actions, the `table` component has dedicated `edit_url` and `delete_url` properties to add buttons for these actions. -The value of these properties should be a URL, containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. - -### Column with fixed action buttons - -You may want to add custom action buttons to your table rows, for instance to view details, download a file, or perform a custom operation. -For this, the `table` component has a `custom_actions` top-level property that lets you define a column of buttons, each button defined by a name, an icon, a link, and an optional tooltip. - -### Column with variable action buttons - -The `table` component also supports the row level `_sqlpage_actions` column in your data table. -This is helpful if you want a more complex logic, for instance to disable a button on some rows, or to change the link or icon based on the row data. - -> WARNING! -> If the number of array items in `_sqlpage_actions` is not consistent across all rows, the table may not render correctly. -> You can leave blank spaces by including an object with only the `name` property. - -The table has a column of buttons, each button defined by the `custom_actions` column at the table level, and by the `_sqlpage_actions` property at the row level. - -### `custom_actions` & `_sqlpage_actions` JSON properties. - -Each button is defined by the following properties: -* `name`: sets the column header and the tooltip if no tooltip is provided, -* `tooltip`: text to display when hovering over the button, -* `link`: the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row, -* `icon`: the tabler icon name or image link to display on the button - -### Example using all of the above -' - , - json('[ - { - "component": "table", - "edit_url": "/examples/show_variables.sql?action=edit&update_id={id}", - "delete_url": "/examples/show_variables.sql?action=delete&delete_id={id}", - "custom_actions": { - "name": "history", - "tooltip": "View Standard History", - "link": "/examples/show_variables.sql?action=history&standard_id={id}", - "icon": "history" - } - }, - { - "name": "CalStd", - "vendor": "PharmaCo", - "Product": "P1234", - "lot number": "T23523", - "status": "Available", - "expires on": "2026-10-13", - "_sqlpage_id": 32, - "_sqlpage_actions": [ - { - "name": "View PDF", - "tooltip": "View Presentation", - "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf", - "icon": "file-type-pdf" - }, - { - "name": "Action", - "tooltip": "Set In Use", - "link": "/examples/show_variables.sql?action=set_in_use&standard_id=32", - "icon": "caret-right" - } - ] - }, - { - "name": "CalStd", - "vendor": "PharmaCo", - "Product": "P1234", - "lot number": "T2352", - "status": "In Use", - "expires on": "2026-10-14", - "_sqlpage_id": 33, - "_sqlpage_actions": [ - { - "name": "View PDF", - "tooltip": "View Presentation", - "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf", - "icon": "file-type-pdf" - }, - { - "name": "Action", - "tooltip": "Retire Standard", - "link": "/examples/show_variables.sql?action=retire&standard_id=33", - "icon": "test-pipe-off" - } - ] - }, - { - "name": "CalStd", - "vendor": "PharmaCo", - "Product": "P1234", - "lot number": "A123", - "status": "Discarded", - "expires on": "2026-09-30", - "_sqlpage_id": 31, - "_sqlpage_actions": [ - { - "name": "View PDF", - "tooltip": "View Presentation", - "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf", - "icon": "file-type-pdf" - }, - { - "name": "Action" - } - ] - } -]' -) +CREATE TABLE example ( + component TEXT NOT NULL REFERENCES component(name) ON DELETE CASCADE, + number INTEGER NOT NULL CHECK (number > 0), + title TEXT NOT NULL, + description TEXT NOT NULL, + path TEXT UNIQUE, + source TEXT, + preview BOOLEAN AS (path IS NOT NULL AND path NOT LIKE '%.standalone.sql'), + CHECK ((path IS NULL) = (source IS NULL)), + PRIMARY KEY (component, number) ); - - - -INSERT INTO component(name, icon, description) VALUES - ('csv', 'download', 'Lets the user download data as a CSV file. -Each column from the items in the component will map to a column in the resulting CSV. - -When `csv` is used as a **header component** (without a [shell](?component=shell)), it will trigger a download of the CSV file directly on page load. -If the csv file to download is large, we recommend using this approach. - -When used inside a page (after calling the shell component), this will add a button to the page that lets the user download the CSV file. -The button will need to load the entire contents of the CSV file in memory, inside the browser, even if the user does not click on it. -If the csv file to download is large, we recommend using this component without a shell component in order to efficiently stream the data to the browser. -'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'csv', * FROM (VALUES - -- top level - ('separator', 'How individual values should be separated in the CSV. "," by default, set it to "\t" for tab-separated values.', 'TEXT', TRUE, TRUE), - ('title', 'The text displayed on the download button.', 'TEXT', TRUE, FALSE), - ('filename', 'The name of the file that should be downloaded (without the extension).', 'TEXT', TRUE, TRUE), - ('icon', 'Name of the icon (from tabler-icons.io) to display in the button. Ignored when used as a header component.', 'ICON', TRUE, TRUE), - ('color', 'Color of the button. Ignored when used as a header component.', 'COLOR', TRUE, TRUE), - ('size', 'The size of the button (e.g., sm, lg). Ignored when used as a header component.', 'TEXT', TRUE, TRUE), - ('bom', 'Whether to include a Byte Order Mark (a special character indicating the character encoding) at the beginning of the file. This is useful for Excel compatibility.', 'BOOLEAN', TRUE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('csv', ' -### Header component: creating a CSV download URL - -You can create a page that will trigger a download of the CSV file when the user visits it. -The contents will be streamed efficiently from the database to the browser, without being fully loaded in memory. -This makes it possible to download even very large files without overloading the database server, the web server, or the client''s browser. - -#### `csv_download.sql` - -```sql -select ''csv'' as component, ''example.csv'' as filename; -SELECT * FROM my_large_table; -``` - -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. -', - json('[{"component":"button"}, {"title": "Download my data", "link": "/examples/csv_download.sql"}]')), - ('csv', ' -### CSV download button - -This will generate a button to download the CSV file. -The button element itself will embed the entire contents of the CSV file, so it should not be used for large files. -The file will be entirely loaded in memory on the user''s browser, even if the user does not click on the button. -For smaller files, this is easier and faster to use than creating a separate SQL file to generate the CSV. -', - json('[{"component":"csv", "title": "Download my data", "filename": "people", "icon": "file-download", "color": "green", "separator": ";", "bom": true}, '|| - '{"Forename": "Ophir", "Surname": "Lojkine", "Pseudonym": "lovasoa"},' || - '{"Forename": "Linus", "Surname": "Torvalds", "Pseudonym": "torvalds"}]')); - - -INSERT INTO component(name, icon, description) VALUES - ('dynamic', 'repeat', 'Renders other components, given their properties as JSON. -If you are looking for a way to run FOR loops, to share similar code between pages of your site, -or to render multiple components for every line returned by your SQL query, then this is the component to use'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'dynamic', * FROM (VALUES - -- top level - ('properties', 'A json object or array that contains the names and properties of other components.', 'JSON', TRUE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('dynamic', 'The dynamic component has a single top-level property named `properties`, but it can render any number of other components. -Let''s start with something simple to illustrate the logic. We''ll render a `text` component with two row-level properties: `contents` and `italics`. -', json('[{"component":"dynamic", "properties": "[{\"component\":\"text\"}, {\"contents\":\"Hello, I am a dynamic component !\", \"italics\":true}]"}]')), - ('dynamic', ' -## Static component data stored in `.json` files - -You can also store the data for a component in a `.json` file, and load it using the `dynamic` component. - -This is particularly useful to create a single [shell](?component=shell#component) defining the site''s overall appearance and menus, -and displaying it on all pages without duplicating its code. - -The following will load the data for a `shell` component from a file named `shell.json`, -using the [`sqlpage.read_file_as_text`](/functions.sql?function=read_file_as_text) function. - -```sql -SELECT ''dynamic'' AS component, sqlpage.read_file_as_text(''shell.json'') AS properties; -``` - -and `shell.json` would be placed at the website''s root and contain the following: - -```json -{ - "component": "shell", - "title": "SQLPage documentation", - "link": "/", - "menu_item": [ - {"link": "index.sql", "title": "Home"}, - {"title": "Community", "submenu": [ - {"link": "blog.sql", "title": "Blog"}, - {"link": "https//github.com/sqlpage/SQLPage/issues", "title": "Issues"}, - {"link": "https//github.com/sqlpage/SQLPage/discussions", "title": "Discussions"}, - {"link": "https//github.com/sqlpage/SQLPage", "title": "Github"} - ]} - ] -} -``` -', NULL), -('dynamic', ' -## Including another SQL file - -To avoid repeating the same code on multiple pages, you can include another SQL file using the `dynamic` component -together with the [`sqlpage.run_sql`](/functions.sql?function=run_sql) function. - -For instance, the following will include the file `shell.sql` at the top of the page, -and pass it a `$title` variable to display the page title. - -```sql -SELECT ''dynamic'' AS component, - sqlpage.run_sql(''shell.sql'', json_object(''title'', ''SQLPage documentation'')) AS properties; -``` - -And `shell.sql` could contain the following: - -```sql -SELECT ''shell'' AS component, - COALESCE($title, ''Default title'') AS title, - ''/my_icon.png'' AS icon, - ''products'' AS menu_item, - ''about'' AS menu_item; -``` - -', NULL), - ('dynamic', ' -## Dynamic shell - -On databases without a native JSON type (such as the default SQLite database), -you can use the `dynamic` component to generate -json data to pass to components that expect it. - -This example generates a menu similar to the [shell example](?component=shell#component), but without using a native JSON type. - -```sql -SELECT ''dynamic'' AS component, '' -{ - "component": "shell", - "title": "SQLPage documentation", - "link": "/", - "menu_item": [ - {"link": "index.sql", "title": "Home"}, - {"title": "Community", "submenu": [ - {"link": "blog.sql", "title": "Blog"}, - {"link": "https//github.com/sqlpage/SQLPage/issues", "title": "Issues"}, - {"link": "https//github.com/sqlpage/SQLPage/discussions", "title": "Discussions"}, - {"link": "https//github.com/sqlpage/SQLPage", "title": "Github"} - ]} - ] -} -'' AS properties -``` - -[View the result of this query, as well as an example of how to generate a dynamic menu -based on the database contents](./examples/dynamic_shell.sql). -', NULL), - ('dynamic', ' -## Dynamic tables - -The `dynamic` component can be used to generate [tables](?component=table#component) with dynamic columns, -using [your database''s JSON functions](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). - -For instance, let''s say we have a table with three columns: user_id, name, and role. -We want to create a table where each row is a user, and each column is a role. -We will return a set of json objects that look like this: `{"name": "Alice", "admin": true, "editor": false, "viewer": true}` -```sql -SELECT ''table'' AS component; -SELECT ''dynamic'' AS component, - json_patch( - json_object(''name'', name), - json_object_agg(role, is_admin) - ) AS properties -FROM users -GROUP BY name; -``` -', NULL); - -INSERT INTO component(name, icon, description) VALUES - ('shell', 'layout-navbar', ' -Customize the overall layout, header and footer of the page. - -This is a special component that provides the page structure wrapping all other components on your page. - -It generates the complete HTML document including the `` section with metadata, title, and stylesheets, -as well as the navigation bar, main content area, and footer. - -If you don''t explicitly call the shell component at the top of your SQL file, SQLPage will automatically -add a default shell component before your first try to display data on the page. - -Use the shell component to customize page-wide settings like the page title, navigation menu, theme, fonts, -and to include custom visual styles (with CSS) or interactive behavior (with JavaScript) that should be loaded on the page. -'); - -INSERT INTO parameter(component, name, description_md, type, top_level, optional) SELECT 'shell', * FROM (VALUES - ('favicon', 'The URL of the icon the web browser should display in bookmarks and tabs. This property is particularly useful if multiple sites are hosted on the same domain with different [``site_prefix``](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage).', 'URL', TRUE, TRUE), - ('manifest', 'The location of the [manifest.json](https://developer.mozilla.org/en-US/docs/Web/Manifest) if the site is a [PWA](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps). Among other features, serving a manifest enables your site to be "installed" as an app on most mobile devices.', 'URL', TRUE, TRUE) -) x; -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'shell', * FROM (VALUES - -- top level - ('title', 'The title of your page. Will be shown in a top bar above the page contents. Also usually displayed by web browsers as the name of the web page''s tab.', 'TEXT', TRUE, TRUE), - ('layout', 'The general page layout. Can be "boxed" (the default), "horizontal" (for a full-width menu), "vertical"(vertical menu), "fluid" (removes side margins).', 'TEXT', TRUE, TRUE), - ('description', 'A description of the page. It can be displayed by search engines when your page appears in their results.', 'TEXT', TRUE, TRUE), - ('link', 'The target of the link in the top navigation bar.', 'URL', TRUE, TRUE), - ('css', 'The URL of a CSS file to load and apply to the page.', 'URL', TRUE, TRUE), - ('javascript', 'The URL of a Javascript file to load and execute on the page.', 'URL', TRUE, TRUE), - ('javascript_module', 'The URL of a javascript module in the ESM format (see javascript.info/modules)', 'URL', TRUE, TRUE), - ('rss', 'The URL of an RSS feed to display in the top navigation bar. You can use the rss component to generate the field.', 'URL', TRUE, TRUE), - ('image', 'The URL of an image to display next to the page title.', 'URL', TRUE, TRUE), - ('social_image', 'The URL of the preview image that will appear in the Open Graph metadata when the page is shared on social media.', 'URL', TRUE, TRUE), - ('icon', 'Name of an icon (from tabler-icons.io) to display next to the title in the navigation bar.', 'ICON', TRUE, TRUE), - ('menu_item', 'Adds a menu item in the navigation bar at the top of the page. The menu item will have the specified name, and will link to as .sql file of the same name. A dropdown can be generated by passing a json object with a `title` and `submenu` properties.', 'TEXT', TRUE, TRUE), - ('fixed_top_menu', 'Fixes the top bar with menu at the top (the top bar remains visible when scrolling long pages).', 'BOOLEAN', TRUE, TRUE), - ('search_target', 'When this is set, a search field will appear in the top navigation bar, and load the specified sql file with an URL parameter named "search" when the user searches something.', 'TEXT', TRUE, TRUE), - ('search_value', 'This value will be placed in the search field when "search_target" is set. Using the "$search" query parameter value will mirror the value that the user has searched for.', 'TEXT', TRUE, TRUE), - ('search_placeholder', 'Customizes the placeholder text shown in the search input field. Replaces the default "Search" with text that better describes what users should search for. It is also used as the accessible name of the search field, which screen readers announce.', 'TEXT', TRUE, TRUE), - ('search_button', 'Customizes the text displayed on the search button. Replaces the default "Search" label with custom text that may better match your applications terminology or language.', 'TEXT', TRUE, TRUE), - ('navbar_toggle_label', 'Customizes the accessible name of the button that opens and closes the navigation menu on small screens, which screen readers announce. Replaces the default "Toggle navigation".', 'TEXT', TRUE, TRUE), - ('norobot', 'Forbids robots to save this page in their database and follow the links on this page. This will prevent this page to appear in Google search results for any query, for instance.', 'BOOLEAN', TRUE, TRUE), - ('font', 'Specifies the font to be used for displaying text, which can be a valid font name from fonts.google.com or the path to a local WOFF2 font file starting with a slash (e.g., "/fonts/MyLocalFont.woff2").', 'TEXT', TRUE, TRUE), - ('font_size', 'Font size on the page, in pixels. Set to 18 by default.', 'INTEGER', TRUE, TRUE), - ('language', 'The language of the page. This can be used by search engines and screen readers to determine in which language the page is written.', 'TEXT', TRUE, TRUE), - ('rtl', 'Whether the page should be displayed in right-to-left mode. Used to display Arabic, Hebrew, Persian, etc.', 'BOOLEAN', TRUE, TRUE), - ('refresh', 'Number of seconds after which the page should refresh. This can be useful to display dynamic content that updates automatically.', 'INTEGER', TRUE, TRUE), - ('sidebar', 'Whether the menu defined by menu_item should be displayed on the left side of the page instead of the top. Introduced in v0.27.', 'BOOLEAN', TRUE, TRUE), - ('sidebar_theme', 'Used with sidebar property, It can be set to "dark" to exclusively set the sidebar into dark theme.', 'TEXT', TRUE, TRUE), - ('theme', 'Set to "dark" to use a dark theme.', 'TEXT', TRUE, TRUE), - ('footer', 'Muted text to display in the footer of the page. This can be used to display a link to the terms and conditions of your application, for instance. By default, shows "Built with SQLPage". Supports links with markdown.', 'TEXT', TRUE, TRUE), - ('preview_image', 'The URL of an image to display as a link preview when the page is shared on social media', 'URL', TRUE, TRUE), - ('navbar_title', 'The title shown in the navigation bar or sidebar. Defaults to the page title. Set an empty string to show just the logo, if configured. With neither a navigation title nor a logo, there is no home link in the navigation bar.', 'TEXT', TRUE, TRUE), - ('target', 'Where the menu items should open: "_blank" for a new tab, "_self" for the same tab, "_parent" for the parent frame, or "_top" for the full body of the window. Set it inside a "menu_item" json object; it has no effect when set directly on the shell.', 'TEXT', TRUE, TRUE), - ('class', 'class attribute added to the page''s html element. It can be used to apply custom styling to the whole page through css.', 'TEXT', TRUE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('shell', ' -This example configures a dark shell with menus linking to pages on this site. - -Each `menu_item` object defines a link or a dropdown. The "Community" menu links to the blog, issue tracker, discussions, and source code. - -The object form can be used directly only on database engines that have a native JSON type. -On other engines (such as SQLite), you can use the [`dynamic`](?component=dynamic#component) component to generate the same result. - - -You see the [page layouts demo](./examples/layouts.sql) for a live example of the different layouts. -', - json('[{ - "component": "shell", - "title": "SQLPage: SQL websites", - "navbar_title": "SQLPage", - "link": "/", - "menu_item": [ - {"title": "About", "submenu": [ - {"link": "/safety.sql", "title": "Security", "icon": "lock"}, - {"link": "/performance.sql", "title": "Performance", "icon": "bolt"}, - {"link": "//github.com/sqlpage/SQLPage/blob/main/LICENSE.txt", "title": "License", "icon": "file-text"}, - {"link": "/blog.sql", "title": "Articles", "icon": "book"} - ]}, - {"title": "Examples", "submenu": [ - {"link": "/examples/tabs/", "title": "Tabs", "icon": "layout-navbar"}, - {"link": "/examples/layouts.sql", "title": "Layouts", "icon": "layout"}, - {"link": "/examples/multistep-form", "title": "Forms", "icon": "edit"}, - {"link": "/examples/handle_picture_upload.sql", "title": "File uploads", "icon": "upload"}, - {"link": "/examples/authentication/", "title": "Password protection", "icon": "password-user"}, - {"link": "//github.com/sqlpage/SQLPage/blob/main/examples/", "title": "All examples & demos", "icon": "code"} - ]}, - {"title": "Community", "submenu": [ - {"link": "/blog.sql", "title": "Blog", "icon": "book"}, - {"link": "//github.com/sqlpage/SQLPage/issues", "title": "Report a bug", "icon": "bug"}, - {"link": "//github.com/sqlpage/SQLPage/discussions", "title": "Discussions", "icon": "message"}, - {"link": "//github.com/sqlpage/SQLPage", "title": "Github", "icon": "brand-github"} - ]}, - {"title": "Documentation", "submenu": [ - {"link": "/your-first-sql-website", "title": "Getting started", "icon": "book"}, - {"link": "/components.sql", "title": "All Components", "icon": "list-details"}, - {"link": "/functions.sql", "title": "SQLPage Functions", "icon": "math-function"}, - {"link": "/extensions-to-sql", "title": "Extensions to SQL", "icon": "cube-plus"}, - {"link": "/custom_components.sql", "title": "Custom Components", "icon": "puzzle"}, - {"link": "//github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage", "title": "Configuration", "icon": "settings"} - ]}, - {"title": "Search", "link": "/search"} - ], - "layout": "boxed", - "language": "en-US", - "description": "Go from SQL queries to web applications in an instant.", - "preview_image": "https://sql-page.com/sqlpage_social_preview.webp", - "theme": "dark", - "font_size": 19, - "image": "/assets/icon.webp", - "favicon": "/favicon.ico", - "javascript_module": "/assets/highlightjs-launch.js", - "css": "/assets/highlightjs-and-tabler-theme.css", - "footer": "[Built with SQLPage](https://github.com/sqlpage/SQLPage/tree/main/examples/official-site)" - }]')), - ('shell', ' -This example shows how to set menu items as active in the navigation, so that they are highlighted in the nav bar. - -In this example you can see that two menu items are created, "Home" and "About" and the "Home" tab is marked as active. -', - json('[{ - "component": "shell", - "title": "SQLPage: SQL websites", - "icon": "database", - "link": "/", - "menu_item": [ - {"title": "Home", "active": true}, - {"title": "About"} - ] - }]')), - - ('shell', ' -### Sharing the shell between multiple pages - -It is common to want to share the same shell between multiple pages. - -#### Static menu - -If your menu is completely static (it does not depend on the database content), -you can use the [`dynamic`](?component=dynamic#component) component together with the -[`sqlpage.read_file_as_text`](functions.sql?function=read_file_as_text#function) function to load the shell from -a json file. - -```sql -SELECT ''dynamic'' AS component, sqlpage.read_file_as_text(''shell.json'') AS properties; -``` - -and in `shell.json`: - -```json -{ - "component": "shell", - "title": "SQL + JSON = <3", - "link": "/", - "menu_item": [ - {"link": "index.sql", "title": "Home"}, - {"title": "Community", "submenu": [ - {"link": "/blog.sql", "title": "Blog"}, - {"link": "//github.com/sqlpage/SQLPage", "title": "Github"} - ]} - ] -} -``` - -#### Dynamic menu - -If your menu depends on the database content, or on special `sqlpage` functions, -you can use the `dynamic` component, -but this time with the [`sqlpage.run_sql`](functions.sql?function=run_sql#function) -function to generate the menu from the database. - -```sql -SELECT ''dynamic'' AS component, sqlpage.run_sql(''shell.sql'') AS properties; -``` - -and in `shell.sql`: - -```sql -SELECT ''shell'' AS component, ''run_sql is cool'' as title, - json_group_array(json_object( - ''link'', link, - ''title'', title - )) as menu_item -FROM my_menu_items -``` - -(check your database documentation for the exact syntax of the `json_group_array` function). - -Another case when dynamic menus are useful is when you want to show some -menu items only in certain conditions. - -For instance, you could show an "Admin panel" menu item only to users with the "admin" role, -a "Profile" menu item only to authenticated users, -and a "Login" menu item only to unauthenticated users: - -```sql -set role = ( - SELECT role FROM users - INNER JOIN sessions ON users.id = sessions.user_id - WHERE sessions.session_id = sqlpage.cookie(''session_id'') -); -- Read more about how to handle user sessions in the "authentication" component documentation - -SELECT - ''shell'' AS component, - ''My authenticated website'' AS title, - - -- Add an admin panel link if the user is an admin - CASE WHEN $role = ''admin'' THEN ''{"link": "admin.sql", "title": "Admin panel"}'' END AS menu_item, - - -- Add a profile page if the user is authenticated - CASE WHEN $role IS NOT NULL THEN ''{"link": "profile.sql", "title": "My profile"}'' END AS menu_item, - - -- Add a login link if the user is not authenticated - CASE WHEN $role IS NULL THEN ''login'' END AS menu_item -; -``` - -More about how to handle user sessions in the [authentication component documentation](?component=authentication#component). - -### Menu with icons - -The "icon" attribute may be specified for items in the top menu and submenus to display an icon -before the title (or instead). Similarly, the "image" attribute defines a file-based icon. For -image-based icons, the "size" attribute may be specified at the top level of menu_item only to -reduce the size of image-based icons. The following snippet provides an example, which is also -available [here](examples/menu_icon.sql). - -```sql -SELECT - ''shell'' AS component, - ''SQLPage'' AS title, - ''database'' AS icon, - ''/'' AS link, - TRUE AS fixed_top_menu, - ''{"title":"About","icon": "settings","submenu":[{"link":"/safety.sql","title":"Security","icon": "logout"},{"link":"/performance.sql","title":"Performance"}]}'' AS menu_item, - ''{"title":"Examples","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg","submenu":[{"link":"/examples/tabs/","title":"Tabs","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg"},{"link":"/examples/layouts.sql","title":"Layouts"}]}'' AS menu_item, - ''{"title":"Examples","size":"sm","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg","submenu":[{"link":"/examples/tabs/","title":"Tabs","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg"},{"link":"/examples/layouts.sql","title":"Layouts"}]}'' AS menu_item, - ''Official [SQLPage](https://sql-page.com) documentation'' as footer; -``` -', NULL), - ('shell', ' -### Returning custom HTML, XML, plain text, or other formats - -Use `shell-empty` to opt out of SQLPage''s component system and return raw data directly. - -By default, SQLPage wraps all your content in a complete HTML page with navigation and styling. -The `shell-empty` component tells SQLPage to skip this HTML wrapper and return only the raw content you specify. - -Use it to create endpoints that return things like - - XML (for JSON, use the [json](?component=json) component) - - plain text or markdown content (for instance for consumption by LLMs) - - a custom data format you need - -When using `shell-empty`, you should use the [http_header](component.sql?component=http%5Fheader) component first -to set the correct [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) (like `application/json` or `application/xml`). -', - json('[ - { - "component":"http_header", - "Content-Type":"application/xml" - }, - { - "component":"shell-empty", - "contents": "\n \n 42\n john.doe\n " - } - ]') - ), - ('shell',' -### Generate your own HTML -If you generate your own HTML from a SQL query, you can also use the `shell-empty` component to include it in a page. -This is useful when you want to generate a snippet of HTML that can be dynamically included in a larger page. -Make sure you know what you are doing, and be careful to escape the HTML properly, -as you are stepping out of the safe SQLPage framework and into the wild world of HTML. - -In this scenario, you can use the `html` property, which serves as an alias for the `contents` property. -This property improves code readability by clearly indicating that you are generating HTML. -Since SQLPage returns HTML by default, there is no need to specify the content type in the HTTP header. -', - json('[{"component":"shell-empty", "html": "\n\n\n My page\n\n\n

My page

\n\n"}]')); diff --git a/examples/official-site/sqlpage/migrations/02_hero_component.sql b/examples/official-site/sqlpage/migrations/02_hero_component.sql deleted file mode 100644 index bee6a8d90..000000000 --- a/examples/official-site/sqlpage/migrations/02_hero_component.sql +++ /dev/null @@ -1,184 +0,0 @@ --- Hero -INSERT INTO - component(name, icon, description) -VALUES - ( - 'hero', - 'home', - 'Display a large title and description for your page, with an optional large illustrative image. Useful in your home page, for instance.' - ); - -INSERT INTO - parameter( - component, - name, - description, - type, - top_level, - optional - ) -SELECT - 'hero', - * -FROM - ( - VALUES - -- top level - ( - 'title', - 'The title of your page. Will be shown in very large characters at the top.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'description', - 'A description of the page. Displayed below the title, in smaller characters and slightly greyed out.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'description_md', - 'A description of the page. Displayed below the title, in smaller characters and slightly greyed out - formatted using markdown.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'image', - 'The URL of an image to display next to the page title.', - 'URL', - TRUE, - TRUE - ), - ( - 'video', - 'The URL of a video to display next to the page title.', - 'URL', - TRUE, - TRUE - ), - ( - 'link', - 'Creates a large "call to action" button below the description, linking to the specified URL.', - 'URL', - TRUE, - TRUE - ), - ( - 'link_text', - 'The text to display in the call to action button. Defaults to "Go".', - 'TEXT', - TRUE, - TRUE - ), - ( - 'poster', - 'URL of the image to be displayed before the video starts. Ignored if no video is present.', - 'URL', - TRUE, - TRUE - ), - ( - 'nocontrols', - 'Hide the video controls (play, pause, volume, etc.), and autoplay the video.', - 'BOOLEAN', - TRUE, - TRUE - ), - ('muted', 'Mute the video', 'BOOLEAN', TRUE, TRUE), - ('autoplay', 'Automatically start playing the video', 'BOOLEAN', TRUE, TRUE), - ('loop', 'Loop the video', 'BOOLEAN', TRUE, TRUE), - ( - 'reverse', - 'Reverse the order of the image and text: the image will be on the left, and the text on the right. On small screens, the image will be above the text.', - 'BOOLEAN', - TRUE, - TRUE - ), - -- item level - ( - 'title', - 'The name of a single feature section highlighted by this hero.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'description', - 'Description of the feature section.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'description_md', - 'Description of the feature section - formatted using markdown.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'icon', - 'Icon of the feature section.', - 'ICON', - FALSE, - TRUE - ), - ( - 'color', - 'Color of the badge behind the feature section''s icon. Defaults to "success".', - 'COLOR', - FALSE, - TRUE - ), - ( - 'link', - 'An URL to which the user should be taken when they click on the section title.', - 'TEXT', - FALSE, - TRUE - ) - ) x; - -INSERT INTO - example(component, description, properties) -VALUES - ( - 'hero', - 'The simplest possible hero section', - json( - '[{ - "component":"hero", - "title": "Welcome", - "description": "This is a very simple site built with SQLPage." - }]' - ) - ), - ( - 'hero', - 'A hero with a background image.', - json( - '[{ - "component":"hero", - "title": "SQLPage", - "description_md": "Documentation for the *SQLPage* low-code web application framework.", - "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Lac_de_Zoug.jpg/1280px-Lac_de_Zoug.jpg", - "link": "/documentation.sql", - "link_text": "Read Documentation !"},' || '{"title": "Fast", "description": "Pages load instantly, even on slow mobile networks.", "icon": "car", "color": "red", "link": "/"},' || '{"title": "Beautiful", "description": "Uses pre-defined components that look professional.", "icon": "eye", "color": "green", "link": "/"},' || '{"title": "Easy", "description_md": "You can teach yourself enough SQL to use [**SQLPage**](https://sql-page.com) in a weekend.", "icon": "sofa", "color": "blue", "link": "/"}' || ']' - ) - ), - ( - 'hero', - 'A hero with a video', - json( - '[{ - "component":"hero", - "title": "Databases", - "reverse": true, - "description_md": "# “The goal is to turn data into information, and information into insight.”", - "poster": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Lac_de_Zoug.jpg/1280px-Lac_de_Zoug.jpg", - "video": "/sqlpage_introduction_video.mp4" - }]') - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/03_alert_component.sql b/examples/official-site/sqlpage/migrations/03_alert_component.sql deleted file mode 100644 index 7fd2ee908..000000000 --- a/examples/official-site/sqlpage/migrations/03_alert_component.sql +++ /dev/null @@ -1,197 +0,0 @@ --- Alert component -INSERT INTO component(name, icon, description) -VALUES ( - 'alert', - 'alert-triangle', - 'A visually distinctive message or notification.' - ); -INSERT INTO parameter( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'alert', - 'title', - 'Title of the alert message.', - 'TEXT', - TRUE, - FALSE - ), - ( - 'alert', - 'icon', - 'Icon name (from tabler-icons.io) to display next to the alert message.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'color', - 'The color theme for the alert message. The default is `info`.', - 'COLOR', - TRUE, - TRUE - ), - ( - 'alert', - 'description', - 'Detailed description or content of the alert message.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'description_md', - 'Detailed description or content of the alert message, in Markdown format, allowing you to use rich text formatting, including `**bold**` and `*italic*` text.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'dismissible', - 'Whether the user can close the alert message.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'alert', - 'close_label', - 'Accessible name of the close button of a dismissible alert, which screen readers announce. The default is "Close".', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'important', - 'Set this to TRUE to make the alert message more prominent.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'alert', - 'link', - 'A URL to link to from the alert message.', - 'URL', - TRUE, - TRUE - ), - ( - 'alert', - 'link_text', - 'Customize the text of the link in the alert message. The default is "Ok".', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'link', - 'A URL to link to from the alert message.', - 'URL', - FALSE, - TRUE - ), - ( - 'alert', - 'title', - 'Customize the text of the link in the alert message. The default is "Ok".', - 'TEXT', - FALSE, - TRUE - ), - ( - 'alert', - 'color', - 'Customize the color of the link.', - 'COLOR', - FALSE, - TRUE - ); --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'alert', - 'A basic alert message', - JSON( - '[{"component":"alert", "title":"Attention", "description":"This is an important message."}]' - ) - ), - ( - 'alert', - 'A list of notifications', - JSON( - '[ - {"component" :"alert", "title":"Success","description":"Item successfully added to your cart.", "icon":"check", "color": "green"}, - {"component":"alert", "title":"Warning","description":"Your cart is almost full.", "icon":"alert-triangle", "color": "yellow"}, - {"component":"alert", "title":"Error","description":"Your cart is full.", "icon":"alert-circle", "color": "red"} - ]' - ) - ), - ( - 'alert', - 'A full-featured notification message with multiple links', - JSON( - '[ - { - "component" :"alert", - "title": "Your dashboard is ready!", - "icon":"analyze", - "color":"teal", - "dismissible": true, - "description":"Your public web dashboard was successfully created." - }, - { - "link":"dashboard.sql", - "title": "View your dashboard" - }, - { - "link" :"index.sql", - "title": "Back to home", - "color": "secondary" - } - ]' - ) - ), - ( - 'alert', - 'A dismissible alert. `close_label` names the close button for screen readers.', - JSON( - '[ - { - "component":"alert", - "title":"Alert", - "icon":"alert-circle", - "color":"red", - "important": true, - "dismissible": true, - "close_label": "Dismiss this alert", - "description":"SQLPage is entirely free and open source.", - "link":"https://github.com/sqlpage/SQLPage", - "link_text":"See source code" - }]' - ) - ), - ( - 'alert', - 'An alert message with a Markdown-formatted description', - JSON( - '[ - { - "component":"alert", - "title":"Free and open source", - "icon": "free-rights", - "color": "info", - "description_md":"*SQLPage* is entirely free and open source. You can **contribute** to it on [GitHub](https://github.com/sqlpage/SQLPage)." - }]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/04_http_header.sql b/examples/official-site/sqlpage/migrations/04_http_header.sql deleted file mode 100644 index 1667e4260..000000000 --- a/examples/official-site/sqlpage/migrations/04_http_header.sql +++ /dev/null @@ -1,116 +0,0 @@ --- Insert the http_header component into the component table -INSERT INTO component (name, description, icon) -VALUES ( - 'http_header', - ' -An advanced component to set arbitrary HTTP headers: can be used to set a custom caching policy to your pages, or implement custom redirections, for example. -If you are a beginner, you probably don''t need this component. - -When used, this component has to be the first component in the page, because once the page is sent to the browser, it is too late to change the headers. - -HTTP headers are additional pieces of information sent with responses to web requests that provide instructions -or metadata about the data being sent — for example, -setting cache control directives to control caching behavior -or specifying the content type of a response. - -Any valid HTTP header name can be used as a top-level parameter for this component. -The examples shown here are just that, examples; and you can create any custom header -if needed simply by declaring it. - -If your header''s name contains a dash or any other special character, -you will have to use your database''s quoting mechanism to declare it. -In standard SQL, you can use double quotes to quote identifiers (like "X-My-Header"), -in Microsoft SQL Server, you can use square brackets (like [X-My-Header]). - ', - 'world-www' - ); --- Insert the parameters for the http_header component into the parameter table -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'http_header', - 'Cache-Control', - 'Directives for how long the page should be cached by the browser. Set this to max-age=N to keep the page in cache for N seconds.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'http_header', - 'Content-Disposition', - 'Provides instructions on how the response content should be displayed or handled by the client, such as inline or as an attachment.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'http_header', - 'Location', - 'Specifies the URL to redirect the client to, usually used in 3xx redirection responses.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'http_header', - 'Set-Cookie', - 'Sets a cookie in the client browser, used for session management and storing user-related information.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'http_header', - 'Access-Control-Allow-Origin', - 'Specifies which origins are allowed to access the resource in a cross-origin request, used for implementing Cross-Origin Resource Sharing (CORS).', - 'TEXT', - TRUE, - TRUE - ); - --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description, properties) -VALUES ( - 'http_header', - 'Set cache control directives for caching behavior. In this example, the response can be cached by the browser - and served from the cache for up to 600 seconds (10 minutes) after it is first requested. - During that time, even if the cached response becomes stale (outdated), the browser can still use it (stale-while-revalidate) - for up to 3600 seconds (1 hour) while it retrieves a fresh copy from the server in the background. - If there is an error while trying to retrieve a fresh copy from the server, - the browser can continue to serve the stale response for up to 86400 seconds (24 hours) (stale-if-error) instead of showing an error page. - This caching behavior helps improve the performance and responsiveness of the website by reducing the number of requests made to the server - and allowing the browser to serve content from its cache when appropriate.', - JSON( - '[{ - "component": "http_header", - "Cache-Control": "public, max-age=600, stale-while-revalidate=3600, stale-if-error=86400" - }]' - ) - ), - ( - 'http_header', - 'Redirect the user to another page. In this example, the user is redirected to a file named another-page.sql at the root of the website. The current page will not be displayed at all. - This is useful in particular for content creation pages that contain only INSERT statements, because you can redirect the user to the page that lists the content after it has been created.', - JSON( - '[{ - "component": "http_header", - "Location": "/another-page.sql" - }]' - ) - ), - ( - 'http_header', - 'Set a custom non-standard header for the response. In this example, the response will include a custom header named X-My-Header with the value "my value".', - JSON( - '[{ - "component": "http_header", - "X-My-Header": "my value" - }]' - ) - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/05_cookie.sql b/examples/official-site/sqlpage/migrations/05_cookie.sql deleted file mode 100644 index 8e2f2db4f..000000000 --- a/examples/official-site/sqlpage/migrations/05_cookie.sql +++ /dev/null @@ -1,125 +0,0 @@ --- Insert the http_header component into the component table -INSERT INTO component (name, description, icon) -VALUES ( - 'cookie', - ' -Sets a cookie in the client browser, used for session management and storing user-related information. - -This component creates a single cookie. Since cookies need to be set before the response body is sent to the client, -this component should be **placed at the top of the page**, before any other components that generate output. - -After being set, a cookie can be accessed anywhere in your SQL code using the `sqlpage.cookie(''cookie_name'')` pseudo-function. - -Note that if your site is accessed over HTTP (and not HTTPS), you have to set `false as secure` to force browsers to accept your cookies.', - 'cookie' - ); --- Insert the parameters for the http_header component into the parameter table -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'cookie', - 'name', - 'The name of the cookie to set.', - 'TEXT', - TRUE, - FALSE - ), - ( - 'cookie', - 'value', - 'The value of the cookie to set.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'cookie', - 'path', - 'The path for which the cookie will be sent. If not specified, the cookie will be sent for all paths.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'cookie', - 'domain', - 'The domain for which the cookie will be sent. If not specified, the cookie will be sent for all domains.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'cookie', - 'secure', - 'Whether the cookie should only be sent over a secure (HTTPS) connection. Defaults to TRUE.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'cookie', - 'http_only', - 'Whether the cookie should only be accessible via HTTP and not via client-side scripts. If explicitly set to false, the cookie will be accessible via both HTTP and client-side scripts.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'cookie', - 'remove', - 'Set to TRUE to remove the cookie from the client browser. When specified, other parameters are ignored.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'cookie', - 'max_age', - 'The maximum age of the cookie in seconds. number of seconds until the cookie expires. If both Expires and Max-Age are set, Max-Age has precedence.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'cookie', - 'expires', - 'The date at which the cookie expires (either a timestamp or a date object). If not specified, the cookie will expire when the browser is closed.', - 'TIMESTAMP', - TRUE, - TRUE - ), - ( - 'cookie', - 'same_site', - 'Whether the cookie should only be sent for requests originating from the same site. See owasp.org/www-community/SameSite. `strict` is the recommended and default value, but you may want to set it to `lax` if you want your users to keep their session when they click on a link to your site from an external site.', - 'TEXT', - TRUE, - TRUE - ); --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description) -VALUES ( - 'cookie', - '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/sqlpage/migrations/06_debug.sql b/examples/official-site/sqlpage/migrations/06_debug.sql deleted file mode 100644 index 7df4263b5..000000000 --- a/examples/official-site/sqlpage/migrations/06_debug.sql +++ /dev/null @@ -1,25 +0,0 @@ --- Insert the http_header component into the component table -INSERT INTO component (name, description, icon) -VALUES ( - 'debug', - 'Visualize any set of values as JSON. -Can be used to display all the parameters passed to the component. -Useful for debugging: just replace the name of the component you want to debug with ''debug'', and see all the top-level and row-level parameters that are passed to it, and their types.', - 'bug' - ); --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description, properties) -VALUES ( - 'debug', - 'At any time, if you are confused about what data you are passing to a component, just replace the component name with ''debug'' to see all the parameters that are passed to it.', - JSON('[{"component": "debug", "my_top_level_property": true}, {"x": "y", "z": 42}, {"a": "b", "c": null}]') - ), - ( - 'debug', - 'Show the result of a SQLPage function: - -```sql -select ''debug'' as component, sqlpage.environment_variable(''HOME''); -```', - NULL - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/07_authentication.sql b/examples/official-site/sqlpage/migrations/07_authentication.sql deleted file mode 100644 index 766428763..000000000 --- a/examples/official-site/sqlpage/migrations/07_authentication.sql +++ /dev/null @@ -1,182 +0,0 @@ --- Insert the http_header component into the component table -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'authentication', - ' -Create pages with password-restricted access. - - -When you want to add user authentication to your SQLPage application, -you have two main options: - -1. The `authentication` component: - - lets you manage usernames and passwords yourself - - does not require any external service - - gives you fine-grained control over - - which pages and actions are protected - - the look of the [login form](?component=login) - - the duration of the session - - the permissions of each user -2. [**Single sign-on**](/sso) - - lets users log in with their existing accounts (like Google, Microsoft, or your organization''s own identity provider) - - requires setting up an external service (Google, Microsoft, etc.) - - frees you from implementing a lot of features like password reset, account creation, user management, etc. - -This page describes the first option. - -When used, this component has to be at the top of your page, -because once the page has begun being sent to the browser, -it is too late to restrict access to it. - -The authentication component checks if the user has sent the correct password, -and if not, redirects them to the URL specified in the link parameter. - -If you don''t want to re-check the password on every page (which is an expensive operation), -you can check the password only once and store a session token in your database -(see the session example below). - -You can use the [cookie component](?component=cookie) to set the session token cookie in the client browser, -and then check whether the token matches what you stored in subsequent pages.', - 'lock', - '0.7.2' - ); --- Insert the parameters for the http_header component into the parameter table -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'authentication', - 'link', - 'The URL to redirect the user to if they are not logged in. If this parameter is not specified, the user will stay on the current page, but be asked to log in using a popup in their browser (HTTP basic authentication).', - 'TEXT', - TRUE, - TRUE - ), - ( - 'authentication', - 'password', - 'The password that was sent by the user. You can set this to :password if you have a login form leading to your page.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'authentication', - 'password_hash', - 'The hash of the password that you stored for the user that is currently trying to log in. These hashes can be generated ahead of time using a tool like https://argon2.online/.', - 'TEXT', - TRUE, - TRUE - ); - --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description) -VALUES ( - 'authentication', - ' - -### Usage with HTTP basic authentication - -The most basic usage of the authentication component is with the -[`sqlpage.basic_auth_username()`](functions.sql?function=basic_auth_username#function) and -[`sqlpage.basic_auth_password()`](functions.sql?function=basic_auth_password#function) functions. -The component will check if the provided password matches the stored [password hash](/examples/hash_password.sql), -and if not, it will prompt the user to enter a password in a browser popup: - -```sql -SELECT ''authentication'' AS component, - ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w'' AS password_hash, -- this is a hash of the password ''password'' - sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup -``` - -You can [generate a password hash using the `hash_password` function](/examples/hash_password.sql). - -If you want to have multiple users with different passwords, -you could store them with their password hashes in the database, -or just hardcode them use a `CASE` statement: - -```sql -SELECT ''authentication'' AS component, - case sqlpage.basic_auth_username() - when ''admin'' - then ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w'' -- the password is ''password'' - when ''user'' - then ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$qsrWdjgl96ooYw'' -- the password is ''user'' - end AS password_hash, -- this is a hash of the password ''password'' - sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup -``` - -Try this example online: [SQL Basic Auth](/examples/authentication/basic_auth.sql). - -### Advanced user session management - -*Basic auth* is the simplest way to password-protect a page, -but it is not very flexible nor user-friendly, -because the browser will show an unstyled popup asking for the username and password. - -For more advanced authentication, you can store user information and user sessions in your database. -You can then use the [`form`](/component.sql?component=form#component) component to create a custom login form. -When the user submits the form, you check if the password is correct using the `authentication` component. -You then store a unique string of numbers and letters (a session token) both in the user''s browser -using the [`cookie`](/component.sql?component=cookie#component) component and in your database. -Then, in all the pages that require authentication, you check if the cookie is present and matches the session token in your database. - -You can check if the user has sent the correct password in a form, and if not, redirect them to a login page. - -Create a login form in a file called `login.sql` that uses the [login component](?component=login): - -```sql -select ''login'' as component, ''create_session_token.sql'' as action; -``` - -And then, in `create_session_token.sql` : - -```sql -SELECT ''authentication'' AS component, - ''login.sql'' AS link, - ''$argon2id$v=19$m=16,t=2,p=1$TERTd0lIcUpraWFTcmRQYw$+bjtag7Xjb6p1dsuYOkngw'' AS password_hash, -- generated using sqlpage.hash_password - :password AS password; -- this is the password that the user sent through our form - --- The code after this point is only executed if the user has sent the correct password - -``` - -### Advanced: usage with a session token - -Calling the `authentication` component is expensive. -The password hashing algorithm is designed to be slow, so that it is difficult to brute-force the password, -even if an attacker gets access to the database. - -If you want to avoid calling the `authentication` component on every page, you can use a session token. -A session token is a random string that is generated when the user logs in, and stored in the database. -It has a limited lifetime, and is stored in a cookie in the user''s browser. -When the user visits a page, the session token is sent to the server, and the server checks if it is valid. - -```sql -SELECT ''authentication'' AS component, - ''login.sql'' AS link, - (SELECT password_hash FROM user WHERE username = :username) AS password_hash, - :password AS password; - --- The code after this point is only executed if the user has sent the correct password - --- Generate a random session token -INSERT INTO session (id, username) -VALUES (sqlpage.random_string(32), :username) -RETURNING - ''cookie'' AS component, - ''session_token'' AS name, - id AS value; -``` - -### Single sign-on with OIDC (OpenID Connect) - -If you don''t want to manage your own user database, -you can [use OpenID Connect and OAuth2](/sso) to authenticate users. -This allows users to log in with their Google, Microsoft, or internal company account. -'); diff --git a/examples/official-site/sqlpage/migrations/09_redirect.sql b/examples/official-site/sqlpage/migrations/09_redirect.sql deleted file mode 100644 index eb6942125..000000000 --- a/examples/official-site/sqlpage/migrations/09_redirect.sql +++ /dev/null @@ -1,69 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'redirect', - 'Redirects the user to another page. - -This component helps you: -1. Send users to a different page -1. Stop execution of the current page - -### Conditional logic - -There is no `IF` statement in SQL. Even when you use a [`CASE` expression](https://modern-sql.com/caniuse/case_(simple)), all branches are always evaluated (and only one is returned). - -To conditionally execute a component or a [SQLPage function](/functions.sql), you can use the `redirect` component. -A common use case is error handling. You may want to proceed with the rest of a page only when certain pre-conditions are met. - -```sql -SELECT - ''redirect'' AS component, - ''error_page.sql'' AS link -WHERE NOT your_condition; - --- The rest of the page is only executed if the condition is true -``` -### Technical limitation - -You must use this component **at the beginning of your SQL file**, before any other components that might send content to the browser. -Since the component needs to tell the browser to go to a different page by sending an *HTTP header*, -it will fail if the HTTP headers have already been sent by the time it is executed. - -> **Important difference from [http_header](?component=http_header)** -> -> This component completely stops the page from running after it''s called. -> This makes it a good choice for protecting sensitive information from unauthorized users. - -', - 'arrow-right', - '0.7.2' - ); --- Insert the parameters for the http_header component into the parameter table -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'redirect', - 'link', - 'The URL to redirect the user to.', - 'TEXT', - TRUE, - FALSE - ); --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description) -VALUES ( - 'redirect', - ' -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'')); -``` -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/10_map.sql b/examples/official-site/sqlpage/migrations/10_map.sql deleted file mode 100644 index 33a6bbe4b..000000000 --- a/examples/official-site/sqlpage/migrations/10_map.sql +++ /dev/null @@ -1,266 +0,0 @@ -INSERT INTO - component (name, description, icon, introduced_in_version) -VALUES - ( - 'map', - ' - -## Visualize SQL data on a map. - -The map component displays a custom interactive map with markers on it. - -In its simplest form, the component displays points on a map from a table of latitudes and longitudes. -But it can also be used by cartographers in combination with PostgreSQL''s PostGIS or SQLite''s spatialite, -to create custom visualizations of geospatial data. -Use the `geojson` property to generate rich maps from a GIS database. - -### Example Use Cases - -1. **Store Locator**: Build an interactive map to find the nearest store information using SQL-stored geospatial data. -2. **Delivery Route Optimization**: Visualize the results of delivery route optimization algorithms. -3. **Sales Heatmap**: Identify high-performing regions by mapping sales data stored in SQL. -4. **Real-Time Tracking**: Create dynamic dashboards that track vehicles, assets, or users live using PostGIS or MS SQL Server geospatial time series data. Use the [shell](?component=shell) component to auto-refresh the map. -5. **Demographic Insights**: Map customer demographics or trends geographically to uncover opportunities for growth or better decision-making. -', - 'map', - '0.8.0' - ); - --- Insert the parameters for the http_header component into the parameter table -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'map', - 'title', - 'A text header displayed above the map.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'map', - 'latitude', - 'Latitude of the center of the map. If omitted, the map will be centered on its markers.', - 'REAL', - TRUE, - TRUE - ), - ( - 'map', - 'longitude', - 'Longitude of the center of the map.', - 'REAL', - TRUE, - TRUE - ), - ( - 'map', - 'zoom', - 'Zoom Level to apply to the map. Defaults to 5.', - 'REAL', - TRUE, - TRUE - ), - ( - 'map', - 'max_zoom', - 'How far the map can be zoomed in. Defaults to 18. Added in v0.15.2.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'map', - 'tile_source', - 'Custom map tile images to use, as a URL. Defaults to "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png". Added in v0.15.2.', - 'URL', - TRUE, - TRUE - ), - ( - 'map', - 'attribution', - 'Text to display at the bottom right of the map. Defaults to "© OpenStreetMap".', - 'HTML', - TRUE, - TRUE - ), - ( - 'map', - 'height', - 'Height of the map, in pixels. Default to 350px', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'map', - 'latitude', - 'Latitude of the marker. Required only if geojson is not set.', - 'REAL', - FALSE, - FALSE - ), - ( - 'map', - 'longitude', - 'Longitude of the marker. Required only if geojson is not set.', - 'REAL', - FALSE, - FALSE - ), - ( - 'map', - 'title', - 'Title of the marker, displayed on hover and in the tooltip when the marker is clicked.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'map', - 'link', - 'A link to associate to the marker''s title. If set, the marker tooltip''s title will be clickable and will open the link.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'map', - 'description', - 'Plain text description of the marker, to be displayed in a tooltip when the marker is clicked.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'map', - 'description_md', - 'Description of the marker, in markdown, rendered in a tooltip when the marker is clicked.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'map', - 'icon', - 'Name of the icon to use for the marker', - 'ICON', - FALSE, - TRUE - ), - ( - 'map', - 'color', - 'Background color of the marker on the map. Requires "icon" to be set.', - 'COLOR', - FALSE, - TRUE - ), - ( - 'map', - 'geojson', - 'A GeoJSON geometry (line, polygon, ...) to display on the map. Can be styled using geojson properties using the name of leaflet path options. Introduced in 0.15.1. Accepts raw strings in addition to JSON objects since 0.15.2.', - 'JSON', - FALSE, - TRUE - ), - ( - 'map', - 'size', - 'Size of the marker icon. Requires "icon" to be set. Introduced in 0.15.2.', - 'INTEGER', - FALSE, - TRUE - ); - --- Insert an example usage of the map component into the example table -INSERT INTO - example (component, description, properties) -VALUES - ( - 'map', - ' -### Adding a marker to a map - -Showing how to place a marker on a map. Useful for basic location displays like showing a single office location, event venue, or point of interest. The marker shows basic hover and click interactions. -', - JSON ( - '[{ "component": "map" }, { "title": "New Delhi", "latitude": 28.6139, "longitude": 77.2090 }]' - ) - ), - ( - 'map', - ' -### Advanced map customization using GeoJSON and custom map tiles - -This example demonstrates using topographic map tiles, custom marker styling, -and clickable markers that link to external content - perfect for educational or tourism applications. - -The [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) feature here is a single point. Its coordinates are `[longitude, latitude]`; the top-level `latitude` and `longitude` set the map''s initial center. - - - You can generate GeoJSON data from PostGIS geometries using the [`ST_AsGeoJSON`](https://postgis.net/docs/ST_AsGeoJSON.html) function. - - In spatialite, you can use the [`AsGeoJSON`](https://www.gaia-gis.it/gaia-sins/spatialite-sql-5.1.0.html#p3misc) function. - - In MySQL, you can use the [`ST_AsGeoJSON()`](https://dev.mysql.com/doc/refman/8.0/en/spatial-geojson-functions.html#function_st-asgeojson) function. -', - JSON ( - '[{ "component": "map", "zoom": 5, "max_zoom": 8, "height": 600, "latitude": -25, "longitude": 28, "tile_source": "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", "attribution": "" }, - { "icon": "peace", - "size": 20, - "link": "https://en.wikipedia.org/wiki/Nelson_Mandela", - "geojson": "{\"type\":\"Feature\", \"properties\": { \"title\":\"Mvezo, Birth Place of Nelson Mandela\" }, \"geometry\": { \"type\":\"Point\", \"coordinates\": [28.49, -31.96] }}"}, - {"component": "text", "contents_md": "Map data: [© OpenStreetMap contributors](https://www.openstreetmap.org/copyright), SRTM. Map style: [© OpenTopoMap](https://opentopomap.org/) ([CC BY-SA](https://creativecommons.org/licenses/by-sa/3.0/))."}]' - ) - ), - ( - 'map', - ' -### Maps with links and rich descriptions - -Demonstrates how to create an engaging map with custom icons, colors, rich descriptions with markdown support, and connecting points with lines. -Perfect for visualizing multi-dimensional relationships between points on a map, like routes between locations. - -Note that the map tile source is set to a MapTiler map. The API key included in the URL in this demo will not work on your own website. -You should get your own API key at [MapTiler](https://www.maptiler.com/cloud/). -', - JSON ( - '[ - { "component": "map", "title": "Paris", "zoom": 13, "latitude": 48.85, "longitude": 2.34, "tile_source": "https://api.maptiler.com/maps/streets-v2/{z}/{x}/{y}.png?key=RwoF6Y3gcKx4OBMbvqOY" }, - { "title": "Notre Dame", "icon": "building-castle", "color": "indigo", "latitude": 48.8530, "longitude": 2.3498, "description_md": "A beautiful cathedral.", "link": "https://en.wikipedia.org/wiki/Notre-Dame_de_Paris" }, - { "title": "Eiffel Tower", "icon": "tower", "color": "red", "latitude": 48.8584, "longitude": 2.2945, "description_md": "A tall tower. [Wikipedia](https://en.wikipedia.org/wiki/Eiffel_Tower)" }, - { "title": "Tower to Cathedral", "geojson": {"type": "LineString", "coordinates": [[2.2945, 48.8584], [2.3498, 48.8530]]}, "color": "teal", "description": "A nice 45 minutes walk." } - ]' - ) - ), - ( - 'map', - ' -### Abstract geometric visualizations - -Example showing how to create abstract geometric visualizations without a base map. -Useful for displaying spatial data that doesn''t need geographic context, like floor plans, seating charts, -or abstract 2D data visualizations. -', - JSON ( - '[ - { "component": "map", "tile_source": false }, - { "title": "MySQL", - "color": "red", "description": "This literal red square is defined as a GeoJSON polygon. Each (x,y) coordinate is a JSON array.", - "geojson": {"type": "Polygon", "coordinates": [[[0, 0], [0, 4], [4, 4], [4, 0], [0, 0]]]} - }, - { - "title": "SQLite", - "color": "blue", "description": "This 2D shape was generated by a SQL query.", - "geojson": {"type": "Polygon", "coordinates": [[[5, 0], [9, 0], [7, 4], [5, 0]]]} - } - ]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/11_json.sql b/examples/official-site/sqlpage/migrations/11_json.sql deleted file mode 100644 index 5c6010819..000000000 --- a/examples/official-site/sqlpage/migrations/11_json.sql +++ /dev/null @@ -1,211 +0,0 @@ -INSERT INTO - component (name, description, icon, introduced_in_version) -VALUES - ( - 'json', - 'Converts SQL query results into the JSON machine-readable data format. Ideal to quickly build APIs for interfacing with external systems. - -**JSON** is a widely used data format for programmatic data exchange. -For example, you can use it to integrate with web services written in different languages, -with mobile or desktop apps, or with [custom client-side components](/custom_components.sql) inside your SQLPage app. - -Use it when your application needs to expose data to external systems. -If you only need to render standard web pages, -and do not need other software to access your data, -you can ignore this component. - -This component **must appear at the top of your SQL file**, before any other data has been sent to the browser. -An HTTP response can have only a single datatype, and it must be declared in the headers. -So if you have already called the `shell` component, or another traditional HTML component, -you cannot use this component in the same file. - -SQLPage can also return JSON or JSON Lines when the incoming request says it prefers them with an HTTP `Accept` header, so the same `/users.sql` page can show a table in a browser but return raw data to `curl -H "Accept: application/json" http://localhost:8080/users.sql`. - -Use this component when you want to control the payload or force JSON output even for requests that would normally get HTML. -', - 'code', - '0.9.0' - ); - --- Insert the parameters for the http_header component into the parameter table -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'json', - 'contents', - 'A single JSON payload to send. You can use your database''s built-in json functions to build the value to enter here. If not provided, the contents will be taken from the next SQL statements and rendered as a JSON array.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'json', - 'type', - 'The type of the JSON payload to send: "array", "jsonlines", or "sse". -In "array" mode, each query result is rendered as a JSON object in a single top-level array. -In "jsonlines" mode, results are rendered as JSON objects in separate lines, without a top-level array. -In "sse" mode, results are rendered as JSON objects in separate lines, prefixed by "data: ", which allows you to read the results as server-sent events in real-time from javascript.', - 'TEXT', - TRUE, - TRUE - ); - --- Insert an example usage of the http_header component into the example table -INSERT INTO - example (component, description) -VALUES - ( - 'json', - ' -## Send query results as a single JSON array: `''array'' as type` - -The default `array` mode sends the query results as a single JSON array. - -If a query returns an error, the array will contain an object with an `error` property. - -If multiple queries are executed, all query results will be concatenated into a single array -of heterogeneous objects. - -### SQL - -```sql -select ''json'' AS component; -select * from users; -``` - -### Result - -```json -[ - {"username":"James","userid":1}, - {"username":"John","userid":2} -] -``` - -Clients can also receive JSON or JSON Lines automatically by requesting the same SQL file with an HTTP `Accept` header such as `application/json` or `application/x-ndjson` when the component is omitted, for example: - -``` -curl -H "Accept: application/json" http://localhost:8080/users.sql -``` - ' - ), - ( - 'json', - ' -## Send one JSON object per row: `''jsonlines'' as type` - -In `jsonlines` mode, each query result is rendered as a JSON object in a separate line, -without a top-level array. - -If there 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 } -``` -' - ), - ( - 'json', - ' -## Create a complex API endpoint: the `''contents''` property - -You can create an API endpoint that will return a JSON value in any format you want, -to implement a complex API. - -You should use [the json functions provided by your database](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) to form the value you pass to the `contents` property. -To build a json array out of rows from the database, you can use: - - `json_group_array()` in SQLite, - - `json_agg()` in Postgres, or - - `JSON_ARRAYAGG()` in MySQL. - - `FOR JSON PATH` in SQL Server. - - -```sql -SELECT ''json'' AS component, - JSON_OBJECT( - ''users'', ( - SELECT JSON_GROUP_ARRAY( - JSON_OBJECT( - ''username'', username, - ''userid'', id - ) - ) FROM users - ) - ) AS contents; -``` - -This will return a JSON response that looks like this: - -```json -{ - "users" : [ - { "username":"James", "userid":1 } - ] -} -``` - -If you want to handle custom API routes, like `POST /api/users/:id`, -you can use - - the [`404.sql` file](/your-first-sql-website/custom_urls.sql) to handle the request despite the URL not matching any file, - - the [`request_method` function](/functions.sql?function=request_method#function) to differentiate between GET and POST requests, - - and the [`path` function](/functions.sql?function=path#function) to extract the `:id` parameter from the URL. -' - ), - ( - 'json', - ' -## Access query results in real-time with server-sent events: `''sse'' as type` - -Using server-sent events, you can stream large query results to the client in real-time, -row by row. - -This allows building sophisticated dynamic web applications that will start processing and displaying -the first rows of data in the browser while the database server is still processing the end of the query. - -### SQL - -```sql -select ''json'' AS component, ''sse'' AS type; -select * from users; -``` - -### JavaScript - -```javascript -const eventSource = new EventSource("users.sql"); -eventSource.onmessage = function (event) { - const user = JSON.parse(event.data); - console.log(user.username); -} -eventSource.onerror = () => eventSource.close(); // do not reconnect after reading all the data -``` -' - ); diff --git a/examples/official-site/sqlpage/migrations/13_tab.sql b/examples/official-site/sqlpage/migrations/13_tab.sql deleted file mode 100644 index 1fd5ad472..000000000 --- a/examples/official-site/sqlpage/migrations/13_tab.sql +++ /dev/null @@ -1,130 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'tab', - 'Build a tabbed interface, with each tab being a link to a page. Each tab can be in two states: active or inactive.', - 'row-insert-bottom', - '0.9.5' - ); -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'tab', - 'title', - 'Text to display on the tab. If link is not set, the link will be the current page with a ''$tab'' parameter set to the tab''s title. If ''id'' is set, the page will be scrolled to the tab.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'tab', - 'link', - 'Link to the page to display when the tab is clicked. By default, the link refers to the current page, with a ''tab'' parameter set to the tab''s title and hash set to the id (if passed) - this brings us back to the location of the tab after submission.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tab', - 'active', - 'Whether the tab is active or not. Defaults to false.', - 'BOOLEAN', - FALSE, - TRUE - ), - ( - 'tab', - 'icon', - 'Name of the icon to display on the tab. See tabler-icons.io for a list of available icons.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tab', - 'color', - 'Color of the tab''s text, and of its underline when it is active. See preview.tabler.io/colors.html for a list of available colors.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tab', - 'description', - 'Description of the tab. This is displayed when the user hovers over the tab.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tab', - 'center', - 'Whether the tabs should be centered or not. Defaults to false.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'tab', - 'center', - 'Whether this individual tab''s label should be centered inside the tab. Defaults to false.', - 'BOOLEAN', - FALSE, - TRUE - ) - ; - -INSERT INTO example (component, description, properties) -VALUES ( - 'tab', - 'This example shows a very basic set of three tabs. The first tab is active. You could use this at the top of a page for easy navigation. - -To implement contents that change based on the active tab, use the `tab` parameter in the page query string. -For example, if the page is `/my-page.sql`, then the first tab will have a link of `/my-page.sql?tab=My+First+tab`. - -You could then for instance display contents coming from the database based on the value of the `tab` parameter. -For instance: `SELECT ''text'' AS component, contents_md FROM my_page_contents WHERE tab = $tab`. -Or you could write different queries for different tabs and use the `$tab` parameter with a static value in a where clause to switch between tabs: - -```sql -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; - -select ''table'' as component; - -select * from my_projects where $tab = ''Projects''; -select * from my_tasks where $tab = ''Tasks''; -``` - -Note that the example below is completely static, and does not use the `tab` parameter to actually switch between tabs. -The query above defaults to Projects on the first visit; the links then select either `?tab=Projects` or `?tab=Tasks`. -', - JSON( - '[ - { "component": "tab" }, - { "title": "This tab does not exist", "active": true, "link": "?component=tab&tab=tab_1" }, - { "title": "I am not a true tab", "link": "?component=tab&tab=tab_2" }, - { "title": "Do not click here", "link": "?component=tab&tab=tab_3" } - ]' - ) - ), - ( - 'tab', - 'This example shows a more sophisticated set of tabs. The tabs are centered, the active tab has a different color, and all the tabs have a custom link and icon.', - JSON( - '[ - { "component": "tab", "center": true }, - { "title": "Hero", "link": "?component=hero#component", "icon": "home", "description": "The hero component is a full-width banner with a title and an image." }, - { "title": "Tab", "link": "?component=tab#component", "icon": "user", "color": "purple" }, - { "title": "Card", "link": "?component=card#component", "icon": "credit-card" } - ]' - ) - ) - ; diff --git a/examples/official-site/sqlpage/migrations/16_timeline.sql b/examples/official-site/sqlpage/migrations/16_timeline.sql deleted file mode 100644 index 78f19ba5f..000000000 --- a/examples/official-site/sqlpage/migrations/16_timeline.sql +++ /dev/null @@ -1,103 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'timeline', - 'A list of events with a vertical line connecting them.', - 'git-commit', - '0.13.0' - ); -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'timeline', - 'simple', - 'If set to true, the timeline will be displayed in a condensed format without icons.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'timeline', - 'title', - 'Name of the event.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'timeline', - 'date', - 'Date of the event.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'timeline', - 'icon', - 'Name of the icon to display next to the event. See tabler-icons.io for a list of available icons.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'timeline', - 'color', - 'Color of the icon. See preview.tabler.io/colors.html for a list of available colors.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'timeline', - 'description', - 'Textual description of the event.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'timeline', - 'description_md', - 'Description of the event in Markdown.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'timeline', - 'link', - 'Link to a page with more information about the event.', - 'TEXT', - FALSE, - TRUE - ); -INSERT INTO example (component, description, properties) -VALUES ( - 'timeline', - 'A basic timeline with just names and dates.', - JSON( - '[ - { "component": "timeline", "simple": true }, - { "title": "New message from Elon Musk", "date": "13:00" }, - { "title": "Jeff Bezos assigned task \"work more\" to you.", "date": "yesterday, 16:35" } - ]' - ) - ), - ( - 'timeline', - 'A full-fledged timeline with icons, colors, and rich text descriptions.', - JSON( - '[ - { "component": "timeline" }, - { "title": "v0.13.0 was just released !", "link": "https://github.com/sqlpage/SQLPage/releases/", "date": "2023-10-16", "icon": "brand-github", "color": "green", "description_md": "This version introduces the `timeline` component." }, - { "title": "They are talking about us...", "description_md": "[This article](https://www.postgresql.org/about/news/announcing-sqlpage-build-dynamic-web-applications-in-sql-2672/) on the official PostgreSQL website mentions SQLPage.", "date": "2023-07-12", "icon": "database", "color": "blue" } - ]' - ) - ) - ; \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/18_button.sql b/examples/official-site/sqlpage/migrations/18_button.sql deleted file mode 100644 index 4cfd80e88..000000000 --- a/examples/official-site/sqlpage/migrations/18_button.sql +++ /dev/null @@ -1,122 +0,0 @@ --- Button Component Documentation - --- Component Definition -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('button', 'hand-click', 'Displays one or more buttons that follow links, download files, or submit a form.', '0.14.0'); - --- Inserting parameter information for the button component -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'button', * FROM (VALUES - -- Top-level parameters (for the whole button list) - ('justify', 'The horizontal alignment of the button list (e.g., start, end, center, between).', 'TEXT', TRUE, TRUE), - ('size', 'The size of the buttons (e.g., sm, lg).', 'TEXT', TRUE, TRUE), - ('shape', 'Shape of the buttons (e.g., pill, square)', 'TEXT', TRUE, TRUE), - -- Item-level parameters (for each button) - ('link', 'The URL to which the button should navigate when clicked. If the form attribute is specified, then this overrides the page to which the form is submitted.', 'URL', FALSE, TRUE), - ('color', 'The color of the button (e.g., red, green, blue, but also primary, warning, danger, etc.). Only base color names are supported, not variations like "blue-lt" or "gray-300". Use a custom CSS stylesheet to further customize the colors.', 'COLOR', FALSE, TRUE), - ('title', 'The text displayed on the button.', 'TEXT', FALSE, TRUE), - ('tooltip', 'Text displayed when the user hovers over the button.', 'TEXT', FALSE, TRUE), - ('disabled', 'Whether the button is disabled or not.', 'BOOLEAN', FALSE, TRUE), - ('outline', 'Outline color of the button (e.g. red, purple, ...)', 'COLOR', FALSE, TRUE), - ('space_after', 'Whether there should be extra space to the right of the button. In a line of buttons, this will put the buttons before this one on the left, and the ones after on the right.', 'BOOLEAN', FALSE, TRUE), - ('icon_after', 'Name of an icon to display after the text in the button', 'ICON', FALSE, TRUE), - ('icon', 'Name of an icon to be displayed on the left side of the button.', 'ICON', FALSE, TRUE), - ('image', 'Path to image file (relative. relative to web root or URL) to be displayed on the button.', 'TEXT', FALSE, TRUE), - ('narrow', 'Whether to trim horizontal padding.', 'BOOLEAN', FALSE, TRUE), - ('form', 'Identifier (id) of the form to which the button should submit.', 'TEXT', FALSE, TRUE), - ('rel', '"nofollow" when the contents of the target link are not endorsed, "noopener" when the target is not trusted, and "noreferrer" to hide where the user came from when they open the link.', 'TEXT', FALSE, TRUE), - ('target', '"_blank" to open the link in a new tab, "_self" to open it in the same tab, "_parent" to open it in the parent frame, or "_top" to open it in the full body of the window.', 'TEXT', FALSE, TRUE), - ('download', 'If defined, the link will download the target instead of navigating to it. Set the value to the desired name of the downloaded file.', 'TEXT', FALSE, TRUE), - ('id', 'HTML Identifier to add to the button element.', 'TEXT', FALSE, TRUE) -) x; - --- Inserting example information for the button component -INSERT INTO example(component, description, properties) VALUES - ('button', 'A basic button with a link', - json('[{"component":"button"}, {"link":"/documentation.sql", "title":"Enabled"}, {"link":"#", "title":"Disabled", "disabled":true}]')) -; - - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A button with a custom shape, size, and outline color', - json('[{"component":"button", "size":"sm", "shape":"pill" }, - {"title":"Purple", "outline":"purple" }, - {"title":"Orange", "outline":"orange" }, - {"title":"Red", "outline":"red" }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A list of buttons aligned in the center', - json('[{"component":"button", "justify":"center"}, - {"link":"#", "color":"light", "title":"Light"}, - {"link":"#", "color":"success", "title":"Success"}, - {"link":"#", "color":"info", "title":"Info"}, - {"link":"#", "color":"dark", "title":"Dark"}, - {"link":"#", "color":"warning", "title":"Warning"}, - {"link":"#", "color":"danger", "title":"Narrow"}]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'Icon buttons using the narrow property', - json('[{"component":"button"}, - {"link":"#", "narrow":true, "icon":"edit", "color":"primary", "tooltip":"Edit" }, - {"link":"#", "narrow":true, "icon":"trash", "color":"danger", "tooltip":"Delete" }, - {"link":"#", "narrow":true, "icon":"corner-down-right", "color":"info", "tooltip":"Preview" }, - {"link":"#", "narrow":true, "icon":"download", "color":"success", "tooltip":"Download" }, - {"link":"#", "narrow":true, "icon":"upload", "color":"warning", "tooltip":"Upload" }, - {"link":"#", "narrow":true, "icon":"info-circle", "color":"cyan", "tooltip":"Info" }, - {"link":"#", "narrow":true, "icon":"help-circle", "color":"purple", "tooltip":"Help" }, - {"link":"#", "narrow":true, "icon":"settings", "color":"indigo", "tooltip":"Settings" }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'Buttons with icons and different sizes', - json('[{"component":"button", "size":"lg" }, - {"link":"#", "outline":"azure", "title":"Edit", "icon":"edit"}, - {"link":"#", "outline":"danger", "title":"Delete", "icon":"trash"}]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A row of square buttons with spacing in between', - json('[{"component":"button", "shape":"square"}, - {"link":"#", "color":"green", "title":"Save", "icon": "device-floppy" }, - {"link":"#", "title":"Cancel", "space_after":true, "tooltip": "This will delete your draft"}, - {"link":"#", "outline":"indigo", "title":"Preview", "icon_after": "corner-down-right", "tooltip": "View temporary draft" }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'Multiple buttons sending the same form to different pages. - -We use `'''' AS validate` to remove the submit button from inside the form itself, -and instead use the button component to submit the form to pages with different GET variables. - -In the target page, we could then use the GET variable `$action` to determine what to do with the form data. - ', - json('[{"component":"form", "id": "poem", "validate": ""}, - {"type": "textarea", "name": "Poem", "placeholder": "Write a poem"}, - {"component":"button"}, - {"link":"?action=save", "form":"poem", "color":"primary", "title":"Save" }, - {"link":"?action=preview", "form":"poem", "outline":"yellow", "title":"Preview" }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A button that downloads a file when clicked, and prevents search engines from following the link.', - json('[{"component":"button"}, - {"link":"/sqlpage_introduction_video.mp4", - "title":"Download Video", - "icon":"download", - "download":"Introduction Video.webm", - "rel":"nofollow" - }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A button with an image-based icon.', - json('[{"component":"button"}, - {"link":"https://en.wikipedia.org/wiki/File:Globe.svg", - "title":"Open an article", - "image":"https://upload.wikimedia.org/wikipedia/commons/f/fa/Globe.svg" - }]') - ); - -INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES - ('button', 'image_alt', 'Alternative text for an informative button image. Leave empty if decorative or repeated by the button title.', 'TEXT', FALSE, TRUE); diff --git a/examples/official-site/sqlpage/migrations/28_tracking_component.sql b/examples/official-site/sqlpage/migrations/28_tracking_component.sql deleted file mode 100644 index e873f5bf0..000000000 --- a/examples/official-site/sqlpage/migrations/28_tracking_component.sql +++ /dev/null @@ -1,136 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'tracking', - 'Component for visualising activity logs or other monitoring-related data.', - 'timeline-event-text', - '0.18.0' - ); - -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'tracking', - 'title', - 'Title of the tracking component.', - 'TEXT', - TRUE, - FALSE - ), - ( - 'tracking', - 'information', - 'A short text displayed below the title.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'tracking', - 'description', - 'A short paragraph.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'tracking', - 'description_md', - 'A short paragraph formatted using markdown.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'tracking', - 'width', - 'Width of the component, between 1 and 12.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'tracking', - 'placement', - 'Position of the tooltip (e.g. top, bottom, right, left)', - 'TEXT', - TRUE, - TRUE - ), - ( - 'tracking', - 'color', - 'Color of the tracked item (e.g. success, warning, danger)', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tracking', - 'title', - 'Description of the state.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'tracking', - 'link', - 'A URL to open when the user clicks on the tracked item.', - 'URL', - FALSE, - TRUE - ), - ( - 'tracking', - 'center', - 'Whether to center the component.', - 'BOOLEAN', - TRUE, - TRUE - ); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES - ( - 'tracking', - 'A basic example of servers tracking component', - JSON( - '[ - {"component":"tracking","title":"Servers status"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"} - ]' - ) - ), - ( - 'tracking', - 'An example of servers tracking component', - JSON( - '[ - {"component":"tracking","title":"Servers status","information":"60% are running","description_md":"Status of all **currently running servers**","placement":"top","width":4}, - {"color":"success","title":"operational"}, - {"color":"success","title":"operational"}, - {"color":"success","title":"operational"}, - {"color":"danger","title":"Downtime"}, - {"title":"No data"}, - {"color":"success","title":"operational"}, - {"color":"warning","title":"Big load"}, - {"color":"success","title":"operational"} - ]' - ) - ); - - diff --git a/examples/official-site/sqlpage/migrations/29_divider_component.sql b/examples/official-site/sqlpage/migrations/29_divider_component.sql deleted file mode 100644 index 3acaa4e4b..000000000 --- a/examples/official-site/sqlpage/migrations/29_divider_component.sql +++ /dev/null @@ -1,152 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'divider', - 'Dividers help organize content and make the interface layout clear and uncluttered.', - 'separator', - '0.18.0' - ); - -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'divider', - 'contents', - 'A text in the divider.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'divider', - 'position', - 'Position of the text (e.g. left, right).', - 'TEXT', - TRUE, - TRUE - ), - ( - 'divider', - 'color', - 'The name of a color for this span of text.', - 'COLOR', - TRUE, - TRUE - ), - ( - 'divider', - 'size', - 'The size of the divider text, from 1 to 6.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'divider', - 'bold', - 'Whether the text is bold.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'divider', - 'italics', - 'Whether the text is italicized.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'divider', - 'underline', - 'Whether the text is underlined.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'divider', - 'link', - 'URL of the link for the divider text. Available only when contents is present.', - 'URL', - TRUE, - TRUE - ); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES - ( - 'divider', - 'An empty divider', - JSON( - '[ - { - "component":"divider" - } - ]' - ) - ), - ( - 'divider', - 'A divider with centered text', - JSON( - '[ - { - "component":"divider", - "contents":"Hello" - } - ]' - ) - ), - ( - 'divider', - 'A divider with text at left', - JSON( - '[ - { - "component":"divider", - "contents":"Hello", - "position":"left" - } - ]' - ) - ), - ( - 'divider', - 'A divider with blue text and a link', - JSON( - '[ - { - "component":"divider", - "contents":"SQLPage components", - "link":"/documentation.sql", - "color":"blue" - } - ]' - ) - ), - ( - 'divider', - 'A divider with bold, italic, and underlined text', - JSON( - '[ - { - "component":"divider", - "contents":"Important notice", - "position":"left", - "color":"red", - "size":5, - "bold":true, - "italics":true, - "underline":true - } - ]' - ) - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql b/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql deleted file mode 100644 index 6ec48379a..000000000 --- a/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql +++ /dev/null @@ -1,76 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'breadcrumb', - 'A secondary navigation aid that helps users understand their location on a website or mobile application.', - 'dots', - '0.18.0' - ); - -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) - VALUES ( - 'breadcrumb', - 'title', - 'Hyperlink text to display.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'breadcrumb', - 'link', - 'Link to the page to display when the link is clicked. By default, the link refers to the current page, with a ''link'' parameter set to the link''s title.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'breadcrumb', - 'active', - 'Whether the link is active or not. Defaults to false.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'breadcrumb', - 'description', - 'Description of the link. This is displayed when the user hovers over the link.', - 'TEXT', - FALSE, - TRUE - ); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES - ( - 'breadcrumb', - 'Basic usage of the breadcrumb component', - JSON( - '[ - {"component":"breadcrumb"}, - {"title":"Home","link":"/"}, - {"title":"Components", "link":"/documentation.sql"}, - {"title":"Breadcrumb", "link":"?component=breadcrumb"} - ]' - ) - ), - ( - 'breadcrumb', - 'Description of a link and selection of the current page.', - JSON( - '[ - {"component":"breadcrumb"}, - {"title":"Home","link":"/","active": true}, - {"title":"Articles","link":"/blog.sql","description":"Stay informed with the latest news"}, - {"title":"JSON in SQL","link":"/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide", "description": "Learn advanced json functions for MySQL, SQLite, PostgreSQL, and SQL Server" } - ]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/31_card_docs_update.sql b/examples/official-site/sqlpage/migrations/31_card_docs_update.sql deleted file mode 100644 index 3046dcd7d..000000000 --- a/examples/official-site/sqlpage/migrations/31_card_docs_update.sql +++ /dev/null @@ -1,93 +0,0 @@ -DELETE FROM component WHERE name = 'card'; - -INSERT INTO component(name, icon, description) VALUES - ('card', 'credit-card', 'A grid where each element is a small card that displays a piece of data.'); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'card', * FROM (VALUES - -- top level - ('title', 'Text header at the top of the list of cards.', 'TEXT', TRUE, TRUE), - ('description', 'A short paragraph displayed below the title.', 'TEXT', TRUE, TRUE), - ('description_md', 'A short paragraph displayed below the title - formatted using markdown.', 'TEXT', TRUE, TRUE), - ('columns', 'The number of columns in the grid of cards. This is just a hint, the grid will adjust dynamically to the user''s screen size, rendering fewer columns if needed to fit the contents. To control the size of cards individually, use the `width` row-level property instead.', 'INTEGER', TRUE, TRUE), - -- item level - ('title', 'Name of the card, displayed at the top.', 'TEXT', FALSE, FALSE), - ('description', 'The body of the card, where you put the main text contents of the card. - This does not support rich text formatting, only plain text. - If you want to use rich text formatting, use the `description_md` property instead.', 'TEXT', FALSE, TRUE), - ('description_md', ' - The body of the card, in Markdown format. - This is useful if you want to display a lot of text in the card, with many options for formatting, such as - line breaks, **bold**, *italics*, lists, #titles, [links](target.sql), ![images](photo.jpg), etc.', 'TEXT', FALSE, TRUE), - ('top_image', 'The URL (absolute or relative) of an image to display at the top of the card.', 'URL', FALSE, TRUE), - ('top_image_lazy', 'Whether the top image must be lazily loaded. Defaults to false, meaning eagerly loaded.', 'BOOLEAN', FALSE, TRUE), - ('top_image_width', 'Specify the top image width, in pixels. Helps prevent layout shifts.', 'INTEGER', FALSE, TRUE), - ('top_image_height', 'Specify the top image height, in pixels. Helps prevent layout shifts.', 'INTEGER', FALSE, TRUE), - ('footer', 'Muted text to display at the bottom of the card.', 'TEXT', FALSE, TRUE), - ('footer_md', 'Muted text to display at the bottom of the card, with rich text formatting in Markdown format.', 'TEXT', FALSE, TRUE), - ('link', 'An URL to which the user should be taken when they click on the card.', 'URL', FALSE, TRUE), - ('target', 'Where the card''s link opens: "_blank" for a new tab, "_self" for the same tab, "_parent" for the parent frame, or "_top" for the full body of the window.', 'TEXT', FALSE, TRUE), - ('footer_link', 'An URL to which the user should be taken when they click on the footer.', 'URL', FALSE, TRUE), - ('style', 'Inline style property to your iframe embed code. For example "background-color: #FFFFFF"', 'TEXT', FALSE, TRUE), - ('height', 'Height of the iframe embed code, in pixels. Used only when embed_mode is ''iframe''.', 'INTEGER', FALSE, TRUE), - ('allow', 'The permissions policy of the iframe embed code, for instance "fullscreen; clipboard-write". Used only when embed_mode is ''iframe''.', 'TEXT', FALSE, TRUE), - ('sandbox', 'The restrictions to apply to the iframe embed code, for instance "allow-scripts allow-same-origin". Used only when embed_mode is ''iframe''.', 'TEXT', FALSE, TRUE), - ('icon', 'Name of an icon to display on the right side of the card.', 'ICON', FALSE, TRUE), - ('color', 'The name of a color, to be displayed on the left of the card to highlight it. If the embed parameter is enabled and you don''t have a title or description, this parameter won''t apply.', 'COLOR', FALSE, TRUE), - ('background_color', 'The background color of the card.', 'COLOR', FALSE, TRUE), - ('active', 'Whether this item in the grid is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE), - ('width', 'The width of the card, between 1 (smallest) and 12 (full-width). The default width is 3, resulting in 4 cards per line. When embed_mode is ''iframe'', this is used as the width of the iframe instead, and defaults to 100%.', 'INTEGER', FALSE, TRUE) -) x; -INSERT INTO parameter(component, name, description_md, type, top_level, optional) SELECT 'card', * FROM (VALUES - ('embed', 'A url whose contents will be fetched and injected into the body of this card. - This can be used to inject arbitrary html content, but is especially useful for injecting - the output of other sql files rendered by SQLPage. For the latter case you can pass the - `?_sqlpage_embed` query parameter, which will skip the shell layout. - Components inside the fetched content initialize automatically. Custom scripts that insert - SQLPage fragments should dispatch a bubbling `fragment-loaded` event on the element containing - the new content. Initialization includes that element and its descendants; dispatching the - event on `document` initializes pending components throughout the page. Repeated events - preserve existing form and widget handlers', 'TEXT', FALSE, TRUE), - ('embed_mode', 'Set to ''iframe'' to embed the target (specified through embed property) in an iframe. - Unless this is explicitly set, the embed target is fetched and injected within the parent page. If embed_mode is set to iframe, - You can also set height and width parameters to configure the appearance and the sandbox and allow parameters to configure - security aspects of the iframe. Refer to the [MDN page](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) - for an explanation of these parameters.', 'TEXT', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('card', 'A beautiful card grid with bells and whistles, showing examples of SQLPage features.', - json('[{"component":"card", "title":"Popular SQLPage features", "columns": 2}, - {"title": "Download as spreadsheet", "link": "?component=csv#component", "description": "Using the CSV component, you can download your data as a spreadsheet.", "icon":"file-plus", "color": "green", "footer_md": "SQLPage can both [read](?component=form#component) and [write](?component=csv#component) **CSV** files."}, - {"title": "Custom components", "link": "/custom_components.sql", "description": "If you know some HTML, you can create your own components for your application.", "icon":"code", "color": "orange", "footer_md": "You can look at the [source of the official components](https://github.com/sqlpage/SQLPage/tree/main/sqlpage/templates) for inspiration."} - ]')), - ('card', 'You can use cards to display a dashboard with quick access to important information. Use [markdown](https://www.markdownguide.org/basic-syntax) to format the text.', - json('[ - {"component": "card", "columns": 4}, - {"description_md": "**152** sales today", "active": true, "icon": "currency-euro"}, - {"description_md": "**13** new users", "icon": "user-plus", "color": "green"}, - {"description_md": "**2** complaints", "icon": "alert-circle", "color": "danger", "link": "?view_complaints", "background_color": "red-lt"}, - {"description_md": "**1** pending support request", "icon": "mail-question", "color": "warning"} - ]')), - ('card', 'A gallery of images.', - json('[ - {"component":"card", "title":"My favorite animals in pictures", "columns": 3}, - {"title": "Lynx", "description_md": "The **lynx** is a medium-sized **wild cat** native to Northern, Central and Eastern Europe to Central Asia and Siberia, the Tibetan Plateau and the Himalayas.", "top_image_alt": "A Eurasian lynx", "top_image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Lynx_lynx_-_05.jpg/330px-Lynx_lynx_-_05.jpg", "top_image_width": 330, "top_image_height": 495, "top_image_lazy": true, "icon":"star" }, - {"title": "Squirrel", "description_md": "The **chipmunk** is a small, striped rodent of the family Sciuridae. Chipmunks are found in North America, with the exception of the Siberian chipmunk which is found primarily in Asia.", "top_image_alt": "A squirrel eating a nut", "top_image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/American_squirrel_eating_nut%2C_13_Jun_2013.JPG/330px-American_squirrel_eating_nut%2C_13_Jun_2013.JPG", "top_image_width": 330, "top_image_height": 495, "top_image_lazy": true }, - {"title": "Spider", "description_md": "The **jumping spider family** (_Salticidae_) contains more than 600 described genera and about *6000 described species*, making it the largest family of spiders with about 13% of all species.", "top_image_alt": "An orb weaver spinning a web", "top_image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Australian_orb_weaver_spinning_web.jpg/330px-Australian_orb_weaver_spinning_web.jpg", "top_image_width": 330, "top_image_height": 495, "top_image_lazy": true } - ]')), - ('card', 'Beautifully colored cards with variable width. The blue card (width 6) takes half the screen, whereas of the red and green cards have the default width of 3', - json('[ - {"component":"card", "title":"Beautifully colored cards" }, - {"title": "Red card", "color": "red", "background_color": "red-lt", "description": "Penalty! You are out!", "icon":"play-football" }, - {"title": "Blue card", "color": "blue", "width": 6, "background_color": "blue-lt", "description": "The Blue Card facilitates migration of foreigners to Europe.", "icon":"currency-euro" }, - {"title": "Green card", "color": "green", "background_color": "green-lt", "description": "Welcome to the United States of America !", "icon":"user-dollar" } - ]')), - ('card', 'The first card embeds a SQLPage chart as a page fragment. The second embeds a video player in an iframe with its own `height` and `allow` attributes.', - json('[ - {"component":"card", "title":"Card with embedded remote content", "columns": 2}, - {"title": "Embedded Chart", "embed": "/examples/chart.sql" }, - {"title": "Embedded Video", "embed": "https://www.youtube.com/embed/mXdgmSdaXkg", "allow": "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share", "embed_mode": "iframe", "height": "350" } - ]')); - -INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES - ('card', 'top_image_alt', 'Alternative text for an informative card image. Leave empty if decorative.', 'TEXT', FALSE, TRUE), - ('card', 'embed_title', 'Accessible name of the iframe. Defaults to the card title, or Embedded content if no title is set.', 'TEXT', FALSE, TRUE); diff --git a/examples/official-site/sqlpage/migrations/34_carousel.sql b/examples/official-site/sqlpage/migrations/34_carousel.sql deleted file mode 100644 index 70f74b53b..000000000 --- a/examples/official-site/sqlpage/migrations/34_carousel.sql +++ /dev/null @@ -1,163 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'carousel', - 'A carousel is used to display images. When used with multiple images, it will cycle through them automatically or with controls, creating a slideshow.', - 'carousel-horizontal', - '0.18.3' - ); -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'carousel', - 'title', - 'A name to display at the top of the carousel.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'carousel', - 'indicators', - 'Style of image indicators (square or dot).', - 'TEXT', - TRUE, - TRUE - ), - ( - 'carousel', - 'vertical', - 'Whether to use the vertical image indicators.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'controls', - 'Whether to show the control links to go previous or next item.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'width', - 'Width of the component, between 1 and 12. Default is 12.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'carousel', - 'auto', - 'Whether to automatically cycle through the carousel items. Default is false.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'center', - 'Whether to center the carousel.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'fade', - 'Whether to apply the fading effect.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'delay', - 'Specify the delay, in milliseconds, between two images.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'carousel', - 'image', - 'The URL (absolute or relative) of an image to display in the carousel.', - 'URL', - FALSE, - FALSE - ), - ( - 'carousel', - 'title', - 'Add caption to the slide.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'carousel', - 'description', - 'A short paragraph.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'carousel', - 'description_md', - 'A short paragraph formatted using markdown.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'carousel', - 'width', - 'The width of the image, in pixels.', - 'INTEGER', - FALSE, - TRUE - ), - ( - 'carousel', - 'height', - 'The height of the image, in pixels.', - 'INTEGER', - FALSE, - TRUE - ); -INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES - ('carousel', 'image_alt', 'Alternative text describing the slide image. Leave empty if the image is decorative or its caption already describes it.', 'TEXT', FALSE, TRUE); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'carousel', - 'A basic example of carousel', - JSON( - '[ - {"component":"carousel","name":"cats1","title":"Famous Database Animals"}, - {"image_alt":"African elephants at a watering hole","image":"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Elefantes_africanos_de_sabana_%28Loxodonta_africana%29%2C_Elephant_Sands%2C_Botsuana%2C_2018-07-28%2C_DD_114-117_PAN.jpg/1280px-Elefantes_africanos_de_sabana_%28Loxodonta_africana%29%2C_Elephant_Sands%2C_Botsuana%2C_2018-07-28%2C_DD_114-117_PAN.jpg"}, - {"image_alt":"A panoramic view of Penguin Island","image":"https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Penguin_Island_panorama_with_ferry_and_dolphins_in_foreground%2C_March_2023_06.jpg/1280px-Penguin_Island_panorama_with_ferry_and_dolphins_in_foreground%2C_March_2023_06.jpg"} - ]' - ) - ), - ( - 'carousel', - 'An advanced example of carousel with controls', - JSON( - '[ - {"component":"carousel","title":"SQL web apps","width":10, "center":true,"controls":true,"auto":true}, - {"image":"/sqlpage_cover_image.webp","title":"SQLPage is modern","description":"Built by engineers who have built so many web applications the old way, they decided they just wouldn''t anymore.", "height": 512}, - {"image":"/sqlpage_illustration_alien.webp","title":"SQLPage is easy", "description":"SQLPage connects to your database, then it turns your SQL queries into nice websites.", "height": 512} - ]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/35_code_title.sql b/examples/official-site/sqlpage/migrations/35_code_title.sql deleted file mode 100644 index bfa8b12cc..000000000 --- a/examples/official-site/sqlpage/migrations/35_code_title.sql +++ /dev/null @@ -1,115 +0,0 @@ --- Documentation for the title component -INSERT INTO component (name, description, icon, introduced_in_version) VALUES ( - 'title', - '`level` sets the HTML heading (`h1` through `h6`). Use level 1 for the page title, level 2 for sections, and level 3 for subsections so readers can navigate by heading.', - 'letter-case-upper', - '0.19.0' -); - -INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES ( - 'title', - 'center', - 'Whether to center the title.', - 'BOOLEAN', - TRUE, - TRUE -),( - 'title', - 'contents', - 'A text to display.', - 'TEXT', - TRUE, - FALSE -),( - 'title', - 'level', - 'Set the heading level (default level is 1)', - 'INTEGER', - TRUE, - TRUE -); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) VALUES ( - 'title', - 'Displays several titles with different levels.', - JSON( - '[ - {"component":"title","contents":"Level 1"}, - {"component":"title","contents":"Level 2","level": 2}, - {"component":"title","contents":"Level 3","level": 3} - ]' - ) -); - -INSERT INTO example(component, description, properties) VALUES ( - 'title', - 'Displays a centered title.', - JSON( - '[ - {"component":"title","contents":"Level 1","center": true} - ]' - ) -); - --- Documentation for the code component -INSERT INTO component (name, description, icon, introduced_in_version) VALUES ( - 'code', - 'Displays one or many blocks of code from a programming language or formated text as XML or JSON.', - 'code', - '0.19.0' -); - -INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES ( - 'code', - 'title', - 'Set the heading level (default level is 1)', - 'TEXT', - FALSE, - TRUE -),( - 'code', - 'contents', - 'A block of code.', - 'TEXT', - FALSE, - FALSE -),( - 'code', - 'description', - 'Description of the snipet of code.', - 'TEXT', - FALSE, - TRUE -),( - 'code', - 'description_md', - 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.', - 'TEXT', - FALSE, - TRUE -),( - 'code', - 'language', - 'Set the programming language name.', - 'TEXT', - FALSE, - TRUE -); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) VALUES ( - 'code', - 'Displays a block of HTML code.', - JSON( - '[ - {"component":"code"}, - { - "title":"A HTML5 example", - "language":"html", - "description":"Here’s the very minimum that an HTML document should contain, assuming it has CSS and JavaScript linked to it.", - "contents":"\n\n\t\n\t\t\n\t\ttitle\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n" - } - ]' - ) -); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/37_rss.sql b/examples/official-site/sqlpage/migrations/37_rss.sql deleted file mode 100644 index 0a3e70bb8..000000000 --- a/examples/official-site/sqlpage/migrations/37_rss.sql +++ /dev/null @@ -1,287 +0,0 @@ --- Documentation for the RSS component -INSERT INTO component (name, description, icon, introduced_in_version) VALUES ( - 'rss', - 'Produces a data flow in the RSS format. -Can be used to generate a podcast feed. -To use this component, you must first return an HTTP header with the "application/rss+xml" content type (see http_header component). Next, you must use the shell-empty component to avoid that SQLPage generates HTML code.', - 'rss', - '0.20.0' -); - -INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES ( - 'rss', - 'title', - 'Defines the title of the channel.', - 'TEXT', - TRUE, - FALSE -),( - 'rss', - 'link', - 'Defines the hyperlink to the channel.', - 'URL', - TRUE, - FALSE -),( - 'rss', - 'description', - 'Describes the channel.', - 'TEXT', - TRUE, - FALSE -),( - 'rss', - 'language', - 'Defines the language of the channel, specified in the ISO 639 format. For example, "en" for English, "fr" for French.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'category', - 'Defines the category of the channel. The value should be a string representing the category (e.g., "News", "Technology", etc.).', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'sub_category', - 'Defines a sub-category, nested inside the "category". Ignored unless "category" is also set.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'explicit', - 'Indicates whether the channel contains explicit content. The value can be either TRUE or FALSE.', - 'BOOLEAN', - TRUE, - TRUE -),( - 'rss', - 'image_url', - 'Provides a URL linking to the artwork for the channel.', - 'URL', - TRUE, - TRUE -),( - 'rss', - 'author', - 'Defines the group, person, or people responsible for creating the channel.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'copyright', - 'Provides the copyright details for the channel.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'self_link', - 'URL of the RSS feed.', - 'URL', - TRUE, - TRUE -),( - 'rss', - 'funding_url', - 'Specifies the donation/funding links for the channel. The content of the tag is the recommended string to be used with the link.', - 'URL', - TRUE, - TRUE -),( - 'rss', - 'funding_text', - 'The text to display with the donation/funding link. Ignored unless "funding_url" is also set.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'type', - 'Specifies the channel as either episodic or serial. The value can be either "episodic" or "serial".', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'complete', - 'Specifies that a channel is complete and will not post any more items in the future.', - 'BOOLEAN', - TRUE, - TRUE -),( - 'rss', - 'locked', - 'Tells podcast hosting platforms whether they are allowed to import this feed.', - 'BOOLEAN', - TRUE, - TRUE -),( - 'rss', - 'guid', - 'The globally unique identifier (GUID) for a channel. The value is a UUIDv5.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'title', - 'Defines the title of the feed item (episode name, blog post title, etc.).', - 'TEXT', - FALSE, - FALSE -),( - 'rss', - 'link', - 'Defines the hyperlink to the item (blog post URL, etc.).', - 'URL', - FALSE, - FALSE -),( - 'rss', - 'description', - 'Describes the item', - 'TEXT', - FALSE, - FALSE -),( - 'rss', - 'date', - 'Indicates when the item was published (RFC-822 date-time).', - 'TEXT', - FALSE, - TRUE -),( - 'rss', - 'enclosure_url', - 'For podcast episodes, provides a URL linking to the audio/video episode content, in mp3, m4a, m4v, or mp4 format.', - 'URL', - FALSE, - TRUE -),( - 'rss', - 'enclosure_length', - 'The length in bytes of the audio/video episode content.', - 'INTEGER', - FALSE, - TRUE -),( - 'rss', - 'enclosure_type', - 'The MIME media type of the audio/video episode content (e.g., "audio/mpeg", "audio/m4a", "video/m4v", "video/mp4").', - 'TEXT', - FALSE, - TRUE -),( - 'rss', - 'guid', - 'The globally unique identifier (GUID) for an item.', - 'TEXT', - FALSE, - TRUE -),( - 'rss', - 'episode', - 'The chronological number that is associated with an item.', - 'INTEGER', - FALSE, - TRUE -),( - 'rss', - 'season', - 'The chronological number associated with an item''s season.', - 'INTEGER', - FALSE, - TRUE -),( - 'rss', - 'episode_type', - 'Defines the type of content for a specific item. The value can be either "full", "trailer", or "bonus".', - 'TEXT', - FALSE, - TRUE -),( - 'rss', - 'block', - 'Prevents a specific item from appearing in podcast listening applications.', - 'BOOLEAN', - FALSE, - TRUE -),( - 'rss', - 'explicit', - 'Indicates whether the item contains explicit content. The value can be either TRUE or FALSE.', - 'BOOLEAN', - FALSE, - TRUE -),( - 'rss', - 'image_url', - 'Provides a URL linking to the artwork for the item.', - 'URL', - FALSE, - TRUE -),( - 'rss', - 'duration', - 'The duration of an item in seconds.', - 'INTEGER', - FALSE, - TRUE -),( - 'rss', - 'transcript_url', - 'A link to a transcript or closed captions file for the item.', - 'URL', - FALSE, - TRUE -),( - 'rss', - 'transcript_type', - 'The type of the transcript or closed captions file for the item (e.g., "text/plain", "text/html", "text/vtt", "application/json", "application/x-subrip").', - 'TEXT', - FALSE, - TRUE -); - --- Insert example(s) for the component -INSERT INTO example (component, description) -VALUES ( - 'rss', - ' -### An RSS channel about SQLPage latest news. - -```sql -select ''http_header'' as component, ''application/rss+xml'' as content_type; -select ''shell-empty'' as component; -select - ''rss'' as component, - ''SQLPage blog'' as title, - ''https://sql-page.com/blog.sql'' as link, - ''latest news about SQLpage'' as description, - ''en'' as language, - ''Technology'' as category, - FALSE as explicit, - ''https://sql-page.com/favicon.ico'' as image_url, - ''Ophir Lojkine'' as author, - ''https://github.com/sponsors/lovasoa'' as funding_url, - ''episodic'' as type; -select - ''Hello everyone !'' as title, - ''https://sql-page.com/blog.sql?post=Come%20see%20me%20build%20twitter%20live%20on%20stage%20in%20Prague'' as link, - ''If some of you european SQLPagers are around Prague this december, I will be giving a talk about SQLPage at pgconf.eu on December 14th.'' as description, - ''http://127.0.0.1:8080/sqlpage_introduction_video.mp4'' as enclosure_url, - 123456789 as enclosure_length, - ''video/mp4'' as enclosure_type, - ''2023-12-04'' as date; -``` - -Once you have your rss feed ready, you can submit it to podcast directories like -[Apple Podcasts](https://podcastsconnect.apple.com/my-podcasts), -[Spotify](https://podcasters.spotify.com/), -[Google Podcasts](https://podcastsmanager.google.com/)... -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/46_html.sql b/examples/official-site/sqlpage/migrations/46_html.sql deleted file mode 100644 index 58168c0d4..000000000 --- a/examples/official-site/sqlpage/migrations/46_html.sql +++ /dev/null @@ -1,97 +0,0 @@ --- Documentation for the RSS component -INSERT INTO - component (name, description, icon, introduced_in_version) -VALUES - ( - 'html', - 'Include raw HTML in the output. For advanced users only. Use this component to create complex layouts or to include external content. - Be very careful when using this component with user-generated content, as it can lead to security vulnerabilities. - Use this component only if you are familiar with the security implications of including raw HTML, and understand the risks of cross-site scripting (XSS) attacks.', - 'html', - '0.25.0' - ); - -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'html', - 'html', - 'Raw HTML content to include in the page. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'html', - 'html', - 'Raw HTML content to include in the page. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'html', - 'text', - 'Text content to include in the page. This will be sanitized and escaped. Use this property to include user-generated content that should not contain HTML tags.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'html', - 'post_html', - 'Raw HTML content to include after the text content. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.', - 'TEXT', - FALSE, - TRUE - ); - --- Insert example(s) for the component -INSERT INTO - example (component, description, properties) -VALUES - ( - 'html', - 'Include a simple HTML snippet. In this example, the HTML code is hardcoded in the SQL query, so it is safe. You should never include data that may be manipulated by a user in the HTML content. - ', - JSON ( - '[{ - "component": "html", - "html": "

This text is safe because it is hardcoded!

" - }]' - ) - ), - ( - 'html', - 'Include multiple html snippets as row-level parameters. Again, be careful what you include in the HTML content. If the data comes from a user, it can be manipulated to include malicious code.', - JSON ( - '[{"component":"html", "html":"
"}, - {"html":"
20%
"}, - {"html":"
80%
"}, - {"html":"
"} - ]' - ) - ), - ( - 'html', - 'In order to include user-generated content that should be sanitized, use the `text` property instead of `html`. The `text` property will display the text as-is, without interpreting any HTML tags.', - JSON ( - ' - [ - {"component": "html"}, - { - "html": "

The following will be sanitized: ", - "text": "", - "post_html": ". Phew! That was close!

" - } - ]' - ) - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/48_status_code.sql b/examples/official-site/sqlpage/migrations/48_status_code.sql deleted file mode 100644 index f80d4266a..000000000 --- a/examples/official-site/sqlpage/migrations/48_status_code.sql +++ /dev/null @@ -1,65 +0,0 @@ --- Insert the status_code component into the component table -INSERT INTO - component (name, description, icon) -VALUES - ( - 'status_code', - 'Sets the HTTP response code for the current page. - -This is an advanced technical component. -You typically need it when building internet-facing APIs and websites, -but you may not need it for simple internal applications. - -- Indicating operation results when using [SQLPage as an API](?component=json) - - `200`: *OK*, for successful operations - - `201`: *Created*, for successful record insertion - - `404`: *Not Found*, for missing resources - - `500`: *Internal Server Error*, for failed operations -- Handling data validation errors - - `400`: *Bad Request*, for invalid data -- Enforcing access controls - - `403`: *Forbidden*, for unauthorized access - - `401`: *Unauthorized*, for unauthenticated access -- Tracking system health - - `500`: *Internal Server Error*, for failed operations - -For search engine optimization: -- Use `404` for deleted content to remove outdated URLs from search engines -- For redirection from one page to another, use - - `301` (moved permanently), or - - `302` (moved temporarily) -- Use `503` during maintenance', - 'error-404' - ); - --- Insert the parameters for the status_code component into the parameter table -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'status_code', - 'status', - 'HTTP status code (e.g., 200 OK, 401 Unauthorized, 409 Conflict)', - 'INTEGER', - TRUE, - FALSE - ); - -INSERT INTO example (component, description) -VALUES ( - 'status_code', - ' -Set the HTTP status code to 404, indicating that the requested resource was not found. -Useful in combination with [`404.sql` files](/your-first-sql-website/custom_urls.sql): - -```sql -SELECT ''status_code'' as component, 404 as status; -``` -'); diff --git a/examples/official-site/sqlpage/migrations/49_big_number.sql b/examples/official-site/sqlpage/migrations/49_big_number.sql deleted file mode 100644 index acdb2858d..000000000 --- a/examples/official-site/sqlpage/migrations/49_big_number.sql +++ /dev/null @@ -1,66 +0,0 @@ --- Big Number Component Documentation - --- Component Definition -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('big_number', 'chart-area', 'A component to display key metrics or statistics with optional description, change indicator, and progress bar. Useful in dashboards.', '0.28.0'); - --- Inserting parameter information for the big_number component -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'big_number', * FROM (VALUES - -- Top-level parameters (for the whole big_number list) - ('columns', 'The number of columns to display the big numbers in (default is one column per item).', 'INTEGER', TRUE, TRUE), - ('wrap', 'Wrap long titles and descriptions onto multiple lines. By default, they are truncated with an ellipsis.', 'BOOLEAN', TRUE, TRUE), - -- id and class, at both levels, come from 99_shared_id_class_attributes.sql - -- Item-level parameters (for each big number) - ('title', 'The title or label for the big number.', 'TEXT', FALSE, TRUE), - ('title_link', 'A link for the Big Number title. If set, the entire title becomes clickable.', 'TEXT', FALSE, TRUE), - ('title_link_new_tab', 'If true, the title link will open in a new tab/window.', 'BOOLEAN', FALSE, TRUE), - ('value_link', 'A link for the Big Number value. If set, the entire value becomes clickable.', 'TEXT', FALSE, TRUE), - ('value_link_new_tab', 'If true, the value link will open in a new tab/window.', 'BOOLEAN', FALSE, TRUE), - ('value', 'The main value to be displayed prominently.', 'TEXT', FALSE, FALSE), - ('unit', 'The unit of measurement for the value.', 'TEXT', FALSE, TRUE), - ('description', 'A description or additional context for the big number.', 'TEXT', FALSE, TRUE), - ('change_percent', 'The percentage change in value (e.g., 7 for 7% increase, -8 for 8% decrease).', 'INTEGER', FALSE, TRUE), - ('progress_percent', 'The value of the progress (0-100).', 'INTEGER', FALSE, TRUE), - ('progress_color', 'The color of the progress bar (e.g., "primary", "success", "danger").', 'TEXT', FALSE, TRUE), - ('dropdown_item', 'A list of JSON objects containing links. e.g. {"label":"This week", "link":"?days=7"}', 'JSON', FALSE, TRUE), - ('color', 'The color of the card background and its main value.', 'COLOR', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('big_number', 'Big numbers with change indicators and progress bars', - json('[ - {"component":"big_number"}, - { - "title":"Sales", - "value":75, - "unit":"%", - "title_link": "#sales_dashboard", - "title_link_new_tab": true, - "value_link": "#sales_details", - "value_link_new_tab": false, - "description":"Conversion rate", - "change_percent": 9, - "progress_percent": 75, - "progress_color": "blue" - }, - { - "title":"Revenue", - "value":"4,300", - "unit":"$", - "description":"Year on year", - "change_percent": -8 - } - ]')); - -INSERT INTO example(component, description, properties) VALUES - ('big_number', 'Big numbers with dropdowns and customized layout', - json('[ - {"component":"big_number", "columns":3, "id":"colorfull_dashboard"}, - {"title":"Users", "value":"1,234", "color": "red", "title_link": "#users", "title_link_new_tab": false, "value_link": "#users_details", "value_link_new_tab": true }, - {"title":"Orders", "value":56, "color": "green", "title_link": "#orders", "title_link_new_tab": true }, - {"title":"Revenue", "value":"9,876", "unit": "€", "color": "blue", "change_percent": -7, "dropdown_item": [ - {"label":"This week", "link":"?days=7&component=big_number#colorfull_dashboard"}, - {"label":"This month", "link":"?days=30&component=big_number#colorfull_dashboard"}, - {"label":"This quarter", "link":"?days=90&component=big_number#colorfull_dashboard"} - ]} - ]')); diff --git a/examples/official-site/sqlpage/migrations/51_column.sql b/examples/official-site/sqlpage/migrations/51_column.sql deleted file mode 100644 index 8785b3955..000000000 --- a/examples/official-site/sqlpage/migrations/51_column.sql +++ /dev/null @@ -1,118 +0,0 @@ --- Column Component Documentation - --- Component Definition -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('columns', 'columns', 'Use one row per plan, feature, or metric to compare them side by side. For a dashboard of values with trends and progress bars, see [`big_number`](?component=big_number).', '0.29.0'); - --- Inserting parameter information for the column component -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'columns', * FROM (VALUES - ('title', 'The title or label for the item.', 'TEXT', FALSE, TRUE), - ('value', 'The value associated with the item.', 'TEXT', FALSE, TRUE), - ('description', 'A brief description of the item.', 'TEXT', FALSE, TRUE), - ('description_md', 'A brief description of the item, formatted using markdown.', 'TEXT', FALSE, TRUE), - ('item', 'A list of bullet points associated with the columns, represented either as text, or as a json object with "icon", "color", and "description" or "description_md" fields.', 'JSON', FALSE, TRUE), - ('link', 'A link associated with the item.', 'TEXT', FALSE, TRUE), - ('button_text', 'Text for the button.', 'TEXT', FALSE, TRUE), - ('button_color', 'Optional color for the button.', 'TEXT', FALSE, TRUE), - ('target', 'Optional target for the button. Set to "_blank" to open links in a new tab.', 'TEXT', FALSE, TRUE), - ('value_color', 'Color for the value text.', 'TEXT', FALSE, TRUE), - ('small_text', 'Optional small text to display after the value.', 'TEXT', FALSE, TRUE), - ('icon', 'Optional icon to display in a ribbon.', 'ICON', FALSE, TRUE), - ('icon_color', 'Color for the icon in the ribbon.', 'TEXT', FALSE, TRUE), - ('size', 'Width on a 12-column grid on larger screens. For three equal columns, return three rows with `size` set to 4.', 'INTEGER', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('columns', 'Pricing Plans Display', - json('[ - {"component":"columns"}, - { - "title":"Start Plan", - "value":"€18", - "description":"Perfect for testing and small-scale projects", - "item": [ - "128MB Database", - "SQLPage hosting", - "Community support" - ], - "link":"https://datapage.app", - "button_text":"Start Free Trial", - "small_text":"/month" - }, - { - "title":"Pro Plan", - "value":"€40", - "icon":"rocket", - "description":"For growing projects needing enhanced features", - "item": [ - {"icon":"database", "color": "blue", "description":"1GB Database"}, - {"icon":"headset", "color": "green", "description":"Priority Support"}, - {"icon":"world", "color": "purple", "description":"Custom Domain"} - ], - "link":"https://datapage.app", - "button_text":"Start Free Trial", - "button_color":"indigo", - "value_color":"indigo", - "small_text":"/month" - }, - { - "title":"Enterprise Plan", - "value":"€600", - "icon":"building-skyscraper", - "description":"For large-scale operations with custom needs", - "item": [ - {"icon":"database-plus", "description_md":"**Custom Database Scaling**"}, - {"icon":"shield-lock", "description_md":"**Enterprise Auth** with Single Sign-On"}, - {"icon":"headset", "description_md":"**Monthly** Expert Support time"}, - {"icon":"file-certificate", "description_md":"**SLA** with guaranteed uptime"} - ], - "link":"mailto:contact@datapage.app", - "button_text":"Contact Us", - "small_text":"/month", - "target":"_blank" - } - ]')), - - ('columns', 'Tech Company KPIs Display', - json('[ - {"component":"columns"}, - { - "title":"Monthly Active Users", - "value":"10k", - "value_color":"blue", - "size": 4, - "description":"Total active users this month, showcasing user engagement.", - "item": [ - {"icon": "target", "description":"Target: 12,000"} - ], - "link":"#", - "button_text":"User Activity Overview", - "button_color":"info" - }, - { - "title":"Revenue", - "value":"$49k", - "value_color":"blue", - "size": 4, - "description":"Total revenue generated this month, indicating financial performance.", - "item": [ - {"icon":"trending-down", "color": "red", "description":"down from $51k last month" } - ], - "link":"#", - "button_text":"Financial Dashboard", - "button_color":"info" - }, - { - "title":"Customer Satisfaction", - "value":"94%", - "value_color":"blue", - "size": 4, - "description":"Percentage of satisfied customers, reflecting service quality.", - "item": [ - {"icon":"trending-up", "color": "green", "description":"+ 2% this month" } - ], - "link":"#", - "button_text": "Open Google Ratings", - "button_color":"info" - } - ]')); diff --git a/examples/official-site/sqlpage/migrations/52_foldable.sql b/examples/official-site/sqlpage/migrations/52_foldable.sql deleted file mode 100644 index d70201dfe..000000000 --- a/examples/official-site/sqlpage/migrations/52_foldable.sql +++ /dev/null @@ -1,27 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('foldable', 'chevrons-down', 'A foldable list of elements which can be expanded individually.', '0.29.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'foldable', * FROM (VALUES - ('id', 'ID attribute added to the container in HTML. Used for targeting through CSS or for scrolling via links. When set at the top level, applies to the entire foldable component.', 'TEXT', TRUE, TRUE), - ('class', 'CSS class(es) to add to the foldable container. When set at the top level, applies to the entire foldable component.', 'TEXT', TRUE, TRUE), - ('id', 'ID attribute added to individual foldable items. Used for targeting through CSS or for scrolling via links.', 'TEXT', FALSE, TRUE), - ('class', 'CSS class(es) to add to individual foldable items.', 'TEXT', FALSE, TRUE), - ('title', 'Title of the foldable item, displayed on the button.', 'TEXT', FALSE, TRUE), - ('description', 'Plain text description of the item, displayed when expanded.', 'TEXT', FALSE, TRUE), - ('description_md', 'Markdown description of the item, displayed when expanded.', 'TEXT', FALSE, TRUE), - ('expanded', 'If set to TRUE, the foldable item starts in an expanded state. Defaults FALSE', 'BOOLEAN', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('foldable', 'A single foldable paragraph of text', json('[ - {"component":"foldable"}, - {"title":"The foldable component", "description": "This is a simple foldable component. It can be used to show and hide content. It is a list of items, each with a title and a description. The description is displayed when the item is expanded."}, - ]')); - -INSERT INTO example(component, description, properties) VALUES - ('foldable', 'A SQLPage-themed foldable list with Markdown', json('[ - {"component":"foldable"}, - {"title":"Quick Prototyping", "description_md": "Build a functional web app prototype in minutes using just SQL queries:\n\n- Rapid development\n- Ideal for MVPs\n- Great for internal tools\n\nLearn more about [quick prototyping](/your-first-sql-website/).", "expanded": true}, - {"title":"Data Visualization", "description_md": "Quickly transform your database into useful insights:\n\n1. **Charts**: Line, bar, pie\n2. **KPIs**: Appealing visualizations of key metrics\n3. **Maps**: Geospatial data\n\nAs simple as:\n\n```sql\nSELECT ''chart'' as component;\nSELECT date as x, revenue as y FROM sales;\n```"}, - {"title":"Don''t stare, interact!", "description_md": "SQLPage is not just a passive *Business Intelligence* tool. With SQLPage, you can act upon user input:\n\n- *User input collection*: Building a form is just as easy as building a chart.\n- *Data validation*: Write your own validation rules in SQL.\n- *Database updates*: `INSERT` and `UPDATE` are first-class citizens.\n- *File uploads*: Upload `CSV` and other files, store and display them the way you want.\n\n> Let users interact with your data, not just look at it!"} - ]')); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/59_unsafe_contents_md.sql b/examples/official-site/sqlpage/migrations/59_unsafe_contents_md.sql deleted file mode 100644 index 5f8f2c97a..000000000 --- a/examples/official-site/sqlpage/migrations/59_unsafe_contents_md.sql +++ /dev/null @@ -1,4 +0,0 @@ -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'text', * FROM (VALUES -('unsafe_contents_md','Markdown format with html blocks. Use this only with trusted content. See the html-blocks section of the Commonmark spec for additional info.', 'TEXT', TRUE, TRUE), -('unsafe_contents_md','Markdown format with html blocks. Use this only with trusted content. See the html-blocks section of the Commonmark spec for additional info.', 'TEXT', FALSE, TRUE) -); diff --git a/examples/official-site/sqlpage/migrations/60_empty_state.sql b/examples/official-site/sqlpage/migrations/60_empty_state.sql deleted file mode 100644 index 1f0b65518..000000000 --- a/examples/official-site/sqlpage/migrations/60_empty_state.sql +++ /dev/null @@ -1,52 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('empty_state', 'info-circle', 'Displays a large placeholder message to communicate a single information to the user and invite them to take action. - -Typically includes a title, an optional icon/image, descriptive text (rich text formatting and images supported via Markdown), and a call-to-action button. - -Ideal for first-use screens, empty data sets, "no results" pages, or error messages.', '0.35.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'empty_state', * FROM (VALUES - ('title','Description of the empty state.','TEXT',TRUE,FALSE), - ('header','Text displayed on the top of the empty state.','TEXT',TRUE,TRUE), - ('icon','Name of an icon to be displayed on the top of the empty state.','ICON',TRUE,TRUE), - ('image','The URL (absolute or relative) of an image to display at the top of the empty state.','URL',TRUE,TRUE), - ('description','A short text displayed below the title.','TEXT',TRUE,TRUE), - ('description_md','A short text displayed below the title, formatted using markdown.','TEXT',TRUE,TRUE), - ('link_text','The text displayed on the button.','TEXT',TRUE,FALSE), - ('link_icon','Name of an icon to be displayed on the left side of the button.','ICON',TRUE,FALSE), - ('link','The URL to which the button should navigate when clicked.','URL',TRUE,FALSE) - -- id and class come from 99_shared_id_class_attributes.sql -) x; - -INSERT INTO example(component, description, properties) VALUES - ('empty_state', ' -This example shows how to create a 404-style "Not Found" empty state with - - a prominent header displaying "404", - - a helpful description suggesting to adjust search parameters, and - - a "Search again" button with a search icon that links back to the search page. -', - json('[{ - "component": "empty_state", - "title": "No results found", - "header": "404", - "description": "Try adjusting your search or filter to find what you''re looking for.", - "link_text": "Search again", - "link_icon": "search", - "link": "#not-found", - "id": "not-found" - }]')), - ('empty_state', ' -It''s possible to use an icon or an image to illustrate the problem. -', - json('[{ - "component": "empty_state", - "title": "A critical problem has occurred", - "icon": "mood-wrrr", - "description_md": "SQLPage can do a lot of things, but this is not one of them. - -Please restart your browser and **cross your fingers**.", - "link_text": "Close and restart", - "link_icon": "rotate-clockwise", - "link": "#" - }]')); - diff --git a/examples/official-site/sqlpage/migrations/63_modal.sql b/examples/official-site/sqlpage/migrations/63_modal.sql deleted file mode 100644 index 0d03337ec..000000000 --- a/examples/official-site/sqlpage/migrations/63_modal.sql +++ /dev/null @@ -1,85 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('modal', 'app-window', ' -Defines the a temporary popup box displayed on top of a webpage’s content. -Useful for displaying additional information, help, or collect data from users. - -Modals are closed by default, and can be opened by clicking on a button or link targeting their ID.', '0.36.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'modal', * FROM (VALUES - ('title','Description of the modal box.','TEXT',TRUE,FALSE), - ('close','The text to display in the Close button.','TEXT',TRUE,TRUE), - ('close_label','The same as `close`. Use it on databases where `close` is a reserved word, such as SQL Server.','TEXT',TRUE,TRUE), - ('contents','A paragraph of text to display, without any formatting, without having to make additional queries.','TEXT',FALSE,TRUE), - ('contents_md','Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.','TEXT',FALSE,TRUE), - ('scrollable','Create a scrollable modal that allows scroll the modal body.','BOOLEAN',TRUE,TRUE), - ('class','Class attribute added to the container in HTML. It can be used to apply custom styling to this item through css.','TEXT',TRUE,TRUE), - ('id','ID attribute added to the container in HTML. It can be used to target this item through css or for displaying this item.','TEXT',TRUE,FALSE), - ('large','Indicates that the modal box has an increased width.','BOOLEAN',TRUE,TRUE), - ('small','Indicates that the modal box has a reduced width.','BOOLEAN',TRUE,TRUE), - ('embed','Embed remote content in an iframe.','TEXT',TRUE,TRUE), - ('embed_mode','Use "iframe" to display embedded content within an iframe.','TEXT',TRUE,TRUE), - ('height','Height of the modal content, in pixels. Overflow content scrolls.','INTEGER',TRUE,TRUE), - ('allow','For embedded content, this attribute specifies the features or permissions that can be used.','TEXT',TRUE,TRUE), - ('sandbox','For embedded content, this attribute specifies the security restrictions on the loaded content.','TEXT',TRUE,TRUE), - ('style','Applies CSS styles to the embedded content.','TEXT',TRUE,TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('modal', - 'This example shows how to create a modal box that displays a paragraph of text. The modal window is opened with the help of a button.', - json('[ - {"component": "modal","id": "my_modal","title": "A modal box","close": "Close"}, - {"contents":"I''m a modal window, and I allow you to display additional information or help for the user."}, - {"component": "button"}, - {"title":"Open a simple modal","link":"#my_modal"} - ]') - ), - ('modal', - 'The button opens the dialog by its `id`. `embed` loads the form from another SQLPage file without its surrounding page shell.', - json('[ - { - "component":"modal", - "id":"my_embed_form_modal", - "title":"Embedded form", - "large":true, - "embed":"/examples/form.sql" - }, - {"component": "button"}, - {"title":"Open a modal with a form","link":"#my_embed_form_modal"} - ]') - ), - ('modal', - 'A popup modal that contains a chart generated by a separate SQL file. The modal is triggered by links inside a datagrid.', - json('[ - { - "component":"modal", - "id":"my_embed_chart_modal", - "title":"Embeded chart content", - "close":"Close", - "embed":"/examples/chart.sql?_sqlpage_embed" - }, - {"component": "datagrid"}, - {"title":"Chart", "color":"blue", "description":"Revenue", "link":"#my_embed_chart_modal"}, - {"title":"Form", "color":"green", "description":"Fill info", "link":"#my_embed_form_modal"}, - ]') - ), - ('modal', - 'Example of modal video content', - json('[ - { - "component":"modal", - "id":"my_embed_video_modal", - "title":"Embeded video content", - "close":"Close", - "embed":"https://www.youtube.com/embed/mXdgmSdaXkg", - "allow":"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share", - "embed_mode":"iframe", - "height":"350" - }, - {"component": "text", "contents_md": "Open a [modal with a video](#my_embed_video_modal)"} - ]') - ); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'button', * FROM (VALUES - ('modal','Display the modal window corresponding to the specified ID.','TEXT',FALSE,TRUE) -) x; diff --git a/examples/official-site/sqlpage/migrations/65_download.sql b/examples/official-site/sqlpage/migrations/65_download.sql deleted file mode 100644 index a05b49ab8..000000000 --- a/examples/official-site/sqlpage/migrations/65_download.sql +++ /dev/null @@ -1,140 +0,0 @@ --- Insert the download component into the component table -INSERT INTO - component (name, description, icon, introduced_in_version) -VALUES - ( - 'download', - ' -The *download* component lets a page immediately return a file to the visitor. - -Instead of showing a web page, it sends the file''s bytes as the whole response, -so it should be used **at the very top of your SQL page** (before the shell or any other page contents). -It is an error to use this component after another component that would display content. - -## Sending a file - -- You provide the file content using a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs). -A data URL is just a text string that contains both the file type and the actual data. -- Optionally, you provide a "filename" so the browser shows a proper Save As name. -If you do not provide a filename, many browsers will try to display the file inline (for example images or JSON), depending on the content type. -- You link to the page that uses the download component from another page, using the [button](/component.sql?component=button) component for example. - -## Data URL format - -- It looks like this: `data:[content-type][;base64],DATA` -- Examples: - - Plain text (URL-encoded): `data:text/plain,Hello%20world` - - JSON (URL-encoded): `data:application/json,%7B%22message%22%3A%22Hi%22%7D` - - Binary data (Base64): `data:application/octet-stream;base64,SGVsbG8h` - -Tips: -- Use URL encoding when you have textual data. You can use [`sqlpage.url_encode(source_text)`](/functions?function=url_encode) to encode the data. -- Use Base64 when you have binary data (images, PDFs, or content that may include special characters). -- Use [`sqlpage.read_file_as_data_url(file_path)`](/functions?function=read_file_as_data_url) to read a file from the server and return it as a data URL. - -> Keep in mind that large files are better served from disk or object storage. Data URLs are best for small to medium files. -There is a big performance penalty for loading large files as data URLs, so it is not recommended. -', - 'download', - '0.37.0' - ); - --- Insert the parameters for the download component into the parameter table -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'download', - 'data_url', - 'The file content to send, written as a data URL (for example: data:text/plain,Hello%20world or data:application/octet-stream;base64,SGVsbG8h). The part before the comma declares the content type and whether the data is base64-encoded. The part after the comma is the actual data.', - 'TEXT', - TRUE, - FALSE - ), - ( - 'download', - 'filename', - 'The suggested name of the file to save (for example: report.csv). When set, the browser will download the file as an attachment with this name. When omitted, many browsers may try to display the file inline depending on its content type.', - 'TEXT', - TRUE, - TRUE - ); - --- Insert usage examples of the download component into the example table -INSERT INTO - example (component, description) -VALUES - ( - 'download', - ' -## Simple plain text file -Download a small text file. The content is URL-encoded (spaces become %20). - -```sql -select - ''download'' as component, - ''data:text/plain,Hello%20SQLPage%20world!'' as data_url, - ''hello.txt'' as filename; -``` -' - ), - ( - 'download', - ' -## Download a PDF file from the server - -Download a PDF file with the proper content type so PDF readers recognize it. -Uses [`sqlpage.read_file_as_data_url(file_path)`](/functions?function=read_file_as_data_url) to read the file from the server. - -```sql -select - ''download'' as component, - ''report.pdf'' as filename, - sqlpage.read_file_as_data_url(''report.pdf'') as data_url; -``` -' - ), - ( - 'download', - ' -## Serve an image stored as a BLOB in the database - -### Automatically detect the mime type - -If you have a table with a column `content` that contains a BLOB -(depending on the database, the type may be named `BYTEA`, `BLOB`, `VARBINARY`, or `IMAGE`), -you can just return its contents directly, and SQLPage will automatically detect the mime type, -and convert it to a data URL. - -```sql -select - ''download'' as component, - content as data_url -from document -where id = $doc_id; -``` - -### Customize the mime type - -In PostgreSQL, you can use the [encode(bytes, format)](https://www.postgresql.org/docs/current/functions-binarystring.html#FUNCTION-ENCODE) function to encode the file content as Base64, -and manually create your own data URL. - -```sql -select - ''download'' as component, - ''data:'' || doc.mime_type || '';base64,'' || encode(doc.content::bytea, ''base64'') as data_url -from document as doc -where doc.id = $doc_id; -``` - - - In Microsoft SQL Server, you can use the [BASE64_ENCODE(bytes)](https://learn.microsoft.com/en-us/sql/t-sql/functions/base64-encode-transact-sql) function to encode the file content as Base64. - - In MySQL and MariaDB, you can use the [TO_BASE64(str)](https://mariadb.com/docs/server/reference/sql-functions/string-functions/to_base64) function. -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/66_log_component.sql b/examples/official-site/sqlpage/migrations/66_log_component.sql deleted file mode 100644 index 3a2cb083b..000000000 --- a/examples/official-site/sqlpage/migrations/66_log_component.sql +++ /dev/null @@ -1,61 +0,0 @@ -INSERT INTO component(name, icon, introduced_in_version, description) VALUES -('log', 'logs', '0.37.1', 'A component that writes messages to the server logs. -When a page runs, it prints your message to the terminal/console (standard error). -Use it to track what happens and troubleshoot issues. - -## Reading log messages - -- Running from a terminal (Linux, macOS, or Windows PowerShell/Command Prompt): they show up in the window. -- Docker: run `docker logs `. -- Linux service (systemd): run `journalctl -u sqlpage`. -- This component''s output is written to [standard error (stderr)](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)). SQLPage request access logs are separate and are written to standard output (stdout). -'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'log', * FROM (VALUES - -- top level - ('message', 'The text to write to the server logs. It is printed when the page runs.', 'TEXT', TRUE, FALSE), - ('level', 'How important the message is. One of ''trace'', ''debug'', ''info'' (default), ''warn'', ''error''. Not case-sensitive. Controls the level shown in the logs.', 'TEXT', TRUE, TRUE) -) x; - -INSERT INTO example(component, description) VALUES -('log', ' -### Record a simple message - -This writes "Hello, World!" to the server logs. - -```sql -SELECT ''log'' as component, ''Hello, World!'' as message; -``` - -Example output: - -```text -[2025-09-13T22:30:14.722Z INFO sqlpage::log from "x.sql" statement 1] Hello, World! -``` - -### Set the importance (level) - -Choose how important the message is. - -```sql -SELECT ''log'' as component, ''error'' as level, ''This is an error message'' as message; -``` - -Example output: - -```text -[2025-09-13T22:30:14.722Z ERROR sqlpage::log from "x.sql" statement 2] This is an error message -``` - -### Log dynamic information - -Include variables like a username. - -```sql -set username = ''user'' - -select ''log'' as component, - ''403 - failed for '' || coalesce($username, ''None'') as message, - ''error'' as level; -``` -') diff --git a/examples/official-site/sqlpage/migrations/68_login.sql b/examples/official-site/sqlpage/migrations/68_login.sql deleted file mode 100644 index 11d29de18..000000000 --- a/examples/official-site/sqlpage/migrations/68_login.sql +++ /dev/null @@ -1,79 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('login', 'password-user', ' -The login component is an authentication form with numerous customization options. -It offers the main functionalities for this type of form. -The user can enter their username and password. -There are many optional attributes such as the use of icons on input fields, the insertion of a link to a page to reset the password, an option for the application to maintain the user''s identity via a cookie. -It is also possible to set the title of the form, display the company logo, or customize the appearance of the form submission button. - -This component should be used in conjunction with other components such as [authentication](component.sql?component=authentication) and [cookie](component.sql?component=cookie). -It does not implement any logic and simply collects the username and password to pass them to the code responsible for authentication. - -A few things to know : -- The form uses the POST method to transmit information to the destination page, -- The user''s username and password are entered into fields with the names `username` and `password`, -- To obtain the values of username and password, you must use the variables `:username` and `:password`, -- When you set the `remember_me_text` property, the variable `:remember` becomes available after form submission to check if the user checked the "remember me" checkbox. -', '0.39.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'login', * FROM (VALUES - ('title','Title of the authentication form.','TEXT',TRUE,TRUE), - ('enctype','Form data encoding.','TEXT',TRUE,TRUE), - ('action','An optional link to a target page that will handle the results of the form. ','TEXT',TRUE,TRUE), - ('error_message','An error message to display above the form, typically shown after a failed login attempt.','TEXT',TRUE,TRUE), - ('error_message_md','A markdown error message to display above the form, typically shown after a failed login attempt.','TEXT',TRUE,TRUE), - ('username','Label and placeholder for the user account identifier text field.','TEXT',TRUE,FALSE), - ('password','Label and placeholder for the password field.','TEXT',TRUE,FALSE), - ('autofocus','Focus the username field when the page opens. Defaults to true. Set to false when the form is one part of a larger page.','BOOLEAN',TRUE,TRUE), - ('username_icon','Icon to display on the left side of the input field, on the same line.','ICON',TRUE,TRUE), - ('password_icon','Icon to display on the left side of the input field, on the same line.','ICON',TRUE,TRUE), - ('image','The URL of an centered image displayed before the title.','URL',TRUE,TRUE), - ('forgot_password_text','A text for the link allowing the user to reset their password. If the text is empty, the link is not displayed.','TEXT',TRUE,TRUE), - ('forgot_password_link','The link to the page allowing the user to reset their password.','TEXT',TRUE,TRUE), - ('remember_me_text','A text for the option allowing the user to request the preservation of their identity. If the text is empty, the option is not displayed.','TEXT',TRUE,TRUE), - ('footer','A text placed at the bottom of the authentication form. If both footer and footer_md are specified, footer takes precedence.','TEXT',TRUE,TRUE), - ('footer_md','A markdown text placed at the bottom of the authentication form. Useful for creating links to other pages (creating a new account, contacting technical support, etc.).','TEXT',TRUE,TRUE), - ('validate','The text to display in the button at the bottom of the form that submits the values.','TEXT',TRUE,TRUE), - ('validate_color','The color of the button at the bottom of the form that submits the values. Omit this property to use the default color.','COLOR',TRUE,TRUE), - ('validate_shape','The shape of the validation button.','TEXT',TRUE,TRUE), - ('validate_outline','A color to outline the validation button.','COLOR',TRUE,TRUE), - ('validate_size','The size of the validation button.','TEXT',TRUE,TRUE) -) x; - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'login', - 'Using the main options of the login component - -When the user clicks the "Sign in" button, the form is submitted to the `/examples/show_variables.sql` page. -There, you will have access to the variables: - - `:username`: the username entered by the user - - `:password`: the password entered by the user - - `:remember`: the string "on" if the checkbox was checked, or NULL if it was not checked -', - JSON( - '[ - { - "component": "login", - "action": "/examples/show_variables", - "image": "../assets/icon.webp", - "title": "Please login to your account", - "username": "Username", - "password": "Password", - "autofocus": false, - "username_icon": "user", - "password_icon": "lock", - "forgot_password_text": "Forgot your password?", - "forgot_password_link": "reset_password.sql", - "remember_me_text": "Remember me", - "footer_md": "Don''t have an account? [Register here](register.sql)", - "validate": "Sign in" - } - ]' - ) - ), - ('login', 'Basic login form', JSON('[{"component": "login", "username": "Username", "password": "Password", "autofocus": false}]')); - -INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES - ('login', 'image_alt', 'Alternative text for an informative login image. Leave empty if decorative.', 'TEXT', TRUE, TRUE); diff --git a/examples/official-site/sqlpage/migrations/70_pagination.sql b/examples/official-site/sqlpage/migrations/70_pagination.sql deleted file mode 100644 index d791e3a29..000000000 --- a/examples/official-site/sqlpage/migrations/70_pagination.sql +++ /dev/null @@ -1,253 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('pagination', 'sailboat-2', ' -Navigation links to go to the first, previous, next, or last page of a dataset. -Useful when data is divided into pages, each containing a fixed number of rows. - -This component only handles the display of pagination. -**Your sql queries are responsible for filtering data** based on the page number passed as a URL parameter. - -This component is typically used in conjunction with a [table](?component=table), -[list](?component=list), or [card](?component=card) component. - -The pagination component displays navigation buttons (first, previous, next, last) customizable with text or icons. - -For large numbers of pages, an offset can limit the visible page links. - -This SQLite example uses the first page when no offset is supplied. Order by a unique key so successive pages have a stable order. -```sql -set offset = max(0, coalesce(cast($offset as integer), 0)); -select ''table'' as component; -select * from my_table order by id limit 100 offset cast($offset as integer); - -select ''pagination'' as component; -with recursive pages as ( - select 0 as offset - union all - select offset + 100 from pages - where offset + 100 < (select count(*) from my_table) -) -select - (offset/100+1) as contents, - sqlpage.link(sqlpage.path(), json_object(''offset'', offset)) as link, - offset = cast($offset as integer) as active -from pages; -``` - -For more advanced usage, the [pagination guide](blog.sql?post=How+to+use+the+pagination+component) provides a complete tutorial. -', '0.40.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'pagination', * FROM (VALUES - -- Top-level parameters - ('first_link','A target URL to which the user should be directed to get to the first page. If none, the link is not displayed.','URL',TRUE,TRUE), - ('previous_link','A target URL to which the user should be directed to get to the previous page. If none, the link is not displayed.','URL',TRUE,TRUE), - ('next_link','A target URL to which the user should be directed to get to the next page. If none, the link is not displayed.','URL',TRUE,TRUE), - ('last_link','A target URL to which the user should be directed to get to the last page. If none, the link is not displayed.','URL',TRUE,TRUE), - ('first_title','The text displayed on the button to go to the first page.','TEXT',TRUE,TRUE), - ('previous_title','The text displayed on the button to go to the previous page.','TEXT',TRUE,TRUE), - ('next_title','The text displayed on the button to go to the next page.','TEXT',TRUE,TRUE), - ('last_title','The text displayed on the button to go to the last page.','TEXT',TRUE,TRUE), - ('first_disabled','disables the button to go to the first page.','BOOLEAN',TRUE,TRUE), - ('previous_disabled','disables the button to go to the previous page.','BOOLEAN',TRUE,TRUE), - ('next_disabled','Disables the button to go to the next page.','BOOLEAN',TRUE,TRUE), - ('last_disabled','disables the button to go to the last page.','BOOLEAN',TRUE,TRUE), - ('outline','Whether to use outline version of the pagination.','BOOLEAN',TRUE,TRUE), - ('circle','Whether to use circle version of the pagination.','BOOLEAN',TRUE,TRUE), - -- Item-level parameters (for each page) - ('contents','Page number.','INTEGER',FALSE,FALSE), - ('link','A target URL to which the user should be redirected to view the requested page of data.','URL',FALSE,TRUE), - ('offset','Whether to use offset to show only a few pages at a time. Usefull if the count of pages is too large. Defaults to false','BOOLEAN',FALSE,TRUE), - ('active','Whether the link is active or not. Defaults to false.','BOOLEAN',FALSE,TRUE) -) x; - - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'pagination', - 'This is an extremely simple example of a pagination component that displays only the page numbers, with the first page being the current page.', - JSON( - '[ - { - "component": "pagination" - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'The ouline style adds a rectangular border to each navigation link.', - JSON( - '[ - { - "component": "pagination", - "outline": true - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'The circle style adds a circular border to each navigation link.', - JSON( - '[ - { - "component": "pagination", - "circle": true - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'The following example implements navigation links that can be enabled or disabled as needed. Since a navigation link does not appear if no link is assigned to it, you must always assign a link to display it as disabled.', - JSON( - '[ - { - "component": "pagination", - "first_link": "?component=pagination", - "first_disabled": true, - "previous_link": "?component=pagination", - "previous_disabled": true, - "next_link": "#?page=2", - "last_link": "#?page=3" - - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'Instead of using icons, you can apply text to the navigation links.', - JSON( - '[ - { - "component": "pagination", - "first_title": "First", - "last_title": "Last", - "previous_title": "Previous", - "next_title": "Next", - "first_link": "?component=pagination", - "first_disabled": true, - "previous_link": "?component=pagination", - "previous_disabled": true, - "next_link": "#?page=2", - "last_link": "#?page=3" - - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'If you have a large number of pages to display, you can use an offset to represent a group of pages.', - JSON( - '[ - { - "component": "pagination", - "first_link": "#?page=1", - "previous_link": "#?page=3", - "next_link": "#?page=4", - "last_link": "#?page=99" - - }, - { - "contents": 1, - "link": "?component=pagination&page=1" - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - }, - { - "contents": 4, - "link": "?component=pagination&page=4", - "active": true - }, - { - "contents": 5, - "link": "?component=pagination&page=5" - }, - { - "contents": 6, - "link": "?component=pagination&page=6" - }, - { - "offset": true - }, - { - "contents": 99, - "link": "?component=pagination&page=99" - }, - ]' - ) - ); - \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/76_toast.sql b/examples/official-site/sqlpage/migrations/76_toast.sql deleted file mode 100644 index 4afc43fbd..000000000 --- a/examples/official-site/sqlpage/migrations/76_toast.sql +++ /dev/null @@ -1,48 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('toast', 'notification', ' -Displays a brief notification above the page. Each top-level `toast` row creates one notification, and consecutive toasts at the same position are queued in a shared stack. - -Ordinary notifications use `role="status"` and `aria-live="polite"`. Colored variants retain a readable contrasting foreground. Automatic dismissal and the manual close control are configured independently.', '0.46.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'toast', * FROM (VALUES - ('title', 'Optional notification heading.', 'TEXT', TRUE, TRUE), - ('description', 'Escaped plain-text body. This is used only when `description_md` is not supplied.', 'TEXT', TRUE, TRUE), - ('description_md', 'Rich-text alternative to `description`, rendered as Markdown. When both properties are supplied, `description_md` takes precedence.', 'TEXT', TRUE, TRUE), - ('icon', 'Optional [Tabler icon](https://tabler.io/icons) name.', 'ICON', TRUE, TRUE), - ('color', 'Optional Tabler color. The default is the neutral toast appearance; colored variants use the matching contrasting foreground utility.', 'COLOR', TRUE, TRUE), - ('dismissible', 'Whether to render an accessible manual close button. Defaults to true and is independent of automatic dismissal.', 'BOOLEAN', TRUE, TRUE), - ('duration', 'Automatic dismissal delay in milliseconds. Defaults to 5000. Set to 0 to keep the toast visible until manually dismissed (when `dismissible` is true) or the page is left.', 'INTEGER', TRUE, TRUE), - ('position', 'Screen placement: `top-start`, `top-center`, `top-end`, `bottom-start`, `bottom-center`, or `bottom-end`. Defaults to `top-end`; invalid values safely fall back to that default.', 'TEXT', TRUE, TRUE), - ('trigger', 'Optional URL fragment that opens the toast without reloading the page, with or without the leading `#`. When set, the toast does not open on page load and can be opened repeatedly by a link or button whose target is that fragment. Multiple toasts can share a trigger to open as a stack.', 'TEXT', TRUE, TRUE) - -- id and class come from 99_shared_id_class_attributes.sql -) x; - -INSERT INTO example(component, description, properties) VALUES - ('toast', 'A toast that opens when the page loads and disappears automatically after the default 5000 milliseconds.', json('[ - {"component":"toast","id":"toast-auto","title":"This is a SQLPage toast","description":"This toast will open automatically when the page loads.","icon":"check","color":"green"} - ]')), - ('toast', 'A persistent error notification that disables automatic dismissal and requires the user to activate its close button.', json('[ - {"component":"toast","id":"toast-dismissible","trigger":"persistent-error","title":"Could not save","description":"Review the highlighted fields and try again.","icon":"alert-triangle","color":"black","duration":0,"dismissible":true}, - {"component":"toast","id":"toast-nondismissible","trigger":"persistent-status","title":"Connection unavailable","description":"This persistent notification has no manual close control.","duration":0,"dismissible":false}, - {"component":"button"}, - {"title":"Show dismissible error","link":"#persistent-error","color":"red"}, - {"title":"Show non-dismissible status","link":"#persistent-status"} - ]')), - ('toast', 'A persistent rich Markdown notification. Markdown takes precedence over plain text and renders emphasis and a link as HTML, while plain-text content remains escaped.', json('[ - {"component":"toast","id":"toast-markdown","trigger":"rich-notifications","title":"Release available","description":"This fallback stays escaped","description_md":"Version **2.0** is ready. [Read the notes](https://example.com/releases).","color":"blue","duration":0}, - {"component":"toast","id":"toast-plain","trigger":"rich-notifications","description":"Plain text stays escaped","color":"white","duration":0}, - {"component":"button"}, - {"title":"Show rich notifications","link":"#rich-notifications"} - ]')), - ('toast', 'Several persistent queued notifications. Toasts with the same position share a container and stack instead of overlapping.', json('[ - {"component":"toast","id":"toast-stack-one","trigger":"queued notifications","title":"Import started","description":"Preparing records.","duration":0}, - {"component":"toast","id":"toast-stack-two","trigger":"queued notifications","title":"Import running","description":"Processing records.","duration":0}, - {"component":"toast","id":"toast-short","trigger":"queued notifications","title":"Temporary update","description":"This message closes shortly.","duration":2000}, - {"component":"button"}, - {"title":"Show queued notifications","link":"#queued notifications"} - ]')), - ('toast', 'A notification placed at the bottom center of the screen instead of the default top end.', json('[ - {"component":"toast","id":"toast-bottom-center","trigger":"bottom-notification","title":"Download ready","description":"Your export is ready.","position":"bottom-center","duration":0}, - {"component":"button"}, - {"title":"Show bottom notification","link":"#bottom-notification"} - ]')); diff --git a/examples/official-site/sqlpage/migrations/77_facet.sql b/examples/official-site/sqlpage/migrations/77_facet.sql deleted file mode 100644 index c721d2ff4..000000000 --- a/examples/official-site/sqlpage/migrations/77_facet.sql +++ /dev/null @@ -1,130 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('facet', 'filter', ' -Navigation links for filtering a dataset by a category, status, owner, or other attribute. - -This component only renders the filter navigation. **Your SQL query is responsible for filtering the data** based on the URL parameter selected by the user. - -Use it alongside a [table](?component=table), [list](?component=list), or [card](?component=card). The links use GET parameters, so the selected filter can be bookmarked and shared. - -Set `compact` to display the facets in a dropdown, which is useful for a moderate number of choices or on narrow screens. Use `selected_facet` to show the active facet in the closed dropdown. `all_link` and `all_title` add a link that clears the filter. - -The following portable pattern filters a table by category. `sqlpage.link` preserves the current page path while safely generating the URL. - -```sql -select ''table'' as component; -select title, category -from my_table -where $category is null or category = $category; - -select ''facet'' as component, - ''Category'' as description, - sqlpage.link(sqlpage.path(), json_object(''category'', null)) as all_link, - $category is null as all_active; -select category as title, - sqlpage.link(sqlpage.path(), json_object(''category'', category)) as link, - category = $category as active -from my_table -group by category -order by category; -``` -', '0.46.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'facet', * FROM (VALUES - -- Top-level parameters - ('description','The facet category label.','TEXT',TRUE,TRUE), - ('dropdown_title','Text shown on the compact-mode dropdown button when no facet is selected. Defaults to `Choose facet`.','TEXT',TRUE,TRUE), - ('selected_facet','An alias for `dropdown_title`.','TEXT',TRUE,TRUE), - ('compact','Displays the facets in a dropdown instead of links.','BOOLEAN',TRUE,TRUE), - ('center','Whether to center the facet selector','BOOLEAN',TRUE,TRUE), - ('all_link','URL that clears the filter. If omitted, no All link is displayed.','URL',TRUE,TRUE), - ('all_title','Text for the link that clears the filter. Defaults to "ALL".','TEXT',TRUE,TRUE), - ('all_active','Whether the link that clears the filter is active. Defaults to false.','BOOLEAN',TRUE,TRUE), - -- Item-level parameters (for each facet) - ('title','Facet title.','TEXT',FALSE,FALSE), - ('link','URL for the facet.','URL',FALSE,FALSE), - ('active','Whether the link is active or not. Defaults to false.','BOOLEAN',FALSE,TRUE) -) x; - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'facet', - 'A category selector with an All link. In an application, the SQL pattern above uses the chosen URL parameter to filter the displayed data.', - JSON( - '[ - { - "component": "table" - }, - { - "name": "USS Enterprise (NCC-1701)", - "class": "Constitution" - }, - { - "name": "USS Exeter (NCC-1672)", - "class": "Galaxy" - }, - { - "name": "USS Exeter (NCC-1672)", - "class": "Constitution" - }, - { - "component": "facet", - "description": "Classes", - "all_link": "?component=facet", - "all_title": "All", - "all_active": false - }, - { - "title": "Constitution", - "link": "?component=facet&class=Constitution", - "active": true - }, - { - "title": "Galaxy", - "link": "?component=facet&class=Galaxy" - } - ]' - ) - ), - ( - 'facet', - 'Compact mode displays the facet choices in a dropdown.', - JSON( - '[ - { - "component": "table" - }, - { - "name": "USS Enterprise (NCC-1701)", - "class": "Constitution" - }, - { - "name": "USS Defiant (NCC-1764)", - "class": "Constitution" - }, - { - "name": "USS Exeter (NCC-1672)", - "class": "Constitution" - }, - { - "component": "facet", - "description": "Classes", - "all_link": "?component=facet", - "all_title": "All", - "all_active": false, - "compact": true, - "dropdown_title": "Select a spaceship class", - "selected_facet": "Constitution" - }, - { - "title": "Constitution", - "link": "?component=facet&class=Constitution", - "active": true - }, - { - "title": "Galaxy", - "link": "?component=facet&class=Galaxy" - } - ]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/80_status_bar.sql b/examples/official-site/sqlpage/migrations/80_status_bar.sql deleted file mode 100644 index 9a4ce68d6..000000000 --- a/examples/official-site/sqlpage/migrations/80_status_bar.sql +++ /dev/null @@ -1,23 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('status_bar', 'layout-bottombar', - 'Display short status messages and links in a single horizontal bar. Each row adds one segment. When there are several segments, the last one aligns to the far edge. If the segments do not all fit, scroll the bar horizontally to see the rest.', - '0.49.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) -SELECT 'status_bar', * FROM (VALUES - ('fixed', 'Keep the bar at the bottom of the screen while the page scrolls. Defaults to true. A fixed bar overlays page content, so leave space below your last item if needed. Set to false to place the bar in the page where the SQL appears.', 'BOOLEAN', TRUE, TRUE), - ('label', 'Accessible name for the bar. Defaults to "Status bar".', 'TEXT', TRUE, TRUE), - ('title', 'Text displayed in the segment.', 'TEXT', FALSE, TRUE), - ('icon', 'Icon displayed before the text.', 'ICON', FALSE, TRUE), - ('color', 'Color of the segment text and icon.', 'COLOR', FALSE, TRUE), - ('tooltip', 'Text shown when hovering over the segment or focusing its link. For an icon without a title, supply a tooltip to give the segment an accessible name.', 'TEXT', FALSE, TRUE), - ('link', 'URL to open when the segment is clicked.', 'URL', FALSE, TRUE) -) p; - -INSERT INTO example(component, description, properties) VALUES - ('status_bar', 'A query workspace shows the database connection, row count, and a link to the function reference. Omit `fixed` to pin this bar to the bottom of the screen.', json('[ - {"component":"status_bar","label":"Query status","fixed":false}, - {"title":"Connected","icon":"database","color":"green","tooltip":"Connected to the reporting database"}, - {"title":"24 rows"}, - {"title":"SQL functions","icon":"book","link":"/functions.sql"} - ]')); diff --git a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql b/examples/official-site/sqlpage/migrations/82_reference_catalog.sql index 3f5be829d..81689e61c 100644 --- a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql +++ b/examples/official-site/sqlpage/migrations/82_reference_catalog.sql @@ -1,10 +1,3 @@ --- Short catalog descriptions help readers choose a page before opening its full reference. -CREATE TABLE reference_category ( - id TEXT PRIMARY KEY, - title TEXT NOT NULL, - sort_order INTEGER NOT NULL -); - INSERT INTO reference_category (id, title, sort_order) VALUES ('display-data', 'Display data', 1), ('forms-and-feedback', 'Forms and feedback', 2), @@ -19,8 +12,6 @@ INSERT INTO reference_category (id, title, sort_order) VALUES ('external-services', 'External services', 5), ('server-and-runtime', 'Server and runtime', 6); -ALTER TABLE component ADD COLUMN catalog_category TEXT REFERENCES reference_category(id); -ALTER TABLE component ADD COLUMN catalog_summary TEXT; ALTER TABLE sqlpage_functions ADD COLUMN catalog_category TEXT REFERENCES reference_category(id); ALTER TABLE sqlpage_functions ADD COLUMN catalog_summary TEXT; ALTER TABLE sqlpage_function_parameters ADD COLUMN optional BOOLEAN NOT NULL DEFAULT FALSE; @@ -37,59 +28,51 @@ UPDATE sqlpage_function_parameters SET optional = TRUE WHERE ("function", name) ('variables', 'method') ); -WITH copy(name, category, summary) AS (VALUES - ('big_number', 'display-data', 'Highlight a metric with a trend or progress indicator.'), - ('card', 'display-data', 'Arrange records in cards with images, links, or embedded content.'), - ('carousel', 'display-data', 'Show a slideshow of images with optional captions and controls.'), - ('chart', 'display-data', 'Plot query results as line, area, bar, or pie charts.'), - ('datagrid', 'display-data', 'Lay out labeled values in a compact grid.'), - ('list', 'display-data', 'Present rows as a vertical list with optional links and icons.'), - ('map', 'display-data', 'Plot locations and geographic shapes on an interactive map.'), - ('table', 'display-data', 'Turn query results into a sortable, searchable table.'), - ('timeline', 'display-data', 'Arrange events along a vertical timeline.'), - ('tracking', 'display-data', 'Show a sequence of activity or status changes as colored segments.'), - - ('alert', 'forms-and-feedback', 'Draw attention to a message with a color and an icon.'), - ('button', 'forms-and-feedback', 'Follow a link, download a file, or submit a form.'), - ('empty_state', 'forms-and-feedback', 'Explain an empty view and offer the reader a next step.'), - ('form', 'forms-and-feedback', 'Collect input with text fields, file uploads, and other controls.'), - ('login', 'forms-and-feedback', 'Display a sign-in form for a username and password.'), - ('modal', 'forms-and-feedback', 'Open a dialog over the page for details, forms, or media.'), - ('toast', 'forms-and-feedback', 'Show a brief notification above the page.'), - - ('breadcrumb', 'navigation', 'Link the current page to its parent pages.'), - ('facet', 'navigation', 'Let readers choose filters for a dataset.'), - ('pagination', 'navigation', 'Link to other pages of a query result.'), - ('status_bar', 'navigation', 'Show status messages and links in a horizontal bar.'), - ('steps', 'navigation', 'Mark progress through the stages of a task.'), - ('tab', 'navigation', 'Switch between related pages using labeled tabs.'), - - ('code', 'page-layout', 'Display source code with syntax highlighting.'), - ('columns', 'page-layout', 'Compare plans, features, or options in side-by-side cards.'), - ('divider', 'page-layout', 'Separate sections with a horizontal rule.'), - ('foldable', 'page-layout', 'Let readers expand individual sections to see their contents.'), - ('hero', 'page-layout', 'Introduce a page with a headline, media, and a call to action.'), - ('html', 'page-layout', 'Insert your own HTML markup into the page.'), - ('shell', 'page-layout', 'Set the page layout, navigation, branding, and footer.'), - ('text', 'page-layout', 'Write paragraphs using plain text or Markdown.'), - ('title', 'page-layout', 'Add a heading and choose its level.'), - - ('cookie', 'http-responses', 'Set a cookie in the visitor''s browser.'), - ('csv', 'http-responses', 'Export query rows as a downloadable CSV file.'), - ('download', 'http-responses', 'Send a file directly to the visitor.'), - ('http_header', 'http-responses', 'Set response headers for caching, content types, and more.'), - ('json', 'http-responses', 'Return query results as JSON for an API.'), - ('redirect', 'http-responses', 'Send the visitor to another URL.'), - ('rss', 'http-responses', 'Publish an RSS feed from query results.'), - ('status_code', 'http-responses', 'Set the HTTP status code returned by a page.'), - - ('authentication', 'server-logic', 'Restrict access by checking a password against a stored hash.'), - ('debug', 'server-logic', 'Inspect the values passed to a component as JSON.'), - ('dynamic', 'server-logic', 'Render SQLPage components described by JSON data.'), - ('log', 'server-logic', 'Write a message to the SQLPage server log.') -) -UPDATE component SET (catalog_category, catalog_summary) = (copy.category, copy.summary) -FROM copy WHERE component.name = copy.name; +INSERT INTO component (name, icon, introduced_in_version, catalog_category) VALUES + ('alert', 'alert-triangle', NULL, 'forms-and-feedback'), + ('authentication', 'lock', '0.7.2', 'server-logic'), + ('big_number', 'chart-area', '0.28.0', 'display-data'), + ('breadcrumb', 'dots', '0.18.0', 'navigation'), + ('button', 'hand-click', '0.14.0', 'forms-and-feedback'), + ('card', 'credit-card', NULL, 'display-data'), + ('carousel', 'carousel-horizontal', '0.18.3', 'display-data'), + ('chart', 'timeline', NULL, 'display-data'), + ('code', 'code', '0.19.0', 'page-layout'), + ('columns', 'columns', '0.29.0', 'page-layout'), + ('cookie', 'cookie', NULL, 'http-responses'), + ('csv', 'download', NULL, 'http-responses'), + ('datagrid', 'grid-dots', NULL, 'display-data'), + ('debug', 'bug', NULL, 'server-logic'), + ('divider', 'separator', '0.18.0', 'page-layout'), + ('download', 'download', '0.37.0', 'http-responses'), + ('dynamic', 'repeat', NULL, 'server-logic'), + ('empty_state', 'info-circle', '0.35.0', 'forms-and-feedback'), + ('facet', 'filter', '0.46.0', 'navigation'), + ('foldable', 'chevrons-down', '0.29.0', 'page-layout'), + ('form', 'cursor-text', NULL, 'forms-and-feedback'), + ('hero', 'home', NULL, 'page-layout'), + ('html', 'html', '0.25.0', 'page-layout'), + ('http_header', 'world-www', NULL, 'http-responses'), + ('json', 'code', '0.9.0', 'http-responses'), + ('list', 'list', NULL, 'display-data'), + ('log', 'logs', '0.37.1', 'server-logic'), + ('login', 'password-user', '0.39.0', 'forms-and-feedback'), + ('map', 'map', '0.8.0', 'display-data'), + ('modal', 'app-window', '0.36.0', 'forms-and-feedback'), + ('pagination', 'sailboat-2', '0.40.0', 'navigation'), + ('redirect', 'arrow-right', '0.7.2', 'http-responses'), + ('rss', 'rss', '0.20.0', 'http-responses'), + ('shell', 'layout-navbar', NULL, 'page-layout'), + ('status_bar', 'layout-bottombar', '0.49.0', 'navigation'), + ('status_code', 'error-404', NULL, 'http-responses'), + ('steps', 'dots-circle-horizontal', NULL, 'navigation'), + ('tab', 'row-insert-bottom', '0.9.5', 'navigation'), + ('table', 'table', NULL, 'display-data'), + ('text', 'align-left', NULL, 'page-layout'), + ('timeline', 'git-commit', '0.13.0', 'display-data'), + ('title', 'letter-case-upper', '0.19.0', 'page-layout'), + ('toast', 'notification', '0.46.0', 'forms-and-feedback'), + ('tracking', 'timeline-event-text', '0.18.0', 'display-data'); WITH copy(name, category, summary) AS (VALUES ('client_ip', 'request-data', 'Get the IP address of the client making the request.'), @@ -170,7 +153,7 @@ CREATE VIEW reference_parameter AS WITH fields AS ( SELECT 'component' AS kind, component AS entry, CASE WHEN top_level THEN 'top-level-parameters' ELSE 'row-level-parameters' END AS section, - name, type, optional, coalesce(description_md, description) AS description_md, optional AS position + name, type, optional, description_md, optional AS position FROM parameter UNION ALL SELECT 'function', "function", 'parameters', name, type, optional, description_md, "index" diff --git a/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql b/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql deleted file mode 100644 index 712cb683f..000000000 --- a/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql +++ /dev/null @@ -1,87 +0,0 @@ --- Every component whose `id` and `class` properties behave in the ordinary way --- is documented from the lists below, so that the wording stays identical --- across components and so that the (component, top_level, name) primary key --- of `parameter` is not violated. --- --- A handful of components deliberately document `id` or `class` in their own --- migration instead, because the generic wording would be wrong for them: --- `modal` (`id` is required, and is what a button targets), `form` (`id` is --- what an outside submit button references), `foldable` (top level and item --- level mean different things) and `button` (`id` lands on each button, not on --- the container). Do not duplicate those here. - -INSERT INTO parameter(component, top_level, name, description, type, optional) -SELECT *, 'id', 'id attribute added to the container in HTML. It can be used to target this item through css or for scrolling to this item through links (use "#id" in link url).', 'TEXT', TRUE -FROM (VALUES - ('alert', TRUE), - ('big_number', TRUE), - ('big_number', FALSE), - ('breadcrumb', TRUE), - ('card', FALSE), - ('chart', TRUE), - ('code', TRUE), - ('csv', TRUE), - ('datagrid', TRUE), - ('datagrid', FALSE), - ('empty_state', TRUE), - ('hero', TRUE), - ('list', TRUE), - ('list', FALSE), - ('map', TRUE), - ('status_bar', TRUE), - ('tab', TRUE), - ('tab', FALSE), - ('table', TRUE), - ('timeline', TRUE), - ('timeline', FALSE), - ('title', TRUE), - ('toast', TRUE), - ('tracking', TRUE), - ('text', TRUE), - ('carousel', TRUE), - ('login', TRUE), - ('pagination', TRUE), - ('facet', TRUE) -); - -INSERT INTO parameter(component, top_level, name, description, type, optional) -SELECT *, 'id', 'id attribute injected as an anchor in HTML. It can be used for scrolling to this item through links (use "#id" in link url). Added in v0.18.0.', 'TEXT', TRUE -FROM (VALUES - ('steps', TRUE) -); - -INSERT INTO parameter(component, top_level, name, description, type, optional) -SELECT *, 'class', 'class attribute added to the container in HTML. It can be used to apply custom styling to this item through css. Added in v0.18.0.', 'TEXT', TRUE -FROM (VALUES - ('alert', TRUE), - ('big_number', TRUE), - ('big_number', FALSE), - ('breadcrumb', TRUE), - ('button', TRUE), - ('card', TRUE), - ('card', FALSE), - ('chart', TRUE), - ('code', TRUE), - ('csv', TRUE), - ('datagrid', TRUE), - ('divider', TRUE), - ('empty_state', TRUE), - ('form', TRUE), - ('list', TRUE), - ('list', FALSE), - ('map', TRUE), - ('status_bar', TRUE), - ('status_bar', FALSE), - ('tab', TRUE), - ('tab', FALSE), - ('table', TRUE), - ('timeline', TRUE), - ('timeline', FALSE), - ('title', TRUE), - ('toast', TRUE), - ('tracking', TRUE), - ('carousel', TRUE), - ('login', TRUE), - ('pagination', TRUE), - ('facet', TRUE) -); diff --git a/examples/official-site/sqlpage/sqlpage.yaml b/examples/official-site/sqlpage/sqlpage.yaml index 262527f3a..3b4235c78 100644 --- a/examples/official-site/sqlpage/sqlpage.yaml +++ b/examples/official-site/sqlpage/sqlpage.yaml @@ -1,6 +1,3 @@ -# The documentation site is fully static, so we don't need to persist any data. -database_url: "sqlite::memory:?cache=shared" - # We have a file upload example, and would like to limit the size of the uploaded files max_uploaded_file_size: 256000 diff --git a/examples/official-site/sqlpage/templates/docs-example.handlebars b/examples/official-site/sqlpage/templates/docs-example.handlebars index 4d637c5e2..1d6428117 100644 --- a/examples/official-site/sqlpage/templates/docs-example.handlebars +++ b/examples/official-site/sqlpage/templates/docs-example.handlebars @@ -6,7 +6,7 @@ {{else}}
-

{{#if title}}{{title}}{{else}}Example {{number}}{{/if}}

+

{{title}}

{{#if description_md}}
{{{markdown description_md}}}
{{/if}} {{#if preview}}
{{/if}} {{#if source}} diff --git a/examples/official-site/test.hurl b/examples/official-site/test.hurl index 6cc606187..37cf68ac5 100644 --- a/examples/official-site/test.hurl +++ b/examples/official-site/test.hurl @@ -32,6 +32,20 @@ body contains "The form component" body contains "Building forms in SQL" body not contains "An error occurred" +GET http://localhost:8080/component.sql?component=alert +HTTP 200 +[Asserts] +xpath "normalize-space(//*[@id='example-4']/h3)" == "A dismissible alert" +xpath "normalize-space(//*[@id='example-4']//p/code)" == "close_label" + +GET http://localhost:8080/reference/components/rss/01-sqlpage-news-feed.standalone.sql +HTTP 200 +[Asserts] +header "Content-Type" == "application/rss+xml" +xpath "string(/rss/@version)" == "2.0" +xpath "string(/rss/channel/title)" == "SQLPage blog" +xpath "string(/rss/channel/item/title)" == "Hello everyone !" + GET http://localhost:8080/component.sql?component=unknowncomponent HTTP 302 [Asserts] @@ -99,8 +113,8 @@ GET http://localhost:8080/component.sql?component=list HTTP 200 [Asserts] xpath "//*[@id='top-level-parameters-empty_description']//dt//a[@href='#top-level-parameters-empty_description']" count == 1 -xpath "//*[@id='row-level-parameters-title']" count == 1 -xpath "//*[@id='top-level-parameters-title']" count == 1 +xpath "normalize-space(//*[@id='row-level-parameters-title']/dt)" == "title TEXT Required" +xpath "normalize-space(//*[@id='top-level-parameters-title']/dt)" == "title TEXT" GET http://localhost:8080/search.sql?search=migrations HTTP 200 diff --git a/package.json b/package.json index 1c6e91300..510907eff 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,8 @@ "typecheck": "tsc && tsc -p tests/js && tsc -p tests/end-to-end", "format": "biome format --write .", "fix": "biome check --fix --unsafe .", - "presite:test": "npm run site:build", - "site:build": "node scripts/site-build.mjs", - "site:test": "node --test tests/js/component_documentation.checks.ts", + "site:build": "cargo run --locked --example build-site", + "site:test": "cargo test --locked --example build-site", "site": "npm run build && npm run site:build && cd target/official-site && cargo run --locked --manifest-path ../../Cargo.toml" }, "repository": { diff --git a/scripts/official-site/main.rs b/scripts/official-site/main.rs new file mode 100644 index 000000000..0b335a184 --- /dev/null +++ b/scripts/official-site/main.rs @@ -0,0 +1,279 @@ +mod parameters; + +use anyhow::{Context, Result, ensure}; +use markdown::{ParseOptions, mdast::Node}; +use parameters::Document; +use sqlx::connection::{ConnectOptions, Connection}; +use sqlx::executor::Executor; +use sqlx::migrate::Migrator; +use sqlx::query::query; +use sqlx::query_as::query_as; +use sqlx::query_scalar::query_scalar; +use sqlx::sqlite::{SqliteConnectOptions, SqliteConnection}; +use std::fs; +use std::path::Path; +use walkdir::WalkDir; + +const COMPONENTS: &str = "reference/components"; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<()> { + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let site = root.join("examples/official-site"); + let target = root.join("target"); + fs::create_dir_all(&target)?; + let staging = tempfile::tempdir_in(&target)?; + let output = staging.path().join("next"); + fs::create_dir_all(output.join("sqlpage"))?; + fs::copy( + root.join("configuration.md"), + output.join("configuration.md"), + )?; + let mut db = SqliteConnectOptions::new() + .filename(output.join("sqlpage/sqlpage.db")) + .create_if_missing(true) + .connect() + .await?; + Migrator::new(site.join("sqlpage/migrations")) + .await? + .run(&mut db) + .await?; + let mut tx = db.begin().await?; + + for entry in fs::read_dir(root.join("sqlpage/templates"))? { + let path = entry?.path(); + let Some(name) = basename(&path)?.strip_suffix(".handlebars") else { + continue; + }; + let public = !matches!(name, "default" | "error" | "shell-empty"); + let doc = parameters::template(name, &read(&path)?, public) + .with_context(|| path.display().to_string())?; + if public { + store_doc(&mut tx, name, doc) + .await + .with_context(|| path.display().to_string())?; + } + } + let example_count = stage_site(&site, &output, &mut tx).await?; + let missing: Option = + query_scalar("SELECT group_concat(name, ', ') FROM component WHERE description = ''") + .fetch_one(&mut *tx) + .await?; + if let Some(names) = missing { + anyhow::bail!("Missing component documentation for {names}"); + } + tx.execute(read(&site.join("reference/search-index.sql"))?.as_str()) + .await + .context("Building the documentation search index")?; + verify_examples(&mut tx, &output, example_count).await?; + tx.commit().await?; + db.close().await?; + + let published = target.join("official-site"); + let previous = staging.path().join("previous"); + match fs::rename(&published, &previous) { + Err(err) if err.kind() != std::io::ErrorKind::NotFound => return Err(err.into()), + _ => {} + } + if let Err(err) = fs::rename(output, &published) { + if !published.exists() && previous.exists() { + fs::rename(previous, &published)?; + } + return Err(err.into()); + } + println!("Prepared {}", published.display()); + Ok(()) +} + +#[test] +fn builds_official_site() -> Result<()> { + main() +} + +async fn stage_site(source: &Path, output: &Path, db: &mut SqliteConnection) -> Result { + let mut example_count = 0; + let excluded = [ + "README.md", + "docker-compose.yml", + "test.hurl", + "reference/search-index.sql", + "sqlpage/migrations", + "sqlpage/https", + "sqlpage/sqlpage.db", + "sqlpage/sqlpage.db-wal", + "sqlpage/sqlpage.db-shm", + "sqlpage/sqlpage.db-journal", + ]; + let entries = WalkDir::new(source) + .sort_by_file_name() + .into_iter() + .filter_entry(|entry| { + let relative = entry.path().strip_prefix(source).unwrap(); + !excluded.iter().any(|name| relative == Path::new(name)) + }); + for entry in entries { + let entry = entry?; + let path = entry.path(); + let relative = path.strip_prefix(source)?; + let destination = output.join(relative); + if entry.file_type().is_dir() { + fs::create_dir_all(destination)?; + } else if let Ok(example) = relative.strip_prefix(COMPONENTS) { + let name = example + .parent() + .and_then(Path::to_str) + .context("Expected a component directory")?; + let file = basename(example)?; + let text = read(path)?; + if file == "README.md" { + let doc = + parameters::document(&text).with_context(|| path.display().to_string())?; + store_doc(db, name, doc).await + } else { + example_count += 1; + store_example(db, &destination, name, file, &text).await + } + .with_context(|| path.display().to_string())?; + } else { + fs::copy(path, destination).with_context(|| path.display().to_string())?; + } + } + Ok(example_count) +} + +async fn verify_examples(db: &mut SqliteConnection, output: &Path, expected: usize) -> Result<()> { + let indexed: Vec<(Option, Option)> = query_as( + "SELECT e.path, e.source FROM example e JOIN documentation_fts f + ON f.page = '/component.sql?component=' || e.component AND f.fragment = 'example-' || e.number + GROUP BY e.component, e.number HAVING count(*) = 1 + AND f.title = e.title AND f.description = e.description AND f.example_source IS e.source", + ) + .fetch_all(db) + .await?; + ensure!( + indexed.len() == expected, + "Expected {expected} indexed examples, found {}", + indexed.len() + ); + for (path, sql) in indexed.into_iter().filter_map(|(path, sql)| path.zip(sql)) { + ensure!( + fs::read_to_string(output.join(&path))? == sql, + "Published SQL differs from the indexed source for {path}" + ); + } + Ok(()) +} + +fn basename(path: &Path) -> Result<&str> { + path.file_name() + .and_then(std::ffi::OsStr::to_str) + .with_context(|| format!("Expected a UTF-8 filename in {}", path.display())) +} + +fn read(path: &Path) -> Result { + Ok(fs::read_to_string(path) + .with_context(|| path.display().to_string())? + .replace("\r\n", "\n")) +} + +async fn store_doc(db: &mut SqliteConnection, name: &str, doc: Document) -> Result<()> { + let updated = query( + "UPDATE component SET description = ?, catalog_summary = ? WHERE name = ? AND description = ''", + ) + .bind(doc.overview) + .bind(doc.summary) + .bind(name) + .execute(&mut *db) + .await?; + ensure!( + updated.rows_affected() == 1, + "Unknown or already documented component {name}" + ); + for field in doc.fields { + query( + "INSERT INTO parameter (component, top_level, name, type, optional, description_md) + VALUES (?, ?, ?, ?, ?, ?)", + ) + .bind(name) + .bind(field.scope == parameters::Scope::Top) + .bind(&field.name) + .bind(field.kind) + .bind(field.optional) + .bind(field.description) + .execute(&mut *db) + .await + .with_context(|| format!("Invalid parameter {name}.{}", field.name))?; + } + Ok(()) +} + +async fn store_example( + db: &mut SqliteConnection, + destination: &Path, + name: &str, + file: &str, + text: &str, +) -> Result<()> { + static FILENAME: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r"^([0-9]{2,})-[a-z0-9]+(?:-[a-z0-9]+)*\.(.+)$").unwrap() + }); + let (_, [digits, extension]) = FILENAME + .captures(file) + .context("Expected a numbered filename such as 01-basic-list.sql")? + .extract(); + let number: i64 = digits.parse()?; + let (title, description, source) = match extension { + "md" => { + let tree = + markdown::to_mdast(text, &ParseOptions::gfm()).map_err(anyhow::Error::msg)?; + let title = tree + .children() + .and_then(|nodes| nodes.first()) + .context("Missing walkthrough title")?; + ensure!( + matches!(title, Node::Heading(h) if h.depth == 1), + "Expected a level-one Markdown title" + ); + let body = text[title.position().unwrap().end.offset..].trim(); + ensure!(!body.is_empty(), "Expected a walkthrough below the title"); + (title.to_string(), body, None) + } + "sql" | "standalone.sql" => { + let (header, body) = text + .strip_prefix("/*") + .and_then(|s| s.split_once("*/")) + .context("Expected a leading SQL title comment")?; + let (title, description) = header + .trim() + .split_once('\n') + .unwrap_or((header.trim(), "")); + ensure!( + !title.is_empty() && !body.trim().is_empty(), + "Expected a title and SQL body" + ); + ( + title.to_owned(), + description.trim(), + Some(body.strip_prefix('\n').unwrap_or(body)), + ) + } + _ => anyhow::bail!("Unknown example extension .{extension}"), + }; + let path = source.map(|_| format!("{COMPONENTS}/{name}/{file}")); + if let Some(sql) = source { + fs::write(destination, sql)?; + } + query( + "INSERT INTO example (component, number, title, description, path, source) + VALUES (?, ?, ?, ?, ?, ?)", + ) + .bind(name) + .bind(number) + .bind(title) + .bind(description) + .bind(path) + .bind(source) + .execute(db) + .await?; + Ok(()) +} diff --git a/scripts/official-site/parameters.rs b/scripts/official-site/parameters.rs new file mode 100644 index 000000000..e6ea29208 --- /dev/null +++ b/scripts/official-site/parameters.rs @@ -0,0 +1,302 @@ +use anyhow::{Context, Result, bail, ensure}; +use handlebars::{ + Path, PathSeg, Template, + template::{Parameter, TemplateElement as Element}, +}; +use markdown::{ParseOptions, mdast::Node}; +use std::collections::BTreeSet; + +pub(super) struct Document { + pub(super) overview: String, + pub(super) summary: String, + pub(super) fields: Vec, +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub(super) enum Scope { + Top, + Row, + Nested, +} + +pub(super) struct Field { + pub(super) scope: Scope, + pub(super) name: String, + pub(super) kind: String, + pub(super) optional: bool, + pub(super) description: String, +} + +pub(super) fn template(component: &str, source: &str, verify: bool) -> Result { + let template = Template::compile_with_name(source, component.to_owned())?; + let Some(Element::Comment(markdown)) = template.elements.first() else { + bail!("Expected a leading documentation comment"); + }; + let doc = document(markdown)?; + if verify { + verify_reads(component, &template, &doc.fields)?; + } + Ok(doc) +} + +pub(super) fn document(markdown: &str) -> Result { + let tree = + markdown::to_mdast(markdown, &ParseOptions::gfm()).expect("GFM has no syntax errors"); + let nodes = tree.children().expect("Markdown parses to a root node"); + let mut overview_end = markdown.len(); + let mut summary = None; + let mut scope = None; + let mut fields = Vec::new(); + for node in nodes { + let span = node.position().expect("parsed Markdown has positions"); + let heading = match node { + Node::Heading(h) if h.depth == 2 => match node.to_string().as_str() { + "Top-level parameters" => Some(Scope::Top), + "Row-level parameters" => Some(Scope::Row), + _ => None, + }, + _ => None, + }; + if heading.is_some() { + scope = heading; + overview_end = overview_end.min(span.start.offset); + continue; + } + match (node, scope) { + (Node::Paragraph(_), None) if summary.is_none() => summary = Some(node.to_string()), + (Node::List(list), Some(scope)) if !list.ordered => { + for item in &list.children { + fields.push(field(markdown, item, scope)?); + } + } + (_, Some(_)) => bail!("Expected an unordered list under the parameter heading"), + _ => {} + } + } + let overview = markdown[..overview_end].trim_matches('\n').to_owned(); + let summary = summary + .filter(|text| !text.trim().is_empty()) + .context("Expected an overview paragraph")? + .replace('\n', " "); + Ok(Document { + overview, + summary, + fields, + }) +} + +fn field(markdown: &str, item: &Node, scope: Scope) -> Result { + let first = item.children().and_then(|blocks| blocks.first()); + let Some(bold @ Node::Strong(_)) = first + .and_then(Node::children) + .and_then(|nodes| nodes.first()) + else { + bail!("Expected a bold parameter name at the start of the item"); + }; + let name = bold.to_string(); + ensure!( + !name.is_empty() + && name + .bytes() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-')), + "Invalid parameter name `{name}`" + ); + let span = bold.position().unwrap(); + // Slice the Markdown source to preserve links, escapes, nested lists and code fences. + let rest = &markdown[span.end.offset..item.position().unwrap().end.offset]; + let (header, continuation) = rest.split_once('\n').unwrap_or((rest, "")); + let (kind, suffix) = header + .trim_start() + .strip_prefix('(') + .and_then(|s| s.split_once(')')) + .with_context(|| format!("Expected a parenthesized type after `{name}`"))?; + let first = if suffix.trim_end().is_empty() { + "" + } else { + suffix + .strip_prefix(':') + .context("Expected `:` before the description")? + .trim_start() + }; + let indentation = " ".repeat(span.start.column - 1); + let description = std::iter::once(first) + .filter(|line| !line.is_empty()) + .chain( + continuation + .lines() + .map(|line| line.strip_prefix(&indentation).unwrap_or(line)), + ) + .collect::>() + .join("\n"); + let (kind, required) = kind + .strip_suffix(", required") + .map_or((kind, false), |kind| (kind, true)); + let description = match (name.as_str(), description.trim_end()) { + ("id", "") => { + "id attribute added to the container in HTML. It can be used to target this item through css or for scrolling to this item through links (use \"#id\" in link url)." + } + ("class", "") => { + "class attribute added to the container in HTML. It can be used to apply custom styling to this item through css. Added in v0.18.0." + } + (_, "") => bail!("Missing description for `{name}`"), + (_, description) => description, + }; + Ok(Field { + scope, + name, + kind: kind.into(), + optional: !required, + description: description.into(), + }) +} + +type Reads<'a> = BTreeSet<(Scope, &'a str)>; + +fn verify_reads(component: &str, template: &Template, fields: &[Field]) -> Result<()> { + let mut reads = Reads::new(); + walk(&template.elements, &mut vec![Scope::Top], &mut reads, true); + let documented: Reads<'_> = fields + .iter() + .map(|field| (field.scope, field.name.as_str())) + .collect(); + // shell.target is documented separately as a sub-property of menu_item. + if component == "shell" && documented.contains(&(Scope::Top, "target")) { + reads.insert((Scope::Top, "target")); + } + let missing: Vec<_> = reads.difference(&documented).collect(); + let unused: Vec<_> = documented.difference(&reads).collect(); + ensure!( + missing.is_empty() && unused.is_empty(), + "Undocumented parameters: {missing:?}; unread parameters: {unused:?}" + ); + Ok(()) +} + +fn walk<'a>( + elements: &'a [Element], + scopes: &mut Vec, + reads: &mut Reads<'a>, + mut top: bool, +) { + for element in elements { + let (params, hash) = match element { + Element::Expression(helper) + | Element::HtmlExpression(helper) + | Element::HelperBlock(helper) => { + // The first direct each_row block is split out by SQLPage's renderer. + let scope = match helper.name.as_name() { + Some("each_row") if top && helper.block => { + top = false; + Some(Scope::Row) + } + Some("each" | "with") => Some(Scope::Nested), + _ => None, + }; + if !helper.block + && helper.params.is_empty() + && helper.hash.is_empty() + && helper.name.as_name() != Some("flush_delayed") + { + read(&helper.name, scopes, reads); + } + if let Some(inverse) = &helper.inverse { + walk(&inverse.elements, scopes, reads, false); + } + if let Some(body) = &helper.template { + scopes.extend(scope); + walk(&body.elements, scopes, reads, false); + if scope.is_some() { + scopes.pop(); + } + } + (&helper.params, &helper.hash) + } + Element::DecoratorExpression(partial) + | Element::DecoratorBlock(partial) + | Element::PartialExpression(partial) + | Element::PartialBlock(partial) => { + // Shell's inline partial uses its declaration's scope at both calls. + if let Some(body) = &partial.template { + walk(&body.elements, scopes, reads, false); + } + (&partial.params, &partial.hash) + } + _ => continue, + }; + for parameter in params.iter().chain(hash.values()) { + read(parameter, scopes, reads); + } + } +} + +fn read<'a>(parameter: &'a Parameter, scopes: &[Scope], reads: &mut Reads<'a>) { + match parameter { + Parameter::Path(Path::Relative((segments, path))) => { + // The path AST exposes names but keeps relative-hop rules private. + let hops = path.split('/').take_while(|part| *part == "..").count(); + let depth = if path.starts_with("@root") { + 0 + } else { + scopes.len().saturating_sub(hops + 1) + }; + let scope = scopes[depth]; + if scope != Scope::Nested + && let Some(name) = segments.iter().find_map(|segment| match segment { + PathSeg::Named(name) => Some(name.as_str()), + _ => None, + }) + { + reads.insert((scope, name)); + } + } + Parameter::Subexpression(sub) => { + if let Element::Expression(helper) = sub.element.as_ref() { + for argument in helper.params.iter().chain(helper.hash.values()) { + read(argument, scopes, reads); + } + } + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::{document, template}; + + #[test] + fn preserves_overview_sections_and_nested_markdown() { + let source = "Résumé with [link](/).\n\n## Usage\n\n- Overview bullet\n\n## Top-level parameters\n\n - __id__ (TEXT) \n - **type** (TEXT, required): First & `code`.\n\n - Nested bullet\n"; + let doc = document(source).unwrap(); + assert_eq!( + doc.overview, + "Résumé with [link](/).\n\n## Usage\n\n- Overview bullet" + ); + assert_eq!(doc.summary, "Résumé with link."); + assert!(doc.fields[0].optional && doc.fields[0].description.starts_with("id attribute")); + assert_eq!(doc.fields[1].kind, "TEXT"); + assert!(!doc.fields[1].optional); + assert_eq!( + doc.fields[1].description, + "First & `code`.\n\n- Nested bullet" + ); + } + + #[test] + fn verifies_parent_paths_and_reports_both_mismatches() { + let source = "{{!--\nOverview.\n\n## Top-level parameters\n\n- **title** (TEXT): Title.\n\n## Row-level parameters\n\n- **data** (JSON): Details.\n--}}{{#each_row}}{{#with data}}{{../../title}}{{nested}}{{/with}}{{/each_row}}"; + assert!(template("sample", "
", false).is_err()); + template("sample", source, true).unwrap(); + let Err(error) = template( + "sample", + &source.replace("../../title", "../../unknown"), + true, + ) else { + panic!("expected a verification error") + }; + assert_eq!( + error.to_string(), + "Undocumented parameters: [(Top, \"unknown\")]; unread parameters: [(Top, \"title\")]" + ); + } +} diff --git a/scripts/site-build.mjs b/scripts/site-build.mjs deleted file mode 100644 index 96a3d5c90..000000000 --- a/scripts/site-build.mjs +++ /dev/null @@ -1,59 +0,0 @@ -import { - copyFileSync, - cpSync, - existsSync, - mkdirSync, - mkdtempSync, - renameSync, - rmSync, -} from "node:fs"; -import { dirname, join, relative, resolve } from "node:path"; - -const repository = resolve(import.meta.dirname, ".."); -const siteDirectory = join(repository, "target", "official-site"); -const source = join(repository, "examples", "official-site"); - -const excluded = new Set([ - "README.md", - "docker-compose.yml", - "test.hurl", - join("sqlpage", "sqlpage.db"), - join("sqlpage", "https"), -]); - -function buildSite() { - const parent = dirname(siteDirectory); - mkdirSync(parent, { recursive: true }); - const temporary = mkdtempSync(join(parent, ".official-site-")); - const next = join(temporary, "next"); - const previous = join(temporary, "previous"); - try { - cpSync(source, next, { - recursive: true, - filter: (file) => !excluded.has(relative(source, file)), - }); - copyFileSync( - join(repository, "configuration.md"), - join(next, "configuration.md"), - ); - // Stage the complete site before exchanging the previous preview. - try { - renameSync(siteDirectory, previous); - } catch (error) { - if (error.code !== "ENOENT") throw error; - } - try { - renameSync(next, siteDirectory); - } catch (error) { - if (!existsSync(siteDirectory) && existsSync(previous)) { - renameSync(previous, siteDirectory); - } - throw error; - } - console.log(`Prepared ${siteDirectory}`); - } finally { - rmSync(temporary, { force: true, recursive: true }); - } -} - -buildSite(); diff --git a/sqlpage/templates/README.md b/sqlpage/templates/README.md index c70a3ace7..a51b2754f 100644 --- a/sqlpage/templates/README.md +++ b/sqlpage/templates/README.md @@ -9,6 +9,13 @@ SQLPage templates are handlebars[^1] files that are used to render the results o SQLPage comes with a set of default[^2] components that you can use without having to write any code. These are documented on https://sql-page.com/components.sql +Start each built-in template with a Handlebars comment. Its first paragraph is +the component's summary in the reference catalog. Add usage notes below it, +then list parameters under `## Top-level parameters` and `## Row-level parameters`. +Omit sections for levels with no parameters. + +See the [component reference authoring guide](../../examples/official-site/README.md#component-reference) for parameter and example formats. + ## Custom components You can [write your own component templates](https://sql-page.com/custom_components.sql) @@ -17,4 +24,4 @@ To override a default component, create a file with the same name as the default If you want to start from an existing component, you can copy it from the `sqlpage/templates` directory in the SQLPage source code[^2]. -[^2]: A simple component to start from: https://github.com/sqlpage/SQLPage/blob/main/sqlpage/templates/code.handlebars \ No newline at end of file +[^2]: A simple component to start from: https://github.com/sqlpage/SQLPage/blob/main/sqlpage/templates/code.handlebars diff --git a/sqlpage/templates/alert.handlebars b/sqlpage/templates/alert.handlebars index 5c4660f4f..6bef47547 100644 --- a/sqlpage/templates/alert.handlebars +++ b/sqlpage/templates/alert.handlebars @@ -1,4 +1,27 @@ -