66 lines
1.8 KiB
Python
66 lines
1.8 KiB
Python
import os
|
|
import sqlite3
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# Adiciona o diretório raiz ao PYTHONPATH
|
|
root_dir = str(Path(__file__).parent.parent)
|
|
sys.path.append(root_dir)
|
|
|
|
from functions.base import Base, engine
|
|
from functions.database import init_database
|
|
from functions.rbac import init_rbac
|
|
|
|
def execute_sql_file(file_path):
|
|
"""Executa um arquivo SQL"""
|
|
print(f"Executando arquivo {file_path}...")
|
|
|
|
try:
|
|
with open(file_path, 'r') as sql_file:
|
|
sql_commands = sql_file.read().split(';')
|
|
|
|
conn = sqlite3.connect('database.db')
|
|
cursor = conn.cursor()
|
|
|
|
for command in sql_commands:
|
|
command = command.strip()
|
|
if command:
|
|
try:
|
|
cursor.execute(command)
|
|
except sqlite3.OperationalError as e:
|
|
if "already exists" in str(e):
|
|
print(f"Aviso: {str(e)}")
|
|
else:
|
|
raise e
|
|
|
|
conn.commit()
|
|
conn.close()
|
|
print(f"Arquivo {file_path} executado com sucesso!")
|
|
except Exception as e:
|
|
print(f"Erro ao executar {file_path}: {str(e)}")
|
|
raise e
|
|
|
|
def migrate_database():
|
|
"""Executa a migração do banco de dados"""
|
|
print("Inicializando banco de dados...")
|
|
|
|
# Criar todas as tabelas
|
|
Base.metadata.create_all(engine)
|
|
|
|
# Executar scripts SQL
|
|
sql_dir = Path(__file__).parent
|
|
rbac_tables_sql = sql_dir / 'rbac_tables.sql'
|
|
|
|
if rbac_tables_sql.exists():
|
|
execute_sql_file(rbac_tables_sql)
|
|
|
|
# Inicializar RBAC
|
|
init_rbac()
|
|
|
|
# Inicializar banco de dados
|
|
init_database()
|
|
|
|
print("Migração concluída com sucesso!")
|
|
|
|
if __name__ == '__main__':
|
|
migrate_database() |