"""Miscellaneous helper functions for mysql queries."""## (C) Pywikibot team, 2016-2022## Distributed under the terms of the MIT license.#from__future__importannotationsimportpywikibotfrompywikibotimportconfigtry:importpymysqlexceptImportError:raiseImportError('MySQL python module not found. Please install PyMySQL.')
[docs]defmysql_query(query:str,params=None,dbname:str|None=None,verbose:bool|None=None):"""Yield rows from a MySQL query. An example query that yields all ns0 pages might look like:: SELECT page_namespace, page_title, FROM page WHERE page_namespace = 0; Supported MediaWiki projects use Unicode (UTF-8) character encoding. Cursor charset is utf8. :param query: MySQL query to execute :param params: input parameters for the query, if needed if list or tuple, %s shall be used as placeholder in the query string. if a dict, %(key)s shall be used as placeholder in the query string. :type params: tuple, list or dict of str :param dbname: db name :param verbose: if True, print query to be executed; if None, config.verbose_output will be used. :return: generator which yield tuples """# These are specified in config.py or your user config fileifverboseisNone:verbose=config.verbose_outputifconfig.db_connect_fileisNone:credentials={'user':config.db_username,'password':config.db_password}else:credentials={'read_default_file':config.db_connect_file}args={'host':config.db_hostname_format.format(dbname),'database':config.db_name_format.format(dbname),'port':config.db_port,'charset':'utf8','defer_connect':query=='test',# for tests}connection=pymysql.connect(**args,**credentials)withconnectionasconn,conn.cursor()ascursor:ifverbose:_query=cursor.mogrify(query,params)ifnotisinstance(_query,str):_query=str(_query,encoding='utf-8')_query=_query.strip()_query='\n'.join(f' {line}'forlinein_query.splitlines())pywikibot.info('Executing query:\n'+_query)ifquery=='test':# for tests onlyyieldquerycursor.execute(query,params)yield fromcursor