oxigraph 0.1.0.rc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,491 @@
1
+ use std::cell::{Cell, RefCell};
2
+
3
+ use magnus::{
4
+ function, method, prelude::*, r_hash::ForEach, scan_args, typed_data::Obj, Error, RArray,
5
+ RHash, RModule, RString, Ruby, Symbol, TryConvert, Value,
6
+ };
7
+ use oxigraph::sparql::{
8
+ QueryResults, QuerySolution as Row, QuerySolutionIter, QueryTripleIter, SparqlEvaluator,
9
+ };
10
+ use oxigraph::store::Store;
11
+ use spargebra::algebra::{AggregateExpression, Expression, GraphPattern, OrderExpression};
12
+ use spargebra::SparqlParser;
13
+
14
+ use crate::error::{argument_error, error, named_error};
15
+ use crate::model::{frozen, term_to_value, triple_to_value};
16
+
17
+ /// A parsed SPARQL query, exposed to Ruby as `Oxigraph::Query`.
18
+ #[magnus::wrap(class = "Oxigraph::Query", free_immediately, size)]
19
+ pub struct Query {
20
+ inner: spargebra::Query,
21
+ /// Whether a `SERVICE` clause appears anywhere in the query.
22
+ service: bool,
23
+ }
24
+
25
+ impl Query {
26
+ fn parse(ruby: &Ruby, arguments: &[Value]) -> Result<Obj<Self>, Error> {
27
+ let (text, parser) = text_and_parser(ruby, arguments)?;
28
+ Ok(frozen(ruby, Self::from_text(ruby, parser, &text)?))
29
+ }
30
+
31
+ fn from_text(ruby: &Ruby, parser: SparqlParser, text: &str) -> Result<Self, Error> {
32
+ let inner = parser
33
+ .parse_query(text)
34
+ .map_err(|cause| named_error(ruby, "QuerySyntaxError", cause))?;
35
+ let service = pattern_has_service(pattern_of(&inner));
36
+ Ok(Self { inner, service })
37
+ }
38
+
39
+ fn form(ruby: &Ruby, rb_self: &Self) -> Symbol {
40
+ ruby.to_symbol(match rb_self.inner {
41
+ spargebra::Query::Select { .. } => "select",
42
+ spargebra::Query::Construct { .. } => "construct",
43
+ spargebra::Query::Describe { .. } => "describe",
44
+ spargebra::Query::Ask { .. } => "ask",
45
+ })
46
+ }
47
+
48
+ fn has_service(&self) -> bool {
49
+ self.service
50
+ }
51
+
52
+ fn has_dataset(&self) -> bool {
53
+ match &self.inner {
54
+ spargebra::Query::Select { dataset, .. }
55
+ | spargebra::Query::Construct { dataset, .. }
56
+ | spargebra::Query::Describe { dataset, .. }
57
+ | spargebra::Query::Ask { dataset, .. } => dataset.is_some(),
58
+ }
59
+ }
60
+
61
+ fn to_s(&self) -> String {
62
+ self.inner.to_string()
63
+ }
64
+
65
+ fn inspect(&self) -> String {
66
+ format!("#<Oxigraph::Query {}>", self.inner)
67
+ }
68
+ }
69
+
70
+ /// A parsed SPARQL update, exposed to Ruby as `Oxigraph::Update`. It can be
71
+ /// recognized and printed, and nothing here runs it.
72
+ #[magnus::wrap(class = "Oxigraph::Update", free_immediately, size)]
73
+ pub struct Update {
74
+ inner: spargebra::Update,
75
+ }
76
+
77
+ impl Update {
78
+ fn parse(ruby: &Ruby, arguments: &[Value]) -> Result<Obj<Self>, Error> {
79
+ let (text, parser) = text_and_parser(ruby, arguments)?;
80
+ let inner = parser
81
+ .parse_update(&text)
82
+ .map_err(|cause| named_error(ruby, "QuerySyntaxError", cause))?;
83
+ Ok(frozen(ruby, Self { inner }))
84
+ }
85
+
86
+ /// Upstream ends each operation with a line break, which the text of a
87
+ /// single value has no use for.
88
+ fn to_s(&self) -> String {
89
+ self.inner.to_string().trim_end().to_owned()
90
+ }
91
+
92
+ fn inspect(&self) -> String {
93
+ format!("#<Oxigraph::Update {}>", self.to_s())
94
+ }
95
+ }
96
+
97
+ /// Reads the arguments that `Query.parse` and `Update.parse` share: the text,
98
+ /// then `base_iri:` and `prefixes:`.
99
+ fn text_and_parser(ruby: &Ruby, arguments: &[Value]) -> Result<(String, SparqlParser), Error> {
100
+ let arguments = scan_args::scan_args::<(String,), (), (), (), RHash, ()>(arguments)?;
101
+ let keywords = scan_args::get_kwargs::<
102
+ _,
103
+ (),
104
+ (Option<Option<String>>, Option<Option<RHash>>),
105
+ (),
106
+ >(arguments.keywords, &[], &["base_iri", "prefixes"])?;
107
+ let (base_iri, prefixes) = keywords.optional;
108
+
109
+ let mut parser = SparqlParser::new();
110
+ if let Some(base_iri) = base_iri.flatten() {
111
+ parser = parser
112
+ .with_base_iri(base_iri)
113
+ .map_err(|cause| argument_error(ruby, cause))?;
114
+ }
115
+ if let Some(prefixes) = prefixes.flatten() {
116
+ let mut declared = Vec::new();
117
+ prefixes.foreach(|name: Value, iri: String| {
118
+ let name = match Symbol::from_value(name) {
119
+ Some(name) => name.name()?.into_owned(),
120
+ None => String::try_convert(name)?,
121
+ };
122
+ declared.push((name, iri));
123
+ Ok(ForEach::Continue)
124
+ })?;
125
+ for (name, iri) in declared {
126
+ parser = parser
127
+ .with_prefix(name, iri)
128
+ .map_err(|cause| argument_error(ruby, cause))?;
129
+ }
130
+ }
131
+ Ok((arguments.required.0, parser))
132
+ }
133
+
134
+ fn pattern_of(query: &spargebra::Query) -> &GraphPattern {
135
+ match query {
136
+ spargebra::Query::Select { pattern, .. }
137
+ | spargebra::Query::Construct { pattern, .. }
138
+ | spargebra::Query::Describe { pattern, .. }
139
+ | spargebra::Query::Ask { pattern, .. } => pattern,
140
+ }
141
+ }
142
+
143
+ /// Whether `pattern` holds a `SERVICE` clause at any depth. Both matches name
144
+ /// every variant, so a new kind of pattern or expression upstream stops the
145
+ /// build here until someone decides whether it can hold one.
146
+ fn pattern_has_service(pattern: &GraphPattern) -> bool {
147
+ match pattern {
148
+ GraphPattern::Service { .. } => true,
149
+ GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => false,
150
+ GraphPattern::Join { left, right }
151
+ | GraphPattern::Lateral { left, right }
152
+ | GraphPattern::Union { left, right }
153
+ | GraphPattern::Minus { left, right } => {
154
+ pattern_has_service(left) || pattern_has_service(right)
155
+ }
156
+ GraphPattern::LeftJoin {
157
+ left,
158
+ right,
159
+ expression,
160
+ } => {
161
+ pattern_has_service(left)
162
+ || pattern_has_service(right)
163
+ || expression.as_ref().is_some_and(expression_has_service)
164
+ }
165
+ GraphPattern::Filter { expr, inner } => {
166
+ expression_has_service(expr) || pattern_has_service(inner)
167
+ }
168
+ GraphPattern::Extend {
169
+ inner, expression, ..
170
+ } => pattern_has_service(inner) || expression_has_service(expression),
171
+ GraphPattern::OrderBy { inner, expression } => {
172
+ pattern_has_service(inner)
173
+ || expression.iter().any(|order| match order {
174
+ OrderExpression::Asc(expression) | OrderExpression::Desc(expression) => {
175
+ expression_has_service(expression)
176
+ }
177
+ })
178
+ }
179
+ GraphPattern::Group {
180
+ inner, aggregates, ..
181
+ } => {
182
+ pattern_has_service(inner)
183
+ || aggregates.iter().any(|(_, aggregate)| match aggregate {
184
+ AggregateExpression::CountSolutions { .. } => false,
185
+ AggregateExpression::FunctionCall { expr, .. } => expression_has_service(expr),
186
+ })
187
+ }
188
+ GraphPattern::Graph { inner, .. }
189
+ | GraphPattern::Project { inner, .. }
190
+ | GraphPattern::Distinct { inner }
191
+ | GraphPattern::Reduced { inner }
192
+ | GraphPattern::Slice { inner, .. } => pattern_has_service(inner),
193
+ }
194
+ }
195
+
196
+ /// Whether `expression` holds a `SERVICE` clause, which it can only do inside
197
+ /// the pattern of an `EXISTS`.
198
+ fn expression_has_service(expression: &Expression) -> bool {
199
+ match expression {
200
+ Expression::Exists(pattern) => pattern_has_service(pattern),
201
+ Expression::NamedNode(_)
202
+ | Expression::Literal(_)
203
+ | Expression::Variable(_)
204
+ | Expression::Bound(_) => false,
205
+ Expression::Or(left, right)
206
+ | Expression::And(left, right)
207
+ | Expression::Equal(left, right)
208
+ | Expression::SameTerm(left, right)
209
+ | Expression::Greater(left, right)
210
+ | Expression::GreaterOrEqual(left, right)
211
+ | Expression::Less(left, right)
212
+ | Expression::LessOrEqual(left, right)
213
+ | Expression::Add(left, right)
214
+ | Expression::Subtract(left, right)
215
+ | Expression::Multiply(left, right)
216
+ | Expression::Divide(left, right) => {
217
+ expression_has_service(left) || expression_has_service(right)
218
+ }
219
+ Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) | Expression::Not(inner) => {
220
+ expression_has_service(inner)
221
+ }
222
+ Expression::In(tested, candidates) => {
223
+ expression_has_service(tested) || candidates.iter().any(expression_has_service)
224
+ }
225
+ Expression::If(condition, then, otherwise) => {
226
+ expression_has_service(condition)
227
+ || expression_has_service(then)
228
+ || expression_has_service(otherwise)
229
+ }
230
+ Expression::Coalesce(arguments) | Expression::FunctionCall(_, arguments) => {
231
+ arguments.iter().any(expression_has_service)
232
+ }
233
+ }
234
+ }
235
+
236
+ /// Runs a query against `store` for `Store#query`. `query` is an
237
+ /// `Oxigraph::Query` or a `String` of SPARQL.
238
+ pub fn evaluate(ruby: &Ruby, store: &Store, query: Value) -> Result<Value, Error> {
239
+ let parsed;
240
+ let query = match <&Query>::try_convert(query) {
241
+ Ok(query) => query,
242
+ Err(_) => {
243
+ let Some(text) = RString::from_value(query) else {
244
+ return Err(Error::new(
245
+ ruby.exception_type_error(),
246
+ format!(
247
+ "wrong argument type {} (expected a String or Oxigraph::Query)",
248
+ query.class()
249
+ ),
250
+ ));
251
+ };
252
+ parsed = Query::from_text(ruby, SparqlParser::new(), &text.to_string()?)?;
253
+ &parsed
254
+ }
255
+ };
256
+ // Refused before anything is evaluated: with no handler for it, a SERVICE
257
+ // fails on its first row, but a SERVICE SILENT quietly matches nothing.
258
+ if query.service {
259
+ return Err(named_error(
260
+ ruby,
261
+ "UnsupportedError",
262
+ "SERVICE is not supported: a query never opens a network connection",
263
+ ));
264
+ }
265
+
266
+ let results = SparqlEvaluator::new()
267
+ .for_query(query.inner.clone())
268
+ .on_store(store)
269
+ .execute()
270
+ .map_err(|cause| named_error(ruby, "QueryEvaluationError", cause))?;
271
+ Ok(match results {
272
+ QueryResults::Boolean(answer) => ruby.into_value(answer),
273
+ QueryResults::Solutions(solutions) => ruby
274
+ .obj_wrap(QuerySolutions {
275
+ variables: solutions
276
+ .variables()
277
+ .iter()
278
+ .map(|variable| variable.as_str().to_owned())
279
+ .collect(),
280
+ rows: Rows::new(solutions),
281
+ })
282
+ .as_value(),
283
+ QueryResults::Graph(triples) => ruby
284
+ .obj_wrap(QueryTriples {
285
+ rows: Rows::new(triples),
286
+ })
287
+ .as_value(),
288
+ })
289
+ }
290
+
291
+ /// A result iterator that is read once, from Ruby, one row per call.
292
+ struct Rows<I> {
293
+ iterator: RefCell<Option<I>>,
294
+ started: Cell<bool>,
295
+ }
296
+
297
+ // SAFETY: upstream's result iterators are not `Send` because they hold `Rc`s.
298
+ // Every clone of those `Rc`s lives inside the iterator itself, and Ruby only
299
+ // calls into a wrapped object, or frees it, while it holds the GVL. So no two
300
+ // threads ever touch one at the same time, whichever thread that is. This
301
+ // stops being true if the extension ever evaluates a query with the GVL
302
+ // released.
303
+ unsafe impl<I> Send for Rows<I> {}
304
+
305
+ impl<I: Iterator<Item = Result<T, E>>, T, E: std::fmt::Display> Rows<I> {
306
+ fn new(iterator: I) -> Self {
307
+ Self {
308
+ iterator: RefCell::new(Some(iterator)),
309
+ started: Cell::new(false),
310
+ }
311
+ }
312
+
313
+ /// Marks the rows as being read, and fails if they already were.
314
+ fn start(&self, ruby: &Ruby) -> Result<(), Error> {
315
+ if self.started.replace(true) {
316
+ return Err(error(
317
+ ruby,
318
+ "query results can be read only once; run the query again to read them again",
319
+ ));
320
+ }
321
+ Ok(())
322
+ }
323
+
324
+ /// The next row, or `None` once they are used up. The iterator is dropped
325
+ /// at its end or at its first error, which frees its snapshot of the store.
326
+ fn advance(&self, ruby: &Ruby) -> Result<Option<T>, Error> {
327
+ let mut iterator = self.iterator.borrow_mut();
328
+ match iterator.as_mut().and_then(Iterator::next) {
329
+ Some(Ok(row)) => Ok(Some(row)),
330
+ Some(Err(cause)) => {
331
+ *iterator = None;
332
+ Err(named_error(ruby, "QueryEvaluationError", cause))
333
+ }
334
+ None => {
335
+ *iterator = None;
336
+ Ok(None)
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ /// The rows of a `SELECT`, exposed to Ruby as `Oxigraph::QuerySolutions`.
343
+ #[magnus::wrap(class = "Oxigraph::QuerySolutions", free_immediately, size)]
344
+ pub struct QuerySolutions {
345
+ variables: Vec<String>,
346
+ rows: Rows<QuerySolutionIter<'static>>,
347
+ }
348
+
349
+ impl QuerySolutions {
350
+ fn variables(ruby: &Ruby, rb_self: &Self) -> RArray {
351
+ ruby.ary_from_iter(rb_self.variables.iter().map(|name| ruby.to_symbol(name)))
352
+ }
353
+
354
+ fn start(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
355
+ rb_self.rows.start(ruby)
356
+ }
357
+
358
+ fn advance(ruby: &Ruby, rb_self: &Self) -> Result<Option<Obj<QuerySolution>>, Error> {
359
+ let row = rb_self.rows.advance(ruby)?;
360
+ Ok(row.map(|inner| frozen(ruby, QuerySolution { inner })))
361
+ }
362
+ }
363
+
364
+ /// One row of a `SELECT`, exposed to Ruby as `Oxigraph::QuerySolution`.
365
+ #[magnus::wrap(class = "Oxigraph::QuerySolution", free_immediately, size)]
366
+ pub struct QuerySolution {
367
+ inner: Row,
368
+ }
369
+
370
+ impl QuerySolution {
371
+ fn get(ruby: &Ruby, rb_self: &Self, key: Value) -> Result<Option<Value>, Error> {
372
+ let row = &rb_self.inner;
373
+ let term = if let Some(position) = magnus::Integer::from_value(key) {
374
+ usize::try_from(position.to_i64()?)
375
+ .ok()
376
+ .and_then(|position| row.get(position))
377
+ } else {
378
+ let name = if let Some(name) = Symbol::from_value(key) {
379
+ name.name()?.into_owned()
380
+ } else if let Some(name) = RString::from_value(key) {
381
+ name.to_string()?
382
+ } else {
383
+ return Err(Error::new(
384
+ ruby.exception_type_error(),
385
+ format!(
386
+ "wrong argument type {} (expected a Symbol, a String, or an Integer)",
387
+ key.class()
388
+ ),
389
+ ));
390
+ };
391
+ if !row
392
+ .variables()
393
+ .iter()
394
+ .any(|variable| variable.as_str() == name)
395
+ {
396
+ return Err(Error::new(
397
+ ruby.exception_index_error(),
398
+ format!("the query selects no variable named {name}"),
399
+ ));
400
+ }
401
+ row.get(name.as_str())
402
+ };
403
+ Ok(term.map(|term| term_to_value(ruby, term.clone())))
404
+ }
405
+
406
+ fn to_h(ruby: &Ruby, rb_self: &Self) -> Result<RHash, Error> {
407
+ let row = &rb_self.inner;
408
+ let bindings = ruby.hash_new();
409
+ for (variable, term) in row.variables().iter().zip(row.values()) {
410
+ bindings.aset(
411
+ ruby.to_symbol(variable.as_str()),
412
+ term.clone().map(|term| term_to_value(ruby, term)),
413
+ )?;
414
+ }
415
+ Ok(bindings)
416
+ }
417
+
418
+ fn inspect(&self) -> String {
419
+ let row = &self.inner;
420
+ let mut text = String::from("#<Oxigraph::QuerySolution");
421
+ for (variable, term) in row.variables().iter().zip(row.values()) {
422
+ text.push(' ');
423
+ text.push_str(variable.as_str());
424
+ text.push('=');
425
+ match term {
426
+ Some(term) => text.push_str(&term.to_string()),
427
+ None => text.push_str("nil"),
428
+ }
429
+ }
430
+ text.push('>');
431
+ text
432
+ }
433
+ }
434
+
435
+ /// The triples of a `CONSTRUCT` or a `DESCRIBE`, exposed to Ruby as
436
+ /// `Oxigraph::QueryTriples`.
437
+ #[magnus::wrap(class = "Oxigraph::QueryTriples", free_immediately, size)]
438
+ pub struct QueryTriples {
439
+ rows: Rows<QueryTripleIter<'static>>,
440
+ }
441
+
442
+ impl QueryTriples {
443
+ fn start(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
444
+ rb_self.rows.start(ruby)
445
+ }
446
+
447
+ fn advance(ruby: &Ruby, rb_self: &Self) -> Result<Option<Value>, Error> {
448
+ let row = rb_self.rows.advance(ruby)?;
449
+ Ok(row.map(|triple| triple_to_value(ruby, triple)))
450
+ }
451
+ }
452
+
453
+ /// None of these classes can be built from Ruby, so each loses its allocator
454
+ /// here, before `new` could make an instance with nothing inside it.
455
+ pub fn init(ruby: &Ruby, module: RModule) -> Result<(), Error> {
456
+ let class = module.define_class("Query", ruby.class_object())?;
457
+ class.undef_default_alloc_func();
458
+ class.define_singleton_method("parse", function!(Query::parse, -1))?;
459
+ class.define_method("form", method!(Query::form, 0))?;
460
+ class.define_method("service?", method!(Query::has_service, 0))?;
461
+ class.define_method("dataset?", method!(Query::has_dataset, 0))?;
462
+ class.define_method("to_s", method!(Query::to_s, 0))?;
463
+ class.define_method("inspect", method!(Query::inspect, 0))?;
464
+
465
+ let class = module.define_class("Update", ruby.class_object())?;
466
+ class.undef_default_alloc_func();
467
+ class.define_singleton_method("parse", function!(Update::parse, -1))?;
468
+ class.define_method("to_s", method!(Update::to_s, 0))?;
469
+ class.define_method("inspect", method!(Update::inspect, 0))?;
470
+
471
+ // `lib/oxigraph/query_results.rb` builds `each` on these two private
472
+ // methods, so that Ruby does the yielding.
473
+ let class = module.define_class("QuerySolutions", ruby.class_object())?;
474
+ class.undef_default_alloc_func();
475
+ class.define_method("variables", method!(QuerySolutions::variables, 0))?;
476
+ class.define_private_method("start_reading", method!(QuerySolutions::start, 0))?;
477
+ class.define_private_method("next_result", method!(QuerySolutions::advance, 0))?;
478
+
479
+ let class = module.define_class("QueryTriples", ruby.class_object())?;
480
+ class.undef_default_alloc_func();
481
+ class.define_private_method("start_reading", method!(QueryTriples::start, 0))?;
482
+ class.define_private_method("next_result", method!(QueryTriples::advance, 0))?;
483
+
484
+ let class = module.define_class("QuerySolution", ruby.class_object())?;
485
+ class.undef_default_alloc_func();
486
+ class.define_method("[]", method!(QuerySolution::get, 1))?;
487
+ class.define_method("to_h", method!(QuerySolution::to_h, 0))?;
488
+ class.define_method("inspect", method!(QuerySolution::inspect, 0))?;
489
+
490
+ Ok(())
491
+ }
@@ -0,0 +1,54 @@
1
+ use magnus::{function, method, prelude::*, Error, RModule, Ruby, Symbol, Value};
2
+
3
+ use crate::error::error;
4
+ use crate::load::load;
5
+ use crate::query::evaluate;
6
+
7
+ /// An RDF dataset held in memory, exposed to Ruby as `Oxigraph::Store`.
8
+ #[magnus::wrap(class = "Oxigraph::Store", free_immediately, size)]
9
+ pub struct Store {
10
+ inner: oxigraph::store::Store,
11
+ }
12
+
13
+ impl Store {
14
+ fn new(ruby: &Ruby) -> Result<Self, Error> {
15
+ let inner = oxigraph::store::Store::new().map_err(|cause| error(ruby, cause))?;
16
+ Ok(Self { inner })
17
+ }
18
+
19
+ fn size(ruby: &Ruby, rb_self: &Self) -> Result<usize, Error> {
20
+ rb_self.inner.len().map_err(|cause| error(ruby, cause))
21
+ }
22
+
23
+ fn is_empty(ruby: &Ruby, rb_self: &Self) -> Result<bool, Error> {
24
+ rb_self.inner.is_empty().map_err(|cause| error(ruby, cause))
25
+ }
26
+
27
+ fn query(ruby: &Ruby, rb_self: &Self, query: Value) -> Result<Value, Error> {
28
+ evaluate(ruby, &rb_self.inner, query)
29
+ }
30
+
31
+ /// The private half of `Store#load`, which `lib/oxigraph/store.rb` calls
32
+ /// once it has settled where the input comes from.
33
+ fn load_input(
34
+ ruby: &Ruby,
35
+ rb_self: &Self,
36
+ input: Value,
37
+ format: Option<Symbol>,
38
+ extension: Option<String>,
39
+ base_iri: Option<String>,
40
+ ) -> Result<Value, Error> {
41
+ load(ruby, &rb_self.inner, input, format, extension, base_iri)
42
+ }
43
+ }
44
+
45
+ pub fn init(ruby: &Ruby, module: RModule) -> Result<(), Error> {
46
+ let class = module.define_class("Store", ruby.class_object())?;
47
+ class.undef_default_alloc_func();
48
+ class.define_singleton_method("new", function!(Store::new, 0))?;
49
+ class.define_method("size", method!(Store::size, 0))?;
50
+ class.define_method("empty?", method!(Store::is_empty, 0))?;
51
+ class.define_method("query", method!(Store::query, 1))?;
52
+ class.define_private_method("load_input", method!(Store::load_input, 4))?;
53
+ Ok(())
54
+ }
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oxigraph
4
+ # The base class of every error this gem raises on its own account.
5
+ class Error < StandardError; end
6
+
7
+ # Raised when RDF input is malformed. +line+ and +column+ count from one and
8
+ # are +nil+ when the parser reports no position.
9
+ class ParseError < Error
10
+ attr_reader :line, :column
11
+
12
+ def initialize(message = nil, line: nil, column: nil)
13
+ super(message)
14
+ @line = line
15
+ @column = column
16
+ end
17
+ end
18
+
19
+ # Raised when a SPARQL query or update does not parse. The message says
20
+ # where.
21
+ class QuerySyntaxError < Error; end
22
+
23
+ # Raised when a query fails while it runs.
24
+ class QueryEvaluationError < Error; end
25
+
26
+ # Raised for a query that uses a feature this gem leaves out on purpose,
27
+ # which is SERVICE.
28
+ class UnsupportedError < Error; end
29
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oxigraph
4
+ # What Store#load learned from its input: the prefixes it declared, as a
5
+ # frozen Hash of prefix name to namespace IRI, and the base IRI in effect at
6
+ # its end, or +nil+.
7
+ LoadSummary = Data.define(:prefixes, :base_iri)
8
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oxigraph
4
+ # What QuerySolutions and QueryTriples share: results that arrive from the
5
+ # store one at a time and can be read once.
6
+ module QueryResults
7
+ include Enumerable
8
+
9
+ # Yields each result in turn, or returns an Enumerator without a block.
10
+ # Reading a second time raises Error, whether or not the first reading
11
+ # reached the end.
12
+ def each
13
+ return enum_for(:each) unless block_given?
14
+
15
+ start_reading
16
+ while (result = next_result)
17
+ yield result
18
+ end
19
+ self
20
+ end
21
+ end
22
+
23
+ class QuerySolutions
24
+ include QueryResults
25
+ end
26
+
27
+ class QueryTriples
28
+ include QueryResults
29
+ end
30
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oxigraph
4
+ class Store
5
+ # Loads RDF and returns a LoadSummary.
6
+ #
7
+ # Give either +input+, a String of RDF content or an object that responds
8
+ # to +read+ as an IO does, or +path:+, the name of a file. +format:+ is one
9
+ # of +:turtle+, +:rdf_xml+, +:n_triples+, +:n_quads+, +:trig+, +:n3+, and
10
+ # +:json_ld+. It is required with +input+; with +path:+ it defaults to the
11
+ # format the file extension names.
12
+ #
13
+ # A load is all or nothing: malformed input raises ParseError and leaves
14
+ # the store unchanged.
15
+ def load(input = nil, format: nil, path: nil, base_iri: nil)
16
+ if path.nil?
17
+ raise ArgumentError, "give RDF content, a reader, or path:" if input.nil?
18
+
19
+ load_input(input, format, nil, base_iri)
20
+ else
21
+ raise ArgumentError, "give input or path:, not both" unless input.nil?
22
+
23
+ File.open(path, "rb") { |file| load_input(file, format, File.extname(path), base_iri) }
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oxigraph
4
+ VERSION = "0.1.0.rc2"
5
+ end
data/lib/oxigraph.rb ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "oxigraph/version"
4
+ require_relative "oxigraph/errors"
5
+ require_relative "oxigraph/load_summary"
6
+
7
+ # The extension raises the error classes and builds a LoadSummary, so it loads
8
+ # after they exist. A precompiled gem ships one extension for each Ruby minor
9
+ # version, in a directory named for it; a gem compiled at install time has
10
+ # one, beside this file's directory. Only a missing file falls back, so an
11
+ # extension that is present and fails to load reports its own error.
12
+ versioned_extension = "oxigraph/#{RUBY_VERSION[/\A\d+\.\d+/]}/oxigraph"
13
+ begin
14
+ require versioned_extension
15
+ rescue LoadError => error
16
+ raise unless error.path == versioned_extension
17
+
18
+ require "oxigraph/oxigraph"
19
+ end
20
+
21
+ require_relative "oxigraph/query_results"
22
+ require_relative "oxigraph/store"