Skip to content

Commit f6ef890

Browse files
committed
Start the documentation site from one validated seed
1 parent a5fa7f0 commit f6ef890

20 files changed

Lines changed: 279 additions & 223 deletions

‎AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@ relevant tests and the formatting/lint checks in CONTRIBUTING.md before stopping
3838
Report unavailable checks and failures accurately; a test summary followed by a
3939
hung process is a failure.
4040

41-
Update the existing page or documentation migration for changed behavior. Add a
42-
migration only for new documentation content.
41+
Update the existing documentation page or its authored source under
42+
`examples/official-site/content/` for changed behavior.
4343

4444
Build and preview the official site with the commands in its [README](./examples/official-site/README.md).
4545
Document server settings on `AppConfig`, where the site build reads them.

‎CONTRIBUTING.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,8 @@ Architectural constraints and documentation maintenance rules are in
111111
[AGENTS.md](./AGENTS.md).
112112

113113
Edit existing documentation in the [official site](./examples/official-site/) in place.
114-
Deployment recreates the website's database from the site's SQL migrations.
114+
Deployment recreates the website's database from the generated documentation
115+
seed and the site's checked-in migrations.
115116

116117
Run `npm run site` to preview changes using the same site build as deployment.
117118

‎examples/build_site/blog.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,9 @@ mod tests {
5353
)?;
5454
let schema = "CREATE TABLE blog_posts (title PRIMARY KEY, created_at, icon, description, external_url, content);";
5555
let mut seed = Seed::new()?;
56-
seed.execute(schema)?;
56+
seed.script(schema)?;
5757
insert(&mut seed, dir.path())?;
5858
let db = Connection::open_in_memory()?;
59-
db.execute_batch(schema)?;
6059
db.execute_batch(&seed.finish())?;
6160
let post: (String, String) =
6261
db.query_row("SELECT title, content FROM blog_posts", [], |row| {

‎examples/build_site/components.rs‎

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use super::{
22
Seed,
33
content::{Parameter, at, pages},
44
};
5-
use anyhow::{Context, Result};
5+
use anyhow::{Context, Result, ensure};
66
use serde::Deserialize;
77
use serde_json::Value;
88
use std::{collections::BTreeMap, fs, path::Path};
@@ -45,6 +45,19 @@ pub(super) fn insert(seed: &mut Seed, content: &Path) -> Result<()> {
4545
Ok(entries)
4646
})?;
4747
let dir = content.join("components");
48+
for entry in fs::read_dir(&dir)? {
49+
let entry = entry?;
50+
if entry.file_type()?.is_dir() {
51+
let mut reference = entry.file_name();
52+
reference.push(".md");
53+
ensure!(
54+
dir.join(&reference).is_file(),
55+
"{} has no corresponding reference {}",
56+
entry.path().display(),
57+
reference.to_string_lossy()
58+
);
59+
}
60+
}
4861
pages(&dir, |name, c: Component, body| {
4962
seed.row(
5063
"INSERT INTO component (name, description, icon, introduced_in_version, catalog_category, catalog_summary)
@@ -67,22 +80,12 @@ pub(super) fn insert(seed: &mut Seed, content: &Path) -> Result<()> {
6780
)?;
6881
}
6982
}
70-
Ok(())
71-
})?;
72-
73-
// Some examples move before their component reference. That reference
74-
// still comes from a checked-in migration in that case.
75-
let mut dirs = fs::read_dir(&dir)?.collect::<std::io::Result<Vec<_>>>()?;
76-
dirs.sort_by_key(fs::DirEntry::file_name);
77-
for entry in dirs {
78-
let examples = entry.path().join("examples");
79-
if entry.file_type()?.is_dir() && examples.try_exists()? {
80-
let name = entry.file_name();
81-
let component = name.to_str().context("Invalid component directory name")?;
82-
insert_examples(seed, component, &examples)?;
83+
let examples = dir.join(name).join("examples");
84+
if examples.try_exists()? {
85+
insert_examples(seed, name, &examples)?;
8386
}
84-
}
85-
Ok(())
87+
Ok(())
88+
})
8689
}
8790

8891
fn insert_examples(seed: &mut Seed, component: &str, dir: &Path) -> Result<()> {
@@ -113,10 +116,9 @@ mod tests {
113116
fs::write(examples.path().join("01-notes.md"), "Just a note.\n")?;
114117
let schema = "CREATE TABLE example (component, description, properties);";
115118
let mut seed = Seed::new()?;
116-
seed.execute(schema)?;
119+
seed.script(schema)?;
117120
insert_examples(&mut seed, "text", examples.path())?;
118121
let db = Connection::open_in_memory()?;
119-
db.execute_batch(schema)?;
120122
db.execute_batch(&seed.finish())?;
121123
let rows = db
122124
.prepare("SELECT description, properties FROM example ORDER BY rowid")?

‎examples/build_site/configuration.rs‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,6 @@ use serde_json::Value;
55
use sqlpage::app_config::AppConfig;
66

77
pub(super) fn insert(seed: &mut Seed) -> Result<()> {
8-
seed.script(
9-
"CREATE TABLE config_option (
10-
name TEXT PRIMARY KEY,
11-
type TEXT NOT NULL,
12-
default_md TEXT,
13-
description_md TEXT NOT NULL
14-
);",
15-
)?;
168
let schema = SchemaSettings::draft2020_12()
179
.with(|settings| settings.inline_subschemas = true)
1810
.into_generator()

‎examples/build_site/directories.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,14 @@ use anyhow::Result;
33
use serde::Deserialize;
44
use std::path::Path;
55

6+
#[derive(Deserialize)]
7+
#[serde(deny_unknown_fields)]
8+
struct Category {
9+
id: String,
10+
title: String,
11+
sort_order: i64,
12+
}
13+
614
#[derive(Deserialize)]
715
#[serde(deny_unknown_fields)]
816
struct Guide {
@@ -22,6 +30,12 @@ struct Project {
2230
}
2331

2432
pub(super) fn insert(seed: &mut Seed, dir: &Path) -> Result<()> {
33+
collection(dir, "categories.yaml", |c: Category| {
34+
seed.row(
35+
"INSERT INTO reference_category (id, title, sort_order) VALUES (?, ?, ?)",
36+
&[&c.id, &c.title, &c.sort_order],
37+
)
38+
})?;
2539
collection(dir, "guides.yaml", |g: Guide| {
2640
seed.row(
2741
"INSERT INTO guide (title, link, description, sort_order) VALUES (?, ?, ?, ?)",

‎examples/build_site/main.rs‎

Lines changed: 42 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,16 @@ mod directories;
66
mod functions;
77
mod seed;
88

9-
use anyhow::{Context, Result, bail, ensure};
9+
use anyhow::{Context, Result, bail};
1010
use seed::Seed;
11-
use sqlx::migrate::Migrator;
1211
use std::{fs, path::Path};
1312

14-
const CONTENT_VERSION: i64 = 100;
15-
const SEED_FILE: &str = "sqlpage/migrations/100_documentation_content.sql";
13+
const SEED_FILE: &str = "sqlpage/migrations/01_documentation.sql";
1614

17-
#[tokio::main(flavor = "current_thread")]
18-
async fn main() -> Result<()> {
15+
fn main() -> Result<()> {
1916
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
2017
let source = root.join("examples/official-site");
21-
let seed = documentation_seed(&source).await?;
18+
let seed = documentation_seed(&source.join("content"))?;
2219

2320
let parent = root.join("target");
2421
fs::create_dir_all(&parent)?;
@@ -76,27 +73,45 @@ fn copy_site(source: &Path, target: &Path, relative: &Path) -> Result<()> {
7673
Ok(())
7774
}
7875

79-
async fn documentation_seed(site: &Path) -> Result<String> {
76+
fn documentation_seed(content: &Path) -> Result<String> {
8077
let mut seed = Seed::new()?;
81-
let migrations = Migrator::new(site.join("sqlpage/migrations")).await?;
82-
for migration in migrations
83-
.iter()
84-
.filter(|m| !m.migration_type.is_down_migration())
85-
{
86-
ensure!(
87-
migration.version != CONTENT_VERSION,
88-
"Migration {CONTENT_VERSION} is generated"
89-
);
90-
if migration.version < CONTENT_VERSION {
91-
seed.execute(&migration.sql).with_context(|| {
92-
format!("Migration {} {}", migration.version, migration.description)
93-
})?;
94-
}
95-
}
96-
blog::insert(&mut seed, &site.join("content/blog"))?;
97-
components::insert(&mut seed, &site.join("content"))?;
78+
seed.script(include_str!("schema.sql"))?;
79+
directories::insert(&mut seed, content)?;
80+
blog::insert(&mut seed, &content.join("blog"))?;
81+
components::insert(&mut seed, content)?;
9882
configuration::insert(&mut seed)?;
99-
directories::insert(&mut seed, &site.join("content"))?;
100-
functions::insert(&mut seed, &site.join("content/functions"))?;
83+
functions::insert(&mut seed, &content.join("functions"))?;
84+
seed.script(include_str!("search.sql"))?;
10185
Ok(seed.finish())
10286
}
87+
88+
#[cfg(test)]
89+
mod tests {
90+
use super::*;
91+
use rusqlite::Connection;
92+
93+
#[test]
94+
fn the_seed_replays_and_indexes_the_prepared_reference() -> Result<()> {
95+
let content = Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/official-site/content");
96+
let seed = documentation_seed(&content)?;
97+
assert_eq!(seed, documentation_seed(&content)?);
98+
99+
let db = Connection::open_in_memory()?;
100+
db.pragma_update(None, "foreign_keys", true)?;
101+
db.execute_batch(&seed)?;
102+
let link: String = db.query_row(
103+
"SELECT page || '#' || fragment FROM documentation_fts
104+
WHERE documentation_fts MATCH 'listen_on' AND fragment = 'listen_on'",
105+
[],
106+
|row| row.get(0),
107+
)?;
108+
assert_eq!(link, "/configuration#listen_on");
109+
let source: String = db.query_row(
110+
"SELECT source FROM example_with_source WHERE component = 'table' AND example_number = 4",
111+
[],
112+
|row| row.get(0),
113+
)?;
114+
assert!(source.contains("'Chart' as \"embed\""), "{source}");
115+
Ok(())
116+
}
117+
}

‎examples/build_site/schema.sql‎

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
CREATE TABLE reference_category (
2+
id TEXT PRIMARY KEY,
3+
title TEXT NOT NULL,
4+
sort_order INTEGER NOT NULL
5+
);
6+
7+
CREATE TABLE config_option (
8+
name TEXT PRIMARY KEY,
9+
type TEXT NOT NULL,
10+
default_md TEXT,
11+
description_md TEXT NOT NULL
12+
);
13+
14+
CREATE TABLE component (
15+
name TEXT PRIMARY KEY,
16+
description TEXT NOT NULL,
17+
icon TEXT,
18+
introduced_in_version TEXT,
19+
catalog_category TEXT REFERENCES reference_category(id),
20+
catalog_summary TEXT
21+
);
22+
23+
CREATE TABLE parameter_type (name TEXT PRIMARY KEY);
24+
INSERT INTO parameter_type VALUES
25+
('BOOLEAN'), ('COLOR'), ('HTML'), ('ICON'), ('INTEGER'), ('JSON'), ('REAL'), ('TEXT'), ('TIMESTAMP'), ('URL');
26+
27+
CREATE TABLE parameter (
28+
component TEXT NOT NULL REFERENCES component(name),
29+
top_level BOOLEAN NOT NULL,
30+
name TEXT NOT NULL,
31+
type TEXT NOT NULL REFERENCES parameter_type(name),
32+
description_md TEXT NOT NULL,
33+
optional BOOLEAN NOT NULL,
34+
PRIMARY KEY (component, top_level, name)
35+
);
36+
37+
CREATE TABLE example (
38+
component TEXT NOT NULL REFERENCES component(name),
39+
description TEXT NOT NULL,
40+
properties JSON
41+
);
42+
43+
CREATE TABLE sqlpage_functions (
44+
name TEXT PRIMARY KEY,
45+
icon TEXT,
46+
description_md TEXT NOT NULL,
47+
return_type TEXT,
48+
introduced_in_version TEXT,
49+
catalog_category TEXT REFERENCES reference_category(id),
50+
catalog_summary TEXT
51+
);
52+
53+
CREATE TABLE sqlpage_function_parameters (
54+
"function" TEXT NOT NULL REFERENCES sqlpage_functions(name),
55+
"index" INTEGER NOT NULL,
56+
name TEXT NOT NULL,
57+
description_md TEXT NOT NULL,
58+
type TEXT NOT NULL,
59+
optional BOOLEAN NOT NULL,
60+
PRIMARY KEY ("function", "index"),
61+
UNIQUE ("function", name)
62+
);
63+
64+
CREATE TABLE blog_posts (
65+
title TEXT PRIMARY KEY,
66+
description TEXT NOT NULL,
67+
icon TEXT NOT NULL,
68+
external_url TEXT,
69+
content TEXT,
70+
created_at TEXT NOT NULL
71+
);
72+
73+
CREATE TABLE guide (
74+
sort_order INTEGER PRIMARY KEY,
75+
title TEXT NOT NULL,
76+
link TEXT NOT NULL UNIQUE,
77+
description TEXT NOT NULL
78+
);
79+
80+
CREATE TABLE example_cards (
81+
title TEXT NOT NULL,
82+
folder TEXT NOT NULL,
83+
db_engine TEXT,
84+
description TEXT NOT NULL
85+
);
86+
87+
-- The reference shows the SQL and renders the same stored component rows.
88+
-- Arrays with several items become repeated column aliases, as in handwritten SQLPage files.
89+
CREATE VIEW example_with_source AS
90+
SELECT example.rowid AS example_id,
91+
row_number() OVER (PARTITION BY component ORDER BY example.rowid) AS example_number,
92+
example.*,
93+
(SELECT group_concat('select' || char(10) || (
94+
WITH fields AS (
95+
SELECT field.key AS name, coalesce(item.type, field.type) AS type,
96+
CASE WHEN item.key IS NULL THEN field.value ELSE item.value END AS value
97+
FROM json_each(statement.value) AS field
98+
LEFT JOIN json_each(
99+
CASE WHEN field.type = 'array' AND json_array_length(field.value) > 1 THEN field.value END
100+
) AS item ON true
101+
)
102+
SELECT group_concat(' ' || CASE type
103+
WHEN 'true' THEN 'TRUE'
104+
WHEN 'false' THEN 'FALSE'
105+
WHEN 'array' THEN 'JSON(' || quote(value) || ')'
106+
WHEN 'object' THEN 'JSON(' || quote(value) || ')'
107+
ELSE quote(value)
108+
END || format(' as "%w"', name), ',' || char(10))
109+
FROM fields
110+
) || ';', char(10) || char(10)) FROM json_each(example.properties) AS statement) AS source
111+
FROM example;
112+
113+
-- The catalog, topic navigation, and reference pages use the same entries and links.
114+
CREATE VIEW reference_entry AS
115+
WITH entries AS (
116+
SELECT 'component' AS kind, name, icon, catalog_category, catalog_summary,
117+
description AS description_md, introduced_in_version, NULL AS return_type,
118+
'/component.sql?component=' || name AS link,
119+
(SELECT count(*) FROM example WHERE example.component = component.name) AS example_count,
120+
NULL AS arguments
121+
FROM component
122+
UNION ALL
123+
SELECT 'function', name, icon, catalog_category, catalog_summary,
124+
description_md, introduced_in_version, return_type, '/functions.sql?function=' || name, NULL,
125+
coalesce((SELECT group_concat(CASE WHEN optional THEN '[' || name || ']' ELSE name END, ', ' ORDER BY "index")
126+
FROM sqlpage_function_parameters WHERE "function" = f.name), '')
127+
FROM sqlpage_functions AS f
128+
)
129+
SELECT kind, name, icon, link, description_md, introduced_in_version, return_type, example_count, arguments,
130+
coalesce(category.id, 'other') AS category_id,
131+
coalesce(category.title, 'Other') AS category_title,
132+
coalesce(category.sort_order, 99) AS category_order,
133+
coalesce(catalog_summary, substr(trim(description_md, char(10) || ' #'), 1,
134+
instr(trim(description_md, char(10) || ' #') || char(10), char(10)) - 1)) AS summary
135+
FROM entries
136+
LEFT JOIN reference_category AS category ON category.id = entries.catalog_category;
137+
138+
-- The section is part of the anchor: a component can accept the same name at both levels.
139+
CREATE VIEW reference_parameter AS
140+
WITH fields AS (
141+
SELECT 'component' AS kind, component AS entry,
142+
CASE WHEN top_level THEN 'top-level-parameters' ELSE 'row-level-parameters' END AS section,
143+
name, type, optional, description_md, optional AS position
144+
FROM parameter
145+
UNION ALL
146+
SELECT 'function', "function", 'parameters', name, type, optional, description_md, "index"
147+
FROM sqlpage_function_parameters
148+
), sections(section, title, introduction, section_order) AS (VALUES
149+
('top-level-parameters', 'Top-level parameters', 'Set these in the SELECT that names the component.', 1),
150+
('row-level-parameters', 'Row-level parameters', 'Return these columns in the rows that follow the component.', 2),
151+
('parameters', 'Parameters', NULL, 1)
152+
)
153+
SELECT fields.*, title, introduction, section_order, section || '-' || name AS anchor
154+
FROM fields JOIN sections USING (section);

examples/official-site/sqlpage/migrations/999_fts_search_index.sql renamed to examples/build_site/search.sql

File renamed without changes.

0 commit comments

Comments
 (0)