sparqlite 0.1.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3b02a4b2e49d23e887e1a9c1030c736693e7e33029d35ac903b14fb48fbb1e99
4
+ data.tar.gz: 98f14d49829f9c0bc3e0e67ce6ee03971745d17c2fd9dcaa0e33a81fdf06b6dc
5
+ SHA512:
6
+ metadata.gz: f29900a85f2bccedc8aeb40a77cdbc964236818400cce3b986bac5facbe4c6daebaa907269edaccd6aea9c70da49bd03e578485a5d1e821af39c70850f384e02
7
+ data.tar.gz: 963430ae07c36a3ac4ca4b9040e8081563782bc74b1ffb4fa360345cda111fae8c51ce9bc2ef977a766c8804a6e003ac99f3706c50489e16fff3a6672f0af132
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shoji Tokunaga
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # sparqlite
2
+
3
+ An interactive SPARQL shell for local RDF files, in the spirit of sqlite3 and irb.
4
+
5
+ ![A sparq session: completing a query, its result table, and an unknown-prefix error](demo.gif)
6
+
7
+ sparqlite opens a Turtle file and drops you into a SPARQL prompt — no server,
8
+ no configuration. Queries are syntax-highlighted as you type, and keywords,
9
+ variables, and the terms in your data are completed. Prefixes declared in the
10
+ file are available automatically, results are printed as aligned tables, and
11
+ history is kept across sessions.
12
+
13
+ ```
14
+ $ sparqlite example.ttl
15
+ sparql> SELECT ?film WHERE { :ArnoldSchwarzenegger :starredIn ?film };
16
+ film
17
+ --------------
18
+ :TheTerminator
19
+ :Commando
20
+ :Predator
21
+ :TotalRecall
22
+ ```
23
+
24
+ ## Installation
25
+
26
+ ```
27
+ gem install sparqlite
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ```
33
+ sparqlite FILE...
34
+ ```
35
+
36
+ The same command is also installed under the shorter name `sparq`.
37
+
38
+ Several files are loaded into one graph and queried together, for example
39
+ `sparq people.ttl films.ttl` or `sparq data/*.ttl`. When files declare the
40
+ same prefix differently, the first file given wins. A `FILE` may also be an
41
+ `http://` or `https://` URL of an RDF file.
42
+
43
+ - End a statement with `;`. A statement may span several lines.
44
+ - Press Tab to complete keywords, `?variables` already used in the statement,
45
+ and prefixed names found in the data.
46
+ - Every prefix in the file is declared for you, and so are `rdf:`, `rdfs:`,
47
+ `owl:`, `xsd:` and the common vocabularies known to
48
+ [rdf-vocab](https://github.com/ruby-rdf/rdf-vocab) (`foaf:`, `schema:`,
49
+ `skos:`, `dc:`, ...), so queries usually need no `PREFIX` lines. A prefix
50
+ declared in the file wins over a built-in one of the same name.
51
+ - A prefix that is declared nowhere is reported as `unknown prefix: ...`
52
+ instead of silently matching nothing. Add a `PREFIX` line to the query to
53
+ use one.
54
+ - Type `.exit` or press Ctrl-D to quit.
55
+ - History is saved to `~/.sparql_history`.
56
+ - Colors are turned off when the output is not a terminal or `NO_COLOR` is set.
57
+
58
+ ## License
59
+
60
+ [MIT](LICENSE)
data/exe/sparq ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # Short name for the sparqlite command.
4
+ load File.expand_path('sparqlite', __dir__)
data/exe/sparqlite ADDED
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'sparqlite'
4
+
5
+ # Also run as "sparq", so messages use the name it was started with.
6
+ program = File.basename($PROGRAM_NAME)
7
+ usage = "Usage: #{program} FILE..."
8
+
9
+ case ARGV[0]
10
+ when nil
11
+ warn usage
12
+ exit 1
13
+ when '-h', '--help'
14
+ puts usage
15
+ puts 'Open one or more RDF files and start an interactive SPARQL prompt.'
16
+ puts 'End a statement with ";". Type ".exit" or press Ctrl-D to quit.'
17
+ when '-v', '--version'
18
+ puts Sparqlite::VERSION
19
+ else
20
+ # A URL is fetched by the reader, so only local paths are checked here.
21
+ missing = ARGV.reject { |path| path.match?(%r{\Ahttps?://}) || File.file?(path) }
22
+ unless missing.empty?
23
+ missing.each { |path| warn "#{program}: no such file: #{path}" }
24
+ exit 1
25
+ end
26
+ Sparqlite::Shell.new(ARGV).start
27
+ end
@@ -0,0 +1,274 @@
1
+ require 'rdf/turtle'
2
+ require 'rdf/vocab'
3
+ require 'sparql'
4
+ require 'reline'
5
+
6
+ module Sparqlite
7
+ # An interactive SPARQL prompt over one RDF file.
8
+ class Shell
9
+ # Always available, so common vocabularies (foaf:, schema:, skos:, ...)
10
+ # work without a declaration. Prefixes declared in the data file take
11
+ # precedence over these.
12
+ DEFAULT_PREFIXES = {
13
+ 'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
14
+ 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
15
+ 'owl' => 'http://www.w3.org/2002/07/owl#',
16
+ 'xsd' => 'http://www.w3.org/2001/XMLSchema#'
17
+ }.merge(RDF::Vocab::VOCABS.to_h { |name, vocab| [name.to_s, vocab[:uri]] }) { |_, ours, _| ours }.freeze
18
+
19
+ KEYWORDS = %w[
20
+ SELECT DISTINCT REDUCED CONSTRUCT DESCRIBE ASK FROM NAMED WHERE
21
+ OPTIONAL UNION MINUS GRAPH SERVICE FILTER BIND VALUES AS
22
+ GROUP ORDER BY ASC DESC HAVING LIMIT OFFSET
23
+ NOT EXISTS IN UNDEF PREFIX BASE
24
+ COUNT SUM MIN MAX AVG SAMPLE GROUP_CONCAT SEPARATOR
25
+ STR LANG LANGMATCHES DATATYPE BOUND IRI URI BNODE
26
+ ISIRI ISURI ISBLANK ISLITERAL ISNUMERIC SAMETERM
27
+ REGEX REPLACE CONCAT CONTAINS STRSTARTS STRENDS STRLEN SUBSTR
28
+ UCASE LCASE COALESCE IF
29
+ ].freeze
30
+
31
+ # Colors follow irb where the token kinds overlap (keywords green,
32
+ # strings red, numbers bold blue).
33
+ STYLES = {
34
+ keyword: '32',
35
+ variable: '36',
36
+ iri: '34;4',
37
+ pname: '33',
38
+ string: '31',
39
+ number: '34;1',
40
+ comment: '90',
41
+ header: '1'
42
+ }.freeze
43
+
44
+ # One alternative per token kind. The IRI comes before the comment so a
45
+ # "#" inside <...> is not taken as a comment start.
46
+ TOKEN = /
47
+ (?<iri><[^<>\s]*>) |
48
+ (?<comment>\#.*) |
49
+ (?<string>"(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?) |
50
+ (?<variable>[?$]\w+) |
51
+ (?<pname>(?:[A-Za-z_][\w-]*)?:[\w-]*) |
52
+ (?<number>\b\d+(?:\.\d+)?\b) |
53
+ (?<word>[A-Za-z_]\w*)
54
+ /x
55
+
56
+ HISTORY_FILE = File.expand_path('~/.sparql_history')
57
+ HISTORY_MAX = 1000
58
+
59
+ # All files are loaded into one graph. Blank nodes stay separate per
60
+ # file even when two files use the same label.
61
+ def initialize(paths)
62
+ @prefixes = {}
63
+ @graph = RDF::Graph.new
64
+ Array(paths).each do |path|
65
+ RDF::Reader.open(path) do |reader|
66
+ @graph << reader
67
+ # The empty prefix (":") is stored under nil. When files disagree
68
+ # on a prefix, the first file given wins.
69
+ reader.prefixes.each { |name, ns| @prefixes[name.to_s] ||= ns.to_s }
70
+ end
71
+ end
72
+ # The files' prefixes come first so they win, both by name and when
73
+ # two prefixes share a namespace.
74
+ @prefixes = @prefixes.merge(DEFAULT_PREFIXES) { |_, from_file, _| from_file }
75
+ # Longest namespace first, for format_term.
76
+ @namespaces = @prefixes.each_with_index.sort_by { |(_, ns), i| [-ns.length, i] }.map(&:first)
77
+ @terms = (graph_terms + @prefixes.keys.map { |name| "#{name}:" } + ['a']).uniq.sort
78
+ @buffer = ''
79
+ # No escape codes when piped to a file or another command.
80
+ @color = $stdout.tty? && !ENV.key?('NO_COLOR')
81
+ end
82
+
83
+ def start
84
+ setup_reline
85
+ load_history
86
+ # History is managed by hand (second argument false) so that
87
+ # continuation lines are not stored one by one.
88
+ while (line = Reline.readline(@buffer.empty? ? 'sparql> ' : ' ...> ', false))
89
+ if @buffer.empty?
90
+ break if line.strip == '.exit'
91
+ next if line.strip.empty?
92
+ end
93
+
94
+ @buffer << line << "\n"
95
+ next unless complete?(@buffer)
96
+
97
+ history_entries(@buffer).each { |entry| remember(entry) }
98
+ run(@buffer.rstrip.chomp(';'))
99
+ @buffer = ''
100
+ end
101
+ ensure
102
+ save_history
103
+ end
104
+
105
+ private
106
+
107
+ # Render a term the way it would be typed in a query.
108
+ def format_term(term)
109
+ return '' if term.nil?
110
+ return term.to_s unless term.is_a?(RDF::URI)
111
+
112
+ uri = term.to_s
113
+ # Prefer the longest matching namespace.
114
+ @namespaces.each do |name, ns|
115
+ next unless uri.start_with?(ns)
116
+
117
+ local = uri.delete_prefix(ns)
118
+ return "#{name}:#{local}" if local.match?(/\A[\w-]*\z/)
119
+ end
120
+ "<#{uri}>"
121
+ end
122
+
123
+ def paint(text, style)
124
+ return text unless @color && style && !text.empty?
125
+
126
+ "\e[#{STYLES.fetch(style)}m#{text}\e[0m"
127
+ end
128
+
129
+ def term_style(term)
130
+ case term
131
+ when RDF::URI then format_term(term).start_with?('<') ? :iri : :pname
132
+ when RDF::Literal then term.is_a?(RDF::Literal::Numeric) ? :number : :string
133
+ end
134
+ end
135
+
136
+ def highlight(input)
137
+ input.gsub(TOKEN) do |token|
138
+ kind = $~.named_captures.find { |_, v| v }.first.to_sym
139
+ if kind == :word
140
+ known = KEYWORDS.include?(token.upcase) || %w[a true false].include?(token)
141
+ kind = known ? :keyword : nil
142
+ end
143
+ paint(token, kind)
144
+ end
145
+ end
146
+
147
+ # Print rows of RDF terms like sqlite3's ".mode column" with ".headers on".
148
+ def print_table(headers, rows)
149
+ # "SELECT *" with no solutions has no variables to show.
150
+ return if headers.empty?
151
+
152
+ texts = rows.map { |r| r.map { |t| format_term(t) } }
153
+ widths = headers.each_index.map do |i|
154
+ ([headers[i]] + texts.map { |r| r[i] }).map(&:length).max
155
+ end
156
+ # Pad by the visible width; the escape codes must not count.
157
+ line = lambda do |cells, styles|
158
+ cells.each_with_index.map { |c, i| paint(c, styles[i]) + ' ' * (widths[i] - c.length) }
159
+ .join(' ').rstrip
160
+ end
161
+
162
+ puts line.call(headers, headers.map { :header })
163
+ puts widths.map { |w| '-' * w }.join(' ')
164
+ rows.each_with_index { |r, i| puts line.call(texts[i], r.map { |t| term_style(t) }) }
165
+ end
166
+
167
+ def print_result(result)
168
+ case result
169
+ when RDF::Query::Solutions
170
+ names = result.variable_names
171
+ print_table(names.map(&:to_s), result.map { |s| names.map { |n| s[n] } })
172
+ when RDF::Enumerable
173
+ # CONSTRUCT / DESCRIBE return a graph.
174
+ print_table(%w[subject predicate object], result.map { |st| [st.subject, st.predicate, st.object] })
175
+ else
176
+ # ASK returns true / false.
177
+ puts paint(result.to_s, :keyword)
178
+ end
179
+ end
180
+
181
+ # A statement ends with ";" outside of any { } block, so the ";" used
182
+ # inside triple patterns does not terminate it.
183
+ def complete?(buffer)
184
+ buffer.rstrip.end_with?(';') && buffer.count('{') == buffer.count('}')
185
+ end
186
+
187
+ # Prefixes the query uses and the ones it declares itself. "_:" is a
188
+ # blank node label, not a prefix.
189
+ def query_prefixes(query)
190
+ used = []
191
+ declared = []
192
+ after_prefix = false
193
+ query.scan(TOKEN) do
194
+ match = $~
195
+ (after_prefix ? declared : used) << match[:pname].split(':', 2).first if match[:pname]
196
+ after_prefix = match[:word]&.casecmp?('PREFIX') || false
197
+ end
198
+ [(used - declared - ['_']).uniq, declared]
199
+ end
200
+
201
+ def run(query)
202
+ used, = query_prefixes(query)
203
+ # The engine silently matches nothing for an undeclared prefix, which
204
+ # looks like missing data, so reject it here.
205
+ unknown = used - @prefixes.keys
206
+ return puts("unknown prefix: #{unknown.map { |name| "#{name}:" }.join(', ')}") unless unknown.empty?
207
+
208
+ # Declare only what the query uses, on the query's first line so the
209
+ # line numbers in error messages match what was typed.
210
+ header = used.map { |name| "PREFIX #{name}: <#{@prefixes[name]}> " }.join
211
+ print_result(SPARQL.execute("#{header}#{query}", @graph))
212
+ rescue StandardError, SPARQL::MalformedQuery => e
213
+ # MalformedQuery does not inherit from StandardError.
214
+ puts e.message
215
+ end
216
+
217
+ # Every IRI in the data that can be written as a prefixed name.
218
+ def graph_terms
219
+ @graph.each_statement.flat_map(&:to_a).grep(RDF::URI).uniq
220
+ .map { |t| format_term(t) }.reject { |t| t.start_with?('<') }
221
+ end
222
+
223
+ def setup_reline
224
+ # Show candidates in a dropdown while typing, as irb does.
225
+ Reline.autocompletion = true
226
+ # ":" and "?" must stay inside a word, so set the break characters explicitly.
227
+ Reline.completer_word_break_characters = " \t\n{}()[];,|/^!"
228
+ Reline.completion_proc = ->(word) { candidates(word) }
229
+ # Color the line being edited, as irb does.
230
+ Reline.output_modifier_proc = ->(output, complete:) { highlight(output) }
231
+ end
232
+
233
+ def candidates(word)
234
+ if word.start_with?('?')
235
+ # Variables already typed in this statement; the word under the
236
+ # cursor is not a candidate for itself.
237
+ seen = "#{@buffer}#{Reline.line_buffer}".scan(/\?\w+/).uniq - [word]
238
+ return seen.select { |v| v.start_with?(word) }
239
+ end
240
+ return ['.exit'] if word.start_with?('.')
241
+
242
+ # Keywords follow the case being typed.
243
+ keywords = KEYWORDS.select { |k| k.start_with?(word.upcase) }
244
+ keywords = keywords.map(&:downcase) if word.match?(/\A[a-z]/)
245
+ keywords + @terms.select { |t| t.start_with?(word) }
246
+ end
247
+
248
+ # History entries for a finished statement. A multi-line statement becomes
249
+ # one entry so a single Up brings back the whole query, as in bash.
250
+ def history_entries(statement)
251
+ lines = statement.lines.map(&:strip).reject(&:empty?)
252
+ # A "#" comment would swallow the rest of a joined line, so keep such
253
+ # statements line by line. "#" inside <...> is part of an IRI.
254
+ return lines if lines.any? { |l| l.gsub(/<[^>]*>/, '').include?('#') }
255
+
256
+ [lines.join(' ')]
257
+ end
258
+
259
+ def remember(entry)
260
+ # Skip immediate repeats.
261
+ Reline::HISTORY << entry unless Reline::HISTORY.to_a.last == entry
262
+ end
263
+
264
+ def load_history
265
+ return unless File.exist?(HISTORY_FILE)
266
+
267
+ File.readlines(HISTORY_FILE, chomp: true).each { |entry| Reline::HISTORY << entry }
268
+ end
269
+
270
+ def save_history
271
+ File.write(HISTORY_FILE, Reline::HISTORY.to_a.last(HISTORY_MAX).map { |e| "#{e}\n" }.join)
272
+ end
273
+ end
274
+ end
@@ -0,0 +1,3 @@
1
+ module Sparqlite
2
+ VERSION = '0.1.0'
3
+ end
data/lib/sparqlite.rb ADDED
@@ -0,0 +1,2 @@
1
+ require 'sparqlite/version'
2
+ require 'sparqlite/shell'
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sparqlite
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Shoji Tokunaga
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2026-11-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rdf-turtle
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.3'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rdf-vocab
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.3'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.3'
41
+ - !ruby/object:Gem::Dependency
42
+ name: reline
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.3'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.3'
55
+ - !ruby/object:Gem::Dependency
56
+ name: sparql
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.3'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.3'
69
+ description: |
70
+ sparqlite opens a Turtle file and drops you into a SPARQL prompt with no
71
+ server and no configuration. Queries are syntax-highlighted as you type,
72
+ and keywords, variables, and the terms in your data are completed.
73
+ email:
74
+ executables:
75
+ - sparqlite
76
+ - sparq
77
+ extensions: []
78
+ extra_rdoc_files: []
79
+ files:
80
+ - LICENSE
81
+ - README.md
82
+ - exe/sparq
83
+ - exe/sparqlite
84
+ - lib/sparqlite.rb
85
+ - lib/sparqlite/shell.rb
86
+ - lib/sparqlite/version.rb
87
+ homepage: https://github.com/sean2121/sparqlite
88
+ licenses:
89
+ - MIT
90
+ metadata:
91
+ source_code_uri: https://github.com/sean2121/sparqlite
92
+ bug_tracker_uri: https://github.com/sean2121/sparqlite/issues
93
+ post_install_message:
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '3.0'
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ requirements: []
108
+ rubygems_version: 3.2.33
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: An interactive SPARQL shell for local RDF files, in the spirit of sqlite3
112
+ and irb.
113
+ test_files: []