Module:SPARQL

local sparql = {} local f = require("Module:Functional")

-- -- basic text manipulation --

-- auxiliary function for text formatting : indent once all lines of the texts in "subquery" with a tab character function sparql.indent_lines(subquery) return string.gsub("\t" .. subquery, "\n", "\n\t") end

local function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end

local function numlines(text) local _, count = string.gsub(trim(text), "\n", "") return count end

local function is_var(var) mw.log(var) return string.sub(var, 1, 1) == "?" end sparql.is_var = is_var

local function remove_questionmark(var) if is_var(var) then var= string.sub(var, 2) end return string.gsub(var," ", "_") end

function sparql.prefix_var(var, prefix) return "?" .. remove_questionmark(prefix) .. remove_questionmark(var) end

function sparql.create_var(var) return "?" ..remove_questionmark(var) end

-- -- SPARQL generation --

-- select

-- select generation -- generates the query to compute the projection of a subset of variable ("vars") in the "query" result set function sparql.pi(vars, query) return "select " .. table.concat(vars, ', ') .. " where " .. sparql.build_block(query) end

-- union

function sparql.union (queries) if #queries > 1 then return table.concat( 			f.map(function(query) return sparql.build_block(query) end, queries),			" union "		) else return queries[1] end end

-- minus

function sparql.minus(init_q, to_remove) return init_q .. " minus " .. sparql.build_block(to_remove) end

-- intersection

function sparql.intersect(queries) local prepare = function(query) if numlines(query) ~= 0 then return sparql.build_block(query) else return trim(query) end end return table.concat(		f.map(prepare, queries),		" .\n"		) .. " ." end

-- -- SPARQL formatting --

-- put a subquery in brackets and formats the block function sparql.build_block(query) return "{\n" .. sparql.indent_lines(query) .. "\n}" end

return sparql