Simplify SQL queries across databases
Project description
Multi Database Query Builder
A powerful and flexible query builder for multiple databases with a clean, professional architecture.
Overview
This package simplifies SQL query construction for various databases by offering a unified set of methods and operations. It abstracts database-specific syntax, allowing you to focus on crafting the logic of your queries rather than dealing with different database dialects.
Supported Databases:
- Snowflake
- PostgreSQL
- BigQuery
- Redshift
Table of Contents
Installation
To avoid conflicts with other packages, we recommend installing multi-db-query-builder within a virtual environment:
pip install multi-db-query-builder
Requirements
data_store: Supported data stores aresnowflake,postgresql,bigquery,redshiftdb_session: Database session object
Usage
Basic Usage
from sfn_db_query_builder import check_if_table_exists, mode_function, MultiDatabaseQueryBuilder
# Function interface - works with all databases
data_store = "snowflake" # or "postgresql", "bigquery", "redshift"
db_session = "your_database_session"
schema_name = "your_schema_name"
table_name = "your_table_name"
# Check if a table exists
exists = check_if_table_exists(data_store, db_session, schema_name, table_name)
print(exists) # True if exists, otherwise False
# Generate SQL functions
mode_sql = mode_function(data_store, "column_name", "alias_name")
print(mode_sql) # Database-specific SQL for mode function
Class Interface
# Class interface - works with all databases
builder = MultiDatabaseQueryBuilder(data_store)
exists = builder.check_if_table_exists(db_session, schema_name, table_name)
mode_sql = builder.mode_function("column_name", "alias_name")
Modern Service Layer (Future)
# When ready, use the modern service layer
from sfn_db_query_builder.services import QueryService, FunctionService
query_service = QueryService(data_store)
exists = query_service.check_table_exists(db_session, schema_name, table_name)
function_service = FunctionService(data_store)
mode_sql = function_service.generate_mode_function("column_name", "alias_name")
Architecture
The package follows a clean, professional architecture with:
Core Components
config/: Configuration management and database typescore/: Core abstractions, interfaces, and factory patternsimplementations/: Database-specific implementations
Database Implementations
Each database has its own implementation with:
- Database-specific SQL generation
- Proper error handling
- Reserved keyword management
Legacy Compatibility
- 100% Backward Compatible: Existing code works unchanged
- Unified Interface: Single entry point for all databases
- Database-Specific: Each database handles its own functions
How It Works
The package uses an Abstract Factory Pattern where:
- User provides database type (e.g., "postgresql")
MultiDatabaseQueryBuildercreates the appropriate database-specific implementation- All method calls are delegated to the database-specific implementation
- Database-specific SQL is generated and returned
📊 See detailed flow diagrams for visual representation of the architecture.
API Reference
Core Functions
Table Operations
check_if_table_exists(data_store, db_session, schema_name, table_name)- Check if a table existscheck_if_column_exists(data_store, db_session, schema_name, table_name, column_name)- Check if a column existsfetch_column_name(data_store, db_session, schema_name, table_name)- Get column namesfetch_column_name_datatype(data_store, db_session, schema_name, table_name, filter_val="")- Get column names and typesfetch_single_column_name_datatype(data_store, db_session, schema_name, table_name, column_name)- Get single column infofetch_all_tables_in_schema(data_store, db_session, schema_name, pattern=None)- Get all tables in schemafetch_all_views_in_schema(data_store, db_session, schema_name, pattern=None)- Get all views in schemafetch_table_type_in_schema(data_store, db_session, schema_name, table_name)- Get table typeget_tables_under_schema(data_store, db_session, schema)- Get tables under schemaget_schemas_like_pattern(data_store, db_session, schema_name=None)- Get schemas matching pattern
SQL Functions
mode_function(data_store, column, alias=None)- Generate mode function SQLmedian_function(data_store, column, alias=None)- Generate median function SQLconcat_function(data_store, column, alias, separator)- Generate concat function SQLpivot_function(data_store, fields, column_list, schema, table_name)- Generate pivot function SQLtrim_function(data_store, column, value, condition, alias=None)- Generate trim function SQLsplit_function(data_store, column, delimiter, part, alias=None)- Generate split function SQLtimestamp_to_date_function(data_store, column, alias=None)- Generate timestamp to date SQLsubstring_function(data_store, column, start, end)- Generate substring function SQLdate_diff_in_hours(data_store, start_date, end_date, table_name, alias)- Generate date diff SQLdate_substraction(data_store, date_part, start_date, end_date, alias=None)- Generate date subtraction SQL
Utility Functions
enclose_reserved_keywords(data_store, query)- Enclose reserved keywords in queryenclose_reserved_keywords_v2(data_store, columns_string)- Enclose reserved keywords in columnshandle_reserved_keywords(data_store, query_string)- Handle reserved keywordstable_rename_query(data_store, schema_name, old_table_name, new_table_name)- Generate table rename SQL
Class Interface
MultiDatabaseQueryBuilder(data_store)- Legacy class interface with all above methods
Testing
The package includes comprehensive tests with meaningful, descriptive names:
Test Structure
test_main_entry_point.py- Tests the main entry point and public API (27 tests)test_core_components.py- Tests core infrastructure and components (25 tests)test_database_implementations.py- Tests all database-specific implementations (39 tests)
Test Coverage
- Main Entry Point: MultiDatabaseQueryBuilder class and function interfaces
- Core Components: Factory pattern, database types, configuration, error handling
- Database Implementations: PostgreSQL, BigQuery, Redshift, and Snowflake
- Backward Compatibility: Legacy function and class interfaces
- Integration: End-to-end workflows across all databases
Run tests:
pytest tests/ -v
Total: 91 tests covering all functionality with professional organization.
Troubleshooting
Common Issues
-
Unsupported Data Source: Check if the
data_storeis among the supported ones (snowflake,postgresql,bigquery,redshift). -
Import Errors: Ensure you're importing from the correct module:
from sfn_db_query_builder import check_if_table_exists # Correct from multi_database_query_builder import check_if_table_exists # Legacy
-
Database Session: Ensure your
db_sessionobject is properly configured for your database.
Error Handling
The package provides specific exception types:
UnsupportedDatabaseError: For unsupported database typesQueryExecutionError: For database query execution errorsValidationError: For input validation errors
Migration Guide
From Legacy to New Structure
The package maintains 100% backward compatibility. Your existing code will continue to work:
# This still works
from multi_database_query_builder import check_if_table_exists
# But you can also use the new import
from sfn_db_query_builder import check_if_table_exists
Future Migration Path
- Phase 1: Continue using existing imports (no changes needed)
- Phase 2: Update to new imports when convenient
- Phase 3: Migrate to service layer for new features
Conclusion
The multi-db-query-builder package provides a clean, professional, and maintainable solution for building database queries across multiple database systems. With its modern architecture, comprehensive testing, and 100% backward compatibility, it's ready for production use.
Key Benefits:
- ✅ Database-Specific: Each database handles its own logic
- ✅ Self-Contained: Each implementation is complete and independent
- ✅ Unified Interface: Single entry point for all databases
- ✅ 100% Backward Compatible: Existing code works unchanged
- ✅ Clean Architecture: Professional structure with proper separation of concerns
- ✅ Easy Maintenance: Each database team can maintain their own functions
- ✅ Future-Proof: Easy to extend and migrate
Happy coding! 🚀
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sfn_db_query_builder-2.2.tar.gz.
File metadata
- Download URL: sfn_db_query_builder-2.2.tar.gz
- Upload date:
- Size: 31.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
559c04a14b8d289efa579942aac3a21753c9b14e7652706ece4d8bd8e0b880ba
|
|
| MD5 |
b26208ede5d6d2a401015b20133fb168
|
|
| BLAKE2b-256 |
e7cafe0c9b5d5ee53ca44edd1e921babff966fc8c56b1358b65d09bfc81e7dea
|
File details
Details for the file sfn_db_query_builder-2.2-py3-none-any.whl.
File metadata
- Download URL: sfn_db_query_builder-2.2-py3-none-any.whl
- Upload date:
- Size: 36.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
48c19fda430748bccb30ec3e45e8fd03e4e8acc8f7ad97bbc60c244e00bde471
|
|
| MD5 |
f43154c4e44a8c730effe8be7d8ec282
|
|
| BLAKE2b-256 |
6075a0369cd4db937370ea42181ece5ac65e18ffd2680664f5d572337eb51d85
|