pdfgen/migration/main.py
2025-08-16 07:28:01 +00:00

129 lines
4.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import mysql.connector
import os
import sys
import config
import calendar
import time
import datetime
import list
conn = mysql.connector.connect(host=config.host,
port=config.port,
user=config.user,
password=config.password,
database=config.database)
# Создайте объект cursor для выполнения SQL-запросов
cursor = conn.cursor()
cursor.execute("SHOW TABLES LIKE 'migration';")
# Получите результаты запроса
if len(cursor.fetchall()) >= 1:
roleTableExistenceCheck = True
else:
roleTableExistenceCheck = False
if not roleTableExistenceCheck:
cursor.execute("""CREATE TABLE migration(
ID INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) CHARACTER SET utf8mb4,
datatime DATETIME );""")
print("Создали таблицу migration")
else:
print("migration уже существует")
# Закрыть соединение
conn.close()
#------------------------------------------
# Создаем пустой список
files = []
# Добавляем файлы в список
files += os.listdir(config.directory_sql)
def create():
print("Команда 'create'")
current_GMT = time.gmtime()
time_stamp = calendar.timegm(current_GMT)
filename = "sql/sql_{}.py".format(time_stamp)
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("sql = [] \n")
f.write("drop = [] \n")
filename_short = "sql_{}".format(time_stamp)
list_filename = "from sql import {} \n".format(filename_short)
with open('list.py', "a") as f:
f.write(list_filename)
def run():
try:
lastInjection = query("SELECT name FROM migration ORDER BY id DESC LIMIT 1;")
print(lastInjection)
for sm in sys.modules.keys():
if "sql.sql_" in sm:
smt = sm.replace("sql.", "")
# print(smt, lastInjection[0][0])
if len(lastInjection) < 1 or smt > lastInjection[0][0]:
try:
result = query(eval(f"list.{smt}.sql[0]"))
print(result)
except Exception as e:
print(f"Произошла ошибка в eval: {e}")
if result != "err":
#Создайте объект datetime
now = datetime.datetime.now()
# Преобразуйте его в строку в формате DATETIME
formatted_datetime = now.strftime('%Y-%m-%d %H:%M:%S')
query(f"""INSERT into migration (name, datatime) VALUES ('{smt}', '{formatted_datetime}');""")
except Exception as e:
print(f"Произошла ошибка: {e}")
def downgrade(arg):
print(f"Команда 'downgrade',c аргументом - '{arg}'")
reversTable = query(f"SELECT id FROM migration where name = '{arg}';")
for id in reversTable:
result = query(eval(f"list.{arg}.drop[0]"))
print(result)
if result != "err":
query(f"""delete from migration where id={id[0]};""")
def help():
print("migration.py create - Для создании новой миграции")
print("migration.py run - Для запуска миграций")
print("migration.py downgrade - Для отката миграций")
def query(sql):
try:
conn = mysql.connector.connect(host=config.host,
port=config.port,
user=config.user,
password=config.password,
database=config.database)
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()
conn.commit()
cursor.close()
conn.close()
except Exception as e:
result = 'err'
print(f"Произошла ошибка: {e}")
return result