-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.py
More file actions
1288 lines (1070 loc) · 49.8 KB
/
cli.py
File metadata and controls
1288 lines (1070 loc) · 49.8 KB
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
"""
CLI interface for excel-to-sql using Typer.
"""
from pathlib import Path
from typer import Typer, Option, Exit
from rich.console import Console
from rich.table import Table
import pandas as pd
import logging
from excel_to_sql.entities.project import Project
from excel_to_sql.entities.excel_file import ExcelFile
from excel_to_sql.entities.dataframe import DataFrame
from excel_to_sql.__version__ import __version__
from excel_to_sql.exceptions import (
ExcelToSqlError,
ExcelFileError,
ConfigurationError,
ValidationError,
DatabaseError,
)
app = Typer(
name="excel-to-sql",
help="Excel to SQL CLI - Import Excel files to SQL and export back",
no_args_is_help=True,
add_completion=False,
)
console = Console()
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────
# Command: INIT
# ──────────────────────────────────────────────────────────────
@app.command()
def init(
db_path: str = Option("data/excel-to-sql.db", "--db-path", help="Path to SQLite database"),
) -> None:
"""Initialize project structure and database."""
console.print("[bold cyan]Initializing excel-to-sql project...[/bold cyan]")
project = Project()
project.initialize()
console.print("[green]OK[/green] Project initialized successfully")
console.print(f" Location: {project.root}")
console.print(f" Database: {project.database.path}")
console.print(f" Imports: {project.imports_dir}")
console.print(f" Exports: {project.exports_dir}")
# ──────────────────────────────────────────────────────────────
# Command: IMPORT
# ──────────────────────────────────────────────────────────────
@app.command("import")
def import_cmd(
excel_path: str = Option(..., "--file", "-f", help="Path to Excel file"),
type: str = Option(..., "--type", "-t", help="Type configuration from mappings"),
force: bool = Option(False, "--force", help="Re-import even if content unchanged"),
) -> None:
"""Import an Excel file into the database."""
import sys
import traceback
path = Path(excel_path)
try:
# 1. Validate file exists
if not path.exists():
console.print(f"[red]Error:[/red] File not found: {excel_path}")
raise Exit(1)
# 2. Validate file extension
if path.suffix.lower() not in {".xlsx", ".xls"}:
console.print(f"[red]Error:[/red] Not an Excel file: {excel_path}")
raise Exit(1)
# 3. Load project
try:
project = Project.from_current_directory()
except Exception:
console.print("[red]Error:[/red] Not an excel-to-sql project")
console.print(" Run 'excel-to-sql init' first")
raise Exit(1)
# 4. Validate type exists
if type not in project.mappings:
console.print(f"[red]Error:[/red] Unknown type: '{type}'")
available_types = ", ".join(project.list_types())
console.print(f" Available types: {available_types}")
raise Exit(1)
mapping = project.mappings[type]
# 5. Load Excel file
console.print(f"[bold cyan]Reading {excel_path}...[/bold cyan]")
excel_file = ExcelFile(path)
# Validate file is readable
if not excel_file.validate():
console.print("[red]Error:[/red] Invalid or corrupted Excel file")
raise Exit(1)
# Get content hash
content_hash = excel_file.content_hash
console.print(f" Content hash: {content_hash[:16]}...")
# 6. Check if already imported
if not force and project.database.is_imported(content_hash):
console.print("[yellow]Already imported[/yellow]")
console.print(" Use --force to re-import")
# Show previous import details
history = project.database.query(
"SELECT * FROM _import_history WHERE content_hash = :hash",
{"hash": content_hash}
)
if len(history) > 0:
record = history.iloc[0]
console.print(f" Imported: {record['imported_at']}")
console.print(f" Rows: {record['rows_imported']}")
raise Exit(0)
# 7. Read data
console.print("[dim]Loading data...[/dim]")
raw_df = excel_file.read()
initial_rows = len(raw_df)
console.print(f" Rows loaded: {initial_rows}")
# 8. Clean data
console.print("[dim]Cleaning data...[/dim]")
df_wrapper = DataFrame(raw_df)
df_wrapper.clean()
cleaned_rows = len(df_wrapper.to_pandas())
rows_removed = initial_rows - cleaned_rows
console.print(f" Rows removed (empty): {rows_removed}")
# 9. Apply mapping
console.print("[dim]Applying mappings...[/dim]")
df_wrapper.apply_mapping(mapping)
final_df = df_wrapper.to_pandas()
final_rows = len(final_df)
console.print(f" Columns: {len(final_df.columns)}")
console.print(f" Rows: {final_rows}")
# 10. Import to database
console.print("[dim]Importing to database...[/dim]")
table = project.database.get_table(mapping["target_table"])
stats = table.upsert(final_df, primary_key=mapping["primary_key"])
console.print(f" Inserted: {stats['inserted']}")
console.print(f" Updated: {stats['updated']}")
# 11. Record import in history
# If using --force and content_hash exists, delete old record first
if force and project.database.is_imported(content_hash):
project.database.execute(
"DELETE FROM _import_history WHERE content_hash = :hash",
{"hash": content_hash}
)
project.database.record_import(
file_name=excel_file.name,
file_path=str(path.absolute()),
content_hash=content_hash,
file_type=type,
rows_imported=stats["inserted"] + stats["updated"],
rows_skipped=0,
status="success",
)
# 12. Display summary
console.print()
console.print("[green]OK[/green] Import completed successfully")
summary_table = Table(show_header=True, title="Import Summary")
summary_table.add_column("Metric", style="cyan")
summary_table.add_column("Value", style="green")
summary_table.add_row("File", excel_file.name)
summary_table.add_row("Type", type)
summary_table.add_row("Table", mapping["target_table"])
summary_table.add_row("Rows inserted", str(stats["inserted"]))
summary_table.add_row("Rows updated", str(stats["updated"]))
summary_table.add_row("Total rows", str(final_rows))
summary_table.add_row("Content hash", content_hash[:16] + "...")
console.print(summary_table)
except FileNotFoundError:
console.print(f"[red]Error:[/red] File not found: {excel_path}")
console.print("[dim]Tip: Check the file path and try again[/dim]")
raise Exit(1)
except PermissionError:
console.print(f"[red]Error:[/red] Permission denied: {excel_path}")
console.print("[dim]Tip: Check file permissions or run with appropriate access[/dim]")
raise Exit(1)
except pd.errors.EmptyDataError:
console.print(f"[red]Error:[/red] Excel file is empty: {excel_path}")
console.print("[dim]Tip: Ensure the file contains data in the first sheet[/dim]")
raise Exit(1)
except pd.errors.ParserError as e:
console.print(f"[red]Error:[/red] Invalid Excel file format: {excel_path}")
console.print(f"[dim]Details: {e}[/dim]")
console.print("[dim]Tip: Ensure the file is a valid .xlsx or .xls file[/dim]")
raise Exit(1)
except ConfigurationError as e:
console.print(f"[red]Error:[/red] Configuration error: {e.message}")
if e.context:
console.print(f"[dim]Context: {e.context}[/dim]")
console.print("[dim]Tip: Check your configuration files or run 'excel-to-sql init'[/dim]")
raise Exit(1)
except ValidationError as e:
console.print(f"[red]Error:[/red] Validation error: {e.message}")
if e.context:
console.print(f"[dim]Details: {e.context}[/dim]")
raise Exit(1)
except DatabaseError as e:
console.print(f"[red]Error:[/red] Database error: {e.message}")
if e.context:
console.print(f"[dim]Context: {e.context}[/dim]")
raise Exit(1)
except Exit:
# Re-raise Exit exceptions (they're intentional)
raise
except Exception as e:
# Log unexpected errors
logger.exception(f"Unexpected error importing {excel_path}")
console.print("[red]Error:[/red] An unexpected error occurred during import")
console.print(f"[dim]Details: {e}[/dim]")
if "--debug" in sys.argv:
console.print(traceback.format_exc())
else:
console.print("[dim]Use --debug for more information[/dim]")
raise Exit(1)
# ──────────────────────────────────────────────────────────────
# Command: EXPORT
# ──────────────────────────────────────────────────────────────
@app.command("export")
def export_cmd(
output: str = Option(..., "--output", "-o", help="Output Excel file path"),
table: str = Option(None, "--table", help="Export entire table"),
query: str = Option(None, "--query", help="Custom SQL query"),
) -> None:
"""Export data from database to Excel."""
# Validation
if not table and not query:
console.print("[red]Error:[/red] Must specify --table or --query")
raise Exit(1)
if table and query:
console.print("[red]Error:[/red] Cannot specify both --table and --query")
raise Exit(1)
try:
# Load project
project = Project.from_current_directory()
except Exception:
console.print("[red]Error:[/red] Not an excel-to-sql project")
console.print("[dim]Run 'excel-to-sql init' to initialize[/dim]")
raise Exit(1)
console.print(f"[bold cyan]Exporting to {output}...[/bold cyan]")
try:
# Execute export
if table:
# Export table
console.print(f" Table: {table}")
try:
df = project.database.export_table(table)
source_desc = f"table '{table}'"
except ValueError as e:
console.print(f"[red]Error:[/red] {e}")
raise Exit(1)
else:
# Export query
console.print(f" Query: {query[:50]}...")
# Validate query starts with SELECT
if not query.strip().upper().startswith("SELECT"):
console.print("[red]Error:[/red] Query must start with SELECT")
raise Exit(1)
try:
df = project.database.query(query)
source_desc = "custom query"
except Exception as e:
console.print(f"[red]Error:[/red] Invalid SQL query")
console.print(f"[dim]{e}[/dim]")
raise Exit(1)
# Check for empty results
if len(df) == 0:
console.print("[yellow]Warning:[/yellow] No data to export")
raise Exit(0)
# Create output directory if needed
output_path = Path(output)
output_path.parent.mkdir(parents=True, exist_ok=True)
# Write to Excel with formatting
with pd.ExcelWriter(str(output_path), engine='openpyxl') as writer:
df.to_excel(writer, index=False, sheet_name='Sheet1')
# Apply formatting
worksheet = writer.sheets['Sheet1']
# Bold headers
for cell in worksheet[1]:
cell.font = cell.font.copy(bold=True)
# Auto-adjust column widths
for column in worksheet.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except (AttributeError, TypeError):
# Cell value is None or has unexpected type, skip it
continue
adjusted_width = min(max_length + 2, 50) # Cap at 50
worksheet.column_dimensions[column_letter].width = adjusted_width
# Freeze header row
worksheet.freeze_panes = 'A2'
# Record export history
project.database.record_export(
table_name=table,
query=query,
output_path=str(output_path),
row_count=len(df)
)
# Display summary
console.print("")
console.print("[bold green]OK[/bold green] Export completed successfully")
console.print("")
summary_table = Table(title="Export Summary")
summary_table.add_column("Metric", style="cyan")
summary_table.add_column("Value", style="green")
summary_table.add_row("Source", source_desc)
summary_table.add_row("Output", str(output_path))
summary_table.add_row("Rows", str(len(df)))
summary_table.add_row("Columns", str(len(df.columns)))
# Get file size
file_size = output_path.stat().st_size
if file_size > 1024 * 1024:
size_str = f"{file_size / (1024 * 1024):.2f} MB"
elif file_size > 1024:
size_str = f"{file_size / 1024:.2f} KB"
else:
size_str = f"{file_size} bytes"
summary_table.add_row("File size", size_str)
console.print(summary_table)
except FileNotFoundError:
console.print(f"[red]Error:[/red] Table not found in database")
if table:
console.print(f"[dim]Table: {table}[/dim]")
console.print("[dim]Tip: Check the table name or import data first[/dim]")
raise Exit(1)
except PermissionError:
console.print(f"[red]Error:[/red] Permission denied: {output}")
console.print("[dim]Tip: Check write permissions for the output directory[/dim]")
raise Exit(1)
except DatabaseError as e:
console.print(f"[red]Error:[/red] Database error: {e.message}")
if e.context:
console.print(f"[dim]Context: {e.context}[/dim]")
raise Exit(1)
except Exit:
raise
except Exception as e:
logger.exception(f"Unexpected error during export to {output}")
console.print("[red]Error:[/red] An unexpected error occurred during export")
console.print(f"[dim]Details: {e}[/dim]")
console.print("[dim]Use --debug for more information[/dim]")
raise Exit(1)
# ──────────────────────────────────────────────────────────────
# Command: STATUS
# ──────────────────────────────────────────────────────────────
@app.command()
def status() -> None:
"""Show import history."""
try:
# Load project
project = Project.from_current_directory()
except ConfigurationError as e:
console.print(f"[red]Error:[/red] Configuration error: {e.message}")
console.print("[dim]Tip: Run 'excel-to-sql init' to initialize[/dim]")
raise Exit(1)
except Exception:
console.print("[red]Error:[/red] Not an excel-to-sql project")
console.print("[dim]Run 'excel-to-sql init' to initialize[/dim]")
raise Exit(1)
# Get import history
history = project.database.get_import_history()
# Handle empty history
if len(history) == 0:
console.print("[dim]No imports yet[/dim]")
console.print("")
console.print("[dim]Run 'excel-to-sql import --file <file> --type <type>' to start importing[/dim]")
return
# Create Rich table for display
table = Table(title="Import History")
table.add_column("Date", style="cyan", no_wrap=False)
table.add_column("File", style="green")
table.add_column("Type", style="yellow")
table.add_column("Rows", style="magenta", justify="right")
table.add_column("Status", style="blue")
# Add rows to table
for _, row in history.iterrows():
# Format date (remove seconds for cleaner display)
date_str = str(row["imported_at"]).split(".")[0] # Remove microseconds if present
if "T" in date_str:
date_str = date_str.replace("T", " ")
# Style status based on value
status = str(row["status"])
status_style = "green" if status == "success" else "red"
table.add_row(
date_str,
str(row["file_name"]),
str(row["file_type"]),
str(row["rows_imported"]),
f"[{status_style}]{status}[/{status_style}]"
)
# Display table
console.print("")
console.print(table)
# Display statistics
total_imports = len(history)
total_rows = history["rows_imported"].sum()
total_skipped = history["rows_skipped"].sum()
# Count successful imports
successful = len(history[history["status"] == "success"])
success_rate = (successful / total_imports * 100) if total_imports > 0 else 0
# Get last import date
last_import = history.iloc[0]["imported_at"]
last_import_str = str(last_import).split(".")[0]
if "T" in last_import_str:
last_import_str = last_import_str.replace("T", " ")
# Display statistics
console.print("")
console.print(f"[bold]Statistics:[/bold]")
console.print(f" Total imports: {total_imports}")
console.print(f" Total rows: {total_rows}")
console.print(f" Total skipped: {total_skipped}")
console.print(f" Success rate: {success_rate:.1f}%")
console.print(f" Last import: {last_import_str}")
# ──────────────────────────────────────────────────────────────
# Command: VERSION
# ──────────────────────────────────────────────────────────────
@app.command()
def version() -> None:
"""Show version information."""
console.print(f"[bold cyan]excel-to-sql[/bold cyan] version [bold green]{__version__}[/bold green]")
console.print("")
console.print("[dim]GitHub:[/dim] https://github.com/wareflowx/excel-to-sql")
console.print("[dim]PyPI:[/dim] https://pypi.org/project/excel-to-sql/")
console.print("")
console.print(f"[dim]Python: {__import__('sys').version.split()[0]}[/dim]")
# ──────────────────────────────────────────────────────────────
# Command: MAGIC (Auto-Pilot)
# ──────────────────────────────────────────────────────────────
@app.command()
def magic(
data_path: str = Option(".", "--data", "-d", help="Path to directory containing Excel files"),
output_path: str = Option(".excel-to-sql", "--output", "-o", help="Output directory for generated mappings"),
dry_run: bool = Option(False, "--dry-run", help="Analyze files without generating configuration"),
interactive: bool = Option(False, "--interactive", "-i", help="Interactive mode with guided configuration"),
) -> None:
"""Auto-pilot: Automatically detect patterns and generate configuration."""
import sys
from pathlib import Path
from typing import Dict, Any, List
from openpyxl import load_workbook
from rich.panel import Panel
from rich.progress import Progress, BarColumn, TextColumn
from rich.text import Text
from rich.table import Table
from rich.live import Live
from rich.align import Align
# Import Auto-Pilot components
try:
from excel_to_sql.auto_pilot.detector import PatternDetector
from excel_to_sql.auto_pilot.header_detector import HeaderDetector
from excel_to_sql.auto_pilot.quality import QualityScorer
from excel_to_sql.ui.interactive import InteractiveWizard
except ImportError as e:
console.print(f"[red]Error:[/red] {e}")
console.print("[dim]This feature requires the auto_pilot module[/dim]")
raise Exit(1)
# Display styled header
header_text = Text("AUTO-PILOT MODE", style="bold cyan")
version_info = Text("Intelligent Excel to SQLite Configuration", style="dim")
header = Panel(
Text.assemble(
header_text, "\n", version_info
),
title="excel-to-sql",
border_style="cyan",
padding=(1, 2),
)
console.print(header)
console.print("")
# Initialize detectors
detector = PatternDetector()
header_detector = HeaderDetector()
# Find Excel files
data_dir = Path(data_path)
if not data_dir.exists():
console.print(f"[red]Error:[/red] Directory not found: {data_path}")
raise Exit(1)
excel_files = list(data_dir.glob("*.xlsx")) + list(data_dir.glob("*.xls"))
if not excel_files:
console.print(f"[yellow]Warning:[/yellow] No Excel files found in {data_path}")
console.print("[dim]Place .xlsx or .xls files in the directory and try again[/dim]")
raise Exit(1)
# Display files found panel
files_panel = Panel(
f"Found [bold green]{len(excel_files)}[/bold green] Excel file(s) in [cyan]{data_path}[/cyan]",
title="Files Discovered",
border_style="green",
padding=(0, 1),
)
console.print(files_panel)
console.print("")
# Process with progress bar
all_results: Dict[str, Any] = {}
with console.status("[bold]Analyzing Excel files...", spinner="dots") as status:
for excel_file in excel_files:
status.update(f"Processing {excel_file.name}...")
try:
# Load workbook to get sheet names
wb = load_workbook(excel_file, read_only=True)
sheet_names = wb.sheetnames
wb.close()
for sheet_name in sheet_names:
try:
# Read sheet with automatic header detection
df = header_detector.read_excel_with_header_detection(excel_file, sheet_name)
table_name = excel_file.stem.lower()
# Skip empty sheets
if len(df) == 0:
continue
# Detect patterns
patterns = detector.detect_patterns(df, table_name)
all_results[f"{excel_file.stem}/{sheet_name}"] = {
"file": str(excel_file),
"sheet": sheet_name,
"table_name": table_name,
"patterns": patterns,
"row_count": len(df),
"column_count": len(df.columns),
}
except FileNotFoundError:
console.print(f" [red]Error:[/red] File not found: {sheet_name}")
except PermissionError:
console.print(f" [red]Error:[/red] Permission denied: {sheet_name}")
except pd.errors.EmptyDataError:
console.print(f" [yellow]Warning:[/yellow] Empty sheet: {sheet_name}")
except pd.errors.ParserError as e:
console.print(f" [red]Error analyzing {sheet_name}:[/red] Invalid Excel format")
except ExcelFileError as e:
console.print(f" [red]Error analyzing {sheet_name}:[/red] {e.message}")
except Exception as e:
logger.warning(f"Unexpected error analyzing {sheet_name}: {e}")
console.print(f" [red]Error analyzing {sheet_name}:[/red] {e}")
except FileNotFoundError:
console.print(f"[red]Error:[/red] File not found: {excel_file.name}")
except PermissionError:
console.print(f"[red]Error:[/red] Permission denied: {excel_file.name}")
except ExcelFileError as e:
console.print(f"[red]Error processing {excel_file.name}:[/red] {e.message}")
except Exception as e:
logger.warning(f"Unexpected error processing {excel_file.name}: {e}")
console.print(f"[red]Error processing {excel_file.name}:[/red] {e}")
# Interactive mode
if interactive:
console.print("")
console.print("[bold cyan]Starting Interactive Mode...[/bold cyan]")
console.print("")
# Initialize quality scorer
scorer = QualityScorer()
# Prepare patterns and quality dictionaries for wizard
patterns_dict: Dict[str, Dict[str, Any]] = {}
quality_dict: Dict[str, Dict[str, Any]] = {}
for key, result in all_results.items():
table_name = result["table_name"]
patterns_dict[table_name] = result["patterns"]
# Generate quality report
try:
df = header_detector.read_excel_with_header_detection(result["file"], result["sheet"])
quality_report = scorer.generate_quality_report(df, table_name)
quality_dict[table_name] = quality_report
except FileNotFoundError:
# Default quality report if file not found
quality_dict[table_name] = {
"score": 0,
"grade": "F",
"issues": ["File not found"]
}
except PermissionError:
# Default quality report if permission denied
quality_dict[table_name] = {
"score": 0,
"grade": "F",
"issues": ["Permission denied"]
}
except ExcelFileError:
# Default quality report if analysis fails
quality_dict[table_name] = {
"score": 50,
"grade": "C",
"issues": ["Excel file error"]
}
except Exception:
# Default quality report if analysis fails
quality_dict[table_name] = {
"score": 100,
"grade": "A",
"issues": []
}
# Launch interactive wizard
wizard = InteractiveWizard(console)
wizard_result = wizard.run_interactive_mode(
excel_files,
patterns_dict,
quality_dict,
Path(output_path)
)
# Check if user wants to save configuration
if wizard_result.get("action") == "save":
# Generate configuration based on user choices
output_dir = Path(output_path)
output_dir.mkdir(parents=True, exist_ok=True)
mappings_file = output_dir / "mappings.json"
# Build mappings configuration from accepted files
mappings_config: Dict[str, Any] = {"mappings": {}}
for file_data in wizard_result.get("files_data", []):
if file_data.get("skipped"):
continue
file_path_str = file_data["file_path"]
file_path = Path(file_path_str)
table_name = file_path.stem
# Get patterns for this file
patterns = patterns_dict.get(table_name, {})
# Build column mappings
column_mappings = {}
try:
df = header_detector.read_excel_with_header_detection(file_path)
for col in df.columns:
col_type = _infer_sql_type(df[col])
column_mappings[str(col)] = {
"target": str(col),
"type": col_type,
"required": False,
"default": None,
}
except Exception:
pass
# Build value mappings from accepted transformations
value_mappings = []
for trans in file_data.get("accepted_transformations", []):
if trans["type"] == "value_mapping":
value_mappings.append({
"column": trans["column"],
"mappings": trans.get("mappings", {}),
})
# Build validation rules
validation_rules = []
pk = patterns.get("primary_key")
if pk:
validation_rules.append({
"column": pk,
"type": "unique",
"params": {},
"message": f"{pk} must be unique",
"severity": "error",
})
# Build reference validations
reference_validations = []
for fk in patterns.get("foreign_keys", []):
reference_validations.append({
"column": fk["column"],
"reference_table": fk["ref_table"],
"reference_column": fk.get("ref_column", "id"),
})
# Build metadata
metadata = {
"row_count": len(pd.read_excel(file_path)),
"column_count": len(pd.read_excel(file_path).columns),
"detection_confidence": patterns.get("confidence", 0.0),
"auto_generated": True,
"interactive_mode": True,
"primary_key_detected": pk is not None,
"has_value_mappings": len(value_mappings) > 0,
"has_foreign_keys": len(reference_validations) > 0,
}
# Build complete type mapping
type_mapping = {
"target_table": table_name,
"primary_key": [pk] if pk else [],
"column_mappings": column_mappings,
"value_mappings": value_mappings,
"calculated_columns": [],
"validation_rules": validation_rules,
"reference_validations": reference_validations,
"hooks": [],
"tags": ["auto-generated", "interactive"],
"metadata": metadata,
}
mappings_config["mappings"][table_name] = type_mapping
# Save to file
import json
with open(mappings_file, "w", encoding="utf-8") as f:
json.dump(mappings_config, f, indent=2, ensure_ascii=False)
# Display success message
console.print("")
console.print("[bold green]Configuration saved successfully![/bold green]")
console.print(f" Location: [cyan]{mappings_file}[/cyan]")
return # Exit interactive mode
# Display results in file cards
console.print("")
console.print("[bold cyan]Detection Results[/bold cyan]")
console.print("")
for key, result in sorted(all_results.items()):
patterns = result["patterns"]
pk = patterns.get("primary_key")
# Create file card
file_info = Text.assemble(
f"[bold cyan]{result['table_name'].title()}[/bold cyan]\n",
f"File: [dim]{result['file']}[/dim]\n",
f"Sheet: [cyan]{result['sheet']}[/cyan]\n",
f"Rows: [green]{result['row_count']:,}[/green] ",
f"Cols: [blue]{result['column_count']}[/blue]\n"
)
if pk:
file_info += f"PK: [bold green]{pk}[/bold green]\n"
else:
file_info += f"PK: [yellow]Not detected[/yellow]\n"
if patterns.get("value_mappings"):
mappings_text = ", ".join(patterns["value_mappings"].keys())
file_info += f"Value Maps: [green]{mappings_text}[/green]\n"
if patterns.get("foreign_keys"):
fk_text = ", ".join([f"{fk['column']}->{fk['ref_table']}" for fk in patterns["foreign_keys"]])
file_info += f"Foreign Keys: [cyan]{fk_text}[/cyan]\n"
if patterns.get("split_fields"):
split_text = ", ".join(patterns["split_fields"])
file_info += f"Split Fields: [yellow]{split_text}[/yellow]\n"
file_info += f"Confidence: [bold]{patterns['confidence']:.0%}[/bold]"
file_card = Panel(
file_info,
border_style="blue",
padding=(0, 2),
title_align="left",
)
console.print(file_card)
console.print("")
# Display summary table
if all_results:
summary_title = Text.assemble(
"[bold cyan]DETECTION SUMMARY[/bold cyan]\n",
f"[dim]{len(all_results)} table(s) analyzed[/dim]"
)
console.print(Panel(summary_title, border_style="cyan", padding=(0, 1)))
console.print("")
table = Table(show_header=True, header_style="bold cyan", title_style="cyan", show_lines=True)
table.add_column("Table", style="cyan", width=20)
table.add_column("Rows", justify="right", style="green")
table.add_column("Primary Key", style="bold green", width=15)
table.add_column("Value Maps", justify="center", width=12)
table.add_column("FKs", justify="center", width=8)
table.add_column("Score", justify="right", width=8)
for key, result in sorted(all_results.items()):
patterns = result["patterns"]
pk = patterns.get("primary_key") or "[dim]-[/dim]"
value_maps = "[green]OK[/green]" if patterns.get("value_mappings") else "-"
fks = str(len(patterns.get("foreign_keys", []))) if patterns.get("foreign_keys") else "-"
score = f"[cyan]{patterns.get('confidence', 0):.0%}[/cyan]"
table.add_row(
result["table_name"],
f"{result['row_count']:,}",
pk,
value_maps,
fks,
score,
)
console.print(table)
console.print("")
# Generate configuration
if not dry_run and all_results:
output_dir = Path(output_path)
output_dir.mkdir(parents=True, exist_ok=True)
mappings_file = output_dir / "mappings.json"
# Show generation progress
with console.status("[bold]Generating configuration...", spinner="dots2") as status:
status.update("Building mappings structure...")
# Build mappings configuration
mappings_config: Dict[str, Any] = {"mappings": {}}
for key, result in all_results.items():
patterns = result["patterns"]
table_name = result["table_name"]
# Build column mappings
column_mappings = {}
try:
df = header_detector.read_excel_with_header_detection(result["file"], result["sheet"])
for col in df.columns:
col_type = _infer_sql_type(df[col])
column_mappings[str(col)] = {
"target": str(col),
"type": col_type,
"required": False,
"default": None,
}
except Exception:
pass
# Build value mappings
value_mappings = []
for col, mappings in patterns.get("value_mappings", {}).items():
value_mappings.append({
"column": col,
"mappings": mappings,
})
# Build validation rules
validation_rules = []
pk = patterns.get("primary_key")
if pk:
validation_rules.append({
"column": pk,
"type": "unique",
"params": {},
"message": f"{pk} must be unique",
"severity": "error",
})
# Build reference validations
reference_validations = []
for fk in patterns.get("foreign_keys", []):
reference_validations.append({
"column": fk["column"],
"reference_table": fk["ref_table"],
"reference_column": fk.get("ref_column", "id"),
})
# Build metadata
metadata = {
"row_count": result["row_count"],
"column_count": result["column_count"],
"detection_confidence": patterns.get("confidence", 0.0),
"auto_generated": True,
"primary_key_detected": pk is not None,
"has_value_mappings": len(value_mappings) > 0,
"has_foreign_keys": len(reference_validations) > 0,
"has_split_fields": patterns.get("split_fields") is not None,
}
# Build complete type mapping
type_mapping = {
"target_table": table_name,
"primary_key": [pk] if pk else [],
"column_mappings": column_mappings,
"value_mappings": value_mappings,
"calculated_columns": [],
"validation_rules": validation_rules,
"reference_validations": reference_validations,
"hooks": [],
"tags": ["auto-generated"],
"metadata": metadata,
}
mappings_config["mappings"][table_name] = type_mapping
status.update(f"Saving to {mappings_file}...")
# Save to file
import json
with open(mappings_file, "w", encoding="utf-8") as f:
json.dump(mappings_config, f, indent=2, ensure_ascii=False)
# Display success panel
success_panel = Panel(
Text.assemble(
"[bold green]Configuration generated successfully![/bold green]\n\n",
f"Location: [cyan]{mappings_file}[/cyan]\n",
f"Tables: [green]{len(mappings_config['mappings'])}[/green]\n",