Module:PersonOtherRelations

From MaRDI portal
Revision as of 10:17, 8 December 2023 by Tconrad (talk | contribs) (Created page with "-- Required modules for SPARQL queries and HTML table generation local sparql = require('SPARQL') local mwHtml = require('mw.html') -- Main table to hold all functions local p = {} -- Function to build a HTML table from SPARQL query results function p.buildTableFromSparql(frame) -- Retrieve target1 from frame arguments or return error message if not set local target = frame.args[1] if not target or target == '' then return "No records found" end...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Overview

This Lua module queries the local SPARQL endpoints to show all known relations and their values (e.g. is doctoral student of) and not a value (e.g birthdate).

The module operates by executing the SPARQL query against a specified Wikidata entity. The query is constructed to retrieve a set of properties (?property), their labels (?propertyLabel), and their corresponding values (?value) for the target entity. In cases where a value is another Wikidata entity, an optional clause in the query attempts to fetch the label (?valueLabel) for these entities, enhancing the readability of the results.

Dependencies

SPARQL Module: Used for executing SPARQL queries. mw.html Module: Utilized for constructing HTML content, particularly for table generation.

Module Functions

buildTableFromSparql(frame)

Constructs an HTML table based on SPARQL query results related to a specified entity.

Parameters
* frame: A frame object containing arguments passed to the module. The first argument should be the entity ID.
Returns
* A string representing an HTML table with the SPARQL query results.
* If the target entity ID is not provided, it returns "No records found".
Description
This function forms a SPARQL query using the provided entity ID, executes the query, and processes the results into a formatted HTML table. It handles errors in SPARQL query execution and logs them for debugging. The table contains columns for properties and their values related to the entity.

convertJsonToTable(jsonResults)

Converts JSON-formatted SPARQL query results into a Lua table.

Parameters
* jsonResults: The JSON object containing the SPARQL query results.
Returns
* A Lua table representation of the SPARQL query results.
Description
Parses the JSON results from a SPARQL query and converts them into a structured Lua table for further processing.

createHtmlTableWithMergedCols(dataTable, headers)

Generates an HTML table from a Lua table with specified headers, merging certain columns for readability.

Parameters
* dataTable: The data table obtained from SPARQL query results.
* headers: A table of strings representing the headers for the HTML table.
Returns
* A string representing the constructed HTML table.
Description
Constructs an HTML table using mw.html. It merges specific columns from the data table based on their content (URLs or literal values) for better presentation in the HTML format.

Usage Example

To use this module in a MediaWiki template or page, invoke it with the necessary parameters, such as the Wikidata entity ID:

{{#invoke:YourModuleName|buildTableFromSparql|Q161115}}

Replace YourModuleName with the actual name of this module. The parameter (e.g., 'Q161115') should be the Wikidata entity ID for which you want to fetch and display data.

Debugging Example

For testing or debugging purposes, you can simulate the module's function in a Lua sandbox using:

local mockFrame = { args = { 'Q161115' } }
local result = p.buildTableFromSparql(mockFrame)
mw.log(result)

Replace 'Q161115' with the desired entity ID.


-- Required modules for SPARQL queries and HTML table generation
local sparql = require('SPARQL')
local mwHtml = require('mw.html')

-- Main table to hold all functions
local p = {}

-- Function to build a HTML table from SPARQL query results
function p.buildTableFromSparql(frame)
	
    -- Retrieve target1 from frame arguments or return error message if not set
	local target = frame.args[1]
    if not target or target == '' then
        return "No records found"
    end    

    -- Constructing the SPARQL query with dynamic entity target1
    local sparqlQuery = [[
PREFIX target: <https://portal.mardi4nfdi.de/entity/]] .. target .. [[>
PREFIX wdt: <https://portal.mardi4nfdi.de/prop/direct/>
PREFIX wd: <https://portal.mardi4nfdi.de/entity/>

SELECT ?property ?propertyLabel ?value ?valueLabel
WHERE {
    target: ?p ?value .
    ?property ?ref ?p .
    ?property a wikibase:Property .

    ?value rdfs:label ?valueLabel .
    FILTER(LANG(?valueLabel) = "en")

    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY ?propertyLabel

    ]]

	-- Executing the SPARQL query and retrieving results in JSON format
	local jsonResults = sparql.runQuery(sparqlQuery)

	-- Handle error in SPARQL query execution
	if jsonResults and jsonResults.error then
    	mw.log("Error in SPARQL query: " .. tostring(jsonResults.error))
    	return nil
	end
	
	-- Extracting headers from the SPARQL query results
	-- NOTE that these headers are not used since we will use hard coded ones below
	local headers = {}
	if jsonResults and jsonResults.head and jsonResults.head.vars then
		headers = jsonResults.head.vars
	end
	
	-- Hard-code headers
    local headers = {"Property", "Value"}

	-- Convert the JSON results into a Lua table
	local dataTable = convertJsonToTable(jsonResults)

	-- Create and return a HTML table from the data
	return createHtmlTableWithMergedCols(dataTable, headers)
end

-- Utility function to trim and lowercase a string
function trimAndLower(str)
	if str == nil then return nil end
	str = str:gsub("^%s*(.-)%s*$", "%1")
	return str:lower()
end

-- Function to convert JSON results into a Lua table
function convertJsonToTable(jsonResults)
    local resultsTable = {}
    if jsonResults and jsonResults.results and jsonResults.results.bindings then
        local bindings = jsonResults.results.bindings
        for j = 1, #bindings do
            local row = {}
            for key, value in pairs(bindings[j]) do
                table.insert(row, value.value)
            end
            table.insert(resultsTable, row)
        end
    end
    return resultsTable
end

-- Function to create a HTML table from a Lua table
function createHtmlTableWithMergedCols(dataTable, headers)
	local htmlTable = mwHtml.create('table')
	htmlTable:addClass('wikitable'):attr('border', '1')

	local headerRow = htmlTable:tag('tr')
	
	-- Use the provided headers
    for _, header in ipairs(headers) do
        headerRow:tag('th'):wikitext(header)
    end

	-- The first two columns are merged
	for _, row in ipairs(dataTable) do

		if not string.find(row[1], "/entity/statement/") then

			-- mw.logObject(row)
		
			local dataRow = htmlTable:tag('tr')
			local combinedData1, combinedData2
			
			combinedData1 = '[' .. row[2] .. ' ' .. row[4] .. ']'
			combinedData2 = '[' .. row[1] .. ' ' .. row[3] .. ']'

			-- Add rows to table
		    dataRow:tag('td'):wikitext(combinedData1)
		    dataRow:tag('td'):wikitext(combinedData2)

		end -- if not string.find(row[1], "/entity/statement/") then
		
	end
	
	mw.log(htmlTable)

	return tostring(htmlTable)
end

-- Return the created html table
return p