Skip to content

Commit

Permalink
Initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
KMax committed Oct 9, 2018
1 parent 0fccf56 commit 4d119ef
Show file tree
Hide file tree
Showing 8 changed files with 299 additions and 1 deletion.
1 change: 1 addition & 0 deletions .clasp.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"scriptId":"14QLsgsgzNn6KLfr_avbbp_cLX4dNGcA_AjjWyiTswB0bXqqdkKC5SZTC"}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
8 changes: 8 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

Copyright 2018 DataFabric LLC.

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.
65 changes: 64 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,64 @@
# datastudio-sparql-connector
# SPARQL Connector for Google Data Studio

It allows to load data from a SPARQL endpoint using the SELECT queries.

## Getting started

1. Open the [link](https://datastudio.google.com/datasources/create?connectorId=AKfycbzDHEBN9qHXPni4xO4P2cIZtyQ3rnYmzkCnVsnh9oEJrnhGe4MntBF-t1zAu2Lm-Vjc) to create a new Data Source.
1. Once authorization has successfully completed, you're ready to configure the parameters. You should be see the form:

![Screenshot of the configuration page](screenshot_parameters.png)

1. Enter the SPARQL endpoint URL, e.g. http://dbpedia.org/sparql
1. Enter your SELECT query, e.g.

```
PREFIX dbr: <http://dbpedia.org/resource/>
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT ?name ?gender ?birthDate WHERE {
?person dbo:birthPlace dbr:Berlin ;
dbo:birthDate ?birthDate ;
foaf:name ?name ;
foaf:gender ?gender .
FILTER (?birthDate > "{dateRange.startDate}"^^xsd:date && ?birthDate < "{dateRange.endDate}"^^xsd:date) .
}
```
The following variables are supported:
* `dateRange.startDate` - format `YYYY-MM-DD`, e.g. 2018-10-01,
* `dateRange.endDate` - format `YYYY-MM-DD`, e.g. 2018-10-01,
* `dateRange.numDays` - it's a positive integer value.
If you don't use `dateRange.startDate` and `dateRange.endDate`, then you won't be able to use **Date range** filter.
1. Enter the schema of projections, e.g.
```
[
{"name": "name", "dataType": "STRING"},
{"name": "gender", "dataType": "STRING"},
{"name": "birtDate", "dataType": "STRING"}
]
```
At this step is enough to set only data types for each projection, at the next step you'll be able to refine it. More about the schema elements, data types you can read in https://developers.google.com/datastudio/connector/semantics.
1. Press **Connect** button and the next page is the same for all connectors.
## Supported data type conversions
Google Data Studio uses it's own formats for some of the data types. Therefore the connector automatically converts them. The following data types are supported:
* `xsd:date` is converted to `YYYYMMDD`,
* `xsd:dateTime` is converted to `YYYYMMDDHH`,
* `xsd:duration` is converted to an integer corresponding to the number of seconds.
## License
MIT License
12 changes: 12 additions & 0 deletions appsscript.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"dataStudio": {
"name": "SPARQL Connector",
"logoUrl": "https://www.w3.org/RDF/icons/rdf_w3c_icon.48.gif",
"company": "DataFabric LLC.",
"companyUrl": "http://datafabric.cc",
"addonUrl": "https://github.com/DataFabricRus/datastudio-sparql-connector",
"supportUrl": "https://github.com/DataFabricRus/datastudio-sparql-connector/issues",
"description": "Load data with a SPARQL SELECT query",
"feeType": ["FREE"]
}
}
168 changes: 168 additions & 0 deletions connector.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
var startDateRegex = /\{dateRange\.startDate\}/gi;
var endDateRegex = /\{dateRange\.endDate\}/gi;
var numDaysRegex = /\{dateRange\.numDays\}/gi;

var ONE_DAY = 24 * 60 * 60 * 1000; //milliseconds

var cachedSchemaFields = null;

function getAuthType() {
return {type: 'NONE'};
}

function getConfig() {
console.info("getConfig");
return {
configParams: [
{
type: 'TEXTINPUT',
name: 'endpoint',
displayName: 'Enter the SPARQL Endpoint URL'
},
{
type: 'TEXTAREA',
name: 'query',
displayName: 'Enter a SPARQL SELECT query'
},
{
type: 'INFO',
name: 'query-instructions',
text: "Only SPARQL SELECT queries with projections are supported (query with * isn\'t supported). " +
"Add a filter by date with placeholders for start and end dates, e.g. " +
"FILTER(?startTime > \"{dateRange.startDate}\"^^xsd:dateTime && ?endTime < \"{dateRange.endDate}\"^^xsd:dateTime)"
},
{
type: 'TEXTAREA',
name: 'schema',
displayName: 'Enter the schema of query results'
},
{
type: 'INFO',
name: 'schema-instructions',
text: "The schema defines data types, etc. of the projected variables. An example:\n" +
"[{ \"name\":\"location\", \"dataType\":\"STRING\" }, { \"name\":\"price\", \"dataType\":\"NUMBER\" }]. More about schemas: https://developers.google.com/datastudio/connector/semantics"
}
],
dateRangeRequired: true
};
}

function isAdminUser() {
return true;
}

function getSchema(request) {
console.info('[getSchema] request: %s', request);

var schema = JSON.parse(request.configParams.schema);

return {schema: schema};
}

function getData(request) {
console.info("[getData] request: %s", request);

var schema = filteredSchema(JSON.parse(request.configParams.schema), request.fields);

if(request.scriptParams && request.scriptParams.sampleExtraction) {
console.log("[getData] sampleExtraction");
return { schema: schema, rows: [] };
} else {
var rows = execute(request.configParams.endpoint, request.configParams.query, request);

console.info("[getData] schema: %s", schema);
console.info("[getData] rows: %s", rows);

return { schema: schema, rows: rows };
}
}

function execute(endpoint, query, options) {
var formData = {
'query': prepareQuery(query, options)
};
var requestOptions = {
'method': 'post',
'headers': { Accept: 'application/sparql-results+json' },
'contentType': 'application/x-www-form-urlencoded',
'payload': formData
};
var response = UrlFetchApp.fetch(endpoint, requestOptions);
console.info("[execute] response: %s", response);

var body = JSON.parse(response);
console.info("[execute] body: %s", body);

if(isQueryResultEmpty(body)) {
return { values: [] };
} else {
return body.results.bindings.map(function(row) {
var values = new Array();

options.fields.forEach(function(rf) {
var cell = row[rf.name];

cell.value = reformatByDatatypes(cell.value, cell.datatype);

values.push(cell.value);
});

return { values: values };
});
}
}

function filteredSchema(schema, requestedFields) {
if(!cachedSchemaFields) {
cachedSchemaFields = new Object();
schema.forEach(function(field) {
cachedSchemaFields[field.name] = field;
});
}

return requestedFields.map(function(field) {
return cachedSchemaFields[field.name];
});
}

function prepareQuery(query, options) {
var preparedQuery = query;
if(options.dateRange && options.dateRange.startDate && options.dateRange.endDate) {
var startDate = new Date(options.dateRange.startDate);
var endDate = new Date(options.dateRange.endDate);
if(endDate.getTime() > Date.now()) {
var now = new Date();
now.setDate(now.getDate() - 1);
endDate = now;
}
var numDays = Math.round((endDate.getTime() - startDate.getTime()) / ONE_DAY) + 1;
preparedQuery = preparedQuery
.replace(startDateRegex, options.dateRange.startDate)
.replace(endDateRegex, options.dateRange.endDate)
.replace(numDaysRegex, numDays);
}
if(options.pagination){
if(options.pagination.rowCount) {
preparedQuery += "\nLIMIT " + parseInt(options.pagination.rowCount);
}
if(options.pagination.startRow) {
preparedQuery += "\nOFFSET " + (parseInt(options.pagination.startRow) - 1);
}
}

console.info("[prepareQuery] query: %s", preparedQuery);

return preparedQuery;
}

function isQueryResultEmpty(qr) {
if(qr.results.bindings.length == 0) {
return true;
} else if(qr.results.bindings.length == 1) {
return qr.head.vars.some(function(variable){
return !qr.results.bindings[variable];
});
}

return false;
}
Binary file added screenshot_parameters.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
45 changes: 45 additions & 0 deletions utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
function reformatByDatatypes(value, xsdDatatype) {
if(xsdDatatype) {
if(xsdDatatype == "http://www.w3.org/2001/XMLSchema#date") {
return value.replace(/Z|-/gi, "");
}
if(xsdDatatype == "http://www.w3.org/2001/XMLSchema#dateTime") {
var match = value.match(/^\d{4}-\d{2}-\d{2}T\d{2}/g);
if(match) {
return match[0].replace(/T|-/gi, "");
}
}
if(xsdDatatype == "http://www.w3.org/2001/XMLSchema#duration") {
return durationToSecs(value);
}
}

return value;
};

function durationToSecs(value) {
var match = value.match(/PT(\d{1,2}H)*(\d{1,2}M)*([\d{1,2}\.]+S)*/i);
if(match) {
var seconds = 0;

for(var i = 1; i < match.length; i++) {
var d = match[i] || "";

Logger.log(d);

if(d[d.length - 1] == 'H') {
seconds += parseInt(d.substring(0, d.length - 1)) * 60 * 60;
} else if(d[d.length - 1] == 'M') {
seconds += parseInt(d.substring(0, d.length - 1)) * 60;
} else if(d[d.length - 1] == 'S') {
seconds += parseInt(d.substring(0, d.length - 1));
}
}

Logger.log(seconds);

return seconds;
}

return 0;
};

0 comments on commit 4d119ef

Please sign in to comment.