Дополнительные действия
Для документации этого модуля может быть создана страница Модуль:VarQuery/doc
local p = {}
local iccupdb = mw.ext.iCCupDB
local getArgs = require('Module:Arguments').getArgs
local split = require('Module:Split')
local Json = require('Module:Json')
local Variables = require('Module:Variables')
local i18n = {
error = {
multiple_results = 'Найдено более одного результата.',
no_results = 'Результаты не найдены.',
no_table = 'Не указана таблица',
}
}
--- Проверка полученных строк.
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
--- Очистка существующих переменных, которые могут мешать новым.
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
--- Запись значений строк в соответствующие переменные.
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_'
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)
local rows = iccupdb.iccupdb(table, {
query = fields,
conditions = args.where,
group = args['group by'],
order = args['order by'],
limit = 1,
})
if validate(rows, args.failquiet) then
write_variables(prefix, rows[1])
end
end
return p