You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
3.1 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ITD Transport Tracking - проверка за достъп до база данни.
Ако липсват таблиците ITD_Cards и ITD_Cycles, изпълнява schema.sql.
"""
import os
import sys
from itd_db import load_connection_string
try:
import pyodbc
except ImportError:
pyodbc = None
def check_tables(cursor):
"""Проверява дали съществуват таблиците ITD_Cards и ITD_Cycles."""
cursor.execute("""
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME IN ('ITD_Cards', 'ITD_Cycles')
""")
found = {row[0] for row in cursor.fetchall()}
return "ITD_Cards" in found, "ITD_Cycles" in found
def run_schema(cursor, schema_path):
"""Изпълнява schema.sql (батчове разделени с GO)."""
with open(schema_path, "r", encoding="utf-8") as f:
content = f.read()
content = content.replace("\r\n", "\n")
# Разделяме по редове съдържащи само GO
batches = []
current = []
for line in content.split("\n"):
if line.strip().upper() == "GO":
batch = "\n".join(current).strip()
if batch and not all(l.strip().startswith("--") or not l.strip() for l in current):
batches.append(batch)
current = []
else:
current.append(line)
if current:
batch = "\n".join(current).strip()
if batch:
batches.append(batch)
for batch in batches:
try:
cursor.execute(batch)
except pyodbc.Error as e:
print(f"Грешка при изпълнение на батч: {e}", file=sys.stderr)
raise
def main():
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
print("ITD: проверка за достъп до база данни...")
try:
conn_str = load_connection_string()
except Exception as e:
print(f"Грешка при зареждане на настройките: {e}", file=sys.stderr)
return 1
if pyodbc is None:
print("Грешка: инсталирайте pyodbc (pip install pyodbc)", file=sys.stderr)
return 1
try:
conn = pyodbc.connect(conn_str, autocommit=True)
except Exception as e:
print(f"Грешка при свързване към SQL Server: {e}", file=sys.stderr)
return 1
try:
cursor = conn.cursor()
schema_path = os.path.join(script_dir, "schema.sql")
if os.path.isfile(schema_path):
run_schema(cursor, schema_path)
has_cards, has_cycles = check_tables(cursor)
if has_cards and has_cycles:
print("Достъп до база данни: OK. Таблиците ITD_Cards и ITD_Cycles съществуват.")
return 0
print("Внимание: след изпълнение на schema.sql липсват таблици.", file=sys.stderr)
return 1
finally:
conn.close()
if __name__ == "__main__":
sys.exit(main())