I'm focused on the fundamental building blocks now. Source, transform, and load are the key phases, and I'm identifying the key components within each. Considering different source types is crucial.
Mapping the Data Flow
The CSV source is a go. Now I'm detailing the transform step, including data cleaning and filtering with pandas. SQLite will be the initial destination, as requested, with plans for SQLAlchemy integration to support other databases. Logging is essential for monitoring and debugging. I'm building a random CSV generator to test the pipeline.
Outlining the Structure
I'm now zeroing in on the pipeline's structure, focusing on the class design. Considering an ETLPipeline class with extract, transform, load, and run methods. Thinking about the data flow within these methods and the required error handling at each stage.
Detailing the Implementation
Now I'm delving deeper into the code, sketching out functions for data extraction, transformation (cleaning, calculations), and loading into SQLite. Using the object-oriented approach is paying off; it's making the pipeline logic more modular and easier to debug. I'm focusing on exception handling and logging now.
Developing the Implementation Details
Now I'm designing the code with all the parts. Using a class-based structure for modularity. Planning for a CSV extractor, and transformation including column renaming, calculations, and data cleaning, then loading it into SQLite via to_sql. I will create dummy data to make the code runnable and integrate logging and error handling.
Here is a robust, modular implementation of an ETL pipeline using Python.
We will use the industry-standard library pandas for data manipulation and SQLAlchemy for database interaction. For this example, we will use SQLite because it requires no server setup, but the code is designed to work with PostgreSQL, MySQL, or SQL Server often by changing just one line of connection code.
Prerequisites
You will need to install the following libraries:
bash
pip install pandas sqlalchemy
The Complete ETL Pipeline Code
You can save this code to a file (e.g., etl_pipeline.py) and run it. It includes a setup step that generates dummy data so the script works immediately.
python
import pandas as pd
from sqlalchemy import create_engine
import logging
import os
from datetime import datetime
# 1. Configure Logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("etl_pipeline.log"),
logging.StreamHandler()
]
)
class ETLPipeline:
def __init__(self, source_file, db_connection_string, table_name):
self.source_file = source_file
self.db_engine = create_engine(db_connection_string)
self.table_name = table_name
self.data = None
def extract(self):
"""
EXTRACT: Read data from the source (CSV file).
"""
logging.info(f"Starting extraction from {self.source_file}...")
try:
if not os.path.exists(self.source_file):
raise FileNotFoundError(f"File {self.source_file} not found.")
self.data = pd.read_csv(self.source_file)
logging.info(f"Extraction successful. Rows extracted: {len(self.data)}")
except Exception as e:
logging.error(f"Extraction failed: {e}")
raise
def transform(self):
"""
TRANSFORM: Clean and process the data.
Logic:
1. Drop rows with missing values.
2. Convert date strings to datetime objects.
3. Calculate 'Total Revenue' (Price * Quantity).
4. Filter out transactions with 0 or negative quantity.
"""
logging.info("Starting transformation...")
try:
if self.data is None:
raise ValueError("No data to transform.")
original_count = len(self.data)
# 1. Drop Nulls
self.data.dropna(inplace=True)
# 2. Convert Date Column
if 'date' in self.data.columns:
self.data['date'] = pd.to_datetime(self.data['date'])
# 3. Data Type Conversion & Filtering
self.data['price'] = pd.to_numeric(self.data['price'])
self.data['quantity'] = pd.to_numeric(self.data['quantity'])
# Filter: Keep only positive quantities
self.data = self.data[self.data['quantity'] > 0]
# 4. Create new derived column
self.data['total_revenue'] = self.data['price'] * self.data['quantity']
# 5. Normalize text (e.g., Uppercase product names)
self.data['product_name'] = self.data['product_name'].str.upper().str.strip()
rows_dropped = original_count - len(self.data)
logging.info(f"Transformation successful. Rows dropped: {rows_dropped}. Final count: {len(self.data)}")
except Exception as e:
logging.error(f"Transformation failed: {e}")
raise
def load(self):
"""
LOAD: Write the data into the database.
"""
logging.info(f"Starting load into table '{self.table_name}'...")
try:
# if_exists='append' adds to existing data
# if_exists='replace' drops table and recreates it
self.data.to_sql(
self.table_name,
con=self.db_engine,
if_exists='replace',
index=False
)
logging.info("Load successful.")
except Exception as e:
logging.error(f"Load failed: {e}")
raise
def run_pipeline(self):
"""
Orchestrator method to run the ETL process sequentially.
"""
try:
self.extract()
self.transform()
self.load()
logging.info("ETL Pipeline completed successfully.")
except Exception as e:
logging.error("ETL Pipeline terminated with errors.")
# --- HELPER FUNCTION TO CREATE DUMMY DATA ---
def create_dummy_csv(filename):
data = {
'date': ['2023-10-01', '2023-10-02', '2023-10-02', '2023-10-03', None],
'product_name': ['Widget A', ' Widget B ', 'Widget A', 'Widget C', 'Widget A'],
'price': [10.00, 20.50, 10.00, 15.75, 10.00],
'quantity': [5, 2, -1, 10, 5] # Includes a negative value to test logic
}
df = pd.DataFrame(data)
df.to_csv(filename, index=False)
print(f"Dummy data created: {filename}")
# --- MAIN EXECUTION ---
if __name__ == "__main__":
# Configuration
SOURCE_FILE = 'sales_data.csv'
DB_CONNECTION = 'sqlite:///warehouse.db' # Creates a local SQLite file
TABLE_NAME = 'daily_sales'
# 1. Setup: Create a dummy CSV file to read
create_dummy_csv(SOURCE_FILE)
# 2. Initialize Pipeline
etl = ETLPipeline(SOURCE_FILE, DB_CONNECTION, TABLE_NAME)
# 3. Run Pipeline
etl.run_pipeline()
# 4. Verification (Optional: Read back from DB to prove it worked)
print("\n--- Verifying Database Data ---")
engine = create_engine(DB_CONNECTION)
result = pd.read_sql(f"SELECT * FROM {TABLE_NAME}", engine)
print(result)
How it works
1. Extract (The extract method)
Input: A CSV file (sales_data.csv).
Library: Uses pd.read_csv.
Logic: It checks if the file exists and loads it into a pandas DataFrame (self.data).
2. Transform (The transform method)
Logic: This simulates real-world messy data cleaning:
Cleaning: Removes rows where data (NaN) is missing.
Formatting: Converts strings to DateTime objects using pd.to_datetime.
Standardizing: Trims whitespace and upper-cases strings (Widget B becomes WIDGET B).
Filtering: Removes invalid business logic (rows where quantity is less than 0).
Calculation: Creates a new column total_revenue (Price × Quantity).
3. Load (The load method)
Input: The cleaned DataFrame.
Library: Uses df.to_sql.
Connection: It uses SQLAlchemy. We used SQLite (sqlite:///warehouse.db), but to use PostgreSQL, you would simply change the connection string to:
postgresql://username:password@localhost:5432/mydatabase
Behavior: The if_exists='replace' argument drops the table and recreates it. In a daily pipeline, you might use 'append' instead.
4. Logging
Instead of just using print(), we use Python's logging module. This is crucial for production pipelines to track errors, timings, and row counts.
Scaling this for Production
If you move this to a production environment, you would make the following changes:
Scheduling: Do not run the script manually. Use a tool like Apache Airflow, Cron, or Prefect to schedule the etl.run_pipeline() method to run every morning.
Secrets: Do not hardcode database credentials. Use environment variables (os.getenv('DB_PASSWORD')).
Batching: If the CSV is 10 GBs, pd.read_csv will crash your RAM. You would need to use chunksize=10000 in pandas to process the file in smaller pieces.