├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── datagen ├── athena.sql └── csvdatagen.py ├── requirements.txt ├── sample-yamls ├── csv.yaml ├── iceberg.yaml └── splitter.yaml └── template └── template.py /.gitignore: -------------------------------------------------------------------------------- 1 | ### AL ### 2 | #Template for AL projects for Dynamics 365 Business Central 3 | #launch.json folder 4 | .vscode/ 5 | #Cache folder 6 | .alcache/ 7 | #Symbols folder 8 | .alpackages/ 9 | #Snapshots folder 10 | .snapshots/ 11 | #Testing Output folder 12 | .output/ 13 | #Extension App-file 14 | *.app 15 | #Rapid Application Development File 16 | rad.json 17 | #Translation Base-file 18 | *.g.xlf 19 | #License-file 20 | *.flf 21 | #Test results file 22 | TestResults.xml -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Build stage 2 | FROM python:3.9-slim as builder 3 | 4 | WORKDIR /app 5 | 6 | # Copy only the requirements file first to leverage Docker cache 7 | COPY requirements.txt . 8 | 9 | # Install dependencies 10 | RUN pip install --no-cache-dir -r requirements.txt 11 | 12 | # Final stage 13 | FROM python:3.9-slim 14 | 15 | WORKDIR /app 16 | 17 | # Copy installed dependencies from builder stage 18 | COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages 19 | 20 | # Copy your application 21 | COPY template/template.py . 22 | 23 | # Install AWS CLI 24 | RUN apt-get update && \ 25 | apt-get install -y awscli && \ 26 | apt-get clean && \ 27 | rm -rf /var/lib/apt/lists/* 28 | 29 | # Set up environment variables for AWS credentials 30 | ENV AWS_ACCESS_KEY_ID="" 31 | ENV AWS_SECRET_ACCESS_KEY="" 32 | ENV AWS_DEFAULT_REGION="us-east-1" 33 | 34 | 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## DuckDB-Powered Lightweight ETL: An Extensible Framework for Seamless Data Integration 2 | 3 | 4 | ![image](https://github.com/user-attachments/assets/02c932f6-66d2-496c-98ce-41da507c8c15) 5 | 6 | 7 | This repository provides a lightweight ETL framework powered by **DuckDB**, designed for seamless data integration. With this framework, you can easily **extract**, **transform**, and **load** data from various sources into your data lake or warehouse. The architecture allows for extensibility, enabling users to integrate with Lakehouse formats like **Iceberg** and implement custom transformation logic as needed. 8 | 9 | 10 | ## Features 11 | 12 | - **Lightweight**: Utilizes DuckDB for in-memory processing, making it efficient and fast. 13 | - **Extensible**: Easily extend functionality to support various data sources and formats, including Lakehouse architectures like Iceberg. 14 | - **Custom Logic**: Implement your own transformation logic to meet specific business requirements. 15 | 16 | ## Getting Started 17 | 18 | ### Step 1: Install Dependencies 19 | 20 | 21 | Before you begin, you'll need to set up your AWS credentials and install the required dependencies. 22 | 23 | ``` 24 | export AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID" 25 | export AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY" 26 | export AWS_REGION="us-east-1" 27 | 28 | ``` 29 | Install Python dependencies: 30 | ``` 31 | pip3 install -r requirements.txt 32 | ``` 33 | 34 | Step 2: Define the Configuration File (config.yaml) 35 | 36 | 37 | #### CSV Files Example 38 | ``` 39 | # DuckDB Configuration 40 | duckdb: 41 | path: default.duckdb 42 | extension: 43 | - name: httpfs # HTTP File System extension 44 | - name: aws # AWS S3 extension 45 | 46 | # Input Tables Configuration 47 | input: 48 | tables: 49 | - name: customers 50 | path: s3:///raw/customers/*.csv 51 | format: csv 52 | mode: full 53 | checkpoint_path: 's3:///checkpoints/customers_checkpoint.json' 54 | - name: orders 55 | path: s3:///raw/orders/ 56 | format: csv 57 | mode: inc 58 | checkpoint_path: 's3:///checkpoints/orders_checkpoint.json' 59 | 60 | # Transformation SQL Query 61 | transform: 62 | sql: | 63 | SELECT 64 | c.customer_id, 65 | c.name, 66 | o.order_id, 67 | o.order_date, 68 | o.total_amount 69 | FROM 70 | customers c 71 | JOIN 72 | orders o ON c.customer_id = o.customer_id; 73 | 74 | # Output Configuration 75 | output: 76 | path: 's3:///output/csv/' 77 | format: csv 78 | mode: overwrite 79 | 80 | ``` 81 | #### Iceberg Tables Example 82 | 83 | ``` 84 | # DuckDB Configuration 85 | duckdb: 86 | path: mydatabase.duckdb 87 | extension: 88 | - name: httpfs # HTTP File System extension 89 | - name: aws # AWS S3 extension 90 | - name: iceberg # Iceberg extension 91 | 92 | # Input Tables Configuration 93 | input: 94 | tables: 95 | - name: customers 96 | path: 's3:///warehouse/customers/' 97 | format: iceberg # Changed to iceberg format 98 | mode: full 99 | 100 | - name: orders 101 | path: 's3:///warehouse/orders/' 102 | format: iceberg # Changed to iceberg format 103 | mode: full 104 | 105 | # Transformation SQL Query (Adjust as needed based on your schema) 106 | transform: 107 | sql: | 108 | SELECT 109 | c.customer_id, 110 | c.name, 111 | o.order_id, 112 | o.order_date, 113 | o.total_amount 114 | FROM 115 | customers c 116 | JOIN 117 | orders o ON c.customer_id = o.customer_id; 118 | 119 | # Output Configuration 120 | output: 121 | path: 's3:///icebergoutput/csv/' 122 | format: csv 123 | mode: overwrite 124 | threshold: 2 125 | 126 | ``` 127 | ### File Splitter Example 128 | ``` 129 | duckdb: 130 | path: mydatabase.duckdb 131 | extension: 132 | - name: httpfs 133 | input: 134 | tables: 135 | - name: nyctaxi 136 | path: '//output/*.csv' 137 | format: csv 138 | mode: full 139 | transform: 140 | sql: | 141 | SELECT 142 | * 143 | FROM 144 | nyctaxi 145 | output: 146 | path: '//transformed_output' 147 | format: csv 148 | mode: overwrite 149 | threshold: 10000000 150 | 151 | ``` 152 | 153 | 154 | #### Step 3: Running the Script 155 | This repository provides a template script, template.py, that can be used with various configuration files for data processing operations. The script supports both local and AWS S3-based configuration files. 156 | 157 | 158 | Run with Local Configurations 159 | ``` 160 | python3 template.py --config /path/to/config.yaml 161 | 162 | ``` 163 | 164 | ### Run with S3-based Configurations 165 | 166 | Upload your config.yaml to an S3 bucket: 167 | ``` 168 | aws s3 cp /localpath/config.yaml s3://bucket/configs/config.yaml 169 | ``` 170 | 171 | Run the script using the S3 path: 172 | ``` 173 | python3 template.py --config s3://bucket/configs/config.yaml 174 | 175 | ``` 176 | 177 | # Docker Setup 178 | 179 | You can also build and run the framework using Docker for easier deployment. 180 | Build the Docker Image 181 | 182 | ``` 183 | export AWS_ACCESS_KEY_ID="XX" 184 | export AWS_SECRET_ACCESS_KEY="XX" 185 | export AWS_DEFAULT_REGION="us-east-1" 186 | 187 | docker build -t my-data-processor \ 188 | --build-arg AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \ 189 | --build-arg AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \ 190 | --build-arg AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION . 191 | 192 | ``` 193 | Run the Docker Container 194 | ``` 195 | docker run -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \ 196 | -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \ 197 | -e AWS_DEFAULT_REGION=us-east-1 \ 198 | my-data-processor python template.py --config s3://soumil-dev-bucket-1995/configs/csv.yaml 199 | 200 | ``` 201 | 202 | 203 | ## Contribution 204 | 205 | 206 | We welcome contributions to enhance this framework! If you'd like to contribute, feel free to fork the repository, make improvements, and submit a merge request (MR) with your changes. Whether you're adding new features, fixing bugs, or improving the documentation, your help is greatly appreciated. Please ensure that your changes are well-tested, and don't forget to update the documentation if necessary. We look forward to your contributions and thank you for helping make this project better! 207 | -------------------------------------------------------------------------------- /datagen/athena.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE default.customers ( 2 | customer_id STRING, 3 | name STRING, 4 | email STRING, 5 | address STRING, 6 | phone STRING 7 | ) 8 | LOCATION 's3:///warehouse/customers' 9 | TBLPROPERTIES ( 10 | 'table_type' = 'ICEBERG', 11 | 'format' = 'PARQUET' 12 | ); 13 | 14 | INSERT INTO default.customers (customer_id, name, email, address, phone) VALUES 15 | ('C001', 'John Doe', 'john.doe@email.com', '123 Main St, City A', '555-0101'), 16 | ('C002', 'Jane Smith', 'jane.smith@email.com', '456 Oak Rd, City B', '555-0202'), 17 | ('C003', 'Bob Johnson', 'bob.johnson@email.com', '789 Pine Ave, City C', '555-0303'), 18 | ('C004', 'Alice Brown', 'alice.brown@email.com', '321 Elm St, City D', '555-0404'), 19 | ('C005', 'Charlie Davis', 'charlie.davis@email.com', '654 Maple Dr, City E', '555-0505'); 20 | 21 | 22 | CREATE TABLE default.orders ( 23 | order_id STRING, 24 | customer_id STRING, 25 | order_date DATE, 26 | total_amount DOUBLE, 27 | status STRING 28 | ) 29 | LOCATION 's3:///warehouse/orders' 30 | TBLPROPERTIES ( 31 | 'table_type' = 'ICEBERG', 32 | 'format' = 'PARQUET' 33 | ); 34 | 35 | 36 | INSERT INTO default.orders (order_id, customer_id, order_date, total_amount, status) VALUES 37 | ('O001', 'C001', DATE '2023-01-15', 100.50, 'Shipped'), 38 | ('O002', 'C002', DATE '2023-02-20', 75.25, 'Delivered'), 39 | ('O003', 'C003', DATE '2023-03-10', 200.00, 'Processing'), 40 | ('O004', 'C001', DATE '2023-04-05', 50.75, 'Shipped'), 41 | ('O005', 'C004', DATE '2023-05-12', 150.00, 'Delivered'), 42 | ('O006', 'C002', DATE '2023-06-18', 80.50, 'Processing'), 43 | ('O007', 'C005', DATE '2023-07-22', 120.25, 'Shipped'), 44 | ('O008', 'C003', DATE '2023-08-30', 90.00, 'Delivered'), 45 | ('O009', 'C004', DATE '2023-09-14', 180.75, 'Processing'), 46 | ('O010', 'C005', DATE '2023-10-25', 60.50, 'Shipped'); 47 | 48 | -------------------------------------------------------------------------------- /datagen/csvdatagen.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import uuid 3 | from io import StringIO 4 | import boto3 5 | from datetime import datetime, timedelta 6 | 7 | def generate_static_customer_data(): 8 | header = ['customer_id', 'name', 'email', 'address', 'phone'] 9 | data = [ 10 | ['C001', 'John Doe', 'john.doe@email.com', '123 Main St, City A', '555-0101'], 11 | ['C002', 'Jane Smith', 'jane.smith@email.com', '456 Oak Rd, City B', '555-0202'], 12 | ['C003', 'Bob Johnson', 'bob.johnson@email.com', '789 Pine Ave, City C', '555-0303'], 13 | ['C004', 'Alice Brown', 'alice.brown@email.com', '321 Elm St, City D', '555-0404'], 14 | ['C005', 'Charlie Davis', 'charlie.davis@email.com', '654 Maple Dr, City E', '555-0505'] 15 | ] 16 | return [header] + data 17 | 18 | def generate_static_order_data(): 19 | header = ['order_id', 'customer_id', 'order_date', 'total_amount', 'status'] 20 | data = [ 21 | ['O001', 'C001', '2023-01-15', 100.50, 'Shipped'], 22 | ['O002', 'C002', '2023-02-20', 75.25, 'Delivered'], 23 | ['O003', 'C003', '2023-03-10', 200.00, 'Processing'], 24 | ['O004', 'C001', '2023-04-05', 50.75, 'Shipped'], 25 | ['O005', 'C004', '2023-05-12', 150.00, 'Delivered'], 26 | ['O006', 'C002', '2023-06-18', 80.50, 'Processing'], 27 | ['O007', 'C005', '2023-07-22', 120.25, 'Shipped'], 28 | ['O008', 'C003', '2023-08-30', 90.00, 'Delivered'], 29 | ['O009', 'C004', '2023-09-14', 180.75, 'Processing'], 30 | ['O010', 'C005', '2023-10-25', 60.50, 'Shipped'] 31 | ] 32 | return [header] + data 33 | 34 | def upload_to_s3(data, bucket, key): 35 | s3 = boto3.client('s3') 36 | csv_buffer = StringIO() 37 | csv_writer = csv.writer(csv_buffer) 38 | csv_writer.writerows(data) 39 | s3.put_object(Bucket=bucket, Key=key, Body=csv_buffer.getvalue()) 40 | print(f"Uploaded {key} to S3 bucket {bucket}") 41 | 42 | def main(): 43 | bucket = 'XX' 44 | customer_key = f'raw/customers/customers_{datetime.now().strftime("%Y%m%d%H%M%S")}.csv' 45 | order_key = f'raw/orders/orders_{datetime.now().strftime("%Y%m%d%H%M%S")}.csv' 46 | 47 | customer_data = generate_static_customer_data() 48 | order_data = generate_static_order_data() 49 | 50 | upload_to_s3(customer_data, bucket, customer_key) 51 | upload_to_s3(order_data, bucket, order_key) 52 | 53 | if __name__ == "__main__": 54 | main() 55 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 2 | duckdb 3 | PyYAML 4 | -------------------------------------------------------------------------------- /sample-yamls/csv.yaml: -------------------------------------------------------------------------------- 1 | # DuckDB Configuration 2 | duckdb: 3 | path: mydatabase.duckdb 4 | extension: 5 | - name: httpfs # HTTP File System extension 6 | - name: aws # AWS S3 extension 7 | 8 | # Input Tables Configuration 9 | input: 10 | tables: 11 | - name: customers 12 | path: 's3:///raw/customers/*.csv' 13 | format: csv 14 | mode: full 15 | checkpoint_path: 's3:///checkpoints/customers_checkpoint.json' 16 | - name: orders 17 | path: 's3:///raw/orders/*.csv' 18 | format: csv 19 | mode: full 20 | checkpoint_path: 's3:///checkpoints/orders_checkpoint.json' 21 | 22 | # Transformation SQL Query 23 | transform: 24 | sql: | 25 | SELECT 26 | c.customer_id, 27 | c.name, 28 | o.order_id, 29 | o.order_date, 30 | o.total_amount 31 | FROM 32 | customers c 33 | JOIN 34 | orders o ON c.customer_id = o.customer_id; 35 | 36 | # Output Configuration 37 | output: 38 | path: 's3:///output/csv/' 39 | format: csv 40 | mode: overwrite 41 | 42 | -------------------------------------------------------------------------------- /sample-yamls/iceberg.yaml: -------------------------------------------------------------------------------- 1 | # DuckDB Configuration 2 | duckdb: 3 | path: mydatabase.duckdb 4 | extension: 5 | - name: httpfs # HTTP File System extension 6 | - name: aws # AWS S3 extension 7 | - name: iceberg # Iceberg extension 8 | 9 | # Input Tables Configuration 10 | input: 11 | tables: 12 | - name: customers 13 | path: 's3:///warehouse/customers/' 14 | format: iceberg # Changed to iceberg format 15 | mode: full 16 | 17 | - name: orders 18 | path: 's3:///warehouse/orders/' 19 | format: iceberg # Changed to iceberg format 20 | mode: full 21 | 22 | # Transformation SQL Query (Adjust as needed based on your schema) 23 | transform: 24 | sql: | 25 | SELECT 26 | c.customer_id, 27 | c.name, 28 | o.order_id, 29 | o.order_date, 30 | o.total_amount 31 | FROM 32 | customers c 33 | JOIN 34 | orders o ON c.customer_id = o.customer_id; 35 | 36 | # Output Configuration 37 | output: 38 | path: 's3:///icebergoutput/csv/' 39 | format: csv 40 | mode: overwrite 41 | 42 | -------------------------------------------------------------------------------- /sample-yamls/splitter.yaml: -------------------------------------------------------------------------------- 1 | duckdb: 2 | path: mydatabase.duckdb 3 | extension: 4 | - name: httpfs 5 | input: 6 | tables: 7 | - name: nyctaxi 8 | path: '/Users/sshah/IdeaProjects/poc-projects/duckdb/duckdb-file-splitter/output/*.csv' 9 | format: csv 10 | mode: full 11 | transform: 12 | sql: | 13 | SELECT 14 | * 15 | FROM 16 | nyctaxi 17 | output: 18 | path: '/Users/sshah/IdeaProjects/poc-projects/duckdb/duckdb-file-splitter/transformed_output' 19 | format: csv 20 | mode: overwrite 21 | threshold: 10000000 22 | 23 | 24 | -------------------------------------------------------------------------------- /template/template.py: -------------------------------------------------------------------------------- 1 | import os 2 | import duckdb 3 | import yaml 4 | import glob 5 | from datetime import datetime 6 | import json 7 | from urllib.parse import urlparse 8 | import boto3 9 | from abc import ABC, abstractmethod 10 | import argparse 11 | import tempfile 12 | 13 | 14 | class FileProcessor(ABC): 15 | @abstractmethod 16 | def read_to_temp_table(self, conn, input_path, table_name): 17 | pass 18 | 19 | 20 | class CSVFileProcessor(FileProcessor): 21 | def read_to_temp_table(self, conn, input_path, table_name): 22 | table_exists = \ 23 | conn.execute( 24 | f"SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '{table_name}'").fetchone()[ 25 | 0] > 0 26 | if not table_exists: 27 | query = f""" 28 | CREATE TABLE {table_name} AS 29 | SELECT * FROM read_csv_auto('{input_path}', union_by_name=True); 30 | """ 31 | conn.execute(query) 32 | print(f"Table '{table_name}' created and data inserted from CSV.") 33 | else: 34 | query = f""" 35 | INSERT INTO {table_name} 36 | SELECT * FROM read_csv_auto('{input_path}', union_by_name=True); 37 | """ 38 | conn.execute(query) 39 | print(f"New data inserted into '{table_name}' from CSV.") 40 | 41 | 42 | class ParquetFileProcessor(FileProcessor): 43 | def read_to_temp_table(self, conn, input_path, table_name): 44 | table_exists = \ 45 | conn.execute( 46 | f"SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '{table_name}'").fetchone()[ 47 | 0] > 0 48 | if not table_exists: 49 | query = f""" 50 | CREATE TABLE {table_name} AS 51 | SELECT * FROM read_parquet('{input_path}'); 52 | """ 53 | conn.execute(query) 54 | print(f"Table '{table_name}' created and data inserted from Parquet.") 55 | else: 56 | query = f""" 57 | INSERT INTO {table_name} 58 | SELECT * FROM read_parquet('{input_path}'); 59 | """ 60 | conn.execute(query) 61 | print(f"New data inserted into '{table_name}' from Parquet.") 62 | 63 | 64 | class IcebergFileProcessor(FileProcessor): 65 | def read_to_temp_table(self, conn, iceberg_path, table_name): 66 | metadata_file = self.get_latest_metadata_file(iceberg_path) 67 | if metadata_file: 68 | query = f"CREATE TABLE {table_name} AS SELECT * FROM iceberg_scan('{metadata_file}');" 69 | conn.execute(query) 70 | print(f"Table '{table_name}' created and data inserted from Iceberg.") 71 | else: 72 | print(f"No metadata files found for Iceberg at path: {iceberg_path}") 73 | 74 | def drop_table(self, conn, table_name): 75 | try: 76 | conn.execute(f"DROP TABLE IF EXISTS {table_name};") 77 | print(f"Dropped temporary table '{table_name}'.") 78 | except Exception as e: 79 | print(f"Error dropping table '{table_name}': {e}") 80 | 81 | def get_latest_metadata_file(self, iceberg_path): 82 | bucket_name = urlparse(iceberg_path).netloc 83 | path_without_bucket = iceberg_path.replace(f's3://{bucket_name}/', '') 84 | metadata_prefix = f"{path_without_bucket.strip('/')}/metadata/" 85 | 86 | s3 = boto3.client('s3') 87 | try: 88 | response = s3.list_objects_v2(Bucket=bucket_name, Prefix=metadata_prefix) 89 | metadata_files = [ 90 | obj['Key'] for obj in response.get('Contents', []) 91 | if obj['Key'].endswith('.metadata.json') 92 | ] 93 | 94 | if metadata_files: 95 | latest_metadata = sorted(metadata_files)[-1] 96 | print("Latest Metadata File:", latest_metadata) 97 | return f"s3://{bucket_name}/{latest_metadata}" 98 | else: 99 | print("No metadata files found") 100 | return None 101 | 102 | except Exception as e: 103 | print(f"Error listing objects: {str(e)}") 104 | return None 105 | 106 | 107 | class IncrementalFileProcessor: 108 | def __init__(self, path, checkpoint_path, minio_config=None): 109 | self.path = path 110 | self.checkpoint_path = checkpoint_path 111 | self.parsed_url = urlparse(self.path) 112 | self.checkpoint_parsed_url = urlparse(self.checkpoint_path) 113 | self.client = self._get_client(minio_config) 114 | self.last_checkpoint_time = self._load_checkpoint() 115 | 116 | def _get_client(self, minio_config): 117 | if self.parsed_url.scheme in ['s3', 's3a'] or self.checkpoint_parsed_url.scheme in ['s3', 's3a']: 118 | if minio_config: 119 | return boto3.client('s3', endpoint_url=minio_config['endpoint_url'], 120 | aws_access_key_id=minio_config['access_key'], 121 | aws_secret_access_key=minio_config['secret_key']) 122 | else: 123 | return boto3.client('s3') 124 | return None 125 | 126 | def _load_checkpoint(self): 127 | if self.checkpoint_parsed_url.scheme in ['s3', 's3a']: 128 | try: 129 | bucket, key = self._parse_s3_path(self.checkpoint_path) 130 | response = self.client.get_object(Bucket=bucket, Key=key) 131 | return json.load(response['Body']).get('last_processed_time', 0) 132 | except self.client.exceptions.NoSuchKey: 133 | return 0 134 | else: 135 | if os.path.exists(self.checkpoint_path): 136 | with open(self.checkpoint_path, 'r') as f: 137 | return json.load(f).get('last_processed_time', 0) 138 | return 0 139 | 140 | def _parse_s3_path(self, s3_path): 141 | parsed = urlparse(s3_path) 142 | return parsed.netloc, parsed.path.lstrip('/') 143 | 144 | def _list_s3_files(self): 145 | bucket, prefix = self._parse_s3_path(self.path) 146 | files = [] 147 | paginator = self.client.get_paginator('list_objects_v2') 148 | for page in paginator.paginate(Bucket=bucket, Prefix=prefix): 149 | for obj in page.get('Contents', []): 150 | if obj['LastModified'].timestamp() > self.last_checkpoint_time: 151 | files.append(f"s3://{bucket}/{obj['Key']}") 152 | return files 153 | 154 | def _list_local_files(self): 155 | files = [] 156 | directory = self.parsed_url.path 157 | for root, _, filenames in os.walk(directory): 158 | for filename in filenames: 159 | file_path = os.path.join(root, filename) 160 | if os.path.getmtime(file_path) > self.last_checkpoint_time: 161 | files.append(file_path) 162 | return files 163 | 164 | def get_new_files(self): 165 | if self.parsed_url.scheme in ['s3', 's3a']: 166 | return self._list_s3_files() 167 | elif self.parsed_url.scheme == 'file' or not self.parsed_url.scheme: 168 | return self._list_local_files() 169 | else: 170 | raise ValueError(f"Unsupported scheme: {self.parsed_url.scheme}") 171 | 172 | def commit_checkpoint(self): 173 | current_time = datetime.now().timestamp() 174 | checkpoint_data = json.dumps({'last_processed_time': current_time}) 175 | if self.checkpoint_parsed_url.scheme in ['s3', 's3a']: 176 | bucket, key = self._parse_s3_path(self.checkpoint_path) 177 | self.client.put_object(Bucket=bucket, Key=key, Body=checkpoint_data) 178 | else: 179 | os.makedirs(os.path.dirname(self.checkpoint_path), exist_ok=True) 180 | with open(self.checkpoint_path, 'w') as f: 181 | f.write(checkpoint_data) 182 | print(f"Checkpoint updated to: {datetime.fromtimestamp(current_time)}") 183 | 184 | 185 | class DataTransformer: 186 | def __init__(self, conn): 187 | self.conn = conn 188 | 189 | def transform_and_export(self, transform_sql, output_path, mode='append', output_format='csv', threshold=None): 190 | self.conn.execute(f"CREATE OR REPLACE VIEW transformed_data AS {transform_sql};") 191 | 192 | timestamp = datetime.now().strftime("%Y_%m_%d_%H_%M_%S") 193 | 194 | if mode == 'overwrite': 195 | for file in glob.glob(os.path.join(output_path, f"*.{output_format}")): 196 | os.remove(file) 197 | print(f"Deleted existing file: {file}") 198 | 199 | if threshold is not None: 200 | output_file_template = os.path.join(output_path, f"{timestamp}") 201 | 202 | copy_query = f""" 203 | COPY ( 204 | SELECT *, 205 | FLOOR((ROW_NUMBER() OVER () - 1) / {threshold}) AS file_number 206 | FROM transformed_data 207 | ) 208 | TO '{output_file_template}' (FORMAT {output_format.upper()}, PARTITION_BY file_number); 209 | """ 210 | 211 | else: 212 | output_file = os.path.join(output_path, f"{timestamp}.{output_format}") 213 | 214 | copy_query = f"COPY (SELECT * FROM transformed_data) TO '{output_file}' WITH (FORMAT {output_format.upper()}, HEADER);" 215 | 216 | self.conn.execute(copy_query) 217 | print(f"Data exported successfully!") 218 | 219 | 220 | def create_output_directory(output_path): 221 | if not output_path.startswith('s3'): 222 | if not os.path.exists(output_path): 223 | os.makedirs(output_path) 224 | print(f"Created output directory: {output_path}") 225 | else: 226 | print(f"Skipping directory creation for S3 path: {output_path}") 227 | 228 | 229 | def download_s3_file(s3_path, local_path): 230 | parsed_url = urlparse(s3_path) 231 | bucket = parsed_url.netloc 232 | key = parsed_url.path.lstrip('/') 233 | 234 | s3 = boto3.client('s3') 235 | s3.download_file(bucket, key, local_path) 236 | print(f"Downloaded config file from S3: {s3_path} to {local_path}") 237 | 238 | 239 | def load_config(config_path): 240 | if config_path.startswith('s3://'): 241 | with tempfile.NamedTemporaryFile(mode='w+', delete=False) as temp_file: 242 | download_s3_file(config_path, temp_file.name) 243 | config_path = temp_file.name 244 | 245 | with open(config_path, 'r', encoding="utf-8") as file: 246 | config = yaml.safe_load(file) 247 | 248 | if config_path.startswith('/tmp/'): 249 | os.unlink(config_path) 250 | 251 | return config 252 | 253 | 254 | def main(config_path): 255 | config = load_config(config_path) 256 | conn = duckdb.connect(config['duckdb']['path']) 257 | 258 | for extension in config['duckdb'].get('extension', []): 259 | extension_name = extension['name'] 260 | conn.execute(f"INSTALL {extension_name};") 261 | conn.execute(f"LOAD {extension_name};") 262 | print(f"Loaded extension: {extension_name}") 263 | 264 | create_output_directory(config['output']['path']) 265 | 266 | input_format_processor_map = { 267 | 'csv': CSVFileProcessor(), 268 | 'parquet': ParquetFileProcessor(), 269 | 'iceberg': IcebergFileProcessor() 270 | } 271 | 272 | temp_tables = [] 273 | 274 | for table_config in config['input']['tables']: 275 | table_name = table_config['name'] 276 | input_format = table_config['format'] 277 | input_path = table_config['path'] 278 | input_mode = table_config['mode'] 279 | 280 | input_processor = input_format_processor_map[input_format] 281 | 282 | if input_mode == 'full': 283 | input_processor.read_to_temp_table(conn, input_path, table_name) 284 | elif input_mode == 'INC': 285 | processor = IncrementalFileProcessor(input_path, f"{table_name}_checkpoint.json") 286 | new_files = processor.get_new_files() 287 | 288 | if new_files: 289 | for new_file in new_files: 290 | print(f"Processing new file for {table_name}: {new_file}") 291 | input_processor.read_to_temp_table(conn, new_file, table_name) 292 | processor.commit_checkpoint() 293 | else: 294 | print(f"No new files to process for {table_name} in incremental mode.") 295 | 296 | temp_tables.append(table_name) 297 | 298 | transformer = DataTransformer(conn) 299 | transform_sql = config['transform']['sql'] 300 | 301 | transformer.transform_and_export( 302 | transform_sql, 303 | config['output']['path'], 304 | config['output']['mode'], 305 | config['output']['format'], 306 | config['output'].get('threshold') 307 | ) 308 | 309 | iceberg_processor = IcebergFileProcessor() 310 | for temp_table in temp_tables: 311 | iceberg_processor.drop_table(conn, temp_table) 312 | 313 | conn.close() 314 | 315 | 316 | if __name__ == '__main__': 317 | parser = argparse.ArgumentParser(description='Process data using a configuration file.') 318 | parser.add_argument('--config', type=str, required=True, help='Path to the configuration file') 319 | args = parser.parse_args() 320 | main(args.config) 321 | --------------------------------------------------------------------------------