Дополнительные действия
Для документации этого модуля может быть создана страница Модуль:VarQuery/doc
local p = {}
local cargo = mw.ext.cargo -- используем Cargo API
local getArgs = require('Module:Arguments').getArgs
local Json = require('Module:Json')
local Variables = require('Module:Variables')
local i18n = {
error = {
multiple_results = 'More than one result.',
no_results = 'No results found.',
no_table = 'No table given',
}
}
-- Функция для разделения строки
local function split(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
--- Validates the given rows.
local function validate(rows, surpress)
local errorMsg
if type(rows) == 'string' then
errorMsg = rows
mw.logObject(rows)
end
local nrows = #rows
if nrows ~= 1 then
if nrows == 0 then
errorMsg = (i18n.error.no_results)
else
errorMsg = (i18n.error.multiple_results)
end
end
if errorMsg then
if surpress then
mw.log(errorMsg)
else
error(errorMsg)
end
return false
end
return true
end
--- Clear already existing variables that could interfere with the new ones.
local function clear_variables(prefix, fields)
for _, field in ipairs(split(fields, '%s*,%s*')) do
local var_key = prefix .. field
if Variables.varExists(var_key) then
Variables.varDefine(var_key, '')
end
end
end
--- Write the row values to the corresponding variables.
local function write_variables(prefix, row)
for key, value in pairs(row) do
if type(value) == 'table' then
write_variables(prefix .. key .. '_', value)
elseif key == 'extradata' then
write_variables(prefix .. key .. '_', Json.parse(mw.text.decode(value)))
else
local var_key = prefix .. key
Variables.varDefine(var_key, value)
end
end
end
function p.main(frame)
local args = getArgs(frame)
local fields = args['field'] or args['fields'] or 'pagename'
local prefix = args['prefix'] or 'cargo_'
-- Логируем перед началом работы
mw.log('Параметры:', args)
if args.fromArgs then
clear_variables(prefix, fields)
write_variables(prefix, args)
return
end
local table = args['table'] or args['tables']
assert(table, i18n.error.no_table)
clear_variables(prefix, fields)
-- Логируем перед запросом
mw.log('Запрос к Cargo:', table, fields)
local rows = cargo.query(table, fields, {
where = args.where,
groupBy = args['group by'],
orderBy = args['order by'],
limit = 1,
format = 'table'
})
-- Логируем результат запроса
mw.log('Результат запроса:', rows)
if validate(rows, args.failquiet) then
write_variables(prefix, rows[1])
end
end
return p