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.

63 lines
1.9 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.

import psycopg2
from const import DB_CONFIG
def add_product_to_shop(
name: str,
cost: str, # строка, например "100.00" или "50"
count: int,
reserved: int = 0, # по умолчанию 0
picture_url: str = "",
description: str = "",
type: str = ""
) -> int:
connection = psycopg2.connect(**DB_CONFIG)
cursor = connection.cursor()
try:
# Вставка с автоматической генерацией id и возвратом id
cursor.execute("""
INSERT INTO shop (name, cost, count, reserved, picture_url, description, type)
VALUES (%s, %s::NUMERIC, %s, %s, %s, %s, %s)
RETURNING id
""", (name, cost, count, reserved, picture_url, description, type))
product_id = cursor.fetchone()[0]
connection.commit()
return product_id
except psycopg2.Error as e:
print("Ошибка при работе с PostgreSQL:", e)
connection.rollback()
raise
except Exception as e:
print("Ошибка при добавлении товара:", e)
connection.rollback()
raise
finally:
cursor.close()
connection.close()
def delete_product_from_shop(product_id: int) -> bool:
connection = psycopg2.connect(**DB_CONFIG)
cursor = connection.cursor()
try:
# Удаляем товар по id
cursor.execute("DELETE FROM shop WHERE id = %s", (product_id,))
if cursor.rowcount == 0:
raise ValueError(f"Товар с id={product_id} не найден")
connection.commit()
return True
except psycopg2.Error as e:
print("Ошибка при работе с PostgreSQL:", e)
connection.rollback()
raise
except ValueError:
connection.rollback()
raise
finally:
cursor.close()
connection.close()