-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathsparql.js
More file actions
378 lines (302 loc) · 9.06 KB
/
sparql.js
File metadata and controls
378 lines (302 loc) · 9.06 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
const config = require('../config')
const request = require('request')
const fs = require('mz/fs')
const sparqlResultsToArray = require('./sparql-results-to-array')
const spawn = require('child_process').spawn
const tmp = require('tmp-promise')
var path = require('path')
var exec = require('child_process').exec
function escapeSparqlIRI (uri) {
return '<' + uri + '>'
}
function updateQuery (sparql, graphUri, accept) {
const triplestoreConfig = config.get('triplestore')
graphUri = graphUri || triplestoreConfig.defaultGraph
if (config.get('logSparqlQueries')) { console.log(sparql) }
return new Promise((resolve, reject) => {
request({
method: 'POST',
url: triplestoreConfig.sparqlEndpoint + '-auth',
qs: {
query: sparql,
'default-graph-uri': graphUri
},
auth: {
user: triplestoreConfig.username,
pass: triplestoreConfig.password,
sendImmediately: false
},
headers: {
accept: accept
}
}, (err, res, body) => {
if (err) {
reject(err)
return
}
if (res.statusCode >= 300) {
reject(new Error(body))
return
}
resolve({
type: res.headers['content-type'],
statusCode: res.statusCode,
body: body
})
})
})
}
function updateQueryJson (sparql, graphUri) {
// const timer = Timer('sparql query')
return updateQuery(sparql, graphUri, 'application/sparql-results+json')
.then(parseResult)
.catch(handleError)
function parseResult (res) {
// timer()
// console.log('res status code is ' + res.statusCode)
var results = JSON.parse(res.body)
return Promise.resolve(sparqlResultsToArray(results))
}
function handleError (error) {
console.error('SPARQL update query failed')
console.error(error.stack)
return Promise.reject(error)
}
}
function query (sparql, graphUri, accept, explorer = false) {
const triplestoreConfig = config.get('triplestore')
graphUri = graphUri || triplestoreConfig.defaultGraph
if (config.get('logSparqlQueries')) { console.log(sparql) }
var endpoint
if (explorer) {
endpoint = config.get('SBOLExplorerEndpoint')
} else {
endpoint = triplestoreConfig.sparqlEndpoint
}
let qs = {
'default-graph-uri': graphUri
}
if (sparql) { qs.query = sparql }
return new Promise((resolve, reject) => {
request({
method: 'get',
url: endpoint,
qs: qs,
headers: {
accept: accept
}
}, (err, res, body) => {
if (err) {
reject(err)
return
}
if (res.statusCode >= 300) {
reject(new Error(body))
return
}
resolve({
type: res.headers['content-type'],
statusCode: res.statusCode,
body: body
})
})
})
}
function queryJson (sparql, graphUri, explorer = false) {
// const timer = Timer('sparql query')
return query(sparql, graphUri, 'application/sparql-results+json', explorer).then(parseResult, handleError)
function parseResult (res) {
// timer()
// console.log('res status code is ' + res.statusCode)
var results = JSON.parse(res.body)
return Promise.resolve(sparqlResultsToArray(results))
}
function handleError (error) {
if (explorer) {
console.log(error + ' -> retrying query with SBOLExplorer bypassed')
return query(sparql, graphUri, 'application/sparql-results+json', false).then(parseResult).catch((err) => {
console.error('Virtuoso not responding search')
console.error(err.stack)
return Promise.resolve([])
})
} else {
console.error('Virtuoso not responding')
console.error(error.stack)
return Promise.resolve([])
}
}
}
function queryJsonStaggered (sparql, graphUri) {
var offset = 0
var limit = config.get('staggeredQueryLimit')
var resultsUnion = []
return performQuery()
function performQuery () {
console.log('queryJsonStaggered: offset ' + offset + ', limit ' + limit + ', ' + resultsUnion.length + ' results so far')
return queryJson(sparql + ' OFFSET ' + offset + ' LIMIT ' + limit, graphUri).then((results) => {
// console.log('qj results')
// console.log(JSON.stringify(results))
if (results.length === 0) {
return Promise.resolve(resultsUnion)
} else {
Array.prototype.push.apply(resultsUnion, results)
offset += limit
return performQuery()
}
})
}
}
// Removed staggering since it is causing incomplete deletes
function deleteStaggered (sparql, graphUri) {
// var limit = config.get('staggeredQueryLimit')
return performQuery()
function performQuery () {
// console.log('deleteStaggered: limit ' + limit)
return updateQueryJson(sparql, graphUri).then((results) => {
// hacks! delete succeeds even if nothing was deleted, but it
// does give us a nice message.
//
if (results[0]['callret-0'].indexOf('nothing to do') !== -1) {
return Promise.resolve()
} else {
return performQuery()
}
}).catch((error) => {
console.error('Delete operation failed')
console.error(error.stack)
return Promise.reject(error)
})
}
}
function upload (graphUri, data, type) {
const triplestoreConfig = config.get('triplestore')
graphUri = graphUri || triplestoreConfig.defaultGraph
return new Promise((resolve, reject) => {
request({
method: 'POST',
url: triplestoreConfig.graphStoreEndpoint,
qs: {
'graph-uri': graphUri
},
auth: {
user: triplestoreConfig.username,
pass: triplestoreConfig.password,
sendImmediately: false
},
headers: {
'content-type': type
},
body: data
}, (err, res, body) => {
if (err) {
reject(err)
return
}
if (res.statusCode >= 300) {
reject(new Error(body))
return
}
resolve(body)
})
})
}
function uploadSmallFile (graphUri, filename, type) {
const triplestoreConfig = config.get('triplestore')
graphUri = graphUri || triplestoreConfig.defaultGraph
return new Promise((resolve, reject) => {
console.log('sparql upload file: ' + filename)
console.log('gui ' + graphUri)
/* TODO: it would be very nice to stream the file to the request
* instead of loading it all into memory.
* unfortunately, with auth: { sendImmediately: false }, the file gets
* streamed to the initial request (which will fail), and then when the
* retry request with authentication happens requestjs sends content
* length of 0.
*/
fs.readFile(filename).then((contents) => {
request({
method: 'POST',
url: triplestoreConfig.graphStoreEndpoint,
qs: {
'graph-uri': graphUri
},
auth: {
user: triplestoreConfig.username,
pass: triplestoreConfig.password,
sendImmediately: false
},
headers: {
'content-type': type
},
body: contents
}, (err, res, body) => {
if (err) {
reject(err)
return
}
console.log('uploadfile done; ' + res.statusCode)
console.log(body)
if (res.statusCode >= 300) {
reject(new Error(body))
return
}
resolve(body)
})
})
})
}
function uploadFile (graphUri, filename, type) {
return tmp.dir().then((tempDir) => {
console.log('file before splitting ' + filename)
console.log('splitting RDF to n3 in temp dir ' + tempDir.path)
return new Promise((resolve, reject) => {
const splitProcess = spawn(path.join(__dirname, '/../../scripts/split_to_n3.sh'), [
filename
], {
cwd: tempDir.path
})
splitProcess.stderr.on('data', (data) => {
console.log('[split_to_n3.sh]', data.toString())
})
splitProcess.on('close', (exitCode) => {
if (exitCode !== 0) {
reject(new Error('split_to_n3 returned exit code ' + exitCode))
return
}
resolve(tempDir.path)
})
})
}).then((tempDir) => {
return fs.readdir(tempDir).then((files) => {
var filesToUpload = files.filter(
(filename) => filename.indexOf('upload_') === 0)
// var total = filesToUpload.length
console.log(filesToUpload + ' chunks to upload')
return uploadNextFile()
function uploadNextFile () {
if (filesToUpload.length > 0) {
var nextFile = tempDir + '/' + filesToUpload[0]
filesToUpload = filesToUpload.slice(1)
console.log('Uploading n3 chunk: ' + nextFile)
return uploadSmallFile(graphUri, nextFile, 'text/n3')
.then(() => fs.unlink(nextFile))
.then(() => uploadNextFile())
} else {
return exec('rm -r ' + tempDir)
}
}
})
})
}
module.exports = {
escape: require('pg-escape'),
escapeIRI: escapeSparqlIRI,
updateQuery: updateQuery,
updateQueryJson: updateQueryJson,
query: query,
queryJson: queryJson,
queryJsonStaggered: queryJsonStaggered,
deleteStaggered: deleteStaggered,
upload: upload,
uploadFile: uploadFile
}