Module:PersonOtherProperties: Difference between revisions

From MaRDI portal
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 target1 = frame.args[1] if not target1 or target1 == '' then return "No records found" e..."
 
No edit summary
 
(40 intermediate revisions by the same user not shown)
Line 1: Line 1:
-- Required module containing helper methods
local helper = require('Module:HelperMethods')
-- Required modules for SPARQL queries and HTML table generation
-- Required modules for SPARQL queries and HTML table generation
local sparql = require('SPARQL')
local sparql = require('SPARQL')
Line 10: Line 13:
     -- Retrieve target1 from frame arguments or return error message if not set
     -- Retrieve target1 from frame arguments or return error message if not set
local target1 = frame.args[1]
local target = frame.args[1]
     if not target1 or target1 == '' then
     if not target or target == '' then
         return "No records found"
         return "No records found"
     end     
     end     
Line 17: Line 20:
     -- Constructing the SPARQL query with dynamic entity target1
     -- Constructing the SPARQL query with dynamic entity target1
     local sparqlQuery = [[
     local sparqlQuery = [[
PREFIX target1: <https://portal.mardi4nfdi.de/entity/]] .. target1 .. [[>
PREFIX target: <https://portal.mardi4nfdi.de/entity/]] .. target .. [[>
PREFIX wdt: <https://portal.mardi4nfdi.de/prop/direct/>
PREFIX wdt: <https://portal.mardi4nfdi.de/prop/direct/>
PREFIX wd: <https://portal.mardi4nfdi.de/entity/>
PREFIX wd: <https://portal.mardi4nfdi.de/entity/>


SELECT ?property ?propertyLabel ?value ?valueLabel ?relatedEntity ?relatedEntityLabel ?relatedProperty ?relatedPropertyValue
SELECT ?property ?propertyLabel ?value ?valueLabel
WHERE {
WHERE {
     target: ?p ?value .
     target: ?p ?value .
     ?property ?ref ?p .
     ?property ?ref ?p .
     ?property a wikibase:Property .
     ?property a wikibase:Property .
    OPTIONAL {
        ?value ?relatedProperty ?relatedPropertyValue .
        ?relatedEntity ?x ?relatedProperty .
        ?relatedEntity rdf:type wikibase:Item .
        FILTER(STRSTARTS(STR(?relatedPropertyValue), "https://portal.mardi4nfdi.de/entity/"))
    }


     OPTIONAL {
     OPTIONAL {
Line 39: Line 35:
     }
     }


     FILTER (!isURI(?value) || (!STRSTARTS(STR(?value), "https://portal.mardi4nfdi.de/entity/statement/") && !BOUND(?valueLabel)))
     FILTER NOT EXISTS { FILTER(STRSTARTS(STR(?value), "http")) }


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


Line 54: Line 53:
end
end
-- Extracting headers from the SPARQL query results
if not jsonResults then
-- NOTE that these headers are not used since we will use hard coded ones below
        return "Could not fetch data."
local headers = {}
end
if jsonResults and jsonResults.head and jsonResults.head.vars then
 
headers = jsonResults.head.vars
if helper.countElementsInBindings(jsonResults.results.bindings) == 0 then
        return "No records found."
end
end
-- Hard-code headers
    local headers = {"Publication", "Date of Publication"}


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


-- Create and return a HTML table from the data
-- Create and return a HTML table from the data
return createHtmlTableWithMergedCols(dataTable, headers)
    local headers = {"Property", "Value"}
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
local dataRow = htmlTable:tag('tr')
local combinedData = '[' .. row[1] .. ' ' .. row[2] .. ']'
dataRow:tag('td'):wikitext(combinedData)
-- Add subsequent columns, skipping the third one
for j = 4, #row do
dataRow:tag('td'):wikitext(row[j])
end
end


return tostring(htmlTable)
    return helper.createHtmlTableWithMergedCols(dataTable, headers, {{2, 3}, {1}})
   
end
end


-- Return the created html table
-- Return the created html table
return p
return p

Latest revision as of 17:32, 7 February 2024

Overview

This Lua module queries the local SPARQL endpoints to show all known properties that are having a direct value (e.g. birthdate) and not a relationship (e.g doctoral student of).

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 module containing helper methods
local helper = require('Module:HelperMethods')

-- 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 .

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

    FILTER NOT EXISTS { FILTER(STRSTARTS(STR(?value), "http")) }

    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
	
	if not jsonResults then
        return "Could not fetch data."
	end

	if helper.countElementsInBindings(jsonResults.results.bindings) == 0 then
        return "No records found."
	end

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

	-- Create and return a HTML table from the data
    local headers = {"Property", "Value"}

    return helper.createHtmlTableWithMergedCols(dataTable, headers, {{2, 3}, {1}})
    
end

-- Return the created html table
return p