Module:QuickQuery

Lua
CodeDiscussionLinksLink count SubpagesDocumentationTestsResultsSandboxLive code All modules

Documentation for this module may be created at Module:QuickQuery/doc

Code

local p = {}

local VAR_REGEX = '?[a-zA-Z]+'

-- debug with e.g. =p.main(nil, {'?cat wdt:P31 wd:Q146'})
function p.main (frame, debugArgs)
	local args = debugArgs or frame:getParent().args
	local where = mw.text.trim(args[1] or error('expected first argument with WHERE clause'))
	
	local exprs = {}
	local vars = {}

	for var in where:gmatch(VAR_REGEX) do
		if not vars[var] then
			table.insert(exprs, var)
			table.insert(exprs, var .. 'Label')
			if args.description == 'yes' then
				table.insert(exprs, var .. 'Description')
			end
			vars[var] = true
		end
	end
	
	local query = ''
	
	if args.defaultView then
		query = '#defaultView:'	.. args.defaultView .. '\n'
	end
	
	query = query .. 'SELECT ' .. table.concat(exprs, ' ') .. ' WHERE {\n    ' .. where .. '\n    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }\n}'
	if args.limit then
		query = query .. ' LIMIT ' .. args.limit	
	end
	local label = args[2]
	if not label then
		label = where:gsub('[PQ][0-9]+', function (s)
			local label = mw.wikibase.getLabel( s ) or error('property ' .. s .. ' does not exist')
			return '<span class=quickquery-label>' .. mw.text.nowiki(label) .. ' <small>(' .. s .. ')</small></span>'
		end)
		label = label:gsub(VAR_REGEX, function (s)
			return '<span class=quickquery-var>' .. s .. '</span>'
		end)
	end
	return '[//query.wikidata.org/embed.html#' .. mw.uri.encode(query, 'PATH') .. ' ' .. label:gsub('\]', '&#93;') .. ']'
end
return p