-
Notifications
You must be signed in to change notification settings - Fork 0
Add SQL DB ingestion to elt-common #339
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import dataclasses as dc | ||
| from typing import TYPE_CHECKING, Any, Callable, Iterator, Literal, Optional, get_args | ||
|
|
||
| WriteMode = Literal["append", "merge", "replace"] | ||
|
|
||
| if TYPE_CHECKING: | ||
| import pyarrow as pa | ||
|
|
||
|
|
||
| @dc.dataclass(frozen=True) | ||
| class Watermark: | ||
| column: str | ||
| value: Any | ||
|
|
||
|
|
||
| @dc.dataclass(frozen=True, kw_only=True) | ||
| class ResourceWriteProperties: | ||
| # Destination table | ||
| merge_on: list[str] = dc.field(default_factory=list) | ||
| partition: dict[str, str] = dc.field(default_factory=dict) | ||
| sort_order: dict[str, str] = dc.field(default_factory=dict) | ||
| write_mode: WriteMode = "append" | ||
|
|
||
| def __post_init__(self): | ||
| if self.write_mode not in get_args(WriteMode): | ||
| raise ValueError( | ||
| f"Invalid write mode '{self.write_mode}'. Allowed values: {get_args(WriteMode)}" | ||
| ) | ||
| if self.write_mode == "merge" and not self.merge_on: | ||
| raise ValueError("'merge_on' must be provided when mode='merge'") | ||
|
|
||
|
|
||
| @dc.dataclass(frozen=True, kw_only=True) | ||
| class ResourceProperties: | ||
| """Configuration for a single resource to be extracted.""" | ||
|
|
||
| # Required properties | ||
| extractor: Callable[[Optional[Watermark]], "Iterator[pa.Table]"] | ||
| write_properties: ResourceWriteProperties | ||
|
|
||
| # Ingestion properties | ||
| watermark_column: Optional[str] | ||
Empty file.
167 changes: 167 additions & 0 deletions
167
elt-common/src/elt_common/sources/sqldatabase/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| """Support for ingesting data from an SQL database.""" | ||
|
|
||
| import logging | ||
| from abc import ABC, abstractmethod | ||
| from typing import Generator, Iterator, NamedTuple, Optional | ||
|
|
||
| import pyarrow as pa | ||
| import sqlalchemy as sa | ||
| from pydantic import SecretStr | ||
| from pydantic_settings import BaseSettings | ||
|
|
||
| from elt_common.extract import ResourceProperties, ResourceWriteProperties, Watermark | ||
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class SqlDatabaseSourceConfig(BaseSettings): | ||
| """Configuration required to connect to a database""" | ||
|
|
||
| # connection | ||
| drivername: str | ||
| database: str | ||
| database_schema: Optional[str] = None | ||
| port: Optional[int] = None | ||
| host: Optional[str] = None | ||
| username: Optional[str] = None | ||
| password: Optional[SecretStr] = None | ||
|
|
||
| # loading behaviour | ||
| chunk_size: int = 5000 | ||
|
|
||
| @property | ||
| def connection_url(self): | ||
| return sa.URL.create( | ||
| drivername=self.drivername, | ||
| username=self.username, | ||
| password=self.password.get_secret_value() if self.password else None, | ||
| host=self.host, | ||
| port=self.port, | ||
| database=self.database, | ||
| ) | ||
|
|
||
|
|
||
| class TableInfo(NamedTuple): | ||
| """Extra information for controlling how a table is ingested. | ||
|
|
||
| Each table in a DB can have nondefault write properties, a watermark column, | ||
| both, or neither. | ||
|
|
||
| :ivar write_properties: properties to control how the table is written to the | ||
| destination. If omitted, will default to appending with no partitions or sorting. | ||
| :ivar watermark_column: the column to use for watermarking. If omitted, the | ||
| entire table will be queried on every run | ||
| """ | ||
|
|
||
| write_properties: Optional[ResourceWriteProperties] = None | ||
| watermark_column: Optional[str] = None | ||
|
|
||
|
|
||
| class SqlDatabaseExtract(ABC): | ||
| """Base class for defining SQL ingest Extract classes. | ||
|
|
||
| Example usage, for an ingest script that reads from 3 tables:: | ||
|
|
||
| class Extract(SqlDatabaseExtract): | ||
| def table_info(self): | ||
| return { | ||
| "a_table": None, | ||
| "a_table_that_watermarks_ingest_progress": TableInfo( | ||
| watermark_column="id" | ||
| ), | ||
| "a_table_to_replace_entirely_every_time": TableInfo( | ||
| write_properties=ResourceWriteProperties( | ||
| write_mode="replace" | ||
| ) | ||
| ) | ||
| } | ||
| """ | ||
|
|
||
| source_config_cls = SqlDatabaseSourceConfig | ||
|
|
||
| def __init__(self, source_config: SqlDatabaseSourceConfig): | ||
| self._source_config = source_config | ||
|
|
||
| LOGGER.debug( | ||
| f"Creating engine for {source_config.drivername} database at " | ||
| f"{source_config.host}:{source_config.port}/{source_config.database}" | ||
| ) | ||
| self._engine = sa.create_engine(source_config.connection_url) | ||
| self._metadata = sa.MetaData(schema=source_config.database_schema) | ||
|
|
||
| @property | ||
| def _chunk_size(self): | ||
| return self._source_config.chunk_size | ||
|
|
||
| @abstractmethod | ||
| def table_info(self) -> dict[str, Optional[TableInfo]]: | ||
| """Define the tables to be extracted from the DB. | ||
|
|
||
| Each key in the returned dict is a table name. Their values can include | ||
| extra properties for controlling ingestion, see :class:`TableInfo`. | ||
| """ | ||
| pass | ||
|
|
||
| def resource_properties(self): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed that we would rename this as they no longer return static data and "do" something. Renaming can happen in the next stage of the work when implementing the runner. |
||
| """Open a connection to the DB and return ingest properties for tables | ||
| defined by :func:`table_info`. | ||
|
|
||
| The extractor functions yielded as part of this function use the DB | ||
| connection which is only active whilst this function is executing. | ||
| This means the extractors must be called whilst iterating over the | ||
| results of this function. | ||
| """ | ||
| with self._engine.connect() as conn: | ||
| yield from self._make_table_properties(conn) | ||
|
|
||
| def _make_table_properties( | ||
| self, conn: sa.Connection | ||
| ) -> Generator[tuple[str, ResourceProperties]]: | ||
| """For each table defined in :func:`table_info`, build a | ||
| :class:`ResourceProperties` which can be used to ingest it""" | ||
|
|
||
| for name, table_props in self.table_info().items(): | ||
| write_properties = ( | ||
| table_props.write_properties | ||
| if table_props and table_props.write_properties | ||
| else ResourceWriteProperties() | ||
| ) | ||
| watermark_column = ( | ||
| table_props.watermark_column | ||
| if table_props and table_props.watermark_column | ||
| else None | ||
| ) | ||
|
|
||
| def extractor(watermark): | ||
| return self._extract_table(name, watermark=watermark, conn=conn) | ||
|
|
||
| properties = ResourceProperties( | ||
| extractor=extractor, | ||
| write_properties=write_properties, | ||
| watermark_column=watermark_column, | ||
| ) | ||
|
|
||
| yield name, properties | ||
|
|
||
| def _extract_table( | ||
| self, | ||
| name: str, | ||
| *, | ||
| conn: sa.Connection, | ||
| watermark: Watermark | None = None, | ||
| ) -> Iterator[pa.Table]: | ||
| LOGGER.debug(f"Extracting table {name} in chunks of {self._chunk_size} rows.") | ||
| table = sa.Table( | ||
| name, | ||
| self._metadata, | ||
| autoload_with=self._engine, | ||
| ) | ||
| query = sa.select(table) | ||
| if watermark is not None: | ||
| column, max_value = watermark.column, watermark.value | ||
| LOGGER.debug(f"Cursor value detected. Limiting query to {column} > {max_value}") | ||
| query = query.where(sa.column(column) > max_value) | ||
|
|
||
| result = conn.execution_options(yield_per=self._chunk_size).execute(query) | ||
| for partition in result.mappings().partitions(): | ||
| yield pa.Table.from_pylist(partition) | ||
Empty file.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a nice distinction and makes it clearer that these are purely about writing to the table.