diff --git a/examples/official-site/README.md b/examples/official-site/README.md index 331bbf199..f7b6c1704 100644 --- a/examples/official-site/README.md +++ b/examples/official-site/README.md @@ -68,6 +68,13 @@ select 'html' as language, '

Hello

' as contents; Run `npm run site:test` to build the site, check its search index and published SQL, and run the documentation parser tests. Run `npm run site` to preview the site. +## Blog posts + +Edit posts in [`sqlpage/content/blog/`](sqlpage/content/blog/). Start with YAML +front matter containing `title`, `date` (YYYY-MM-DD), `icon`, and `summary`, +then write the article in Markdown. Use `external_url` for posts published +elsewhere. Keep the title of a published post to preserve its permalink. + ## Landing page The home page is rendered by `index.sql` and the `landing-page` custom template. diff --git a/examples/official-site/sqlpage/content/blog/3-solutions-to-the-3-layer-problem.md b/examples/official-site/sqlpage/content/blog/3-solutions-to-the-3-layer-problem.md new file mode 100644 index 000000000..348921268 --- /dev/null +++ b/examples/official-site/sqlpage/content/blog/3-solutions-to-the-3-layer-problem.md @@ -0,0 +1,82 @@ +--- +title: 3 solutions to the 3 layer problem +date: '2023-08-10' +icon: adjustments-question +summary: What is the 3 layer problem, and how SQLPage solves it? +--- + +# 3 solutions to the 3 layer problem + +> Some interesting questions emerged from the article [Repeating yourself thrice doesn't turn you into a 3X developer](https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0). +> This short follow-up article aims to answer them and clarify some points. + +Hello all, + +I am Ophir Lojkine, the main contributor of the open-source application server **SQLPage**. + +The previous article focused on the conventional model of splitting applications into three distinct tiers: + +1. a graphical interface (_front-end_), +2. an application server (_back-end_), +3. and a database. + +In many projects, this results in three distinct implementations of the application’s data model: + +1. First, in SQL, in the form of tables, views, and relationships in the database, +2. Then, in _server side_ languages such as Java, Python, or PHP, to create an API managing access to the data, and to implement the business logic of the application, +3. Finally, in JavaScript or TypeScript to implement data manipulation in the user interface. + +![Traditional tiers model](blog/three-layers.svg) + +--- + +The topic of interest here is the duplication of the data model between the different layers, +and the communication overhead between them. +We are not talking about how the code is structured within each layer. +It can follow a Model-View-Controller pattern or not, it doesn't matter. + +This three-layer model has several advantages: +specialization of the programmers, +parallelization of work, +scalability, +separation of concerns, +and an optimal exploitation of the capacities of the infrastructure on which each layer is deployed: +web browser, server application and database. + +Nevertheless, in large-scale projects, +there is often a certain redundancy of the code between the different layers, +as well as a non-negligible share of code dedicated to communication between them. +For small teams and solo developers, this becomes a major drawback. + +## 3 solutions + +Fortunately, there are several approaches to solving this problem: + +1. For **UI-centric applications** without complicated data processing needs, +you can almost completely abandon server-side development and **directly expose the data to the frontend**. +Open-source tools available in this space include Supabase, PocketBase or Hasura. +2. For **applications with a predominant business logic**, traditional _web frameworks_ +solve this problem by centralizing frontend and database control in the backend code. +A common solution involves using an ORM and templating system instead of a dedicated javascript application. +Popular solutions include Django, Ruby on Rails, or Symphony. +3. For simpler applications, it is possible to **avoid both backend and frontend development** +by adopting a _database-first_ approach. +This alternative, although less widespread, allows taking advantage of under-exploited modern capacities of relational databases. +The purpose of the original article was to introduce this lesser known approach. + * **SQLPage** is representative of this last category, + which allows designing a complete web application _in SQL_. + This leads to a loss of control over the precise visual appearance of the application, + which will get a “standardized” look and feel. + On the other hand, this translates into significant gains in terms of development speed, + simplicity and performance. + This solution is not intended to compete with traditional _frameworks_, + but rather integrate earlier in the life cycle of a project. + It thus makes it possible to quickly develop a data structure adapted to the application, + and to iterate over it while benefiting from continuous visual feedback on the final result. + Then, when the application grows, it’s easy to add a classic frontend and backend on top of the existing database, + without having to start from scratch. + +Whichever approach is chosen in the end, +a solid understanding of the conventional three-tier architecture, +as well as a clear perspective on the challenges it creates and the possible solutions, +facilitates decision-making and the evolution of the project with the best suited technologies. diff --git a/examples/official-site/sqlpage/migrations/53_blog_pgconf2024.sql b/examples/official-site/sqlpage/content/blog/come-and-see-us-in-athens.md similarity index 63% rename from examples/official-site/sqlpage/migrations/53_blog_pgconf2024.sql rename to examples/official-site/sqlpage/content/blog/come-and-see-us-in-athens.md index 1f859c282..a74383aa3 100644 --- a/examples/official-site/sqlpage/migrations/53_blog_pgconf2024.sql +++ b/examples/official-site/sqlpage/content/blog/come-and-see-us-in-athens.md @@ -1,12 +1,10 @@ +--- +title: Come and see us in Athens ! +date: '2024-10-15' +icon: microphone-2 +summary: PGConf 2024 is coming to Athens, Greece. And we will be there to talk about SQLPage & Archeology ! +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Come and see us in Athens !', - 'PGConf 2024 is coming to Athens, Greece. And we will be there to talk about SQLPage & Archeology !', - 'microphone-2', - '2024-10-15', - ' # PostgreSQL & SQLPage at PGConf 2024 We have been invited to give a talk at PGConf 2024 in Athens, Greece. @@ -20,9 +18,8 @@ drastically reduce the time spent on data entry and management. There will be two presenters: - **Ophir Lojkine**, the creator and maintainer of SQLPage, will present the project and its capabilities. - - **Thomas Guillemard**, an archaeologist from France''s National Institute for Preventive Archaeological Research, will present the project''s use case and its benefits. + - **Thomas Guillemard**, an archaeologist from France's National Institute for Preventive Archaeological Research, will present the project's use case and its benefits. Come and see us in Athens ! https://www.postgresql.eu/events/pgconfeu2024/schedule/session/5707-unearthing-the-past-with-postgresql-how-open-source-is-revolutionizing-digital-archaeology/ -'); diff --git a/examples/official-site/sqlpage/migrations/22_pgconf_eu.sql b/examples/official-site/sqlpage/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md similarity index 75% rename from examples/official-site/sqlpage/migrations/22_pgconf_eu.sql rename to examples/official-site/sqlpage/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md index 2647d3b09..81b8eed4f 100644 --- a/examples/official-site/sqlpage/migrations/22_pgconf_eu.sql +++ b/examples/official-site/sqlpage/content/blog/come-see-me-build-twitter-live-on-stage-in-prague.md @@ -1,10 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES ( - 'Come see me build twitter live on stage in Prague', - 'I will speak about SQLPage at pgconf.eu in Prague on December 14th. Come see me !', - 'calendar-event', - '2023-11-11', - ' +--- +title: Come see me build twitter live on stage in Prague +date: '2023-11-11' +icon: calendar-event +summary: I will speak about SQLPage at pgconf.eu in Prague on December 14th. Come see me ! +--- + # SQLPage live on stage Hello everyone ! @@ -25,5 +25,3 @@ Come see me ! - [Information about the talk](https://www.postgresql.eu/events/pgconfeu2023/schedule/session/4687-sqlpage-building-a-full-web-application-with-nothing-but-postgres-and-sql-queries/) - When ? **December 14th, 2023**, **09:30 - 10:20** - Where ? Zenit Room, [Clarion Congress Hotel, Prague, Czech Republic](https://maps.app.goo.gl/qHCAaRFRjXmx2kQA7) - -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/64_blog_routing.sql b/examples/official-site/sqlpage/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/sqlpage/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/sqlpage/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/sqlpage/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/sqlpage/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/sqlpage/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/sqlpage/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/sqlpage/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/sqlpage/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/14_sorry_i_forked.sql b/examples/official-site/sqlpage/content/blog/im-sorry-i-forked-you.md similarity index 94% rename from examples/official-site/sqlpage/migrations/14_sorry_i_forked.sql rename to examples/official-site/sqlpage/content/blog/im-sorry-i-forked-you.md index a21276b27..43bd7614f 100644 --- a/examples/official-site/sqlpage/migrations/14_sorry_i_forked.sql +++ b/examples/official-site/sqlpage/content/blog/im-sorry-i-forked-you.md @@ -1,10 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES ( - 'I’m sorry I forked you', - 'SQLPage forked the sqlx database drivers library. Here is why.', - 'git-fork', - '2023-08-13', - ' +--- +title: I’m sorry I forked you +date: '2023-08-13' +icon: git-fork +summary: SQLPage forked the sqlx database drivers library. Here is why. +--- + # I’m sorry I forked you I’ve been immersed in open source coding since my teenage years, and now, I can’t fathom a world without it. @@ -13,7 +13,7 @@ Each company adds its proprietary touch to this vast open source landscape, but they are ultimately just forming a unique blend atop a colossal iceberg of shared resources. In the software world, open source truly is the driving force behind innovation. -## Unconventional Financial Currents in Software +## Unconventional Financial Currents in Software The software industry operates on a financial current that defies conventional norms. Unlike other sectors where key players like oil companies rake in the riches by supplying essentials to other businesses, @@ -45,7 +45,7 @@ and the introduction of a new API, making it non trivial to migrate from the pre ## SQLPage As the principal caretaker of the [SQLPage web application server](/), which relies on sqlx, -I faced a pivotal juncture. The path ahead diverged into two distinct trails: +I faced a pivotal juncture. The path ahead diverged into two distinct trails: 1. a challenging migration to sqlx v0.7, making a cross on MSSQL support; 2. persisting with v0.6, a realm housing outdated and potentially vulnerable dependencies. @@ -94,4 +94,3 @@ The main contributor to sqlx reacted to this post, and they wanted to clarify tw (unlike SQLPage, which is free to use even in conjunction with proprietary software, under the *MIT* license). Companies that want to use these future sqlx drivers in proprietary software will have to pay for a commercial license. That change in the decision has been announced in 2022, and I should have been aware of it when I wrote this post. My bad. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/42_blog_video.sql b/examples/official-site/sqlpage/content/blog/introduction-video.md similarity index 70% rename from examples/official-site/sqlpage/migrations/42_blog_video.sql rename to examples/official-site/sqlpage/content/blog/introduction-video.md index 4cd0a09d4..78ce294b4 100644 --- a/examples/official-site/sqlpage/migrations/42_blog_video.sql +++ b/examples/official-site/sqlpage/content/blog/introduction-video.md @@ -1,12 +1,10 @@ +--- +title: Introduction video +date: '2024-05-14' +icon: brand-youtube +summary: A 30-minute live presentation of SQLPage, its raison d'être, and how to use it. +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Introduction video', - 'A 30-minute live presentation of SQLPage, its raison d''être, and how to use it.', - 'brand-youtube', - '2024-05-14', - ' # Introduction video ## Canadians love SQLPage @@ -16,7 +14,7 @@ by Anton Avramov, an avid SQLPage user and community member, who gave a live dem ## The video -The user group kindly invited me (Ophir, the initial creator and main contributor to SQLPage) +The user group kindly invited me (Ophir, the initial creator and main contributor to SQLPage) to record a video introduction to SQLPage, which I did. The video is a 5 minute introduction to the philosophy behind SQLPage, @@ -24,7 +22,6 @@ followed by a 25 minute live demonstration of how to create [this todo list application](https://github.com/sqlpage/SQLPage/tree/main/examples/todo%20application) from scratch. -Watch it on youtube: +Watch it on youtube: [![video cover](https://i.ytimg.com/vi/9NJgH_-zXjY/maxresdefault.jpg)](https://www.youtube.com/watch?v=9NJgH_-zXjY) -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/50_blog_json.sql b/examples/official-site/sqlpage/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/sqlpage/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/sqlpage/content/blog/json-in-sql-a-comprehensive-guide.md @@ -1,11 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'JSON in SQL: A Comprehensive Guide', - 'A comprehensive guide to working with JSON data in SQLite, PostgreSQL, MySQL, and SQL Server.', - 'braces', - '2024-09-03', - ' +--- +title: 'JSON in SQL: A Comprehensive Guide' +date: '2024-09-03' +icon: braces +summary: A comprehensive guide to working with JSON data in SQLite, PostgreSQL, MySQL, and SQL Server. +--- + # JSON in SQL: A Comprehensive Guide ## Introduction @@ -29,7 +28,7 @@ JSON supports the following data types: ## Sample Table -We''ll use the following sample table for our examples: +We'll use the following sample table for our examples: ```sql CREATE TABLE users ( @@ -40,9 +39,9 @@ CREATE TABLE users ( ); INSERT INTO users (id, name, birthday, group_name) VALUES -(1, ''Alice'', ''1990-01-15'', ''Admin''), -(2, ''Bob'', ''1985-05-22'', ''User''), -(3, ''Charlie'', ''1992-09-30'', ''User''); +(1, 'Alice', '1990-01-15', 'Admin'), +(2, 'Bob', '1985-05-22', 'User'), +(3, 'Charlie', '1992-09-30', 'User'); ``` ## SQLite @@ -55,7 +54,7 @@ See [the list of JSON functions in SQLite](https://www.sqlite.org/json1.html) fo We can use the standard `json_object()` function to create a JSON object from columns in a table: ```sql -SELECT json_object(''name'', name, ''birthday'', birthday) AS user_json +SELECT json_object('name', name, 'birthday', birthday) AS user_json FROM users; ``` @@ -106,7 +105,7 @@ FROM users; SQLite provides the `json_each()` table-valued function to iterate over JSON arrays. This function returns one row for each element in the JSON array. ```sql -SELECT value FROM json_each(''["Alice", "Bob", "Charlie"]''); +SELECT value FROM json_each('["Alice", "Bob", "Charlie"]'); ``` | value | @@ -119,21 +118,21 @@ The `json_each()` function returns a table with several columns. The most common - `key`: The array index (0-based) for elements of a JSON array - `value`: The value of the current element -- `type`: The type of the current element (e.g., ''text'', ''integer'', ''real'', ''true'', ''false'', ''null'') +- `type`: The type of the current element (e.g., 'text', 'integer', 'real', 'true', 'false', 'null') For more complex JSON structures, you can use the `json_tree()` function, which recursively walks through the entire JSON structure. These iteration functions can be used to check if specific values exist in a JSON array. -Here''s a practical example: -Let''s say you have a form with a [multiple-choice dropdown](documentation.sql?component=form#component) that allows selecting multiple users. +Here's a practical example: +Let's say you have a form with a [multiple-choice dropdown](documentation.sql?component=form#component) that allows selecting multiple users. Some users might already be selected, and their IDs are stored in a JSON array passed as an URL parameter called `$selected_ids`. You can create this dropdown using the following query: ```sql select json_group_array(json_object( - ''label'', name, - ''value'', id, - ''selected'', id in (select value from json_each_text($selected_ids)) + 'label', name, + 'value', id, + 'selected', id in (select value from json_each_text($selected_ids)) )) as options from users; ``` @@ -142,14 +141,14 @@ This query will: 1. Create a dropdown option for each user 2. Use their name as the display label 3. Use their ID as the value -4. Mark the option as selected if the user''s ID exists in the $selected_ids array +4. Mark the option as selected if the user's ID exists in the $selected_ids array ### Combining two JSON objects SQLite provides the `json_patch()` function to combine two JSON objects. This function takes two JSON objects as arguments and returns a new JSON object that is the result of merging the two input objects. ```sql -SELECT json_patch(''{"name": "Alice"}'', ''{"birthday": "1990-01-15"}'') AS user_json; +SELECT json_patch('{"name": "Alice"}', '{"birthday": "1990-01-15"}') AS user_json; ``` | user_json | @@ -166,8 +165,8 @@ See [the list of JSON functions in PostgreSQL](https://www.postgresql.org/docs/c ```sql SELECT jsonb_build_object( - ''name'', name, - ''birthday'', birthday + 'name', name, + 'birthday', birthday ) AS user_json FROM users; ``` @@ -222,7 +221,7 @@ FROM users; ### Iterating over a JSON array ```sql -SELECT name FROM jsonb_array_elements_text(''["Alice", "Bob", "Charlie"]''::jsonb) AS name; +SELECT name FROM jsonb_array_elements_text('["Alice", "Bob", "Charlie"]'::jsonb) AS name; ``` | name | @@ -236,9 +235,9 @@ You can use this function to test whether a value is present in a JSON array. Fo ```sql SELECT jsonb_agg(jsonb_build_object( - ''label'', name, - ''value'', id, - ''selected'', id in (SELECT value FROM jsonb_array_elements_text($selected_ids::jsonb)) + 'label', name, + 'value', id, + 'selected', id in (SELECT value FROM jsonb_array_elements_text($selected_ids::jsonb)) )) AS options FROM users; ``` @@ -247,7 +246,7 @@ FROM users; ```sql SELECT key, value -FROM jsonb_each_text(''{"name": "Alice", "birthday": "1990-01-15"}''::jsonb); +FROM jsonb_each_text('{"name": "Alice", "birthday": "1990-01-15"}'::jsonb); ``` | key | value | @@ -260,12 +259,12 @@ FROM jsonb_each_text(''{"name": "Alice", "birthday": "1990-01-15"}''::jsonb); PostgreSQL allows you to query JSON data using the `->` and `->>` operators: ```sql -SELECT name, user_data->>''age'' AS age +SELECT name, user_data->>'age' AS age FROM ( - SELECT name, jsonb_build_object(''age'', EXTRACT(YEAR FROM AGE(birthday))) AS user_data + SELECT name, jsonb_build_object('age', EXTRACT(YEAR FROM AGE(birthday))) AS user_data FROM users ) subquery -WHERE (user_data->>''age'')::int > 30; +WHERE (user_data->>'age')::int > 30; ``` | name | age | @@ -274,10 +273,10 @@ WHERE (user_data->>''age'')::int > 30; ### Combining two JSON objects -PostgreSQL provides the `||` operator to combine two JSON objects. +PostgreSQL provides the `||` operator to combine two JSON objects. ```sql -SELECT ''{"name": "Alice"}''::jsonb || ''{"birthday": "1990-01-15"}''::jsonb AS user_json; +SELECT '{"name": "Alice"}'::jsonb || '{"birthday": "1990-01-15"}'::jsonb AS user_json; ``` | user_json | @@ -292,7 +291,7 @@ See [the list of JSON functions in MySQL](https://dev.mysql.com/doc/refman/8.0/e ### Creating a JSON object ```sql -SELECT JSON_OBJECT(''name'', name, ''birthday'', birthday) AS user_json +SELECT JSON_OBJECT('name', name, 'birthday', birthday) AS user_json FROM users; ``` @@ -341,13 +340,13 @@ FROM users; MySQL provides the JSON_TABLE() function to iterate over JSON arrays. This powerful function allows you to convert JSON data into a relational table format, making it easy to work with JSON arrays. -Here''s an example of how to use JSON_TABLE() to iterate over a JSON array: +Here's an example of how to use JSON_TABLE() to iterate over a JSON array: ```sql SELECT jt.name FROM JSON_TABLE( - ''["Alice", "Bob", "Charlie"]'', - ''$[*]'' COLUMNS( name VARCHAR(50) PATH ''$'' ) + '["Alice", "Bob", "Charlie"]', + '$[*]' COLUMNS( name VARCHAR(50) PATH '$' ) ) AS jt; ``` @@ -359,19 +358,19 @@ FROM JSON_TABLE( In this example: - The first argument to JSON_TABLE() is the JSON array. -- `''$[*]''` is the path expression that selects all elements of the array. +- `'$[*]'` is the path expression that selects all elements of the array. - The `COLUMNS` clause defines the structure of the output table. In our case, we want a single column named `name`: - - `name VARCHAR(50) PATH ''$''` creates a text column that contains the raw value of each array element in its entirety (`$` is the current element). + - `name VARCHAR(50) PATH '$'` creates a text column that contains the raw value of each array element in its entirety (`$` is the current element). You can also use JSON_TABLE() with more complex JSON structures: ```sql SELECT jt.* FROM JSON_TABLE( - ''[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]'', - ''$[*]'' COLUMNS( - id INT PATH ''$.id'', - name VARCHAR(50) PATH ''$.name'' + '[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]', + '$[*]' COLUMNS( + id INT PATH '$.id', + name VARCHAR(50) PATH '$.name' ) ) AS jt; ``` @@ -391,9 +390,9 @@ The `JSON_TABLE` function can also be used to iterate over JSON objects: ```sql SELECT jt.* FROM JSON_TABLE( - ''{"name": "Alice", "birthday": "1990-01-15"}'', - ''$.*'' COLUMNS ( - value JSON PATH ''$'' + '{"name": "Alice", "birthday": "1990-01-15"}', + '$.*' COLUMNS ( + value JSON PATH '$' ) ) AS jt; ``` @@ -409,10 +408,10 @@ You can use the `JSON_KEYS()` function to retrieve the list of keys in a JSON ob then use that array to iterate over the keys of a JSON object: ```sql -SELECT json_key, json_extract(json_str, CONCAT(''$.'', json_key)) as json_value +SELECT json_key, json_extract(json_str, CONCAT('$.', json_key)) as json_value FROM - (select ''{"name": "Alice", "birthday": "1990-01-15"}'' as json_str) AS my_json, - JSON_TABLE(json_keys(json_str), ''$[*]'' COLUMNS (json_key JSON PATH ''$'')) AS json_keys; + (select '{"name": "Alice", "birthday": "1990-01-15"}' as json_str) AS my_json, + JSON_TABLE(json_keys(json_str), '$[*]' COLUMNS (json_key JSON PATH '$')) AS json_keys; ``` | json_key | json_value | @@ -425,12 +424,12 @@ FROM MySQL allows you to query JSON data using the `->` and `->>` operators: ```sql -SELECT name, user_data->''$.age'' AS age +SELECT name, user_data->'$.age' AS age FROM ( - SELECT name, JSON_OBJECT(''age'', YEAR(CURDATE()) - YEAR(birthday)) AS user_data + SELECT name, JSON_OBJECT('age', YEAR(CURDATE()) - YEAR(birthday)) AS user_data FROM users ) subquery -WHERE user_data->''$.age'' > 30; +WHERE user_data->'$.age' > 30; ``` | name | age | @@ -469,7 +468,7 @@ FROM users; Alternatively, you can use the `JSON_OBJECT` function: ```sql -SELECT JSON_OBJECT(''name'': name, ''birthday'': birthday) AS user_json +SELECT JSON_OBJECT('name': name, 'birthday': birthday) AS user_json FROM users; ``` @@ -524,7 +523,7 @@ SELECT JSON_OBJECTAGG(name: birthday) AS name_birthday_map FROM users; Use the `OPENJSON` function to iterate over JSON arrays: ```sql -SELECT value FROM OPENJSON(''["Alice", "Bob", "Charlie"]''); +SELECT value FROM OPENJSON('["Alice", "Bob", "Charlie"]'); ``` | value | @@ -539,10 +538,10 @@ Use `OPENJSON` to iterate over JSON objects: ```sql SELECT * -FROM OPENJSON(''{"name": "Alice", "birthday": "1990-01-15"}'') +FROM OPENJSON('{"name": "Alice", "birthday": "1990-01-15"}') WITH ( - name NVARCHAR(50) ''$.name'', - birthday DATE ''$.birthday'' + name NVARCHAR(50) '$.name', + birthday DATE '$.birthday' ); ``` @@ -555,7 +554,7 @@ WITH ( Use the `JSON_VALUE` function to extract scalar values from JSON: ```sql -SELECT JSON_VALUE(''{"age": 38}'', ''$.age'') AS age +SELECT JSON_VALUE('{"age": 38}', '$.age') AS age ``` | age | @@ -574,7 +573,7 @@ SQL Server provides several other useful JSON functions: Example using `JSON_MODIFY`: ```sql -SELECT JSON_MODIFY(''{"name": "Alice", "age": 30}'', ''$.age'', 31) AS updated_json; +SELECT JSON_MODIFY('{"name": "Alice", "age": 30}', '$.age', 31) AS updated_json; ``` | updated_json | @@ -582,4 +581,3 @@ SELECT JSON_MODIFY(''{"name": "Alice", "age": 30}'', ''$.age'', 31) AS updated_j | {"name": "Alice", "age": 31} | This comprehensive guide covers the basics of working with JSON in SQLite, PostgreSQL, MySQL, and SQL Server. Each database has its own set of functions and syntax for JSON operations, but the general concepts remain similar across all platforms. -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/33_blog_v018.sql b/examples/official-site/sqlpage/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md similarity index 81% rename from examples/official-site/sqlpage/migrations/33_blog_v018.sql rename to examples/official-site/sqlpage/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md index 627b6d971..141987463 100644 --- a/examples/official-site/sqlpage/migrations/33_blog_v018.sql +++ b/examples/official-site/sqlpage/content/blog/new-sqlpage-and-a-talk-at-pgconf-eu.md @@ -1,33 +1,31 @@ +--- +title: New SQLPage, and a talk at PGConf.eu +date: '2024-01-29' +icon: brand-youtube +summary: SQLPage v0.18.0 is out, and there is detailed introduction to SQLPage on youtube +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'New SQLPage, and a talk at PGConf.eu', - 'SQLPage v0.18.0 is out, and there is detailed introduction to SQLPage on youtube', - 'brand-youtube', - '2024-01-29', - ' -[SQLPage](https://sql-page.com) is a small web server that renders your SQL queries as beautiful interactive websites. This release has seen significant new features and fixes from new contributors, which is great and show the health of the project ! If you feel something is missing or isn''t working quite right, all your contributions are always welcome. +[SQLPage](https://sql-page.com) is a small web server that renders your SQL queries as beautiful interactive websites. This release has seen significant new features and fixes from new contributors, which is great and show the health of the project ! If you feel something is missing or isn't working quite right, all your contributions are always welcome. On a side note, I [gave a talk about SQLPage last December at PGConf.eu](https://www.youtube.com/watch?v=mXdgmSdaXkg). It is a great detailed introduction to SQLPage, and I recommend it if you want to learn more about the project. -1. **New `tracking` component for beautiful and compact status reports:** This feature adds a new way to display status reports, making them more visually appealing and concise. +1. **New `tracking` component for beautiful and compact status reports:** This feature adds a new way to display status reports, making them more visually appealing and concise. 1. ![screenshot](https://github.com/sqlpage/SQLPage/assets/552629/3e792953-3870-469d-a01d-898316b2ab32) 3. **New `divider` component to add a horizontal line between other components:** This simple yet useful addition allows for better separation of elements on your pages. 1. ![image](https://github.com/sqlpage/SQLPage/assets/552629/09a2cc77-3b37-401f-ab3e-441637a2c022) -5. **New `breadcrumb` component to display a breadcrumb navigation bar:** This component helps users navigate through your website''s hierarchical structure, providing a clear path back to the homepage. +5. **New `breadcrumb` component to display a breadcrumb navigation bar:** This component helps users navigate through your website's hierarchical structure, providing a clear path back to the homepage. 1. ![image](https://github.com/sqlpage/SQLPage/assets/552629/cbf2174a-1d75-499e-9d6b-e111136dbbbc) 8. **Multi-column layouts with `embed` attribute in `card` component:** This feature enables you to create more complex and dynamic layouts within cards. 1. ![image](https://github.com/sqlpage/SQLPage/assets/552629/3f4435f0-d89b-424e-8b8a-39385a61d5ad) -6. **Customizable y-axis step size in `chart` component with `ystep` attribute:** This feature gives you more control over the chart''s appearance, especially for situations with multiple series. - +6. **Customizable y-axis step size in `chart` component with `ystep` attribute:** This feature gives you more control over the chart's appearance, especially for situations with multiple series. + 7. **Updated default graph colors for better distinction:** This enhancement ensures clarity and easy identification of different data series. 10. **ID and class attributes for all components for easier styling and referencing:** This improvement simplifies custom CSS customization and inter-page element linking. @@ -39,6 +37,3 @@ It is a great detailed introduction to SQLPage, and I recommend it if you want t 13. **Unicode support for built-in SQLite database:** This enables case-insensitive string comparisons and lower/upper case transformations. 5. **Improved `card` component with smaller margin below footer text:** This fix ensures consistent and visually balanced card layouts. - - ' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/69_blog_performance_guide.sql b/examples/official-site/sqlpage/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/sqlpage/content/blog/performance-guide.md index c9f369d49..2bb0f24b1 100644 --- a/examples/official-site/sqlpage/migrations/69_blog_performance_guide.sql +++ b/examples/official-site/sqlpage/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/content/blog/repeating-yourself-thrice-won-t-make-you-a-3x-developer.md b/examples/official-site/sqlpage/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/sqlpage/content/blog/repeating-yourself-thrice-won-t-make-you-a-3x-developer.md @@ -0,0 +1,8 @@ +--- +title: Repeating yourself thrice won't make you a 3X developer +date: '2023-08-01' +icon: box-multiple-3 +summary: A dive into the traditional 3-tier architecture and the DRY principle, and how tools like SQLPage + helps you avoid repeating yourself. +external_url: https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0 +--- diff --git a/examples/official-site/sqlpage/migrations/26_v0.17_release.sql b/examples/official-site/sqlpage/content/blog/sqlpage-v0-17.md similarity index 78% rename from examples/official-site/sqlpage/migrations/26_v0.17_release.sql rename to examples/official-site/sqlpage/content/blog/sqlpage-v0-17.md index 60bff5990..e435dee90 100644 --- a/examples/official-site/sqlpage/migrations/26_v0.17_release.sql +++ b/examples/official-site/sqlpage/content/blog/sqlpage-v0-17.md @@ -1,14 +1,14 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES ( - 'SQLPage v0.17', - 'SQLPage v0.17 introduces file uploads, HTTPS, and more.', - 'git-fork', - '2023-11-28', - ' +--- +title: SQLPage v0.17 +date: '2023-11-28' +icon: git-fork +summary: SQLPage v0.17 introduces file uploads, HTTPS, and more. +--- + # SQLPage v0.17 is out ! [SQLPage](/) is a web application server that lets you build entire web applications with just SQL queries. -v0.17 was just released, and it''s worth a blog post to highlight some of the coolest new features. +v0.17 was just released, and it's worth a blog post to highlight some of the coolest new features. Mostly, this release makes it a matter of minutes to build a data import pipeline for your website, and a matter of seconds to deploy your SQLPage website securely with automatic HTTPS certificates. @@ -19,11 +19,11 @@ This release is all about a long awaited feature: **file uploads**. Your SQLPage website can now accept file uploads from users, store them either in a directory or directly in a database table. -You can add a file upload button to a form with a simple +You can add a file upload button to a form with a simple ```sql -select ''form'' as component; -select ''profile_picture'' as name, ''file'' as type; +select 'form' as component; +select 'profile_picture' as name, 'file' as type; ``` when received by the server, the file will be saved in a temporary directory @@ -35,8 +35,8 @@ You can then persist the upload as a permanent file on the server with the [`sqlpage.exec`](https://sql-page.com/functions.sql?function=exec#function) function: ```sql -set file_path = sqlpage.uploaded_file_path(''profile_picture''); -select sqlpage.exec(''mv'', $file_path, ''/path/to/my/file''); +set file_path = sqlpage.uploaded_file_path('profile_picture'); +select sqlpage.exec('mv', $file_path, '/path/to/my/file'); ``` or you can store it directly in a database table with the new @@ -44,8 +44,8 @@ or you can store it directly in a database table with the new [`sqlpage.read_file_as_text`](https://sql-page.com/functions.sql?function=read_file_as_text#function) functions: ```sql -insert into files (url) values (sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''profile_picture''))) -returning ''text'' as component, ''Uploaded new file with id: '' || id as contents; +insert into files (url) values (sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('profile_picture'))) +returning 'text' as component, 'Uploaded new file with id: ' || id as contents; ``` The maximum size of uploaded files is configurable with the [`max_uploaded_file_size`](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) @@ -54,7 +54,7 @@ configuration parameter. By default, it is set to 5 MiB. ### Parsing CSV files SQLPage can also parse uploaded [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) files and insert them directly into a database table. -SQLPage re-uses PostgreSQL''s [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html) +SQLPage re-uses PostgreSQL's [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html) to import the CSV file into the database. When connected to a PostgreSQL database, SQLPage will use the native `COPY` statement, for super fast and efficient on-database CSV parsing. @@ -63,8 +63,8 @@ parsing the CSV locally and emulating the same behavior with simple `INSERT` sta #### `user_file_upload.sql` ```sql -select ''form'' as component, ''bulk_user_import.sql'' as action; -select ''user_csv_file'' as name, ''file'' as type, ''text/csv'' as accept; +select 'form' as component, 'bulk_user_import.sql' as action; +select 'user_csv_file' as name, 'file' as type, 'text/csv' as accept; ``` #### `bulk_user_import.sql` @@ -72,18 +72,18 @@ select ''user_csv_file'' as name, ''file'' as type, ''text/csv'' as accept; -- create a temporary table to preprocess the data create temporary table if not exists csv_import(name text, age text); delete from csv_import; -- empty the table --- If you don''t have any preprocessing to do, you can skip the temporary table and use the target table directly +-- If you don't have any preprocessing to do, you can skip the temporary table and use the target table directly -copy csv_import(name, age) from ''user_csv_file'' -with (header true, delimiter '','', quote ''"'', null ''NaN''); -- all the options are optional +copy csv_import(name, age) from 'user_csv_file' +with (header true, delimiter ',', quote '"', null 'NaN'); -- all the options are optional -- since header is true, the first line of the file will be used to find the "name" and "age" columns --- if you don''t have a header line, the first column in the CSV will be interpreted as the first column of the table, etc +-- if you don't have a header line, the first column in the CSV will be interpreted as the first column of the table, etc -- run any preprocessing you want on the data here -- insert the data into the users table insert into users (name, birth_date) -select upper(name), date_part(''year'', CURRENT_DATE) - cast(age as int) from csv_import; +select upper(name), date_part('year', CURRENT_DATE) - cast(age as int) from csv_import; ``` ### New functions @@ -116,7 +116,7 @@ that would compromise your security if you get it wrong. With SQLPage v0.17, you just give your domain name, and it takes care of everything. -And while we''re at it, SQLPage also supports HTTP/2, for even faster page loads. +And while we're at it, SQLPage also supports HTTP/2, for even faster page loads. To enable HTTPS, you need to buy a [domain name](https://en.wikipedia.org/wiki/Domain_name) and make it point to the server where SQLPage is running. @@ -128,9 +128,9 @@ Then set the `https_domain` configuration parameter to `yourdomain.com` in your } ``` -That''s it. No external tool to install, no certificate to generate, no configuration to tweak. +That's it. No external tool to install, no certificate to generate, no configuration to tweak. No need to restart SQLPage regularly either, or to worry about renewing your certificate when it expires. -SQLPage will automatically request a certificate from [Let''s Encrypt](https://letsencrypt.org/) by default, +SQLPage will automatically request a certificate from [Let's Encrypt](https://letsencrypt.org/) by default, and does not even need to listen on port 80 to do so. ## SQL parser improvements @@ -139,7 +139,7 @@ SQLPage needs to parse SQL queries to be able to bind the right parameters to th and to inject the results of built-in sqlpage functions in them. The parser we use is very powerful and supports most SQL features, but there are some edge cases where it fails to parse a query. -That''s why we contribute to it a lot, and bring the latest version of the parser to SQLPage as soon as it is released. +That's why we contribute to it a lot, and bring the latest version of the parser to SQLPage as soon as it is released. ### JSON functions in MS SQL Server @@ -163,8 +163,7 @@ and to create JSON APIs. - The `cookie` component now supports setting an explicit expiration date for cookies. - The `cookie` component now supports setting the `SameSite` attribute of cookies, and defaults to `SameSite=Strict` for all cookies. What this means in practice is that cookies set by SQLPage will not be sent to your website if the user is coming from another website. This prevents someone from tricking your users into executing SQLPage queries on your website by sending them a malicious link. - Bugfix: setting `min` or `max` to `0` in a number field in the `form` component now works as expected. - - Added support for `.env` files to set SQLPage''s [environment variables](./configuration.md#environment-variables). + - Added support for `.env` files to set SQLPage's [environment variables](./configuration.md#environment-variables). - Better responsive design in the card component. Up to 5 cards per line on large screens. The number of cards per line is still customizable with the `columns` attribute. - - [New icons](https://tabler-icons.io/changelog): + - [New icons](https://tabler-icons.io/changelog): - ![new icons in tabler 42](https://github.com/tabler/tabler-icons/assets/1282324/00856af9-841d-4aa9-995d-121c7ddcc005) -'); \ No newline at end of file diff --git a/examples/official-site/sqlpage/content/blog/sqlpage-versus-no-code-tools.md b/examples/official-site/sqlpage/content/blog/sqlpage-versus-no-code-tools.md new file mode 100644 index 000000000..396480cdd --- /dev/null +++ b/examples/official-site/sqlpage/content/blog/sqlpage-versus-no-code-tools.md @@ -0,0 +1,80 @@ +--- +title: SQLPage versus No-Code tools +date: '2023-08-03' +icon: code-minus +summary: What are the advantages and disadvantages of SQLPage compared to No-Code tools? +--- + +# Choosing Your Path: No-Code, Low-Code, or SQL-Based Development + +The platform you select shapes the entire trajectory of your application. +Each approach offers distinct advantages, yet demands different compromises - a choice that warrants careful consideration. + +## No-Code Platforms: Speed with Limitations + +No-Code platforms present a visual canvas for building applications without traditional programming. Whilst brilliant for rapid prototypes and straightforward departmental tools, they falter when confronted with complexity and scale. + +**Best suited to**: Quick internal tools and simple workflows + +### **Notable examples** + + - [NocoBase](https://www.nocobase.com/) + - [NocoDB](https://www.nocodb.com/) + - [Saltcorn](https://github.com/saltcorn/saltcorn) + + +## Low-Code Platforms: The Flexible Middle Ground + +These platforms artfully combine visual development with traditional coding. They maintain the power of custom code whilst accelerating development through carefully designed components. + +**Best suited to**: Complex applications requiring both speed and customisation + +### **Notable examples** + + - [Budibase](https://budibase.com/) + - [Directus](https://github.com/directus/directus) + - [Rowy](https://github.com/rowyio/rowy) + +## SQL-Based Development: Elegant Simplicity + +SQLPage offers a refreshingly direct approach: pure SQL-driven web applications. + +For those versed in SQL, it enables sophisticated data-driven applications without the overhead of additional frameworks. + +**Best suited to**: Data-centric applications and dashboards + +**Details**: [SQLPage on GitHub](https://github.com/sqlpage/SQLPage) + +## The AI Revolution in Development + +The emergence of Large Language Models (LLMs) has fundamentally shifted the landscape of application development. Tools that once demanded extensive coding expertise have become remarkably more accessible. AI assistants like ChatGPT excel particularly at generating SQL queries and database operations, making SQL-based platforms surprisingly approachable even for those with limited database experience. These AI companions serve as expert pair programmers, offering suggestions, debugging assistance, and ready-to-use code snippets. + +This transformation especially benefits platforms like SQLPage, where the AI's prowess in SQL generation can bridge the traditional expertise gap. Even complex queries and database operations can be created through natural language conversations with AI assistants, democratising access to sophisticated data manipulation capabilities. + +## Making an Informed Choice + +Selecting the right development approach requires weighing multiple factors against your project's specific needs. + +Consider these key decision points to guide your platform selection: + +### **Time Constraints** + - Immediate delivery required → No-Code + - Several days available → SQLPage or Low-Code + +### **Data Complexity** + - Structured data manipulation → SQLPage + - Complex workflows → Low-Code + +### **Team Expertise** + - SQL skills → SQLPage + - Limited technical expertise → No-Code + - Varied technical capabilities → Low-Code + +### **Control Requirements** + - Precise data layer control → SQLPage + - Visual design flexibility → Low-Code + - Speed over customisation → No-Code + +## Further Investigation + +For a thorough demonstration of SQLPage's capabilities: [Building a Full Web Application with SQLPage](https://www.youtube.com/watch?v=mXdgmSdaXkg) diff --git a/examples/official-site/sqlpage/migrations/41_blog_performance.sql b/examples/official-site/sqlpage/content/blog/sqlpage-website-update.md similarity index 86% rename from examples/official-site/sqlpage/migrations/41_blog_performance.sql rename to examples/official-site/sqlpage/content/blog/sqlpage-website-update.md index 684640d3a..fd583218e 100644 --- a/examples/official-site/sqlpage/migrations/41_blog_performance.sql +++ b/examples/official-site/sqlpage/content/blog/sqlpage-website-update.md @@ -1,12 +1,10 @@ +--- +title: SQLPage website update +date: '2024-05-01' +icon: browser +summary: Performance, security, and new features +--- -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'SQLPage website update', - 'Performance, security, and new features', - 'browser', - '2024-05-01', - ' Today is may day, and we are happy to announce that the SQLPage website has been updated with new contents. ## Homepage @@ -33,5 +31,3 @@ or an academic institution using [CAS](https://apereo.github.io/cas/). The README of the SQLPage repository now includes a [clear yet detailed architecture diagram](https://github.com/sqlpage/SQLPage?tab=readme-ov-file#how-it-works). -' - ); \ No newline at end of file diff --git a/examples/official-site/sqlpage/migrations/73_blog_tracing.sql b/examples/official-site/sqlpage/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/sqlpage/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/sqlpage/content/blog/tracing-sqlpage-with-opentelemetry-and-grafana.md @@ -1,11 +1,10 @@ -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'Tracing SQLPage with OpenTelemetry and Grafana', - 'How to inspect requests, SQL queries, and database wait time with distributed tracing', - 'route-2', - '2026-03-09', - ' +--- +title: Tracing SQLPage with OpenTelemetry and Grafana +date: '2026-03-09' +icon: route-2 +summary: How to inspect requests, SQL queries, and database wait time with distributed tracing +--- + # Tracing SQLPage with OpenTelemetry and Grafana When a page is slow, a log line telling you that the request took 1.8 seconds is only the start of the investigation. What you usually want to know next is where that time went: @@ -41,9 +40,9 @@ Tracing is especially helpful in SQLPage because one request often maps cleanly ## Run the example stack -The simplest way to explore tracing is to run +The simplest way to explore tracing is to run [the example shipped with SQLPage](https://github.com/sqlpage/SQLPage/tree/main/examples/telemetry). -After downloading or cloning the example, run this from the example''s folder: +After downloading or cloning the example, run this from the example's folder: ```bash docker compose up --build @@ -123,7 +122,7 @@ SELECT application_name, query, state FROM pg_stat_activity; ``` -If you also include `%a` in PostgreSQL''s `log_line_prefix`, your database logs can contain the same trace context. +If you also include `%a` in PostgreSQL's `log_line_prefix`, your database logs can contain the same trace context. ## A practical debugging example @@ -171,5 +170,3 @@ SQLPage already makes the application logic easy to inspect because it lives in By enabling OpenTelemetry and connecting SQLPage to Grafana, you can see not just that a request was slow, but why it was slow, where the time was spent, and which query or resource caused the delay. For a complete working setup, start with the [OpenTelemetry + Grafana example](https://github.com/sqlpage/SQLPage/tree/main/examples/telemetry) and adapt it to your own deployment. -' - ); diff --git a/examples/official-site/sqlpage/migrations/12_blog.sql b/examples/official-site/sqlpage/migrations/12_blog.sql index 773e29ecb..e5a13a442 100644 --- a/examples/official-site/sqlpage/migrations/12_blog.sql +++ b/examples/official-site/sqlpage/migrations/12_blog.sql @@ -6,180 +6,3 @@ CREATE TABLE blog_posts ( content TEXT, created_at TIMESTAMP NOT NULL ); - -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES - ( - 'SQLPage versus No-Code tools', - 'What are the advantages and disadvantages of SQLPage compared to No-Code tools?', - 'code-minus', - '2023-08-03', - ' -# Choosing Your Path: No-Code, Low-Code, or SQL-Based Development - -The platform you select shapes the entire trajectory of your application. -Each approach offers distinct advantages, yet demands different compromises - a choice that warrants careful consideration. - -## No-Code Platforms: Speed with Limitations - -No-Code platforms present a visual canvas for building applications without traditional programming. Whilst brilliant for rapid prototypes and straightforward departmental tools, they falter when confronted with complexity and scale. - -**Best suited to**: Quick internal tools and simple workflows - -### **Notable examples** - - - [NocoBase](https://www.nocobase.com/) - - [NocoDB](https://www.nocodb.com/) - - [Saltcorn](https://github.com/saltcorn/saltcorn) - - -## Low-Code Platforms: The Flexible Middle Ground - -These platforms artfully combine visual development with traditional coding. They maintain the power of custom code whilst accelerating development through carefully designed components. - -**Best suited to**: Complex applications requiring both speed and customisation - -### **Notable examples** - - - [Budibase](https://budibase.com/) - - [Directus](https://github.com/directus/directus) - - [Rowy](https://github.com/rowyio/rowy) - -## SQL-Based Development: Elegant Simplicity - -SQLPage offers a refreshingly direct approach: pure SQL-driven web applications. - -For those versed in SQL, it enables sophisticated data-driven applications without the overhead of additional frameworks. - -**Best suited to**: Data-centric applications and dashboards - -**Details**: [SQLPage on GitHub](https://github.com/sqlpage/SQLPage) - -## The AI Revolution in Development - -The emergence of Large Language Models (LLMs) has fundamentally shifted the landscape of application development. Tools that once demanded extensive coding expertise have become remarkably more accessible. AI assistants like ChatGPT excel particularly at generating SQL queries and database operations, making SQL-based platforms surprisingly approachable even for those with limited database experience. These AI companions serve as expert pair programmers, offering suggestions, debugging assistance, and ready-to-use code snippets. - -This transformation especially benefits platforms like SQLPage, where the AI''s prowess in SQL generation can bridge the traditional expertise gap. Even complex queries and database operations can be created through natural language conversations with AI assistants, democratising access to sophisticated data manipulation capabilities. - -## Making an Informed Choice - -Selecting the right development approach requires weighing multiple factors against your project''s specific needs. - -Consider these key decision points to guide your platform selection: - -### **Time Constraints** - - Immediate delivery required → No-Code - - Several days available → SQLPage or Low-Code - -### **Data Complexity** - - Structured data manipulation → SQLPage - - Complex workflows → Low-Code - -### **Team Expertise** - - SQL skills → SQLPage - - Limited technical expertise → No-Code - - Varied technical capabilities → Low-Code - -### **Control Requirements** - - Precise data layer control → SQLPage - - Visual design flexibility → Low-Code - - Speed over customisation → No-Code - -## Further Investigation - -For a thorough demonstration of SQLPage''s capabilities: [Building a Full Web Application with SQLPage](https://www.youtube.com/watch?v=mXdgmSdaXkg) -'); - -INSERT INTO blog_posts (title, description, icon, created_at, external_url) -VALUES ( - 'Repeating yourself thrice won''t make you a 3X developer', - 'A dive into the traditional 3-tier architecture and the DRY principle, and how tools like SQLPage helps you avoid repeating yourself.', - 'box-multiple-3', - '2023-08-01', - 'https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0' -); - -INSERT INTO blog_posts (title, description, icon, created_at, content) -VALUES ( - '3 solutions to the 3 layer problem', - 'What is the 3 layer problem, and how SQLPage solves it?', - 'adjustments-question', - '2023-08-10', - ' -# 3 solutions to the 3 layer problem - -> Some interesting questions emerged from the article [Repeating yourself thrice doesn''t turn you into a 3X developer](https://yrashk.medium.com/repeating-yourself-thrice-doesnt-turn-you-into-a-3x-developer-a778495229c0). -> This short follow-up article aims to answer them and clarify some points. - -Hello all, - -I am Ophir Lojkine, the main contributor of the open-source application server **SQLPage**. - -The previous article focused on the conventional model of splitting applications into three distinct tiers: - -1. a graphical interface (_front-end_), -2. an application server (_back-end_), -3. and a database. - -In many projects, this results in three distinct implementations of the application’s data model: - -1. First, in SQL, in the form of tables, views, and relationships in the database, -2. Then, in _server side_ languages such as Java, Python, or PHP, to create an API managing access to the data, and to implement the business logic of the application, -3. Finally, in JavaScript or TypeScript to implement data manipulation in the user interface. - -![Traditional tiers model](blog/three-layers.svg) - ---- - -The topic of interest here is the duplication of the data model between the different layers, -and the communication overhead between them. -We are not talking about how the code is structured within each layer. -It can follow a Model-View-Controller pattern or not, it doesn''t matter. - -This three-layer model has several advantages: -specialization of the programmers, -parallelization of work, -scalability, -separation of concerns, -and an optimal exploitation of the capacities of the infrastructure on which each layer is deployed: -web browser, server application and database. - -Nevertheless, in large-scale projects, -there is often a certain redundancy of the code between the different layers, -as well as a non-negligible share of code dedicated to communication between them. -For small teams and solo developers, this becomes a major drawback. - -## 3 solutions - -Fortunately, there are several approaches to solving this problem: - -1. For **UI-centric applications** without complicated data processing needs, -you can almost completely abandon server-side development and **directly expose the data to the frontend**. -Open-source tools available in this space include Supabase, PocketBase or Hasura. -2. For **applications with a predominant business logic**, traditional _web frameworks_ -solve this problem by centralizing frontend and database control in the backend code. -A common solution involves using an ORM and templating system instead of a dedicated javascript application. -Popular solutions include Django, Ruby on Rails, or Symphony. -3. For simpler applications, it is possible to **avoid both backend and frontend development** -by adopting a _database-first_ approach. -This alternative, although less widespread, allows taking advantage of under-exploited modern capacities of relational databases. -The purpose of the original article was to introduce this lesser known approach. - * **SQLPage** is representative of this last category, - which allows designing a complete web application _in SQL_. - This leads to a loss of control over the precise visual appearance of the application, - which will get a “standardized” look and feel. - On the other hand, this translates into significant gains in terms of development speed, - simplicity and performance. - This solution is not intended to compete with traditional _frameworks_, - but rather integrate earlier in the life cycle of a project. - It thus makes it possible to quickly develop a data structure adapted to the application, - and to iterate over it while benefiting from continuous visual feedback on the final result. - Then, when the application grows, it’s easy to add a classic frontend and backend on top of the existing database, - without having to start from scratch. - -Whichever approach is chosen in the end, -a solid understanding of the conventional three-tier architecture, -as well as a clear perspective on the challenges it creates and the possible solutions, -facilitates decision-making and the evolution of the project with the best suited technologies. - ' - ); \ No newline at end of file diff --git a/examples/official-site/test.hurl b/examples/official-site/test.hurl index 8e9bc41a5..4fca24280 100644 --- a/examples/official-site/test.hurl +++ b/examples/official-site/test.hurl @@ -71,6 +71,12 @@ HTTP 200 [Asserts] xpath "normalize-space(//main//h3/a[@href='/functions.sql?function=variables'])" == "variables([method])" +GET http://localhost:8080/blog.sql?post=How+to+use+the+pagination+component +HTTP 200 +[Asserts] +body contains "idx_page" +body not contains "An error occurred" + GET http://localhost:8080/blog.sql?post=Repeating+yourself+thrice+won%27t+make+you+a+3X+developer HTTP 302 [Asserts] diff --git a/scripts/official-site/blog.rs b/scripts/official-site/blog.rs new file mode 100644 index 000000000..28a723825 --- /dev/null +++ b/scripts/official-site/blog.rs @@ -0,0 +1,46 @@ +use super::content::markdown_pages; +use anyhow::{Context, Result, ensure}; +use chrono::NaiveDate; +use serde::Deserialize; +use sqlx::{query::query, sqlite::SqliteConnection}; +use std::path::Path; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Post { + title: String, + date: String, + icon: String, + summary: String, + external_url: Option, +} + +pub(super) async fn insert(db: &mut SqliteConnection, site: &Path) -> Result<()> { + for (path, post, body) in markdown_pages::(&site.join("sqlpage/content/blog"))? { + let date = NaiveDate::parse_from_str(&post.date, "%Y-%m-%d") + .with_context(|| format!("Invalid publication date in {}", path.display()))?; + ensure!( + !body.is_empty() + || post + .external_url + .as_ref() + .is_some_and(|url| !url.is_empty()), + "Expected article text or an external URL in {}", + path.display() + ); + query( + "INSERT INTO blog_posts (title, created_at, icon, description, external_url, content) + VALUES (?, ?, ?, ?, ?, ?)", + ) + .bind(post.title) + .bind(date) + .bind(post.icon) + .bind(post.summary) + .bind(post.external_url) + .bind((!body.is_empty()).then_some(body)) + .execute(&mut *db) + .await + .with_context(|| format!("Storing blog post {}", path.display()))?; + } + Ok(()) +} diff --git a/scripts/official-site/content.rs b/scripts/official-site/content.rs new file mode 100644 index 000000000..04bb75381 --- /dev/null +++ b/scripts/official-site/content.rs @@ -0,0 +1,43 @@ +use anyhow::{Context, Result, ensure}; +use config::{Config, File, FileFormat}; +use serde::de::DeserializeOwned; +use std::path::{Path, PathBuf}; +use walkdir::WalkDir; + +pub(super) fn markdown_pages( + directory: &Path, +) -> Result> { + let mut pages = Vec::new(); + for entry in WalkDir::new(directory) + .min_depth(1) + .max_depth(1) + .sort_by_file_name() + { + let entry = entry?; + let path = entry.into_path(); + if path.extension().and_then(std::ffi::OsStr::to_str) != Some("md") { + continue; + } + let (metadata, body) = read_page(&path).with_context(|| path.display().to_string())?; + pages.push((path, metadata, body)); + } + ensure!( + !pages.is_empty(), + "No Markdown pages in {}", + directory.display() + ); + Ok(pages) +} + +fn read_page(path: &Path) -> Result<(T, String)> { + let text = super::read(path)?; + let (metadata, body) = text + .strip_prefix("---\n") + .and_then(|text| text.split_once("\n---\n")) + .context("Expected YAML front matter delimited by ---")?; + let metadata = Config::builder() + .add_source(File::from_str(metadata, FileFormat::Yaml)) + .build()? + .try_deserialize()?; + Ok((metadata, body.trim().to_owned())) +} diff --git a/scripts/official-site/main.rs b/scripts/official-site/main.rs index 8069eebc5..a065bd011 100644 --- a/scripts/official-site/main.rs +++ b/scripts/official-site/main.rs @@ -1,5 +1,7 @@ mod parameters; +mod blog; + use anyhow::{Context, Result, ensure}; use markdown::{ParseOptions, mdast::Node}; use parameters::Document; @@ -14,6 +16,8 @@ use std::fs; use std::path::Path; use walkdir::WalkDir; +mod content; + const COMPONENTS: &str = "reference/components"; #[tokio::main(flavor = "current_thread")] @@ -39,6 +43,7 @@ async fn main() -> Result<()> { .run(&mut db) .await?; let mut tx = db.begin().await?; + blog::insert(&mut tx, &site).await?; for entry in fs::read_dir(root.join("sqlpage/templates"))? { let path = entry?.path();