156 lines
6.0 KiB
Python
156 lines
6.0 KiB
Python
"""Ordered application settings in PostgreSQL; credentials stay in the environment."""
|
|
|
|
import configparser
|
|
import os
|
|
from contextlib import closing
|
|
|
|
import psycopg2
|
|
from psycopg2.extras import Json
|
|
|
|
|
|
HEADER = ["대분류 (Section)", "항목 (Key)", "설정값 1", "설정값 2", "설정값 3", "설정값 4", "설정값 5"]
|
|
|
|
|
|
def settings_db_config():
|
|
"""Share server credentials, but never fall back to the item-code database."""
|
|
return {
|
|
"host": os.getenv("POSTGRES_HOST", "postgres-db"),
|
|
"port": int(os.getenv("POSTGRES_PORT", "5432")),
|
|
"dbname": os.getenv("SETTINGS_DB", "corm_db").strip() or "corm_db",
|
|
"user": os.getenv("POSTGRES_USER", "king"),
|
|
"password": os.getenv("POSTGRES_PASSWORD", ""),
|
|
}
|
|
|
|
|
|
class SettingsNotInitialized(RuntimeError):
|
|
pass
|
|
|
|
|
|
class SettingsConflict(RuntimeError):
|
|
pass
|
|
|
|
|
|
class SettingsAlreadyInitialized(RuntimeError):
|
|
pass
|
|
|
|
|
|
def rows_to_config(rows):
|
|
config = configparser.ConfigParser(allow_no_value=True)
|
|
config.optionxform = str
|
|
for row in rows:
|
|
if not row or not row[0].strip():
|
|
continue
|
|
section = row[0].strip()
|
|
if section == HEADER[0]:
|
|
continue
|
|
key = row[1].strip() if len(row) > 1 else ""
|
|
cells = [cell.strip() for cell in row[2:]]
|
|
while cells and not cells[-1]:
|
|
cells.pop()
|
|
if not config.has_section(section):
|
|
config.add_section(section)
|
|
if key:
|
|
config.set(section, key, " | ".join(cells) or None)
|
|
return config
|
|
|
|
|
|
def config_to_rows(config):
|
|
rows = [HEADER.copy()]
|
|
for section in config.sections():
|
|
items = config.items(section)
|
|
if not items:
|
|
rows.append([section, "", ""])
|
|
for key, value in items:
|
|
rows.append([section, key] if value is None else
|
|
[section, key] + [part.strip() for part in value.split("|")])
|
|
return rows
|
|
|
|
|
|
def validate_rows(rows):
|
|
if not isinstance(rows, list) or not rows or not all(
|
|
isinstance(row, list) and all(isinstance(cell, str) and "\x00" not in cell for cell in row)
|
|
for row in rows
|
|
):
|
|
raise ValueError("설정은 문자열 셀로 구성된 비어 있지 않은 행 배열이어야 합니다.")
|
|
config = rows_to_config(rows)
|
|
if not config.sections():
|
|
raise ValueError("이전할 설정이 없습니다. 원본의 '설정' 탭을 확인해주세요.")
|
|
# Also validate interpolation before committing, as the existing API uses items().
|
|
config_to_rows(config)
|
|
return config
|
|
|
|
|
|
class PostgresSettingsStore:
|
|
def __init__(self, db_config):
|
|
self.db_config = dict(db_config)
|
|
|
|
def _connect(self):
|
|
return psycopg2.connect(
|
|
**self.db_config, connect_timeout=3,
|
|
options="-c statement_timeout=5000 -c lock_timeout=3000",
|
|
)
|
|
|
|
@staticmethod
|
|
def _create_table(cursor):
|
|
cursor.execute("""
|
|
CREATE TABLE IF NOT EXISTS corm_settings (
|
|
id SMALLINT PRIMARY KEY CHECK (id = 1),
|
|
rows JSONB NOT NULL CHECK (jsonb_typeof(rows) = 'array'),
|
|
version BIGINT NOT NULL DEFAULT 1 CHECK (version > 0),
|
|
source TEXT NOT NULL,
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
""")
|
|
|
|
def read(self):
|
|
with closing(self._connect()) as connection, connection:
|
|
with connection.cursor() as cursor:
|
|
try:
|
|
cursor.execute("SELECT rows, version FROM corm_settings WHERE id = 1")
|
|
except psycopg2.errors.UndefinedTable as exc:
|
|
raise SettingsNotInitialized("설정 DB가 없습니다. 먼저 settings_migrate.py로 이전해주세요.") from exc
|
|
record = cursor.fetchone()
|
|
if record is None:
|
|
raise SettingsNotInitialized("설정 DB가 비어 있습니다. 먼저 settings_migrate.py로 이전해주세요.")
|
|
validate_rows(record[0])
|
|
return record[0], record[1]
|
|
|
|
def write(self, rows, expected_version):
|
|
validate_rows(rows)
|
|
if not isinstance(expected_version, int) or expected_version < 1:
|
|
raise SettingsConflict("설정을 다시 읽은 후 저장해주세요.")
|
|
with closing(self._connect()) as connection, connection:
|
|
with connection.cursor() as cursor:
|
|
cursor.execute("""
|
|
UPDATE corm_settings
|
|
SET rows = %s, version = version + 1, updated_at = CURRENT_TIMESTAMP
|
|
WHERE id = 1 AND version = %s RETURNING version
|
|
""", (Json(rows, dumps=_json_dumps), expected_version))
|
|
record = cursor.fetchone()
|
|
if record is None:
|
|
raise SettingsConflict("다른 요청이 설정을 변경했습니다. 새로고침 후 다시 저장해주세요.")
|
|
return record[0]
|
|
|
|
def import_rows(self, rows, source):
|
|
"""Initialize once; DDL, insert and readback all share one transaction."""
|
|
validate_rows(rows)
|
|
with closing(self._connect()) as connection, connection:
|
|
with connection.cursor() as cursor:
|
|
self._create_table(cursor)
|
|
cursor.execute("""
|
|
INSERT INTO corm_settings (id, rows, source)
|
|
VALUES (1, %s, %s) ON CONFLICT (id) DO NOTHING RETURNING version
|
|
""", (Json(rows, dumps=_json_dumps), source))
|
|
record = cursor.fetchone()
|
|
if record is None:
|
|
raise SettingsAlreadyInitialized("이미 DB 설정이 있습니다. 기존 설정을 덮어쓰지 않았습니다.")
|
|
cursor.execute("SELECT rows FROM corm_settings WHERE id = 1")
|
|
if cursor.fetchone()[0] != rows:
|
|
raise RuntimeError("이전 후 설정 검증에 실패했습니다. 트랜잭션을 취소합니다.")
|
|
return record[0]
|
|
|
|
|
|
def _json_dumps(value):
|
|
import json
|
|
return json.dumps(value, ensure_ascii=False)
|