delta-lake-utils 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Nalini Panwar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: delta-lake-utils
3
+ Version: 1.0.0
4
+ Summary: Production-grade utilities for Delta Lake management
5
+ Home-page: https://github.com/panwarnalini-hub/delta-lake-utils
6
+ Author: Nalini Panwar
7
+ Author-email: panwarnalini@gmail.com
8
+ Classifier: Programming Language :: Python :: 3.8
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pyspark>=3.2.0
16
+ Requires-Dist: delta-spark>=2.0.0
17
+ Requires-Dist: click>=8.0.0
18
+ Requires-Dist: pandas>=1.3.0
19
+ Dynamic: author
20
+ Dynamic: author-email
21
+ Dynamic: classifier
22
+ Dynamic: description
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: requires-python
28
+ Dynamic: summary
29
+
30
+ # delta-lake-utils
31
+
32
+ Production-grade utilities for Delta Lake table management and optimization on Databricks.
33
+
34
+ ## What Does This Package Do?
35
+
36
+ Automates Delta Lake table optimization, health monitoring, and pipeline generation for Databricks data engineers.
37
+
38
+ ### Main Features:
39
+
40
+ 1. **Smart OPTIMIZE** - Automatically consolidates small files and improves query performance
41
+ - Detects when your Delta table has too many small files
42
+ - Intelligently chooses which columns to Z-ORDER by
43
+ - Reduces query time by up to 10x
44
+
45
+ 2. **Health Checker** - Diagnoses table problems before they impact production
46
+ - Identifies small file problems
47
+ - Detects data skew across partitions
48
+ - Finds configuration issues
49
+
50
+ 3. **Performance Profiler** - Measures how fast your Delta operations run
51
+ - Track read/write speeds
52
+ - Identify bottlenecks
53
+ - Compare before/after optimization
54
+
55
+ 4. **Medallion Generator** - Auto-creates Bronze/Silver/Gold pipeline code
56
+ - Generates production-ready notebooks
57
+ - Follows best practices
58
+ - Saves hours of boilerplate coding
59
+
60
+ 5. **Unity Catalog Auditor** - Manages permissions and access control
61
+ - Audits table permissions
62
+ - Generates permission scripts
63
+ - Ensures security compliance
64
+
65
+ ## Installation
66
+ ```bash
67
+ pip install delta-lake-utils
68
+ ```
69
+
70
+ ## Quick Start
71
+ ```python
72
+ from pyspark.sql import SparkSession
73
+ from delta_utils import DeltaOptimizer
74
+
75
+ spark = SparkSession.builder.getOrCreate()
76
+ optimizer = DeltaOptimizer(spark)
77
+
78
+ # Optimize a table - reduces files, improves performance
79
+ result = optimizer.auto_optimize('/mnt/delta/my_table')
80
+ print(f"Optimized! Removed {result.files_removed} files")
81
+ ```
82
+
83
+ ## Use Cases
84
+
85
+ ### Use Case 1: Your queries are slow
86
+ Problem: Delta table has 5000 small files, queries take 10 minutes
87
+ Solution: Run optimizer, consolidates to 50 files, queries now take 1 minute
88
+
89
+ ### Use Case 2: Starting a new data pipeline
90
+ Problem: Need to build Bronze/Silver/Gold architecture from scratch
91
+ Solution: Use medallion generator, get complete pipeline in 30 seconds
92
+
93
+ ### Use Case 3: Data quality issues
94
+ Problem: Not sure if table is healthy, production keeps failing
95
+ Solution: Run health checker, get specific recommendations to fix issues
96
+
97
+ ### Use Case 4: Permission audit required
98
+ Problem: Need to verify all tables have correct access controls
99
+ Solution: Use catalog auditor to check and fix permissions
100
+
101
+ ## Documentation
102
+
103
+ - See [QUICKSTART.md](QUICKSTART.md) for 5-minute tutorial
104
+ - See [EXPLANATION.md](EXPLANATION.md) for detailed use cases
105
+ - See [examples/EXAMPLES.md](examples/EXAMPLES.md) for code examples
106
+
107
+ ## Requirements
108
+
109
+ - Python 3.8+
110
+ - PySpark 3.2+
111
+ - Delta Lake 2.0+
112
+ - Databricks Runtime 11.0+ recommended
113
+
114
+ ## Author
115
+
116
+ Nalini Panwar
117
+ GitHub: [@panwarnalini-hub](https://github.com/panwarnalini-hub)
118
+
119
+ ## License
120
+
121
+ MIT License - see [LICENSE](LICENSE) file for details
@@ -0,0 +1,92 @@
1
+ # delta-lake-utils
2
+
3
+ Production-grade utilities for Delta Lake table management and optimization on Databricks.
4
+
5
+ ## What Does This Package Do?
6
+
7
+ Automates Delta Lake table optimization, health monitoring, and pipeline generation for Databricks data engineers.
8
+
9
+ ### Main Features:
10
+
11
+ 1. **Smart OPTIMIZE** - Automatically consolidates small files and improves query performance
12
+ - Detects when your Delta table has too many small files
13
+ - Intelligently chooses which columns to Z-ORDER by
14
+ - Reduces query time by up to 10x
15
+
16
+ 2. **Health Checker** - Diagnoses table problems before they impact production
17
+ - Identifies small file problems
18
+ - Detects data skew across partitions
19
+ - Finds configuration issues
20
+
21
+ 3. **Performance Profiler** - Measures how fast your Delta operations run
22
+ - Track read/write speeds
23
+ - Identify bottlenecks
24
+ - Compare before/after optimization
25
+
26
+ 4. **Medallion Generator** - Auto-creates Bronze/Silver/Gold pipeline code
27
+ - Generates production-ready notebooks
28
+ - Follows best practices
29
+ - Saves hours of boilerplate coding
30
+
31
+ 5. **Unity Catalog Auditor** - Manages permissions and access control
32
+ - Audits table permissions
33
+ - Generates permission scripts
34
+ - Ensures security compliance
35
+
36
+ ## Installation
37
+ ```bash
38
+ pip install delta-lake-utils
39
+ ```
40
+
41
+ ## Quick Start
42
+ ```python
43
+ from pyspark.sql import SparkSession
44
+ from delta_utils import DeltaOptimizer
45
+
46
+ spark = SparkSession.builder.getOrCreate()
47
+ optimizer = DeltaOptimizer(spark)
48
+
49
+ # Optimize a table - reduces files, improves performance
50
+ result = optimizer.auto_optimize('/mnt/delta/my_table')
51
+ print(f"Optimized! Removed {result.files_removed} files")
52
+ ```
53
+
54
+ ## Use Cases
55
+
56
+ ### Use Case 1: Your queries are slow
57
+ Problem: Delta table has 5000 small files, queries take 10 minutes
58
+ Solution: Run optimizer, consolidates to 50 files, queries now take 1 minute
59
+
60
+ ### Use Case 2: Starting a new data pipeline
61
+ Problem: Need to build Bronze/Silver/Gold architecture from scratch
62
+ Solution: Use medallion generator, get complete pipeline in 30 seconds
63
+
64
+ ### Use Case 3: Data quality issues
65
+ Problem: Not sure if table is healthy, production keeps failing
66
+ Solution: Run health checker, get specific recommendations to fix issues
67
+
68
+ ### Use Case 4: Permission audit required
69
+ Problem: Need to verify all tables have correct access controls
70
+ Solution: Use catalog auditor to check and fix permissions
71
+
72
+ ## Documentation
73
+
74
+ - See [QUICKSTART.md](QUICKSTART.md) for 5-minute tutorial
75
+ - See [EXPLANATION.md](EXPLANATION.md) for detailed use cases
76
+ - See [examples/EXAMPLES.md](examples/EXAMPLES.md) for code examples
77
+
78
+ ## Requirements
79
+
80
+ - Python 3.8+
81
+ - PySpark 3.2+
82
+ - Delta Lake 2.0+
83
+ - Databricks Runtime 11.0+ recommended
84
+
85
+ ## Author
86
+
87
+ Nalini Panwar
88
+ GitHub: [@panwarnalini-hub](https://github.com/panwarnalini-hub)
89
+
90
+ ## License
91
+
92
+ MIT License - see [LICENSE](LICENSE) file for details
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,35 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ with open("README.md", "r") as f:
4
+ long_description = f.read()
5
+
6
+ setup(
7
+ name="delta-lake-utils",
8
+ version="1.0.0",
9
+ author="Nalini Panwar",
10
+ author_email="panwarnalini@gmail.com",
11
+ description="Production-grade utilities for Delta Lake management",
12
+ long_description=long_description,
13
+ long_description_content_type="text/markdown",
14
+ url="https://github.com/panwarnalini-hub/delta-lake-utils",
15
+ packages=find_packages(where="src"),
16
+ package_dir={"": "src"},
17
+ install_requires=[
18
+ "pyspark>=3.2.0",
19
+ "delta-spark>=2.0.0",
20
+ "click>=8.0.0",
21
+ "pandas>=1.3.0",
22
+ ],
23
+ entry_points={
24
+ "console_scripts": [
25
+ "delta-utils=delta_utils.cli:cli",
26
+ ],
27
+ },
28
+ classifiers=[
29
+ "Programming Language :: Python :: 3.8",
30
+ "Programming Language :: Python :: 3.9",
31
+ "Programming Language :: Python :: 3.10",
32
+ "License :: OSI Approved :: MIT License",
33
+ ],
34
+ python_requires=">=3.8",
35
+ )
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: delta-lake-utils
3
+ Version: 1.0.0
4
+ Summary: Production-grade utilities for Delta Lake management
5
+ Home-page: https://github.com/panwarnalini-hub/delta-lake-utils
6
+ Author: Nalini Panwar
7
+ Author-email: panwarnalini@gmail.com
8
+ Classifier: Programming Language :: Python :: 3.8
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pyspark>=3.2.0
16
+ Requires-Dist: delta-spark>=2.0.0
17
+ Requires-Dist: click>=8.0.0
18
+ Requires-Dist: pandas>=1.3.0
19
+ Dynamic: author
20
+ Dynamic: author-email
21
+ Dynamic: classifier
22
+ Dynamic: description
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: requires-python
28
+ Dynamic: summary
29
+
30
+ # delta-lake-utils
31
+
32
+ Production-grade utilities for Delta Lake table management and optimization on Databricks.
33
+
34
+ ## What Does This Package Do?
35
+
36
+ Automates Delta Lake table optimization, health monitoring, and pipeline generation for Databricks data engineers.
37
+
38
+ ### Main Features:
39
+
40
+ 1. **Smart OPTIMIZE** - Automatically consolidates small files and improves query performance
41
+ - Detects when your Delta table has too many small files
42
+ - Intelligently chooses which columns to Z-ORDER by
43
+ - Reduces query time by up to 10x
44
+
45
+ 2. **Health Checker** - Diagnoses table problems before they impact production
46
+ - Identifies small file problems
47
+ - Detects data skew across partitions
48
+ - Finds configuration issues
49
+
50
+ 3. **Performance Profiler** - Measures how fast your Delta operations run
51
+ - Track read/write speeds
52
+ - Identify bottlenecks
53
+ - Compare before/after optimization
54
+
55
+ 4. **Medallion Generator** - Auto-creates Bronze/Silver/Gold pipeline code
56
+ - Generates production-ready notebooks
57
+ - Follows best practices
58
+ - Saves hours of boilerplate coding
59
+
60
+ 5. **Unity Catalog Auditor** - Manages permissions and access control
61
+ - Audits table permissions
62
+ - Generates permission scripts
63
+ - Ensures security compliance
64
+
65
+ ## Installation
66
+ ```bash
67
+ pip install delta-lake-utils
68
+ ```
69
+
70
+ ## Quick Start
71
+ ```python
72
+ from pyspark.sql import SparkSession
73
+ from delta_utils import DeltaOptimizer
74
+
75
+ spark = SparkSession.builder.getOrCreate()
76
+ optimizer = DeltaOptimizer(spark)
77
+
78
+ # Optimize a table - reduces files, improves performance
79
+ result = optimizer.auto_optimize('/mnt/delta/my_table')
80
+ print(f"Optimized! Removed {result.files_removed} files")
81
+ ```
82
+
83
+ ## Use Cases
84
+
85
+ ### Use Case 1: Your queries are slow
86
+ Problem: Delta table has 5000 small files, queries take 10 minutes
87
+ Solution: Run optimizer, consolidates to 50 files, queries now take 1 minute
88
+
89
+ ### Use Case 2: Starting a new data pipeline
90
+ Problem: Need to build Bronze/Silver/Gold architecture from scratch
91
+ Solution: Use medallion generator, get complete pipeline in 30 seconds
92
+
93
+ ### Use Case 3: Data quality issues
94
+ Problem: Not sure if table is healthy, production keeps failing
95
+ Solution: Run health checker, get specific recommendations to fix issues
96
+
97
+ ### Use Case 4: Permission audit required
98
+ Problem: Need to verify all tables have correct access controls
99
+ Solution: Use catalog auditor to check and fix permissions
100
+
101
+ ## Documentation
102
+
103
+ - See [QUICKSTART.md](QUICKSTART.md) for 5-minute tutorial
104
+ - See [EXPLANATION.md](EXPLANATION.md) for detailed use cases
105
+ - See [examples/EXAMPLES.md](examples/EXAMPLES.md) for code examples
106
+
107
+ ## Requirements
108
+
109
+ - Python 3.8+
110
+ - PySpark 3.2+
111
+ - Delta Lake 2.0+
112
+ - Databricks Runtime 11.0+ recommended
113
+
114
+ ## Author
115
+
116
+ Nalini Panwar
117
+ GitHub: [@panwarnalini-hub](https://github.com/panwarnalini-hub)
118
+
119
+ ## License
120
+
121
+ MIT License - see [LICENSE](LICENSE) file for details
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ src/delta_lake_utils.egg-info/PKG-INFO
5
+ src/delta_lake_utils.egg-info/SOURCES.txt
6
+ src/delta_lake_utils.egg-info/dependency_links.txt
7
+ src/delta_lake_utils.egg-info/entry_points.txt
8
+ src/delta_lake_utils.egg-info/requires.txt
9
+ src/delta_lake_utils.egg-info/top_level.txt
10
+ src/delta_utils/__init__.py
11
+ src/delta_utils/catalog_auditor.py
12
+ src/delta_utils/cli.py
13
+ src/delta_utils/health_checker.py
14
+ src/delta_utils/medallion_generator.py
15
+ src/delta_utils/optimizer.py
16
+ src/delta_utils/profiler.py
17
+ src/delta_utils/utils.py
18
+ tests/test_basic.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ delta-utils = delta_utils.cli:cli
@@ -0,0 +1,4 @@
1
+ pyspark>=3.2.0
2
+ delta-spark>=2.0.0
3
+ click>=8.0.0
4
+ pandas>=1.3.0
@@ -0,0 +1,20 @@
1
+ """Delta Lake Utilities - Production-grade Delta table management"""
2
+
3
+ from delta_utils.optimizer import DeltaOptimizer, OptimizationResult
4
+ from delta_utils.health_checker import DeltaHealthChecker, HealthStatus, HealthIssue
5
+ from delta_utils.profiler import DeltaProfiler, ProfileResult
6
+ from delta_utils.medallion_generator import MedallionGenerator
7
+ from delta_utils.catalog_auditor import CatalogAuditor
8
+
9
+ __version__ = "1.0.0"
10
+ __all__ = [
11
+ "DeltaOptimizer",
12
+ "OptimizationResult",
13
+ "DeltaHealthChecker",
14
+ "HealthStatus",
15
+ "HealthIssue",
16
+ "DeltaProfiler",
17
+ "ProfileResult",
18
+ "MedallionGenerator",
19
+ "CatalogAuditor",
20
+ ]
@@ -0,0 +1,33 @@
1
+ from pyspark.sql import SparkSession
2
+ from typing import Dict, List
3
+ import pandas as pd
4
+
5
+
6
+ class CatalogAuditor:
7
+ """Audit Unity Catalog permissions"""
8
+
9
+ def __init__(self, spark: SparkSession):
10
+ self.spark = spark
11
+
12
+ def list_catalogs(self) -> pd.DataFrame:
13
+ """List all catalogs"""
14
+ return self.spark.sql("SHOW CATALOGS").toPandas()
15
+
16
+ def list_schemas(self, catalog: str) -> pd.DataFrame:
17
+ """List schemas in a catalog"""
18
+ return self.spark.sql(f"SHOW SCHEMAS IN {catalog}").toPandas()
19
+
20
+ def get_table_permissions(
21
+ self,
22
+ catalog: str,
23
+ schema: str,
24
+ table: str
25
+ ) -> pd.DataFrame:
26
+ """Get permissions for a table"""
27
+ try:
28
+ return self.spark.sql(
29
+ f"SHOW GRANTS ON TABLE {catalog}.{schema}.{table}"
30
+ ).toPandas()
31
+ except Exception as e:
32
+ print(f"Error getting permissions: {str(e)}")
33
+ return pd.DataFrame()
@@ -0,0 +1,39 @@
1
+ import click
2
+ from pyspark.sql import SparkSession
3
+
4
+
5
+ @click.group()
6
+ def cli():
7
+ """Delta Lake Utilities CLI"""
8
+ pass
9
+
10
+
11
+ @cli.command()
12
+ @click.argument('table_path')
13
+ def optimize(table_path):
14
+ """Optimize Delta table"""
15
+ from delta_utils import DeltaOptimizer
16
+
17
+ spark = SparkSession.builder.appName("DeltaOptimizer").getOrCreate()
18
+ optimizer = DeltaOptimizer(spark)
19
+ result = optimizer.auto_optimize(table_path)
20
+
21
+ click.echo(f"\nOptimization complete!")
22
+ click.echo(f"Files: {result.files_before} -> {result.files_after}")
23
+
24
+
25
+ @cli.command()
26
+ @click.argument('table_path')
27
+ def health(table_path):
28
+ """Check Delta table health"""
29
+ from delta_utils import DeltaHealthChecker
30
+
31
+ spark = SparkSession.builder.appName("DeltaHealthChecker").getOrCreate()
32
+ checker = DeltaHealthChecker(spark)
33
+ report = checker.check_table(table_path)
34
+
35
+ checker.print_report(report)
36
+
37
+
38
+ if __name__ == '__main__':
39
+ cli()
@@ -0,0 +1,115 @@
1
+ from pyspark.sql import SparkSession
2
+ from delta.tables import DeltaTable
3
+ from typing import Dict, List, Any, Optional
4
+ from dataclasses import dataclass
5
+ from enum import Enum
6
+
7
+
8
+ class HealthStatus(Enum):
9
+ HEALTHY = "HEALTHY"
10
+ WARNING = "WARNING"
11
+ CRITICAL = "CRITICAL"
12
+
13
+
14
+ @dataclass
15
+ class HealthIssue:
16
+ severity: HealthStatus
17
+ category: str
18
+ message: str
19
+ recommendation: str
20
+ metric_value: Any
21
+
22
+
23
+ class DeltaHealthChecker:
24
+ """Comprehensive Delta Lake table health diagnostics"""
25
+
26
+ SMALL_FILE_THRESHOLD_MB = 10
27
+ SMALL_FILE_COUNT_WARNING = 100
28
+ SMALL_FILE_COUNT_CRITICAL = 500
29
+
30
+ def __init__(self, spark: SparkSession, verbose: bool = True):
31
+ self.spark = spark
32
+ self.verbose = verbose
33
+
34
+ def check_table(self, table_path: str) -> Dict[str, Any]:
35
+ """Run comprehensive health check"""
36
+ issues = []
37
+
38
+ # Check small files
39
+ small_files_issue = self._check_small_files(table_path)
40
+ if small_files_issue:
41
+ issues.append(small_files_issue)
42
+
43
+ # Calculate overall status
44
+ if not issues:
45
+ overall_status = HealthStatus.HEALTHY
46
+ score = 100
47
+ elif any(i.severity == HealthStatus.CRITICAL for i in issues):
48
+ overall_status = HealthStatus.CRITICAL
49
+ score = 30
50
+ else:
51
+ overall_status = HealthStatus.WARNING
52
+ score = 60
53
+
54
+ return {
55
+ 'overall_status': overall_status,
56
+ 'score': score,
57
+ 'issues': issues,
58
+ 'num_issues': len(issues),
59
+ 'table_path': table_path
60
+ }
61
+
62
+ def _check_small_files(self, table_path: str) -> Optional[HealthIssue]:
63
+ """Check for excessive small files"""
64
+ try:
65
+ query = f"""
66
+ SELECT
67
+ COUNT(*) as total_files,
68
+ SUM(CASE WHEN size < {self.SMALL_FILE_THRESHOLD_MB * 1024 * 1024}
69
+ THEN 1 ELSE 0 END) as small_files
70
+ FROM delta.`{table_path}`
71
+ """
72
+ stats = self.spark.sql(query).collect()[0]
73
+
74
+ small_count = stats['small_files']
75
+
76
+ if small_count >= self.SMALL_FILE_COUNT_CRITICAL:
77
+ return HealthIssue(
78
+ severity=HealthStatus.CRITICAL,
79
+ category="Small Files",
80
+ message=f"{small_count:,} files smaller than {self.SMALL_FILE_THRESHOLD_MB}MB",
81
+ recommendation="Run OPTIMIZE to consolidate files",
82
+ metric_value=small_count
83
+ )
84
+ elif small_count >= self.SMALL_FILE_COUNT_WARNING:
85
+ return HealthIssue(
86
+ severity=HealthStatus.WARNING,
87
+ category="Small Files",
88
+ message=f"{small_count:,} small files detected",
89
+ recommendation="Consider running OPTIMIZE",
90
+ metric_value=small_count
91
+ )
92
+ return None
93
+ except Exception as e:
94
+ if self.verbose:
95
+ print(f"Error checking small files: {str(e)}")
96
+ return None
97
+
98
+ def print_report(self, health_report: Dict[str, Any]):
99
+ """Print formatted health report"""
100
+ print("\n" + "=" * 70)
101
+ print("DELTA TABLE HEALTH REPORT")
102
+ print("=" * 70)
103
+ print(f"Table: {health_report['table_path']}")
104
+ print(f"Overall Status: {health_report['overall_status'].value}")
105
+ print(f"Health Score: {health_report['score']}/100")
106
+ print("=" * 70)
107
+
108
+ if not health_report['issues']:
109
+ print("\nNo issues detected. Table is healthy.")
110
+ else:
111
+ print(f"\nIssues Found: {health_report['num_issues']}\n")
112
+ for i, issue in enumerate(health_report['issues'], 1):
113
+ print(f"{i}. [{issue.severity.value}] {issue.category}")
114
+ print(f" Problem: {issue.message}")
115
+ print(f" Fix: {issue.recommendation}\n")
@@ -0,0 +1,88 @@
1
+ import os
2
+ from typing import Dict, Optional
3
+
4
+
5
+ class MedallionGenerator:
6
+ """Generate medallion architecture boilerplate code"""
7
+
8
+ BRONZE_TEMPLATE = '''# Bronze Layer - {table_name}
9
+ # Raw data ingestion
10
+
11
+ from pyspark.sql import functions as F
12
+
13
+ source_path = "{source_path}"
14
+ bronze_path = "{bronze_path}"
15
+
16
+ df = spark.read.format("{source_format}").load(source_path)
17
+
18
+ bronze_df = df.withColumn("_ingestion_timestamp", F.current_timestamp())
19
+
20
+ bronze_df.write.format("delta").mode("append").save(bronze_path)
21
+ '''
22
+
23
+ def __init__(self, base_path: str):
24
+ self.base_path = base_path.rstrip('/')
25
+
26
+ def generate_layer(
27
+ self,
28
+ table_name: str,
29
+ layer: str,
30
+ source_path: Optional[str] = None,
31
+ source_format: str = "json",
32
+ output_dir: str = "./notebooks"
33
+ ) -> str:
34
+ """Generate notebook for a specific layer"""
35
+ layer = layer.lower()
36
+
37
+ if layer not in ['bronze', 'silver', 'gold']:
38
+ raise ValueError(f"Invalid layer: {layer}")
39
+
40
+ os.makedirs(output_dir, exist_ok=True)
41
+
42
+ bronze_path = f"{self.base_path}/bronze/{table_name}"
43
+
44
+ if layer == 'bronze':
45
+ template = self.BRONZE_TEMPLATE
46
+ context = {
47
+ 'table_name': table_name,
48
+ 'source_path': source_path or '/mnt/source/data',
49
+ 'bronze_path': bronze_path,
50
+ 'source_format': source_format
51
+ }
52
+ else:
53
+ template = f"# {layer.capitalize()} Layer - {table_name}\n"
54
+ context = {'table_name': table_name}
55
+
56
+ notebook_content = template.format(**context)
57
+
58
+ output_path = os.path.join(output_dir, f"{table_name}_{layer}.py")
59
+ with open(output_path, 'w') as f:
60
+ f.write(notebook_content)
61
+
62
+ return output_path
63
+
64
+ def generate_full_pipeline(
65
+ self,
66
+ table_name: str,
67
+ source_path: Optional[str] = None,
68
+ source_format: str = "json",
69
+ output_dir: str = "./notebooks"
70
+ ) -> Dict[str, str]:
71
+ """Generate complete medallion pipeline"""
72
+ notebooks = {}
73
+
74
+ for layer in ['bronze', 'silver', 'gold']:
75
+ path = self.generate_layer(
76
+ table_name=table_name,
77
+ layer=layer,
78
+ source_path=source_path,
79
+ source_format=source_format,
80
+ output_dir=output_dir
81
+ )
82
+ notebooks[layer] = path
83
+
84
+ print(f"\nGenerated medallion pipeline for '{table_name}':")
85
+ for layer, path in notebooks.items():
86
+ print(f" {layer}: {path}")
87
+
88
+ return notebooks
@@ -0,0 +1,197 @@
1
+ from pyspark.sql import SparkSession
2
+ from delta.tables import DeltaTable
3
+ import time
4
+ from typing import Optional, List, Dict, Any
5
+ from dataclasses import dataclass, asdict
6
+
7
+
8
+ @dataclass
9
+ class OptimizationResult:
10
+ """Results from optimization operation"""
11
+ table_name: str
12
+ files_before: int
13
+ files_after: int
14
+ size_before_mb: float
15
+ size_after_mb: float
16
+ duration_seconds: float
17
+ zorder_columns: Optional[List[str]]
18
+ recommendations: List[str]
19
+ files_removed: int
20
+ compression_ratio: float
21
+
22
+ def to_dict(self) -> Dict[str, Any]:
23
+ return asdict(self)
24
+
25
+
26
+ class DeltaOptimizer:
27
+ """Smart Delta Lake table optimizer with auto-tuning capabilities"""
28
+
29
+ DEFAULT_TARGET_FILE_SIZE_MB = 128
30
+ MIN_FILE_SIZE_MB = 10
31
+ MAX_ZORDER_COLUMNS = 3
32
+
33
+ def __init__(
34
+ self,
35
+ spark: SparkSession,
36
+ target_file_size_mb: int = DEFAULT_TARGET_FILE_SIZE_MB,
37
+ verbose: bool = True
38
+ ):
39
+ self.spark = spark
40
+ self.target_file_size_mb = target_file_size_mb
41
+ self.verbose = verbose
42
+
43
+ def _log(self, message: str):
44
+ if self.verbose:
45
+ print(message)
46
+
47
+ def analyze_table(self, table_path: str) -> Dict[str, Any]:
48
+ """Analyze table structure and file statistics"""
49
+ delta_table = DeltaTable.forPath(self.spark, table_path)
50
+ detail = delta_table.detail().collect()[0]
51
+
52
+ file_stats_query = f"""
53
+ SELECT
54
+ COUNT(*) as num_files,
55
+ SUM(size) as total_bytes,
56
+ AVG(size) as avg_bytes,
57
+ MIN(size) as min_bytes,
58
+ MAX(size) as max_bytes,
59
+ STDDEV(size) as stddev_bytes
60
+ FROM delta.`{table_path}`
61
+ """
62
+
63
+ stats = self.spark.sql(file_stats_query).collect()[0]
64
+
65
+ return {
66
+ 'num_files': stats['num_files'],
67
+ 'total_size_mb': stats['total_bytes'] / (1024 * 1024) if stats['total_bytes'] else 0,
68
+ 'avg_file_size_mb': stats['avg_bytes'] / (1024 * 1024) if stats['avg_bytes'] else 0,
69
+ 'min_file_size_mb': stats['min_bytes'] / (1024 * 1024) if stats['min_bytes'] else 0,
70
+ 'max_file_size_mb': stats['max_bytes'] / (1024 * 1024) if stats['max_bytes'] else 0,
71
+ 'stddev_file_size_mb': stats['stddev_bytes'] / (1024 * 1024) if stats['stddev_bytes'] else 0,
72
+ 'partition_columns': detail.get('partitionColumns', [])
73
+ }
74
+
75
+ def recommend_zorder_columns(
76
+ self,
77
+ table_path: str,
78
+ max_columns: int = MAX_ZORDER_COLUMNS
79
+ ) -> List[str]:
80
+ """Recommend Z-ORDER columns based on column characteristics"""
81
+ df = self.spark.read.format("delta").load(table_path)
82
+ total_count = df.count()
83
+
84
+ if total_count == 0:
85
+ return []
86
+
87
+ recommendations = []
88
+ unsuitable_types = ['binary', 'array', 'map', 'struct']
89
+
90
+ for field in df.schema.fields:
91
+ col_name = field.name
92
+ col_type = field.dataType.typeName()
93
+
94
+ if col_type in unsuitable_types:
95
+ continue
96
+
97
+ distinct_count = df.select(col_name).distinct().count()
98
+ cardinality_ratio = distinct_count / total_count
99
+
100
+ if 0.1 <= cardinality_ratio <= 0.8:
101
+ score = 1 - abs(cardinality_ratio - 0.5) / 0.5
102
+ recommendations.append({
103
+ 'column': col_name,
104
+ 'score': score
105
+ })
106
+
107
+ recommendations.sort(key=lambda x: x['score'], reverse=True)
108
+ return [r['column'] for r in recommendations[:max_columns]]
109
+
110
+ def auto_optimize(
111
+ self,
112
+ table_path: str,
113
+ zorder_columns: Optional[List[str]] = None,
114
+ auto_zorder: bool = True,
115
+ dry_run: bool = False,
116
+ force: bool = False
117
+ ) -> OptimizationResult:
118
+ """Optimize Delta table with intelligent defaults"""
119
+ self._log(f"Analyzing table: {table_path}")
120
+ start_time = time.time()
121
+
122
+ before_stats = self.analyze_table(table_path)
123
+
124
+ self._log(f"Current state:")
125
+ self._log(f" Files: {before_stats['num_files']:,}")
126
+ self._log(f" Total size: {before_stats['total_size_mb']:.2f} MB")
127
+ self._log(f" Average file size: {before_stats['avg_file_size_mb']:.2f} MB")
128
+
129
+ reasons = []
130
+ if before_stats['num_files'] > 100:
131
+ reasons.append(f"High file count: {before_stats['num_files']} files")
132
+
133
+ if before_stats['avg_file_size_mb'] < self.target_file_size_mb * 0.5:
134
+ reasons.append(f"Small files detected: avg {before_stats['avg_file_size_mb']:.1f}MB")
135
+
136
+ if auto_zorder and zorder_columns is None:
137
+ self._log("\nAnalyzing columns for Z-ORDER...")
138
+ zorder_columns = self.recommend_zorder_columns(table_path)
139
+ if zorder_columns:
140
+ self._log(f" Recommended: {', '.join(zorder_columns)}")
141
+
142
+ if dry_run:
143
+ self._log("\nDry run mode - no changes made")
144
+ return OptimizationResult(
145
+ table_name=table_path,
146
+ files_before=before_stats['num_files'],
147
+ files_after=before_stats['num_files'],
148
+ size_before_mb=before_stats['total_size_mb'],
149
+ size_after_mb=before_stats['total_size_mb'],
150
+ duration_seconds=time.time() - start_time,
151
+ zorder_columns=zorder_columns,
152
+ recommendations=reasons,
153
+ files_removed=0,
154
+ compression_ratio=1.0
155
+ )
156
+
157
+ self._log("\nExecuting OPTIMIZE...")
158
+ delta_table = DeltaTable.forPath(self.spark, table_path)
159
+
160
+ if zorder_columns:
161
+ self._log(f" Z-ORDER by: {', '.join(zorder_columns)}")
162
+ delta_table.optimize().executeZOrderBy(zorder_columns)
163
+ else:
164
+ delta_table.optimize().executeCompaction()
165
+
166
+ after_stats = self.analyze_table(table_path)
167
+ duration = time.time() - start_time
168
+ files_removed = before_stats['num_files'] - after_stats['num_files']
169
+
170
+ self._log("\nOptimization complete:")
171
+ self._log(f" Files: {before_stats['num_files']:,} -> {after_stats['num_files']:,}")
172
+ self._log(f" Duration: {duration:.1f} seconds")
173
+
174
+ return OptimizationResult(
175
+ table_name=table_path,
176
+ files_before=before_stats['num_files'],
177
+ files_after=after_stats['num_files'],
178
+ size_before_mb=before_stats['total_size_mb'],
179
+ size_after_mb=after_stats['total_size_mb'],
180
+ duration_seconds=duration,
181
+ zorder_columns=zorder_columns,
182
+ recommendations=reasons,
183
+ files_removed=files_removed,
184
+ compression_ratio=before_stats['total_size_mb'] / after_stats['total_size_mb'] if after_stats['total_size_mb'] > 0 else 1.0
185
+ )
186
+
187
+ def batch_optimize(self, table_paths: List[str], **kwargs) -> List[OptimizationResult]:
188
+ """Optimize multiple tables"""
189
+ results = []
190
+ for i, table_path in enumerate(table_paths, 1):
191
+ self._log(f"\n[{i}/{len(table_paths)}] Processing: {table_path}")
192
+ try:
193
+ result = self.auto_optimize(table_path, **kwargs)
194
+ results.append(result)
195
+ except Exception as e:
196
+ self._log(f"Error: {str(e)}")
197
+ return results
@@ -0,0 +1,89 @@
1
+ from pyspark.sql import SparkSession, DataFrame
2
+ from delta.tables import DeltaTable
3
+ from typing import Dict, List, Any
4
+ from dataclasses import dataclass, asdict
5
+ import time
6
+
7
+
8
+ @dataclass
9
+ class ProfileResult:
10
+ """Results from performance profiling"""
11
+ operation_name: str
12
+ duration_seconds: float
13
+ rows_processed: int
14
+ bytes_processed: int
15
+ throughput_rows_per_sec: float
16
+ throughput_mb_per_sec: float
17
+
18
+ def to_dict(self) -> Dict[str, Any]:
19
+ return asdict(self)
20
+
21
+
22
+ class DeltaProfiler:
23
+ """Performance profiling for Delta Lake operations"""
24
+
25
+ def __init__(self, spark: SparkSession, verbose: bool = True):
26
+ self.spark = spark
27
+ self.verbose = verbose
28
+ self.results: List[ProfileResult] = []
29
+
30
+ def profile_read(
31
+ self,
32
+ table_path: str,
33
+ filter_expr: str = None
34
+ ) -> ProfileResult:
35
+ """Profile read operation performance"""
36
+ start_time = time.time()
37
+
38
+ df = self.spark.read.format("delta").load(table_path)
39
+
40
+ if filter_expr:
41
+ df = df.filter(filter_expr)
42
+
43
+ row_count = df.count()
44
+ duration = time.time() - start_time
45
+
46
+ delta_table = DeltaTable.forPath(self.spark, table_path)
47
+ detail = delta_table.detail().collect()[0]
48
+ total_bytes = detail.get('sizeInBytes', 0)
49
+
50
+ throughput_rows = row_count / duration if duration > 0 else 0
51
+ throughput_mb = (total_bytes / 1024 / 1024) / duration if duration > 0 else 0
52
+
53
+ result = ProfileResult(
54
+ operation_name=f"read:{table_path}",
55
+ duration_seconds=duration,
56
+ rows_processed=row_count,
57
+ bytes_processed=total_bytes,
58
+ throughput_rows_per_sec=throughput_rows,
59
+ throughput_mb_per_sec=throughput_mb
60
+ )
61
+
62
+ self.results.append(result)
63
+
64
+ if self.verbose:
65
+ print(f"\nProfiling Results:")
66
+ print(f" Duration: {duration:.2f}s")
67
+ print(f" Rows: {row_count:,}")
68
+ print(f" Throughput: {throughput_rows:,.0f} rows/sec")
69
+
70
+ return result
71
+
72
+ def get_summary(self) -> Dict[str, Any]:
73
+ """Get summary of all profiling results"""
74
+ if not self.results:
75
+ return {"message": "No profiling results available"}
76
+
77
+ total_duration = sum(r.duration_seconds for r in self.results)
78
+ total_rows = sum(r.rows_processed for r in self.results)
79
+
80
+ return {
81
+ 'num_operations': len(self.results),
82
+ 'total_duration_seconds': total_duration,
83
+ 'total_rows_processed': total_rows,
84
+ 'operations': [r.to_dict() for r in self.results]
85
+ }
86
+
87
+ def clear_results(self):
88
+ """Clear all stored profiling results"""
89
+ self.results.clear()
@@ -0,0 +1,22 @@
1
+ import math
2
+ from typing import Dict, Any
3
+
4
+
5
+ def format_bytes(bytes_val: float, precision: int = 2) -> str:
6
+ """Format bytes into human-readable string"""
7
+ if bytes_val == 0:
8
+ return "0 B"
9
+
10
+ units = ['B', 'KB', 'MB', 'GB', 'TB']
11
+ unit_index = int(math.floor(math.log(bytes_val, 1024)))
12
+ unit_index = min(unit_index, len(units) - 1)
13
+
14
+ value = bytes_val / math.pow(1024, unit_index)
15
+ return f"{value:.{precision}f} {units[unit_index]}"
16
+
17
+
18
+ def validate_table_path(table_path: str) -> bool:
19
+ """Validate Delta table path format"""
20
+ if not table_path:
21
+ raise ValueError("Table path cannot be empty")
22
+ return True
@@ -0,0 +1,15 @@
1
+ """Basic tests for delta-lake-utils"""
2
+
3
+
4
+ def test_import():
5
+ """Test that package can be imported"""
6
+ from delta_utils import DeltaOptimizer, DeltaHealthChecker
7
+ assert DeltaOptimizer is not None
8
+ assert DeltaHealthChecker is not None
9
+
10
+
11
+ def test_version():
12
+ """Test version is defined"""
13
+ import delta_utils
14
+ assert hasattr(delta_utils, '__version__')
15
+ assert delta_utils.__version__ == "1.0.0"