# Copyright (c) 2014, 2026, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is designed to work with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms,
# as designated in a particular file or component or in included license
# documentation. The authors of MySQL hereby grant you an
# additional permission to link the program and your derivative works
# with the separately licensed software that they have either included with
# the program or referenced in the documentation.
#
# Without limiting anything contained in the foregoing, this file,
# which is part of MySQL Connector/Python, is also subject to the
# Universal FOSS Exception, version 1.0, a copy of which can be found at
# http://oss.oracle.com/licenses/universal-foss-exception.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License, version 2.0, for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# mypy: disable-error-code="attr-defined"
"""Implements parser to parse MySQL option files."""
import ast
import codecs
import io
import os
import re
from configparser import ConfigParser as SafeConfigParser, MissingSectionHeaderError
from typing import Any, Dict, List, Optional, Tuple, Union
from .constants import CNX_POOL_ARGS, DEFAULT_CONFIGURATION
DEFAULT_EXTENSIONS: Dict[str, Tuple[str, ...]] = {
"nt": ("ini", "cnf"),
"posix": ("cnf",),
}
def read_option_files(**config: Union[str, List[str]]) -> Dict[str, Any]:
"""
Read option files for connection parameters.
Checks if connection arguments contain option file arguments, and then
reads option files accordingly.
"""
if "option_files" in config:
try:
if isinstance(config["option_groups"], str):
config["option_groups"] = [config["option_groups"]]
groups = config["option_groups"]
del config["option_groups"]
except KeyError:
groups = ["client", "connector_python"]
if isinstance(config["option_files"], str):
config["option_files"] = [config["option_files"]]
option_parser = MySQLOptionsParser(
list(config["option_files"]), keep_dashes=False
)
del config["option_files"]
config_from_file: Dict[str, Any] = (
option_parser.get_groups_as_dict_with_priority(*groups)
)
config_options: Dict[str, Tuple[str, int, str]] = {}
for group in groups:
try:
for option, value in config_from_file[group].items():
value += (group,)
try:
if option == "socket":
option = "unix_socket"
option_parser.set(group, "unix_socket", value[0])
if option not in CNX_POOL_ARGS and option != "failover":
_ = DEFAULT_CONFIGURATION[option]
if (
option not in config_options
or config_options[option][1] <= value[1]
):
config_options[option] = value
except KeyError:
if group == "connector_python":
raise AttributeError(
f"Unsupported argument '{option}'"
) from None
except KeyError:
continue
for option, values in config_options.items():
value, _, section = values
if (
option not in config
and option_parser.has_section(section)
and option_parser.has_option(section, option)
):
if option in ("password", "passwd"): # keep the value as string
config[option] = str(value)
else:
try:
config[option] = ast.literal_eval(value)
except (ValueError, TypeError, SyntaxError):
config[option] = value
if "socket" in config:
config["unix_socket"] = config.pop("socket")
return config
class MySQLOptionsParser(SafeConfigParser):
"""This class implements methods to parse MySQL option files"""
def __init__(
self, files: Optional[Union[List[str], str]] = None, keep_dashes: bool = True
) -> None:
"""Initialize
If defaults is True, default option files are read first
Raises ValueError if defaults is set to True but defaults files
cannot be found.
"""
# Regular expression to allow options with no value(For Python v2.6)
self.optcre: re.Pattern = re.compile(
r"(?P