118 lines
5.1 KiB
Python
118 lines
5.1 KiB
Python
# import psycopg2
|
|
# from psycopg2.extras import DictCursor
|
|
# import os
|
|
# from dotenv import load_dotenv
|
|
|
|
# load_dotenv()
|
|
|
|
# class Database:
|
|
# def __init__(self):
|
|
# self.connection_params = {
|
|
# 'dbname': os.getenv('DB_NAME', 'kpp_db'),
|
|
# 'user': os.getenv('DB_USER', 'postgres'),
|
|
# 'password': os.getenv('DB_PASSWORD', ''),
|
|
# 'host': os.getenv('DB_HOST', 'localhost'),
|
|
# 'port': os.getenv('DB_PORT', '5432')
|
|
# }
|
|
|
|
# def test_connection(self):
|
|
# """Проверка подключения к базе данных"""
|
|
# try:
|
|
# with self.get_connection() as conn:
|
|
# with conn.cursor() as cur:
|
|
# # Проверяем существование таблицы
|
|
# cur.execute("""
|
|
# SELECT EXISTS (
|
|
# SELECT FROM information_schema.tables
|
|
# WHERE table_name = 'license_plates'
|
|
# );
|
|
# """)
|
|
# table_exists = cur.fetchone()[0]
|
|
|
|
# # Проверяем количество записей
|
|
# if table_exists:
|
|
# cur.execute("SELECT COUNT(*) FROM license_plates;")
|
|
# record_count = cur.fetchone()[0]
|
|
# return True, f"Подключение успешно. Записей в базе: {record_count}"
|
|
# else:
|
|
# return True, "Подключение успешно. Таблица 'license_plates' не существует."
|
|
|
|
# except Exception as e:
|
|
# return False, f"Ошибка подключения: {str(e)}"
|
|
|
|
# def get_connection(self):
|
|
# return psycopg2.connect(**self.connection_params)
|
|
|
|
# def findCar(self, plate_number: str) -> bool:
|
|
# try:
|
|
# with self.get_connection() as conn:
|
|
# with conn.cursor(cursor_factory=DictCursor) as cur:
|
|
# cur.execute(
|
|
# "SELECT EXISTS(SELECT 1 FROM license_plates WHERE plate_number = %s AND is_active = true)",
|
|
# (plate_number,)
|
|
# )
|
|
# return cur.fetchone()[0]
|
|
# except Exception as e:
|
|
# print(f"Database error in findCar: {e}")
|
|
# return False
|
|
|
|
# def add_car(self, plate_number: str, owner_name: str = None) -> bool:
|
|
# try:
|
|
# with self.get_connection() as conn:
|
|
# with conn.cursor() as cur:
|
|
# cur.execute(
|
|
# """
|
|
# INSERT INTO license_plates (plate_number, owner_name, is_active)
|
|
# VALUES (%s, %s, true)
|
|
# ON CONFLICT (plate_number)
|
|
# DO UPDATE SET is_active = true, owner_name = EXCLUDED.owner_name
|
|
# """,
|
|
# (plate_number, owner_name)
|
|
# )
|
|
# conn.commit()
|
|
# return True
|
|
# except Exception as e:
|
|
# print(f"Database error in add_car: {e}")
|
|
# return False
|
|
|
|
# def remove_car(self, plate_number: str) -> bool:
|
|
# try:
|
|
# with self.get_connection() as conn:
|
|
# with conn.cursor() as cur:
|
|
# cur.execute(
|
|
# "UPDATE license_plates SET is_active = false WHERE plate_number = %s",
|
|
# (plate_number,)
|
|
# )
|
|
# conn.commit()
|
|
# return True
|
|
# except Exception as e:
|
|
# print(f"Database error in remove_car: {e}")
|
|
# return False
|
|
|
|
# def init_db(self):
|
|
# """Initialize database tables if they don't exist"""
|
|
# try:
|
|
# with self.get_connection() as conn:
|
|
# with conn.cursor() as cur:
|
|
# cur.execute("""
|
|
# CREATE TABLE IF NOT EXISTS license_plates (
|
|
# plate_number VARCHAR(20) PRIMARY KEY,
|
|
# owner_name VARCHAR(100),
|
|
# is_active BOOLEAN DEFAULT true,
|
|
# created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
# updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
# )
|
|
# """)
|
|
# conn.commit()
|
|
# print("База данных успешно инициализирована")
|
|
# except Exception as e:
|
|
# print(f"Ошибка инициализации базы данных: {e}")
|
|
|
|
# database = Database()
|
|
|
|
# # Проверяем подключение при импорте модуля
|
|
# success, message = database.test_connection()
|
|
# print(f"Проверка базы данных: {message}")
|
|
|
|
# if success:
|
|
# database.init_db() # Инициализируем таблицы только если подключение успешно |