Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(gatsby-source-sql): add new plugin to handle sql as a source #11100

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions examples/using-gatsby-source-sql/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
PATH_PREFIX=/

DATAFILE1=./data/sqlite_markdown.sqlite3
DATAFILE2=./data/Chinook_Sqlite.sqlite

PG_HOST=
PG_USERNAME=
PG_PASSWORD=
PG_DATABAS=
9 changes: 9 additions & 0 deletions examples/using-gatsby-source-sql/.env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
PATH_PREFIX=/using-gatsby-source-sql

DATAFILE1=./data/sqlite_markdown.sqlite3
DATAFILE2=./data/Chinook_Sqlite.sqlite

PG_HOST=
PG_USERNAME=
PG_PASSWORD=
PG_DATABAS=
75 changes: 75 additions & 0 deletions examples/using-gatsby-source-sql/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# dotenv environment variables file
.env

# gatsby files
.cache/
public

# Mac files
.DS_Store

# Yarn
yarn-error.log
.pnp/
.pnp.js
# Yarn Integrity file
.yarn-integrity

# Local plugins
plugins/

# Python Virtual Env
venv/
5 changes: 5 additions & 0 deletions examples/using-gatsby-source-sql/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"semi": false,
"singleQuote": true,
"trailingComma": "es5"
}
22 changes: 22 additions & 0 deletions examples/using-gatsby-source-sql/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2015 gatsbyjs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

10 changes: 10 additions & 0 deletions examples/using-gatsby-source-sql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<p align="center">
<a href="https://www.gatsbyjs.org">
<img alt="Gatsby" src="https://www.gatsbyjs.org/monogram.svg" width="60" />
</a>
</p>
<h1 align="center">
Gatsby's SQL Source Example
</h1>

This is an example site built with an SQLite source.
Binary file not shown.
Binary file not shown.
7 changes: 7 additions & 0 deletions examples/using-gatsby-source-sql/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Implement Gatsby's Browser APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/browser-apis/
*/

// You can delete this file if you're not using it
86 changes: 86 additions & 0 deletions examples/using-gatsby-source-sql/gatsby-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
require(`dotenv`).config({
path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
pathPrefix: process.env.PATH_PREFIX,
siteMetadata: {
title: `Gatsby with a SQL source`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-sql`,
options: {
typeName: `Article`,
fieldName: `articles`,
dbEngine: {
client: `sqlite3`,
connection: {
filename: process.env.DATAFILE1,
},
useNullAsDefault: true,
},
queryChain: function(x) {
return x
.select(`id as article_id`, `title`, `slug`, `body`, `date`)
.from(`articles`)
},
},
},
{
resolve: `gatsby-source-sql`,
options: {
typeName: `Classical`,
fieldName: `chinook`,
dbEngine: {
client: `sqlite3`,
connection: {
filename: process.env.DATAFILE2,
},
useNullAsDefault: true,
},
queryChain: function(x) {
return x
.select(
`Track.TrackId as TrackId`,
`Track.Name as Track`,
`Album.Title as Album`,
`Genre.Name as Genre`,
`Artist.Name as Artist`
)
.from(`Track`)
.innerJoin(`Album`, `Album.AlbumId`, `Track.AlbumId`)
.innerJoin(`Artist`, `Artist.ArtistId`, `Album.ArtistId`)
.innerJoin(`Genre`, `Genre.GenreId`, `Track.GenreId`)
.where(`Genre.Name`, `=`, `Classical`)
},
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-transformer-remark`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.app/offline
// 'gatsby-plugin-offline',
],
}
59 changes: 59 additions & 0 deletions examples/using-gatsby-source-sql/gatsby-node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/

// You can delete this file if you're not using it

var unified = require(`unified`)
var markdown = require(`remark-parse`)
var html = require(`remark-html`)
const path = require(`path`)

exports.onCreateNode = async ({ node, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `Article`) {
console.log(node.title)
await unified()
.use(markdown)
.use(html)
.process(node.body)
.then(res => {
createNodeField({
node,
name: `html`,
value: res.contents,
})
})
}
}

exports.createPages = ({ graphql, actions }) => {
// **Note:** The graphql function call returns a Promise
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise for more info
const { createPage } = actions
return graphql(`
{
allArticle {
edges {
node {
slug
}
}
}
}
`).then(result => {
result.data.allArticle.edges.forEach(({ node }) => {
createPage({
path: node.slug,
component: path.resolve(`./src/templates/article.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
slug: node.slug,
},
})
})
})
}
7 changes: 7 additions & 0 deletions examples/using-gatsby-source-sql/gatsby-ssr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Implement Gatsby's SSR (Server Side Rendering) APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/ssr-apis/
*/

// You can delete this file if you're not using it
47 changes: 47 additions & 0 deletions examples/using-gatsby-source-sql/lorem_markdown.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import requests
import sqlite3
from random import randint
import datetime

url = 'https://jaspervdj.be/lorem-markdownum/markdown.txt'

with sqlite3.connect('./data/sqlite_markdown.sqlite3') as conn:
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS articles;')
cur.execute('''CREATE TABLE "articles" (
"id" INTEGER NOT NULL UNIQUE,
"title" TEXT,
"slug" TEXT,
"body" TEXT,
"date" TEXT,
PRIMARY KEY("id")
);''')

insert_sql = '''INSERT INTO articles (
title,
slug,
body,
date
) VALUES (?,?,?,?);'''

today = datetime.datetime.now()
startdate = today - datetime.timedelta(3)

for i in range(10):

response = requests.get(url, params={
'underline-headers': 'off',
'no-external-links': 'on',
'no-code': 'on'})

lines = response.text.splitlines()
title = lines[0][2:]
slug = title.replace(' ', '-').lower()
date = startdate + datetime.timedelta(randint(0, 7))
body = ' \n'.join(lines[1:])

cur.execute(insert_sql, (
title,
slug,
body,
date.strftime('%Y-%m-%d')))
41 changes: 41 additions & 0 deletions examples/using-gatsby-source-sql/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "using-gatsby-source-sql",
"description": "Gatsby SQLite source example site",
"version": "1.0.0",
"author": "Edgar Ramírez-Mondragón <[email protected]>",
"dependencies": {
"dotenv": "^6.1.0",
"gatsby": "^2.0.19",
"gatsby-cli": "^2.4.5",
"gatsby-image": "^2.0.15",
"gatsby-plugin-manifest": "^2.0.5",
"gatsby-plugin-offline": "^2.0.11",
"gatsby-plugin-react-helmet": "^3.0.0",
"gatsby-plugin-sharp": "^2.0.7",
"gatsby-source-filesystem": "^2.0.4",
"gatsby-source-sql": "git+https://github.com/mrfunnyshoes/gatsby-source-sql.git",
"gatsby-transformer-remark": "^2.2.0",
"gatsby-transformer-sharp": "^2.1.4",
"react": "^16.5.1",
"react-dom": "^16.5.1",
"react-helmet": "^5.2.0",
"remark-html": "^9.0.0",
"sqlite3": "^4.0.4"
},
"keywords": [
"gatsby"
],
"license": "MIT",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"start": "npm run develop",
"format": "prettier --write \"src/**/*.js\"",
"test": "echo \"Error: no test specified\" && exit 1",
"deploy": "gatsby build --prefix-paths && gh-pages -d public"
},
"devDependencies": {
"gh-pages": "^2.0.1",
"prettier": "^1.14.2"
}
}
1 change: 1 addition & 0 deletions examples/using-gatsby-source-sql/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
requests
Loading