diff --git a/examples/official-site/README.md b/examples/official-site/README.md index e26e8af7d..cd8912446 100644 --- a/examples/official-site/README.md +++ b/examples/official-site/README.md @@ -30,7 +30,7 @@ live examples using SQLPage's stock theme. For example, visit Write posts in `content/blog/` as Markdown with YAML metadata: `title`, `date` (quoted as `YYYY-MM-DD`), `icon`, and `summary`. For a link to a post elsewhere, set `external_url` and omit the body. The title is the public URL key, so keep it -when editing an existing post. Older posts are still in the SQL migrations. +when editing an existing post. ## Landing page diff --git a/examples/official-site/sqlpage/migrations/64_blog_routing.sql b/examples/official-site/content/blog/file-based-routing-in-sqlpage.md similarity index 73% rename from examples/official-site/sqlpage/migrations/64_blog_routing.sql rename to examples/official-site/content/blog/file-based-routing-in-sqlpage.md index 3467dc7fa..d1bc0c417 100644 --- a/examples/official-site/sqlpage/migrations/64_blog_routing.sql +++ b/examples/official-site/content/blog/file-based-routing-in-sqlpage.md @@ -1,12 +1,10 @@ +--- +title: File-based routing in SQLPage +date: '2025-07-28' +icon: route +summary: Understanding how SQLPage maps URLs to files and handles errors +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'File-based routing in SQLPage', - 'Understanding how SQLPage maps URLs to files and handles errors', - 'route', - '2025-07-28', - ' SQLPage uses a simple file-based routing system that maps URLs directly to SQL files in your project directory. No complex configuration is needed. Just create files and they become accessible endpoints. @@ -16,7 +14,7 @@ This guide explains how SQLPage resolves URLs, handles different file types, and ### 1. Site Prefix Handling -If you''ve configured a [`site_prefix`](/your-first-sql-website/nginx) in your settings, +If you've configured a [`site_prefix`](/your-first-sql-website/nginx) in your settings, SQLPage will redirect all requests that do not start with the prefix to `/`. ### 2. Path Resolution Priority @@ -27,18 +25,18 @@ SQLPage will redirect all requests that do not start with the prefix to `/ This is the english translation of an article [originally published in French on linuxfr.org](https://linuxfr.org/news/comment-l-archeologie-entre-progressivement-dans-l-ere-du-logiciel-libre). -> It illustrates how SQLPage is used by non-developers +> It illustrates how SQLPage is used by non-developers # How archaeology is gradually entering the era of free software @@ -19,7 +17,7 @@ Archaeology has, since its beginnings, focused on cataloging, structuring and ar French archaeology is divided into two main branches: preventive archaeology, which intervenes during construction projects, and programmed archaeology, conducted on sites chosen to address research issues. Supervised by the Regional Archaeological Services of the Ministry of Culture, these activities are carried out by different organizations: public and private operators for preventive archaeology, and associations, CNRS or universities for programmed archaeology. The latter often mobilizes volunteers, especially students, offering them complementary practical training. -For the archaeologist, excavation is a tool, not an end in itself. What the archaeologist seeks is information. In essence, it''s about understanding the history of a site, its evolution, its inhabitants through the elements they left behind, whether it''s the ruins of their habitats, their crafts or their burials. This is all the more important as excavation is a destructive act, since the archaeologist dismantles his subject of study as the excavation progresses. +For the archaeologist, excavation is a tool, not an end in itself. What the archaeologist seeks is information. In essence, it's about understanding the history of a site, its evolution, its inhabitants through the elements they left behind, whether it's the ruins of their habitats, their crafts or their burials. This is all the more important as excavation is a destructive act, since the archaeologist dismantles his subject of study as the excavation progresses. To be exploited, archaeological information must be organized according to well-established principles. The first key concept is the sedimentary layer (*Stratigraphic Unit* - SU), which testifies to a human action or a natural phenomenon. The study of the arrangement of these layers reveals the chronology of the site, the succession of events that took place there. These layers can be grouped into archaeological *facts*: ditches, cellars, burials, are indeed groupings of layers that define a specific element. Finally, the objects found in these layers, or *artifacts*, are cataloged and identified by their layer of origin, providing crucial chronological and cultural indications. @@ -41,7 +39,7 @@ Based on this report, the publication of articles in specialized journals allows The use of numerous paper listings is a constant. These listings allow keeping up-to-date records of data in the form of inventory tables of layers, facts, surveys, photos, etc. Specific recording sheets are also used in many specialties of archaeology, such as funerary anthropology. -In the field, the unearthed elements are still, for a very large majority, drawn by hand, on tracing or graph paper, whether it''s a plan of remains or the numerous stratigraphic section drawings. This of course requires significant time, especially in the case of complex remains. +In the field, the unearthed elements are still, for a very large majority, drawn by hand, on tracing or graph paper, whether it's a plan of remains or the numerous stratigraphic section drawings. This of course requires significant time, especially in the case of complex remains. The use of electronic tacheometers, then differential GPS, has made it possible to do without tape measures, or grid systems, when excavating sites. Topographers, specifically trained, then began to intervene on site for the realization of general plans. The documentary collection obtained at the end of an excavation is particularly precious. These are the only elements that will allow reconstructing the history of the site, by crossing these data with the result of the studies carried out. The fear of the disappearance of this data, or its use by others due to a remarkable discovery, is a feeling often shared within the archaeological community. The archaeologist may feel like a custodian of this information, even expressing a feeling of possession that goes completely against the idea of shared and open science. The idea that opening up data is the best way to protect it is far from obvious. @@ -60,7 +58,7 @@ In post-excavation, paper documentation is still often a fundamental documentary Listings can be integrated into databases (most often proprietary such as MS Access, FileMaker or 4D) or spreadsheets. Many databases have been developed internally, locally, by archaeologists themselves. Only attributive, they have gradually networked and adapted to the medium, allowing consideration of use in the field, without this being widely deployed. -![Database](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/exemple_bdd_fmp.png) +![Database](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/exemple_bdd_fmp.png) > *Example of a database at the turn of the 2000s* All documentation drawn in the field is to be redrawn cleanly on digital media, in vector drawing software, very often Adobe Illustrator, sometimes Inkscape. @@ -98,7 +96,7 @@ Indeed, in a complete dematerialization process, the memory of the site is no lo Unfortunately, free software remains little used in our archaeological daily life, and proprietary software is often very well established. Free software still suffers today from preconceptions and a bad image within the archaeological community, which finds it more complicated, less pretty, less effective, etc. -However, free software has made a major incursion with the arrival of the free Geographic Information System (GIS) [QGIS](https://www.qgis.org/en/site/), which allowed installing a GIS on all the agents'' workstations of the institute and considering it as an analysis tool at the scale of an archaeological site. Through support and the implementation of an adequate training plan, many archaeologists have been trained in the use of the software within the Institute. +However, free software has made a major incursion with the arrival of the free Geographic Information System (GIS) [QGIS](https://www.qgis.org/en/site/), which allowed installing a GIS on all the agents' workstations of the institute and considering it as an analysis tool at the scale of an archaeological site. Through support and the implementation of an adequate training plan, many archaeologists have been trained in the use of the software within the Institute. QGIS has truly revolutionized our practices by allowing immediate interrogation of attributive data by spatial data (what is this remains I see on the plan?) or, conversely, locating remains by their attributive data (where is burial 525?). However, it is still very common to have on one side the attributive data in spreadsheets or proprietary databases, and spatial data in QGIS, with the interrogation of both relying on joins. @@ -126,11 +124,11 @@ The format of the database was originally SpatiaLite. But the mass of documentat Naturally, Badass has been coupled with a QGIS project already offering default styles, but also some queries or views commonly used during an archaeological study. A QGIS extension has been developed by several students to allow automatic generation of the project and database. -Here''s the translation into idiomatic American English, keeping the original formatting: +Here's the translation into idiomatic American English, keeping the original formatting: -## Entering Badass: The Bad''Mobil +## Entering Badass: The Bad'Mobil -The question of the system''s portability remained. QGIS is a resource-intensive software with an interface ill-suited for small screens, which are preferred for their portability in the field (phones and tablets). +The question of the system's portability remained. QGIS is a resource-intensive software with an interface ill-suited for small screens, which are preferred for their portability in the field (phones and tablets). Choosing to use a SpatiaLite or PostGIS database allowed us to consider a web interface from the start, which could then be used on any device. Initially, we considered developing in PHP/HTML/CSS with an Apache web server. However, this required having a web server and programming an entire interface. There were also some infrastructure questions to address: where to host it, how to finance it, and who would manage it all? @@ -143,7 +141,7 @@ SQLPage is based on an executable file which, when launched on a computer, turns Thus, the installation of the entire system is very simple and relies only on a file structure to be deployed on the server: the database, and a directory containing the SQLPage binary and the files making up the web pages. -By relying on the documentation (and occasionally asking questions to the software''s author), we were able to develop a very comprehensive interface on our own that meets our needs in the field. Named Bad''Mobil, the web interface provides access to all the attribute data recorded by archaeologists and now allows, thanks to the constant development of SQLPage, **to visualize spatial data**. Documentation produced during the excavation can also be consulted if the files (photos, scanned drawings, etc.) are placed in the right location in the file structure. The pages mainly consist of creation or modification forms, as well as tables listing already recorded elements. The visualization of geometry allows for spatial orientation in the field, particularly in complex excavation sites, and interaction with attribute data. +By relying on the documentation (and occasionally asking questions to the software's author), we were able to develop a very comprehensive interface on our own that meets our needs in the field. Named Bad'Mobil, the web interface provides access to all the attribute data recorded by archaeologists and now allows, thanks to the constant development of SQLPage, **to visualize spatial data**. Documentation produced during the excavation can also be consulted if the files (photos, scanned drawings, etc.) are placed in the right location in the file structure. The pages mainly consist of creation or modification forms, as well as tables listing already recorded elements. The visualization of geometry allows for spatial orientation in the field, particularly in complex excavation sites, and interaction with attribute data. [![The BadMobil interface, with SQLPage](https://github.com/sqlpage/SQLPage/assets/552629/b421eebd-1d7a-446a-90d4-f360300453d5)](https://gitlab.com/projet-r-d-bddsarcheo/tutos/-/raw/main/illustrations_diverses/interface_badmobil.webp?ref_type=heads) *The BadMobil interface, with SQLPage* @@ -162,10 +160,10 @@ The homogeneity of the entered data is thus better, and the possibilities for qu ## Future Prospects -Following the development of Badass and Bad''mobil at the Les Mastraits necropolis, it seemed possible to consider its deployment in the context of preventive archaeology. While the question of the network infrastructure necessary for the operation of this solution may arise (need for stable electricity supply on remote sites in the countryside, availability of tablets, network coverage...), the benefits in terms of data homogeneity and ease of entry are very significant. A few preventive archaeology sites have thus been able to test the system, mostly on small-scale sites, benefiting from the support of collective members. +Following the development of Badass and Bad'mobil at the Les Mastraits necropolis, it seemed possible to consider its deployment in the context of preventive archaeology. While the question of the network infrastructure necessary for the operation of this solution may arise (need for stable electricity supply on remote sites in the countryside, availability of tablets, network coverage...), the benefits in terms of data homogeneity and ease of entry are very significant. A few preventive archaeology sites have thus been able to test the system, mostly on small-scale sites, benefiting from the support of collective members. Future developments will likely focus on integrating new forms or new monitoring tools. Currently, Badass allows for collecting observations common to all archaeological sites, as well as anthropological observations due to its use within the Les Mastraits necropolis. -We could consider integrating the many specialties of archaeology, but it''s likely that we would end up with a huge machine that could be complex to maintain. We therefore remain cautious on this subject. +We could consider integrating the many specialties of archaeology, but it's likely that we would end up with a huge machine that could be complex to maintain. We therefore remain cautious on this subject. # Conclusion @@ -177,10 +175,8 @@ QGIS has fundamentally revolutionized archaeological practice by offering GIS ac SQLpage has allowed us to offer archaeologists a complete and simple interface to access a networked database. While its development requires certain knowledge of SQL and website functioning, its deployment and maintenance are quite manageable. SQLPage addresses a real need in the field. For archaeologists, it simplifies their practice while responding to the growing complexity in the face of the documentary mass to be processed, and the increasing qualitative demands of deliverables. -The combination of QGIS, spatial and relational databases, and a web interface perfectly adapted to the field now fills the observed lack of an effective and reliable archaeological recording tool at the operation level. As such, Badass associated with Bad''Mobil fully meets the expectations of archaeologists who have experimented with them. +The combination of QGIS, spatial and relational databases, and a web interface perfectly adapted to the field now fills the observed lack of an effective and reliable archaeological recording tool at the operation level. As such, Badass associated with Bad'Mobil fully meets the expectations of archaeologists who have experimented with them. While open-source software has, in recent years, begun a timid breakthrough among many archaeological operators (some have fully adopted them), reluctance remains, whether from users or sometimes from the IT departments of public administrations, who may prefer to opt for an all-in-one service with technical support. -But the persistence of proprietary software usage is not without posing real problems regarding the sustainability of archaeological data, and archaeologists are just beginning to discover the issue. Their attachment to their data -- although it sometimes goes against the principle of open science -- should, however, encourage them to opt for formats whose durability appears certain, thereby guaranteeing access to this data in the future, regardless of the software or operating system used, if they don''t want their work to fall into oblivion... - ' - ); \ No newline at end of file +But the persistence of proprietary software usage is not without posing real problems regarding the sustainability of archaeological data, and archaeologists are just beginning to discover the issue. Their attachment to their data -- although it sometimes goes against the principle of open science -- should, however, encourage them to opt for formats whose durability appears certain, thereby guaranteeing access to this data in the future, regardless of the software or operating system used, if they don't want their work to fall into oblivion... diff --git a/examples/official-site/sqlpage/migrations/54_blog_bompard.sql b/examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md similarity index 91% rename from examples/official-site/sqlpage/migrations/54_blog_bompard.sql rename to examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md index 5fd16cd45..9670cc51c 100644 --- a/examples/official-site/sqlpage/migrations/54_blog_bompard.sql +++ b/examples/official-site/content/blog/how-i-built-a-360-performance-monitoring-tool-with-sql-queries.md @@ -1,12 +1,10 @@ +--- +title: How I built a 360° performance monitoring tool with SQL Queries +date: '2025-01-25' +icon: shirt +summary: Alexis built a performance monitoring tool with SQLPage for a 100M€/year company +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'How I built a 360° performance monitoring tool with SQL Queries', - 'Alexis built a performance monitoring tool with SQLPage for a 100M€/year company', - 'shirt', - '2025-01-25', - ' # How I Built And Deployed An Exhaustive Performance Monitoring Tool For a 100M€/year Company Using SQL Queries Only ### Building web applications in SQL @@ -48,12 +46,12 @@ I am using SQLPage to build a 360° Performance tool for my company, integrating Here are some pages I built using only SQL queries, allowing everyone in the company to instantly access any level of information, from the fiscal year 2024 revenue trends to the top-selling products in Marseille in October 2022. -![](https://cdn-images-1.medium.com/max/800/1*MkORbAC7oGEG-8I1mthu6A.png) - +![](https://cdn-images-1.medium.com/max/800/1*MkORbAC7oGEG-8I1mthu6A.png)\ + *Performance of different channels vs last year and best sellers. -![](https://cdn-images-1.medium.com/max/800/1*_3-g1om_p9ghXhdcw0zHmw.png) - +![](https://cdn-images-1.medium.com/max/800/1*_3-g1om_p9ghXhdcw0zHmw.png)\ + *Examples of views built with SQLPage to provide a 360° tool for the company. ### Populating a chart from a query @@ -68,27 +66,27 @@ You can find the full list of components: [https://sql-page.com/documentation.sq Here’s an example of a parameterized SQL query that uses the “chart” component, along with the query to feed data into it: - - -```sql --- Chart Component -SELECT ''chart'' AS component, - CONCAT(''Daily Revenue from '', $start_date_comparison, '' to '', $end_date_comparison) AS title, - ''area'' AS type, - ''indigo'' AS color, - 5 AS marker, - 0 AS ymin; - --- Chart Data Query -SELECT DATE(business_date) AS x, - ROUND(SUM(value), 2) AS y -FROM data_example -WHERE DATE(business_date) BETWEEN $start_date_comparison AND $end_date_comparison - AND variable_name = ''CA'' -GROUP BY DATE(business_date) -ORDER BY x ASC; - --- NB: The variables $start_date_comparison and $end_date_comparison are + + +```sql +-- Chart Component +SELECT 'chart' AS component, + CONCAT('Daily Revenue from ', $start_date_comparison, ' to ', $end_date_comparison) AS title, + 'area' AS type, + 'indigo' AS color, + 5 AS marker, + 0 AS ymin; + +-- Chart Data Query +SELECT DATE(business_date) AS x, + ROUND(SUM(value), 2) AS y +FROM data_example +WHERE DATE(business_date) BETWEEN $start_date_comparison AND $end_date_comparison + AND variable_name = 'CA' +GROUP BY DATE(business_date) +ORDER BY x ASC; + +-- NB: The variables $start_date_comparison and $end_date_comparison are -- defined dynamically in the SQL script ``` And the result: @@ -138,4 +136,3 @@ What all these projects have in common is that they were built by a single perso - 📹Youtube tutorial videos on SQLPage channel: [https://www.youtube.com/@SQLPage/playlists](https://www.youtube.com/@SQLPage/playlists) - 🤓github: [https://github.com/sqlpage/SQLPage/](https://github.com/sqlpage/SQLPage/) - ☁️Host your applications: [https://datapage.app](https://datapage.app) -'); diff --git a/examples/official-site/sqlpage/migrations/71_blog_pagination.sql b/examples/official-site/content/blog/how-to-use-the-pagination-component.md similarity index 83% rename from examples/official-site/sqlpage/migrations/71_blog_pagination.sql rename to examples/official-site/content/blog/how-to-use-the-pagination-component.md index 0a2a34f43..ceef0e3d6 100644 --- a/examples/official-site/sqlpage/migrations/71_blog_pagination.sql +++ b/examples/official-site/content/blog/how-to-use-the-pagination-component.md @@ -1,12 +1,10 @@ +--- +title: How to use the pagination component +date: '2025-11-10' +icon: sailboat-2 +summary: A tutorial for using the pagination component +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'How to use the pagination component', - 'A tutorial for using the pagination component', - 'sailboat-2', - '2025-11-10', - ' # How to use the pagination component To display a large number of records from a database, it is often practical to split these data into pages. The user can thus navigate from one page to another, as well as directly to the first or last page. With SQLPage, it is possible to perform these operations using the pagination component. @@ -34,17 +32,17 @@ SET pages_count = (CAST($records_count AS INTEGER) / CAST($MAX_RECORD_PER_PAGE A ``` It is possible that the number of rows in the table is greater than the estimated number of pages multiplied by the number of rows per page. In this case, it is necessary to add an additional page. - + ``` SET pages_count = ( - CASE - WHEN MOD(CAST($records_count AS INTEGER),CAST($MAX_RECORD_PER_PAGE AS INTEGER)) = 0 THEN $pages_count - ELSE (CAST($pages_count AS INTEGER) + 1) + CASE + WHEN MOD(CAST($records_count AS INTEGER),CAST($MAX_RECORD_PER_PAGE AS INTEGER)) = 0 THEN $pages_count + ELSE (CAST($pages_count AS INTEGER) + 1) END ); ``` -We will need to transmit the page number to be displayed in the URL using the `page` parameter. We do the same for the number of the first page (`idx_page`) appearing at the left end of the pagination component. +We will need to transmit the page number to be displayed in the URL using the `page` parameter. We do the same for the number of the first page (`idx_page`) appearing at the left end of the pagination component. ![Meaning of URL parameters](blog/pagination.png) @@ -58,15 +56,15 @@ SET idx_page = COALESCE($idx_page,1); ## Read the data -We can now read and display the data based on the active page. To do this, we simply use a table component. +We can now read and display the data based on the active page. To do this, we simply use a table component. ``` -SELECT - ''table'' as component; SELECT - user_id AS id, + 'table' as component; +SELECT + user_id AS id, last_name AS "Last name", - first_name AS "First name" + first_name AS "First name" FROM users ORDER BY user_id @@ -89,13 +87,13 @@ SET previous_parameters = ( CASE WHEN CAST($page AS INTEGER) > 1 THEN json_object( - ''page'', (CAST($page AS INTEGER) - 1), - ''idx_page'', (CASE + 'page', (CAST($page AS INTEGER) - 1), + 'idx_page', (CASE WHEN CAST($idx_page AS INTEGER) > 1 THEN (CAST($idx_page AS INTEGER) - 1) ELSE $idx_page - END) + END) ) - ELSE json_object() END + ELSE json_object() END ); ``` @@ -106,11 +104,11 @@ SET next_parameters = ( CASE WHEN CAST($page AS INTEGER) < CAST($pages_count AS INTEGER) THEN json_object( - ''page'', (CAST($page AS INTEGER) + 1), - ''idx_page'', (CASE + 'page', (CAST($page AS INTEGER) + 1), + 'idx_page', (CASE WHEN CAST($idx_page AS INTEGER) < (CAST($pages_count AS INTEGER) - CAST($MAX_PAGES AS INTEGER) + 1) THEN (CAST($idx_page AS INTEGER) + 1) ELSE $idx_page - END) + END) ) ELSE json_object() END ); @@ -123,27 +121,27 @@ We can now add the pagination component, which is placed below the table display ``` SELECT - ''pagination'' AS component, + 'pagination' AS component, (CAST($page AS INTEGER) = 1) AS first_disabled, (CAST($page AS INTEGER) = 1) AS previous_disabled, (CAST($page AS INTEGER) = CAST($pages_count AS INTEGER)) AS next_disabled, (CAST($page AS INTEGER) = CAST($pages_count AS INTEGER)) AS last_disabled, - sqlpage.link(sqlpage.path(), json_object(''page'', 1, ''idx_page'', 1)) as first_link, + sqlpage.link(sqlpage.path(), json_object('page', 1, 'idx_page', 1)) as first_link, sqlpage.link(sqlpage.path(), $previous_parameters) AS previous_link, sqlpage.link(sqlpage.path(), $next_parameters) AS next_link, sqlpage.link( sqlpage.path(), - json_object(''page'', $pages_count, ''idx_page'', ( + json_object('page', $pages_count, 'idx_page', ( CASE WHEN (CAST($pages_count AS INTEGER) <= CAST($MAX_PAGES AS INTEGER)) THEN 1 - ELSE (CAST($pages_count AS INTEGER) - CAST($MAX_PAGES AS INTEGER) + 1) + ELSE (CAST($pages_count AS INTEGER) - CAST($MAX_PAGES AS INTEGER) + 1) END) ) ) AS last_link, TRUE AS outline; ``` -The final step is to generate the page numbers based on the number of pages and the index of the first page displayed to the left of the component. To do this, we use a recursive CTE query. +The final step is to generate the page numbers based on the number of pages and the index of the first page displayed to the left of the component. To do this, we use a recursive CTE query. ``` WITH RECURSIVE page_numbers AS ( @@ -155,12 +153,11 @@ WITH RECURSIVE page_numbers AS ( WHERE number < CAST($pages_count AS INTEGER) LIMIT CAST($MAX_PAGES AS INTEGER) ) -SELECT +SELECT number AS contents, - sqlpage.link(sqlpage.path(), json_object(''page'', number, ''idx_page'', $idx_page)) as link, - (number = CAST($page AS INTEGER)) AS active + sqlpage.link(sqlpage.path(), json_object('page', number, 'idx_page', $idx_page)) as link, + (number = CAST($page AS INTEGER)) AS active FROM page_numbers; ``` If the added page matches the content of the `page` variable, the `active` option is set to `TRUE` so that the user knows it is the current page. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/50_blog_json.sql b/examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md similarity index 78% rename from examples/official-site/sqlpage/migrations/50_blog_json.sql rename to examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md index 7e6aa4662..44c42339c 100644 --- a/examples/official-site/sqlpage/migrations/50_blog_json.sql +++ b/examples/official-site/content/blog/json-in-sql-a-comprehensive-guide.md @@ -1,11 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'JSON in SQL: A Comprehensive Guide', - 'A comprehensive guide to working with JSON data in SQLite, PostgreSQL, MySQL, and SQL Server.', - 'braces', - '2024-09-03', - ' +--- +title: 'JSON in SQL: A Comprehensive Guide' +date: '2024-09-03' +icon: braces +summary: A comprehensive guide to working with JSON data in SQLite, PostgreSQL, MySQL, and SQL Server. +--- + # JSON in SQL: A Comprehensive Guide ## Introduction @@ -29,7 +28,7 @@ JSON supports the following data types: ## Sample Table -We''ll use the following sample table for our examples: +We'll use the following sample table for our examples: ```sql CREATE TABLE users ( @@ -40,9 +39,9 @@ CREATE TABLE users ( ); INSERT INTO users (id, name, birthday, group_name) VALUES -(1, ''Alice'', ''1990-01-15'', ''Admin''), -(2, ''Bob'', ''1985-05-22'', ''User''), -(3, ''Charlie'', ''1992-09-30'', ''User''); +(1, 'Alice', '1990-01-15', 'Admin'), +(2, 'Bob', '1985-05-22', 'User'), +(3, 'Charlie', '1992-09-30', 'User'); ``` ## SQLite @@ -55,7 +54,7 @@ See [the list of JSON functions in SQLite](https://www.sqlite.org/json1.html) fo We can use the standard `json_object()` function to create a JSON object from columns in a table: ```sql -SELECT json_object(''name'', name, ''birthday'', birthday) AS user_json +SELECT json_object('name', name, 'birthday', birthday) AS user_json FROM users; ``` @@ -106,7 +105,7 @@ FROM users; SQLite provides the `json_each()` table-valued function to iterate over JSON arrays. This function returns one row for each element in the JSON array. ```sql -SELECT value FROM json_each(''["Alice", "Bob", "Charlie"]''); +SELECT value FROM json_each('["Alice", "Bob", "Charlie"]'); ``` | value | @@ -119,21 +118,21 @@ The `json_each()` function returns a table with several columns. The most common - `key`: The array index (0-based) for elements of a JSON array - `value`: The value of the current element -- `type`: The type of the current element (e.g., ''text'', ''integer'', ''real'', ''true'', ''false'', ''null'') +- `type`: The type of the current element (e.g., 'text', 'integer', 'real', 'true', 'false', 'null') For more complex JSON structures, you can use the `json_tree()` function, which recursively walks through the entire JSON structure. These iteration functions can be used to check if specific values exist in a JSON array. -Here''s a practical example: -Let''s say you have a form with a [multiple-choice dropdown](documentation.sql?component=form#component) that allows selecting multiple users. +Here's a practical example: +Let's say you have a form with a [multiple-choice dropdown](documentation.sql?component=form#component) that allows selecting multiple users. Some users might already be selected, and their IDs are stored in a JSON array passed as an URL parameter called `$selected_ids`. You can create this dropdown using the following query: ```sql select json_group_array(json_object( - ''label'', name, - ''value'', id, - ''selected'', id in (select value from json_each_text($selected_ids)) + 'label', name, + 'value', id, + 'selected', id in (select value from json_each_text($selected_ids)) )) as options from users; ``` @@ -142,14 +141,14 @@ This query will: 1. Create a dropdown option for each user 2. Use their name as the display label 3. Use their ID as the value -4. Mark the option as selected if the user''s ID exists in the $selected_ids array +4. Mark the option as selected if the user's ID exists in the $selected_ids array ### Combining two JSON objects SQLite provides the `json_patch()` function to combine two JSON objects. This function takes two JSON objects as arguments and returns a new JSON object that is the result of merging the two input objects. ```sql -SELECT json_patch(''{"name": "Alice"}'', ''{"birthday": "1990-01-15"}'') AS user_json; +SELECT json_patch('{"name": "Alice"}', '{"birthday": "1990-01-15"}') AS user_json; ``` | user_json | @@ -166,8 +165,8 @@ See [the list of JSON functions in PostgreSQL](https://www.postgresql.org/docs/c ```sql SELECT jsonb_build_object( - ''name'', name, - ''birthday'', birthday + 'name', name, + 'birthday', birthday ) AS user_json FROM users; ``` @@ -222,7 +221,7 @@ FROM users; ### Iterating over a JSON array ```sql -SELECT name FROM jsonb_array_elements_text(''["Alice", "Bob", "Charlie"]''::jsonb) AS name; +SELECT name FROM jsonb_array_elements_text('["Alice", "Bob", "Charlie"]'::jsonb) AS name; ``` | name | @@ -236,9 +235,9 @@ You can use this function to test whether a value is present in a JSON array. Fo ```sql SELECT jsonb_agg(jsonb_build_object( - ''label'', name, - ''value'', id, - ''selected'', id in (SELECT value FROM jsonb_array_elements_text($selected_ids::jsonb)) + 'label', name, + 'value', id, + 'selected', id in (SELECT value FROM jsonb_array_elements_text($selected_ids::jsonb)) )) AS options FROM users; ``` @@ -247,7 +246,7 @@ FROM users; ```sql SELECT key, value -FROM jsonb_each_text(''{"name": "Alice", "birthday": "1990-01-15"}''::jsonb); +FROM jsonb_each_text('{"name": "Alice", "birthday": "1990-01-15"}'::jsonb); ``` | key | value | @@ -260,12 +259,12 @@ FROM jsonb_each_text(''{"name": "Alice", "birthday": "1990-01-15"}''::jsonb); PostgreSQL allows you to query JSON data using the `->` and `->>` operators: ```sql -SELECT name, user_data->>''age'' AS age +SELECT name, user_data->>'age' AS age FROM ( - SELECT name, jsonb_build_object(''age'', EXTRACT(YEAR FROM AGE(birthday))) AS user_data + SELECT name, jsonb_build_object('age', EXTRACT(YEAR FROM AGE(birthday))) AS user_data FROM users ) subquery -WHERE (user_data->>''age'')::int > 30; +WHERE (user_data->>'age')::int > 30; ``` | name | age | @@ -274,10 +273,10 @@ WHERE (user_data->>''age'')::int > 30; ### Combining two JSON objects -PostgreSQL provides the `||` operator to combine two JSON objects. +PostgreSQL provides the `||` operator to combine two JSON objects. ```sql -SELECT ''{"name": "Alice"}''::jsonb || ''{"birthday": "1990-01-15"}''::jsonb AS user_json; +SELECT '{"name": "Alice"}'::jsonb || '{"birthday": "1990-01-15"}'::jsonb AS user_json; ``` | user_json | @@ -292,7 +291,7 @@ See [the list of JSON functions in MySQL](https://dev.mysql.com/doc/refman/8.0/e ### Creating a JSON object ```sql -SELECT JSON_OBJECT(''name'', name, ''birthday'', birthday) AS user_json +SELECT JSON_OBJECT('name', name, 'birthday', birthday) AS user_json FROM users; ``` @@ -341,13 +340,13 @@ FROM users; MySQL provides the JSON_TABLE() function to iterate over JSON arrays. This powerful function allows you to convert JSON data into a relational table format, making it easy to work with JSON arrays. -Here''s an example of how to use JSON_TABLE() to iterate over a JSON array: +Here's an example of how to use JSON_TABLE() to iterate over a JSON array: ```sql SELECT jt.name FROM JSON_TABLE( - ''["Alice", "Bob", "Charlie"]'', - ''$[*]'' COLUMNS( name VARCHAR(50) PATH ''$'' ) + '["Alice", "Bob", "Charlie"]', + '$[*]' COLUMNS( name VARCHAR(50) PATH '$' ) ) AS jt; ``` @@ -359,19 +358,19 @@ FROM JSON_TABLE( In this example: - The first argument to JSON_TABLE() is the JSON array. -- `''$[*]''` is the path expression that selects all elements of the array. +- `'$[*]'` is the path expression that selects all elements of the array. - The `COLUMNS` clause defines the structure of the output table. In our case, we want a single column named `name`: - - `name VARCHAR(50) PATH ''$''` creates a text column that contains the raw value of each array element in its entirety (`$` is the current element). + - `name VARCHAR(50) PATH '$'` creates a text column that contains the raw value of each array element in its entirety (`$` is the current element). You can also use JSON_TABLE() with more complex JSON structures: ```sql SELECT jt.* FROM JSON_TABLE( - ''[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]'', - ''$[*]'' COLUMNS( - id INT PATH ''$.id'', - name VARCHAR(50) PATH ''$.name'' + '[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]', + '$[*]' COLUMNS( + id INT PATH '$.id', + name VARCHAR(50) PATH '$.name' ) ) AS jt; ``` @@ -391,9 +390,9 @@ The `JSON_TABLE` function can also be used to iterate over JSON objects: ```sql SELECT jt.* FROM JSON_TABLE( - ''{"name": "Alice", "birthday": "1990-01-15"}'', - ''$.*'' COLUMNS ( - value JSON PATH ''$'' + '{"name": "Alice", "birthday": "1990-01-15"}', + '$.*' COLUMNS ( + value JSON PATH '$' ) ) AS jt; ``` @@ -409,10 +408,10 @@ You can use the `JSON_KEYS()` function to retrieve the list of keys in a JSON ob then use that array to iterate over the keys of a JSON object: ```sql -SELECT json_key, json_extract(json_str, CONCAT(''$.'', json_key)) as json_value +SELECT json_key, json_extract(json_str, CONCAT('$.', json_key)) as json_value FROM - (select ''{"name": "Alice", "birthday": "1990-01-15"}'' as json_str) AS my_json, - JSON_TABLE(json_keys(json_str), ''$[*]'' COLUMNS (json_key JSON PATH ''$'')) AS json_keys; + (select '{"name": "Alice", "birthday": "1990-01-15"}' as json_str) AS my_json, + JSON_TABLE(json_keys(json_str), '$[*]' COLUMNS (json_key JSON PATH '$')) AS json_keys; ``` | json_key | json_value | @@ -425,12 +424,12 @@ FROM MySQL allows you to query JSON data using the `->` and `->>` operators: ```sql -SELECT name, user_data->''$.age'' AS age +SELECT name, user_data->'$.age' AS age FROM ( - SELECT name, JSON_OBJECT(''age'', YEAR(CURDATE()) - YEAR(birthday)) AS user_data + SELECT name, JSON_OBJECT('age', YEAR(CURDATE()) - YEAR(birthday)) AS user_data FROM users ) subquery -WHERE user_data->''$.age'' > 30; +WHERE user_data->'$.age' > 30; ``` | name | age | @@ -469,7 +468,7 @@ FROM users; Alternatively, you can use the `JSON_OBJECT` function: ```sql -SELECT JSON_OBJECT(''name'': name, ''birthday'': birthday) AS user_json +SELECT JSON_OBJECT('name': name, 'birthday': birthday) AS user_json FROM users; ``` @@ -524,7 +523,7 @@ SELECT JSON_OBJECTAGG(name: birthday) AS name_birthday_map FROM users; Use the `OPENJSON` function to iterate over JSON arrays: ```sql -SELECT value FROM OPENJSON(''["Alice", "Bob", "Charlie"]''); +SELECT value FROM OPENJSON('["Alice", "Bob", "Charlie"]'); ``` | value | @@ -539,10 +538,10 @@ Use `OPENJSON` to iterate over JSON objects: ```sql SELECT * -FROM OPENJSON(''{"name": "Alice", "birthday": "1990-01-15"}'') +FROM OPENJSON('{"name": "Alice", "birthday": "1990-01-15"}') WITH ( - name NVARCHAR(50) ''$.name'', - birthday DATE ''$.birthday'' + name NVARCHAR(50) '$.name', + birthday DATE '$.birthday' ); ``` @@ -555,7 +554,7 @@ WITH ( Use the `JSON_VALUE` function to extract scalar values from JSON: ```sql -SELECT JSON_VALUE(''{"age": 38}'', ''$.age'') AS age +SELECT JSON_VALUE('{"age": 38}', '$.age') AS age ``` | age | @@ -574,7 +573,7 @@ SQL Server provides several other useful JSON functions: Example using `JSON_MODIFY`: ```sql -SELECT JSON_MODIFY(''{"name": "Alice", "age": 30}'', ''$.age'', 31) AS updated_json; +SELECT JSON_MODIFY('{"name": "Alice", "age": 30}', '$.age', 31) AS updated_json; ``` | updated_json | @@ -582,4 +581,3 @@ SELECT JSON_MODIFY(''{"name": "Alice", "age": 30}'', ''$.age'', 31) AS updated_j | {"name": "Alice", "age": 31} | This comprehensive guide covers the basics of working with JSON in SQLite, PostgreSQL, MySQL, and SQL Server. Each database has its own set of functions and syntax for JSON operations, but the general concepts remain similar across all platforms. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/69_blog_performance_guide.sql b/examples/official-site/content/blog/performance-guide.md similarity index 89% rename from examples/official-site/sqlpage/migrations/69_blog_performance_guide.sql rename to examples/official-site/content/blog/performance-guide.md index c9f369d49..2bb0f24b1 100644 --- a/examples/official-site/sqlpage/migrations/69_blog_performance_guide.sql +++ b/examples/official-site/content/blog/performance-guide.md @@ -1,12 +1,10 @@ +--- +title: Performance Guide +date: '2025-10-31' +icon: bolt +summary: Concrete advice on how to make your SQLPage webapp fast +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Performance Guide', - 'Concrete advice on how to make your SQLPage webapp fast', - 'bolt', - '2025-10-31', - ' # Performance Guide SQLPage is [optimized](/performance) @@ -23,7 +21,7 @@ the second part of the quide: *SQLPage-specific advice*. The best way to ensure your SQLPage webapp is fast is to ensure your database is well managed and your SQL queries are well written. -We''ll go over the most common database performance pitfalls so that you know how to avoid them. +We'll go over the most common database performance pitfalls so that you know how to avoid them. ### Choose the right database schema @@ -61,7 +59,7 @@ CREATE TABLE sale ( Always use foreign keys instead of trying to store redundant data such as store names in the sales table. -This way, when you need to display the list of stores in your application, you don''t have to +This way, when you need to display the list of stores in your application, you don't have to run a slow `select distinct store from sales`, that would have to go through your millions of sales (*even if you have an index on the store column*), you just query the tiny `stores` table directly. @@ -172,7 +170,7 @@ Such databases can be used with SQLPage by using their [ODBC](https://en.wikiped ## SQLPage-specific advice The best way to make your SQLPage webapp fast is to make your queries fast. -Sometimes, you just don''t have control over the database, and have to run slow queries. +Sometimes, you just don't have control over the database, and have to run slow queries. This section will help you minimize the impact to your users. ### Order matters @@ -186,7 +184,7 @@ So, if you have to execute a slow query, put it as far down in the page as possi Every user-facing page in a SQLPage site has a [shell](/component.sql?component=shell). The first queries in any sql file (all the ones that come before the [shell](/component.sql?component=shell)) -are executed before any data has been sent to the user''s browser. +are executed before any data has been sent to the user's browser. During that time, the user will see a blank screen. So, ensure your shell comes as early as possible, and does not require any heavy computation. If you can make your shell entirely static (independent of the database), do so, @@ -204,16 +202,16 @@ In this case, avoid recomputing it on every use inside the page. #### Reusing a single database record -When that data is small, store it in a sqlpage variable as JSON and then +When that data is small, store it in a sqlpage variable as JSON and then extract the data you need using [json operations](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide). ```sql set product = ( - select json_object(''name'', name, ''price'', price) -- in postgres, you can simply use row_to_json(product) + select json_object('name', name, 'price', price) -- in postgres, you can simply use row_to_json(product) from products where id = $product_id ); -select ''alert'' as component, ''Product'' as title, $product->>''name'' as description; +select 'alert' as component, 'Product' as title, $product->>'name' as description; ``` #### Reusing a large query result set @@ -226,14 +224,14 @@ In this case, store the filtered data in a temporary table and then reuse it in ```sql drop table if exists filtered_products; create temporary table filtered_products as -select * from products where +select * from products where ($category is null or category = $category) and ($manufacturer is null or manufacturer = $manufacturer); -select ''alert'' as component, count(*) || '' products'' as title +select 'alert' as component, count(*) || ' products' as title from filtered_products; -select ''list'' as component; +select 'list' as component; select name as title from filtered_products; ``` @@ -241,25 +239,25 @@ select name as title from filtered_products; Each query you execute has an overhead of at least the time it takes to send a packet back and forth between SQLPage and the database. -When it''s possible, combine multiple queries into a single one, possibly using +When it's possible, combine multiple queries into a single one, possibly using [`UNION ALL`](https://en.wikipedia.org/wiki/Set_operations_(SQL)#UNION_operator). ```sql -select ''big_number'' as component; +select 'big_number' as component; with stats as ( select count(*) as total, avg(price) as average_price from filtered_products ) -select ''count'' as title, stats.total as value from stats +select 'count' as title, stats.total as value from stats union all -select ''average price'' as title, stats.average_price as value from stats; +select 'average price' as title, stats.average_price as value from stats; ``` ### Lazy loading -Use the [card](/component?component=card) and [modal](/component?component=modal) components +Use the [card](/component?component=card) and [modal](/component?component=modal) components with the `embed` attribute to load data lazily. -Lazy loaded content is not sent to the user''s browser when the page initially loads, +Lazy loaded content is not sent to the user's browser when the page initially loads, so it does not block the initial rendering of the page and provides a better experience for data that might be slow to load. @@ -277,8 +275,7 @@ database is configured to allow opening many simultaneous connections. When `environment` is set to `development` in its [configuration](https://github.com/sqlpage/SQLPage/blob/main/configuration.md), SQLPage will include precise measurement of the time it spends in each of the steps it has to go through before starting to send data -back to the user''s browser. You can visualize that performance data in your browser''s network inspector. +back to the user's browser. You can visualize that performance data in your browser's network inspector. You can set the `RUST_LOG` environment variable to `sqlpage=debug` to make SQLPage print detailed messages associated with precise timing for everything it does. -'); diff --git a/examples/official-site/sqlpage/migrations/73_blog_tracing.sql b/examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md similarity index 93% rename from examples/official-site/sqlpage/migrations/73_blog_tracing.sql rename to examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md index ef4b63d7f..32aa40cb8 100644 --- a/examples/official-site/sqlpage/migrations/73_blog_tracing.sql +++ b/examples/official-site/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md @@ -1,11 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Tracing SQLPage with OpenTelemetry and Grafana', - 'How to inspect requests, SQL queries, and database wait time with distributed tracing', - 'route-2', - '2026-03-09', - ' +--- +title: Tracing SQLPage with OpenTelemetry and Grafana +date: '2026-03-09' +icon: route-2 +summary: How to inspect requests, SQL queries, and database wait time with distributed tracing +--- + # Tracing SQLPage with OpenTelemetry and Grafana When a page is slow, a log line telling you that the request took 1.8 seconds is only the start of the investigation. What you usually want to know next is where that time went: @@ -41,9 +40,9 @@ Tracing is especially helpful in SQLPage because one request often maps cleanly ## Run the example stack -The simplest way to explore tracing is to run +The simplest way to explore tracing is to run [the example shipped with SQLPage](https://github.com/sqlpage/SQLPage/tree/main/examples/telemetry). -After downloading or cloning the example, run this from the example''s folder: +After downloading or cloning the example, run this from the example's folder: ```bash docker compose up --build @@ -123,7 +122,7 @@ SELECT application_name, query, state FROM pg_stat_activity; ``` -If you also include `%a` in PostgreSQL''s `log_line_prefix`, your database logs can contain the same trace context. +If you also include `%a` in PostgreSQL's `log_line_prefix`, your database logs can contain the same trace context. ## A practical debugging example @@ -171,5 +170,3 @@ SQLPage already makes the application logic easy to inspect because it lives in By enabling OpenTelemetry and connecting SQLPage to Grafana, you can see not just that a request was slow, but why it was slow, where the time was spent, and which query or resource caused the delay. For a complete working setup, start with the [OpenTelemetry + Grafana example](https://github.com/sqlpage/SQLPage/tree/main/examples/telemetry) and adapt it to your own deployment. -' - );