Skip to content

Commit 4d119ef

Browse files
committed
Initial version
1 parent 0fccf56 commit 4d119ef

File tree

8 files changed

+299
-1
lines changed

8 files changed

+299
-1
lines changed

.clasp.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"scriptId":"14QLsgsgzNn6KLfr_avbbp_cLX4dNGcA_AjjWyiTswB0bXqqdkKC5SZTC"}

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.idea

LICENSE

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
Copyright 2018 DataFabric LLC.
3+
4+
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:
5+
6+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7+
8+
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.

README.md

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,64 @@
1-
# datastudio-sparql-connector
1+
# SPARQL Connector for Google Data Studio
2+
3+
It allows to load data from a SPARQL endpoint using the SELECT queries.
4+
5+
## Getting started
6+
7+
1. Open the [link](https://datastudio.google.com/datasources/create?connectorId=AKfycbzDHEBN9qHXPni4xO4P2cIZtyQ3rnYmzkCnVsnh9oEJrnhGe4MntBF-t1zAu2Lm-Vjc) to create a new Data Source.
8+
1. Once authorization has successfully completed, you're ready to configure the parameters. You should be see the form:
9+
10+
![Screenshot of the configuration page](screenshot_parameters.png)
11+
12+
1. Enter the SPARQL endpoint URL, e.g. http://dbpedia.org/sparql
13+
1. Enter your SELECT query, e.g.
14+
15+
```
16+
PREFIX dbr: <http://dbpedia.org/resource/>
17+
PREFIX dbo: <http://dbpedia.org/ontology/>
18+
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
19+
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
20+
21+
SELECT ?name ?gender ?birthDate WHERE {
22+
?person dbo:birthPlace dbr:Berlin ;
23+
dbo:birthDate ?birthDate ;
24+
foaf:name ?name ;
25+
foaf:gender ?gender .
26+
27+
FILTER (?birthDate > "{dateRange.startDate}"^^xsd:date && ?birthDate < "{dateRange.endDate}"^^xsd:date) .
28+
}
29+
```
30+
31+
The following variables are supported:
32+
33+
* `dateRange.startDate` - format `YYYY-MM-DD`, e.g. 2018-10-01,
34+
* `dateRange.endDate` - format `YYYY-MM-DD`, e.g. 2018-10-01,
35+
* `dateRange.numDays` - it's a positive integer value.
36+
37+
If you don't use `dateRange.startDate` and `dateRange.endDate`, then you won't be able to use **Date range** filter.
38+
39+
1. Enter the schema of projections, e.g.
40+
41+
```
42+
[
43+
{"name": "name", "dataType": "STRING"},
44+
{"name": "gender", "dataType": "STRING"},
45+
{"name": "birtDate", "dataType": "STRING"}
46+
]
47+
```
48+
49+
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.
50+
51+
1. Press **Connect** button and the next page is the same for all connectors.
52+
53+
## Supported data type conversions
54+
55+
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:
56+
57+
* `xsd:date` is converted to `YYYYMMDD`,
58+
* `xsd:dateTime` is converted to `YYYYMMDDHH`,
59+
* `xsd:duration` is converted to an integer corresponding to the number of seconds.
60+
61+
## License
62+
63+
MIT License
64+

appsscript.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"dataStudio": {
3+
"name": "SPARQL Connector",
4+
"logoUrl": "https://www.w3.org/RDF/icons/rdf_w3c_icon.48.gif",
5+
"company": "DataFabric LLC.",
6+
"companyUrl": "http://datafabric.cc",
7+
"addonUrl": "https://github.com/DataFabricRus/datastudio-sparql-connector",
8+
"supportUrl": "https://github.com/DataFabricRus/datastudio-sparql-connector/issues",
9+
"description": "Load data with a SPARQL SELECT query",
10+
"feeType": ["FREE"]
11+
}
12+
}

connector.js

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
var startDateRegex = /\{dateRange\.startDate\}/gi;
2+
var endDateRegex = /\{dateRange\.endDate\}/gi;
3+
var numDaysRegex = /\{dateRange\.numDays\}/gi;
4+
5+
var ONE_DAY = 24 * 60 * 60 * 1000; //milliseconds
6+
7+
var cachedSchemaFields = null;
8+
9+
function getAuthType() {
10+
return {type: 'NONE'};
11+
}
12+
13+
function getConfig() {
14+
console.info("getConfig");
15+
return {
16+
configParams: [
17+
{
18+
type: 'TEXTINPUT',
19+
name: 'endpoint',
20+
displayName: 'Enter the SPARQL Endpoint URL'
21+
},
22+
{
23+
type: 'TEXTAREA',
24+
name: 'query',
25+
displayName: 'Enter a SPARQL SELECT query'
26+
},
27+
{
28+
type: 'INFO',
29+
name: 'query-instructions',
30+
text: "Only SPARQL SELECT queries with projections are supported (query with * isn\'t supported). " +
31+
"Add a filter by date with placeholders for start and end dates, e.g. " +
32+
"FILTER(?startTime > \"{dateRange.startDate}\"^^xsd:dateTime && ?endTime < \"{dateRange.endDate}\"^^xsd:dateTime)"
33+
},
34+
{
35+
type: 'TEXTAREA',
36+
name: 'schema',
37+
displayName: 'Enter the schema of query results'
38+
},
39+
{
40+
type: 'INFO',
41+
name: 'schema-instructions',
42+
text: "The schema defines data types, etc. of the projected variables. An example:\n" +
43+
"[{ \"name\":\"location\", \"dataType\":\"STRING\" }, { \"name\":\"price\", \"dataType\":\"NUMBER\" }]. More about schemas: https://developers.google.com/datastudio/connector/semantics"
44+
}
45+
],
46+
dateRangeRequired: true
47+
};
48+
}
49+
50+
function isAdminUser() {
51+
return true;
52+
}
53+
54+
function getSchema(request) {
55+
console.info('[getSchema] request: %s', request);
56+
57+
var schema = JSON.parse(request.configParams.schema);
58+
59+
return {schema: schema};
60+
}
61+
62+
function getData(request) {
63+
console.info("[getData] request: %s", request);
64+
65+
var schema = filteredSchema(JSON.parse(request.configParams.schema), request.fields);
66+
67+
if(request.scriptParams && request.scriptParams.sampleExtraction) {
68+
console.log("[getData] sampleExtraction");
69+
return { schema: schema, rows: [] };
70+
} else {
71+
var rows = execute(request.configParams.endpoint, request.configParams.query, request);
72+
73+
console.info("[getData] schema: %s", schema);
74+
console.info("[getData] rows: %s", rows);
75+
76+
return { schema: schema, rows: rows };
77+
}
78+
}
79+
80+
function execute(endpoint, query, options) {
81+
var formData = {
82+
'query': prepareQuery(query, options)
83+
};
84+
var requestOptions = {
85+
'method': 'post',
86+
'headers': { Accept: 'application/sparql-results+json' },
87+
'contentType': 'application/x-www-form-urlencoded',
88+
'payload': formData
89+
};
90+
var response = UrlFetchApp.fetch(endpoint, requestOptions);
91+
console.info("[execute] response: %s", response);
92+
93+
var body = JSON.parse(response);
94+
console.info("[execute] body: %s", body);
95+
96+
if(isQueryResultEmpty(body)) {
97+
return { values: [] };
98+
} else {
99+
return body.results.bindings.map(function(row) {
100+
var values = new Array();
101+
102+
options.fields.forEach(function(rf) {
103+
var cell = row[rf.name];
104+
105+
cell.value = reformatByDatatypes(cell.value, cell.datatype);
106+
107+
values.push(cell.value);
108+
});
109+
110+
return { values: values };
111+
});
112+
}
113+
}
114+
115+
function filteredSchema(schema, requestedFields) {
116+
if(!cachedSchemaFields) {
117+
cachedSchemaFields = new Object();
118+
schema.forEach(function(field) {
119+
cachedSchemaFields[field.name] = field;
120+
});
121+
}
122+
123+
return requestedFields.map(function(field) {
124+
return cachedSchemaFields[field.name];
125+
});
126+
}
127+
128+
function prepareQuery(query, options) {
129+
var preparedQuery = query;
130+
if(options.dateRange && options.dateRange.startDate && options.dateRange.endDate) {
131+
var startDate = new Date(options.dateRange.startDate);
132+
var endDate = new Date(options.dateRange.endDate);
133+
if(endDate.getTime() > Date.now()) {
134+
var now = new Date();
135+
now.setDate(now.getDate() - 1);
136+
endDate = now;
137+
}
138+
var numDays = Math.round((endDate.getTime() - startDate.getTime()) / ONE_DAY) + 1;
139+
preparedQuery = preparedQuery
140+
.replace(startDateRegex, options.dateRange.startDate)
141+
.replace(endDateRegex, options.dateRange.endDate)
142+
.replace(numDaysRegex, numDays);
143+
}
144+
if(options.pagination){
145+
if(options.pagination.rowCount) {
146+
preparedQuery += "\nLIMIT " + parseInt(options.pagination.rowCount);
147+
}
148+
if(options.pagination.startRow) {
149+
preparedQuery += "\nOFFSET " + (parseInt(options.pagination.startRow) - 1);
150+
}
151+
}
152+
153+
console.info("[prepareQuery] query: %s", preparedQuery);
154+
155+
return preparedQuery;
156+
}
157+
158+
function isQueryResultEmpty(qr) {
159+
if(qr.results.bindings.length == 0) {
160+
return true;
161+
} else if(qr.results.bindings.length == 1) {
162+
return qr.head.vars.some(function(variable){
163+
return !qr.results.bindings[variable];
164+
});
165+
}
166+
167+
return false;
168+
}

screenshot_parameters.png

23.2 KB
Loading

utils.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
function reformatByDatatypes(value, xsdDatatype) {
2+
if(xsdDatatype) {
3+
if(xsdDatatype == "http://www.w3.org/2001/XMLSchema#date") {
4+
return value.replace(/Z|-/gi, "");
5+
}
6+
if(xsdDatatype == "http://www.w3.org/2001/XMLSchema#dateTime") {
7+
var match = value.match(/^\d{4}-\d{2}-\d{2}T\d{2}/g);
8+
if(match) {
9+
return match[0].replace(/T|-/gi, "");
10+
}
11+
}
12+
if(xsdDatatype == "http://www.w3.org/2001/XMLSchema#duration") {
13+
return durationToSecs(value);
14+
}
15+
}
16+
17+
return value;
18+
};
19+
20+
function durationToSecs(value) {
21+
var match = value.match(/PT(\d{1,2}H)*(\d{1,2}M)*([\d{1,2}\.]+S)*/i);
22+
if(match) {
23+
var seconds = 0;
24+
25+
for(var i = 1; i < match.length; i++) {
26+
var d = match[i] || "";
27+
28+
Logger.log(d);
29+
30+
if(d[d.length - 1] == 'H') {
31+
seconds += parseInt(d.substring(0, d.length - 1)) * 60 * 60;
32+
} else if(d[d.length - 1] == 'M') {
33+
seconds += parseInt(d.substring(0, d.length - 1)) * 60;
34+
} else if(d[d.length - 1] == 'S') {
35+
seconds += parseInt(d.substring(0, d.length - 1));
36+
}
37+
}
38+
39+
Logger.log(seconds);
40+
41+
return seconds;
42+
}
43+
44+
return 0;
45+
};

0 commit comments

Comments
 (0)