sidra-sql 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sidra_sql/config.py ADDED
@@ -0,0 +1,137 @@
1
+ import configparser
2
+ import logging
3
+ from logging import handlers
4
+ from pathlib import Path
5
+
6
+ import platformdirs
7
+ from rich.logging import RichHandler
8
+
9
+ APP_NAME = "sidra-sql"
10
+
11
+ GLOBAL_CONFIG_PATH = (
12
+ Path(platformdirs.user_config_dir("quantilica", appauthor=False))
13
+ / APP_NAME
14
+ / "config.ini"
15
+ )
16
+ _OLD_GLOBAL_CONFIG_PATH = (
17
+ Path(platformdirs.user_config_dir(APP_NAME, appauthor=False)) / "config.ini"
18
+ )
19
+ LOCAL_CONFIG_PATH = Path("config.ini")
20
+
21
+
22
+ _REQUIRED_KEYS = {
23
+ "database": [
24
+ "user",
25
+ "password",
26
+ "host",
27
+ "port",
28
+ "dbname",
29
+ "schema",
30
+ ],
31
+ "storage": ["data_dir"],
32
+ }
33
+
34
+ _SETUP_HINT = """\
35
+ No configuration found. Run the following commands to get started:
36
+
37
+ sidra-sql config set database.host <host>
38
+ sidra-sql config set database.port 5432
39
+ sidra-sql config set database.user <user>
40
+ sidra-sql config set database.password <password>
41
+ sidra-sql config set database.dbname <dbname>
42
+ sidra-sql config set database.schema <schema>
43
+ sidra-sql config set storage.data_dir <path>
44
+
45
+ Add --global to write to the user-level config \
46
+ (~/.config/quantilica/sidra-sql/config.ini).\
47
+ """
48
+
49
+
50
+ class ConfigError(Exception):
51
+ pass
52
+
53
+
54
+ class Config:
55
+ def __init__(self):
56
+ if not GLOBAL_CONFIG_PATH.exists() and _OLD_GLOBAL_CONFIG_PATH.exists():
57
+ import warnings
58
+
59
+ GLOBAL_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
60
+ GLOBAL_CONFIG_PATH.write_text(_OLD_GLOBAL_CONFIG_PATH.read_text())
61
+ warnings.warn(
62
+ f"Config migrated from {_OLD_GLOBAL_CONFIG_PATH} "
63
+ f"to {GLOBAL_CONFIG_PATH}",
64
+ stacklevel=2,
65
+ )
66
+
67
+ self.config = configparser.ConfigParser()
68
+ self.config.read([GLOBAL_CONFIG_PATH, LOCAL_CONFIG_PATH])
69
+
70
+ self._validate()
71
+
72
+ self.data_dir = Path(self.config["storage"]["data_dir"])
73
+
74
+ self.db_user = self.config["database"]["user"]
75
+ self.db_password = self.config["database"]["password"]
76
+ self.db_host = self.config["database"]["host"]
77
+ self.db_port = self.config["database"]["port"]
78
+
79
+ self.db_name = self.config["database"]["dbname"]
80
+ self.db_schema = self.config["database"]["schema"]
81
+
82
+ def _validate(self):
83
+ missing = []
84
+ for section, keys in _REQUIRED_KEYS.items():
85
+ for key in keys:
86
+ if not self.config.has_option(section, key):
87
+ missing.append(f"{section}.{key}")
88
+
89
+ if missing:
90
+ if len(missing) == sum(len(v) for v in _REQUIRED_KEYS.values()):
91
+ raise ConfigError(_SETUP_HINT)
92
+ lines = "\n".join(f" sidra-sql config set {k} <value>" for k in missing)
93
+ raise ConfigError(f"Missing configuration keys:\n\n{lines}")
94
+
95
+ def __str__(self):
96
+ return (
97
+ f"db_user: {self.db_user}\n"
98
+ f"db_password: {self.db_password}\n"
99
+ f"db_host: {self.db_host}\n"
100
+ f"db_port: {self.db_port}\n"
101
+ f"db_name: {self.db_name}\n"
102
+ f"db_schema: {self.db_schema}\n"
103
+ )
104
+
105
+
106
+ def setup_logging(logger_name: str, log_filepath: Path):
107
+ logger = logging.getLogger(logger_name)
108
+ logger.setLevel(logging.DEBUG)
109
+ logger.propagate = False
110
+
111
+ log_formatter = logging.Formatter(
112
+ fmt="%(asctime)s.%(msecs)03d %(levelname)s %(message)s",
113
+ datefmt="%Y-%m-%d %H:%M:%S",
114
+ )
115
+
116
+ # File log
117
+ filehandler = handlers.RotatingFileHandler(
118
+ filename=log_filepath,
119
+ mode="a",
120
+ maxBytes=50 * 2**20,
121
+ backupCount=100,
122
+ )
123
+ filehandler.setFormatter(log_formatter)
124
+ filehandler.setLevel(logging.INFO)
125
+ logger.addHandler(filehandler)
126
+
127
+ # Console log — only warnings and above; RichHandler integrates with Progress bars
128
+ richhandler = RichHandler(
129
+ show_time=False,
130
+ show_path=False,
131
+ rich_tracebacks=True,
132
+ )
133
+ richhandler.setFormatter(log_formatter)
134
+ richhandler.setLevel(logging.WARNING)
135
+ logger.addHandler(richhandler)
136
+
137
+ return logger