Overview
Thecrear_base_datos.py module automates the generation of complete SQL Server database scripts, including schema definitions (DDL) and data insertion statements. This approach ensures consistent database deployments and provides version control for database structures.
Core Functions
generar_sql_crear_bd()
Generates the complete DDL (Data Definition Language) script for creating the database and all tables. Returns: SQL script string containing database and table creation statements Generated SQL Structure:generar_sql_insertar_datos()
Generates INSERT statements for normalized tables by reading cleaned CSV files from thecleanData/ directory.
CSV Files Read:
ciudades.csvsegmentos.csvcanales.csvmonedas.csvclientes_normalizados.csvventas_normalizadas.csv
- Escapes single quotes in string values
- Removes line breaks and carriage returns
- Handles NULL values appropriately
- Uses UTF-8 encoding with BOM handling
generar_sql_insertar_raw()
Generates INSERT statements for raw tables by reading original CSV files directly from the root directory. CSV Files Read:clientes_prueba_mas_datos.csvventas_prueba_mas_datos.csv
- Preserves original data formats (strings for dates and numbers)
- Escapes special characters
- Handles missing values as NULL
- No data transformation applied
leer_csv(archivo)
Utility function that reads CSV files from thecleanData/ directory.
Parameters:
archivo: Filename relative to thecleanData/directory
- UTF-8-sig encoding to handle BOM
- Error handling for missing files
- Uses Python’s csv.DictReader for structured data access
generar_script_completo()
Orchestrates the entire script generation process by combining all SQL components in the correct order. Execution Order:- Database and table creation (DDL)
- Raw data insertion
- Normalized data insertion
guardar_script_sql()
Saves the complete SQL script to a file and displays execution instructions. Output File:crear_base_datos.sql
Console Output:
String Sanitization
All string values are sanitized before insertion to prevent SQL syntax errors: Transformations Applied:- Single quotes:
'→''(SQL escaping) - Line breaks:
\n→(space) - Carriage returns:
\r→(space)
Execution
Run the script generator:crear_base_datos.sql containing the complete database creation script ready for execution in SQL Server Management Studio.
Error Handling
- Missing CSV Files: Warnings displayed but script continues
- Reading Errors: Captured and written as SQL comments
- Encoding Issues: Handled via UTF-8-sig encoding
Next Steps
Table Structure
Explore the complete database schema
SQL Server Deployment
Deploy the database to SQL Server