-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
199 lines (172 loc) · 5.79 KB
/
server.py
File metadata and controls
199 lines (172 loc) · 5.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!/usr/bin/env python3
"""Local web server for PostgreSQL tree viewer with OID resolution."""
from __future__ import annotations
import json
import os
import shutil
import subprocess
from http import HTTPStatus
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
ROOT = Path(__file__).resolve().parent
QUERY_BY_KIND = {
"relid": """
SELECT c.oid::text,
quote_ident(n.nspname) || '.' || quote_ident(c.relname)
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.oid = ANY (ARRAY[{ids}]::oid[])
ORDER BY c.oid
""",
"nspid": """
SELECT n.oid::text,
quote_ident(n.nspname)
FROM pg_namespace n
WHERE n.oid = ANY (ARRAY[{ids}]::oid[])
ORDER BY n.oid
""",
"opno": """
SELECT o.oid::text,
quote_ident(n.nspname) || '.' || quote_ident(o.oprname) ||
'(' || pg_catalog.format_type(o.oprleft, NULL) || ',' ||
pg_catalog.format_type(o.oprright, NULL) || ')'
FROM pg_operator o
JOIN pg_namespace n ON n.oid = o.oprnamespace
WHERE o.oid = ANY (ARRAY[{ids}]::oid[])
ORDER BY o.oid
""",
"funcid": """
SELECT p.oid::text,
p.oid::regprocedure::text
FROM pg_proc p
WHERE p.oid = ANY (ARRAY[{ids}]::oid[])
ORDER BY p.oid
""",
"typeid": """
SELECT t.oid::text,
t.oid::regtype::text
FROM pg_type t
WHERE t.oid = ANY (ARRAY[{ids}]::oid[])
ORDER BY t.oid
""",
"collid": """
SELECT c.oid::text,
quote_ident(n.nspname) || '.' || quote_ident(c.collname)
FROM pg_collation c
JOIN pg_namespace n ON n.oid = c.collnamespace
WHERE c.oid = ANY (ARRAY[{ids}]::oid[])
ORDER BY c.oid
""",
}
def _int_list(raw):
out = []
for v in raw or []:
try:
iv = int(v)
except (TypeError, ValueError):
continue
if iv > 0:
out.append(iv)
return sorted(set(out))
def run_lookup(connection: dict, kind: str, oids: list[int]) -> dict[str, str]:
psql = shutil.which("psql")
if not psql:
raise RuntimeError("psql not found in PATH")
ids_sql = ",".join(str(x) for x in oids)
sql = QUERY_BY_KIND[kind].format(ids=ids_sql)
connection = dict(connection or {})
if not (connection.get("database") or "").strip():
connection["database"] = "postgres"
def run_with_env(conn: dict):
env = os.environ.copy()
conn_map = {
"host": "PGHOST",
"port": "PGPORT",
"database": "PGDATABASE",
"user": "PGUSER",
"password": "PGPASSWORD",
"application_name": "PGAPPNAME",
}
for src, dst in conn_map.items():
val = (conn or {}).get(src)
if val:
env[dst] = str(val)
else:
env.pop(dst, None)
return subprocess.run(
[
psql,
"-X",
"-A",
"-t",
"-F",
"\t",
"-v",
"ON_ERROR_STOP=1",
"-c",
sql,
],
cwd=ROOT,
env=env,
capture_output=True,
text=True,
check=False,
)
proc = run_with_env(connection)
if proc.returncode != 0:
stderr = (proc.stderr or "").strip()
raise RuntimeError(stderr or f"psql failed with exit code {proc.returncode}")
resolved = {}
for line in (proc.stdout or "").splitlines():
if not line.strip():
continue
parts = line.split("\t", 1)
if len(parts) != 2:
continue
oid, label = parts
resolved[oid.strip()] = " ".join(label.split())
return resolved
class Handler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(ROOT), **kwargs)
def do_POST(self):
if self.path != "/api/resolve":
self.send_error(HTTPStatus.NOT_FOUND, "Not found")
return
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
try:
payload = json.loads(body.decode("utf-8"))
except json.JSONDecodeError:
self._json(HTTPStatus.BAD_REQUEST, {"error": "Invalid JSON"})
return
connection = payload.get("connection") or {}
lookups = payload.get("lookups") or {}
resolved = {}
errors = []
try:
for kind, query in QUERY_BY_KIND.items():
oids = _int_list(lookups.get(kind))
if not oids:
continue
try:
resolved[kind] = run_lookup(connection, kind, oids)
except RuntimeError as exc:
errors.append(f"{kind}: {exc}")
except Exception as exc: # unexpected failure
self._json(HTTPStatus.INTERNAL_SERVER_ERROR, {"error": str(exc)})
return
self._json(HTTPStatus.OK, {"resolved": resolved, "errors": errors})
def _json(self, status: HTTPStatus, payload: dict):
raw = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
if __name__ == "__main__":
host = os.environ.get("PG_TREE_HOST", "127.0.0.1")
port = int(os.environ.get("PG_TREE_PORT", "8765"))
with ThreadingHTTPServer((host, port), Handler) as server:
print(f"Serving http://{host}:{port}")
server.serve_forever()