-
Notifications
You must be signed in to change notification settings - Fork 8
/
sparql.go
305 lines (254 loc) · 7.31 KB
/
sparql.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Copyright © 2017 Delving B.V. <info@delving.eu>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// TODO(kiivihal): DELETE whole file
package models
import (
"bytes"
"fmt"
"log"
"strconv"
"time"
"github.com/delving/hub3/config"
"github.com/delving/hub3/hub3/fragments"
"github.com/knakk/sparql"
)
const queries = `
# SPARQL queries that are loaded as a QueryBank
# ask returns a boolean
# tag: ask_subject
ASK { <{{ .URI }}> ?p ?o }
# tag: ask_predicate
ASK { ?s <{{ .URI }}> ?o }
# tag: ask_object
ASK { ?s <{{ .URI }}> ?o }
# tag: ask_query
ASK { {{ .Query }} }
# The DESCRIBE form returns a single result RDF graph containing RDF data about resources.
# tag: describe
DESCRIBE <{{.URI}}>
# tag: countGraphPerSpec
SELECT (count(?subject) as ?count)
WHERE {
?subject <http://schemas.delving.eu/nave/terms/datasetSpec> "{{.Spec}}"
}
LIMIT 1
# tag: countRevisionsBySpec
SELECT ?revision (COUNT(?revision) as ?rCount)
WHERE
{
?subject <http://schemas.delving.eu/nave/terms/datasetSpec> "{{.Spec}}";
<http://schemas.delving.eu/nave/terms/specRevision> ?revision .
}
GROUP BY ?revision
# tag: deleteAllGraphsBySpec
DELETE {
GRAPH ?g {
?s ?p ?o .
}
}
WHERE {
GRAPH ?g {
?subject <http://schemas.delving.eu/nave/terms/datasetSpec> "{{.Spec}}".
}
GRAPH ?g {
?s ?p ?o .
}
};
# tag: deleteOrphanGraphsBySpec
DELETE {
GRAPH ?g {
?s ?p ?o .
}
}
WHERE {
GRAPH ?g {
?subject <http://schemas.delving.eu/nave/terms/datasetSpec> "{{.Spec}}";
<http://schemas.delving.eu/nave/terms/specRevision> ?revision .
FILTER (?revision != {{.RevisionNumber}}).
}
GRAPH ?g {
?s ?p ?o .
}
};
# tag: countAllTriples
SELECT (count(?s) as ?count)
WHERE {
?s ?p ?o .
};
# tag: harvestTriples
SELECT *
WHERE {
?s ?p ?o .
} LIMIT {{.Limit}} OFFSET {{.Offset}}
`
var queryBank sparql.Bank
// sparqlQueryURL is the fully qualified URI to the SPARQL endpoint
var sparqlQueryURL string
// sparqlUpdateURL is the fully qualified URI to the SPARQL Update endpoint
var sparqlUpdateURL string
// sparqlRepo is the repository used for querying
var sparqlRepo *sparql.Repo
// sparqlUpdateRepo is the repository used for updating the TripleStore
var sparqlUpdateRepo *sparql.Repo
func init() {
f := bytes.NewBufferString(queries)
queryBank = sparql.LoadBank(f)
}
func SparqlRepo(orgID string) *sparql.Repo {
if sparqlRepo == nil {
sparqlRepo = buildRepo(orgID, config.Config.GetSparqlEndpoint(orgID, ""))
}
return sparqlRepo
}
func SparqlUpdateRepo(orgID string) *sparql.Repo {
if sparqlUpdateRepo == nil {
sparqlUpdateRepo = buildRepo(orgID, config.Config.GetSparqlUpdateEndpoint(orgID, ""))
}
return sparqlUpdateRepo
}
// buildRepo builds the query repository
func buildRepo(orgID, endPoint string) *sparql.Repo {
if endPoint == "" {
endPoint = config.Config.GetSparqlEndpoint(orgID, "")
}
repo, err := sparql.NewRepo(endPoint,
sparql.Timeout(time.Millisecond*1500),
)
if err != nil {
log.Fatal(err)
}
return repo
}
// DeleteAllGraphsBySpec issues an SPARQL Update query to delete all graphs for a DataSet from the triple store
func DeleteAllGraphsBySpec(orgID, spec string) (bool, error) {
query, err := queryBank.Prepare("deleteAllGraphsBySpec", struct{ Spec string }{spec})
if err != nil {
log.Printf("Unable to build deleteAllGraphsBySpec query: %s", err)
return false, err
}
errs := fragments.UpdateViaSparql(orgID, query)
if errs != nil {
logUnableToQueryEndpoint(errs)
return false, errs[0]
}
return true, nil
}
// DeleteGraphsOrphansBySpec issues an SPARQL Update query to delete all orphaned graphs
// for a DataSet from the triple store.
func DeleteGraphsOrphansBySpec(orgID, spec string, revision int) (bool, error) {
query, err := queryBank.Prepare("deleteOrphanGraphsBySpec", struct {
Spec string
RevisionNumber int
}{spec, revision})
if err != nil {
log.Printf("Unable to build deleteOrphanGraphsBySpec query: %s", err)
return false, err
}
errs := fragments.UpdateViaSparql(orgID, query)
if errs != nil {
logUnableToQueryEndpoint(errs)
return false, errs[0]
}
return true, nil
}
// CountRevisionsBySpec counts each revision available in the spec
func CountRevisionsBySpec(orgID, spec string) ([]DataSetRevisions, error) {
query, err := queryBank.Prepare("countRevisionsBySpec", struct{ Spec string }{spec})
revisions := []DataSetRevisions{}
if err != nil {
log.Printf("Unable to build countRevisionsBySpec query: %s", err)
return revisions, err
}
res, err := SparqlRepo(orgID).Query(query)
if err != nil {
logUnableToQueryEndpoint([]error{err})
return revisions, err
}
for _, v := range res.Solutions() {
revisionTerm, ok := v["revision"]
if !ok {
log.Printf("No revisions found for spec %s", spec)
return revisions, nil
}
revision, err := strconv.ParseInt(revisionTerm.String(), 10, 32)
if err != nil {
return revisions, fmt.Errorf("unable to convert %#v to integer", v["revision"])
}
revisionCount, err := strconv.ParseInt(v["rCount"].String(), 10, 32)
if err != nil {
return revisions, fmt.Errorf("unable to convert %#v to integer", v["rCount"])
}
revisions = append(revisions, DataSetRevisions{
Number: int(revision),
RecordCount: int(revisionCount),
})
}
return revisions, nil
}
// CountGraphsBySpec counts all the named graphs for a spec
func CountGraphsBySpec(orgID, spec string) (int, error) {
query, err := queryBank.Prepare("countGraphPerSpec", struct{ Spec string }{spec})
if err != nil {
log.Printf("Unable to build CountGraphsBySpec query: %s", err)
return 0, err
}
res, err := SparqlRepo(orgID).Query(query)
if err != nil {
logUnableToQueryEndpoint([]error{err})
return 0, err
}
countStr, ok := res.Bindings()["count"]
if !ok {
return 0, fmt.Errorf("unable to get count from result bindings: %#v", res.Bindings())
}
var count int
count, err = strconv.Atoi(countStr[0].String())
if err != nil {
return 0, fmt.Errorf("unable to convert %s to integer", countStr)
}
return count, err
}
// PrepareAsk takes an a string and returns a valid SPARQL ASK query
func PrepareAsk(uri string) (string, error) {
q, err := queryBank.Prepare("ask_subject", struct{ URI string }{uri})
if err != nil {
return "", err
}
return q, err
}
// AskSPARQL performs a SPARQL ASK query
func AskSPARQL(orgID, query string) (bool, error) {
res, err := SparqlRepo(orgID).Query(query)
if err != nil {
return false, err
}
bindings := res.Results.Bindings
fmt.Println(bindings)
return false, nil
}
// // DescribeSPARQL creates a describe query for a given URI.
// func DescribeSPARQL(uri string) (map[string][]rdf.Term, error) {
// query, err := queryBank.Prepare("describe", struct{ URI string }{uri})
// if err != nil {
// return nil, err
// }
// res, err := SparqlRepo().Query(query)
// if err != nil {
// return nil, err
// }
// return res.Bindings(), nil
// }
func logUnableToQueryEndpoint(errs []error) {
log.Printf("Unable query endpoint: %s", errs)
}