diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 496277efa..4c18cf074 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,6 +63,7 @@ jobs: shared-key: rust-sqlpage-proj-test save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo fmt --all -- --check + - run: cargo test --locked --features config-schema --test mod configuration_docs - run: cargo clippy --all-targets --all-features -- -D warnings # The database matrix below runs the same Rust test harnesses against # different DATABASE_URL values. Package the Linux test executables once diff --git a/Cargo.lock b/Cargo.lock index 565cc9428..15c5167d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4210,10 +4210,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 +4328,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" @@ -4630,6 +4654,7 @@ dependencies = [ "rustls", "rustls-acme", "rustls-native-certs", + "schemars 1.2.3", "serde", "serde_json", "sha2 0.11.1", diff --git a/Cargo.toml b/Cargo.toml index d5c3b4fa8..94a2789cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,7 @@ tokio = { version = "1.24.1", features = ["macros", "rt", "process", "sync"] } tokio-stream = "0.1.9" anyhow = "1" serde = "1" +schemars = { version = "1", optional = true } serde_json = { version = "1.0.82", features = [ "preserve_order", "raw_value", @@ -137,6 +138,7 @@ opentelemetry-semantic-conventions = { version = "0.33", features = ["semconv_ex [features] default = [] +config-schema = ["dep:schemars"] odbc-static = ["odbc-sys", "odbc-sys/vendored-unix-odbc"] lambda-web = [ "dep:actix-http", @@ -151,3 +153,7 @@ actix-http = "3" tempfile = "3" tokio = { version = "1", features = ["rt", "time", "test-util"] } +[[example]] +name = "export_config_schema" +required-features = ["config-schema"] + diff --git a/examples/export_config_schema.rs b/examples/export_config_schema.rs new file mode 100644 index 000000000..3101475b3 --- /dev/null +++ b/examples/export_config_schema.rs @@ -0,0 +1,15 @@ +use schemars::generate::SchemaSettings; +use sqlpage::app_config::AppConfig; +use std::io::{self, Write}; + +fn main() -> anyhow::Result<()> { + let settings = + SchemaSettings::draft2020_12().with(|settings| settings.inline_subschemas = true); + let schema = settings + .into_generator() + .into_root_schema_for::(); + let mut stdout = io::stdout().lock(); + serde_json::to_writer_pretty(&mut stdout, &schema)?; + writeln!(stdout)?; + Ok(()) +} 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/content/blog/come-and-see-us-in-athens.md b/examples/official-site/content/blog/come-and-see-us-in-athens.md new file mode 100644 index 000000000..a74383aa3 --- /dev/null +++ b/examples/official-site/content/blog/come-and-see-us-in-athens.md @@ -0,0 +1,25 @@ +--- +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 ! +--- + +# PostgreSQL & SQLPage at PGConf 2024 + +We have been invited to give a talk at PGConf 2024 in Athens, Greece. + +Last year, we gave a general introduction to SQLPage at PGConf.eu 2023 in Prague. + +This year, we will focus on a more specific use case: +using SQLPage to build a power-tool for archaeologists to explore and understand archaeological sites, +radically changing the way archaeologists work, and allowing them to +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. + +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/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md b/examples/official-site/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md new file mode 100644 index 000000000..81b8eed4f --- /dev/null +++ b/examples/official-site/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md @@ -0,0 +1,27 @@ +--- +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 ! + +If some of you european SQLPagers are around Prague this december, +I will be giving a talk about SQLPage at [pgconf.eu](https://2023.pgconf.eu/) on December 14th. + +I will be talking about website building in general, SQLPage in particular, +cool things you can do with it, +how it works, how and why I built it, +and why I still think it can cut web development and prototyping times by a factor of 10. + +I will also be building a tiny social network live on stage, using SQLPage. + +Come see me ! + + - [pgconf.eu](https://2023.pgconf.eu/) + - [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) diff --git a/examples/official-site/content/blog/file-based-routing-in-sqlpage.md b/examples/official-site/content/blog/file-based-routing-in-sqlpage.md new file mode 100644 index 000000000..d1bc0c417 --- /dev/null +++ b/examples/official-site/content/blog/file-based-routing-in-sqlpage.md @@ -0,0 +1,61 @@ +--- +title: File-based routing in SQLPage +date: '2025-07-28' +icon: route +summary: Understanding how SQLPage maps URLs to files and handles errors +--- + +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. + +This guide explains how SQLPage resolves URLs, handles different file types, and manages 404 errors so you can structure your application effectively. + +## Request routing order + +### 1. Site Prefix Handling + +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 + +**Directory requests (paths ending with `/`)**: SQLPage looks for an `index.sql` file in that directory and executes it if found. + +**Direct SQL file requests (`.sql` extension)**: SQLPage executes the requested SQL file if it exists. The extension is matched without regard to ASCII letter case, so `/report.SQL` is also executed. It is never served as source text. + +**Static asset requests (other extensions)**: SQLPage serves files like CSS, JavaScript, images, or any other static content directly. + +**Clean URL requests (no extension)**: SQLPage first tries to find a matching `.sql` file. If that doesn't exist but there's an `index.sql` file in a directory with the same name, it redirects to the directory path with a trailing slash. + +Paths with trailing spaces are rejected. On Windows, paths with trailing dots or NTFS stream names are rejected too. These spellings can refer to a different file than their URL suggests on some storage systems. + +### Error Handling + +When, after applying each of the rules above in order, SQLPage can't find a requested file, +it walks up your directory structure looking for [custom `404.sql` files](/your-first-sql-website/custom_urls). + +## Dynamic Routing with SQLPage + +SQLPage's file-based routing becomes powerful when combined with strategic use of 404.sql files to handle dynamic URLs. Here's how to build APIs and pages with dynamic parameters: + +### Product Catalog with Dynamic IDs + +**Goal**: Handle URLs like `/products/123`, `/products/abc`, `/products/new-laptop` + +**Setup**: +```text +products/ +├── index.sql # Lists all products (/products/) +├── 404.sql # Handles /products/ +└── categories.sql # Product categories (/products/categories) +``` + +**Request paths** +- `/products/` → Executes `products/index.sql` (product listing) +- `/products/123` → No `123.sql` file exists, so executes `products/404.sql` +- `/products/laptop` → No `laptop.sql` file exists, so executes `products/404.sql` + +**In `products/404.sql`**: +```sql +set product_id = substr(sqlpage.path(), 1+length('/products/')); +``` diff --git a/examples/official-site/content/blog/how-archaeology-is-gradually-entering-the-era-of-free-software.md b/examples/official-site/content/blog/how-archaeology-is-gradually-entering-the-era-of-free-software.md new file mode 100644 index 000000000..9fe5ddc89 --- /dev/null +++ b/examples/official-site/content/blog/how-archaeology-is-gradually-entering-the-era-of-free-software.md @@ -0,0 +1,182 @@ +--- +title: How archaeology is gradually entering the era of free software +date: '2024-07-02' +icon: skull +summary: A team of french archaeologists is working on the first all-digital excavation site, using SQLPage +--- + +> 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 + +# How archaeology is gradually entering the era of free software + +Archaeology has, since its beginnings, focused on cataloging, structuring and archiving data from excavations. In the field, it has long relied on creating forms, manually collecting information on paper, and hand drawing, transcribed during study phases onto digital media. It is only recently that some archaeologists have launched the movement of "all-digital" excavation. I propose to tell here the story of the digitization of archaeology, which, as you will see, relies in part on free software. + + +## Archaeological excavation in France + +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. + +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. + +![mastraits site](https://github.com/sqlpage/SQLPage/assets/552629/3dbdf81e-b9d3-4268-a8e3-99e568feb695) + +*The excavation site of the Necropolis of Mastraits, in Noisy-le-Grand (93).* + +The actions carried out by the archaeologist throughout the site are also recorded. Indeed, the archaeologist carries out surveys, digs trenches, but also takes many photos, or drawings of everything he discovers as the site progresses. The documentation produced can be plethoric, and cataloging is essential. + +This descriptive information is complemented by **spatial information**, the plan of the uncovered remains being essential for the analysis and presentation of results. The study of this plan, associated with descriptive and chronological information, highlights the major evolutions of the site or specific details. Its realization is generally entrusted to a topographer in collaboration with archaeologists. + +At the end of the field phase, a phase of analysis of the collected data is carried out. This so-called post-excavation phase allows for processing all the information collected, carrying out a complete description, conducting the studies necessary for understanding the site by calling on numerous specialists: ceramologists, anthropologists, archaeozoologists, lithicists, carpologists, anthracologists, paleometallurgy specialists, etc. + +This post-excavation phase initially results in the production of an operation report, the most exhaustive account possible of the site and its evolution. These reports are submitted to the Ministry of Culture, which judges their quality. They are not intended to be widely disseminated, but are normally accessible to anyone who requests them from the concerned administration. They are an important working basis for the entire scientific community. + +Based on this report, the publication of articles in specialized journals allows for presenting the results of the operation more widely, sometimes according to specific themes or issues. + +# Practice of archaeology: example in preventive archaeology + +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. +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. + +![conservation sheet, illustrating manual coloring of found skeleton parts](https://github.com/sqlpage/SQLPage/assets/552629/ca9c0f99-a520-4f2b-9826-ae49a89f844b) +> *Conservation sheet, illustrating manual coloring of found skeleton parts* + +![Example of a descriptive sheet of an archaeological layer](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/fiche_us.svg) +> *Example, among many others, of a blank descriptive sheet of an archaeological layer* + +# The beginning of digitization + +It is essentially after the field phase that digital tools have been tamed by archaeologists. + +In post-excavation, paper documentation is still often a fundamental documentary basis for site analysis. The irruption of computing in the mid-80s led archaeologists to transcribe this data into digital form, to facilitate its analysis and presentation. Although the software has evolved, the process is practically the same today, with digitization of documentation in many formats. + +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) +> *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. +Plan data, surveyed by the topographer, is carried out under Autocad and was exported in .dxf or .dwg before being cleaned up under Adobe Illustrator, which is also the case for drawings made in the field. +The artifacts are entrusted to specialists who describe them, draw them, make an inventory, most often in spreadsheets. Their drawings are again scanned and cleaned up digitally. + +In hindsight, we find that digital tools are mainly used as tools for cleaning up information collected in the field. Many spreadsheets are thus the strict transcription of paper tables used by archaeologists, to which some totals, averages or medians will be added. Drawings made on paper are traced in vectorization software for better readability and the scientific added values are ultimately quite limited. + +This results in relatively disparate digital documentation, with the use of many proprietary tools, closed formats, and a very strong separation between spatial information and descriptive (or attributive) information. + +The progressive use of databases has, however, allowed for agglomerating certain data and gathering and relating information. University work has also helped to feed reflection on the structuring of archaeological data and to train many archaeologists, allowing for the adoption of more virtuous practices. + +# The all-digital movement + +Until now, going fully digital in the archaeological context seemed relatively utopian. It took new technologies to appear, portable and simple-to-use supports to be put in place, networks to develop, and archaeologists to seize these new tools. + +The Ramen collective (Archaeological Research in Digital Recording Modeling) was born from the exchanges and experiences of various archaeologists from the National Institute of Preventive Archaeological Research (Inrap) who grouped around the realization of [the programmed excavation of the medieval necropolis of Noisy-Le-Grand](https://archeonec.hypotheses.org/), excavation managed by the Necropolis Archaeology Association and entrusted to the scientific direction of Cyrille Le Forestier (Inrap). This programmed excavation allowed launching an experiment on the complete dematerialization of archaeological data based on photogrammetry, GIS, and a spatial database. + +## General principle + +While the topographer still intervenes for taking reference points, the detailed survey of remains is ensured, for this experiment, by the systematic implementation of photogrammetry. This method allows, by taking multiple photos of an object or scene, to create an accurate 3D model, and therefore exploitable a posteriori by the archaeologist in post-excavation. Photogrammetry constitutes in Noisy the only survey tool, purely and simply replacing drawing on paper. Indeed, from this 3D point cloud, it is possible to extract multiple 2D supports and add geometry or additional information to the database: burial contours, representation of the skeleton in situ, profiles, measurements, altitudes, etc. + +![Photogrammetric survey of a burial](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/photogrammetrie3.png) +[*Photogrammetric survey of a burial*](https://sketchfab.com/3d-models/973-5d7513dd1dc941228d4a4b7b984c7af7) + +Data recording is ensured by the use of a relational and spatial database whose interface is accessible in QGIS, but also via a web interface directly in the field, without going through paper inventories or listings. The web interface was created using [SQLPage](https://sql-page.com/), a web server that uses an SQL-based language for creating the graphical interface, without having to go through more complex programming languages classically used for creating web applications, such as PHP. + +Of course, this approach also continues in the laboratory during the site analysis stage. + +## Free software and formats + +But abandoning paper support requires us to question the durability of the files and the data they contain. + +Indeed, in a complete dematerialization process, the memory of the site is no longer contained on hundreds of handwritten sheets, but in digital files of which we do not know a priori if we will be able to preserve them in the long term. The impossibility of accessing this data with other software than those originally used during their creation is equivalent to their destruction. Only standard formats can address this issue, and they are particularly used by free software. For photogrammetry, the [`.ply`](https://en.wikipedia.org/wiki/PLY_(file_format)) and [`.obj`](https://en.wikipedia.org/wiki/Wavefront_.obj_file) formats, which are implemented in many software, free and proprietary, were chosen. For attributive and spatial data, it is recorded in free relational databases (Spatialite and Postgis), and easily exportable in `.sql`, which is a standardized format recognized by many databases. + +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. + +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. + +Of course, QGIS also allows data analysis, the creation of thematic or chronological plans, essential supports for our reflections. We can, from these elements, create the numerous figures of the operation report, without going through vector drawing software, in plan as in section (vertical representation of stratigraphy). It allows normalizing figures through the use of styles, and, through the use of the Atlas tool, creating complete catalogs, provided that the data is rigorously structured. + +![spatial analysis](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/ex_plan_analyse.png?ref_type=heads) +> *Example of spatial analysis in Qgis of ceramic waste distribution on a Gallic site* + +In the context of the experiment on the Mastraits necropolis, while Qgis is indeed one of the pillars of the system, a few proprietary software are still used. + +The processing software used for photogrammetry is proprietary. The ultimate goal is to be able to use free software, MicMac, developed by IGN, being a possible candidate. However, it still lacks a fully intuitive interface for archaeologists to appropriate the tool autonomously. + +Similarly, the exciting latest developments of the Inkscape project should encourage us to turn more towards this software and systematically use .svg. The use of Scribus for DTP should also be seriously considered. + +Free software and its undeniable advantages are thus slowly taking place, mainly via QGIS, in the production chain of our archaeological data. We can only hope that this place will grow. The path still seems long, but the way is free... + +## Badass, spatial and attributive united + +The development of the Archaeological Database of Attributive and Spatial Data (Badass) aimed to integrate, within a single database, the attributive information provided by archaeologists and the spatial information collected by the topographer. It even involves gathering, within dedicated tables, attributive and spatial information, thus ensuring data integrity. +Its principle is based on the functioning of the operational chain in archaeology, namely the identification and recording by the archaeologist of the uncovered remains, followed by the three-dimensional survey carried out by the topographer. The latter has, in the database, specific tables in which he can pour the geometry and minimal attributive data (number, type). Triggers then feed the tables filled by archaeologists with geometry, according to their identifier and type. + +The database is thus the unique repository of attributive and spatial information throughout the operation, from field to post-excavation. + +The format of the database was originally SpatiaLite. But the mass of documentation produced by the Mastraits necropolis led us to port it to PostGIS. Many archaeological operations, however, only require a small SpatiaLite base, which also allows the archaeologist to have control over their data file. Only a few large sites may need a PostgreSQL solution, otherwise used for the ARchaeological VIsualization CATalogue (Caviar) which is intended to host spatial and attributive data produced at the institute. + +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: + +## 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). + +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? + +It was on LinuxFR that one of the members of the collective discovered [SQLPage](https://sql-page.com/). This open-source software, developed by [lovasoa](https://linuxfr.org/users/lovasoa), provides a very simple web server and allows for the creation of a [CRUD](https://en.wikipedia.org/wiki/CRUD) application with an interface that only requires SQL development. + +SQLPage is based on an executable file which, when launched on a computer, turns it into a web server. A configuration file allows you to define the location of the database to be queried, among other things. For each web page of the interface, you write a `.sql` file to define the data to fetch or modify in the database, and the interface components to display it (tables, forms, graphs...). The interface is accessed through a web browser. If the computer is on a network, its IP address allows remote access, with an address like `http://192.168.1.5:8080`, for example. Using a VPN allows us to use the mobile phone network, eliminating the need for setting up a local network with routers, antennas, etc. + +![principle](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/sqlpage_badass.svg) +*General operating principle* + +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. + +[![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* + +# Use Cases and Concrete Benefits + +## First Experience at Les Mastraits + +The excavation of the [Les Mastraits Necropolis](https://www.inrap.fr/la-necropole-alto-medievale-des-mastraits-noisy-le-grand-15374) was the test site for these developments. The significant amount of data collected, as well as its status as a planned excavation, allows for this kind of experimentation with much less impact than in a preventive excavation where deadlines are particularly tight. + +The implementation of the SQLPage interface has allowed for the complete digitization of attribute recording and proves to be very efficient. This is a major change in our practices and will save us an enormous amount of time during data processing. + +This also allows for centralizing information, working with multiple people simultaneously without waiting for traditional recording binders to become available, and guiding archaeologists through the recording process, avoiding omissions and errors. Thanks to a simplified interface, data entry can be done very intuitively without the need for extensive training. + +The homogeneity of the entered data is thus better, and the possibilities for querying are much greater. + +## 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. + +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. + +# Conclusion + +Gradually, the use of digital tools has become widespread in archaeological professions. After the word processors and spreadsheets of the 90s (often on Mac), the first vectorized drawings digitized in Adobe Illustrator, and databases in Filemaker, Access, or 4D, digital tools are now able to be used throughout the entire data acquisition chain. + +The contribution of open-source software and formats is major for this new step. + +QGIS has fundamentally revolutionized archaeological practice by offering GIS access to the greatest number, allowing for the connection and manipulation of attribute and spatial data. It has paved the way for new developments and the integration of technologies previously little used by archaeology (notably the use of relational and spatial databases in SQL format). +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. + +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... diff --git a/examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md b/examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md new file mode 100644 index 000000000..9670cc51c --- /dev/null +++ b/examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md @@ -0,0 +1,138 @@ +--- +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 +--- + +# How I Built And Deployed An Exhaustive Performance Monitoring Tool For a 100M€/year Company Using SQL Queries Only + +### Building web applications in SQL + +> [SQLPage](http://sql-page.com) allows anyone with SQL skills to build and deploy digital tools (websites, data applications, dashboards, user forms…) using only **SQL queries**. Official website: [https://sql-page.com/](https://sql-page.com/) + +SQLPage eliminates the need to learn server languages, HTML, CSS, JavaScript, or front-end frameworks, and instead uses SQL to generate modern UI layouts populated with database query results. You get native SQL interactions with the database, without all the other layers that typically get in the way. + +The execution of the project is straightforward: simply run a single executable without any installation dependencies. Everything from authentication to security, and even HTTPS termination is automated. The code required to complete most real-world development tasks is minimal and seamless. + +Finally, it’s open source with an MIT license. + +### Choosing SQLPage for my data team + +As a Head of Data at a mid-size company, I understand the challenge of juggling multiple tools — often expensive and proprietary — alongside a variety of dashboards. Building an **all-in-one**, **user-friendly**, **mobile-compatible** platform for data monitoring and visualization that serves everyone, from C-level executives to store managers, is no small feat. + +The struggle intensifies when teams are small and lack coding skills or experience with diverse tech stacks. A typical data flow in a digital-native company involves several teams, specialized skills, and costly tools: + +![](https://cdn-images-1.medium.com/max/800/1*1IoXc8-07rqXO3yvKC13nQ.png) + +*Typical Data Flow of digital native companies. + +SQLPage changes this by allowing data professionals to use the same language — SQL — across the entire process, from building data pipelines to creating fully functional digital tools. Data analysts, scientists, business analysts, DBAs, and IT teams already have the expertise to craft their own custom data applications from the ground up. + +### Building an all-in one monitoring tool using SQL-queries only +[![youtube](https://github.com/user-attachments/assets/1afe36d7-9deb-40fc-a174-7a869348500b)](https://www.youtube.com/embed/R-5Pej8Sw18?si=qgxacwip2Mm-0wC7) + +*Excerpt from a series of videos explaining how to build and deploy your first digital tool with SQLPage* ([https://www.youtube.com/@SQLPage](https://www.youtube.com/@SQLPage)). + + +I am using SQLPage to build a 360° Performance tool for my company, integrating data from multiple sources — Revenue, traffic, marketing investments, live performance monitoring, financial targets, images of top sold products, Google Analytics for the online traffic… — . + +#### With SQLPage, I can: + +- **Centralize** all company data in one tool for visualizations, year-over-year comparisons, financial targets, and more. +- **Provide tailored insights**: A store owner can instantly access last year’s performance and top-selling products, while the e-commerce director can track conversion rate history. SQLPage’s pre-built components offer limitless possibilities for displaying results. +- **Perform CRUD operations**: Unlike traditional BI tools, SQLPage not only displays data but also allows users to interact with it — inputting data, such as comments or updates, directly through the interface. This capability to both display and collect data is a significant enhancement over traditional BI tools, which typically do not support data input. +- **Ensure a single source of truth**: By connecting directly to the database, SQLPage avoids discrepancies between dashboards, ensuring all teams work with consistent and accurate data. + +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)\ + +*Performance of different channels vs last year and best sellers. + +![](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 + +The process in SQLPage follows a simple pattern: + +> 1) Select a component + +> 2) Write a query to populate the selected component with data + +You can find the full list of components: [https://sql-page.com/documentation.sql](https://sql-page.com/documentation.sql) + +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 +-- defined dynamically in the SQL script +``` +And the result: + +![Example of a SQL-generated page using the “graph” and the “table” components](https://cdn-images-1.medium.com/max/800/1*mtgJNP7DSOmMnq0iu6dDcg.png) + +*Example of a SQL-generated page using the components “graphs” and “tables”.* + +That’s it! Each component comes with customizable parameters, allowing you to tailor the display. As shown in the screenshot, links are clickable, enabling users to add data, such as leaving a comment for a specific date. + +The ability to perform CRUD operations and interact directly with databases is a game changer compared to traditional BI tools. You can try it yourself by clicking “add” in the column “COMMENT THIS YEAR” [https://demo-test.datapage.app/lets_see_some_graphs.sql](https://demo-test.datapage.app/lets_see_some_graphs.sql) + +### Generating SQL queries with AI + +I couldn’t write an article about data in 2024 without mentioning GenAI. The great news is that SQLPage, relying solely on SQL queries, is naturally GenAI-friendly. In fact, I rarely write SQL queries myself anymore — I let GenAI handle that. My workflow in SQLPage now becomes: + +> 1) Select a component + +> 2) Ask a GenAI tool to write the query I need + +![](https://cdn-images-1.medium.com/max/800/1*mg45EO7XCVPNiuIQ_5Xg0Q.png) + +*Example of Generated SQL to display a specific format of numbers.* + +### Hosting the application + +Once my app was ready, I could have chosen to host it myself on any server for a few euros a month, but I opted for SQLPage’s official hosting service, DataPage ([https://datapage.app/](https://beta.datapage.app/)), which is fully managed and very convenient. My app was hosted at _domainname.datapage.app._ The service includes a Postgres database, allowing you to either store your data on the server or connect directly to your existing database (Microsoft SQL Server, SQLite, Postgres, MySQL, etc). + +### Maintaining complex SQL queries + +While SQLPage simplifies the process of building digital tools, it does come with some challenges. + +As applications grow in complexity, so do the SQL queries required to power them, which can result in long and intricate scripts. Additionally, to fully leverage SQLPage, you need to understand how its components work, especially if user input is involved. Developers should be comfortable with creating tables in a database, writing `INSERT` queries, and managing data effectively. Without a solid grasp of these fundamentals, building more advanced apps can become a bit overwhelming. + +### Conclusion + +With SQLPage, any company with a database and one employee who knows how to query it has the tools and workforce to build and deploy virtually any digital tool. + +In this article, I focused on creating an enhanced Business Intelligence tool, but SQLPage’s versatility goes far beyond that. It is being used to build a planning tool for lumberjacks in Finland, a monitoring app for a South African transport and logistics company, by archaeologists to input excavation data in the field… + +What all these projects have in common is that they were built by a single person, using nothing but SQL queries. If you’re ready to streamline your processes and build powerful tools with ease, SQLPage is worth exploring further. + +### Useful links + +- 🏡Official website [https://sql-page.com](https://sql-page.com/) +- 🔰Quick start (written by [Nick Antonaccio](https://medium.com/u/b6a791990395)): [https://learnsqlpage.com/sqlpage_quickstart.html](https://learnsqlpage.com/sqlpage_quickstart.html) +- 📹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/content/blog/how-to-use-the-pagination-component.md b/examples/official-site/content/blog/how-to-use-the-pagination-component.md new file mode 100644 index 000000000..374fab9e3 --- /dev/null +++ b/examples/official-site/content/blog/how-to-use-the-pagination-component.md @@ -0,0 +1,160 @@ +--- +title: How to use the pagination component +date: '2025-11-10' +icon: sailboat-2 +summary: A tutorial for using the pagination component +--- + +# 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. + +This component offers many options, and I recommend consulting its documentation before proceeding with the rest of this tutorial. + +Of course, this component only handles its display and does not implement any logic for data processing or state changes. In this tutorial, we will implement a complete example of using the pagination component with a SQLite database, but the code should work without modification (or with very little modification) with any relational database management system (RDBMS). + +> This article serves as a tutorial on the pagination component, rather than an advanced guide on paginated data retrieval from a database. The document employs a straightforward approach using the LIMIT and OFFSET instructions. This approach is interesting only for datasets that are big enough not to be realistically loadable on a single webpage, yet small enough for being queryable with OFFSET...LIMIT. + +## Initialization + +We first need to define two constants that indicate the maximum number of rows per page and the maximum number of pages that the component should display. + +``` +SET MAX_RECORD_PER_PAGE = 10; +SET MAX_PAGES = 10; +``` + +Now, we need to know the number of rows present in the table to be displayed. We can then calculate the number of pages required. + +``` +SET records_count = (SELECT COUNT(*) FROM album); +SET pages_count = (CAST($records_count AS INTEGER) / CAST($MAX_RECORD_PER_PAGE AS INTEGER)); +``` + +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) + 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. + +![Meaning of URL parameters](blog/pagination.png) + + +If the page number or index is not present in the URL, the value of 1 is applied by default. + +``` +SET page = COALESCE($page,1); +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. + +``` +SELECT + 'table' as component +SELECT + user_id AS id, + last_name AS "Last name", + first_name AS "First name" +FROM + users +LIMIT CAST($MAX_RECORD_PER_PAGE AS INTEGER) +OFFSET (CAST($page AS INTEGER) - 1) * CAST($MAX_RECORD_PER_PAGE AS INTEGER); +``` + +The SQL LIMIT clause allows us to not read more rows than the maximum allowed for a page. With the SQL OFFSET clause, we specify from which row the data is selected. + +On each HTML page load, the table content will be updated based on the `page` and `idx_page` variables, whose values will be extracted from the URL + +## Set up the pagination component + +Now, we need to set up the parameters that will be included in the URL for the buttons to navigate to the previous or next page. + +If the user wants to view the previous page and the current page is not the first one, the value of the `page` variable is decremented. The same applies to `idx_page`, which is decremented if its value does not correspond to the first page. + +``` +SET previous_parameters = ( + CASE + WHEN CAST($page AS INTEGER) > 1 THEN + json_object( + '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) + ) + ELSE json_object() END +); +``` + +The logic is quite similar for the URL to view the next page. First, it is necessary to verify that the user is not already on the last page. Then, the `page` variable can be incremented and the `idx_page` variable updated. + +``` +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 + 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) + ) + ELSE json_object() END +); +``` + +We can now add the pagination component, which is placed below the table displaying the data. All the logic for managing the buttons is entirely handled in SQL: +- the buttons to access the first or last page, +- the buttons to view the previous or next page, +- the enabling or disabling of these buttons based on the context. + +``` +SELECT + '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(), $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', ( + 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) + 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. + +``` +WITH RECURSIVE page_numbers AS ( + SELECT $idx_page AS number + UNION ALL + SELECT number + 1 + FROM page_numbers + LIMIT CAST($MAX_PAGES AS INTEGER) +) +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 +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. diff --git a/examples/official-site/content/blog/im-sorry-i-forked-you.md b/examples/official-site/content/blog/im-sorry-i-forked-you.md new file mode 100644 index 000000000..43bd7614f --- /dev/null +++ b/examples/official-site/content/blog/im-sorry-i-forked-you.md @@ -0,0 +1,96 @@ +--- +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. +Throughout my career as a computer engineer, I’ve yet to encounter a tech company that isn’t built on the foundation of free and open source software. +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 + +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, +the software realm flips the script. +In this landscape, it’s user-facing giants like Google that reap the profits, +while the very creators crafting the software forming the bedrock for Google and countless others often find themselves on a different end of the economic spectrum. + + +Open source developers observe this intriguing dynamic, +sometimes even finding satisfaction in witnessing how their freely contributed software +fuels the creation of multimillion-dollar ventures. + +## SQLx: A Rust Marvel + +[sqlx](https://crates.io/crates/sqlx) is one of the numerous software libraries +that lie at the foundation of this software iceberg. +It’s a formidable SQL database driver for the *Rust* programming language, +that harmonizes connection to a multitude of databases. +It garners approximately 20,000 daily downloads. + +### Version 0.7 + +sqlx’s main maintainer sought to find a middle ground – crafting good open source software while seeking a sustainable livelihood. +This endeavor led to a pivotal decision: extracting the database drivers from the core library. +While retaining most drivers as open source, **compatibility with Microsoft SQL Server was relinquished**. +This significant architectural shift also necessitated the removal of some other features from the core framework, +and the introduction of a new API, making it non trivial to migrate from the previous version. + +## 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: +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. + +After a lot of hesitation I chose a third path: **forking sqlx**. + +## I’m sorry I forked you + +I’m sorry I forked you, sqlx. I really am all for financially sustainable open source. +My hope is that the newfound proprietary drivers find success, +duly compensating *@abonander* for the invaluable contributions made. + +But I really need a good fully open source set of database drivers for Rust, +I need some of the features that were removed in v0.7, and most importantly, +I want to support SQL Server in SQLPage. +So I created [sqlx-oldapi](https://lib.rs/crates/sqlx-oldapi), a fork of sqlx v0.6. + +In the fork: + - I’ve meticulously updated all dependencies to their latest iterations, ensuring the foundation remains robust and secure. + - Essential features that were missing have been thoughtfully incorporated to address specific needs, and longstanding bugs have been resolved. Notably, data type support has been fortified, with efficient lossy decoding of `DECIMAL` values as floats across all drivers. + - My endeavors have been focused on elevating the SQL Server driver to the same level as its peers. This involved fixing bugs and crashes, and supporting new data types like `DATETIME` and `DECIMAL`. + +The full list of changes can be found in the [changelog](https://github.com/lovasoa/sqlx/blob/main/CHANGELOG.md). + +## Concluding Notes + + - My best wishes extend to sqlx on their pursuit of successful monetization. + May their path be paved with prosperity as they navigate this new chapter. + - To fellow developers facing a similar crossroads as I did with SQLPage, + know that [sqlx-oldapi](https://lib.rs/crates/sqlx-oldapi) awaits you, ready to empower your endeavors, for free. + Contributions and bug reports are all welcomed [on github](https://github.com/lovasoa/sqlx-oldapi). + +And if you are curious about why this page’s URL ends in `.sql`, check out [SQLPage](/). + +--- + +**Important addendum**: +The main contributor to sqlx reacted to this post, and they wanted to clarify two things: + + - sqlx is a project of the *Launchbase* company, not a personal project of *@abonander*. + Although he is the main contributor, important decisions are taken in consultation with the company. + If new drivers are monetized, the money will go to the company, not to him personally. + The stated goal is to then allocate the money to the development of sqlx. + - Most importantly: the current plan for the new drivers **is not to release them as proprietary** + code as initially planned, but to release them as open source, under the more restrictive *AGPL* license. + This means that they will be free to use for similarly licensed open source projects + (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. diff --git a/examples/official-site/content/blog/introduction-video.md b/examples/official-site/content/blog/introduction-video.md new file mode 100644 index 000000000..78ce294b4 --- /dev/null +++ b/examples/official-site/content/blog/introduction-video.md @@ -0,0 +1,27 @@ +--- +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. +--- + +# Introduction video + +## Canadians love SQLPage + +The Kitchener-Waterloo Linux User Group had the pleasure of [hosting a presentation](https://kwlug.org/node/1374) +by Anton Avramov, an avid SQLPage user and community member, who gave a live demonstration of SQLPage. + +## The video + +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, +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: + +[![video cover](https://i.ytimg.com/vi/9NJgH_-zXjY/maxresdefault.jpg)](https://www.youtube.com/watch?v=9NJgH_-zXjY) diff --git a/examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md b/examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md new file mode 100644 index 000000000..44c42339c --- /dev/null +++ b/examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md @@ -0,0 +1,583 @@ +--- +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 + +JSON (JavaScript Object Notation) is a popular data format for unstructured data. It allows storing composite data types, such as arrays and objects, in a single SQL value. +Many modern applications use JSON to store and exchange data. As a result, SQL databases have incorporated JSON support to allow developers to work with structured and semi-structured data within the same database. + +This guide will cover JSON operations in SQLite, PostgreSQL, MySQL, and SQL Server, focusing on querying JSON data. + +SQLPage uses JSON both to pass data to the database (when a SQLPage variable contains an array), and to pass data to components (when a component has a JSON parameter). +Thus, understanding how to work with JSON in SQL will allow you to fully leverage advanced SQLPage features. + +JSON supports the following data types: + +- **Objects**: A mapping between keys and values (`{ "key": "value" }`). Keys must be strings, and values can be of different types. +- **Arrays**: An ordered list of values enclosed in square brackets (`[ "value1", "value2" ]`). Values can be of different types. +- **Strings**: A sequence of characters enclosed in double quotes (`"Hello, World!"`). +- **Numbers**: An integer or floating-point number (`42`, `3.14`). +- **Boolean**: A true or false value (`true`, `false`). +- **Null**: A null value (`null`). + +## Sample Table + +We'll use the following sample table for our examples: + +```sql +CREATE TABLE users ( + id INT PRIMARY KEY, + name VARCHAR(50), + birthday DATE, + group_name VARCHAR(50) +); + +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'); +``` + +## SQLite + +SQLite provides increasingly better JSON support since version 3.38.0. +See [the list of JSON functions in SQLite](https://www.sqlite.org/json1.html) for more details. + +### Creating a JSON object + +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 +FROM users; +``` + +| user_json | +|-----------| +| `{"name":"Alice","birthday":"1990-01-15"}` | +| `{"name":"Bob","birthday":"1985-05-22"}` | +| `{"name":"Charlie","birthday":"1992-09-30"}` | + +### Creating a JSON array + +```sql +SELECT json_array(name, birthday, group_name) AS user_array +FROM users; +``` + +| user_array | +|------------| +| `["Alice","1990-01-15","Admin"]` | +| `["Bob","1985-05-22","User"]` | +| `["Charlie","1992-09-30","User"]` | + +### Aggregating multiple values into a JSON array + +```sql +SELECT json_group_array(name) AS names +FROM users; +``` + +| names | +|-------| +| `["Alice","Bob","Charlie"]` | + +### Aggregating values into a JSON object + +```sql +SELECT json_group_object(name, group_name) AS name_group_map +FROM users; +``` + +| name_group_map | +|-------------------| +| `{"Alice":"Admin", "Bob":"User", "Charlie":"User"}` | + + +### Iterating over a JSON array + +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"]'); +``` + +| value | +|-------| +| Alice | +| Bob | +| Charlie | + +The `json_each()` function returns a table with several columns. The most commonly used are: + +- `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') + +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. +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)) +)) as options +from users; +``` + +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 + +### 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; +``` + +| user_json | +|-----------| +| {"name": "Alice", "birthday": "1990-01-15"} | + +## PostgreSQL + +PostgreSQL has extensive support for JSON, including the `jsonb` type, which offers better performance and more functionality than the `json` type. +See [the list of JSON functions in PostgreSQL](https://www.postgresql.org/docs/current/functions-json.html) for more details. + +### Creating a JSON object + +```sql +SELECT + jsonb_build_object( + 'name', name, + 'birthday', birthday + ) AS user_json +FROM users; +``` + +| user_json | +|-----------| +| `{"name":"Alice","birthday":"1990-01-15"}` | +| `{"name":"Bob","birthday":"1985-05-22"}` | +| `{"name":"Charlie","birthday":"1992-09-30"}` | + +### Creating a JSON array + +```sql +SELECT + jsonb_build_array( + name, birthday, group_name + ) AS user_array +FROM users; +``` + +| user_array | +|------------| +| `["Alice", "1990-01-15", "Admin"]` | +| `["Bob", "1985-05-22", "User"]` | +| `["Charlie", "1992-09-30", "User"]` | + +### Aggregating multiple values into a JSON array + +```sql +SELECT jsonb_agg(name) AS names FROM users; +``` + +| names | +|-------| +| `["Alice","Bob","Charlie"]` | + +### Aggregating values into a JSON object + +```sql +SELECT + jsonb_object_agg( + name, birthday + ) AS name_birthday_map +FROM users; +``` + +| name_birthday_map | +|-------------------| +| `{"Alice":"1990-01-15","Bob":"1985-05-22","Charlie":"1992-09-30"}` | + + +### Iterating over a JSON array + +```sql +SELECT name FROM jsonb_array_elements_text('["Alice", "Bob", "Charlie"]'::jsonb) AS name; +``` + +| name | +|------| +| Alice | +| Bob | +| Charlie | + +You can use this function to test whether a value is present in a JSON array. For instance, to create a +[multi-value select dropdown](documentation.sql?component=form#component) with pre-selected values, you can use the following query: + +```sql +SELECT jsonb_agg(jsonb_build_object( + 'label', name, + 'value', id, + 'selected', id in (SELECT value FROM jsonb_array_elements_text($selected_ids::jsonb)) +)) AS options +FROM users; +``` + +### Iterating over a JSON object + +```sql +SELECT key, value +FROM jsonb_each_text('{"name": "Alice", "birthday": "1990-01-15"}'::jsonb); +``` + +| key | value | +|-----|-------| +| name | Alice | +| birthday | 1990-01-15 | + +### Querying JSON data + +PostgreSQL allows you to query JSON data using the `->` and `->>` operators: + +```sql +SELECT name, user_data->>'age' AS age +FROM ( + SELECT name, jsonb_build_object('age', EXTRACT(YEAR FROM AGE(birthday))) AS user_data + FROM users +) subquery +WHERE (user_data->>'age')::int > 30; +``` + +| name | age | +|------|-----| +| Bob | 38 | + +### Combining 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; +``` + +| user_json | +|-----------| +| {"name": "Alice", "birthday": "1990-01-15"} | + +## MySQL / MariaDB + +MySQL has good support for JSON operations starting from version 5.7. +See [the list of JSON functions in MySQL](https://dev.mysql.com/doc/refman/8.0/en/json-functions.html) for more details. + +### Creating a JSON object + +```sql +SELECT JSON_OBJECT('name', name, 'birthday', birthday) AS user_json +FROM users; +``` + +| user_json | +|-----------| +| `{"name":"Alice","birthday":"1990-01-15"}` | +| `{"name":"Bob","birthday":"1985-05-22"}` | +| `{"name":"Charlie","birthday":"1992-09-30"}` | + +### Creating a JSON array + +```sql +SELECT JSON_ARRAY(name, birthday, group_name) AS user_array +FROM users; +``` + +| user_array | +|------------| +| `["Alice","1990-01-15","Admin"]` | +| `["Bob","1985-05-22","User"]` | +| `["Charlie","1992-09-30","User"]` | + +### Aggregating multiple values into a JSON array + +```sql +SELECT JSON_ARRAYAGG(name) AS names +FROM users; +``` + +| names | +|-------| +| `["Alice","Bob","Charlie"]` | + +### Aggregating values into a JSON object + +```sql +SELECT JSON_OBJECTAGG(name, birthday) AS name_birthday_map +FROM users; +``` + +| name_birthday_map | +|-------------------| +| `{"Alice":"1990-01-15","Bob":"1985-05-22","Charlie":"1992-09-30"}` | + +### Iterating over a JSON array + +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: + +```sql +SELECT jt.name +FROM JSON_TABLE( + '["Alice", "Bob", "Charlie"]', + '$[*]' COLUMNS( name VARCHAR(50) PATH '$' ) +) AS jt; +``` + +| name | +|---------| +| Alice | +| Bob | +| Charlie | + +In this example: +- The first argument to JSON_TABLE() is the JSON 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). + +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' + ) +) AS jt; +``` + +| id | name | +|----|---------| +| 1 | Alice | +| 2 | Bob | +| 3 | Charlie | + +This approach allows you to easily iterate over JSON arrays and access their elements in a tabular format, which can be very useful for further processing or joining with other tables in your database. + +### Iterating over a JSON object + +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 '$' + ) +) AS jt; +``` + +| value | +|-------| +| "Alice" | +| "1990-01-15" | + +#### Iterating over key-value pairs + +You can use the `JSON_KEYS()` function to retrieve the list of keys in a JSON object as a JSON array, +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 +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; +``` + +| json_key | json_value | +|----------|------------| +| name | Alice | +| birthday | 1990-01-15 | + +### Querying JSON data + +MySQL allows you to query JSON data using the `->` and `->>` operators: + +```sql +SELECT name, user_data->'$.age' AS age +FROM ( + SELECT name, JSON_OBJECT('age', YEAR(CURDATE()) - YEAR(birthday)) AS user_data + FROM users +) subquery +WHERE user_data->'$.age' > 30; +``` + +| name | age | +|------|-----| +| Bob | 38 | + +## Microsoft SQL Server + +SQL Server has support for JSON operations starting from SQL Server 2016. +See [the list of JSON functions in SQL Server](https://learn.microsoft.com/en-us/sql/t-sql/functions/json-functions-transact-sql?view=sql-server-ver16) for more details. + +# JSON in SQL: A Comprehensive Guide + +[Previous sections remain unchanged] + +## Microsoft SQL Server + +SQL Server has support for JSON operations starting from SQL Server 2016. It provides a comprehensive set of functions for working with JSON data. +See [the list of JSON functions in SQL Server](https://learn.microsoft.com/en-us/sql/t-sql/functions/json-functions-transact-sql?view=sql-server-ver16) for more details. + +### Creating a JSON object + +Use the `FOR JSON PATH` clause to create a JSON object: + +```sql +SELECT (SELECT name, birthday FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS user_json +FROM users; +``` + +| user_json | +|-----------| +| `{"name":"Alice","birthday":"1990-01-15"}` | +| `{"name":"Bob","birthday":"1985-05-22"}` | +| `{"name":"Charlie","birthday":"1992-09-30"}` | + +Alternatively, you can use the `JSON_OBJECT` function: + +```sql +SELECT JSON_OBJECT('name': name, 'birthday': birthday) AS user_json +FROM users; +``` + +### Creating a JSON array + +Use the `FOR JSON PATH` clause to create a JSON array: + +```sql +SELECT (SELECT name, birthday, group_name FOR JSON PATH) AS user_array +FROM users; +``` + +| user_array | +|------------| +| `[{"name":"Alice","birthday":"1990-01-15","group_name":"Admin"}]` | +| `[{"name":"Bob","birthday":"1985-05-22","group_name":"User"}]` | +| `[{"name":"Charlie","birthday":"1992-09-30","group_name":"User"}]` | + +You can also use the `JSON_ARRAY` function: + +```sql +SELECT JSON_ARRAY(name, birthday, group_name) AS user_array +FROM users; +``` + +### Aggregating multiple values into a JSON array + +Use the `FOR JSON PATH` clause to aggregate values into a JSON array: + +```sql +SELECT (SELECT name FROM users FOR JSON PATH) AS names; +``` + +| names | +|-------| +| `[{"name":"Alice"},{"name":"Bob"},{"name":"Charlie"}]` | + +Alternatively, use the `JSON_ARRAYAGG` function: + +```sql +SELECT JSON_ARRAYAGG(name) AS names FROM users; +``` + +### Aggregating values into a JSON object + +```sql +SELECT JSON_OBJECTAGG(name: birthday) AS name_birthday_map FROM users; +``` + +### Iterating over a JSON array + +Use the `OPENJSON` function to iterate over JSON arrays: + +```sql +SELECT value FROM OPENJSON('["Alice", "Bob", "Charlie"]'); +``` + +| value | +|-------| +| Alice | +| Bob | +| Charlie | + +### Iterating over a JSON object + +Use `OPENJSON` to iterate over JSON objects: + +```sql +SELECT * +FROM OPENJSON('{"name": "Alice", "birthday": "1990-01-15"}') +WITH ( + name NVARCHAR(50) '$.name', + birthday DATE '$.birthday' +); +``` + +| name | birthday | +|------|----------| +| Alice | 1990-01-15 | + +### Querying JSON data + +Use the `JSON_VALUE` function to extract scalar values from JSON: + +```sql +SELECT JSON_VALUE('{"age": 38}', '$.age') AS age +``` + +| age | +|-----| +| 38 | + +### Additional JSON Functions + +SQL Server provides several other useful JSON functions: + +- `ISJSON`: Tests whether a string contains valid JSON. +- `JSON_MODIFY`: Updates the value of a property in a JSON string. +- `JSON_PATH_EXISTS`: Tests whether a specified SQL/JSON path exists in the input JSON string. +- `JSON_QUERY`: Extracts an object or an array from a JSON string. + +Example using `JSON_MODIFY`: + +```sql +SELECT JSON_MODIFY('{"name": "Alice", "age": 30}', '$.age', 31) AS updated_json; +``` + +| updated_json | +|--------------| +| {"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. diff --git a/examples/official-site/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md b/examples/official-site/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md new file mode 100644 index 000000000..141987463 --- /dev/null +++ b/examples/official-site/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md @@ -0,0 +1,39 @@ +--- +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 +--- + +[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. ![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. + 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. + +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. + +11. **Implementation of `uploaded_file_mime_type` function:** This function allows you to determine the MIME type of a uploaded file. + +12. **Upgraded built-in SQLite database to version 3.45.0:** This ensures compatibility with recent SQLite features and bug fixes. See [sqlite release notes](https://www.sqlite.org/releaselog/3_45_0.html) + +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. diff --git a/examples/official-site/content/blog/performance-guide.md b/examples/official-site/content/blog/performance-guide.md new file mode 100644 index 000000000..90773d0d0 --- /dev/null +++ b/examples/official-site/content/blog/performance-guide.md @@ -0,0 +1,281 @@ +--- +title: Performance Guide +date: '2025-10-31' +icon: bolt +summary: Concrete advice on how to make your SQLPage webapp fast +--- + +# Performance Guide + +SQLPage is [optimized](/performance) +to allow you to create web pages that feel snappy. +This guide contains advice on how to ensure your users never wait +behind a blank screen waiting for your pages to load. + +A lot of the advice here is not specific to SQLPage, but applies +to making SQL queries fast in general. +If you are already comfortable with SQL performance optimization, feel free to jump right to +the second part of the quide: *SQLPage-specific advice*. + +## Make your queries fast + +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. + +### Choose the right database schema + +#### Normalize (but not too much) + +Your database schema should be [normalized](https://en.wikipedia.org/wiki/Database_normalization): +one piece of information should be stored in only one place in the database. +This is a good practice that will not only make your queries faster, +but also make it impossible to store incoherent data. +You should use meaningful natural [primary keys](https://en.wikipedia.org/wiki/Primary_key) for your tables +and resort to surrogate keys (such as auto-incremented integer ids) only when the data is not naturally keyed. +Relationships between tables should be explicitly represented by [foreign keys](https://en.wikipedia.org/wiki/Foreign_key). + +```sql +-- Products table, naturally keyed by catalog_number +CREATE TABLE product ( + catalog_number VARCHAR(20) PRIMARY KEY, + name TEXT NOT NULL, + price DECIMAL(10,2) NOT NULL +); + +-- Sales table: natural key = (sale_date, store_id, transaction_number) +-- composite primary key used since no single natural attribute alone uniquely identifies a sale +CREATE TABLE sale ( + sale_date DATE NOT NULL, + store_id VARCHAR(10) NOT NULL, + transaction_number INT NOT NULL, + product_catalog_number VARCHAR(20) NOT NULL, + quantity INT NOT NULL CHECK (quantity > 0), + PRIMARY KEY (sale_date, store_id, transaction_number), + FOREIGN KEY (product_catalog_number) REFERENCES product(catalog_number), + FOREIGN KEY (store_id) REFERENCES store(store_id) +); +``` + +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 +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. + +You also need to use the right [data types](https://en.wikipedia.org/wiki/Data_type) for your columns, +otherwise you will waste a lot of space and time converting data at query time. +See [postgreSQL data types](https://www.postgresql.org/docs/current/datatype.html), +[MySQL data types](https://dev.mysql.com/doc/refman/8.0/en/data-types.html), +[Microsoft SQL Server data types](https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-types-transact-sql?view=sql-server-ver16), +[SQLite data types](https://www.sqlite.org/datatype3.html). + +[Denormalization](https://en.wikipedia.org/wiki/Denormalization) can be introduced +only after you have already normalized your data, and is often not required at all. + +### Use views + +Querying normalized views can be cumbersome. +`select store_name, sum(paid_eur) from sale group by store_name` +is more readable than + +```sql +select store.name, sum(sale.paid_eur) +from sales + inner join stores on sale.store_id = store.store_id +group by store_name +``` + +To work around that, you can create views that contain +useful table joins so that you do not have to duplicate them in all your queries: + +```sql +create view enriched_sales as +select sales.sales_eur, sales.client_id, store.store_name +from sales +inner join store +``` + +#### Materialized views + +Some analytical queries just have to compute aggregated statistics over large quantities of data. +For instance, you might want to compute the total sales per store, or the total sales per product. +These queries are slow to compute when there are many rows, and you might not want to run them on every request. +You can use [materialized views](https://en.wikipedia.org/wiki/Materialized_view) to cache the results of these queries. +Materialized views are views that are stored as regular tables in the database. + +Depending on the database, you might have to refresh the materialized view manually. +You can either refresh the view manually from inside your sql pages when you detect they are outdated, +or write an external script to refresh the view periodically. + +```sql +create materialized view total_sales_per_store as +select store_name, sum(sales_eur) as total_sales +from sales +group by store_name; +``` + +### Use database indices + +When a query on a large table uses non-primary column in a `WHERE`, `GROUP BY`, `ORDER BY`, or `JOIN`, +you should create an [index](https://en.wikipedia.org/wiki/Database_index) on that column. +When multiple columns are used in the query, you should create a composite index on those columns. +When creating a composite index, the order of the columns is important. +The most frequently used columns should be first. + +```sql +create index idx_sales_store_date on sale (store_id, sale_date); -- useful for queries that filter by "store" or by "store and date" +create index idx_sales_product_date on sale (product_id, sale_date); +create index idx_sales_store_product_date on sale (store_id, product_id, sale_date); +``` + +Indexes are updated automatically when the table is modified. +They slow down the insertion and deletion of rows in the table, +but speed up the retrieval of rows in queries that use the indexed columns. + +### Query performance debugging + +When a query is slow, you can use the `EXPLAIN` keyword to see how the database will execute the query. +Just add `EXPLAIN` before the query you want to analyze. + +On PostgreSQL, you can use a tool like [explain.dalibo.com](https://explain.dalibo.com/) to visualize the query plan. + +What to look for: + - Are indexes used? You should see references to the indices you created. + - Are full table scans used? Large tables should never be scanned. + - Are expensive operations used? Such as sorting, hashing, bitmap index scans, etc. + - Are operations happening in the order you expected them to? Filtering large tables should come first. + +### Vacuum your database regularly + +On PostgreSQL, you can use the [`VACUUM`](https://www.postgresql.org/docs/current/sql-vacuum.html) command to garbage-collect and analyze a database. + +On MySQL, you can use the [`OPTIMIZE TABLE`](https://dev.mysql.com/doc/refman/8.0/en/optimize-table.html) command to reorganize it on disk and make it faster. +On Microsoft SQL Server, you can use the [`DBCC DBREINDEX`](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-dbreindex-transact-sql?view=sql-server-ver17) command to rebuild the indexes. +On SQLite, you can use the [`VACUUM`](https://www.sqlite.org/lang_vacuum.html) command to garbage-collect and analyze the database. + +### Use the right database engine + +If the amount of data you are working with is very large, does not change frequently, and you need to run complex queries on it, +you could use a specialized analytical database such as [ClickHouse](https://clickhouse.com/) or [DuckDB](https://duckdb.org/). +Such databases can be used with SQLPage by using their [ODBC](https://en.wikipedia.org/wiki/Open_Database_Connectivity) drivers. + +### Database-specific performance recommendations + + - [PostgreSQL "Performance Tips"](https://www.postgresql.org/docs/current/performance-tips.html) + - [MySQL optimization guide](https://dev.mysql.com/doc/refman/8.0/en/optimization.html) + - [Microsoft SQL Server "Monitor and Tune for Performance"](https://learn.microsoft.com/en-us/sql/relational-databases/performance/monitor-and-tune-for-performance?view=sql-server-ver17) + - [SQLite query optimizer overview](https://www.sqlite.org/optoverview.html) + +## 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. +This section will help you minimize the impact to your users. + +### Order matters + +SQLPage executes the queries in your `.sql` files in order. +It does not start executing a query before the previous one has returned all its results. +So, if you have to execute a slow query, put it as far down in the page as possible. + +#### No heavy computation before the shell + +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. +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, +and it will be rendered before SQLPage even finishes acquiring a database connection. + +#### Set variables just above their first usage + +For the reasons explained above, you should avoid defining all variables at the top of your sql file. +Instead, define them just above their first usage. + +### Avoid recomputing the same data multiple times + +Often, a single page will require the same pieces of data in multiple places. +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 +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) + from products where id = $product_id +); + +select 'alert' as component, 'Product' as title, $product->>'name' as description; +``` + +#### Reusing a large query result set + +You may have a page that lets the user filter a large dataset by many different criteria, +and then displays multiple charts and tables based on the filtered data. + +In this case, store the filtered data in a temporary table and then reuse it in multiple places. + +```sql +drop table if exists filtered_products; +create temporary table filtered_products as +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 +from filtered_products; + +select 'list' as component; +select name as title from filtered_products; +``` + +### Reduce the number of queries + +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 +[`UNION ALL`](https://en.wikipedia.org/wiki/Set_operations_(SQL)#UNION_operator). + +```sql +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 +union all +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 +with the `embed` attribute to load data lazily. +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. + +### Database connections + +SQLPage uses connection pooling: it keeps multiple database connections opened, +and reuses them for consecutive requests. When it does not receive requests for a long time, +it closes idle connection. When it receives many requests, it opens new connection, +but never more than the value specified by `max_database_pool_connections` in its +[configuration](/configuration#max_database_pool_connections). +You can increase the value of that parameter if your website has many concurrent users and your +database is configured to allow opening many simultaneous connections. + +### SQLPage performance debugging + +When `environment` is set to `development` in its [configuration](/configuration#environment), +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. + +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/content/blog/sqlpage-v0-17.md b/examples/official-site/content/blog/sqlpage-v0-17.md new file mode 100644 index 000000000..19ac4d400 --- /dev/null +++ b/examples/official-site/content/blog/sqlpage-v0-17.md @@ -0,0 +1,169 @@ +--- +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. + +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. + +## Uploads + +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 + +```sql +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 +(customizable with `TMPDIR` on linux). +You can access the temporary file path with +the new [`sqlpage.uploaded_file_path`](/functions.sql?function=uploaded_file_path#function) function. + +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'); +``` + +or you can store it directly in a database table with the new +[`sqlpage.read_file_as_data_url`](https://sql-page.com/functions.sql?function=read_file_as_data_url#function) and +[`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; +``` + +The maximum size of uploaded files is configurable with the [`max_uploaded_file_size`](/configuration#max_uploaded_file_size) +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) +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. +But it will also work with any other database as well, by +parsing the CSV locally and emulating the same behavior with simple `INSERT` statements. + +#### `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; +``` + +#### `bulk_user_import.sql` +```sql +-- 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 + +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 + +-- 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; +``` + +### New functions + +#### Handle uploaded files + + - [`sqlpage.uploaded_file_path`](https://sql-page.com/functions.sql?function=uploaded_file_path#function) to get the temprary local path of a file uploaded by the user. This path will be valid until the end of the current request, and will be located in a temporary directory (customizable with `TMPDIR`). You can use [`sqlpage.exec`](https://sql-page.com/functions.sql?function=exec#function) to operate on the file, for instance to move it to a permanent location. + - [`sqlpage.uploaded_file_mime_type`](https://sql-page.com/functions.sql?function=uploaded_file_mime_type#function) to get the type of file uploaded by the user. This is the MIME type of the file, such as `image/png` or `text/csv`. You can use this to easily check that the file is of the expected type before storing it. + + The new [*Image gallery* example](https://github.com/sqlpage/SQLPage/tree/main/examples/image%20gallery%20with%20user%20uploads) +in the official repository shows how to use these functions to create a simple image gallery with user uploads. + +#### Read files + +These new functions are useful to read the contents of a file uploaded by the user, +but can also be used to read any file on the computer where SQLPage is running: + + - [`sqlpage.read_file_as_text`](https://sql-page.com/functions.sql?function=read_file_as_text#function) reads the contents of a file on the server and returns a text string. + - [`sqlpage.read_file_as_data_url`](https://sql-page.com/functions.sql?function=read_file_as_data_url#function) reads the contents of a file on the server and returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs). This is useful to embed images directly in web pages, or make link + +## HTTPS + +This is the other big feature of this release: SQLPage now supports HTTPS ! +Until now, if you wanted to use HTTPS with SQLPage, you had to put it behind a +*reverse proxy*, which is what the official documentation website does. + +This required a lot of manual configuration +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. + +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. +Then set the `https_domain` configuration parameter to `yourdomain.com` in your [`sqlpage.json` configuration file](./configuration.md). + +```json +{ + "https_domain": "my-cool-website.com" +} +``` + +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, +and does not even need to listen on port 80 to do so. + +## SQL parser improvements + +SQLPage needs to parse SQL queries to be able to bind the right parameters to them, +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. + +### JSON functions in MS SQL Server + +SQLPage now supports the [`FOR JSON` syntax](https://learn.microsoft.com/en-us/sql/relational-databases/json/format-query-results-as-json-with-for-json-sql-server?view=sql-server-ver16&tabs=json-path) in MS SQL Server. + +This unlocks a lot of new possibilities, that were previously only available in other databases. + +This is particularly interesting to build complex menus with the `shell` component, +to build multiple-answer select inputs with the `form` component, +and to create JSON APIs. + +### Other sql syntax enhancements + + - SQLPage now supports the custom `CONVERT` expression syntax for MS SQL Server, and the one for MySQL. + - The `VARCHAR(MAX)` type in MS SQL Server new works. We now use it for all variables bound as parameters to your SQL queries (we used to use `VARCHAR(8000)` before). + - `INSERT INTO ... DEFAULT VALUES ...` is now parsed correctly. + +## Other news + + - Dates and timestamps returned from the database are now always formatted in ISO 8601 format, which is the standard format for dates in JSON. This makes it easier to use dates in SQLPage. + - 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). + - 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 in tabler 42](https://github.com/tabler/tabler-icons/assets/1282324/00856af9-841d-4aa9-995d-121c7ddcc005) 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/content/blog/sqlpage-website-update.md b/examples/official-site/content/blog/sqlpage-website-update.md new file mode 100644 index 000000000..fd583218e --- /dev/null +++ b/examples/official-site/content/blog/sqlpage-website-update.md @@ -0,0 +1,33 @@ +--- +title: SQLPage website update +date: '2024-05-01' +icon: browser +summary: Performance, security, and new features +--- + +Today is may day, and we are happy to announce that the SQLPage website has been updated with new contents. + +## Homepage + +The [homepage](/) has been updated to include prominent information about commonly asked questions, +such as the [security guarantees](/safety.sql) of SQLPage, and the [performance](/performance.sql) of SQLPage applications. + +## Performance of SQLPage applications + +We now have a [detailled explanation of the performance of SQLPage applications](/performance.sql) on the website. +It explains why and how SQLPage applications are often faster than equivalent applications written in other frameworks. + +## Single-Sign-On + +Since SQLPage v0.20.3, SQLPage can natively make requests to external HTTP APIs with [the `fetch` function](/documentation.sql#fetch), +which opens the door to many new possibilities. + +An example of this is the [**SSO demo**](https://github.com/sqlpage/SQLPage/tree/main/examples/single%20sign%20on), +which demonstrates how to use SQLPage to authenticate users on a website using a third-party authentication service, +such as Google, Facebook, an enterprise identity provider using [OIDC](https://openid.net/connect/), +or an academic institution using [CAS](https://apereo.github.io/cas/). + +## New architecture diagram + +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). diff --git a/examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md b/examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md new file mode 100644 index 000000000..32aa40cb8 --- /dev/null +++ b/examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md @@ -0,0 +1,172 @@ +--- +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: + +- Did the request wait for a database connection? +- Which SQL file was executed? +- Which query took the longest? +- Did the delay start in SQLPage, in the reverse proxy, or in the database? + +SQLPage now supports [OpenTelemetry](https://opentelemetry.io/), the standard way to emit distributed traces. Combined with Grafana, Tempo, Loki, and an OpenTelemetry collector, this gives you a detailed timeline of each request and lets you jump directly from logs to traces. + +If you want a ready-to-run demo, see the [OpenTelemetry + Grafana example](https://github.com/sqlpage/SQLPage/tree/main/examples/telemetry), which this article is based on. + +## Tracing a request across services + +With tracing enabled, one HTTP request becomes a tree of timed operations called spans. In a typical SQLPage app, you will see something like: + +```text +[nginx] GET /todos + └─ [sqlpage] GET /todos + └─ [sqlpage] SQL website/todos.sql + ├─ db.pool.acquire + └─ db.query +``` + +This is immediately useful for: + +- Debugging slow pages by seeing exactly which query consumed the time +- Detecting connection pool pressure by measuring time spent in `db.pool.acquire` +- Following one request end-to-end from the reverse proxy to SQLPage to PostgreSQL + +Tracing is especially helpful in SQLPage because one request often maps cleanly to one SQL file. That makes traces easy to interpret even when you are not used to application performance tooling. + +## Run the example stack + +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: + +```bash +docker compose up --build +``` + +That stack starts: + +- nginx as the reverse proxy +- SQLPage +- PostgreSQL +- an OpenTelemetry collector +- Grafana Tempo for traces +- Grafana Loki for logs +- Promtail for log shipping +- Grafana for visualization + +Then: + +1. Open [http://localhost](http://localhost) and use the sample todo application. +2. Open [http://localhost:3000](http://localhost:3000) to access Grafana. +3. Inspect recent traces and logs from the default dashboard. +4. Open a trace to see the full span waterfall for a single request. + +This setup is useful both as a demo and as a reference architecture for production deployments. + +## Enabling tracing in SQLPage + +Tracing is built into SQLPage. There is no plugin to install and no SQLPage-specific tracing configuration file to write. + +You only need to set standard OpenTelemetry environment variables before starting SQLPage: + +```bash +export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318" +export OTEL_SERVICE_NAME="sqlpage" +sqlpage +``` + +The `OTEL_EXPORTER_OTLP_ENDPOINT` variable tells SQLPage where to send traces. +The `OTEL_SERVICE_NAME` variable controls how the service appears in your tracing backend. + +If `OTEL_EXPORTER_OTLP_ENDPOINT` is not set, SQLPage falls back to normal logging and tracing stays disabled. + +## SQLPage spans + +The most useful spans emitted by SQLPage are: + +- The HTTP request span, with attributes such as method, path, status code, and user agent +- The SQL file execution span, showing which `.sql` file handled the request +- The `db.pool.acquire` span, showing time spent waiting for a database connection +- The `db.query` span, containing the SQL statement and database system + +In practice, that means you can answer questions like: + +- Is the page slow because the SQL itself is slow? +- Is the request queued because the connection pool is exhausted? +- Is the delay happening before SQLPage even receives the request? + +This is much more actionable than a single request duration number. + +## Logs and traces together + +Tracing is even more useful when logs and traces are connected. + +In the example stack, SQLPage writes request access logs to stdout and diagnostic logs to stderr. The OpenTelemetry Collector forwards both streams to Loki, and Grafana lets you move from a log line to the matching trace using the trace id. This makes it possible to start from an error log and immediately inspect the full request timeline. + +That workflow is often the difference between guessing and knowing. + +## PostgreSQL correlation + +SQLPage also propagates trace context to PostgreSQL through the connection `application_name`. +This makes it possible to correlate live PostgreSQL activity or database logs with the trace that triggered it. + +For example, inspecting `pg_stat_activity` can show which trace is attached to a running query: + +```sql +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. + +## A practical debugging example + +Suppose users report that a page occasionally becomes slow under load. + +With tracing enabled, you might see that: + +- the HTTP span is long +- the SQL file execution span is also long +- the `db.query` span is short +- but `db.pool.acquire` takes several hundred milliseconds + +That immediately tells you the database query itself is not the problem. The real issue is contention on the connection pool. You can then increase `max_database_pool_connections`, reduce concurrent load, or review long-running requests that keep connections busy. + +Without tracing, this kind of diagnosis usually requires guesswork. + +## Deployment options + +The example uses Grafana Tempo and Loki, but SQLPage is not tied to a single backend. Because it emits standard OTLP traces, you can also send data to: + +- Jaeger +- Grafana Cloud +- Datadog +- Honeycomb +- New Relic +- Axiom + +In small setups, SQLPage can often send traces directly to the backend. In larger deployments, placing an OpenTelemetry collector in the middle is usually better because it centralizes routing, batching, and authentication. + +## Production tracing use cases + +Tracing is particularly valuable when: + +- you are running SQLPage behind a reverse proxy +- several SQL files participate in user-facing workflows +- you want to understand production latency, not just local development behavior +- you need a shared debugging tool for developers and operators + +If your application is already important enough to monitor, it is important enough to trace. + +## Conclusion + +SQLPage already makes the application logic easy to inspect because it lives in SQL files. Tracing extends that visibility to runtime behavior. + +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/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/package-lock.json b/package-lock.json index d6d8f9697..4da34788f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,8 @@ "@types/leaflet": "^1.9.22", "@types/node": "^26.6.6", "rolldown": "^1.3.1", - "typescript": "^7.0.2" + "typescript": "^7.0.2", + "yaml": "2.9.1" } }, "node_modules/@biomejs/biome": { @@ -1175,6 +1176,22 @@ "dev": true, "license": "MIT" }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "tests/end-to-end": { "version": "1.0.0", "license": "ISC", diff --git a/package.json b/package.json index 752f16714..c18b41ee6 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,8 @@ "@types/leaflet": "^1.9.22", "@types/node": "^26.6.6", "rolldown": "^1.3.1", - "typescript": "^7.0.2" + "typescript": "^7.0.2", + "yaml": "2.9.1" }, "workspaces": [ "tests/end-to-end" diff --git a/scripts/site-content.mjs b/scripts/site-content.mjs new file mode 100644 index 000000000..8b024322c --- /dev/null +++ b/scripts/site-content.mjs @@ -0,0 +1,304 @@ +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { basename, join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { fileURLToPath } from "node:url"; +import { parse } from "yaml"; + +const defaultContent = fileURLToPath( + new URL("../examples/official-site/content/", import.meta.url), +); + +function read(path) { + return readFileSync(path, "utf8"); +} + +function at(path, callback) { + try { + return callback(); + } catch (error) { + throw new Error(`${path}: ${error.message}`, { cause: error }); + } +} + +function fields(object, allowed) { + if (!object || typeof object !== "object" || Array.isArray(object)) { + throw new Error("Expected a mapping of field names to values"); + } + for (const key of Object.keys(object)) { + if (!allowed.includes(key)) throw new Error(`Unknown field "${key}"`); + } + return object; +} + +function text(value, name) { + if (typeof value !== "string" || !value.trim()) { + throw new Error(`Expected text in "${name}"`); + } + return value; +} + +function list(value, name) { + if (!Array.isArray(value)) throw new Error(`Expected a list in "${name}"`); + return value; +} + +function markdownFiles(dir, visit, parseHeader = parse) { + for (const name of readdirSync(dir) + .filter((s) => s.endsWith(".md")) + .sort()) { + const path = join(dir, name); + at(path, () => { + const file = read(path).replaceAll("\r\n", "\n"); + const match = + file.startsWith("---\n") && + /^---\n([\s\S]*?)^---[ \t]*(?:\n|$)/m.exec(file); + if (file.startsWith("---\n") && !match) + throw new Error("Unclosed YAML front matter"); + const meta = match ? (parseHeader(match[1]) ?? {}) : {}; + const body = file.slice(match ? match[0].length : 0).trim(); + visit(basename(name, ".md"), meta, body); + }); + } +} + +function exampleHeader(header) { + const meta = parse(header, { + mapAsMap: true, + intAsBigInt: true, + stringKeys: true, + }); + return meta instanceof Map ? Object.fromEntries(meta) : meta; +} + +// A JS object would reorder numeric column names, and a JS Number would +// round 64-bit integers. The example's JSON determines the SQL shown on the site. +function exampleJson(value) { + if (Array.isArray(value)) return `[${value.map(exampleJson).join(",")}]`; + if (value instanceof Map) { + return `{${Array.from(value, ([key, v]) => `${JSON.stringify(key)}:${exampleJson(v)}`).join(",")}}`; + } + if (typeof value === "bigint") return value.toString(); + if (typeof value === "number" && !Number.isFinite(value)) + throw new Error("Example numbers must be finite"); + return JSON.stringify(value); +} + +function schemaType(schema) { + if (schema.enum) + return schema.enum.map((value) => JSON.stringify(value)).join(" | "); + if (schema.anyOf) return schema.anyOf.map(schemaType).join(" or "); + const types = Array.isArray(schema.type) ? schema.type : [schema.type]; + return types + .map((type) => { + if (type === "array") return `${schemaType(schema.items)}[]`; + if (type === "integer" || type === "number") { + if (schema.minimum !== undefined && schema.maximum !== undefined) + return `${type} (${schema.minimum} to ${schema.maximum})`; + if (schema.minimum !== undefined) + return `${type} (≥ ${schema.minimum})`; + if (schema.maximum !== undefined) + return `${type} (≤ ${schema.maximum})`; + } + return text(type, "type"); + }) + .join(" or "); +} + +function configDefault(schema) { + if (schema["x-default-description"]) return schema["x-default-description"]; + if (!Object.hasOwn(schema, "default")) return null; + const value = JSON.stringify(schema.default); + const longestTick = Math.max( + 0, + ...(value.match(/`+/g) ?? []).map((s) => s.length), + ); + const delimiter = "`".repeat(longestTick + 1); + return `${delimiter}${value}${delimiter}`; +} + +export function buildDocumentationSeed(schema, content = defaultContent) { + const db = new DatabaseSync(":memory:"); + const statements = []; + + function sqlFile(name) { + const path = join(import.meta.dirname, "site", name); + at(path, () => { + const sql = read(path); + db.exec(sql); + statements.push(sql); + }); + } + + function insert(table, record) { + const columns = Object.keys(record).map((name) => `"${name}"`); + const values = Object.values(record).map((v) => v ?? null); + if (values.some((v) => typeof v === "string" && v.includes("\0"))) { + throw new Error(`NUL character in ${table}`); + } + const query = db.prepare( + `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${values.map(() => "?").join(", ")});`, + ); + query.run(...values); + // SQLite quotes the exact same values for SQLPage's startup migration. + statements.push(query.expandedSQL); + } + + function collection(name, table, columns) { + const path = join(content, `${name}.yaml`); + at(path, () => { + for (const record of list(parse(read(path)), name)) { + fields(record, columns); + for (const column of columns) { + if (!(column in record)) throw new Error(`Missing "${column}"`); + } + insert(table, record); + } + }); + } + + function parameter(record) { + fields(record, ["name", "type", "description", "required"]); + if (record.required !== undefined && typeof record.required !== "boolean") { + throw new Error(`Expected a boolean in "${record.name}.required"`); + } + return { + name: text(record.name, "name"), + type: text(record.type, "type"), + description_md: text(record.description, "description"), + optional: record.required ? 0 : 1, + }; + } + + function references(kind, shared) { + const directory = join(content, kind); + const component = kind === "components"; + const extra = component ? ["top", "row"] : ["parameters", "return_type"]; + for (const entry of readdirSync(directory, { withFileTypes: true })) { + if ( + entry.isDirectory() && + !existsSync(join(directory, `${entry.name}.md`)) + ) { + throw new Error( + `${join(directory, entry.name)} has no corresponding reference ${entry.name}.md`, + ); + } + } + markdownFiles(directory, (name, meta, body) => { + fields(meta, ["icon", "since", "category", "summary", ...extra]); + const common = { + name, + icon: meta.icon, + introduced_in_version: meta.since, + catalog_category: meta.category, + catalog_summary: meta.summary, + }; + if (!component) { + insert("sqlpage_functions", { + ...common, + description_md: body, + return_type: meta.return_type, + }); + for (const [i, p] of list( + meta.parameters ?? [], + "parameters", + ).entries()) { + insert("sqlpage_function_parameters", { + function: name, + index: i + 1, + ...parameter(p), + }); + } + return; + } + insert("component", { ...common, description: body }); + for (const level of ["top", "row"]) { + for (let p of list(meta[level] ?? [], level)) { + if (typeof p === "string") { + if (!Object.hasOwn(shared, p)) + throw new Error(`Unknown shared parameter "${p}"`); + p = shared[p]; + } + insert("parameter", { + component: name, + top_level: level === "top" ? 1 : 0, + ...parameter(p), + }); + } + } + const examples = join(directory, name, "examples"); + if (existsSync(examples)) { + markdownFiles( + examples, + (_, example, description) => { + fields(example, ["rows"]); + const rows = + example.rows === undefined ? null : list(example.rows, "rows"); + if (rows?.some((row) => !(row instanceof Map))) { + throw new Error("Expected objects in example rows"); + } + insert("example", { + component: name, + description, + properties: rows === null ? null : exampleJson(rows), + }); + }, + exampleHeader, + ); + } + }); + } + + try { + sqlFile("schema.sql"); + collection("categories", "reference_category", [ + "id", + "title", + "sort_order", + ]); + collection("guides", "guide", [ + "title", + "link", + "description", + "sort_order", + ]); + collection("projects", "example_cards", [ + "title", + "folder", + "db_engine", + "description", + ]); + const sharedPath = join(content, "shared-parameters.yaml"); + const shared = at(sharedPath, () => { + const entries = parse(read(sharedPath)); + for (const field of Object.values(entries)) parameter(field); + return entries; + }); + references("components", shared); + references("functions", shared); + markdownFiles(join(content, "blog"), (_, meta, body) => { + fields(meta, ["title", "date", "icon", "summary", "external_url"]); + insert("blog_posts", { + title: text(meta.title, "title"), + created_at: text(meta.date, "date"), + icon: text(meta.icon, "icon"), + description: text(meta.summary, "summary"), + external_url: meta.external_url, + content: body || null, + }); + }); + for (const [name, option] of Object.entries(schema.properties)) { + at(`Configuration option ${name}`, () => + insert("config_option", { + name, + type: schemaType(option), + default_md: configDefault(option), + description_md: text(option.description, "description"), + }), + ); + } + sqlFile("search.sql"); + return `${statements.join("\n")}\n`; + } finally { + db.close(); + } +} diff --git a/scripts/site/schema.sql b/scripts/site/schema.sql new file mode 100644 index 000000000..2f8999ed8 --- /dev/null +++ b/scripts/site/schema.sql @@ -0,0 +1,221 @@ +CREATE TABLE reference_category ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL, + sort_order INTEGER 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 +); + +CREATE TABLE config_option ( + name TEXT PRIMARY KEY, + type TEXT NOT NULL, + default_md TEXT, + description_md 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); + +-- The authentication example. +create table users ( + username text primary key, + password_hash text not null, + role text not null +); + +-- Create example users with trivial passwords for the website's demo +insert into users (username, password_hash, role) +values + ('admin', '$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$ROyXNhK0utkzTA', 'admin'), -- password: admin + ('user', '$argon2i$v=19$m=8,t=1,p=1$YWFhYWFhYWE$qsrWdjgl96ooYw', 'user'); -- password: user +-- (the password hashes can be generated using the `sqlpage.hash_password` function) + +create table user_sessions ( + session_token text primary key, + username text not null references users(username), + created_at timestamp not null default current_timestamp +); + +-- Sample data for the landing page's live SQLPage components. +CREATE TABLE customers ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + plan TEXT NOT NULL, + status TEXT NOT NULL, + seats INTEGER NOT NULL +); +INSERT INTO customers VALUES + (1, 'Acme Corp', 'Pro', 'Active', 12), + (2, 'Globex', 'Team', 'Active', 8), + (3, 'Initech', 'Free', 'Trial', 3), + (4, 'Umbrella', 'Pro', 'Late', 20); + +CREATE TABLE tickets ( + id INTEGER PRIMARY KEY, + customer_id INTEGER NOT NULL REFERENCES customers(id), + resolved_at TEXT NOT NULL +); +WITH RECURSIVE ticket(id) AS ( + SELECT 1 UNION ALL SELECT id + 1 FROM ticket WHERE id < 42 +) +INSERT INTO tickets +SELECT id, 1 + (id % 4), + CASE WHEN id <= 18 THEN '2026-09-28 14:30:00' + WHEN id <= 32 THEN '2026-09-29 10:15:00' + ELSE '2026-09-30 16:45:00' END +FROM ticket; + +CREATE TABLE customer_feedback ( + id INTEGER PRIMARY KEY, + customer_id INTEGER NOT NULL REFERENCES customers(id), + satisfied BOOLEAN NOT NULL +); +WITH RECURSIVE response(id) AS ( + SELECT 1 UNION ALL SELECT id + 1 FROM response WHERE id < 50 +) +INSERT INTO customer_feedback +SELECT id, 1 + (id % 4), id <> 50 FROM response; + +CREATE TABLE profiles ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + team TEXT NOT NULL +); +INSERT INTO profiles VALUES (1, 'Ada', 'SQL builders'); diff --git a/scripts/site/search.sql b/scripts/site/search.sql new file mode 100644 index 000000000..23d6db026 --- /dev/null +++ b/scripts/site/search.sql @@ -0,0 +1,28 @@ +CREATE VIRTUAL TABLE documentation_fts USING fts5( + title, description, example_source, + page UNINDEXED, parameters UNINDEXED, fragment UNINDEXED +); + +INSERT INTO documentation_fts(title, description, page) +SELECT title, description, link FROM guide +UNION ALL +SELECT CASE kind WHEN 'component' THEN name || ' component' ELSE 'sqlpage.' || name || '()' END, + description_md, link FROM reference_entry; + +INSERT INTO documentation_fts(title, description, page, fragment) +SELECT CASE p.kind WHEN 'component' THEN p.entry || ' component: ' || p.name + ELSE 'sqlpage.' || p.entry || '(' || p.name || ')' END, + p.description_md, e.link, p.anchor +FROM reference_parameter AS p +JOIN reference_entry AS e ON e.kind = p.kind AND e.name = p.entry; + +INSERT INTO documentation_fts(title, description, example_source, page, fragment) +SELECT component || ' component example', description, properties, e.link, 'example-' || example_number +FROM example_with_source AS x +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/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/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/site_content.spec.ts b/tests/js/site_content.spec.ts new file mode 100644 index 000000000..845949744 --- /dev/null +++ b/tests/js/site_content.spec.ts @@ -0,0 +1,107 @@ +import assert from "node:assert/strict"; +import { + mkdirSync, + mkdtempSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import test from "node:test"; +import { buildDocumentationSeed } from "../../scripts/site-content.mjs"; + +test("authored examples keep their order, quoting, and optional previews in the startup migration", (t) => { + const content = mkdtempSync(join(tmpdir(), "sqlpage-content-")); + t.after(() => rmSync(content, { recursive: true, force: true })); + for (const dir of ["components", "functions", "blog"]) + mkdirSync(join(content, dir)); + for (const manifest of ["categories", "guides", "projects"]) { + writeFileSync(join(content, `${manifest}.yaml`), "[]\n"); + } + writeFileSync( + join(content, "shared-parameters.yaml"), + "id: {name: id, type: TEXT, description: HTML id}\n", + ); + const topic = join(content, "components", "demo.md"); + writeFileSync(topic, "---\ntop: [id]\n---\n\nA contributor's demo.\n"); + const examples = join(content, "components", "demo", "examples"); + mkdirSync(examples, { recursive: true }); + writeFileSync( + join(examples, "02-result.md"), + `--- +rows: + - component: text + contents: "Reader's choice" + "2": 9007199254740993 + "1": 42 +--- +Result +`, + ); + writeFileSync(join(examples, "01-notes.md"), "Just a note.\n"); + const schema = { + properties: { + toggle: { type: "boolean", default: false, description: "Turn this on." }, + recipient: { type: ["string", "null"], description: "Recipient." }, + count: { + type: "integer", + minimum: 0, + maximum: 8, + "x-default-description": "Depends on the database.", + description: "Limit.", + }, + }, + }; + const db = new DatabaseSync(":memory:"); + t.after(() => db.close()); + const seed = buildDocumentationSeed(schema, content); + assert.equal(seed, buildDocumentationSeed(schema, content)); + db.exec(seed); + assert.deepEqual( + db + .prepare( + "SELECT description, source FROM example_with_source WHERE component = 'demo' ORDER BY example_number", + ) + .all() + .map((row) => [row.description, row.source]), + [ + ["Just a note.", null], + [ + "Result", + `select\n 'text' as "component",\n 'Reader''s choice' as "contents",\n 9007199254740993 as "2",\n 42 as "1";`, + ], + ], + ); + assert.deepEqual( + db + .prepare("SELECT name, type, default_md FROM config_option ORDER BY name") + .all() + .map((row) => [row.name, row.type, row.default_md]), + [ + ["count", "integer (0 to 8)", "Depends on the database."], + ["recipient", "string or null", null], + ["toggle", "boolean", "`false`"], + ], + ); + assert.equal( + db + .prepare( + "SELECT fragment FROM documentation_fts WHERE documentation_fts MATCH 'recipient' AND page = '/configuration'", + ) + .get()?.fragment, + "recipient", + ); + + writeFileSync(topic, "---\ntop: [missing]\n---\nExample.\n"); + assert.throws( + () => buildDocumentationSeed(schema, content), + /demo\.md: Unknown shared parameter "missing"/, + ); + renameSync(topic, join(content, "components", "moved.md")); + assert.throws( + () => buildDocumentationSeed(schema, content), + /no corresponding reference demo\.md/, + ); +}); diff --git a/tests/js/tsconfig.json b/tests/js/tsconfig.json index 752910d94..f9b84cfc8 100644 --- a/tests/js/tsconfig.json +++ b/tests/js/tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../tsconfig.json", "compilerOptions": { "lib": ["es2022"], + "allowJs": true, "module": "nodenext", "moduleResolution": "nodenext", "types": ["node"]