Spaces:
Runtime error
Runtime error
File size: 75,922 Bytes
68e9069 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 | # db_generator.py
import streamlit as st
import pandas as pd
import numpy as np
import sqlite3
import json
import io
import tempfile
import os
from pathlib import Path
from datetime import datetime
import re
from typing import Dict, List, Tuple, Optional, Any
# AGREGAR ESTE IMPORT
from metrics_dashboard import MetricsDashboard
# CREAR LA INSTANCIA
metrics_dashboard = MetricsDashboard()
# Configurar página
# st.set_page_config(
# page_title="Generador de BD",
# page_icon="🗃️",
# layout="wide"
# )
class ProfessionalDatabaseGenerator:
"""Generador profesional de bases de datos para producción"""
def __init__(self, df: pd.DataFrame):
self.df = self._clean_dataframe(df)
self.schema = {}
self.custom_types = {}
self.conversion_errors = {}
self.original_schema = {}
self.include_auto_id = True # Por defecto incluir ID automático
self.id_column_name = "id" # Nombre por defecto para la columna ID
def _clean_dataframe(self, df: pd.DataFrame) -> pd.DataFrame:
"""Limpia el DataFrame para evitar problemas de serialización"""
df_clean = df.copy()
for col in df_clean.columns:
if str(df_clean[col].dtype) == 'Int64':
df_clean[col] = df_clean[col].astype('object').fillna(0).astype('int64')
elif pd.api.types.is_bool_dtype(df_clean[col]):
df_clean[col] = df_clean[col].astype('int64')
elif pd.api.types.is_integer_dtype(df_clean[col]) and hasattr(df_clean[col].dtype, 'na_value'):
df_clean[col] = df_clean[col].astype('object').fillna(0).astype('int64')
df_clean[col] = df_clean[col].fillna('')
return df_clean
def set_auto_id_config(self, include_auto_id: bool, id_column_name: str = "id") -> None:
"""Configura si incluir ID automático y el nombre de la columna"""
self.include_auto_id = include_auto_id
self.id_column_name = id_column_name.strip() or "id"
# Si ya hay esquema analizado, actualizarlo
if self.schema:
self._update_schema_with_auto_id()
def _update_schema_with_auto_id(self) -> None:
"""Actualiza el esquema con la configuración de ID automático"""
if self.include_auto_id:
# Agregar columna ID al esquema si no existe
if self.id_column_name not in self.schema:
self.schema[self.id_column_name] = {
"original_type": "auto_generated",
"detected_type": "BIGINT",
"sqlite_type": "INTEGER PRIMARY KEY AUTOINCREMENT",
"mysql_type": "BIGINT AUTO_INCREMENT PRIMARY KEY",
"postgres_type": "BIGSERIAL PRIMARY KEY",
"unique_values": len(self.df),
"nullable": False,
"sample_values": list(range(1, min(4, len(self.df) + 1))),
"max_length": len(str(len(self.df))),
"conversion_confidence": "high",
"conversion_warnings": [],
"is_auto_id": True
}
else:
# Remover columna ID del esquema si existe
if self.id_column_name in self.schema and self.schema[self.id_column_name].get("is_auto_id", False):
del self.schema[self.id_column_name]
def _is_valid_numeric(self, series: pd.Series) -> Tuple[bool, float, List[str]]:
"""Valida si una serie puede ser convertida completamente a numérico"""
error_samples = []
try:
numeric_series = pd.to_numeric(series, errors='coerce')
failed_mask = (numeric_series.isna()) & (series.notna())
failed_conversions = failed_mask.sum()
if failed_conversions > 0:
error_samples = series[failed_mask].head(3).astype(str).tolist()
conversion_success_rate = 1 - (failed_conversions / len(series))
return conversion_success_rate > 0.95, conversion_success_rate, error_samples
except Exception as e:
return False, 0.0, [f"Error en validación: {str(e)}"]
def _is_valid_integer(self, series: pd.Series) -> Tuple[bool, float, List[str]]:
"""Valida si una serie puede ser convertida completamente a entero"""
error_samples = []
try:
is_numeric, success_rate, numeric_errors = self._is_valid_numeric(series)
if not is_numeric:
return False, success_rate, numeric_errors
numeric_series = pd.to_numeric(series, errors='coerce')
valid_numeric = numeric_series.dropna()
if len(valid_numeric) == 0:
return False, 0.0, ["No hay valores numéricos válidos"]
non_integer_mask = valid_numeric.apply(lambda x: not float(x).is_integer())
non_integer_count = non_integer_mask.sum()
if non_integer_count > 0:
original_non_integer = series[numeric_series.notna()][non_integer_mask]
error_samples = original_non_integer.head(3).astype(str).tolist()
all_integers = non_integer_count == 0
integer_success_rate = 1 - (non_integer_count / len(valid_numeric))
return all_integers, integer_success_rate, error_samples
except Exception as e:
return False, 0.0, [f"Error en validación entero: {str(e)}"]
def _validate_type_conversion(self, column_name: str, new_type: str) -> Tuple[bool, str, List[str]]:
"""Valida si una conversión de tipo es segura"""
# No validar conversión para columnas ID automáticas
if (self.include_auto_id and column_name == self.id_column_name and
self.schema.get(column_name, {}).get("is_auto_id", False)):
return True, "Columna ID automática", []
series = self.df[column_name]
error_samples = []
if any(text_type in new_type.upper() for text_type in ['VARCHAR', 'TEXT', 'CHAR']):
return True, "Conversión a texto siempre es segura", []
if any(num_type in new_type.upper() for num_type in ['INT', 'DECIMAL', 'REAL', 'NUMERIC']):
is_numeric, success_rate, errors = self._is_valid_numeric(series)
if not is_numeric:
error_msg = f"No se puede convertir '{column_name}' a {new_type}. {len(errors)} valores no numéricos encontrados."
return False, error_msg, errors
if any(int_type in new_type.upper() for int_type in ['INT', 'SMALLINT', 'BIGINT']):
is_integer, int_success, int_errors = self._is_valid_integer(series)
if not is_integer:
error_msg = f"No se puede convertir '{column_name}' a {new_type}. {len(int_errors)} valores no enteros encontrados."
return False, error_msg, int_errors
elif 'BOOL' in new_type.upper():
unique_values = series.astype(str).str.lower().unique()
boolean_values = ['true', 'false', '1', '0', 'si', 'no', 'yes', 'no', 'verdadero', 'falso', 'sí', '']
invalid_values = [val for val in unique_values if val not in boolean_values and pd.notna(val) and str(val).strip() != '']
if invalid_values:
error_msg = f"No se puede convertir '{column_name}' a BOOLEAN. Valores inválidos: {invalid_values[:3]}"
return False, error_msg, invalid_values[:3]
elif any(date_type in new_type.upper() for date_type in ['DATE', 'TIME', 'DATETIME']):
date_series = pd.to_datetime(series, errors='coerce')
failed_conversions = ((date_series.isna()) & (series.notna()) & (series.astype(str).str.strip() != '')).sum()
if failed_conversions > 0:
error_mask = (date_series.isna()) & (series.notna()) & (series.astype(str).str.strip() != '')
error_samples = series[error_mask].head(3).astype(str).tolist()
error_msg = f"No se puede convertir '{column_name}' a {new_type}. {failed_conversions} valores no son fechas válidas."
return False, error_msg, error_samples
return True, "Conversión válida", []
def analyze_schema(self) -> Dict:
"""Análisis profesional del esquema"""
schema = {}
# Si se incluye ID automático, agregarlo al esquema primero
if self.include_auto_id:
schema[self.id_column_name] = {
"original_type": "auto_generated",
"detected_type": "BIGINT",
"sqlite_type": "INTEGER PRIMARY KEY AUTOINCREMENT",
"mysql_type": "BIGINT AUTO_INCREMENT PRIMARY KEY",
"postgres_type": "BIGSERIAL PRIMARY KEY",
"unique_values": len(self.df),
"nullable": False,
"sample_values": list(range(1, min(4, len(self.df) + 1))),
"max_length": len(str(len(self.df))),
"conversion_confidence": "high",
"conversion_warnings": [],
"is_auto_id": True # Bandera para identificar columnas ID automáticas
}
for col in self.df.columns:
try:
col_series = self.df[col]
dtype = str(col_series.dtype)
unique_count = col_series.nunique()
nullable = col_series.isna().any()
sample_values = col_series.head(3).tolist()
detected_type = self._detect_sql_type(col_series, col)
schema[col] = {
"original_type": dtype,
"detected_type": detected_type,
"sqlite_type": detected_type,
"mysql_type": self._map_to_mysql_type(detected_type),
"postgres_type": self._map_to_postgres_type(detected_type),
"unique_values": unique_count,
"nullable": nullable,
"sample_values": sample_values,
"max_length": col_series.astype(str).str.len().max() if col_series.astype(str).str.len().max() > 0 else 1,
"conversion_confidence": self._get_conversion_confidence(col_series, detected_type),
"conversion_warnings": [],
"is_auto_id": False # No es ID automático
}
except Exception as e:
schema[col] = {
"original_type": "object",
"detected_type": "TEXT",
"sqlite_type": "TEXT",
"mysql_type": "TEXT",
"postgres_type": "TEXT",
"unique_values": 0,
"nullable": True,
"sample_values": [],
"max_length": 255,
"conversion_confidence": "low",
"conversion_warnings": [f"Error en análisis: {str(e)}"],
"is_auto_id": False
}
self.schema = schema
self.original_schema = schema.copy()
return schema
def _get_conversion_confidence(self, series: pd.Series, detected_type: str) -> str:
"""Obtiene la confianza de la conversión de tipo"""
if any(num_type in detected_type for num_type in ['INT', 'DECIMAL', 'REAL', 'SMALL', 'BIG']):
is_numeric, success_rate, _ = self._is_valid_numeric(series)
if success_rate > 0.98:
return "high"
elif success_rate > 0.90:
return "medium"
else:
return "low"
else:
return "high"
def update_column_type(self, column_name: str, new_type: str) -> Tuple[bool, str]:
"""Actualiza el tipo de una columna específica con validación"""
# No permitir modificar columnas ID automáticas
if (self.include_auto_id and column_name == self.id_column_name and
self.schema.get(column_name, {}).get("is_auto_id", False)):
return False, "No se puede modificar el tipo de una columna ID automática"
is_valid, message, error_samples = self._validate_type_conversion(column_name, new_type)
if not is_valid:
self.conversion_errors[column_name] = {
"message": message,
"samples": error_samples,
"requested_type": new_type
}
return False, message
if column_name in self.schema:
self.schema[column_name]["sqlite_type"] = new_type
self.schema[column_name]["mysql_type"] = self._map_to_mysql_type(new_type)
self.schema[column_name]["postgres_type"] = self._map_to_postgres_type(new_type)
self.schema[column_name]["conversion_warnings"] = []
self.custom_types[column_name] = new_type
if column_name in self.conversion_errors:
del self.conversion_errors[column_name]
return True, f"Tipo de {column_name} actualizado exitosamente a {new_type}"
def reset_column_type(self, column_name: str) -> bool:
"""Restablece el tipo de columna al valor original detectado"""
# No permitir restablecer columnas ID automáticas
if (self.include_auto_id and column_name == self.id_column_name and
self.schema.get(column_name, {}).get("is_auto_id", False)):
return False
if column_name in self.original_schema:
original_type = self.original_schema[column_name]["detected_type"]
self.schema[column_name]["sqlite_type"] = original_type
self.schema[column_name]["mysql_type"] = self._map_to_mysql_type(original_type)
self.schema[column_name]["postgres_type"] = self._map_to_postgres_type(original_type)
if column_name in self.custom_types:
del self.custom_types[column_name]
if column_name in self.conversion_errors:
del self.conversion_errors[column_name]
return True
return False
def reset_all_types(self) -> None:
"""Restablece todos los tipos a los valores originales detectados"""
self.custom_types = {}
self.conversion_errors = {}
for col_name in self.schema.keys():
# No restablecer columnas ID automáticas
if (col_name in self.original_schema and
not self.schema[col_name].get("is_auto_id", False)):
original_type = self.original_schema[col_name]["detected_type"]
self.schema[col_name]["sqlite_type"] = original_type
self.schema[col_name]["mysql_type"] = self._map_to_mysql_type(original_type)
self.schema[col_name]["postgres_type"] = self._map_to_postgres_type(original_type)
def _detect_sql_type(self, series: pd.Series, col_name: str) -> str:
"""Detecta el tipo SQL más apropiado con validación robusta"""
col_lower = col_name.lower()
if any(keyword in col_lower for keyword in ['id', 'dni', 'cedula', 'codigo']):
is_numeric, success_rate, _ = self._is_valid_numeric(series)
if is_numeric and success_rate > 0.98:
is_integer, int_success, _ = self._is_valid_integer(series)
if is_integer:
numeric_series = pd.to_numeric(series, errors='coerce')
max_val = numeric_series.max()
if max_val < 32768:
return "SMALLINT"
elif max_val < 2147483648:
return "INTEGER"
else:
return "BIGINT"
else:
return "DECIMAL(15,2)"
else:
max_len = series.astype(str).str.len().max()
if max_len <= 50:
return f"VARCHAR({int(max_len)})"
else:
return "VARCHAR(255)"
elif any(keyword in col_lower for keyword in ['fecha', 'date', 'time']):
return "DATETIME"
elif any(keyword in col_lower for keyword in ['monto', 'precio', 'saldo', 'valor', 'limite', 'credito', 'volumen']):
is_numeric, success_rate, _ = self._is_valid_numeric(series)
if is_numeric and success_rate > 0.95:
return "DECIMAL(15,2)"
else:
max_len = series.astype(str).str.len().max()
return f"VARCHAR({min(255, int(max_len))})"
elif any(keyword in col_lower for keyword in ['activo', 'estado', 'flag']):
unique_values = series.astype(str).str.lower().unique()
boolean_values = ['true', 'false', '1', '0', 'si', 'no', 'yes', 'no', 'verdadero', 'falso']
if all(str(val).lower() in boolean_values for val in unique_values if pd.notna(val)):
return "BOOLEAN"
else:
max_len = series.astype(str).str.len().max()
return f"VARCHAR({min(10, int(max_len))})"
elif any(keyword in col_lower for keyword in ['email', 'correo']):
return "VARCHAR(255)"
elif any(keyword in col_lower for keyword in ['telefono', 'phone', 'celular']):
return "VARCHAR(20)"
try:
is_numeric, success_rate, _ = self._is_valid_numeric(series)
if is_numeric and success_rate > 0.95:
is_integer, int_success, _ = self._is_valid_integer(series)
if is_integer and int_success > 0.98:
numeric_series = pd.to_numeric(series, errors='coerce')
max_val = numeric_series.max()
if max_val < 32768:
return "SMALLINT"
elif max_val < 2147483648:
return "INTEGER"
else:
return "BIGINT"
else:
return "DECIMAL(15,2)"
except Exception:
pass
dtype = str(series.dtype)
if 'int' in dtype:
is_numeric, success_rate, _ = self._is_valid_numeric(series)
if success_rate > 0.98:
return "INTEGER"
elif 'float' in dtype:
is_numeric, success_rate, _ = self._is_valid_numeric(series)
if success_rate > 0.98:
return "REAL"
elif 'bool' in dtype:
return "BOOLEAN"
elif 'date' in dtype or 'time' in dtype:
return "DATETIME"
max_len = series.astype(str).str.len().max()
if max_len <= 50:
return f"VARCHAR({int(max_len)})"
elif max_len <= 255:
return "VARCHAR(255)"
else:
return "TEXT"
def _map_to_mysql_type(self, sql_type: str) -> str:
"""Mapea a tipos MySQL"""
type_map = {
"INTEGER": "INT",
"SMALLINT": "SMALLINT",
"BIGINT": "BIGINT",
"REAL": "DOUBLE",
"DECIMAL(15,2)": "DECIMAL(15,2)",
"BOOLEAN": "TINYINT(1)",
"DATETIME": "DATETIME",
"TEXT": "TEXT",
"INTEGER PRIMARY KEY AUTOINCREMENT": "BIGINT AUTO_INCREMENT PRIMARY KEY"
}
if sql_type.startswith("VARCHAR"):
return sql_type
return type_map.get(sql_type, "TEXT")
def _map_to_postgres_type(self, sql_type: str) -> str:
"""Mapea a tipos PostgreSQL"""
type_map = {
"INTEGER": "INTEGER",
"SMALLINT": "SMALLINT",
"BIGINT": "BIGINT",
"REAL": "DOUBLE PRECISION",
"DECIMAL(15,2)": "DECIMAL(15,2)",
"BOOLEAN": "BOOLEAN",
"DATETIME": "TIMESTAMP",
"TEXT": "TEXT",
"INTEGER PRIMARY KEY AUTOINCREMENT": "BIGSERIAL PRIMARY KEY"
}
if sql_type.startswith("VARCHAR"):
return sql_type
return type_map.get(sql_type, "TEXT")
def get_available_types(self, current_type: str, column_name: str = "") -> List[str]:
"""Devuelve tipos disponibles para una columna basado en su tipo actual y nombre"""
# No permitir cambiar tipos de columnas ID automáticas
if (self.include_auto_id and column_name == self.id_column_name and
self.schema.get(column_name, {}).get("is_auto_id", False)):
return [current_type] # Solo el tipo actual
all_types = [
"INTEGER", "BIGINT", "SMALLINT",
"DECIMAL(15,2)", "REAL",
"VARCHAR(50)", "VARCHAR(100)", "VARCHAR(255)", "TEXT",
"BOOLEAN", "DATETIME"
]
if any(num_type in current_type for num_type in ['INT', 'DECIMAL', 'REAL', 'SMALL', 'BIG']):
numeric_types = [t for t in all_types if any(num_type in t for num_type in ['INT', 'DECIMAL', 'REAL', 'SMALL', 'BIG'])]
text_options = ["VARCHAR(50)", "VARCHAR(100)", "VARCHAR(255)", "TEXT"]
return numeric_types + text_options
elif any(text_type in current_type for text_type in ['VARCHAR', 'TEXT', 'CHAR']):
text_types = [t for t in all_types if any(text_type in t for text_type in ['VARCHAR', 'TEXT', 'CHAR'])]
numeric_options = ["INTEGER", "BIGINT", "DECIMAL(15,2)", "REAL"]
return text_types + numeric_options
elif 'BOOL' in current_type.upper():
return all_types
else:
return all_types
def generate_sqlite_database(self, table_name: str) -> Tuple[bool, str]:
"""Genera base de datos SQLite profesional"""
try:
with tempfile.NamedTemporaryFile(delete=False, suffix='.db') as temp_file:
temp_path = temp_file.name
conn = sqlite3.connect(temp_path)
columns_sql = []
for col, info in self.schema.items():
# Para columnas ID automáticas, usar el tipo específico
if info.get("is_auto_id", False):
sql_type = "INTEGER PRIMARY KEY AUTOINCREMENT"
else:
sql_type = self.custom_types.get(col, info["sqlite_type"])
col_def = f'"{col}" {sql_type}'
columns_sql.append(col_def)
create_sql = f'CREATE TABLE "{table_name}" ({", ".join(columns_sql)})'
conn.execute(create_sql)
# CORREGIDO: Preparar placeholders e inserción de datos
data_columns = [col for col in self.schema.keys() if not self.schema[col].get("is_auto_id", False)]
placeholders = ', '.join(['?' for _ in data_columns])
# CORREGIDO: Usar formato correcto sin backslash en f-string
columns_str = ', '.join([f'"{col}"' for col in data_columns])
insert_sql = f'INSERT INTO "{table_name}" ({columns_str}) VALUES ({placeholders})'
data = []
for _, row in self.df.iterrows():
row_data = []
for col in data_columns:
val = row[col] if col in self.df.columns else None
sql_type = self.custom_types.get(col, self.schema[col]["sqlite_type"])
if pd.isna(val) or val is None or str(val).strip() == '':
row_data.append(None)
elif any(num_type in sql_type for num_type in ['INT', 'DECIMAL', 'REAL', 'SMALL', 'BIG']):
try:
numeric_val = pd.to_numeric(val, errors='coerce')
if pd.isna(numeric_val):
row_data.append(None)
else:
row_data.append(float(numeric_val))
except:
row_data.append(None)
elif 'BOOL' in sql_type:
str_val = str(val).lower().strip()
if str_val in ['true', '1', 'si', 'yes', 'verdadero', 'sí']:
row_data.append(1)
elif str_val in ['false', '0', 'no']:
row_data.append(0)
else:
row_data.append(None)
else:
row_data.append(str(val))
data.append(tuple(row_data))
conn.executemany(insert_sql, data)
conn.commit()
conn.close()
return True, temp_path
except Exception as e:
return False, f"Error generando SQLite: {str(e)}"
def generate_sql_script(self, table_name: str, db_type: str = "sqlite") -> str:
"""Genera script SQL completo y optimizado"""
try:
total_columns = len([col for col in self.schema.keys() if not self.schema[col].get("is_auto_id", False)])
script = f"""-- =============================================
-- SCRIPT SQL GENERADO AUTOMÁTICAMENTE
-- Tabla: {table_name}
-- Filas: {len(self.df):,}
-- Columnas: {total_columns} {'+ ID automático' if self.include_auto_id else ''}
-- Base de datos: {db_type.upper()}
-- Generado: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
-- =============================================
"""
if db_type == "sqlite":
columns = []
for col, info in self.schema.items():
if info.get("is_auto_id", False):
sql_type = "INTEGER PRIMARY KEY AUTOINCREMENT"
else:
sql_type = self.custom_types.get(col, info["sqlite_type"])
columns.append(f' "{col}" {sql_type}')
script += f'CREATE TABLE IF NOT EXISTS "{table_name}" (\n'
script += ',\n'.join(columns)
script += '\n);\n\n'
elif db_type == "mysql":
columns = []
for col, info in self.schema.items():
if info.get("is_auto_id", False):
sql_type = "BIGINT AUTO_INCREMENT PRIMARY KEY"
else:
sql_type = self.custom_types.get(col, info["mysql_type"])
columns.append(f' `{col}` {sql_type}')
script += f'CREATE TABLE IF NOT EXISTS `{table_name}` (\n'
script += ',\n'.join(columns)
script += '\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\n\n'
elif db_type == "postgresql":
columns = []
for col, info in self.schema.items():
if info.get("is_auto_id", False):
sql_type = "BIGSERIAL PRIMARY KEY"
else:
sql_type = self.custom_types.get(col, info["postgres_type"])
columns.append(f' "{col}" {sql_type}')
script += f'CREATE TABLE IF NOT EXISTS "{table_name}" (\n'
script += ',\n'.join(columns)
script += '\n);\n\n'
script += "-- =============================================\n"
script += "-- DATOS\n"
script += "-- =============================================\n\n"
batch_size = 50
data_columns = [col for col in self.schema.keys() if not self.schema[col].get("is_auto_id", False)]
for i in range(0, len(self.df), batch_size):
batch = self.df.iloc[i:i + batch_size]
values_list = []
for _, row in batch.iterrows():
values = []
for col in data_columns:
val = row[col]
sql_type = self.custom_types.get(col, self.schema[col]["sqlite_type"])
if pd.isna(val) or val is None or str(val).strip() == '':
values.append("NULL")
elif any(num_type in sql_type for num_type in ['INT', 'DECIMAL', 'REAL', 'SMALL', 'BIG']):
try:
numeric_val = pd.to_numeric(val, errors='coerce')
if pd.isna(numeric_val):
values.append("NULL")
else:
values.append(str(numeric_val))
except:
values.append("NULL")
elif 'BOOL' in sql_type:
str_val = str(val).lower().strip()
if str_val in ['true', '1', 'si', 'yes', 'verdadero', 'sí']:
values.append("1")
elif str_val in ['false', '0', 'no']:
values.append("0")
else:
values.append("NULL")
else:
escaped_val = str(val).replace("'", "''")
values.append(f"'{escaped_val}'")
values_list.append(f"({', '.join(values)})")
if values_list:
if db_type == "mysql":
columns_str = "`, `".join(data_columns)
script += f"INSERT INTO `{table_name}` (`{columns_str}`) VALUES\n"
else:
columns_str = '", "'.join(data_columns)
script += f'INSERT INTO "{table_name}" ("{columns_str}") VALUES\n'
script += ",\n".join(values_list) + ";\n\n"
return script
except Exception as e:
return f"-- ERROR GENERANDO SCRIPT: {str(e)}"
def generate_mongodb_documents(self, collection_name: str, include_all: bool = True, limit: int = None) -> str:
"""Genera documentos JSON para MongoDB"""
try:
if include_all:
export_df = self.df
actual_limit = len(self.df)
else:
export_df = self.df.head(limit) if limit else self.df.head(10)
actual_limit = limit if limit else 10
documents = []
for idx, (_, row) in enumerate(export_df.iterrows()):
doc = {}
# Incluir ID automático si está configurado
if self.include_auto_id:
doc[self.id_column_name] = idx + 1
for col in export_df.columns:
val = row[col]
sql_type = self.custom_types.get(col, self.schema[col]["sqlite_type"])
if pd.isna(val) or val is None or str(val).strip() == '':
doc[col] = None
elif any(num_type in sql_type for num_type in ['INT', 'DECIMAL', 'REAL', 'SMALL', 'BIG']):
try:
numeric_val = pd.to_numeric(val, errors='coerce')
doc[col] = float(numeric_val) if not pd.isna(numeric_val) else None
except:
doc[col] = None
elif 'BOOL' in sql_type:
str_val = str(val).lower().strip()
if str_val in ['true', '1', 'si', 'yes', 'verdadero', 'sí']:
doc[col] = True
elif str_val in ['false', '0', 'no']:
doc[col] = False
else:
doc[col] = None
else:
doc[col] = str(val)
documents.append(doc)
result = {
"collection_name": collection_name,
"documents_count": len(documents),
"total_documents": len(self.df),
"included_all": include_all,
"limit_applied": actual_limit if not include_all else None,
"include_auto_id": self.include_auto_id,
"id_column_name": self.id_column_name if self.include_auto_id else None,
"schema_analysis": self.schema,
"documents": documents
}
return json.dumps(result, indent=2, ensure_ascii=False, default=str)
except Exception as e:
return json.dumps({"error": f"Error generando documentos: {str(e)}"})
def initialize_session_state():
"""Inicializa el session state correctamente"""
if 'db_initialized' not in st.session_state:
st.session_state.db_initialized = True
st.session_state.schema_analyzed = False
st.session_state.current_tab = "Esquema"
st.session_state.custom_types = {}
st.session_state.mongo_include_all = False
st.session_state.conversion_errors = {}
st.session_state.show_data_preview = True
st.session_state.show_schema_details = True
st.session_state.include_auto_id = True # Configuración de ID automático
st.session_state.id_column_name = "id" # Nombre de columna ID
def show_database_generator():
"""Interfaz principal del generador de BD"""
if st.session_state.get('global_df') is None:
st.error("🚫 No hay datos cargados en el sistema")
st.info("💡 Por favor, carga un archivo en la barra lateral principal")
return
df = st.session_state.global_df
filename = st.session_state.get('global_filename', 'datos')
# Header principal
st.title("🗃️ Generador Profesional de Bases de Datos")
st.markdown("---")
# Información del dataset
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("📊 Archivo", filename)
with col2:
st.metric("📈 Filas", f"{len(df):,}")
with col3:
st.metric("📋 Columnas", len(df.columns))
with col4:
st.metric("💾 Tamaño", f"{df.memory_usage(deep=True).sum() / 1024 / 1024:.1f} MB")
# Preview de datos
if st.session_state.get('show_data_preview', True):
with st.expander("👁️ **VISTA PREVIA DE DATOS - Primeras 10 filas**", expanded=True):
st.dataframe(df.head(10), use_container_width=True)
st.caption(f"Mostrando 10 de {len(df)} filas - Use la barra lateral para analizar el esquema")
st.markdown("---")
# Sidebar con configuración de ID automático
with st.sidebar:
st.header("⚙️ Configuración")
table_name = st.text_input(
"📝 Nombre de tabla/colección:",
value=re.sub(r'[^a-zA-Z0-9_]', '_', filename.lower().split('.')[0]),
help="Nombre válido para base de datos"
)
st.markdown("---")
st.subheader("🆔 Configuración de ID Automático")
include_auto_id = st.checkbox(
"Incluir campo ID automático",
value=st.session_state.include_auto_id,
help="Agrega un campo ID único auto-incremental a la tabla"
)
if include_auto_id:
id_column_name = st.text_input(
"Nombre del campo ID:",
value=st.session_state.id_column_name,
help="Nombre de la columna ID (por defecto: 'id')"
)
else:
id_column_name = "id"
st.markdown("---")
if st.button("🔍 ANALIZAR ESQUEMA",
type="primary",
use_container_width=True,
key="analyze_btn"):
with st.spinner("🔬 Analizando estructura de datos..."):
try:
st.session_state.generator = ProfessionalDatabaseGenerator(df)
# Configurar ID automático antes de analizar el esquema
st.session_state.generator.set_auto_id_config(include_auto_id, id_column_name)
st.session_state.schema = st.session_state.generator.analyze_schema()
st.session_state.schema_analyzed = True
st.session_state.table_name = table_name
st.session_state.conversion_errors = {}
st.session_state.include_auto_id = include_auto_id
st.session_state.id_column_name = id_column_name
st.success("✅ Esquema analizado correctamente!")
st.rerun()
except Exception as e:
st.error(f"❌ Error en análisis: {str(e)}")
# Estado del análisis
if st.session_state.get('schema_analyzed'):
st.success("✅ Esquema listo")
if st.session_state.generator.custom_types:
st.info(f"🎯 {len(st.session_state.generator.custom_types)} tipo(s) personalizado(s)")
if st.session_state.include_auto_id:
st.info(f"🆔 ID automático: {st.session_state.id_column_name}")
else:
st.warning("⏳ Esperando análisis")
st.info("""
**Para comenzar:**
1. Verifica los datos en el preview
2. Configura el nombre de tabla
3. Configura ID automático (opcional)
4. Haz clic en **ANALIZAR ESQUEMA**
""")
st.markdown("---")
st.info("💡 **Flujo recomendado:**\n1. Analizar esquema\n2. Personalizar tipos\n3. Generar base de datos")
# Tabs principales
if st.session_state.get('schema_analyzed', False):
tab1, tab2, tab3, tab4 = st.tabs([
"📊 Esquema & Tipos",
"🗃️ SQLite DB",
"📜 Scripts SQL",
"🔧 MongoDB"
])
with tab1:
show_schema_analysis()
with tab2:
show_sqlite_generation()
with tab3:
show_sql_scripts()
with tab4:
show_mongodb_section()
else:
# Solo mostrar cuando no hay análisis
st.info("""
## 🎯 ¿Qué puedes generar?
Esta herramienta te permite convertir tus datos en diferentes formatos de base de datos:
**📊 Esquema & Tipos**
- Análisis automático de la estructura de datos
- Detección inteligente de tipos de datos
- Personalización de tipos de columnas
- Opción de ID automático
- Recomendaciones de optimización
**🗃️ SQLite DB**
- Base de datos SQLite completa para descargar
- Archivo .db listo para usar
- Compatible con cualquier cliente SQLite
**📜 Scripts SQL**
- Scripts para MySQL, PostgreSQL y SQLite
- Incluye creación de tabla e inserción de datos
- Optimizado para entornos de producción
**🔧 MongoDB**
- Documentos JSON listos para MongoDB
- Configuración de muestras o datos completos
- Estructura optimizada para NoSQL
---
⚡ **Para comenzar:**
1. Verifica que tus datos se muestren correctamente arriba
2. Configura el nombre de tabla en el panel lateral
3. Decide si incluir ID automático
4. Haz clic en **ANALIZAR ESQUEMA**
""")
def show_schema_analysis():
"""Muestra análisis detallado del esquema"""
st.header("📊 Análisis Profesional del Esquema")
schema = st.session_state.schema
generator = st.session_state.generator
# Información de configuración de ID
if st.session_state.include_auto_id:
st.success(f"🆔 **ID Automático Configurado:** `{st.session_state.id_column_name}` - Se incluirá como clave primaria auto-incremental")
# Botones de control superiores
st.subheader("🎛️ Controles de Configuración")
control_col1, control_col2, control_col3, control_col4 = st.columns(4)
with control_col1:
if st.button("🔄 Restablecer Todo",
help="Volver a todos los tipos detectados automáticamente",
use_container_width=True):
generator.reset_all_types()
st.success("✅ Todos los tipos han sido restablecidos a los valores detectados automáticamente")
st.rerun()
with control_col2:
if st.session_state.generator.custom_types:
st.metric("🎯 Personalizados", len(st.session_state.generator.custom_types))
else:
st.metric("🎯 Personalizados", 0)
with control_col3:
if st.session_state.get('show_data_preview', True):
if st.button("👁️ Ocultar Preview", use_container_width=True):
st.session_state.show_data_preview = False
st.rerun()
else:
if st.button("👁️ Mostrar Preview", use_container_width=True):
st.session_state.show_data_preview = True
st.rerun()
with control_col4:
if st.session_state.get('show_schema_details', True):
if st.button("📊 Ocultar Detalles", use_container_width=True):
st.session_state.show_schema_details = False
st.rerun()
else:
if st.button("📊 Mostrar Detalles", use_container_width=True):
st.session_state.show_schema_details = True
st.rerun()
st.markdown("---")
# Resumen del esquema
if st.session_state.get('show_schema_details', True):
st.subheader("📈 Resumen del Esquema")
# Métricas principales
auto_id_count = 1 if st.session_state.include_auto_id else 0
data_columns = len([col for col in schema.keys() if not schema[col].get("is_auto_id", False)])
col1, col2, col3, col4, col5 = st.columns(5)
with col1:
st.metric("🗂️ Columnas", f"{data_columns} + {auto_id_count}" if auto_id_count else data_columns)
with col2:
numeric_cols = sum(1 for info in schema.values() if any(t in info['sqlite_type'] for t in ['INT', 'REAL', 'DECIMAL']) and not info.get("is_auto_id", False))
st.metric("🔢 Numéricas", numeric_cols)
with col3:
text_cols = sum(1 for info in schema.values() if any(t in info['sqlite_type'] for t in ['TEXT', 'VARCHAR']) and not info.get("is_auto_id", False))
st.metric("📝 Texto", text_cols)
with col4:
nullable_cols = sum(1 for info in schema.values() if info['nullable'] and not info.get("is_auto_id", False))
st.metric("⚡ Nulables", nullable_cols)
with col5:
unique_cols = sum(1 for info in schema.values() if info['unique_values'] == len(st.session_state.generator.df) and not info.get("is_auto_id", False))
st.metric("🎯 Únicas", unique_cols)
# Distribución de tipos en tabla
type_counts = {}
for col_info in schema.values():
if col_info.get("is_auto_id", False):
continue # Excluir ID automático de la distribución
sql_type = col_info['sqlite_type']
base_type = sql_type.split('(')[0] if '(' in sql_type else sql_type
type_counts[base_type] = type_counts.get(base_type, 0) + 1
st.write("**Distribución de Tipos Detectados:**")
type_cols = st.columns(6)
type_items = list(type_counts.items())
for idx, (tipo, count) in enumerate(type_items):
with type_cols[idx % 6]:
st.metric(tipo, count)
st.markdown("---")
# Errores de conversión
if generator.conversion_errors:
st.error("🚫 Errores en Conversión de Tipos")
st.warning("Los siguientes errores deben resolverse antes de generar la base de datos:")
for col_name, error_info in generator.conversion_errors.items():
with st.expander(f"❌ Problema en columna: '{col_name}'", expanded=True):
col_err1, col_err2 = st.columns([2, 1])
with col_err1:
st.write(f"**Tipo solicitado:** `{error_info['requested_type']}`")
st.write(f"**Problema detectado:** {error_info['message']}")
if error_info['samples']:
st.write("**Valores problemáticos encontrados:**")
for sample in error_info['samples']:
st.code(f"• {sample}")
with col_err2:
st.write("**Solución rápida:**")
if st.button(f"🔧 Corregir '{col_name}'",
key=f"fix_error_{col_name}",
use_container_width=True):
if generator.reset_column_type(col_name):
st.success(f"✅ Columna '{col_name}' restablecida al tipo detectado")
st.rerun()
st.markdown("---")
# Personalización de tipos por columna
st.subheader("🎛️ Personalización de Tipos por Columna")
st.info("💡 **Instrucciones:** Para cada columna puedes seleccionar un tipo diferente. Las conversiones inválidas se mostrarán como errores arriba.")
# Filtro y búsqueda
search_col1, search_col2 = st.columns([2, 1])
with search_col1:
search_term = st.text_input("🔍 Buscar columna:", placeholder="Escribe para filtrar columnas...")
with search_col2:
filter_type = st.selectbox("Filtrar por tipo:",
["Todos"] + list(set([info['sqlite_type'].split('(')[0] for info in schema.values() if not info.get("is_auto_id", False)])))
# Aplicar filtros
filtered_columns = []
for col_name, col_info in schema.items():
# Excluir columnas ID automáticas de la personalización
if col_info.get("is_auto_id", False):
continue
if search_term and search_term.lower() not in col_name.lower():
continue
if filter_type != "Todos" and not col_info['sqlite_type'].startswith(filter_type):
continue
filtered_columns.append((col_name, col_info))
if not filtered_columns:
st.warning("ℹ️ No se encontraron columnas con los filtros aplicados.")
return
# Mostrar columnas filtradas
for col_name, col_info in filtered_columns:
# Determinar si es tipo personalizado
is_custom = col_name in generator.custom_types
custom_badge = " 🎯" if is_custom else ""
confidence_color = {
"high": "✅",
"medium": "⚠️",
"low": "🔴"
}.get(col_info['conversion_confidence'], "⚪")
with st.expander(f"{confidence_color} **{col_name}** - `{col_info['sqlite_type']}`{custom_badge}", expanded=False):
col_left, col_center, col_right = st.columns([2, 2, 3])
with col_left:
st.write("**📋 Información de la Columna**")
st.write(f"**Tipo detectado:** `{col_info['detected_type']}`")
st.write(f"**Valores únicos:** `{col_info['unique_values']}`")
st.write(f"**Permite nulos:** {'✅ Sí' if col_info['nullable'] else '❌ No'}")
st.write(f"**Longitud máxima:** `{col_info['max_length']}`")
st.write(f"**Confianza:** {confidence_color} {col_info['conversion_confidence'].upper()}")
# Botón para restablecer tipo individual
if is_custom:
st.write("---")
if st.button(f"↩️ Restablecer '{col_name}'",
key=f"reset_{col_name}",
use_container_width=True):
if generator.reset_column_type(col_name):
st.success(f"✅ '{col_name}' restablecida a `{col_info['detected_type']}`")
st.rerun()
with col_center:
st.write("**🗃️ Tipos por Base de Datos**")
st.write(f"**SQLite:** `{col_info['sqlite_type']}`")
st.write(f"**MySQL:** `{col_info['mysql_type']}`")
st.write(f"**PostgreSQL:** `{col_info['postgres_type']}`")
# Mostrar warnings si existen
if col_info.get('conversion_warnings'):
st.write("---")
st.warning("⚠️ Advertencias:")
for warning in col_info['conversion_warnings']:
st.write(f"• {warning}")
with col_right:
st.write("**⚙️ Personalizar Tipo**")
available_types = generator.get_available_types(col_info['sqlite_type'], col_name)
current_type = generator.custom_types.get(col_name, col_info['sqlite_type'])
# Asegurar que el tipo actual esté en la lista
if current_type not in available_types:
available_types.insert(0, current_type)
new_type = st.selectbox(
f"Seleccionar tipo para '{col_name}':",
options=available_types,
index=available_types.index(current_type) if current_type in available_types else 0,
key=f"type_select_{col_name}",
help="Selecciona un tipo diferente para personalizar esta columna"
)
# Mostrar acciones solo si hay cambio
if new_type != current_type:
st.write("**¿Aplicar cambio?**")
col_apply, col_cancel = st.columns(2)
with col_apply:
if st.button("✅ Sí, Aplicar",
key=f"apply_{col_name}",
type="primary",
use_container_width=True):
success, message = generator.update_column_type(col_name, new_type)
if success:
st.success(f"✅ {message}")
else:
st.error(f"❌ {message}")
st.rerun()
with col_cancel:
if st.button("❌ No, Cancelar",
key=f"cancel_{col_name}",
use_container_width=True):
st.info("🔄 Cambio cancelado - El tipo no se modificó")
st.rerun()
else:
st.info("💡 Selecciona un tipo diferente del desplegable para personalizar esta columna")
st.write("---")
st.write("**👀 Muestra de Valores**")
sample_values = col_info['sample_values'][:5] # Mostrar hasta 5 valores
sample_text = "`, `".join(map(str, sample_values))
if len(sample_text) > 100:
sample_text = sample_text[:100] + "..."
st.code(f"[{sample_text}]")
def show_sqlite_generation():
"""Interfaz para generación de SQLite"""
st.header("🗃️ Generador de Base de Datos SQLite")
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("📋 Configuración de la Base de Datos")
# Información básica
data_columns = len([col for col in st.session_state.schema.keys() if not st.session_state.schema[col].get("is_auto_id", False)])
auto_id_info = " + ID automático" if st.session_state.include_auto_id else ""
info_col1, info_col2, info_col3 = st.columns(3)
with info_col1:
st.metric("📝 Tabla", st.session_state.table_name)
with info_col2:
st.metric("📈 Filas", f"{len(st.session_state.generator.df):,}")
with info_col3:
st.metric("📊 Columnas", f"{data_columns}{auto_id_info}")
st.write("---")
# Información de ID automático
if st.session_state.include_auto_id:
st.success(f"🆔 **ID Automático Incluido:** `{st.session_state.id_column_name}` será la clave primaria auto-incremental")
# Tipos personalizados aplicados
if st.session_state.generator.custom_types:
st.subheader("🎛️ Tipos Personalizados Aplicados")
st.info("Se han aplicado los siguientes tipos personalizados:")
# Mostrar en columnas para mejor visualización
custom_cols = st.columns(2)
custom_items = list(st.session_state.generator.custom_types.items())
for idx, (col_name, custom_type) in enumerate(custom_items):
with custom_cols[idx % 2]:
original_type = st.session_state.schema[col_name]['detected_type']
st.write(f"**{col_name}**")
st.write(f"`{original_type}` → `{custom_type}`")
else:
st.info("ℹ️ No se han aplicado tipos personalizados. Se usarán los tipos detectados automáticamente.")
st.write("---")
# Validación previa a la generación
if st.session_state.generator.conversion_errors:
st.error("🚫 No se puede generar la base de datos")
st.warning("**Existen errores de conversión que deben resolverse:**")
for col_name in st.session_state.generator.conversion_errors.keys():
st.write(f"• **{col_name}**: {st.session_state.generator.conversion_errors[col_name]['message']}")
st.info("💡 **Solución:** Regresa a la pestaña '📊 Esquema & Tipos' y corrige los errores mostrados.")
return
# Información de validación exitosa
st.success("✅ **Validación exitosa** - Todos los tipos de datos son válidos y consistentes")
st.info("""
**📋 La base de datos incluirá:**
- Estructura de tabla optimizada
- Todos los datos convertidos correctamente
- Tipos de datos validados
- Archivo SQLite listo para usar
""" + (f"- Campo `{st.session_state.id_column_name}` como clave primaria auto-incremental" if st.session_state.include_auto_id else ""))
with col2:
st.subheader("🚀 Generación")
if st.button("🏗️ GENERAR SQLite DB",
type="primary",
use_container_width=True,
key="generate_sqlite_db",
help="Crear base de datos SQLite con la estructura definida"):
with st.spinner("🏗️ Construyendo base de datos SQLite..."):
success, result = st.session_state.generator.generate_sqlite_database(
st.session_state.table_name
)
if success:
st.success("🎉 ¡Base de datos creada exitosamente!")
# Leer archivo generado
with open(result, 'rb') as f:
db_data = f.read()
# Mostrar información del archivo
file_size = len(db_data) / 1024 / 1024
st.metric("📦 Tamaño del archivo", f"{file_size:.2f} MB")
# Vista previa de la estructura generada con scrolls COMPLETO
st.write("---")
st.subheader("👁️ Vista Previa de la Estructura")
# Generar script SQL para mostrar la estructura
sql_structure = st.session_state.generator.generate_sql_script(
st.session_state.table_name, "sqlite"
)
# Mostrar el script COMPLETO con scroll
structure_lines = sql_structure.split('\n')
# Usar el mismo diseño que MongoDB con altura fija y scroll para el contenido COMPLETO
with st.expander("📋 **ESQUEMA DE TABLA GENERADO - VISTA COMPLETA**", expanded=True):
st.code(sql_structure, language='sql', height=500) # Altura fija con scroll vertical para TODO el contenido
st.caption(f"📊 Script completo: {len(structure_lines)} líneas - Use el scroll para navegar")
# BOTÓN DE DESCARGA PARA SQLite - MÉTODO SIMPLE Y CORRECTO
def register_sqlite_metric():
"""Función para registrar métrica de SQLite"""
try:
file_size = len(db_data)
metrics_dashboard.record_download(
module_type="database",
file_type="db",
file_size=file_size
)
st.toast("✅ Descarga registrada en estadísticas", icon="📊")
except Exception as e:
st.error(f"Error registrando métrica: {e}")
# Botón de descarga que funciona
st.download_button(
label="💾 DESCARGAR SQLite DB",
data=db_data,
file_name=f"{st.session_state.table_name}.db",
mime="application/x-sqlite3",
use_container_width=True,
type="primary",
help="Descargar archivo .db listo para usar",
on_click=register_sqlite_metric # ¡ESTO ES CLAVE!
)
# Información de uso
st.info("""
**🔧 Compatible con:**
- SQLite Browser
- DBeaver
- Python sqlite3
- Cualquier cliente SQLite
**💡 Para usar en Python:**
```python
import sqlite3
conn = sqlite3.connect('tu_archivo.db')
```
""")
# Limpiar archivo temporal
try:
os.unlink(result)
except:
pass
else:
st.error(f"❌ Error en la generación: {result}")
st.info("💡 Verifica que los tipos de datos sean consistentes y vuelve a intentar.")
def show_sql_scripts():
"""Interfaz para generación de scripts SQL"""
st.header("📜 Generador de Scripts SQL")
# Selección de base de datos
st.subheader("🎯 Configuración del Motor de Base de Datos")
db_type = st.selectbox(
"Selecciona el tipo de base de datos:",
["mysql", "postgresql", "sqlite"],
format_func=lambda x: {
"mysql": "🐬 MySQL (Optimizado para producción)",
"postgresql": "🐘 PostgreSQL (Tipos nativos avanzados)",
"sqlite": "🔧 SQLite (Compatibilidad universal)"
}[x],
help="El script se generará con la sintaxis específica del motor seleccionado"
)
# Información específica del motor
db_info = {
"mysql": """
**✅ Características del script MySQL:**
- Motor InnoDB para transacciones ACID
- Charset UTF8mb4 para soporte Unicode completo
- Tipos de datos MySQL nativos
- Sintaxis MySQL optimizada
""" + ("- `" + st.session_state.id_column_name + "` como BIGINT AUTO_INCREMENT PRIMARY KEY" if st.session_state.include_auto_id else ""),
"postgresql": """
**✅ Características del script PostgreSQL:**
- Tipos de datos PostgreSQL nativos
- Soporte para arrays y JSON
- Sequences para auto-increment
- Sintaxis PostgreSQL estándar
""" + ("- `" + st.session_state.id_column_name + "` como BIGSERIAL PRIMARY KEY" if st.session_state.include_auto_id else ""),
"sqlite": """
**✅ Características del script SQLite:**
- Compatibilidad universal
- Tipos de datos SQLite
- Sintaxis simple y portable
- Ideal para desarrollo y testing
""" + ("- `" + st.session_state.id_column_name + "` como INTEGER PRIMARY KEY AUTOINCREMENT" if st.session_state.include_auto_id else "")
}
st.info(db_info[db_type])
# Botón de generación
if st.button(f"📝 GENERAR SCRIPT {db_type.upper()}",
type="primary",
use_container_width=True,
help=f"Generar script SQL compatible con {db_type.upper()}"):
with st.spinner(f"✍️ Generando script {db_type.upper()}..."):
script = st.session_state.generator.generate_sql_script(
st.session_state.table_name, db_type
)
st.session_state.current_script = script
st.session_state.current_script_type = db_type
st.success(f"✅ Script {db_type.upper()} generado exitosamente!")
# Mostrar script generado
if st.session_state.get('current_script'):
st.subheader(f"📄 Script {st.session_state.current_script_type.upper()} Generado")
# Estadísticas del script
lines = st.session_state.current_script.split('\n')
col_stat1, col_stat2, col_stat3 = st.columns(3)
with col_stat1:
st.metric("📊 Líneas de código", len(lines))
with col_stat2:
st.metric("🔤 Caracteres", f"{len(st.session_state.current_script):,}")
with col_stat3:
st.metric("⚡ Tipo", st.session_state.current_script_type.upper())
# Vista previa del script COMPLETO con altura fija y scroll
with st.expander("👁️ **VISTA PREVIA COMPLETA DEL SCRIPT**", expanded=True):
st.code(st.session_state.current_script, language='sql', height=800) # Altura fija con scroll para TODO el script
st.caption(f"📊 Mostrando script completo: {len(lines)} líneas - Use el scroll para navegar por todo el contenido")
# Opciones de descarga CON MÉTRICAS
st.subheader("💾 Opciones de Descarga")
download_col1, download_col2 = st.columns(2)
with download_col1:
# BOTÓN DE DESCARGA PARA SCRIPT COMPLETO - MÉTODO SIMPLE Y CORRECTO
def register_full_script_metric():
"""Función para registrar métrica de script completo"""
try:
file_size = len(st.session_state.current_script.encode('utf-8'))
metrics_dashboard.record_download(
module_type="database",
file_type="sql",
file_size=file_size
)
st.toast("✅ Descarga registrada en estadísticas", icon="📊")
except Exception as e:
st.error(f"Error registrando métrica: {e}")
st.download_button(
label="📦 DESCARGAR SCRIPT COMPLETO",
data=st.session_state.current_script,
file_name=f"{st.session_state.table_name}_{st.session_state.current_script_type}.sql",
mime="text/plain",
use_container_width=True,
help="Descargar script completo con estructura y datos",
on_click=register_full_script_metric # ¡ESTO ES CLAVE!
)
with download_col2:
# Extraer solo el esquema (sin datos)
schema_lines = [line for line in lines if "INSERT" not in line and "DATOS" not in line and "VALUES" not in line]
schema_only = "\n".join(schema_lines)
# BOTÓN DE DESCARGA PARA SOLO ESQUEMA - MÉTODO SIMPLE Y CORRECTO
def register_schema_metric():
"""Función para registrar métrica de solo esquema"""
try:
file_size = len(schema_only.encode('utf-8'))
metrics_dashboard.record_download(
module_type="database",
file_type="sql",
file_size=file_size
)
st.toast("✅ Descarga registrada en estadísticas", icon="📊")
except Exception as e:
st.error(f"Error registrando métrica: {e}")
st.download_button(
label="📋 SOLO ESQUEMA (Sin datos)",
data=schema_only,
file_name=f"{st.session_state.table_name}_schema_only.sql",
mime="text/plain",
use_container_width=True,
help="Descargar solo la estructura de la tabla sin datos",
on_click=register_schema_metric # ¡ESTO ES CLAVE!
)
# Información de uso
st.info(f"""
**🚀 Para ejecutar el script en {st.session_state.current_script_type.upper()}:**
**MySQL:**
```bash
mysql -u usuario -p base_datos < {st.session_state.table_name}_mysql.sql
```
**PostgreSQL:**
```bash
psql -U usuario -d base_datos -f {st.session_state.table_name}_postgresql.sql
```
**SQLite:**
```bash
sqlite3 base_datos.db < {st.session_state.table_name}_sqlite.sql
```
""")
def show_mongodb_section():
"""Interfaz para MongoDB"""
st.header("🔧 Generador de Documentos MongoDB")
col1, col2 = st.columns(2)
with col1:
st.subheader("⚙️ Configuración de Documentos")
# Información de ID automático
if st.session_state.include_auto_id:
st.success(f"🆔 **ID Automático Incluido:** Los documentos incluirán `{st.session_state.id_column_name}` como campo único")
# Selección de alcance
mongo_option = st.radio(
"📊 Selecciona el alcance de los documentos:",
["Todos los documentos", "Solo muestra representativa"],
index=1,
help="Generar todos los documentos o solo una muestra para testing"
)
include_all = (mongo_option == "Todos los documentos")
# Configuración de límite si es muestra
if not include_all:
st.write("**🔢 Configuración de la Muestra**")
limit = st.slider(
"Número de documentos de muestra:",
min_value=1,
max_value=min(100, len(st.session_state.generator.df)),
value=10,
help="Selecciona cuántos documentos incluir en la muestra"
)
st.info(f"📊 Se generará una muestra de **{limit} documentos** de {len(st.session_state.generator.df):,} totales")
else:
limit = None
st.info(f"📊 Se generarán **{len(st.session_state.generator.df):,} documentos** (todos los datos)")
# Información de la colección
st.write("---")
st.write("**📁 Información de la Colección**")
st.write(f"**Nombre de colección:** `{st.session_state.table_name}`")
st.write(f"**Documentos totales:** {len(st.session_state.generator.df):,}")
st.write(f"**Campos por documento:** {len(st.session_state.generator.df.columns)}" + (" + ID" if st.session_state.include_auto_id else ""))
# Botón de generación
if st.button("📄 GENERAR DOCUMENTOS JSON",
type="primary",
use_container_width=True,
help="Generar documentos JSON listos para MongoDB"):
with st.spinner("🔄 Generando documentos MongoDB..."):
documents = st.session_state.generator.generate_mongodb_documents(
st.session_state.table_name, include_all, limit
)
st.session_state.mongo_documents = documents
st.session_state.mongo_include_all = include_all
st.success(f"✅ Documentos generados exitosamente! ({'Todos los documentos' if include_all else f'Muestra de {limit} documentos'})")
with col2:
if st.session_state.get('mongo_documents'):
st.subheader("📦 Documentos Generados")
try:
doc_info = json.loads(st.session_state.mongo_documents)
if "error" not in doc_info:
# Estadísticas
stat_col1, stat_col2 = st.columns(2)
with stat_col1:
st.metric("📄 Total Documentos", f"{doc_info.get('total_documents', 0):,}")
st.metric("🔧 Incluye Todos", "✅" if doc_info.get('included_all', False) else "❌")
with stat_col2:
st.metric("📊 Generados", f"{doc_info.get('documents_count', 0):,}")
if doc_info.get('limit_applied'):
st.metric("🎯 Límite Aplicado", doc_info.get('limit_applied'))
# Información de ID automático
if doc_info.get('include_auto_id'):
st.success(f"🆔 **ID Automático:** Campo `{doc_info.get('id_column_name')}` incluido en cada documento")
# Vista previa del JSON COMPLETO con altura limitada y scroll
with st.expander("👁️ **VISTA PREVIA DEL DOCUMENTO JSON - COMPLETA**", expanded=True):
# Mostrar el JSON COMPLETO con scroll
st.code(st.session_state.mongo_documents, language='json', height=500) # Altura fija con scroll para TODO el contenido
st.caption(f"📊 Documento JSON completo - Use el scroll para navegar por todo el contenido")
# BOTÓN DE DESCARGA PARA MONGODB - MÉTODO SIMPLE Y CORRECTO
def register_mongodb_metric():
"""Función para registrar métrica de MongoDB"""
try:
file_size = len(st.session_state.mongo_documents.encode('utf-8'))
metrics_dashboard.record_download(
module_type="database",
file_type="json",
file_size=file_size
)
st.toast("✅ Descarga registrada en estadísticas", icon="📊")
except Exception as e:
st.error(f"Error registrando métrica: {e}")
st.download_button(
label="💾 DESCARGAR DOCUMENTOS JSON",
data=st.session_state.mongo_documents,
file_name=f"{st.session_state.table_name}_mongodb.json",
mime="application/json",
use_container_width=True,
type="primary",
on_click=register_mongodb_metric # ¡ESTO ES CLAVE!
)
# Información de importación
st.info("""
**📋 Para importar en MongoDB:**
```bash
# Importar usando mongoimport
mongoimport --db nombre_base_datos \\
--collection {st.session_state.table_name} \\
--file {st.session_state.table_name}_mongodb.json \\
--jsonArray
# O desde MongoDB Shell
use nombre_base_datos
db.{st.session_state.table_name}.insertMany({st.session_state.mongo_documents})
```
**🔧 Características del export:**
- Tipos de datos convertidos apropiadamente
- Estructura optimizada para MongoDB
- Metadatos del esquema incluidos
""" + ("- Campo `" + st.session_state.id_column_name + "` único en cada documento" if st.session_state.include_auto_id else "- `_id` automático de MongoDB"))
else:
st.error(f"❌ Error en la generación: {doc_info['error']}")
except Exception as e:
st.error(f"❌ Error procesando documentos: {str(e)}")
else:
st.info("""
**🔧 Generador de Documentos MongoDB**
Esta herramienta convierte tus datos tabulares en documentos JSON optimizados para MongoDB.
**📋 Características:**
- Conversión automática de tipos de datos
- Generación de campos únicos
- Opción de muestra o datos completos
- Estructura JSON lista para importar
""" + ("- Campo ID automático incluido" if st.session_state.include_auto_id else "- `_id` automático de MongoDB") + """
**🚀 Para comenzar:**
1. Configura el alcance (todos o muestra)
2. Ajusta el tamaño de muestra si es necesario
3. Haz clic en **GENERAR DOCUMENTOS JSON**
4. Descarga y importa en MongoDB
""")
def show():
"""Función principal"""
initialize_session_state()
show_database_generator()
if __name__ == "__main__":
show()
|