|
| 1 | +from typing import Any, Dict, Iterator, List, Optional, Tuple |
| 2 | + |
| 3 | +from pyairtable import Table |
| 4 | +from shillelagh.adapters.base import Adapter |
| 5 | +from shillelagh.fields import Field, Filter, String |
| 6 | +from shillelagh.typing import RequestedOrder |
| 7 | + |
| 8 | +from .types import BaseMetadata |
| 9 | + |
| 10 | +# ----------------------------------------------------------------------------- |
| 11 | + |
| 12 | + |
| 13 | +class AirtableAdapter(Adapter): |
| 14 | + safe = True |
| 15 | + |
| 16 | + def __init__( |
| 17 | + self, |
| 18 | + table: str, |
| 19 | + base_id: str, |
| 20 | + api_key: str, |
| 21 | + base_metadata: BaseMetadata, |
| 22 | + ): |
| 23 | + super().__init__() |
| 24 | + |
| 25 | + self.table = table |
| 26 | + self.base_metadata = base_metadata |
| 27 | + |
| 28 | + self._table_api = Table(api_key, base_id, table) |
| 29 | + |
| 30 | + fields: List[str] |
| 31 | + if self.base_metadata is not None: |
| 32 | + # TODO(cancan101): Better error handling here |
| 33 | + # We search by name here. |
| 34 | + # Alternatively we could have the user specify the name as an id |
| 35 | + table_metadata = [ |
| 36 | + table_value |
| 37 | + for table_value in self.base_metadata.values() |
| 38 | + if table_value["name"] == table |
| 39 | + ][0] |
| 40 | + columns_metadata = table_metadata["columns"] |
| 41 | + fields = [col["name"] for col in columns_metadata] |
| 42 | + self.strict_col = True |
| 43 | + else: |
| 44 | + # This introspects the first row in the table. |
| 45 | + # This is super not reliable |
| 46 | + # as Airtable removes the key if the value is empty. |
| 47 | + # We should probably look at more than one entry. |
| 48 | + fields = self._table_api.first()["fields"] |
| 49 | + self.strict_col = False |
| 50 | + |
| 51 | + # TODO(cancan101): parse out types |
| 52 | + self.columns: Dict[str, Field] = dict( |
| 53 | + {k: String() for k in fields}, id=String() |
| 54 | + ) |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def supports(uri: str, fast: bool = True, **kwargs: Any) -> Optional[bool]: |
| 58 | + # TODO the slow path here could connect to the GQL Server |
| 59 | + return True |
| 60 | + |
| 61 | + @staticmethod |
| 62 | + def parse_uri(table: str) -> Tuple[str]: |
| 63 | + return (table,) |
| 64 | + |
| 65 | + def get_columns(self) -> Dict[str, Field]: |
| 66 | + return self.columns |
| 67 | + |
| 68 | + def get_data( |
| 69 | + self, |
| 70 | + bounds: Dict[str, Filter], |
| 71 | + order: List[Tuple[str, RequestedOrder]], |
| 72 | + ) -> Iterator[Dict[str, Any]]: |
| 73 | + for page in self._table_api.iterate(): |
| 74 | + for result in page: |
| 75 | + yield dict( |
| 76 | + { |
| 77 | + k: v |
| 78 | + for k, v in result["fields"].items() |
| 79 | + if self.strict_col or k in self.columns |
| 80 | + }, |
| 81 | + id=result["id"], |
| 82 | + ) |
0 commit comments