Module:VarQuery

From Dota 2 Wiki
Jump to: navigation, search

Documentation for Module:VarQuery Jump to code ↴ [ edit | purge ]

Reality Rift icon.png
▶️ Planeshift.
The documentation for this module can be found at Template:VarQuery.
You may be forwarded to another wiki language, in case a translation is not available.


Dependencies

local p = {}
local cargo = mw.ext.cargo
local getArgs = require( 'Module:Arguments' ).getArgs
local split = require( 'Module:Split' )
local vardefine = require( 'Module:Variables' ).vardefine
local varexists = require( 'Module:Variables' ).varexists

local i18n = {
  error = {
    multiple_results = 'More than one result.',
    no_results = 'No results found.',
    no_table = 'No table given',
  }
}

--- Validates the given rows.
local function validate( rows )
  local nrows = #rows
  if nrows ~= 1 then
    if nrows == 0 then
      error( i18n.error.no_results )
    else
      error( i18n.error.multiple_results )
    end
  end
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 varexists( var_key ) then
      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
    local var_key = prefix .. key
    vardefine( var_key, value )
  end
end


function p.main( frame )
  local args = getArgs( frame )
  local tables = args['table'] or args['tables']
  local fields = args['field'] or args['fields'] or '_pageName'
  local prefix = args['prefix'] or 'cargo_'

  assert( tables, i18n.error.no_table )

  clear_variables( prefix, fields )
  local rows = cargo.query( tables, fields, {
    where = args['where'],
    join = args['join on'],
    groupBy = args['group by'],
    having = args['having'],
    orderBy = args['order by'],
    limit = args['limit']
  } )
  validate( rows )
  write_variables( prefix, rows[1] )
end


return p