Principle:173TECH Sayn Database Abstraction
| Knowledge Sources | |
|---|---|
| Domains | Software_Engineering, Database |
| Last Updated | 2026-10-17 00:00 GMT |
Overview
Pattern for abstracting database operations behind a unified interface with capability flags, enabling the same task code to run against PostgreSQL, SQLite, MySQL, Snowflake, Redshift, and BigQuery.
Description
Database abstraction is the practice of providing a single Database base class that defines ETL operations (create table, replace table, merge query, load data, read data) while delegating database-specific behavior to adapter subclasses. The feature() method allows adapters to declare which capabilities they support, so the base class can generate appropriate SQL.
Key concepts:
- Feature flags:
CAN REPLACE TABLE,CAN REPLACE VIEW,NEEDS CASCADE,NO SCHEMA SUPPORT,CANNOT ALTER INDEXES, etc. - SQL generation via Jinja templates: ETL operations render SQL from templates, adjusting based on feature flags
- Bulk loading: Each adapter overrides
_load_data_batchfor efficient loading (PostgreSQL COPY, Redshift S3, Snowflake bulk, BigQuery native) - Introspection: The base class introspects database objects to check existence and types before DDL generation
Usage
Use this principle when a system must support multiple database engines with different SQL dialects and capabilities. The feature-flag approach avoids complex conditional logic by letting each adapter declare what it can do.
Theoretical Basis
The adapter pattern with capability flags:
- Base class:
Databasedefines the API (create_table,replace_table,merge_query,load_data,read_data,execute) - Feature method:
feature(feature_name) -> boolreturns whether the database supports a capability - Template rendering: SQL operations use Jinja templates that conditionally include clauses based on feature flags
- Adapter overrides: Subclasses override
create_engine,_load_data_batch,_list_databases, and optionallyload_data
Factory pattern for creation:
# Abstract algorithm (NOT real implementation)
drivers = {"postgresql": Postgresql, "sqlite": Sqlite, ...}
def create(name, settings):
db_type = settings.pop("type")
return drivers[db_type](name, ..., settings)
Practical Guide
Supported databases and their features:
| Database | Bulk Load Method | Schema Support | Replace Table |
|---|---|---|---|
| PostgreSQL | COPY | Yes | No (temp table + move) |
| SQLite | INSERT | No | No |
| MySQL | INSERT | Yes | No |
| Snowflake | Bulk INSERT | Yes | Yes |
| Redshift | S3 COPY | Yes | No |
| BigQuery | Native API | Yes | Yes |
Related Pages
Implemented By
- Implementation:173TECH_Sayn_Database_etl
- Implementation:173TECH_Sayn_read_settings
- Implementation:173TECH_Sayn_DatabaseCreator