Открыть меню
Открыть персональное меню
Вы не представились системе
Your IP address will be publicly visible if you make any edits.

Модуль:VarQuery: различия между версиями

Материал из wiki.iccup.org
Новая страница: «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 = 'Не указана таблица', } } --- Провер...»
 
Нет описания правки
 
(не показаны 2 промежуточные версии этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
local iccupdb = mw.ext.iCCupDB
local cargo = mw.ext.cargo -- используем Cargo API
local getArgs = require('Module:Arguments').getArgs
local getArgs = require('Module:Arguments').getArgs
local split = require('Module:Split')
local Json = require('Module:Json')
local Json = require('Module:Json')
local Variables = require('Module:Variables')
local Variables = require('Module:Variables')
Строка 8: Строка 7:
local i18n = {
local i18n = {
error = {
error = {
multiple_results = 'Найдено более одного результата.',
multiple_results = 'More than one result.',
no_results = 'Результаты не найдены.',
no_results = 'No results found.',
no_table = 'Не указана таблица',
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 function validate(rows, surpress)
local errorMsg
local errorMsg
Строка 40: Строка 51:
end
end


--- Очистка существующих переменных, которые могут мешать новым.
--- Clear already existing variables that could interfere with the new ones.
local function clear_variables(prefix, fields)
local function clear_variables(prefix, fields)
for _, field in ipairs(split(fields, '%s*,%s*')) do
for _, field in ipairs(split(fields, '%s*,%s*')) do
Строка 50: Строка 61:
end
end


--- Запись значений строк в соответствующие переменные.
--- Write the row values to the corresponding variables.
local function write_variables(prefix, row)
local function write_variables(prefix, row)
for key, value in pairs(row) do
for key, value in pairs(row) do
Строка 65: Строка 76:


function p.main(frame)
function p.main(frame)
local args = getArgs(frame)
    local args = getArgs(frame)
local fields = args['field'] or args['fields'] or 'pagename'
    local fields = args['field'] or args['fields'] or 'pagename'
local prefix = args['prefix'] or 'cargo_'
    local prefix = args['prefix'] or 'cargo_'
if args.fromArgs then
   
clear_variables(prefix, fields)
    -- Логируем перед началом работы
write_variables(prefix, args)
    mw.log('Параметры:', args)
return
   
end
    if args.fromArgs then
local table = args['table'] or args['tables']
        clear_variables(prefix, fields)
assert(table, i18n.error.no_table)
        write_variables(prefix, args)
        return
    end
   
    local table = args['table'] or args['tables']
    assert(table, i18n.error.no_table)


clear_variables(prefix, fields)
    clear_variables(prefix, fields)
local rows = iccupdb.iccupdb(table, {
   
query = fields,
    -- Логируем перед запросом
conditions = args.where,
    mw.log('Запрос к Cargo:', table, fields)
group = args['group by'],
   
order = args['order by'],
    local rows = cargo.query(table, fields, {
limit = 1,
        where = args.where,
})
        groupBy = args['group by'],
if validate(rows, args.failquiet) then
        orderBy = args['order by'],
write_variables(prefix, rows[1])
        limit = 1,
end
        format = 'table'
    })
   
    -- Логируем результат запроса
    mw.log('Результат запроса:', rows)
   
    if validate(rows, args.failquiet) then
        write_variables(prefix, rows[1])
    end
end
end


return p
return p

Текущая версия от 14:14, 21 сентября 2024

Для документации этого модуля может быть создана страница Модуль: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