jekyll-sqlite
Advanced tools
+3
-0
@@ -13,2 +13,5 @@ --- | ||
| ## [0.4.0] - 2026-05-05 | ||
| - Adds collection support | ||
| ## [0.2.1] - 2026-01-03 | ||
@@ -15,0 +18,0 @@ - Only passes named parameters in SQLite query. Requires sqlite3-ruby 2.9.0 |
| # frozen_string_literal: true | ||
| require "sqlite3" | ||
| require "time" | ||
| module JekyllSQlite | ||
| # Main generator class | ||
| # rubocop:disable Metrics/ClassLength | ||
| class Generator < Jekyll::Generator | ||
@@ -62,8 +64,10 @@ # Set to high to be higher than the Jekyll Datapages Plugin | ||
| ## | ||
| # Validate given configuration object | ||
| # Validate given configuration object. | ||
| # A config is valid when it is a Hash with a query, a readable file, | ||
| # and either a data: or collection: target. | ||
| def valid_config?(config) | ||
| return false unless config.is_a? Hash | ||
| return false unless config.key?("query") | ||
| return false unless File.exist?(config["file"]) | ||
| return false unless config.key?("data") | ||
| return false unless config["file"] && File.exist?(config["file"]) | ||
| return false unless config.key?("data") || config.key?("collection") | ||
@@ -105,3 +109,8 @@ true | ||
| end | ||
| generate_data_from_config(root, config) | ||
| if config["collection"] | ||
| generate_collection_from_config(config) | ||
| else | ||
| generate_data_from_config(root, config) | ||
| end | ||
| end | ||
@@ -111,5 +120,57 @@ end | ||
| ## | ||
| # Build documents from query rows and append them to the named site collection. | ||
| def generate_collection_from_config(config) | ||
| name = config["collection"] | ||
| collection = @site.collections[name] | ||
| unless collection | ||
| Jekyll.logger.error "Jekyll SQLite:", "Collection '#{name}' not declared in _config.yml" | ||
| return | ||
| end | ||
| db = get_database(config["file"]) | ||
| db.results_as_hash = config.fetch("results_as_hash", true) | ||
| rows = db.execute(config["query"]) | ||
| rows.each_with_index { |row, idx| collection.docs << build_collection_doc(collection, row, idx) } | ||
| Jekyll.logger.info "Jekyll SQLite:", "Loaded collection #{name}. Count=#{rows.size}" | ||
| end | ||
| # Build a synthetic document path from optional `name` and `path` columns. | ||
| # Falls back to a 1-based row id (idx+1) when `name` is missing, and to | ||
| # no subdirectory when `path` is missing. The `name` and `path` SQL | ||
| # columns are what feed Jekyll's :name and :path permalink placeholders. | ||
| def synth_doc_path(collection, row, idx) | ||
| name = column_string(row, "name") || (idx + 1).to_s | ||
| subdir = column_string(row, "path") | ||
| parts = ["_#{collection.label}"] | ||
| parts << subdir if subdir | ||
| parts << "#{name}.md" | ||
| File.join(@site.source, *parts) | ||
| end | ||
| def build_collection_doc(collection, row, idx) | ||
| doc = Jekyll::Document.new(synth_doc_path(collection, row, idx), | ||
| site: @site, collection: collection) | ||
| row.each do |k, v| | ||
| next unless k.is_a?(String) | ||
| v = Time.parse(v) if k == "date" && v.is_a?(String) | ||
| doc.data[k] = v | ||
| end | ||
| # Jekyll's :title permalink placeholder reads data["slug"], not data["title"]. | ||
| # Auto-populate slug from title so SQL-provided titles show up in URLs. | ||
| doc.data["slug"] ||= doc.data["title"] | ||
| doc.content = row.key?("content") ? row["content"].to_s : "" | ||
| doc | ||
| end | ||
| def column_string(row, key) | ||
| v = row[key] | ||
| v.is_a?(String) && !v.empty? ? v : nil | ||
| end | ||
| ## | ||
| # Entrpoint to the generator, called by Jekyll | ||
| def generate(site) | ||
| @db = {} | ||
| @site = site | ||
| gen(site.data, site.config) | ||
@@ -123,2 +184,3 @@ site.pages.each do |page| | ||
| end | ||
| # rubocop:enable Metrics/ClassLength | ||
| end |
@@ -5,4 +5,4 @@ # frozen_string_literal: true | ||
| module Sqlite | ||
| VERSION = "0.2.1" | ||
| VERSION = "0.4.0" | ||
| end | ||
| end |
-26
| plugins: rubocop-rake | ||
| AllCops: | ||
| TargetRubyVersion: 3.2 | ||
| NewCops: enable | ||
| Exclude: | ||
| - "node_modules/**/*" | ||
| - "tmp/**/*" | ||
| - "vendor/**/*" | ||
| - ".git/**/*" | ||
| - "test/_plugins/jekyll_sqlite_generator.rb" | ||
| - "docs/**/*" | ||
| Style/StringLiterals: | ||
| Enabled: true | ||
| EnforcedStyle: double_quotes | ||
| Style/StringLiteralsInInterpolation: | ||
| Enabled: true | ||
| EnforcedStyle: double_quotes | ||
| Layout/LineLength: | ||
| Max: 120 | ||
| Metrics/AbcSize: | ||
| Max: 20 | ||
| Metrics/MethodLength: | ||
| Max: 100 |
| # Contributor Covenant Code of Conduct | ||
| ## Our Pledge | ||
| We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. | ||
| We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. | ||
| ## Our Standards | ||
| Examples of behavior that contributes to a positive environment for our community include: | ||
| * Demonstrating empathy and kindness toward other people | ||
| * Being respectful of differing opinions, viewpoints, and experiences | ||
| * Giving and gracefully accepting constructive feedback | ||
| * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience | ||
| * Focusing on what is best not just for us as individuals, but for the overall community | ||
| Examples of unacceptable behavior include: | ||
| * The use of sexualized language or imagery, and sexual attention or | ||
| advances of any kind | ||
| * Trolling, insulting or derogatory comments, and personal or political attacks | ||
| * Public or private harassment | ||
| * Publishing others' private information, such as a physical or email | ||
| address, without their explicit permission | ||
| * Other conduct which could reasonably be considered inappropriate in a | ||
| professional setting | ||
| ## Enforcement Responsibilities | ||
| Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. | ||
| Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. | ||
| ## Scope | ||
| This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. | ||
| ## Enforcement | ||
| Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at coc@captnemo.in. All complaints will be reviewed and investigated promptly and fairly. | ||
| All community leaders are obligated to respect the privacy and security of the reporter of any incident. | ||
| ## Enforcement Guidelines | ||
| Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: | ||
| ### 1. Correction | ||
| **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. | ||
| **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. | ||
| ### 2. Warning | ||
| **Community Impact**: A violation through a single incident or series of actions. | ||
| **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. | ||
| ### 3. Temporary Ban | ||
| **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. | ||
| **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. | ||
| ### 4. Permanent Ban | ||
| **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. | ||
| **Consequence**: A permanent ban from any sort of public interaction within the community. | ||
| ## Attribution | ||
| This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, | ||
| available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. | ||
| Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). | ||
| [homepage]: https://www.contributor-covenant.org | ||
| For answers to common questions about this code of conduct, see the FAQ at | ||
| https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. |
| --- | ||
| title: Contribution Guide | ||
| --- | ||
| # Contributing to jekyll-sqlite | ||
| **This document is a work-in-progress.** | ||
| This doc is a short introduction on how to modify and maintain the sqlite3-ruby gem. | ||
| ## Making a Release | ||
| 0. Update `version.rb` | ||
| 0. Update CHANGELOG.md | ||
| 1. Run `bundle exec rake rubocop` to lint | ||
| 2. Commit + push | ||
| 3. If build passes, tag and push the tag. | ||
| Gem publication on rubygems automatically happens via GitHub Actions. | ||
| ## Running Tests | ||
| `bundle exec rake test` | ||
| ## Test Infrastructure | ||
| The tests are maintained in `test` directory as a separate jekyll website. | ||
| The site is built inside `Rakefile`, and it uses JSON output files as templates. | ||
| These JSON output files can then be used for testing the plugin. | ||
| ## Rubocop | ||
| Linting is mandatory to pass the CI. | ||
| ## Docs | ||
| Docs are maintained in docs/ directory as a separate Jekyll site that uses | ||
| just-the-docs theme. A few markdown files are symlinked inside docs so that | ||
| they get published to the website as well. | ||
| ## Demo | ||
| The demo is maintained separately on another repo, but the expectation is that | ||
| all important features are used in the demo. If you contribute such a change | ||
| that adds a new feature, please update the demo as well. |
| theme: just-the-docs | ||
| title: Jekyll SQLite | ||
| description: >- | ||
| generator plugin to lets you use SQLite database instead of data files as a | ||
| data source. It lets you easily create APIs and websites from a SQLite | ||
| database, by linking together a database file, your template, and the relevant | ||
| queries. | ||
| baseurl: "/jekyll-sqlite" | ||
| url: "https://captnemo.in" | ||
| github_username: captn3m0 | ||
| # https://just-the-docs.com/docs/configuration/ | ||
| favicon_ico: https://jekyllrb.com/favicon.ico | ||
| aux_links: | ||
| GitHub: | ||
| - "https://github.com/captn3m0/jekyll-sqlite/" | ||
| RubyGems: | ||
| - "https://rubygems.org/gems/jekyll-sqlite" | ||
| gh_edit_link: true | ||
| gh_edit_link_text: "Edit this page on GitHub." | ||
| gh_edit_repository: "https://github.com/captn3m0/jekyll-sqlite" # the github URL for your repo | ||
| gh_edit_branch: "main" | ||
| gh_edit_source: docs | ||
| gh_edit_view_mode: "edit" | ||
| callouts: | ||
| demo: | ||
| color: green | ||
| opacity: 0.5 | ||
| note: | ||
| color: yellow | ||
| opacity: 0.3 | ||
| # https://jekyllrb.com/docs/configuration/front-matter-defaults/ | ||
| defaults: | ||
| - scope: | ||
| path: "" | ||
| values: | ||
| layout: default | ||
| encoding: utf-8 | ||
| markdown: kramdown | ||
| strict_front_matter: true | ||
| # Silence Saas deprecation warnings, to be removed after this is fixed in just-the-docs | ||
| sass: | ||
| quiet_deps: true # https://github.com/just-the-docs/just-the-docs/issues/1541 | ||
| silence_deprecations: ['import'] |
| _site | ||
| .sass-cache | ||
| .jekyll-cache | ||
| .jekyll-metadata | ||
| vendor |
| --- | ||
| permalink: /404.html | ||
| layout: page | ||
| --- | ||
| <h1>404</h1> | ||
| <p><strong>Page not found :(</strong></p> | ||
| <p>The requested page could not be found.</p> |
-30
| --- | ||
| title: Demo | ||
| --- | ||
| 🏁 A fully-functional demo website that uses this plugin is available at | ||
| [northwind.captnemo.in](https://northwind.captnemo.in). The source code for | ||
| the demo is available at [captn3m0/northwind](https://github.com/captn3m0/northwind). | ||
| You can find more details at the demo page. | ||
| Here is a screenshot: | ||
|  | ||
| It relies on all features of the plugin, along with using `jekyll-datapage_gen` | ||
| plugin to generate individual pages for each data item. | ||
| 1. A [per-page query](usage/#per-page-queries) is used on the restock page to generate list of | ||
| products that need to be restocked. [source](https://github.com/captn3m0/northwind/blob/main/restock.md?plain=1) | ||
| 2. Customers, Orders, Products, Categories are set as global data items | ||
| in [config.yml](https://github.com/captn3m0/northwind/blob/main/_config.yml) | ||
| 3. `site.data.categories[*].products` is filled using a parameterised query | ||
| in [`config.yml`](https://github.com/captn3m0/northwind/blob/main/_config.yml#L47-L49) | ||
| 4. Featured Product and Employee of the Month, shown on homepage are set by a query | ||
| in `config.yml`, but the query parameters are set in [`_data`](https://github.com/captn3m0/northwind/tree/main/_data) | ||
| directory as YML files. | ||
| 5. The datapage plugin config generates a page for every product and customer. | ||
| 6. A multi-level nested query is used to generate a list of employees. See [Nested Query]({% link usage/nested.md %}) in docs. | ||
| 7. A permalink is set for all the customers by creating a permalink attribute in the select query: `SELECT ... as permalink`. Since we are setting a top-level attribute in the final page, it cannot be set alongside `page_data_prefix` in the datapage_gen configuration. See [this commit](https://github.com/captn3m0/northwind/commit/3d70d6a81be34af5f1ebbcfa5da09a170f2ee9ff) for the implementation. I'd suggest only using this when the `dir + name/name_expr` configuration in the `datapage` plugin fall short. | ||
| The database is a trimmed-version of the northwind database from <https://github.com/jpwhite3/northwind-SQLite3>. |
| source "https://rubygems.org" | ||
| gem "jekyll", "~> 4.4.1" | ||
| gem "just-the-docs" | ||
| gem "logger", "~> 1.7" |
-14
| --- | ||
| title: Help | ||
| --- | ||
| Need help? You can file a new issue on GitHub at | ||
| <https://github.com/captn3m0/jekyll-sqlite/issues/new>. | ||
| This project is intended to be a safe, welcoming space for collaboration, and | ||
| contributors are expected to adhere to the [code of conduct][coc]. | ||
| Note that only maintained versions of [Jekyll](https://endoflife.date/jekyll) | ||
| and [Ruby](https://endoflife.date/ruby) are supported. | ||
| [coc]: https://github.com/captn3m0/jekyll-sqlite/blob/main/CODE_OF_CONDUCT.md |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
| --- | ||
| title: Home | ||
| nav_order: 0 | ||
| --- | ||
| A Jekyll generator plugin to lets you use SQLite databases instead of [Data Files][df] as a | ||
| data source. It lets you easily create APIs and websites from a SQLite | ||
| database, by linking together a database file, your template, and the relevant | ||
| queries. | ||
| Jekyll's Data Files are great, but they are limited to YAML/JSON/TSV/CSV file | ||
| formats - this plugin gives you another option: SQLite databases. | ||
| It supports site-level queries, per-page queries, and prepared queries that can | ||
| use existing data (possibly generated via more queries) as parameters. | ||
| The primary usecase is to **avoid Liquid Hell**, wherein you're left mangling | ||
| multiple data sources from CSV/JSON/YAML files using liquid templating by | ||
| saving temporary variables, creating maps, and so on. SQL is a decent language | ||
| for reshaping datasets - supporting joins, filters, and aggregations. So this | ||
| allows you to use SQL for reshaping your data, and then use liquid | ||
| for what it was meant for - presentation and templating. | ||
| [](https://github.com/captn3m0/jekyll-sqlite/actions/workflows/main.yml) [](https://rubygems.org/gems/jekyll-sqlite) | ||
| [df]: https://jekyllrb.com/docs/datafiles/ "Data Files at Jekyll Docs site" |
| --- | ||
| title: Installation | ||
| --- | ||
| Add this line to your site's `Gemfile`: | ||
| ```ruby | ||
| gem 'jekyll-sqlite' | ||
| ``` | ||
| And then add this line to your site's `_config.yml`: | ||
| ```yml | ||
| plugins: | ||
| - jekyll_sqlite | ||
| ``` | ||
| See [Usage](/jekyll-sqlite/usage/) for next steps. | ||
| --- | ||
| Note that only supported versions of [Ruby](https://endoflife.date/ruby) | ||
| and [Jekyll](https://endoflife.date/ruby) are supported. |
| --- | ||
| title: Using with Datapage Plugin | ||
| parent: Usage | ||
| nav_order: 2 | ||
| --- | ||
| The Jekyll [Datapage Generator](https://github.com/avillafiorita/jekyll-datapage_gen) | ||
| plugin allows you to specify data files for which we want to | ||
| generate one page per record. | ||
| You can use it alongside this plugin to generate data from a SQLite database, | ||
| and generate a page per row of your resultset. | ||
| This is how a simple configuration would look: | ||
| ```yaml | ||
| # for the sqlite plugin | ||
| sqlite: | ||
| - data: restaurants | ||
| file: _db/reviews.db | ||
| query: SELECT id, name, last_review_date > 1672531200 as active, address FROM restaurants; | ||
| # for the datapage_gen plugin | ||
| page_gen: | ||
| - data: restaurants | ||
| # The layout used for each generated page _layouts/restaurant.html | ||
| template: restaurant | ||
| page_data_prefix: restaurants | ||
| name: id | ||
| title: name | ||
| filter: active | ||
| ``` | ||
| This will automatically generate a file for each restaurant `restaurants/# | ||
| {id}.html` file with the layout `_layouts/restaurant.html` and page.id, | ||
| page.name, page.active set and page.title set to restaurant name. Query data is | ||
| accessed in the page template via `{%raw%}{{ page.restaurants.address }}{%endraw%}` - the | ||
| namespace set in `page_data_prefix`. | ||
| Note that the `datapage_gen` plugin will run _after_ the `jekyll-sqlite` plugin, if you generate any pages with per-page queries, these queries will not execute. | ||
| ## Demo Example | ||
| The following example comes from the [Demo]({% link demo.md %}). | ||
| The following datapage configuration in `_config.yml`: | ||
| ```yml | ||
| page_gen: | ||
| - data: products | ||
| template: product # _layouts/product.html | ||
| page_data_prefix: product | ||
| title: ProductName | ||
| name: ProductID | ||
| extension: html | ||
| ``` | ||
| will generate a page for each product in the `site.data.products` array. | ||
| In order to get data into the array, we can use: | ||
| ```yml | ||
| sqlite: | ||
| - data: products | ||
| file: _db/northwind.db | ||
| query: SELECT * from Products | ||
| ``` | ||
| Here's a screenshot of how it looks: | ||
|  | ||
| See it in action at <https://northwind.captnemo.in/products/1.html> |
| --- | ||
| title: Dynamic DB File | ||
| parent: Usage | ||
| nav_order: 3 | ||
| --- | ||
| If you want to select the database filename via an environment variable, | ||
| you can use the following options as a workaround: | ||
| ## Using `envsubst` from GNU gettext | ||
| You can install it via [brew](https://formulae.brew.sh/formula/gettext) | ||
| or [on linux](https://repology.org/project/gettext/versions). | ||
| First, define your database filename, | ||
| and create a new configuration template file. | ||
| ```sh | ||
| export JEKYLL_DB=events-blr.db | ||
| cp _config.yml _config.txt | ||
| ``` | ||
| Then, use the database name in your new ocnfig file | ||
| ```yaml | ||
| sqlite: | ||
| data: events | ||
| file: $JEKYLL_DB | ||
| query: SELECT * FROM events | ||
| ``` | ||
| Then, use `envsubst` to generate the `_config.yml` | ||
| ```bash | ||
| envsubst < "_config.txt" > "_config.yml" | ||
| ``` | ||
| ## Using multiple configuration files | ||
| You can define your `sqlite` parameter multiple times | ||
| across multiple files, using different database filenames | ||
| For eg, `_config-blr.yml` could only include: | ||
| ``` | ||
| sqlite: | ||
| data: events | ||
| file: events-blr.db | ||
| query: SELECT * FROM events | ||
| ``` | ||
| And you can run jekyll using `jekyll --config _config.yml,_config-blr.yml` | ||
| However, this requires duplicating your query across multiple files. |
| --- | ||
| title: Usage | ||
| has_toc: false | ||
| permalink: /usage/ | ||
| --- | ||
| Update your `_config.yml` to define your data sources with your SQLite database. | ||
| ```yml | ||
| ... | ||
| sqlite: | ||
| - data: customers | ||
| file: *db | ||
| query: SELECT * from Customers | ||
| ``` | ||
| Then, you can use the `site.data` attributes accordingly: | ||
| ```liquid{%raw%} | ||
| {{ site.data.customers | jsonify }}{%endraw%} | ||
| ``` |
| --- | ||
| title: Nested Queries | ||
| parent: Usage | ||
| nav_order: 4 | ||
| --- | ||
| Starting from `0.2.0`, queries can be nested infinitely. | ||
| The following configuration is used in the [Demo]({% link demo.md %}): | ||
| ```yaml | ||
| sqlite: | ||
| - data: regions | ||
| file: *db | ||
| query: | | ||
| SELECT RegionID, RegionDescription FROM Regions | ||
| ORDER BY RegionID | ||
| - data: regions.territories | ||
| file: *db | ||
| query: | | ||
| SELECT TerritoryID, TerritoryDescription FROM Territories | ||
| WHERE RegionID = :RegionID | ||
| ORDER BY TerritoryDescription | ||
| - data: regions.territories.EmployeeIDs | ||
| file: *db | ||
| query: | | ||
| SELECT T.EmployeeID as EmployeeID, FirstName,LastName | ||
| FROM EmployeeTerritories T,Employees | ||
| WHERE T.TerritoryID = :TerritoryID | ||
| AND T.EmployeeID = Employees.EmployeeID | ||
| ``` | ||
| The first query generates `site.data.regions` as a list. The second query | ||
| sets territories inside each of the regions, and the third query | ||
| sets the list of employees inside each territory. | ||
| {: .note } | ||
| > Per Page Query | ||
| > | ||
| > On the Demo website, you can see the result at | ||
| > [the regions page](https://northwind.captnemo.in/regions.html) | ||
| > where each region is broken into territories, with the name | ||
| > of the employee under each region. |
| --- | ||
| title: Per-page Queries | ||
| nav_order: 0 | ||
| parent: Usage | ||
| --- | ||
| The exact same syntax can be used on a per-page basis to generate data within | ||
| each page. This is helpful for keeping page-specific queries within the page | ||
| itself. Here's an example: | ||
| ```yaml | ||
| --- | ||
| FeaturedSupplierID: 2 | ||
| sqlite: | ||
| - data: suppliers | ||
| file: "_db/northwind.db" | ||
| query: "SELECT CompanyName, SupplierID FROM suppliers ORDER BY SupplierID" | ||
| - data: suppliers.products | ||
| # This is a prepared query, where SupplierID is coming from the previous query. | ||
| file: "_db/northwind.db" | ||
| query: "SELECT ProductName, CategoryID,UnitPrice FROM products WHERE SupplierID = :SupplierID" | ||
| # :FeaturedSupplierID is picked up automatically from the page frontmatter. | ||
| - data: FeaturedSupplier | ||
| file: "_db/northwind.db" | ||
| query: "SELECT * SupplierID = :FeaturedSupplierID" | ||
| --- | ||
| {%raw%}{{page.suppliers|jsonify}}{%endraw%} | ||
| ``` | ||
| This will generate a `page.suppliers` array with all the suppliers, and a `page.FeaturedSupplier` object with the details of the featured supplier. | ||
| Each supplier will have a `products` array with all the products for that supplier. | ||
| {: .note } | ||
| > Per Page Query | ||
| > | ||
| > On the Demo website, a per-page query | ||
| > is used on the restock page to generate | ||
| > list of products that need to be restocked. You can see the | ||
| > [source](https://github.com/captn3m0/northwind/blob/main/restock.md?plain=1) | ||
| > and the [resulting page](https://northwind.captnemo.in/restock.html) |
| --- | ||
| title: Parametrized Queries | ||
| parent: Usage | ||
| nav_order: 1 | ||
| --- | ||
| This plugin supports prepared queries with parameter binding. This lets you | ||
| use existing data from a previous query, or some other source (such as | ||
| `site.data.*` or `page.*`) as a parameter in your query. | ||
| Say you have a YAML file defining your items (`data/books.yaml`): | ||
| ```yaml | ||
| - id: 31323952-2708-42dc-a995-6006a23cbf00 | ||
| name: Time Travel with a Rubber Band | ||
| - id: 5c8e67a0-d490-4743-b5b8-8e67bd1f95a2 | ||
| name: The Art of Cache Invalidation | ||
| ``` | ||
| and the prices for the items in your SQLite database, the following configuration will enrich the `items` array with the price: | ||
| ```yaml | ||
| sql: | ||
| - data: items.books | ||
| file: books.db | ||
| query: SELECT price, author FROM pricing WHERE id =:id | ||
| ``` | ||
| This would allow the following Liquid loop to be written: | ||
| ```liquid{%raw%} | ||
| {% for item in site.data.items %} | ||
| {{item.meta.price}}, {{item.meta.author}} | ||
| {% endfor %}{%endraw%} | ||
| ``` |
| # frozen_string_literal: true | ||
| require_relative "lib/jekyll-sqlite/version" | ||
| Gem::Specification.new do |spec| | ||
| spec.name = "jekyll-sqlite" | ||
| spec.license = "MIT" | ||
| spec.version = Jekyll::Sqlite::VERSION | ||
| spec.authors = ["Nemo"] | ||
| spec.email = ["jekyll-sqlite@captnemo.in"] | ||
| spec.summary = "A Jekyll plugin to use SQLite databases as a data source." | ||
| spec.homepage = "https://github.com/captn3m0/jekyll-sqlite" | ||
| spec.required_ruby_version = ">= 3.2.0" | ||
| spec.metadata["homepage_uri"] = spec.homepage | ||
| spec.metadata["source_code_uri"] = spec.homepage | ||
| spec.metadata["changelog_uri"] = "https://github.com/captn3m0/jekyll-sqlite/blob/master/CHANGELOG.md" | ||
| # Specify which files should be added to the gem when it is released. | ||
| # The `git ls-files -z` loads the files in the RubyGem that have been added into git. | ||
| spec.files = Dir.chdir(__dir__) do | ||
| `git ls-files -z`.split("\x0").reject do |f| | ||
| (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|circleci)|appveyor)}) | ||
| end | ||
| end | ||
| spec.bindir = "exe" | ||
| spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } | ||
| spec.require_paths = ["lib"] | ||
| spec.add_dependency "sqlite3", "~> 2.9.0" | ||
| spec.metadata["rubygems_mfa_required"] = "true" | ||
| end |
-84
| # frozen_string_literal: true | ||
| require "bundler/gem_tasks" | ||
| require "rubocop/rake_task" | ||
| require "jekyll" | ||
| require "sqlite3" | ||
| RuboCop::RakeTask.new | ||
| def assert(cond, msg = "Assertion Failed") | ||
| raise msg unless cond | ||
| end | ||
| def query_db(query) | ||
| db = SQLite3::Database.new "_db/northwind.db" | ||
| db.results_as_hash = true | ||
| results = db.execute query | ||
| results[0] | ||
| end | ||
| # rubocop:disable Metrics/AbcSize | ||
| def validate_json | ||
| file = "_site/data.json" | ||
| data = JSON.parse(File.read(file)) | ||
| assert data["orders"].size == 53, "Expected 53 orders, got #{data["orders"].size}" | ||
| assert data["customers"].size == 93, "Expected 93 customers, got #{data["customers"].size}" | ||
| assert data["categories"].size == 8, "Expected 93 categories, got #{data["categories"].size}" | ||
| assert data["orders"][0] == query_db("SELECT * FROM Orders LIMIT 1"), "Order Fetch Failed" | ||
| assert data["customers"][0] == query_db("SELECT * FROM Customers LIMIT 1"), "Customer Fetch Failed" | ||
| assert data["customers"][0] == query_db("SELECT * FROM Customers LIMIT 1"), "Customer Fetch Failed" | ||
| assert data["categories"][0]["products"].size == 12, "Products don't match" | ||
| data["categories"][0]["products"].each do |p| | ||
| assert p["CategoryID"] == 1, "CategoryID doesn't match" | ||
| end | ||
| assert data["delayedOrders"].size == 17 | ||
| assert data["delayedOrders"][0]["OrderID"] == 10_249 | ||
| end | ||
| def validate_page_json | ||
| file = "_site/suppliers.json" | ||
| read_data = JSON.parse(File.read(file)) | ||
| data = read_data["allSuppliers"] | ||
| assert data.size == 29, "Expected 29 suppliers, got #{data.size}" | ||
| r = query_db("SELECT CompanyName, SupplierID FROM Suppliers ORDER BY SupplierID LIMIT 1") | ||
| assert r["CompanyName"] == data[0]["CompanyName"], "Company Name doesn't match" | ||
| assert r["SupplierID"] == data[0]["SupplierID"], "Supplier ID doesn't match" | ||
| assert data[0]["products"].size == 3, "Products don't match" | ||
| assert data[0]["products"][0]["ProductName"] == "Chai" | ||
| assert data[0]["products"][1]["ProductName"] == "Chang" | ||
| assert data[0]["products"][2]["ProductName"] == "Aniseed Syrup" | ||
| # Focus Supplier - this uses the data from the page front-matter to prepare a query | ||
| fs = query_db("SELECT * FROM Suppliers WHERE SupplierID = 6") | ||
| assert read_data["focusSupplier"][0] == fs, "Focus Supplier doesn't match" | ||
| end | ||
| def validate_employees_json | ||
| file = "_site/employees.json" | ||
| regions = JSON.parse(File.read(file)) | ||
| assert regions.size == 4 | ||
| assert regions[0]["RegionID"] == 1, "First RegionID should be 1" | ||
| assert regions[0]["RegionDescription"] == "Eastern", "First Region is Eastern" | ||
| assert regions[-1]["RegionID"] == 4, "Four zotal Regions" | ||
| assert regions[0]["territories"].size == 19, "There should be 19 territories in Eastern" | ||
| assert regions[0]["territories"][0]["TerritoryID"] == "01730", "First TerritoryID should be 1" | ||
| assert regions[0]["territories"][0]["TerritoryDescription"] == "Bedford", "First TerritoryID should be Bedford" | ||
| bedford = regions[0]["territories"][0] | ||
| assert bedford == { | ||
| "TerritoryID" => "01730", | ||
| "TerritoryDescription" => "Bedford", | ||
| "EmployeeIDs" => [{ "EmployeeID" => 2, "FirstName" => "Andrew", "LastName" => "Fuller" }] | ||
| }, "Bedford should have Andrew Fuller" | ||
| end | ||
| # rubocop:enable Metrics/AbcSize | ||
| task default: :rubocop | ||
| desc "Build Test Site" | ||
| task :test do | ||
| Dir.chdir("test") | ||
| Jekyll::Site.new(Jekyll.configuration).process | ||
| validate_json | ||
| validate_page_json | ||
| validate_employees_json | ||
| end |