Implementation:173TECH Sayn Database etl
| Knowledge Sources | |
|---|---|
| Domains | Database, ETL |
| Last Updated | 2026-10-17 00:00 GMT |
Overview
Concrete tool for executing ETL operations — create table, replace table, merge query, load data, read data — against multiple database engines via SQLAlchemy with feature-flag-based SQL generation.
Description
The Database base class provides the ETL API used by all SAYN tasks. It uses Jinja templates to generate SQL, adjusting the output based on database-specific feature flags. Adapter subclasses (PostgreSQL, SQLite, MySQL, Snowflake, Redshift, BigQuery) override create_engine and _load_data_batch for engine-specific optimizations.
Key methods:
execute(script): Run arbitrary SQL with autocommitread_data(query): Execute SELECT, return list of dicts_read_data_stream(query): Server-side cursor for streamingload_data(table, data, ...): Batch-insert records, auto-create table if neededcreate_table(table, ...): Generate CREATE TABLE SQL from DDLreplace_table(table, select, ...): Atomic table replacement via temp table + movereplace_view(view, select, ...): Create or replace a SQL viewmerge_query(table, select, delete_key, ...): Create temp table and merge by delete_keymerge_tables(src, dst, delete_key, ...): Merge source into destination by delete_keymove_table(src, dst, ...): Rename/move a tablefeature(feature_name): Check if database supports a capability
Usage
Used by all task types (SqlTask, CopyTask, PythonTask) for database operations. In Python tasks, accessed via context.connections["db_name"].
Code Reference
Source Location
- Repository: SAYN
- File:
sayn/database/__init__.py - Lines: L16-17 (
Hook), L20-37 (Columns,Tests), L40-99 (BaseDDL,DDL), L101-864 (Databaseclass)
Signature
class Database:
DDL = DDL
def __init__(self, name: str, name_in_settings: str, db_type: str, common_params: dict, settings: dict)
def feature(self, feature: str) -> bool
def execute(self, script: str) -> None
def read_data(self, query: str, **params) -> List[dict]
def _read_data_stream(self, query, **params) -> Iterator[dict]
def load_data(self, table: str, data: list, db=None, schema=None, batch_size=None, replace=False, **ddl) -> int
def _load_data_batch(self, table: str, data: list, schema: str, db: str) -> None
def create_table(self, table: str, schema=None, db=None, select=None, replace=False, temporary=False, **ddl) -> str
def replace_table(self, table: str, select: str, schema=None, db=None, tmp_schema=None, tmp_db=None, **ddl) -> Dict[str, str]
def replace_view(self, view: str, select: str, schema=None, db=None, **ddl) -> Dict[str, str]
def merge_query(self, table: str, select: str, delete_key: str, schema=None, db=None, tmp_schema=None, **ddl) -> Dict[str, str]
def merge_tables(self, src_table: str, dst_table: str, delete_key: str, cleanup=True, src_schema=None, dst_schema=None, src_db=None, dst_db=None, **ddl) -> str
def move_table(self, src_table: str, dst_table: str, src_schema=None, dst_schema=None, src_db=None, dst_db=None, **ddl) -> str
def _validate_ddl(self, columns: list, table_properties: dict, post_hook: list) -> Result[Dict]
def _construct_tests(self, columns: list, table: str, schema: str = None) -> Result[List]
def _py2sqa(self, from_type: type) -> str
def _introspect(self, objects_to_introspect: dict) -> None
Import
from sayn.database import Database
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| name | str | Yes Connection name from project.yaml | |
| name_in_settings | str | Yes Credential name from settings.yaml | |
| db_type | str | Yes Database type (postgresql, sqlite, etc.) | |
| settings | dict | Yes Connection-specific parameters |
Outputs
| Name | Type | Description |
|---|---|---|
| engine | sqlalchemy.Engine SQLAlchemy engine for the connection | |
| metadata | sqlalchemy.MetaData Metadata for introspection | |
| load_data returns | int Number of records loaded | |
| read_data returns | List[dict] Query results as list of dicts |
Usage Examples
Using Database in Python Tasks
from sayn import task
@task
def load_data(context, warehouse):
# Read from a table
data = warehouse.read_data("SELECT * FROM raw.users")
print(f"Loaded {len(data)} records")
# Load data into a table
records = [
{"user_id": 1, "name": "Alice"},
{"user_id": 2, "name": "Bob"},
]
count = warehouse.load_data(
"users",
records,
schema="staging",
replace=True,
columns=[
{"name": "user_id", "type": "INTEGER"},
{"name": "name", "type": "VARCHAR"},
],
)
print(f"Loaded {count} records")
# Execute arbitrary SQL
warehouse.execute("CREATE INDEX idx_users ON staging.users(user_id)")
Streaming Data (Internal)
# Used internally by CopyTask for cross-database transfer
for record in source_db._read_data_stream(select_query):
# record is a dict
process(record)
Related Pages
Implements Principle
- Principle:173TECH_Sayn_Database_Abstraction
- Principle:173TECH_Sayn_SQL_Materialisation
- Principle:173TECH_Sayn_Incremental_Loading
- Principle:173TECH_Sayn_Cross_Database_Copy
- Principle:173TECH_Sayn_Batch_Processing