-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
303 lines (260 loc) · 11.8 KB
/
Copy pathserver.py
File metadata and controls
303 lines (260 loc) · 11.8 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python
"""Database Diagram Studio - servidor local.
Uso:
python server.py (abre o navegador em http://127.0.0.1:8777)
python server.py --port 9000 --no-browser
"""
import argparse
import json
import mimetypes
import os
import socket
import sys
import tempfile
import threading
import traceback
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, unquote, urlparse
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
WEB_DIR = os.path.join(BASE_DIR, "web")
sys.path.insert(0, BASE_DIR)
from app import demo, model, typemap # noqa: E402
from app.generate import ddl as gen_ddl # noqa: E402
from app.generate import diff as gen_diff # noqa: E402
from app.generate import seed as gen_seed # noqa: E402
from app.introspect import access as ax # noqa: E402
from app.introspect import sqlserver as mssql # noqa: E402
MAX_UPLOAD = 512 * 1024 * 1024 # 512 MB
class Handler(BaseHTTPRequestHandler):
server_version = "DatabaseDiagramStudio/1.0"
protocol_version = "HTTP/1.1"
# ------------------------------------------------------------------
# infra
# ------------------------------------------------------------------
def log_message(self, fmt, *args):
if os.environ.get("DDS_VERBOSE"):
sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))
def _send(self, status, body: bytes, content_type="application/json; charset=utf-8",
extra=None):
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for k, v in (extra or {}).items():
self.send_header(k, v)
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def _json(self, data, status=200):
self._send(status, json.dumps(data, ensure_ascii=False, default=str).encode("utf-8"))
def _error(self, message, status=400, detail=None):
payload = {"ok": False, "error": str(message)}
if detail:
payload["detail"] = detail
self._json(payload, status)
def _read_body(self) -> bytes:
length = int(self.headers.get("Content-Length") or 0)
if length > MAX_UPLOAD:
raise ValueError("Arquivo maior que o limite de 512 MB.")
data, remaining = b"", length
while remaining > 0:
chunk = self.rfile.read(min(remaining, 1 << 20))
if not chunk:
break
data += chunk
remaining -= len(chunk)
return data
def _read_json(self) -> dict:
raw = self._read_body()
if not raw:
return {}
return json.loads(raw.decode("utf-8"))
# ------------------------------------------------------------------
# roteamento
# ------------------------------------------------------------------
def do_GET(self):
path = urlparse(self.path).path
try:
if path.startswith("/api/"):
return self._api_get(path)
return self._static(path)
except Exception as exc: # noqa: BLE001
traceback.print_exc()
return self._error(exc, 500)
def do_HEAD(self):
self.do_GET()
def do_POST(self):
path = urlparse(self.path).path
try:
return self._api_post(path)
except json.JSONDecodeError as exc:
return self._error(f"JSON invalido: {exc}", 400)
except Exception as exc: # noqa: BLE001
traceback.print_exc()
return self._error(exc, 500, detail=traceback.format_exc(limit=3))
# ------------------------------------------------------------------
# arquivos estaticos
# ------------------------------------------------------------------
def _static(self, path):
rel = "index.html" if path in ("/", "") else path.lstrip("/")
full = os.path.normpath(os.path.join(WEB_DIR, unquote(rel)))
if not full.startswith(WEB_DIR) or not os.path.isfile(full):
return self._send(404, b"Nao encontrado", "text/plain; charset=utf-8")
ctype = mimetypes.guess_type(full)[0] or "application/octet-stream"
if ctype.startswith("text/") or ctype in ("application/javascript", "application/json"):
ctype += "; charset=utf-8"
with open(full, "rb") as fh:
return self._send(200, fh.read(), ctype)
# ------------------------------------------------------------------
# API GET
# ------------------------------------------------------------------
def _api_get(self, path):
if path == "/api/env":
try:
import pyodbc
pyodbc_version = pyodbc.version
all_drivers = pyodbc.drivers()
except ImportError:
pyodbc_version, all_drivers = None, []
return self._json({
"ok": True,
"pyodbc": pyodbc_version,
"accessAvailable": ax.available(),
"sqlDrivers": mssql.drivers(),
"allDrivers": all_drivers,
"dialects": typemap.DIALECTS,
"baseTypes": typemap.BASE_TYPES,
"fkActions": model.FK_ACTIONS,
"colors": model.TABLE_COLORS,
"cwd": os.path.abspath(os.getcwd()),
})
if path == "/api/demo":
query = parse_qs(urlparse(self.path).query)
lang = (query.get("lang") or ["pt-BR"])[0]
return self._json({"ok": True, "schema": demo.build(lang)})
return self._error("Rota nao encontrada", 404)
# ------------------------------------------------------------------
# API POST
# ------------------------------------------------------------------
def _api_post(self, path):
# ---------- upload de arquivo Access ----------
if path == "/api/access/upload":
filename = unquote(self.headers.get("X-Filename") or "banco.accdb")
password = unquote(self.headers.get("X-DB-Password") or "") or None
data = self._read_body()
if not data:
return self._error("Arquivo vazio.")
ext = os.path.splitext(filename)[1].lower() or ".accdb"
if ext not in (".accdb", ".mdb"):
return self._error("Envie um arquivo .accdb ou .mdb.")
tmpdir = tempfile.mkdtemp(prefix="dds_")
tmp = os.path.join(tmpdir, os.path.basename(filename))
try:
with open(tmp, "wb") as fh:
fh.write(data)
schema = ax.read_schema(tmp, password)
schema["name"] = os.path.splitext(os.path.basename(filename))[0]
return self._json({"ok": True, "schema": schema})
except Exception as exc: # noqa: BLE001
return self._error(exc, 400)
finally:
try:
os.remove(tmp)
os.rmdir(tmpdir)
except OSError:
pass
body = self._read_json()
# ---------- Access por caminho local ----------
if path == "/api/access/schema":
file_path = (body.get("path") or "").strip().strip('"')
if not file_path:
return self._error("Informe o caminho do arquivo .accdb")
schema = ax.read_schema(file_path, body.get("password") or None,
bool(body.get("includeViews")))
return self._json({"ok": True, "schema": schema})
# ---------- SQL Server ----------
if path == "/api/sqlserver/parse":
return self._json({"ok": True,
"params": mssql.parse_connection_input(body.get("text", ""))})
if path == "/api/sqlserver/test":
return self._json(mssql.test_connection(body.get("params") or body))
if path == "/api/sqlserver/databases":
return self._json({"ok": True,
"databases": mssql.list_databases(body.get("params") or body)})
if path == "/api/sqlserver/schema":
params = body.get("params") or body
schema = mssql.read_schema(params, body.get("schemas"),
bool(body.get("includeSystem")))
return self._json({"ok": True, "schema": schema})
# ---------- geracao de SQL ----------
if path == "/api/generate/ddl":
sql = gen_ddl.generate(body.get("schema") or {}, body.get("dialect"),
body.get("options") or {})
return self._json({"ok": True, "sql": sql})
if path == "/api/generate/diff":
sql = gen_diff.generate(body.get("source") or {}, body.get("target") or {},
body.get("dialect"), body.get("options") or {})
return self._json({"ok": True, "sql": sql})
if path == "/api/generate/seed":
sql = gen_seed.generate(body.get("schema") or {}, body.get("dialect"),
body.get("options") or {})
return self._json({"ok": True, "sql": sql})
# ---------- utilitarios de modelo ----------
if path == "/api/layout":
schema = model.normalize(body.get("schema") or {})
model.auto_layout(schema,
spacing_x=int(body.get("spacingX") or 380),
spacing_y=int(body.get("spacingY") or 60))
return self._json({"ok": True, "schema": schema})
if path == "/api/normalize":
return self._json({"ok": True, "schema": model.normalize(body.get("schema") or {})})
if path == "/api/save":
target = (body.get("path") or "").strip()
if not target:
return self._error("Informe o caminho do arquivo de projeto.")
if not target.lower().endswith(".dbdiag.json"):
target += ".dbdiag.json"
with open(target, "w", encoding="utf-8") as fh:
json.dump(model.normalize(body.get("schema") or {}), fh,
ensure_ascii=False, indent=2)
return self._json({"ok": True, "path": os.path.abspath(target)})
return self._error("Rota nao encontrada", 404)
def _free_port(preferred: int) -> int:
for port in [preferred] + list(range(preferred + 1, preferred + 25)):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(("127.0.0.1", port)) != 0:
return port
return preferred
def main():
ap = argparse.ArgumentParser(description="Database Diagram Studio")
ap.add_argument("--port", type=int, default=8777)
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--no-browser", action="store_true")
args = ap.parse_args()
port = _free_port(args.port)
httpd = ThreadingHTTPServer((args.host, port), Handler)
url = f"http://{args.host}:{port}/"
print("=" * 60)
print(" Database Diagram Studio")
print("=" * 60)
print(f" Servidor: {url}")
try:
import pyodbc
print(f" pyodbc: {pyodbc.version}")
print(f" Access: {'disponivel' if ax.available() else 'driver nao encontrado'}")
print(f" SQL Server:{' ' + (mssql.drivers() or ['nenhum driver'])[0]}")
except ImportError:
print(" pyodbc: NAO INSTALADO -> pip install pyodbc")
print("=" * 60)
print(" Ctrl+C para encerrar.")
print()
if not args.no_browser:
threading.Timer(0.6, lambda: webbrowser.open(url)).start()
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nEncerrando...")
httpd.shutdown()
if __name__ == "__main__":
main()