|
| 1 | +import multiprocessing |
| 2 | +from typing import TYPE_CHECKING, Optional, Union |
| 3 | + |
| 4 | +from .. import Dataset, Features, config |
| 5 | +from ..formatting import query_table |
| 6 | +from ..packaged_modules.sql.sql import Sql |
| 7 | +from ..utils import logging |
| 8 | +from .abc import AbstractDatasetInputStream |
| 9 | + |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + import sqlite3 |
| 13 | + |
| 14 | + import sqlalchemy |
| 15 | + |
| 16 | + |
| 17 | +class SqlDatasetReader(AbstractDatasetInputStream): |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + sql: Union[str, "sqlalchemy.sql.Selectable"], |
| 21 | + con: str, |
| 22 | + features: Optional[Features] = None, |
| 23 | + cache_dir: str = None, |
| 24 | + keep_in_memory: bool = False, |
| 25 | + **kwargs, |
| 26 | + ): |
| 27 | + super().__init__(features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs) |
| 28 | + self.builder = Sql( |
| 29 | + cache_dir=cache_dir, |
| 30 | + features=features, |
| 31 | + sql=sql, |
| 32 | + con=con, |
| 33 | + **kwargs, |
| 34 | + ) |
| 35 | + |
| 36 | + def read(self): |
| 37 | + download_config = None |
| 38 | + download_mode = None |
| 39 | + ignore_verifications = False |
| 40 | + use_auth_token = None |
| 41 | + base_path = None |
| 42 | + |
| 43 | + self.builder.download_and_prepare( |
| 44 | + download_config=download_config, |
| 45 | + download_mode=download_mode, |
| 46 | + ignore_verifications=ignore_verifications, |
| 47 | + # try_from_hf_gcs=try_from_hf_gcs, |
| 48 | + base_path=base_path, |
| 49 | + use_auth_token=use_auth_token, |
| 50 | + ) |
| 51 | + |
| 52 | + # Build dataset for splits |
| 53 | + dataset = self.builder.as_dataset( |
| 54 | + split="train", ignore_verifications=ignore_verifications, in_memory=self.keep_in_memory |
| 55 | + ) |
| 56 | + return dataset |
| 57 | + |
| 58 | + |
| 59 | +class SqlDatasetWriter: |
| 60 | + def __init__( |
| 61 | + self, |
| 62 | + dataset: Dataset, |
| 63 | + name: str, |
| 64 | + con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"], |
| 65 | + batch_size: Optional[int] = None, |
| 66 | + num_proc: Optional[int] = None, |
| 67 | + **to_sql_kwargs, |
| 68 | + ): |
| 69 | + |
| 70 | + if num_proc is not None and num_proc <= 0: |
| 71 | + raise ValueError(f"num_proc {num_proc} must be an integer > 0.") |
| 72 | + |
| 73 | + self.dataset = dataset |
| 74 | + self.name = name |
| 75 | + self.con = con |
| 76 | + self.batch_size = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE |
| 77 | + self.num_proc = num_proc |
| 78 | + self.to_sql_kwargs = to_sql_kwargs |
| 79 | + |
| 80 | + def write(self) -> int: |
| 81 | + _ = self.to_sql_kwargs.pop("sql", None) |
| 82 | + _ = self.to_sql_kwargs.pop("con", None) |
| 83 | + |
| 84 | + written = self._write(**self.to_sql_kwargs) |
| 85 | + return written |
| 86 | + |
| 87 | + def _batch_sql(self, args): |
| 88 | + offset, to_sql_kwargs = args |
| 89 | + to_sql_kwargs = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs |
| 90 | + batch = query_table( |
| 91 | + table=self.dataset.data, |
| 92 | + key=slice(offset, offset + self.batch_size), |
| 93 | + indices=self.dataset._indices, |
| 94 | + ) |
| 95 | + df = batch.to_pandas() |
| 96 | + num_rows = df.to_sql(self.name, self.con, **to_sql_kwargs) |
| 97 | + return num_rows or len(df) |
| 98 | + |
| 99 | + def _write(self, **to_sql_kwargs) -> int: |
| 100 | + """Writes the pyarrow table as SQL to a database. |
| 101 | +
|
| 102 | + Caller is responsible for opening and closing the SQL connection. |
| 103 | + """ |
| 104 | + written = 0 |
| 105 | + |
| 106 | + if self.num_proc is None or self.num_proc == 1: |
| 107 | + for offset in logging.tqdm( |
| 108 | + range(0, len(self.dataset), self.batch_size), |
| 109 | + unit="ba", |
| 110 | + disable=not logging.is_progress_bar_enabled(), |
| 111 | + desc="Creating SQL from Arrow format", |
| 112 | + ): |
| 113 | + written += self._batch_sql((offset, to_sql_kwargs)) |
| 114 | + else: |
| 115 | + num_rows, batch_size = len(self.dataset), self.batch_size |
| 116 | + with multiprocessing.Pool(self.num_proc) as pool: |
| 117 | + for num_rows in logging.tqdm( |
| 118 | + pool.imap( |
| 119 | + self._batch_sql, |
| 120 | + [(offset, to_sql_kwargs) for offset in range(0, num_rows, batch_size)], |
| 121 | + ), |
| 122 | + total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size, |
| 123 | + unit="ba", |
| 124 | + disable=not logging.is_progress_bar_enabled(), |
| 125 | + desc="Creating SQL from Arrow format", |
| 126 | + ): |
| 127 | + written += num_rows |
| 128 | + |
| 129 | + return written |
0 commit comments