diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 808d8bab7..9de900283 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,10 +62,16 @@ jobs: with: shared-key: rust-sqlpage-proj-test save-if: ${{ github.ref == 'refs/heads/main' }} + - run: sudo apt-get update && sudo apt-get install -y unixodbc-dev - run: cargo fmt --all -- --check - run: cargo clippy --all-targets --all-features -- -D warnings - name: Prepare official website run: npm run site:build + - name: Check official documentation + run: | + npm run site:test + cargo test --locked --features site-build --example build_site + cargo test --locked --features site-build --test mod configuration_docs - name: Upload prepared website uses: actions/upload-artifact@v7 with: diff --git a/AGENTS.md b/AGENTS.md index a2cc6a4bd..648d69809 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,11 +38,12 @@ relevant tests and the formatting/lint checks in CONTRIBUTING.md before stopping Report unavailable checks and failures accurately; a test summary followed by a hung process is a failure. -Update the existing page or documentation migration for changed behavior. Add a -migration only for new documentation content. +Edit the authored content under `examples/official-site/content/` and the site’s +standalone SQL and Markdown pages in place. Build and preview the official site with the commands in its [README](./examples/official-site/README.md). -Update `configuration.md` for configuration changes. +Document server options on `AppConfig` where the site build reads them. Keep +setup examples in `configuration.md`. Add a concise CHANGELOG.md entry only for user-visible changes, and never edit an already tagged release. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f73ed19c..185ca37a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## unreleased +- The [configuration reference](https://sql-page.com/configuration) now lists server settings and their defaults directly from SQLPage. Search for a setting by name or link to it with a URL such as `/configuration#listen_on`. - 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. - Button, card, carousel, and login images accept alternative text. Embedded card frames use their own title or the card title. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 128ef1568..c45c112ff 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -57,6 +57,7 @@ types, and frontend unit tests. Dynamic frontend changes also need Playwright: ```bash npm run site:build +npm run site:test cd tests/end-to-end npx playwright install --with-deps --only-shell chromium npm test @@ -107,9 +108,10 @@ 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. +The site [README](./examples/official-site/README.md) describes the format for authoring references and examples. Run `npm run site` to preview changes using the same site build as deployment. -Update [configuration.md](./configuration.md) for configuration changes and +Document server options on the Rust fields of [`AppConfig`](./src/app_config.rs). +Keep setup examples in [configuration.md](./configuration.md). Update [CHANGELOG.md](./CHANGELOG.md) for user-visible changes in an unreleased version. diff --git a/Cargo.lock b/Cargo.lock index 565cc9428..c471702b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1650,6 +1650,18 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.5.0" @@ -4042,6 +4054,19 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rusqlite" +version = "0.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" +dependencies = [ + "bitflags 2.13.2", + "fallible-iterator", + "fallible-streaming-iterator", + "libsqlite3-sys", + "smallvec", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -4210,10 +4235,23 @@ checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", "ref-cast", + "schemars_derive", "serde", "serde_json", ] +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.10", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -4315,6 +4353,17 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "serde_json" version = "1.0.154" @@ -4404,6 +4453,19 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_yaml_ng" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" +dependencies = [ + "indexmap 2.14.2", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serdect" version = "0.4.3" @@ -4627,11 +4689,14 @@ dependencies = [ "percent-encoding", "rand 0.10.3", "regex", + "rusqlite", "rustls", "rustls-acme", "rustls-native-certs", + "schemars 1.2.3", "serde", "serde_json", + "serde_yaml_ng", "sha2 0.11.1", "sqlparser", "sqlx-core-oldapi", @@ -5255,6 +5320,12 @@ dependencies = [ "cc", ] +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index d5c3b4fa8..ff67561c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,10 @@ tokio = { version = "1.24.1", features = ["macros", "rt", "process", "sync"] } tokio-stream = "0.1.9" anyhow = "1" serde = "1" +schemars = { version = "1", optional = true } +# Share SQLPage's bundled libsqlite3-sys with the site builder. +rusqlite = { version = "0.41", default-features = false, optional = true } +serde_yaml_ng = { version = "0.10", optional = true } serde_json = { version = "1.0.82", features = [ "preserve_order", "raw_value", @@ -137,6 +141,8 @@ opentelemetry-semantic-conventions = { version = "0.33", features = ["semconv_ex [features] default = [] +config-schema = ["dep:schemars"] +site-build = ["config-schema", "dep:rusqlite", "dep:serde_yaml_ng"] odbc-static = ["odbc-sys", "odbc-sys/vendored-unix-odbc"] lambda-web = [ "dep:actix-http", @@ -151,3 +157,8 @@ actix-http = "3" tempfile = "3" tokio = { version = "1", features = ["rt", "time", "test-util"] } +[[example]] +name = "build_site" +# The application Docker build omits examples. +path = "examples/build_site/main.rs" +required-features = ["site-build"] diff --git a/README.md b/README.md index 6bed71d75..650716c9d 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ select ## Supported databases -- [SQLite](https://www.sqlite.org/index.html), including the ability to [load extensions](./configuration.md) such as *Spatialite*. +- [SQLite](https://www.sqlite.org/index.html), including the ability to [load extensions](https://sql-page.com/configuration#sqlite_extensions) such as *Spatialite*. - [PostgreSQL](https://www.postgresql.org/), and other compatible databases such as *YugabyteDB*, *CockroachDB* and *Aurora*. - [MySQL](https://www.mysql.com/), and other compatible databases such as *MariaDB* and *TiDB*. - [Microsoft SQL Server](https://www.microsoft.com/en-us/sql-server), and all compatible databases and providers such as *Azure SQL* and *Amazon RDS*. @@ -218,7 +218,7 @@ You still need to install or provide the database-specific ODBC driver for the d - Find your [connection string](https://www.connectionstrings.com/). - It will look like this: `Driver=/opt/snowflake_odbc/lib/libSnowflake.so;Server=xyz.snowflakecomputing.com;Database=MY_DB;Schema=PUBLIC;UID=my_user;PWD=my_password` - It must reference the path to the database driver you installed earlier, plus any connection parameter required by the driver itself. Follow the instructions from the driver's own documentation. - - Use it in the [DATABASE_URL configuration option](./configuration.md) + - Use it in the [DATABASE_URL configuration option](https://sql-page.com/configuration#database_url) ## How it works diff --git a/configuration.md b/configuration.md index 9b4e504c8..790ace096 100644 --- a/configuration.md +++ b/configuration.md @@ -3,67 +3,20 @@ SQLPage can be configured through either [environment variables](https://en.wikipedia.org/wiki/Environment_variable) or a [JSON](https://en.wikipedia.org/wiki/JSON) file placed in `sqlpage/sqlpage.json`. -You can find an example configuration file in [`sqlpage/sqlpage.json`](./sqlpage/sqlpage.json). -Here are the available configuration options and their default values: - -| variable | default | description | -| --------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `listen_on` | 0.0.0.0:8080 | Interface and port on which the web server should listen | -| `database_url` | `sqlite://sqlpage.db?mode=rwc` in the `configuration_directory` | Database connection URL, either `dbengine://user:password@host:port/dbname` or an ODBC connection string. Special characters should be [percent-encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). See [Database connection strings](#database-connection-strings) for details and examples. When left unset, SQLPage looks for an existing db or creates `sqlpage.db` in the `configuration_directory`, with a fallback to in-memory if unwritable.| -| `database_password` | | Database password. If set, this will override any password specified in the `database_url`. This allows you to keep the password separate from the connection string for better security. | -| `port` | 8080 | Like listen_on, but specifies only the port. | -| `unix_socket` | | Path to a UNIX socket to listen on instead of the TCP port. If specified, SQLPage will accept HTTP connections only on this socket and not on any TCP port. This option is mutually exclusive with `listen_on` and `port`. -| `host` | | The web address where your application is accessible (e.g., "myapp.example.com"). Used for login redirects with OIDC. | -| `max_database_pool_connections` | PostgreSQL: 50
MySql: 75
SQLite: 16, or 128 in memory
MSSQL: 100
ODBC: 50 | How many simultaneous database connections to open at most | -| `database_connection_idle_timeout_seconds` | SQLite: None
All other: 30 minutes | Automatically close database connections after this period of inactivity. Set to 0 to disable. | -| `database_connection_max_lifetime_seconds` | SQLite: None
All other: 60 minutes | Always close database connections after this amount of time. Set to 0 to disable. | -| `database_connection_retries` | 6 | Database connection attempts before giving up. Retries will happen every 5 seconds. | -| `database_connection_acquire_timeout_seconds` | 10 | How long to wait when acquiring a database connection from the pool before giving up and returning an error. | -| `sqlite_extensions` | | An array of SQLite extensions to load, such as `mod_spatialite`. When set through an environment variable, use a space-separated list. | -| `web_root` | `.` | The root directory of the web server, where the `index.sql` file is located. Static file serving follows symlinks, so do not place symlinks under `web_root` that point to private paths (such as the `sqlpage/` config directory) or to files outside `web_root`, as their targets would become publicly reachable (see [`SECURITY.md`](./SECURITY.md)). | -| `site_prefix` | `/` | Base path of the site. If you want to host SQLPage at `https://example.com/sqlpage/`, set this to `/sqlpage/`. When using a reverse proxy, this allows hosting SQLPage together with other applications on the same subdomain. | -| `configuration_directory` | `./sqlpage/` | The directory where the `sqlpage.json` file is located. This is used to find the path to [`templates/`](https://sql-page.com/custom_components.sql), [`migrations/`](https://sql-page.com/your-first-sql-website/migrations.sql), and `on_connect.sql`. Obviously, this configuration parameter can be set only through environment variables, not through the `sqlpage.json` file itself in order to find the `sqlpage.json` file. Be careful not to use a path that is accessible from the public WEB_ROOT | -| `allow_exec` | false | Allow usage of the `sqlpage.exec` function. Do this only if all users with write access to sqlpage query files and to the optional `sqlpage_files` table on the database are trusted. | -| `max_uploaded_file_size` | 5242880 | Maximum size of forms and uploaded files in bytes. Defaults to 5 MiB. | -| `oidc_protected_paths` | `["/"]` | A list of URL prefixes that should be protected by OIDC authentication. By default, all paths are protected (`["/"]`). If you want to make some pages public, you can restrict authentication to a sub-path, for instance `["/admin", "/users/settings"]`. Decoded dot and repeated-separator aliases are normalized before matching, and protected prefixes also match ASCII case aliases on case-insensitive storage. All paths must start with a "/" and will be prepended by `site_prefix` if defined. When set through an environment variable, use a space-separated list, such as `/admin /users/settings`.| -| `oidc_public_paths` | `[]` | A list of URL prefixes that should be publicly available. By default, no paths are publicly accessible (`[]`). If you want to make some pages public, you can bypass authentication for a sub-path, for instance `["/public/", "/assets/"]`. Keep in mind that without the closing backslashes, that any directory or file starting with `public` or `assets` will be publicly available. This will also overwrite any protected path restriction. If you have a private path `/private` and you define the public path `/private/public/` everything in `/private/public/` will be publicly accessible, while everything else in private will still need authentication. All paths must start with a "/" and will be prepended by `site_prefix` if defined. When set through an environment variable, use a space-separated list, such as `/public/ /assets/`. -| `oidc_issuer_url` | | The base URL of the [OpenID Connect provider](#openid-connect-oidc-authentication). Required for enabling Single Sign-On. | -| `oidc_client_id` | sqlpage | The ID that identifies your SQLPage application to the OIDC provider. You get this when registering your app with the provider. | -| `oidc_client_secret` | | The secret key for your SQLPage application. Keep this confidential as it allows your app to authenticate with the OIDC provider. | -| `oidc_scopes` | openid email profile | Space-separated list of [scopes](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims) your app requests from the OIDC provider. | -| `oidc_additional_trusted_audiences` | unset | A list of additional audiences that are allowed in JWT tokens, beyond the client ID. When empty or unset, any additional audience is accepted. For increased security, set to an empty list `[]` in the configuration file to only allow the client ID as audience. When set through an environment variable, use a space-separated list, such as `audience-one audience-two`. | -| `max_pending_rows` | 256 | Maximum number of rendered rows that can be queued up in memory when a client is slow to receive them. | -| `compress_responses` | false | When the client supports it, compress the http response body. This can save bandwidth and speed up page loading on slow connections, but can also increase CPU usage and cause rendering delays on pages that take time to render (because streaming responses are buffered for longer than necessary). | -| `https_domain` | | Domain name to request a certificate for. Setting this parameter will automatically make SQLPage listen on port 443 and request an SSL certificate. The server will take a little bit longer to start the first time it has to request a certificate. HTTPS is always served on port 443; if `listen_on` or `port` names a different port, SQLPage also serves plain HTTP there. | -| `https_certificate_email` | contact@ | The email address to use when requesting a certificate. | -| `https_certificate_cache_dir` | ./sqlpage/https | A writeable directory where to cache the certificates, so that SQLPage can serve https traffic immediately when it restarts. The default ignores `web_root` and `configuration_directory`. | -| `https_acme_directory_url` | https://acme-v02.api.letsencrypt.org/directory | The URL of the ACME directory to use when requesting a certificate. | -| `environment` | development | The environment in which SQLPage is running. Can be either `development` or `production`. In `production` mode, SQLPage will hide error messages and stack traces from the user, and will cache sql files in memory to avoid reloading them from disk. | -| `cache_stale_duration_ms` | 1000 (prod), 0 (dev) | The duration in milliseconds that a file can be cached before its freshness is checked against the filesystem. Defaults to 1000ms (1 second) in production and 0ms in development. | -| `content_security_policy` | `script-src 'self' 'nonce-{NONCE}'` | The [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) to set in the HTTP headers. If you get CSP errors in the browser console, you can set this to the empty string to disable CSP. If you want a custom CSP that contains a nonce, include the `'nonce-{NONCE}'` directive in your configuration string and it will be populated with a random value per request. | -| `smtp_host` | | SMTP server host used by the `sqlpage.send_mail` function. Set with `SMTP_HOST` in the environment. | -| `smtp_port` | 25 (`none`), 465 (`tls`), or 587 (`starttls`) | SMTP server port. The default depends on `smtp_tls_mode`. Set this explicitly for relays using a nonstandard port. | -| `smtp_username` | | Optional SMTP user name for `sqlpage.send_mail`. When set, SQLPage authenticates to `SMTP_HOST` using this user name and `smtp_password`. Credentials require `smtp_tls_mode` to be `starttls` or `tls`. | -| `smtp_password` | | Optional SMTP password for `sqlpage.send_mail`. `smtp_username` and `smtp_password` must be configured together. | -| `smtp_from` | | Default sender address for `sqlpage.send_mail`, optionally including a display name. Individual messages can override it with their `from` property. | -| `smtp_tls_mode` | `starttls` | Encryption mode for `sqlpage.send_mail`: `starttls` requires a STARTTLS upgrade, `tls` uses TLS from connection start, and `none` permits plaintext only without credentials for trusted local SMTP servers. | -| `max_email_attachment_size` | 10485760 | Maximum combined decoded size, in bytes, of all attachments in one email. Defaults to 10 MiB. This is independent of `max_uploaded_file_size` because attachments may come from sources other than form uploads. | -| `system_root_ca_certificates` | true when `SSL_CERT_FILE` or `SSL_CERT_DIR` is set, false otherwise | Whether to use the system root CA certificates to validate SSL certificates when making http requests with `sqlpage.fetch`. If set to false, SQLPage will use its own set of root CA certificates. The `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables define what the system store contains, so setting either of them also turns this option on by default. | -| `max_recursion_depth` | 10 | Maximum depth of recursion allowed in the `run_sql` function. Values above 255 stop the server from starting. | -| `markdown_allow_dangerous_html` | false | Whether to allow raw HTML in markdown content. Only enable this if the markdown content is fully trusted (not user generated). | -| `markdown_allow_dangerous_protocol` | false | Whether to allow dangerous protocols (like javascript:) in markdown links. Only enable this if the markdown content is fully trusted (not user generated). | +You can find an example configuration file in [`sqlpage/sqlpage.json`](https://github.com/sqlpage/SQLPage/blob/main/sqlpage/sqlpage.json). +See the [configuration reference](https://sql-page.com/configuration) for every option, its accepted values, and its default. Multiple configuration file formats are supported: you can use a [`.json5`](https://json5.org/) file, a [`.toml`](https://toml.io/) file, or a [`.yaml`](https://en.wikipedia.org/wiki/YAML#Syntax) file. ## Environment variables -All the parameters above can be set through environment variables. +Configuration options can also be set through environment variables. The name of the environment variable is the same as the name of the configuration variable, but in uppercase. -The environment variable name can optionally be prefixed with `SQLPAGE_`. +For settings read from the configuration file, the environment variable overrides the file, and a variable prefixed with `SQLPAGE_` takes precedence over its unprefixed form. Additionnally, when troubleshooting, you can set the [`LOG_LEVEL`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html) @@ -121,7 +74,7 @@ DATABASE_URL="Driver={SnowflakeDSIIDriver};Server=account.snowflakecomputing.com ODBC drivers must be installed and configured on your system. On Linux, the `unixODBC` driver manager is statically linked into the SQLPage binary, so you usually only need to install and configure the database-specific ODBC driver for your target database (for example Snowflake, Oracle, DuckDB...). -The `-duckdb` [docker image variants](./README.md#install-your-odbc-database-driver) ships with `DATABASE_URL` set to `DSN=DuckDB`so that the container uses a DuckDB file instead of SQLite. +The [DuckDB image variant](https://github.com/sqlpage/SQLPage#install-your-odbc-database-driver) includes the DuckDB ODBC driver and defaults to a DuckDB database file. If the `database_password` configuration parameter is set, it will override any password specified in the `database_url`. It does not need to be percent-encoded. diff --git a/examples/build_site/configuration.rs b/examples/build_site/configuration.rs new file mode 100644 index 000000000..b7b40e790 --- /dev/null +++ b/examples/build_site/configuration.rs @@ -0,0 +1,78 @@ +use super::Seed; +use anyhow::{Context, Result}; +use schemars::generate::SchemaSettings; +use serde_json::Value; +use sqlpage::app_config::AppConfig; + +pub(super) fn insert(seed: &mut Seed) -> Result<()> { + let schema = SchemaSettings::draft2020_12() + .with(|settings| settings.inline_subschemas = true) + .into_generator() + .into_root_schema_for::(); + let properties = schema + .get("properties") + .and_then(Value::as_object) + .context("Missing AppConfig properties")?; + for (name, option) in properties { + let description = option["description"] + .as_str() + .filter(|text| !text.trim().is_empty()) + .with_context(|| format!("{name} needs a Rust doc comment"))?; + let kind = schema_type(option).with_context(|| format!("Documenting {name}"))?; + let default = option["x-default-description"] + .as_str() + .map(str::to_owned) + .or_else(|| { + option.get("default").map(|value| { + let value = value.to_string(); + let ticks = value.split(|c| c != '`').map(str::len).max().unwrap_or(0); + let delimiter = "`".repeat(ticks + 1); + format!("{delimiter}{value}{delimiter}") + }) + }); + seed.row( + "INSERT INTO config_option (name, type, default_md, description_md) VALUES (?, ?, ?, ?)", + &[&name, &kind, &default, &description], + )?; + } + Ok(()) +} + +fn schema_type(schema: &Value) -> Result { + if let Some(values) = schema["enum"].as_array() { + return Ok(values + .iter() + .map(Value::to_string) + .collect::>() + .join(" | ")); + } + if let Some(types) = schema["anyOf"].as_array() { + return Ok(types + .iter() + .map(schema_type) + .collect::>>()? + .join(" or ")); + } + if let Some(types) = schema["type"].as_array() { + return Ok(types + .iter() + .map(|kind| format_type(schema, kind)) + .collect::>>()? + .join(" or ")); + } + format_type(schema, &schema["type"]) +} + +fn format_type(schema: &Value, kind: &Value) -> Result { + let kind = kind.as_str().context("Missing configuration option type")?; + Ok(match kind { + "array" => format!("{}[]", schema_type(&schema["items"])?), + "integer" | "number" => match (schema.get("minimum"), schema.get("maximum")) { + (Some(min), Some(max)) => format!("{kind} ({min} to {max})"), + (Some(min), None) => format!("{kind} (≥ {min})"), + (None, Some(max)) => format!("{kind} (≤ {max})"), + (None, None) => kind.to_owned(), + }, + _ => kind.to_owned(), + }) +} diff --git a/examples/build_site/content.rs b/examples/build_site/content.rs new file mode 100644 index 000000000..15f5189f9 --- /dev/null +++ b/examples/build_site/content.rs @@ -0,0 +1,279 @@ +use super::{Seed, markdown_files, read}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, de::DeserializeOwned}; +use serde_json::Value; +use std::{collections::BTreeMap, fs, path::Path}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Category { + id: String, + title: String, + sort_order: i64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Guide { + title: String, + link: String, + description: String, + sort_order: i64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Project { + title: String, + folder: String, + db_engine: Option, + description: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Parameter { + name: String, + r#type: String, + description: String, + #[serde(default)] + required: bool, +} + +impl Parameter { + fn validate(&self) -> Result<()> { + for (name, value) in [ + ("name", &self.name), + ("type", &self.r#type), + ("description", &self.description), + ] { + ensure!(!value.trim().is_empty(), "Expected text in {name}"); + } + Ok(()) + } +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum ComponentParameter { + Shared(String), + Inline(Parameter), +} + +#[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct Component { + icon: Option, + since: Option, + category: Option, + summary: Option, + #[serde(default)] + top: Vec, + #[serde(default)] + row: Vec, +} + +#[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct Function { + icon: Option, + since: Option, + category: Option, + summary: Option, + return_type: Option, + #[serde(default)] + parameters: Vec, +} + +#[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct Example { + // serde_json preserves mapping order and large integers. The same rows + // drive both the live preview and the SQL shown to the reader. + rows: Option>>, +} + +#[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct Blog { + title: String, + date: String, + icon: String, + summary: String, + external_url: Option, +} + +pub(super) fn insert(seed: &mut Seed, dir: &Path) -> Result<()> { + collection(dir, "categories.yaml", |c: Category| { + seed.row( + "INSERT INTO reference_category (id, title, sort_order) VALUES (?, ?, ?)", + &[&c.id, &c.title, &c.sort_order], + ) + })?; + collection(dir, "guides.yaml", |g: Guide| { + seed.row( + "INSERT INTO guide (title, link, description, sort_order) VALUES (?, ?, ?, ?)", + &[&g.title, &g.link, &g.description, &g.sort_order], + ) + })?; + collection(dir, "projects.yaml", |p: Project| { + seed.row( + "INSERT INTO example_cards (title, folder, db_engine, description) VALUES (?, ?, ?, ?)", + &[&p.title, &p.folder, &p.db_engine, &p.description], + ) + })?; + let shared_path = dir.join("shared-parameters.yaml"); + let shared: BTreeMap = at(&shared_path, || { + let entries: BTreeMap = serde_yaml_ng::from_str(&read(&shared_path)?)?; + for parameter in entries.values() { + parameter.validate()?; + } + Ok(entries) + })?; + components(seed, &dir.join("components"), &shared)?; + functions(seed, &dir.join("functions"))?; + pages(&dir.join("blog"), |_, b: Blog, body| { + ensure!( + [&b.title, &b.date, &b.icon, &b.summary] + .iter() + .all(|s| !s.trim().is_empty()), + "Expected title, date, icon and summary" + ); + seed.row( + "INSERT INTO blog_posts (title, created_at, icon, description, external_url, content) + VALUES (?, ?, ?, ?, ?, ?)", + &[ + &b.title, + &b.date, + &b.icon, + &b.summary, + &b.external_url, + &(!body.is_empty()).then_some(body), + ], + ) + }) +} + +fn components(seed: &mut Seed, dir: &Path, shared: &BTreeMap) -> Result<()> { + for entry in fs::read_dir(dir)? { + let entry = entry?; + if entry.file_type()?.is_dir() { + let mut reference = entry.file_name(); + reference.push(".md"); + ensure!( + dir.join(&reference).is_file(), + "{} has no corresponding reference {}", + entry.path().display(), + reference.to_string_lossy() + ); + } + } + pages(dir, |name, c: Component, body| { + seed.row( + "INSERT INTO component (name, description, icon, introduced_in_version, catalog_category, catalog_summary) + VALUES (?, ?, ?, ?, ?, ?)", + &[&name, &body, &c.icon, &c.since, &c.category, &c.summary], + )?; + for (top, parameters) in [(true, c.top), (false, c.row)] { + for p in ¶meters { + let p = match p { + ComponentParameter::Inline(p) => p, + ComponentParameter::Shared(key) => shared + .get(key) + .with_context(|| format!("Unknown shared parameter {key:?}"))?, + }; + p.validate()?; + seed.row( + "INSERT INTO parameter (component, top_level, name, type, description_md, optional) + VALUES (?, ?, ?, ?, ?, ?)", + &[&name, &top, &p.name, &p.r#type, &p.description, &!p.required], + )?; + } + } + let examples = dir.join(name).join("examples"); + if examples.try_exists()? { + pages(&examples, |_, e: Example, description| { + let properties = e + .rows + .map(|rows| serde_json::to_string(&rows)) + .transpose()?; + seed.row( + "INSERT INTO example (component, description, properties) VALUES (?, ?, ?)", + &[&name, &description, &properties], + ) + })?; + } + Ok(()) + }) +} + +fn functions(seed: &mut Seed, dir: &Path) -> Result<()> { + pages(dir, |name, f: Function, body| { + seed.row( + "INSERT INTO sqlpage_functions (name, icon, description_md, return_type, + introduced_in_version, catalog_category, catalog_summary) VALUES (?, ?, ?, ?, ?, ?, ?)", + &[&name, &f.icon, &body, &f.return_type, &f.since, &f.category, &f.summary], + )?; + for (index, p) in (1_i64..).zip(f.parameters) { + p.validate()?; + seed.row( + "INSERT INTO sqlpage_function_parameters (\"function\", \"index\", name, description_md, type, optional) + VALUES (?, ?, ?, ?, ?, ?)", + &[&name, &index, &p.name, &p.description, &p.r#type, &!p.required], + )?; + } + Ok(()) + }) +} + +fn collection( + dir: &Path, + file: &str, + mut insert: impl FnMut(T) -> Result<()>, +) -> Result<()> { + let path = dir.join(file); + at(&path, || { + for item in serde_yaml_ng::from_str::>(&read(&path)?)? { + insert(item)?; + } + Ok(()) + }) +} + +fn pages( + dir: &Path, + mut visit: impl FnMut(&str, T, &str) -> Result<()>, +) -> Result<()> { + for path in markdown_files(dir)? { + at(&path, || { + let name = path + .file_stem() + .and_then(|s| s.to_str()) + .context("Invalid filename")?; + let file = read(&path)?.replace("\r\n", "\n"); + let (meta, body) = if let Some(rest) = file.strip_prefix("---\n") { + let mut offset = 0; + let end = rest + .split_inclusive('\n') + .find_map(|line| { + let start = offset; + offset += line.len(); + (line.trim_end_matches([' ', '\t', '\n']) == "---").then_some(start) + }) + .context("Unclosed YAML front matter")?; + ( + serde_yaml_ng::from_str::>(&rest[..end])?.unwrap_or_default(), + &rest[offset..], + ) + } else { + (T::default(), file.as_str()) + }; + visit(name, meta, body.trim()) + })?; + } + Ok(()) +} + +fn at(path: &Path, f: impl FnOnce() -> Result) -> Result { + f().with_context(|| path.display().to_string()) +} diff --git a/examples/build_site/main.rs b/examples/build_site/main.rs new file mode 100644 index 000000000..397c10f65 --- /dev/null +++ b/examples/build_site/main.rs @@ -0,0 +1,230 @@ +mod configuration; +mod content; + +use anyhow::{Context, Result, bail}; +use rusqlite::{ + Connection, ToSql, + types::{ToSqlOutput, Value, ValueRef}, +}; +use std::{ + fs, + path::{Path, PathBuf}, +}; + +const SEED_FILE: &str = "sqlpage/migrations/01_documentation.sql"; + +fn main() -> Result<()> { + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let source = root.join("examples/official-site"); + let seed = documentation_seed(&source.join("content"))?; + + let parent = root.join("target"); + fs::create_dir_all(&parent)?; + let destination = parent.join("official-site"); + let staging = tempfile::tempdir_in(parent)?; + let next = staging.path().join("next"); + let previous = staging.path().join("previous"); + copy_site(&source, &next, Path::new(""))?; + fs::copy(root.join("configuration.md"), next.join("configuration.md"))?; + fs::write(next.join(SEED_FILE), seed)?; + + // Leave the current preview in place until the replacement is ready. + let had_previous = match fs::rename(&destination, &previous) { + Ok(()) => true, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, + Err(error) => return Err(error.into()), + }; + if let Err(error) = fs::rename(next, &destination) { + if had_previous && let Err(restore) = fs::rename(&previous, &destination) { + let backup = staging.keep().join("previous"); + bail!( + "Could not publish site ({error}) or restore it ({restore}). Backup: {}", + backup.display() + ); + } + return Err(error).context("Publishing the prepared site"); + } + println!("Prepared {}", destination.display()); + Ok(()) +} + +fn copy_site(source: &Path, target: &Path, relative: &Path) -> Result<()> { + const EXCLUDED: &[&str] = &[ + "content", + "README.md", + "docker-compose.yml", + "test.hurl", + "sqlpage/sqlpage.db", + "sqlpage/https", + ]; + fs::create_dir(target)?; + for entry in fs::read_dir(source)? { + let entry = entry?; + let child = relative.join(entry.file_name()); + if EXCLUDED.iter().any(|path| child == Path::new(path)) { + continue; + } + let dest = target.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_site(&entry.path(), &dest, &child)?; + } else { + fs::copy(entry.path(), dest)?; + } + } + Ok(()) +} + +fn documentation_seed(content: &Path) -> Result { + let mut seed = Seed { + db: Connection::open_in_memory()?, + sql: String::new(), + }; + seed.db.pragma_update(None, "foreign_keys", true)?; + seed.script(include_str!("schema.sql"))?; + content::insert(&mut seed, content)?; + configuration::insert(&mut seed)?; + seed.script(include_str!("search.sql"))?; + Ok(seed.sql) +} + +struct Seed { + db: Connection, + sql: String, +} + +impl Seed { + fn script(&mut self, sql: &str) -> Result<()> { + self.db.execute_batch(sql)?; + self.sql.push_str(sql); + Ok(()) + } + + fn row(&mut self, sql: &str, values: &[&dyn ToSql]) -> Result<()> { + // SQLite's expanded SQL cannot round-trip NUL bytes in text. + for value in values { + let output = value.to_sql()?; + let text = match &output { + ToSqlOutput::Borrowed(ValueRef::Text(bytes)) => *bytes, + ToSqlOutput::Owned(Value::Text(text)) => text.as_bytes(), + _ => continue, + }; + anyhow::ensure!(!text.contains(&0), "NUL byte in SQL text value"); + } + let mut statement = self.db.prepare(sql)?; + statement.execute(values)?; + // SQLite renders the bound values for the startup seed. + let expanded = statement + .expanded_sql() + .context("Expanding SQLite bindings")?; + self.sql.push_str(&expanded); + self.sql.push_str(";\n"); + Ok(()) + } +} + +fn read(path: &Path) -> Result { + Ok(fs::read_to_string(path)?) +} + +fn markdown_files(dir: &Path) -> Result> { + let mut files = Vec::new(); + for entry in fs::read_dir(dir).with_context(|| format!("Reading {}", dir.display()))? { + let path = entry?.path(); + if path.extension().is_some_and(|ext| ext == "md") { + files.push(path); + } + } + files.sort(); + Ok(files) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn startup_seed_round_trips_examples_and_indexes_configuration() -> Result<()> { + let temp = tempfile::tempdir()?; + let content = temp.path(); + for dir in ["components/demo/examples", "functions", "blog"] { + fs::create_dir_all(content.join(dir))?; + } + for file in ["categories.yaml", "guides.yaml", "projects.yaml"] { + fs::write(content.join(file), "[]\n")?; + } + fs::write( + content.join("shared-parameters.yaml"), + "id: {name: id, type: TEXT, description: HTML id}\n", + )?; + let topic = content.join("components/demo.md"); + fs::write(&topic, "---\ntop: [id]\n---\n\nA contributor's demo.\n")?; + let examples = content.join("components/demo/examples"); + fs::write( + examples.join("02-result.md"), + "---\nrows:\n - component: text\n contents: \"Reader's choice\"\n \"2\": 9007199254740993\n \"1\": 42\n---\nResult\n", + )?; + fs::write(examples.join("01-notes.md"), "Just a note.\n")?; + + let seed = documentation_seed(content)?; + assert_eq!(seed, documentation_seed(content)?); + let db = Connection::open_in_memory()?; + db.execute_batch(&seed)?; + let rows = db + .prepare("SELECT description, source FROM example_with_source ORDER BY example_number")? + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, Option>(1)?)) + })? + .collect::>>()?; + assert_eq!( + rows, + [ + ("Just a note.".into(), None), + ("Result".into(), Some("select\n 'text' as \"component\",\n 'Reader''s choice' as \"contents\",\n 9007199254740993 as \"2\",\n 42 as \"1\";".into())), + ] + ); + let config = db + .prepare("SELECT name, type, default_md FROM config_option + WHERE name IN ('allow_exec', 'listen_on', 'max_recursion_depth', 'smtp_from') ORDER BY name")? + .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, Option>(2)?)))? + .collect::>>()?; + assert_eq!( + config[0], + ( + "allow_exec".into(), + "boolean".into(), + Some("`false`".into()) + ) + ); + assert_eq!(config[1].1, "string or null"); + assert_eq!( + config[1].2.as_deref(), + Some("`0.0.0.0:443` with `https_domain`, otherwise `0.0.0.0:8080`.") + ); + assert_eq!(config[2].1, "integer (0 to 255)"); + assert_eq!( + config[3], + ("smtp_from".into(), "string or null".into(), None) + ); + let link: String = db.query_row( + "SELECT page || '#' || fragment FROM documentation_fts + WHERE documentation_fts MATCH 'listen_on' AND fragment = 'listen_on'", + [], + |row| row.get(0), + )?; + assert_eq!(link, "/configuration#listen_on"); + + fs::write(&topic, "---\ntop: [missing]\n---\nExample.\n")?; + let error = format!("{:#}", documentation_seed(content).unwrap_err()); + assert!( + error.contains("demo.md: Unknown shared parameter \"missing\""), + "{error}" + ); + fs::rename(topic, content.join("components/moved.md"))?; + let error = documentation_seed(content).unwrap_err().to_string(); + assert!( + error.contains("no corresponding reference demo.md"), + "{error}" + ); + Ok(()) + } +} diff --git a/examples/build_site/schema.sql b/examples/build_site/schema.sql new file mode 100644 index 000000000..99b0dbcad --- /dev/null +++ b/examples/build_site/schema.sql @@ -0,0 +1,154 @@ +CREATE TABLE reference_category ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL, + sort_order INTEGER NOT NULL +); + +CREATE TABLE config_option ( + name TEXT PRIMARY KEY, + type TEXT NOT NULL, + default_md TEXT, + description_md TEXT NOT NULL +); + +CREATE TABLE component ( + name TEXT PRIMARY KEY, + description TEXT NOT NULL, + icon TEXT, + introduced_in_version TEXT, + catalog_category TEXT REFERENCES reference_category(id), + catalog_summary TEXT +); + +CREATE TABLE parameter_type (name TEXT PRIMARY KEY); +INSERT INTO parameter_type VALUES + ('BOOLEAN'), ('COLOR'), ('HTML'), ('ICON'), ('INTEGER'), ('JSON'), ('REAL'), ('TEXT'), ('TIMESTAMP'), ('URL'); + +CREATE TABLE parameter ( + component TEXT NOT NULL REFERENCES component(name), + top_level BOOLEAN NOT NULL, + name TEXT NOT NULL, + type TEXT NOT NULL REFERENCES parameter_type(name), + description_md TEXT NOT NULL, + optional BOOLEAN NOT NULL, + PRIMARY KEY (component, top_level, name) +); + +CREATE TABLE example ( + component TEXT NOT NULL REFERENCES component(name), + description TEXT NOT NULL, + properties JSON +); + +CREATE TABLE sqlpage_functions ( + name TEXT PRIMARY KEY, + icon TEXT, + description_md TEXT NOT NULL, + return_type TEXT, + introduced_in_version TEXT, + catalog_category TEXT REFERENCES reference_category(id), + catalog_summary TEXT +); + +CREATE TABLE sqlpage_function_parameters ( + "function" TEXT NOT NULL REFERENCES sqlpage_functions(name), + "index" INTEGER NOT NULL, + name TEXT NOT NULL, + description_md TEXT NOT NULL, + type TEXT NOT NULL, + optional BOOLEAN NOT NULL, + PRIMARY KEY ("function", "index"), + UNIQUE ("function", name) +); + +CREATE TABLE blog_posts ( + title TEXT PRIMARY KEY, + description TEXT NOT NULL, + icon TEXT NOT NULL, + external_url TEXT, + content TEXT, + created_at TEXT NOT NULL +); + +CREATE TABLE guide ( + sort_order INTEGER PRIMARY KEY, + title TEXT NOT NULL, + link TEXT NOT NULL UNIQUE, + description TEXT NOT NULL +); + +CREATE TABLE example_cards ( + title TEXT NOT NULL, + folder TEXT NOT NULL, + db_engine TEXT, + description TEXT NOT NULL +); + +-- 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; + +-- The catalog, topic navigation, and reference pages use the same entries and links. +CREATE VIEW reference_entry AS +WITH entries AS ( + SELECT 'component' AS kind, name, icon, catalog_category, catalog_summary, + description AS description_md, introduced_in_version, NULL AS return_type, + '/component.sql?component=' || name AS link, + (SELECT count(*) FROM example WHERE example.component = component.name) AS example_count, + NULL AS arguments + FROM component + UNION ALL + SELECT 'function', name, icon, catalog_category, catalog_summary, + description_md, introduced_in_version, return_type, '/functions.sql?function=' || name, NULL, + coalesce((SELECT group_concat(CASE WHEN optional THEN '[' || name || ']' ELSE name END, ', ' ORDER BY "index") + FROM sqlpage_function_parameters WHERE "function" = f.name), '') + FROM sqlpage_functions AS f +) +SELECT kind, name, icon, link, description_md, introduced_in_version, return_type, example_count, arguments, + coalesce(category.id, 'other') AS category_id, + coalesce(category.title, 'Other') AS category_title, + coalesce(category.sort_order, 99) AS category_order, + coalesce(catalog_summary, substr(trim(description_md, char(10) || ' #'), 1, + instr(trim(description_md, char(10) || ' #') || char(10), char(10)) - 1)) AS summary +FROM entries +LEFT JOIN reference_category AS category ON category.id = entries.catalog_category; + +-- The section is part of the anchor: a component can accept the same name at both levels. +CREATE VIEW reference_parameter AS +WITH fields AS ( + SELECT 'component' AS kind, component AS entry, + CASE WHEN top_level THEN 'top-level-parameters' ELSE 'row-level-parameters' END AS section, + name, type, optional, description_md, optional AS position + FROM parameter + UNION ALL + SELECT 'function', "function", 'parameters', name, type, optional, description_md, "index" + FROM sqlpage_function_parameters +), sections(section, title, introduction, section_order) AS (VALUES + ('top-level-parameters', 'Top-level parameters', 'Set these in the SELECT that names the component.', 1), + ('row-level-parameters', 'Row-level parameters', 'Return these columns in the rows that follow the component.', 2), + ('parameters', 'Parameters', NULL, 1) +) +SELECT fields.*, title, introduction, section_order, section || '-' || name AS anchor +FROM fields JOIN sections USING (section); diff --git a/examples/official-site/sqlpage/migrations/999_fts_search_index.sql b/examples/build_site/search.sql similarity index 89% rename from examples/official-site/sqlpage/migrations/999_fts_search_index.sql rename to examples/build_site/search.sql index ee0ba09e8..23d6db026 100644 --- a/examples/official-site/sqlpage/migrations/999_fts_search_index.sql +++ b/examples/build_site/search.sql @@ -23,3 +23,6 @@ JOIN reference_entry AS e ON e.kind = 'component' AND e.name = x.component; INSERT INTO documentation_fts(title, description, page, parameters) SELECT title, description, '/blog.sql', json_object('post', title) FROM blog_posts; + +INSERT INTO documentation_fts(title, description, page, fragment) +SELECT name, description_md, '/configuration', name FROM config_option; diff --git a/examples/official-site/README.md b/examples/official-site/README.md index f44983a13..cd5ff89cc 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 + - The [component reference](./content/components/) and its live examples - The [advanced multistep form example](./examples/multistep-form/) It is hosted as a simple Docker container on [sql-page.com](https://sql-page.com). @@ -17,7 +17,9 @@ Run `npm ci --ignore-scripts` from the repository root, then `npm run site`. The preview uses the same build as CI and deployment. Rerun the command after editing the site. After `npm run build`, run `npm run site:build` to prepare the site under -`target/official-site/`. +`target/official-site/`. The build command is also available directly: +`cargo run --locked --features site-build --example build_site`. +Run `npm run site:test` against the prepared site to check component coverage. Run SQLPage from that directory, or run `docker compose -f examples/official-site/docker-compose.yml up --build` from the repository root. @@ -26,6 +28,15 @@ 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`. +## Editing documentation + +- Edit [component](./content/components/form.md) and [function](./content/functions/link.md) descriptions in Markdown. The filename is the public name. Put the summary, category, and parameters in the YAML header. +- Add [component examples](./content/components/form/examples/) beside the component page. The numbered filename determines display order. The Markdown body explains the example. When supplied, the `rows` in the header provide both the rendered preview and the displayed SQL. +- Edit [blog posts](./content/blog/) in Markdown and the [guides](./content/guides.yaml) and [example project cards](./content/projects.yaml) in YAML. +- Document configuration settings on [`AppConfig`](../../src/app_config.rs). The site uses its Serde field names, schema types, and defaults for the searchable configuration reference. + +The Rust builder loads these sources into SQLite and generates one startup seed from bound values. The checked-in SQL migrations supply the site’s demos and installation options. + ## Landing page The home page is rendered by `index.sql` and the `landing-page` custom template. diff --git a/examples/official-site/configuration.sql b/examples/official-site/configuration.sql new file mode 100644 index 000000000..3dea998a3 --- /dev/null +++ b/examples/official-site/configuration.sql @@ -0,0 +1,14 @@ +select 'shell-docs' as component, 'Configuration | SQLPage' as title, 'Configuration' as section; + +select 'docs-reference-heading' as component, 'configuration' as id, 'Documentation' as section, + '/documentation.sql' as link, 'settings' as icon, 'Configuration' as title, + 'Server settings, accepted values, and defaults.' as description; + +select 'text' as component, + 'Set options in your configuration file or use their uppercase names as environment variables. The [configuration guide](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) covers file formats, connection strings, and setup examples.' as contents_md; + +select 'docs-parameters' as component; +select 'options' as id, 'Options' as title, json_group_array(json_object( + 'name', name, 'anchor', name, 'type', type, 'description_md', description_md, + 'default_md', coalesce(default_md, 'Unset') +) order by name) as parameters from config_option; diff --git a/examples/official-site/content/blog/3-solutions-to-the-3-layer-problem.md b/examples/official-site/content/blog/3-solutions-to-the-3-layer-problem.md new file mode 100644 index 000000000..348921268 --- /dev/null +++ b/examples/official-site/content/blog/3-solutions-to-the-3-layer-problem.md @@ -0,0 +1,82 @@ +--- +title: 3 solutions to the 3 layer problem +date: '2023-08-10' +icon: adjustments-question +summary: What is the 3 layer problem, and how SQLPage solves it? +--- + +# 3 solutions to the 3 layer problem + +> Some interesting questions emerged from the article [Repeating yourself thrice doesn't turn you into a 3X developer](https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0). +> This short follow-up article aims to answer them and clarify some points. + +Hello all, + +I am Ophir Lojkine, the main contributor of the open-source application server **SQLPage**. + +The previous article focused on the conventional model of splitting applications into three distinct tiers: + +1. a graphical interface (_front-end_), +2. an application server (_back-end_), +3. and a database. + +In many projects, this results in three distinct implementations of the application’s data model: + +1. First, in SQL, in the form of tables, views, and relationships in the database, +2. Then, in _server side_ languages such as Java, Python, or PHP, to create an API managing access to the data, and to implement the business logic of the application, +3. Finally, in JavaScript or TypeScript to implement data manipulation in the user interface. + +![Traditional tiers model](blog/three-layers.svg) + +--- + +The topic of interest here is the duplication of the data model between the different layers, +and the communication overhead between them. +We are not talking about how the code is structured within each layer. +It can follow a Model-View-Controller pattern or not, it doesn't matter. + +This three-layer model has several advantages: +specialization of the programmers, +parallelization of work, +scalability, +separation of concerns, +and an optimal exploitation of the capacities of the infrastructure on which each layer is deployed: +web browser, server application and database. + +Nevertheless, in large-scale projects, +there is often a certain redundancy of the code between the different layers, +as well as a non-negligible share of code dedicated to communication between them. +For small teams and solo developers, this becomes a major drawback. + +## 3 solutions + +Fortunately, there are several approaches to solving this problem: + +1. For **UI-centric applications** without complicated data processing needs, +you can almost completely abandon server-side development and **directly expose the data to the frontend**. +Open-source tools available in this space include Supabase, PocketBase or Hasura. +2. For **applications with a predominant business logic**, traditional _web frameworks_ +solve this problem by centralizing frontend and database control in the backend code. +A common solution involves using an ORM and templating system instead of a dedicated javascript application. +Popular solutions include Django, Ruby on Rails, or Symphony. +3. For simpler applications, it is possible to **avoid both backend and frontend development** +by adopting a _database-first_ approach. +This alternative, although less widespread, allows taking advantage of under-exploited modern capacities of relational databases. +The purpose of the original article was to introduce this lesser known approach. + * **SQLPage** is representative of this last category, + which allows designing a complete web application _in SQL_. + This leads to a loss of control over the precise visual appearance of the application, + which will get a “standardized” look and feel. + On the other hand, this translates into significant gains in terms of development speed, + simplicity and performance. + This solution is not intended to compete with traditional _frameworks_, + but rather integrate earlier in the life cycle of a project. + It thus makes it possible to quickly develop a data structure adapted to the application, + and to iterate over it while benefiting from continuous visual feedback on the final result. + Then, when the application grows, it’s easy to add a classic frontend and backend on top of the existing database, + without having to start from scratch. + +Whichever approach is chosen in the end, +a solid understanding of the conventional three-tier architecture, +as well as a clear perspective on the challenges it creates and the possible solutions, +facilitates decision-making and the evolution of the project with the best suited technologies. diff --git a/examples/official-site/sqlpage/migrations/53_blog_pgconf2024.sql b/examples/official-site/content/blog/come-and-see-us-in-athens.md similarity index 63% rename from examples/official-site/sqlpage/migrations/53_blog_pgconf2024.sql rename to examples/official-site/content/blog/come-and-see-us-in-athens.md index 1f859c282..a74383aa3 100644 --- a/examples/official-site/sqlpage/migrations/53_blog_pgconf2024.sql +++ b/examples/official-site/content/blog/come-and-see-us-in-athens.md @@ -1,12 +1,10 @@ +--- +title: Come and see us in Athens ! +date: '2024-10-15' +icon: microphone-2 +summary: PGConf 2024 is coming to Athens, Greece. And we will be there to talk about SQLPage & Archeology ! +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Come and see us in Athens !', - 'PGConf 2024 is coming to Athens, Greece. And we will be there to talk about SQLPage & Archeology !', - 'microphone-2', - '2024-10-15', - ' # PostgreSQL & SQLPage at PGConf 2024 We have been invited to give a talk at PGConf 2024 in Athens, Greece. @@ -20,9 +18,8 @@ drastically reduce the time spent on data entry and management. There will be two presenters: - **Ophir Lojkine**, the creator and maintainer of SQLPage, will present the project and its capabilities. - - **Thomas Guillemard**, an archaeologist from France''s National Institute for Preventive Archaeological Research, will present the project''s use case and its benefits. + - **Thomas Guillemard**, an archaeologist from France's National Institute for Preventive Archaeological Research, will present the project's use case and its benefits. Come and see us in Athens ! https://www.postgresql.eu/events/pgconfeu2024/schedule/session/5707-unearthing-the-past-with-postgresql-how-open-source-is-revolutionizing-digital-archaeology/ -'); diff --git a/examples/official-site/sqlpage/migrations/22_pgconf_eu.sql b/examples/official-site/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md similarity index 75% rename from examples/official-site/sqlpage/migrations/22_pgconf_eu.sql rename to examples/official-site/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md index 2647d3b09..81b8eed4f 100644 --- a/examples/official-site/sqlpage/migrations/22_pgconf_eu.sql +++ b/examples/official-site/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md @@ -1,10 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES ( - 'Come see me build twitter live on stage in Prague', - 'I will speak about SQLPage at pgconf.eu in Prague on December 14th. Come see me !', - 'calendar-event', - '2023-11-11', - ' +--- +title: Come see me build twitter live on stage in Prague +date: '2023-11-11' +icon: calendar-event +summary: I will speak about SQLPage at pgconf.eu in Prague on December 14th. Come see me ! +--- + # SQLPage live on stage Hello everyone ! @@ -25,5 +25,3 @@ Come see me ! - [Information about the talk](https://www.postgresql.eu/events/pgconfeu2023/schedule/session/4687-sqlpage-building-a-full-web-application-with-nothing-but-postgres-and-sql-queries/) - When ? **December 14th, 2023**, **09:30 - 10:20** - Where ? Zenit Room, [Clarion Congress Hotel, Prague, Czech Republic](https://maps.app.goo.gl/qHCAaRFRjXmx2kQA7) - -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/64_blog_routing.sql b/examples/official-site/content/blog/file-based-routing-in-sqlpage.md similarity index 73% rename from examples/official-site/sqlpage/migrations/64_blog_routing.sql rename to examples/official-site/content/blog/file-based-routing-in-sqlpage.md index 3467dc7fa..d1bc0c417 100644 --- a/examples/official-site/sqlpage/migrations/64_blog_routing.sql +++ b/examples/official-site/content/blog/file-based-routing-in-sqlpage.md @@ -1,12 +1,10 @@ +--- +title: File-based routing in SQLPage +date: '2025-07-28' +icon: route +summary: Understanding how SQLPage maps URLs to files and handles errors +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'File-based routing in SQLPage', - 'Understanding how SQLPage maps URLs to files and handles errors', - 'route', - '2025-07-28', - ' SQLPage uses a simple file-based routing system that maps URLs directly to SQL files in your project directory. No complex configuration is needed. Just create files and they become accessible endpoints. @@ -16,7 +14,7 @@ This guide explains how SQLPage resolves URLs, handles different file types, and ### 1. Site Prefix Handling -If you''ve configured a [`site_prefix`](/your-first-sql-website/nginx) in your settings, +If you've configured a [`site_prefix`](/your-first-sql-website/nginx) in your settings, SQLPage will redirect all requests that do not start with the prefix to `/`. ### 2. Path Resolution Priority @@ -27,18 +25,18 @@ SQLPage will redirect all requests that do not start with the prefix to `/ This is the english translation of an article [originally published in French on linuxfr.org](https://linuxfr.org/news/comment-l-archeologie-entre-progressivement-dans-l-ere-du-logiciel-libre). -> It illustrates how SQLPage is used by non-developers +> It illustrates how SQLPage is used by non-developers # How archaeology is gradually entering the era of free software @@ -19,7 +17,7 @@ Archaeology has, since its beginnings, focused on cataloging, structuring and ar French archaeology is divided into two main branches: preventive archaeology, which intervenes during construction projects, and programmed archaeology, conducted on sites chosen to address research issues. Supervised by the Regional Archaeological Services of the Ministry of Culture, these activities are carried out by different organizations: public and private operators for preventive archaeology, and associations, CNRS or universities for programmed archaeology. The latter often mobilizes volunteers, especially students, offering them complementary practical training. -For the archaeologist, excavation is a tool, not an end in itself. What the archaeologist seeks is information. In essence, it''s about understanding the history of a site, its evolution, its inhabitants through the elements they left behind, whether it''s the ruins of their habitats, their crafts or their burials. This is all the more important as excavation is a destructive act, since the archaeologist dismantles his subject of study as the excavation progresses. +For the archaeologist, excavation is a tool, not an end in itself. What the archaeologist seeks is information. In essence, it's about understanding the history of a site, its evolution, its inhabitants through the elements they left behind, whether it's the ruins of their habitats, their crafts or their burials. This is all the more important as excavation is a destructive act, since the archaeologist dismantles his subject of study as the excavation progresses. To be exploited, archaeological information must be organized according to well-established principles. The first key concept is the sedimentary layer (*Stratigraphic Unit* - SU), which testifies to a human action or a natural phenomenon. The study of the arrangement of these layers reveals the chronology of the site, the succession of events that took place there. These layers can be grouped into archaeological *facts*: ditches, cellars, burials, are indeed groupings of layers that define a specific element. Finally, the objects found in these layers, or *artifacts*, are cataloged and identified by their layer of origin, providing crucial chronological and cultural indications. @@ -41,7 +39,7 @@ Based on this report, the publication of articles in specialized journals allows The use of numerous paper listings is a constant. These listings allow keeping up-to-date records of data in the form of inventory tables of layers, facts, surveys, photos, etc. Specific recording sheets are also used in many specialties of archaeology, such as funerary anthropology. -In the field, the unearthed elements are still, for a very large majority, drawn by hand, on tracing or graph paper, whether it''s a plan of remains or the numerous stratigraphic section drawings. This of course requires significant time, especially in the case of complex remains. +In the field, the unearthed elements are still, for a very large majority, drawn by hand, on tracing or graph paper, whether it's a plan of remains or the numerous stratigraphic section drawings. This of course requires significant time, especially in the case of complex remains. The use of electronic tacheometers, then differential GPS, has made it possible to do without tape measures, or grid systems, when excavating sites. Topographers, specifically trained, then began to intervene on site for the realization of general plans. The documentary collection obtained at the end of an excavation is particularly precious. These are the only elements that will allow reconstructing the history of the site, by crossing these data with the result of the studies carried out. The fear of the disappearance of this data, or its use by others due to a remarkable discovery, is a feeling often shared within the archaeological community. The archaeologist may feel like a custodian of this information, even expressing a feeling of possession that goes completely against the idea of shared and open science. The idea that opening up data is the best way to protect it is far from obvious. @@ -60,7 +58,7 @@ In post-excavation, paper documentation is still often a fundamental documentary Listings can be integrated into databases (most often proprietary such as MS Access, FileMaker or 4D) or spreadsheets. Many databases have been developed internally, locally, by archaeologists themselves. Only attributive, they have gradually networked and adapted to the medium, allowing consideration of use in the field, without this being widely deployed. -![Database](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/exemple_bdd_fmp.png) +![Database](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/exemple_bdd_fmp.png) > *Example of a database at the turn of the 2000s* All documentation drawn in the field is to be redrawn cleanly on digital media, in vector drawing software, very often Adobe Illustrator, sometimes Inkscape. @@ -98,7 +96,7 @@ Indeed, in a complete dematerialization process, the memory of the site is no lo Unfortunately, free software remains little used in our archaeological daily life, and proprietary software is often very well established. Free software still suffers today from preconceptions and a bad image within the archaeological community, which finds it more complicated, less pretty, less effective, etc. -However, free software has made a major incursion with the arrival of the free Geographic Information System (GIS) [QGIS](https://www.qgis.org/en/site/), which allowed installing a GIS on all the agents'' workstations of the institute and considering it as an analysis tool at the scale of an archaeological site. Through support and the implementation of an adequate training plan, many archaeologists have been trained in the use of the software within the Institute. +However, free software has made a major incursion with the arrival of the free Geographic Information System (GIS) [QGIS](https://www.qgis.org/en/site/), which allowed installing a GIS on all the agents' workstations of the institute and considering it as an analysis tool at the scale of an archaeological site. Through support and the implementation of an adequate training plan, many archaeologists have been trained in the use of the software within the Institute. QGIS has truly revolutionized our practices by allowing immediate interrogation of attributive data by spatial data (what is this remains I see on the plan?) or, conversely, locating remains by their attributive data (where is burial 525?). However, it is still very common to have on one side the attributive data in spreadsheets or proprietary databases, and spatial data in QGIS, with the interrogation of both relying on joins. @@ -126,11 +124,11 @@ The format of the database was originally SpatiaLite. But the mass of documentat Naturally, Badass has been coupled with a QGIS project already offering default styles, but also some queries or views commonly used during an archaeological study. A QGIS extension has been developed by several students to allow automatic generation of the project and database. -Here''s the translation into idiomatic American English, keeping the original formatting: +Here's the translation into idiomatic American English, keeping the original formatting: -## Entering Badass: The Bad''Mobil +## Entering Badass: The Bad'Mobil -The question of the system''s portability remained. QGIS is a resource-intensive software with an interface ill-suited for small screens, which are preferred for their portability in the field (phones and tablets). +The question of the system's portability remained. QGIS is a resource-intensive software with an interface ill-suited for small screens, which are preferred for their portability in the field (phones and tablets). Choosing to use a SpatiaLite or PostGIS database allowed us to consider a web interface from the start, which could then be used on any device. Initially, we considered developing in PHP/HTML/CSS with an Apache web server. However, this required having a web server and programming an entire interface. There were also some infrastructure questions to address: where to host it, how to finance it, and who would manage it all? @@ -143,7 +141,7 @@ SQLPage is based on an executable file which, when launched on a computer, turns Thus, the installation of the entire system is very simple and relies only on a file structure to be deployed on the server: the database, and a directory containing the SQLPage binary and the files making up the web pages. -By relying on the documentation (and occasionally asking questions to the software''s author), we were able to develop a very comprehensive interface on our own that meets our needs in the field. Named Bad''Mobil, the web interface provides access to all the attribute data recorded by archaeologists and now allows, thanks to the constant development of SQLPage, **to visualize spatial data**. Documentation produced during the excavation can also be consulted if the files (photos, scanned drawings, etc.) are placed in the right location in the file structure. The pages mainly consist of creation or modification forms, as well as tables listing already recorded elements. The visualization of geometry allows for spatial orientation in the field, particularly in complex excavation sites, and interaction with attribute data. +By relying on the documentation (and occasionally asking questions to the software's author), we were able to develop a very comprehensive interface on our own that meets our needs in the field. Named Bad'Mobil, the web interface provides access to all the attribute data recorded by archaeologists and now allows, thanks to the constant development of SQLPage, **to visualize spatial data**. Documentation produced during the excavation can also be consulted if the files (photos, scanned drawings, etc.) are placed in the right location in the file structure. The pages mainly consist of creation or modification forms, as well as tables listing already recorded elements. The visualization of geometry allows for spatial orientation in the field, particularly in complex excavation sites, and interaction with attribute data. [![The BadMobil interface, with SQLPage](https://github.com/sqlpage/SQLPage/assets/552629/b421eebd-1d7a-446a-90d4-f360300453d5)](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/interface_badmobil.webp?ref_type=heads) *The BadMobil interface, with SQLPage* @@ -162,10 +160,10 @@ The homogeneity of the entered data is thus better, and the possibilities for qu ## Future Prospects -Following the development of Badass and Bad''mobil at the Les Mastraits necropolis, it seemed possible to consider its deployment in the context of preventive archaeology. While the question of the network infrastructure necessary for the operation of this solution may arise (need for stable electricity supply on remote sites in the countryside, availability of tablets, network coverage...), the benefits in terms of data homogeneity and ease of entry are very significant. A few preventive archaeology sites have thus been able to test the system, mostly on small-scale sites, benefiting from the support of collective members. +Following the development of Badass and Bad'mobil at the Les Mastraits necropolis, it seemed possible to consider its deployment in the context of preventive archaeology. While the question of the network infrastructure necessary for the operation of this solution may arise (need for stable electricity supply on remote sites in the countryside, availability of tablets, network coverage...), the benefits in terms of data homogeneity and ease of entry are very significant. A few preventive archaeology sites have thus been able to test the system, mostly on small-scale sites, benefiting from the support of collective members. Future developments will likely focus on integrating new forms or new monitoring tools. Currently, Badass allows for collecting observations common to all archaeological sites, as well as anthropological observations due to its use within the Les Mastraits necropolis. -We could consider integrating the many specialties of archaeology, but it''s likely that we would end up with a huge machine that could be complex to maintain. We therefore remain cautious on this subject. +We could consider integrating the many specialties of archaeology, but it's likely that we would end up with a huge machine that could be complex to maintain. We therefore remain cautious on this subject. # Conclusion @@ -177,10 +175,8 @@ QGIS has fundamentally revolutionized archaeological practice by offering GIS ac SQLpage has allowed us to offer archaeologists a complete and simple interface to access a networked database. While its development requires certain knowledge of SQL and website functioning, its deployment and maintenance are quite manageable. SQLPage addresses a real need in the field. For archaeologists, it simplifies their practice while responding to the growing complexity in the face of the documentary mass to be processed, and the increasing qualitative demands of deliverables. -The combination of QGIS, spatial and relational databases, and a web interface perfectly adapted to the field now fills the observed lack of an effective and reliable archaeological recording tool at the operation level. As such, Badass associated with Bad''Mobil fully meets the expectations of archaeologists who have experimented with them. +The combination of QGIS, spatial and relational databases, and a web interface perfectly adapted to the field now fills the observed lack of an effective and reliable archaeological recording tool at the operation level. As such, Badass associated with Bad'Mobil fully meets the expectations of archaeologists who have experimented with them. While open-source software has, in recent years, begun a timid breakthrough among many archaeological operators (some have fully adopted them), reluctance remains, whether from users or sometimes from the IT departments of public administrations, who may prefer to opt for an all-in-one service with technical support. -But the persistence of proprietary software usage is not without posing real problems regarding the sustainability of archaeological data, and archaeologists are just beginning to discover the issue. Their attachment to their data -- although it sometimes goes against the principle of open science -- should, however, encourage them to opt for formats whose durability appears certain, thereby guaranteeing access to this data in the future, regardless of the software or operating system used, if they don''t want their work to fall into oblivion... - ' - ); \ No newline at end of file +But the persistence of proprietary software usage is not without posing real problems regarding the sustainability of archaeological data, and archaeologists are just beginning to discover the issue. Their attachment to their data -- although it sometimes goes against the principle of open science -- should, however, encourage them to opt for formats whose durability appears certain, thereby guaranteeing access to this data in the future, regardless of the software or operating system used, if they don't want their work to fall into oblivion... diff --git a/examples/official-site/sqlpage/migrations/54_blog_bompard.sql b/examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md similarity index 91% rename from examples/official-site/sqlpage/migrations/54_blog_bompard.sql rename to examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md index 5fd16cd45..9670cc51c 100644 --- a/examples/official-site/sqlpage/migrations/54_blog_bompard.sql +++ b/examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md @@ -1,12 +1,10 @@ +--- +title: How I built a 360° performance monitoring tool with SQL Queries +date: '2025-01-25' +icon: shirt +summary: Alexis built a performance monitoring tool with SQLPage for a 100M€/year company +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'How I built a 360° performance monitoring tool with SQL Queries', - 'Alexis built a performance monitoring tool with SQLPage for a 100M€/year company', - 'shirt', - '2025-01-25', - ' # How I Built And Deployed An Exhaustive Performance Monitoring Tool For a 100M€/year Company Using SQL Queries Only ### Building web applications in SQL @@ -48,12 +46,12 @@ I am using SQLPage to build a 360° Performance tool for my company, integrating Here are some pages I built using only SQL queries, allowing everyone in the company to instantly access any level of information, from the fiscal year 2024 revenue trends to the top-selling products in Marseille in October 2022. -![](https://cdn-images-1.medium.com/max/800/1*MkORbAC7oGEG-8I1mthu6A.png) - +![](https://cdn-images-1.medium.com/max/800/1*MkORbAC7oGEG-8I1mthu6A.png)\ + *Performance of different channels vs last year and best sellers. -![](https://cdn-images-1.medium.com/max/800/1*_3-g1om_p9ghXhdcw0zHmw.png) - +![](https://cdn-images-1.medium.com/max/800/1*_3-g1om_p9ghXhdcw0zHmw.png)\ + *Examples of views built with SQLPage to provide a 360° tool for the company. ### Populating a chart from a query @@ -68,27 +66,27 @@ You can find the full list of components: [https://sql-page.com/documentation.sq Here’s an example of a parameterized SQL query that uses the “chart” component, along with the query to feed data into it: - - -```sql --- Chart Component -SELECT ''chart'' AS component, - CONCAT(''Daily Revenue from '', $start_date_comparison, '' to '', $end_date_comparison) AS title, - ''area'' AS type, - ''indigo'' AS color, - 5 AS marker, - 0 AS ymin; - --- Chart Data Query -SELECT DATE(business_date) AS x, - ROUND(SUM(value), 2) AS y -FROM data_example -WHERE DATE(business_date) BETWEEN $start_date_comparison AND $end_date_comparison - AND variable_name = ''CA'' -GROUP BY DATE(business_date) -ORDER BY x ASC; - --- NB: The variables $start_date_comparison and $end_date_comparison are + + +```sql +-- Chart Component +SELECT 'chart' AS component, + CONCAT('Daily Revenue from ', $start_date_comparison, ' to ', $end_date_comparison) AS title, + 'area' AS type, + 'indigo' AS color, + 5 AS marker, + 0 AS ymin; + +-- Chart Data Query +SELECT DATE(business_date) AS x, + ROUND(SUM(value), 2) AS y +FROM data_example +WHERE DATE(business_date) BETWEEN $start_date_comparison AND $end_date_comparison + AND variable_name = 'CA' +GROUP BY DATE(business_date) +ORDER BY x ASC; + +-- NB: The variables $start_date_comparison and $end_date_comparison are -- defined dynamically in the SQL script ``` And the result: @@ -138,4 +136,3 @@ What all these projects have in common is that they were built by a single perso - 📹Youtube tutorial videos on SQLPage channel: [https://www.youtube.com/@SQLPage/playlists](https://www.youtube.com/@SQLPage/playlists) - 🤓github: [https://github.com/sqlpage/SQLPage/](https://github.com/sqlpage/SQLPage/) - ☁️Host your applications: [https://datapage.app](https://datapage.app) -'); diff --git a/examples/official-site/sqlpage/migrations/71_blog_pagination.sql b/examples/official-site/content/blog/how-to-use-the-pagination-component.md similarity index 83% rename from examples/official-site/sqlpage/migrations/71_blog_pagination.sql rename to examples/official-site/content/blog/how-to-use-the-pagination-component.md index 859b9e8cc..374fab9e3 100644 --- a/examples/official-site/sqlpage/migrations/71_blog_pagination.sql +++ b/examples/official-site/content/blog/how-to-use-the-pagination-component.md @@ -1,12 +1,10 @@ +--- +title: How to use the pagination component +date: '2025-11-10' +icon: sailboat-2 +summary: A tutorial for using the pagination component +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'How to use the pagination component', - 'A tutorial for using the pagination component', - 'sailboat-2', - '2025-11-10', - ' # How to use the pagination component To display a large number of records from a database, it is often practical to split these data into pages. The user can thus navigate from one page to another, as well as directly to the first or last page. With SQLPage, it is possible to perform these operations using the pagination component. @@ -34,17 +32,17 @@ SET pages_count = (CAST($records_count AS INTEGER) / CAST($MAX_RECORD_PER_PAGE A ``` It is possible that the number of rows in the table is greater than the estimated number of pages multiplied by the number of rows per page. In this case, it is necessary to add an additional page. - + ``` SET pages_count = ( - CASE - WHEN MOD(CAST($records_count AS INTEGER),CAST($MAX_RECORD_PER_PAGE AS INTEGER)) = 0 THEN $pages_count - ELSE (CAST($pages_count AS INTEGER) + 1) + CASE + WHEN MOD(CAST($records_count AS INTEGER),CAST($MAX_RECORD_PER_PAGE AS INTEGER)) = 0 THEN $pages_count + ELSE (CAST($pages_count AS INTEGER) + 1) END ); ``` -We will need to transmit the page number to be displayed in the URL using the `page` parameter. We do the same for the number of the first page (`idx_page`) appearing at the left end of the pagination component. +We will need to transmit the page number to be displayed in the URL using the `page` parameter. We do the same for the number of the first page (`idx_page`) appearing at the left end of the pagination component. ![Meaning of URL parameters](blog/pagination.png) @@ -58,15 +56,15 @@ SET idx_page = COALESCE($idx_page,1); ## Read the data -We can now read and display the data based on the active page. To do this, we simply use a table component. +We can now read and display the data based on the active page. To do this, we simply use a table component. ``` -SELECT - ''table'' as component SELECT - user_id AS id, + 'table' as component +SELECT + user_id AS id, last_name AS "Last name", - first_name AS "First name" + first_name AS "First name" FROM users LIMIT CAST($MAX_RECORD_PER_PAGE AS INTEGER) @@ -88,13 +86,13 @@ SET previous_parameters = ( CASE WHEN CAST($page AS INTEGER) > 1 THEN json_object( - ''page'', (CAST($page AS INTEGER) - 1), - ''idx_page'', (CASE + 'page', (CAST($page AS INTEGER) - 1), + 'idx_page', (CASE WHEN CAST($idx_page AS INTEGER) > 1 THEN (CAST($idx_page AS INTEGER) - 1) ELSE $idx_page - END) + END) ) - ELSE json_object() END + ELSE json_object() END ); ``` @@ -105,11 +103,11 @@ SET next_parameters = ( CASE WHEN CAST($page AS INTEGER) < CAST($pages_count AS INTEGER) THEN json_object( - ''page'', (CAST($page AS INTEGER) + 1), - ''idx_page'', (CASE + 'page', (CAST($page AS INTEGER) + 1), + 'idx_page', (CASE WHEN CAST($idx_page AS INTEGER) < (CAST($pages_count AS INTEGER) - CAST($MAX_PAGES AS INTEGER) + 1) THEN (CAST($idx_page AS INTEGER) + 1) ELSE $idx_page - END) + END) ) ELSE json_object() END ); @@ -122,27 +120,27 @@ We can now add the pagination component, which is placed below the table display ``` SELECT - ''pagination'' AS component, + 'pagination' AS component, (CAST($page AS INTEGER) = 1) AS first_disabled, (CAST($page AS INTEGER) = 1) AS previous_disabled, (CAST($page AS INTEGER) = CAST($pages_count AS INTEGER)) AS next_disabled, (CAST($page AS INTEGER) = CAST($pages_count AS INTEGER)) AS last_disabled, - sqlpage.link(sqlpage.path(), json_object(''page'', 1, ''idx_page'', 1)) as first_link, + sqlpage.link(sqlpage.path(), json_object('page', 1, 'idx_page', 1)) as first_link, sqlpage.link(sqlpage.path(), $previous_parameters) AS previous_link, sqlpage.link(sqlpage.path(), $next_parameters) AS next_link, sqlpage.link( sqlpage.path(), - json_object(''page'', $pages_count, ''idx_page'', ( + json_object('page', $pages_count, 'idx_page', ( CASE WHEN (CAST($pages_count AS INTEGER) <= CAST($MAX_PAGES AS INTEGER)) THEN 1 - ELSE (CAST($pages_count AS INTEGER) - CAST($MAX_PAGES AS INTEGER) + 1) + ELSE (CAST($pages_count AS INTEGER) - CAST($MAX_PAGES AS INTEGER) + 1) END) ) ) AS last_link, TRUE AS outline; ``` -The final step is to generate the page numbers based on the number of pages and the index of the first page displayed to the left of the component. To do this, we use a recursive CTE query. +The final step is to generate the page numbers based on the number of pages and the index of the first page displayed to the left of the component. To do this, we use a recursive CTE query. ``` WITH RECURSIVE page_numbers AS ( @@ -152,12 +150,11 @@ WITH RECURSIVE page_numbers AS ( FROM page_numbers LIMIT CAST($MAX_PAGES AS INTEGER) ) -SELECT +SELECT number AS contents, - sqlpage.link(sqlpage.path(), json_object(''page'', number, ''idx_page'', $idx_page)) as link, - (number = CAST($page AS INTEGER)) AS active + sqlpage.link(sqlpage.path(), json_object('page', number, 'idx_page', $idx_page)) as link, + (number = CAST($page AS INTEGER)) AS active FROM page_numbers; ``` If the added page matches the content of the `page` variable, the `active` option is set to `TRUE` so that the user knows it is the current page. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/14_sorry_i_forked.sql b/examples/official-site/content/blog/im-sorry-i-forked-you.md similarity index 94% rename from examples/official-site/sqlpage/migrations/14_sorry_i_forked.sql rename to examples/official-site/content/blog/im-sorry-i-forked-you.md index a21276b27..43bd7614f 100644 --- a/examples/official-site/sqlpage/migrations/14_sorry_i_forked.sql +++ b/examples/official-site/content/blog/im-sorry-i-forked-you.md @@ -1,10 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES ( - 'I’m sorry I forked you', - 'SQLPage forked the sqlx database drivers library. Here is why.', - 'git-fork', - '2023-08-13', - ' +--- +title: I’m sorry I forked you +date: '2023-08-13' +icon: git-fork +summary: SQLPage forked the sqlx database drivers library. Here is why. +--- + # I’m sorry I forked you I’ve been immersed in open source coding since my teenage years, and now, I can’t fathom a world without it. @@ -13,7 +13,7 @@ Each company adds its proprietary touch to this vast open source landscape, but they are ultimately just forming a unique blend atop a colossal iceberg of shared resources. In the software world, open source truly is the driving force behind innovation. -## Unconventional Financial Currents in Software +## Unconventional Financial Currents in Software The software industry operates on a financial current that defies conventional norms. Unlike other sectors where key players like oil companies rake in the riches by supplying essentials to other businesses, @@ -45,7 +45,7 @@ and the introduction of a new API, making it non trivial to migrate from the pre ## SQLPage As the principal caretaker of the [SQLPage web application server](/), which relies on sqlx, -I faced a pivotal juncture. The path ahead diverged into two distinct trails: +I faced a pivotal juncture. The path ahead diverged into two distinct trails: 1. a challenging migration to sqlx v0.7, making a cross on MSSQL support; 2. persisting with v0.6, a realm housing outdated and potentially vulnerable dependencies. @@ -94,4 +94,3 @@ The main contributor to sqlx reacted to this post, and they wanted to clarify tw (unlike SQLPage, which is free to use even in conjunction with proprietary software, under the *MIT* license). Companies that want to use these future sqlx drivers in proprietary software will have to pay for a commercial license. That change in the decision has been announced in 2022, and I should have been aware of it when I wrote this post. My bad. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/42_blog_video.sql b/examples/official-site/content/blog/introduction-video.md similarity index 70% rename from examples/official-site/sqlpage/migrations/42_blog_video.sql rename to examples/official-site/content/blog/introduction-video.md index 4cd0a09d4..78ce294b4 100644 --- a/examples/official-site/sqlpage/migrations/42_blog_video.sql +++ b/examples/official-site/content/blog/introduction-video.md @@ -1,12 +1,10 @@ +--- +title: Introduction video +date: '2024-05-14' +icon: brand-youtube +summary: A 30-minute live presentation of SQLPage, its raison d'être, and how to use it. +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Introduction video', - 'A 30-minute live presentation of SQLPage, its raison d''être, and how to use it.', - 'brand-youtube', - '2024-05-14', - ' # Introduction video ## Canadians love SQLPage @@ -16,7 +14,7 @@ by Anton Avramov, an avid SQLPage user and community member, who gave a live dem ## The video -The user group kindly invited me (Ophir, the initial creator and main contributor to SQLPage) +The user group kindly invited me (Ophir, the initial creator and main contributor to SQLPage) to record a video introduction to SQLPage, which I did. The video is a 5 minute introduction to the philosophy behind SQLPage, @@ -24,7 +22,6 @@ followed by a 25 minute live demonstration of how to create [this todo list application](https://github.com/sqlpage/SQLPage/tree/main/examples/todo%20application) from scratch. -Watch it on youtube: +Watch it on youtube: [![video cover](https://i.ytimg.com/vi/9NJgH_-zXjY/maxresdefault.jpg)](https://www.youtube.com/watch?v=9NJgH_-zXjY) -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/50_blog_json.sql b/examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md similarity index 78% rename from examples/official-site/sqlpage/migrations/50_blog_json.sql rename to examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md index 7e6aa4662..44c42339c 100644 --- a/examples/official-site/sqlpage/migrations/50_blog_json.sql +++ b/examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md @@ -1,11 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'JSON in SQL: A Comprehensive Guide', - 'A comprehensive guide to working with JSON data in SQLite, PostgreSQL, MySQL, and SQL Server.', - 'braces', - '2024-09-03', - ' +--- +title: 'JSON in SQL: A Comprehensive Guide' +date: '2024-09-03' +icon: braces +summary: A comprehensive guide to working with JSON data in SQLite, PostgreSQL, MySQL, and SQL Server. +--- + # JSON in SQL: A Comprehensive Guide ## Introduction @@ -29,7 +28,7 @@ JSON supports the following data types: ## Sample Table -We''ll use the following sample table for our examples: +We'll use the following sample table for our examples: ```sql CREATE TABLE users ( @@ -40,9 +39,9 @@ CREATE TABLE users ( ); INSERT INTO users (id, name, birthday, group_name) VALUES -(1, ''Alice'', ''1990-01-15'', ''Admin''), -(2, ''Bob'', ''1985-05-22'', ''User''), -(3, ''Charlie'', ''1992-09-30'', ''User''); +(1, 'Alice', '1990-01-15', 'Admin'), +(2, 'Bob', '1985-05-22', 'User'), +(3, 'Charlie', '1992-09-30', 'User'); ``` ## SQLite @@ -55,7 +54,7 @@ See [the list of JSON functions in SQLite](https://www.sqlite.org/json1.html) fo We can use the standard `json_object()` function to create a JSON object from columns in a table: ```sql -SELECT json_object(''name'', name, ''birthday'', birthday) AS user_json +SELECT json_object('name', name, 'birthday', birthday) AS user_json FROM users; ``` @@ -106,7 +105,7 @@ FROM users; SQLite provides the `json_each()` table-valued function to iterate over JSON arrays. This function returns one row for each element in the JSON array. ```sql -SELECT value FROM json_each(''["Alice", "Bob", "Charlie"]''); +SELECT value FROM json_each('["Alice", "Bob", "Charlie"]'); ``` | value | @@ -119,21 +118,21 @@ The `json_each()` function returns a table with several columns. The most common - `key`: The array index (0-based) for elements of a JSON array - `value`: The value of the current element -- `type`: The type of the current element (e.g., ''text'', ''integer'', ''real'', ''true'', ''false'', ''null'') +- `type`: The type of the current element (e.g., 'text', 'integer', 'real', 'true', 'false', 'null') For more complex JSON structures, you can use the `json_tree()` function, which recursively walks through the entire JSON structure. These iteration functions can be used to check if specific values exist in a JSON array. -Here''s a practical example: -Let''s say you have a form with a [multiple-choice dropdown](documentation.sql?component=form#component) that allows selecting multiple users. +Here's a practical example: +Let's say you have a form with a [multiple-choice dropdown](documentation.sql?component=form#component) that allows selecting multiple users. Some users might already be selected, and their IDs are stored in a JSON array passed as an URL parameter called `$selected_ids`. You can create this dropdown using the following query: ```sql select json_group_array(json_object( - ''label'', name, - ''value'', id, - ''selected'', id in (select value from json_each_text($selected_ids)) + 'label', name, + 'value', id, + 'selected', id in (select value from json_each_text($selected_ids)) )) as options from users; ``` @@ -142,14 +141,14 @@ This query will: 1. Create a dropdown option for each user 2. Use their name as the display label 3. Use their ID as the value -4. Mark the option as selected if the user''s ID exists in the $selected_ids array +4. Mark the option as selected if the user's ID exists in the $selected_ids array ### Combining two JSON objects SQLite provides the `json_patch()` function to combine two JSON objects. This function takes two JSON objects as arguments and returns a new JSON object that is the result of merging the two input objects. ```sql -SELECT json_patch(''{"name": "Alice"}'', ''{"birthday": "1990-01-15"}'') AS user_json; +SELECT json_patch('{"name": "Alice"}', '{"birthday": "1990-01-15"}') AS user_json; ``` | user_json | @@ -166,8 +165,8 @@ See [the list of JSON functions in PostgreSQL](https://www.postgresql.org/docs/c ```sql SELECT jsonb_build_object( - ''name'', name, - ''birthday'', birthday + 'name', name, + 'birthday', birthday ) AS user_json FROM users; ``` @@ -222,7 +221,7 @@ FROM users; ### Iterating over a JSON array ```sql -SELECT name FROM jsonb_array_elements_text(''["Alice", "Bob", "Charlie"]''::jsonb) AS name; +SELECT name FROM jsonb_array_elements_text('["Alice", "Bob", "Charlie"]'::jsonb) AS name; ``` | name | @@ -236,9 +235,9 @@ You can use this function to test whether a value is present in a JSON array. Fo ```sql SELECT jsonb_agg(jsonb_build_object( - ''label'', name, - ''value'', id, - ''selected'', id in (SELECT value FROM jsonb_array_elements_text($selected_ids::jsonb)) + 'label', name, + 'value', id, + 'selected', id in (SELECT value FROM jsonb_array_elements_text($selected_ids::jsonb)) )) AS options FROM users; ``` @@ -247,7 +246,7 @@ FROM users; ```sql SELECT key, value -FROM jsonb_each_text(''{"name": "Alice", "birthday": "1990-01-15"}''::jsonb); +FROM jsonb_each_text('{"name": "Alice", "birthday": "1990-01-15"}'::jsonb); ``` | key | value | @@ -260,12 +259,12 @@ FROM jsonb_each_text(''{"name": "Alice", "birthday": "1990-01-15"}''::jsonb); PostgreSQL allows you to query JSON data using the `->` and `->>` operators: ```sql -SELECT name, user_data->>''age'' AS age +SELECT name, user_data->>'age' AS age FROM ( - SELECT name, jsonb_build_object(''age'', EXTRACT(YEAR FROM AGE(birthday))) AS user_data + SELECT name, jsonb_build_object('age', EXTRACT(YEAR FROM AGE(birthday))) AS user_data FROM users ) subquery -WHERE (user_data->>''age'')::int > 30; +WHERE (user_data->>'age')::int > 30; ``` | name | age | @@ -274,10 +273,10 @@ WHERE (user_data->>''age'')::int > 30; ### Combining two JSON objects -PostgreSQL provides the `||` operator to combine two JSON objects. +PostgreSQL provides the `||` operator to combine two JSON objects. ```sql -SELECT ''{"name": "Alice"}''::jsonb || ''{"birthday": "1990-01-15"}''::jsonb AS user_json; +SELECT '{"name": "Alice"}'::jsonb || '{"birthday": "1990-01-15"}'::jsonb AS user_json; ``` | user_json | @@ -292,7 +291,7 @@ See [the list of JSON functions in MySQL](https://dev.mysql.com/doc/refman/8.0/e ### Creating a JSON object ```sql -SELECT JSON_OBJECT(''name'', name, ''birthday'', birthday) AS user_json +SELECT JSON_OBJECT('name', name, 'birthday', birthday) AS user_json FROM users; ``` @@ -341,13 +340,13 @@ FROM users; MySQL provides the JSON_TABLE() function to iterate over JSON arrays. This powerful function allows you to convert JSON data into a relational table format, making it easy to work with JSON arrays. -Here''s an example of how to use JSON_TABLE() to iterate over a JSON array: +Here's an example of how to use JSON_TABLE() to iterate over a JSON array: ```sql SELECT jt.name FROM JSON_TABLE( - ''["Alice", "Bob", "Charlie"]'', - ''$[*]'' COLUMNS( name VARCHAR(50) PATH ''$'' ) + '["Alice", "Bob", "Charlie"]', + '$[*]' COLUMNS( name VARCHAR(50) PATH '$' ) ) AS jt; ``` @@ -359,19 +358,19 @@ FROM JSON_TABLE( In this example: - The first argument to JSON_TABLE() is the JSON array. -- `''$[*]''` is the path expression that selects all elements of the array. +- `'$[*]'` is the path expression that selects all elements of the array. - The `COLUMNS` clause defines the structure of the output table. In our case, we want a single column named `name`: - - `name VARCHAR(50) PATH ''$''` creates a text column that contains the raw value of each array element in its entirety (`$` is the current element). + - `name VARCHAR(50) PATH '$'` creates a text column that contains the raw value of each array element in its entirety (`$` is the current element). You can also use JSON_TABLE() with more complex JSON structures: ```sql SELECT jt.* FROM JSON_TABLE( - ''[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]'', - ''$[*]'' COLUMNS( - id INT PATH ''$.id'', - name VARCHAR(50) PATH ''$.name'' + '[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]', + '$[*]' COLUMNS( + id INT PATH '$.id', + name VARCHAR(50) PATH '$.name' ) ) AS jt; ``` @@ -391,9 +390,9 @@ The `JSON_TABLE` function can also be used to iterate over JSON objects: ```sql SELECT jt.* FROM JSON_TABLE( - ''{"name": "Alice", "birthday": "1990-01-15"}'', - ''$.*'' COLUMNS ( - value JSON PATH ''$'' + '{"name": "Alice", "birthday": "1990-01-15"}', + '$.*' COLUMNS ( + value JSON PATH '$' ) ) AS jt; ``` @@ -409,10 +408,10 @@ You can use the `JSON_KEYS()` function to retrieve the list of keys in a JSON ob then use that array to iterate over the keys of a JSON object: ```sql -SELECT json_key, json_extract(json_str, CONCAT(''$.'', json_key)) as json_value +SELECT json_key, json_extract(json_str, CONCAT('$.', json_key)) as json_value FROM - (select ''{"name": "Alice", "birthday": "1990-01-15"}'' as json_str) AS my_json, - JSON_TABLE(json_keys(json_str), ''$[*]'' COLUMNS (json_key JSON PATH ''$'')) AS json_keys; + (select '{"name": "Alice", "birthday": "1990-01-15"}' as json_str) AS my_json, + JSON_TABLE(json_keys(json_str), '$[*]' COLUMNS (json_key JSON PATH '$')) AS json_keys; ``` | json_key | json_value | @@ -425,12 +424,12 @@ FROM MySQL allows you to query JSON data using the `->` and `->>` operators: ```sql -SELECT name, user_data->''$.age'' AS age +SELECT name, user_data->'$.age' AS age FROM ( - SELECT name, JSON_OBJECT(''age'', YEAR(CURDATE()) - YEAR(birthday)) AS user_data + SELECT name, JSON_OBJECT('age', YEAR(CURDATE()) - YEAR(birthday)) AS user_data FROM users ) subquery -WHERE user_data->''$.age'' > 30; +WHERE user_data->'$.age' > 30; ``` | name | age | @@ -469,7 +468,7 @@ FROM users; Alternatively, you can use the `JSON_OBJECT` function: ```sql -SELECT JSON_OBJECT(''name'': name, ''birthday'': birthday) AS user_json +SELECT JSON_OBJECT('name': name, 'birthday': birthday) AS user_json FROM users; ``` @@ -524,7 +523,7 @@ SELECT JSON_OBJECTAGG(name: birthday) AS name_birthday_map FROM users; Use the `OPENJSON` function to iterate over JSON arrays: ```sql -SELECT value FROM OPENJSON(''["Alice", "Bob", "Charlie"]''); +SELECT value FROM OPENJSON('["Alice", "Bob", "Charlie"]'); ``` | value | @@ -539,10 +538,10 @@ Use `OPENJSON` to iterate over JSON objects: ```sql SELECT * -FROM OPENJSON(''{"name": "Alice", "birthday": "1990-01-15"}'') +FROM OPENJSON('{"name": "Alice", "birthday": "1990-01-15"}') WITH ( - name NVARCHAR(50) ''$.name'', - birthday DATE ''$.birthday'' + name NVARCHAR(50) '$.name', + birthday DATE '$.birthday' ); ``` @@ -555,7 +554,7 @@ WITH ( Use the `JSON_VALUE` function to extract scalar values from JSON: ```sql -SELECT JSON_VALUE(''{"age": 38}'', ''$.age'') AS age +SELECT JSON_VALUE('{"age": 38}', '$.age') AS age ``` | age | @@ -574,7 +573,7 @@ SQL Server provides several other useful JSON functions: Example using `JSON_MODIFY`: ```sql -SELECT JSON_MODIFY(''{"name": "Alice", "age": 30}'', ''$.age'', 31) AS updated_json; +SELECT JSON_MODIFY('{"name": "Alice", "age": 30}', '$.age', 31) AS updated_json; ``` | updated_json | @@ -582,4 +581,3 @@ SELECT JSON_MODIFY(''{"name": "Alice", "age": 30}'', ''$.age'', 31) AS updated_j | {"name": "Alice", "age": 31} | This comprehensive guide covers the basics of working with JSON in SQLite, PostgreSQL, MySQL, and SQL Server. Each database has its own set of functions and syntax for JSON operations, but the general concepts remain similar across all platforms. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/33_blog_v018.sql b/examples/official-site/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md similarity index 81% rename from examples/official-site/sqlpage/migrations/33_blog_v018.sql rename to examples/official-site/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md index 627b6d971..141987463 100644 --- a/examples/official-site/sqlpage/migrations/33_blog_v018.sql +++ b/examples/official-site/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md @@ -1,33 +1,31 @@ +--- +title: New SQLPage, and a talk at PGConf.eu +date: '2024-01-29' +icon: brand-youtube +summary: SQLPage v0.18.0 is out, and there is detailed introduction to SQLPage on youtube +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'New SQLPage, and a talk at PGConf.eu', - 'SQLPage v0.18.0 is out, and there is detailed introduction to SQLPage on youtube', - 'brand-youtube', - '2024-01-29', - ' -[SQLPage](https://sql-page.com) is a small web server that renders your SQL queries as beautiful interactive websites. This release has seen significant new features and fixes from new contributors, which is great and show the health of the project ! If you feel something is missing or isn''t working quite right, all your contributions are always welcome. +[SQLPage](https://sql-page.com) is a small web server that renders your SQL queries as beautiful interactive websites. This release has seen significant new features and fixes from new contributors, which is great and show the health of the project ! If you feel something is missing or isn't working quite right, all your contributions are always welcome. On a side note, I [gave a talk about SQLPage last December at PGConf.eu](https://www.youtube.com/watch?v=mXdgmSdaXkg). It is a great detailed introduction to SQLPage, and I recommend it if you want to learn more about the project. -1. **New `tracking` component for beautiful and compact status reports:** This feature adds a new way to display status reports, making them more visually appealing and concise. +1. **New `tracking` component for beautiful and compact status reports:** This feature adds a new way to display status reports, making them more visually appealing and concise. 1. ![screenshot](https://github.com/sqlpage/SQLPage/assets/552629/3e792953-3870-469d-a01d-898316b2ab32) 3. **New `divider` component to add a horizontal line between other components:** This simple yet useful addition allows for better separation of elements on your pages. 1. ![image](https://github.com/sqlpage/SQLPage/assets/552629/09a2cc77-3b37-401f-ab3e-441637a2c022) -5. **New `breadcrumb` component to display a breadcrumb navigation bar:** This component helps users navigate through your website''s hierarchical structure, providing a clear path back to the homepage. +5. **New `breadcrumb` component to display a breadcrumb navigation bar:** This component helps users navigate through your website's hierarchical structure, providing a clear path back to the homepage. 1. ![image](https://github.com/sqlpage/SQLPage/assets/552629/cbf2174a-1d75-499e-9d6b-e111136dbbbc) 8. **Multi-column layouts with `embed` attribute in `card` component:** This feature enables you to create more complex and dynamic layouts within cards. 1. ![image](https://github.com/sqlpage/SQLPage/assets/552629/3f4435f0-d89b-424e-8b8a-39385a61d5ad) -6. **Customizable y-axis step size in `chart` component with `ystep` attribute:** This feature gives you more control over the chart''s appearance, especially for situations with multiple series. - +6. **Customizable y-axis step size in `chart` component with `ystep` attribute:** This feature gives you more control over the chart's appearance, especially for situations with multiple series. + 7. **Updated default graph colors for better distinction:** This enhancement ensures clarity and easy identification of different data series. 10. **ID and class attributes for all components for easier styling and referencing:** This improvement simplifies custom CSS customization and inter-page element linking. @@ -39,6 +37,3 @@ It is a great detailed introduction to SQLPage, and I recommend it if you want t 13. **Unicode support for built-in SQLite database:** This enables case-insensitive string comparisons and lower/upper case transformations. 5. **Improved `card` component with smaller margin below footer text:** This fix ensures consistent and visually balanced card layouts. - - ' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/69_blog_performance_guide.sql b/examples/official-site/content/blog/performance-guide.md similarity index 89% rename from examples/official-site/sqlpage/migrations/69_blog_performance_guide.sql rename to examples/official-site/content/blog/performance-guide.md index c9f369d49..2bb0f24b1 100644 --- a/examples/official-site/sqlpage/migrations/69_blog_performance_guide.sql +++ b/examples/official-site/content/blog/performance-guide.md @@ -1,12 +1,10 @@ +--- +title: Performance Guide +date: '2025-10-31' +icon: bolt +summary: Concrete advice on how to make your SQLPage webapp fast +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Performance Guide', - 'Concrete advice on how to make your SQLPage webapp fast', - 'bolt', - '2025-10-31', - ' # Performance Guide SQLPage is [optimized](/performance) @@ -23,7 +21,7 @@ the second part of the quide: *SQLPage-specific advice*. The best way to ensure your SQLPage webapp is fast is to ensure your database is well managed and your SQL queries are well written. -We''ll go over the most common database performance pitfalls so that you know how to avoid them. +We'll go over the most common database performance pitfalls so that you know how to avoid them. ### Choose the right database schema @@ -61,7 +59,7 @@ CREATE TABLE sale ( Always use foreign keys instead of trying to store redundant data such as store names in the sales table. -This way, when you need to display the list of stores in your application, you don''t have to +This way, when you need to display the list of stores in your application, you don't have to run a slow `select distinct store from sales`, that would have to go through your millions of sales (*even if you have an index on the store column*), you just query the tiny `stores` table directly. @@ -172,7 +170,7 @@ Such databases can be used with SQLPage by using their [ODBC](https://en.wikiped ## SQLPage-specific advice The best way to make your SQLPage webapp fast is to make your queries fast. -Sometimes, you just don''t have control over the database, and have to run slow queries. +Sometimes, you just don't have control over the database, and have to run slow queries. This section will help you minimize the impact to your users. ### Order matters @@ -186,7 +184,7 @@ So, if you have to execute a slow query, put it as far down in the page as possi Every user-facing page in a SQLPage site has a [shell](/component.sql?component=shell). The first queries in any sql file (all the ones that come before the [shell](/component.sql?component=shell)) -are executed before any data has been sent to the user''s browser. +are executed before any data has been sent to the user's browser. During that time, the user will see a blank screen. So, ensure your shell comes as early as possible, and does not require any heavy computation. If you can make your shell entirely static (independent of the database), do so, @@ -204,16 +202,16 @@ In this case, avoid recomputing it on every use inside the page. #### Reusing a single database record -When that data is small, store it in a sqlpage variable as JSON and then +When that data is small, store it in a sqlpage variable as JSON and then extract the data you need using [json operations](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). ```sql set product = ( - select json_object(''name'', name, ''price'', price) -- in postgres, you can simply use row_to_json(product) + select json_object('name', name, 'price', price) -- in postgres, you can simply use row_to_json(product) from products where id = $product_id ); -select ''alert'' as component, ''Product'' as title, $product->>''name'' as description; +select 'alert' as component, 'Product' as title, $product->>'name' as description; ``` #### Reusing a large query result set @@ -226,14 +224,14 @@ In this case, store the filtered data in a temporary table and then reuse it in ```sql drop table if exists filtered_products; create temporary table filtered_products as -select * from products where +select * from products where ($category is null or category = $category) and ($manufacturer is null or manufacturer = $manufacturer); -select ''alert'' as component, count(*) || '' products'' as title +select 'alert' as component, count(*) || ' products' as title from filtered_products; -select ''list'' as component; +select 'list' as component; select name as title from filtered_products; ``` @@ -241,25 +239,25 @@ select name as title from filtered_products; Each query you execute has an overhead of at least the time it takes to send a packet back and forth between SQLPage and the database. -When it''s possible, combine multiple queries into a single one, possibly using +When it's possible, combine multiple queries into a single one, possibly using [`UNION ALL`](https://en.wikipedia.org/wiki/Set_operations_(SQL)#UNION_operator). ```sql -select ''big_number'' as component; +select 'big_number' as component; with stats as ( select count(*) as total, avg(price) as average_price from filtered_products ) -select ''count'' as title, stats.total as value from stats +select 'count' as title, stats.total as value from stats union all -select ''average price'' as title, stats.average_price as value from stats; +select 'average price' as title, stats.average_price as value from stats; ``` ### Lazy loading -Use the [card](/component?component=card) and [modal](/component?component=modal) components +Use the [card](/component?component=card) and [modal](/component?component=modal) components with the `embed` attribute to load data lazily. -Lazy loaded content is not sent to the user''s browser when the page initially loads, +Lazy loaded content is not sent to the user's browser when the page initially loads, so it does not block the initial rendering of the page and provides a better experience for data that might be slow to load. @@ -277,8 +275,7 @@ database is configured to allow opening many simultaneous connections. When `environment` is set to `development` in its [configuration](https://github.com/sqlpage/SQLPage/blob/main/configuration.md), SQLPage will include precise measurement of the time it spends in each of the steps it has to go through before starting to send data -back to the user''s browser. You can visualize that performance data in your browser''s network inspector. +back to the user's browser. You can visualize that performance data in your browser's network inspector. You can set the `RUST_LOG` environment variable to `sqlpage=debug` to make SQLPage print detailed messages associated with precise timing for everything it does. -'); diff --git a/examples/official-site/content/blog/repeating-yourself-thrice-won-t-make-you-a-3x-developer.md b/examples/official-site/content/blog/repeating-yourself-thrice-won-t-make-you-a-3x-developer.md new file mode 100644 index 000000000..06c635513 --- /dev/null +++ b/examples/official-site/content/blog/repeating-yourself-thrice-won-t-make-you-a-3x-developer.md @@ -0,0 +1,8 @@ +--- +title: Repeating yourself thrice won't make you a 3X developer +date: '2023-08-01' +icon: box-multiple-3 +summary: A dive into the traditional 3-tier architecture and the DRY principle, and how tools like SQLPage + helps you avoid repeating yourself. +external_url: https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0 +--- diff --git a/examples/official-site/sqlpage/migrations/26_v0.17_release.sql b/examples/official-site/content/blog/sqlpage-v0-17.md similarity index 78% rename from examples/official-site/sqlpage/migrations/26_v0.17_release.sql rename to examples/official-site/content/blog/sqlpage-v0-17.md index 60bff5990..e435dee90 100644 --- a/examples/official-site/sqlpage/migrations/26_v0.17_release.sql +++ b/examples/official-site/content/blog/sqlpage-v0-17.md @@ -1,14 +1,14 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES ( - 'SQLPage v0.17', - 'SQLPage v0.17 introduces file uploads, HTTPS, and more.', - 'git-fork', - '2023-11-28', - ' +--- +title: SQLPage v0.17 +date: '2023-11-28' +icon: git-fork +summary: SQLPage v0.17 introduces file uploads, HTTPS, and more. +--- + # SQLPage v0.17 is out ! [SQLPage](/) is a web application server that lets you build entire web applications with just SQL queries. -v0.17 was just released, and it''s worth a blog post to highlight some of the coolest new features. +v0.17 was just released, and it's worth a blog post to highlight some of the coolest new features. Mostly, this release makes it a matter of minutes to build a data import pipeline for your website, and a matter of seconds to deploy your SQLPage website securely with automatic HTTPS certificates. @@ -19,11 +19,11 @@ This release is all about a long awaited feature: **file uploads**. Your SQLPage website can now accept file uploads from users, store them either in a directory or directly in a database table. -You can add a file upload button to a form with a simple +You can add a file upload button to a form with a simple ```sql -select ''form'' as component; -select ''profile_picture'' as name, ''file'' as type; +select 'form' as component; +select 'profile_picture' as name, 'file' as type; ``` when received by the server, the file will be saved in a temporary directory @@ -35,8 +35,8 @@ You can then persist the upload as a permanent file on the server with the [`sqlpage.exec`](https://sql-page.com/functions.sql?function=exec#function) function: ```sql -set file_path = sqlpage.uploaded_file_path(''profile_picture''); -select sqlpage.exec(''mv'', $file_path, ''/path/to/my/file''); +set file_path = sqlpage.uploaded_file_path('profile_picture'); +select sqlpage.exec('mv', $file_path, '/path/to/my/file'); ``` or you can store it directly in a database table with the new @@ -44,8 +44,8 @@ or you can store it directly in a database table with the new [`sqlpage.read_file_as_text`](https://sql-page.com/functions.sql?function=read_file_as_text#function) functions: ```sql -insert into files (url) values (sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''profile_picture''))) -returning ''text'' as component, ''Uploaded new file with id: '' || id as contents; +insert into files (url) values (sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('profile_picture'))) +returning 'text' as component, 'Uploaded new file with id: ' || id as contents; ``` The maximum size of uploaded files is configurable with the [`max_uploaded_file_size`](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) @@ -54,7 +54,7 @@ configuration parameter. By default, it is set to 5 MiB. ### Parsing CSV files SQLPage can also parse uploaded [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) files and insert them directly into a database table. -SQLPage re-uses PostgreSQL''s [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html) +SQLPage re-uses PostgreSQL's [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html) to import the CSV file into the database. When connected to a PostgreSQL database, SQLPage will use the native `COPY` statement, for super fast and efficient on-database CSV parsing. @@ -63,8 +63,8 @@ parsing the CSV locally and emulating the same behavior with simple `INSERT` sta #### `user_file_upload.sql` ```sql -select ''form'' as component, ''bulk_user_import.sql'' as action; -select ''user_csv_file'' as name, ''file'' as type, ''text/csv'' as accept; +select 'form' as component, 'bulk_user_import.sql' as action; +select 'user_csv_file' as name, 'file' as type, 'text/csv' as accept; ``` #### `bulk_user_import.sql` @@ -72,18 +72,18 @@ select ''user_csv_file'' as name, ''file'' as type, ''text/csv'' as accept; -- create a temporary table to preprocess the data create temporary table if not exists csv_import(name text, age text); delete from csv_import; -- empty the table --- If you don''t have any preprocessing to do, you can skip the temporary table and use the target table directly +-- If you don't have any preprocessing to do, you can skip the temporary table and use the target table directly -copy csv_import(name, age) from ''user_csv_file'' -with (header true, delimiter '','', quote ''"'', null ''NaN''); -- all the options are optional +copy csv_import(name, age) from 'user_csv_file' +with (header true, delimiter ',', quote '"', null 'NaN'); -- all the options are optional -- since header is true, the first line of the file will be used to find the "name" and "age" columns --- if you don''t have a header line, the first column in the CSV will be interpreted as the first column of the table, etc +-- if you don't have a header line, the first column in the CSV will be interpreted as the first column of the table, etc -- run any preprocessing you want on the data here -- insert the data into the users table insert into users (name, birth_date) -select upper(name), date_part(''year'', CURRENT_DATE) - cast(age as int) from csv_import; +select upper(name), date_part('year', CURRENT_DATE) - cast(age as int) from csv_import; ``` ### New functions @@ -116,7 +116,7 @@ that would compromise your security if you get it wrong. With SQLPage v0.17, you just give your domain name, and it takes care of everything. -And while we''re at it, SQLPage also supports HTTP/2, for even faster page loads. +And while we're at it, SQLPage also supports HTTP/2, for even faster page loads. To enable HTTPS, you need to buy a [domain name](https://en.wikipedia.org/wiki/Domain_name) and make it point to the server where SQLPage is running. @@ -128,9 +128,9 @@ Then set the `https_domain` configuration parameter to `yourdomain.com` in your } ``` -That''s it. No external tool to install, no certificate to generate, no configuration to tweak. +That's it. No external tool to install, no certificate to generate, no configuration to tweak. No need to restart SQLPage regularly either, or to worry about renewing your certificate when it expires. -SQLPage will automatically request a certificate from [Let''s Encrypt](https://letsencrypt.org/) by default, +SQLPage will automatically request a certificate from [Let's Encrypt](https://letsencrypt.org/) by default, and does not even need to listen on port 80 to do so. ## SQL parser improvements @@ -139,7 +139,7 @@ SQLPage needs to parse SQL queries to be able to bind the right parameters to th and to inject the results of built-in sqlpage functions in them. The parser we use is very powerful and supports most SQL features, but there are some edge cases where it fails to parse a query. -That''s why we contribute to it a lot, and bring the latest version of the parser to SQLPage as soon as it is released. +That's why we contribute to it a lot, and bring the latest version of the parser to SQLPage as soon as it is released. ### JSON functions in MS SQL Server @@ -163,8 +163,7 @@ and to create JSON APIs. - The `cookie` component now supports setting an explicit expiration date for cookies. - The `cookie` component now supports setting the `SameSite` attribute of cookies, and defaults to `SameSite=Strict` for all cookies. What this means in practice is that cookies set by SQLPage will not be sent to your website if the user is coming from another website. This prevents someone from tricking your users into executing SQLPage queries on your website by sending them a malicious link. - Bugfix: setting `min` or `max` to `0` in a number field in the `form` component now works as expected. - - Added support for `.env` files to set SQLPage''s [environment variables](./configuration.md#environment-variables). + - Added support for `.env` files to set SQLPage's [environment variables](./configuration.md#environment-variables). - Better responsive design in the card component. Up to 5 cards per line on large screens. The number of cards per line is still customizable with the `columns` attribute. - - [New icons](https://tabler-icons.io/changelog): + - [New icons](https://tabler-icons.io/changelog): - ![new icons in tabler 42](https://github.com/tabler/tabler-icons/assets/1282324/00856af9-841d-4aa9-995d-121c7ddcc005) -'); \ No newline at end of file diff --git a/examples/official-site/content/blog/sqlpage-versus-no-code-tools.md b/examples/official-site/content/blog/sqlpage-versus-no-code-tools.md new file mode 100644 index 000000000..396480cdd --- /dev/null +++ b/examples/official-site/content/blog/sqlpage-versus-no-code-tools.md @@ -0,0 +1,80 @@ +--- +title: SQLPage versus No-Code tools +date: '2023-08-03' +icon: code-minus +summary: What are the advantages and disadvantages of SQLPage compared to No-Code tools? +--- + +# Choosing Your Path: No-Code, Low-Code, or SQL-Based Development + +The platform you select shapes the entire trajectory of your application. +Each approach offers distinct advantages, yet demands different compromises - a choice that warrants careful consideration. + +## No-Code Platforms: Speed with Limitations + +No-Code platforms present a visual canvas for building applications without traditional programming. Whilst brilliant for rapid prototypes and straightforward departmental tools, they falter when confronted with complexity and scale. + +**Best suited to**: Quick internal tools and simple workflows + +### **Notable examples** + + - [NocoBase](https://www.nocobase.com/) + - [NocoDB](https://www.nocodb.com/) + - [Saltcorn](https://github.com/saltcorn/saltcorn) + + +## Low-Code Platforms: The Flexible Middle Ground + +These platforms artfully combine visual development with traditional coding. They maintain the power of custom code whilst accelerating development through carefully designed components. + +**Best suited to**: Complex applications requiring both speed and customisation + +### **Notable examples** + + - [Budibase](https://budibase.com/) + - [Directus](https://github.com/directus/directus) + - [Rowy](https://github.com/rowyio/rowy) + +## SQL-Based Development: Elegant Simplicity + +SQLPage offers a refreshingly direct approach: pure SQL-driven web applications. + +For those versed in SQL, it enables sophisticated data-driven applications without the overhead of additional frameworks. + +**Best suited to**: Data-centric applications and dashboards + +**Details**: [SQLPage on GitHub](https://github.com/sqlpage/SQLPage) + +## The AI Revolution in Development + +The emergence of Large Language Models (LLMs) has fundamentally shifted the landscape of application development. Tools that once demanded extensive coding expertise have become remarkably more accessible. AI assistants like ChatGPT excel particularly at generating SQL queries and database operations, making SQL-based platforms surprisingly approachable even for those with limited database experience. These AI companions serve as expert pair programmers, offering suggestions, debugging assistance, and ready-to-use code snippets. + +This transformation especially benefits platforms like SQLPage, where the AI's prowess in SQL generation can bridge the traditional expertise gap. Even complex queries and database operations can be created through natural language conversations with AI assistants, democratising access to sophisticated data manipulation capabilities. + +## Making an Informed Choice + +Selecting the right development approach requires weighing multiple factors against your project's specific needs. + +Consider these key decision points to guide your platform selection: + +### **Time Constraints** + - Immediate delivery required → No-Code + - Several days available → SQLPage or Low-Code + +### **Data Complexity** + - Structured data manipulation → SQLPage + - Complex workflows → Low-Code + +### **Team Expertise** + - SQL skills → SQLPage + - Limited technical expertise → No-Code + - Varied technical capabilities → Low-Code + +### **Control Requirements** + - Precise data layer control → SQLPage + - Visual design flexibility → Low-Code + - Speed over customisation → No-Code + +## Further Investigation + +For a thorough demonstration of SQLPage's capabilities: [Building a Full Web Application with SQLPage](https://www.youtube.com/watch?v=mXdgmSdaXkg) diff --git a/examples/official-site/sqlpage/migrations/41_blog_performance.sql b/examples/official-site/content/blog/sqlpage-website-update.md similarity index 86% rename from examples/official-site/sqlpage/migrations/41_blog_performance.sql rename to examples/official-site/content/blog/sqlpage-website-update.md index 684640d3a..fd583218e 100644 --- a/examples/official-site/sqlpage/migrations/41_blog_performance.sql +++ b/examples/official-site/content/blog/sqlpage-website-update.md @@ -1,12 +1,10 @@ +--- +title: SQLPage website update +date: '2024-05-01' +icon: browser +summary: Performance, security, and new features +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'SQLPage website update', - 'Performance, security, and new features', - 'browser', - '2024-05-01', - ' Today is may day, and we are happy to announce that the SQLPage website has been updated with new contents. ## Homepage @@ -33,5 +31,3 @@ or an academic institution using [CAS](https://apereo.github.io/cas/). The README of the SQLPage repository now includes a [clear yet detailed architecture diagram](https://github.com/sqlpage/SQLPage?tab=readme-ov-file#how-it-works). -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/73_blog_tracing.sql b/examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md similarity index 93% rename from examples/official-site/sqlpage/migrations/73_blog_tracing.sql rename to examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md index ef4b63d7f..32aa40cb8 100644 --- a/examples/official-site/sqlpage/migrations/73_blog_tracing.sql +++ b/examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md @@ -1,11 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Tracing SQLPage with OpenTelemetry and Grafana', - 'How to inspect requests, SQL queries, and database wait time with distributed tracing', - 'route-2', - '2026-03-09', - ' +--- +title: Tracing SQLPage with OpenTelemetry and Grafana +date: '2026-03-09' +icon: route-2 +summary: How to inspect requests, SQL queries, and database wait time with distributed tracing +--- + # Tracing SQLPage with OpenTelemetry and Grafana When a page is slow, a log line telling you that the request took 1.8 seconds is only the start of the investigation. What you usually want to know next is where that time went: @@ -41,9 +40,9 @@ Tracing is especially helpful in SQLPage because one request often maps cleanly ## Run the example stack -The simplest way to explore tracing is to run +The simplest way to explore tracing is to run [the example shipped with SQLPage](https://github.com/sqlpage/SQLPage/tree/main/examples/telemetry). -After downloading or cloning the example, run this from the example''s folder: +After downloading or cloning the example, run this from the example's folder: ```bash docker compose up --build @@ -123,7 +122,7 @@ SELECT application_name, query, state FROM pg_stat_activity; ``` -If you also include `%a` in PostgreSQL''s `log_line_prefix`, your database logs can contain the same trace context. +If you also include `%a` in PostgreSQL's `log_line_prefix`, your database logs can contain the same trace context. ## A practical debugging example @@ -171,5 +170,3 @@ SQLPage already makes the application logic easy to inspect because it lives in By enabling OpenTelemetry and connecting SQLPage to Grafana, you can see not just that a request was slow, but why it was slow, where the time was spent, and which query or resource caused the delay. For a complete working setup, start with the [OpenTelemetry + Grafana example](https://github.com/sqlpage/SQLPage/tree/main/examples/telemetry) and adapt it to your own deployment. -' - ); diff --git a/examples/official-site/content/categories.yaml b/examples/official-site/content/categories.yaml new file mode 100644 index 000000000..94861623f --- /dev/null +++ b/examples/official-site/content/categories.yaml @@ -0,0 +1,36 @@ +- id: display-data + title: Display data + sort_order: 1 +- id: forms-and-feedback + title: Forms and feedback + sort_order: 2 +- id: navigation + title: Navigation + sort_order: 3 +- id: page-layout + title: Page layout and content + sort_order: 4 +- id: http-responses + title: HTTP responses + sort_order: 5 +- id: server-logic + title: Server logic + sort_order: 6 +- id: request-data + title: Request data + sort_order: 1 +- id: links-and-routing + title: Links and routing + sort_order: 2 +- id: files-and-uploads + title: Files and uploads + sort_order: 3 +- id: identity-and-security + title: Identity and security + sort_order: 4 +- id: external-services + title: External services + sort_order: 5 +- id: server-and-runtime + title: Server and runtime + sort_order: 6 diff --git a/examples/official-site/content/components/alert.md b/examples/official-site/content/components/alert.md new file mode 100644 index 000000000..d65119c08 --- /dev/null +++ b/examples/official-site/content/components/alert.md @@ -0,0 +1,49 @@ +--- +icon: alert-triangle +category: forms-and-feedback +summary: Draw attention to a message with a color and an icon. +top: + - class + - name: color + type: COLOR + description: The color theme for the alert message. + - name: description + type: TEXT + description: Detailed description or content of the alert message. + - name: description_md + type: TEXT + description: Detailed description or content of the alert message, in Markdown format, allowing you to + use rich text formatting, including `**bold**` and `*italic*` text. + - name: dismissible + type: BOOLEAN + description: Whether the user can close the alert message. + - name: icon + type: TEXT + description: Icon name (from tabler-icons.io) to display next to the alert message. + - id + - name: important + type: BOOLEAN + description: Set this to TRUE to make the alert message more prominent. + - name: link + type: URL + description: A URL to link to from the alert message. + - name: link_text + type: TEXT + description: Customize the text of the link in the alert message. The default is "Ok". + - name: title + type: TEXT + required: true + description: Title of the alert message. +row: + - name: color + type: COLOR + description: Customize the color of the link. + - name: link + type: URL + description: A URL to link to from the alert message. + - name: title + type: TEXT + description: Customize the text of the link in the alert message. The default is "Ok". +--- + +A visually distinctive message or notification. diff --git a/examples/official-site/content/components/alert/examples/01-basic.md b/examples/official-site/content/components/alert/examples/01-basic.md new file mode 100644 index 000000000..980732ae5 --- /dev/null +++ b/examples/official-site/content/components/alert/examples/01-basic.md @@ -0,0 +1,8 @@ +--- +rows: + - component: alert + title: Attention + description: This is an important message. +--- + +A basic alert message diff --git a/examples/official-site/content/components/alert/examples/02-notifications.md b/examples/official-site/content/components/alert/examples/02-notifications.md new file mode 100644 index 000000000..177d145f7 --- /dev/null +++ b/examples/official-site/content/components/alert/examples/02-notifications.md @@ -0,0 +1,20 @@ +--- +rows: + - 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 +--- + +A list of notifications diff --git a/examples/official-site/content/components/alert/examples/03-multiple-links.md b/examples/official-site/content/components/alert/examples/03-multiple-links.md new file mode 100644 index 000000000..76635214e --- /dev/null +++ b/examples/official-site/content/components/alert/examples/03-multiple-links.md @@ -0,0 +1,16 @@ +--- +rows: + - 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 +--- + +A full-featured notification message with multiple links diff --git a/examples/official-site/content/components/alert/examples/04-danger.md b/examples/official-site/content/components/alert/examples/04-danger.md new file mode 100644 index 000000000..631efda20 --- /dev/null +++ b/examples/official-site/content/components/alert/examples/04-danger.md @@ -0,0 +1,14 @@ +--- +rows: + - component: alert + title: Alert + icon: alert-circle + color: red + important: true + dismissible: true + description: SQLPage is entirely free and open source. + link: https://github.com/sqlpage/SQLPage + link_text: See source code +--- + +An important danger alert message with an icon and color diff --git a/examples/official-site/content/components/alert/examples/05-markdown.md b/examples/official-site/content/components/alert/examples/05-markdown.md new file mode 100644 index 000000000..b91bd0460 --- /dev/null +++ b/examples/official-site/content/components/alert/examples/05-markdown.md @@ -0,0 +1,10 @@ +--- +rows: + - 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).' +--- + +An alert message with a Markdown-formatted description diff --git a/examples/official-site/content/components/authentication.md b/examples/official-site/content/components/authentication.md new file mode 100644 index 000000000..0d37d500a --- /dev/null +++ b/examples/official-site/content/components/authentication.md @@ -0,0 +1,55 @@ +--- +icon: lock +since: 0.7.2 +category: server-logic +summary: Restrict access by checking a password against a stored hash. +top: + - name: link + type: TEXT + description: 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). + - name: password + type: TEXT + description: The password that was sent by the user. You can set this to :password if you have a login + form leading to your page. + - name: password_hash + type: TEXT + description: 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/. +--- + +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. diff --git a/examples/official-site/content/components/authentication/examples/01-http-basic.md b/examples/official-site/content/components/authentication/examples/01-http-basic.md new file mode 100644 index 000000000..a12270a0e --- /dev/null +++ b/examples/official-site/content/components/authentication/examples/01-http-basic.md @@ -0,0 +1,106 @@ +### Usage with HTTP basic authentication + +The most basic usage of the authentication component is with the +[`sqlpage.basic_auth_username()`](functions.sql?function=basic_auth_username#function) and +[`sqlpage.basic_auth_password()`](functions.sql?function=basic_auth_password#function) functions. +The component will check if the provided password matches the stored [password hash](/examples/hash_password.sql), +and if not, it will prompt the user to enter a password in a browser popup: + +```sql +SELECT 'authentication' AS component, + '$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w' AS password_hash, -- this is a hash of the password 'password' + sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup +``` + +You can [generate a password hash using the `hash_password` function](/examples/hash_password.sql). + +If you want to have multiple users with different passwords, +you could store them with their password hashes in the database, +or just hardcode them use a `CASE` statement: + +```sql +SELECT 'authentication' AS component, + case sqlpage.basic_auth_username() + when 'admin' + then '$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w' -- the password is 'password' + when 'user' + then '$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$qsrWdjgl96ooYw' -- the password is 'user' + end AS password_hash, -- this is a hash of the password 'password' + sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup +``` + +Try this example online: [SQL Basic Auth](/examples/authentication/basic_auth.sql). + +### Advanced user session management + +*Basic auth* is the simplest way to password-protect a page, +but it is not very flexible nor user-friendly, +because the browser will show an unstyled popup asking for the username and password. + +For more advanced authentication, you can store user information and user sessions in your database. +You can then use the [`form`](/component.sql?component=form#component) component to create a custom login form. +When the user submits the form, you check if the password is correct using the `authentication` component. +You then store a unique string of numbers and letters (a session token) both in the user's browser +using the [`cookie`](/component.sql?component=cookie#component) component and in your database. +Then, in all the pages that require authentication, you check if the cookie is present and matches the session token in your database. + +You can check if the user has sent the correct password in a form, and if not, redirect them to a login page. + +Create a login form in a file called `login.sql` that uses the [login component](?component=login): + +```sql +select 'login' as component; +``` + +And then, in `create_session_token.sql` : + +```sql +SELECT 'authentication' AS component, + 'login.sql' AS link, + '$argon2id$v=19$m=16,t=2,p=1$TERTd0lIcUpraWFTcmRQYw$+bjtag7Xjb6p1dsuYOkngw' AS password_hash, -- generated using sqlpage.hash_password + :password AS password; -- this is the password that the user sent through our form + +-- The code after this point is only executed if the user has sent the correct password + +``` + +and in `login.sql` : + +```sql +SELECT 'form' AS component, 'Login' AS title, 'my_protected_page.sql' AS action; +SELECT 'password' AS type, 'password' AS name, 'Password' AS label; +``` + +### Advanced: usage with a session token + +Calling the `authentication` component is expensive. +The password hashing algorithm is designed to be slow, so that it is difficult to brute-force the password, +even if an attacker gets access to the database. + +If you want to avoid calling the `authentication` component on every page, you can use a session token. +A session token is a random string that is generated when the user logs in, and stored in the database. +It has a limited lifetime, and is stored in a cookie in the user's browser. +When the user visits a page, the session token is sent to the server, and the server checks if it is valid. + +```sql +SELECT 'authentication' AS component, + 'login.sql' AS link, + (SELECT password_hash FROM user WHERE username = :username) AS password_hash, + :password AS password; + +-- The code after this point is only executed if the user has sent the correct password + +-- Generate a random session token +INSERT INTO session (id, username) +VALUES (sqlpage.random_string(32), :username) +RETURNING + 'cookie' AS component, + 'session_token' AS name, + id AS value; +``` + +### Single sign-on with OIDC (OpenID Connect) + +If you don't want to manage your own user database, +you can [use OpenID Connect and OAuth2](/sso) to authenticate users. +This allows users to log in with their Google, Microsoft, or internal company account. diff --git a/examples/official-site/content/components/big_number.md b/examples/official-site/content/components/big_number.md new file mode 100644 index 000000000..a0b9b96a0 --- /dev/null +++ b/examples/official-site/content/components/big_number.md @@ -0,0 +1,61 @@ +--- +icon: chart-area +since: 0.28.0 +category: display-data +summary: Highlight a metric with a trend or progress indicator. +top: + - class + - name: columns + type: INTEGER + description: The number of columns to display the big numbers in (default is one column per item). + - id + - name: wrap + type: BOOLEAN + description: Wrap long titles and descriptions onto multiple lines. By default, they are truncated with + an ellipsis. +row: + - name: change_percent + type: INTEGER + description: The percentage change in value (e.g., 7 for 7% increase, -8 for 8% decrease). + - class + - name: color + type: COLOR + description: The color of the card background and its main value. + - name: description + type: TEXT + description: A description or additional context for the big number. + - name: dropdown_item + type: JSON + description: A list of JSON objects containing links. e.g. {"label":"This week", "link":"?days=7"} + - id + - name: progress_color + type: TEXT + description: The color of the progress bar (e.g., "primary", "success", "danger"). + - name: progress_percent + type: INTEGER + description: The value of the progress (0-100). + - name: title + type: TEXT + description: The title or label for the big number. + - name: title_link + type: TEXT + description: A link for the Big Number title. If set, the entire title becomes clickable. + - name: title_link_new_tab + type: BOOLEAN + description: If true, the title link will open in a new tab/window. + - name: unit + type: TEXT + description: The unit of measurement for the value. + - name: value + type: TEXT + required: true + description: The main value to be displayed prominently. + - name: value_link + type: TEXT + description: A link for the Big Number value. If set, the entire value becomes clickable. + - name: value_link_new_tab + type: BOOLEAN + description: If true, the value link will open in a new tab/window. +--- + +A component to display key metrics or statistics with optional description, change indicator, and progress bar. Useful in dashboards. diff --git a/examples/official-site/content/components/big_number/examples/01-change-and-progress.md b/examples/official-site/content/components/big_number/examples/01-change-and-progress.md new file mode 100644 index 000000000..e0b4cf8fe --- /dev/null +++ b/examples/official-site/content/components/big_number/examples/01-change-and-progress.md @@ -0,0 +1,22 @@ +--- +rows: + - 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 +--- + +Big numbers with change indicators and progress bars diff --git a/examples/official-site/content/components/big_number/examples/02-dropdowns-and-layout.md b/examples/official-site/content/components/big_number/examples/02-dropdowns-and-layout.md new file mode 100644 index 000000000..662d83696 --- /dev/null +++ b/examples/official-site/content/components/big_number/examples/02-dropdowns-and-layout.md @@ -0,0 +1,32 @@ +--- +rows: + - 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 +--- + +Big numbers with dropdowns and customized layout diff --git a/examples/official-site/content/components/breadcrumb.md b/examples/official-site/content/components/breadcrumb.md new file mode 100644 index 000000000..4f7630508 --- /dev/null +++ b/examples/official-site/content/components/breadcrumb.md @@ -0,0 +1,26 @@ +--- +icon: dots +since: 0.18.0 +category: navigation +summary: Link the current page to its parent pages. +top: + - class + - id +row: + - name: active + type: TEXT + description: Whether the link is active or not. Defaults to false. + - name: description + type: TEXT + description: Description of the link. This is displayed when the user hovers over the link. + - name: link + type: TEXT + description: 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. + - name: title + type: TEXT + required: true + description: Hyperlink text to display. +--- + +A secondary navigation aid that helps users understand their location on a website or mobile application. diff --git a/examples/official-site/content/components/breadcrumb/examples/01-basic.md b/examples/official-site/content/components/breadcrumb/examples/01-basic.md new file mode 100644 index 000000000..4de79d141 --- /dev/null +++ b/examples/official-site/content/components/breadcrumb/examples/01-basic.md @@ -0,0 +1,12 @@ +--- +rows: + - component: breadcrumb + - title: Home + link: / + - title: Components + link: /documentation.sql + - title: Breadcrumb + link: ?component=breadcrumb +--- + +Basic usage of the breadcrumb component diff --git a/examples/official-site/content/components/breadcrumb/examples/02-selected-page.md b/examples/official-site/content/components/breadcrumb/examples/02-selected-page.md new file mode 100644 index 000000000..5a87fe176 --- /dev/null +++ b/examples/official-site/content/components/breadcrumb/examples/02-selected-page.md @@ -0,0 +1,15 @@ +--- +rows: + - 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 +--- + +Description of a link and selection of the current page. diff --git a/examples/official-site/content/components/button.md b/examples/official-site/content/components/button.md new file mode 100644 index 000000000..0ecc6a912 --- /dev/null +++ b/examples/official-site/content/components/button.md @@ -0,0 +1,81 @@ +--- +icon: hand-click +since: 0.14.0 +category: forms-and-feedback +summary: Follow a link, download a file, or submit a form. +top: + - class + - name: justify + type: TEXT + description: The horizontal alignment of the button list (e.g., start, end, center, between). + - name: shape + type: TEXT + description: Shape of the buttons (e.g., pill, square) + - name: size + type: TEXT + description: The size of the buttons (e.g., sm, lg). +row: + - name: color + type: COLOR + description: 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. + - name: disabled + type: BOOLEAN + description: Whether the button is disabled or not. + - name: download + type: TEXT + description: If defined, the link will download the target instead of navigating to it. Set the value to + the desired name of the downloaded file. + - name: form + type: TEXT + description: Identifier (id) of the form to which the button should submit. + - name: icon + type: ICON + description: Name of an icon to be displayed on the left side of the button. + - name: icon_after + type: ICON + description: Name of an icon to display after the text in the button + - name: id + type: TEXT + description: HTML Identifier to add to the button element. + - name: image + type: TEXT + description: Path to image file (relative. relative to web root or URL) to be displayed on the button. + - name: image_alt + type: TEXT + description: Alternative text for an informative button image. Leave empty if decorative or repeated by the button title. + - name: link + type: URL + description: 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. + - name: modal + type: TEXT + description: Display the modal window corresponding to the specified ID. + - name: narrow + type: BOOLEAN + description: Whether to trim horizontal padding. + - name: outline + type: COLOR + description: Outline color of the button (e.g. red, purple, ...) + - name: rel + type: TEXT + description: '"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.' + - name: space_after + type: BOOLEAN + description: 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. + - name: target + type: TEXT + description: '"_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.' + - name: title + type: TEXT + description: The text displayed on the button. + - name: tooltip + type: TEXT + description: Text displayed when the user hovers over the button. +--- + +Displays one or more buttons that follow links, download files, or submit a form. diff --git a/examples/official-site/content/components/button/examples/01-basic.md b/examples/official-site/content/components/button/examples/01-basic.md new file mode 100644 index 000000000..25baa56fb --- /dev/null +++ b/examples/official-site/content/components/button/examples/01-basic.md @@ -0,0 +1,11 @@ +--- +rows: + - component: button + - link: /documentation.sql + title: Enabled + - link: '#' + title: Disabled + disabled: true +--- + +A basic button with a link diff --git a/examples/official-site/content/components/button/examples/02-shape-and-color.md b/examples/official-site/content/components/button/examples/02-shape-and-color.md new file mode 100644 index 000000000..b8e1891cb --- /dev/null +++ b/examples/official-site/content/components/button/examples/02-shape-and-color.md @@ -0,0 +1,14 @@ +--- +rows: + - component: button + size: sm + shape: pill + - title: Purple + outline: purple + - title: Orange + outline: orange + - title: Red + outline: red +--- + +A button with a custom shape, size, and outline color diff --git a/examples/official-site/content/components/button/examples/03-centered.md b/examples/official-site/content/components/button/examples/03-centered.md new file mode 100644 index 000000000..f6f832792 --- /dev/null +++ b/examples/official-site/content/components/button/examples/03-centered.md @@ -0,0 +1,25 @@ +--- +rows: + - 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 +--- + +A list of buttons aligned in the center diff --git a/examples/official-site/content/components/button/examples/04-narrow.md b/examples/official-site/content/components/button/examples/04-narrow.md new file mode 100644 index 000000000..0fadda248 --- /dev/null +++ b/examples/official-site/content/components/button/examples/04-narrow.md @@ -0,0 +1,46 @@ +--- +rows: + - 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 +--- + +Icon buttons using the narrow property diff --git a/examples/official-site/content/components/button/examples/05-icons.md b/examples/official-site/content/components/button/examples/05-icons.md new file mode 100644 index 000000000..c1c3ce94a --- /dev/null +++ b/examples/official-site/content/components/button/examples/05-icons.md @@ -0,0 +1,15 @@ +--- +rows: + - component: button + size: lg + - link: '#' + outline: azure + title: Edit + icon: edit + - link: '#' + outline: danger + title: Delete + icon: trash +--- + +Buttons with icons and different sizes diff --git a/examples/official-site/content/components/button/examples/06-square.md b/examples/official-site/content/components/button/examples/06-square.md new file mode 100644 index 000000000..b705ff25f --- /dev/null +++ b/examples/official-site/content/components/button/examples/06-square.md @@ -0,0 +1,20 @@ +--- +rows: + - 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 +--- + +A row of square buttons with spacing in between diff --git a/examples/official-site/content/components/button/examples/07-form-actions.md b/examples/official-site/content/components/button/examples/07-form-actions.md new file mode 100644 index 000000000..c8aee4e7d --- /dev/null +++ b/examples/official-site/content/components/button/examples/07-form-actions.md @@ -0,0 +1,25 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/button/examples/08-download.md b/examples/official-site/content/components/button/examples/08-download.md new file mode 100644 index 000000000..68bdf46c4 --- /dev/null +++ b/examples/official-site/content/components/button/examples/08-download.md @@ -0,0 +1,11 @@ +--- +rows: + - component: button + - link: /sqlpage_introduction_video.mp4 + title: Download Video + icon: download + download: Introduction Video.webm + rel: nofollow +--- + +A button that downloads a file when clicked, and prevents search engines from following the link. diff --git a/examples/official-site/content/components/button/examples/09-image.md b/examples/official-site/content/components/button/examples/09-image.md new file mode 100644 index 000000000..4420566b6 --- /dev/null +++ b/examples/official-site/content/components/button/examples/09-image.md @@ -0,0 +1,9 @@ +--- +rows: + - 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 +--- + +A button with an image-based icon. diff --git a/examples/official-site/content/components/card.md b/examples/official-site/content/components/card.md new file mode 100644 index 000000000..4f9051891 --- /dev/null +++ b/examples/official-site/content/components/card.md @@ -0,0 +1,129 @@ +--- +icon: credit-card +category: display-data +summary: Arrange records in cards with images, links, or embedded content. +top: + - class + - name: columns + type: INTEGER + description: 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. + - name: description + type: TEXT + description: A short paragraph displayed below the title. + - name: description_md + type: TEXT + description: A short paragraph displayed below the title - formatted using markdown. + - name: title + type: TEXT + description: Text header at the top of the list of cards. +row: + - name: active + type: BOOLEAN + description: Whether this item in the grid is considered "active". Active items are displayed more prominently. + - name: allow + type: TEXT + description: The permissions policy of the iframe embed code, for instance "fullscreen; clipboard-write". + Used only when embed_mode is 'iframe'. + - name: background_color + type: COLOR + description: The background color of the card. + - class + - name: color + type: COLOR + description: 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. + - name: description + type: TEXT + 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. + - name: description_md + type: TEXT + description: |2- + + 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. + - name: embed + type: TEXT + description: |- + 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 + - name: embed_mode + type: TEXT + description: |- + 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. + - name: embed_title + type: TEXT + description: Accessible name of the iframe. Defaults to the card title, or Embedded content if no title is set. + - name: footer + type: TEXT + description: Muted text to display at the bottom of the card. + - name: footer_link + type: URL + description: An URL to which the user should be taken when they click on the footer. + - name: footer_md + type: TEXT + description: Muted text to display at the bottom of the card, with rich text formatting in Markdown format. + - name: height + type: INTEGER + description: Height of the iframe embed code, in pixels. Used only when embed_mode is 'iframe'. + - name: icon + type: ICON + description: Name of an icon to display on the right side of the card. + - id + - name: link + type: URL + description: An URL to which the user should be taken when they click on the card. + - name: sandbox + type: TEXT + description: The restrictions to apply to the iframe embed code, for instance "allow-scripts allow-same-origin". + Used only when embed_mode is 'iframe'. + - name: style + type: TEXT + description: 'Inline style property to your iframe embed code. For example "background-color: #FFFFFF"' + - name: target + type: TEXT + description: '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.' + - name: title + type: TEXT + required: true + description: Name of the card, displayed at the top. + - name: top_image + type: URL + description: The URL (absolute or relative) of an image to display at the top of the card. + - name: top_image_alt + type: TEXT + description: Alternative text for an informative card image. Leave empty if decorative. + - name: top_image_height + type: INTEGER + description: Specify the top image height, in pixels. Helps prevent layout shifts. + - name: top_image_lazy + type: BOOLEAN + description: Whether the top image must be lazily loaded. Defaults to false, meaning eagerly loaded. + - name: top_image_width + type: INTEGER + description: Specify the top image width, in pixels. Helps prevent layout shifts. + - name: width + type: INTEGER + description: 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%. +--- + +A grid where each element is a small card that displays a piece of data. diff --git a/examples/official-site/content/components/card/examples/01-grid.md b/examples/official-site/content/components/card/examples/01-grid.md new file mode 100644 index 000000000..eb80da3c6 --- /dev/null +++ b/examples/official-site/content/components/card/examples/01-grid.md @@ -0,0 +1,22 @@ +--- +rows: + - 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. +--- + +A beautiful card grid with bells and whistles, showing examples of SQLPage features. diff --git a/examples/official-site/content/components/card/examples/02-dashboard.md b/examples/official-site/content/components/card/examples/02-dashboard.md new file mode 100644 index 000000000..8cca72541 --- /dev/null +++ b/examples/official-site/content/components/card/examples/02-dashboard.md @@ -0,0 +1,21 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/card/examples/03-image-gallery.md b/examples/official-site/content/components/card/examples/03-image-gallery.md new file mode 100644 index 000000000..786c7a497 --- /dev/null +++ b/examples/official-site/content/components/card/examples/03-image-gallery.md @@ -0,0 +1,33 @@ +--- +rows: + - component: card + title: My favorite animals in pictures + columns: 3 + - title: Lynx + top_image_alt: A Eurasian 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: 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 + top_image_alt: A squirrel eating a nut + 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: 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 + top_image_alt: An orb weaver spinning a web + 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: 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 +--- + +A gallery of images. diff --git a/examples/official-site/content/components/card/examples/04-variable-width.md b/examples/official-site/content/components/card/examples/04-variable-width.md new file mode 100644 index 000000000..348c64adf --- /dev/null +++ b/examples/official-site/content/components/card/examples/04-variable-width.md @@ -0,0 +1,23 @@ +--- +rows: + - 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 +--- + +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 diff --git a/examples/official-site/content/components/card/examples/05-remote-content.md b/examples/official-site/content/components/card/examples/05-remote-content.md new file mode 100644 index 000000000..831a1b17d --- /dev/null +++ b/examples/official-site/content/components/card/examples/05-remote-content.md @@ -0,0 +1,15 @@ +--- +rows: + - component: card + title: Card with embedded remote content + columns: 2 + - title: Embedded Chart + embed: /examples/chart.sql?_sqlpage_embed + - title: Embedded Video + embed: https://www.youtube.com/embed/mXdgmSdaXkg + allow: accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share + embed_mode: iframe + height: '350' +--- + +Cards with remote content diff --git a/examples/official-site/content/components/carousel.md b/examples/official-site/content/components/carousel.md new file mode 100644 index 000000000..c633b249d --- /dev/null +++ b/examples/official-site/content/components/carousel.md @@ -0,0 +1,61 @@ +--- +icon: carousel-horizontal +since: 0.18.3 +category: display-data +summary: Show a slideshow of images with optional captions and controls. +top: + - name: auto + type: BOOLEAN + description: Whether to automatically cycle through the carousel items. Default is false. + - name: center + type: BOOLEAN + description: Whether to center the carousel. + - class + - name: controls + type: BOOLEAN + description: Whether to show the control links to go previous or next item. + - name: delay + type: INTEGER + description: Specify the delay, in milliseconds, between two images. + - name: fade + type: BOOLEAN + description: Whether to apply the fading effect. + - id + - name: indicators + type: TEXT + description: Style of image indicators (square or dot). + - name: title + type: TEXT + description: A name to display at the top of the carousel. + - name: vertical + type: BOOLEAN + description: Whether to use the vertical image indicators. + - name: width + type: INTEGER + description: Width of the component, between 1 and 12. Default is 12. +row: + - name: description + type: TEXT + description: A short paragraph. + - name: description_md + type: TEXT + description: A short paragraph formatted using markdown. + - name: height + type: INTEGER + description: The height of the image, in pixels. + - name: image + type: URL + required: true + description: The URL (absolute or relative) of an image to display in the carousel. + - name: image_alt + type: TEXT + description: Alternative text describing the slide image. Leave empty if the image is decorative or its caption already describes it. + - name: title + type: TEXT + description: Add caption to the slide. + - name: width + type: INTEGER + description: The width of the image, in pixels. +--- + +A carousel is used to display images. When used with multiple images, it will cycle through them automatically or with controls, creating a slideshow. diff --git a/examples/official-site/content/components/carousel/examples/01-basic.md b/examples/official-site/content/components/carousel/examples/01-basic.md new file mode 100644 index 000000000..b9d04d23d --- /dev/null +++ b/examples/official-site/content/components/carousel/examples/01-basic.md @@ -0,0 +1,12 @@ +--- +rows: + - component: carousel + name: cats1 + title: Famous Database Animals + - 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: African elephants at a watering hole + - 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 + image_alt: A panoramic view of Penguin Island +--- + +A basic example of carousel diff --git a/examples/official-site/content/components/carousel/examples/02-controls.md b/examples/official-site/content/components/carousel/examples/02-controls.md new file mode 100644 index 000000000..1235f2337 --- /dev/null +++ b/examples/official-site/content/components/carousel/examples/02-controls.md @@ -0,0 +1,20 @@ +--- +rows: + - 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 +--- + +An advanced example of carousel with controls diff --git a/examples/official-site/content/components/chart.md b/examples/official-site/content/components/chart.md new file mode 100644 index 000000000..4af99e84c --- /dev/null +++ b/examples/official-site/content/components/chart.md @@ -0,0 +1,134 @@ +--- +icon: timeline +category: display-data +summary: Plot query results as line, area, bar, or pie charts. +top: + - class + - name: color + type: COLOR + description: 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. + - name: height + type: INTEGER + description: 'Height of the chart, in pixels. By default: 250' + - name: horizontal + type: BOOLEAN + description: Displays a bar chart with horizontal bars instead of vertical ones. + - id + - name: labels + type: BOOLEAN + description: Whether to show the data labels on the chart or not. + - name: logarithmic + type: BOOLEAN + description: Display the y-axis in logarithmic scale. + - name: marker + type: REAL + description: Marker size + - name: show_legend + type: BOOLEAN + description: Whether to display the legend listing all chart series. Defaults to true. + - name: stacked + type: BOOLEAN + description: 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. + - name: time + type: BOOLEAN + description: Whether the x-axis represents time. If set to true, the x values will be parsed and formatted + as dates for the user. + - name: title + type: TEXT + description: The name of the chart. + - name: toolbar + type: BOOLEAN + description: Whether to display a toolbar at the top right of the chart, that offers downloading the data + as CSV. + - name: type + type: TEXT + required: true + description: 'The type of chart. One of: "line", "area", "bar", "column", "pie", "scatter", "bubble", "heatmap", + "rangeBar". "column" is a synonym of "bar".' + - name: xmax + type: TEXT + description: The maximum value for the x-axis. When time is true, this can be a date or timestamp. + - name: xmin + type: TEXT + description: The minimal value for the x-axis. When time is true, this can be a date or timestamp. + - name: xticks + type: INTEGER + description: 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. + - name: xtitle + type: TEXT + description: Title of the x axis, displayed below it. + - name: ymax + type: REAL + description: The maximum value for the y-axis. + - name: ymin + type: REAL + description: The minimal value for the y-axis. + - name: ystep + type: REAL + description: Step between ticks on the y axis. + - name: yticks + type: INTEGER + description: Number of ticks on the y axis. + - name: ytitle + type: TEXT + description: Title of the y axis, displayed to its left. + - name: ztitle + type: TEXT + description: Title of the z axis, displayed in tooltips. +row: + - name: color + type: COLOR + description: '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.' + - name: label + type: TEXT + description: 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. + - name: link + type: URL + description: 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. + - name: series + type: TEXT + description: 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. + - name: value + type: REAL + description: An alias for parameter "y" + - name: x + type: REAL + required: true + description: 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. + - name: xline + type: TEXT + description: 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. + - name: xline_end + type: TEXT + description: Makes the xline a band instead of a line, reaching to this value. + - name: y + type: REAL + required: true + description: The value of the point on the vertical axis + - name: yline + type: REAL + description: 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. + - name: yline_end + type: REAL + description: Makes the yline a band instead of a line, reaching to this value. + - name: z + type: REAL + description: 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". +--- + +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. diff --git a/examples/official-site/content/components/chart/examples/01-time-series.md b/examples/official-site/content/components/chart/examples/01-time-series.md new file mode 100644 index 000000000..38b0dd87b --- /dev/null +++ b/examples/official-site/content/components/chart/examples/01-time-series.md @@ -0,0 +1,26 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/chart/examples/02-pie.md b/examples/official-site/content/components/chart/examples/02-pie.md new file mode 100644 index 000000000..f4c2ba71a --- /dev/null +++ b/examples/official-site/content/components/chart/examples/02-pie.md @@ -0,0 +1,13 @@ +--- +rows: + - component: chart + title: Answers + type: pie + labels: true + - label: 'Yes' + value: 65 + - label: 'No' + value: 35 +--- + +A pie chart. diff --git a/examples/official-site/content/components/chart/examples/03-bar.md b/examples/official-site/content/components/chart/examples/03-bar.md new file mode 100644 index 000000000..61dc61ad4 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/03-bar.md @@ -0,0 +1,14 @@ +--- +rows: + - component: chart + type: bar + title: Quarterly Results + horizontal: true + labels: true + - label: Tom + value: 35 + - label: Olive + value: 15 +--- + +A basic bar chart diff --git a/examples/official-site/content/components/chart/examples/04-treemap.md b/examples/official-site/content/components/chart/examples/04-treemap.md new file mode 100644 index 000000000..558a5822d --- /dev/null +++ b/examples/official-site/content/components/chart/examples/04-treemap.md @@ -0,0 +1,27 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/chart/examples/05-multi-series-bar.md b/examples/official-site/content/components/chart/examples/05-multi-series-bar.md new file mode 100644 index 000000000..90404ed89 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/05-multi-series-bar.md @@ -0,0 +1,24 @@ +--- +rows: + - 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 +--- + +A bar chart with multiple series. diff --git a/examples/official-site/content/components/chart/examples/06-stacked-area.md b/examples/official-site/content/components/chart/examples/06-stacked-area.md new file mode 100644 index 000000000..b84a60c9f --- /dev/null +++ b/examples/official-site/content/components/chart/examples/06-stacked-area.md @@ -0,0 +1,39 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/chart/examples/07-multi-series-line.md b/examples/official-site/content/components/chart/examples/07-multi-series-line.md new file mode 100644 index 000000000..dc58f2e45 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/07-multi-series-line.md @@ -0,0 +1,28 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/chart/examples/08-scatter.md b/examples/official-site/content/components/chart/examples/08-scatter.md new file mode 100644 index 000000000..a11d855e8 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/08-scatter.md @@ -0,0 +1,32 @@ +--- +rows: + - 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 +--- + +A scatter plot with multiple custom options. diff --git a/examples/official-site/content/components/chart/examples/09-heatmap.md b/examples/official-site/content/components/chart/examples/09-heatmap.md new file mode 100644 index 000000000..fe309f00d --- /dev/null +++ b/examples/official-site/content/components/chart/examples/09-heatmap.md @@ -0,0 +1,51 @@ +--- +rows: + - component: chart + title: Survey Results + type: heatmap + ytitle: Database managemet system + xtitle: Year + color: + - purple + - purple + - purple + - series: PostgreSQL + x: '2000' + y: 48 + - series: SQLite + x: '2000' + y: 44 + - series: MySQL + x: '2000' + y: 78 + - series: PostgreSQL + x: '2010' + y: 65 + - series: SQLite + x: '2010' + y: 62 + - series: MySQL + x: '2010' + y: 83 + - series: PostgreSQL + x: '2020' + y: 73 + - series: SQLite + x: '2020' + y: 38 + - series: MySQL + x: '2020' + y: 87 +--- + +## Heatmaps + +You can build heatmaps using the `heatmap` top-level property. + +The data format follows the [apexcharts heatmap format](https://apexcharts.com/angular-chart-demos/heatmap-charts/basic/), +where each series is represented as a line in the chart: + - The `x` property of each item will be used as the x-axis value. + - The `series` property of each item will be used as the y-axis value. + - The `y` property of each item will be used as the value to display in the heatmap + +The `color` property sets the color of each series separately, in order. diff --git a/examples/official-site/content/components/chart/examples/10-timeline.md b/examples/official-site/content/components/chart/examples/10-timeline.md new file mode 100644 index 000000000..ad4ce54f6 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/10-timeline.md @@ -0,0 +1,31 @@ +--- +rows: + - 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' +--- + +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. diff --git a/examples/official-site/content/components/chart/examples/11-single-value-color.md b/examples/official-site/content/components/chart/examples/11-single-value-color.md new file mode 100644 index 000000000..14149ba21 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/11-single-value-color.md @@ -0,0 +1,38 @@ +--- +rows: + - 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 +--- + +## 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. diff --git a/examples/official-site/content/components/chart/examples/12-pie-slice-colors.md b/examples/official-site/content/components/chart/examples/12-pie-slice-colors.md new file mode 100644 index 000000000..8a0dafbfd --- /dev/null +++ b/examples/official-site/content/components/chart/examples/12-pie-slice-colors.md @@ -0,0 +1,18 @@ +--- +rows: + - 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 +--- + +A pie chart whose rows choose their own slice colors. diff --git a/examples/official-site/content/components/chart/examples/13-reference-lines.md b/examples/official-site/content/components/chart/examples/13-reference-lines.md new file mode 100644 index 000000000..413fd86b4 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/13-reference-lines.md @@ -0,0 +1,54 @@ +--- +rows: + - 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 +--- + +## 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. diff --git a/examples/official-site/content/components/chart/examples/14-event-markers.md b/examples/official-site/content/components/chart/examples/14-event-markers.md new file mode 100644 index 000000000..5b8339440 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/14-event-markers.md @@ -0,0 +1,49 @@ +--- +rows: + - 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 +--- + +## 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. diff --git a/examples/official-site/content/components/chart/examples/15-reference-line-axes.md b/examples/official-site/content/components/chart/examples/15-reference-line-axes.md new file mode 100644 index 000000000..7b54b217e --- /dev/null +++ b/examples/official-site/content/components/chart/examples/15-reference-line-axes.md @@ -0,0 +1,42 @@ +--- +rows: + - 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 +--- + +## 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. diff --git a/examples/official-site/content/components/chart/examples/16-side-by-side.md b/examples/official-site/content/components/chart/examples/16-side-by-side.md new file mode 100644 index 000000000..b59fdbe08 --- /dev/null +++ b/examples/official-site/content/components/chart/examples/16-side-by-side.md @@ -0,0 +1,17 @@ +--- +rows: + - 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 +--- + +## 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`. diff --git a/examples/official-site/content/components/code.md b/examples/official-site/content/components/code.md new file mode 100644 index 000000000..677e403ed --- /dev/null +++ b/examples/official-site/content/components/code.md @@ -0,0 +1,29 @@ +--- +icon: code +since: 0.19.0 +category: page-layout +summary: Display source code with syntax highlighting. +top: + - class + - id +row: + - name: contents + type: TEXT + required: true + description: A block of code. + - name: description + type: TEXT + description: Description of the snipet of code. + - name: description_md + type: TEXT + description: 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)`. + - name: language + type: TEXT + description: Set the programming language name. + - name: title + type: TEXT + description: Set the heading level (default level is 1) +--- + +Displays one or many blocks of code from a programming language or formated text as XML or JSON. diff --git a/examples/official-site/content/components/code/examples/01-html-source.md b/examples/official-site/content/components/code/examples/01-html-source.md new file mode 100644 index 000000000..6ed2e7909 --- /dev/null +++ b/examples/official-site/content/components/code/examples/01-html-source.md @@ -0,0 +1,23 @@ +--- +rows: + - 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: |- + + + + + title + + + + + + + +--- + +Displays a block of HTML code. diff --git a/examples/official-site/content/components/columns.md b/examples/official-site/content/components/columns.md new file mode 100644 index 000000000..d23fbc6b4 --- /dev/null +++ b/examples/official-site/content/components/columns.md @@ -0,0 +1,52 @@ +--- +icon: columns +since: 0.29.0 +category: page-layout +summary: Compare plans, features, or options in side-by-side cards. +row: + - name: button_color + type: TEXT + description: Optional color for the button. + - name: button_text + type: TEXT + description: Text for the button. + - name: description + type: TEXT + description: A brief description of the item. + - name: description_md + type: TEXT + description: A brief description of the item, formatted using markdown. + - name: icon + type: ICON + description: Optional icon to display in a ribbon. + - name: icon_color + type: TEXT + description: Color for the icon in the ribbon. + - name: item + type: JSON + description: 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. + - name: link + type: TEXT + description: A link associated with the item. + - name: size + type: INTEGER + description: Size of the column, affecting layout. + - name: small_text + type: TEXT + description: Optional small text to display after the value. + - name: target + type: TEXT + description: Optional target for the button. Set to "_blank" to open links in a new tab. + - name: title + type: TEXT + description: The title or label for the item. + - name: value + type: TEXT + description: The value associated with the item. + - name: value_color + type: TEXT + description: Color for the value text. +--- + +A component to display various items in a card layout, allowing users to choose options. Useful for showcasing different features or services, or KPIs. See also the big_number component. diff --git a/examples/official-site/content/components/columns/examples/01-pricing-plans.md b/examples/official-site/content/components/columns/examples/01-pricing-plans.md new file mode 100644 index 000000000..a13093f93 --- /dev/null +++ b/examples/official-site/content/components/columns/examples/01-pricing-plans.md @@ -0,0 +1,52 @@ +--- +rows: + - 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 +--- + +Pricing Plans Display diff --git a/examples/official-site/content/components/columns/examples/02-company-metrics.md b/examples/official-site/content/components/columns/examples/02-company-metrics.md new file mode 100644 index 000000000..c194d35bb --- /dev/null +++ b/examples/official-site/content/components/columns/examples/02-company-metrics.md @@ -0,0 +1,41 @@ +--- +rows: + - 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 +--- + +Tech Company KPIs Display diff --git a/examples/official-site/content/components/cookie.md b/examples/official-site/content/components/cookie.md new file mode 100644 index 000000000..4b5076d36 --- /dev/null +++ b/examples/official-site/content/components/cookie.md @@ -0,0 +1,54 @@ +--- +icon: cookie +category: http-responses +summary: Set a cookie in the visitor's browser. +top: + - name: domain + type: TEXT + description: The domain for which the cookie will be sent. If not specified, the cookie will be sent for + all domains. + - name: expires + type: TIMESTAMP + description: 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. + - name: http_only + type: BOOLEAN + description: 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. + - name: max_age + type: INTEGER + description: 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. + - name: name + type: TEXT + required: true + description: The name of the cookie to set. + - name: path + type: TEXT + description: The path for which the cookie will be sent. If not specified, the cookie will be sent for + all paths. + - name: remove + type: BOOLEAN + description: Set to TRUE to remove the cookie from the client browser. When specified, other parameters + are ignored. + - name: same_site + type: TEXT + description: 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. + - name: secure + type: BOOLEAN + description: Whether the cookie should only be sent over a secure (HTTPS) connection. Defaults to TRUE. + - name: value + type: TEXT + description: The value of the cookie to set. +--- + +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. diff --git a/examples/official-site/content/components/cookie/examples/01-set-a-cookie.md b/examples/official-site/content/components/cookie/examples/01-set-a-cookie.md new file mode 100644 index 000000000..054b57adc --- /dev/null +++ b/examples/official-site/content/components/cookie/examples/01-set-a-cookie.md @@ -0,0 +1,15 @@ +Create a cookie named `username` with the value `John Doe`... + +```sql +SELECT 'cookie' as component, + 'username' as name, + 'John Doe' as value + FALSE AS secure; -- You can remove this if the site is served over HTTPS. +``` + +and then display the value of the cookie using the [`sqlpage.cookie`](functions.sql?function=cookie) function: + +```sql +SELECT 'text' as component, + 'Your name is ' || COALESCE(sqlpage.cookie('username'), 'not known to us'); +``` diff --git a/examples/official-site/content/components/csv.md b/examples/official-site/content/components/csv.md new file mode 100644 index 000000000..61481c179 --- /dev/null +++ b/examples/official-site/content/components/csv.md @@ -0,0 +1,43 @@ +--- +icon: download +category: http-responses +summary: Export query rows as a downloadable CSV file. +top: + - name: bom + type: BOOLEAN + description: 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. + - class + - name: color + type: COLOR + description: Color of the button. Ignored when used as a header component. + - name: filename + type: TEXT + description: The name of the file that should be downloaded (without the extension). + - name: icon + type: ICON + description: Name of the icon (from tabler-icons.io) to display in the button. Ignored when used as a header + component. + - id + - name: separator + type: TEXT + description: How individual values should be separated in the CSV. "," by default, set it to "\t" for tab-separated + values. + - name: size + type: TEXT + description: The size of the button (e.g., sm, lg). Ignored when used as a header component. + - name: title + type: TEXT + required: true + description: The text displayed on the download button. +--- + +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. diff --git a/examples/official-site/content/components/csv/examples/01-download-url.md b/examples/official-site/content/components/csv/examples/01-download-url.md new file mode 100644 index 000000000..dcc16529e --- /dev/null +++ b/examples/official-site/content/components/csv/examples/01-download-url.md @@ -0,0 +1,21 @@ +--- +rows: + - component: button + - title: Download my data + link: /examples/csv_download.sql +--- + +### Header component: creating a CSV download URL + +You can create a page that will trigger a download of the CSV file when the user visits it. +The contents will be streamed efficiently from the database to the browser, without being fully loaded in memory. +This makes it possible to download even very large files without overloading the database server, the web server, or the client's browser. + +#### `csv_download.sql` + +```sql +select 'csv' as component, 'example.csv' as filename; +SELECT * FROM my_large_table; +``` + +#### `index.sql` diff --git a/examples/official-site/content/components/csv/examples/02-download-button.md b/examples/official-site/content/components/csv/examples/02-download-button.md new file mode 100644 index 000000000..e0e771c6b --- /dev/null +++ b/examples/official-site/content/components/csv/examples/02-download-button.md @@ -0,0 +1,23 @@ +--- +rows: + - 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 +--- + +### 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. diff --git a/examples/official-site/content/components/datagrid.md b/examples/official-site/content/components/datagrid.md new file mode 100644 index 000000000..c29817693 --- /dev/null +++ b/examples/official-site/content/components/datagrid.md @@ -0,0 +1,55 @@ +--- +icon: grid-dots +category: display-data +summary: Lay out labeled values in a compact grid. +top: + - class + - name: description + type: TEXT + description: A short paragraph displayed below the title. + - name: description_md + type: TEXT + description: A short paragraph displayed below the title - formatted using markdown. + - name: icon + type: ICON + description: Name of an icon to display on the left side of the title. + - id + - name: image_url + type: URL + description: URL of an image to display on the left side of the title. + - name: title + type: TEXT + description: Text header at the top of the data grid. +row: + - name: active + type: BOOLEAN + description: Whether this item in the grid is considered "active". Active items are displayed more prominently. + - name: color + type: COLOR + description: If set to a color name, the value will be displayed in a pill of that color. + - name: description + type: TEXT + description: Value to display below the name. + - name: footer + type: TEXT + description: Muted text to display below the value. + - name: icon + type: ICON + description: An icon name (from tabler-icons.io) to display on the left side of the value. + - id + - name: image_url + type: URL + description: URL of a small image (such as an avatar) to display on the left side of the value. + - name: link + type: URL + description: A target URL to which the user should be taken when they click on the value. + - name: title + type: TEXT + required: true + description: Name of the piece of information. + - name: tooltip + type: TEXT + description: A tooltip to display when the user passes their mouse over the value. +--- + +Display small pieces of information in a clear and readable way. Each item has a name and is associated with a value. diff --git a/examples/official-site/content/components/datagrid/examples/01-sections.md b/examples/official-site/content/components/datagrid/examples/01-sections.md new file mode 100644 index 000000000..48369e46d --- /dev/null +++ b/examples/official-site/content/components/datagrid/examples/01-sections.md @@ -0,0 +1,12 @@ +--- +rows: + - component: datagrid + - title: Language + description: SQL + - title: Creation date + description: '1974' + - title: Language family + description: Query language +--- + +Just some sections of information. diff --git a/examples/official-site/content/components/datagrid/examples/02-icons-and-colors.md b/examples/official-site/content/components/datagrid/examples/02-icons-and-colors.md new file mode 100644 index 000000000..6024d81a8 --- /dev/null +++ b/examples/official-site/content/components/datagrid/examples/02-icons-and-colors.md @@ -0,0 +1,24 @@ +--- +rows: + - 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 +--- + +A beautiful data grid with nice colors and icons. diff --git a/examples/official-site/content/components/datagrid/examples/03-picture.md b/examples/official-site/content/components/datagrid/examples/03-picture.md new file mode 100644 index 000000000..26d049fa1 --- /dev/null +++ b/examples/official-site/content/components/datagrid/examples/03-picture.md @@ -0,0 +1,20 @@ +--- +rows: + - 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 +--- + +Using a picture in the data grid card header. diff --git a/examples/official-site/content/components/debug.md b/examples/official-site/content/components/debug.md new file mode 100644 index 000000000..1d4d1732f --- /dev/null +++ b/examples/official-site/content/components/debug.md @@ -0,0 +1,9 @@ +--- +icon: bug +category: server-logic +summary: Inspect the values passed to a component as JSON. +--- + +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. diff --git a/examples/official-site/content/components/debug/examples/01-component-data.md b/examples/official-site/content/components/debug/examples/01-component-data.md new file mode 100644 index 000000000..98ece7b12 --- /dev/null +++ b/examples/official-site/content/components/debug/examples/01-component-data.md @@ -0,0 +1,11 @@ +--- +rows: + - component: debug + my_top_level_property: true + - x: y + z: 42 + - a: b + c: null +--- + +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. diff --git a/examples/official-site/content/components/debug/examples/02-function-result.md b/examples/official-site/content/components/debug/examples/02-function-result.md new file mode 100644 index 000000000..c8f6a57bc --- /dev/null +++ b/examples/official-site/content/components/debug/examples/02-function-result.md @@ -0,0 +1,5 @@ +Show the result of a SQLPage function: + +```sql +select 'debug' as component, sqlpage.environment_variable('HOME'); +``` diff --git a/examples/official-site/content/components/divider.md b/examples/official-site/content/components/divider.md new file mode 100644 index 000000000..f68c22c66 --- /dev/null +++ b/examples/official-site/content/components/divider.md @@ -0,0 +1,34 @@ +--- +icon: separator +since: 0.18.0 +category: page-layout +summary: Separate sections with a horizontal rule. +top: + - name: bold + type: BOOLEAN + description: Whether the text is bold. + - class + - name: color + type: COLOR + description: The name of a color for this span of text. + - name: contents + type: TEXT + description: A text in the divider. + - name: italics + type: BOOLEAN + description: Whether the text is italicized. + - name: link + type: URL + description: URL of the link for the divider text. Available only when contents is present. + - name: position + type: TEXT + description: Position of the text (e.g. left, right). + - name: size + type: INTEGER + description: The size of the divider text, from 1 to 6. + - name: underline + type: BOOLEAN + description: Whether the text is underlined. +--- + +Dividers help organize content and make the interface layout clear and uncluttered. diff --git a/examples/official-site/content/components/divider/examples/01-empty.md b/examples/official-site/content/components/divider/examples/01-empty.md new file mode 100644 index 000000000..c21749819 --- /dev/null +++ b/examples/official-site/content/components/divider/examples/01-empty.md @@ -0,0 +1,6 @@ +--- +rows: + - component: divider +--- + +An empty divider diff --git a/examples/official-site/content/components/divider/examples/02-centered.md b/examples/official-site/content/components/divider/examples/02-centered.md new file mode 100644 index 000000000..382c17827 --- /dev/null +++ b/examples/official-site/content/components/divider/examples/02-centered.md @@ -0,0 +1,7 @@ +--- +rows: + - component: divider + contents: Hello +--- + +A divider with centered text diff --git a/examples/official-site/content/components/divider/examples/03-left.md b/examples/official-site/content/components/divider/examples/03-left.md new file mode 100644 index 000000000..3ffd03b54 --- /dev/null +++ b/examples/official-site/content/components/divider/examples/03-left.md @@ -0,0 +1,8 @@ +--- +rows: + - component: divider + contents: Hello + position: left +--- + +A divider with text at left diff --git a/examples/official-site/content/components/divider/examples/04-colored-link.md b/examples/official-site/content/components/divider/examples/04-colored-link.md new file mode 100644 index 000000000..7e47ed5f8 --- /dev/null +++ b/examples/official-site/content/components/divider/examples/04-colored-link.md @@ -0,0 +1,9 @@ +--- +rows: + - component: divider + contents: SQLPage components + link: /documentation.sql + color: blue +--- + +A divider with blue text and a link diff --git a/examples/official-site/content/components/divider/examples/05-text-formatting.md b/examples/official-site/content/components/divider/examples/05-text-formatting.md new file mode 100644 index 000000000..09176aa3d --- /dev/null +++ b/examples/official-site/content/components/divider/examples/05-text-formatting.md @@ -0,0 +1,13 @@ +--- +rows: + - component: divider + contents: Important notice + position: left + color: red + size: 5 + bold: true + italics: true + underline: true +--- + +A divider with bold, italic, and underlined text diff --git a/examples/official-site/content/components/download.md b/examples/official-site/content/components/download.md new file mode 100644 index 000000000..10a36ef7a --- /dev/null +++ b/examples/official-site/content/components/download.md @@ -0,0 +1,48 @@ +--- +icon: download +since: 0.37.0 +category: http-responses +summary: Send a file directly to the visitor. +top: + - name: data_url + type: TEXT + required: true + description: '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.' + - name: filename + type: TEXT + description: '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.' +--- + +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. diff --git a/examples/official-site/content/components/download/examples/01-plain-text.md b/examples/official-site/content/components/download/examples/01-plain-text.md new file mode 100644 index 000000000..295457da5 --- /dev/null +++ b/examples/official-site/content/components/download/examples/01-plain-text.md @@ -0,0 +1,9 @@ +## 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; +``` diff --git a/examples/official-site/content/components/download/examples/02-pdf.md b/examples/official-site/content/components/download/examples/02-pdf.md new file mode 100644 index 000000000..522795d46 --- /dev/null +++ b/examples/official-site/content/components/download/examples/02-pdf.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/content/components/download/examples/03-image-blob.md b/examples/official-site/content/components/download/examples/03-image-blob.md new file mode 100644 index 000000000..60aebdd87 --- /dev/null +++ b/examples/official-site/content/components/download/examples/03-image-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/content/components/dynamic.md b/examples/official-site/content/components/dynamic.md new file mode 100644 index 000000000..69246e50d --- /dev/null +++ b/examples/official-site/content/components/dynamic.md @@ -0,0 +1,13 @@ +--- +icon: repeat +category: server-logic +summary: Render SQLPage components described by JSON data. +top: + - name: properties + type: JSON + description: A json object or array that contains the names and properties of other components. +--- + +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 diff --git a/examples/official-site/content/components/dynamic/examples/01-component-rows.md b/examples/official-site/content/components/dynamic/examples/01-component-rows.md new file mode 100644 index 000000000..422acb34a --- /dev/null +++ b/examples/official-site/content/components/dynamic/examples/01-component-rows.md @@ -0,0 +1,8 @@ +--- +rows: + - component: dynamic + properties: '[{"component":"text"}, {"contents":"Hello, I am a dynamic component !", "italics":true}]' +--- + +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`. diff --git a/examples/official-site/content/components/dynamic/examples/02-json-file.md b/examples/official-site/content/components/dynamic/examples/02-json-file.md new file mode 100644 index 000000000..93ed89c7e --- /dev/null +++ b/examples/official-site/content/components/dynamic/examples/02-json-file.md @@ -0,0 +1,32 @@ +## 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"} + ]} + ] +} +``` diff --git a/examples/official-site/content/components/dynamic/examples/03-include-sql.md b/examples/official-site/content/components/dynamic/examples/03-include-sql.md new file mode 100644 index 000000000..52ed2af27 --- /dev/null +++ b/examples/official-site/content/components/dynamic/examples/03-include-sql.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/content/components/dynamic/examples/04-shared-shell.md b/examples/official-site/content/components/dynamic/examples/04-shared-shell.md new file mode 100644 index 000000000..702a152a4 --- /dev/null +++ b/examples/official-site/content/components/dynamic/examples/04-shared-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=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/content/components/dynamic/examples/05-tables.md b/examples/official-site/content/components/dynamic/examples/05-tables.md new file mode 100644 index 000000000..5bdc8c87e --- /dev/null +++ b/examples/official-site/content/components/dynamic/examples/05-tables.md @@ -0,0 +1,18 @@ +## 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; +``` diff --git a/examples/official-site/content/components/empty_state.md b/examples/official-site/content/components/empty_state.md new file mode 100644 index 000000000..8b511fe90 --- /dev/null +++ b/examples/official-site/content/components/empty_state.md @@ -0,0 +1,46 @@ +--- +icon: info-circle +since: 0.35.0 +category: forms-and-feedback +summary: Explain an empty view and offer the reader a next step. +top: + - class + - name: description + type: TEXT + description: A short text displayed below the title. + - name: description_md + type: TEXT + description: A short text displayed below the title, formatted using markdown. + - name: header + type: TEXT + description: Text displayed on the top of the empty state. + - name: icon + type: ICON + description: Name of an icon to be displayed on the top of the empty state. + - id + - name: image + type: URL + description: The URL (absolute or relative) of an image to display at the top of the empty state. + - name: link + type: URL + required: true + description: The URL to which the button should navigate when clicked. + - name: link_icon + type: ICON + required: true + description: Name of an icon to be displayed on the left side of the button. + - name: link_text + type: TEXT + required: true + description: The text displayed on the button. + - name: title + type: TEXT + required: true + description: Description of the empty state. +--- + +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. diff --git a/examples/official-site/content/components/empty_state/examples/01-not-found.md b/examples/official-site/content/components/empty_state/examples/01-not-found.md new file mode 100644 index 000000000..f1342e3db --- /dev/null +++ b/examples/official-site/content/components/empty_state/examples/01-not-found.md @@ -0,0 +1,16 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/empty_state/examples/02-illustration.md b/examples/official-site/content/components/empty_state/examples/02-illustration.md new file mode 100644 index 000000000..d5836daf0 --- /dev/null +++ b/examples/official-site/content/components/empty_state/examples/02-illustration.md @@ -0,0 +1,15 @@ +--- +rows: + - 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: '#' +--- + +It's possible to use an icon or an image to illustrate the problem. diff --git a/examples/official-site/content/components/facet.md b/examples/official-site/content/components/facet.md new file mode 100644 index 000000000..4ecbfbe22 --- /dev/null +++ b/examples/official-site/content/components/facet.md @@ -0,0 +1,74 @@ +--- +icon: filter +since: 0.46.0 +category: navigation +summary: Let readers choose filters for a dataset. +top: + - name: all_active + type: BOOLEAN + description: Whether the link that clears the filter is active. Defaults to false. + - name: all_link + type: URL + description: URL that clears the filter. If omitted, no All link is displayed. + - name: all_title + type: TEXT + description: Text for the link that clears the filter. Defaults to "ALL". + - name: center + type: BOOLEAN + description: Whether to center the facet selector + - class + - name: compact + type: BOOLEAN + description: Displays the facets in a dropdown instead of links. + - name: description + type: TEXT + description: The facet category label. + - name: dropdown_title + type: TEXT + description: Text shown on the compact-mode dropdown button when no facet is selected. Defaults to `Choose + facet`. + - id + - name: selected_facet + type: TEXT + description: An alias for `dropdown_title`. +row: + - name: active + type: BOOLEAN + description: Whether the link is active or not. Defaults to false. + - name: link + type: URL + required: true + description: URL for the facet. + - name: title + type: TEXT + required: true + description: Facet title. +--- + +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; +``` diff --git a/examples/official-site/content/components/facet/examples/01-category-selector.md b/examples/official-site/content/components/facet/examples/01-category-selector.md new file mode 100644 index 000000000..21a48b4f4 --- /dev/null +++ b/examples/official-site/content/components/facet/examples/01-category-selector.md @@ -0,0 +1,22 @@ +--- +rows: + - 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 +--- + +A category selector with an All link. In an application, the SQL pattern above uses the chosen URL parameter to filter the displayed data. diff --git a/examples/official-site/content/components/facet/examples/02-compact-dropdown.md b/examples/official-site/content/components/facet/examples/02-compact-dropdown.md new file mode 100644 index 000000000..4fb8bc6cf --- /dev/null +++ b/examples/official-site/content/components/facet/examples/02-compact-dropdown.md @@ -0,0 +1,25 @@ +--- +rows: + - 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 +--- + +Compact mode displays the facet choices in a dropdown. diff --git a/examples/official-site/content/components/foldable.md b/examples/official-site/content/components/foldable.md new file mode 100644 index 000000000..feccb9a1a --- /dev/null +++ b/examples/official-site/content/components/foldable.md @@ -0,0 +1,37 @@ +--- +icon: chevrons-down +since: 0.29.0 +category: page-layout +summary: Let readers expand individual sections to see their contents. +top: + - name: class + type: TEXT + description: CSS class(es) to add to the foldable container. When set at the top level, applies to the + entire foldable component. + - name: id + type: TEXT + description: 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. +row: + - name: class + type: TEXT + description: CSS class(es) to add to individual foldable items. + - name: description + type: TEXT + description: Plain text description of the item, displayed when expanded. + - name: description_md + type: TEXT + description: Markdown description of the item, displayed when expanded. + - name: expanded + type: BOOLEAN + description: If set to TRUE, the foldable item starts in an expanded state. Defaults FALSE + - name: id + type: TEXT + description: ID attribute added to individual foldable items. Used for targeting through CSS or for scrolling + via links. + - name: title + type: TEXT + description: Title of the foldable item, displayed on the button. +--- + +A foldable list of elements which can be expanded individually. diff --git a/examples/official-site/content/components/foldable/examples/01-paragraph.md b/examples/official-site/content/components/foldable/examples/01-paragraph.md new file mode 100644 index 000000000..00f1b1f67 --- /dev/null +++ b/examples/official-site/content/components/foldable/examples/01-paragraph.md @@ -0,0 +1,9 @@ +--- +rows: + - 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. +--- + +A single foldable paragraph of text diff --git a/examples/official-site/content/components/foldable/examples/02-markdown-list.md b/examples/official-site/content/components/foldable/examples/02-markdown-list.md new file mode 100644 index 000000000..5203e3b5d --- /dev/null +++ b/examples/official-site/content/components/foldable/examples/02-markdown-list.md @@ -0,0 +1,40 @@ +--- +rows: + - component: foldable + - title: Quick Prototyping + description_md: |- + 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/). + expanded: true + - title: Data Visualization + description_md: |- + 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; + ``` + - title: Don't stare, interact! + description_md: |- + 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! +--- + +A SQLPage-themed foldable list with Markdown diff --git a/examples/official-site/content/components/form.md b/examples/official-site/content/components/form.md new file mode 100644 index 000000000..4a65b4aaf --- /dev/null +++ b/examples/official-site/content/components/form.md @@ -0,0 +1,257 @@ +--- +icon: cursor-text +category: forms-and-feedback +summary: Collect input with text fields, file uploads, and other controls. +top: + - name: action + type: TEXT + description: 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. + - name: auto_submit + type: BOOLEAN + description: Automatically submit the form when the user changes any of its fields, and remove the validation + button. + - class + - name: enctype + type: TEXT + description: |2 + + When ``method="post"``, this specifies how the form-data should be encoded + when submitting it to the server. + - name: id + type: TEXT + description: A unique identifier for the form, which can then be used to validate the form from a button + outside of the form. + - name: method + type: TEXT + description: Set this to 'GET' to pass the form contents directly as URL parameters. If the user enters + a value v in a field named x, submitting the form will load target.sql?x=v. If target.sql contains SELECT + $x, it will display the value v. + - name: narrow + type: BOOLEAN + description: Whether to trim the horizontal padding between the icon and the label of the validation and + reset buttons. + - name: reset + type: TEXT + description: 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. + - name: reset_color + type: COLOR + description: 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. + - name: reset_icon + type: ICON + description: Name of an icon to be displayed on the left side of the reset button. + - name: reset_outline + type: COLOR + description: A color to outline the reset button. + - name: reset_shape + type: TEXT + description: The shape of the reset button (e.g., pill, square). + - name: reset_size + type: TEXT + description: The size of the reset button (e.g., sm, lg). + - name: title + type: TEXT + description: 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. + - name: validate + type: TEXT + description: 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. + - name: validate_color + type: COLOR + description: The color of the button at the bottom of the form that submits the values. Omit this property + to use the default color. + - name: validate_icon + type: ICON + description: Name of an icon to be displayed on the left side of the submit button. + - name: validate_outline + type: COLOR + description: A color to outline the validation button. + - name: validate_shape + type: TEXT + description: The shape of the validation button (e.g., pill, square). + - name: validate_size + type: TEXT + description: The size of the validation button (e.g., sm, lg). +row: + - name: accept + type: TEXT + description: 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/*"). + - name: autocomplete + type: BOOLEAN + description: Whether the browser should suggest previously entered values for this field. + - name: autofocus + type: BOOLEAN + description: Automatically focus the field when the page is loaded + - name: checked + type: BOOLEAN + description: Used only for checkboxes and radio buttons. Indicates whether the checkbox should appear as + already checked. + - name: class + type: TEXT + description: A CSS class to apply to the form element. + - name: create_new + type: BOOLEAN + description: 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. + - name: description + type: TEXT + description: A helper text to display near the input field. + - name: description_md + type: TEXT + description: A helper text to display near the input field - formatted using markdown. + - name: disabled + type: BOOLEAN + description: Makes the field non-editable, non-focusable, and not submitted with the form. Use readonly + instead for simple non-editable fields. + - name: dropdown + type: BOOLEAN + description: An alias for "searchable". + - name: empty_option + type: TEXT + description: 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. + - name: formaction + type: TEXT + description: When type is "submit", this specifies the URL of the file that will handle the form submission. + Useful when you need multiple submit buttons. + - name: formenctype + type: TEXT + description: |2 + + 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. + - name: formmethod + type: TEXT + description: When type is "submit", the HTTP method to submit the form with. Takes precedence over the + form's own "method". + - name: formnovalidate + type: BOOLEAN + description: When type is "submit", skips the browser's validation of the other fields when this button + submits the form. + - name: formtarget + type: TEXT + description: '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.' + - name: id + type: TEXT + description: 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. + - name: label + type: TEXT + description: A friendly name for the text field to show to the user. + - name: list + type: TEXT + description: 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. + - name: max + type: REAL + description: The maximum value to accept for an input of type number + - name: maxlength + type: INTEGER + description: Maximum length of text allowed in the field. + - name: min + type: REAL + description: The minimum value to accept for an input of type number + - name: minlength + type: INTEGER + description: Minimum length of text allowed in the field. + - name: multiple + type: BOOLEAN + description: '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).' + - name: name + type: TEXT + required: true + description: The name of the input field, that you can use in the target page to get the value the user + entered for the field. + - name: options + type: JSON + description: 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". + - name: options_source + type: URL + description: 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. + - name: pattern + type: TEXT + description: A regular expression that the value must match. For instance, [0-9]{3} will only accept 3 + digits. + - name: placeholder + type: TEXT + description: A placeholder text that will be shown in the field when is is empty. + - name: prefix + type: TEXT + description: Text to display on the left side of the input field, on the same line. + - name: prefix_icon + type: ICON + description: Icon to display on the left side of the input field, on the same line. + - name: readonly + type: BOOLEAN + description: Set to true to prevent the user from modifying the value of the input field. + - name: required + type: BOOLEAN + description: Set this to true to prevent the form contents from being sent if this field is left empty + by the user. + - name: rows + type: INTEGER + description: Number of rows to display for a textarea. Defaults to 3. + - name: searchable + type: BOOLEAN + description: For select and multiple-select elements, displays them with a nice dropdown that allows searching + for options. + - name: step + type: REAL + description: The increment of values in an input of type number. Set to 1 to allow only integers. + - name: suffix + type: TEXT + description: Short text to display after th input, on the same line. Useful to add units or a currency + symbol to an input. + - name: type + type: TEXT + description: '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' + - name: value + type: TEXT + description: A default value that will already be present in the field when the user loads the page. + - name: width + type: INTEGER + description: Width of the form field, between 1 and 12. +--- + +## 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. diff --git a/examples/official-site/content/components/form/examples/01-submit-to-another-page.md b/examples/official-site/content/components/form/examples/01-submit-to-another-page.md new file mode 100644 index 000000000..7649a1eda --- /dev/null +++ b/examples/official-site/content/components/form/examples/01-submit-to-another-page.md @@ -0,0 +1,25 @@ +--- +rows: + - component: form + action: create_user.sql + - name: username +--- + +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. diff --git a/examples/official-site/content/components/form/examples/02-registration.md b/examples/official-site/content/components/form/examples/02-registration.md new file mode 100644 index 000000000..25abab145 --- /dev/null +++ b/examples/official-site/content/components/form/examples/02-registration.md @@ -0,0 +1,29 @@ +--- +rows: + - 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 +--- + +A user registration form, illustrating the use of required fields, and different input types. diff --git a/examples/official-site/content/components/form/examples/03-input-prefix-and-suffix.md b/examples/official-site/content/components/form/examples/03-input-prefix-and-suffix.md new file mode 100644 index 000000000..0c020d82e --- /dev/null +++ b/examples/official-site/content/components/form/examples/03-input-prefix-and-suffix.md @@ -0,0 +1,10 @@ +--- +rows: + - component: form + - name: Your account + prefix_icon: mail + prefix: 'Email:' + suffix: '@mydomain.com' +--- + +Create prepended and appended inputs to make your forms easier to use. diff --git a/examples/official-site/content/components/form/examples/04-groups.md b/examples/official-site/content/components/form/examples/04-groups.md new file mode 100644 index 000000000..948d35edc --- /dev/null +++ b/examples/official-site/content/components/form/examples/04-groups.md @@ -0,0 +1,16 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/form/examples/05-switch.md b/examples/official-site/content/components/form/examples/05-switch.md new file mode 100644 index 000000000..400e4337e --- /dev/null +++ b/examples/official-site/content/components/form/examples/05-switch.md @@ -0,0 +1,19 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/form/examples/06-select.md b/examples/official-site/content/components/form/examples/06-select.md new file mode 100644 index 000000000..5979e3118 --- /dev/null +++ b/examples/official-site/content/components/form/examples/06-select.md @@ -0,0 +1,32 @@ +--- +rows: + - 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}]' +--- + +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 +``` diff --git a/examples/official-site/content/components/form/examples/07-multi-select.md b/examples/official-site/content/components/form/examples/07-multi-select.md new file mode 100644 index 000000000..d7e75a4c8 --- /dev/null +++ b/examples/official-site/content/components/form/examples/07-multi-select.md @@ -0,0 +1,82 @@ +--- +rows: + - 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'... +--- + +### 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` diff --git a/examples/official-site/content/components/form/examples/08-radio.md b/examples/official-site/content/components/form/examples/08-radio.md new file mode 100644 index 000000000..be9fe906c --- /dev/null +++ b/examples/official-site/content/components/form/examples/08-radio.md @@ -0,0 +1,41 @@ +--- +rows: + - 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 +--- + +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". diff --git a/examples/official-site/content/components/form/examples/09-refresh-on-change.md b/examples/official-site/content/components/form/examples/09-refresh-on-change.md new file mode 100644 index 000000000..0de27b1e9 --- /dev/null +++ b/examples/official-site/content/components/form/examples/09-refresh-on-change.md @@ -0,0 +1,24 @@ +--- +rows: + - 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 +--- + +### 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. diff --git a/examples/official-site/content/components/form/examples/10-hidden-input.md b/examples/official-site/content/components/form/examples/10-hidden-input.md new file mode 100644 index 000000000..ba4aced2e --- /dev/null +++ b/examples/official-site/content/components/form/examples/10-hidden-input.md @@ -0,0 +1,22 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/form/examples/11-custom-submit.md b/examples/official-site/content/components/form/examples/11-custom-submit.md new file mode 100644 index 000000000..6bfbd9407 --- /dev/null +++ b/examples/official-site/content/components/form/examples/11-custom-submit.md @@ -0,0 +1,38 @@ +--- +rows: + - 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 +--- + +This example illustrates the use of custom validation buttons and half-width fields. diff --git a/examples/official-site/content/components/form/examples/12-file-upload.md b/examples/official-site/content/components/form/examples/12-file-upload.md new file mode 100644 index 000000000..798d51eb5 --- /dev/null +++ b/examples/official-site/content/components/form/examples/12-file-upload.md @@ -0,0 +1,31 @@ +--- +rows: + - 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 +--- + +## File upload + +You can use the `file` type to allow the user to upload a file. + +The file will be uploaded to the server, and you will be able to access it using the +[`sqlpage.uploaded_file_path`](functions.sql?function=uploaded_file_path#function) function. + +Here is how you could save the uploaded file to a table in the database: + +```sql +INSERT INTO uploaded_file(name, data) +VALUES ( + :filename, + sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('my_file')) +) +``` diff --git a/examples/official-site/content/components/form/examples/13-encoding.md b/examples/official-site/content/components/form/examples/13-encoding.md new file mode 100644 index 000000000..ff0387ace --- /dev/null +++ b/examples/official-site/content/components/form/examples/13-encoding.md @@ -0,0 +1,42 @@ +--- +rows: + - 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 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. diff --git a/examples/official-site/content/components/form/examples/14-bulk-insert.md b/examples/official-site/content/components/form/examples/14-bulk-insert.md new file mode 100644 index 000000000..f4f81a02f --- /dev/null +++ b/examples/official-site/content/components/form/examples/14-bulk-insert.md @@ -0,0 +1,61 @@ +--- +rows: + - 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 +--- + +## Bulk data insertion + +You can use the `file` type to allow the user to upload a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) +file containing data to insert in a table. + +SQLPage can load data from a CSV file and insert it into a database table. +SQLPage re-uses PostgreSQL's [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html) +to specify the format of the CSV file, but makes it work with all supported databases. + +> When connected to a PostgreSQL database, SQLPage will use the native `COPY` statement, +> for super fast and efficient on-database CSV parsing. +> But it will also work transparently with other databases, by +> parsing the CSV locally and emulating the same behavior with simple `INSERT` statements. + +Here is how you could easily copy data from a CSV to a table in the database: + +```sql +copy product(name, description) from 'product_data_input' +with (header true, delimiter ',', quote '"'); +``` + +If you want to pre-process the data before inserting it into the final table, +you can use a temporary table to store the data, and then insert it into the final table: + +```sql +-- temporarily store the data in a table with text columns +create temporary table if not exists product_tmp(name text, description text, price text); +delete from product_tmp; + +-- copy the data from the CSV file into the temporary table +copy product_tmp(name, description, price) from 'product_data_input'; + +-- insert the data into the final table, converting the price column to an integer +insert into product(name, description, price) +select name, description, CAST(price AS integer) from product_tmp +where price is not null and description is not null and length(description) > 10; +``` + +This will load the processed CSV into the product table, provided it has the following structure: + +```csv +name,description,price +"SQLPage","A tool to create websites using SQL",0 +"PostgreSQL","A powerful open-source relational database",0 +"SQLite","A lightweight relational database",0 +"MySQL","A popular open-source relational database",0 +``` diff --git a/examples/official-site/content/components/hero.md b/examples/official-site/content/components/hero.md new file mode 100644 index 000000000..7b0009b55 --- /dev/null +++ b/examples/official-site/content/components/hero.md @@ -0,0 +1,70 @@ +--- +icon: home +category: page-layout +summary: Introduce a page with a headline, media, and a call to action. +top: + - name: autoplay + type: BOOLEAN + description: Automatically start playing the video + - name: description + type: TEXT + description: A description of the page. Displayed below the title, in smaller characters and slightly greyed + out. + - name: description_md + type: TEXT + description: A description of the page. Displayed below the title, in smaller characters and slightly greyed + out - formatted using markdown. + - id + - name: image + type: URL + description: The URL of an image to display next to the page title. + - name: link + type: URL + description: Creates a large "call to action" button below the description, linking to the specified URL. + - name: link_text + type: TEXT + description: The text to display in the call to action button. Defaults to "Go". + - name: loop + type: BOOLEAN + description: Loop the video + - name: muted + type: BOOLEAN + description: Mute the video + - name: nocontrols + type: BOOLEAN + description: Hide the video controls (play, pause, volume, etc.), and autoplay the video. + - name: poster + type: URL + description: URL of the image to be displayed before the video starts. Ignored if no video is present. + - name: reverse + type: BOOLEAN + description: '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.' + - name: title + type: TEXT + description: The title of your page. Will be shown in very large characters at the top. + - name: video + type: URL + description: The URL of a video to display next to the page title. +row: + - name: color + type: COLOR + description: Color of the badge behind the feature section's icon. Defaults to "success". + - name: description + type: TEXT + description: Description of the feature section. + - name: description_md + type: TEXT + description: Description of the feature section - formatted using markdown. + - name: icon + type: ICON + description: Icon of the feature section. + - name: link + type: TEXT + description: An URL to which the user should be taken when they click on the section title. + - name: title + type: TEXT + description: The name of a single feature section highlighted by this hero. +--- + +Display a large title and description for your page, with an optional large illustrative image. Useful in your home page, for instance. diff --git a/examples/official-site/content/components/hero/examples/01-basic.md b/examples/official-site/content/components/hero/examples/01-basic.md new file mode 100644 index 000000000..2860656e0 --- /dev/null +++ b/examples/official-site/content/components/hero/examples/01-basic.md @@ -0,0 +1,8 @@ +--- +rows: + - component: hero + title: Welcome + description: This is a very simple site built with SQLPage. +--- + +The simplest possible hero section diff --git a/examples/official-site/content/components/hero/examples/02-background-image.md b/examples/official-site/content/components/hero/examples/02-background-image.md new file mode 100644 index 000000000..03ed29373 --- /dev/null +++ b/examples/official-site/content/components/hero/examples/02-background-image.md @@ -0,0 +1,26 @@ +--- +rows: + - 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: / +--- + +A hero with a background image. diff --git a/examples/official-site/content/components/hero/examples/03-video.md b/examples/official-site/content/components/hero/examples/03-video.md new file mode 100644 index 000000000..ba7083034 --- /dev/null +++ b/examples/official-site/content/components/hero/examples/03-video.md @@ -0,0 +1,11 @@ +--- +rows: + - 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 +--- + +A hero with a video diff --git a/examples/official-site/content/components/html.md b/examples/official-site/content/components/html.md new file mode 100644 index 000000000..37f8e419c --- /dev/null +++ b/examples/official-site/content/components/html.md @@ -0,0 +1,29 @@ +--- +icon: html +since: 0.25.0 +category: page-layout +summary: Insert your own HTML markup into the page. +top: + - name: html + type: TEXT + description: 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. +row: + - name: html + type: TEXT + description: 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. + - name: post_html + type: TEXT + description: 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. + - name: text + type: TEXT + description: 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. +--- + +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. diff --git a/examples/official-site/content/components/html/examples/01-html-snippet.md b/examples/official-site/content/components/html/examples/01-html-snippet.md new file mode 100644 index 000000000..23e4d1be9 --- /dev/null +++ b/examples/official-site/content/components/html/examples/01-html-snippet.md @@ -0,0 +1,7 @@ +--- +rows: + - component: html + html:

This text is safe because it is hardcoded!

+--- + +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. diff --git a/examples/official-site/content/components/html/examples/02-multiple-snippets.md b/examples/official-site/content/components/html/examples/02-multiple-snippets.md new file mode 100644 index 000000000..665dadb70 --- /dev/null +++ b/examples/official-site/content/components/html/examples/02-multiple-snippets.md @@ -0,0 +1,12 @@ +--- +rows: + - component: html + html: '
' + - html: '
20%
' + - html: '
80%
' + - 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. diff --git a/examples/official-site/content/components/html/examples/03-sanitized-text.md b/examples/official-site/content/components/html/examples/03-sanitized-text.md new file mode 100644 index 000000000..5fb5f835d --- /dev/null +++ b/examples/official-site/content/components/html/examples/03-sanitized-text.md @@ -0,0 +1,9 @@ +--- +rows: + - component: html + - html: '

The following will be sanitized: ' + text: + post_html: . Phew! That was close!

+--- + +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. diff --git a/examples/official-site/content/components/http_header.md b/examples/official-site/content/components/http_header.md new file mode 100644 index 000000000..0c56e47d8 --- /dev/null +++ b/examples/official-site/content/components/http_header.md @@ -0,0 +1,44 @@ +--- +icon: world-www +category: http-responses +summary: Set response headers for caching, content types, and more. +top: + - name: Access-Control-Allow-Origin + type: TEXT + description: Specifies which origins are allowed to access the resource in a cross-origin request, used + for implementing Cross-Origin Resource Sharing (CORS). + - name: Cache-Control + type: TEXT + description: 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. + - name: Content-Disposition + type: TEXT + description: Provides instructions on how the response content should be displayed or handled by the client, + such as inline or as an attachment. + - name: Location + type: TEXT + description: Specifies the URL to redirect the client to, usually used in 3xx redirection responses. + - name: Set-Cookie + type: TEXT + description: Sets a cookie in the client browser, used for session management and storing user-related + information. +--- + +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]). diff --git a/examples/official-site/content/components/http_header/examples/01-cache-control.md b/examples/official-site/content/components/http_header/examples/01-cache-control.md new file mode 100644 index 000000000..4c10e8f04 --- /dev/null +++ b/examples/official-site/content/components/http_header/examples/01-cache-control.md @@ -0,0 +1,14 @@ +--- +rows: + - component: http_header + Cache-Control: public, max-age=600, stale-while-revalidate=3600, stale-if-error=86400 +--- + +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. diff --git a/examples/official-site/content/components/http_header/examples/02-redirect.md b/examples/official-site/content/components/http_header/examples/02-redirect.md new file mode 100644 index 000000000..cb0d1db78 --- /dev/null +++ b/examples/official-site/content/components/http_header/examples/02-redirect.md @@ -0,0 +1,8 @@ +--- +rows: + - component: http_header + Location: /another-page.sql +--- + +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. diff --git a/examples/official-site/content/components/http_header/examples/03-custom-header.md b/examples/official-site/content/components/http_header/examples/03-custom-header.md new file mode 100644 index 000000000..2b746e83f --- /dev/null +++ b/examples/official-site/content/components/http_header/examples/03-custom-header.md @@ -0,0 +1,7 @@ +--- +rows: + - component: http_header + X-My-Header: my value +--- + +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". diff --git a/examples/official-site/content/components/json.md b/examples/official-site/content/components/json.md new file mode 100644 index 000000000..81c48edce --- /dev/null +++ b/examples/official-site/content/components/json.md @@ -0,0 +1,39 @@ +--- +icon: code +since: 0.9.0 +category: http-responses +summary: Return query results as JSON for an API. +top: + - name: contents + type: TEXT + description: 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. + - name: type + type: TEXT + description: |- + 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. +--- + +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. diff --git a/examples/official-site/content/components/json/examples/01-array.md b/examples/official-site/content/components/json/examples/01-array.md new file mode 100644 index 000000000..8510c9305 --- /dev/null +++ b/examples/official-site/content/components/json/examples/01-array.md @@ -0,0 +1,30 @@ +## 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 +``` diff --git a/examples/official-site/content/components/json/examples/02-jsonlines.md b/examples/official-site/content/components/json/examples/02-jsonlines.md new file mode 100644 index 000000000..f8e60e649 --- /dev/null +++ b/examples/official-site/content/components/json/examples/02-jsonlines.md @@ -0,0 +1,30 @@ +## Send a single JSON object: `'jsonlines' as type` + +In `jsonlines` mode, each query result is rendered as a JSON object in a separate line, +without a top-level array. + +If there is a single query result, the response will be a valid JSON object. +If there are multiple query results, you will need to parse each line of the response as a separate JSON object. + +If a query returns an error, the response will be a JSON object with an `error` property. + +### SQL + +The following SQL creates an API endpoint that takes a `user_id` URL parameter +and returns a single JSON object containing the user's details, with one json object key per column in the `users` table. + +```sql +select 'json' AS component, 'jsonlines' AS type; +select * from users where id = $user_id LIMIT 1; +``` + +> Note the `LIMIT 1` clause. The `jsonlines` type will send one JSON object per result row, +> separated only by a single newline character (\n). +> So if your query returns multiple rows, the result will not be a single valid JSON object, +> like most JSON parsers expect. + +### Result + +```json +{ "username":"James", "userid":1 } +``` diff --git a/examples/official-site/content/components/json/examples/03-custom-response.md b/examples/official-site/content/components/json/examples/03-custom-response.md new file mode 100644 index 000000000..53ef56fbf --- /dev/null +++ b/examples/official-site/content/components/json/examples/03-custom-response.md @@ -0,0 +1,42 @@ +## 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. diff --git a/examples/official-site/content/components/json/examples/04-server-sent-events.md b/examples/official-site/content/components/json/examples/04-server-sent-events.md new file mode 100644 index 000000000..d2c4c6a4e --- /dev/null +++ b/examples/official-site/content/components/json/examples/04-server-sent-events.md @@ -0,0 +1,25 @@ +## 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/content/components/list.md b/examples/official-site/content/components/list.md new file mode 100644 index 000000000..253463b6e --- /dev/null +++ b/examples/official-site/content/components/list.md @@ -0,0 +1,73 @@ +--- +icon: list +category: display-data +summary: Present rows as a vertical list with optional links and icons. +top: + - class + - name: compact + type: BOOLEAN + description: Whether to display the list in a more compact format, allowing more items to be displayed + on the screen. + - name: empty_description + type: TEXT + description: Description to display if the list is empty. + - name: empty_description_md + type: TEXT + description: Description to display if the list is empty, in Markdown format. + - name: empty_link + type: URL + description: URL to which the user should be taken if they click on the empty list. + - name: empty_title + type: TEXT + description: Title text to display if the list is empty. + - id + - name: title + type: TEXT + description: Text header at the top of the list. + - name: wrap + type: BOOLEAN + description: Wrap list items onto multiple lines if they are too long +row: + - name: active + type: BOOLEAN + description: Whether this item in the list is considered "active". Active items are displayed more prominently. + - class + - name: color + type: COLOR + description: The name of a color, to be displayed as a dot near the list item contents. + - name: delete_link + type: URL + description: 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. + - name: description + type: TEXT + description: A description of the list item, displayed as greyed-out text. + - name: description_md + type: TEXT + description: 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. + - name: edit_link + type: URL + description: A URL to which the user should be taken when they click on the "edit" icon. Does not show + the icon when omitted. + - name: icon + type: ICON + description: Name of an icon to display on the left side of the item. + - id + - name: image_url + type: URL + description: The URL of a small image to display on the left side of the item. + - name: link + type: URL + description: An URL to which the user should be taken when they click on the list item. + - name: title + type: TEXT + required: true + description: Name of the list item, displayed prominently. + - name: view_link + type: URL + description: A URL to which the user should be taken when they click on the "view" icon. Does not show + the icon when omitted. +--- + +A vertical list of items. Each item can be clickable and link to another page. diff --git a/examples/official-site/content/components/list/examples/01-compact.md b/examples/official-site/content/components/list/examples/01-compact.md new file mode 100644 index 000000000..53df3fc27 --- /dev/null +++ b/examples/official-site/content/components/list/examples/01-compact.md @@ -0,0 +1,11 @@ +--- +rows: + - component: list + compact: true + title: SQLPage lists are... + - title: Beautiful + - title: Useful + - title: Versatile +--- + +A basic compact list diff --git a/examples/official-site/content/components/list/examples/02-empty.md b/examples/official-site/content/components/list/examples/02-empty.md new file mode 100644 index 000000000..61c192fdd --- /dev/null +++ b/examples/official-site/content/components/list/examples/02-empty.md @@ -0,0 +1,9 @@ +--- +rows: + - component: list + empty_title: No items yet + empty_description: This list is empty. Click here to create a new item ! + empty_link: documentation.sql +--- + +An empty list with a link to add an item diff --git a/examples/official-site/content/components/list/examples/03-markdown.md b/examples/official-site/content/components/list/examples/03-markdown.md new file mode 100644 index 000000000..5de310e98 --- /dev/null +++ b/examples/official-site/content/components/list/examples/03-markdown.md @@ -0,0 +1,31 @@ +--- +rows: + - 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.' +--- + +### 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. diff --git a/examples/official-site/content/components/list/examples/04-full-list.md b/examples/official-site/content/components/list/examples/04-full-list.md new file mode 100644 index 000000000..cdb65986a --- /dev/null +++ b/examples/official-site/content/components/list/examples/04-full-list.md @@ -0,0 +1,29 @@ +--- +rows: + - 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 +--- + +A beautiful list with bells and whistles. diff --git a/examples/official-site/content/components/log.md b/examples/official-site/content/components/log.md new file mode 100644 index 000000000..4a8a8bac9 --- /dev/null +++ b/examples/official-site/content/components/log.md @@ -0,0 +1,26 @@ +--- +icon: logs +since: 0.37.1 +category: server-logic +summary: Write a message to the SQLPage server log. +top: + - name: level + type: TEXT + description: How important the message is. One of 'trace', 'debug', 'info' (default), 'warn', 'error'. + Not case-sensitive. Controls the level shown in the logs. + - name: message + type: TEXT + required: true + description: The text to write to the server logs. It is printed when the page runs. +--- + +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). diff --git a/examples/official-site/content/components/log/examples/01-message.md b/examples/official-site/content/components/log/examples/01-message.md new file mode 100644 index 000000000..d09da451c --- /dev/null +++ b/examples/official-site/content/components/log/examples/01-message.md @@ -0,0 +1,39 @@ +### 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/content/components/login.md b/examples/official-site/content/components/login.md new file mode 100644 index 000000000..dcec0d9e4 --- /dev/null +++ b/examples/official-site/content/components/login.md @@ -0,0 +1,98 @@ +--- +icon: password-user +since: 0.39.0 +category: forms-and-feedback +summary: Display a sign-in form for a username and password. +top: + - name: action + type: TEXT + description: 'An optional link to a target page that will handle the results of the form. ' + - name: autofocus + type: BOOLEAN + description: Focus the username field when the page opens. Defaults to true. Set to false when the form + is one part of a larger page. + - class + - name: enctype + type: TEXT + description: Form data encoding. + - name: error_message + type: TEXT + description: An error message to display above the form, typically shown after a failed login attempt. + - name: error_message_md + type: TEXT + description: A markdown error message to display above the form, typically shown after a failed login attempt. + - name: footer + type: TEXT + description: A text placed at the bottom of the authentication form. If both footer and footer_md are specified, + footer takes precedence. + - name: footer_md + type: TEXT + description: 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.). + - name: forgot_password_link + type: TEXT + description: The link to the page allowing the user to reset their password. + - name: forgot_password_text + type: TEXT + description: A text for the link allowing the user to reset their password. If the text is empty, the link + is not displayed. + - id + - name: image + type: URL + description: The URL of an centered image displayed before the title. + - name: image_alt + type: TEXT + description: Alternative text for an informative login image. Leave empty if decorative. + - name: password + type: TEXT + required: true + description: Label and placeholder for the password field. + - name: password_icon + type: ICON + description: Icon to display on the left side of the input field, on the same line. + - name: remember_me_text + type: TEXT + description: 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. + - name: title + type: TEXT + description: Title of the authentication form. + - name: username + type: TEXT + required: true + description: Label and placeholder for the user account identifier text field. + - name: username_icon + type: ICON + description: Icon to display on the left side of the input field, on the same line. + - name: validate + type: TEXT + description: The text to display in the button at the bottom of the form that submits the values. + - name: validate_color + type: COLOR + description: The color of the button at the bottom of the form that submits the values. Omit this property + to use the default color. + - name: validate_outline + type: COLOR + description: A color to outline the validation button. + - name: validate_shape + type: TEXT + description: The shape of the validation button. + - name: validate_size + type: TEXT + description: The size of the validation button. +--- + +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. diff --git a/examples/official-site/content/components/login/examples/01-options.md b/examples/official-site/content/components/login/examples/01-options.md new file mode 100644 index 000000000..e5711698a --- /dev/null +++ b/examples/official-site/content/components/login/examples/01-options.md @@ -0,0 +1,25 @@ +--- +rows: + - 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 +--- + +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 diff --git a/examples/official-site/content/components/login/examples/02-basic.md b/examples/official-site/content/components/login/examples/02-basic.md new file mode 100644 index 000000000..8fddbf420 --- /dev/null +++ b/examples/official-site/content/components/login/examples/02-basic.md @@ -0,0 +1,9 @@ +--- +rows: + - component: login + username: Username + password: Password + autofocus: false +--- + +Basic login form diff --git a/examples/official-site/content/components/map.md b/examples/official-site/content/components/map.md new file mode 100644 index 000000000..42ea16e8e --- /dev/null +++ b/examples/official-site/content/components/map.md @@ -0,0 +1,87 @@ +--- +icon: map +since: 0.8.0 +category: display-data +summary: Plot locations and geographic shapes on an interactive map. +top: + - name: attribution + type: HTML + description: Text to display at the bottom right of the map. Defaults to "© OpenStreetMap". + - class + - name: height + type: INTEGER + description: Height of the map, in pixels. Default to 350px + - id + - name: latitude + type: REAL + description: Latitude of the center of the map. If omitted, the map will be centered on its markers. + - name: longitude + type: REAL + description: Longitude of the center of the map. + - name: max_zoom + type: INTEGER + description: How far the map can be zoomed in. Defaults to 18. Added in v0.15.2. + - name: tile_source + type: URL + description: 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. + - name: title + type: TEXT + description: A text header displayed above the map. + - name: zoom + type: REAL + description: Zoom Level to apply to the map. Defaults to 5. +row: + - name: color + type: COLOR + description: Background color of the marker on the map. Requires "icon" to be set. + - name: description + type: TEXT + description: Plain text description of the marker, to be displayed in a tooltip when the marker is clicked. + - name: description_md + type: TEXT + description: Description of the marker, in markdown, rendered in a tooltip when the marker is clicked. + - name: geojson + type: JSON + description: 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. + - name: icon + type: ICON + description: Name of the icon to use for the marker + - name: latitude + type: REAL + required: true + description: Latitude of the marker. Required only if geojson is not set. + - name: link + type: TEXT + description: A link to associate to the marker's title. If set, the marker tooltip's title will be clickable + and will open the link. + - name: longitude + type: REAL + required: true + description: Longitude of the marker. Required only if geojson is not set. + - name: size + type: INTEGER + description: Size of the marker icon. Requires "icon" to be set. Introduced in 0.15.2. + - name: title + type: TEXT + description: Title of the marker, displayed on hover and in the tooltip when the marker is clicked. +--- + +## 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. diff --git a/examples/official-site/content/components/map/examples/01-marker.md b/examples/official-site/content/components/map/examples/01-marker.md new file mode 100644 index 000000000..638f78a30 --- /dev/null +++ b/examples/official-site/content/components/map/examples/01-marker.md @@ -0,0 +1,11 @@ +--- +rows: + - component: map + - title: New Delhi + latitude: 28.6139 + longitude: 77.209 +--- + +### 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. diff --git a/examples/official-site/content/components/map/examples/02-geojson-and-tiles.md b/examples/official-site/content/components/map/examples/02-geojson-and-tiles.md new file mode 100644 index 000000000..37c985320 --- /dev/null +++ b/examples/official-site/content/components/map/examples/02-geojson-and-tiles.md @@ -0,0 +1,27 @@ +--- +rows: + - 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] }}' +--- + +### Advanced map customization using GeoJSON and custom map tiles + +This example demonstrates using topographic map tiles, custom marker styling, +and clickable markers that link to external content - perfect for educational or tourism applications. + +It uses [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) to display polygons and lines. + + - You can generate GeoJSON data from PostGIS geometries using the [`ST_AsGeoJSON`](https://postgis.net/docs/ST_AsGeoJSON.html) function. + - In spatialite, you can use the [`AsGeoJSON`](https://www.gaia-gis.it/gaia-sins/spatialite-sql-5.1.0.html#p3misc) function. + - In MySQL, you can use the [`ST_AsGeoJSON()`](https://dev.mysql.com/doc/refman/8.0/en/spatial-geojson-functions.html#function_st-asgeojson) function. diff --git a/examples/official-site/content/components/map/examples/03-rich-links.md b/examples/official-site/content/components/map/examples/03-rich-links.md new file mode 100644 index 000000000..f7e7e1a50 --- /dev/null +++ b/examples/official-site/content/components/map/examples/03-rich-links.md @@ -0,0 +1,40 @@ +--- +rows: + - 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.853 + 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.853 + color: teal + description: A nice 45 minutes walk. +--- + +### 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/). diff --git a/examples/official-site/content/components/map/examples/04-geometric-visualizations.md b/examples/official-site/content/components/map/examples/04-geometric-visualizations.md new file mode 100644 index 000000000..b19f39b10 --- /dev/null +++ b/examples/official-site/content/components/map/examples/04-geometric-visualizations.md @@ -0,0 +1,41 @@ +--- +rows: + - 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 +--- + +### 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. diff --git a/examples/official-site/content/components/modal.md b/examples/official-site/content/components/modal.md new file mode 100644 index 000000000..59fc9f397 --- /dev/null +++ b/examples/official-site/content/components/modal.md @@ -0,0 +1,67 @@ +--- +icon: app-window +since: 0.36.0 +category: forms-and-feedback +summary: Open a dialog over the page for details, forms, or media. +top: + - name: allow + type: TEXT + description: For embedded content, this attribute specifies the features or permissions that can be used. + - name: class + type: TEXT + description: Class attribute added to the container in HTML. It can be used to apply custom styling to + this item through css. + - name: close + type: TEXT + description: The text to display in the Close button. + - name: close_label + type: TEXT + description: The same as `close`. Use it on databases where `close` is a reserved word, such as SQL Server. + - name: embed + type: TEXT + description: Embed remote content in an iframe. + - name: embed_mode + type: TEXT + description: Use "iframe" to display embedded content within an iframe. + - name: height + type: INTEGER + description: Height of the modal content, in pixels. Overflow content scrolls. + - name: id + type: TEXT + required: true + description: ID attribute added to the container in HTML. It can be used to target this item through css + or for displaying this item. + - name: large + type: BOOLEAN + description: Indicates that the modal box has an increased width. + - name: sandbox + type: TEXT + description: For embedded content, this attribute specifies the security restrictions on the loaded content. + - name: scrollable + type: BOOLEAN + description: Create a scrollable modal that allows scroll the modal body. + - name: small + type: BOOLEAN + description: Indicates that the modal box has a reduced width. + - name: style + type: TEXT + description: Applies CSS styles to the embedded content. + - name: title + type: TEXT + required: true + description: Description of the modal box. +row: + - name: contents + type: TEXT + description: A paragraph of text to display, without any formatting, without having to make additional + queries. + - name: contents_md + type: TEXT + description: 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)`. +--- + +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. diff --git a/examples/official-site/content/components/modal/examples/01-text.md b/examples/official-site/content/components/modal/examples/01-text.md new file mode 100644 index 000000000..ef4092e6c --- /dev/null +++ b/examples/official-site/content/components/modal/examples/01-text.md @@ -0,0 +1,13 @@ +--- +rows: + - 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' +--- + +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. diff --git a/examples/official-site/content/components/modal/examples/02-form.md b/examples/official-site/content/components/modal/examples/02-form.md new file mode 100644 index 000000000..318c060c7 --- /dev/null +++ b/examples/official-site/content/components/modal/examples/02-form.md @@ -0,0 +1,13 @@ +--- +rows: + - component: modal + id: my_embed_form_modal + title: Embeded form content + large: true + embed: /examples/form.sql?_sqlpage_embed + - component: button + - title: Open a modal with a form + link: '#my_embed_form_modal' +--- + +Example of modal form content diff --git a/examples/official-site/content/components/modal/examples/03-chart.md b/examples/official-site/content/components/modal/examples/03-chart.md new file mode 100644 index 000000000..2185f46f1 --- /dev/null +++ b/examples/official-site/content/components/modal/examples/03-chart.md @@ -0,0 +1,19 @@ +--- +rows: + - 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' +--- + +A popup modal that contains a chart generated by a separate SQL file. The modal is triggered by links inside a datagrid. diff --git a/examples/official-site/content/components/modal/examples/04-video.md b/examples/official-site/content/components/modal/examples/04-video.md new file mode 100644 index 000000000..c73372895 --- /dev/null +++ b/examples/official-site/content/components/modal/examples/04-video.md @@ -0,0 +1,15 @@ +--- +rows: + - 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) +--- + +Example of modal video content diff --git a/examples/official-site/content/components/pagination.md b/examples/official-site/content/components/pagination.md new file mode 100644 index 000000000..45ada6d28 --- /dev/null +++ b/examples/official-site/content/components/pagination.md @@ -0,0 +1,104 @@ +--- +icon: sailboat-2 +since: 0.40.0 +category: navigation +summary: Link to other pages of a query result. +top: + - name: circle + type: BOOLEAN + description: Whether to use circle version of the pagination. + - class + - name: first_disabled + type: BOOLEAN + description: disables the button to go to the first page. + - name: first_link + type: URL + description: A target URL to which the user should be directed to get to the first page. If none, the link + is not displayed. + - name: first_title + type: TEXT + description: The text displayed on the button to go to the first page. + - id + - name: last_disabled + type: BOOLEAN + description: disables the button to go to the last page. + - name: last_link + type: URL + description: A target URL to which the user should be directed to get to the last page. If none, the link + is not displayed. + - name: last_title + type: TEXT + description: The text displayed on the button to go to the last page. + - name: next_disabled + type: BOOLEAN + description: Disables the button to go to the next page. + - name: next_link + type: URL + description: A target URL to which the user should be directed to get to the next page. If none, the link + is not displayed. + - name: next_title + type: TEXT + description: The text displayed on the button to go to the next page. + - name: outline + type: BOOLEAN + description: Whether to use outline version of the pagination. + - name: previous_disabled + type: BOOLEAN + description: disables the button to go to the previous page. + - name: previous_link + type: URL + description: A target URL to which the user should be directed to get to the previous page. If none, the + link is not displayed. + - name: previous_title + type: TEXT + description: The text displayed on the button to go to the previous page. +row: + - name: active + type: BOOLEAN + description: Whether the link is active or not. Defaults to false. + - name: contents + type: INTEGER + required: true + description: Page number. + - name: link + type: URL + description: A target URL to which the user should be redirected to view the requested page of data. + - name: offset + type: BOOLEAN + description: 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 +--- + +Navigation links to go to the first, previous, next, or last page of a dataset. +Useful when data is divided into pages, each containing a fixed number of rows. + +This component only handles the display of pagination. +**Your sql queries are responsible for filtering data** based on the page number passed as a URL parameter. + +This component is typically used in conjunction with a [table](?component=table), +[list](?component=list), or [card](?component=card) component. + +The pagination component displays navigation buttons (first, previous, next, last) customizable with text or icons. + +For large numbers of pages, an offset can limit the visible page links. + +A minimal example of a SQL query that uses the pagination would be: +```sql +select 'table' as component; +select * from my_table limit 100 offset $offset; + +select 'pagination' as component; +with recursive pages as ( + select 0 as offset + union all + select offset + 100 from pages + where offset + 100 < (select count(*) from my_table) +) +select + (offset/100+1) as contents, + sqlpage.link(sqlpage.path(), json_object('offset', offset)) as link, + offset = coalesce(cast($offset as integer), 0) as active +from pages; +``` + +For more advanced usage, the [pagination guide](blog.sql?post=How+to+use+the+pagination+component) provides a complete tutorial. diff --git a/examples/official-site/content/components/pagination/examples/01-page-numbers.md b/examples/official-site/content/components/pagination/examples/01-page-numbers.md new file mode 100644 index 000000000..aed328b9a --- /dev/null +++ b/examples/official-site/content/components/pagination/examples/01-page-numbers.md @@ -0,0 +1,13 @@ +--- +rows: + - 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 +--- + +This is an extremely simple example of a pagination component that displays only the page numbers, with the first page being the current page. diff --git a/examples/official-site/content/components/pagination/examples/02-outline.md b/examples/official-site/content/components/pagination/examples/02-outline.md new file mode 100644 index 000000000..dd10f95f0 --- /dev/null +++ b/examples/official-site/content/components/pagination/examples/02-outline.md @@ -0,0 +1,14 @@ +--- +rows: + - 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 +--- + +The ouline style adds a rectangular border to each navigation link. diff --git a/examples/official-site/content/components/pagination/examples/03-circle.md b/examples/official-site/content/components/pagination/examples/03-circle.md new file mode 100644 index 000000000..832f214b0 --- /dev/null +++ b/examples/official-site/content/components/pagination/examples/03-circle.md @@ -0,0 +1,14 @@ +--- +rows: + - 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 +--- + +The circle style adds a circular border to each navigation link. diff --git a/examples/official-site/content/components/pagination/examples/04-disabled-links.md b/examples/official-site/content/components/pagination/examples/04-disabled-links.md new file mode 100644 index 000000000..1b2237f66 --- /dev/null +++ b/examples/official-site/content/components/pagination/examples/04-disabled-links.md @@ -0,0 +1,19 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/pagination/examples/05-text-links.md b/examples/official-site/content/components/pagination/examples/05-text-links.md new file mode 100644 index 000000000..fd77de6ae --- /dev/null +++ b/examples/official-site/content/components/pagination/examples/05-text-links.md @@ -0,0 +1,23 @@ +--- +rows: + - 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 +--- + +Instead of using icons, you can apply text to the navigation links. diff --git a/examples/official-site/content/components/pagination/examples/06-offset.md b/examples/official-site/content/components/pagination/examples/06-offset.md new file mode 100644 index 000000000..cbb6e3d82 --- /dev/null +++ b/examples/official-site/content/components/pagination/examples/06-offset.md @@ -0,0 +1,26 @@ +--- +rows: + - 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 +--- + +If you have a large number of pages to display, you can use an offset to represent a group of pages. diff --git a/examples/official-site/sqlpage/migrations/09_redirect.sql b/examples/official-site/content/components/redirect.md similarity index 55% rename from examples/official-site/sqlpage/migrations/09_redirect.sql rename to examples/official-site/content/components/redirect.md index eb6942125..4ab88c356 100644 --- a/examples/official-site/sqlpage/migrations/09_redirect.sql +++ b/examples/official-site/content/components/redirect.md @@ -1,7 +1,16 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'redirect', - 'Redirects the user to another page. +--- +icon: arrow-right +since: 0.7.2 +category: http-responses +summary: Send the visitor to another URL. +top: + - name: link + type: TEXT + required: true + description: The URL to redirect the user to. +--- + +Redirects the user to another page. This component helps you: 1. Send users to a different page @@ -16,8 +25,8 @@ A common use case is error handling. You may want to proceed with the rest of a ```sql SELECT - ''redirect'' AS component, - ''error_page.sql'' AS link + '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 @@ -30,40 +39,5 @@ it will fail if the HTTP headers have already been sent by the time it is execut > **Important difference from [http_header](?component=http_header)** > -> This component completely stops the page from running after it''s called. +> 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/content/components/redirect/examples/01-require-login.md b/examples/official-site/content/components/redirect/examples/01-require-login.md new file mode 100644 index 000000000..70a84f3ea --- /dev/null +++ b/examples/official-site/content/components/redirect/examples/01-require-login.md @@ -0,0 +1,6 @@ +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/content/components/rss.md b/examples/official-site/content/components/rss.md new file mode 100644 index 000000000..e4c00061d --- /dev/null +++ b/examples/official-site/content/components/rss.md @@ -0,0 +1,128 @@ +--- +icon: rss +since: 0.20.0 +category: http-responses +summary: Publish an RSS feed from query results. +top: + - name: author + type: TEXT + description: Defines the group, person, or people responsible for creating the channel. + - name: category + type: TEXT + description: Defines the category of the channel. The value should be a string representing the category + (e.g., "News", "Technology", etc.). + - name: complete + type: BOOLEAN + description: Specifies that a channel is complete and will not post any more items in the future. + - name: copyright + type: TEXT + description: Provides the copyright details for the channel. + - name: description + type: TEXT + required: true + description: Describes the channel. + - name: explicit + type: BOOLEAN + description: Indicates whether the channel contains explicit content. The value can be either TRUE or FALSE. + - name: funding_text + type: TEXT + description: The text to display with the donation/funding link. Ignored unless "funding_url" is also set. + - name: funding_url + type: URL + description: Specifies the donation/funding links for the channel. The content of the tag is the recommended + string to be used with the link. + - name: guid + type: TEXT + description: The globally unique identifier (GUID) for a channel. The value is a UUIDv5. + - name: image_url + type: URL + description: Provides a URL linking to the artwork for the channel. + - name: language + type: TEXT + description: Defines the language of the channel, specified in the ISO 639 format. For example, "en" for + English, "fr" for French. + - name: link + type: URL + required: true + description: Defines the hyperlink to the channel. + - name: locked + type: BOOLEAN + description: Tells podcast hosting platforms whether they are allowed to import this feed. + - name: self_link + type: URL + description: URL of the RSS feed. + - name: sub_category + type: TEXT + description: Defines a sub-category, nested inside the "category". Ignored unless "category" is also set. + - name: title + type: TEXT + required: true + description: Defines the title of the channel. + - name: type + type: TEXT + description: Specifies the channel as either episodic or serial. The value can be either "episodic" or + "serial". +row: + - name: block + type: BOOLEAN + description: Prevents a specific item from appearing in podcast listening applications. + - name: date + type: TEXT + description: Indicates when the item was published (RFC-822 date-time). + - name: description + type: TEXT + required: true + description: Describes the item + - name: duration + type: INTEGER + description: The duration of an item in seconds. + - name: enclosure_length + type: INTEGER + description: The length in bytes of the audio/video episode content. + - name: enclosure_type + type: TEXT + description: The MIME media type of the audio/video episode content (e.g., "audio/mpeg", "audio/m4a", "video/m4v", + "video/mp4"). + - name: enclosure_url + type: URL + description: For podcast episodes, provides a URL linking to the audio/video episode content, in mp3, m4a, + m4v, or mp4 format. + - name: episode + type: INTEGER + description: The chronological number that is associated with an item. + - name: episode_type + type: TEXT + description: Defines the type of content for a specific item. The value can be either "full", "trailer", + or "bonus". + - name: explicit + type: BOOLEAN + description: Indicates whether the item contains explicit content. The value can be either TRUE or FALSE. + - name: guid + type: TEXT + description: The globally unique identifier (GUID) for an item. + - name: image_url + type: URL + description: Provides a URL linking to the artwork for the item. + - name: link + type: URL + required: true + description: Defines the hyperlink to the item (blog post URL, etc.). + - name: season + type: INTEGER + description: The chronological number associated with an item's season. + - name: title + type: TEXT + required: true + description: Defines the title of the feed item (episode name, blog post title, etc.). + - name: transcript_type + type: TEXT + description: 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"). + - name: transcript_url + type: URL + description: A link to a transcript or closed captions file for the item. +--- + +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. diff --git a/examples/official-site/content/components/rss/examples/01-news-channel.md b/examples/official-site/content/components/rss/examples/01-news-channel.md new file mode 100644 index 000000000..0e0c8d291 --- /dev/null +++ b/examples/official-site/content/components/rss/examples/01-news-channel.md @@ -0,0 +1,31 @@ +### 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/)... diff --git a/examples/official-site/content/components/shell.md b/examples/official-site/content/components/shell.md new file mode 100644 index 000000000..7cd788c3f --- /dev/null +++ b/examples/official-site/content/components/shell.md @@ -0,0 +1,146 @@ +--- +icon: layout-navbar +category: page-layout +summary: Set the page layout, navigation, branding, and footer. +top: + - name: class + type: TEXT + description: class attribute added to the page's html element. It can be used to apply custom styling to + the whole page through css. + - name: css + type: URL + description: The URL of a CSS file to load and apply to the page. + - name: description + type: TEXT + description: A description of the page. It can be displayed by search engines when your page appears in + their results. + - name: favicon + type: URL + description: 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). + - name: fixed_top_menu + type: BOOLEAN + description: Fixes the top bar with menu at the top (the top bar remains visible when scrolling long pages). + - name: font + type: TEXT + description: 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"). + - name: font_size + type: INTEGER + description: Font size on the page, in pixels. Set to 18 by default. + - name: footer + type: TEXT + description: 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. + - name: icon + type: ICON + description: Name of an icon (from tabler-icons.io) to display next to the title in the navigation bar. + - name: image + type: URL + description: The URL of an image to display next to the page title. + - name: javascript + type: URL + description: The URL of a Javascript file to load and execute on the page. + - name: javascript_module + type: URL + description: The URL of a javascript module in the ESM format (see javascript.info/modules) + - name: language + type: TEXT + description: The language of the page. This can be used by search engines and screen readers to determine + in which language the page is written. + - name: layout + type: TEXT + description: The general page layout. Can be "boxed" (the default), "horizontal" (for a full-width menu), + "vertical"(vertical menu), "fluid" (removes side margins). + - name: link + type: URL + description: The target of the link in the top navigation bar. + - name: manifest + type: URL + description: 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. + - name: menu_item + type: TEXT + description: 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. + - name: navbar_title + type: TEXT + description: The title shown in the navigation bar or sidebar. Defaults to the page title. Set an empty + string to show just the logo. + - name: norobot + type: BOOLEAN + description: 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. + - name: preview_image + type: URL + description: The URL of an image to display as a link preview when the page is shared on social media + - name: refresh + type: INTEGER + description: Number of seconds after which the page should refresh. This can be useful to display dynamic + content that updates automatically. + - name: rss + type: URL + description: The URL of an RSS feed to display in the top navigation bar. You can use the rss component + to generate the field. + - name: rtl + type: BOOLEAN + description: Whether the page should be displayed in right-to-left mode. Used to display Arabic, Hebrew, + Persian, etc. + - name: search_button + type: TEXT + description: 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. + - name: search_placeholder + type: TEXT + description: 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. + - name: search_target + type: TEXT + description: 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. + - name: search_value + type: TEXT + description: 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. + - name: sidebar + type: BOOLEAN + description: 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. + - name: sidebar_theme + type: TEXT + description: Used with sidebar property, It can be set to "dark" to exclusively set the sidebar into dark + theme. + - name: social_image + type: URL + description: The URL of the preview image that will appear in the Open Graph metadata when the page is + shared on social media. + - name: target + type: TEXT + description: '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.' + - name: theme + type: TEXT + description: Set to "dark" to use a dark theme. + - name: title + type: TEXT + description: 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. +--- + +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. diff --git a/examples/official-site/content/components/shell/examples/01-dark-navigation.md b/examples/official-site/content/components/shell/examples/01-dark-navigation.md new file mode 100644 index 000000000..70e3c0476 --- /dev/null +++ b/examples/official-site/content/components/shell/examples/01-dark-navigation.md @@ -0,0 +1,99 @@ +--- +rows: + - 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: https://github.com/sqlpage/SQLPage/blob/main/configuration.md + 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)' +--- + +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. diff --git a/examples/official-site/content/components/shell/examples/02-active-menu.md b/examples/official-site/content/components/shell/examples/02-active-menu.md new file mode 100644 index 000000000..9da9f86b7 --- /dev/null +++ b/examples/official-site/content/components/shell/examples/02-active-menu.md @@ -0,0 +1,15 @@ +--- +rows: + - component: shell + title: 'SQLPage: SQL websites' + icon: database + link: / + menu_item: + - title: Home + active: true + - title: About +--- + +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. diff --git a/examples/official-site/content/components/shell/examples/03-shared-shell.md b/examples/official-site/content/components/shell/examples/03-shared-shell.md new file mode 100644 index 000000000..a7a3b1358 --- /dev/null +++ b/examples/official-site/content/components/shell/examples/03-shared-shell.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=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; +``` diff --git a/examples/official-site/content/components/shell/examples/04-custom-response.md b/examples/official-site/content/components/shell/examples/04-custom-response.md new file mode 100644 index 000000000..2027c4c16 --- /dev/null +++ b/examples/official-site/content/components/shell/examples/04-custom-response.md @@ -0,0 +1,27 @@ +--- +rows: + - component: http_header + Content-Type: application/xml + - component: shell-empty + contents: |- + + + 42 + john.doe + +--- + +### 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`). diff --git a/examples/official-site/content/components/shell/examples/05-custom-html.md b/examples/official-site/content/components/shell/examples/05-custom-html.md new file mode 100644 index 000000000..0ade399d2 --- /dev/null +++ b/examples/official-site/content/components/shell/examples/05-custom-html.md @@ -0,0 +1,24 @@ +--- +rows: + - component: shell-empty + html: |- + + + + My page + + +

My page

+ + +--- + +### 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. diff --git a/examples/official-site/content/components/status_bar.md b/examples/official-site/content/components/status_bar.md new file mode 100644 index 000000000..e51cbf03a --- /dev/null +++ b/examples/official-site/content/components/status_bar.md @@ -0,0 +1,37 @@ +--- +icon: layout-bottombar +since: 0.49.0 +category: navigation +summary: Show status messages and links in a horizontal bar. +top: + - class + - name: fixed + type: BOOLEAN + description: 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. + - id + - name: label + type: TEXT + description: Accessible name for the bar. Defaults to "Status bar". +row: + - class + - name: color + type: COLOR + description: Color of the segment text and icon. + - name: icon + type: ICON + description: Icon displayed before the text. + - name: link + type: URL + description: URL to open when the segment is clicked. + - name: title + type: TEXT + description: Text displayed in the segment. + - name: tooltip + type: TEXT + description: 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. +--- + +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. diff --git a/examples/official-site/content/components/status_bar/examples/01-query-workspace.md b/examples/official-site/content/components/status_bar/examples/01-query-workspace.md new file mode 100644 index 000000000..c414aa8e7 --- /dev/null +++ b/examples/official-site/content/components/status_bar/examples/01-query-workspace.md @@ -0,0 +1,16 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/status_code.md b/examples/official-site/content/components/status_code.md new file mode 100644 index 000000000..4baaea56b --- /dev/null +++ b/examples/official-site/content/components/status_code.md @@ -0,0 +1,36 @@ +--- +icon: error-404 +category: http-responses +summary: Set the HTTP status code returned by a page. +top: + - name: status + type: INTEGER + required: true + description: HTTP status code (e.g., 200 OK, 401 Unauthorized, 409 Conflict) +--- + +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 diff --git a/examples/official-site/content/components/status_code/examples/01-not-found.md b/examples/official-site/content/components/status_code/examples/01-not-found.md new file mode 100644 index 000000000..81fae347e --- /dev/null +++ b/examples/official-site/content/components/status_code/examples/01-not-found.md @@ -0,0 +1,6 @@ +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/content/components/steps.md b/examples/official-site/content/components/steps.md new file mode 100644 index 000000000..3a62986ad --- /dev/null +++ b/examples/official-site/content/components/steps.md @@ -0,0 +1,40 @@ +--- +icon: dots-circle-horizontal +category: navigation +summary: Mark progress through the stages of a task. +top: + - name: color + type: COLOR + description: Color of the bars displayed between steps. + - name: counter + type: TEXT + description: Display the number of the step on top of its name. + - name: description + type: TEXT + description: Description of the section. + - name: id + type: TEXT + description: 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. + - name: title + type: TEXT + description: Title of the section. +row: + - name: active + type: BOOLEAN + description: Whether this item in the grid is considered "active". Active items are displayed more prominently. + - name: description + type: TEXT + description: Tooltip to display when the user passes their mouse over the step's name. + - name: icon + type: ICON + description: An icon name (from tabler-icons.io) to display on the left side of the step name. + - name: link + type: URL + description: A target URL to which the user should be taken when they click on the step. + - name: title + type: TEXT + description: Name of the step. +--- + +Guide users through multi-stage processes, displaying a clear list of previous and future steps. diff --git a/examples/official-site/content/components/steps/examples/01-checkout.md b/examples/official-site/content/components/steps/examples/01-checkout.md new file mode 100644 index 000000000..454d71979 --- /dev/null +++ b/examples/official-site/content/components/steps/examples/01-checkout.md @@ -0,0 +1,11 @@ +--- +rows: + - component: steps + - title: Shopping + - title: Store pickup + - title: Payment + active: true + - title: Review & Order +--- + +Online store checkout steps. diff --git a/examples/official-site/content/components/steps/examples/02-progress-indicator.md b/examples/official-site/content/components/steps/examples/02-progress-indicator.md new file mode 100644 index 000000000..e448c2a2c --- /dev/null +++ b/examples/official-site/content/components/steps/examples/02-progress-indicator.md @@ -0,0 +1,27 @@ +--- +rows: + - 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 +--- + +A progress indicator with custom color, auto-generated step numbers, icons, and description tooltips. diff --git a/examples/official-site/content/components/tab.md b/examples/official-site/content/components/tab.md new file mode 100644 index 000000000..a08986583 --- /dev/null +++ b/examples/official-site/content/components/tab.md @@ -0,0 +1,43 @@ +--- +icon: row-insert-bottom +since: 0.9.5 +category: navigation +summary: Switch between related pages using labeled tabs. +top: + - name: center + type: BOOLEAN + description: Whether the tabs should be centered or not. Defaults to false. + - class + - id +row: + - name: active + type: BOOLEAN + description: Whether the tab is active or not. Defaults to false. + - name: center + type: BOOLEAN + description: Whether this individual tab's label should be centered inside the tab. Defaults to false. + - class + - name: color + type: TEXT + description: 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. + - name: description + type: TEXT + description: Description of the tab. This is displayed when the user hovers over the tab. + - name: icon + type: TEXT + description: Name of the icon to display on the tab. See tabler-icons.io for a list of available icons. + - id + - name: link + type: TEXT + description: 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. + - name: title + type: TEXT + required: true + description: 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. +--- + +Build a tabbed interface, with each tab being a link to a page. Each tab can be in two states: active or inactive. diff --git a/examples/official-site/content/components/tab/examples/01-basic.md b/examples/official-site/content/components/tab/examples/01-basic.md new file mode 100644 index 000000000..9e9a48615 --- /dev/null +++ b/examples/official-site/content/components/tab/examples/01-basic.md @@ -0,0 +1,34 @@ +--- +rows: + - 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 +--- + +This example shows a very basic set of three tabs. The first tab is active. You could use this at the top of a page for easy navigation. + +To implement contents that change based on the active tab, use the `tab` parameter in the page query string. +For example, if the page is `/my-page.sql`, then the first tab will have a link of `/my-page.sql?tab=My+First+tab`. + +You could then for instance display contents coming from the database based on the value of the `tab` parameter. +For instance: `SELECT 'text' AS component, contents_md FROM my_page_contents WHERE tab = $tab`. +Or you could write different queries for different tabs and use the `$tab` parameter with a static value in a where clause to switch between tabs: + +```sql +select 'tab' as component; +select 'Projects' as title, $tab = 'Projects' as active; +select 'Tasks' as title, $tab = 'Tasks' as active; + +select 'table' as component; + +select * from my_projects where $tab = 'Projects'; +select * from my_tasks where $tab = 'Tasks'; +``` + +Note that the example below is completely static, and does not use the `tab` parameter to actually switch between tabs. +View the [dynamic tabs example](/examples/tabs/). diff --git a/examples/official-site/content/components/tab/examples/02-centered-icons.md b/examples/official-site/content/components/tab/examples/02-centered-icons.md new file mode 100644 index 000000000..6e3c3b83b --- /dev/null +++ b/examples/official-site/content/components/tab/examples/02-centered-icons.md @@ -0,0 +1,18 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/table.md b/examples/official-site/content/components/table.md new file mode 100644 index 000000000..633f0a744 --- /dev/null +++ b/examples/official-site/content/components/table.md @@ -0,0 +1,149 @@ +--- +icon: table +category: display-data +summary: Turn query results into a sortable, searchable table. +top: + - name: align_center + type: TEXT + description: 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. + - name: align_right + type: TEXT + description: 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. + - name: border + type: BOOLEAN + description: Whether to draw borders on all sides of the table and cells. + - class + - name: currency + type: TEXT + description: The ISO 4217 currency code (e.g., USD, EUR, GBP, etc.) to use when formatting monetary values. + - name: custom_actions + type: JSON + description: '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' + - name: delete_url + type: TEXT + description: 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 + - name: description + type: TEXT + description: Description of the table contents. Helps users with screen readers to find a table and understand + what it’s about. + - name: edit_url + type: TEXT + description: 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 + - name: empty_description + type: TEXT + description: Text to display if the table does not contain any row. Defaults to "no data". + - name: freeze_columns + type: BOOLEAN + description: Whether to freeze the leftmost column of the table. + - name: freeze_footers + type: BOOLEAN + description: Whether to freeze the footer (bottom row) of the table, only works if that row has the `_sqlpage_footer` + property applied to it. + - name: freeze_headers + type: BOOLEAN + description: Whether to freeze the top row of the table. + - name: hover + type: BOOLEAN + description: Whether to enable a hover state on table rows. + - name: icon + type: TEXT + description: 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. + - id + - name: initial_search_value + type: TEXT + description: 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. + - name: markdown + type: TEXT + description: 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. + - name: money + type: TEXT + description: 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. + - name: monospace + type: TEXT + description: 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. + - name: number_format_digits + type: INTEGER + description: Maximum number of decimal digits to display for numeric values. + - name: number_format_locale + type: TEXT + description: 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. + - name: overflow + type: BOOLEAN + description: Whether to to let "wide" tables overflow across the right border and enable browser-based + horizontal scrolling. + - name: raw_numbers + type: TEXT + description: 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. + - name: search + type: BOOLEAN + description: Add a search bar at the top of the table, letting users easily filter table rows by value. + - name: search_placeholder + type: TEXT + description: Customizes the placeholder text shown in the search input field. Replaces the default "Search..." + with text that better describes what users should search for. + - name: small + type: BOOLEAN + description: Whether to use compact table. + - name: sort + type: BOOLEAN + description: Make the columns clickable to let the user sort by the value contained in the column. + - name: striped_columns + type: BOOLEAN + description: Whether to add zebra-striping to any table column. + - name: striped_rows + type: BOOLEAN + description: Whether to add zebra-striping to any table row. + - name: title + type: TEXT + description: A title displayed above the table. +row: + - name: _sqlpage_actions + type: JSON + description: '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' + - name: _sqlpage_color + type: COLOR + description: Sets the background color of the row. Added in v0.8.0. + - name: _sqlpage_css_class + type: TEXT + description: For advanced users. Sets a css class on the table row. Added in v0.8.0. + - name: _sqlpage_footer + type: BOOLEAN + description: Sets this row as the table footer. It is recommended that this parameter is applied to the + last row. Added in v0.34.0. + - name: _sqlpage_id + type: TEXT + description: Sets the id of the html tabler row element. Allows you to make links targeting a specific + row in a 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. diff --git a/examples/official-site/content/components/table/examples/01-basic.md b/examples/official-site/content/components/table/examples/01-basic.md new file mode 100644 index 000000000..f510ed56f --- /dev/null +++ b/examples/official-site/content/components/table/examples/01-basic.md @@ -0,0 +1,10 @@ +--- +rows: + - component: table + - a: 1 + b: 2 + - a: 3 + b: 4 +--- + +The most basic table. diff --git a/examples/official-site/content/components/table/examples/02-filtering-and-sorting.md b/examples/official-site/content/components/table/examples/02-filtering-and-sorting.md new file mode 100644 index 000000000..55ddc3b74 --- /dev/null +++ b/examples/official-site/content/components/table/examples/02-filtering-and-sorting.md @@ -0,0 +1,15 @@ +--- +rows: + - 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 +--- + +A table of users with filtering and sorting. diff --git a/examples/official-site/content/components/table/examples/03-markdown-links.md b/examples/official-site/content/components/table/examples/03-markdown-links.md new file mode 100644 index 000000000..440668108 --- /dev/null +++ b/examples/official-site/content/components/table/examples/03-markdown-links.md @@ -0,0 +1,16 @@ +--- +rows: + - 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. +--- + +A table that uses markdown to display links diff --git a/examples/official-site/content/components/table/examples/04-totals-footer.md b/examples/official-site/content/components/table/examples/04-totals-footer.md new file mode 100644 index 000000000..21c8f7fc9 --- /dev/null +++ b/examples/official-site/content/components/table/examples/04-totals-footer.md @@ -0,0 +1,17 @@ +--- +rows: + - 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 +--- + +A sortable table with a colored footer showing the average value of its entries. diff --git a/examples/official-site/content/components/table/examples/05-sorting.md b/examples/official-site/content/components/table/examples/05-sorting.md new file mode 100644 index 000000000..655db0105 --- /dev/null +++ b/examples/official-site/content/components/table/examples/05-sorting.md @@ -0,0 +1,34 @@ +--- +rows: + - 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 +--- + +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. diff --git a/examples/official-site/content/components/table/examples/06-presentation.md b/examples/official-site/content/components/table/examples/06-presentation.md new file mode 100644 index 000000000..1b9aa5687 --- /dev/null +++ b/examples/official-site/content/components/table/examples/06-presentation.md @@ -0,0 +1,29 @@ +--- +rows: + - 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 +--- + +A table with some presentation options diff --git a/examples/official-site/content/components/table/examples/07-empty.md b/examples/official-site/content/components/table/examples/07-empty.md new file mode 100644 index 000000000..03e34cdb0 --- /dev/null +++ b/examples/official-site/content/components/table/examples/07-empty.md @@ -0,0 +1,7 @@ +--- +rows: + - component: table + empty_description: Nothing to see here at the moment. +--- + +An empty table with a friendly message diff --git a/examples/official-site/content/components/table/examples/08-frozen-columns.md b/examples/official-site/content/components/table/examples/08-frozen-columns.md new file mode 100644 index 000000000..1f38590bb --- /dev/null +++ b/examples/official-site/content/components/table/examples/08-frozen-columns.md @@ -0,0 +1,47 @@ +--- +rows: + - 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. +--- + +A large table with many rows and columns, with frozen columns on the left and headers on top. This allows users to browse large datasets without loosing track of their position. diff --git a/examples/official-site/content/components/table/examples/09-dynamic-columns.md b/examples/official-site/content/components/table/examples/09-dynamic-columns.md new file mode 100644 index 000000000..5e686f67a --- /dev/null +++ b/examples/official-site/content/components/table/examples/09-dynamic-columns.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/content/components/table/examples/10-action-buttons.md b/examples/official-site/content/components/table/examples/10-action-buttons.md new file mode 100644 index 000000000..e876665d5 --- /dev/null +++ b/examples/official-site/content/components/table/examples/10-action-buttons.md @@ -0,0 +1,88 @@ +--- +rows: + - 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 +--- + +## 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 diff --git a/examples/official-site/content/components/text.md b/examples/official-site/content/components/text.md new file mode 100644 index 000000000..07a002713 --- /dev/null +++ b/examples/official-site/content/components/text.md @@ -0,0 +1,72 @@ +--- +icon: align-left +category: page-layout +summary: Write paragraphs using plain text or Markdown. +top: + - name: article + type: BOOLEAN + description: Makes long texts more readable by increasing the line height, adding margins, using a serif + font, and decorating the initial letter. + - name: center + type: BOOLEAN + description: Whether to center the title. + - name: contents + type: TEXT + description: A top-level paragraph of text to display, without any formatting, without having to make additional + queries. + - name: contents_md + type: TEXT + description: 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)`. + - name: html + type: TEXT + description: 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. + - id + - name: title + type: TEXT + description: Text header before the paragraph. + - name: unsafe_contents_md + type: TEXT + description: Markdown format with html blocks. Use this only with trusted content. See the html-blocks + section of the Commonmark spec for additional info. +row: + - name: bold + type: BOOLEAN + description: Whether the span of text should be displayed as bold. + - name: break + type: BOOLEAN + description: Indicates that the current span of text starts a new paragraph. + - name: code + type: BOOLEAN + description: Use a monospace font. Useful to display the text as code. + - name: color + type: COLOR + description: The name of a color for this span of text. + - name: contents + type: TEXT + required: true + description: A span of text to display + - name: contents_md + type: TEXT + description: 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)`. + - name: italics + type: BOOLEAN + description: Whether the span of text should be displayed as italics. + - name: link + type: URL + description: An URL to which the user should be taken when they click on this span of text. + - name: size + type: INTEGER + description: A number between 1 and 6 indicating the font size. + - name: underline + type: BOOLEAN + description: Whether the span of text should be underlined. + - name: unsafe_contents_md + type: TEXT + description: Markdown format with html blocks. Use this only with trusted content. See the html-blocks + section of the Commonmark spec for additional info. +--- + +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. diff --git a/examples/official-site/content/components/text/examples/01-paragraph.md b/examples/official-site/content/components/text/examples/01-paragraph.md new file mode 100644 index 000000000..8c26f7bf7 --- /dev/null +++ b/examples/official-site/content/components/text/examples/01-paragraph.md @@ -0,0 +1,7 @@ +--- +rows: + - component: text + contents: Hello, world ! <3 +--- + +Rendering a simple text paragraph. diff --git a/examples/official-site/content/components/text/examples/02-markdown.md b/examples/official-site/content/components/text/examples/02-markdown.md new file mode 100644 index 000000000..e9c3cb708 --- /dev/null +++ b/examples/official-site/content/components/text/examples/02-markdown.md @@ -0,0 +1,52 @@ +--- +rows: + - component: text + article: true + contents_md: |+ + + # Markdown in SQLPage + + ## Simple formatting + + 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). + + ## 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](https://sql-page.com/documentation.sql?component=text) | + | list | A list of items. | [Documentation](https://sql-page.com/documentation.sql?component=list) | + | steps | A progress indicator. | [Documentation](https://sql-page.com/documentation.sql?component=steps) | + | form | A series of input fields. | [Documentation](https://sql-page.com/documentation.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 + --- + +--- + +Rendering rich text using markdown diff --git a/examples/official-site/content/components/text/examples/03-rich-text.md b/examples/official-site/content/components/text/examples/03-rich-text.md new file mode 100644 index 000000000..30fb497fe --- /dev/null +++ b/examples/official-site/content/components/text/examples/03-rich-text.md @@ -0,0 +1,14 @@ +--- +rows: + - 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. +--- + +Rendering a paragraph with links and styling. diff --git a/examples/official-site/content/components/text/examples/04-section-link.md b/examples/official-site/content/components/text/examples/04-section-link.md new file mode 100644 index 000000000..968029b74 --- /dev/null +++ b/examples/official-site/content/components/text/examples/04-section-link.md @@ -0,0 +1,11 @@ +--- +rows: + - 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. +--- + +An intra-page link to a section of the page. diff --git a/examples/official-site/content/components/timeline.md b/examples/official-site/content/components/timeline.md new file mode 100644 index 000000000..fb727e9ec --- /dev/null +++ b/examples/official-site/content/components/timeline.md @@ -0,0 +1,41 @@ +--- +icon: git-commit +since: 0.13.0 +category: display-data +summary: Arrange events along a vertical timeline. +top: + - class + - id + - name: simple + type: BOOLEAN + description: If set to true, the timeline will be displayed in a condensed format without icons. +row: + - class + - name: color + type: TEXT + description: Color of the icon. See preview.tabler.io/colors.html for a list of available colors. + - name: date + type: TEXT + required: true + description: Date of the event. + - name: description + type: TEXT + description: Textual description of the event. + - name: description_md + type: TEXT + description: Description of the event in Markdown. + - name: icon + type: TEXT + description: Name of the icon to display next to the event. See tabler-icons.io for a list of available + icons. + - id + - name: link + type: TEXT + description: Link to a page with more information about the event. + - name: title + type: TEXT + required: true + description: Name of the event. +--- + +A list of events with a vertical line connecting them. diff --git a/examples/official-site/content/components/timeline/examples/01-basic.md b/examples/official-site/content/components/timeline/examples/01-basic.md new file mode 100644 index 000000000..91d2c899a --- /dev/null +++ b/examples/official-site/content/components/timeline/examples/01-basic.md @@ -0,0 +1,11 @@ +--- +rows: + - 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 +--- + +A basic timeline with just names and dates. diff --git a/examples/official-site/content/components/timeline/examples/02-rich-items.md b/examples/official-site/content/components/timeline/examples/02-rich-items.md new file mode 100644 index 000000000..0548505af --- /dev/null +++ b/examples/official-site/content/components/timeline/examples/02-rich-items.md @@ -0,0 +1,18 @@ +--- +rows: + - 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 +--- + +A full-fledged timeline with icons, colors, and rich text descriptions. diff --git a/examples/official-site/content/components/title.md b/examples/official-site/content/components/title.md new file mode 100644 index 000000000..9c8dad5bc --- /dev/null +++ b/examples/official-site/content/components/title.md @@ -0,0 +1,21 @@ +--- +icon: letter-case-upper +since: 0.19.0 +category: page-layout +summary: Add a heading and choose its level. +top: + - name: center + type: BOOLEAN + description: Whether to center the title. + - class + - name: contents + type: TEXT + required: true + description: A text to display. + - id + - name: level + type: INTEGER + description: Set the heading level (default level is 1) +--- + +Defines HTML headings. The level 1 is used for the maximal size and the level 6 is used for the minimal size. diff --git a/examples/official-site/content/components/title/examples/01-levels.md b/examples/official-site/content/components/title/examples/01-levels.md new file mode 100644 index 000000000..8161c6827 --- /dev/null +++ b/examples/official-site/content/components/title/examples/01-levels.md @@ -0,0 +1,13 @@ +--- +rows: + - component: title + contents: Level 1 + - component: title + contents: Level 2 + level: 2 + - component: title + contents: Level 3 + level: 3 +--- + +Displays several titles with different levels. diff --git a/examples/official-site/content/components/title/examples/02-centered.md b/examples/official-site/content/components/title/examples/02-centered.md new file mode 100644 index 000000000..77497f3d6 --- /dev/null +++ b/examples/official-site/content/components/title/examples/02-centered.md @@ -0,0 +1,8 @@ +--- +rows: + - component: title + contents: Level 1 + center: true +--- + +Displays a centered title. diff --git a/examples/official-site/content/components/toast.md b/examples/official-site/content/components/toast.md new file mode 100644 index 000000000..cd190a9a7 --- /dev/null +++ b/examples/official-site/content/components/toast.md @@ -0,0 +1,47 @@ +--- +icon: notification +since: 0.46.0 +category: forms-and-feedback +summary: Show a brief notification above the page. +top: + - class + - name: color + type: COLOR + description: Optional Tabler color. The default is the neutral toast appearance; colored variants use the + matching contrasting foreground utility. + - name: description + type: TEXT + description: Escaped plain-text body. This is used only when `description_md` is not supplied. + - name: description_md + type: TEXT + description: Rich-text alternative to `description`, rendered as Markdown. When both properties are supplied, + `description_md` takes precedence. + - name: dismissible + type: BOOLEAN + description: Whether to render an accessible manual close button. Defaults to true and is independent of + automatic dismissal. + - name: duration + type: INTEGER + description: 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. + - name: icon + type: ICON + description: Optional [Tabler icon](https://tabler.io/icons) name. + - id + - name: position + type: TEXT + description: '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.' + - name: title + type: TEXT + description: Optional notification heading. + - name: trigger + type: TEXT + description: 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. +--- + +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. diff --git a/examples/official-site/content/components/toast/examples/01-automatic.md b/examples/official-site/content/components/toast/examples/01-automatic.md new file mode 100644 index 000000000..2f8d5a163 --- /dev/null +++ b/examples/official-site/content/components/toast/examples/01-automatic.md @@ -0,0 +1,11 @@ +--- +rows: + - 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 +--- + +A toast that opens when the page loads and disappears automatically after the default 5000 milliseconds. diff --git a/examples/official-site/content/components/toast/examples/02-manual-dismissal.md b/examples/official-site/content/components/toast/examples/02-manual-dismissal.md new file mode 100644 index 000000000..d9ae49a2b --- /dev/null +++ b/examples/official-site/content/components/toast/examples/02-manual-dismissal.md @@ -0,0 +1,27 @@ +--- +rows: + - 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' +--- + +A persistent error notification that disables automatic dismissal and requires the user to activate its close button. diff --git a/examples/official-site/content/components/toast/examples/03-markdown.md b/examples/official-site/content/components/toast/examples/03-markdown.md new file mode 100644 index 000000000..a1853a575 --- /dev/null +++ b/examples/official-site/content/components/toast/examples/03-markdown.md @@ -0,0 +1,22 @@ +--- +rows: + - 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' +--- + +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. diff --git a/examples/official-site/content/components/toast/examples/04-queue.md b/examples/official-site/content/components/toast/examples/04-queue.md new file mode 100644 index 000000000..fb766ce5c --- /dev/null +++ b/examples/official-site/content/components/toast/examples/04-queue.md @@ -0,0 +1,26 @@ +--- +rows: + - 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' +--- + +Several persistent queued notifications. Toasts with the same position share a container and stack instead of overlapping. diff --git a/examples/official-site/content/components/toast/examples/05-placement.md b/examples/official-site/content/components/toast/examples/05-placement.md new file mode 100644 index 000000000..9452db113 --- /dev/null +++ b/examples/official-site/content/components/toast/examples/05-placement.md @@ -0,0 +1,15 @@ +--- +rows: + - 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' +--- + +A notification placed at the bottom center of the screen instead of the default top end. diff --git a/examples/official-site/content/components/tracking.md b/examples/official-site/content/components/tracking.md new file mode 100644 index 000000000..ae6bfe0be --- /dev/null +++ b/examples/official-site/content/components/tracking.md @@ -0,0 +1,44 @@ +--- +icon: timeline-event-text +since: 0.18.0 +category: display-data +summary: Show a sequence of activity or status changes as colored segments. +top: + - name: center + type: BOOLEAN + description: Whether to center the component. + - class + - name: description + type: TEXT + description: A short paragraph. + - name: description_md + type: TEXT + description: A short paragraph formatted using markdown. + - id + - name: information + type: TEXT + description: A short text displayed below the title. + - name: placement + type: TEXT + description: Position of the tooltip (e.g. top, bottom, right, left) + - name: title + type: TEXT + required: true + description: Title of the tracking component. + - name: width + type: INTEGER + description: Width of the component, between 1 and 12. +row: + - name: color + type: TEXT + description: Color of the tracked item (e.g. success, warning, danger) + - name: link + type: URL + description: A URL to open when the user clicks on the tracked item. + - name: title + type: TEXT + required: true + description: Description of the state. +--- + +Component for visualising activity logs or other monitoring-related data. diff --git a/examples/official-site/content/components/tracking/examples/01-server-status.md b/examples/official-site/content/components/tracking/examples/01-server-status.md new file mode 100644 index 000000000..7edc7ddf4 --- /dev/null +++ b/examples/official-site/content/components/tracking/examples/01-server-status.md @@ -0,0 +1,15 @@ +--- +rows: + - 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 +--- + +A basic example of servers tracking component diff --git a/examples/official-site/content/components/tracking/examples/02-server-status-history.md b/examples/official-site/content/components/tracking/examples/02-server-status-history.md new file mode 100644 index 000000000..808f7c8b9 --- /dev/null +++ b/examples/official-site/content/components/tracking/examples/02-server-status-history.md @@ -0,0 +1,26 @@ +--- +rows: + - 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 +--- + +An example of servers tracking component diff --git a/examples/official-site/content/functions/basic_auth_password.md b/examples/official-site/content/functions/basic_auth_password.md new file mode 100644 index 000000000..67162811a --- /dev/null +++ b/examples/official-site/content/functions/basic_auth_password.md @@ -0,0 +1,18 @@ +--- +icon: key +since: 0.7.2 +category: identity-and-security +summary: Read the password sent with HTTP Basic authentication. +return_type: TEXT +--- + +Returns the password from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. + If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials. + +### Example + +```sql +SELECT 'authentication' AS component, + (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, + sqlpage.basic_auth_password() AS password; +``` diff --git a/examples/official-site/content/functions/basic_auth_username.md b/examples/official-site/content/functions/basic_auth_username.md new file mode 100644 index 000000000..d6252e841 --- /dev/null +++ b/examples/official-site/content/functions/basic_auth_username.md @@ -0,0 +1,18 @@ +--- +icon: user +since: 0.7.2 +category: identity-and-security +summary: Read the username sent with HTTP Basic authentication. +return_type: TEXT +--- + +Returns the username from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. + If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials. + +### Example + +```sql +SELECT 'authentication' AS component, + (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, + sqlpage.basic_auth_password() AS password; +``` diff --git a/examples/official-site/sqlpage/migrations/57_client_ip.sql b/examples/official-site/content/functions/client_ip.md similarity index 63% rename from examples/official-site/sqlpage/migrations/57_client_ip.sql rename to examples/official-site/content/functions/client_ip.md index 168451f40..ef5afe844 100644 --- a/examples/official-site/sqlpage/migrations/57_client_ip.sql +++ b/examples/official-site/content/functions/client_ip.md @@ -1,16 +1,11 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'client_ip', - '0.33.0', - 'network', - 'Returns the IP address of the client making the HTTP request. +--- +icon: network +since: 0.33.0 +category: request-data +summary: Get the IP address of the client making the request. +--- + +Returns the IP address of the client making the HTTP request. ### Example @@ -28,19 +23,17 @@ The function returns: When [running behind a reverse proxy](/your-first-sql-website/nginx.sql) (e.g., Nginx, Apache, Cloudflare): - This function will return the IP address of the reverse proxy, not the actual client -- To get the real client IP, use [`sqlpage.header`](?function=header): `sqlpage.header(''x-forwarded-for'')` or `sqlpage.header(''x-real-ip'')` +- To get the real client IP, use [`sqlpage.header`](?function=header): `sqlpage.header('x-forwarded-for')` or `sqlpage.header('x-real-ip')` - The exact header name depends on your reverse proxy configuration Example with reverse proxy: ```sql -- Choose the appropriate header based on your setup select coalesce( - sqlpage.header(''x-forwarded-for''), - sqlpage.header(''x-real-ip''), + sqlpage.header('x-forwarded-for'), + sqlpage.header('x-real-ip'), sqlpage.client_ip() ) as real_client_ip; ``` For security-critical applications, ensure your reverse proxy is properly configured to set and validate these headers. -' - ); \ No newline at end of file diff --git a/examples/official-site/content/functions/configuration_directory.md b/examples/official-site/content/functions/configuration_directory.md new file mode 100644 index 000000000..ee7c260e4 --- /dev/null +++ b/examples/official-site/content/functions/configuration_directory.md @@ -0,0 +1,33 @@ +--- +icon: folder-cog +since: 0.42.0 +category: server-and-runtime +summary: Locate the directory for SQLPage configuration and templates. +--- + +Returns the configuration directory where SQLPage looks for `sqlpage.json`, templates, and migrations. + +### Example + +```sql +SELECT 'text' AS component; +SELECT 'Configuration files are in ' AS contents; +SELECT sqlpage.configuration_directory() as contents, true as code; +``` + +#### Result + +Configuration files are in `/home/user/my_sqlpage_website/sqlpage` + +#### Notes + +The configuration directory is where SQLPage looks for: + - `sqlpage.json` (the configuration file) + - `templates/` (custom component templates) + - `migrations/` (database migration files) + +By default, it is `./sqlpage` relative to the current working directory, but it can be changed using: + - the `--config-dir` command line argument + - the `SQLPAGE_CONFIGURATION_DIRECTORY` or `CONFIGURATION_DIRECTORY` environment variable + +This function is useful when you need to reference configuration-related files in your SQL code. diff --git a/examples/official-site/content/functions/cookie.md b/examples/official-site/content/functions/cookie.md new file mode 100644 index 000000000..5f92673c1 --- /dev/null +++ b/examples/official-site/content/functions/cookie.md @@ -0,0 +1,39 @@ +--- +icon: cookie +since: 0.7.1 +category: request-data +summary: Read a named cookie from the incoming request. +return_type: TEXT +parameters: + - name: name + type: TEXT + required: true + description: The name of the cookie to read. +--- + +Reads a [cookie](https://en.wikipedia.org/wiki/HTTP_cookie) with the given name from the request. +Returns the value of the cookie as text, or NULL if the cookie is not present. + +Cookies can be set using the [cookie component](documentation.sql?component=cookie#component). + +### Example + +#### Set a cookie + +Set a cookie called `username` to greet the user by name every time they visit the page: + +```sql +select 'cookie' as component, 'username' as name, :username as value; + +SELECT 'form' as component; +SELECT 'username' as name, 'text' as type; +``` + +#### Read a cookie + +Read a cookie called `username` and greet the user by name: + +```sql +SELECT 'text' as component, + 'Hello, ' || sqlpage.cookie('username') || '!' as contents; +``` diff --git a/examples/official-site/content/functions/current_working_directory.md b/examples/official-site/content/functions/current_working_directory.md new file mode 100644 index 000000000..9099c6428 --- /dev/null +++ b/examples/official-site/content/functions/current_working_directory.md @@ -0,0 +1,26 @@ +--- +icon: folder-question +since: 0.11.0 +category: server-and-runtime +summary: Get the working directory of the SQLPage server process. +--- + +Returns the [current working directory](https://en.wikipedia.org/wiki/Working_directory) of the SQLPage server process. + +### Example + +```sql +SELECT 'text' AS component; +SELECT 'Currently running from ' AS contents; +SELECT sqlpage.current_working_directory() as contents, true as code; +``` + +#### Result + +Currently running from `/home/user/my_sqlpage_website` + +#### Notes + +The current working directory is the directory from which the SQLPage server process was started. +By default, this is also the directory from which `.sql` files are loaded and served. +However, this can be changed by setting the `web_root` [configuration option](https://github.com/sqlpage/SQLPage/blob/main/configuration.md). diff --git a/examples/official-site/content/functions/environment_variable.md b/examples/official-site/content/functions/environment_variable.md new file mode 100644 index 000000000..b46b60549 --- /dev/null +++ b/examples/official-site/content/functions/environment_variable.md @@ -0,0 +1,21 @@ +--- +icon: variable +since: 0.11.0 +category: server-and-runtime +summary: Read a named environment variable from the server. +parameters: + - name: name + type: TEXT + required: true + description: The name of the environment variable to read. Must be a literal string. +--- + +Returns the value of the given [environment variable](https://en.wikipedia.org/wiki/Environment_variable). + +### Example + +```sql +SELECT 'text' AS component; +SELECT 'The value of the HOME environment variable is ' AS contents; +SELECT sqlpage.environment_variable('HOME') as contents, true as code; +``` diff --git a/examples/official-site/content/functions/exec.md b/examples/official-site/content/functions/exec.md new file mode 100644 index 000000000..97c847a20 --- /dev/null +++ b/examples/official-site/content/functions/exec.md @@ -0,0 +1,42 @@ +--- +icon: terminal-2 +since: 0.12.0 +category: server-and-runtime +summary: Run a program on the server and capture its output. +parameters: + - name: program + type: TEXT + required: true + description: The name of the program to execute. Must be a literal string. + - name: arguments... + type: TEXT + description: The arguments to pass to the program. +--- + +Executes a shell command and returns its output as text. + +### Example + +#### Fetch data from a remote API using curl + +```sql +select 'card' as component; +select value->>'name' as title, value->>'email' as description +from json_each(sqlpage.exec('curl', 'https://jsonplaceholder.typicode.com/users')); +``` + +#### Notes + + - This function is disabled by default for security reasons. You can enable it by setting `"allow_exec" : true` in `sqlpage/sqlpage.json`. Enable it only if you trust all the users that can access your SQLPage server files (both locally and on the database). + - Be careful when using this function, as it can be used to execute arbitrary shell commands on your server. Do not use it with untrusted input. + - The command is executed in the current working directory of the SQLPage server process. + - The command is executed with the same user as the SQLPage server process. + - The environment variables of the SQLPage server process are passed to the command, including potentially sensitive variables such as `DATABASE_URL`. + - The command is executed asynchronously, but the SQLPage server has to wait for it to finish before sending the result to the client. + This means that the SQLPage server will not be blocked while the command is running, it will be able to serve other requests, but it will not be able to serve the current request until the command has finished. + You should generally avoid long running commands. + - If the program name is NULL, the result will be NULL. + - If any argument is NULL, it will be passed to the command as an empty string. + - If the command exits with a non-zero exit code, the function will raise an error. + - Arbitrary SQL operations are not allowed as sqlpage function arguments. Use `SET` to assign the result of a SQL query to a variable, and then use that variable as an argument to `sqlpage.exec`. + - When `sqlpage.exec(...)` is a standalone selected column, the command runs once per returned row. Use `SET command_result = sqlpage.exec(...)` first if the command should run only once for the page. diff --git a/examples/official-site/sqlpage/migrations/40_fetch.sql b/examples/official-site/content/functions/fetch.md similarity index 68% rename from examples/official-site/sqlpage/migrations/40_fetch.sql rename to examples/official-site/content/functions/fetch.md index 0118eaa49..972b3a434 100644 --- a/examples/official-site/sqlpage/migrations/40_fetch.sql +++ b/examples/official-site/content/functions/fetch.md @@ -1,14 +1,17 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'fetch', - '0.20.3', - 'transfer-vertical', - 'Sends an HTTP request and returns the results as a string. +--- +icon: transfer-vertical +since: 0.20.3 +category: external-services +summary: Send an HTTP request and read the response body. +parameters: + - name: url + type: TEXT + required: true + description: Either a string containing an URL to request, or a json object in the standard format of the + request interface of the web fetch API. +--- + +Sends an HTTP request and returns the results as a string. ## HTTP request examples @@ -21,13 +24,13 @@ We use the simplest form of the fetch function, that takes the URL to fetch as a ```sql -set url = ''https://nominatim.openstreetmap.org/search?format=json&q='' || sqlpage.url_encode($user_search) +set url = 'https://nominatim.openstreetmap.org/search?format=json&q=' || sqlpage.url_encode($user_search) set api_results = sqlpage.fetch($url); -select ''map'' as component; +select 'map' as component; select $user_search as title, - CAST($api_results->>0->>''lat'' AS FLOAT) as latitude, - CAST($api_results->>0->>''lon'' AS FLOAT) as longitude; + CAST($api_results->>0->>'lat' AS FLOAT) as latitude, + CAST($api_results->>0->>'lon' AS FLOAT) as longitude; ``` ### POST query with a body @@ -35,41 +38,41 @@ select $user_search as title, In this example, we use the complex form of the function to make an authenticated POST request, with custom request headers and a custom request body. -We use SQLite''s json functions to build the request body. +We use SQLite's json functions to build the request body. See [the list of SQL databases and their JSON functions](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) for more information on how to build JSON objects in your database. ```sql set request = json_object( - ''method'', ''POST'', - ''url'', ''https://postman-echo.com/post'', - ''headers'', json_object( - ''Content-Type'', ''application/json'', - ''Authorization'', ''Bearer '' || sqlpage.environment_variable(''MY_API_TOKEN'') + 'method', 'POST', + 'url', 'https://postman-echo.com/post', + 'headers', json_object( + 'Content-Type', 'application/json', + 'Authorization', 'Bearer ' || sqlpage.environment_variable('MY_API_TOKEN') ), - ''body'', json_object( - ''Hello'', ''world'' + 'body', json_object( + 'Hello', 'world' ) ); set api_results = sqlpage.fetch($request); -select ''code'' as component; +select 'code' as component; select - ''API call results'' as title, - ''json'' as language, + 'API call results' as title, + 'json' as language, $api_results as contents; ``` ### Authenticated request using Basic Auth -Here''s how to make a request to an API that requires [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication): +Here's how to make a request to an API that requires [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication): ```sql set request = json_object( - ''url'', ''https://api.example.com/data'', - ''username'', ''my_username'', - ''password'', ''my_password'' + 'url', 'https://api.example.com/data', + 'username', 'my_username', + 'password', 'my_password' ); set api_results = sqlpage.fetch($request); ``` @@ -101,7 +104,7 @@ This makes it easier to conditionnally query an API: ```sql set current_field_value = (select field from my_table where id = 1); -set target_url = nullif(''http://example.com/api/field/1'', null); -- null if the field is currently null in the db +set target_url = nullif('http://example.com/api/field/1', null); -- null if the field is currently null in the db set api_value = sqlpage.fetch($target_url); -- no http request made if the field is not null in the db update my_table set field = $api_value where id = 1 and $api_value is not null; -- update the field only if it was not present before ``` @@ -124,19 +127,3 @@ If the query returns more than one row or more than one column, SQLPage returns If you need to handle errors or inspect the response headers or the status code, use [`sqlpage.fetch_with_meta`](?function=fetch_with_meta). -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'fetch', - 1, - 'url', - 'Either a string containing an URL to request, or a json object in the standard format of the request interface of the web fetch API.', - 'TEXT' - ); diff --git a/examples/official-site/content/functions/fetch_with_meta.md b/examples/official-site/content/functions/fetch_with_meta.md new file mode 100644 index 000000000..c266356f0 --- /dev/null +++ b/examples/official-site/content/functions/fetch_with_meta.md @@ -0,0 +1,84 @@ +--- +icon: transfer-vertical +since: 0.34.0 +category: external-services +summary: Send an HTTP request and read its status, headers, and body. +parameters: + - name: url + type: TEXT + required: true + description: Either a string containing an URL to request, or a json object in the standard format of the + request interface of the web fetch API. +--- + +Sends an HTTP request and returns detailed metadata about the response, including status code, headers, and body. + +This function is similar to [`fetch`](?function=fetch), but returns a JSON object containing detailed information about the response. +When the response declares a `content-type` of `application/json`, the parsed body is returned under `json_body`: +```json +{ + "status": 200, + "headers": { + "content-type": "application/json", + "content-length": "1234" + }, + "json_body": { "name": "ditto" } +} +``` + +For every other content type, the body is returned as a string under `body`: +```json +{ + "status": 200, + "headers": { + "content-type": "text/html", + "content-length": "1234" + }, + "body": "..." +} +``` + +If the request fails or encounters an error (e.g., network issues, invalid UTF-8 response), instead of throwing an error, +the function returns a JSON object with an "error" field containing the error message. + +### Example: Basic Usage + +```sql +-- Make a request and get detailed response information +set response = sqlpage.fetch_with_meta('https://pokeapi.co/api/v2/pokemon/ditto'); + +-- redirect the user to an error page if the request failed +select 'redirect' as component, 'error.sql' as url +where + json_extract($response, '$.error') is not null + or json_extract($response, '$.status') != 200; + +-- Extract data from the response json body +select 'card' as component; +select + json_extract($response, '$.json_body.name') as title, + json_extract($response, '$.json_body.abilities[0].ability.name') as description +from $response; +``` + +### Example: Advanced Request with Authentication + +```sql +set request = json_object( + 'method', 'POST', + 'url', 'https://sqlpage.free.beeceptor.com', + 'headers', json_object( + 'Content-Type', 'application/json', + 'Authorization', 'Bearer ' || sqlpage.environment_variable('API_TOKEN') + ), + 'body', json_object( + 'key', 'value' + ) +); +set response = sqlpage.fetch_with_meta($request); + +-- Check response content type +select 'debug' as component, $response as response; +``` + +The function accepts the same parameters as the [`fetch` function](?function=fetch). diff --git a/examples/official-site/content/functions/hash_password.md b/examples/official-site/content/functions/hash_password.md new file mode 100644 index 000000000..b81c05c91 --- /dev/null +++ b/examples/official-site/content/functions/hash_password.md @@ -0,0 +1,31 @@ +--- +icon: spy +since: 0.7.2 +category: identity-and-security +summary: Hash a password with Argon2id for storage. +parameters: + - name: password + type: TEXT + required: true + description: The password to hash. +--- + +Hashes a password with the Argon2id variant and outputs it in the [PHC string format](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md), ready to store in your users table. + +Every call generates a brand new cryptographic salt so that two people choosing the same password still end up with different hashes, which defeats rainbow-table attacks and lets you safely reveal only the hash. + +Use this function only when creating or resetting a password (for example while inserting a brand new user): it writes the stored value. Later, at login time, the [authentication component](documentation.sql?component=authentication#component) reads the stored hash, hashes the visitor's password with the embedded salt and parameters, and grants access only if they match. + +### Example + +```sql +SELECT 'form' AS component; +SELECT 'username' AS name; +SELECT 'password' AS name, 'password' AS type; + +INSERT INTO users (name, password_hash) VALUES (:username, sqlpage.hash_password(:password)); +``` + +### Try online + +You can try the password hashing function [on this page](/examples/hash_password.sql). diff --git a/examples/official-site/content/functions/header.md b/examples/official-site/content/functions/header.md new file mode 100644 index 000000000..e31561b06 --- /dev/null +++ b/examples/official-site/content/functions/header.md @@ -0,0 +1,24 @@ +--- +icon: heading +since: 0.7.2 +category: request-data +summary: Read the value of one HTTP request header. +parameters: + - name: name + type: TEXT + required: true + description: The name of the HTTP header to read. +--- + +Reads a [header](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) with the given name from the request. + Returns the value of the header as text, or NULL if the header is not present. + +### Example + +Log the [`User-Agent`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) of the browser making the request in the database: + +```sql +INSERT INTO user_agent_log (user_agent) VALUES (sqlpage.header('user-agent')); +``` + +If you need access to all headers at once, use [`sqlpage.headers()`](?function=headers) instead. diff --git a/examples/official-site/sqlpage/migrations/56_headers.sql b/examples/official-site/content/functions/headers.md similarity index 56% rename from examples/official-site/sqlpage/migrations/56_headers.sql rename to examples/official-site/content/functions/headers.md index b88aaf4e2..dc75859b4 100644 --- a/examples/official-site/sqlpage/migrations/56_headers.sql +++ b/examples/official-site/content/functions/headers.md @@ -1,28 +1,25 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'headers', - '0.33.0', - 'circle-dotted-letter-h', - 'Returns all HTTP request headers as a JSON object. +--- +icon: circle-dotted-letter-h +since: 0.33.0 +category: request-data +summary: Read all HTTP request headers as a JSON object. +--- + +Returns all HTTP request headers as a JSON object. ### Example The following displays all HTTP request headers in a list, -using SQLite''s `json_each()` function. +using SQLite's `json_each()` function. ```sql -select ''list'' as component; +select 'list' as component; select key as title, value as description from json_each(sqlpage.headers()); -- json_each() is SQLite only ``` -If not on SQLite, use your [database''s JSON function](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). +If not on SQLite, use your [database's JSON function](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). ### Details @@ -36,4 +33,3 @@ This is useful when you need to: - Access multiple headers at once If you only need access to a single known header, use [`sqlpage.header(name)`](?function=header) instead. -'); \ No newline at end of file diff --git a/examples/official-site/content/functions/hmac.md b/examples/official-site/content/functions/hmac.md new file mode 100644 index 000000000..08514b6ed --- /dev/null +++ b/examples/official-site/content/functions/hmac.md @@ -0,0 +1,111 @@ +--- +icon: shield-lock +since: 0.38.0 +category: identity-and-security +summary: Sign data with a shared secret using HMAC. +parameters: + - name: data + type: TEXT + required: true + description: The input data to compute the HMAC for. Can be any text string. Cannot be NULL. + - name: key + type: TEXT + required: true + description: The secret key used to compute the HMAC. Should be kept confidential. Cannot be NULL. + - name: algorithm + type: TEXT + description: 'The hash algorithm and output format. Optional, defaults to `sha256` (hex output). Supported + values: `sha256`, `sha256-base64`, `sha512`, `sha512-base64`. Defaults to `sha256`.' +--- + +Creates a unique "signature" for some data using a secret key. +This signature proves that the data hasn't been tampered with and comes from someone who knows the secret. + +## HMAC use cases + +[**HMAC**](https://en.wikipedia.org/wiki/HMAC) (Hash-based Message Authentication Code) is commonly used to: + - **Verify webhooks**: Use HMAC to ensure only a given external service can call a given endpoint in your application. +The service signs their request with a secret key, and you verify the signature before processing the data they sent you. +Used for instance by [Stripe](https://docs.stripe.com/webhooks?verify=verify-manually), and [Shopify](https://shopify.dev/docs/apps/build/webhooks/subscribe/https#step-2-validate-the-origin-of-your-webhook-to-ensure-its-coming-from-shopify). + - **Secure API requests**: Prove that an API request comes from an authorized source + - **Generate secure tokens**: Create temporary access codes for downloads or password resets + - **Protect data**: Ensure data hasn't been modified during transmission + +## Signing data + +The `sqlpage.hmac` function takes three inputs: +1. **Your data** - The text you want to sign (like a message or request body) +2. **Your secret key** - A password only you know (keep this safe!) +3. **Algorithm** (optional) - The hash algorithm and output format: + - `sha256` (default) - SHA-256 with hexadecimal output + - `sha256-base64` - SHA-256 with base64 output + - `sha512` - SHA-512 with hexadecimal output + - `sha512-base64` - SHA-512 with base64 output + +It returns a signature string. If someone changes even one letter in your data, the signature will be completely different. + +### Example: Verify a Webhooks signature + +When Shopify sends you a webhook (like when someone places an order), it includes a signature. Here's how to verify it's really from Shopify. +This supposes you store the secret key in an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) named `WEBHOOK_SECRET`. + +```sql +SET body = sqlpage.request_body(); +SET secret = sqlpage.environment_variable('WEBHOOK_SECRET'); +SET expected_signature = sqlpage.hmac($body, $secret, 'sha256'); +SET actual_signature = sqlpage.header('X-Webhook-Signature'); + +-- redirect to an error page and stop execution if the signature does not match +SELECT + 'redirect' as component, + '/error.sql?err=bad_webhook_signature' as link +WHERE $actual_signature != $expected_signature OR $actual_signature IS NULL; + +-- If we reach here, the signature is valid - process the order +INSERT INTO orders (order_data) VALUES ($body); + +SELECT 'json' as component, 'jsonlines' as type; +SELECT 'success' as status; +``` + +### Example: Time-limited links + +You can create links that will be valid only for a limited time by including a signature in them. +Let's say we have a `download.sql` page we want to link to, +but we don't want it to be accessible to anyone who can find the link. +Sign `file_id|expires_at` with a secret. Accept only if not expired and the signature matches. + +#### Generate a signed link + +```sql +SET expires_at = datetime('now', '+1 hour'); +SET token = sqlpage.hmac( + $file_id || '|' || $expires_at, + sqlpage.environment_variable('DOWNLOAD_SECRET'), + 'sha256' +); +SELECT '/download.sql?file_id=' || $file_id || '&expires_at=' || $expires_at || '&token=' || $token AS link; +``` + +#### Verify the signed link + +```sql +SET expected = sqlpage.hmac( + $file_id || '|' || $expires_at, + sqlpage.environment_variable('DOWNLOAD_SECRET'), + 'sha256' +); +SELECT 'redirect' AS component, '/error.sql?err=expired' AS link +WHERE $expected != $token OR $token IS NULL OR $expires_at < datetime('now'); + +-- serve the file +``` + +### Important Security Notes + + - **Keep your secret key safe**: If your secret leaks, anyone can forge signatures and access protected pages + - **The signature is case-sensitive**: Even a single wrong letter means the signature won't match + - **NULL handling**: Always use `IS DISTINCT FROM`, not `=` to check for hmac matches. + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) != $signature` will not redirect if `$signature` is NULL (the signature is absent). + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) IS DISTINCT FROM $signature` checks for both NULL and non-NULL values (but is not available in all SQL dialects). + - `SELECT 'redirect' as component WHERE sqlpage.hmac(...) != $signature OR $signature IS NULL` is the most portable solution. diff --git a/examples/official-site/content/functions/link.md b/examples/official-site/content/functions/link.md new file mode 100644 index 000000000..3c9bdbe89 --- /dev/null +++ b/examples/official-site/content/functions/link.md @@ -0,0 +1,51 @@ +--- +icon: link +since: 0.25.0 +category: links-and-routing +summary: Build a page URL with optional query parameters and a fragment. +parameters: + - name: file + type: TEXT + required: true + description: The path of the SQLPage file to link to, relative to the current file. + - name: parameters + type: JSON + description: A JSON object with the parameters to pass to the linked file. + - name: fragment + type: TEXT + description: An optional fragment (hash) to append to the URL to link to a specific section of the target + page. +--- + +Returns the URL of a SQLPage file with the given parameters. + +### Example + +Let's say you have a database of products, and you want the main page (`index.sql`) to link to the page of each product (`product.sql`) with the product name as a parameter. + +In `index.sql`, you can use the `link` function to generate the URL of the product page for each product. + +```sql +select 'list' as component; +select + name as title, + sqlpage.link('product', json_object('product_name', name)) as link +from products; +``` + +In `product.sql`, you can then use `$product_name` to get the name of the product from the URL parameter: + +```sql +select 'hero' as component, $product_name as title, product_info as description +from products +where name = $product_name; +``` + +> You could also have manually constructed the URL with `CONCAT('product?product_name=', name)`, +> but using `sqlpage.link` is better because it ensures that the URL is properly encoded. +> `sqlpage.link` will work even if the product name contains special characters like `&`, while `CONCAT(...)` would break the URL. + +### Parameters + - `file` (TEXT): The name of the SQLPage file to link to. + - `parameters` (JSON): The parameters to pass to the linked file. + - `fragment` (TEXT): An optional fragment (hash) to append to the URL. This is useful for linking to a specific section of a page. For instance if `product.sql` contains `select 'text' as component, 'product_description' as id;`, you can link to the product description section with `sqlpage.link('product.sql', json_object('product_name', name), 'product_description')`. diff --git a/examples/official-site/content/functions/oidc_logout_url.md b/examples/official-site/content/functions/oidc_logout_url.md new file mode 100644 index 000000000..dcc8ae54e --- /dev/null +++ b/examples/official-site/content/functions/oidc_logout_url.md @@ -0,0 +1,100 @@ +--- +icon: logout +since: 0.41.0 +category: identity-and-security +summary: Build a sign-out URL for an OpenID Connect session. +parameters: + - name: redirect_uri + type: TEXT + description: The relative URL path where the user should be redirected after logout. Must start with `/`. + Defaults to `/` if not provided. +--- + +The `sqlpage.oidc_logout_url` function generates a secure logout URL for users authenticated via [OIDC Single Sign-On](/sso). + +When a user visits this URL, SQLPage will: +1. Remove the authentication cookie +2. Redirect the user to the OIDC provider's logout endpoint (if available) +3. Finally redirect back to the specified `redirect_uri` + +## Security Features + +This function provides protection against **Cross-Site Request Forgery (CSRF)** attacks: +- The generated URL contains a cryptographically signed token +- The token includes a timestamp and expires after 10 minutes +- The token is signed using your OIDC client secret +- Only relative URLs (starting with `/`) are allowed as redirect targets + +This means that malicious websites cannot trick your users into logging out by simply including an image or link to your logout URL. + +## Add a logout button + +```sql +select 'button' as component; +select + 'Logout' as title, + sqlpage.oidc_logout_url('/') as link, + 'logout' as icon, + 'red' as outline; +``` + +This creates a logout button that, when clicked: +1. Logs the user out of your SQLPage application +2. Logs the user out of the OIDC provider (if the provider supports [RP-Initiated Logout](https://openid.net/specs/openid-connect-rpinitiated-1_0.html)) +3. Redirects the user back to your homepage (`/`) + +## Examples + +### Logout Button in Navigation + +```sql +select 'shell' as component, + 'My App' as title, + json_array( + json_object( + 'title', 'Logout', + 'link', sqlpage.oidc_logout_url('/'), + 'icon', 'logout' + ) + ) as menu_item; +``` + +### Logout with Return to Current Page + +```sql +select 'button' as component; +select + 'Sign Out' as title, + sqlpage.oidc_logout_url(sqlpage.path()) as link; +``` + +### Conditional Logout Link + +```sql +select 'button' as component +where sqlpage.user_info('sub') is not null; +select + 'Logout ' || sqlpage.user_info('name') as title, + sqlpage.oidc_logout_url('/') as link +where sqlpage.user_info('sub') is not null; +``` + +## Requirements + +- OIDC must be [configured](/sso) in your `sqlpage.json` +- If OIDC is not configured, this function returns NULL +- The `redirect_uri` must be a relative path starting with `/` + +## Provider Support + +The logout behavior depends on your OIDC provider: + +| Provider | Full Logout Support | +|----------|-------------------| +| Keycloak | ✅ Yes | +| Auth0 | ✅ Yes | +| Google | ❌ No (local logout only) | +| Azure AD | ✅ Yes | +| Okta | ✅ Yes | + +When the provider doesn't support RP-Initiated Logout, SQLPage will still remove the local authentication cookie and redirect to your specified URI. diff --git a/examples/official-site/sqlpage/migrations/21_path.sql b/examples/official-site/content/functions/path.md similarity index 53% rename from examples/official-site/sqlpage/migrations/21_path.sql rename to examples/official-site/content/functions/path.md index 5fc1afaa4..2e3101e37 100644 --- a/examples/official-site/sqlpage/migrations/21_path.sql +++ b/examples/official-site/content/functions/path.md @@ -1,14 +1,11 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'path', - '0.15.0', - 'slashes', - 'Returns the request path of the current page. +--- +icon: slashes +since: 0.15.0 +category: request-data +summary: Get the URL path of the current request. +--- + +Returns the request path of the current page. This is useful to generate links to the current page, and when you have a proxy in front of your SQLPage server that rewrites the URL. ### Example @@ -17,10 +14,9 @@ If we have a page in a file named `my page.sql` at the root of your SQLPage inst then the following SQL query: ```sql -select ''text'' as component, sqlpage.path() as contents; +select 'text' as component, sqlpage.path() as contents; ``` will return `/my%20page.sql`. > Note that the path is URL-encoded. -'); \ No newline at end of file diff --git a/examples/official-site/content/functions/persist_uploaded_file.md b/examples/official-site/content/functions/persist_uploaded_file.md new file mode 100644 index 000000000..c1060588d --- /dev/null +++ b/examples/official-site/content/functions/persist_uploaded_file.md @@ -0,0 +1,54 @@ +--- +icon: device-floppy +since: 0.20.1 +category: files-and-uploads +summary: Save an uploaded file and return its path. +parameters: + - name: file + type: TEXT + required: true + description: Name of the form field containing the uploaded file. The current page must be referenced in + the `action` property of a `form` component that contains a file input field. + - name: destination_folder + type: TEXT + description: |- + Optional. Path to the folder where the file will be saved, relative to the web root (the root folder of your website files). By default, the file will be saved in the `uploads` folder. + + **Security note**: this value must be a folder name you choose yourself in your SQL code (a trusted constant). Never build it from untrusted input such as a form field, a query parameter, a request header, or anything else the visitor controls. The folder is joined directly to the web root, so a value containing `..` or an absolute path would cause the uploaded file to be written *outside* the web root, anywhere the SQLPage process can write. Keeping `destination_folder` a fixed value chosen by the application author avoids this. + - name: allowed_extensions + type: TEXT + description: |- + Optional. Comma-separated list of allowed file extensions. By default: jpg,jpeg,png,gif,bmp,webp,pdf,txt,doc,docx,xls,xlsx,csv,mp3,mp4,wav,avi,mov. + Changing this may be dangerous ! If you add "sql", "svg" or "html" to the list, an attacker could execute arbitrary SQL queries on your database, or impersonate other users. + - name: mode + type: TEXT + description: |- + Optional. Unix permissions to set on the file, in octal notation. By default, the file will be saved with "600" (read/write for the owner only). + Octal notation works by using three digits from 0 to 7: the first for the owner, the second for the group, and the third for others. + For example, "644" means read/write for the owner, and read-only for others. + [Learn more about numeric notation for file-system permissions on Wikipedia](https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation). +--- + +Persists an uploaded file to the local filesystem, and returns its path. +If the file input field is empty, the function returns NULL. + +### Example + +#### User profile picture + +##### `upload_form.sql` + +```sql +select 'form' as component, 'persist_uploaded_file.sql' as action; +select 'file' as type, 'profile_picture' as name, 'Upload your profile picture' as label; +``` + +##### `persist_uploaded_file.sql` + +```sql +update user +set profile_picture = sqlpage.persist_uploaded_file('profile_picture', 'profile_pictures', 'jpg,jpeg,png,gif,webp') +where id = ( + select user_id from session where session_id = sqlpage.cookie('session_id') +); +``` diff --git a/examples/official-site/content/functions/persist_uploaded_files.md b/examples/official-site/content/functions/persist_uploaded_files.md new file mode 100644 index 000000000..34d6cca49 --- /dev/null +++ b/examples/official-site/content/functions/persist_uploaded_files.md @@ -0,0 +1,66 @@ +--- +icon: files +since: 0.49.0 +category: files-and-uploads +summary: Save multiple uploads from one field and return their file details. +parameters: + - name: files + type: TEXT + required: true + description: Name of the form field containing the uploaded files. A field named `photos[]` in the form + can be referenced as `photos`. + - name: destination_folder + type: TEXT + description: |- + Optional. Path to the folder where the files will be saved, relative to the web root. By default, the files will be saved in the `uploads` folder. + + **Security note**: this value must be a folder name you choose yourself in your SQL code (a trusted constant). Never build it from untrusted input: see [`persist_uploaded_file`](?function=persist_uploaded_file). + - name: allowed_extensions + type: TEXT + description: |- + Optional. Comma-separated list of allowed file extensions, checked for every file. By default: jpg,jpeg,png,gif,bmp,webp,pdf,txt,doc,docx,xls,xlsx,csv,mp3,mp4,wav,avi,mov. + Changing this may be dangerous ! If you add "sql", "svg" or "html" to the list, an attacker could execute arbitrary SQL queries on your database, or impersonate other users. + - name: mode + type: TEXT + description: Optional. Unix permissions to set on the files, in octal notation. By default, "600" (read/write + for the owner only). +--- + +Persists all the files uploaded in a single form field, and returns a JSON array with one object per file: + + - `path`: where the file was saved, relative to the web root (like the return value of [`persist_uploaded_file`](?function=persist_uploaded_file)), + - `name`: the original name of the file on the user's device, + - `mime_type`: the type of the file, as sent by the browser, + - `size`: the size of the file, in bytes. + +If no file was uploaded in the field, the function returns NULL. + +Use it with a file input that has the `multiple` attribute, so that users can select several files at once. +It works like [`persist_uploaded_file`](?function=persist_uploaded_file), +which only persists one file (the last one, when several were sent). + +If one of the files has an extension that is not allowed, or cannot be saved, the function fails and no file is persisted. + +### Example + +#### Photo gallery + +##### `upload_form.sql` + +```sql +select 'form' as component, 'save_photos.sql' as action; +select 'file' as type, 'photos[]' as name, 'Photos' as label, true as multiple, 'image/*' as accept; +``` + +##### `save_photos.sql` + +```sql +set files = sqlpage.persist_uploaded_files('photos', 'photos', 'jpg,jpeg,png,webp'); + +-- SQLite (PostgreSQL: json_array_elements($files::json), SQL Server: OPENJSON($files)) +insert into photo (local_path, name, mime_type, size) +select value ->> 'path', value ->> 'name', value ->> 'mime_type', value ->> 'size' +from json_each($files); + +select 'redirect' as component, 'gallery.sql' as link; +``` diff --git a/examples/official-site/content/functions/protocol.md b/examples/official-site/content/functions/protocol.md new file mode 100644 index 000000000..3578c54ff --- /dev/null +++ b/examples/official-site/content/functions/protocol.md @@ -0,0 +1,26 @@ +--- +icon: network +since: 0.17.1 +category: request-data +summary: Identify whether the request used HTTP or HTTPS. +--- + +Returns the protocol that was used to access the current page. + +This can be either `http` or `https`. + +This is useful to generate links to the current page. + +### Example + +```sql +select 'text' as component, + sqlpage.protocol() || '://' || sqlpage.header('host') || sqlpage.path() as contents; +``` + +will return `https://example.com/example.sql`. + +> Note that the path is URL-encoded. The protocol is resolved in this order: +> - `Forwarded` header +> - `X-Forwarded-Proto` header +> request target / URI diff --git a/examples/official-site/content/functions/random_string.md b/examples/official-site/content/functions/random_string.md new file mode 100644 index 000000000..c90b48688 --- /dev/null +++ b/examples/official-site/content/functions/random_string.md @@ -0,0 +1,28 @@ +--- +icon: arrows-shuffle +since: 0.7.2 +category: identity-and-security +summary: Generate a cryptographically secure random string. +parameters: + - name: length + type: INTEGER + required: true + description: The length of the string to generate. +--- + +Returns a cryptographically secure random string of the given length. + +When used as a standalone selected column in a query that returns several rows, `random_string` runs once per returned row. +Use `SET token = sqlpage.random_string(32)` first if you want one token reused later in the page. + +### Example + +Generate a random string of 32 characters and use it as a session ID stored in a cookie: + +```sql +INSERT INTO login_session (session_token, username) VALUES (sqlpage.random_string(32), :username) +RETURNING + 'cookie' AS component, + 'session_id' AS name, + session_token AS value; +``` diff --git a/examples/official-site/sqlpage/migrations/24_read_file_as_data_url.sql b/examples/official-site/content/functions/read_file_as_data_url.md similarity index 62% rename from examples/official-site/sqlpage/migrations/24_read_file_as_data_url.sql rename to examples/official-site/content/functions/read_file_as_data_url.md index eba68adc3..e5bdb522e 100644 --- a/examples/official-site/sqlpage/migrations/24_read_file_as_data_url.sql +++ b/examples/official-site/content/functions/read_file_as_data_url.md @@ -1,15 +1,16 @@ --- Insert the 'variables' function into sqlpage_functions table -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" -) -VALUES ( - 'read_file_as_data_url', - '0.17.0', - 'file-dollar', - 'Returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) +--- +icon: file-dollar +since: 0.17.0 +category: files-and-uploads +summary: Read a file as a data URL for embedding in a page. +parameters: + - name: name + type: TEXT + required: true + description: Path to the file to read. +--- + +Returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) containing the contents of the given file. The file path is relative to the `web root` directory, which is the directory from which your website is served. @@ -18,7 +19,7 @@ with the `web_root` [configuration option](https://github.com/sqlpage/SQLPage/bl If the given argument is null, the function will return null. -As with other functions, if an error occurs during execution +As with other functions, if an error occurs during execution (because the file does not exist, for instance), the function will display an error message and the database query will not be executed. @@ -37,30 +38,12 @@ Otherwise, the MIME type will be guessed from the file extension, without lookin ## Example: inlining a picture - + ```sql -select ''card'' as component; -select ''Picture'' as title, sqlpage.read_file_as_data_url(''/path/to/picture.jpg'') as top_image; +select 'card' as component; +select 'Picture' as title, sqlpage.read_file_as_data_url('/path/to/picture.jpg') as top_image; ``` > **Note:** Data URLs are larger than the original file they represent, so they should only be used for small files > (under a few hundred kilobytes). > Otherwise, the page will take a long time to load. -'); - --- Insert the parameters for the 'variables' function into sqlpage_function_parameters table --- Parameter 1: 'method' parameter -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" -) -VALUES ( - 'read_file_as_data_url', - 1, - 'name', - 'Path to the file to read.', - 'TEXT' -); diff --git a/examples/official-site/content/functions/read_file_as_text.md b/examples/official-site/content/functions/read_file_as_text.md new file mode 100644 index 000000000..b7b78a2fc --- /dev/null +++ b/examples/official-site/content/functions/read_file_as_text.md @@ -0,0 +1,37 @@ +--- +icon: file-invoice +since: 0.17.0 +category: files-and-uploads +summary: Read the text of a UTF-8 file from the web root. +parameters: + - name: name + type: TEXT + required: true + description: Path to the file to read. +--- + +Returns a string containing the contents of the given file. + +The file must be a raw text file using UTF-8 encoding. + +The file path is relative to the `web root` directory, which is the directory from which your website is served +(not necessarily the directory SQLPage is launched from). + +If the given argument is null, the function will return null. + +As with other functions, if an error occurs during execution +(because the file does not exist, for instance), +the function will display an error message and the +database query will not be executed. + +If you are using a `sqlpage_files` table to store files directly in the database (serverless mode), +the function will attempt to read the file from the database filesystem if it is not found on the local disk, +using the same logic as for serving files in response to HTTP requests. + +## Example + +### Rendering a markdown file + +```sql +select 'text' as component, sqlpage.read_file_as_text('/path/to/file.md') as contents_md; +``` diff --git a/examples/official-site/sqlpage/migrations/74_regex_match.sql b/examples/official-site/content/functions/regex_match.md similarity index 61% rename from examples/official-site/sqlpage/migrations/74_regex_match.sql rename to examples/official-site/content/functions/regex_match.md index 8e0540458..f8e9e6699 100644 --- a/examples/official-site/sqlpage/migrations/74_regex_match.sql +++ b/examples/official-site/content/functions/regex_match.md @@ -1,16 +1,21 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'regex_match', - '0.43.0', - 'regex', - 'Matches a text value against a regular expression and returns the capture groups as a JSON object. +--- +icon: regex +since: 0.43.0 +category: links-and-routing +summary: Match text against a regular expression and extract capture groups. +parameters: + - name: pattern + type: TEXT + required: true + description: The regular expression pattern to match against the input text. Named capture groups such + as `(?...)` are supported. + - name: text + type: TEXT + required: true + description: The text to match against the regular expression. Returns `NULL` when this argument is `NULL`. +--- + +Matches a text value against a regular expression and returns the capture groups as a JSON object. If the text matches the pattern, the result contains one entry for each capture group that matched: - key `0` contains the full match @@ -31,16 +36,16 @@ You can put a `categories/404.sql` file in your project and extract the dynamic #### `categories/404.sql` ```sql set route = sqlpage.regex_match( - ''/categories/(?\w+)/post/(?\d+)'', + '/categories/(?\w+)/post/(?\d+)', sqlpage.path() ); -select ''redirect'' as component, ''/404'' as link +select 'redirect' as component, '/404' as link where $route is null; -select ''text'' as component; +select 'text' as component; select - ''Category: '' || ($route->>''category'') || '' | Post id: '' || ($route->>''id'') as contents; + 'Category: ' || ($route->>'category') || ' | Post id: ' || ($route->>'id') as contents; ``` If the current path is `/categories/sql/post/42`, `sqlpage.regex_match()` returns: @@ -54,8 +59,8 @@ You can then use those extracted values to query your database: ```sql select title, body from posts -where category = $route->>''category'' - and id = cast($route->>''id'' as integer); +where category = $route->>'category' + and id = cast($route->>'id' as integer); ``` ### Details @@ -67,37 +72,11 @@ where category = $route->>''category'' - Some databases, such as MySQL and MariaDB, treat backslashes specially inside SQL strings. In those databases, you may need to write `\\w` and `\\d`, or use portable character classes such as `[A-Za-z0-9_]` and `[0-9]` instead. - In SQLite, PostgreSQL, and some other databases, you can read fields from the returned JSON with `->` and `->>` -- On databases that do not support that syntax, use their JSON extraction function instead, such as `json_extract($route, ''$.category'')` +- On databases that do not support that syntax, use their JSON extraction function instead, such as `json_extract($route, '$.category')` - For the full regular expression syntax supported by SQLPage, see the Rust `regex` crate documentation: [regex syntax reference](https://docs.rs/regex/latest/regex/#syntax) - If the input text is `NULL`, the function returns `NULL` - If an optional capture group does not match, that key is omitted from the JSON object - If the regular expression is invalid, SQLPage returns an error -The returned JSON can then be processed with your database''s JSON functions. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'regex_match', - 1, - 'pattern', - 'The regular expression pattern to match against the input text. Named capture groups such as `(?...)` are supported.', - 'TEXT' - ), - ( - 'regex_match', - 2, - 'text', - 'The text to match against the regular expression. Returns `NULL` when this argument is `NULL`.', - 'TEXT' - ); +The returned JSON can then be processed with your database's JSON functions. diff --git a/examples/official-site/content/functions/request_body.md b/examples/official-site/content/functions/request_body.md new file mode 100644 index 000000000..724a327c4 --- /dev/null +++ b/examples/official-site/content/functions/request_body.md @@ -0,0 +1,72 @@ +--- +icon: http-post +since: 0.33.0 +category: request-data +summary: Read the raw request body as text. +--- + +Returns the raw request body as a string. + +A client (like a web browser, mobile app, or another server) can send information to your server in the request body. +This function allows you to read that information in your SQL code, +in order to create or update a resource in your database for instance. + +The request body is commonly used when building **REST APIs** (machines-to-machines interfaces) +that receive data from the client. + +This is especially useful in: +- `POST` and `PUT` requests for creating or updating resources in your database +- Any API endpoint that needs to receive complex data + +### Example: Building a REST API + +Here's an example of building an API endpoint that receives a json object, +and inserts it into a database. + +#### `api/create_user.sql` +```sql +-- Get the raw JSON body +set user_data = sqlpage.request_body(); + +-- Insert the user into database +with parsed_data as ( + select + json_extract($user_data, '$.name') as name, + json_extract($user_data, '$.email') as email +) +insert into users (name, email) +select name, email from parsed_data; + +-- Return success response +select 'json' as component, + json_object( + 'status', 'success', + 'message', 'User created successfully' + ) as contents; +``` + +### Testing the API + +You can test this API using curl: +```bash +curl -X POST http://localhost:8080/api/create_user \ + -H "Content-Type: application/json" \ + -d '{"name": "John", "email": "john@example.com"}' +``` + +## Special cases + +### NULL + +This function returns NULL if: + - There is no request body + - The request content type is `application/x-www-form-urlencoded` or `multipart/form-data` + (in these cases, use [`sqlpage.variables('post')`](?function=variables) instead) + +### Binary data + +If the request body is not valid text encoded in UTF-8, +invalid characters are replaced with the Unicode replacement character `�` (U+FFFD). + +If you need to handle binary data, +use [`sqlpage.request_body_base64()`](?function=request_body_base64) instead. diff --git a/examples/official-site/content/functions/request_body_base64.md b/examples/official-site/content/functions/request_body_base64.md new file mode 100644 index 000000000..47cac0860 --- /dev/null +++ b/examples/official-site/content/functions/request_body_base64.md @@ -0,0 +1,52 @@ +--- +icon: photo-up +since: 0.33.0 +category: request-data +summary: Read a binary request body as a Base64 string. +--- + +Returns the raw request body encoded in base64. This is useful when receiving binary data or when you need to handle non-text content in your API endpoints. + +## Base64 encoding + +Base64 is a way to encode binary data (like images or files) into text that can be safely stored and transmitted. This function automatically converts the incoming request body into this format. + +## Receiving binary data in an API + +This example shows how to receive and process an image uploaded directly in the request body: + +```sql +-- Assuming this is api/upload_image.sql +-- Client would send a POST request with the raw image data + +-- Get the base64-encoded image data +set image_data = sqlpage.request_body_base64(); + +-- Store the image data in the database +insert into images (data, uploaded_at) +values ($image_data, current_timestamp); + +-- Return success response +select 'json' as component, + json_object( + 'status', 'success', + 'message', 'Image uploaded successfully' + ) as contents; +``` + +You can test this API using curl: +```bash +curl -X POST http://localhost:8080/api/upload_image.sql \ + -H "Content-Type: application/octet-stream" \ + --data-binary "@/path/to/image.jpg" +``` + +This is particularly useful when: +- Working with binary data (images, files, etc.) +- The request body contains non-UTF8 characters +- You need to pass the raw body to another system that expects base64 + +> Note: Like [`sqlpage.request_body()`](?function=request_body), this function returns NULL if: +> - There is no request body +> - The request content type is `application/x-www-form-urlencoded` or `multipart/form-data` +> (in these cases, use [`sqlpage.variables('post')`](?function=variables) instead) diff --git a/examples/official-site/sqlpage/migrations/43_request_method.sql b/examples/official-site/content/functions/request_method.md similarity index 65% rename from examples/official-site/sqlpage/migrations/43_request_method.sql rename to examples/official-site/content/functions/request_method.md index e5868b6d8..2c415d4bf 100644 --- a/examples/official-site/sqlpage/migrations/43_request_method.sql +++ b/examples/official-site/content/functions/request_method.md @@ -1,16 +1,11 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'request_method', - '0.21.0', - 'http-get', - 'Returns the HTTP request method (GET, POST, etc.) used to access the page. +--- +icon: http-get +since: 0.21.0 +category: request-data +summary: Get the HTTP method, such as GET or POST. +--- + +Returns the HTTP request method (GET, POST, etc.) used to access the page. ## HTTP request methods @@ -24,11 +19,9 @@ HTTP request methods (also known as verbs) are used to indicate the desired acti ## Require a PUT request ```sql -select ''redirect'' as component, - ''/error?msg=expected+a+PUT+request'' as link -where sqlpage.request_method() != ''PUT''; +select 'redirect' as component, + '/error?msg=expected+a+PUT+request' as link +where sqlpage.request_method() != 'PUT'; insert into my_table (column1, column2) values (:value1, :value2); ``` -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/38_run_sql.sql b/examples/official-site/content/functions/run_sql.md similarity index 67% rename from examples/official-site/sqlpage/migrations/38_run_sql.sql rename to examples/official-site/content/functions/run_sql.md index 314755f2e..9a077cc29 100644 --- a/examples/official-site/sqlpage/migrations/38_run_sql.sql +++ b/examples/official-site/content/functions/run_sql.md @@ -1,14 +1,23 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'run_sql', - '0.20.0', - 'login', - 'Executes another SQL file and returns its result as a JSON array. +--- +icon: login +since: 0.20.0 +category: server-and-runtime +summary: Run another SQLPage file and return its rows as JSON. +parameters: + - name: file + type: TEXT + required: true + description: |- + Path to the SQL file to execute, can be absolute, or relative to the web root (the root folder of your website sql files). + In-database files, from the sqlpage_files(path, contents, last_modified) table are supported. + - name: parameters + type: JSON + description: Optional JSON object to pass as parameters to the included SQL file. The keys of the object + will be available as variables in the included file. By default, the included file will have access to + the same variables as the calling file. +--- + +Executes another SQL file and returns its result as a JSON array. ### Example @@ -21,7 +30,7 @@ and use the [`dynamic`](documentation.sql?component=dynamic#component) component to include it in all your pages. ```sql -select ''dynamic'' as component, sqlpage.run_sql(''common_header.sql'') as properties; +select 'dynamic' as component, sqlpage.run_sql('common_header.sql') as properties; ``` #### Factorize logic between pages @@ -38,7 +47,7 @@ select some_field from some_table; ```sql -- save the value of some_field from the first result row of reusable.sql into $my_var -set my_var = sqlpage.run_sql(''reusable.sql'')->>0->>''some_field''; +set my_var = sqlpage.run_sql('reusable.sql')->>0->>'some_field'; ``` See [json in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) @@ -65,31 +74,8 @@ You can pass parameters to the included file, as if it had been with a URL param For instance, you can use: ```sql -sqlpage.run_sql(''included_file.sql'', json_object(''param1'', ''value1'', ''param2'', ''value2'')) +sqlpage.run_sql('included_file.sql', json_object('param1', 'value1', 'param2', 'value2')) ``` Which will make `$param1` and `$param2` available in the included file. [More information about building JSON objects in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'run_sql', - 1, - 'file', - 'Path to the SQL file to execute, can be absolute, or relative to the web root (the root folder of your website sql files). - In-database files, from the sqlpage_files(path, contents, last_modified) table are supported.', - 'TEXT' - ),( - 'run_sql', - 2, - 'parameters', - 'Optional JSON object to pass as parameters to the included SQL file. The keys of the object will be available as variables in the included file. By default, the included file will have access to the same variables as the calling file.', - 'JSON' - ); diff --git a/examples/official-site/sqlpage/migrations/75_send_mail.sql b/examples/official-site/content/functions/send_mail.md similarity index 80% rename from examples/official-site/sqlpage/migrations/75_send_mail.sql rename to examples/official-site/content/functions/send_mail.md index 01d6281c0..4bbadd98c 100644 --- a/examples/official-site/sqlpage/migrations/75_send_mail.sql +++ b/examples/official-site/content/functions/send_mail.md @@ -1,16 +1,25 @@ -INSERT INTO sqlpage_functions ( - "name", - "return_type", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'send_mail', - 'JSON', - '0.45.0', - 'mail', - 'Sends a plain-text email using the outgoing mail server configured in SQLPage. +--- +icon: mail +since: 0.45.0 +category: external-services +summary: Send email with optional attachments through an SMTP server. +return_type: JSON +parameters: + - name: message + type: JSON + required: true + description: 'A JSON object containing the email to send. Required properties are `to` (an address or non-empty + address array), `subject`, and either `body` or `body_md`. Optional properties are `from` (required unless + `smtp_from` or `SMTP_FROM` is configured), `reply_to`, `cc` (an address or non-empty address array), + `body` (the plain-text body; required unless `body_md` is provided), `body_html` (an HTML alternative + body sent as `multipart/alternative` alongside `body`), `body_md` (a Markdown body rendered to HTML and + sent as `multipart/alternative` with the raw Markdown as the plain-text alternative; cannot be combined + with `body_html`), and `attachments` (an array of `{ "filename": "...", "data_url": "data:..." }` objects). + Invalid JSON and invalid or unknown properties return `{ "status": "error", "error_code": "...", "error": + "..." }`. SQL `NULL` returns SQL `NULL` without sending.' +--- + +Sends a plain-text email using the outgoing mail server configured in SQLPage. ### Quick start @@ -35,9 +44,9 @@ You can now send an email from any SQL file: ```sql set result = sqlpage.send_mail(json_object( - ''to'', ''alice@example.com'', - ''subject'', ''Hello from SQLPage'', - ''body'', ''Your first email is working!'' + 'to', 'alice@example.com', + 'subject', 'Hello from SQLPage', + 'body', 'Your first email is working!' )); ``` @@ -50,16 +59,16 @@ The sender comes from `smtp_from`. The result is a JSON object: If the message cannot be sent, the function returns the reason instead of stopping the request: ```json -{"status":"error","error_code":"INVALID_EMAIL_TO","error":"''xxx'' is not a valid to email address"} +{"status":"error","error_code":"INVALID_EMAIL_TO","error":"'xxx' is not a valid to email address"} ``` For every non-`NULL` call, `status` is either `accepted` or `error`. Always check it before showing a success message or continuing work that depends on the email: ```sql -select ''alert'' as component, - case when json_extract($result, ''$.status'') = ''accepted'' then ''success'' else ''danger'' end as color, - case when json_extract($result, ''$.status'') = ''accepted'' then ''Email sent'' else ''Email could not be sent'' end as title, - json_extract($result, ''$.error'') as description; +select 'alert' as component, + case when json_extract($result, '$.status') = 'accepted' then 'success' else 'danger' end as color, + case when json_extract($result, '$.status') = 'accepted' then 'Email sent' else 'Email could not be sent' end as title, + json_extract($result, '$.error') as description; ``` ### SMTP provider settings @@ -137,13 +146,13 @@ Each attachment has a file name and a [data URL](https://developer.mozilla.org/e ```sql set result = sqlpage.send_mail(json_object( - ''to'', json_array(''alice@example.com'', ''bob@example.com''), - ''cc'', ''team@example.com'', - ''subject'', ''Monthly report'', - ''body'', ''The report is attached.'', - ''attachments'', json_array(json_object( - ''filename'', ''report.pdf'', - ''data_url'', sqlpage.read_file_as_data_url(''report.pdf'') + 'to', json_array('alice@example.com', 'bob@example.com'), + 'cc', 'team@example.com', + 'subject', 'Monthly report', + 'body', 'The report is attached.', + 'attachments', json_array(json_object( + 'filename', 'report.pdf', + 'data_url', sqlpage.read_file_as_data_url('report.pdf') )) )); ``` @@ -158,10 +167,10 @@ Set `body_html` to send an HTML version of the message alongside the plain-text ```sql set result = sqlpage.send_mail(json_object( - ''to'', ''alice@example.com'', - ''subject'', ''Welcome'', - ''body'', ''Welcome to our service.'', - ''body_html'', ''

Welcome to our service.

'' + 'to', 'alice@example.com', + 'subject', 'Welcome', + 'body', 'Welcome to our service.', + 'body_html', '

Welcome to our service.

' )); ``` @@ -173,9 +182,9 @@ Set `body_md` to send a [Markdown](https://daringfireball.net/projects/markdown/ ```sql set result = sqlpage.send_mail(json_object( - ''to'', ''alice@example.com'', - ''subject'', ''Welcome'', - ''body_md'', ''# Welcome\n\nWelcome to **our service**.'' + 'to', 'alice@example.com', + 'subject', 'Welcome', + 'body_md', '# Welcome\n\nWelcome to **our service**.' )); ``` @@ -186,25 +195,25 @@ SQLPage renders Markdown using the same [GFM](https://github.github.com/gfm/) op ### Contact form ```sql -select ''form'' as component, ''post'' as method; -select ''email'' as name, ''email'' as type, true as required; -select ''message'' as name, ''textarea'' as type, true as required; +select 'form' as component, 'post' as method; +select 'email' as name, 'email' as type, true as required; +select 'message' as name, 'textarea' as type, true as required; set mail = json_object( - ''to'', ''admin@example.com'', - ''reply_to'', :email, - ''subject'', ''Website contact form'', - ''body'', :message + 'to', 'admin@example.com', + 'reply_to', :email, + 'subject', 'Website contact form', + 'body', :message ); set result = ( select sqlpage.send_mail($mail) where :message is not null ); -select ''alert'' as component, - case when json_extract($result, ''$.status'') = ''accepted'' then ''success'' else ''danger'' end as color, - case when json_extract($result, ''$.status'') = ''accepted'' then ''Message sent'' else ''Message could not be sent'' end as title, - json_extract($result, ''$.error'') as description +select 'alert' as component, + case when json_extract($result, '$.status') = 'accepted' then 'success' else 'danger' end as color, + case when json_extract($result, '$.status') = 'accepted' then 'Message sent' else 'Message could not be sent' end as title, + json_extract($result, '$.error') as description where :message is not null; ``` @@ -279,20 +288,3 @@ SQLPage does not currently support: | `SMTP_TIMEOUT` | The SMTP operation timed out. | | `SMTP_REJECTED` | The SMTP server returned a temporary or permanent rejection, including authentication failures. | | `SMTP_CONNECTION_FAILED` | SQLPage could not connect to or communicate with the SMTP server. | -' - ); - -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'send_mail', - 1, - 'message', - 'A JSON object containing the email to send. Required properties are `to` (an address or non-empty address array), `subject`, and either `body` or `body_md`. Optional properties are `from` (required unless `smtp_from` or `SMTP_FROM` is configured), `reply_to`, `cc` (an address or non-empty address array), `body` (the plain-text body; required unless `body_md` is provided), `body_html` (an HTML alternative body sent as `multipart/alternative` alongside `body`), `body_md` (a Markdown body rendered to HTML and sent as `multipart/alternative` with the raw Markdown as the plain-text alternative; cannot be combined with `body_html`), and `attachments` (an array of `{ "filename": "...", "data_url": "data:..." }` objects). Invalid JSON and invalid or unknown properties return `{ "status": "error", "error_code": "...", "error": "..." }`. SQL `NULL` returns SQL `NULL` without sending.', - 'JSON' - ); diff --git a/examples/official-site/content/functions/set_variable.md b/examples/official-site/content/functions/set_variable.md new file mode 100644 index 000000000..1b1692e49 --- /dev/null +++ b/examples/official-site/content/functions/set_variable.md @@ -0,0 +1,41 @@ +--- +icon: variable +since: 0.40.0 +category: links-and-routing +summary: Build a link to this page with a query parameter changed or removed. +parameters: + - name: name + type: TEXT + required: true + description: The name of the variable to set. + - name: value + type: TEXT + description: The value to set the variable to. +--- + +Returns a URL that is the same as the current page's URL, but with a variable set to a new value. + +This function is useful when you want to create a link that changes a parameter on the current page, while preserving other parameters. + +It is equivalent to `sqlpage.link(sqlpage.path(), json_patch(sqlpage.variables('get'), json_object(name, value)))`. + +### Example + +Let's say you have a list of products, and you want to filter them by category. You can use `sqlpage.set_variable` to create links that change the category filter, without losing other potential filters (like a search query or a sort order). + +```sql +select 'button' as component, 'sm' as size, 'center' as justify; +select + category as title, + sqlpage.set_variable('category', category) as link, + case when $category = category then 'primary' else 'secondary' end as color +from categories; +``` + +When `sqlpage.set_variable(...)` is used as a standalone selected column in a query that returns several rows, it runs once per returned row. +This is useful for generating one link per row, as in the example above. +If you need a single link reused later in the page, store it with `SET` first. + +### Parameters + - `name` (TEXT): The name of the variable to set. + - `value` (TEXT): The value to set the variable to. If `NULL` is passed, the variable is removed from the URL. diff --git a/examples/official-site/content/functions/uploaded_file_mime_type.md b/examples/official-site/content/functions/uploaded_file_mime_type.md new file mode 100644 index 000000000..7114f3a9a --- /dev/null +++ b/examples/official-site/content/functions/uploaded_file_mime_type.md @@ -0,0 +1,41 @@ +--- +icon: file-settings +since: 0.18.0 +category: files-and-uploads +summary: Read the media type supplied by the browser for an uploaded file. +parameters: + - name: name + type: TEXT + required: true + description: Name of the file input field in the form. +--- + +Returns the MIME type of an uploaded file. + +## Example: handling a picture upload + +When letting the user upload a picture, you may want to check that the uploaded file is indeed an image. + +```sql +select 'redirect' as component, + 'invalid_file.sql' as link +where sqlpage.uploaded_file_mime_type('myfile') not like 'image/%'; +``` + +In `invalid_file.sql`, you can display an error message to the user: + +```sql +select 'alert' as component, 'Error' as title, + 'Invalid file type' as description, + 'alert-circle' as icon, 'red' as color; +``` + +## Example: white-listing file types + +You could have a database table containing the allowed MIME types, and check that the uploaded file is of one of those types: + +```sql +select 'redirect' as component, + 'invalid_file.sql' as link +where sqlpage.uploaded_file_mime_type('myfile') not in (select mime_type from allowed_mime_types); +``` diff --git a/examples/official-site/content/functions/uploaded_file_name.md b/examples/official-site/content/functions/uploaded_file_name.md new file mode 100644 index 000000000..82f0fc169 --- /dev/null +++ b/examples/official-site/content/functions/uploaded_file_name.md @@ -0,0 +1,54 @@ +--- +icon: file-description +since: 0.23.0 +category: files-and-uploads +summary: Read the original filename supplied by the browser. +parameters: + - name: name + type: TEXT + required: true + description: Name of the file input field in the form. +--- + +Returns the `filename` value in the `content-disposition` header. + +## Example: saving uploaded file metadata for later download + +### Making a form + +```sql +select 'form' as component, 'handle_file_upload.sql' as action; +select 'myfile' as name, 'file' as type, 'File' as label; +``` + +### Handling the form response + +### Inserting an arbitrary file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database + +In `handle_file_upload.sql`, one can process the form results like this: + +```sql +insert into uploaded_files (fname, content, uploaded) values ( + sqlpage.uploaded_file_name('myfile'), + sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('myfile')), + CURRENT_TIMESTAMP +); +``` + +> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files. + +### Downloading the uploaded files + +The file can be downloaded by clicking a link like this: +```sql +select 'button' as component; +select name as title, content as link from uploaded_files where name = $file_name limit 1; +``` + +> *Note*: because the file is ecoded as a data uri, the file is transferred to the client whether or not the link is clicked + +### Large files + +See the [`sqlpage.uploaded_file_path`](?function=uploaded_file_path#function) function. + +See the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function. diff --git a/examples/official-site/content/functions/uploaded_file_path.md b/examples/official-site/content/functions/uploaded_file_path.md new file mode 100644 index 000000000..4f12188ce --- /dev/null +++ b/examples/official-site/content/functions/uploaded_file_path.md @@ -0,0 +1,72 @@ +--- +icon: upload +since: 0.17.0 +category: files-and-uploads +summary: Get the temporary path of an uploaded file. +parameters: + - name: name + type: TEXT + required: true + description: Name of the file input field in the form. +--- + +Returns the path to a temporary file containing the contents of an uploaded file. + +## Example: handling a picture upload + +### Making a form + +```sql +select 'form' as component, 'handle_picture_upload.sql' as action; +select 'myfile' as name, 'file' as type, 'Picture' as label; +select 'title' as name, 'text' as type, 'Title' as label; +``` + +### Handling the form response + +### Inserting an image file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database + +In `handle_picture_upload.sql`, one can process the form results like this: + +```sql +insert into pictures (title, path) values (:title, sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('myfile'))); +``` + +> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files. + +### Inserting file contents as text into the database + +When the uploaded file is a simple raw text file (e.g. a `.txt` file), +one can use the [`sqlpage.read_file_as_text`](?function=read_file_as_text#function) +function to insert the contents of the file into the database like this: + +```sql +insert into text_documents (title, path) values (:title, sqlpage.read_file_as_text(sqlpage.uploaded_file_path('my_text_file'))); +``` + +### Saving the uploaded file to a permanent location + +When the uploaded file is larger than a few megabytes, it is not recommended to store it in the database. +Instead, one can save the file to a permanent location on the server, and store the path to the file in the database. + +You can move the file to a permanent location using the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function. +### Advanced file handling + +For more advanced file handling, such as uploading files to a cloud storage service, +you can write a small script in your favorite programming language, +and call it using the [`sqlpage.exec`](?function=exec#function) function. + +For instance, one could save the following small bash script to `/usr/local/bin/upload_to_s3`: + +```bash +#!/bin/bash +aws s3 cp "$1" s3://your-s3-bucket-name/ +echo "https://your-s3-bucket-url/$(basename "$1")" +``` + +Then, you can call it from SQL like this: + +```sql +set url = sqlpage.exec('upload_to_s3', sqlpage.uploaded_file_path('myfile')); +insert into uploaded_files (title, path) values (:title, $url); +``` diff --git a/examples/official-site/content/functions/url_encode.md b/examples/official-site/content/functions/url_encode.md new file mode 100644 index 000000000..f9adb2818 --- /dev/null +++ b/examples/official-site/content/functions/url_encode.md @@ -0,0 +1,24 @@ +--- +icon: percentage +since: 0.12.0 +category: links-and-routing +summary: Encode text for use in a URL. +parameters: + - name: string + type: TEXT + required: true + description: The string to encode. +--- + +Returns the given string, with all characters that are not allowed in a URL encoded. + +### Example + +```sql +select 'text' as component; +select 'https://example.com/?q=' || sqlpage.url_encode($user_search) as contents; +``` + +#### Result + +`https://example.com/?q=hello%20world` diff --git a/examples/official-site/content/functions/user_info.md b/examples/official-site/content/functions/user_info.md new file mode 100644 index 000000000..d63d9b24c --- /dev/null +++ b/examples/official-site/content/functions/user_info.md @@ -0,0 +1,104 @@ +--- +icon: user +since: 0.34.0 +category: identity-and-security +summary: Read a named claim for the signed-in user. +parameters: + - name: claim + type: TEXT + required: true + description: The name of the user information to retrieve. Common values include 'name', 'email', 'picture', + 'sub', 'preferred_username', 'given_name', and 'family_name'. The exact values available depend on your + OIDC provider and configuration. +--- + +The `sqlpage.user_info` function is a convenient way to access specific pieces of information about the currently logged-in user. +When you [configure Single Sign-On](/sso), your OIDC provider will issue an [ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) for the user, +which contains *claims*, with information about the user. + +Calling `sqlpage.user_info(claim_name)` lets you access these claims directly from SQL. + +## Read a claim + +The function takes one parameter: the name of the *claim* (the piece of information you want to retrieve). + +For example, to display a personalized welcome message, with the user's name, you can use: + +```sql +select 'text' as component; +select 'Welcome, ' || sqlpage.user_info('name') || '!' as title; +``` + +## Available Information + +The exact information available depends on your identity provider (the service you chose to authenticate with), +its configuration, and the scopes you requested. +Use [`sqlpage.user_info_token()`](?function=user_info_token) to see all the information available in the ID token of the current user. + +Here are some commonly available fields: + +### Basic Information +- `name`: The user's full name (usually first and last name separated by a space) +- `email`: The user's email address (*warning*: there is no guarantee that the user currently controls this email address. Use the `sub` claim for database references instead.) +- `picture`: URL to the user's profile picture + +### User Identifiers +- `sub`: A unique identifier for the user (use this to uniquely identify the user in your database) +- `preferred_username`: The username the user prefers to use + +### Name Components +- `given_name`: The user's first name +- `family_name`: The user's last name + +## Examples + +### Personalized Welcome Message +```sql +select 'text' as component, + 'Welcome back, **' || sqlpage.user_info('given_name') || '**!' as contents_md; +``` + +### User Profile Card +```sql +select 'card' as component; +select + sqlpage.user_info('name') as title, + sqlpage.user_info('email') as description, + sqlpage.user_info('picture') as image; +``` + +### Conditional Content Based on custom claims + +Some identity providers let you add custom claims to the ID token. +This lets you customize the behavior of your application based on arbitrary user attributes, +such as the user's role. + +```sql +-- show everything to admins, only public items to others +select 'list' as component; +select title from my_items + where is_public or sqlpage.user_info('role') = 'admin' +``` + +## Security Best Practices + +> ⚠️ **Important**: Always use the `sub` claim to identify users in your database, not their email address. +> The `sub` claim is guaranteed to be unique and stable for each user, while email addresses can change. +> In most providers, receiving an id token with a given email does not guarantee that the user currently controls that email. + +```sql +-- Store the user's ID in your database +insert into user_preferences (user_id, theme) +values (sqlpage.user_info('sub'), 'dark'); +``` + +## Troubleshooting + +If you're not getting the information you expect: + +1. Check that OIDC is properly configured in your `sqlpage.json` +2. Verify that you requested the right scopes in your OIDC configuration +3. Try using `sqlpage.user_info_token()` to see all available information +4. Check your OIDC provider's documentation for the exact claim names they use + +Remember: If the user is not logged in or the requested information is not available, this function returns NULL. diff --git a/examples/official-site/content/functions/user_info_token.md b/examples/official-site/content/functions/user_info_token.md new file mode 100644 index 000000000..5d6ecc7d6 --- /dev/null +++ b/examples/official-site/content/functions/user_info_token.md @@ -0,0 +1,39 @@ +--- +icon: key +since: 0.35.0 +category: identity-and-security +summary: Read all claims from the user's OpenID Connect ID token. +--- + +This function can be used only when you have [configured Single Sign-On with an OIDC provider](/sso). + +## The ID Token + +When a user logs in through OIDC, your application receives an [identity token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) from the identity provider. +This token contains information about the user, such as their name and email address. +The `sqlpage.user_info_token()` function lets you access the entire contents of the ID token, as a JSON object. +You can then use [your database's JSON functions](/blog.sql?post=JSON+in+SQL%3A+A+Comprehensive+Guide) to process that JSON. + +If you need to access a specific claim, it is easier and more performant to use the +[`sqlpage.user_info()`](?function=user_info) function instead. + +## Displaying user claims + +```sql +select 'list' as component; +select key as title, value as description +from json_each(sqlpage.user_info_token()); +``` + +This sqlite-specific example will show all the information available about the current user, such as: +- `sub`: A unique identifier for the user +- `name`: The user's full name +- `email`: The user's email address +- `picture`: A URL to the user's profile picture + +## Security notes + +- The ID token is automatically verified by SQLPage to ensure it hasn't been tampered with. +- The token is only available to authenticated users: if no user is logged in or sso is not configured, this function returns NULL +- If some information is not available in the token, you have to configure it on your OIDC provider, SQLPage can't do anything about it. +- The token is stored in a signed http-only cookie named `sqlpage_auth`. You can use [the cookie component](/component.sql?component=cookie) to delete it, and the user will be redirected to the login page on the next page load. diff --git a/examples/official-site/sqlpage/migrations/20_variables_function.sql b/examples/official-site/content/functions/variables.md similarity index 57% rename from examples/official-site/sqlpage/migrations/20_variables_function.sql rename to examples/official-site/content/functions/variables.md index 792285695..a7c48f161 100644 --- a/examples/official-site/sqlpage/migrations/20_variables_function.sql +++ b/examples/official-site/content/functions/variables.md @@ -1,17 +1,19 @@ --- Insert the 'variables' function into sqlpage_functions table -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" -) -VALUES ( - 'variables', - '0.15.0', - 'variable', - 'Returns a JSON string containing variables from the HTTP request and user-defined variables. - -The [database''s json handling functions](/blog?post=JSON+in+SQL%3A+A+Comprehensive+Guide) can then be used to process the data. +--- +icon: variable +since: 0.15.0 +category: request-data +summary: Read request or page variables as a JSON object. +parameters: + - name: method + type: TEXT + description: 'Optional. Filter variables by source: ''get'' (URL parameters), ''post'' (form data), or + ''set'' (user-defined variables). When not provided, all variables are returned with SET variables taking + precedence over request parameters.' +--- + +Returns a JSON string containing variables from the HTTP request and user-defined variables. + +The [database's json handling functions](/blog?post=JSON+in+SQL%3A+A+Comprehensive+Guide) can then be used to process the data. ## Variable Types @@ -26,9 +28,9 @@ For more information about SQLPage variables, see the [*SQL in SQLPage* guide](/ ## Usage - `sqlpage.variables()` - returns all variables (GET, POST, and SET combined). When multiple variables of the same name are present, the order of precedence is: set > post > get. -- `sqlpage.variables(''get'')` - returns only URL parameters -- `sqlpage.variables(''post'')` - returns only POST form data -- `sqlpage.variables(''set'')` - returns only user-defined variables created with `SET` +- `sqlpage.variables('get')` - returns only URL parameters +- `sqlpage.variables('post')` - returns only POST form data +- `sqlpage.variables('set')` - returns only user-defined variables created with `SET` When a SET variable has the same name as a GET or POST variable, the SET variable takes precedence in the combined result. @@ -39,13 +41,13 @@ When a SET variable has the same name as a GET or POST variable, the SET variabl We can create a form which has a field for each value in a given table like this: ```sql -select ''form'' as component, ''handle_survey_answer.sql'' as action; +select 'form' as component, 'handle_survey_answer.sql' as action; select question_id as name, question_text as label from survey_questions; ``` ### Handling form responses using `sqlpage.variables` -In `handle_survey_answer.sql`, one can process the form results even if we don''t know in advance +In `handle_survey_answer.sql`, one can process the form results even if we don't know in advance how many fields it contains. The function to parse JSON data varies depending on the database engine you use. @@ -54,7 +56,7 @@ In SQLite, one can use [`json_each`](https://www.sqlite.org/json1.html#jeach) : ```sql insert into survey_answers(question_id, answer) -select "key", "value" from json_each(sqlpage.variables(''post'')) +select "key", "value" from json_each(sqlpage.variables('post')) ``` #### In Postgres @@ -64,7 +66,7 @@ Postgres has [`json_each_text`](https://www.postgresql.org/docs/9.3/functions-js ```sql INSERT INTO survey_answers (question_id, answer) SELECT key AS question_id, value AS answer -FROM json_each_text(sqlpage.variables(''post'')::json); +FROM json_each_text(sqlpage.variables('post')::json); ``` @@ -73,7 +75,7 @@ FROM json_each_text(sqlpage.variables(''post'')::json); ```sql INSERT INTO survey_answers SELECT [key] AS question_id, [value] AS answer -FROM OPENJSON(sqlpage.variables(''post'')); +FROM OPENJSON(sqlpage.variables('post')); ``` #### In MySQL @@ -88,32 +90,12 @@ SELECT question_id, json_unquote( json_extract( - sqlpage.variables(''post''), - concat(''$."'', question_id, ''"'') + sqlpage.variables('post'), + concat('$."', question_id, '"') ) ) FROM json_table( - json_keys(sqlpage.variables(''post'')), - ''$[*]'' columns (question_id int path ''$'') + json_keys(sqlpage.variables('post')), + '$[*]' columns (question_id int path '$') ) as question_ids ``` - -' -); - --- Insert the parameters for the 'variables' function into sqlpage_function_parameters table --- Parameter 1: 'method' parameter -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" -) -VALUES ( - 'variables', - 1, - 'method', - 'Optional. Filter variables by source: ''get'' (URL parameters), ''post'' (form data), or ''set'' (user-defined variables). When not provided, all variables are returned with SET variables taking precedence over request parameters.', - 'TEXT' -); diff --git a/examples/official-site/content/functions/version.md b/examples/official-site/content/functions/version.md new file mode 100644 index 000000000..4a5327aaa --- /dev/null +++ b/examples/official-site/content/functions/version.md @@ -0,0 +1,8 @@ +--- +icon: git-commit +since: 0.11.0 +category: server-and-runtime +summary: Read the version of SQLPage serving the page. +--- + +Returns the current version of SQLPage as a string. diff --git a/examples/official-site/content/functions/web_root.md b/examples/official-site/content/functions/web_root.md new file mode 100644 index 000000000..e56340181 --- /dev/null +++ b/examples/official-site/content/functions/web_root.md @@ -0,0 +1,30 @@ +--- +icon: folder-code +since: 0.42.0 +category: server-and-runtime +summary: Locate the directory that holds the site's public files. +--- + +Returns the web root directory where SQLPage serves `.sql` files from. + +### Example + +```sql +SELECT 'text' AS component; +SELECT 'SQL files are served from ' AS contents; +SELECT sqlpage.web_root() as contents, true as code; +``` + +#### Result + +SQL files are served from `/home/user/my_sqlpage_website` + +#### Notes + +The web root is the directory from which `.sql` files are loaded and served. +By default, it is the current working directory, but it can be changed using: + - the `--web-root` command line argument + - the `web_root` [configuration option](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) in `sqlpage.json` + - the `WEB_ROOT` environment variable + +This is more reliable than `sqlpage.current_working_directory()` when you need to reference the location of your SQL files. diff --git a/examples/official-site/content/guides.yaml b/examples/official-site/content/guides.yaml new file mode 100644 index 000000000..025aef47f --- /dev/null +++ b/examples/official-site/content/guides.yaml @@ -0,0 +1,28 @@ +- sort_order: 1 + title: Your first website + link: /your-first-sql-website/ + description: Install SQLPage and build a website from a SQL file. +- sort_order: 2 + title: SQL and variables + link: /extensions-to-sql.sql + description: Read request parameters, set variables, and call SQLPage functions. +- sort_order: 3 + title: Custom components + link: /custom_components.sql + description: Render your own HTML with Handlebars templates. +- sort_order: 4 + title: Database migrations + link: /your-first-sql-website/migrations.sql + description: Create and update your database schema with versioned SQL files. +- sort_order: 5 + title: Custom URLs + link: /your-first-sql-website/custom_urls.sql + description: Give your pages readable URLs and route requests to SQL files. +- sort_order: 6 + title: Reverse proxy + link: /your-first-sql-website/nginx.sql + description: Serve your site with Nginx and HTTPS. +- sort_order: 7 + title: Managed hosting + link: /your-first-sql-website/hosted.sql + description: Try SQLPage online or publish your website with DataPage. diff --git a/examples/official-site/content/projects.yaml b/examples/official-site/content/projects.yaml new file mode 100644 index 000000000..2dcd2f96a --- /dev/null +++ b/examples/official-site/content/projects.yaml @@ -0,0 +1,68 @@ +- title: Advanced Authentication + folder: user-authentication + db_engine: postgres + description: Build a secure user authentication system with login, signup, and in-database session management. +- title: Authenticated CRUD + folder: CRUD - Authentication + db_engine: sqlite + description: Complete Create-Read-Update-Delete operations with user authentication. +- title: Image Gallery + folder: image gallery with user uploads + db_engine: sqlite + description: Create an image gallery with user uploads and session management. +- title: Developer UI + folder: SQLPage developer user interface + db_engine: postgres + description: A web-based interface for managing SQLPage files and database tables. +- title: Corporate Game + folder: corporate-conundrum + db_engine: sqlite + description: An interactive multiplayer board game with real-time updates. +- title: Roundest Pokemon + folder: roundest_pokemon_rating + db_engine: sqlite + description: Demo app with a distinct non-default design, using custom HTML templates for everything. +- title: Todo Application + folder: todo application (PostgreSQL) + db_engine: postgres + description: A full-featured todo list application with PostgreSQL backend. +- title: MySQL & JSON + folder: mysql json handling + db_engine: mysql + description: Learn advanced JSON manipulation in MySQL to build advanced SQLPage applications. +- title: Apache Web Server + folder: web servers - apache + db_engine: mysql + description: Use an existing Apache httpd Web Server to expose your SQLPage application. +- title: Sending Emails + folder: sending emails + db_engine: sqlite + description: Use the fetch function to send emails (or interact with any other HTTP API). +- title: Simple Website + folder: simple-website-example + db_engine: sqlite + description: Basic website example with navigation and data management. +- title: Geographic App + folder: PostGIS - using sqlpage with geographic data + db_engine: postgres + description: Use SQLPage to create and manage geodata. +- title: Multi-step form + folder: forms-with-multiple-steps + db_engine: sqlite + description: Guide to the implementation of forms that spread over multiple pages. +- title: Custom HTML & JS + folder: custom form component + db_engine: mysql + description: Building a custom form component with a dynamic widget using HTML and javascript. +- title: Splitwise Clone + folder: splitwise + db_engine: sqlite + description: An expense tracker app to split expenses with your friends, with nice debt charts. +- title: Advanced Forms with MS SQL Server + folder: microsoft sql server advanced forms + db_engine: sql server + description: Forms with multi-value dropdowns, using SQL Server and its JSON functions. +- title: Rich Text Editor + folder: rich-text-editor + db_engine: sqlite + description: A rich text editor with bold, italic, lists, images, and more. It posts its contents as Markdown. diff --git a/examples/official-site/content/shared-parameters.yaml b/examples/official-site/content/shared-parameters.yaml new file mode 100644 index 000000000..573207c8c --- /dev/null +++ b/examples/official-site/content/shared-parameters.yaml @@ -0,0 +1,10 @@ +id: + name: id + type: TEXT + description: id attribute added to the container in HTML. It can be used to target this item through css + or for scrolling to this item through links (use "#id" in link url). +class: + name: class + type: TEXT + description: class attribute added to the container in HTML. It can be used to apply custom styling to this + item through css. Added in v0.18.0. diff --git a/examples/official-site/documentation.sql b/examples/official-site/documentation.sql index 58a8074a4..92017596d 100644 --- a/examples/official-site/documentation.sql +++ b/examples/official-site/documentation.sql @@ -29,6 +29,8 @@ select case kind when 'component' then 'Components' else 'Functions' end as titl (kind = 'function' and name in ('fetch', 'link', 'run_sql', 'variables')) ) as links from reference_entry group by kind order by kind; +select 'Configuration' as title, 'settings' as icon, '/configuration' as link, + 'Look up server settings, accepted values, and defaults.' as description; select 'title' as component, 'Anatomy of a SQL page' as contents, 2 as level, 'how-it-works' as id; select 'text' as component, 'Each SQL file is a page. Its first SELECT names a component and sets its top-level parameters. The rows returned by the next SELECT supply the row-level parameters. This list uses both.' as contents; diff --git a/examples/official-site/llms.txt.sql b/examples/official-site/llms.txt.sql index 106080336..a88439718 100644 --- a/examples/official-site/llms.txt.sql +++ b/examples/official-site/llms.txt.sql @@ -51,7 +51,7 @@ Key features: - [Components reference](/components.sql): List of all ' || (select count(*) from component) || ' built-in UI components with parameters and examples - [Functions reference](/functions.sql): SQLPage built-in functions for handling requests, encoding data, and more -- [Configuration guide](https://github.com/sqlpage/SQLPage/blob/main/configuration.md): Complete list of configuration options in sqlpage.json +- [Configuration reference](/configuration): Accepted values and defaults for SQLPage server settings ## Components diff --git a/examples/official-site/safety.sql b/examples/official-site/safety.sql index 2ba06a7fc..8522ed1cb 100644 --- a/examples/official-site/safety.sql +++ b/examples/official-site/safety.sql @@ -144,7 +144,7 @@ For more information, see the [this discussion](https://github.com/sqlpage/SQLPa ## Database connections SQLPage uses a fixed pool of database connections, and will never open more connections than the ones you -[configured](https://github.com/sqlpage/SQLPage/blob/main/configuration.md). So even under heavy load, your database +[configured](/configuration#max_database_pool_connections). So even under heavy load, your database connection limit will never be saturated by SQLPage. And SQLPage will accept any restriction you put on the database user you use to connect to your database, so you can diff --git a/examples/official-site/search.sql b/examples/official-site/search.sql index eede7173a..a367e5891 100644 --- a/examples/official-site/search.sql +++ b/examples/official-site/search.sql @@ -7,6 +7,9 @@ where name = lower($search) or (kind = 'function' and lower($search) in ( )) order by kind limit 1; +select 'redirect' as component, '/configuration#' || name as link +from config_option where name = lower($search); + select 'shell-docs' as component, 'Search' as section, coalesce($search || ' | ', '') || 'SQLPage documentation search' as title; @@ -17,7 +20,10 @@ set escaped_search = '"' || replace(coalesce($search, ''), '"', '""') || '"'; with matches as ( select title, trim(description, char(13) || char(10) || ' ') as summary, page, parameters, fragment, rank, - row_number() over (partition by page, parameters order by rank, rowid) as position + row_number() over ( + partition by page, parameters, case when page = '/configuration' then fragment end + order by rank, rowid + ) as position from documentation_fts where documentation_fts match $escaped_search ) diff --git a/examples/official-site/sqlpage/migrations/01_documentation.sql b/examples/official-site/sqlpage/migrations/01_documentation.sql deleted file mode 100644 index 98b72ab0e..000000000 --- a/examples/official-site/sqlpage/migrations/01_documentation.sql +++ /dev/null @@ -1,1771 +0,0 @@ -CREATE TABLE component( - name TEXT PRIMARY KEY, - description TEXT NOT NULL, - icon TEXT, -- icon name from tabler icon - introduced_in_version TEXT -); - -CREATE TABLE parameter_type( - name TEXT PRIMARY KEY -); -INSERT INTO parameter_type(name) VALUES - ('BOOLEAN'), ('COLOR'), ('HTML'), ('ICON'), ('INTEGER'), ('JSON'), ('REAL'), ('TEXT'), ('TIMESTAMP'), ('URL'); - -CREATE TABLE parameter( - top_level BOOLEAN DEFAULT FALSE, - name TEXT, - component TEXT REFERENCES component(name) ON DELETE CASCADE, - description TEXT, - description_md TEXT, - type TEXT REFERENCES parameter_type(name) ON DELETE CASCADE, - optional BOOLEAN DEFAULT FALSE, - PRIMARY KEY (component, top_level, name) -); - -CREATE TABLE example( - component TEXT REFERENCES component(name) ON DELETE CASCADE, - description TEXT, - properties JSON, - FOREIGN KEY (component) REFERENCES component(name) ON DELETE CASCADE -); - --- The reference shows the SQL and renders the same stored component rows. --- Arrays with several items become repeated column aliases, as in handwritten SQLPage files. -CREATE VIEW example_with_source AS -SELECT example.rowid AS example_id, - row_number() OVER (PARTITION BY component ORDER BY example.rowid) AS example_number, - example.*, - (SELECT group_concat('select' || char(10) || ( - WITH fields AS ( - SELECT field.key AS name, coalesce(item.type, field.type) AS type, - CASE WHEN item.key IS NULL THEN field.value ELSE item.value END AS value - FROM json_each(statement.value) AS field - LEFT JOIN json_each( - CASE WHEN field.type = 'array' AND json_array_length(field.value) > 1 THEN field.value END - ) AS item ON true - ) - SELECT group_concat(' ' || CASE type - WHEN 'true' THEN 'TRUE' - WHEN 'false' THEN 'FALSE' - WHEN 'array' THEN 'JSON(' || quote(value) || ')' - WHEN 'object' THEN 'JSON(' || quote(value) || ')' - ELSE quote(value) - END || format(' as "%w"', name), ',' || char(10)) - FROM fields - ) || ';', char(10) || char(10)) FROM json_each(example.properties) AS statement) AS source -FROM example; - -INSERT INTO component(name, icon, description) VALUES - ('list', 'list', 'A vertical list of items. Each item can be clickable and link to another page.'); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'list', * FROM (VALUES - -- top level - ('title', 'Text header at the top of the list.', 'TEXT', TRUE, TRUE), - ('empty_title', 'Title text to display if the list is empty.', 'TEXT', TRUE, TRUE), - ('empty_description', 'Description to display if the list is empty.', 'TEXT', TRUE, TRUE), - ('empty_description_md', 'Description to display if the list is empty, in Markdown format.', 'TEXT', TRUE, TRUE), - ('empty_link', 'URL to which the user should be taken if they click on the empty list.', 'URL', TRUE, TRUE), - ('compact', 'Whether to display the list in a more compact format, allowing more items to be displayed on the screen.', 'BOOLEAN', TRUE, TRUE), - ('wrap', 'Wrap list items onto multiple lines if they are too long', 'BOOLEAN', TRUE, TRUE), - -- item level - ('title', 'Name of the list item, displayed prominently.', 'TEXT', FALSE, FALSE), - ('description', 'A description of the list item, displayed as greyed-out text.', 'TEXT', FALSE, TRUE), - ('description_md', 'A description of the list item, displayed as greyed-out text, in Markdown format, allowing you to use rich text formatting, including `**bold**` and `*italic*` text.', 'TEXT', FALSE, TRUE), - ('link', 'An URL to which the user should be taken when they click on the list item.', 'URL', FALSE, TRUE), - ('icon', 'Name of an icon to display on the left side of the item.', 'ICON', FALSE, TRUE), - ('image_url', 'The URL of a small image to display on the left side of the item.', 'URL', FALSE, TRUE), - ('color', 'The name of a color, to be displayed as a dot near the list item contents.', 'COLOR', FALSE, TRUE), - ('active', 'Whether this item in the list is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE), - ('view_link', 'A URL to which the user should be taken when they click on the "view" icon. Does not show the icon when omitted.', 'URL', FALSE, TRUE), - ('edit_link', 'A URL to which the user should be taken when they click on the "edit" icon. Does not show the icon when omitted.', 'URL', FALSE, TRUE), - ('delete_link', 'A page that will be loaded when the user clicks on the delete button for this specific item. The link will be submitted as a POST request.', 'URL', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('list', 'A basic compact list', json('[{"component":"list", "compact": true, "title": "SQLPage lists are..."},{"title":"Beautiful"},{"title":"Useful"},{"title":"Versatile"}]')), - ('list', 'An empty list with a link to add an item', json('[{"component":"list", "empty_title": "No items yet", "empty_description": "This list is empty. Click here to create a new item !", "empty_link": "documentation.sql"}]')), - ('list', ' -### A list with rich text descriptions - -This example illustrates creating a nice list where each item has a title, a description, an image, and a link to another page. - -> Be careful, nested links are not supported. If you use the list''s `link` property, then your markdown `description_md` should not contain any link. -', json('[{"component":"list", "wrap": true}, - {"title":"SQL Websites", "image_url": "/favicon.ico", "description_md":"Write SQL, get a website. SQLPage is a **SQL**-based **site** generator for **PostgreSQL**, **MySQL**, **SQLite** and **SQL Server**.", "link": "/"}, - {"title":"SQL Forms", "image_url": "https://upload.wikimedia.org/wikipedia/commons/b/b6/FileStack_retouched.jpg", "description_md":"Easily collect data **from users to your database** using the *form* component. Handle the data in SQL with `INSERT` or `UPDATE` queries.", "link": "?component=form"}, - {"title":"SQL Maps", "image_url": "https://upload.wikimedia.org/wikipedia/commons/1/15/Vatican_City_map_EN.png", "description_md":"Show database contents on a map using the *map* component. Works well with *PostGIS* and *SpatiaLite*.", "link": "?component=map"}, - {"title":"Advanced features", "icon": "settings", "description_md":"[Authenticate users](?component=authentication), [edit data](?component=form), [generate an API](?component=json), [maintain your database schema](/your-first-sql-website/migrations.sql), and more."} - ]')), - ('list', 'A beautiful list with bells and whistles.', - json('[{"component":"list", "title":"Top SQLPage features", "compact": true }, - {"title":"Authentication", "link":"?component=authentication", "description": "Authenticate users with a login form or HTTP basic authentication", "color": "red", "icon":"lock", "active": true, "view_link": "?component=authentication#view" }, - {"title":"Editing data", "link":"?component=form", "description": "SQLPage makes it easy to UPDATE, INSERT and DELETE data in your database tables", "color": "blue", "icon":"database", "edit_link": "?component=form#edit", "delete_link": "?component=form#delete" }, - {"title":"API", "link":"?component=json", "description": "Generate a REST API from a single SQL query to connect with other applications and services", "color": "green", "icon":"plug-connected", "edit_link": "?component=json#edit", "delete_link": "?component=json#delete" } - ]')); - -INSERT INTO component(name, icon, description) VALUES - ('datagrid', 'grid-dots', 'Display small pieces of information in a clear and readable way. Each item has a name and is associated with a value.'); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'datagrid', * FROM (VALUES - -- top level - ('title', 'Text header at the top of the data grid.', 'TEXT', TRUE, TRUE), - ('description', 'A short paragraph displayed below the title.', 'TEXT', TRUE, TRUE), - ('description_md', 'A short paragraph displayed below the title - formatted using markdown.', 'TEXT', TRUE, TRUE), - ('icon', 'Name of an icon to display on the left side of the title.', 'ICON', TRUE, TRUE), - ('image_url', 'URL of an image to display on the left side of the title.', 'URL', TRUE, TRUE), - -- item level - ('title', 'Name of the piece of information.', 'TEXT', FALSE, FALSE), - ('description', 'Value to display below the name.', 'TEXT', FALSE, TRUE), - ('footer', 'Muted text to display below the value.', 'TEXT', FALSE, TRUE), - ('image_url', 'URL of a small image (such as an avatar) to display on the left side of the value.', 'URL', FALSE, TRUE), - ('link', 'A target URL to which the user should be taken when they click on the value.', 'URL', FALSE, TRUE), - ('icon', 'An icon name (from tabler-icons.io) to display on the left side of the value.', 'ICON', FALSE, TRUE), - ('color', 'If set to a color name, the value will be displayed in a pill of that color.', 'COLOR', FALSE, TRUE), - ('active', 'Whether this item in the grid is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE), - ('tooltip', 'A tooltip to display when the user passes their mouse over the value.', 'TEXT', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('datagrid', 'Just some sections of information.', json('[{"component":"datagrid"},{"title":"Language","description":"SQL"},{"title":"Creation date","description":"1974"}, {"title":"Language family","description":"Query language"}]')), - ('datagrid', 'A beautiful data grid with nice colors and icons.', - json('[{"component":"datagrid", "title": "Ophir Lojkine", "image_url": "https://avatars.githubusercontent.com/u/552629", "description_md": "Member since **2021**"}, - {"title": "Pseudo", "description": "lovasoa", "image_url": "https://avatars.githubusercontent.com/u/552629" }, - {"title": "Status", "description": "Active", "color": "green"}, - {"title": "Email Status", "description": "Validated", "icon": "check", "active": true, "tooltip": "Email address has been validated."}, - {"title": "Personal page", "description": "ophir.dev", "link": "https://ophir.dev/", "tooltip": "About me"} - ]')), - ('datagrid', 'Using a picture in the data grid card header.', json('[ - {"component":"datagrid", "title": "Website Ideas", "icon": "bulb"}, - {"title": "Search engine", "link":"https://google.com", "description": "Google", "color": "red", "icon":"brand-google", "footer": "Owned by Alphabet Inc."}, - {"title": "Encyclopedia", "link":"https://wikipedia.org", "description": "Wikipedia", "color": "blue", "icon":"world", "footer": "Owned by the Wikimedia Foundation"} - ]')); - - -INSERT INTO component(name, icon, description) VALUES - ('steps', 'dots-circle-horizontal', 'Guide users through multi-stage processes, displaying a clear list of previous and future steps.'); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'steps', * FROM (VALUES - -- top level - ('color', 'Color of the bars displayed between steps.', 'COLOR', TRUE, TRUE), - ('counter', 'Display the number of the step on top of its name.', 'TEXT', TRUE, TRUE), - ('title', 'Title of the section.', 'TEXT', TRUE, TRUE), - ('description', 'Description of the section.', 'TEXT', TRUE, TRUE), - -- item level - ('title', 'Name of the step.', 'TEXT', FALSE, TRUE), - ('description', 'Tooltip to display when the user passes their mouse over the step''s name.', 'TEXT', FALSE, TRUE), - ('link', 'A target URL to which the user should be taken when they click on the step.', 'URL', FALSE, TRUE), - ('icon', 'An icon name (from tabler-icons.io) to display on the left side of the step name.', 'ICON', FALSE, TRUE), - ('active', 'Whether this item in the grid is considered "active". Active items are displayed more prominently.', 'BOOLEAN', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('steps', 'Online store checkout steps.', json('[{"component":"steps"},{"title":"Shopping"},{"title":"Store pickup"}, {"title":"Payment","active":true},{"title":"Review & Order"}]')), - ('steps', 'A progress indicator with custom color, auto-generated step numbers, icons, and description tooltips.', - json('[{"component":"steps", "counter": true, "color":"purple"}, '|| - '{"title": "Registration form", "icon":"forms", "link": "https://github.com/sqlpage/SQLPage", "description": "Initial account data creation."},' || - '{"title": "Email confirmation", "icon": "mail", "link": "https://sql-page.com", "description": "Confirm your email by clicking on a link in a validation email."},' || - '{"title": "ID verification", "description": "Checking personal information", "icon": "user", "link": "#"},' || - '{"title": "Final account approval", "description": "ophir.dev", "link": "https://ophir.dev/", "icon":"eye-check", "active": true},' || - '{"title":"Account creation", "icon":"check"}]')); - -INSERT INTO component(name, icon, description) VALUES - ('text', 'align-left', 'A paragraph of text. The entire component will render as a single paragraph, with each item being rendered as a span of text inside it, the styling of which can be customized using parameters.'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'text', * FROM (VALUES - -- top level - ('title', 'Text header before the paragraph.', 'TEXT', TRUE, TRUE), - ('center', 'Whether to center the title.', 'BOOLEAN', TRUE, TRUE), - ('html', 'Raw html code to include on the page. Don''t use that if you are not sure what you are doing, it may have security implications.', 'TEXT', TRUE, TRUE), - ('contents', 'A top-level paragraph of text to display, without any formatting, without having to make additional queries.', 'TEXT', TRUE, TRUE), - ('contents_md', 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.', 'TEXT', TRUE, TRUE), - ('article', 'Makes long texts more readable by increasing the line height, adding margins, using a serif font, and decorating the initial letter.', 'BOOLEAN', TRUE, TRUE), - -- item level - ('contents', 'A span of text to display', 'TEXT', FALSE, FALSE), - ('contents_md', 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.', 'TEXT', FALSE, TRUE), - ('link', 'An URL to which the user should be taken when they click on this span of text.', 'URL', FALSE, TRUE), - ('color', 'The name of a color for this span of text.', 'COLOR', FALSE, TRUE), - ('underline', 'Whether the span of text should be underlined.', 'BOOLEAN', FALSE, TRUE), - ('bold', 'Whether the span of text should be displayed as bold.', 'BOOLEAN', FALSE, TRUE), - ('code', 'Use a monospace font. Useful to display the text as code.', 'BOOLEAN', FALSE, TRUE), - ('italics', 'Whether the span of text should be displayed as italics.', 'BOOLEAN', FALSE, TRUE), - ('break', 'Indicates that the current span of text starts a new paragraph.', 'BOOLEAN', FALSE, TRUE), - ('size', 'A number between 1 and 6 indicating the font size.', 'INTEGER', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('text', 'Rendering a simple text paragraph.', json('[{"component":"text", "contents":"Hello, world ! <3"}]')), - ('text', 'Rendering rich text using markdown', json('[{"component":"text", "article": true, "contents_md":"\n'|| - '# Markdown in SQLPage\n\n' || - '## Simple formatting\n\n' || - 'SQLPage supports only plain text as column values, but markdown allows easily adding **bold**, *italics*, [external links](https://github.com/sqlpage/SQLPage), [links to other pages](/index.sql) and [intra-page links](#my-paragraph). \n\n' || - '## Lists\n' || - '### Unordered lists\n' || - '* SQLPage is easy\n' || - '* SQLPage is fun\n' || - '* SQLPage is free\n\n' || - '### Ordered lists\n' || - '1. SQLPage is fast\n' || - '2. SQLPage is safe\n' || - '3. SQLPage is open-source\n\n' || - '## Code\n' || - '```sql\n' || - 'SELECT ''list'' AS component;\n' || - 'SELECT name as title FROM users;\n' || - '```\n\n' || - '## Tables\n\n' || - '| SQLPage component | Description | Documentation link |\n' || - '| --- | --- | --- |\n' || - '| text | A paragraph of text. | [Documentation](https://sql-page.com/documentation.sql?component=text) |\n' || - '| list | A list of items. | [Documentation](https://sql-page.com/documentation.sql?component=list) |\n' || - '| steps | A progress indicator. | [Documentation](https://sql-page.com/documentation.sql?component=steps) |\n' || - '| form | A series of input fields. | [Documentation](https://sql-page.com/documentation.sql?component=form) |\n\n' || - '## Quotes\n' || - '> Fantastic.\n>\n' || - '> — [HackerNews User](https://news.ycombinator.com/item?id=36194473#36209061) about SQLPage\n\n' || - '## Images\n' || - '![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', ' -When ``method="post"``, this specifies how the form-data should be encoded -when submitting it to the server. -', 'TEXT', TRUE, TRUE), - -- item level - ('formenctype', ' -When ``type`` is ``submit`` or ``image``, this specifies how the form-data -should be encoded when submitting it to the server. - -Takes precedence over any ``enctype`` set on the ``form`` element. - -NOTE: when a ``file`` type input is present, then ``formenctype="multipart/form-data"`` -is automatically applied to the default validate button. -', 'TEXT', FALSE, TRUE) -); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'form', * FROM (VALUES - -- top level - ('method', 'Set this to ''GET'' to pass the form contents directly as URL parameters. If the user enters a value v in a field named x, submitting the form will load target.sql?x=v. If target.sql contains SELECT $x, it will display the value v.', 'TEXT', TRUE, TRUE), - ('action', 'An optional link to a target page that will handle the results of the form. By default the target page is the current page with the id of the form (if passed) used as hash - this will bring us back to the location of the form after submission. Setting it to the name of a different sql file will load that file when the user submits the form.', 'TEXT', TRUE, TRUE), - ('title', 'A name to display at the top of the form. It will be displayed in a larger font size at the top of the form.', 'TEXT', TRUE, TRUE), - ('validate', 'The text to display in the button at the bottom of the form that submits the values. Omit this property to let the browser display the default form validation text, or set it to the empty string to remove the button completely.', 'TEXT', TRUE, TRUE), - ('validate_color', 'The color of the button at the bottom of the form that submits the values. Omit this property to use the default color.', 'COLOR', TRUE, TRUE), - ('validate_outline', 'A color to outline the validation button.', 'COLOR', TRUE, TRUE), - ('validate_shape', 'The shape of the validation button (e.g., pill, square).', 'TEXT', TRUE, TRUE), - ('validate_size', 'The size of the validation button (e.g., sm, lg).', 'TEXT', TRUE, TRUE), - ('reset', 'The text to display in the button at the bottom of the form that resets the form to its original state. Omit this property not to show a reset button at all.', 'TEXT', TRUE, TRUE), - ('id', 'A unique identifier for the form, which can then be used to validate the form from a button outside of the form.', 'TEXT', TRUE, TRUE), - ('auto_submit', 'Automatically submit the form when the user changes any of its fields, and remove the validation button.', 'BOOLEAN', TRUE, TRUE), - ('validate_icon', 'Name of an icon to be displayed on the left side of the submit button.', 'ICON', TRUE, TRUE), - ('reset_icon', 'Name of an icon to be displayed on the left side of the reset button.', 'ICON', TRUE, TRUE), - ('reset_color', 'The color of the button at the bottom of the form that resets the form to its original state. Omit this property to use the default color.', 'COLOR', TRUE, TRUE), - ('reset_outline', 'A color to outline the reset button.', 'COLOR', TRUE, TRUE), - ('reset_shape', 'The shape of the reset button (e.g., pill, square).', 'TEXT', TRUE, TRUE), - ('reset_size', 'The size of the reset button (e.g., sm, lg).', 'TEXT', TRUE, TRUE), - ('narrow', 'Whether to trim the horizontal padding between the icon and the label of the validation and reset buttons.', 'BOOLEAN', TRUE, TRUE), - -- item level - ('type', 'Declares input control behavior and expected format. All HTML input types are supported (text, number, date, file, checkbox, radio, hidden, ...). SQLPage adds some custom types: textarea, switch, header. text by default. See https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#input_types', 'TEXT', FALSE, TRUE), - ('name', 'The name of the input field, that you can use in the target page to get the value the user entered for the field.', 'TEXT', FALSE, FALSE), - ('label', 'A friendly name for the text field to show to the user.', 'TEXT', FALSE, TRUE), - ('placeholder', 'A placeholder text that will be shown in the field when is is empty.', 'TEXT', FALSE, TRUE), - ('value', 'A default value that will already be present in the field when the user loads the page.', 'TEXT', FALSE, TRUE), - ('options', 'A json array of objects containing the label and value of initial options of a select field. Used only when type=select. JSON objects in the array can contain the properties "label", "value" and "selected".', 'JSON', FALSE, TRUE), - ('options_source', 'Only for inputs of type `select`. URL of a SQL file that returns JSON search results for the dropdown. The SQL file receives the search text as `$search` and must return an array of objects with exactly `label` and `value`. Use `options` for options that should be available before the user searches.', 'URL', FALSE, TRUE), - ('required', 'Set this to true to prevent the form contents from being sent if this field is left empty by the user.', 'BOOLEAN', FALSE, TRUE), - ('min', 'The minimum value to accept for an input of type number', 'REAL', FALSE, TRUE), - ('max', 'The maximum value to accept for an input of type number', 'REAL', FALSE, TRUE), - ('checked', 'Used only for checkboxes and radio buttons. Indicates whether the checkbox should appear as already checked.', 'BOOLEAN', FALSE, TRUE), - ('multiple', 'For select elements, indicates that multiple elements can be selected simultaneously. When using multiple, you should add square brackets after the variable name: ''my_variable[]'' as name. For file inputs, lets the user select several files at once: save them all with [sqlpage.persist_uploaded_files](functions.sql?function=persist_uploaded_files).', 'BOOLEAN', FALSE, TRUE), - ('empty_option', 'Only for inputs of type `select`. Adds an empty option with the given label before the ones defined in `options`. Useful when generating other options from a database table.', 'TEXT', FALSE, TRUE), - ('searchable', 'For select and multiple-select elements, displays them with a nice dropdown that allows searching for options.', 'BOOLEAN', FALSE, TRUE), - ('dropdown', 'An alias for "searchable".', 'BOOLEAN', FALSE, TRUE), - ('create_new', 'In a select with a dropdown (`searchable`, `dropdown` or `options_source`), this option allows the user to enter new values, that are not in the list of options. Works for single selects and for multiselects.', 'BOOLEAN', FALSE, TRUE), - ('step', 'The increment of values in an input of type number. Set to 1 to allow only integers.', 'REAL', FALSE, TRUE), - ('description', 'A helper text to display near the input field.', 'TEXT', FALSE, TRUE), - ('description_md', 'A helper text to display near the input field - formatted using markdown.', 'TEXT', FALSE, TRUE), - ('pattern', 'A regular expression that the value must match. For instance, [0-9]{3} will only accept 3 digits.', 'TEXT', FALSE, TRUE), - ('autofocus', 'Automatically focus the field when the page is loaded', 'BOOLEAN', FALSE, TRUE), - ('width', 'Width of the form field, between 1 and 12.', 'INTEGER', FALSE, TRUE), - ('autocomplete', 'Whether the browser should suggest previously entered values for this field.', 'BOOLEAN', FALSE, TRUE), - ('minlength', 'Minimum length of text allowed in the field.', 'INTEGER', FALSE, TRUE), - ('maxlength', 'Maximum length of text allowed in the field.', 'INTEGER', FALSE, TRUE), - ('formaction', 'When type is "submit", this specifies the URL of the file that will handle the form submission. Useful when you need multiple submit buttons.', 'TEXT', FALSE, TRUE), - ('formmethod', 'When type is "submit", the HTTP method to submit the form with. Takes precedence over the form''s own "method".', 'TEXT', FALSE, TRUE), - ('formnovalidate', 'When type is "submit", skips the browser''s validation of the other fields when this button submits the form.', 'BOOLEAN', FALSE, TRUE), - ('formtarget', 'When type is "submit", where to display the response. Takes the same values as a link target: "_blank" to open a new tab, "_self" to stay in the same one.', 'TEXT', FALSE, TRUE), - ('accept', 'Used only for inputs of type "file". A comma-separated list of the file types the user can pick, given as extensions (".pdf,.png") or as MIME types ("image/*").', 'TEXT', FALSE, TRUE), - ('list', 'The id of a datalist element holding the suggestions to show for this field. The datalist itself has to be rendered by the "html" component.', 'TEXT', FALSE, TRUE), - ('class', 'A CSS class to apply to the form element.', 'TEXT', FALSE, TRUE), - ('prefix_icon','Icon to display on the left side of the input field, on the same line.','ICON',FALSE,TRUE), - ('prefix','Text to display on the left side of the input field, on the same line.','TEXT',FALSE,TRUE), - ('suffix','Short text to display after th input, on the same line. Useful to add units or a currency symbol to an input.','TEXT',FALSE,TRUE), - ('readonly','Set to true to prevent the user from modifying the value of the input field.','BOOLEAN',FALSE,TRUE), - ('rows','Number of rows to display for a textarea. Defaults to 3.','INTEGER',FALSE,TRUE), - ('disabled','Makes the field non-editable, non-focusable, and not submitted with the form. Use readonly instead for simple non-editable fields.','BOOLEAN',FALSE,TRUE), - ('id','A unique identifier for the input, which can then be used to select and manage the field with Javascript code. Usefull for advanced using as setting client side event listeners, interactive control of input field (disabled, visibility, read only, e.g.) and AJAX requests.','TEXT',FALSE,TRUE) -) x; -INSERT INTO example(component, description, properties) VALUES - ( - 'form', - ' - -The best way to manage forms in SQLPage is to create at least two separate files: - - - one that will contain the form itself, and will be loaded when the user visits the page, - - one that will handle the form submission, and will redirect to whatever page you want to display after the form has been submitted. - -For instance, if you were creating a form to manage a list of users, you could create: - - - a file named `users.sql` that would contain a list of users and a form to create a new user, - - a file named `create_user.sql` that would insert the new user in the database, and then redirect to `users.sql`. - -`create_user.sql` could contain the following sql statement to [safely](safety.sql) insert the new user in the database: - -```sql -INSERT INTO users(name) VALUES(:username) -RETURNING ''redirect'' AS component, ''users.sql'' AS link -``` - -When loading the page, the value for `:username` will be `NULL` if no value has been submitted. -', - json('[{"component":"form", "action": "create_user.sql"}, {"name": "username"}]')), - ('form', 'A user registration form, illustrating the use of required fields, and different input types.', - json('[{"component":"form", "title": "User", "validate": "Create new user"}, '|| - '{"name": "First name", "placeholder": "John"}, '|| - '{"name": "Last name", "required": true, "description": "We need your last name for legal purposes."},'|| - '{"name": "Resume", "type": "textarea"},'|| - '{"name": "Birth date", "type": "date", "max": "2010-01-01", "value": "1994-04-16"},'|| - '{"name": "Password", "type": "password", "pattern": "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$", "required": true, "description_md": "**Password Requirements:** Minimum **8 characters**, at least **one letter** & **one number**. *Tip:* Use a passphrase for better security!"},'|| - '{"label": "I accept the terms and conditions", "name": "terms", "type": "checkbox", "required": true}'|| - ']')), - ('form','Create prepended and appended inputs to make your forms easier to use.', - json('[{"component":"form"}, '|| - '{"name": "Your account", "prefix_icon": "mail", "prefix": "Email:", "suffix": "@mydomain.com"}, ' || - ']')), - - ('form','With the header type, you can group your input fields based on a theme. For example, you can categorize fields according to a person''s identity and their contact information.', - json('[{"component":"form","title":"Information about the person"}, '|| - '{"type": "header", "label": "Identity"},' || - '{"name": "Name"},' || - '{"name": "Surname"},' || - '{"type": "header","label": "Contact"},' || - '{"name": "phone", "label": "Phone number"},' || - '{"name": "Email"},' || - ']')), - - ('form','A toggle switch in an HTML form is a user interface element that allows users to switch between two states, typically "on" and "off." It visually resembles a physical switch and is often used for settings or options that can be enabled or disabled.', - json('[{"component":"form"}, - {"type": "switch", "label": "Dark theme", "name": "dark", "description": "Enable dark theme"}, - {"type": "switch", "label": "A required toggle switch", "name": "my_checkbox", "required": true,"checked": true}, - {"type": "switch", "label": "A disabled toggle switch", "name": "my_field", "disabled": true} - ]')), - - ('form', 'This example illustrates the use of the `select` type. -In this select input, the various options are hardcoded, but they could also be loaded from a database table, -[using a function to convert the rows into a json array](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) like - - `json_group_array()` in SQLite, - - `json_agg()` in Postgres, - - `JSON_ARRAYAGG()` in MySQL, or - - `FOR JSON PATH` in Microsoft SQL Server. - - -In SQLite, the query would look like -```sql -SELECT - ''select'' as type, - ''Select a fruit...'' as empty_option, - ''cherry'' as prefix_icon, - json_group_array(json_object( - ''label'', name, - ''value'', id - )) as options -FROM fruits -``` -', json('[{"component":"form", "action":"examples/show_variables.sql"}, - {"name": "Fruit", "type": "select", - "empty_option": "Select a fruit...", - "options": - "[{\"label\": \"Orange\", \"value\": 0}, {\"label\": \"Apple\", \"value\": 1}, {\"label\": \"Banana\", \"value\": 3}]"} - ]')), - ('form', '### Multi-select -You can authorize the user to select multiple options by setting the `multiple` property to `true`. -This creates a more compact (but arguably less user-friendly) alternative to a series of checkboxes. -In this case, you should add square brackets to the name of the field (e.g. `''my_field[]'' as name`). -The target page will then receive the value as a JSON array of strings, which you can iterate over using - - the `json_each` function [in SQLite](https://www.sqlite.org/json1.html) and [Postgres](https://www.postgresql.org/docs/9.3/functions-json.html), - - the [`OPENJSON`](https://learn.microsoft.com/fr-fr/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16) function in Microsoft SQL Server. - - in MySQL, json manipulation is less straightforward: see [the SQLPage MySQL json example](https://github.com/sqlpage/SQLPage/tree/main/examples/mysql%20json%20handling) - -[More information on how to handle JSON in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). - -The target page could then look like this: - -```sql -insert into best_fruits(id) -- INSERT INTO ... SELECT ... runs the SELECT query and inserts the results into the table -select CAST(value AS integer) as id -- all values are transmitted by the browser as strings -from json_each($my_field); -- in SQLite, json_each returns a table with a "value" column for each element in the JSON array -``` - -### Example multiselect generated from a database table - -If you have a table of all possible options (`my_options(id int, label text)`), -and want to generate a multi-select field from it, you have two options: -- if the number of options is not too large, you can use the `options` parameter to return them all as a JSON array in the SQL query -- if the number of options is large (e.g. more than 1000), you can use `options_source` to load options dynamically from a different SQL query as the user types - -#### Embedding all options in the SQL query - -Let''s say you have a table that contains the selected options per user (`my_user_options(user_id int, option_id int)`). -You can use a query like this to generate the multi-select field: - -```sql -select ''select'' as type, true as multiple, json_group_array(json_object( - ''label'', my_options.label, - ''value'', my_options.id, - ''selected'', my_user_options.option_id is not null -)) as options -from my_options -left join my_user_options - on my_options.id = my_user_options.option_id - and my_user_options.user_id = $user_id -``` - -This will generate a json array of objects, each containing the label, value and selected status of each option. - -#### Loading options dynamically from a different SQL query with `options_source` - -If the `my_options` table has a large number of rows, you can use the `options_source` parameter to load options dynamically from a different SQL query as the user types. - -We''ll write a second SQL file, `options_source.sql`, that will receive the user''s search string as a parameter named `$search`, - and return a json array of objects, each containing the label and value of each option. - -When both `options` and `options_source` are set, the local `options` are loaded first. Search results from `options_source` are loaded into the same option list; a result with the same `value` updates the existing option. This is useful to set a default preselected value with `options_source`. - -`options_source` may already contain query parameters. SQLPage preserves them and adds or replaces the `search` parameter when loading options. - -##### `options_source.sql` - -```sql -select ''json'' as component; - -select id as value, label as label -from my_options -where label like $search || ''%''; -``` - -##### `form` - -', json('[{"component":"form", "action":"examples/show_variables.sql", "reset": "Reset"}, - {"name": "component", "type": "select", - "value": "form", - "options": [{"label": "Form", "value": "form"}], - "options_source": "examples/from_component_options_source.sql?category=component", - "description": "Start typing the name of a component like ''map'' or ''form''..." - }]')), - ('form', 'This example illustrates the use of the `radio` type. -The `name` parameter is used to group the radio buttons together. -The `value` parameter is used to set the value that will be submitted when the user selects the radio button. -The `label` parameter is used to display a friendly name for the radio button. -The `description` parameter is used to display a helper text near the radio button. - -We could also save all the options in a database table, and then run a simple query like - -```sql -SELECT ''form'' AS component; -SELECT - ''radio'' as type, - ''db'' as name, - option_name as label, - option_id as value -FROM my_options; -``` - -In this example, depending on what the user clicks, the page will be reloaded with a the variable `$component` set to the string "form", "map", or "chart". - - ', json('[{"component":"form", "method": "GET"}, - {"name": "component", "type": "radio", "value": "form", "description": "Read user input in SQL", "label": "Form"}, - {"name": "component", "type": "radio", "value": "map", "checked": true, "description": "Display a map based on database data", "label": "Map"}, - {"name": "component", "type": "radio", "value": "chart", "description": "Interactive plots of SQL query results", "label": "Chart"} - ]')), - ('form', ' -### Dynamically refresh the page when the user changes the form - -The form will be automatically submitted when the user changes any of its fields, and the page will be reloaded with the new value. -The validation button is removed. -', json('[{"component":"form", "auto_submit": true}, - {"name": "component", "type": "select", "autocomplete": false, "options": [ - {"label": "Form", "value": "form", "selected": true}, - {"label": "Map", "value": "map"}, - {"label": "Chart", "value": "chart"} - ], "description": "Choose a component to view its documentation. No need to click a button, the page will be reloaded automatically.", "label": "Component"} - ]')), - ('form', 'When you want to include some information in the form data, but not display it to the user, you can use a hidden field. - -This can be used to track simple data such as the current user''s id, -or to implement more complex flows, such as a multi-step form, -where the user is redirected to a different page after each step. - -This can also be used to implement [CSRF protection](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern), -if your website has authenticated users that can perform sensitive actions through simple links. -But note that SQLPage cookies already have the `SameSite=strict` attribute by default, which protects you against CSRF attacks by default in most cases. - -', json('[{"component":"form", "validate": "Delete", "validate_color": "red"}, - {"type": "hidden", "name": "resource_id", "value": "1234"}, - {"name": "confirm", "label": "Please type \"sensitive resource\" here to confirm the deletion", "required": true} - ]')), - ('form', 'This example illustrates the use of custom validation buttons and half-width fields.', - json('[{"component":"form", "title": "User", "validate": "Create new user", "validate_color": "green", "reset": "Clear"}, - {"name": "first_name", "label": "First name", "placeholder": "John", "width": 4}, - {"name": "middle_name", "label": "Middle name", "placeholder": "Fitzgerald", "width": 4}, - {"name": "last_name", "label": "Last name", "placeholder": "Doe", "width": 4}, - {"name": "email", "label": "Email", "placeholder": "john.doe@gmail.com", "width": 12}, - {"name": "password", "label": "Password", "type": "password", "width": 6}, - {"name": "password_confirmation", "label": "Password confirmation", "type": "password", "width": 6}, - {"name": "terms", "label": "I accept the terms and conditions", "type": "checkbox", "required": true} - ]')), - ('form', ' -## File upload - -You can use the `file` type to allow the user to upload a file. - -The file will be uploaded to the server, and you will be able to access it using the -[`sqlpage.uploaded_file_path`](functions.sql?function=uploaded_file_path#function) function. - -Here is how you could save the uploaded file to a table in the database: - -```sql -INSERT INTO uploaded_file(name, data) -VALUES ( - :filename, - sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''my_file'')) -) -``` -', - json('[{"component":"form", "enctype": "multipart/form-data", "title": "Upload a picture", "validate": "Upload", "action": "examples/handle_picture_upload.sql"}, - {"name": "my_file", "type": "file", "accept": "image/png, image/jpeg", "label": "Picture", "description": "Upload a small picture", "required": true} - ]')), - ('form', ' -## Form Encoding - -You can specify the way form data should be encoded by setting the `enctype` -top-level property on the form. - -You may also specify `formenctype` on `submit` and `image` type inputs. -This will take precedence over the `enctype` specified on the form and is -useful in the case there are multiple `submit` buttons on the form. -For example, an external site may have specific requirements on encoding type. - -As a rule of thumb, ``multipart/form-data`` is best when fields may contain -copious non-ascii characters or for binary data such as an image or a file. -However, ``application/x-www-form-urlencoded`` creates less overhead when -many short ascii text values are submitted. -', - json('[ - { - "component": "form", - "method": "post", - "enctype": "multipart/form-data", - "title": "Submit with different encoding types", - "validate": "Submit with form encoding type", - "action": "examples/handle_enctype.sql" - }, - {"name": "data", "type": "text", "label": "Data", "required": true}, - { - "name": "percent_encoded", - "type": "submit", - "label": "Submit as", - "width": 4, - "formaction": "examples/handle_enctype.sql", - "formenctype": "application/x-www-form-urlencoded", - "value": "application/x-www-form-urlencoded" - }, - { - "name": "multipart_form_data", - "type": "submit", - "label": "Submit as", - "width": 4, - "formaction": "examples/handle_enctype.sql", - "formenctype": "multipart/form-data", - "value": "multipart/form-data" - } -]')), - ('form', ' -## Bulk data insertion - -You can use the `file` type to allow the user to upload a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) -file containing data to insert in a table. - -SQLPage can load data from a CSV file and insert it into a database table. -SQLPage re-uses PostgreSQL''s [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html) -to specify the format of the CSV file, but makes it work with all supported databases. - -> When connected to a PostgreSQL database, SQLPage will use the native `COPY` statement, -> for super fast and efficient on-database CSV parsing. -> But it will also work transparently with other databases, by -> parsing the CSV locally and emulating the same behavior with simple `INSERT` statements. - -Here is how you could easily copy data from a CSV to a table in the database: - -```sql -copy product(name, description) from ''product_data_input'' -with (header true, delimiter '','', quote ''"''); -``` - -If you want to pre-process the data before inserting it into the final table, -you can use a temporary table to store the data, and then insert it into the final table: - -```sql --- temporarily store the data in a table with text columns -create temporary table if not exists product_tmp(name text, description text, price text); -delete from product_tmp; - --- copy the data from the CSV file into the temporary table -copy product_tmp(name, description, price) from ''product_data_input''; - --- insert the data into the final table, converting the price column to an integer -insert into product(name, description, price) -select name, description, CAST(price AS integer) from product_tmp -where price is not null and description is not null and length(description) > 10; -``` - -This will load the processed CSV into the product table, provided it has the following structure: - -```csv -name,description,price -"SQLPage","A tool to create websites using SQL",0 -"PostgreSQL","A powerful open-source relational database",0 -"SQLite","A lightweight relational database",0 -"MySQL","A popular open-source relational database",0 -``` -', - json('[{"component":"form", "title": "CSV import", "validate": "Load data", "action": "examples/handle_csv_upload.sql"}, - {"name": "product_data_input", "type": "file", "accept": "text/csv", "label": "Products", "description": "Upload a CSV with a name, description, and price columns", "required": true} - ]')) -; - -INSERT INTO component(name, icon, description) VALUES - ('chart', 'timeline', 'A component that plots data. Line, area, bar, and pie charts are all supported. Each item in the component is a data point in the graph.'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'chart', * FROM (VALUES - -- top level - ('title', 'The name of the chart.', 'TEXT', TRUE, TRUE), - ('type', 'The type of chart. One of: "line", "area", "bar", "column", "pie", "scatter", "bubble", "heatmap", "rangeBar". "column" is a synonym of "bar".', 'TEXT', TRUE, FALSE), - ('time', 'Whether the x-axis represents time. If set to true, the x values will be parsed and formatted as dates for the user.', 'BOOLEAN', TRUE, TRUE), - ('xmin', 'The minimal value for the x-axis. When time is true, this can be a date or timestamp.', 'TEXT', TRUE, TRUE), - ('xmax', 'The maximum value for the x-axis. When time is true, this can be a date or timestamp.', 'TEXT', TRUE, TRUE), - ('ymin', 'The minimal value for the y-axis.', 'REAL', TRUE, TRUE), - ('ymax', 'The maximum value for the y-axis.', 'REAL', TRUE, TRUE), - ('xtitle', 'Title of the x axis, displayed below it.', 'TEXT', TRUE, TRUE), - ('ytitle', 'Title of the y axis, displayed to its left.', 'TEXT', TRUE, TRUE), - ('ztitle', 'Title of the z axis, displayed in tooltips.', 'TEXT', TRUE, TRUE), - ('xticks', 'Number of intervals used to generate a numeric x-axis, normally producing one more tick position. On category and time axes, this is a target for label density, so the visible label count may differ.', 'INTEGER', TRUE, TRUE), - ('yticks', 'Number of ticks on the y axis.', 'INTEGER', TRUE, TRUE), - ('ystep', 'Step between ticks on the y axis.', 'REAL', TRUE, TRUE), - ('marker', 'Marker size', 'REAL', TRUE, TRUE), - ('labels', 'Whether to show the data labels on the chart or not.', 'BOOLEAN', TRUE, TRUE), - ('color', 'The name of a color in which to display the chart. If there are multiple series in the chart, this parameter can be repeated multiple times.', 'COLOR', TRUE, TRUE), - ('stacked', 'Whether to cumulate values from different series. Supported by the "line", "area" and "bar" chart types, and ignored by the others. Series are aligned on their x values, and a series that has no value for a given x counts as zero there.', 'BOOLEAN', TRUE, TRUE), - ('toolbar', 'Whether to display a toolbar at the top right of the chart, that offers downloading the data as CSV.', 'BOOLEAN', TRUE, TRUE), - ('show_legend', 'Whether to display the legend listing all chart series. Defaults to true.', 'BOOLEAN', TRUE, TRUE), - ('logarithmic', 'Display the y-axis in logarithmic scale.', 'BOOLEAN', TRUE, TRUE), - ('horizontal', 'Displays a bar chart with horizontal bars instead of vertical ones.', 'BOOLEAN', TRUE, TRUE), - ('height', 'Height of the chart, in pixels. By default: 250', 'INTEGER', TRUE, TRUE), - -- item level - ('x', 'The value of the point on the horizontal axis. Numeric values use continuous, proportionate positioning; text values are evenly spaced categories. Set the top-level time property for dates and timestamps.', 'REAL', FALSE, FALSE), - ('y', 'The value of the point on the vertical axis', 'REAL', FALSE, FALSE), - ('z', 'A third value carried by the point. Used as the bubble radius in a bubble chart, and shown in the tooltip under the name given by the top-level "ztitle".', 'REAL', FALSE, TRUE), - ('link', 'A URL to open when the data point is clicked. The tooltip value also links to the point, as does a text x value when shown as the tooltip title.', 'URL', FALSE, TRUE), - ('label', 'An alias for parameter "x". On a row that draws a reference line, the text to display next to the line. Labels are plain text; HTML markup is displayed literally.', 'TEXT', FALSE, TRUE), - ('value', 'An alias for parameter "y"', 'REAL', FALSE, TRUE), - ('series', 'If multiple series are represented and share the same y-axis, this parameter can be used to distinguish between them. Series names are plain text; HTML markup is displayed literally.', 'TEXT', FALSE, TRUE), - ('yline', 'Draws a reference line across the chart at this value of the y axis instead of plotting a point, to show a limit such as a quota or an alarm threshold. Not drawn if it falls outside of the axis, so set ymax when the limit is above the data.', 'REAL', FALSE, TRUE), - ('yline_end', 'Makes the yline a band instead of a line, reaching to this value.', 'REAL', FALSE, TRUE), - ('xline', 'Draws a reference line across the chart at this position of the x axis instead of plotting a point, to mark an event such as a deployment. A date or a timestamp when time is set, otherwise one of the x values.', 'TEXT', FALSE, TRUE), - ('xline_end', 'Makes the xline a band instead of a line, reaching to this value.', 'TEXT', FALSE, TRUE), - ('color', 'The name of a color for what this row draws: the bar, slice or point it plots, or the reference line it draws. Defaults to the color of the series for a data point, and to grey for a reference line.', 'COLOR', FALSE, TRUE) -) x; -INSERT INTO example(component, description, properties) VALUES - ('chart', 'An area chart representing a time series, using the top-level property `time`. - Ticks on the x axis are adjusted automatically, and ISO datetimes are parsed and displayed in a readable format.', json('[ - { - "component": "chart", - "title": "Quarterly Revenue", - "type": "area", - "color": "blue-lt", - "marker": 5, - "time": true - }, - {"x":"2022-01-01T00:00:00Z","y":15}, - {"x":"2022-04-01T00:00:00Z","y":46}, - {"x":"2022-07-01T00:00:00Z","y":23}, - {"x":"2022-10-01T00:00:00Z","y":70}, - {"x":"2023-01-01T00:00:00Z","y":35}, - {"x":"2023-04-01T00:00:00Z","y":106}, - {"x":"2023-07-01T00:00:00Z","y":53} - ]')), - ('chart', 'A pie chart.', json('[{"component":"chart", "title": "Answers", "type": "pie", "labels": true}, - {"label": "Yes", "value": 65}, - {"label": "No", "value": 35}]')), - ('chart', 'A basic bar chart', json('[ - {"component":"chart", "type": "bar", "title": "Quarterly Results", "horizontal": true, "labels": true}, - {"label": "Tom", "value": 35}, {"label": "Olive", "value": 15}]')), - ('chart', 'A TreeMap Chart allows you to display hierarchical data in a nested layout. This is useful for visualizing the proportion of each part to the whole.', - json('[ - {"component":"chart", "type": "treemap", "title": "Quarterly Results By Region (in k$)", "labels": true }, - {"series": "North America", "label": "United States", "value": 35}, - {"series": "North America", "label": "Canada", "value": 15}, - {"series": "Europe", "label": "France", "value": 30}, - {"series": "Europe", "label": "Germany", "value": 55}, - {"series": "Asia", "label": "China", "value": 20}, - {"series": "Asia", "label": "Japan", "value": 10} - ]')), - ('chart', 'A bar chart with multiple series.', json('[{"component":"chart", "title": "Expenses", "type": "bar", "stacked": true, "toolbar": true, "show_legend": false, "ystep": 10}, '|| - '{"series": "Marketing", "x": 2021, "value": 35}, '|| - '{"series": "Marketing", "x": 2022, "value": 15}, '|| - '{"series": "Human resources", "x": 2021, "value": 30}, '|| - '{"series": "Human resources", "x": 2022, "value": 55}]')), - ('chart', 'A stacked area chart, showing how each series contributes to a total. -The `stacked` property also works with the `line` and `bar` chart types. - -Series are aligned on their `x` values, and a series that has no value for a given `x` counts as zero there: -below, the graphics card draws no power outside of the render. -If a missing value does not mean zero in your data, make all the series share the same `x` values, -for instance by rounding timestamps to a common interval.', - json('[{"component":"chart", "title": "Power draw", "type": "area", "stacked": true, "time": true, "ytitle": "watts", "color": ["blue", "teal"], "marker": 4}, '|| - '{"series": "CPU", "x": "2024-03-01T10:00:00Z", "value": 45}, '|| - '{"series": "CPU", "x": "2024-03-01T10:15:00Z", "value": 52}, '|| - '{"series": "CPU", "x": "2024-03-01T10:30:00Z", "value": 48}, '|| - '{"series": "CPU", "x": "2024-03-01T10:45:00Z", "value": 44}, '|| - '{"series": "GPU", "x": "2024-03-01T10:15:00Z", "value": 120}, '|| - '{"series": "GPU", "x": "2024-03-01T10:30:00Z", "value": 140}]')), - ('chart', 'A line chart with multiple series. One of the most common types of charts, often used to show trends over time. -Also demonstrates the use of the `toolbar` attribute to allow the user to download the graph as an image or the data as a CSV file.', - json('[{"component":"chart", "title": "Revenue", "ymin": 0, "toolbar": true}, - {"series": "Chicago Store", "x": 2021, "value": 35}, - {"series": "Chicago Store", "x": 2022, "value": 15}, - {"series": "Chicago Store", "x": 2023, "value": 45}, - {"series": "New York Store", "x": 2021, "value": 30}, - {"series": "New York Store", "x": 2022, "value": 55}, - {"series": "New York Store", "x": 2023, "value": 19} - ]')), - ('chart', 'A scatter plot with multiple custom options.', - json('[ - {"component":"chart", "title": "Gross domestic product and its growth", "type": "scatter", - "xtitle": "Growth Rate", "ytitle": "GDP (Trillions USD)", "height": 500, "marker": 8, - "xmin": 0, "xmax": 10, "ymin": 0, "ymax": 25, "yticks": 5}, - - {"series": "Brazil", "x": 2.5, "y": 2}, - {"series": "China", "x": 6.5, "y": 14}, - {"series": "United States", "x": 2.3, "y": 21}, - {"series": "France", "x": 1.5, "y": 3}, - {"series": "South Africa", "x": 0.9, "y": 0.3} - ]')), - ('chart', ' -## Heatmaps - -You can build heatmaps using the `heatmap` top-level property. - -The data format follows the [apexcharts heatmap format](https://apexcharts.com/angular-chart-demos/heatmap-charts/basic/), -where each series is represented as a line in the chart: - - The `x` property of each item will be used as the x-axis value. - - The `series` property of each item will be used as the y-axis value. - - The `y` property of each item will be used as the value to display in the heatmap - -The `color` property sets the color of each series separately, in order. -',json('[ - {"component":"chart", "title": "Survey Results", "type": "heatmap", - "ytitle": "Database managemet system", "xtitle": "Year", "color": ["purple","purple","purple"]}, - { "series": "PostgreSQL", "x": "2000", "y": 48},{ "series": "SQLite", "x": "2000", "y": 44},{ "series": "MySQL", "x": "2000", "y": 78}, - { "series": "PostgreSQL", "x": "2010", "y": 65},{ "series": "SQLite", "x": "2010", "y": 62},{ "series": "MySQL", "x": "2010", "y": 83}, - { "series": "PostgreSQL", "x": "2020", "y": 73},{ "series": "SQLite", "x": "2020", "y": 38},{ "series": "MySQL", "x": "2020", "y": 87} - ]')), - ('chart', 'A timeline displaying events with a start and an end date. A data row can include a `link` to open when its bar or tooltip title is clicked.', - json('[ - {"component":"chart", "title": "Project Timeline", "type": "rangeBar", "time": true, "color": ["teal", "cyan"], "labels": true, "xmin": "2021-12-28", "xmax": "2022-01-04" }, - {"series": "Phase 1", "label": "Operations", "value": ["2021-12-29", "2022-01-02"], "link": "/examples/chart.sql?phase=1"}, - {"series": "Phase 2", "label": "Operations", "value": ["2022-01-03", "2022-01-04"]}, - {"series": "Yearly maintenance", "label": "Maintenance", "value": ["2022-01-01", "2022-01-03"]} - ]')), - ('chart', ' -## Coloring a single value - -A data row can carry its own `color`, to paint the one bar, slice or point it -plots. Use it when the color says something the axes do not: a threshold -crossed, a status, the one category the reader should look at first. - -```sql -select ''chart'' as component, ''bar'' as type, true as horizontal, - true as labels, false as show_legend; -select - window_label as label, - accounts as value, - case when days <= 30 then ''red'' when days <= 60 then ''orange'' else ''green'' end as color -from expiring_accounts order by days; -``` - -A row color takes precedence over the color of its series. On a `line` or an -`area` chart it paints the marker of the point, so set `marker` for it to show. -A `heatmap` shades its cells from their own value and ignores it. -', json('[ - {"component":"chart", "title": "Accounts expiring soon", "type": "bar", - "horizontal": true, "labels": true, "show_legend": false}, - {"label": "30 days", "value": 100, "color": "red"}, - {"label": "60 days", "value": 200, "color": "orange"}, - {"label": "90 days", "value": 300, "color": "green"} - ]')), - ('chart', 'A pie chart whose rows choose their own slice colors.', json('[ - {"component":"chart", "title": "Support tickets", "type": "pie", "labels": true}, - {"label": "Resolved", "value": 72, "color": "green"}, - {"label": "In progress", "value": 21, "color": "yellow"}, - {"label": "Overdue", "value": 7, "color": "red"} - ]')), - ('chart', ' -## Reference lines - -A row with a `yline` is not plotted as a data point, but drawn as a line across -the whole chart, at that value of the y axis. Use it for the limit that the data -should be read against: a disk quota, an alarm threshold, a service level -objective. Add `yline_end` to make it a band instead of a line. - -Reference lines are rows, so they come from a query like everything else, -and a chart can have as many of them as the query returns: - -```sql -select ''chart'' as component, ''CPU temperature'' as title, true as time, 100 as ymax; -select celsius as yline, name as label, color as color from thresholds; -select measured_at as x, celsius as y from readings order by measured_at; -``` - -They are drawn as annotations rather than as an extra series, so they are not -added to the total of a `stacked` chart, and are not filled in an `area` chart. - -A line outside of the y axis is not drawn, and does not stretch the axis to fit, -so set `ymax` when the limit is above the data. -', json('[ - {"component":"chart", "title": "CPU temperature", "type": "line", "time": true, - "ytitle": "°C", "ymax": 100, "color": "azure", "marker": 4}, - {"yline": 70, "label": "target", "color": "green"}, - {"yline": 90, "yline_end": 100, "label": "throttling", "color": "red"}, - {"x": "2024-05-01T08:00:00Z", "y": 52}, - {"x": "2024-05-01T09:00:00Z", "y": 58}, - {"x": "2024-05-01T10:00:00Z", "y": 71}, - {"x": "2024-05-01T11:00:00Z", "y": 83}, - {"x": "2024-05-01T12:00:00Z", "y": 94}, - {"x": "2024-05-01T13:00:00Z", "y": 76}, - {"x": "2024-05-01T14:00:00Z", "y": 63} - ]')), - ('chart', ' -## Marking events - -`xline` is the counterpart of `yline`: it marks a position on the x axis instead -of a value on the y axis. On its own it marks a moment, like a deployment. -With `xline_end`, it covers everything in between, like an incident or a -maintenance window. A single query can draw a whole log of them: - -```sql -select started_at as xline, ended_at as xline_end, summary as label, - case severity when ''outage'' then ''red'' else ''orange'' end as color -from incidents where started_at > $since; -``` - -When `time` is set, an `xline` is a date or a timestamp, written like the `x` of -a data point. On a chart with text labels on the x axis, it is one of those labels. -', json('[ - {"component":"chart", "title": "Request latency", "type": "area", "time": true, - "ytitle": "ms", "color": "blue-lt", "marker": 3}, - {"xline": "2024-05-01T10:00:00Z", "label": "deploy", "color": "green"}, - {"xline": "2024-05-01T11:30:00Z", "xline_end": "2024-05-01T13:00:00Z", - "label": "incident", "color": "red"}, - {"x": "2024-05-01T08:00:00Z", "y": 120}, - {"x": "2024-05-01T09:00:00Z", "y": 134}, - {"x": "2024-05-01T10:00:00Z", "y": 128}, - {"x": "2024-05-01T11:00:00Z", "y": 141}, - {"x": "2024-05-01T12:00:00Z", "y": 512}, - {"x": "2024-05-01T13:00:00Z", "y": 470}, - {"x": "2024-05-01T14:00:00Z", "y": 156}, - {"x": "2024-05-01T15:00:00Z", "y": 133} - ]')), - ('chart', ' -## Reference lines follow their axis - -A reference belongs to the column it is written in, not to a direction on the -screen. `yline` always marks a value of `y`, and `xline` a position on `x`, -whichever way round the chart is drawn. A `horizontal` bar chart runs its y axis -from left to right, so a `yline` is drawn down the chart and an `xline` picks out -one of the bars. - -```sql -select ''chart'' as component, ''bar'' as type, true as horizontal, 100 as ymax; -select 90 as yline, ''full'' as label, ''red'' as color; -select ''db-1'' as xline, ''watched'' as label, ''purple'' as color; -select host as x, percent_used as y from disks order by percent_used; -``` - -A `pie` has no axes and ignores reference lines, and on a `heatmap`, whose y axis -holds the names of the series, only `xline` has a meaning. -', json('[ - {"component":"chart", "title": "Disk usage", "type": "bar", "horizontal": true, - "ymax": 100, "color": "azure", "labels": true}, - {"yline": 90, "label": "full", "color": "red"}, - {"xline": "db-1", "label": "watched", "color": "purple"}, - {"x": "backup-1", "y": 41}, - {"x": "web-2", "y": 63}, - {"x": "db-1", "y": 88}, - {"x": "web-1", "y": 96} - ]')), - ('chart', ' -## Multiple charts on the same line - -You can create information-dense dashboards by using the [card component](?component=card#component) -to put multiple charts on the same line. - -For this, create one sql file per visualization you want to show, -and set the `embed` attribute of the [card](?component=card#component) component -to the path of the file you want to include, followed by `?_sqlpage_embed`. -', - json('[ - {"component":"card", "title":"A dashboard with multiple graphs on the same line", "columns": 2}, - {"embed": "/examples/chart.sql?color=green&n=42&_sqlpage_embed"}, - {"embed": "/examples/chart.sql?_sqlpage_embed" } - ]')); - -INSERT INTO component(name, icon, description) VALUES - ('table', 'table', 'A table with optional filtering and sorting. -Unlike most others, this component does not have a fixed set of item properties, any property that is used will be rendered directly as a column in the table. -Tables can contain rich text, including images, links, and icons. Table rows can be styled with a background color, and the table can be made striped, hoverable, and bordered. - -Advanced users can apply custom styles to table columns using a CSS class with the same name as the column, and to table rows using the `_sqlpage_css_class` property. -'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'table', * FROM (VALUES - -- top level - ('title', 'A title displayed above the table.', 'TEXT', TRUE, TRUE), - ('sort', 'Make the columns clickable to let the user sort by the value contained in the column.', 'BOOLEAN', TRUE, TRUE), - ('search', 'Add a search bar at the top of the table, letting users easily filter table rows by value.', 'BOOLEAN', TRUE, TRUE), - ('initial_search_value', 'Pre-fills the search bar used to filter the table. The user will still be able to edit the value to display table rows that will initially be filtered out.', 'TEXT', TRUE, TRUE), - ('search_placeholder', 'Customizes the placeholder text shown in the search input field. Replaces the default "Search..." with text that better describes what users should search for.', 'TEXT', TRUE, TRUE), - ('markdown', 'Set this to the name of a column whose content should be interpreted as markdown . Used to display rich text with links in the table. This argument can be repeated multiple times to intepret multiple columns as markdown.', 'TEXT', TRUE, TRUE), - ('icon', 'Set this to the name of a column whose content should be interpreted as a tabler icon name. Used to display icons in the table. This argument can be repeated multiple times to intepret multiple columns as icons. Introduced in v0.8.0.', 'TEXT', TRUE, TRUE), - ('align_right', 'Name of a column the contents of which should be right-aligned. This argument can be repeated multiple times to align multiple columns to the right. Introduced in v0.15.0.', 'TEXT', TRUE, TRUE), - ('align_center', 'Name of a column the contents of which should be center-aligned. This argument can be repeated multiple times to align multiple columns to the center.', 'TEXT', TRUE, TRUE), - ('monospace', 'Name of a column the contents of which should be displayed in monospace. This argument can be repeated multiple times to display multiple columns in monospace. Introduced in v0.32.1.', 'TEXT', TRUE, TRUE), - ('striped_rows', 'Whether to add zebra-striping to any table row.', 'BOOLEAN', TRUE, TRUE), - ('striped_columns', 'Whether to add zebra-striping to any table column.', 'BOOLEAN', TRUE, TRUE), - ('hover', 'Whether to enable a hover state on table rows.', 'BOOLEAN', TRUE, TRUE), - ('border', 'Whether to draw borders on all sides of the table and cells.', 'BOOLEAN', TRUE, TRUE), - ('overflow', 'Whether to to let "wide" tables overflow across the right border and enable browser-based horizontal scrolling.', 'BOOLEAN', TRUE, TRUE), - ('small', 'Whether to use compact table.', 'BOOLEAN', TRUE, TRUE), - ('description','Description of the table contents. Helps users with screen readers to find a table and understand what it’s about.','TEXT',TRUE,TRUE), - ('empty_description', 'Text to display if the table does not contain any row. Defaults to "no data".', 'TEXT', TRUE, TRUE), - ('freeze_columns', 'Whether to freeze the leftmost column of the table.', 'BOOLEAN', TRUE, TRUE), - ('freeze_headers', 'Whether to freeze the top row of the table.', 'BOOLEAN', TRUE, TRUE), - ('freeze_footers', 'Whether to freeze the footer (bottom row) of the table, only works if that row has the `_sqlpage_footer` property applied to it.', 'BOOLEAN', TRUE, TRUE), - ('raw_numbers', 'Name of a column whose values are numeric, but should be displayed as raw numbers without any formatting (no thousands separators, decimal separator is always a dot). This argument can be repeated multiple times.', 'TEXT', TRUE, TRUE), - ('money', 'Name of a numeric column whose values should be displayed as currency amounts, in the currency defined by the `currency` property. This argument can be repeated multiple times.', 'TEXT', TRUE, TRUE), - ('currency', 'The ISO 4217 currency code (e.g., USD, EUR, GBP, etc.) to use when formatting monetary values.', 'TEXT', TRUE, TRUE), - ('number_format_digits', 'Maximum number of decimal digits to display for numeric values.', 'INTEGER', TRUE, TRUE), - ('number_format_locale', 'A BCP 47 language tag (e.g. "de-DE", "en-IN") deciding how numbers and monetary values are formatted. Defaults to the locale of the visitor''s browser.', 'TEXT', TRUE, TRUE), - ('edit_url', 'If set, an edit button will be added to each row. The value of this property should be a URL, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. Clicking the edit button will take the user to that URL. Added in v0.39.0', 'TEXT', TRUE, TRUE), - ('delete_url', 'If set, a delete button will be added to each row. The value of this property should be a URL, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. Clicking the delete button will take the user to that URL. Added in v0.39.0', 'TEXT', TRUE, TRUE), - ('custom_actions', 'If set, a column of custom action buttons will be added to each row. The value of this property should be a JSON array of objects, each object defining a button with the following properties: `name` (the text to display on the button), `icon` (the tabler icon name or image link to display on the button), `link` (the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row), and `tooltip` (optional text to display when hovering over the button). Added in v0.39.0', 'JSON', TRUE, TRUE), - -- row level - ('_sqlpage_css_class', 'For advanced users. Sets a css class on the table row. Added in v0.8.0.', 'TEXT', FALSE, TRUE), - ('_sqlpage_color', 'Sets the background color of the row. Added in v0.8.0.', 'COLOR', FALSE, TRUE), - ('_sqlpage_footer', 'Sets this row as the table footer. It is recommended that this parameter is applied to the last row. Added in v0.34.0.', 'BOOLEAN', FALSE, TRUE), - ('_sqlpage_id', 'Sets the id of the html tabler row element. Allows you to make links targeting a specific row in a table.', 'TEXT', FALSE, TRUE), - ('_sqlpage_actions', 'Sets custom action buttons for this specific row in addition to any defined at the table level, The value of this property should be a JSON array of objects, each object defining a button with the following properties: `name` (the text to display on the button), `icon` (the tabler icon name or image link to display on the button), `link` (the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row), and `tooltip` (optional text to display when hovering over the button). Added in v0.39.0', 'JSON', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('table', 'The most basic table.', - json('[{"component":"table"}, {"a": 1, "b": 2}, {"a": 3, "b": 4}]')), - ('table', 'A table of users with filtering and sorting.', - json('[ - {"component":"table", "sort":true, "search":true, "search_placeholder": "Filter by name"}, - {"First Name": "Ophir", "Last Name": "Lojkine", "Pseudonym": "lovasoa"}, - {"First Name": "Linus", "Last Name": "Torvalds", "Pseudonym": "torvalds"} - ]')), - ('table', 'A table that uses markdown to display links', - json('[{"component":"table", "markdown": "Name", "icon": "icon", "search": true}, '|| - '{"icon": "table", "name": "[Table](?component=table)", "description": "Displays SQL results as a searchable table.", "_sqlpage_color": "red"}, - {"icon": "timeline", "name": "[Chart](?component=chart)", "description": "Show graphs based on numeric data."} - ]')), - ('table', 'A sortable table with a colored footer showing the average value of its entries.', - json('[{"component":"table", "sort":true}, '|| - '{"Person": "Rudolph Lingens", "Height": 190},' || - '{"Person": "Jane Doe", "Height": 150},' || - '{"Person": "John Doe", "Height": 200},' || - '{"_sqlpage_footer":true, "_sqlpage_color": "green", "Person": "Average", "Height": 180}]')), - ( - 'table', - 'A table with column sorting. Sorting sorts numbers in numeric order, and strings in alphabetical order. - -Numbers can be displayed - - as raw digits without formatting using the `raw_numbers` property, - - as currency using the `money` property to define columns that contain monetary values and `currency` to define the currency, - - as numbers with a fixed maximum number of decimal digits using the `number_format_digits` property. -', - json( - '[{"component":"table", "sort": true, "align_right": ["Price", "Amount in stock"], "align_center": ["part_no"], "raw_numbers": ["id"], "currency": "USD", "money": ["Price"] }, - {"id": 31456, "part_no": "SQL-TABLE-856-G", "Price": 12, "Amount in stock": 5}, - {"id": 996, "part_no": "SQL-FORMS-86-M", "Price": 1, "Amount in stock": 1234}, - {"id": 131456, "part_no": "SQL-CARDS-56-K", "Price": 127, "Amount in stock": 98} - ]' - )), - ( - 'table', - 'A table with some presentation options', - json( - '[{"component":"table", - "hover": true, "striped_rows": true, - "description": "Some Star Trek Starfleet starships", - "small": true, "initial_search_value": "NCC-" - }, - {"name": "USS Enterprise", "registry": "NCC-1701-C", "class":"Ambassador"}, - {"name": "USS Archer", "registry": "NCC-44278", "class":"Archer"}, - {"name": "USS Endeavour", "registry": "NCC-06", "class":"Columbia"}, - {"name": "USS Constellation", "registry": "NCC-1974", "class":"Constellation"}, - {"name": "USS Dakota", "registry": "NCC-63892", "class":"Akira"}, - {"name": "USS Defiant", "registry": "IX-74205", "class":"Defiant"} - ]' - )), - ( - 'table', - 'An empty table with a friendly message', - json('[{"component":"table", "empty_description": "Nothing to see here at the moment."}]') - ), - ( - 'table', - 'A large table with many rows and columns, with frozen columns on the left and headers on top. This allows users to browse large datasets without loosing track of their position.', - json('[ - {"component": "table", "freeze_columns": true, "freeze_headers": true}, - { - "feature": "SQL Execution", - "description": "Fully compatible with existing databases SQL dialects, executes any SQL query.", - "benefits": "Short learning curve, easy to use, interoperable with existing tools." - }, - { - "feature": "Data Visualization", - "description": "Automatic visualizations of query results: graphs, plots, pie charts, heatmaps, etc.", - "benefits": "Quickly analyze data trends, attractive and easy to understand, no external visualization tools or languages to learn." - }, - { - "feature": "User Authentication", - "description": "Supports user sessions, from basic auth to single sign-on.", - "benefits": "Secure, enforces access control policies, and provides a customizable security layer." - }, - { - "feature": "APIs", - "description": "Allows building JSON REST APIs and integrating with external APIs.", - "benefits": "Enables automation and integration with other platforms, facilitates data exchange." - }, - { - "feature": "Files", - "description": "File uploads, downloads and processing. Supports local filesystem and database storage.", - "benefits": "Convenient file management, secure data handling, flexible storage options, integrates with existing systems." - }, - { - "feature": "Maps", - "description": "Supports GeoJSON and is compatible with GIS data for map visualization.", - "benefits": "Geospatial data representation, integrates with geographic information systems." - }, - { - "feature": "Custom Components", - "description": "Build advanced features using HTML, JavaScript, and CSS.", - "benefits": "Tailor-made user experiences, easy to implement custom UI requirements." - }, - { - "feature": "Forms", - "description": "Insert and update data in databases based on user input.", - "benefits": "Simplified data input and management, efficient user interactions with databases." - }, - { - "feature": "DB Compatibility", - "description": "Works with MySQL, PostgreSQL, SQLite, Microsoft SQL Server and compatible databases.", - "benefits": "Broad compatibility with popular database systems, ensures seamless integration." - }, - { - "feature": "Security", - "description": "Built-in protection against common web vulnerabilities: no SQL injection, no XSS.", - "benefits": "Passes audits and security reviews, reduces the risk of data breaches." - }, - { - "feature": "Performance", - "description": "Designed for performance, with a focus on efficient data processing and minimal overhead.", - "benefits": "Quickly processes large datasets, handles high volumes of requests, and minimizes server load." - }, - { - "_sqlpage_footer": true, - "feature": "Summary", - "description": "Summarizes the features of the product.", - "benefits": "Provides a quick overview of the product''s features and benefits." - } -]') - ), - ( - 'table', - '#### Dynamic column names in a table - -In all the previous examples, the column names were hardcoded in the SQL query. -This makes it very easy to quickly visualize the results of a query as a table, -but it can be limiting if you want to include columns that are not known in advance. -In situations when the number and names of the columns depend on the data, or on variables, -you can use the `dynamic` component to generate the table columns dynamically. - -For that, you will need to return JSON objects from your SQL query, where the keys are the column names, -and the values are the cell contents. - -Databases [offer utilities to generate JSON objects from query results](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) - - In PostgreSQL, you can use the [`json_build_object`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING) -function for a fixed number of columns, or [`json_object_agg`](https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-AGGREGATE) for a dynamic number of columns. - - In SQLite, you can use the [`json_object`](https://www.sqlite.org/json1.html) function for a fixed number of columns, -or the `json_group_object` function for a dynamic number of columns. - - In MySQL, you can use the [`JSON_OBJECT`](https://dev.mysql.com/doc/refman/8.0/en/json-creation-functions.html#function_json-object) function for a fixed number of columns, -or the [`JSON_OBJECTAGG`](https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html#function_json-objectagg) function for a dynamic number of columns. - - In Microsoft SQL Server, you can use the [`FOR JSON PATH`](https://docs.microsoft.com/en-us/sql/relational-databases/json/format-query-results-as-json-with-for-json-sql-server?view=sql-server-ver15) clause. - -For instance, let''s say we have a table with three columns: store, item, and quantity_sold. -We want to create a pivot table where each row is a store, and each column is an item. -We will return a set of json objects that look like this: `{"store":"Madrid", "Item1": 42, "Item2": 7, "Item3": 0}` - -```sql -SELECT ''table'' AS component; -with filled_data as ( - select - stores.store, items.item, - (select coalesce(sum(quantity_sold), 0) from store_sales where store=stores.store and item=items.item) as quantity - from (select distinct store from store_sales) as stores - cross join (select distinct item from store_sales) as items - order by stores.store, items.item -) -SELECT - ''dynamic'' AS component, - JSON_PATCH( -- SQLite-specific, refer to your database documentation for the equivalent JSON functions - JSON_OBJECT(''store'', store), - JSON_GROUP_OBJECT(item, quantity) - ) AS properties -FROM - filled_data -GROUP BY - store; -``` - -This will generate a table with the stores in the first column, and the items in the following columns, with the quantity sold in each store for each item. - -', NULL - ), - ( - 'table', -'## Using Action Buttons in a table. - -### Preset Actions: `edit_url` & `delete_url` -Since edit and delete are common actions, the `table` component has dedicated `edit_url` and `delete_url` properties to add buttons for these actions. -The value of these properties should be a URL, containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row. - -### Column with fixed action buttons - -You may want to add custom action buttons to your table rows, for instance to view details, download a file, or perform a custom operation. -For this, the `table` component has a `custom_actions` top-level property that lets you define a column of buttons, each button defined by a name, an icon, a link, and an optional tooltip. - -### Column with variable action buttons - -The `table` component also supports the row level `_sqlpage_actions` column in your data table. -This is helpful if you want a more complex logic, for instance to disable a button on some rows, or to change the link or icon based on the row data. - -> WARNING! -> If the number of array items in `_sqlpage_actions` is not consistent across all rows, the table may not render correctly. -> You can leave blank spaces by including an object with only the `name` property. - -The table has a column of buttons, each button defined by the `custom_actions` column at the table level, and by the `_sqlpage_actions` property at the row level. - -### `custom_actions` & `_sqlpage_actions` JSON properties. - -Each button is defined by the following properties: -* `name`: sets the column header and the tooltip if no tooltip is provided, -* `tooltip`: text to display when hovering over the button, -* `link`: the URL to navigate to when the button is clicked, possibly containing the `{id}` placeholder that will be replaced by the value of the `_sqlpage_id` property for that row, -* `icon`: the tabler icon name or image link to display on the button - -### Example using all of the above -' - , - json('[ - { - "component": "table", - "edit_url": "/examples/show_variables.sql?action=edit&update_id={id}", - "delete_url": "/examples/show_variables.sql?action=delete&delete_id={id}", - "custom_actions": { - "name": "history", - "tooltip": "View Standard History", - "link": "/examples/show_variables.sql?action=history&standard_id={id}", - "icon": "history" - } - }, - { - "name": "CalStd", - "vendor": "PharmaCo", - "Product": "P1234", - "lot number": "T23523", - "status": "Available", - "expires on": "2026-10-13", - "_sqlpage_id": 32, - "_sqlpage_actions": [ - { - "name": "View PDF", - "tooltip": "View Presentation", - "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf", - "icon": "file-type-pdf" - }, - { - "name": "Action", - "tooltip": "Set In Use", - "link": "/examples/show_variables.sql?action=set_in_use&standard_id=32", - "icon": "caret-right" - } - ] - }, - { - "name": "CalStd", - "vendor": "PharmaCo", - "Product": "P1234", - "lot number": "T2352", - "status": "In Use", - "expires on": "2026-10-14", - "_sqlpage_id": 33, - "_sqlpage_actions": [ - { - "name": "View PDF", - "tooltip": "View Presentation", - "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf", - "icon": "file-type-pdf" - }, - { - "name": "Action", - "tooltip": "Retire Standard", - "link": "/examples/show_variables.sql?action=retire&standard_id=33", - "icon": "test-pipe-off" - } - ] - }, - { - "name": "CalStd", - "vendor": "PharmaCo", - "Product": "P1234", - "lot number": "A123", - "status": "Discarded", - "expires on": "2026-09-30", - "_sqlpage_id": 31, - "_sqlpage_actions": [ - { - "name": "View PDF", - "tooltip": "View Presentation", - "link": "https://sql-page.com/pgconf/2024-sqlpage-badass.pdf", - "icon": "file-type-pdf" - }, - { - "name": "Action" - } - ] - } -]' -) -); - - - -INSERT INTO component(name, icon, description) VALUES - ('csv', 'download', 'Lets the user download data as a CSV file. -Each column from the items in the component will map to a column in the resulting CSV. - -When `csv` is used as a **header component** (without a [shell](?component=shell)), it will trigger a download of the CSV file directly on page load. -If the csv file to download is large, we recommend using this approach. - -When used inside a page (after calling the shell component), this will add a button to the page that lets the user download the CSV file. -The button will need to load the entire contents of the CSV file in memory, inside the browser, even if the user does not click on it. -If the csv file to download is large, we recommend using this component without a shell component in order to efficiently stream the data to the browser. -'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'csv', * FROM (VALUES - -- top level - ('separator', 'How individual values should be separated in the CSV. "," by default, set it to "\t" for tab-separated values.', 'TEXT', TRUE, TRUE), - ('title', 'The text displayed on the download button.', 'TEXT', TRUE, FALSE), - ('filename', 'The name of the file that should be downloaded (without the extension).', 'TEXT', TRUE, TRUE), - ('icon', 'Name of the icon (from tabler-icons.io) to display in the button. Ignored when used as a header component.', 'ICON', TRUE, TRUE), - ('color', 'Color of the button. Ignored when used as a header component.', 'COLOR', TRUE, TRUE), - ('size', 'The size of the button (e.g., sm, lg). Ignored when used as a header component.', 'TEXT', TRUE, TRUE), - ('bom', 'Whether to include a Byte Order Mark (a special character indicating the character encoding) at the beginning of the file. This is useful for Excel compatibility.', 'BOOLEAN', TRUE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('csv', ' -### Header component: creating a CSV download URL - -You can create a page that will trigger a download of the CSV file when the user visits it. -The contents will be streamed efficiently from the database to the browser, without being fully loaded in memory. -This makes it possible to download even very large files without overloading the database server, the web server, or the client''s browser. - -#### `csv_download.sql` - -```sql -select ''csv'' as component, ''example.csv'' as filename; -SELECT * FROM my_large_table; -``` - -#### `index.sql` -', - json('[{"component":"button"}, {"title": "Download my data", "link": "/examples/csv_download.sql"}]')), - ('csv', ' -### CSV download button - -This will generate a button to download the CSV file. -The button element itself will embed the entire contents of the CSV file, so it should not be used for large files. -The file will be entirely loaded in memory on the user''s browser, even if the user does not click on the button. -For smaller files, this is easier and faster to use than creating a separate SQL file to generate the CSV. -', - json('[{"component":"csv", "title": "Download my data", "filename": "people", "icon": "file-download", "color": "green", "separator": ";", "bom": true}, '|| - '{"Forename": "Ophir", "Surname": "Lojkine", "Pseudonym": "lovasoa"},' || - '{"Forename": "Linus", "Surname": "Torvalds", "Pseudonym": "torvalds"}]')); - - -INSERT INTO component(name, icon, description) VALUES - ('dynamic', 'repeat', 'Renders other components, given their properties as JSON. -If you are looking for a way to run FOR loops, to share similar code between pages of your site, -or to render multiple components for every line returned by your SQL query, then this is the component to use'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'dynamic', * FROM (VALUES - -- top level - ('properties', 'A json object or array that contains the names and properties of other components.', 'JSON', TRUE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('dynamic', 'The dynamic component has a single top-level property named `properties`, but it can render any number of other components. -Let''s start with something simple to illustrate the logic. We''ll render a `text` component with two row-level properties: `contents` and `italics`. -', json('[{"component":"dynamic", "properties": "[{\"component\":\"text\"}, {\"contents\":\"Hello, I am a dynamic component !\", \"italics\":true}]"}]')), - ('dynamic', ' -## Static component data stored in `.json` files - -You can also store the data for a component in a `.json` file, and load it using the `dynamic` component. - -This is particularly useful to create a single [shell](?component=shell#component) defining the site''s overall appearance and menus, -and displaying it on all pages without duplicating its code. - -The following will load the data for a `shell` component from a file named `shell.json`, -using the [`sqlpage.read_file_as_text`](/functions.sql?function=read_file_as_text) function. - -```sql -SELECT ''dynamic'' AS component, sqlpage.read_file_as_text(''shell.json'') AS properties; -``` - -and `shell.json` would be placed at the website''s root and contain the following: - -```json -{ - "component": "shell", - "title": "SQLPage documentation", - "link": "/", - "menu_item": [ - {"link": "index.sql", "title": "Home"}, - {"title": "Community", "submenu": [ - {"link": "blog.sql", "title": "Blog"}, - {"link": "https//github.com/sqlpage/SQLPage/issues", "title": "Issues"}, - {"link": "https//github.com/sqlpage/SQLPage/discussions", "title": "Discussions"}, - {"link": "https//github.com/sqlpage/SQLPage", "title": "Github"} - ]} - ] -} -``` -', NULL), -('dynamic', ' -## Including another SQL file - -To avoid repeating the same code on multiple pages, you can include another SQL file using the `dynamic` component -together with the [`sqlpage.run_sql`](/functions.sql?function=run_sql) function. - -For instance, the following will include the file `shell.sql` at the top of the page, -and pass it a `$title` variable to display the page title. - -```sql -SELECT ''dynamic'' AS component, - sqlpage.run_sql(''shell.sql'', json_object(''title'', ''SQLPage documentation'')) AS properties; -``` - -And `shell.sql` could contain the following: - -```sql -SELECT ''shell'' AS component, - COALESCE($title, ''Default title'') AS title, - ''/my_icon.png'' AS icon, - ''products'' AS menu_item, - ''about'' AS menu_item; -``` - -', NULL), - ('dynamic', ' -## Dynamic shell - -On databases without a native JSON type (such as the default SQLite database), -you can use the `dynamic` component to generate -json data to pass to components that expect it. - -This example generates a menu similar to the [shell example](?component=shell#component), but without using a native JSON type. - -```sql -SELECT ''dynamic'' AS component, '' -{ - "component": "shell", - "title": "SQLPage documentation", - "link": "/", - "menu_item": [ - {"link": "index.sql", "title": "Home"}, - {"title": "Community", "submenu": [ - {"link": "blog.sql", "title": "Blog"}, - {"link": "https//github.com/sqlpage/SQLPage/issues", "title": "Issues"}, - {"link": "https//github.com/sqlpage/SQLPage/discussions", "title": "Discussions"}, - {"link": "https//github.com/sqlpage/SQLPage", "title": "Github"} - ]} - ] -} -'' AS properties -``` - -[View the result of this query, as well as an example of how to generate a dynamic menu -based on the database contents](./examples/dynamic_shell.sql). -', NULL), - ('dynamic', ' -## Dynamic tables - -The `dynamic` component can be used to generate [tables](?component=table#component) with dynamic columns, -using [your database''s JSON functions](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). - -For instance, let''s say we have a table with three columns: user_id, name, and role. -We want to create a table where each row is a user, and each column is a role. -We will return a set of json objects that look like this: `{"name": "Alice", "admin": true, "editor": false, "viewer": true}` -```sql -SELECT ''table'' AS component; -SELECT ''dynamic'' AS component, - json_patch( - json_object(''name'', name), - json_object_agg(role, is_admin) - ) AS properties -FROM users -GROUP BY name; -``` -', NULL); - -INSERT INTO component(name, icon, description) VALUES - ('shell', 'layout-navbar', ' -Customize the overall layout, header and footer of the page. - -This is a special component that provides the page structure wrapping all other components on your page. - -It generates the complete HTML document including the `` section with metadata, title, and stylesheets, -as well as the navigation bar, main content area, and footer. - -If you don''t explicitly call the shell component at the top of your SQL file, SQLPage will automatically -add a default shell component before your first try to display data on the page. - -Use the shell component to customize page-wide settings like the page title, navigation menu, theme, fonts, -and to include custom visual styles (with CSS) or interactive behavior (with JavaScript) that should be loaded on the page. -'); - -INSERT INTO parameter(component, name, description_md, type, top_level, optional) SELECT 'shell', * FROM (VALUES - ('favicon', 'The URL of the icon the web browser should display in bookmarks and tabs. This property is particularly useful if multiple sites are hosted on the same domain with different [``site_prefix``](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage).', 'URL', TRUE, TRUE), - ('manifest', 'The location of the [manifest.json](https://developer.mozilla.org/en-US/docs/Web/Manifest) if the site is a [PWA](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps). Among other features, serving a manifest enables your site to be "installed" as an app on most mobile devices.', 'URL', TRUE, TRUE) -) x; -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'shell', * FROM (VALUES - -- top level - ('title', 'The title of your page. Will be shown in a top bar above the page contents. Also usually displayed by web browsers as the name of the web page''s tab.', 'TEXT', TRUE, TRUE), - ('layout', 'The general page layout. Can be "boxed" (the default), "horizontal" (for a full-width menu), "vertical"(vertical menu), "fluid" (removes side margins).', 'TEXT', TRUE, TRUE), - ('description', 'A description of the page. It can be displayed by search engines when your page appears in their results.', 'TEXT', TRUE, TRUE), - ('link', 'The target of the link in the top navigation bar.', 'URL', TRUE, TRUE), - ('css', 'The URL of a CSS file to load and apply to the page.', 'URL', TRUE, TRUE), - ('javascript', 'The URL of a Javascript file to load and execute on the page.', 'URL', TRUE, TRUE), - ('javascript_module', 'The URL of a javascript module in the ESM format (see javascript.info/modules)', 'URL', TRUE, TRUE), - ('rss', 'The URL of an RSS feed to display in the top navigation bar. You can use the rss component to generate the field.', 'URL', TRUE, TRUE), - ('image', 'The URL of an image to display next to the page title.', 'URL', TRUE, TRUE), - ('social_image', 'The URL of the preview image that will appear in the Open Graph metadata when the page is shared on social media.', 'URL', TRUE, TRUE), - ('icon', 'Name of an icon (from tabler-icons.io) to display next to the title in the navigation bar.', 'ICON', TRUE, TRUE), - ('menu_item', 'Adds a menu item in the navigation bar at the top of the page. The menu item will have the specified name, and will link to as .sql file of the same name. A dropdown can be generated by passing a json object with a `title` and `submenu` properties.', 'TEXT', TRUE, TRUE), - ('fixed_top_menu', 'Fixes the top bar with menu at the top (the top bar remains visible when scrolling long pages).', 'BOOLEAN', TRUE, TRUE), - ('search_target', 'When this is set, a search field will appear in the top navigation bar, and load the specified sql file with an URL parameter named "search" when the user searches something.', 'TEXT', TRUE, TRUE), - ('search_value', 'This value will be placed in the search field when "search_target" is set. Using the "$search" query parameter value will mirror the value that the user has searched for.', 'TEXT', TRUE, TRUE), - ('search_placeholder', 'Customizes the placeholder text shown in the search input field. Replaces the default "Search" with text that better describes what users should search for. It is also used as the accessible name of the search field, which screen readers announce.', 'TEXT', TRUE, TRUE), - ('search_button', 'Customizes the text displayed on the search button. Replaces the default "Search" label with custom text that may better match your applications terminology or language.', 'TEXT', TRUE, TRUE), - ('norobot', 'Forbids robots to save this page in their database and follow the links on this page. This will prevent this page to appear in Google search results for any query, for instance.', 'BOOLEAN', TRUE, TRUE), - ('font', 'Specifies the font to be used for displaying text, which can be a valid font name from fonts.google.com or the path to a local WOFF2 font file starting with a slash (e.g., "/fonts/MyLocalFont.woff2").', 'TEXT', TRUE, TRUE), - ('font_size', 'Font size on the page, in pixels. Set to 18 by default.', 'INTEGER', TRUE, TRUE), - ('language', 'The language of the page. This can be used by search engines and screen readers to determine in which language the page is written.', 'TEXT', TRUE, TRUE), - ('rtl', 'Whether the page should be displayed in right-to-left mode. Used to display Arabic, Hebrew, Persian, etc.', 'BOOLEAN', TRUE, TRUE), - ('refresh', 'Number of seconds after which the page should refresh. This can be useful to display dynamic content that updates automatically.', 'INTEGER', TRUE, TRUE), - ('sidebar', 'Whether the menu defined by menu_item should be displayed on the left side of the page instead of the top. Introduced in v0.27.', 'BOOLEAN', TRUE, TRUE), - ('sidebar_theme', 'Used with sidebar property, It can be set to "dark" to exclusively set the sidebar into dark theme.', 'TEXT', TRUE, TRUE), - ('theme', 'Set to "dark" to use a dark theme.', 'TEXT', TRUE, TRUE), - ('footer', 'Muted text to display in the footer of the page. This can be used to display a link to the terms and conditions of your application, for instance. By default, shows "Built with SQLPage". Supports links with markdown.', 'TEXT', TRUE, TRUE), - ('preview_image', 'The URL of an image to display as a link preview when the page is shared on social media', 'URL', TRUE, TRUE), - ('navbar_title', 'The title shown in the navigation bar or sidebar. Defaults to the page title. Set an empty string to show just the logo.', 'TEXT', TRUE, TRUE), - ('target', 'Where the menu items should open: "_blank" for a new tab, "_self" for the same tab, "_parent" for the parent frame, or "_top" for the full body of the window. Set it inside a "menu_item" json object; it has no effect when set directly on the shell.', 'TEXT', TRUE, TRUE), - ('class', 'class attribute added to the page''s html element. It can be used to apply custom styling to the whole page through css.', 'TEXT', TRUE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('shell', ' -This example configures a dark shell with menus linking to pages on this site. - -Each `menu_item` object defines a link or a dropdown. The "Community" menu links to the blog, issue tracker, discussions, and source code. - -The object form can be used directly only on database engines that have a native JSON type. -On other engines (such as SQLite), you can use the [`dynamic`](?component=dynamic#component) component to generate the same result. - - -You see the [page layouts demo](./examples/layouts.sql) for a live example of the different layouts. -', - json('[{ - "component": "shell", - "title": "SQLPage: SQL websites", - "navbar_title": "SQLPage", - "link": "/", - "menu_item": [ - {"title": "About", "submenu": [ - {"link": "/safety.sql", "title": "Security", "icon": "lock"}, - {"link": "/performance.sql", "title": "Performance", "icon": "bolt"}, - {"link": "//github.com/sqlpage/SQLPage/blob/main/LICENSE.txt", "title": "License", "icon": "file-text"}, - {"link": "/blog.sql", "title": "Articles", "icon": "book"} - ]}, - {"title": "Examples", "submenu": [ - {"link": "/examples/tabs/", "title": "Tabs", "icon": "layout-navbar"}, - {"link": "/examples/layouts.sql", "title": "Layouts", "icon": "layout"}, - {"link": "/examples/multistep-form", "title": "Forms", "icon": "edit"}, - {"link": "/examples/handle_picture_upload.sql", "title": "File uploads", "icon": "upload"}, - {"link": "/examples/authentication/", "title": "Password protection", "icon": "password-user"}, - {"link": "//github.com/sqlpage/SQLPage/blob/main/examples/", "title": "All examples & demos", "icon": "code"} - ]}, - {"title": "Community", "submenu": [ - {"link": "/blog.sql", "title": "Blog", "icon": "book"}, - {"link": "//github.com/sqlpage/SQLPage/issues", "title": "Report a bug", "icon": "bug"}, - {"link": "//github.com/sqlpage/SQLPage/discussions", "title": "Discussions", "icon": "message"}, - {"link": "//github.com/sqlpage/SQLPage", "title": "Github", "icon": "brand-github"} - ]}, - {"title": "Documentation", "submenu": [ - {"link": "/your-first-sql-website", "title": "Getting started", "icon": "book"}, - {"link": "/components.sql", "title": "All Components", "icon": "list-details"}, - {"link": "/functions.sql", "title": "SQLPage Functions", "icon": "math-function"}, - {"link": "/extensions-to-sql", "title": "Extensions to SQL", "icon": "cube-plus"}, - {"link": "/custom_components.sql", "title": "Custom Components", "icon": "puzzle"}, - {"link": "//github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage", "title": "Configuration", "icon": "settings"} - ]}, - {"title": "Search", "link": "/search"} - ], - "layout": "boxed", - "language": "en-US", - "description": "Go from SQL queries to web applications in an instant.", - "preview_image": "https://sql-page.com/sqlpage_social_preview.webp", - "theme": "dark", - "font_size": 19, - "image": "/assets/icon.webp", - "favicon": "/favicon.ico", - "javascript_module": "/assets/highlightjs-launch.js", - "css": "/assets/highlightjs-and-tabler-theme.css", - "footer": "[Built with SQLPage](https://github.com/sqlpage/SQLPage/tree/main/examples/official-site)" - }]')), - ('shell', ' -This example shows how to set menu items as active in the navigation, so that they are highlighted in the nav bar. - -In this example you can see that two menu items are created, "Home" and "About" and the "Home" tab is marked as active. -', - json('[{ - "component": "shell", - "title": "SQLPage: SQL websites", - "icon": "database", - "link": "/", - "menu_item": [ - {"title": "Home", "active": true}, - {"title": "About"} - ] - }]')), - - ('shell', ' -### Sharing the shell between multiple pages - -It is common to want to share the same shell between multiple pages. - -#### Static menu - -If your menu is completely static (it does not depend on the database content), -you can use the [`dynamic`](?component=dynamic#component) component together with the -[`sqlpage.read_file_as_text`](functions.sql?function=read_file_as_text#function) function to load the shell from -a json file. - -```sql -SELECT ''dynamic'' AS component, sqlpage.read_file_as_text(''shell.json'') AS properties; -``` - -and in `shell.json`: - -```json -{ - "component": "shell", - "title": "SQL + JSON = <3", - "link": "/", - "menu_item": [ - {"link": "index.sql", "title": "Home"}, - {"title": "Community", "submenu": [ - {"link": "/blog.sql", "title": "Blog"}, - {"link": "//github.com/sqlpage/SQLPage", "title": "Github"} - ]} - ] -} -``` - -#### Dynamic menu - -If your menu depends on the database content, or on special `sqlpage` functions, -you can use the `dynamic` component, -but this time with the [`sqlpage.run_sql`](functions.sql?function=run_sql#function) -function to generate the menu from the database. - -```sql -SELECT ''dynamic'' AS component, sqlpage.run_sql(''shell.sql'') AS properties; -``` - -and in `shell.sql`: - -```sql -SELECT ''shell'' AS component, ''run_sql is cool'' as title, - json_group_array(json_object( - ''link'', link, - ''title'', title - )) as menu_item -FROM my_menu_items -``` - -(check your database documentation for the exact syntax of the `json_group_array` function). - -Another case when dynamic menus are useful is when you want to show some -menu items only in certain conditions. - -For instance, you could show an "Admin panel" menu item only to users with the "admin" role, -a "Profile" menu item only to authenticated users, -and a "Login" menu item only to unauthenticated users: - -```sql -set role = ( - SELECT role FROM users - INNER JOIN sessions ON users.id = sessions.user_id - WHERE sessions.session_id = sqlpage.cookie(''session_id'') -); -- Read more about how to handle user sessions in the "authentication" component documentation - -SELECT - ''shell'' AS component, - ''My authenticated website'' AS title, - - -- Add an admin panel link if the user is an admin - CASE WHEN $role = ''admin'' THEN ''{"link": "admin.sql", "title": "Admin panel"}'' END AS menu_item, - - -- Add a profile page if the user is authenticated - CASE WHEN $role IS NOT NULL THEN ''{"link": "profile.sql", "title": "My profile"}'' END AS menu_item, - - -- Add a login link if the user is not authenticated - CASE WHEN $role IS NULL THEN ''login'' END AS menu_item -; -``` - -More about how to handle user sessions in the [authentication component documentation](?component=authentication#component). - -### Menu with icons - -The "icon" attribute may be specified for items in the top menu and submenus to display an icon -before the title (or instead). Similarly, the "image" attribute defines a file-based icon. For -image-based icons, the "size" attribute may be specified at the top level of menu_item only to -reduce the size of image-based icons. The following snippet provides an example, which is also -available [here](examples/menu_icon.sql). - -```sql -SELECT - ''shell'' AS component, - ''SQLPage'' AS title, - ''database'' AS icon, - ''/'' AS link, - TRUE AS fixed_top_menu, - ''{"title":"About","icon": "settings","submenu":[{"link":"/safety.sql","title":"Security","icon": "logout"},{"link":"/performance.sql","title":"Performance"}]}'' AS menu_item, - ''{"title":"Examples","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg","submenu":[{"link":"/examples/tabs/","title":"Tabs","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg"},{"link":"/examples/layouts.sql","title":"Layouts"}]}'' AS menu_item, - ''{"title":"Examples","size":"sm","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg","submenu":[{"link":"/examples/tabs/","title":"Tabs","image": "https://upload.wikimedia.org/wikipedia/en/6/6b/Terrestrial_globe.svg"},{"link":"/examples/layouts.sql","title":"Layouts"}]}'' AS menu_item, - ''Official [SQLPage](https://sql-page.com) documentation'' as footer; -``` -', NULL), - ('shell', ' -### Returning custom HTML, XML, plain text, or other formats - -Use `shell-empty` to opt out of SQLPage''s component system and return raw data directly. - -By default, SQLPage wraps all your content in a complete HTML page with navigation and styling. -The `shell-empty` component tells SQLPage to skip this HTML wrapper and return only the raw content you specify. - -Use it to create endpoints that return things like - - XML (for JSON, use the [json](?component=json) component) - - plain text or markdown content (for instance for consumption by LLMs) - - a custom data format you need - -When using `shell-empty`, you should use the [http_header](component.sql?component=http%5Fheader) component first -to set the correct [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) (like `application/json` or `application/xml`). -', - json('[ - { - "component":"http_header", - "Content-Type":"application/xml" - }, - { - "component":"shell-empty", - "contents": "\n \n 42\n john.doe\n " - } - ]') - ), - ('shell',' -### Generate your own HTML -If you generate your own HTML from a SQL query, you can also use the `shell-empty` component to include it in a page. -This is useful when you want to generate a snippet of HTML that can be dynamically included in a larger page. -Make sure you know what you are doing, and be careful to escape the HTML properly, -as you are stepping out of the safe SQLPage framework and into the wild world of HTML. - -In this scenario, you can use the `html` property, which serves as an alias for the `contents` property. -This property improves code readability by clearly indicating that you are generating HTML. -Since SQLPage returns HTML by default, there is no need to specify the content type in the HTTP header. -', - json('[{"component":"shell-empty", "html": "\n\n\n My page\n\n\n

My page

\n\n"}]')); diff --git a/examples/official-site/sqlpage/migrations/02_hero_component.sql b/examples/official-site/sqlpage/migrations/02_hero_component.sql deleted file mode 100644 index bee6a8d90..000000000 --- a/examples/official-site/sqlpage/migrations/02_hero_component.sql +++ /dev/null @@ -1,184 +0,0 @@ --- Hero -INSERT INTO - component(name, icon, description) -VALUES - ( - 'hero', - 'home', - 'Display a large title and description for your page, with an optional large illustrative image. Useful in your home page, for instance.' - ); - -INSERT INTO - parameter( - component, - name, - description, - type, - top_level, - optional - ) -SELECT - 'hero', - * -FROM - ( - VALUES - -- top level - ( - 'title', - 'The title of your page. Will be shown in very large characters at the top.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'description', - 'A description of the page. Displayed below the title, in smaller characters and slightly greyed out.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'description_md', - 'A description of the page. Displayed below the title, in smaller characters and slightly greyed out - formatted using markdown.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'image', - 'The URL of an image to display next to the page title.', - 'URL', - TRUE, - TRUE - ), - ( - 'video', - 'The URL of a video to display next to the page title.', - 'URL', - TRUE, - TRUE - ), - ( - 'link', - 'Creates a large "call to action" button below the description, linking to the specified URL.', - 'URL', - TRUE, - TRUE - ), - ( - 'link_text', - 'The text to display in the call to action button. Defaults to "Go".', - 'TEXT', - TRUE, - TRUE - ), - ( - 'poster', - 'URL of the image to be displayed before the video starts. Ignored if no video is present.', - 'URL', - TRUE, - TRUE - ), - ( - 'nocontrols', - 'Hide the video controls (play, pause, volume, etc.), and autoplay the video.', - 'BOOLEAN', - TRUE, - TRUE - ), - ('muted', 'Mute the video', 'BOOLEAN', TRUE, TRUE), - ('autoplay', 'Automatically start playing the video', 'BOOLEAN', TRUE, TRUE), - ('loop', 'Loop the video', 'BOOLEAN', TRUE, TRUE), - ( - 'reverse', - 'Reverse the order of the image and text: the image will be on the left, and the text on the right. On small screens, the image will be above the text.', - 'BOOLEAN', - TRUE, - TRUE - ), - -- item level - ( - 'title', - 'The name of a single feature section highlighted by this hero.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'description', - 'Description of the feature section.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'description_md', - 'Description of the feature section - formatted using markdown.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'icon', - 'Icon of the feature section.', - 'ICON', - FALSE, - TRUE - ), - ( - 'color', - 'Color of the badge behind the feature section''s icon. Defaults to "success".', - 'COLOR', - FALSE, - TRUE - ), - ( - 'link', - 'An URL to which the user should be taken when they click on the section title.', - 'TEXT', - FALSE, - TRUE - ) - ) x; - -INSERT INTO - example(component, description, properties) -VALUES - ( - 'hero', - 'The simplest possible hero section', - json( - '[{ - "component":"hero", - "title": "Welcome", - "description": "This is a very simple site built with SQLPage." - }]' - ) - ), - ( - 'hero', - 'A hero with a background image.', - json( - '[{ - "component":"hero", - "title": "SQLPage", - "description_md": "Documentation for the *SQLPage* low-code web application framework.", - "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Lac_de_Zoug.jpg/1280px-Lac_de_Zoug.jpg", - "link": "/documentation.sql", - "link_text": "Read Documentation !"},' || '{"title": "Fast", "description": "Pages load instantly, even on slow mobile networks.", "icon": "car", "color": "red", "link": "/"},' || '{"title": "Beautiful", "description": "Uses pre-defined components that look professional.", "icon": "eye", "color": "green", "link": "/"},' || '{"title": "Easy", "description_md": "You can teach yourself enough SQL to use [**SQLPage**](https://sql-page.com) in a weekend.", "icon": "sofa", "color": "blue", "link": "/"}' || ']' - ) - ), - ( - 'hero', - 'A hero with a video', - json( - '[{ - "component":"hero", - "title": "Databases", - "reverse": true, - "description_md": "# “The goal is to turn data into information, and information into insight.”", - "poster": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Lac_de_Zoug.jpg/1280px-Lac_de_Zoug.jpg", - "video": "/sqlpage_introduction_video.mp4" - }]') - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/03_alert_component.sql b/examples/official-site/sqlpage/migrations/03_alert_component.sql deleted file mode 100644 index 92e672c29..000000000 --- a/examples/official-site/sqlpage/migrations/03_alert_component.sql +++ /dev/null @@ -1,188 +0,0 @@ --- Alert component -INSERT INTO component(name, icon, description) -VALUES ( - 'alert', - 'alert-triangle', - 'A visually distinctive message or notification.' - ); -INSERT INTO parameter( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'alert', - 'title', - 'Title of the alert message.', - 'TEXT', - TRUE, - FALSE - ), - ( - 'alert', - 'icon', - 'Icon name (from tabler-icons.io) to display next to the alert message.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'color', - 'The color theme for the alert message.', - 'COLOR', - TRUE, - TRUE - ), - ( - 'alert', - 'description', - 'Detailed description or content of the alert message.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'description_md', - 'Detailed description or content of the alert message, in Markdown format, allowing you to use rich text formatting, including `**bold**` and `*italic*` text.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'dismissible', - 'Whether the user can close the alert message.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'alert', - 'important', - 'Set this to TRUE to make the alert message more prominent.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'alert', - 'link', - 'A URL to link to from the alert message.', - 'URL', - TRUE, - TRUE - ), - ( - 'alert', - 'link_text', - 'Customize the text of the link in the alert message. The default is "Ok".', - 'TEXT', - TRUE, - TRUE - ), - ( - 'alert', - 'link', - 'A URL to link to from the alert message.', - 'URL', - FALSE, - TRUE - ), - ( - 'alert', - 'title', - 'Customize the text of the link in the alert message. The default is "Ok".', - 'TEXT', - FALSE, - TRUE - ), - ( - 'alert', - 'color', - 'Customize the color of the link.', - 'COLOR', - FALSE, - TRUE - ); --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'alert', - 'A basic alert message', - JSON( - '[{"component":"alert", "title":"Attention", "description":"This is an important message."}]' - ) - ), - ( - 'alert', - 'A list of notifications', - JSON( - '[ - {"component" :"alert", "title":"Success","description":"Item successfully added to your cart.", "icon":"check", "color": "green"}, - {"component":"alert", "title":"Warning","description":"Your cart is almost full.", "icon":"alert-triangle", "color": "yellow"}, - {"component":"alert", "title":"Error","description":"Your cart is full.", "icon":"alert-circle", "color": "red"} - ]' - ) - ), - ( - 'alert', - 'A full-featured notification message with multiple links', - JSON( - '[ - { - "component" :"alert", - "title": "Your dashboard is ready!", - "icon":"analyze", - "color":"teal", - "dismissible": true, - "description":"Your public web dashboard was successfully created." - }, - { - "link":"dashboard.sql", - "title": "View your dashboard" - }, - { - "link" :"index.sql", - "title": "Back to home", - "color": "secondary" - } - ]' - ) - ), - ( - 'alert', - 'An important danger alert message with an icon and color', - JSON( - '[ - { - "component":"alert", - "title":"Alert", - "icon":"alert-circle", - "color":"red", - "important": true, - "dismissible": true, - "description":"SQLPage is entirely free and open source.", - "link":"https://github.com/sqlpage/SQLPage", - "link_text":"See source code" - }]' - ) - ), - ( - 'alert', - 'An alert message with a Markdown-formatted description', - JSON( - '[ - { - "component":"alert", - "title":"Free and open source", - "icon": "free-rights", - "color": "info", - "description_md":"*SQLPage* is entirely free and open source. You can **contribute** to it on [GitHub](https://github.com/sqlpage/SQLPage)." - }]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/04_http_header.sql b/examples/official-site/sqlpage/migrations/04_http_header.sql deleted file mode 100644 index 1667e4260..000000000 --- a/examples/official-site/sqlpage/migrations/04_http_header.sql +++ /dev/null @@ -1,116 +0,0 @@ --- Insert the http_header component into the component table -INSERT INTO component (name, description, icon) -VALUES ( - 'http_header', - ' -An advanced component to set arbitrary HTTP headers: can be used to set a custom caching policy to your pages, or implement custom redirections, for example. -If you are a beginner, you probably don''t need this component. - -When used, this component has to be the first component in the page, because once the page is sent to the browser, it is too late to change the headers. - -HTTP headers are additional pieces of information sent with responses to web requests that provide instructions -or metadata about the data being sent — for example, -setting cache control directives to control caching behavior -or specifying the content type of a response. - -Any valid HTTP header name can be used as a top-level parameter for this component. -The examples shown here are just that, examples; and you can create any custom header -if needed simply by declaring it. - -If your header''s name contains a dash or any other special character, -you will have to use your database''s quoting mechanism to declare it. -In standard SQL, you can use double quotes to quote identifiers (like "X-My-Header"), -in Microsoft SQL Server, you can use square brackets (like [X-My-Header]). - ', - 'world-www' - ); --- Insert the parameters for the http_header component into the parameter table -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'http_header', - 'Cache-Control', - 'Directives for how long the page should be cached by the browser. Set this to max-age=N to keep the page in cache for N seconds.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'http_header', - 'Content-Disposition', - 'Provides instructions on how the response content should be displayed or handled by the client, such as inline or as an attachment.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'http_header', - 'Location', - 'Specifies the URL to redirect the client to, usually used in 3xx redirection responses.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'http_header', - 'Set-Cookie', - 'Sets a cookie in the client browser, used for session management and storing user-related information.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'http_header', - 'Access-Control-Allow-Origin', - 'Specifies which origins are allowed to access the resource in a cross-origin request, used for implementing Cross-Origin Resource Sharing (CORS).', - 'TEXT', - TRUE, - TRUE - ); - --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description, properties) -VALUES ( - 'http_header', - 'Set cache control directives for caching behavior. In this example, the response can be cached by the browser - and served from the cache for up to 600 seconds (10 minutes) after it is first requested. - During that time, even if the cached response becomes stale (outdated), the browser can still use it (stale-while-revalidate) - for up to 3600 seconds (1 hour) while it retrieves a fresh copy from the server in the background. - If there is an error while trying to retrieve a fresh copy from the server, - the browser can continue to serve the stale response for up to 86400 seconds (24 hours) (stale-if-error) instead of showing an error page. - This caching behavior helps improve the performance and responsiveness of the website by reducing the number of requests made to the server - and allowing the browser to serve content from its cache when appropriate.', - JSON( - '[{ - "component": "http_header", - "Cache-Control": "public, max-age=600, stale-while-revalidate=3600, stale-if-error=86400" - }]' - ) - ), - ( - 'http_header', - 'Redirect the user to another page. In this example, the user is redirected to a file named another-page.sql at the root of the website. The current page will not be displayed at all. - This is useful in particular for content creation pages that contain only INSERT statements, because you can redirect the user to the page that lists the content after it has been created.', - JSON( - '[{ - "component": "http_header", - "Location": "/another-page.sql" - }]' - ) - ), - ( - 'http_header', - 'Set a custom non-standard header for the response. In this example, the response will include a custom header named X-My-Header with the value "my value".', - JSON( - '[{ - "component": "http_header", - "X-My-Header": "my value" - }]' - ) - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/05_cookie.sql b/examples/official-site/sqlpage/migrations/05_cookie.sql deleted file mode 100644 index 3b3816546..000000000 --- a/examples/official-site/sqlpage/migrations/05_cookie.sql +++ /dev/null @@ -1,125 +0,0 @@ --- Insert the http_header component into the component table -INSERT INTO component (name, description, icon) -VALUES ( - 'cookie', - ' -Sets a cookie in the client browser, used for session management and storing user-related information. - -This component creates a single cookie. Since cookies need to be set before the response body is sent to the client, -this component should be **placed at the top of the page**, before any other components that generate output. - -After being set, a cookie can be accessed anywhere in your SQL code using the `sqlpage.cookie(''cookie_name'')` pseudo-function. - -Note that if your site is accessed over HTTP (and not HTTPS), you have to set `false as secure` to force browsers to accept your cookies.', - 'cookie' - ); --- Insert the parameters for the http_header component into the parameter table -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'cookie', - 'name', - 'The name of the cookie to set.', - 'TEXT', - TRUE, - FALSE - ), - ( - 'cookie', - 'value', - 'The value of the cookie to set.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'cookie', - 'path', - 'The path for which the cookie will be sent. If not specified, the cookie will be sent for all paths.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'cookie', - 'domain', - 'The domain for which the cookie will be sent. If not specified, the cookie will be sent for all domains.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'cookie', - 'secure', - 'Whether the cookie should only be sent over a secure (HTTPS) connection. Defaults to TRUE.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'cookie', - 'http_only', - 'Whether the cookie should only be accessible via HTTP and not via client-side scripts. If explicitly set to false, the cookie will be accessible via both HTTP and client-side scripts.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'cookie', - 'remove', - 'Set to TRUE to remove the cookie from the client browser. When specified, other parameters are ignored.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'cookie', - 'max_age', - 'The maximum age of the cookie in seconds. number of seconds until the cookie expires. If both Expires and Max-Age are set, Max-Age has precedence.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'cookie', - 'expires', - 'The date at which the cookie expires (either a timestamp or a date object). If not specified, the cookie will expire when the browser is closed.', - 'TIMESTAMP', - TRUE, - TRUE - ), - ( - 'cookie', - 'same_site', - 'Whether the cookie should only be sent for requests originating from the same site. See owasp.org/www-community/SameSite. `strict` is the recommended and default value, but you may want to set it to `lax` if you want your users to keep their session when they click on a link to your site from an external site.', - 'TEXT', - TRUE, - TRUE - ); --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description) -VALUES ( - 'cookie', - 'Create a cookie named `username` with the value `John Doe`... - -```sql -SELECT ''cookie'' as component, - ''username'' as name, - ''John Doe'' as value - FALSE AS secure; -- You can remove this if the site is served over HTTPS. -``` - -and then display the value of the cookie using the [`sqlpage.cookie`](functions.sql?function=cookie) function: - -```sql -SELECT ''text'' as component, - ''Your name is '' || COALESCE(sqlpage.cookie(''username''), ''not known to us''); -``` - ' - ); diff --git a/examples/official-site/sqlpage/migrations/06_debug.sql b/examples/official-site/sqlpage/migrations/06_debug.sql deleted file mode 100644 index 7df4263b5..000000000 --- a/examples/official-site/sqlpage/migrations/06_debug.sql +++ /dev/null @@ -1,25 +0,0 @@ --- Insert the http_header component into the component table -INSERT INTO component (name, description, icon) -VALUES ( - 'debug', - 'Visualize any set of values as JSON. -Can be used to display all the parameters passed to the component. -Useful for debugging: just replace the name of the component you want to debug with ''debug'', and see all the top-level and row-level parameters that are passed to it, and their types.', - 'bug' - ); --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description, properties) -VALUES ( - 'debug', - 'At any time, if you are confused about what data you are passing to a component, just replace the component name with ''debug'' to see all the parameters that are passed to it.', - JSON('[{"component": "debug", "my_top_level_property": true}, {"x": "y", "z": 42}, {"a": "b", "c": null}]') - ), - ( - 'debug', - 'Show the result of a SQLPage function: - -```sql -select ''debug'' as component, sqlpage.environment_variable(''HOME''); -```', - NULL - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/07_authentication.sql b/examples/official-site/sqlpage/migrations/07_authentication.sql deleted file mode 100644 index ca44e9c48..000000000 --- a/examples/official-site/sqlpage/migrations/07_authentication.sql +++ /dev/null @@ -1,189 +0,0 @@ --- Insert the http_header component into the component table -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'authentication', - ' -Create pages with password-restricted access. - - -When you want to add user authentication to your SQLPage application, -you have two main options: - -1. The `authentication` component: - - lets you manage usernames and passwords yourself - - does not require any external service - - gives you fine-grained control over - - which pages and actions are protected - - the look of the [login form](?component=login) - - the duration of the session - - the permissions of each user -2. [**Single sign-on**](/sso) - - lets users log in with their existing accounts (like Google, Microsoft, or your organization''s own identity provider) - - requires setting up an external service (Google, Microsoft, etc.) - - frees you from implementing a lot of features like password reset, account creation, user management, etc. - -This page describes the first option. - -When used, this component has to be at the top of your page, -because once the page has begun being sent to the browser, -it is too late to restrict access to it. - -The authentication component checks if the user has sent the correct password, -and if not, redirects them to the URL specified in the link parameter. - -If you don''t want to re-check the password on every page (which is an expensive operation), -you can check the password only once and store a session token in your database -(see the session example below). - -You can use the [cookie component](?component=cookie) to set the session token cookie in the client browser, -and then check whether the token matches what you stored in subsequent pages.', - 'lock', - '0.7.2' - ); --- Insert the parameters for the http_header component into the parameter table -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'authentication', - 'link', - 'The URL to redirect the user to if they are not logged in. If this parameter is not specified, the user will stay on the current page, but be asked to log in using a popup in their browser (HTTP basic authentication).', - 'TEXT', - TRUE, - TRUE - ), - ( - 'authentication', - 'password', - 'The password that was sent by the user. You can set this to :password if you have a login form leading to your page.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'authentication', - 'password_hash', - 'The hash of the password that you stored for the user that is currently trying to log in. These hashes can be generated ahead of time using a tool like https://argon2.online/.', - 'TEXT', - TRUE, - TRUE - ); - --- Insert an example usage of the http_header component into the example table -INSERT INTO example (component, description) -VALUES ( - 'authentication', - ' - -### Usage with HTTP basic authentication - -The most basic usage of the authentication component is with the -[`sqlpage.basic_auth_username()`](functions.sql?function=basic_auth_username#function) and -[`sqlpage.basic_auth_password()`](functions.sql?function=basic_auth_password#function) functions. -The component will check if the provided password matches the stored [password hash](/examples/hash_password.sql), -and if not, it will prompt the user to enter a password in a browser popup: - -```sql -SELECT ''authentication'' AS component, - ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w'' AS password_hash, -- this is a hash of the password ''password'' - sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup -``` - -You can [generate a password hash using the `hash_password` function](/examples/hash_password.sql). - -If you want to have multiple users with different passwords, -you could store them with their password hashes in the database, -or just hardcode them use a `CASE` statement: - -```sql -SELECT ''authentication'' AS component, - case sqlpage.basic_auth_username() - when ''admin'' - then ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$oKBq5E8XFTHO2w'' -- the password is ''password'' - when ''user'' - then ''$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$qsrWdjgl96ooYw'' -- the password is ''user'' - end AS password_hash, -- this is a hash of the password ''password'' - sqlpage.basic_auth_password() AS password; -- this is the password that the user entered in the browser popup -``` - -Try this example online: [SQL Basic Auth](/examples/authentication/basic_auth.sql). - -### Advanced user session management - -*Basic auth* is the simplest way to password-protect a page, -but it is not very flexible nor user-friendly, -because the browser will show an unstyled popup asking for the username and password. - -For more advanced authentication, you can store user information and user sessions in your database. -You can then use the [`form`](/component.sql?component=form#component) component to create a custom login form. -When the user submits the form, you check if the password is correct using the `authentication` component. -You then store a unique string of numbers and letters (a session token) both in the user''s browser -using the [`cookie`](/component.sql?component=cookie#component) component and in your database. -Then, in all the pages that require authentication, you check if the cookie is present and matches the session token in your database. - -You can check if the user has sent the correct password in a form, and if not, redirect them to a login page. - -Create a login form in a file called `login.sql` that uses the [login component](?component=login): - -```sql -select ''login'' as component; -``` - -And then, in `create_session_token.sql` : - -```sql -SELECT ''authentication'' AS component, - ''login.sql'' AS link, - ''$argon2id$v=19$m=16,t=2,p=1$TERTd0lIcUpraWFTcmRQYw$+bjtag7Xjb6p1dsuYOkngw'' AS password_hash, -- generated using sqlpage.hash_password - :password AS password; -- this is the password that the user sent through our form - --- The code after this point is only executed if the user has sent the correct password - -``` - -and in `login.sql` : - -```sql -SELECT ''form'' AS component, ''Login'' AS title, ''my_protected_page.sql'' AS action; -SELECT ''password'' AS type, ''password'' AS name, ''Password'' AS label; -``` - -### Advanced: usage with a session token - -Calling the `authentication` component is expensive. -The password hashing algorithm is designed to be slow, so that it is difficult to brute-force the password, -even if an attacker gets access to the database. - -If you want to avoid calling the `authentication` component on every page, you can use a session token. -A session token is a random string that is generated when the user logs in, and stored in the database. -It has a limited lifetime, and is stored in a cookie in the user''s browser. -When the user visits a page, the session token is sent to the server, and the server checks if it is valid. - -```sql -SELECT ''authentication'' AS component, - ''login.sql'' AS link, - (SELECT password_hash FROM user WHERE username = :username) AS password_hash, - :password AS password; - --- The code after this point is only executed if the user has sent the correct password - --- Generate a random session token -INSERT INTO session (id, username) -VALUES (sqlpage.random_string(32), :username) -RETURNING - ''cookie'' AS component, - ''session_token'' AS name, - id AS value; -``` - -### Single sign-on with OIDC (OpenID Connect) - -If you don''t want to manage your own user database, -you can [use OpenID Connect and OAuth2](/sso) to authenticate users. -This allows users to log in with their Google, Microsoft, or internal company account. -'); diff --git a/examples/official-site/sqlpage/migrations/08_functions.sql b/examples/official-site/sqlpage/migrations/08_functions.sql deleted file mode 100644 index 30a8a7835..000000000 --- a/examples/official-site/sqlpage/migrations/08_functions.sql +++ /dev/null @@ -1,484 +0,0 @@ -CREATE TABLE IF NOT EXISTS sqlpage_functions ( - "name" TEXT PRIMARY KEY, - "icon" TEXT, - "description_md" TEXT, - "return_type" TEXT, - "introduced_in_version" TEXT -); -CREATE TABLE IF NOT EXISTS sqlpage_function_parameters ( - "function" TEXT REFERENCES sqlpage_functions("name"), - "index" INTEGER, - "name" TEXT, - "description_md" TEXT, - "type" TEXT -); -INSERT INTO sqlpage_functions ( - "name", - "return_type", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'cookie', - 'TEXT', - '0.7.1', - 'cookie', - 'Reads a [cookie](https://en.wikipedia.org/wiki/HTTP_cookie) with the given name from the request. -Returns the value of the cookie as text, or NULL if the cookie is not present. - -Cookies can be set using the [cookie component](documentation.sql?component=cookie#component). - -### Example - -#### Set a cookie - -Set a cookie called `username` to greet the user by name every time they visit the page: - -```sql -select ''cookie'' as component, ''username'' as name, :username as value; - -SELECT ''form'' as component; -SELECT ''username'' as name, ''text'' as type; -``` - -#### Read a cookie - -Read a cookie called `username` and greet the user by name: - -```sql -SELECT ''text'' as component, - ''Hello, '' || sqlpage.cookie(''username'') || ''!'' as contents; -``` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'cookie', - 1, - 'name', - 'The name of the cookie to read.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'header', - '0.7.2', - 'heading', - 'Reads a [header](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) with the given name from the request. - Returns the value of the header as text, or NULL if the header is not present. - -### Example - -Log the [`User-Agent`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) of the browser making the request in the database: - -```sql -INSERT INTO user_agent_log (user_agent) VALUES (sqlpage.header(''user-agent'')); -``` - -If you need access to all headers at once, use [`sqlpage.headers()`](?function=headers) instead. - ' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'header', - 1, - 'name', - 'The name of the HTTP header to read.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "return_type", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'basic_auth_username', - 'TEXT', - '0.7.2', - 'user', - 'Returns the username from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. - If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials. - -### Example - -```sql -SELECT ''authentication'' AS component, - (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, - sqlpage.basic_auth_password() AS password; -``` - -' - ), - ( - 'basic_auth_password', - 'TEXT', - '0.7.2', - 'key', - 'Returns the password from the [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) header of the request. - If the header is not present, this function raises an authorization error that will prompt the user to enter their credentials. - -### Example - -```sql -SELECT ''authentication'' AS component, - (SELECT password_hash from users where name = sqlpage.basic_auth_username()) AS password_hash, - sqlpage.basic_auth_password() AS password; -``` -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'hash_password', - '0.7.2', - 'spy', - ' -Hashes a password with the Argon2id variant and outputs it in the [PHC string format](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md), ready to store in your users table. - -Every call generates a brand new cryptographic salt so that two people choosing the same password still end up with different hashes, which defeats rainbow-table attacks and lets you safely reveal only the hash. - -Use this function only when creating or resetting a password (for example while inserting a brand new user): it writes the stored value. Later, at login time, the [authentication component](documentation.sql?component=authentication#component) reads the stored hash, hashes the visitor''s password with the embedded salt and parameters, and grants access only if they match. - -### Example - -```sql -SELECT ''form'' AS component; -SELECT ''username'' AS name; -SELECT ''password'' AS name, ''password'' AS type; - -INSERT INTO users (name, password_hash) VALUES (:username, sqlpage.hash_password(:password)); -``` - -### Try online - -You can try the password hashing function [on this page](/examples/hash_password.sql). - ' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'hash_password', - 1, - 'password', - 'The password to hash.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'random_string', - '0.7.2', - 'arrows-shuffle', - 'Returns a cryptographically secure random string of the given length. - -When used as a standalone selected column in a query that returns several rows, `random_string` runs once per returned row. -Use `SET token = sqlpage.random_string(32)` first if you want one token reused later in the page. - -### Example - -Generate a random string of 32 characters and use it as a session ID stored in a cookie: - -```sql -INSERT INTO login_session (session_token, username) VALUES (sqlpage.random_string(32), :username) -RETURNING - ''cookie'' AS component, - ''session_id'' AS name, - session_token AS value; -``` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'random_string', - 1, - 'length', - 'The length of the string to generate.', - 'INTEGER' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'current_working_directory', - '0.11.0', - 'folder-question', - 'Returns the [current working directory](https://en.wikipedia.org/wiki/Working_directory) of the SQLPage server process. - -### Example - -```sql -SELECT ''text'' AS component; -SELECT ''Currently running from '' AS contents; -SELECT sqlpage.current_working_directory() as contents, true as code; -``` - -#### Result - -Currently running from `/home/user/my_sqlpage_website` - -#### Notes - -The current working directory is the directory from which the SQLPage server process was started. -By default, this is also the directory from which `.sql` files are loaded and served. -However, this can be changed by setting the `web_root` [configuration option](https://github.com/sqlpage/SQLPage/blob/main/configuration.md). -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'web_root', - '0.42.0', - 'folder-code', - 'Returns the web root directory where SQLPage serves `.sql` files from. - -### Example - -```sql -SELECT ''text'' AS component; -SELECT ''SQL files are served from '' AS contents; -SELECT sqlpage.web_root() as contents, true as code; -``` - -#### Result - -SQL files are served from `/home/user/my_sqlpage_website` - -#### Notes - -The web root is the directory from which `.sql` files are loaded and served. -By default, it is the current working directory, but it can be changed using: - - the `--web-root` command line argument - - the `web_root` [configuration option](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) in `sqlpage.json` - - the `WEB_ROOT` environment variable - -This is more reliable than `sqlpage.current_working_directory()` when you need to reference the location of your SQL files. -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'configuration_directory', - '0.42.0', - 'folder-cog', - 'Returns the configuration directory where SQLPage looks for `sqlpage.json`, templates, and migrations. - -### Example - -```sql -SELECT ''text'' AS component; -SELECT ''Configuration files are in '' AS contents; -SELECT sqlpage.configuration_directory() as contents, true as code; -``` - -#### Result - -Configuration files are in `/home/user/my_sqlpage_website/sqlpage` - -#### Notes - -The configuration directory is where SQLPage looks for: - - `sqlpage.json` (the configuration file) - - `templates/` (custom component templates) - - `migrations/` (database migration files) - -By default, it is `./sqlpage` relative to the current working directory, but it can be changed using: - - the `--config-dir` command line argument - - the `SQLPAGE_CONFIGURATION_DIRECTORY` or `CONFIGURATION_DIRECTORY` environment variable - -This function is useful when you need to reference configuration-related files in your SQL code. -' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'environment_variable', - '0.11.0', - 'variable', - 'Returns the value of the given [environment variable](https://en.wikipedia.org/wiki/Environment_variable). - -### Example - -```sql -SELECT ''text'' AS component; -SELECT ''The value of the HOME environment variable is '' AS contents; -SELECT sqlpage.environment_variable(''HOME'') as contents, true as code; -```' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'environment_variable', - 1, - 'name', - 'The name of the environment variable to read. Must be a literal string.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'version', - '0.11.0', - 'git-commit', - 'Returns the current version of SQLPage as a string.' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'exec', - '0.12.0', - 'terminal-2', - 'Executes a shell command and returns its output as text. - -### Example - -#### Fetch data from a remote API using curl - -```sql -select ''card'' as component; -select value->>''name'' as title, value->>''email'' as description -from json_each(sqlpage.exec(''curl'', ''https://jsonplaceholder.typicode.com/users'')); -``` - -#### Notes - - - This function is disabled by default for security reasons. You can enable it by setting `"allow_exec" : true` in `sqlpage/sqlpage.json`. Enable it only if you trust all the users that can access your SQLPage server files (both locally and on the database). - - Be careful when using this function, as it can be used to execute arbitrary shell commands on your server. Do not use it with untrusted input. - - The command is executed in the current working directory of the SQLPage server process. - - The command is executed with the same user as the SQLPage server process. - - The environment variables of the SQLPage server process are passed to the command, including potentially sensitive variables such as `DATABASE_URL`. - - The command is executed asynchronously, but the SQLPage server has to wait for it to finish before sending the result to the client. - This means that the SQLPage server will not be blocked while the command is running, it will be able to serve other requests, but it will not be able to serve the current request until the command has finished. - You should generally avoid long running commands. - - If the program name is NULL, the result will be NULL. - - If any argument is NULL, it will be passed to the command as an empty string. - - If the command exits with a non-zero exit code, the function will raise an error. - - Arbitrary SQL operations are not allowed as sqlpage function arguments. Use `SET` to assign the result of a SQL query to a variable, and then use that variable as an argument to `sqlpage.exec`. - - When `sqlpage.exec(...)` is a standalone selected column, the command runs once per returned row. Use `SET command_result = sqlpage.exec(...)` first if the command should run only once for the page. -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'exec', - 1, - 'program', - 'The name of the program to execute. Must be a literal string.', - 'TEXT' - ), - ( - 'exec', - 2, - 'arguments...', - 'The arguments to pass to the program.', - 'TEXT' - ); -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'url_encode', - '0.12.0', - 'percentage', - 'Returns the given string, with all characters that are not allowed in a URL encoded. - -### Example - -```sql -select ''text'' as component; -select ''https://example.com/?q='' || sqlpage.url_encode($user_search) as contents; -``` - -#### Result - -`https://example.com/?q=hello%20world` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'url_encode', - 1, - 'string', - 'The string to encode.', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/10_map.sql b/examples/official-site/sqlpage/migrations/10_map.sql deleted file mode 100644 index 8ef4693b0..000000000 --- a/examples/official-site/sqlpage/migrations/10_map.sql +++ /dev/null @@ -1,265 +0,0 @@ -INSERT INTO - component (name, description, icon, introduced_in_version) -VALUES - ( - 'map', - ' - -## Visualize SQL data on a map. - -The map component displays a custom interactive map with markers on it. - -In its simplest form, the component displays points on a map from a table of latitudes and longitudes. -But it can also be used by cartographers in combination with PostgreSQL''s PostGIS or SQLite''s spatialite, -to create custom visualizations of geospatial data. -Use the `geojson` property to generate rich maps from a GIS database. - -### Example Use Cases - -1. **Store Locator**: Build an interactive map to find the nearest store information using SQL-stored geospatial data. -2. **Delivery Route Optimization**: Visualize the results of delivery route optimization algorithms. -3. **Sales Heatmap**: Identify high-performing regions by mapping sales data stored in SQL. -4. **Real-Time Tracking**: Create dynamic dashboards that track vehicles, assets, or users live using PostGIS or MS SQL Server geospatial time series data. Use the [shell](?component=shell) component to auto-refresh the map. -5. **Demographic Insights**: Map customer demographics or trends geographically to uncover opportunities for growth or better decision-making. -', - 'map', - '0.8.0' - ); - --- Insert the parameters for the http_header component into the parameter table -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'map', - 'title', - 'A text header displayed above the map.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'map', - 'latitude', - 'Latitude of the center of the map. If omitted, the map will be centered on its markers.', - 'REAL', - TRUE, - TRUE - ), - ( - 'map', - 'longitude', - 'Longitude of the center of the map.', - 'REAL', - TRUE, - TRUE - ), - ( - 'map', - 'zoom', - 'Zoom Level to apply to the map. Defaults to 5.', - 'REAL', - TRUE, - TRUE - ), - ( - 'map', - 'max_zoom', - 'How far the map can be zoomed in. Defaults to 18. Added in v0.15.2.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'map', - 'tile_source', - 'Custom map tile images to use, as a URL. Defaults to "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png". Added in v0.15.2.', - 'URL', - TRUE, - TRUE - ), - ( - 'map', - 'attribution', - 'Text to display at the bottom right of the map. Defaults to "© OpenStreetMap".', - 'HTML', - TRUE, - TRUE - ), - ( - 'map', - 'height', - 'Height of the map, in pixels. Default to 350px', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'map', - 'latitude', - 'Latitude of the marker. Required only if geojson is not set.', - 'REAL', - FALSE, - FALSE - ), - ( - 'map', - 'longitude', - 'Longitude of the marker. Required only if geojson is not set.', - 'REAL', - FALSE, - FALSE - ), - ( - 'map', - 'title', - 'Title of the marker, displayed on hover and in the tooltip when the marker is clicked.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'map', - 'link', - 'A link to associate to the marker''s title. If set, the marker tooltip''s title will be clickable and will open the link.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'map', - 'description', - 'Plain text description of the marker, to be displayed in a tooltip when the marker is clicked.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'map', - 'description_md', - 'Description of the marker, in markdown, rendered in a tooltip when the marker is clicked.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'map', - 'icon', - 'Name of the icon to use for the marker', - 'ICON', - FALSE, - TRUE - ), - ( - 'map', - 'color', - 'Background color of the marker on the map. Requires "icon" to be set.', - 'COLOR', - FALSE, - TRUE - ), - ( - 'map', - 'geojson', - 'A GeoJSON geometry (line, polygon, ...) to display on the map. Can be styled using geojson properties using the name of leaflet path options. Introduced in 0.15.1. Accepts raw strings in addition to JSON objects since 0.15.2.', - 'JSON', - FALSE, - TRUE - ), - ( - 'map', - 'size', - 'Size of the marker icon. Requires "icon" to be set. Introduced in 0.15.2.', - 'INTEGER', - FALSE, - TRUE - ); - --- Insert an example usage of the map component into the example table -INSERT INTO - example (component, description, properties) -VALUES - ( - 'map', - ' -### Adding a marker to a map - -Showing how to place a marker on a map. Useful for basic location displays like showing a single office location, event venue, or point of interest. The marker shows basic hover and click interactions. -', - JSON ( - '[{ "component": "map" }, { "title": "New Delhi", "latitude": 28.6139, "longitude": 77.2090 }]' - ) - ), - ( - 'map', - ' -### Advanced map customization using GeoJSON and custom map tiles - -This example demonstrates using topographic map tiles, custom marker styling, -and clickable markers that link to external content - perfect for educational or tourism applications. - -It uses [GeoJSON](https://en.wikipedia.org/wiki/GeoJSON) to display polygons and lines. - - - You can generate GeoJSON data from PostGIS geometries using the [`ST_AsGeoJSON`](https://postgis.net/docs/ST_AsGeoJSON.html) function. - - In spatialite, you can use the [`AsGeoJSON`](https://www.gaia-gis.it/gaia-sins/spatialite-sql-5.1.0.html#p3misc) function. - - In MySQL, you can use the [`ST_AsGeoJSON()`](https://dev.mysql.com/doc/refman/8.0/en/spatial-geojson-functions.html#function_st-asgeojson) function. -', - JSON ( - '[{ "component": "map", "zoom": 5, "max_zoom": 8, "height": 600, "latitude": -25, "longitude": 28, "tile_source": "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", "attribution": "" }, - { "icon": "peace", - "size": 20, - "link": "https://en.wikipedia.org/wiki/Nelson_Mandela", - "geojson": "{\"type\":\"Feature\", \"properties\": { \"title\":\"Mvezo, Birth Place of Nelson Mandela\" }, \"geometry\": { \"type\":\"Point\", \"coordinates\": [28.49, -31.96] }}"}]' - ) - ), - ( - 'map', - ' -### Maps with links and rich descriptions - -Demonstrates how to create an engaging map with custom icons, colors, rich descriptions with markdown support, and connecting points with lines. -Perfect for visualizing multi-dimensional relationships between points on a map, like routes between locations. - -Note that the map tile source is set to a MapTiler map. The API key included in the URL in this demo will not work on your own website. -You should get your own API key at [MapTiler](https://www.maptiler.com/cloud/). -', - JSON ( - '[ - { "component": "map", "title": "Paris", "zoom": 13, "latitude": 48.85, "longitude": 2.34, "tile_source": "https://api.maptiler.com/maps/streets-v2/{z}/{x}/{y}.png?key=RwoF6Y3gcKx4OBMbvqOY" }, - { "title": "Notre Dame", "icon": "building-castle", "color": "indigo", "latitude": 48.8530, "longitude": 2.3498, "description_md": "A beautiful cathedral.", "link": "https://en.wikipedia.org/wiki/Notre-Dame_de_Paris" }, - { "title": "Eiffel Tower", "icon": "tower", "color": "red", "latitude": 48.8584, "longitude": 2.2945, "description_md": "A tall tower. [Wikipedia](https://en.wikipedia.org/wiki/Eiffel_Tower)" }, - { "title": "Tower to Cathedral", "geojson": {"type": "LineString", "coordinates": [[2.2945, 48.8584], [2.3498, 48.8530]]}, "color": "teal", "description": "A nice 45 minutes walk." } - ]' - ) - ), - ( - 'map', - ' -### Abstract geometric visualizations - -Example showing how to create abstract geometric visualizations without a base map. -Useful for displaying spatial data that doesn''t need geographic context, like floor plans, seating charts, -or abstract 2D data visualizations. -', - JSON ( - '[ - { "component": "map", "tile_source": false }, - { "title": "MySQL", - "color": "red", "description": "This literal red square is defined as a GeoJSON polygon. Each (x,y) coordinate is a JSON array.", - "geojson": {"type": "Polygon", "coordinates": [[[0, 0], [0, 4], [4, 4], [4, 0], [0, 0]]]} - }, - { - "title": "SQLite", - "color": "blue", "description": "This 2D shape was generated by a SQL query.", - "geojson": {"type": "Polygon", "coordinates": [[[5, 0], [9, 0], [7, 4], [5, 0]]]} - } - ]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/11_json.sql b/examples/official-site/sqlpage/migrations/11_json.sql deleted file mode 100644 index 8384ab58c..000000000 --- a/examples/official-site/sqlpage/migrations/11_json.sql +++ /dev/null @@ -1,211 +0,0 @@ -INSERT INTO - component (name, description, icon, introduced_in_version) -VALUES - ( - 'json', - 'Converts SQL query results into the JSON machine-readable data format. Ideal to quickly build APIs for interfacing with external systems. - -**JSON** is a widely used data format for programmatic data exchange. -For example, you can use it to integrate with web services written in different languages, -with mobile or desktop apps, or with [custom client-side components](/custom_components.sql) inside your SQLPage app. - -Use it when your application needs to expose data to external systems. -If you only need to render standard web pages, -and do not need other software to access your data, -you can ignore this component. - -This component **must appear at the top of your SQL file**, before any other data has been sent to the browser. -An HTTP response can have only a single datatype, and it must be declared in the headers. -So if you have already called the `shell` component, or another traditional HTML component, -you cannot use this component in the same file. - -SQLPage can also return JSON or JSON Lines when the incoming request says it prefers them with an HTTP `Accept` header, so the same `/users.sql` page can show a table in a browser but return raw data to `curl -H "Accept: application/json" http://localhost:8080/users.sql`. - -Use this component when you want to control the payload or force JSON output even for requests that would normally get HTML. -', - 'code', - '0.9.0' - ); - --- Insert the parameters for the http_header component into the parameter table -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'json', - 'contents', - 'A single JSON payload to send. You can use your database''s built-in json functions to build the value to enter here. If not provided, the contents will be taken from the next SQL statements and rendered as a JSON array.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'json', - 'type', - 'The type of the JSON payload to send: "array", "jsonlines", or "sse". -In "array" mode, each query result is rendered as a JSON object in a single top-level array. -In "jsonlines" mode, results are rendered as JSON objects in separate lines, without a top-level array. -In "sse" mode, results are rendered as JSON objects in separate lines, prefixed by "data: ", which allows you to read the results as server-sent events in real-time from javascript.', - 'TEXT', - TRUE, - TRUE - ); - --- Insert an example usage of the http_header component into the example table -INSERT INTO - example (component, description) -VALUES - ( - 'json', - ' -## Send query results as a single JSON array: `''array'' as type` - -The default `array` mode sends the query results as a single JSON array. - -If a query returns an error, the array will contain an object with an `error` property. - -If multiple queries are executed, all query results will be concatenated into a single array -of heterogeneous objects. - -### SQL - -```sql -select ''json'' AS component; -select * from users; -``` - -### Result - -```json -[ - {"username":"James","userid":1}, - {"username":"John","userid":2} -] -``` - -Clients can also receive JSON or JSON Lines automatically by requesting the same SQL file with an HTTP `Accept` header such as `application/json` or `application/x-ndjson` when the component is omitted, for example: - -``` -curl -H "Accept: application/json" http://localhost:8080/users.sql -``` - ' - ), - ( - 'json', - ' -## Send a single JSON object: `''jsonlines'' as type` - -In `jsonlines` mode, each query result is rendered as a JSON object in a separate line, -without a top-level array. - -If there is a single query result, the response will be a valid JSON object. -If there are multiple query results, you will need to parse each line of the response as a separate JSON object. - -If a query returns an error, the response will be a JSON object with an `error` property. - -### SQL - -The following SQL creates an API endpoint that takes a `user_id` URL parameter -and returns a single JSON object containing the user''s details, with one json object key per column in the `users` table. - -```sql -select ''json'' AS component, ''jsonlines'' AS type; -select * from users where id = $user_id LIMIT 1; -``` - -> Note the `LIMIT 1` clause. The `jsonlines` type will send one JSON object per result row, -> separated only by a single newline character (\n). -> So if your query returns multiple rows, the result will not be a single valid JSON object, -> like most JSON parsers expect. - -### Result - -```json -{ "username":"James", "userid":1 } -``` -' - ), - ( - 'json', - ' -## Create a complex API endpoint: the `''contents''` property - -You can create an API endpoint that will return a JSON value in any format you want, -to implement a complex API. - -You should use [the json functions provided by your database](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) to form the value you pass to the `contents` property. -To build a json array out of rows from the database, you can use: - - `json_group_array()` in SQLite, - - `json_agg()` in Postgres, or - - `JSON_ARRAYAGG()` in MySQL. - - `FOR JSON PATH` in SQL Server. - - -```sql -SELECT ''json'' AS component, - JSON_OBJECT( - ''users'', ( - SELECT JSON_GROUP_ARRAY( - JSON_OBJECT( - ''username'', username, - ''userid'', id - ) - ) FROM users - ) - ) AS contents; -``` - -This will return a JSON response that looks like this: - -```json -{ - "users" : [ - { "username":"James", "userid":1 } - ] -} -``` - -If you want to handle custom API routes, like `POST /api/users/:id`, -you can use - - the [`404.sql` file](/your-first-sql-website/custom_urls.sql) to handle the request despite the URL not matching any file, - - the [`request_method` function](/functions.sql?function=request_method#function) to differentiate between GET and POST requests, - - and the [`path` function](/functions.sql?function=path#function) to extract the `:id` parameter from the URL. -' - ), - ( - 'json', - ' -## Access query results in real-time with server-sent events: `''sse'' as type` - -Using server-sent events, you can stream large query results to the client in real-time, -row by row. - -This allows building sophisticated dynamic web applications that will start processing and displaying -the first rows of data in the browser while the database server is still processing the end of the query. - -### SQL - -```sql -select ''json'' AS component, ''sse'' AS type; -select * from users; -``` - -### JavaScript - -```javascript -const eventSource = new EventSource("users.sql"); -eventSource.onmessage = function (event) { - const user = JSON.parse(event.data); - console.log(user.username); -} -eventSource.onerror = () => eventSource.close(); // do not reconnect after reading all the data -``` -' - ); diff --git a/examples/official-site/sqlpage/migrations/12_blog.sql b/examples/official-site/sqlpage/migrations/12_blog.sql deleted file mode 100644 index 773e29ecb..000000000 --- a/examples/official-site/sqlpage/migrations/12_blog.sql +++ /dev/null @@ -1,185 +0,0 @@ -CREATE TABLE blog_posts ( - title TEXT PRIMARY KEY, - description TEXT NOT NULL, - icon TEXT NOT NULL, - external_url TEXT, - content TEXT, - created_at TIMESTAMP NOT NULL -); - -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'SQLPage versus No-Code tools', - 'What are the advantages and disadvantages of SQLPage compared to No-Code tools?', - 'code-minus', - '2023-08-03', - ' -# Choosing Your Path: No-Code, Low-Code, or SQL-Based Development - -The platform you select shapes the entire trajectory of your application. -Each approach offers distinct advantages, yet demands different compromises - a choice that warrants careful consideration. - -## No-Code Platforms: Speed with Limitations - -No-Code platforms present a visual canvas for building applications without traditional programming. Whilst brilliant for rapid prototypes and straightforward departmental tools, they falter when confronted with complexity and scale. - -**Best suited to**: Quick internal tools and simple workflows - -### **Notable examples** - - - [NocoBase](https://www.nocobase.com/) - - [NocoDB](https://www.nocodb.com/) - - [Saltcorn](https://github.com/saltcorn/saltcorn) - - -## Low-Code Platforms: The Flexible Middle Ground - -These platforms artfully combine visual development with traditional coding. They maintain the power of custom code whilst accelerating development through carefully designed components. - -**Best suited to**: Complex applications requiring both speed and customisation - -### **Notable examples** - - - [Budibase](https://budibase.com/) - - [Directus](https://github.com/directus/directus) - - [Rowy](https://github.com/rowyio/rowy) - -## SQL-Based Development: Elegant Simplicity - -SQLPage offers a refreshingly direct approach: pure SQL-driven web applications. - -For those versed in SQL, it enables sophisticated data-driven applications without the overhead of additional frameworks. - -**Best suited to**: Data-centric applications and dashboards - -**Details**: [SQLPage on GitHub](https://github.com/sqlpage/SQLPage) - -## The AI Revolution in Development - -The emergence of Large Language Models (LLMs) has fundamentally shifted the landscape of application development. Tools that once demanded extensive coding expertise have become remarkably more accessible. AI assistants like ChatGPT excel particularly at generating SQL queries and database operations, making SQL-based platforms surprisingly approachable even for those with limited database experience. These AI companions serve as expert pair programmers, offering suggestions, debugging assistance, and ready-to-use code snippets. - -This transformation especially benefits platforms like SQLPage, where the AI''s prowess in SQL generation can bridge the traditional expertise gap. Even complex queries and database operations can be created through natural language conversations with AI assistants, democratising access to sophisticated data manipulation capabilities. - -## Making an Informed Choice - -Selecting the right development approach requires weighing multiple factors against your project''s specific needs. - -Consider these key decision points to guide your platform selection: - -### **Time Constraints** - - Immediate delivery required → No-Code - - Several days available → SQLPage or Low-Code - -### **Data Complexity** - - Structured data manipulation → SQLPage - - Complex workflows → Low-Code - -### **Team Expertise** - - SQL skills → SQLPage - - Limited technical expertise → No-Code - - Varied technical capabilities → Low-Code - -### **Control Requirements** - - Precise data layer control → SQLPage - - Visual design flexibility → Low-Code - - Speed over customisation → No-Code - -## Further Investigation - -For a thorough demonstration of SQLPage''s capabilities: [Building a Full Web Application with SQLPage](https://www.youtube.com/watch?v=mXdgmSdaXkg) -'); - -INSERT INTO blog_posts (title, description, icon, created_at, external_url) -VALUES ( - 'Repeating yourself thrice won''t make you a 3X developer', - 'A dive into the traditional 3-tier architecture and the DRY principle, and how tools like SQLPage helps you avoid repeating yourself.', - 'box-multiple-3', - '2023-08-01', - 'https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0' -); - -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES ( - '3 solutions to the 3 layer problem', - 'What is the 3 layer problem, and how SQLPage solves it?', - 'adjustments-question', - '2023-08-10', - ' -# 3 solutions to the 3 layer problem - -> Some interesting questions emerged from the article [Repeating yourself thrice doesn''t turn you into a 3X developer](https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0). -> This short follow-up article aims to answer them and clarify some points. - -Hello all, - -I am Ophir Lojkine, the main contributor of the open-source application server **SQLPage**. - -The previous article focused on the conventional model of splitting applications into three distinct tiers: - -1. a graphical interface (_front-end_), -2. an application server (_back-end_), -3. and a database. - -In many projects, this results in three distinct implementations of the application’s data model: - -1. First, in SQL, in the form of tables, views, and relationships in the database, -2. Then, in _server side_ languages such as Java, Python, or PHP, to create an API managing access to the data, and to implement the business logic of the application, -3. Finally, in JavaScript or TypeScript to implement data manipulation in the user interface. - -![Traditional tiers model](blog/three-layers.svg) - ---- - -The topic of interest here is the duplication of the data model between the different layers, -and the communication overhead between them. -We are not talking about how the code is structured within each layer. -It can follow a Model-View-Controller pattern or not, it doesn''t matter. - -This three-layer model has several advantages: -specialization of the programmers, -parallelization of work, -scalability, -separation of concerns, -and an optimal exploitation of the capacities of the infrastructure on which each layer is deployed: -web browser, server application and database. - -Nevertheless, in large-scale projects, -there is often a certain redundancy of the code between the different layers, -as well as a non-negligible share of code dedicated to communication between them. -For small teams and solo developers, this becomes a major drawback. - -## 3 solutions - -Fortunately, there are several approaches to solving this problem: - -1. For **UI-centric applications** without complicated data processing needs, -you can almost completely abandon server-side development and **directly expose the data to the frontend**. -Open-source tools available in this space include Supabase, PocketBase or Hasura. -2. For **applications with a predominant business logic**, traditional _web frameworks_ -solve this problem by centralizing frontend and database control in the backend code. -A common solution involves using an ORM and templating system instead of a dedicated javascript application. -Popular solutions include Django, Ruby on Rails, or Symphony. -3. For simpler applications, it is possible to **avoid both backend and frontend development** -by adopting a _database-first_ approach. -This alternative, although less widespread, allows taking advantage of under-exploited modern capacities of relational databases. -The purpose of the original article was to introduce this lesser known approach. - * **SQLPage** is representative of this last category, - which allows designing a complete web application _in SQL_. - This leads to a loss of control over the precise visual appearance of the application, - which will get a “standardized” look and feel. - On the other hand, this translates into significant gains in terms of development speed, - simplicity and performance. - This solution is not intended to compete with traditional _frameworks_, - but rather integrate earlier in the life cycle of a project. - It thus makes it possible to quickly develop a data structure adapted to the application, - and to iterate over it while benefiting from continuous visual feedback on the final result. - Then, when the application grows, it’s easy to add a classic frontend and backend on top of the existing database, - without having to start from scratch. - -Whichever approach is chosen in the end, -a solid understanding of the conventional three-tier architecture, -as well as a clear perspective on the challenges it creates and the possible solutions, -facilitates decision-making and the evolution of the project with the best suited technologies. - ' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/13_tab.sql b/examples/official-site/sqlpage/migrations/13_tab.sql deleted file mode 100644 index 162386f15..000000000 --- a/examples/official-site/sqlpage/migrations/13_tab.sql +++ /dev/null @@ -1,129 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'tab', - 'Build a tabbed interface, with each tab being a link to a page. Each tab can be in two states: active or inactive.', - 'row-insert-bottom', - '0.9.5' - ); -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'tab', - 'title', - 'Text to display on the tab. If link is not set, the link will be the current page with a ''$tab'' parameter set to the tab''s title. If ''id'' is set, the page will be scrolled to the tab.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'tab', - 'link', - 'Link to the page to display when the tab is clicked. By default, the link refers to the current page, with a ''tab'' parameter set to the tab''s title and hash set to the id (if passed) - this brings us back to the location of the tab after submission.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tab', - 'active', - 'Whether the tab is active or not. Defaults to false.', - 'BOOLEAN', - FALSE, - TRUE - ), - ( - 'tab', - 'icon', - 'Name of the icon to display on the tab. See tabler-icons.io for a list of available icons.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tab', - 'color', - 'Color of the tab''s text, and of its underline when it is active. See preview.tabler.io/colors.html for a list of available colors.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tab', - 'description', - 'Description of the tab. This is displayed when the user hovers over the tab.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tab', - 'center', - 'Whether the tabs should be centered or not. Defaults to false.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'tab', - 'center', - 'Whether this individual tab''s label should be centered inside the tab. Defaults to false.', - 'BOOLEAN', - FALSE, - TRUE - ) - ; - -INSERT INTO example (component, description, properties) -VALUES ( - 'tab', - 'This example shows a very basic set of three tabs. The first tab is active. You could use this at the top of a page for easy navigation. - -To implement contents that change based on the active tab, use the `tab` parameter in the page query string. -For example, if the page is `/my-page.sql`, then the first tab will have a link of `/my-page.sql?tab=My+First+tab`. - -You could then for instance display contents coming from the database based on the value of the `tab` parameter. -For instance: `SELECT ''text'' AS component, contents_md FROM my_page_contents WHERE tab = $tab`. -Or you could write different queries for different tabs and use the `$tab` parameter with a static value in a where clause to switch between tabs: - -```sql -select ''tab'' as component; -select ''Projects'' as title, $tab = ''Projects'' as active; -select ''Tasks'' as title, $tab = ''Tasks'' as active; - -select ''table'' as component; - -select * from my_projects where $tab = ''Projects''; -select * from my_tasks where $tab = ''Tasks''; -``` - -Note that the example below is completely static, and does not use the `tab` parameter to actually switch between tabs. -View the [dynamic tabs example](/examples/tabs/). -', - JSON( - '[ - { "component": "tab" }, - { "title": "This tab does not exist", "active": true, "link": "?component=tab&tab=tab_1" }, - { "title": "I am not a true tab", "link": "?component=tab&tab=tab_2" }, - { "title": "Do not click here", "link": "?component=tab&tab=tab_3" } - ]' - ) - ), - ( - 'tab', - 'This example shows a more sophisticated set of tabs. The tabs are centered, the active tab has a different color, and all the tabs have a custom link and icon.', - JSON( - '[ - { "component": "tab", "center": true }, - { "title": "Hero", "link": "?component=hero#component", "icon": "home", "description": "The hero component is a full-width banner with a title and an image." }, - { "title": "Tab", "link": "?component=tab#component", "icon": "user", "color": "purple" }, - { "title": "Card", "link": "?component=card#component", "icon": "credit-card" } - ]' - ) - ) - ; diff --git a/examples/official-site/sqlpage/migrations/16_timeline.sql b/examples/official-site/sqlpage/migrations/16_timeline.sql deleted file mode 100644 index 78f19ba5f..000000000 --- a/examples/official-site/sqlpage/migrations/16_timeline.sql +++ /dev/null @@ -1,103 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'timeline', - 'A list of events with a vertical line connecting them.', - 'git-commit', - '0.13.0' - ); -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'timeline', - 'simple', - 'If set to true, the timeline will be displayed in a condensed format without icons.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'timeline', - 'title', - 'Name of the event.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'timeline', - 'date', - 'Date of the event.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'timeline', - 'icon', - 'Name of the icon to display next to the event. See tabler-icons.io for a list of available icons.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'timeline', - 'color', - 'Color of the icon. See preview.tabler.io/colors.html for a list of available colors.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'timeline', - 'description', - 'Textual description of the event.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'timeline', - 'description_md', - 'Description of the event in Markdown.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'timeline', - 'link', - 'Link to a page with more information about the event.', - 'TEXT', - FALSE, - TRUE - ); -INSERT INTO example (component, description, properties) -VALUES ( - 'timeline', - 'A basic timeline with just names and dates.', - JSON( - '[ - { "component": "timeline", "simple": true }, - { "title": "New message from Elon Musk", "date": "13:00" }, - { "title": "Jeff Bezos assigned task \"work more\" to you.", "date": "yesterday, 16:35" } - ]' - ) - ), - ( - 'timeline', - 'A full-fledged timeline with icons, colors, and rich text descriptions.', - JSON( - '[ - { "component": "timeline" }, - { "title": "v0.13.0 was just released !", "link": "https://github.com/sqlpage/SQLPage/releases/", "date": "2023-10-16", "icon": "brand-github", "color": "green", "description_md": "This version introduces the `timeline` component." }, - { "title": "They are talking about us...", "description_md": "[This article](https://www.postgresql.org/about/news/announcing-sqlpage-build-dynamic-web-applications-in-sql-2672/) on the official PostgreSQL website mentions SQLPage.", "date": "2023-07-12", "icon": "database", "color": "blue" } - ]' - ) - ) - ; \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/18_button.sql b/examples/official-site/sqlpage/migrations/18_button.sql deleted file mode 100644 index 4cfd80e88..000000000 --- a/examples/official-site/sqlpage/migrations/18_button.sql +++ /dev/null @@ -1,122 +0,0 @@ --- Button Component Documentation - --- Component Definition -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('button', 'hand-click', 'Displays one or more buttons that follow links, download files, or submit a form.', '0.14.0'); - --- Inserting parameter information for the button component -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'button', * FROM (VALUES - -- Top-level parameters (for the whole button list) - ('justify', 'The horizontal alignment of the button list (e.g., start, end, center, between).', 'TEXT', TRUE, TRUE), - ('size', 'The size of the buttons (e.g., sm, lg).', 'TEXT', TRUE, TRUE), - ('shape', 'Shape of the buttons (e.g., pill, square)', 'TEXT', TRUE, TRUE), - -- Item-level parameters (for each button) - ('link', 'The URL to which the button should navigate when clicked. If the form attribute is specified, then this overrides the page to which the form is submitted.', 'URL', FALSE, TRUE), - ('color', 'The color of the button (e.g., red, green, blue, but also primary, warning, danger, etc.). Only base color names are supported, not variations like "blue-lt" or "gray-300". Use a custom CSS stylesheet to further customize the colors.', 'COLOR', FALSE, TRUE), - ('title', 'The text displayed on the button.', 'TEXT', FALSE, TRUE), - ('tooltip', 'Text displayed when the user hovers over the button.', 'TEXT', FALSE, TRUE), - ('disabled', 'Whether the button is disabled or not.', 'BOOLEAN', FALSE, TRUE), - ('outline', 'Outline color of the button (e.g. red, purple, ...)', 'COLOR', FALSE, TRUE), - ('space_after', 'Whether there should be extra space to the right of the button. In a line of buttons, this will put the buttons before this one on the left, and the ones after on the right.', 'BOOLEAN', FALSE, TRUE), - ('icon_after', 'Name of an icon to display after the text in the button', 'ICON', FALSE, TRUE), - ('icon', 'Name of an icon to be displayed on the left side of the button.', 'ICON', FALSE, TRUE), - ('image', 'Path to image file (relative. relative to web root or URL) to be displayed on the button.', 'TEXT', FALSE, TRUE), - ('narrow', 'Whether to trim horizontal padding.', 'BOOLEAN', FALSE, TRUE), - ('form', 'Identifier (id) of the form to which the button should submit.', 'TEXT', FALSE, TRUE), - ('rel', '"nofollow" when the contents of the target link are not endorsed, "noopener" when the target is not trusted, and "noreferrer" to hide where the user came from when they open the link.', 'TEXT', FALSE, TRUE), - ('target', '"_blank" to open the link in a new tab, "_self" to open it in the same tab, "_parent" to open it in the parent frame, or "_top" to open it in the full body of the window.', 'TEXT', FALSE, TRUE), - ('download', 'If defined, the link will download the target instead of navigating to it. Set the value to the desired name of the downloaded file.', 'TEXT', FALSE, TRUE), - ('id', 'HTML Identifier to add to the button element.', 'TEXT', FALSE, TRUE) -) x; - --- Inserting example information for the button component -INSERT INTO example(component, description, properties) VALUES - ('button', 'A basic button with a link', - json('[{"component":"button"}, {"link":"/documentation.sql", "title":"Enabled"}, {"link":"#", "title":"Disabled", "disabled":true}]')) -; - - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A button with a custom shape, size, and outline color', - json('[{"component":"button", "size":"sm", "shape":"pill" }, - {"title":"Purple", "outline":"purple" }, - {"title":"Orange", "outline":"orange" }, - {"title":"Red", "outline":"red" }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A list of buttons aligned in the center', - json('[{"component":"button", "justify":"center"}, - {"link":"#", "color":"light", "title":"Light"}, - {"link":"#", "color":"success", "title":"Success"}, - {"link":"#", "color":"info", "title":"Info"}, - {"link":"#", "color":"dark", "title":"Dark"}, - {"link":"#", "color":"warning", "title":"Warning"}, - {"link":"#", "color":"danger", "title":"Narrow"}]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'Icon buttons using the narrow property', - json('[{"component":"button"}, - {"link":"#", "narrow":true, "icon":"edit", "color":"primary", "tooltip":"Edit" }, - {"link":"#", "narrow":true, "icon":"trash", "color":"danger", "tooltip":"Delete" }, - {"link":"#", "narrow":true, "icon":"corner-down-right", "color":"info", "tooltip":"Preview" }, - {"link":"#", "narrow":true, "icon":"download", "color":"success", "tooltip":"Download" }, - {"link":"#", "narrow":true, "icon":"upload", "color":"warning", "tooltip":"Upload" }, - {"link":"#", "narrow":true, "icon":"info-circle", "color":"cyan", "tooltip":"Info" }, - {"link":"#", "narrow":true, "icon":"help-circle", "color":"purple", "tooltip":"Help" }, - {"link":"#", "narrow":true, "icon":"settings", "color":"indigo", "tooltip":"Settings" }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'Buttons with icons and different sizes', - json('[{"component":"button", "size":"lg" }, - {"link":"#", "outline":"azure", "title":"Edit", "icon":"edit"}, - {"link":"#", "outline":"danger", "title":"Delete", "icon":"trash"}]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A row of square buttons with spacing in between', - json('[{"component":"button", "shape":"square"}, - {"link":"#", "color":"green", "title":"Save", "icon": "device-floppy" }, - {"link":"#", "title":"Cancel", "space_after":true, "tooltip": "This will delete your draft"}, - {"link":"#", "outline":"indigo", "title":"Preview", "icon_after": "corner-down-right", "tooltip": "View temporary draft" }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'Multiple buttons sending the same form to different pages. - -We use `'''' AS validate` to remove the submit button from inside the form itself, -and instead use the button component to submit the form to pages with different GET variables. - -In the target page, we could then use the GET variable `$action` to determine what to do with the form data. - ', - json('[{"component":"form", "id": "poem", "validate": ""}, - {"type": "textarea", "name": "Poem", "placeholder": "Write a poem"}, - {"component":"button"}, - {"link":"?action=save", "form":"poem", "color":"primary", "title":"Save" }, - {"link":"?action=preview", "form":"poem", "outline":"yellow", "title":"Preview" }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A button that downloads a file when clicked, and prevents search engines from following the link.', - json('[{"component":"button"}, - {"link":"/sqlpage_introduction_video.mp4", - "title":"Download Video", - "icon":"download", - "download":"Introduction Video.webm", - "rel":"nofollow" - }]') - ); - -INSERT INTO example(component, description, properties) VALUES - ('button', 'A button with an image-based icon.', - json('[{"component":"button"}, - {"link":"https://en.wikipedia.org/wiki/File:Globe.svg", - "title":"Open an article", - "image":"https://upload.wikimedia.org/wikipedia/commons/f/fa/Globe.svg" - }]') - ); - -INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES - ('button', 'image_alt', 'Alternative text for an informative button image. Leave empty if decorative or repeated by the button title.', 'TEXT', FALSE, TRUE); diff --git a/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql b/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql deleted file mode 100644 index f97ce0ea0..000000000 --- a/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql +++ /dev/null @@ -1,186 +0,0 @@ --- Insert the 'variables' function into sqlpage_functions table -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" -) -VALUES ( - 'uploaded_file_path', - '0.17.0', - 'upload', - 'Returns the path to a temporary file containing the contents of an uploaded file. - -## Example: handling a picture upload - -### Making a form - -```sql -select ''form'' as component, ''handle_picture_upload.sql'' as action; -select ''myfile'' as name, ''file'' as type, ''Picture'' as label; -select ''title'' as name, ''text'' as type, ''Title'' as label; -``` - -### Handling the form response - -### Inserting an image file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database - -In `handle_picture_upload.sql`, one can process the form results like this: - -```sql -insert into pictures (title, path) values (:title, sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''myfile''))); -``` - -> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files. - -### Inserting file contents as text into the database - -When the uploaded file is a simple raw text file (e.g. a `.txt` file), -one can use the [`sqlpage.read_file_as_text`](?function=read_file_as_text#function) -function to insert the contents of the file into the database like this: - -```sql -insert into text_documents (title, path) values (:title, sqlpage.read_file_as_text(sqlpage.uploaded_file_path(''my_text_file''))); -``` - -### Saving the uploaded file to a permanent location - -When the uploaded file is larger than a few megabytes, it is not recommended to store it in the database. -Instead, one can save the file to a permanent location on the server, and store the path to the file in the database. - -You can move the file to a permanent location using the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function. -### Advanced file handling - -For more advanced file handling, such as uploading files to a cloud storage service, -you can write a small script in your favorite programming language, -and call it using the [`sqlpage.exec`](?function=exec#function) function. - -For instance, one could save the following small bash script to `/usr/local/bin/upload_to_s3`: - -```bash -#!/bin/bash -aws s3 cp "$1" s3://your-s3-bucket-name/ -echo "https://your-s3-bucket-url/$(basename "$1")" -``` - -Then, you can call it from SQL like this: - -```sql -set url = sqlpage.exec(''upload_to_s3'', sqlpage.uploaded_file_path(''myfile'')); -insert into uploaded_files (title, path) values (:title, $url); -``` -' -), -( - 'uploaded_file_mime_type', - '0.18.0', - 'file-settings', - 'Returns the MIME type of an uploaded file. - -## Example: handling a picture upload - -When letting the user upload a picture, you may want to check that the uploaded file is indeed an image. - -```sql -select ''redirect'' as component, - ''invalid_file.sql'' as link -where sqlpage.uploaded_file_mime_type(''myfile'') not like ''image/%''; -``` - -In `invalid_file.sql`, you can display an error message to the user: - -```sql -select ''alert'' as component, ''Error'' as title, - ''Invalid file type'' as description, - ''alert-circle'' as icon, ''red'' as color; -``` - -## Example: white-listing file types - -You could have a database table containing the allowed MIME types, and check that the uploaded file is of one of those types: - -```sql -select ''redirect'' as component, - ''invalid_file.sql'' as link -where sqlpage.uploaded_file_mime_type(''myfile'') not in (select mime_type from allowed_mime_types); -``` -' -), -( - 'uploaded_file_name', - '0.23.0', - 'file-description', - 'Returns the `filename` value in the `content-disposition` header. - -## Example: saving uploaded file metadata for later download - -### Making a form - -```sql -select ''form'' as component, ''handle_file_upload.sql'' as action; -select ''myfile'' as name, ''file'' as type, ''File'' as label; -``` - -### Handling the form response - -### Inserting an arbitrary file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database - -In `handle_file_upload.sql`, one can process the form results like this: - -```sql -insert into uploaded_files (fname, content, uploaded) values ( - sqlpage.uploaded_file_name(''myfile''), - sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''myfile'')), - CURRENT_TIMESTAMP -); -``` - -> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files. - -### Downloading the uploaded files - -The file can be downloaded by clicking a link like this: -```sql -select ''button'' as component; -select name as title, content as link from uploaded_files where name = $file_name limit 1; -``` - -> *Note*: because the file is ecoded as a data uri, the file is transferred to the client whether or not the link is clicked - -### Large files - -See the [`sqlpage.uploaded_file_path`](?function=uploaded_file_path#function) function. - -See the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function. -' -); - -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" -) -VALUES ( - 'uploaded_file_path', - 1, - 'name', - 'Name of the file input field in the form.', - 'TEXT' -), -( - 'uploaded_file_mime_type', - 1, - 'name', - 'Name of the file input field in the form.', - 'TEXT' -), -( - 'uploaded_file_name', - 1, - 'name', - 'Name of the file input field in the form.', - 'TEXT' -) -; diff --git a/examples/official-site/sqlpage/migrations/25_read_file_as_text.sql b/examples/official-site/sqlpage/migrations/25_read_file_as_text.sql deleted file mode 100644 index 9cdae13cf..000000000 --- a/examples/official-site/sqlpage/migrations/25_read_file_as_text.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Insert the 'variables' function into sqlpage_functions table -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" -) -VALUES ( - 'read_file_as_text', - '0.17.0', - 'file-invoice', - 'Returns a string containing the contents of the given file. - -The file must be a raw text file using UTF-8 encoding. - -The file path is relative to the `web root` directory, which is the directory from which your website is served -(not necessarily the directory SQLPage is launched from). - -If the given argument is null, the function will return null. - -As with other functions, if an error occurs during execution -(because the file does not exist, for instance), -the function will display an error message and the -database query will not be executed. - -If you are using a `sqlpage_files` table to store files directly in the database (serverless mode), -the function will attempt to read the file from the database filesystem if it is not found on the local disk, -using the same logic as for serving files in response to HTTP requests. - -## Example - -### Rendering a markdown file - -```sql -select ''text'' as component, sqlpage.read_file_as_text(''/path/to/file.md'') as contents_md; -``` -'); - --- Insert the parameters for the 'variables' function into sqlpage_function_parameters table --- Parameter 1: 'method' parameter -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" -) -VALUES ( - 'read_file_as_text', - 1, - 'name', - 'Path to the file to read.', - 'TEXT' -); diff --git a/examples/official-site/sqlpage/migrations/27_protocol.sql b/examples/official-site/sqlpage/migrations/27_protocol.sql deleted file mode 100644 index 1b0e155c1..000000000 --- a/examples/official-site/sqlpage/migrations/27_protocol.sql +++ /dev/null @@ -1,30 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'protocol', - '0.17.1', - 'network', - 'Returns the protocol that was used to access the current page. - -This can be either `http` or `https`. - -This is useful to generate links to the current page. - -### Example - -```sql -select ''text'' as component, - sqlpage.protocol() || ''://'' || sqlpage.header(''host'') || sqlpage.path() as contents; -``` - -will return `https://example.com/example.sql`. - -> Note that the path is URL-encoded. The protocol is resolved in this order: -> - `Forwarded` header -> - `X-Forwarded-Proto` header -> request target / URI -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/28_tracking_component.sql b/examples/official-site/sqlpage/migrations/28_tracking_component.sql deleted file mode 100644 index e873f5bf0..000000000 --- a/examples/official-site/sqlpage/migrations/28_tracking_component.sql +++ /dev/null @@ -1,136 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'tracking', - 'Component for visualising activity logs or other monitoring-related data.', - 'timeline-event-text', - '0.18.0' - ); - -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'tracking', - 'title', - 'Title of the tracking component.', - 'TEXT', - TRUE, - FALSE - ), - ( - 'tracking', - 'information', - 'A short text displayed below the title.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'tracking', - 'description', - 'A short paragraph.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'tracking', - 'description_md', - 'A short paragraph formatted using markdown.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'tracking', - 'width', - 'Width of the component, between 1 and 12.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'tracking', - 'placement', - 'Position of the tooltip (e.g. top, bottom, right, left)', - 'TEXT', - TRUE, - TRUE - ), - ( - 'tracking', - 'color', - 'Color of the tracked item (e.g. success, warning, danger)', - 'TEXT', - FALSE, - TRUE - ), - ( - 'tracking', - 'title', - 'Description of the state.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'tracking', - 'link', - 'A URL to open when the user clicks on the tracked item.', - 'URL', - FALSE, - TRUE - ), - ( - 'tracking', - 'center', - 'Whether to center the component.', - 'BOOLEAN', - TRUE, - TRUE - ); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES - ( - 'tracking', - 'A basic example of servers tracking component', - JSON( - '[ - {"component":"tracking","title":"Servers status"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"}, - {"title":"No data"} - ]' - ) - ), - ( - 'tracking', - 'An example of servers tracking component', - JSON( - '[ - {"component":"tracking","title":"Servers status","information":"60% are running","description_md":"Status of all **currently running servers**","placement":"top","width":4}, - {"color":"success","title":"operational"}, - {"color":"success","title":"operational"}, - {"color":"success","title":"operational"}, - {"color":"danger","title":"Downtime"}, - {"title":"No data"}, - {"color":"success","title":"operational"}, - {"color":"warning","title":"Big load"}, - {"color":"success","title":"operational"} - ]' - ) - ); - - diff --git a/examples/official-site/sqlpage/migrations/29_divider_component.sql b/examples/official-site/sqlpage/migrations/29_divider_component.sql deleted file mode 100644 index 3acaa4e4b..000000000 --- a/examples/official-site/sqlpage/migrations/29_divider_component.sql +++ /dev/null @@ -1,152 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'divider', - 'Dividers help organize content and make the interface layout clear and uncluttered.', - 'separator', - '0.18.0' - ); - -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES ( - 'divider', - 'contents', - 'A text in the divider.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'divider', - 'position', - 'Position of the text (e.g. left, right).', - 'TEXT', - TRUE, - TRUE - ), - ( - 'divider', - 'color', - 'The name of a color for this span of text.', - 'COLOR', - TRUE, - TRUE - ), - ( - 'divider', - 'size', - 'The size of the divider text, from 1 to 6.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'divider', - 'bold', - 'Whether the text is bold.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'divider', - 'italics', - 'Whether the text is italicized.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'divider', - 'underline', - 'Whether the text is underlined.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'divider', - 'link', - 'URL of the link for the divider text. Available only when contents is present.', - 'URL', - TRUE, - TRUE - ); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES - ( - 'divider', - 'An empty divider', - JSON( - '[ - { - "component":"divider" - } - ]' - ) - ), - ( - 'divider', - 'A divider with centered text', - JSON( - '[ - { - "component":"divider", - "contents":"Hello" - } - ]' - ) - ), - ( - 'divider', - 'A divider with text at left', - JSON( - '[ - { - "component":"divider", - "contents":"Hello", - "position":"left" - } - ]' - ) - ), - ( - 'divider', - 'A divider with blue text and a link', - JSON( - '[ - { - "component":"divider", - "contents":"SQLPage components", - "link":"/documentation.sql", - "color":"blue" - } - ]' - ) - ), - ( - 'divider', - 'A divider with bold, italic, and underlined text', - JSON( - '[ - { - "component":"divider", - "contents":"Important notice", - "position":"left", - "color":"red", - "size":5, - "bold":true, - "italics":true, - "underline":true - } - ]' - ) - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql b/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql deleted file mode 100644 index 6ec48379a..000000000 --- a/examples/official-site/sqlpage/migrations/30_breadcrumb_component.sql +++ /dev/null @@ -1,76 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'breadcrumb', - 'A secondary navigation aid that helps users understand their location on a website or mobile application.', - 'dots', - '0.18.0' - ); - -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) - VALUES ( - 'breadcrumb', - 'title', - 'Hyperlink text to display.', - 'TEXT', - FALSE, - FALSE - ), - ( - 'breadcrumb', - 'link', - 'Link to the page to display when the link is clicked. By default, the link refers to the current page, with a ''link'' parameter set to the link''s title.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'breadcrumb', - 'active', - 'Whether the link is active or not. Defaults to false.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'breadcrumb', - 'description', - 'Description of the link. This is displayed when the user hovers over the link.', - 'TEXT', - FALSE, - TRUE - ); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES - ( - 'breadcrumb', - 'Basic usage of the breadcrumb component', - JSON( - '[ - {"component":"breadcrumb"}, - {"title":"Home","link":"/"}, - {"title":"Components", "link":"/documentation.sql"}, - {"title":"Breadcrumb", "link":"?component=breadcrumb"} - ]' - ) - ), - ( - 'breadcrumb', - 'Description of a link and selection of the current page.', - JSON( - '[ - {"component":"breadcrumb"}, - {"title":"Home","link":"/","active": true}, - {"title":"Articles","link":"/blog.sql","description":"Stay informed with the latest news"}, - {"title":"JSON in SQL","link":"/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide", "description": "Learn advanced json functions for MySQL, SQLite, PostgreSQL, and SQL Server" } - ]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/31_card_docs_update.sql b/examples/official-site/sqlpage/migrations/31_card_docs_update.sql deleted file mode 100644 index 25e79b5f2..000000000 --- a/examples/official-site/sqlpage/migrations/31_card_docs_update.sql +++ /dev/null @@ -1,93 +0,0 @@ -DELETE FROM component WHERE name = 'card'; - -INSERT INTO component(name, icon, description) VALUES - ('card', 'credit-card', 'A grid where each element is a small card that displays a piece of data.'); -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'card', * FROM (VALUES - -- top level - ('title', 'Text header at the top of the list of cards.', 'TEXT', TRUE, TRUE), - ('description', 'A short paragraph displayed below the title.', 'TEXT', TRUE, TRUE), - ('description_md', 'A short paragraph displayed below the title - formatted using markdown.', 'TEXT', TRUE, TRUE), - ('columns', 'The number of columns in the grid of cards. This is just a hint, the grid will adjust dynamically to the user''s screen size, rendering fewer columns if needed to fit the contents. To control the size of cards individually, use the `width` row-level property instead.', 'INTEGER', TRUE, TRUE), - -- item level - ('title', 'Name of the card, displayed at the top.', 'TEXT', FALSE, FALSE), - ('description', 'The body of the card, where you put the main text contents of the card. - This does not support rich text formatting, only plain text. - If you want to use rich text formatting, use the `description_md` property instead.', 'TEXT', FALSE, TRUE), - ('description_md', ' - The body of the card, in Markdown format. - This is useful if you want to display a lot of text in the card, with many options for formatting, such as - line breaks, **bold**, *italics*, lists, #titles, [links](target.sql), ![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', 'Cards with remote content', - json('[ - {"component":"card", "title":"Card with embedded remote content", "columns": 2}, - {"title": "Embedded Chart", "embed": "/examples/chart.sql?_sqlpage_embed" }, - {"title": "Embedded Video", "embed": "https://www.youtube.com/embed/mXdgmSdaXkg", "allow": "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share", "embed_mode": "iframe", "height": "350" } - ]')); - -INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES - ('card', 'top_image_alt', 'Alternative text for an informative card image. Leave empty if decorative.', 'TEXT', FALSE, TRUE), - ('card', 'embed_title', 'Accessible name of the iframe. Defaults to the card title, or Embedded content if no title is set.', 'TEXT', FALSE, TRUE); diff --git a/examples/official-site/sqlpage/migrations/34_carousel.sql b/examples/official-site/sqlpage/migrations/34_carousel.sql deleted file mode 100644 index 70f74b53b..000000000 --- a/examples/official-site/sqlpage/migrations/34_carousel.sql +++ /dev/null @@ -1,163 +0,0 @@ -INSERT INTO component (name, description, icon, introduced_in_version) -VALUES ( - 'carousel', - 'A carousel is used to display images. When used with multiple images, it will cycle through them automatically or with controls, creating a slideshow.', - 'carousel-horizontal', - '0.18.3' - ); -INSERT INTO parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'carousel', - 'title', - 'A name to display at the top of the carousel.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'carousel', - 'indicators', - 'Style of image indicators (square or dot).', - 'TEXT', - TRUE, - TRUE - ), - ( - 'carousel', - 'vertical', - 'Whether to use the vertical image indicators.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'controls', - 'Whether to show the control links to go previous or next item.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'width', - 'Width of the component, between 1 and 12. Default is 12.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'carousel', - 'auto', - 'Whether to automatically cycle through the carousel items. Default is false.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'center', - 'Whether to center the carousel.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'fade', - 'Whether to apply the fading effect.', - 'BOOLEAN', - TRUE, - TRUE - ), - ( - 'carousel', - 'delay', - 'Specify the delay, in milliseconds, between two images.', - 'INTEGER', - TRUE, - TRUE - ), - ( - 'carousel', - 'image', - 'The URL (absolute or relative) of an image to display in the carousel.', - 'URL', - FALSE, - FALSE - ), - ( - 'carousel', - 'title', - 'Add caption to the slide.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'carousel', - 'description', - 'A short paragraph.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'carousel', - 'description_md', - 'A short paragraph formatted using markdown.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'carousel', - 'width', - 'The width of the image, in pixels.', - 'INTEGER', - FALSE, - TRUE - ), - ( - 'carousel', - 'height', - 'The height of the image, in pixels.', - 'INTEGER', - FALSE, - TRUE - ); -INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES - ('carousel', 'image_alt', 'Alternative text describing the slide image. Leave empty if the image is decorative or its caption already describes it.', 'TEXT', FALSE, TRUE); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'carousel', - 'A basic example of carousel', - JSON( - '[ - {"component":"carousel","name":"cats1","title":"Famous Database Animals"}, - {"image_alt":"African elephants at a watering hole","image":"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Elefantes_africanos_de_sabana_%28Loxodonta_africana%29%2C_Elephant_Sands%2C_Botsuana%2C_2018-07-28%2C_DD_114-117_PAN.jpg/1280px-Elefantes_africanos_de_sabana_%28Loxodonta_africana%29%2C_Elephant_Sands%2C_Botsuana%2C_2018-07-28%2C_DD_114-117_PAN.jpg"}, - {"image_alt":"A panoramic view of Penguin Island","image":"https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Penguin_Island_panorama_with_ferry_and_dolphins_in_foreground%2C_March_2023_06.jpg/1280px-Penguin_Island_panorama_with_ferry_and_dolphins_in_foreground%2C_March_2023_06.jpg"} - ]' - ) - ), - ( - 'carousel', - 'An advanced example of carousel with controls', - JSON( - '[ - {"component":"carousel","title":"SQL web apps","width":10, "center":true,"controls":true,"auto":true}, - {"image":"/sqlpage_cover_image.webp","title":"SQLPage is modern","description":"Built by engineers who have built so many web applications the old way, they decided they just wouldn''t anymore.", "height": 512}, - {"image":"/sqlpage_illustration_alien.webp","title":"SQLPage is easy", "description":"SQLPage connects to your database, then it turns your SQL queries into nice websites.", "height": 512} - ]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/35_code_title.sql b/examples/official-site/sqlpage/migrations/35_code_title.sql deleted file mode 100644 index cf2960332..000000000 --- a/examples/official-site/sqlpage/migrations/35_code_title.sql +++ /dev/null @@ -1,115 +0,0 @@ --- Documentation for the title component -INSERT INTO component (name, description, icon, introduced_in_version) VALUES ( - 'title', - 'Defines HTML headings. The level 1 is used for the maximal size and the level 6 is used for the minimal size.', - 'letter-case-upper', - '0.19.0' -); - -INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES ( - 'title', - 'center', - 'Whether to center the title.', - 'BOOLEAN', - TRUE, - TRUE -),( - 'title', - 'contents', - 'A text to display.', - 'TEXT', - TRUE, - FALSE -),( - 'title', - 'level', - 'Set the heading level (default level is 1)', - 'INTEGER', - TRUE, - TRUE -); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) VALUES ( - 'title', - 'Displays several titles with different levels.', - JSON( - '[ - {"component":"title","contents":"Level 1"}, - {"component":"title","contents":"Level 2","level": 2}, - {"component":"title","contents":"Level 3","level": 3} - ]' - ) -); - -INSERT INTO example(component, description, properties) VALUES ( - 'title', - 'Displays a centered title.', - JSON( - '[ - {"component":"title","contents":"Level 1","center": true} - ]' - ) -); - --- Documentation for the code component -INSERT INTO component (name, description, icon, introduced_in_version) VALUES ( - 'code', - 'Displays one or many blocks of code from a programming language or formated text as XML or JSON.', - 'code', - '0.19.0' -); - -INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES ( - 'code', - 'title', - 'Set the heading level (default level is 1)', - 'TEXT', - FALSE, - TRUE -),( - 'code', - 'contents', - 'A block of code.', - 'TEXT', - FALSE, - FALSE -),( - 'code', - 'description', - 'Description of the snipet of code.', - 'TEXT', - FALSE, - TRUE -),( - 'code', - 'description_md', - 'Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.', - 'TEXT', - FALSE, - TRUE -),( - 'code', - 'language', - 'Set the programming language name.', - 'TEXT', - FALSE, - TRUE -); - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) VALUES ( - 'code', - 'Displays a block of HTML code.', - JSON( - '[ - {"component":"code"}, - { - "title":"A HTML5 example", - "language":"html", - "description":"Here’s the very minimum that an HTML document should contain, assuming it has CSS and JavaScript linked to it.", - "contents":"\n\n\t\n\t\t\n\t\ttitle\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n" - } - ]' - ) -); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/37_rss.sql b/examples/official-site/sqlpage/migrations/37_rss.sql deleted file mode 100644 index 0a3e70bb8..000000000 --- a/examples/official-site/sqlpage/migrations/37_rss.sql +++ /dev/null @@ -1,287 +0,0 @@ --- Documentation for the RSS component -INSERT INTO component (name, description, icon, introduced_in_version) VALUES ( - 'rss', - 'Produces a data flow in the RSS format. -Can be used to generate a podcast feed. -To use this component, you must first return an HTTP header with the "application/rss+xml" content type (see http_header component). Next, you must use the shell-empty component to avoid that SQLPage generates HTML code.', - 'rss', - '0.20.0' -); - -INSERT INTO parameter (component,name,description,type,top_level,optional) VALUES ( - 'rss', - 'title', - 'Defines the title of the channel.', - 'TEXT', - TRUE, - FALSE -),( - 'rss', - 'link', - 'Defines the hyperlink to the channel.', - 'URL', - TRUE, - FALSE -),( - 'rss', - 'description', - 'Describes the channel.', - 'TEXT', - TRUE, - FALSE -),( - 'rss', - 'language', - 'Defines the language of the channel, specified in the ISO 639 format. For example, "en" for English, "fr" for French.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'category', - 'Defines the category of the channel. The value should be a string representing the category (e.g., "News", "Technology", etc.).', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'sub_category', - 'Defines a sub-category, nested inside the "category". Ignored unless "category" is also set.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'explicit', - 'Indicates whether the channel contains explicit content. The value can be either TRUE or FALSE.', - 'BOOLEAN', - TRUE, - TRUE -),( - 'rss', - 'image_url', - 'Provides a URL linking to the artwork for the channel.', - 'URL', - TRUE, - TRUE -),( - 'rss', - 'author', - 'Defines the group, person, or people responsible for creating the channel.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'copyright', - 'Provides the copyright details for the channel.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'self_link', - 'URL of the RSS feed.', - 'URL', - TRUE, - TRUE -),( - 'rss', - 'funding_url', - 'Specifies the donation/funding links for the channel. The content of the tag is the recommended string to be used with the link.', - 'URL', - TRUE, - TRUE -),( - 'rss', - 'funding_text', - 'The text to display with the donation/funding link. Ignored unless "funding_url" is also set.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'type', - 'Specifies the channel as either episodic or serial. The value can be either "episodic" or "serial".', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'complete', - 'Specifies that a channel is complete and will not post any more items in the future.', - 'BOOLEAN', - TRUE, - TRUE -),( - 'rss', - 'locked', - 'Tells podcast hosting platforms whether they are allowed to import this feed.', - 'BOOLEAN', - TRUE, - TRUE -),( - 'rss', - 'guid', - 'The globally unique identifier (GUID) for a channel. The value is a UUIDv5.', - 'TEXT', - TRUE, - TRUE -),( - 'rss', - 'title', - 'Defines the title of the feed item (episode name, blog post title, etc.).', - 'TEXT', - FALSE, - FALSE -),( - 'rss', - 'link', - 'Defines the hyperlink to the item (blog post URL, etc.).', - 'URL', - FALSE, - FALSE -),( - 'rss', - 'description', - 'Describes the item', - 'TEXT', - FALSE, - FALSE -),( - 'rss', - 'date', - 'Indicates when the item was published (RFC-822 date-time).', - 'TEXT', - FALSE, - TRUE -),( - 'rss', - 'enclosure_url', - 'For podcast episodes, provides a URL linking to the audio/video episode content, in mp3, m4a, m4v, or mp4 format.', - 'URL', - FALSE, - TRUE -),( - 'rss', - 'enclosure_length', - 'The length in bytes of the audio/video episode content.', - 'INTEGER', - FALSE, - TRUE -),( - 'rss', - 'enclosure_type', - 'The MIME media type of the audio/video episode content (e.g., "audio/mpeg", "audio/m4a", "video/m4v", "video/mp4").', - 'TEXT', - FALSE, - TRUE -),( - 'rss', - 'guid', - 'The globally unique identifier (GUID) for an item.', - 'TEXT', - FALSE, - TRUE -),( - 'rss', - 'episode', - 'The chronological number that is associated with an item.', - 'INTEGER', - FALSE, - TRUE -),( - 'rss', - 'season', - 'The chronological number associated with an item''s season.', - 'INTEGER', - FALSE, - TRUE -),( - 'rss', - 'episode_type', - 'Defines the type of content for a specific item. The value can be either "full", "trailer", or "bonus".', - 'TEXT', - FALSE, - TRUE -),( - 'rss', - 'block', - 'Prevents a specific item from appearing in podcast listening applications.', - 'BOOLEAN', - FALSE, - TRUE -),( - 'rss', - 'explicit', - 'Indicates whether the item contains explicit content. The value can be either TRUE or FALSE.', - 'BOOLEAN', - FALSE, - TRUE -),( - 'rss', - 'image_url', - 'Provides a URL linking to the artwork for the item.', - 'URL', - FALSE, - TRUE -),( - 'rss', - 'duration', - 'The duration of an item in seconds.', - 'INTEGER', - FALSE, - TRUE -),( - 'rss', - 'transcript_url', - 'A link to a transcript or closed captions file for the item.', - 'URL', - FALSE, - TRUE -),( - 'rss', - 'transcript_type', - 'The type of the transcript or closed captions file for the item (e.g., "text/plain", "text/html", "text/vtt", "application/json", "application/x-subrip").', - 'TEXT', - FALSE, - TRUE -); - --- Insert example(s) for the component -INSERT INTO example (component, description) -VALUES ( - 'rss', - ' -### An RSS channel about SQLPage latest news. - -```sql -select ''http_header'' as component, ''application/rss+xml'' as content_type; -select ''shell-empty'' as component; -select - ''rss'' as component, - ''SQLPage blog'' as title, - ''https://sql-page.com/blog.sql'' as link, - ''latest news about SQLpage'' as description, - ''en'' as language, - ''Technology'' as category, - FALSE as explicit, - ''https://sql-page.com/favicon.ico'' as image_url, - ''Ophir Lojkine'' as author, - ''https://github.com/sponsors/lovasoa'' as funding_url, - ''episodic'' as type; -select - ''Hello everyone !'' as title, - ''https://sql-page.com/blog.sql?post=Come%20see%20me%20build%20twitter%20live%20on%20stage%20in%20Prague'' as link, - ''If some of you european SQLPagers are around Prague this december, I will be giving a talk about SQLPage at pgconf.eu on December 14th.'' as description, - ''http://127.0.0.1:8080/sqlpage_introduction_video.mp4'' as enclosure_url, - 123456789 as enclosure_length, - ''video/mp4'' as enclosure_type, - ''2023-12-04'' as date; -``` - -Once you have your rss feed ready, you can submit it to podcast directories like -[Apple Podcasts](https://podcastsconnect.apple.com/my-podcasts), -[Spotify](https://podcasters.spotify.com/), -[Google Podcasts](https://podcastsmanager.google.com/)... -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/39_persist_uploaded_file.sql b/examples/official-site/sqlpage/migrations/39_persist_uploaded_file.sql deleted file mode 100644 index 76619a2db..000000000 --- a/examples/official-site/sqlpage/migrations/39_persist_uploaded_file.sql +++ /dev/null @@ -1,77 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'persist_uploaded_file', - '0.20.1', - 'device-floppy', - 'Persists an uploaded file to the local filesystem, and returns its path. -If the file input field is empty, the function returns NULL. - -### Example - -#### User profile picture - -##### `upload_form.sql` - -```sql -select ''form'' as component, ''persist_uploaded_file.sql'' as action; -select ''file'' as type, ''profile_picture'' as name, ''Upload your profile picture'' as label; -``` - -##### `persist_uploaded_file.sql` - -```sql -update user -set profile_picture = sqlpage.persist_uploaded_file(''profile_picture'', ''profile_pictures'', ''jpg,jpeg,png,gif,webp'') -where id = ( - select user_id from session where session_id = sqlpage.cookie(''session_id'') -); -``` - -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'persist_uploaded_file', - 1, - 'file', - 'Name of the form field containing the uploaded file. The current page must be referenced in the `action` property of a `form` component that contains a file input field.', - 'TEXT' - ), - ( - 'persist_uploaded_file', - 2, - 'destination_folder', - 'Optional. Path to the folder where the file will be saved, relative to the web root (the root folder of your website files). By default, the file will be saved in the `uploads` folder. - -**Security note**: this value must be a folder name you choose yourself in your SQL code (a trusted constant). Never build it from untrusted input such as a form field, a query parameter, a request header, or anything else the visitor controls. The folder is joined directly to the web root, so a value containing `..` or an absolute path would cause the uploaded file to be written *outside* the web root, anywhere the SQLPage process can write. Keeping `destination_folder` a fixed value chosen by the application author avoids this.', - 'TEXT' - ), - ( - 'persist_uploaded_file', - 3, - 'allowed_extensions', - 'Optional. Comma-separated list of allowed file extensions. By default: jpg,jpeg,png,gif,bmp,webp,pdf,txt,doc,docx,xls,xlsx,csv,mp3,mp4,wav,avi,mov. -Changing this may be dangerous ! If you add "sql", "svg" or "html" to the list, an attacker could execute arbitrary SQL queries on your database, or impersonate other users.', - 'TEXT' - ), - ( - 'persist_uploaded_file', - 4, - 'mode', - 'Optional. Unix permissions to set on the file, in octal notation. By default, the file will be saved with "600" (read/write for the owner only). -Octal notation works by using three digits from 0 to 7: the first for the owner, the second for the group, and the third for others. -For example, "644" means read/write for the owner, and read-only for others. -[Learn more about numeric notation for file-system permissions on Wikipedia](https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation).', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/46_html.sql b/examples/official-site/sqlpage/migrations/46_html.sql deleted file mode 100644 index 58168c0d4..000000000 --- a/examples/official-site/sqlpage/migrations/46_html.sql +++ /dev/null @@ -1,97 +0,0 @@ --- Documentation for the RSS component -INSERT INTO - component (name, description, icon, introduced_in_version) -VALUES - ( - 'html', - 'Include raw HTML in the output. For advanced users only. Use this component to create complex layouts or to include external content. - Be very careful when using this component with user-generated content, as it can lead to security vulnerabilities. - Use this component only if you are familiar with the security implications of including raw HTML, and understand the risks of cross-site scripting (XSS) attacks.', - 'html', - '0.25.0' - ); - -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'html', - 'html', - 'Raw HTML content to include in the page. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.', - 'TEXT', - TRUE, - TRUE - ), - ( - 'html', - 'html', - 'Raw HTML content to include in the page. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'html', - 'text', - 'Text content to include in the page. This will be sanitized and escaped. Use this property to include user-generated content that should not contain HTML tags.', - 'TEXT', - FALSE, - TRUE - ), - ( - 'html', - 'post_html', - 'Raw HTML content to include after the text content. This will not be sanitized or escaped. If you include content from an untrusted source, your page will be vulnerable to cross-site scripting attacks.', - 'TEXT', - FALSE, - TRUE - ); - --- Insert example(s) for the component -INSERT INTO - example (component, description, properties) -VALUES - ( - 'html', - 'Include a simple HTML snippet. In this example, the HTML code is hardcoded in the SQL query, so it is safe. You should never include data that may be manipulated by a user in the HTML content. - ', - JSON ( - '[{ - "component": "html", - "html": "

This text is safe because it is hardcoded!

" - }]' - ) - ), - ( - 'html', - 'Include multiple html snippets as row-level parameters. Again, be careful what you include in the HTML content. If the data comes from a user, it can be manipulated to include malicious code.', - JSON ( - '[{"component":"html", "html":"
"}, - {"html":"
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/47_link.sql b/examples/official-site/sqlpage/migrations/47_link.sql deleted file mode 100644 index 267a728d2..000000000 --- a/examples/official-site/sqlpage/migrations/47_link.sql +++ /dev/null @@ -1,77 +0,0 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'link', - '0.25.0', - 'link', - 'Returns the URL of a SQLPage file with the given parameters. - -### Example - -Let''s say you have a database of products, and you want the main page (`index.sql`) to link to the page of each product (`product.sql`) with the product name as a parameter. - -In `index.sql`, you can use the `link` function to generate the URL of the product page for each product. - -```sql -select ''list'' as component; -select - name as title, - sqlpage.link(''product'', json_object(''product_name'', name)) as link -from products; -``` - -In `product.sql`, you can then use `$product_name` to get the name of the product from the URL parameter: - -```sql -select ''hero'' as component, $product_name as title, product_info as description -from products -where name = $product_name; -``` - -> You could also have manually constructed the URL with `CONCAT(''product?product_name='', name)`, -> but using `sqlpage.link` is better because it ensures that the URL is properly encoded. -> `sqlpage.link` will work even if the product name contains special characters like `&`, while `CONCAT(...)` would break the URL. - -### Parameters - - `file` (TEXT): The name of the SQLPage file to link to. - - `parameters` (JSON): The parameters to pass to the linked file. - - `fragment` (TEXT): An optional fragment (hash) to append to the URL. This is useful for linking to a specific section of a page. For instance if `product.sql` contains `select ''text'' as component, ''product_description'' as id;`, you can link to the product description section with `sqlpage.link(''product.sql'', json_object(''product_name'', name), ''product_description'')`. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'link', - 1, - 'file', - 'The path of the SQLPage file to link to, relative to the current file.', - 'TEXT' - ), - ( - 'link', - 2, - 'parameters', - 'A JSON object with the parameters to pass to the linked file.', - 'JSON' - ), - ( - 'link', - 3, - 'fragment', - 'An optional fragment (hash) to append to the URL to link to a specific section of the target page.', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/48_status_code.sql b/examples/official-site/sqlpage/migrations/48_status_code.sql deleted file mode 100644 index f80d4266a..000000000 --- a/examples/official-site/sqlpage/migrations/48_status_code.sql +++ /dev/null @@ -1,65 +0,0 @@ --- Insert the status_code component into the component table -INSERT INTO - component (name, description, icon) -VALUES - ( - 'status_code', - 'Sets the HTTP response code for the current page. - -This is an advanced technical component. -You typically need it when building internet-facing APIs and websites, -but you may not need it for simple internal applications. - -- Indicating operation results when using [SQLPage as an API](?component=json) - - `200`: *OK*, for successful operations - - `201`: *Created*, for successful record insertion - - `404`: *Not Found*, for missing resources - - `500`: *Internal Server Error*, for failed operations -- Handling data validation errors - - `400`: *Bad Request*, for invalid data -- Enforcing access controls - - `403`: *Forbidden*, for unauthorized access - - `401`: *Unauthorized*, for unauthenticated access -- Tracking system health - - `500`: *Internal Server Error*, for failed operations - -For search engine optimization: -- Use `404` for deleted content to remove outdated URLs from search engines -- For redirection from one page to another, use - - `301` (moved permanently), or - - `302` (moved temporarily) -- Use `503` during maintenance', - 'error-404' - ); - --- Insert the parameters for the status_code component into the parameter table -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'status_code', - 'status', - 'HTTP status code (e.g., 200 OK, 401 Unauthorized, 409 Conflict)', - 'INTEGER', - TRUE, - FALSE - ); - -INSERT INTO example (component, description) -VALUES ( - 'status_code', - ' -Set the HTTP status code to 404, indicating that the requested resource was not found. -Useful in combination with [`404.sql` files](/your-first-sql-website/custom_urls.sql): - -```sql -SELECT ''status_code'' as component, 404 as status; -``` -'); diff --git a/examples/official-site/sqlpage/migrations/49_big_number.sql b/examples/official-site/sqlpage/migrations/49_big_number.sql deleted file mode 100644 index acdb2858d..000000000 --- a/examples/official-site/sqlpage/migrations/49_big_number.sql +++ /dev/null @@ -1,66 +0,0 @@ --- Big Number Component Documentation - --- Component Definition -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('big_number', 'chart-area', 'A component to display key metrics or statistics with optional description, change indicator, and progress bar. Useful in dashboards.', '0.28.0'); - --- Inserting parameter information for the big_number component -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'big_number', * FROM (VALUES - -- Top-level parameters (for the whole big_number list) - ('columns', 'The number of columns to display the big numbers in (default is one column per item).', 'INTEGER', TRUE, TRUE), - ('wrap', 'Wrap long titles and descriptions onto multiple lines. By default, they are truncated with an ellipsis.', 'BOOLEAN', TRUE, TRUE), - -- id and class, at both levels, come from 99_shared_id_class_attributes.sql - -- Item-level parameters (for each big number) - ('title', 'The title or label for the big number.', 'TEXT', FALSE, TRUE), - ('title_link', 'A link for the Big Number title. If set, the entire title becomes clickable.', 'TEXT', FALSE, TRUE), - ('title_link_new_tab', 'If true, the title link will open in a new tab/window.', 'BOOLEAN', FALSE, TRUE), - ('value_link', 'A link for the Big Number value. If set, the entire value becomes clickable.', 'TEXT', FALSE, TRUE), - ('value_link_new_tab', 'If true, the value link will open in a new tab/window.', 'BOOLEAN', FALSE, TRUE), - ('value', 'The main value to be displayed prominently.', 'TEXT', FALSE, FALSE), - ('unit', 'The unit of measurement for the value.', 'TEXT', FALSE, TRUE), - ('description', 'A description or additional context for the big number.', 'TEXT', FALSE, TRUE), - ('change_percent', 'The percentage change in value (e.g., 7 for 7% increase, -8 for 8% decrease).', 'INTEGER', FALSE, TRUE), - ('progress_percent', 'The value of the progress (0-100).', 'INTEGER', FALSE, TRUE), - ('progress_color', 'The color of the progress bar (e.g., "primary", "success", "danger").', 'TEXT', FALSE, TRUE), - ('dropdown_item', 'A list of JSON objects containing links. e.g. {"label":"This week", "link":"?days=7"}', 'JSON', FALSE, TRUE), - ('color', 'The color of the card background and its main value.', 'COLOR', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('big_number', 'Big numbers with change indicators and progress bars', - json('[ - {"component":"big_number"}, - { - "title":"Sales", - "value":75, - "unit":"%", - "title_link": "#sales_dashboard", - "title_link_new_tab": true, - "value_link": "#sales_details", - "value_link_new_tab": false, - "description":"Conversion rate", - "change_percent": 9, - "progress_percent": 75, - "progress_color": "blue" - }, - { - "title":"Revenue", - "value":"4,300", - "unit":"$", - "description":"Year on year", - "change_percent": -8 - } - ]')); - -INSERT INTO example(component, description, properties) VALUES - ('big_number', 'Big numbers with dropdowns and customized layout', - json('[ - {"component":"big_number", "columns":3, "id":"colorfull_dashboard"}, - {"title":"Users", "value":"1,234", "color": "red", "title_link": "#users", "title_link_new_tab": false, "value_link": "#users_details", "value_link_new_tab": true }, - {"title":"Orders", "value":56, "color": "green", "title_link": "#orders", "title_link_new_tab": true }, - {"title":"Revenue", "value":"9,876", "unit": "€", "color": "blue", "change_percent": -7, "dropdown_item": [ - {"label":"This week", "link":"?days=7&component=big_number#colorfull_dashboard"}, - {"label":"This month", "link":"?days=30&component=big_number#colorfull_dashboard"}, - {"label":"This quarter", "link":"?days=90&component=big_number#colorfull_dashboard"} - ]} - ]')); diff --git a/examples/official-site/sqlpage/migrations/51_column.sql b/examples/official-site/sqlpage/migrations/51_column.sql deleted file mode 100644 index 06674e936..000000000 --- a/examples/official-site/sqlpage/migrations/51_column.sql +++ /dev/null @@ -1,118 +0,0 @@ --- Column Component Documentation - --- Component Definition -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('columns', 'columns', 'A component to display various items in a card layout, allowing users to choose options. Useful for showcasing different features or services, or KPIs. See also the big_number component.', '0.29.0'); - --- Inserting parameter information for the column component -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'columns', * FROM (VALUES - ('title', 'The title or label for the item.', 'TEXT', FALSE, TRUE), - ('value', 'The value associated with the item.', 'TEXT', FALSE, TRUE), - ('description', 'A brief description of the item.', 'TEXT', FALSE, TRUE), - ('description_md', 'A brief description of the item, formatted using markdown.', 'TEXT', FALSE, TRUE), - ('item', 'A list of bullet points associated with the columns, represented either as text, or as a json object with "icon", "color", and "description" or "description_md" fields.', 'JSON', FALSE, TRUE), - ('link', 'A link associated with the item.', 'TEXT', FALSE, TRUE), - ('button_text', 'Text for the button.', 'TEXT', FALSE, TRUE), - ('button_color', 'Optional color for the button.', 'TEXT', FALSE, TRUE), - ('target', 'Optional target for the button. Set to "_blank" to open links in a new tab.', 'TEXT', FALSE, TRUE), - ('value_color', 'Color for the value text.', 'TEXT', FALSE, TRUE), - ('small_text', 'Optional small text to display after the value.', 'TEXT', FALSE, TRUE), - ('icon', 'Optional icon to display in a ribbon.', 'ICON', FALSE, TRUE), - ('icon_color', 'Color for the icon in the ribbon.', 'TEXT', FALSE, TRUE), - ('size', 'Size of the column, affecting layout.', 'INTEGER', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('columns', 'Pricing Plans Display', - json('[ - {"component":"columns"}, - { - "title":"Start Plan", - "value":"€18", - "description":"Perfect for testing and small-scale projects", - "item": [ - "128MB Database", - "SQLPage hosting", - "Community support" - ], - "link":"https://datapage.app", - "button_text":"Start Free Trial", - "small_text":"/month" - }, - { - "title":"Pro Plan", - "value":"€40", - "icon":"rocket", - "description":"For growing projects needing enhanced features", - "item": [ - {"icon":"database", "color": "blue", "description":"1GB Database"}, - {"icon":"headset", "color": "green", "description":"Priority Support"}, - {"icon":"world", "color": "purple", "description":"Custom Domain"} - ], - "link":"https://datapage.app", - "button_text":"Start Free Trial", - "button_color":"indigo", - "value_color":"indigo", - "small_text":"/month" - }, - { - "title":"Enterprise Plan", - "value":"€600", - "icon":"building-skyscraper", - "description":"For large-scale operations with custom needs", - "item": [ - {"icon":"database-plus", "description_md":"**Custom Database Scaling**"}, - {"icon":"shield-lock", "description_md":"**Enterprise Auth** with Single Sign-On"}, - {"icon":"headset", "description_md":"**Monthly** Expert Support time"}, - {"icon":"file-certificate", "description_md":"**SLA** with guaranteed uptime"} - ], - "link":"mailto:contact@datapage.app", - "button_text":"Contact Us", - "small_text":"/month", - "target":"_blank" - } - ]')), - - ('columns', 'Tech Company KPIs Display', - json('[ - {"component":"columns"}, - { - "title":"Monthly Active Users", - "value":"10k", - "value_color":"blue", - "size": 4, - "description":"Total active users this month, showcasing user engagement.", - "item": [ - {"icon": "target", "description":"Target: 12,000"} - ], - "link":"#", - "button_text":"User Activity Overview", - "button_color":"info" - }, - { - "title":"Revenue", - "value":"$49k", - "value_color":"blue", - "size": 4, - "description":"Total revenue generated this month, indicating financial performance.", - "item": [ - {"icon":"trending-down", "color": "red", "description":"down from $51k last month" } - ], - "link":"#", - "button_text":"Financial Dashboard", - "button_color":"info" - }, - { - "title":"Customer Satisfaction", - "value":"94%", - "value_color":"blue", - "size": 4, - "description":"Percentage of satisfied customers, reflecting service quality.", - "item": [ - {"icon":"trending-up", "color": "green", "description":"+ 2% this month" } - ], - "link":"#", - "button_text": "Open Google Ratings", - "button_color":"info" - } - ]')); diff --git a/examples/official-site/sqlpage/migrations/52_foldable.sql b/examples/official-site/sqlpage/migrations/52_foldable.sql deleted file mode 100644 index d70201dfe..000000000 --- a/examples/official-site/sqlpage/migrations/52_foldable.sql +++ /dev/null @@ -1,27 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('foldable', 'chevrons-down', 'A foldable list of elements which can be expanded individually.', '0.29.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'foldable', * FROM (VALUES - ('id', 'ID attribute added to the container in HTML. Used for targeting through CSS or for scrolling via links. When set at the top level, applies to the entire foldable component.', 'TEXT', TRUE, TRUE), - ('class', 'CSS class(es) to add to the foldable container. When set at the top level, applies to the entire foldable component.', 'TEXT', TRUE, TRUE), - ('id', 'ID attribute added to individual foldable items. Used for targeting through CSS or for scrolling via links.', 'TEXT', FALSE, TRUE), - ('class', 'CSS class(es) to add to individual foldable items.', 'TEXT', FALSE, TRUE), - ('title', 'Title of the foldable item, displayed on the button.', 'TEXT', FALSE, TRUE), - ('description', 'Plain text description of the item, displayed when expanded.', 'TEXT', FALSE, TRUE), - ('description_md', 'Markdown description of the item, displayed when expanded.', 'TEXT', FALSE, TRUE), - ('expanded', 'If set to TRUE, the foldable item starts in an expanded state. Defaults FALSE', 'BOOLEAN', FALSE, TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('foldable', 'A single foldable paragraph of text', json('[ - {"component":"foldable"}, - {"title":"The foldable component", "description": "This is a simple foldable component. It can be used to show and hide content. It is a list of items, each with a title and a description. The description is displayed when the item is expanded."}, - ]')); - -INSERT INTO example(component, description, properties) VALUES - ('foldable', 'A SQLPage-themed foldable list with Markdown', json('[ - {"component":"foldable"}, - {"title":"Quick Prototyping", "description_md": "Build a functional web app prototype in minutes using just SQL queries:\n\n- Rapid development\n- Ideal for MVPs\n- Great for internal tools\n\nLearn more about [quick prototyping](/your-first-sql-website/).", "expanded": true}, - {"title":"Data Visualization", "description_md": "Quickly transform your database into useful insights:\n\n1. **Charts**: Line, bar, pie\n2. **KPIs**: Appealing visualizations of key metrics\n3. **Maps**: Geospatial data\n\nAs simple as:\n\n```sql\nSELECT ''chart'' as component;\nSELECT date as x, revenue as y FROM sales;\n```"}, - {"title":"Don''t stare, interact!", "description_md": "SQLPage is not just a passive *Business Intelligence* tool. With SQLPage, you can act upon user input:\n\n- *User input collection*: Building a form is just as easy as building a chart.\n- *Data validation*: Write your own validation rules in SQL.\n- *Database updates*: `INSERT` and `UPDATE` are first-class citizens.\n- *File uploads*: Upload `CSV` and other files, store and display them the way you want.\n\n> Let users interact with your data, not just look at it!"} - ]')); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/55_request_body.sql b/examples/official-site/sqlpage/migrations/55_request_body.sql deleted file mode 100644 index 423ef6a27..000000000 --- a/examples/official-site/sqlpage/migrations/55_request_body.sql +++ /dev/null @@ -1,135 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'request_body', - '0.33.0', - 'http-post', - 'Returns the raw request body as a string. - -A client (like a web browser, mobile app, or another server) can send information to your server in the request body. -This function allows you to read that information in your SQL code, -in order to create or update a resource in your database for instance. - -The request body is commonly used when building **REST APIs** (machines-to-machines interfaces) -that receive data from the client. - -This is especially useful in: -- `POST` and `PUT` requests for creating or updating resources in your database -- Any API endpoint that needs to receive complex data - -### Example: Building a REST API - -Here''s an example of building an API endpoint that receives a json object, -and inserts it into a database. - -#### `api/create_user.sql` -```sql --- Get the raw JSON body -set user_data = sqlpage.request_body(); - --- Insert the user into database -with parsed_data as ( - select - json_extract($user_data, ''$.name'') as name, - json_extract($user_data, ''$.email'') as email -) -insert into users (name, email) -select name, email from parsed_data; - --- Return success response -select ''json'' as component, - json_object( - ''status'', ''success'', - ''message'', ''User created successfully'' - ) as contents; -``` - -### Testing the API - -You can test this API using curl: -```bash -curl -X POST http://localhost:8080/api/create_user \ - -H "Content-Type: application/json" \ - -d ''{"name": "John", "email": "john@example.com"}'' -``` - -## Special cases - -### NULL - -This function returns NULL if: - - There is no request body - - The request content type is `application/x-www-form-urlencoded` or `multipart/form-data` - (in these cases, use [`sqlpage.variables(''post'')`](?function=variables) instead) - -### Binary data - -If the request body is not valid text encoded in UTF-8, -invalid characters are replaced with the Unicode replacement character `�` (U+FFFD). - -If you need to handle binary data, -use [`sqlpage.request_body_base64()`](?function=request_body_base64) instead. -' - ); - -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'request_body_base64', - '0.33.0', - 'photo-up', - 'Returns the raw request body encoded in base64. This is useful when receiving binary data or when you need to handle non-text content in your API endpoints. - -## Base64 encoding - -Base64 is a way to encode binary data (like images or files) into text that can be safely stored and transmitted. This function automatically converts the incoming request body into this format. - -## Receiving binary data in an API - -This example shows how to receive and process an image uploaded directly in the request body: - -```sql --- Assuming this is api/upload_image.sql --- Client would send a POST request with the raw image data - --- Get the base64-encoded image data -set image_data = sqlpage.request_body_base64(); - --- Store the image data in the database -insert into images (data, uploaded_at) -values ($image_data, current_timestamp); - --- Return success response -select ''json'' as component, - json_object( - ''status'', ''success'', - ''message'', ''Image uploaded successfully'' - ) as contents; -``` - -You can test this API using curl: -```bash -curl -X POST http://localhost:8080/api/upload_image.sql \ - -H "Content-Type: application/octet-stream" \ - --data-binary "@/path/to/image.jpg" -``` - -This is particularly useful when: -- Working with binary data (images, files, etc.) -- The request body contains non-UTF8 characters -- You need to pass the raw body to another system that expects base64 - -> Note: Like [`sqlpage.request_body()`](?function=request_body), this function returns NULL if: -> - There is no request body -> - The request content type is `application/x-www-form-urlencoded` or `multipart/form-data` -> (in these cases, use [`sqlpage.variables(''post'')`](?function=variables) instead) -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/58_fetch_with_meta.sql b/examples/official-site/sqlpage/migrations/58_fetch_with_meta.sql deleted file mode 100644 index c406c3f7a..000000000 --- a/examples/official-site/sqlpage/migrations/58_fetch_with_meta.sql +++ /dev/null @@ -1,97 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'fetch_with_meta', - '0.34.0', - 'transfer-vertical', - 'Sends an HTTP request and returns detailed metadata about the response, including status code, headers, and body. - -This function is similar to [`fetch`](?function=fetch), but returns a JSON object containing detailed information about the response. -When the response declares a `content-type` of `application/json`, the parsed body is returned under `json_body`: -```json -{ - "status": 200, - "headers": { - "content-type": "application/json", - "content-length": "1234" - }, - "json_body": { "name": "ditto" } -} -``` - -For every other content type, the body is returned as a string under `body`: -```json -{ - "status": 200, - "headers": { - "content-type": "text/html", - "content-length": "1234" - }, - "body": "..." -} -``` - -If the request fails or encounters an error (e.g., network issues, invalid UTF-8 response), instead of throwing an error, -the function returns a JSON object with an "error" field containing the error message. - -### Example: Basic Usage - -```sql --- Make a request and get detailed response information -set response = sqlpage.fetch_with_meta(''https://pokeapi.co/api/v2/pokemon/ditto''); - --- redirect the user to an error page if the request failed -select ''redirect'' as component, ''error.sql'' as url -where - json_extract($response, ''$.error'') is not null - or json_extract($response, ''$.status'') != 200; - --- Extract data from the response json body -select ''card'' as component; -select - json_extract($response, ''$.json_body.name'') as title, - json_extract($response, ''$.json_body.abilities[0].ability.name'') as description -from $response; -``` - -### Example: Advanced Request with Authentication - -```sql -set request = json_object( - ''method'', ''POST'', - ''url'', ''https://sqlpage.free.beeceptor.com'', - ''headers'', json_object( - ''Content-Type'', ''application/json'', - ''Authorization'', ''Bearer '' || sqlpage.environment_variable(''API_TOKEN'') - ), - ''body'', json_object( - ''key'', ''value'' - ) -); -set response = sqlpage.fetch_with_meta($request); - --- Check response content type -select ''debug'' as component, $response as response; -``` - -The function accepts the same parameters as the [`fetch` function](?function=fetch).' - ); - -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'fetch_with_meta', - 1, - 'url', - 'Either a string containing an URL to request, or a json object in the standard format of the request interface of the web fetch API.', - 'TEXT' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/59_unsafe_contents_md.sql b/examples/official-site/sqlpage/migrations/59_unsafe_contents_md.sql deleted file mode 100644 index 5f8f2c97a..000000000 --- a/examples/official-site/sqlpage/migrations/59_unsafe_contents_md.sql +++ /dev/null @@ -1,4 +0,0 @@ -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'text', * FROM (VALUES -('unsafe_contents_md','Markdown format with html blocks. Use this only with trusted content. See the html-blocks section of the Commonmark spec for additional info.', 'TEXT', TRUE, TRUE), -('unsafe_contents_md','Markdown format with html blocks. Use this only with trusted content. See the html-blocks section of the Commonmark spec for additional info.', 'TEXT', FALSE, TRUE) -); diff --git a/examples/official-site/sqlpage/migrations/60_empty_state.sql b/examples/official-site/sqlpage/migrations/60_empty_state.sql deleted file mode 100644 index 1f0b65518..000000000 --- a/examples/official-site/sqlpage/migrations/60_empty_state.sql +++ /dev/null @@ -1,52 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('empty_state', 'info-circle', 'Displays a large placeholder message to communicate a single information to the user and invite them to take action. - -Typically includes a title, an optional icon/image, descriptive text (rich text formatting and images supported via Markdown), and a call-to-action button. - -Ideal for first-use screens, empty data sets, "no results" pages, or error messages.', '0.35.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'empty_state', * FROM (VALUES - ('title','Description of the empty state.','TEXT',TRUE,FALSE), - ('header','Text displayed on the top of the empty state.','TEXT',TRUE,TRUE), - ('icon','Name of an icon to be displayed on the top of the empty state.','ICON',TRUE,TRUE), - ('image','The URL (absolute or relative) of an image to display at the top of the empty state.','URL',TRUE,TRUE), - ('description','A short text displayed below the title.','TEXT',TRUE,TRUE), - ('description_md','A short text displayed below the title, formatted using markdown.','TEXT',TRUE,TRUE), - ('link_text','The text displayed on the button.','TEXT',TRUE,FALSE), - ('link_icon','Name of an icon to be displayed on the left side of the button.','ICON',TRUE,FALSE), - ('link','The URL to which the button should navigate when clicked.','URL',TRUE,FALSE) - -- id and class come from 99_shared_id_class_attributes.sql -) x; - -INSERT INTO example(component, description, properties) VALUES - ('empty_state', ' -This example shows how to create a 404-style "Not Found" empty state with - - a prominent header displaying "404", - - a helpful description suggesting to adjust search parameters, and - - a "Search again" button with a search icon that links back to the search page. -', - json('[{ - "component": "empty_state", - "title": "No results found", - "header": "404", - "description": "Try adjusting your search or filter to find what you''re looking for.", - "link_text": "Search again", - "link_icon": "search", - "link": "#not-found", - "id": "not-found" - }]')), - ('empty_state', ' -It''s possible to use an icon or an image to illustrate the problem. -', - json('[{ - "component": "empty_state", - "title": "A critical problem has occurred", - "icon": "mood-wrrr", - "description_md": "SQLPage can do a lot of things, but this is not one of them. - -Please restart your browser and **cross your fingers**.", - "link_text": "Close and restart", - "link_icon": "rotate-clockwise", - "link": "#" - }]')); - diff --git a/examples/official-site/sqlpage/migrations/61_oidc_functions.sql b/examples/official-site/sqlpage/migrations/61_oidc_functions.sql deleted file mode 100644 index 197e68a9c..000000000 --- a/examples/official-site/sqlpage/migrations/61_oidc_functions.sql +++ /dev/null @@ -1,288 +0,0 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'user_info_token', - '0.35.0', - 'key', - 'This function can be used only when you have [configured Single Sign-On with an OIDC provider](/sso). - -## The ID Token - -When a user logs in through OIDC, your application receives an [identity token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) from the identity provider. -This token contains information about the user, such as their name and email address. -The `sqlpage.user_info_token()` function lets you access the entire contents of the ID token, as a JSON object. -You can then use [your database''s JSON functions](/blog.sql?post=JSON+in+SQL%3A+A+Comprehensive+Guide) to process that JSON. - -If you need to access a specific claim, it is easier and more performant to use the -[`sqlpage.user_info()`](?function=user_info) function instead. - -## Displaying user claims - -```sql -select ''list'' as component; -select key as title, value as description -from json_each(sqlpage.user_info_token()); -``` - -This sqlite-specific example will show all the information available about the current user, such as: -- `sub`: A unique identifier for the user -- `name`: The user''s full name -- `email`: The user''s email address -- `picture`: A URL to the user''s profile picture - -## Security notes - -- The ID token is automatically verified by SQLPage to ensure it hasn''t been tampered with. -- The token is only available to authenticated users: if no user is logged in or sso is not configured, this function returns NULL -- If some information is not available in the token, you have to configure it on your OIDC provider, SQLPage can''t do anything about it. -- The token is stored in a signed http-only cookie named `sqlpage_auth`. You can use [the cookie component](/component.sql?component=cookie) to delete it, and the user will be redirected to the login page on the next page load. -' - ); - -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'user_info', - '0.34.0', - 'user', - 'The `sqlpage.user_info` function is a convenient way to access specific pieces of information about the currently logged-in user. -When you [configure Single Sign-On](/sso), your OIDC provider will issue an [ID token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) for the user, -which contains *claims*, with information about the user. - -Calling `sqlpage.user_info(claim_name)` lets you access these claims directly from SQL. - -## Read a claim - -The function takes one parameter: the name of the *claim* (the piece of information you want to retrieve). - -For example, to display a personalized welcome message, with the user''s name, you can use: - -```sql -select ''text'' as component; -select ''Welcome, '' || sqlpage.user_info(''name'') || ''!'' as title; -``` - -## Available Information - -The exact information available depends on your identity provider (the service you chose to authenticate with), -its configuration, and the scopes you requested. -Use [`sqlpage.user_info_token()`](?function=user_info_token) to see all the information available in the ID token of the current user. - -Here are some commonly available fields: - -### Basic Information -- `name`: The user''s full name (usually first and last name separated by a space) -- `email`: The user''s email address (*warning*: there is no guarantee that the user currently controls this email address. Use the `sub` claim for database references instead.) -- `picture`: URL to the user''s profile picture - -### User Identifiers -- `sub`: A unique identifier for the user (use this to uniquely identify the user in your database) -- `preferred_username`: The username the user prefers to use - -### Name Components -- `given_name`: The user''s first name -- `family_name`: The user''s last name - -## Examples - -### Personalized Welcome Message -```sql -select ''text'' as component, - ''Welcome back, **'' || sqlpage.user_info(''given_name'') || ''**!'' as contents_md; -``` - -### User Profile Card -```sql -select ''card'' as component; -select - sqlpage.user_info(''name'') as title, - sqlpage.user_info(''email'') as description, - sqlpage.user_info(''picture'') as image; -``` - -### Conditional Content Based on custom claims - -Some identity providers let you add custom claims to the ID token. -This lets you customize the behavior of your application based on arbitrary user attributes, -such as the user''s role. - -```sql --- show everything to admins, only public items to others -select ''list'' as component; -select title from my_items - where is_public or sqlpage.user_info(''role'') = ''admin'' -``` - -## Security Best Practices - -> ⚠️ **Important**: Always use the `sub` claim to identify users in your database, not their email address. -> The `sub` claim is guaranteed to be unique and stable for each user, while email addresses can change. -> In most providers, receiving an id token with a given email does not guarantee that the user currently controls that email. - -```sql --- Store the user''s ID in your database -insert into user_preferences (user_id, theme) -values (sqlpage.user_info(''sub''), ''dark''); -``` - -## Troubleshooting - -If you''re not getting the information you expect: - -1. Check that OIDC is properly configured in your `sqlpage.json` -2. Verify that you requested the right scopes in your OIDC configuration -3. Try using `sqlpage.user_info_token()` to see all available information -4. Check your OIDC provider''s documentation for the exact claim names they use - -Remember: If the user is not logged in or the requested information is not available, this function returns NULL. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'user_info', - 1, - 'claim', - 'The name of the user information to retrieve. Common values include ''name'', ''email'', ''picture'', ''sub'', ''preferred_username'', ''given_name'', and ''family_name''. The exact values available depend on your OIDC provider and configuration.', - 'TEXT' - ); - -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'oidc_logout_url', - '0.41.0', - 'logout', - 'The `sqlpage.oidc_logout_url` function generates a secure logout URL for users authenticated via [OIDC Single Sign-On](/sso). - -When a user visits this URL, SQLPage will: -1. Remove the authentication cookie -2. Redirect the user to the OIDC provider''s logout endpoint (if available) -3. Finally redirect back to the specified `redirect_uri` - -## Security Features - -This function provides protection against **Cross-Site Request Forgery (CSRF)** attacks: -- The generated URL contains a cryptographically signed token -- The token includes a timestamp and expires after 10 minutes -- The token is signed using your OIDC client secret -- Only relative URLs (starting with `/`) are allowed as redirect targets - -This means that malicious websites cannot trick your users into logging out by simply including an image or link to your logout URL. - -## Add a logout button - -```sql -select ''button'' as component; -select - ''Logout'' as title, - sqlpage.oidc_logout_url(''/'') as link, - ''logout'' as icon, - ''red'' as outline; -``` - -This creates a logout button that, when clicked: -1. Logs the user out of your SQLPage application -2. Logs the user out of the OIDC provider (if the provider supports [RP-Initiated Logout](https://openid.net/specs/openid-connect-rpinitiated-1_0.html)) -3. Redirects the user back to your homepage (`/`) - -## Examples - -### Logout Button in Navigation - -```sql -select ''shell'' as component, - ''My App'' as title, - json_array( - json_object( - ''title'', ''Logout'', - ''link'', sqlpage.oidc_logout_url(''/''), - ''icon'', ''logout'' - ) - ) as menu_item; -``` - -### Logout with Return to Current Page - -```sql -select ''button'' as component; -select - ''Sign Out'' as title, - sqlpage.oidc_logout_url(sqlpage.path()) as link; -``` - -### Conditional Logout Link - -```sql -select ''button'' as component -where sqlpage.user_info(''sub'') is not null; -select - ''Logout '' || sqlpage.user_info(''name'') as title, - sqlpage.oidc_logout_url(''/'') as link -where sqlpage.user_info(''sub'') is not null; -``` - -## Requirements - -- OIDC must be [configured](/sso) in your `sqlpage.json` -- If OIDC is not configured, this function returns NULL -- The `redirect_uri` must be a relative path starting with `/` - -## Provider Support - -The logout behavior depends on your OIDC provider: - -| Provider | Full Logout Support | -|----------|-------------------| -| Keycloak | ✅ Yes | -| Auth0 | ✅ Yes | -| Google | ❌ No (local logout only) | -| Azure AD | ✅ Yes | -| Okta | ✅ Yes | - -When the provider doesn''t support RP-Initiated Logout, SQLPage will still remove the local authentication cookie and redirect to your specified URI. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'oidc_logout_url', - 1, - 'redirect_uri', - 'The relative URL path where the user should be redirected after logout. Must start with `/`. Defaults to `/` if not provided.', - 'TEXT' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/62_example_cards.sql b/examples/official-site/sqlpage/migrations/62_example_cards.sql deleted file mode 100644 index 04a7c90d9..000000000 --- a/examples/official-site/sqlpage/migrations/62_example_cards.sql +++ /dev/null @@ -1,104 +0,0 @@ -create table - example_cards as -select - 'Advanced Authentication' as title, - 'user-authentication' as folder, -- Has to exactly match the folder name in the /examples/ directory - 'postgres' as db_engine, - 'Build a secure user authentication system with login, signup, and in-database session management.' as description -union all -select - 'Authenticated CRUD', - 'CRUD - Authentication', - 'sqlite', - 'Complete Create-Read-Update-Delete operations with user authentication.' -union all -select - 'Image Gallery', - 'image gallery with user uploads', - 'sqlite', - 'Create an image gallery with user uploads and session management.' -union all -select - 'Developer UI', - 'SQLPage developer user interface', - 'postgres', - 'A web-based interface for managing SQLPage files and database tables.' -union all -select - 'Corporate Game', - 'corporate-conundrum', - 'sqlite', - 'An interactive multiplayer board game with real-time updates.' -union all -select - 'Roundest Pokemon', - 'roundest_pokemon_rating', - 'sqlite', - 'Demo app with a distinct non-default design, using custom HTML templates for everything.' -union all -select - 'Todo Application', - 'todo application (PostgreSQL)', - 'postgres', - 'A full-featured todo list application with PostgreSQL backend.' -union all -select - 'MySQL & JSON', - 'mysql json handling', - 'mysql', - 'Learn advanced JSON manipulation in MySQL to build advanced SQLPage applications.' -union all -select - 'Apache Web Server', - 'web servers - apache', - 'mysql', - 'Use an existing Apache httpd Web Server to expose your SQLPage application.' -union all -select - 'Sending Emails', - 'sending emails', - 'sqlite', - 'Use the fetch function to send emails (or interact with any other HTTP API).' -union all -select - 'Simple Website', - 'simple-website-example', - 'sqlite', - 'Basic website example with navigation and data management.' -union all -select - 'Geographic App', - 'PostGIS - using sqlpage with geographic data', - 'postgres', - 'Use SQLPage to create and manage geodata.' -union all -select - 'Multi-step form', - 'forms-with-multiple-steps', - 'sqlite', - 'Guide to the implementation of forms that spread over multiple pages.' -union all -select - 'Custom HTML & JS', - 'custom form component', - 'mysql', - 'Building a custom form component with a dynamic widget using HTML and javascript.' -union all -select - 'Splitwise Clone', - 'splitwise', - 'sqlite', - 'An expense tracker app to split expenses with your friends, with nice debt charts.' -union all -select - 'Advanced Forms with MS SQL Server', - 'microsoft sql server advanced forms', - 'sql server', - 'Forms with multi-value dropdowns, using SQL Server and its JSON functions.' -union all -select - 'Rich Text Editor', - 'rich-text-editor', - 'sqlite', - 'A rich text editor with bold, italic, lists, images, and more. It posts its contents as Markdown.' -; diff --git a/examples/official-site/sqlpage/migrations/63_modal.sql b/examples/official-site/sqlpage/migrations/63_modal.sql deleted file mode 100644 index 308e40e61..000000000 --- a/examples/official-site/sqlpage/migrations/63_modal.sql +++ /dev/null @@ -1,85 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('modal', 'app-window', ' -Defines the a temporary popup box displayed on top of a webpage’s content. -Useful for displaying additional information, help, or collect data from users. - -Modals are closed by default, and can be opened by clicking on a button or link targeting their ID.', '0.36.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'modal', * FROM (VALUES - ('title','Description of the modal box.','TEXT',TRUE,FALSE), - ('close','The text to display in the Close button.','TEXT',TRUE,TRUE), - ('close_label','The same as `close`. Use it on databases where `close` is a reserved word, such as SQL Server.','TEXT',TRUE,TRUE), - ('contents','A paragraph of text to display, without any formatting, without having to make additional queries.','TEXT',FALSE,TRUE), - ('contents_md','Rich text in the markdown format. Among others, this allows you to write bold text using `**bold**`, italics using `*italics*`, and links using `[text](https://example.com)`.','TEXT',FALSE,TRUE), - ('scrollable','Create a scrollable modal that allows scroll the modal body.','BOOLEAN',TRUE,TRUE), - ('class','Class attribute added to the container in HTML. It can be used to apply custom styling to this item through css.','TEXT',TRUE,TRUE), - ('id','ID attribute added to the container in HTML. It can be used to target this item through css or for displaying this item.','TEXT',TRUE,FALSE), - ('large','Indicates that the modal box has an increased width.','BOOLEAN',TRUE,TRUE), - ('small','Indicates that the modal box has a reduced width.','BOOLEAN',TRUE,TRUE), - ('embed','Embed remote content in an iframe.','TEXT',TRUE,TRUE), - ('embed_mode','Use "iframe" to display embedded content within an iframe.','TEXT',TRUE,TRUE), - ('height','Height of the modal content, in pixels. Overflow content scrolls.','INTEGER',TRUE,TRUE), - ('allow','For embedded content, this attribute specifies the features or permissions that can be used.','TEXT',TRUE,TRUE), - ('sandbox','For embedded content, this attribute specifies the security restrictions on the loaded content.','TEXT',TRUE,TRUE), - ('style','Applies CSS styles to the embedded content.','TEXT',TRUE,TRUE) -) x; - -INSERT INTO example(component, description, properties) VALUES - ('modal', - 'This example shows how to create a modal box that displays a paragraph of text. The modal window is opened with the help of a button.', - json('[ - {"component": "modal","id": "my_modal","title": "A modal box","close": "Close"}, - {"contents":"I''m a modal window, and I allow you to display additional information or help for the user."}, - {"component": "button"}, - {"title":"Open a simple modal","link":"#my_modal"} - ]') - ), - ('modal', - 'Example of modal form content', - json('[ - { - "component":"modal", - "id":"my_embed_form_modal", - "title":"Embeded form content", - "large":true, - "embed":"/examples/form.sql?_sqlpage_embed" - }, - {"component": "button"}, - {"title":"Open a modal with a form","link":"#my_embed_form_modal"} - ]') - ), - ('modal', - 'A popup modal that contains a chart generated by a separate SQL file. The modal is triggered by links inside a datagrid.', - json('[ - { - "component":"modal", - "id":"my_embed_chart_modal", - "title":"Embeded chart content", - "close":"Close", - "embed":"/examples/chart.sql?_sqlpage_embed" - }, - {"component": "datagrid"}, - {"title":"Chart", "color":"blue", "description":"Revenue", "link":"#my_embed_chart_modal"}, - {"title":"Form", "color":"green", "description":"Fill info", "link":"#my_embed_form_modal"}, - ]') - ), - ('modal', - 'Example of modal video content', - json('[ - { - "component":"modal", - "id":"my_embed_video_modal", - "title":"Embeded video content", - "close":"Close", - "embed":"https://www.youtube.com/embed/mXdgmSdaXkg", - "allow":"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share", - "embed_mode":"iframe", - "height":"350" - }, - {"component": "text", "contents_md": "Open a [modal with a video](#my_embed_video_modal)"} - ]') - ); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'button', * FROM (VALUES - ('modal','Display the modal window corresponding to the specified ID.','TEXT',FALSE,TRUE) -) x; diff --git a/examples/official-site/sqlpage/migrations/65_download.sql b/examples/official-site/sqlpage/migrations/65_download.sql deleted file mode 100644 index a05b49ab8..000000000 --- a/examples/official-site/sqlpage/migrations/65_download.sql +++ /dev/null @@ -1,140 +0,0 @@ --- Insert the download component into the component table -INSERT INTO - component (name, description, icon, introduced_in_version) -VALUES - ( - 'download', - ' -The *download* component lets a page immediately return a file to the visitor. - -Instead of showing a web page, it sends the file''s bytes as the whole response, -so it should be used **at the very top of your SQL page** (before the shell or any other page contents). -It is an error to use this component after another component that would display content. - -## Sending a file - -- You provide the file content using a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs). -A data URL is just a text string that contains both the file type and the actual data. -- Optionally, you provide a "filename" so the browser shows a proper Save As name. -If you do not provide a filename, many browsers will try to display the file inline (for example images or JSON), depending on the content type. -- You link to the page that uses the download component from another page, using the [button](/component.sql?component=button) component for example. - -## Data URL format - -- It looks like this: `data:[content-type][;base64],DATA` -- Examples: - - Plain text (URL-encoded): `data:text/plain,Hello%20world` - - JSON (URL-encoded): `data:application/json,%7B%22message%22%3A%22Hi%22%7D` - - Binary data (Base64): `data:application/octet-stream;base64,SGVsbG8h` - -Tips: -- Use URL encoding when you have textual data. You can use [`sqlpage.url_encode(source_text)`](/functions?function=url_encode) to encode the data. -- Use Base64 when you have binary data (images, PDFs, or content that may include special characters). -- Use [`sqlpage.read_file_as_data_url(file_path)`](/functions?function=read_file_as_data_url) to read a file from the server and return it as a data URL. - -> Keep in mind that large files are better served from disk or object storage. Data URLs are best for small to medium files. -There is a big performance penalty for loading large files as data URLs, so it is not recommended. -', - 'download', - '0.37.0' - ); - --- Insert the parameters for the download component into the parameter table -INSERT INTO - parameter ( - component, - name, - description, - type, - top_level, - optional - ) -VALUES - ( - 'download', - 'data_url', - 'The file content to send, written as a data URL (for example: data:text/plain,Hello%20world or data:application/octet-stream;base64,SGVsbG8h). The part before the comma declares the content type and whether the data is base64-encoded. The part after the comma is the actual data.', - 'TEXT', - TRUE, - FALSE - ), - ( - 'download', - 'filename', - 'The suggested name of the file to save (for example: report.csv). When set, the browser will download the file as an attachment with this name. When omitted, many browsers may try to display the file inline depending on its content type.', - 'TEXT', - TRUE, - TRUE - ); - --- Insert usage examples of the download component into the example table -INSERT INTO - example (component, description) -VALUES - ( - 'download', - ' -## Simple plain text file -Download a small text file. The content is URL-encoded (spaces become %20). - -```sql -select - ''download'' as component, - ''data:text/plain,Hello%20SQLPage%20world!'' as data_url, - ''hello.txt'' as filename; -``` -' - ), - ( - 'download', - ' -## Download a PDF file from the server - -Download a PDF file with the proper content type so PDF readers recognize it. -Uses [`sqlpage.read_file_as_data_url(file_path)`](/functions?function=read_file_as_data_url) to read the file from the server. - -```sql -select - ''download'' as component, - ''report.pdf'' as filename, - sqlpage.read_file_as_data_url(''report.pdf'') as data_url; -``` -' - ), - ( - 'download', - ' -## Serve an image stored as a BLOB in the database - -### Automatically detect the mime type - -If you have a table with a column `content` that contains a BLOB -(depending on the database, the type may be named `BYTEA`, `BLOB`, `VARBINARY`, or `IMAGE`), -you can just return its contents directly, and SQLPage will automatically detect the mime type, -and convert it to a data URL. - -```sql -select - ''download'' as component, - content as data_url -from document -where id = $doc_id; -``` - -### Customize the mime type - -In PostgreSQL, you can use the [encode(bytes, format)](https://www.postgresql.org/docs/current/functions-binarystring.html#FUNCTION-ENCODE) function to encode the file content as Base64, -and manually create your own data URL. - -```sql -select - ''download'' as component, - ''data:'' || doc.mime_type || '';base64,'' || encode(doc.content::bytea, ''base64'') as data_url -from document as doc -where doc.id = $doc_id; -``` - - - In Microsoft SQL Server, you can use the [BASE64_ENCODE(bytes)](https://learn.microsoft.com/en-us/sql/t-sql/functions/base64-encode-transact-sql) function to encode the file content as Base64. - - In MySQL and MariaDB, you can use the [TO_BASE64(str)](https://mariadb.com/docs/server/reference/sql-functions/string-functions/to_base64) function. -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/66_log_component.sql b/examples/official-site/sqlpage/migrations/66_log_component.sql deleted file mode 100644 index 3a2cb083b..000000000 --- a/examples/official-site/sqlpage/migrations/66_log_component.sql +++ /dev/null @@ -1,61 +0,0 @@ -INSERT INTO component(name, icon, introduced_in_version, description) VALUES -('log', 'logs', '0.37.1', 'A component that writes messages to the server logs. -When a page runs, it prints your message to the terminal/console (standard error). -Use it to track what happens and troubleshoot issues. - -## Reading log messages - -- Running from a terminal (Linux, macOS, or Windows PowerShell/Command Prompt): they show up in the window. -- Docker: run `docker logs `. -- Linux service (systemd): run `journalctl -u sqlpage`. -- This component''s output is written to [standard error (stderr)](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)). SQLPage request access logs are separate and are written to standard output (stdout). -'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'log', * FROM (VALUES - -- top level - ('message', 'The text to write to the server logs. It is printed when the page runs.', 'TEXT', TRUE, FALSE), - ('level', 'How important the message is. One of ''trace'', ''debug'', ''info'' (default), ''warn'', ''error''. Not case-sensitive. Controls the level shown in the logs.', 'TEXT', TRUE, TRUE) -) x; - -INSERT INTO example(component, description) VALUES -('log', ' -### Record a simple message - -This writes "Hello, World!" to the server logs. - -```sql -SELECT ''log'' as component, ''Hello, World!'' as message; -``` - -Example output: - -```text -[2025-09-13T22:30:14.722Z INFO sqlpage::log from "x.sql" statement 1] Hello, World! -``` - -### Set the importance (level) - -Choose how important the message is. - -```sql -SELECT ''log'' as component, ''error'' as level, ''This is an error message'' as message; -``` - -Example output: - -```text -[2025-09-13T22:30:14.722Z ERROR sqlpage::log from "x.sql" statement 2] This is an error message -``` - -### Log dynamic information - -Include variables like a username. - -```sql -set username = ''user'' - -select ''log'' as component, - ''403 - failed for '' || coalesce($username, ''None'') as message, - ''error'' as level; -``` -') diff --git a/examples/official-site/sqlpage/migrations/67_hmac_function.sql b/examples/official-site/sqlpage/migrations/67_hmac_function.sql deleted file mode 100644 index 86ebda476..000000000 --- a/examples/official-site/sqlpage/migrations/67_hmac_function.sql +++ /dev/null @@ -1,137 +0,0 @@ --- HMAC function documentation and examples -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'hmac', - '0.38.0', - 'shield-lock', - 'Creates a unique "signature" for some data using a secret key. -This signature proves that the data hasn''t been tampered with and comes from someone who knows the secret. - -## HMAC use cases - -[**HMAC**](https://en.wikipedia.org/wiki/HMAC) (Hash-based Message Authentication Code) is commonly used to: - - **Verify webhooks**: Use HMAC to ensure only a given external service can call a given endpoint in your application. -The service signs their request with a secret key, and you verify the signature before processing the data they sent you. -Used for instance by [Stripe](https://docs.stripe.com/webhooks?verify=verify-manually), and [Shopify](https://shopify.dev/docs/apps/build/webhooks/subscribe/https#step-2-validate-the-origin-of-your-webhook-to-ensure-its-coming-from-shopify). - - **Secure API requests**: Prove that an API request comes from an authorized source - - **Generate secure tokens**: Create temporary access codes for downloads or password resets - - **Protect data**: Ensure data hasn''t been modified during transmission - -## Signing data - -The `sqlpage.hmac` function takes three inputs: -1. **Your data** - The text you want to sign (like a message or request body) -2. **Your secret key** - A password only you know (keep this safe!) -3. **Algorithm** (optional) - The hash algorithm and output format: - - `sha256` (default) - SHA-256 with hexadecimal output - - `sha256-base64` - SHA-256 with base64 output - - `sha512` - SHA-512 with hexadecimal output - - `sha512-base64` - SHA-512 with base64 output - -It returns a signature string. If someone changes even one letter in your data, the signature will be completely different. - -### Example: Verify a Webhooks signature - -When Shopify sends you a webhook (like when someone places an order), it includes a signature. Here''s how to verify it''s really from Shopify. -This supposes you store the secret key in an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) named `WEBHOOK_SECRET`. - -```sql -SET body = sqlpage.request_body(); -SET secret = sqlpage.environment_variable(''WEBHOOK_SECRET''); -SET expected_signature = sqlpage.hmac($body, $secret, ''sha256''); -SET actual_signature = sqlpage.header(''X-Webhook-Signature''); - --- redirect to an error page and stop execution if the signature does not match -SELECT - ''redirect'' as component, - ''/error.sql?err=bad_webhook_signature'' as link -WHERE $actual_signature != $expected_signature OR $actual_signature IS NULL; - --- If we reach here, the signature is valid - process the order -INSERT INTO orders (order_data) VALUES ($body); - -SELECT ''json'' as component, ''jsonlines'' as type; -SELECT ''success'' as status; -``` - -### Example: Time-limited links - -You can create links that will be valid only for a limited time by including a signature in them. -Let''s say we have a `download.sql` page we want to link to, -but we don''t want it to be accessible to anyone who can find the link. -Sign `file_id|expires_at` with a secret. Accept only if not expired and the signature matches. - -#### Generate a signed link - -```sql -SET expires_at = datetime(''now'', ''+1 hour''); -SET token = sqlpage.hmac( - $file_id || ''|'' || $expires_at, - sqlpage.environment_variable(''DOWNLOAD_SECRET''), - ''sha256'' -); -SELECT ''/download.sql?file_id='' || $file_id || ''&expires_at='' || $expires_at || ''&token='' || $token AS link; -``` - -#### Verify the signed link - -```sql -SET expected = sqlpage.hmac( - $file_id || ''|'' || $expires_at, - sqlpage.environment_variable(''DOWNLOAD_SECRET''), - ''sha256'' -); -SELECT ''redirect'' AS component, ''/error.sql?err=expired'' AS link -WHERE $expected != $token OR $token IS NULL OR $expires_at < datetime(''now''); - --- serve the file -``` - -### Important Security Notes - - - **Keep your secret key safe**: If your secret leaks, anyone can forge signatures and access protected pages - - **The signature is case-sensitive**: Even a single wrong letter means the signature won''t match - - **NULL handling**: Always use `IS DISTINCT FROM`, not `=` to check for hmac matches. - - `SELECT ''redirect'' as component WHERE sqlpage.hmac(...) != $signature` will not redirect if `$signature` is NULL (the signature is absent). - - `SELECT ''redirect'' as component WHERE sqlpage.hmac(...) IS DISTINCT FROM $signature` checks for both NULL and non-NULL values (but is not available in all SQL dialects). - - `SELECT ''redirect'' as component WHERE sqlpage.hmac(...) != $signature OR $signature IS NULL` is the most portable solution. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'hmac', - 1, - 'data', - 'The input data to compute the HMAC for. Can be any text string. Cannot be NULL.', - 'TEXT' - ), - ( - 'hmac', - 2, - 'key', - 'The secret key used to compute the HMAC. Should be kept confidential. Cannot be NULL.', - 'TEXT' - ), - ( - 'hmac', - 3, - 'algorithm', - 'The hash algorithm and output format. Optional, defaults to `sha256` (hex output). Supported values: `sha256`, `sha256-base64`, `sha512`, `sha512-base64`. Defaults to `sha256`.', - 'TEXT' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/68_login.sql b/examples/official-site/sqlpage/migrations/68_login.sql deleted file mode 100644 index 11d29de18..000000000 --- a/examples/official-site/sqlpage/migrations/68_login.sql +++ /dev/null @@ -1,79 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('login', 'password-user', ' -The login component is an authentication form with numerous customization options. -It offers the main functionalities for this type of form. -The user can enter their username and password. -There are many optional attributes such as the use of icons on input fields, the insertion of a link to a page to reset the password, an option for the application to maintain the user''s identity via a cookie. -It is also possible to set the title of the form, display the company logo, or customize the appearance of the form submission button. - -This component should be used in conjunction with other components such as [authentication](component.sql?component=authentication) and [cookie](component.sql?component=cookie). -It does not implement any logic and simply collects the username and password to pass them to the code responsible for authentication. - -A few things to know : -- The form uses the POST method to transmit information to the destination page, -- The user''s username and password are entered into fields with the names `username` and `password`, -- To obtain the values of username and password, you must use the variables `:username` and `:password`, -- When you set the `remember_me_text` property, the variable `:remember` becomes available after form submission to check if the user checked the "remember me" checkbox. -', '0.39.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'login', * FROM (VALUES - ('title','Title of the authentication form.','TEXT',TRUE,TRUE), - ('enctype','Form data encoding.','TEXT',TRUE,TRUE), - ('action','An optional link to a target page that will handle the results of the form. ','TEXT',TRUE,TRUE), - ('error_message','An error message to display above the form, typically shown after a failed login attempt.','TEXT',TRUE,TRUE), - ('error_message_md','A markdown error message to display above the form, typically shown after a failed login attempt.','TEXT',TRUE,TRUE), - ('username','Label and placeholder for the user account identifier text field.','TEXT',TRUE,FALSE), - ('password','Label and placeholder for the password field.','TEXT',TRUE,FALSE), - ('autofocus','Focus the username field when the page opens. Defaults to true. Set to false when the form is one part of a larger page.','BOOLEAN',TRUE,TRUE), - ('username_icon','Icon to display on the left side of the input field, on the same line.','ICON',TRUE,TRUE), - ('password_icon','Icon to display on the left side of the input field, on the same line.','ICON',TRUE,TRUE), - ('image','The URL of an centered image displayed before the title.','URL',TRUE,TRUE), - ('forgot_password_text','A text for the link allowing the user to reset their password. If the text is empty, the link is not displayed.','TEXT',TRUE,TRUE), - ('forgot_password_link','The link to the page allowing the user to reset their password.','TEXT',TRUE,TRUE), - ('remember_me_text','A text for the option allowing the user to request the preservation of their identity. If the text is empty, the option is not displayed.','TEXT',TRUE,TRUE), - ('footer','A text placed at the bottom of the authentication form. If both footer and footer_md are specified, footer takes precedence.','TEXT',TRUE,TRUE), - ('footer_md','A markdown text placed at the bottom of the authentication form. Useful for creating links to other pages (creating a new account, contacting technical support, etc.).','TEXT',TRUE,TRUE), - ('validate','The text to display in the button at the bottom of the form that submits the values.','TEXT',TRUE,TRUE), - ('validate_color','The color of the button at the bottom of the form that submits the values. Omit this property to use the default color.','COLOR',TRUE,TRUE), - ('validate_shape','The shape of the validation button.','TEXT',TRUE,TRUE), - ('validate_outline','A color to outline the validation button.','COLOR',TRUE,TRUE), - ('validate_size','The size of the validation button.','TEXT',TRUE,TRUE) -) x; - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'login', - 'Using the main options of the login component - -When the user clicks the "Sign in" button, the form is submitted to the `/examples/show_variables.sql` page. -There, you will have access to the variables: - - `:username`: the username entered by the user - - `:password`: the password entered by the user - - `:remember`: the string "on" if the checkbox was checked, or NULL if it was not checked -', - JSON( - '[ - { - "component": "login", - "action": "/examples/show_variables", - "image": "../assets/icon.webp", - "title": "Please login to your account", - "username": "Username", - "password": "Password", - "autofocus": false, - "username_icon": "user", - "password_icon": "lock", - "forgot_password_text": "Forgot your password?", - "forgot_password_link": "reset_password.sql", - "remember_me_text": "Remember me", - "footer_md": "Don''t have an account? [Register here](register.sql)", - "validate": "Sign in" - } - ]' - ) - ), - ('login', 'Basic login form', JSON('[{"component": "login", "username": "Username", "password": "Password", "autofocus": false}]')); - -INSERT INTO parameter(component, name, description, type, top_level, optional) VALUES - ('login', 'image_alt', 'Alternative text for an informative login image. Leave empty if decorative.', 'TEXT', TRUE, TRUE); diff --git a/examples/official-site/sqlpage/migrations/70_pagination.sql b/examples/official-site/sqlpage/migrations/70_pagination.sql deleted file mode 100644 index 5bb50d01a..000000000 --- a/examples/official-site/sqlpage/migrations/70_pagination.sql +++ /dev/null @@ -1,252 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('pagination', 'sailboat-2', ' -Navigation links to go to the first, previous, next, or last page of a dataset. -Useful when data is divided into pages, each containing a fixed number of rows. - -This component only handles the display of pagination. -**Your sql queries are responsible for filtering data** based on the page number passed as a URL parameter. - -This component is typically used in conjunction with a [table](?component=table), -[list](?component=list), or [card](?component=card) component. - -The pagination component displays navigation buttons (first, previous, next, last) customizable with text or icons. - -For large numbers of pages, an offset can limit the visible page links. - -A minimal example of a SQL query that uses the pagination would be: -```sql -select ''table'' as component; -select * from my_table limit 100 offset $offset; - -select ''pagination'' as component; -with recursive pages as ( - select 0 as offset - union all - select offset + 100 from pages - where offset + 100 < (select count(*) from my_table) -) -select - (offset/100+1) as contents, - sqlpage.link(sqlpage.path(), json_object(''offset'', offset)) as link, - offset = coalesce(cast($offset as integer), 0) as active -from pages; -``` - -For more advanced usage, the [pagination guide](blog.sql?post=How+to+use+the+pagination+component) provides a complete tutorial. -', '0.40.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'pagination', * FROM (VALUES - -- Top-level parameters - ('first_link','A target URL to which the user should be directed to get to the first page. If none, the link is not displayed.','URL',TRUE,TRUE), - ('previous_link','A target URL to which the user should be directed to get to the previous page. If none, the link is not displayed.','URL',TRUE,TRUE), - ('next_link','A target URL to which the user should be directed to get to the next page. If none, the link is not displayed.','URL',TRUE,TRUE), - ('last_link','A target URL to which the user should be directed to get to the last page. If none, the link is not displayed.','URL',TRUE,TRUE), - ('first_title','The text displayed on the button to go to the first page.','TEXT',TRUE,TRUE), - ('previous_title','The text displayed on the button to go to the previous page.','TEXT',TRUE,TRUE), - ('next_title','The text displayed on the button to go to the next page.','TEXT',TRUE,TRUE), - ('last_title','The text displayed on the button to go to the last page.','TEXT',TRUE,TRUE), - ('first_disabled','disables the button to go to the first page.','BOOLEAN',TRUE,TRUE), - ('previous_disabled','disables the button to go to the previous page.','BOOLEAN',TRUE,TRUE), - ('next_disabled','Disables the button to go to the next page.','BOOLEAN',TRUE,TRUE), - ('last_disabled','disables the button to go to the last page.','BOOLEAN',TRUE,TRUE), - ('outline','Whether to use outline version of the pagination.','BOOLEAN',TRUE,TRUE), - ('circle','Whether to use circle version of the pagination.','BOOLEAN',TRUE,TRUE), - -- Item-level parameters (for each page) - ('contents','Page number.','INTEGER',FALSE,FALSE), - ('link','A target URL to which the user should be redirected to view the requested page of data.','URL',FALSE,TRUE), - ('offset','Whether to use offset to show only a few pages at a time. Usefull if the count of pages is too large. Defaults to false','BOOLEAN',FALSE,TRUE), - ('active','Whether the link is active or not. Defaults to false.','BOOLEAN',FALSE,TRUE) -) x; - - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'pagination', - 'This is an extremely simple example of a pagination component that displays only the page numbers, with the first page being the current page.', - JSON( - '[ - { - "component": "pagination" - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'The ouline style adds a rectangular border to each navigation link.', - JSON( - '[ - { - "component": "pagination", - "outline": true - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'The circle style adds a circular border to each navigation link.', - JSON( - '[ - { - "component": "pagination", - "circle": true - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'The following example implements navigation links that can be enabled or disabled as needed. Since a navigation link does not appear if no link is assigned to it, you must always assign a link to display it as disabled.', - JSON( - '[ - { - "component": "pagination", - "first_link": "?component=pagination", - "first_disabled": true, - "previous_link": "?component=pagination", - "previous_disabled": true, - "next_link": "#?page=2", - "last_link": "#?page=3" - - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'Instead of using icons, you can apply text to the navigation links.', - JSON( - '[ - { - "component": "pagination", - "first_title": "First", - "last_title": "Last", - "previous_title": "Previous", - "next_title": "Next", - "first_link": "?component=pagination", - "first_disabled": true, - "previous_link": "?component=pagination", - "previous_disabled": true, - "next_link": "#?page=2", - "last_link": "#?page=3" - - }, - { - "contents": 1, - "link": "?component=pagination&page=1", - "active": true - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - } - ]' - ) - ), - ( - 'pagination', - 'If you have a large number of pages to display, you can use an offset to represent a group of pages.', - JSON( - '[ - { - "component": "pagination", - "first_link": "#?page=1", - "previous_link": "#?page=3", - "next_link": "#?page=4", - "last_link": "#?page=99" - - }, - { - "contents": 1, - "link": "?component=pagination&page=1" - }, - { - "contents": 2, - "link": "?component=pagination&page=2" - }, - { - "contents": 3, - "link": "?component=pagination&page=3" - }, - { - "contents": 4, - "link": "?component=pagination&page=4", - "active": true - }, - { - "contents": 5, - "link": "?component=pagination&page=5" - }, - { - "contents": 6, - "link": "?component=pagination&page=6" - }, - { - "offset": true - }, - { - "contents": 99, - "link": "?component=pagination&page=99" - }, - ]' - ) - ); - \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/72_set_variable.sql b/examples/official-site/sqlpage/migrations/72_set_variable.sql deleted file mode 100644 index 94ae7aad1..000000000 --- a/examples/official-site/sqlpage/migrations/72_set_variable.sql +++ /dev/null @@ -1,64 +0,0 @@ -INSERT INTO - sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES - ( - 'set_variable', - '0.40.0', - 'variable', - 'Returns a URL that is the same as the current page''s URL, but with a variable set to a new value. - -This function is useful when you want to create a link that changes a parameter on the current page, while preserving other parameters. - -It is equivalent to `sqlpage.link(sqlpage.path(), json_patch(sqlpage.variables(''get''), json_object(name, value)))`. - -### Example - -Let''s say you have a list of products, and you want to filter them by category. You can use `sqlpage.set_variable` to create links that change the category filter, without losing other potential filters (like a search query or a sort order). - -```sql -select ''button'' as component, ''sm'' as size, ''center'' as justify; -select - category as title, - sqlpage.set_variable(''category'', category) as link, - case when $category = category then ''primary'' else ''secondary'' end as color -from categories; -``` - -When `sqlpage.set_variable(...)` is used as a standalone selected column in a query that returns several rows, it runs once per returned row. -This is useful for generating one link per row, as in the example above. -If you need a single link reused later in the page, store it with `SET` first. - -### Parameters - - `name` (TEXT): The name of the variable to set. - - `value` (TEXT): The value to set the variable to. If `NULL` is passed, the variable is removed from the URL. -' - ); - -INSERT INTO - sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES - ( - 'set_variable', - 1, - 'name', - 'The name of the variable to set.', - 'TEXT' - ), - ( - 'set_variable', - 2, - 'value', - 'The value to set the variable to.', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/76_toast.sql b/examples/official-site/sqlpage/migrations/76_toast.sql deleted file mode 100644 index 4afc43fbd..000000000 --- a/examples/official-site/sqlpage/migrations/76_toast.sql +++ /dev/null @@ -1,48 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('toast', 'notification', ' -Displays a brief notification above the page. Each top-level `toast` row creates one notification, and consecutive toasts at the same position are queued in a shared stack. - -Ordinary notifications use `role="status"` and `aria-live="polite"`. Colored variants retain a readable contrasting foreground. Automatic dismissal and the manual close control are configured independently.', '0.46.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'toast', * FROM (VALUES - ('title', 'Optional notification heading.', 'TEXT', TRUE, TRUE), - ('description', 'Escaped plain-text body. This is used only when `description_md` is not supplied.', 'TEXT', TRUE, TRUE), - ('description_md', 'Rich-text alternative to `description`, rendered as Markdown. When both properties are supplied, `description_md` takes precedence.', 'TEXT', TRUE, TRUE), - ('icon', 'Optional [Tabler icon](https://tabler.io/icons) name.', 'ICON', TRUE, TRUE), - ('color', 'Optional Tabler color. The default is the neutral toast appearance; colored variants use the matching contrasting foreground utility.', 'COLOR', TRUE, TRUE), - ('dismissible', 'Whether to render an accessible manual close button. Defaults to true and is independent of automatic dismissal.', 'BOOLEAN', TRUE, TRUE), - ('duration', 'Automatic dismissal delay in milliseconds. Defaults to 5000. Set to 0 to keep the toast visible until manually dismissed (when `dismissible` is true) or the page is left.', 'INTEGER', TRUE, TRUE), - ('position', 'Screen placement: `top-start`, `top-center`, `top-end`, `bottom-start`, `bottom-center`, or `bottom-end`. Defaults to `top-end`; invalid values safely fall back to that default.', 'TEXT', TRUE, TRUE), - ('trigger', 'Optional URL fragment that opens the toast without reloading the page, with or without the leading `#`. When set, the toast does not open on page load and can be opened repeatedly by a link or button whose target is that fragment. Multiple toasts can share a trigger to open as a stack.', 'TEXT', TRUE, TRUE) - -- id and class come from 99_shared_id_class_attributes.sql -) x; - -INSERT INTO example(component, description, properties) VALUES - ('toast', 'A toast that opens when the page loads and disappears automatically after the default 5000 milliseconds.', json('[ - {"component":"toast","id":"toast-auto","title":"This is a SQLPage toast","description":"This toast will open automatically when the page loads.","icon":"check","color":"green"} - ]')), - ('toast', 'A persistent error notification that disables automatic dismissal and requires the user to activate its close button.', json('[ - {"component":"toast","id":"toast-dismissible","trigger":"persistent-error","title":"Could not save","description":"Review the highlighted fields and try again.","icon":"alert-triangle","color":"black","duration":0,"dismissible":true}, - {"component":"toast","id":"toast-nondismissible","trigger":"persistent-status","title":"Connection unavailable","description":"This persistent notification has no manual close control.","duration":0,"dismissible":false}, - {"component":"button"}, - {"title":"Show dismissible error","link":"#persistent-error","color":"red"}, - {"title":"Show non-dismissible status","link":"#persistent-status"} - ]')), - ('toast', 'A persistent rich Markdown notification. Markdown takes precedence over plain text and renders emphasis and a link as HTML, while plain-text content remains escaped.', json('[ - {"component":"toast","id":"toast-markdown","trigger":"rich-notifications","title":"Release available","description":"This fallback stays escaped","description_md":"Version **2.0** is ready. [Read the notes](https://example.com/releases).","color":"blue","duration":0}, - {"component":"toast","id":"toast-plain","trigger":"rich-notifications","description":"Plain text stays escaped","color":"white","duration":0}, - {"component":"button"}, - {"title":"Show rich notifications","link":"#rich-notifications"} - ]')), - ('toast', 'Several persistent queued notifications. Toasts with the same position share a container and stack instead of overlapping.', json('[ - {"component":"toast","id":"toast-stack-one","trigger":"queued notifications","title":"Import started","description":"Preparing records.","duration":0}, - {"component":"toast","id":"toast-stack-two","trigger":"queued notifications","title":"Import running","description":"Processing records.","duration":0}, - {"component":"toast","id":"toast-short","trigger":"queued notifications","title":"Temporary update","description":"This message closes shortly.","duration":2000}, - {"component":"button"}, - {"title":"Show queued notifications","link":"#queued notifications"} - ]')), - ('toast', 'A notification placed at the bottom center of the screen instead of the default top end.', json('[ - {"component":"toast","id":"toast-bottom-center","trigger":"bottom-notification","title":"Download ready","description":"Your export is ready.","position":"bottom-center","duration":0}, - {"component":"button"}, - {"title":"Show bottom notification","link":"#bottom-notification"} - ]')); diff --git a/examples/official-site/sqlpage/migrations/77_facet.sql b/examples/official-site/sqlpage/migrations/77_facet.sql deleted file mode 100644 index c721d2ff4..000000000 --- a/examples/official-site/sqlpage/migrations/77_facet.sql +++ /dev/null @@ -1,130 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('facet', 'filter', ' -Navigation links for filtering a dataset by a category, status, owner, or other attribute. - -This component only renders the filter navigation. **Your SQL query is responsible for filtering the data** based on the URL parameter selected by the user. - -Use it alongside a [table](?component=table), [list](?component=list), or [card](?component=card). The links use GET parameters, so the selected filter can be bookmarked and shared. - -Set `compact` to display the facets in a dropdown, which is useful for a moderate number of choices or on narrow screens. Use `selected_facet` to show the active facet in the closed dropdown. `all_link` and `all_title` add a link that clears the filter. - -The following portable pattern filters a table by category. `sqlpage.link` preserves the current page path while safely generating the URL. - -```sql -select ''table'' as component; -select title, category -from my_table -where $category is null or category = $category; - -select ''facet'' as component, - ''Category'' as description, - sqlpage.link(sqlpage.path(), json_object(''category'', null)) as all_link, - $category is null as all_active; -select category as title, - sqlpage.link(sqlpage.path(), json_object(''category'', category)) as link, - category = $category as active -from my_table -group by category -order by category; -``` -', '0.46.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) SELECT 'facet', * FROM (VALUES - -- Top-level parameters - ('description','The facet category label.','TEXT',TRUE,TRUE), - ('dropdown_title','Text shown on the compact-mode dropdown button when no facet is selected. Defaults to `Choose facet`.','TEXT',TRUE,TRUE), - ('selected_facet','An alias for `dropdown_title`.','TEXT',TRUE,TRUE), - ('compact','Displays the facets in a dropdown instead of links.','BOOLEAN',TRUE,TRUE), - ('center','Whether to center the facet selector','BOOLEAN',TRUE,TRUE), - ('all_link','URL that clears the filter. If omitted, no All link is displayed.','URL',TRUE,TRUE), - ('all_title','Text for the link that clears the filter. Defaults to "ALL".','TEXT',TRUE,TRUE), - ('all_active','Whether the link that clears the filter is active. Defaults to false.','BOOLEAN',TRUE,TRUE), - -- Item-level parameters (for each facet) - ('title','Facet title.','TEXT',FALSE,FALSE), - ('link','URL for the facet.','URL',FALSE,FALSE), - ('active','Whether the link is active or not. Defaults to false.','BOOLEAN',FALSE,TRUE) -) x; - --- Insert example(s) for the component -INSERT INTO example(component, description, properties) -VALUES ( - 'facet', - 'A category selector with an All link. In an application, the SQL pattern above uses the chosen URL parameter to filter the displayed data.', - JSON( - '[ - { - "component": "table" - }, - { - "name": "USS Enterprise (NCC-1701)", - "class": "Constitution" - }, - { - "name": "USS Exeter (NCC-1672)", - "class": "Galaxy" - }, - { - "name": "USS Exeter (NCC-1672)", - "class": "Constitution" - }, - { - "component": "facet", - "description": "Classes", - "all_link": "?component=facet", - "all_title": "All", - "all_active": false - }, - { - "title": "Constitution", - "link": "?component=facet&class=Constitution", - "active": true - }, - { - "title": "Galaxy", - "link": "?component=facet&class=Galaxy" - } - ]' - ) - ), - ( - 'facet', - 'Compact mode displays the facet choices in a dropdown.', - JSON( - '[ - { - "component": "table" - }, - { - "name": "USS Enterprise (NCC-1701)", - "class": "Constitution" - }, - { - "name": "USS Defiant (NCC-1764)", - "class": "Constitution" - }, - { - "name": "USS Exeter (NCC-1672)", - "class": "Constitution" - }, - { - "component": "facet", - "description": "Classes", - "all_link": "?component=facet", - "all_title": "All", - "all_active": false, - "compact": true, - "dropdown_title": "Select a spaceship class", - "selected_facet": "Constitution" - }, - { - "title": "Constitution", - "link": "?component=facet&class=Constitution", - "active": true - }, - { - "title": "Galaxy", - "link": "?component=facet&class=Galaxy" - } - ]' - ) - ); diff --git a/examples/official-site/sqlpage/migrations/79_persist_uploaded_files.sql b/examples/official-site/sqlpage/migrations/79_persist_uploaded_files.sql deleted file mode 100644 index 46b83efc9..000000000 --- a/examples/official-site/sqlpage/migrations/79_persist_uploaded_files.sql +++ /dev/null @@ -1,88 +0,0 @@ -INSERT INTO sqlpage_functions ( - "name", - "introduced_in_version", - "icon", - "description_md" - ) -VALUES ( - 'persist_uploaded_files', - '0.49.0', - 'files', - 'Persists all the files uploaded in a single form field, and returns a JSON array with one object per file: - - - `path`: where the file was saved, relative to the web root (like the return value of [`persist_uploaded_file`](?function=persist_uploaded_file)), - - `name`: the original name of the file on the user''s device, - - `mime_type`: the type of the file, as sent by the browser, - - `size`: the size of the file, in bytes. - -If no file was uploaded in the field, the function returns NULL. - -Use it with a file input that has the `multiple` attribute, so that users can select several files at once. -It works like [`persist_uploaded_file`](?function=persist_uploaded_file), -which only persists one file (the last one, when several were sent). - -If one of the files has an extension that is not allowed, or cannot be saved, the function fails and no file is persisted. - -### Example - -#### Photo gallery - -##### `upload_form.sql` - -```sql -select ''form'' as component, ''save_photos.sql'' as action; -select ''file'' as type, ''photos[]'' as name, ''Photos'' as label, true as multiple, ''image/*'' as accept; -``` - -##### `save_photos.sql` - -```sql -set files = sqlpage.persist_uploaded_files(''photos'', ''photos'', ''jpg,jpeg,png,webp''); - --- SQLite (PostgreSQL: json_array_elements($files::json), SQL Server: OPENJSON($files)) -insert into photo (local_path, name, mime_type, size) -select value ->> ''path'', value ->> ''name'', value ->> ''mime_type'', value ->> ''size'' -from json_each($files); - -select ''redirect'' as component, ''gallery.sql'' as link; -``` -' - ); -INSERT INTO sqlpage_function_parameters ( - "function", - "index", - "name", - "description_md", - "type" - ) -VALUES ( - 'persist_uploaded_files', - 1, - 'files', - 'Name of the form field containing the uploaded files. A field named `photos[]` in the form can be referenced as `photos`.', - 'TEXT' - ), - ( - 'persist_uploaded_files', - 2, - 'destination_folder', - 'Optional. Path to the folder where the files will be saved, relative to the web root. By default, the files will be saved in the `uploads` folder. - -**Security note**: this value must be a folder name you choose yourself in your SQL code (a trusted constant). Never build it from untrusted input: see [`persist_uploaded_file`](?function=persist_uploaded_file).', - 'TEXT' - ), - ( - 'persist_uploaded_files', - 3, - 'allowed_extensions', - 'Optional. Comma-separated list of allowed file extensions, checked for every file. By default: jpg,jpeg,png,gif,bmp,webp,pdf,txt,doc,docx,xls,xlsx,csv,mp3,mp4,wav,avi,mov. -Changing this may be dangerous ! If you add "sql", "svg" or "html" to the list, an attacker could execute arbitrary SQL queries on your database, or impersonate other users.', - 'TEXT' - ), - ( - 'persist_uploaded_files', - 4, - 'mode', - 'Optional. Unix permissions to set on the files, in octal notation. By default, "600" (read/write for the owner only).', - 'TEXT' - ); diff --git a/examples/official-site/sqlpage/migrations/80_status_bar.sql b/examples/official-site/sqlpage/migrations/80_status_bar.sql deleted file mode 100644 index 9a4ce68d6..000000000 --- a/examples/official-site/sqlpage/migrations/80_status_bar.sql +++ /dev/null @@ -1,23 +0,0 @@ -INSERT INTO component(name, icon, description, introduced_in_version) VALUES - ('status_bar', 'layout-bottombar', - 'Display short status messages and links in a single horizontal bar. Each row adds one segment. When there are several segments, the last one aligns to the far edge. If the segments do not all fit, scroll the bar horizontally to see the rest.', - '0.49.0'); - -INSERT INTO parameter(component, name, description, type, top_level, optional) -SELECT 'status_bar', * FROM (VALUES - ('fixed', 'Keep the bar at the bottom of the screen while the page scrolls. Defaults to true. A fixed bar overlays page content, so leave space below your last item if needed. Set to false to place the bar in the page where the SQL appears.', 'BOOLEAN', TRUE, TRUE), - ('label', 'Accessible name for the bar. Defaults to "Status bar".', 'TEXT', TRUE, TRUE), - ('title', 'Text displayed in the segment.', 'TEXT', FALSE, TRUE), - ('icon', 'Icon displayed before the text.', 'ICON', FALSE, TRUE), - ('color', 'Color of the segment text and icon.', 'COLOR', FALSE, TRUE), - ('tooltip', 'Text shown when hovering over the segment or focusing its link. For an icon without a title, supply a tooltip to give the segment an accessible name.', 'TEXT', FALSE, TRUE), - ('link', 'URL to open when the segment is clicked.', 'URL', FALSE, TRUE) -) p; - -INSERT INTO example(component, description, properties) VALUES - ('status_bar', 'A query workspace shows the database connection, row count, and a link to the function reference. Omit `fixed` to pin this bar to the bottom of the screen.', json('[ - {"component":"status_bar","label":"Query status","fixed":false}, - {"title":"Connected","icon":"database","color":"green","tooltip":"Connected to the reporting database"}, - {"title":"24 rows"}, - {"title":"SQL functions","icon":"book","link":"/functions.sql"} - ]')); diff --git a/examples/official-site/sqlpage/migrations/81_guide_directory.sql b/examples/official-site/sqlpage/migrations/81_guide_directory.sql deleted file mode 100644 index 0a8687df1..000000000 --- a/examples/official-site/sqlpage/migrations/81_guide_directory.sql +++ /dev/null @@ -1,15 +0,0 @@ -CREATE TABLE guide ( - sort_order INTEGER PRIMARY KEY, - title TEXT NOT NULL, - link TEXT NOT NULL UNIQUE, - description TEXT NOT NULL -); - -INSERT INTO guide (sort_order, title, link, description) VALUES - (1, 'Your first website', '/your-first-sql-website/', 'Install SQLPage and build a website from a SQL file.'), - (2, 'SQL and variables', '/extensions-to-sql.sql', 'Read request parameters, set variables, and call SQLPage functions.'), - (3, 'Custom components', '/custom_components.sql', 'Render your own HTML with Handlebars templates.'), - (4, 'Database migrations', '/your-first-sql-website/migrations.sql', 'Create and update your database schema with versioned SQL files.'), - (5, 'Custom URLs', '/your-first-sql-website/custom_urls.sql', 'Give your pages readable URLs and route requests to SQL files.'), - (6, 'Reverse proxy', '/your-first-sql-website/nginx.sql', 'Serve your site with Nginx and HTTPS.'), - (7, 'Managed hosting', '/your-first-sql-website/hosted.sql', 'Try SQLPage online or publish your website with DataPage.'); diff --git a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql b/examples/official-site/sqlpage/migrations/82_reference_catalog.sql deleted file mode 100644 index 3f5be829d..000000000 --- a/examples/official-site/sqlpage/migrations/82_reference_catalog.sql +++ /dev/null @@ -1,184 +0,0 @@ --- Short catalog descriptions help readers choose a page before opening its full reference. -CREATE TABLE reference_category ( - id TEXT PRIMARY KEY, - title TEXT NOT NULL, - sort_order INTEGER NOT NULL -); - -INSERT INTO reference_category (id, title, sort_order) VALUES - ('display-data', 'Display data', 1), - ('forms-and-feedback', 'Forms and feedback', 2), - ('navigation', 'Navigation', 3), - ('page-layout', 'Page layout and content', 4), - ('http-responses', 'HTTP responses', 5), - ('server-logic', 'Server logic', 6), - ('request-data', 'Request data', 1), - ('links-and-routing', 'Links and routing', 2), - ('files-and-uploads', 'Files and uploads', 3), - ('identity-and-security', 'Identity and security', 4), - ('external-services', 'External services', 5), - ('server-and-runtime', 'Server and runtime', 6); - -ALTER TABLE component ADD COLUMN catalog_category TEXT REFERENCES reference_category(id); -ALTER TABLE component ADD COLUMN catalog_summary TEXT; -ALTER TABLE sqlpage_functions ADD COLUMN catalog_category TEXT REFERENCES reference_category(id); -ALTER TABLE sqlpage_functions ADD COLUMN catalog_summary TEXT; -ALTER TABLE sqlpage_function_parameters ADD COLUMN optional BOOLEAN NOT NULL DEFAULT FALSE; - -UPDATE sqlpage_function_parameters SET optional = TRUE WHERE ("function", name) IN ( - ('exec', 'arguments...'), - ('hmac', 'algorithm'), - ('link', 'parameters'), ('link', 'fragment'), - ('oidc_logout_url', 'redirect_uri'), - ('persist_uploaded_file', 'destination_folder'), ('persist_uploaded_file', 'allowed_extensions'), ('persist_uploaded_file', 'mode'), - ('persist_uploaded_files', 'destination_folder'), ('persist_uploaded_files', 'allowed_extensions'), ('persist_uploaded_files', 'mode'), - ('run_sql', 'parameters'), - ('set_variable', 'value'), - ('variables', 'method') -); - -WITH copy(name, category, summary) AS (VALUES - ('big_number', 'display-data', 'Highlight a metric with a trend or progress indicator.'), - ('card', 'display-data', 'Arrange records in cards with images, links, or embedded content.'), - ('carousel', 'display-data', 'Show a slideshow of images with optional captions and controls.'), - ('chart', 'display-data', 'Plot query results as line, area, bar, or pie charts.'), - ('datagrid', 'display-data', 'Lay out labeled values in a compact grid.'), - ('list', 'display-data', 'Present rows as a vertical list with optional links and icons.'), - ('map', 'display-data', 'Plot locations and geographic shapes on an interactive map.'), - ('table', 'display-data', 'Turn query results into a sortable, searchable table.'), - ('timeline', 'display-data', 'Arrange events along a vertical timeline.'), - ('tracking', 'display-data', 'Show a sequence of activity or status changes as colored segments.'), - - ('alert', 'forms-and-feedback', 'Draw attention to a message with a color and an icon.'), - ('button', 'forms-and-feedback', 'Follow a link, download a file, or submit a form.'), - ('empty_state', 'forms-and-feedback', 'Explain an empty view and offer the reader a next step.'), - ('form', 'forms-and-feedback', 'Collect input with text fields, file uploads, and other controls.'), - ('login', 'forms-and-feedback', 'Display a sign-in form for a username and password.'), - ('modal', 'forms-and-feedback', 'Open a dialog over the page for details, forms, or media.'), - ('toast', 'forms-and-feedback', 'Show a brief notification above the page.'), - - ('breadcrumb', 'navigation', 'Link the current page to its parent pages.'), - ('facet', 'navigation', 'Let readers choose filters for a dataset.'), - ('pagination', 'navigation', 'Link to other pages of a query result.'), - ('status_bar', 'navigation', 'Show status messages and links in a horizontal bar.'), - ('steps', 'navigation', 'Mark progress through the stages of a task.'), - ('tab', 'navigation', 'Switch between related pages using labeled tabs.'), - - ('code', 'page-layout', 'Display source code with syntax highlighting.'), - ('columns', 'page-layout', 'Compare plans, features, or options in side-by-side cards.'), - ('divider', 'page-layout', 'Separate sections with a horizontal rule.'), - ('foldable', 'page-layout', 'Let readers expand individual sections to see their contents.'), - ('hero', 'page-layout', 'Introduce a page with a headline, media, and a call to action.'), - ('html', 'page-layout', 'Insert your own HTML markup into the page.'), - ('shell', 'page-layout', 'Set the page layout, navigation, branding, and footer.'), - ('text', 'page-layout', 'Write paragraphs using plain text or Markdown.'), - ('title', 'page-layout', 'Add a heading and choose its level.'), - - ('cookie', 'http-responses', 'Set a cookie in the visitor''s browser.'), - ('csv', 'http-responses', 'Export query rows as a downloadable CSV file.'), - ('download', 'http-responses', 'Send a file directly to the visitor.'), - ('http_header', 'http-responses', 'Set response headers for caching, content types, and more.'), - ('json', 'http-responses', 'Return query results as JSON for an API.'), - ('redirect', 'http-responses', 'Send the visitor to another URL.'), - ('rss', 'http-responses', 'Publish an RSS feed from query results.'), - ('status_code', 'http-responses', 'Set the HTTP status code returned by a page.'), - - ('authentication', 'server-logic', 'Restrict access by checking a password against a stored hash.'), - ('debug', 'server-logic', 'Inspect the values passed to a component as JSON.'), - ('dynamic', 'server-logic', 'Render SQLPage components described by JSON data.'), - ('log', 'server-logic', 'Write a message to the SQLPage server log.') -) -UPDATE component SET (catalog_category, catalog_summary) = (copy.category, copy.summary) -FROM copy WHERE component.name = copy.name; - -WITH copy(name, category, summary) AS (VALUES - ('client_ip', 'request-data', 'Get the IP address of the client making the request.'), - ('cookie', 'request-data', 'Read a named cookie from the incoming request.'), - ('header', 'request-data', 'Read the value of one HTTP request header.'), - ('headers', 'request-data', 'Read all HTTP request headers as a JSON object.'), - ('path', 'request-data', 'Get the URL path of the current request.'), - ('protocol', 'request-data', 'Identify whether the request used HTTP or HTTPS.'), - ('request_body', 'request-data', 'Read the raw request body as text.'), - ('request_body_base64', 'request-data', 'Read a binary request body as a Base64 string.'), - ('request_method', 'request-data', 'Get the HTTP method, such as GET or POST.'), - ('variables', 'request-data', 'Read request or page variables as a JSON object.'), - - ('link', 'links-and-routing', 'Build a page URL with optional query parameters and a fragment.'), - ('regex_match', 'links-and-routing', 'Match text against a regular expression and extract capture groups.'), - ('set_variable', 'links-and-routing', 'Build a link to this page with a query parameter changed or removed.'), - ('url_encode', 'links-and-routing', 'Encode text for use in a URL.'), - - ('persist_uploaded_file', 'files-and-uploads', 'Save an uploaded file and return its path.'), - ('persist_uploaded_files', 'files-and-uploads', 'Save multiple uploads from one field and return their file details.'), - ('read_file_as_data_url', 'files-and-uploads', 'Read a file as a data URL for embedding in a page.'), - ('read_file_as_text', 'files-and-uploads', 'Read the text of a UTF-8 file from the web root.'), - ('uploaded_file_mime_type', 'files-and-uploads', 'Read the media type supplied by the browser for an uploaded file.'), - ('uploaded_file_name', 'files-and-uploads', 'Read the original filename supplied by the browser.'), - ('uploaded_file_path', 'files-and-uploads', 'Get the temporary path of an uploaded file.'), - - ('basic_auth_password', 'identity-and-security', 'Read the password sent with HTTP Basic authentication.'), - ('basic_auth_username', 'identity-and-security', 'Read the username sent with HTTP Basic authentication.'), - ('hash_password', 'identity-and-security', 'Hash a password with Argon2id for storage.'), - ('hmac', 'identity-and-security', 'Sign data with a shared secret using HMAC.'), - ('oidc_logout_url', 'identity-and-security', 'Build a sign-out URL for an OpenID Connect session.'), - ('random_string', 'identity-and-security', 'Generate a cryptographically secure random string.'), - ('user_info', 'identity-and-security', 'Read a named claim for the signed-in user.'), - ('user_info_token', 'identity-and-security', 'Read all claims from the user''s OpenID Connect ID token.'), - - ('fetch', 'external-services', 'Send an HTTP request and read the response body.'), - ('fetch_with_meta', 'external-services', 'Send an HTTP request and read its status, headers, and body.'), - ('send_mail', 'external-services', 'Send email with optional attachments through an SMTP server.'), - - ('configuration_directory', 'server-and-runtime', 'Locate the directory for SQLPage configuration and templates.'), - ('current_working_directory', 'server-and-runtime', 'Get the working directory of the SQLPage server process.'), - ('environment_variable', 'server-and-runtime', 'Read a named environment variable from the server.'), - ('exec', 'server-and-runtime', 'Run a program on the server and capture its output.'), - ('run_sql', 'server-and-runtime', 'Run another SQLPage file and return its rows as JSON.'), - ('version', 'server-and-runtime', 'Read the version of SQLPage serving the page.'), - ('web_root', 'server-and-runtime', 'Locate the directory that holds the site''s public files.') -) -UPDATE sqlpage_functions SET (catalog_category, catalog_summary) = (copy.category, copy.summary) -FROM copy WHERE sqlpage_functions.name = copy.name; - --- The catalog, topic navigation, and reference pages use the same entries and links. -CREATE VIEW reference_entry AS -WITH entries AS ( - SELECT 'component' AS kind, name, icon, catalog_category, catalog_summary, - description AS description_md, introduced_in_version, NULL AS return_type, - '/component.sql?component=' || name AS link, - (SELECT count(*) FROM example WHERE example.component = component.name) AS example_count, - NULL AS arguments - FROM component - UNION ALL - SELECT 'function', name, icon, catalog_category, catalog_summary, - description_md, introduced_in_version, return_type, '/functions.sql?function=' || name, NULL, - coalesce((SELECT group_concat(CASE WHEN optional THEN '[' || name || ']' ELSE name END, ', ' ORDER BY "index") - FROM sqlpage_function_parameters WHERE "function" = f.name), '') - FROM sqlpage_functions AS f -) -SELECT kind, name, icon, link, description_md, introduced_in_version, return_type, example_count, arguments, - coalesce(category.id, 'other') AS category_id, - coalesce(category.title, 'Other') AS category_title, - coalesce(category.sort_order, 99) AS category_order, - coalesce(catalog_summary, substr(trim(description_md, char(10) || ' #'), 1, - instr(trim(description_md, char(10) || ' #') || char(10), char(10)) - 1)) AS summary -FROM entries -LEFT JOIN reference_category AS category ON category.id = entries.catalog_category; - --- The section is part of the anchor: a component can accept the same name at both levels. -CREATE VIEW reference_parameter AS -WITH fields AS ( - SELECT 'component' AS kind, component AS entry, - CASE WHEN top_level THEN 'top-level-parameters' ELSE 'row-level-parameters' END AS section, - name, type, optional, coalesce(description_md, description) AS description_md, optional AS position - FROM parameter - UNION ALL - SELECT 'function', "function", 'parameters', name, type, optional, description_md, "index" - FROM sqlpage_function_parameters -), sections(section, title, introduction, section_order) AS (VALUES - ('top-level-parameters', 'Top-level parameters', 'Set these in the SELECT that names the component.', 1), - ('row-level-parameters', 'Row-level parameters', 'Return these columns in the rows that follow the component.', 2), - ('parameters', 'Parameters', NULL, 1) -) -SELECT fields.*, title, introduction, section_order, section || '-' || name AS anchor -FROM fields JOIN sections USING (section); diff --git a/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql b/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql deleted file mode 100644 index 712cb683f..000000000 --- a/examples/official-site/sqlpage/migrations/99_shared_id_class_attributes.sql +++ /dev/null @@ -1,87 +0,0 @@ --- Every component whose `id` and `class` properties behave in the ordinary way --- is documented from the lists below, so that the wording stays identical --- across components and so that the (component, top_level, name) primary key --- of `parameter` is not violated. --- --- A handful of components deliberately document `id` or `class` in their own --- migration instead, because the generic wording would be wrong for them: --- `modal` (`id` is required, and is what a button targets), `form` (`id` is --- what an outside submit button references), `foldable` (top level and item --- level mean different things) and `button` (`id` lands on each button, not on --- the container). Do not duplicate those here. - -INSERT INTO parameter(component, top_level, name, description, type, optional) -SELECT *, 'id', 'id attribute added to the container in HTML. It can be used to target this item through css or for scrolling to this item through links (use "#id" in link url).', 'TEXT', TRUE -FROM (VALUES - ('alert', TRUE), - ('big_number', TRUE), - ('big_number', FALSE), - ('breadcrumb', TRUE), - ('card', FALSE), - ('chart', TRUE), - ('code', TRUE), - ('csv', TRUE), - ('datagrid', TRUE), - ('datagrid', FALSE), - ('empty_state', TRUE), - ('hero', TRUE), - ('list', TRUE), - ('list', FALSE), - ('map', TRUE), - ('status_bar', TRUE), - ('tab', TRUE), - ('tab', FALSE), - ('table', TRUE), - ('timeline', TRUE), - ('timeline', FALSE), - ('title', TRUE), - ('toast', TRUE), - ('tracking', TRUE), - ('text', TRUE), - ('carousel', TRUE), - ('login', TRUE), - ('pagination', TRUE), - ('facet', TRUE) -); - -INSERT INTO parameter(component, top_level, name, description, type, optional) -SELECT *, 'id', 'id attribute injected as an anchor in HTML. It can be used for scrolling to this item through links (use "#id" in link url). Added in v0.18.0.', 'TEXT', TRUE -FROM (VALUES - ('steps', TRUE) -); - -INSERT INTO parameter(component, top_level, name, description, type, optional) -SELECT *, 'class', 'class attribute added to the container in HTML. It can be used to apply custom styling to this item through css. Added in v0.18.0.', 'TEXT', TRUE -FROM (VALUES - ('alert', TRUE), - ('big_number', TRUE), - ('big_number', FALSE), - ('breadcrumb', TRUE), - ('button', TRUE), - ('card', TRUE), - ('card', FALSE), - ('chart', TRUE), - ('code', TRUE), - ('csv', TRUE), - ('datagrid', TRUE), - ('divider', TRUE), - ('empty_state', TRUE), - ('form', TRUE), - ('list', TRUE), - ('list', FALSE), - ('map', TRUE), - ('status_bar', TRUE), - ('status_bar', FALSE), - ('tab', TRUE), - ('tab', FALSE), - ('table', TRUE), - ('timeline', TRUE), - ('timeline', FALSE), - ('title', TRUE), - ('toast', TRUE), - ('tracking', TRUE), - ('carousel', TRUE), - ('login', TRUE), - ('pagination', TRUE), - ('facet', TRUE) -); diff --git a/examples/official-site/sqlpage/templates/docs-parameters.handlebars b/examples/official-site/sqlpage/templates/docs-parameters.handlebars index 4642c7f1f..bf5c9f0c2 100644 --- a/examples/official-site/sqlpage/templates/docs-parameters.handlebars +++ b/examples/official-site/sqlpage/templates/docs-parameters.handlebars @@ -14,7 +14,7 @@ {{#if required}}Required{{/if}} -
{{{markdown description_md}}}
+
{{{markdown description_md}}}{{#if default_md}}

Default

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