Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ include = [
[[example]]
name = "build-site"
path = "scripts/official-site/main.rs"
required-features = ["config-schema"]

[lints.rust]
elided_lifetimes_in_paths = "deny"
Expand Down Expand Up @@ -65,6 +66,7 @@ futures-util = "0.3.21"
tokio = { version = "1.24.1", features = ["macros", "rt", "process", "sync"] }
tokio-stream = "0.1.9"
anyhow = "1"
schemars = { version = "1", optional = true }
serde = "1"
serde_json = { version = "1.0.82", features = [
"preserve_order",
Expand Down Expand Up @@ -140,6 +142,7 @@ opentelemetry-semantic-conventions = { version = "0.33", features = ["semconv_ex


[features]
config-schema = ["dep:schemars"]
default = []
odbc-static = ["odbc-sys", "odbc-sys/vendored-unix-odbc"]
lambda-web = [
Expand Down
49 changes: 2 additions & 47 deletions configuration.md

Large diffs are not rendered by default.

19 changes: 19 additions & 0 deletions examples/official-site/configuration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
select 'dynamic' as component, sqlpage.run_sql('sqlpage/docs-shell.sql', json_object(
'title', 'Configuration | SQLPage',
'section', 'Documentation',
'current', 'Configuration',
'outline', '[{"title":"Options","link":"#options"}]'
)) as properties;

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, optionally prefixed with `SQLPAGE_`. 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', '**Default:** ' || coalesce(default_md, 'Unset')
) order by name) as parameters from config_option;
5 changes: 4 additions & 1 deletion examples/official-site/documentation.sql
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ select case kind when 'component' then 'Components' else 'Functions' end as titl
(kind = 'component' and name in ('form', 'table', 'map', 'chart', 'button')) or
(kind = 'function' and name in ('fetch', 'link', 'run_sql', 'variables'))
) as links
from reference_entry group by kind order by kind;
from reference_entry group by kind
union all
select 'Configuration', 'settings', '/configuration', 'Look up server settings, accepted values, and defaults.', null
order by title;

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;
Expand Down
2 changes: 1 addition & 1 deletion examples/official-site/llms.txt.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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): Server settings, accepted values, and defaults

## Components

Expand Down
4 changes: 4 additions & 0 deletions examples/official-site/reference/search-index.sql
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ 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 || ' (SQLPAGE_' || upper(name) || ')', description_md, '/configuration', name
FROM config_option;
10 changes: 9 additions & 1 deletion examples/official-site/search.sql
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ 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) or 'sqlpage_' || name = lower($search)
limit 1;

select 'shell-docs' as component, 'Search' as section,
coalesce($search || ' | ', '') || 'SQLPage documentation search' as title;

Expand All @@ -17,7 +22,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
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
{{#if required}}<strong class="ms-2 text-primary">Required</strong>{{/if}}
</small>
</dt>
<dd class="col-sm mb-0 text-break remove-bottom-margin">{{{markdown description_md}}}</dd>
<dd class="col-sm mb-0 text-break remove-bottom-margin">
{{{markdown description_md}}}
{{#if default_md}}<div class="mt-2 text-secondary remove-bottom-margin">{{{markdown default_md}}}</div>{{/if}}
</dd>
</div>
{{/each}}
</dl>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
<a href="/blog.sql">Blog</a>
<a href="/performance.sql">Performance</a>
<a href="/safety.sql">Security</a>
<a href="https://github.com/sqlpage/SQLPage/blob/main/configuration.md">Configuration</a>
<a href="/configuration">Configuration</a>
<a href="https://github.com/sqlpage/SQLPage/discussions">Community</a>
</nav>
<a href="#sqlpage_main_wrapper">{{icon_img "arrow-up" 16}} Back to top</a>
Expand Down
28 changes: 28 additions & 0 deletions examples/official-site/test.hurl
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,34 @@ 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/search.sql?search=web_root
HTTP 302
[Asserts]
header "Location" == "/functions.sql?function=web_root"

GET http://localhost:8080/search.sql?search=SQLPAGE_WEB_ROOT
HTTP 302
[Asserts]
header "Location" == "/configuration#web_root"

GET http://localhost:8080/search.sql?search=SMTP
HTTP 200
[Asserts]
xpath "//main//a[starts-with(@href, '/configuration#smtp_')]" count > 1

GET http://localhost:8080/components.sql
HTTP 200
[Asserts]
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +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": "cargo run --locked --example build-site",
"site:test": "cargo test --locked --example build-site",
"site:build": "cargo run --locked --features config-schema --example build-site",
"site:test": "cargo test --locked --features config-schema --example build-site",
"site": "npm run build && npm run site:build && cd target/official-site && cargo run --locked --manifest-path ../../Cargo.toml"
},
"repository": {
Expand Down
98 changes: 98 additions & 0 deletions scripts/official-site/configuration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
use anyhow::{Context, Result};
use schemars::generate::SchemaSettings;
use serde_json::Value;
use sqlpage::app_config::AppConfig;
use sqlx::executor::Executor;
use sqlx::query::query;
use sqlx::sqlite::SqliteConnection;

pub(super) async fn insert(db: &mut SqliteConnection) -> Result<()> {
db.execute(
"CREATE TABLE config_option (
name TEXT PRIMARY KEY,
type TEXT NOT NULL,
default_md TEXT,
description_md TEXT NOT NULL
) STRICT",
)
.await?;
let schema = SchemaSettings::draft2020_12()
.with(|settings| settings.inline_subschemas = true)
.into_generator()
.into_root_schema_for::<AppConfig>();
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}")
})
});
query(
"INSERT INTO config_option (name, type, default_md, description_md) VALUES (?, ?, ?, ?)",
)
.bind(name)
.bind(kind)
.bind(default)
.bind(description)
.execute(&mut *db)
.await
.with_context(|| format!("Storing configuration option {name}"))?;
}
Ok(())
}

fn schema_type(schema: &Value) -> Result<String> {
if let Some(values) = schema["enum"].as_array() {
return Ok(values
.iter()
.map(Value::to_string)
.collect::<Vec<_>>()
.join(" | "));
}
if let Some(types) = schema["anyOf"].as_array() {
return Ok(types
.iter()
.map(schema_type)
.collect::<Result<Vec<_>>>()?
.join(" or "));
}
if let Some(types) = schema["type"].as_array() {
return Ok(types
.iter()
.map(|kind| format_type(schema, kind))
.collect::<Result<Vec<_>>>()?
.join(" or "));
}
format_type(schema, &schema["type"])
}

fn format_type(schema: &Value, kind: &Value) -> Result<String> {
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(),
})
}

#[cfg(test)]
mod tests;
Loading
Loading