pgtoolkit.conf

This module implements postgresql.conf file format. This is the same format for recovery.conf. The main entry point of the API is parse(). The module can be used as a CLI script.

API Reference

pgtoolkit.conf.parse(fo: str | Path | IO[str]) Configuration[source]

Parse a configuration file.

The parser tries to return Python object corresponding to value, based on some heuristics. booleans, octal number, decimal integers and floating point numbers are parsed. Multiplier units like kB or MB are applyied and you get an int. Interval value like 3s are returned as datetime.timedelta.

In case of doubt, the value is kept as a string. It’s up to you to enforce format.

Include directives are processed recursively, when ‘fo’ is a file path (not a file object). If some included file is not found a FileNotFoundError exception is raised. If a loop is detected in include directives, a RuntimeError is raised.

Parameters:

fo – A line iterator such as a file-like object or a path.

Returns:

A Configuration containing parsed configuration.

pgtoolkit.conf.parse_string(string: str, source: str | None = None) Configuration[source]

Parse configuration data from a string.

Optional source argument can be used to set the context path of built Configuration.

class pgtoolkit.conf.Configuration(path: str | None = None)[source]

Holds a parsed configuration.

You can access parameter using attribute or dictionnary syntax.

>>> conf = parse(['port=5432\n', 'pg_stat_statement.min_duration = 3s\n'])
>>> conf.port
5432
>>> conf.port = 5433
>>> conf.port
5433
>>> conf['port'] = 5434
>>> conf.port
5434
>>> conf['pg_stat_statement.min_duration'].total_seconds()
3.0
>>> conf.get("ssl")
>>> conf.get("ssl", False)
False

Configuration instances can be merged:

>>> otherconf = parse(["listen_addresses='*'\n", "port = 5454\n"])
>>> sumconf = conf + otherconf
>>> print(json.dumps(sumconf.as_dict(), cls=JSONDateEncoder, indent=2))
{
  "port": 5454,
  "pg_stat_statement.min_duration": "3s",
  "listen_addresses": "*"
}

though, lines are discarded in the operation: >>> sumconf.lines []

>>> conf += otherconf
>>> print(json.dumps(conf.as_dict(), cls=JSONDateEncoder, indent=2))
{
  "port": 5454,
  "pg_stat_statement.min_duration": "3s",
  "listen_addresses": "*"
}
>>> conf.lines
[]
path

Path to a file. Automatically set when calling parse() with a path to a file. This is default target for save().

edit() Iterator[EntriesProxy][source]

Context manager allowing edition of the Configuration instance.

>>> import sys
>>> cfg = Configuration()
>>> includes = cfg.parse([
...     "#listen_addresses = 'localhost'  # what IP address(es) to listen on;\n",
...     "                                 # comma-separated list of addresses;\n",
...     "port = 5432                      # (change requires restart)\n",
...     "max_connections = 100            # (change requires restart)\n",
... ])
>>> list(includes)
[]
>>> cfg.save(sys.stdout)
#listen_addresses = 'localhost'  # what IP address(es) to listen on;
                                 # comma-separated list of addresses;
port = 5432                      # (change requires restart)
max_connections = 100            # (change requires restart)
>>> with cfg.edit() as entries:
...     entries["port"].value = 2345
...     entries["port"].comment = None
...     entries["listen_addresses"].value = '*'
...     del entries["max_connections"]
...     entries.add(
...         "unix_socket_directories",
...         "'/var/run/postgresql'",
...         comment="comma-separated list of directories",
...     )
>>> cfg.save(sys.stdout)
listen_addresses = '*'  # what IP address(es) to listen on;
                                 # comma-separated list of addresses;
port = 2345
unix_socket_directories = '/var/run/postgresql'  # comma-separated list of directories
save(fo: str | Path | IO[str] | None = None) None[source]

Write configuration to a file.

Configuration entries order and comments are preserved.

Parameters:

fo – A path or file-like object. Required if path is None.

Using as a CLI Script

You can use this module to dump a configuration file as JSON object

$ python -m pgtoolkit.conf postgresql.conf | jq .
{
  "lc_monetary": "fr_FR.UTF8",
  "datestyle": "iso, dmy",
  "log_rotation_age": "1d",
  "log_min_duration_statement": "3s",
  "log_lock_waits": true,
  "log_min_messages": "notice",
  "log_directory": "log",
  "port": 5432,
  "log_truncate_on_rotation": true,
  "log_rotation_size": 0
}
$