<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Data_Eng]]></title><description><![CDATA[Data_Eng]]></description><link>https://abhi1213data.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:15:05 GMT</lastBuildDate><atom:link href="https://abhi1213data.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Forever Retail: Building an End-to-End Modern Data Engineering Pipeline with S3, Snowflake, & dbt]]></title><description><![CDATA[A complete practical implementation, from raw CSVs to automated ingestion, dimensional modelling, incremental pipelines, snapshots, prod-ready design]]></description><link>https://abhi1213data.hashnode.dev/forever-retail-building-an-end-to-end-modern-data-engineering-pipeline-with-s3-snowflake-and-dbt</link><guid isPermaLink="true">https://abhi1213data.hashnode.dev/forever-retail-building-an-end-to-end-modern-data-engineering-pipeline-with-s3-snowflake-and-dbt</guid><category><![CDATA[#CloudDataEngineering]]></category><category><![CDATA[#S3toSnowflake]]></category><category><![CDATA[#ModernDataStack]]></category><category><![CDATA[data-engineering]]></category><category><![CDATA[snowflake]]></category><category><![CDATA[dbt]]></category><category><![CDATA[etl-pipeline]]></category><category><![CDATA[data-modeling]]></category><category><![CDATA[analytics engineering]]></category><category><![CDATA[#DataPipelines]]></category><category><![CDATA[Retail Analytics Market Trends]]></category><dc:creator><![CDATA[Abhishek Kumar]]></dc:creator><pubDate>Sat, 15 Nov 2025 14:33:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1763216809958/fbda87c0-5867-4337-8033-3e143d385827.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-part-1-introduction-project-overview-architecture-diagram-explanation"><mark>Part 1 (Introduction + Project Overview + Architecture Diagram explanation)</mark></h1>
<h2 id="heading-1-introduction"><strong>1. Introduction</strong></h2>
<p>The <strong>Forever Retail Data Engineering Project</strong> is a fully functional, production-grade pipeline designed to showcase:</p>
<ul>
<li><p>cloud data ingestion</p>
</li>
<li><p>scalable warehouse design</p>
</li>
<li><p>proper modeling (RAW → STAGING → MART)</p>
</li>
<li><p>incremental pipelines</p>
</li>
<li><p>Snowflake automation (tasks + pipes)</p>
</li>
<li><p>Slowly Changing Dimensions (Snapshots)</p>
</li>
<li><p>dbt end-to-end project running from your local machine</p>
</li>
<li><p>versioned file ingestion from S3 using regex patterns</p>
</li>
<li><p>historical fact tables</p>
</li>
</ul>
<p>Whether you are preparing for a Data Engineering interview or building your portfolio, this project demonstrates <strong>real-world design patterns</strong> used by modern teams.</p>
<h2 id="heading-2-problem-statement"><strong>2. Problem Statement</strong></h2>
<p>Forever Retail is a fictional retail company that wants to modernize its data platform.<br />Their requirements:</p>
<ol>
<li><strong>All raw CSV files (customers, products, stores, sales) arrive daily in an S3 bucket</strong>, with unique versioned names like: &lt;customers&gt;_&lt;DD_MM_YY&gt;_&lt;version&gt;</li>
</ol>
<pre><code class="lang-python">customers_12_11_25_01.csv
products_12_11_25_01.csv
sales_12_11_25_01.csv
</code></pre>
<ol start="2">
<li><p>Snowflake must:</p>
<ul>
<li><p>automatically ingest new CSVs into RAW tables</p>
</li>
<li><p>maintain a historical repository</p>
</li>
<li><p>preserve ingestion timestamps</p>
</li>
</ul>
</li>
<li><p>dbt must:</p>
<ul>
<li><p>standardize &amp; clean staging tables</p>
</li>
<li><p>build proper dimension tables</p>
</li>
<li><p>build a fact table with all business logic</p>
</li>
<li><p>handle incremental pipeline updates</p>
</li>
<li><p>generate a clean lineage graph</p>
</li>
</ul>
</li>
<li><p>The pipeline must scale without manual triggers.</p>
</li>
</ol>
<h2 id="heading-3-high-level-architecture"><strong>3. High-Level Architecture</strong></h2>
<p>Here is the complete Forever Retail architecture:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763211834274/42062c20-19ed-41fc-bb4e-179b5a9c1136.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-flow"><strong>Flow:</strong></h3>
<h3 id="heading-s3-bucket-snowflake-external-stage-auto-ingestion-pipes-raw-tables-dbtraw-staging-dimensions-facts-analytics">S3 Bucket → Snowflake External Stage → Auto-Ingestion Pipes → RAW Tables→ DBT_RAW → STAGING → DIMENSIONS → FACTS → Analytics</h3>
<p>This results in:</p>
<ul>
<li><p>Fully automated ingestion</p>
</li>
<li><p>Incremental transformation</p>
</li>
<li><p>Clean production-ready marts</p>
</li>
<li><p>Historical &amp; latest views</p>
</li>
<li><p>Fast warehouse optimization</p>
</li>
</ul>
<h2 id="heading-4-core-components-amp-why-they-matter"><strong>4. Core Components &amp; Why They Matter</strong></h2>
<h3 id="heading-41-s3-bucket-landing-zone"><strong>4.1 S3 Bucket (Landing Zone)</strong></h3>
<p>This is where Forever Retail uploads daily CSV files.<br />Files are <strong>versioned</strong> using a naming pattern:</p>
<pre><code class="lang-python">&lt;entity&gt;_&lt;dd_mm_yy&gt;_&lt;sequence&gt;.csv
Example: customers_13_11_25_02.csv
</code></pre>
<p>This helps Snowflake identify only the new files.</p>
<h3 id="heading-42-snowflake-external-stage-awsstage"><strong>4.2 Snowflake External Stage (AWS_STAGE)</strong></h3>
<p>The stage acts as the connection between Snowflake and S3.</p>
<p>It includes:</p>
<ul>
<li><p>S3 bucket path</p>
</li>
<li><p>Credentials (masked in this article)</p>
</li>
<li><p>CSV format details</p>
</li>
</ul>
<p>Snowflake’s stage maintains metadata like file names and timestamps.</p>
<h3 id="heading-43-snowflake-pipes-auto-ingestion"><strong>4.3 Snowflake Pipes (Auto-Ingestion)</strong></h3>
<p>Pipes allow continuous ingestion from S3 → Snowflake.</p>
<p>They use regex patterns to ingest only the correct files into the correct tables:</p>
<pre><code class="lang-python">customers_*.csv  → RAW.CUSTOMERS  
products_*.csv   → RAW.PRODUCTS  
sales_*.csv      → RAW.SALES
stores_*.csv     → RAW.STORES
</code></pre>
<p>They eliminate the need for Airflow or manual runs.</p>
<h3 id="heading-44-snowflake-tasks"><strong>4.4 Snowflake Tasks</strong></h3>
<p>Tasks run on a schedule (every 10 minutes) and trigger:</p>
<ul>
<li><p><code>ALTER STAGE</code> to rescan new S3 files</p>
</li>
<li><p><code>ALTER PIPE … REFRESH</code> to load newly detected files</p>
</li>
<li><p>update a FILE_TRACKER table for monitoring</p>
</li>
<li><p>logs history of ingested files</p>
</li>
</ul>
<p>This is your automation layer inside Snowflake.</p>
<h3 id="heading-45-raw-layer"><strong>4.5 RAW Layer</strong></h3>
<p>The RAW schema holds your <strong>original data</strong>, with:</p>
<ul>
<li><p>No business logic</p>
</li>
<li><p>No transformations</p>
</li>
<li><p>Only ingestion + standard datatypes</p>
</li>
<li><p>A new <code>LOAD_TS</code> column added by Snowflake</p>
</li>
</ul>
<p>This is your <strong>source of truth</strong>, like a Data Lake inside Snowflake.</p>
<h3 id="heading-46-dbtraw-layer-incremental"><strong>4.6 DBT_RAW Layer (Incremental)</strong></h3>
<p>Only <strong>new records</strong> flow from RAW → DBT_RAW.</p>
<p>This layer ensures:</p>
<ul>
<li><p>deduplication</p>
</li>
<li><p>type casting</p>
</li>
<li><p>proper formatting</p>
</li>
<li><p>incremental logic</p>
</li>
</ul>
<h3 id="heading-47-staging-layer"><strong>4.7 STAGING Layer</strong></h3>
<p>Acts as cleaned source tables for the marts.</p>
<p>Differences:</p>
<ul>
<li><p>STAGING fetches only newest records from DBT_RAW</p>
</li>
<li><p>Except STG_SALES → it keeps entire historical data<br />  (because there is no DIM for sales)</p>
</li>
</ul>
<h3 id="heading-48-mart-layer-dimensions-facts"><strong>4.8 MART Layer (Dimensions + Facts)</strong></h3>
<ul>
<li><p><code>dim_customers</code></p>
</li>
<li><p><code>dim_products</code></p>
</li>
<li><p><code>dim_stores</code></p>
</li>
<li><p><code>dim_date</code></p>
</li>
<li><p><code>fct_sales</code></p>
</li>
</ul>
<h3 id="heading-49-snapshots-optional-but-implemented"><strong>4.9 Snapshots (Optional but Implemented)</strong></h3>
<p>For customer tracking over time:</p>
<ul>
<li><p>track changes in name, city, gender, etc.</p>
</li>
<li><p>historical SCD Type-2 behavior using dbt snapshots</p>
</li>
</ul>
<h2 id="heading-5-development-setup-local-machine-vs-code-venv"><strong>5. Development Setup (Local Machine + VS Code + venv)</strong></h2>
<p>This section will include:</p>
<ul>
<li><p>Creating virtual environment</p>
</li>
<li><p>Installing dbt-snowflake</p>
</li>
<li><p>Creating <code>profiles.yml</code></p>
</li>
<li><p>Directory structure for the project</p>
</li>
<li><p>Connecting VS Code to Snowflake</p>
</li>
</ul>
<p>You will get full command blocks when I start writing the next part.</p>
<hr />
<h1 id="heading-part-2-cloud-setup-s3-snowflake-automated-ingestion-layer"><mark>Part 2 — Cloud Setup: S3 + Snowflake + Automated Ingestion Layer</mark></h1>
<p>Now, we set up the <strong>entire ingestion pipeline</strong>:</p>
<ul>
<li><p>AWS S3 bucket</p>
</li>
<li><p>Snowflake RAW tables</p>
</li>
<li><p>File formats</p>
</li>
<li><p>External stage connected to S3</p>
</li>
<li><p>Four Snowflake Pipes (customers/products/stores/sales)</p>
</li>
<li><p>One scheduled Task to keep ingestion automated</p>
</li>
<li><p>File tracker table</p>
</li>
<li><p>Stored procedure to register file history</p>
</li>
</ul>
<p>This is the foundation of your end-to-end data engineering pipeline.</p>
<hr />
<h2 id="heading-1-aws-s3-setup"><strong>1. AWS S3 Setup</strong></h2>
<h3 id="heading-11-create-an-s3-bucket"><strong>1.1 Create an S3 bucket</strong></h3>
<p>Name it something like: forever-retail-bucket</p>
<p>Keep the settings simple:</p>
<ul>
<li><p>No versioning needed</p>
</li>
<li><p>Public access block enabled</p>
</li>
<li><p>Server-side encryption optional</p>
</li>
</ul>
<p>Inside the bucket, you will upload files like:</p>
<pre><code class="lang-plaintext">customers_13_11_25_01.csv
products_13_11_25_01.csv
sales_13_11_25_01.csv
stores_13_11_25_01.csv
</code></pre>
<h3 id="heading-12-create-an-iam-user-for-snowflake"><strong>1.2 Create an IAM User for Snowflake</strong></h3>
<p>Create a new user:</p>
<pre><code class="lang-python">snowflake_s3_access
</code></pre>
<p>Attach policy:</p>
<pre><code class="lang-python">AmazonS3ReadOnlyAccess
</code></pre>
<p>Generate:</p>
<ul>
<li><p>Access Key ID</p>
</li>
<li><p>Secret Access Key</p>
</li>
</ul>
<h2 id="heading-2-snowflake-setup"><strong>2. Snowflake Setup</strong></h2>
<p>We now set up the RAW environment inside Snowflake.</p>
<h3 id="heading-21-create-database-schema-role-and-user"><strong>2.1 Create Database, Schema, Role, and User</strong></h3>
<pre><code class="lang-sql"><span class="hljs-comment">--  STEP 0: Set context and grant role</span>
<span class="hljs-keyword">USE</span> <span class="hljs-keyword">ROLE</span> ACCOUNTADMIN;

<span class="hljs-comment">--  STEP 1: Create database and schemas</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> <span class="hljs-keyword">IF</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">EXISTS</span> RETAIL;
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">SCHEMA</span> <span class="hljs-keyword">IF</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">EXISTS</span> RETAIL.RAW;
<span class="hljs-keyword">USE</span> <span class="hljs-keyword">DATABASE</span> RETAIL;

<span class="hljs-comment">--  STEP 2: Create role &amp; user for dbt</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">ROLE</span> <span class="hljs-keyword">IF</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">EXISTS</span> RETAIL_TRANSFORM;
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> ACCOUNTADMIN;

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">USER</span> <span class="hljs-keyword">IF</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">EXISTS</span> dbt_user 
    <span class="hljs-keyword">PASSWORD</span> = <span class="hljs-string">'**************'</span>
    DEFAULT_ROLE = RETAIL_TRANSFORM
    DEFAULT_WAREHOUSE = <span class="hljs-string">'COMPUTE_WH'</span>
    MUST_CHANGE_PASSWORD = <span class="hljs-literal">FALSE</span>;

<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM <span class="hljs-keyword">TO</span> <span class="hljs-keyword">USER</span> dbt_user;

<span class="hljs-comment">--  STEP 3: Grant warehouse permissions</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">USAGE</span> <span class="hljs-keyword">ON</span> WAREHOUSE COMPUTE_WH <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;

<span class="hljs-comment">--  STEP 4: Grant DBT + RAW schema permissions</span>

<span class="hljs-comment">--  [Critical] Allow dbt to manage downstream schemas (STAGING, MART, etc.)</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">DATABASE</span> RETAIL <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;

<span class="hljs-comment">--  Read-only access to RAW schema (dbt should not write here)</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">USAGE</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">TABLES</span> <span class="hljs-keyword">IN</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">ON</span> FUTURE <span class="hljs-keyword">TABLES</span> <span class="hljs-keyword">IN</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;

<span class="hljs-comment">--  Allow table creation &amp; modification in RAW (for automation and tasks)</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">MODIFY</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;

<span class="hljs-comment">--  Allow all data operations on RAW tables</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">PRIVILEGES</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">TABLES</span> <span class="hljs-keyword">IN</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">PRIVILEGES</span> <span class="hljs-keyword">ON</span> FUTURE <span class="hljs-keyword">TABLES</span> <span class="hljs-keyword">IN</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;

<span class="hljs-comment">--  Allow stage usage (for S3 → Snowflake ingestion)</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">CREATE</span> STAGE <span class="hljs-keyword">ON</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">USAGE</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">ALL</span> STAGES <span class="hljs-keyword">IN</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;


<span class="hljs-comment">--  STEP 5: Grant Tasks and Procedure Execution</span>
<span class="hljs-comment">--  Allow the role to run tasks across account</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">EXECUTE</span> TASK <span class="hljs-keyword">ON</span> <span class="hljs-keyword">ACCOUNT</span> <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;

<span class="hljs-comment">--  Allow execution of stored procedures in RAW schema</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">USAGE</span>, <span class="hljs-keyword">EXECUTE</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">ALL</span> PROCEDURES <span class="hljs-keyword">IN</span> <span class="hljs-keyword">SCHEMA</span> RETAIL.RAW <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;

<span class="hljs-comment">--  Explicitly allow execution of specific procedures (optional)</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">EXECUTE</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">PROCEDURE</span> RETAIL.RAW.SP_TRIGGER_PIPES() <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">EXECUTE</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">PROCEDURE</span> RETAIL.RAW.SP_UPDATE_FILE_TRACKER() <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;

<span class="hljs-comment">--  Ensure it can use the warehouse for task execution</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">USAGE</span> <span class="hljs-keyword">ON</span> WAREHOUSE COMPUTE_WH <span class="hljs-keyword">TO</span> <span class="hljs-keyword">ROLE</span> RETAIL_TRANSFORM;
</code></pre>
<h2 id="heading-3-create-raw-tables"><strong>3. Create RAW Tables</strong></h2>
<h3 id="heading-each-table-includes-a-loadts-column-to-store-ingestion-timestamp">Each table includes a LOAD_TS column to store ingestion timestamp.</h3>
<pre><code class="lang-sql"><span class="hljs-keyword">USE</span> <span class="hljs-keyword">DATABASE</span> RETAIL;
<span class="hljs-keyword">USE</span> <span class="hljs-keyword">SCHEMA</span> <span class="hljs-keyword">RAW</span>;

<span class="hljs-keyword">use</span> <span class="hljs-keyword">role</span> retail_transform;

<span class="hljs-comment">-- 1) FILE FORMAT (shared)</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">FILE</span> <span class="hljs-keyword">FORMAT</span> RETAIL.RAW.CSV_FMT
  <span class="hljs-keyword">TYPE</span> = <span class="hljs-string">'CSV'</span>
  FIELD_OPTIONALLY_ENCLOSED_BY = <span class="hljs-string">'"'</span>
  SKIP_HEADER = <span class="hljs-number">1</span>
  <span class="hljs-keyword">DATE_FORMAT</span> = <span class="hljs-string">'DD-MM-YYYY'</span>
  ERROR_ON_COLUMN_COUNT_MISMATCH = <span class="hljs-literal">FALSE</span>
  TRIM_SPACE = <span class="hljs-literal">TRUE</span>
  NULL_IF = (<span class="hljs-string">''</span>, <span class="hljs-string">'NULL'</span>);


<span class="hljs-comment">-- 2) Create RAW tables</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">TABLE</span> RAW.SALES (
  SALE_ID <span class="hljs-built_in">INT</span>,
  STORE_ID <span class="hljs-built_in">INT</span>,
  CUSTOMER_ID <span class="hljs-built_in">INT</span>,
  PRODUCT_ID <span class="hljs-built_in">INT</span>,
  QUANTITY <span class="hljs-built_in">INT</span>,
  AMOUNT <span class="hljs-built_in">FLOAT</span>,
  SALE_DATE <span class="hljs-built_in">DATE</span>,
  LOAD_TS TIMESTAMP_NTZ
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">TABLE</span> RAW.CUSTOMERS (
  CUSTOMER_ID <span class="hljs-built_in">INT</span>,
  <span class="hljs-keyword">NAME</span> <span class="hljs-keyword">STRING</span>,
  GENDER <span class="hljs-keyword">STRING</span>,
  AGE <span class="hljs-built_in">INT</span>,
  CITY <span class="hljs-keyword">STRING</span>,
  SIGNUP_DATE <span class="hljs-built_in">DATE</span>,
  LOAD_TS TIMESTAMP_NTZ
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">TABLE</span> RAW.PRODUCTS (
  PRODUCT_ID <span class="hljs-built_in">INT</span>,
  PRODUCT_NAME <span class="hljs-keyword">STRING</span>,
  <span class="hljs-keyword">CATEGORY</span> <span class="hljs-keyword">STRING</span>,
  PRICE <span class="hljs-built_in">FLOAT</span>,
  BRAND <span class="hljs-keyword">STRING</span>,
  LOAD_TS TIMESTAMP_NTZ
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">TABLE</span> RAW.STORES (
  STORE_ID <span class="hljs-built_in">INT</span>,
  STORE_NAME <span class="hljs-keyword">STRING</span>,
  CITY <span class="hljs-keyword">STRING</span>,
  REGION <span class="hljs-keyword">STRING</span>,
  MANAGER_NAME <span class="hljs-keyword">STRING</span>,
  LOAD_TS TIMESTAMP_NTZ
);
</code></pre>
<h2 id="heading-4-create-a-file-format-shared-by-all-pipes"><strong>4. Create a FILE FORMAT (shared by all pipes)</strong></h2>
<pre><code class="lang-sql"><span class="hljs-comment">-- 1) FILE FORMAT (shared)</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">FILE</span> <span class="hljs-keyword">FORMAT</span> RETAIL.RAW.CSV_FMT
  <span class="hljs-keyword">TYPE</span> = <span class="hljs-string">'CSV'</span>
  FIELD_OPTIONALLY_ENCLOSED_BY = <span class="hljs-string">'"'</span>
  SKIP_HEADER = <span class="hljs-number">1</span>
  <span class="hljs-keyword">DATE_FORMAT</span> = <span class="hljs-string">'DD-MM-YYYY'</span>
  ERROR_ON_COLUMN_COUNT_MISMATCH = <span class="hljs-literal">FALSE</span>
  TRIM_SPACE = <span class="hljs-literal">TRUE</span>
  NULL_IF = (<span class="hljs-string">''</span>, <span class="hljs-string">'NULL'</span>);
</code></pre>
<h2 id="heading-5-create-external-stage-s3-snowflake"><strong>5. Create External Stage (S3 → Snowflake)</strong></h2>
<pre><code class="lang-python">CREATE OR REPLACE STAGE RETAIL.RAW.AWS_STAGE
URL = <span class="hljs-string">'s3://****************'</span>
CREDENTIALS = (
  AWS_KEY_ID = <span class="hljs-string">'***************'</span>
  AWS_SECRET_KEY = <span class="hljs-string">'***************'</span>
)
FILE_FORMAT = (FORMAT_NAME = <span class="hljs-string">'RETAIL.RAW.CSV_FMT'</span>);
</code></pre>
<p>This stage allows Snowflake to read S3 files directly.</p>
<h2 id="heading-6-auto-ingestion-using-snowflake-pipes"><strong>6. Auto-Ingestion Using Snowflake Pipes</strong></h2>
<p>Each pipe listens for new files matching a pattern.</p>
<h3 id="heading-61-customers-pipe"><strong>6.1 Customers Pipe</strong></h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- Customers</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">PIPE</span> RETAIL.RAW.PIPE_CUSTOMERS <span class="hljs-keyword">AS</span>
COPY <span class="hljs-keyword">INTO</span> RETAIL.RAW.CUSTOMERS (CUSTOMER_ID, <span class="hljs-keyword">NAME</span>, GENDER, AGE, CITY, SIGNUP_DATE, LOAD_TS)
<span class="hljs-keyword">FROM</span> (
  <span class="hljs-keyword">SELECT</span>
    $<span class="hljs-number">1</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">2</span>::<span class="hljs-keyword">STRING</span>,
    $<span class="hljs-number">3</span>::<span class="hljs-keyword">STRING</span>,
    $<span class="hljs-number">4</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">5</span>::<span class="hljs-keyword">STRING</span>,
    TRY_TO_DATE($<span class="hljs-number">6</span>, <span class="hljs-string">'DD-MM-YYYY'</span>),
    <span class="hljs-keyword">CURRENT_TIMESTAMP</span>()
  <span class="hljs-keyword">FROM</span> @RETAIL.RAW.AWS_STAGE (PATTERN =&gt; <span class="hljs-string">'.*customers_.*\\.csv'</span>)
)
FILE_FORMAT = (FORMAT_NAME = <span class="hljs-string">'RETAIL.RAW.CSV_FMT'</span>)
ON_ERROR = <span class="hljs-string">'CONTINUE'</span>;
</code></pre>
<h3 id="heading-62-products-pipe"><strong>6.2 Products Pipe</strong></h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- Products</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">PIPE</span> RETAIL.RAW.PIPE_PRODUCTS <span class="hljs-keyword">AS</span>
COPY <span class="hljs-keyword">INTO</span> RETAIL.RAW.PRODUCTS (PRODUCT_ID, PRODUCT_NAME, <span class="hljs-keyword">CATEGORY</span>, PRICE, BRAND, LOAD_TS)
<span class="hljs-keyword">FROM</span> (
  <span class="hljs-keyword">SELECT</span>
    $<span class="hljs-number">1</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">2</span>::<span class="hljs-keyword">STRING</span>,
    $<span class="hljs-number">3</span>::<span class="hljs-keyword">STRING</span>,
    $<span class="hljs-number">4</span>::<span class="hljs-built_in">FLOAT</span>,
    $<span class="hljs-number">5</span>::<span class="hljs-keyword">STRING</span>,
    <span class="hljs-keyword">CURRENT_TIMESTAMP</span>()
  <span class="hljs-keyword">FROM</span> @RETAIL.RAW.AWS_STAGE (PATTERN =&gt; <span class="hljs-string">'.*products_.*\\.csv'</span>)
)
FILE_FORMAT = (FORMAT_NAME = <span class="hljs-string">'RETAIL.RAW.CSV_FMT'</span>)
ON_ERROR = <span class="hljs-string">'CONTINUE'</span>;
</code></pre>
<h3 id="heading-63-stores-pipe"><strong>6.3 Stores Pipe</strong></h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- Stores</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">PIPE</span> RETAIL.RAW.PIPE_STORES <span class="hljs-keyword">AS</span>
COPY <span class="hljs-keyword">INTO</span> RETAIL.RAW.STORES (STORE_ID, STORE_NAME, CITY, REGION, MANAGER_NAME, LOAD_TS)
<span class="hljs-keyword">FROM</span> (
  <span class="hljs-keyword">SELECT</span>
    $<span class="hljs-number">1</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">2</span>::<span class="hljs-keyword">STRING</span>,
    $<span class="hljs-number">3</span>::<span class="hljs-keyword">STRING</span>,
    $<span class="hljs-number">4</span>::<span class="hljs-keyword">STRING</span>,
    $<span class="hljs-number">5</span>::<span class="hljs-keyword">STRING</span>,
    <span class="hljs-keyword">CURRENT_TIMESTAMP</span>()
  <span class="hljs-keyword">FROM</span> @RETAIL.RAW.AWS_STAGE (PATTERN =&gt; <span class="hljs-string">'.*stores_.*\\.csv'</span>)
)
FILE_FORMAT = (FORMAT_NAME = <span class="hljs-string">'RETAIL.RAW.CSV_FMT'</span>)
ON_ERROR = <span class="hljs-string">'CONTINUE'</span>;
</code></pre>
<h3 id="heading-64-sales-pipe"><strong>6.4 Sales Pipe</strong></h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- Sales</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">PIPE</span> RETAIL.RAW.PIPE_SALES <span class="hljs-keyword">AS</span>
COPY <span class="hljs-keyword">INTO</span> RETAIL.RAW.SALES (SALE_ID, STORE_ID, CUSTOMER_ID, PRODUCT_ID, QUANTITY, AMOUNT, SALE_DATE, LOAD_TS)
<span class="hljs-keyword">FROM</span> (
  <span class="hljs-keyword">SELECT</span>
    $<span class="hljs-number">1</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">2</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">3</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">4</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">5</span>::<span class="hljs-built_in">NUMBER</span>,
    $<span class="hljs-number">6</span>::<span class="hljs-built_in">FLOAT</span>,
    TRY_TO_DATE($<span class="hljs-number">7</span>, <span class="hljs-string">'DD-MM-YYYY'</span>),
    <span class="hljs-keyword">CURRENT_TIMESTAMP</span>()
  <span class="hljs-keyword">FROM</span> @RETAIL.RAW.AWS_STAGE (PATTERN =&gt; <span class="hljs-string">'.*sales_.*\\.csv'</span>)
)
FILE_FORMAT = (FORMAT_NAME = <span class="hljs-string">'RETAIL.RAW.CSV_FMT'</span>)
ON_ERROR = <span class="hljs-string">'CONTINUE'</span>;
</code></pre>
<h2 id="heading-7-automation-scheduled-task"><strong>7. Automation: Scheduled Task</strong></h2>
<p>The task refreshes the stage and pipes every 10 minutes.</p>
<h3 id="heading-71-stored-procedure-to-trigger-pipes"><strong>7.1 Stored Procedure to Trigger Pipes</strong></h3>
<pre><code class="lang-sql"><span class="hljs-comment">--Simple procedure to refresh the stage and refresh each pipe (called by the task)</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">PROCEDURE</span> RETAIL.RAW.SP_TRIGGER_PIPES()
<span class="hljs-keyword">RETURNS</span> <span class="hljs-keyword">STRING</span>
<span class="hljs-keyword">LANGUAGE</span> <span class="hljs-keyword">SQL</span>
<span class="hljs-keyword">EXECUTE</span> <span class="hljs-keyword">AS</span> CALLER
<span class="hljs-keyword">AS</span>
$$
<span class="hljs-keyword">BEGIN</span>
  <span class="hljs-comment">-- ensure Snowflake sees the most recent S3 files</span>
  <span class="hljs-keyword">ALTER</span> STAGE RETAIL.RAW.AWS_STAGE <span class="hljs-keyword">REFRESH</span>;

  <span class="hljs-comment">-- Kick each pipe to check and ingest new files that match its pattern</span>
  <span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">PIPE</span> RETAIL.RAW.PIPE_CUSTOMERS <span class="hljs-keyword">REFRESH</span>;
  <span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">PIPE</span> RETAIL.RAW.PIPE_PRODUCTS <span class="hljs-keyword">REFRESH</span>;
  <span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">PIPE</span> RETAIL.RAW.PIPE_STORES <span class="hljs-keyword">REFRESH</span>;
  <span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">PIPE</span> RETAIL.RAW.PIPE_SALES <span class="hljs-keyword">REFRESH</span>;

  RETURN 'PIPES_TRIGGERED';
<span class="hljs-keyword">END</span>;
$$;
</code></pre>
<h3 id="heading-72-stored-proc-to-log-file-loads"><strong>7.2</strong> Stored proc to log file loads</h3>
<p>→ First create a file tracker to maintain history of loaded files</p>
<pre><code class="lang-sql"><span class="hljs-comment">-- 6 file tracker to maintain history of loaded files</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">TABLE</span> RETAIL.RAW.FILE_TRACKER (
  FILE_NAME <span class="hljs-keyword">STRING</span>,
  TARGET_TABLE <span class="hljs-keyword">STRING</span>,
  LOAD_TS TIMESTAMP_LTZ,
  <span class="hljs-keyword">STATUS</span> <span class="hljs-keyword">STRING</span>
);
</code></pre>
<p>→ Then create a stored proc to log file loads</p>
<pre><code class="lang-sql">
<span class="hljs-comment">--stored proc to log file loads</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">PROCEDURE</span> RETAIL.RAW.SP_UPDATE_FILE_TRACKER()
<span class="hljs-keyword">RETURNS</span> <span class="hljs-keyword">STRING</span>
<span class="hljs-keyword">LANGUAGE</span> <span class="hljs-keyword">SQL</span>
<span class="hljs-keyword">EXECUTE</span> <span class="hljs-keyword">AS</span> CALLER
<span class="hljs-keyword">AS</span>
$$
<span class="hljs-keyword">BEGIN</span>
    <span class="hljs-comment">-- Insert only new COPY INTO entries into the FILE_TRACKER table</span>
    <span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> RETAIL.RAW.FILE_TRACKER (FILE_NAME, TARGET_TABLE, LOAD_TS, <span class="hljs-keyword">STATUS</span>)
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DISTINCT</span>
        FILE_NAME,
        TARGET_TABLE,
        LOAD_TS,
        <span class="hljs-string">'SUCCESS'</span> <span class="hljs-keyword">AS</span> <span class="hljs-keyword">STATUS</span>
    <span class="hljs-keyword">FROM</span> (
        <span class="hljs-comment">-- Wrap union in outer SELECT to define consistent column names</span>
        <span class="hljs-keyword">SELECT</span> FILE_NAME, TARGET_TABLE, LAST_LOAD_TIME <span class="hljs-keyword">AS</span> LOAD_TS
        <span class="hljs-keyword">FROM</span> (
            <span class="hljs-keyword">SELECT</span> 
                FILE_NAME,
                <span class="hljs-string">'CUSTOMERS'</span> <span class="hljs-keyword">AS</span> TARGET_TABLE,
                LAST_LOAD_TIME
            <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">TABLE</span>(
                INFORMATION_SCHEMA.COPY_HISTORY(
                    TABLE_NAME =&gt; <span class="hljs-string">'RETAIL.RAW.CUSTOMERS'</span>,
                    START_TIME =&gt; <span class="hljs-keyword">DATEADD</span>(<span class="hljs-string">'hour'</span>, <span class="hljs-number">-12</span>, <span class="hljs-keyword">CURRENT_TIMESTAMP</span>())
                )
            )
            <span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
            <span class="hljs-keyword">SELECT</span> 
                FILE_NAME,
                <span class="hljs-string">'PRODUCTS'</span>,
                LAST_LOAD_TIME
            <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">TABLE</span>(
                INFORMATION_SCHEMA.COPY_HISTORY(
                    TABLE_NAME =&gt; <span class="hljs-string">'RETAIL.RAW.PRODUCTS'</span>,
                    START_TIME =&gt; <span class="hljs-keyword">DATEADD</span>(<span class="hljs-string">'hour'</span>, <span class="hljs-number">-12</span>, <span class="hljs-keyword">CURRENT_TIMESTAMP</span>())
                )
            )
            <span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
            <span class="hljs-keyword">SELECT</span> 
                FILE_NAME,
                <span class="hljs-string">'STORES'</span>,
                LAST_LOAD_TIME
            <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">TABLE</span>(
                INFORMATION_SCHEMA.COPY_HISTORY(
                    TABLE_NAME =&gt; <span class="hljs-string">'RETAIL.RAW.STORES'</span>,
                    START_TIME =&gt; <span class="hljs-keyword">DATEADD</span>(<span class="hljs-string">'hour'</span>, <span class="hljs-number">-12</span>, <span class="hljs-keyword">CURRENT_TIMESTAMP</span>())
                )
            )
            <span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
            <span class="hljs-keyword">SELECT</span> 
                FILE_NAME,
                <span class="hljs-string">'SALES'</span>,
                LAST_LOAD_TIME
            <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">TABLE</span>(
                INFORMATION_SCHEMA.COPY_HISTORY(
                    TABLE_NAME =&gt; <span class="hljs-string">'RETAIL.RAW.SALES'</span>,
                    START_TIME =&gt; <span class="hljs-keyword">DATEADD</span>(<span class="hljs-string">'hour'</span>, <span class="hljs-number">-12</span>, <span class="hljs-keyword">CURRENT_TIMESTAMP</span>())
                )
            )
        )
    )
    <span class="hljs-keyword">WHERE</span> FILE_NAME <span class="hljs-keyword">IS</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> FILE_NAME <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">IN</span> (<span class="hljs-keyword">SELECT</span> FILE_NAME <span class="hljs-keyword">FROM</span> RETAIL.RAW.FILE_TRACKER);

    RETURN '✅ FILE_TRACKER updated successfully.';
<span class="hljs-keyword">END</span>;
$$;
</code></pre>
<h3 id="heading-73-scheduled-task-to-call-the-procedure-every-10-minutes"><strong>7.3 Scheduled Task</strong> to call the procedure every 10 minutes</h3>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> TASK RETAIL.RAW.TASK_TRIGGER_PIPES
  WAREHOUSE = COMPUTE_WH
  SCHEDULE = <span class="hljs-string">'USING CRON */5 * * * * UTC'</span>
<span class="hljs-keyword">AS</span>
<span class="hljs-keyword">BEGIN</span>
  <span class="hljs-keyword">CALL</span> RETAIL.RAW.SP_TRIGGER_PIPES();        <span class="hljs-comment">-- refresh stage &amp; trigger pipes</span>
  <span class="hljs-keyword">CALL</span> RETAIL.RAW.SP_UPDATE_FILE_TRACKER();  <span class="hljs-comment">-- update tracker with newly loaded files</span>
<span class="hljs-keyword">END</span>;
;
</code></pre>
<p>Enable the task:</p>
<pre><code class="lang-sql"><span class="hljs-comment">-- enable task</span>
<span class="hljs-keyword">ALTER</span> TASK RETAIL.RAW.TASK_TRIGGER_PIPES <span class="hljs-keyword">RESUME</span>;

<span class="hljs-comment">--suspend task</span>
<span class="hljs-keyword">ALTER</span> TASK RETAIL.RAW.TASK_TRIGGER_PIPES <span class="hljs-keyword">suspend</span>;

<span class="hljs-comment">--call procedures manually if u want manual execution</span>
<span class="hljs-keyword">CALL</span> RETAIL.RAW.SP_UPDATE_FILE_TRACKER();

<span class="hljs-comment">--see details pf file load</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> RETAIL.RAW.FILE_TRACKER <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> LOAD_TS <span class="hljs-keyword">DESC</span>;
</code></pre>
<hr />
<h1 id="heading-part-3-dbt-transformation-layer-complete-setup-incremental-models-snapshots"><mark>Part 3 — DBT Transformation Layer (Complete Setup + Incremental Models + Snapshots)</mark></h1>
<p>In Part 2, we automated the <strong>S3 → Snowflake RAW layer</strong> using Pipes + Tasks.</p>
<p>Now in Part 3, we build the entire <strong>transformation layer using dbt</strong>.</p>
<p>This is where our project becomes a true <strong>Data Engineering pipeline</strong>:</p>
<ul>
<li><p>Clean, standardized data (DBT_RAW)</p>
</li>
<li><p>Business-friendly dimensions (DIM tables)</p>
</li>
<li><p>Analytical-ready facts (FCT tables)</p>
</li>
<li><p>Incremental logic to optimize cost</p>
</li>
<li><p>Snapshots for SCD-2 history</p>
</li>
<li><p>End-to-end orchestration with dbt run + dbt test</p>
</li>
</ul>
<p>Let’s begin.</p>
<hr />
<h2 id="heading-1-install-dbt-locally-via-virtual-environment-correct-amp-safe-way"><strong>1. Install dbt Locally via Virtual Environment (Correct &amp; Safe Way)</strong></h2>
<h3 id="heading-11-create-a-project-folder"><strong>1.1 Create a project folder</strong></h3>
<pre><code class="lang-sql">mkdir forever_retail
cd forever_retail
</code></pre>
<h3 id="heading-12-create-python-virtual-environment"><strong>1.2 Create Python Virtual Environment</strong></h3>
<pre><code class="lang-sql">python -m venv venv
</code></pre>
<p>Activate it:</p>
<pre><code class="lang-sql">venv\Scripts\activate
</code></pre>
<h3 id="heading-13-install-dbt-snowflake"><strong>1.3 Install dbt-snowflake</strong></h3>
<pre><code class="lang-sql">pip <span class="hljs-keyword">install</span> dbt-snowflake
</code></pre>
<p>Verify installation:</p>
<pre><code class="lang-sql">dbt <span class="hljs-comment">--version</span>
</code></pre>
<h2 id="heading-2-initialize-dbt-project"><strong>2. Initialize dbt Project</strong></h2>
<p>Inside your project folder:</p>
<pre><code class="lang-sql">dbt init forever_retail
</code></pre>
<p>This creates:</p>
<pre><code class="lang-sql">forever_retail/
  models/
  snapshots/
  dbt_project.yml
  profiles.yml  (configured manually)  -&gt; it may not be created in the same folder. If not this will be globally created, look in ur c drive C:\Users\kabhi\.dbt
</code></pre>
<h2 id="heading-3-configure-snowflake-connection-profilesyml"><strong>3. Configure Snowflake Connection (profiles.yml)</strong></h2>
<p>Open:</p>
<pre><code class="lang-sql">~/.dbt/profiles.yml
</code></pre>
<p>Add:</p>
<pre><code class="lang-sql">forever_retail:
  target: dev
  outputs:
    dev:
      type: snowflake
      account: &lt;your account&gt;
      user: dbt_user
      password: "*********"
      role: RETAIL_TRANSFORM
      warehouse: COMPUTE_WH
      database: RETAIL
      schema: DBT  <span class="hljs-comment">-- final schema name in Snowflake will be generated like DBT + Model names </span>
      threads: 4
      client_session_keep_alive: False
</code></pre>
<h2 id="heading-4-dbt-project-layers-final-structure"><strong>4. DBT Project Layers (Final Structure)</strong></h2>
<p>Your dbt project will follow this folder structure:</p>
<pre><code class="lang-sql">models/
    raw/
        raw_customers.sql
        raw_products.sql
        raw_stores.sql
        raw_sales.sql

    staging/
        stg_customers.sql
        stg_products.sql
        stg_stores.sql
        stg_sales.sql

    marts/    
            dim_customers.sql
            dim_products.sql
            dim_stores.sql
            dim_date.sql

            fct_sales.sql

            agg_sales_by_category.sql
            agg_sales_by_store.sql
            customer_lifetime_value.sql
</code></pre>
<h2 id="heading-5-raw-layer-dbt-models-reading-from-retailraw"><strong>5. RAW Layer (dbt models reading from RETAIL.RAW)</strong></h2>
<p>Remember: <strong>RAW tables contain full history</strong>, so dbt should <strong>load only new records</strong> into DBT_RAW.</p>
<h3 id="heading-rawrawcustomerssql">raw/raw_customers.sql</h3>
<pre><code class="lang-sql">{{ config(
    materialized='table'
) }}

<span class="hljs-keyword">SELECT</span> 
    customer_id::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> customer_id,
    <span class="hljs-keyword">TRIM</span>(<span class="hljs-keyword">name</span>) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">name</span>,
    gender,
    age::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> age,
    city,
    TRY_TO_DATE(signup_date) <span class="hljs-keyword">AS</span> signup_date,
    load_ts
<span class="hljs-keyword">FROM</span> RETAIL.RAW.CUSTOMERS
<span class="hljs-keyword">WHERE</span> load_ts = (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">MAX</span>(load_ts)
    <span class="hljs-keyword">FROM</span> RETAIL.RAW.CUSTOMERS
)
</code></pre>
<h3 id="heading-rawrawproductssql">raw/raw_products.sql</h3>
<pre><code class="lang-sql">{{ config(
    materialized='table'
) }}

<span class="hljs-keyword">SELECT</span> 
    product_id::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> product_id,
    <span class="hljs-keyword">TRIM</span>(product_name) <span class="hljs-keyword">AS</span> product_name,
    <span class="hljs-keyword">TRIM</span>(<span class="hljs-keyword">category</span>) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">category</span>,
    price::<span class="hljs-built_in">FLOAT</span> <span class="hljs-keyword">AS</span> price,
    <span class="hljs-keyword">TRIM</span>(brand) <span class="hljs-keyword">AS</span> brand,
    load_ts
<span class="hljs-keyword">FROM</span> RETAIL.RAW.PRODUCTS
<span class="hljs-keyword">WHERE</span> load_ts = (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">MAX</span>(load_ts)
    <span class="hljs-keyword">FROM</span> RETAIL.RAW.PRODUCTS
)
</code></pre>
<h3 id="heading-rawrawsalessql">raw/raw_sales.sql</h3>
<pre><code class="lang-sql">{{ config(
    materialized='table'
) }}

<span class="hljs-keyword">SELECT</span> 
    sale_id::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> sale_id,
    store_id::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> store_id,
    customer_id::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> customer_id,
    product_id::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> product_id,
    quantity::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> quantity,
    amount::<span class="hljs-built_in">FLOAT</span> <span class="hljs-keyword">AS</span> amount,
    TRY_TO_DATE(sale_date) <span class="hljs-keyword">AS</span> sale_date,
    load_ts
<span class="hljs-keyword">FROM</span> RETAIL.RAW.SALES
<span class="hljs-keyword">WHERE</span> load_ts = (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">MAX</span>(load_ts)
    <span class="hljs-keyword">FROM</span> RETAIL.RAW.SALES
)
</code></pre>
<h3 id="heading-rawrawstoressql">raw/raw_stores.sql</h3>
<pre><code class="lang-sql">{{ config(
    materialized='table'
) }}

<span class="hljs-keyword">SELECT</span> 
    store_id::<span class="hljs-built_in">INT</span> <span class="hljs-keyword">AS</span> store_id,
    <span class="hljs-keyword">TRIM</span>(store_name) <span class="hljs-keyword">AS</span> store_name,
    <span class="hljs-keyword">TRIM</span>(city) <span class="hljs-keyword">AS</span> city,
    <span class="hljs-keyword">TRIM</span>(region) <span class="hljs-keyword">AS</span> region,
    <span class="hljs-keyword">TRIM</span>(manager_name) <span class="hljs-keyword">AS</span> manager_name,
    load_ts
<span class="hljs-keyword">FROM</span> RETAIL.RAW.STORES
<span class="hljs-keyword">WHERE</span> load_ts = (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">MAX</span>(load_ts)
    <span class="hljs-keyword">FROM</span> RETAIL.RAW.STORES
)
</code></pre>
<h2 id="heading-6-staging-layer-cleaned-standardized-models"><strong>6. Staging Layer (Cleaned, Standardized Models)</strong></h2>
<p>Staging models produce <strong>clean, typed fields</strong>.</p>
<h3 id="heading-stagingstgcustomerssql">staging/stg_customers.sql</h3>
<pre><code class="lang-sql">{{ config(materialized = 'table') }}

<span class="hljs-keyword">SELECT</span>
    customer_id,
    INITCAP(<span class="hljs-keyword">TRIM</span>(<span class="hljs-keyword">name</span>)) <span class="hljs-keyword">AS</span> customer_name,
    <span class="hljs-keyword">UPPER</span>(gender) <span class="hljs-keyword">AS</span> gender,
    age,
    INITCAP(city) <span class="hljs-keyword">AS</span> city,
    signup_date,
    load_ts 
<span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'raw_customers'</span>) }}
</code></pre>
<h3 id="heading-stagingstgproductssql">staging/stg_products.sql</h3>
<pre><code class="lang-sql">{{ config(materialized = 'table') }}

<span class="hljs-keyword">SELECT</span>
    product_id,
    INITCAP(product_name) <span class="hljs-keyword">AS</span> product_name,
    INITCAP(<span class="hljs-keyword">category</span>) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">category</span>,
    price,
    INITCAP(brand) <span class="hljs-keyword">AS</span> brand,
    <span class="hljs-keyword">CASE</span>
        <span class="hljs-keyword">WHEN</span> price &lt; <span class="hljs-number">100</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Low'</span>
        <span class="hljs-keyword">WHEN</span> price <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">100</span> <span class="hljs-keyword">AND</span> <span class="hljs-number">500</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Medium'</span>
        <span class="hljs-keyword">ELSE</span> <span class="hljs-string">'High'</span>
    <span class="hljs-keyword">END</span> <span class="hljs-keyword">AS</span> price_segment,
    load_ts
<span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'raw_products'</span>) }}
</code></pre>
<h3 id="heading-stagingstgstoressql">staging/stg_stores.sql</h3>
<pre><code class="lang-sql">{{ config(materialized = 'table') }}

<span class="hljs-keyword">SELECT</span>
    store_id,
    INITCAP(store_name) <span class="hljs-keyword">AS</span> store_name,
    INITCAP(city) <span class="hljs-keyword">AS</span> city,
    INITCAP(region) <span class="hljs-keyword">AS</span> region,
    INITCAP(manager_name) <span class="hljs-keyword">AS</span> manager_name,
    <span class="hljs-keyword">CURRENT_TIMESTAMP</span>() <span class="hljs-keyword">AS</span> load_ts
<span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'raw_stores'</span>) }}
</code></pre>
<h3 id="heading-stagingstgsalessql">staging/stg_sales.sql</h3>
<pre><code class="lang-sql">{{ config(
    materialized = 'incremental',
    unique_key = 'sale_id',
    incremental_strategy = '<span class="hljs-keyword">merge</span><span class="hljs-string">',
    on_schema_change = '</span>sync_all_columns<span class="hljs-string">'
) }}

SELECT
    sale_id,
    store_id,
    customer_id,
    product_id,
    quantity,
    amount,
    TRY_TO_DATE(sale_date) AS sale_date,
    load_ts
FROM {{ ref('</span>raw_sales<span class="hljs-string">') }}</span>
</code></pre>
<p>→ No incremental logic here except stg_sales<br />→ Staging always reflects latest DBT_RAW</p>
<h2 id="heading-7-mart-layer"><strong>7. Mart Layer</strong></h2>
<p>Dimensions must preserve full history (old + new).</p>
<h3 id="heading-martdimcustomerssql">mart/dim_customers.sql</h3>
<pre><code class="lang-sql">{{ config(
    materialized = 'incremental',
    unique_key = 'customer_id',
    incremental_strategy = '<span class="hljs-keyword">merge</span><span class="hljs-string">',
    on_schema_change = '</span>sync_all_columns<span class="hljs-string">'
) }}

WITH src AS (
    SELECT 
        customer_id,
        customer_name,
        gender,
        age,
        city,
        signup_date,
        CURRENT_TIMESTAMP() AS last_updated
    FROM {{ ref('</span>stg_customers<span class="hljs-string">') }}
)

SELECT 
    customer_id,
    customer_name,
    gender,
    age,
    city,
    signup_date,
    CASE 
        WHEN age &lt; 20 THEN '</span>Teen<span class="hljs-string">'
        WHEN age BETWEEN 20 AND 29 THEN '</span><span class="hljs-number">20</span>s<span class="hljs-string">'
        WHEN age BETWEEN 30 AND 39 THEN '</span><span class="hljs-number">30</span>s<span class="hljs-string">'
        WHEN age BETWEEN 40 AND 49 THEN '</span><span class="hljs-number">40</span>s<span class="hljs-string">'
        WHEN age &gt;= 50 THEN '</span><span class="hljs-number">50</span>+<span class="hljs-string">'
        ELSE '</span><span class="hljs-literal">Unknown</span><span class="hljs-string">'
    END AS age_group,
    last_updated
FROM src</span>
</code></pre>
<h3 id="heading-martdimproductssql">mart/dim_products.sql</h3>
<pre><code class="lang-sql">{{ config(
    materialized = 'incremental',
    unique_key = 'product_id',
    incremental_strategy = '<span class="hljs-keyword">merge</span><span class="hljs-string">',
    on_schema_change = '</span>sync_all_columns<span class="hljs-string">'
) }}

WITH src AS (
    SELECT
        product_id,
        product_name,
        category,
        price,
        brand,
        CURRENT_TIMESTAMP() AS last_updated
    FROM {{ ref('</span>stg_products<span class="hljs-string">') }}
)

SELECT
    product_id,
    INITCAP(product_name) AS product_name,
    INITCAP(category) AS category,
    INITCAP(brand) AS brand,
    price,
    CASE
        WHEN price &lt; 500 THEN '</span><span class="hljs-keyword">Low</span><span class="hljs-string">'
        WHEN price BETWEEN 500 AND 1000 THEN '</span><span class="hljs-keyword">Medium</span><span class="hljs-string">'
        ELSE '</span><span class="hljs-keyword">High</span><span class="hljs-string">'
    END AS price_segment,
    last_updated
FROM src</span>
</code></pre>
<h3 id="heading-martdimstoressql">mart/dim_stores.sql</h3>
<pre><code class="lang-sql">{{
  config(
    materialized='incremental',
    unique_key='store_id',
    incremental_strategy='<span class="hljs-keyword">merge</span><span class="hljs-string">',
    on_schema_change='</span>sync_all_columns<span class="hljs-string">'
  )
}}

WITH src AS (
    SELECT
        store_id,
        store_name,
        city,
        region,
        manager_name,
        CURRENT_TIMESTAMP() AS last_updated
    FROM {{ ref('</span>stg_stores<span class="hljs-string">') }}
    WHERE store_id IS NOT NULL
)

SELECT
    store_id,
    store_name,
    city,
    region,
    manager_name,
    CONCAT(region, '</span>-<span class="hljs-string">', city) AS store_location_key,
    last_updated
FROM src</span>
</code></pre>
<h3 id="heading-martdimdatesql">mart/dim_date.sql</h3>
<pre><code class="lang-sql">{{ config(
    materialized = 'incremental',
    unique_key = 'date_key'
) }}

<span class="hljs-keyword">WITH</span> date_spine <span class="hljs-keyword">AS</span> (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DATEADD</span>(<span class="hljs-keyword">DAY</span>, SEQ4(), <span class="hljs-string">'2023-01-01'</span>) <span class="hljs-keyword">AS</span> date_key
    <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">TABLE</span>(GENERATOR(ROWCOUNT =&gt; <span class="hljs-number">1825</span>))
),

base <span class="hljs-keyword">AS</span> (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DISTINCT</span>
        date_key,
        <span class="hljs-keyword">YEAR</span>(date_key) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">year</span>,
        <span class="hljs-keyword">MONTH</span>(date_key) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">month</span>,
        <span class="hljs-keyword">DAY</span>(date_key) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">day</span>,
        <span class="hljs-keyword">DAYNAME</span>(date_key) <span class="hljs-keyword">AS</span> day_name,
        <span class="hljs-keyword">WEEK</span>(date_key) <span class="hljs-keyword">AS</span> week_number,
        MONTHNAME(date_key) <span class="hljs-keyword">AS</span> month_name,
        <span class="hljs-keyword">QUARTER</span>(date_key) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">quarter</span>,
        <span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> <span class="hljs-keyword">DAYOFWEEK</span>(date_key) <span class="hljs-keyword">IN</span> (<span class="hljs-number">6</span>,<span class="hljs-number">7</span>) <span class="hljs-keyword">THEN</span> <span class="hljs-literal">TRUE</span> <span class="hljs-keyword">ELSE</span> <span class="hljs-literal">FALSE</span> <span class="hljs-keyword">END</span> <span class="hljs-keyword">AS</span> is_weekend
    <span class="hljs-keyword">FROM</span> date_spine
)

<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> base
{% <span class="hljs-keyword">if</span> is_incremental() %}
<span class="hljs-keyword">WHERE</span> date_key <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">IN</span> (<span class="hljs-keyword">SELECT</span> date_key <span class="hljs-keyword">FROM</span> {{ this }})
{% endif %}
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> date_key
</code></pre>
<h3 id="heading-martfctsalessql-this-is-the-heart-of-the-analytics-layer">mart/fct_sales.sql - This is the heart of the analytics layer.</h3>
<pre><code class="lang-sql">{{ config(
    materialized='incremental',
    unique_key='sale_id',
    incremental_strategy='<span class="hljs-keyword">merge</span><span class="hljs-string">',
    on_schema_change='</span>sync_all_columns<span class="hljs-string">'
) }}

WITH sales AS (
    SELECT DISTINCT * FROM {{ ref('</span>stg_sales<span class="hljs-string">') }}
),
customers AS (
    SELECT * FROM {{ ref('</span>dim_customers<span class="hljs-string">') }}
),
products AS (
    SELECT * FROM {{ ref('</span>dim_products<span class="hljs-string">') }}
),
stores AS (
    SELECT * FROM {{ ref('</span>dim_stores<span class="hljs-string">') }}
),
dates AS (
    SELECT * FROM {{ ref('</span>dim_date<span class="hljs-string">') }}
)

SELECT
    s.sale_id,
    s.sale_date,
    d.year,
    d.month,
    s.store_id,
    st.store_name,
    st.region,
    s.customer_id,
    c.customer_name,
    c.gender,
    c.age_group,
    c.city AS customer_city,
    s.product_id,
    p.product_name,
    p.category,
    p.price_segment,
    s.quantity,
    s.amount,
    ROUND(s.amount / NULLIF(s.quantity, 0), 2) AS unit_price,
    CURRENT_TIMESTAMP() AS last_updated
FROM sales s
LEFT JOIN customers c ON s.customer_id = c.customer_id
LEFT JOIN products p ON s.product_id = p.product_id
LEFT JOIN stores st ON s.store_id = st.store_id
LEFT JOIN dates d ON s.sale_date = d.date_key</span>
</code></pre>
<h3 id="heading-martaggregatedsalesbycategorysql">mart/aggregated_sales_by_category.sql</h3>
<pre><code class="lang-sql">{{
  config(
    materialized='table',
    on_schema_change='sync_all_columns'
  )
}}

<span class="hljs-keyword">WITH</span> fct <span class="hljs-keyword">AS</span> (
    <span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'fct_sales'</span>) }}
)

<span class="hljs-keyword">SELECT</span>
    <span class="hljs-keyword">category</span>,
    <span class="hljs-keyword">SUM</span>(amount) <span class="hljs-keyword">AS</span> total_revenue,
    <span class="hljs-keyword">SUM</span>(quantity) <span class="hljs-keyword">AS</span> total_units,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> customer_id) <span class="hljs-keyword">AS</span> unique_customers,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">SUM</span>(amount) / <span class="hljs-keyword">NULLIF</span>(<span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> customer_id), <span class="hljs-number">0</span>), <span class="hljs-number">2</span>) <span class="hljs-keyword">AS</span> avg_spend_per_customer,
    <span class="hljs-keyword">CURRENT_TIMESTAMP</span>() <span class="hljs-keyword">AS</span> last_updated
<span class="hljs-keyword">FROM</span> fct
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">category</span>
</code></pre>
<h3 id="heading-martaggregatedsalesbystoressql">mart/aggregated_sales_by_stores.sql</h3>
<pre><code class="lang-sql">{{
  config(
    materialized='table',
    on_schema_change='sync_all_columns'
  )
}}

<span class="hljs-keyword">WITH</span> fct <span class="hljs-keyword">AS</span> (
    <span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'fct_sales'</span>) }}
)

<span class="hljs-keyword">SELECT</span>
    store_name,
    region,
    <span class="hljs-keyword">SUM</span>(amount) <span class="hljs-keyword">AS</span> total_sales,
    <span class="hljs-keyword">SUM</span>(quantity) <span class="hljs-keyword">AS</span> total_units_sold,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> customer_id) <span class="hljs-keyword">AS</span> customers_served,
    <span class="hljs-keyword">CURRENT_TIMESTAMP</span>() <span class="hljs-keyword">AS</span> last_updated
<span class="hljs-keyword">FROM</span> fct
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> store_name, region
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> total_sales <span class="hljs-keyword">DESC</span>
</code></pre>
<h3 id="heading-martcustomerslifetimevaluesql">mart/customers_lifetime_value.sql</h3>
<pre><code class="lang-sql">{{
  config(
    materialized='table',
    on_schema_change='sync_all_columns'
  )
}}

<span class="hljs-keyword">WITH</span> fct <span class="hljs-keyword">AS</span> (
    <span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'fct_sales'</span>) }}
)

<span class="hljs-keyword">SELECT</span>
    customer_id,
    customer_name,
    gender,
    customer_city,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> sale_id) <span class="hljs-keyword">AS</span> total_orders,
    <span class="hljs-keyword">SUM</span>(amount) <span class="hljs-keyword">AS</span> total_revenue,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">SUM</span>(amount) / <span class="hljs-keyword">NULLIF</span>(<span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> sale_id), <span class="hljs-number">0</span>), <span class="hljs-number">2</span>) <span class="hljs-keyword">AS</span> avg_order_value,
    <span class="hljs-keyword">CURRENT_TIMESTAMP</span>() <span class="hljs-keyword">AS</span> last_updated
<span class="hljs-keyword">FROM</span> fct
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> customer_id, customer_name, gender, customer_city
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> total_revenue <span class="hljs-keyword">DESC</span>
</code></pre>
<h3 id="heading-martauditlogsql">mart/audit_log.sql</h3>
<pre><code class="lang-sql">{{ config(materialized='table') }}

<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'dim_customers'</span> <span class="hljs-keyword">AS</span> table_name,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">AS</span> record_count,
    <span class="hljs-keyword">MAX</span>(last_updated) <span class="hljs-keyword">AS</span> last_load_time
<span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'dim_customers'</span>) }}
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'stg_sales'</span>,
    <span class="hljs-keyword">COUNT</span>(*),
    <span class="hljs-keyword">MAX</span>(load_ts)
<span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'stg_sales'</span>) }}
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'dim_products'</span>,
    <span class="hljs-keyword">COUNT</span>(*),
    <span class="hljs-keyword">MAX</span>(last_updated) <span class="hljs-keyword">AS</span> last_load_time
<span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'dim_products'</span>) }}
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'dim_stores'</span>,
    <span class="hljs-keyword">COUNT</span>(*),
    <span class="hljs-keyword">MAX</span>(last_updated) <span class="hljs-keyword">AS</span> last_load_time
<span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'dim_stores'</span>) }}
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'fct_sales'</span>,
    <span class="hljs-keyword">COUNT</span>(*),
    <span class="hljs-keyword">MAX</span>(last_updated) <span class="hljs-keyword">AS</span> last_load_time
<span class="hljs-keyword">FROM</span> {{ <span class="hljs-keyword">ref</span>(<span class="hljs-string">'fct_sales'</span>) }}
</code></pre>
<h2 id="heading-8-dbt-snapshot-scd-2-for-customer-history"><strong>8. dbt Snapshot (SCD-2 for Customer History)</strong></h2>
<p>File: <code>snapshots/customer_snapshot.sql</code></p>
<pre><code class="lang-sql">{% snapshot customer_snapshot %}

{{
    config(
        target_schema='DBT_SNAPSHOTS',
        unique_key='customer_id',
        strategy='<span class="hljs-keyword">check</span><span class="hljs-string">',
        check_cols=['</span><span class="hljs-keyword">name</span><span class="hljs-string">', '</span>gender<span class="hljs-string">', '</span>age<span class="hljs-string">', '</span>city<span class="hljs-string">', '</span>signup_date<span class="hljs-string">'],  
        invalidate_hard_deletes=True
    )
}}

SELECT 
    customer_id,
    name,
    gender,
    age,
    city,
    signup_date
FROM RETAIL.RAW.CUSTOMERS

{% endsnapshot %}</span>
</code></pre>
<p>Run it:</p>
<pre><code class="lang-sql">dbt snapshot
</code></pre>
<h2 id="heading-9-run-the-full-pipeline"><strong>9. Run the Full Pipeline</strong></h2>
<h3 id="heading-initial-full-load"><strong>Initial full load</strong></h3>
<pre><code class="lang-sql">dbt run <span class="hljs-comment">--full-refresh</span>
</code></pre>
<h3 id="heading-incremental-loads"><strong>Incremental loads</strong></h3>
<pre><code class="lang-sql">dbt run
</code></pre>
<h3 id="heading-run-tests"><strong>Run tests</strong></h3>
<p>— add schema.yml in respective marts layer folder to perform this</p>
<pre><code class="lang-sql">dbt test
</code></pre>
<h2 id="heading-10-what-we-achieved-in-dbt"><strong>10. What We Achieved in DBT</strong></h2>
<p>Cleaned &amp; standardized pipeline<br />Incremental processing using merge<br />Business-friendly dimensions<br />Analytical facts<br />Automated date dimension<br />CDC snapshot (SCD2)<br />Efficient &amp; scalable pipeline</p>
<p>This completes the <strong>DBT Transformation Layer</strong> of the Forever Retail project.</p>
<hr />
<h1 id="heading-part-4-orchestration-strategy-for-the-forever-retail-pipeline"><mark>Part 4 — Orchestration Strategy for the Forever Retail Pipeline</mark></h1>
<p>In an end-to-end data engineering project, ingestion + transformation is not enough.<br />You need a <strong>reliable orchestration layer</strong> that ensures:</p>
<ul>
<li><p>Data always flows on schedule</p>
</li>
<li><p>Transformations trigger after ingestion</p>
</li>
<li><p>Dependency order is maintained</p>
</li>
<li><p>Monitoring is possible</p>
</li>
<li><p>Failures can be retried</p>
</li>
<li><p>Lineage is visible end-to-end</p>
</li>
</ul>
<p>In this part, we describe <strong>how the Forever Retail pipeline should be orchestrated</strong>, including Snowflake-native automation and best practices for dbt execution.</p>
<h2 id="heading-1-where-orchestration-happens-in-our-architecture"><strong>1. Where Orchestration Happens in Our Architecture</strong></h2>
<p>Here is the final automation strategy:</p>
<h3 id="heading-ingestion-layer-s3-snowflake-raw"><strong>Ingestion Layer (S3 → Snowflake RAW)</strong></h3>
<p>→ Fully automated inside Snowflake<br />→ Using <em>Snowflake Tasks + Pipes</em><br />→ No need for Airflow / external services<br />→ Runs every 10 minutes<br />→ Detects new files<br />→ Loads RAW tables automatically</p>
<h3 id="heading-transformation-layer-raw-dbtraw-staging-mart"><strong>Transformation Layer (RAW → DBT_RAW → STAGING → MART)</strong></h3>
<p>→ Runs using <strong>dbt CLI</strong><br />→ Local or CI/CD execution<br />→ Can be triggered:<br /> ✓ manually<br /> ✓ on schedule (cron)<br /> ✓ automatically after ingestion (<strong>recommended</strong>)</p>
<h3 id="heading-snapshot-layer"><strong>Snapshot Layer</strong></h3>
<p>→ dbt snapshot runs on separate schedule<br />→ Preserves history changes</p>
<hr />
<h2 id="heading-2-ingestion-orchestration-already-complete"><strong>2. Ingestion Orchestration (Already Complete)</strong></h2>
<p>Your ingestion pipeline runs using:</p>
<ul>
<li><p><strong>Pipes</strong> for automated streaming ingests</p>
</li>
<li><p><strong>Tasks</strong> to “kick” pipes + refresh stage every 10 minutes</p>
</li>
</ul>
<p>This ensures:</p>
<h3 id="heading-whenever-new-files-land-in-s3"><strong>Whenever new files land in S3:</strong></h3>
<p>→ Snowflake sees them<br />→ Pipes match files using patterns (<code>customers_*.csv</code>)<br />→ Data goes into RAW tables<br />→ No duplicates (load_ts is separate per file)</p>
<p>You’ve already implemented this successfully.</p>
<h2 id="heading-3-orchestrating-dbt-the-transformation-layer"><strong>3. Orchestrating dbt (The Transformation Layer)</strong></h2>
<p>( Optional , you can also trigger dbt run &amp; dbt test manually if you do not wish to Orchestrate )</p>
<p>Now let's schedule dbt.</p>
<p>You have <strong>three options</strong>, all valid depending on how you want the system to behave.</p>
<h3 id="heading-option-a-schedule-dbt-via-os-cron-recommended-for-localsmall-projects"><strong>Option A — Schedule dbt via OS Cron (Recommended for Local/Small Projects)</strong></h3>
<p>This is perfect since you’re running dbt locally.</p>
<p><strong>Step 1 — Open Windows Task Scheduler (or crontab on Linux)</strong></p>
<p><strong>Windows Example</strong></p>
<p>Create a <code>.bat</code> file:</p>
<p><strong>dbt_run.bat</strong></p>
<pre><code class="lang-sql">cd D:\System\Workplace\Data Projects\forever_retail
<span class="hljs-keyword">call</span> venv\Scripts\<span class="hljs-keyword">activate</span>
dbt run
dbt <span class="hljs-keyword">test</span>
</code></pre>
<p>Schedule it to run every <strong>10 minutes + 2 minutes offset</strong>.</p>
<p>Why offset?</p>
<p>→ Because ingestion task runs at 00,10,20,30…<br />→ dbt should run <em>after</em> ingestion is likely done</p>
<p>So your schedule:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Task</td><td>Runs</td></tr>
</thead>
<tbody>
<tr>
<td>Snowflake ingestion</td><td>every 10 min (00,10,20…)</td></tr>
<tr>
<td>dbt transform</td><td>2 minutes later (02,12,22…)</td></tr>
</tbody>
</table>
</div><p>This ensures smooth coordination.</p>
<h3 id="heading-option-b-use-github-actions-cicd-style-automation"><strong>Option B — Use GitHub Actions (CI/CD style automation)</strong></h3>
<p>This is great when:</p>
<ul>
<li><p>dbt project is in GitHub</p>
</li>
<li><p>You want cloud-based automation</p>
</li>
<li><p>You want versioned and repeatable transformations</p>
</li>
</ul>
<h3 id="heading-sample-githubworkflowsdbtyml">Sample <code>.github/workflows/dbt.yml</code></h3>
<pre><code class="lang-sql">name: dbt_run

on:
  schedule:
    - cron: "*/12 * * * *"   <span class="hljs-comment"># every 12 minutes</span>
  workflow_dispatch:

jobs:
  run-dbt:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: <span class="hljs-keyword">install</span> python
        uses: actions/setup-python@v3
        <span class="hljs-keyword">with</span>:
          python-<span class="hljs-keyword">version</span>: <span class="hljs-string">"3.10"</span>

      - run: pip <span class="hljs-keyword">install</span> dbt-snowflake

      - <span class="hljs-keyword">name</span>: Run dbt
        run: |
          dbt deps
          dbt run
          dbt <span class="hljs-keyword">test</span>
</code></pre>
<h3 id="heading-option-c-orchestrate-dbt-using-airflow-enterprise"><strong>Option C — Orchestrate dbt Using Airflow (Enterprise)</strong></h3>
<p>We can also Orchestrate the whole thing using Airflow by creating DAGs</p>
<h2 id="heading-4-data-quality-checks-dbt-test"><strong>4. Data Quality Checks (dbt test)</strong></h2>
<p>You now have two layers:</p>
<p><strong>Basic Tests (schema tests)</strong></p>
<p>Examples:</p>
<pre><code class="lang-sql">tests:
  - unique:
      column_name: sale_id
  - not_null:
      column_name: customer_name
  - relationships:
      column_name: customer_id
      to: ref('dim_customers')
      field: customer_id
</code></pre>
<p><strong>Advanced Tests (custom tests)</strong></p>
<ul>
<li><p>Checking null city values</p>
</li>
<li><p>Ensuring sale_date not in future</p>
</li>
<li><p>Ensuring age &gt; 0</p>
</li>
<li><p>Ensuring quantity &gt;= 1</p>
</li>
</ul>
<p>These should all be implemented in your <code>tests/</code> folder.</p>
<p>Running:</p>
<pre><code class="lang-sql">dbt test
</code></pre>
<h2 id="heading-5-to-view-full-lineage"><strong>5. To view full lineage</strong></h2>
<p><code>dbt docs generate</code></p>
<p><code>dbt docs serve</code> ⇒ full lineage browser</p>
<p>This gives a fully professional monitoring suite.</p>
<h2 id="heading-6-summary-of-what-we-achieved"><strong>6. Summary of What We Achieved</strong></h2>
<p>By now, your Forever Retail pipeline includes:</p>
<p>→ <strong>Fully automated data ingestion</strong></p>
<p>S3 → Snowflake stage → Pipes → RAW tables</p>
<p>→ <strong>Full transformation pipeline via dbt</strong></p>
<p>DBT_RAW → STAGING → DIM → FACT → AGG</p>
<p>→ <strong>Incremental Processing &amp; CDC</strong></p>
<p>Using:</p>
<ul>
<li><p><code>load_ts</code></p>
</li>
<li><p>merge strategy</p>
</li>
<li><p>snapshot (SCD-2)</p>
</li>
</ul>
<p>→ <strong>Orchestration &amp; Scheduling</strong></p>
<ul>
<li>Snowflake Tasks for ingestion</li>
</ul>
<p>→ <strong>Data Quality &amp; Lineage</strong></p>
<ul>
<li><p>dbt tests</p>
</li>
<li><p>dbt docs lineage graph</p>
</li>
</ul>
<p>→ <strong>Production-grade design</strong></p>
<p>This is a fully deployable Data Engineering project.  </p>
<hr />
<p><strong>If you found this project helpful or want any clarification, feel free to reach out.</strong><br />Portfolio: <a target="_blank" href="https://theabhishek.vercel.app/">https://theabhishek.vercel.app/</a><br />LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/abhishek-kumar-1409bb211">https://www.linkedin.com/in/abhishek-kumar-1409bb211</a></p>
]]></content:encoded></item></channel></rss>